# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from dateutil.relativedelta import *
from datetime import datetime, date
from requests import Session
from pyautogui import prompt
import fitz, os, re, time

from sys import path
path.append(r'..\..\_comum')
from chrome_comum import _initialize_chrome, _send_input
from comum_comum import _time_execution, _escreve_relatorio_csv, _escreve_header_csv, _open_lista_dados, _where_to_start, _indice

'''
Download dos pdf no período dtInicio-dats_final para a empresa CNPJ (notas prestadas e tomadas)
Os arquivos são obtidos pelo site 'https://valinhos.sigissweb.com' através do usuario e senha
do contribuinte.

url_acesso -> link para acessar o sistema
url_pesquisa -> link para filtrar o período necessário
url_sintético -> link que retorna o arquivo .pdf sintético do período solicitado
url_analitico -> link que retorna o arquivo .pdf analítico do período solicitado
'''

def consulta_xml(execucao, final, empresa, data_inicio, data_final):
    cnpj, senha, nome = empresa
    nome = nome.replace('/', ' ').replace('   ', ' ').replace('  ', ' ')

    url_acesso = "https://valinhos.sigissweb.com/ControleDeAcesso"
    url_pesquisa = "https://valinhos.sigissweb.com/nfecentral?oper=efetuapesquisasimples"
    url_sintetico = "https://valinhos.sigissweb.com/nfecentral?oper=relnfesintetico"
    url_analitico = "https://valinhos.sigissweb.com/nfecentral?oper=relnfeanalitico"
    # obter login e senha do banco de dados utilizando o cnpj

    # inicia a sessão no site, realiza o login e obtém os arquivos para o contribuinte
    with Session() as s:
        login_data = {"loginacesso": cnpj, "senha": senha}
        pagina = s.post(url_acesso, login_data)

        try:
            soup = BeautifulSoup(pagina.content, 'html.parser')
            soup = soup.prettify()
            # print(soup)
            regex = re.compile(r"'Aviso', '(.+)<br>")
            regex2 = re.compile(r"'Aviso', '(.+)\.\.\.', ")
            try:
                documento = regex.search(soup).group(1)
            except:
                documento = regex2.search(soup).group(1)
            _escreve_relatorio_csv(f'{cnpj};{senha};{nome};{documento}', local=final, nome=execucao)
            print(f"❌ {documento}")
            return False
        except:
            pass

        info = {
            'cnpj_cpf_destinatario': '',
            'operCNPJCPFdest': 'EX',
            'RAZAO_SOCIAL_DESTINATARIO': '',
            'selnomedestoper': 'EX',
            'id_codigo_servico': '',
            'serie': '',
            'numero_nf': '',
            'operNFE': '=',
            'numero_nf2': '',
            'rps': '',
            'operRPS': '=',
            'rps2': '',
            'data_emissao': '',
            'operData': '=',
            'data_emissao2': '',
            'mesi': data_inicio[0],
            'anoi': data_inicio[1],
            'mesf': data_final[0],
            'anof': data_final[1],
            'aliq_iss': '',
            'regime': '?',
            'iss_retido': '?',
            'cancelada': '?',
            'tipoPesq': 'normal'
        }

        pagina = s.post(url_pesquisa, info)
        if pagina.status_code != 200:
            _escreve_relatorio_csv(f'{cnpj};{senha};{nome};Erro ao acessar a página', local=final, nome=execucao)
            print('>>> Erro ao acessar a página.')
            return False

        salvar = [(url_sintetico, os.path.join(final, 'Sintético'), 'Sintético'),
                  (url_analitico, os.path.join(final, 'Analítico'), 'Analítico')]

        # salvar relatório sintético depois relatório analítico
        for consulta in salvar:
            url = s.get(str(consulta[0]))
            pasta = consulta[1]
            if data_inicio != data_final:
                file = f'{nome} - {cnpj} - {consulta[2]} - {str(data_inicio[0])}-{str(data_inicio[1])} até {str(data_final[0])}-{str(data_final[1])}'
            else:
                file = f'{nome} - {cnpj} - {consulta[2]} - {str(data_inicio[0])}-{str(data_inicio[1])}'

            # rotina para salvar os arquivos pdf
            if 'text' not in url.headers.get('Content-Type', 'text'):
                os.makedirs(pasta, exist_ok=True)
                os.makedirs(pasta, exist_ok=True)

                arquivo = open(os.path.join(pasta, file + '.pdf'), 'wb')
                for parte in url.iter_content(100000):
                    arquivo.write(parte)
                arquivo.close()

                _escreve_relatorio_csv(f'{cnpj};{senha};{nome};Relatório {consulta[2]} gerado', local=final, nome=execucao)
                print(f"✔ Relatório {consulta[2]} salvo")
            else:
                _escreve_relatorio_csv(f'{cnpj};{senha};{nome};Erro ao acessar a página {consulta[2]}', local=final, nome=execucao)
                print(f'❌ Não gerou relatório {consulta[2]}.')

            # necessário para não sobrepor o cachê da pesquisa
            time.sleep(1)

    return True

def analiza(final):
    print('\n>>> Analisando relatórios Analíticos')
    documentos = os.path.join(final, 'Analítico')
    # Analiza cada pdf que estiver na pasta
    for arq in os.listdir(documentos):
        # Abrir o pdf
        arquivo = os.path.join(documentos, arq)
        with fitz.open(arquivo) as pdf:

            pattern = re.compile(r' - \d+ - Analítico.+.pdf')
            empresa = re.sub(pattern, '', arq)

            cnpj = re.compile(r' - (\d+) - Analítico.+.pdf').search(arq).group(1)

            # Para cada página do pdf
            for page in pdf:
                try:
                    # Pega o texto da pagina
                    textinho = page.get_text('text', flags=1 + 2 + 8)
                    # Procura o valor a recolher da empresa
                    valores = None
                    indice = 20
                    while not valores:
                        indice = str(indice)
                        valores = re.compile(r'\n(.+)\n.+\n.0+(.+)\n(.+)\n(.+)\nSérie:\n(.+\n){' + indice + '}ISS\n.+\nR\$ (.+)\nR\$ (.+)\nR\$ (.+)\nR\$ (.+)\nR\$ (.+)(\n.+){7}\nR\$ (.+)').findall(textinho)
                        indice = int(indice)
                        indice += 1

                        if indice >= 30:
                            break

                    if not valores:
                        continue

                    for valor in valores:
                        # Guarda as infos da empresa
                        emissao = valor[0]
                        numero = valor[1]
                        cnpj_destinatario = valor[2]
                        nome_destinatario = valor[3]
                        iss = valor[11]
                        pis = valor[5]
                        cofins = valor[8]
                        csll = valor[9]
                        inss = valor[6]
                        irrf = valor[7]
                        nome_destinatario = nome_destinatario.replace('–', '-')
                        _escreve_relatorio_csv(f"{cnpj};{empresa};{emissao};{numero};{nome_destinatario};{cnpj_destinatario};{iss};{pis};{cofins};{csll};{inss};{irrf}",
                                               nome='Resumo Relatórios Analíticos', local=final)
                except():
                    print(f'\nArquivo: {arq} - ERRO')

@_time_execution
def run():
    # função para abrir a lista de dados
    empresas = _open_lista_dados()
    execucao = 'Resumo Download Relatórios'
    # função para saber onde o robô começa na lista de dados
    index = _where_to_start(tuple(i[0] for i in empresas))
    if index is None:
        return False

    data_inicio = prompt("Data inicio no formato 00/0000:").split('/')
    data_final = prompt("Data final no formato 00/0000:").split('/')
    if data_inicio != data_final:
        final = os.path.join('Execução', 'Ref. ' + data_inicio[0] + '-' + data_inicio[1] + ' até ' + data_final[0] + '-' + data_final[1])
    else:
        final = os.path.join('Execução', 'Ref. ' + data_inicio[0] + '-' + data_inicio[1])

    # cria o indice para cada empresa da lista de dados
    total_empresas = empresas[index:]

    for count, empresa in enumerate(empresas[index:], start=1):
        # printa o indice da empresa que está sendo executada
        _indice(count, total_empresas, empresa)
        try:
            consulta_xml(execucao, final, empresa, data_inicio, data_final)
        except Exception as e:
            print(e)

    time.sleep(1)
    analiza(final)
    _escreve_header_csv(';'.join(['CNPJ', 'NOME', 'EMISSÃO DA NOTA', 'NÚMERO DA NOTA', 'DESTINATÁRIO', 'CNPJ DESTINATÁRIO', 'ISS', 'PIS', 'COFINS', 'CSLL', 'INSS', 'IRRF']),
                        nome='Resumo Relatórios Analíticos', local=final)

if __name__ == '__main__':
    run()


from collections import deque
class Solution:
    """
    @param graph: the given undirected graph
    @return:  return true if and only if it is bipartite
    """
    def isBipartite(self, graph):
        # Write your code here
        #groups = (set([0]),set(graph[0]))
        # groups = set()
        colors = {}#{0:0}

        q = deque(range(len(graph)))

        while q:
            node = q.popleft()
            #print('there')
            if node not in colors:
                colors[node] = 0

            for i in range(len(graph[node])):
                if graph[node][i] in colors:
                    if colors[graph[node][i]] == colors[node]:
                        #print('here')
                        return False

                else:

                    colors[graph[node][i]] = 1 - colors[node]
                    q.append(graph[node][i])
                    #groups.add(graph[node][i])
            #print(colors)
        return True


import sqlite3

conn = sqlite3.connect('Debian-stable.db')
c = conn.cursor()

# create table
c.execute(
    '''
        CREATE TABLE IF NOT EXISTS packages (
            name text,
            version text,
            dependency text,
            vcsbrowser text,
            vcsname text,
            vcslink text,
            homepage text,
            section text,
            githubapi text
        )
    '''
)

c.execute(''' CREATE INDEX IF NOT EXISTS pname_index ON packages(name) ''')

# clean table before insertion
c.execute(''' DELETE FROM packages ''')

insert_query = ''' INSERT INTO packages(name, version,
                 dependency, vcsbrowser, vcsname, vcslink,
                 homepage, section, githubapi) VALUES(?, ?, ?,
                 ?, ?, ?, ?, ?, ?) '''

# Source file path
fname = "Sources"

# =============================
# retrive an array of vcs names
# =============================
vcs_arr = []

with open(fname, encoding='utf-8') as dpfile:
    for fline in dpfile:
        if (": " in fline):
            attr_name, attr_value = fline.strip("\n").split(": ", 1)

            if ("Vcs-" in attr_name and attr_name not in vcs_arr):
                vcs_arr.append(attr_name)

vcs_arr.pop(vcs_arr.index("Vcs-Browser"))
# =============================

# vcs_arr = [
#     'Vcs-Svn',
#     'Vcs-Git',
#     'Vcs-Bzr',
#     'Vcs-Mtn',
#     'Vcs-Hg',
#     'Vcs-Darcs',
#     'Vcs-Cvs',
#     'Vcs-Arch'
# ]

attr_dict = {
    "Package": "name",
    "Version": "version",
    "Build-Depends": "dependency",
    "Build-Depends-Indep": "dependency",
    "Vcs-Browser": "vcsbrowser",
    "Homepage": "homepage",
    "Section": "section"
}

for vcs in vcs_arr:
    attr_dict[vcs] = "vcslink"

# dictionary key
attr_str = list(attr_dict.keys())

# package info in dictionary
package = {
    "name": None,
    "version": None,
    "dependency": None,
    "vcsbrowser": None,
    "vcsname": None,
    "vcslink": None,
    "homepage": None,
    "section": None,
    "githubapi": None
}
pkg_depends = []
index = 0

def do_db_insert():
    for depend in pkg_depends:
        package["dependency"] = depend

        print(index,": ",list(package.values()))
        c.execute(insert_query, list(package.values()))

    return conn.commit()

with open(fname, encoding='utf-8') as dpfile:
    for fline in dpfile:
        if (": " in fline):
            attr_name, attr_value = fline.strip("\n").split(": ", 1)

            if (attr_name in attr_str):
                # clean package info
                if (attr_name == "Package"):
                    index += 1
                    if (package["name"] is not None):
                        do_db_insert()

                    pkg_depends.clear()
                    package["vcsname"] = None
                    for dbattr in list(attr_dict.values()):
                        package[dbattr] = None

                if (attr_name in vcs_arr):
                    package["vcsname"] = attr_name

                if (attr_name == "Build-Depends" or attr_name == "Build-Depends-Indep"):
                    pkg_depends = [x.strip() for x in attr_value.split(", ")]
                else:
                    package[attr_dict[attr_name]] = attr_value

do_db_insert()

conn.close()
dpfile.close()

# Counts in Notepad++
# Package: 2486
# Vcs-: 40853
# Vcs-browser: 20338
# Vcs-Git: 18014
# Vcs-Svn: 2282
# Vcs-Mtn: 25
# Vcs-Bzr: 124
# Vcs-Hg: 42
# Vcs-Darcs: 14
# Vcs-Cvs: 7
# Vcs-Arch: 7


class Solution:
    def findLadders(self,  beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
        if endWord not in wordList:
            return []

        neighbors = defaultdict(list)
        wordList.append(beginWord)
        for word in wordList:
            for j in range(len(word)):
                pattern = f"{word[:j]}*{word[j+1:]}"
                neighbors[pattern].append(word)

        def bfs() -> int:
            visited = set([beginWord])
            queue = deque([beginWord])
            depth = 1
            while queue:
                for _ in range(len(queue)):
                    word = queue.popleft()
                    if word == endWord:
                        return depth
                    for j in range(len(word)):
                        pattern = f"{word[:j]}*{word[j+1:]}"
                        for neighbor in neighbors[pattern]:
                            if neighbor in visited:
                                continue
                            visited.add(neighbor)
                            queue.append(neighbor)
                depth += 1

        @lru_cache(maxsize=None)
        def dfs_backtrack(word, depth):
            if word == endWord:
                return [[word]]
            elif depth == 1:
                return
            else:
                results = []
                visited.add(word)
                for i in range(len(word)):
                    pattern = f"{word[:i]}*{word[i+1:]}"
                    for neighbor in neighbors[pattern]:
                        if neighbor in visited:
                            continue
                        result = dfs_backtrack(neighbor, depth - 1)
                        if result:
                            for r in result:
                                results.append([word] + r)
                visited.remove(word)
                return results

        depth = bfs()
        visited = set([beginWord])
        results = []

        results = dfs_backtrack(beginWord, depth)

        return results


# coding:utf-8
import requests
import json

def download(src, id):
    dir = './img/wzx/' + str(id) + '.jpg'
    try:
        pic = requests.get(src, timeout=10)
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
    except requests.exceptions.ConnectionError:
        print('图片无法下载')

query = '王祖贤'

headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
    "Host": "httpbin.org",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
    "X-Amzn-Trace-Id": "Root=1-5e5f9a40-ce990b3ad9f29c14644f4e22"
}

for i in range(0, 20, 20):
    url = 'https://www.douban.com/j/search_photo?q=' + query + '&limit=20&start=' + str(i)
    html = requests.get(url,headers=headers)

    print(html)

    response = json.loads(html, encoding='utf-8')
    for image in response['images']:
        print(image['src'])
        download(image['src'], image['id'])


class Fraction:
    def __init__(self, nr, dr=1):
        self.nr = nr
        self.dr = abs(dr)
        if self.dr < 0:
            self.nr *= -1
            self.dr *= -1
        self._reduce()

    def show(self):
        print(f"{self.nr}/{self.dr}")

    def __str__(self):
        return f"{self.nr}/{self.dr}"

    # This is for console interative print
    def __repr__(self):
        return f"Fraction({self.nr},{self.dr})"

    def __add__(self, other):
        if isinstance(other, int):
            other = Fraction(other)
        f = Fraction(self.nr * other.dr + other.nr * self.dr, self.dr * other.dr)
        f._reduce()
        return f

    def __sub__(self, other):
        if isinstance(other, int):
            other = Fraction(other)
        f = Fraction(self.nr * other.dr - other.nr * self.dr, self.dr * other.dr)
        f._reduce()
        return f

    def __mul__(self, other):
        if isinstance(other, int):
            other = Fraction(other)
        f = Fraction(self.nr * other.nr , self.dr * other.dr)
        f._reduce()
        return f

    def __eq__(self, other):
        return (self.nr * other.dr) == (self.dr * other.nr)

    def __lt__(self, other):
        return (self.nr * other.dr) < (self.dr * other.nr)

    def __le__(self, other):
        return (self.nr * other.dr) <= (self.dr * other.nr)

    def _reduce(self):
        h = Fraction.hcf(self.nr, self.dr)
        if h == 0:
            return

        self.nr //= h
        self.dr //= h

    @staticmethod
    def hcf(x, y):
        x = abs(x)
        y = abs(y)
        smaller = y if x > y else x
        s = smaller
        while s > 0:
            if x % s == 0 and y % s == 0:
                break
            s -= 1
        return s

f = Fraction(2,3)
print(f)
# in console prints the fraction
str(f)

f1 = Fraction(3,4)
f2 = Fraction(2,3)
f3 = Fraction(6,7)
L = [f1,f2,f3]
# This call repr method
print(L)


from extract.abstract import extractor_for, AbstractDataExtractor, JSONKey

@extractor_for('www.wildberries.ru')
class WildberriesExtractor(AbstractDataExtractor):
    # Example
    #   https://www.wildberries.ru/catalog/1008827/detail.aspx

    _NAME_SELECTOR = 'div.good-header > h1'
    _TYPE_SELECTOR = 'div#add-options div.j-kit p.pp > span'
    _COLORS_SELECTOR = 'span[class="color j-color-name"]'
    _PRICE_SELECTOR = 'p[class="price j-price"] > ins'
    _SIZES_SELECTOR = 'label[class^="j-size"]'
    _GENDER_SELECTOR = None
    _IMG_SELECTOR = "img#preview-large"

    _DESCRIPTION_SELECTOR = 'div#description p'
    _REVIEWS_SELECTOR = 'div.comment-content p.body'
    _ATTRIBUTES_SELECTOR = 'div#add-options p.pp'

    def _parse_name(self):
        data = self._get_data_by_selector(self._NAME_SELECTOR)
        if len(data) > 0:
            # cutting brand's tail.
            self._save_raw(JSONKey.NAME_KEY, ', '.join(data[0].split(', ')[:-1]))

    def _parse_brand(self):
        data = self._get_data_by_selector(self._NAME_SELECTOR)
        if len(data) > 0:
            v = data[0].split(', ')[-1]
            if len(v) > 1:
                self._save_raw(JSONKey.BRAND_KEY, v.strip())

    def _parse_sizes(self):
        # "35/5" "36/6" "41-42/6"
        def process_size(size):
            size_str = size.split('/')[0]
            if 'мес' in size_str:
                return []
            if '-' in size_str and all(map(lambda s: s.isdigit() and len(s) > 0, size_str.split('-'))):
                # dirty hack for wildberries - child shoes' sizes can be like '12-18мес'
                abstrs = size_str.split('-')
                a, b = map(int, size_str.split('-'))
                return list(map(float, range(a, b + 1)))
            else:
                size_str = size_str.replace(',', '.')
                if all(map(lambda c: c.isdigit() or c == '.', size_str)):
                    return [float(size_str)]
                else:
                    return []

        res_sizes = set()
        labels = self._selectable_data.cssselect(self._SIZES_SELECTOR)
        for label in labels:
            if 'disabled' in label.attrib['class']:
                continue
            span = label.find('span')
            if span is not None:
                res_sizes |= set(process_size(span.text))

        self._save_raw(JSONKey.SIZES_KEY, list(res_sizes))

    def _parse_colors(self):
        data = self._selectable_data.cssselect(self._COLORS_SELECTOR)
        colors = []
        for d in data:
            if d.text is not None:
                colors += d.text.split(', ')
        self._save_raw(JSONKey.COLORS_KEY, colors)

    # def _parse_image(self):
    #     data = self._selectable_data.cssselect(self._IMG_SELECTOR)
    #     if len(data) == 0:
    #         return
    #     img = data[0]
    #     url = img.attrib['src']
    #     if url.startswith('//'):
    #         url = 'http:' + url
    #     self._save_raw(JSONKey.IMG_KEY, url)

    def _parse_attributes(self):
        attributes = dict()
        for attr in self._selectable_data.cssselect(self._ATTRIBUTES_SELECTOR):
            span = attr.find('span')
            if span is not None:
                name = attr.text[:-1]
                value = span.text.strip()
                if 'Пол' in name:
                    self._save_raw(JSONKey.GENDER_KEY, self.unify_gender(value))
                attributes[name] = value
        self._save_raw(JSONKey.ATTRIBUTES_KEY, attributes)


# coding:utf-8
import os
import codecs
from lxml import etree
import re
from connectMysql import Mymysql
import datetime
import uuid
from util import get_pic_md5

def main_page_jiexi(product_id, content, update_time,item_dict,thread_name):
    try:
        x = Mymysql()
        x._GetConnect()

        # 属性插入:
        tree = etree.HTML(content)
        attributes = tree.xpath(".//ul[@class='attributes-list']/li/text()")
        attributes = [item.split(":") for item in attributes]
        for item in attributes:
            if item:
                detail_id = uuid.uuid1()
                index_name = item[0].strip()
                index_value = item[1].strip().replace("'", "")
                sql = """
                          insert into product_detail_information(detail_id,product_id,index_name,index_value,update_time)
                          values('%s','%s','%s','%s','%s')
                      """ % (detail_id, product_id, index_name, index_value, update_time)
                try:
                    x.ExecNonQuery(sql)
                except Exception as ex:
                    print("attributes jiexi error", ex)
                    print(sql)
                    print("=============================")
                    return False
        # 左上角图片插入
        imgs_left = tree.xpath(".//ul[@id='J_UlThumb']/li//img")
        count = 1
        for item in imgs_left:
            src = item.get("src")
            if not src:
                src = item.get("data-src")
            src = "http:" + src
            src = src.replace("50x50", "400x400")
            if not src.endswith("jpg"):
                continue
            from_who = position = 1
            sequence = count
            pic_md5 = get_pic_md5(src, product_id)
            sql = """
                              insert into image(product_id,img_src,position,sequence,update_time,from_who,pic_md5)
                                          values('%s','%s','%s','%s','%s','%s','%s')
                              """ % (product_id, src, position, sequence, update_time, from_who,pic_md5)
            try:
                x.ExecNonQuery(sql)
                count += 1
            except Exception as ex:
                print("left_img jiexi error",ex)
                print(sql)
                print("=============================")
                continue

        # size 插入
        code = tree.xpath(".//ul[@class='J_TSaleProp tb-clearfix']//span/text()")
        for item in code:
            Size_ID = uuid.uuid1()
            Size = item.replace("'", "")
            Size = item.replace("\\", "")
            sql = """
                             insert into  size(product_id,size_id, size,update_time) values('%s','%s','%s','%s')
                  """ % (product_id, Size_ID, Size, update_time)
            try:
                x.ExecNonQuery(sql)
            except Exception as ex:
                    print('size jiexi error',ex)
                    print(sql)
                    print("=============================")
                    return False

        # color 插入
        color = tree.xpath(".//ul[@class='J_TSaleProp tb-img tb-clearfix']//a")
        count = 1
        for item in color:
            src = item.get("style")
            img_id = ""
            if src:  # 有图片
                src = "http:" + re.findall("\((.*?)\)", src)[0]
                src = src.replace("30x30", "400x400")
                if not src.endswith("jpg"):
                    continue
                from_who = 1
                position = 3
                sequence = count
                pic_md5 = get_pic_md5(src, product_id)
                sql = """
                          insert into image(pic_md5,product_id,img_src,position,sequence,update_time,from_who)
                                      values('%s','%s','%s','%s','%s','%s','%s')
                          """ % (pic_md5, product_id, src, position, sequence, update_time, from_who)
                try:
                    x.ExecNonQuery(sql)
                    count += 1
                except Exception as ex:
                    print("color imagejiexi error",ex)
                    print(sql)
                    print("=============================")
                    continue

            color_id = uuid.uuid1()
            color = item.xpath(".//span/text()")[0]
            sql = """
                          insert into color(product_id,img_id,color_id,color,update_time)
                                      values('%s','%s','%s','%s','%s')
                          """ % (product_id, img_id, color_id, color, update_time)
            try:
                x.ExecNonQuery(sql)
            except Exception as ex:
                print("colortext jiexi error",ex)
                print(sql)
                print("=============")
                continue
        # 3 产品名称
        product_name = tree.xpath(".//h3[@class='tb-main-title']")
        if not product_name:
            product_name = ""
        else:
            product_name = product_name[0].get("data-title")
        product_name = product_name.replace("'", "")
        item_dict['product_name'] = product_name

        # 产品简述
        product_profile = tree.xpath(".//*[@id='J_Title']/p/text()")
        product_profile = product_profile[0] if product_profile else ""
        product_profile = product_profile.replace("'", "")
        item_dict['product_profile'] = product_profile

        return "ok"

    except Exception as ex:
        print(product_id, "main_page_jiexi", "error:", ex)
        file_save = os.path.join("jiexi", product_id + "_" + "1" + ".html")
        f = codecs.open(file_save, "a+", encoding="utf-8")
        f.write(content)
        f.close()
        return False


import os
import json
import tempfile
import functools

from typing import Any, Callable, Dict, Optional

DOWNLOADER_RESOURCES_PATH = os.path.join(os.path.dirname(__file__), "resources")

PAPIS_UPDATE_RESOURCES = os.environ.get("PAPIS_UPDATE_RESOURCES", "none").lower()
if PAPIS_UPDATE_RESOURCES not in ("none", "remote", "local", "both"):
    raise ValueError("unsupported value of 'PAPIS_UPDATE_RESOURCES'")

def get_resource(name: str) -> str:
    path = os.path.join(DOWNLOADER_RESOURCES_PATH, name)
    assert os.path.exists(path)

    with open(path, errors="ignore") as f:
        return f.read()

def get_json_resource(name: str) -> Any:
    return json.loads(get_resource(name))

def with_default_config(fn: Callable[..., Any]) -> Callable[..., Any]:
    import papis.config

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        with tempfile.NamedTemporaryFile(mode="w", delete=False) as config:
            pass

        papis.config.set_config_file(config.name)
        papis.config.reset_configuration()

        result = fn(*args, **kwargs)

        papis.config.set_config_file(None)
        papis.config.reset_configuration()

        os.unlink(config.name)

        return result

    return wrapper

def get_remote_resource(
        filename: str, url: str,
        force: bool = False,
        params: Optional[Dict[str, str]] = None,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        ) -> Callable[[], bytes]:
    filename = os.path.join(DOWNLOADER_RESOURCES_PATH, filename)
    if force or PAPIS_UPDATE_RESOURCES in ("remote", "both"):
        import requests
        import papis.config

        if headers is None:
            headers = {}

        headers["User-Agent"] = papis.config.getstring("user-agent")
        response = requests.get(url, params=params, headers=headers, cookies=cookies)

        with open(filename, "w", encoding="utf-8") as f:
            f.write(response.content.decode())

    def factory() -> bytes:
        with open(filename, encoding="utf-8") as f:
            return f.read().encode()

    return factory

def get_local_resource(
        filename: str, data: Any,
        force: bool = False,
        ) -> Any:
    filename = os.path.join(DOWNLOADER_RESOURCES_PATH, filename)
    _, ext = os.path.splitext(filename)

    import yaml
    import papis.yaml

    if force or PAPIS_UPDATE_RESOURCES in ("local", "both"):
        assert data is not None
        with open(filename, "w", encoding="utf-8") as f:
            if ext == ".json":
                json.dump(
                    data, f,
                    indent=2,
                    sort_keys=True,
                    ensure_ascii=False,
                    )
            elif ext == ".yml" or ext == ".yaml":
                yaml.dump(
                    data, f,
                    indent=2,
                    sort_keys=True,
                    )
            else:
                raise ValueError("unknown file extension: '{}'".format(ext))

    with open(filename, "r", encoding="utf-8") as f:
        if ext == ".json":
            return json.load(f)
        elif ext == ".yml" or ext == ".yaml":
            return papis.yaml.yaml_to_data(filename)
        else:
            raise ValueError("unknown file extension: '{}'".format(ext))


# -*- coding: utf-8 -*-
import pytest

@pytest.fixture
def solution():
    from leetcode.divide_two_integers import Solution
    return Solution()

@pytest.mark.parametrize(
    'dividend,divisor,expected',
    [
        (10, 3, 3),
        (7, -3, -2),
        (0, 1, 0),
        (1, 1, 1),
    ],
)
def test_divide_two_integers(solution, dividend, divisor, expected):
    actual = solution.divide(dividend, divisor)
    assert actual == expected


#! python3

from http.server import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep
import json

class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
	def get_memetype(self):
		if self.path.endswith('.html'):
			self.mimetype = 'text/html'
		if self.path.endswith('.png'):
			self.mimetype = 'image/png'
		if self.path.endswith('.gif'):
			self.mimetype = 'image/gif'
		if self.path.endswith('.js'):
			self.mimetype = 'application/javascript'
		if self.path.endswith('.css'):
			self.mimetype = 'text/css'

	def do_GET(self):
		if self.path == '/':
			self.path = '/index.html'

		self.get_memetype()

		try:
			f = open(curdir + sep + self.path, 'rb')
			self.send_response(200)

			if self.path == '/index.html':
				weatherKey = json.load(open('./config.json'))['weatherKey']
				self.send_header('Set-Cookie', 'weatherKey=%s' % weatherKey)

			self.send_header('Content-type', self.mimetype)
			self.end_headers()

			self.wfile.write(f.read())
			f.close()
			return

		except IOError:
			self.send_error(404,'File Not Found: %s' % self.path)

def run():
	address = '127.0.0.1'
	port = 8080
	print('Starting widget-clock web server at ' + address + ':' + str(port))

	server_address = (address, port)
	httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
	httpd.serve_forever()

run()


import sys
from heapq import *
from collections import defaultdict

# N 도시의 수, M 도로의 수, K 면접장의 수
N, M, K = map(int, sys.stdin.readline().split())

graph =defaultdict(list)
for _ in range(M) :
  u,v,c = map(int,sys.stdin.readline().split())
  graph[v].append((u,c)) # 단방향을 거꾸로 연결시킨다.
targets = list(map(int,sys.stdin.readline().split()))

# - 문제 접근 방법-
# 그래프를 거꾸로 연결 시킨다. a -> b 였다면, b -> a와 같은 형태로
# 다익스트라를 한번만 돌리고, 이때 힙에 모든 면접장을 다 넣어준다
  # 한 정점으로부터 모든 정점까지의 경로를 구하는 것이 아니다.
  # 면접장으로부터 가장 가까운 노드만 구하면 되기 때문에, 힙에 면접장을 모두 넣어도 된다.

def dijkstra() :
  distance = [float('inf')] * (N + 1)
  heap = list()

  for target in targets :
    distance[target] = 0
    heappush(heap, (0, target))

  while len(heap) != 0 :
    cur = heappop(heap) # ( sum_weight , vertex )

    if distance[cur[1]] < cur[0] :
      continue

    for next in graph[cur[1]] : # ( vertex, weight )
      cost = distance[cur[1]] + next[1]
      if cost < distance[next[0]] :
        distance[next[0]] = cost
        heappush(heap,(cost, next[0]))
  return distance

result = dijkstra()
i = max(result[1:])
print(result.index(i))
print(i)
# #--------- 시간초과 풀이 ----------#
# # N-> K 까지 이동해야함
# def dijkstra(start) :
#   distance = [float('inf')] * (N+1)
#   distance[start] = 0
#   heap = list()
#   heappush(heap,(0,start))
#
#   while len(heap) != 0 :
#     cur = heappop(heap) # ( sum_weight, vertex )
#
#     if distance[cur[1]] < cur[0] :
#       continue
#
#     for next in graph[cur[1]] : # ( vertex, weight )
#       cost = distance[cur[1]] + next[1]
#       if cost < distance[next[0]] :
#         distance[next[0]] = cost
#         heappush(heap,(cost, next[0]))
#
#   # 여기서 최단거리를 뽑아야함
#   # 타겟중에서 최단거리를 뽑아야함
#   mmin = float('inf')
#   for target in targets :
#     mmin = min(distance[target], mmin)
#
#
#   return (start, mmin)
#
# mmax = (-1, -1)
# for i in range(1,N+1) :
#   result = dijkstra(i)
#   # print(result)
#   mmax = max( mmax, result, key=lambda x: (x[1], -x[0]))
#
# print(mmax[0])
# print(mmax[1])


'''
players.py
Thura Aung
2nd May 2020
'''
import random
import math

class Player():
    def __init__(self,marker):
        self.marker = marker
    def makeMove(self,game):
        pass

class HumanPlayer(Player):
    def __init__(self,marker):
        super().__init__(marker)
    def makeMove(self,game):
        free_pos = False
        while not free_pos:
            position = int(input(self.marker + "\'s turn. Input the move(0-9):"))
            try:
                if position not in game.avaliablePos():
                    raise ValueError
                else:
                    free_pos = True
            except ValueError:
                print("This is invalid. Try again.")
        return position

class RandomComputerPlayer(Player): #for easy mode
    def __init__(self,marker):
        super().__init__(marker)
    def makeMove(self,game):
        position = random.choice(game.avaliablePos())
        return position

class IntelligentComputerPlayer(Player): #for hard mode
    def __init__(self,marker):
        super().__init__(marker)
    def makeMove(self,game):
        if len(game.avaliablePos()) == 9:
            position = random.choice(game.avaliablePos())
        else:
            position = self.minimax(game,self.marker)['pos']
        return position

    def minimax(self,state,player):
        max_player = self.marker
        other_player = 'O' if player == 'X' else 'X'
        if state.current_winner == other_player:
            return {
                'pos' : None,
                'score' : 1*(state.numOfemptyPos() + 1) if other_player == max_player else (-1)*(state.numOfemptyPos() + 1)
            } #score is the utility
        elif not state.emptyPos():
            return {
                'pos': None,
                'score' : 0
            }
        if player == max_player:
            best = {
                'pos' : None,
                'score' : -math.inf # each score should maximize
            }
        else:
            best = {
                'pos' : None,
                'score' : math.inf
            }
        for possible_moves in state.avaliablePos():
            state.checkMove(possible_moves,player)
            simulate_scores = self.minimax(state,other_player)

            state.board[possible_moves] = ' '
            state.current_winner = None
            simulate_scores['pos'] = possible_moves

            if player == max_player:
                if simulate_scores['score'] > best['score']:
                    best = simulate_scores
            elif simulate_scores['score'] < best['score']:
                    best = simulate_scores
            else:
                pass
        return best


import pyaudio
import struct
import subprocess
import math
import numpy as np
from scipy.fftpack import fft
import RPi.GPIO as GPIO

CHUNK = 1024 * 2
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100

p = pyaudio.PyAudio()
PinLowFreq = 27
PinMidFreq = 14
PinHighFreq = 17

micVolume = 8

maxVolume = 120

dutyCycle = 100

GPIO.setmode(GPIO.BCM)
GPIO.setup(PinLowFreq, GPIO.OUT)
GPIO.setup(PinMidFreq, GPIO.OUT)
GPIO.setup(PinHighFreq, GPIO.OUT)

PWMControllerLow = GPIO.PWM(PinLowFreq, dutyCycle)
PWMControllerMid = GPIO.PWM(PinMidFreq, dutyCycle)
PWMControllerHigh = GPIO.PWM(PinHighFreq, dutyCycle)

PWMControllerLow.start(dutyCycle)
PWMControllerMid.start(dutyCycle)
PWMControllerHigh.start(dutyCycle)

stream = p.open(
    format=FORMAT,
    channels=CHANNELS,
    rate=RATE,
    input=True,
    output=True,
    frames_per_buffer=CHUNK
)

x = np.arange(0, 2 * CHUNK, 2)
x_fft = np.linspace(0, RATE, CHUNK)
print(x_fft[int(len(x_fft)/2)])

pastFiveMicSamples = [0,0,0,0,0]

i = 0
x_fft = x_fft[:len(x_fft) // 2]
while True:
    data = stream.read(CHUNK, exception_on_overflow = False)
    data_int = np.array(struct.unpack(str(2 * CHUNK) + "B", data), dtype='b')[::2] #+ 127

    y_fft = fft(data_int) # core algorithm
    # was temp_fft = np.abs(y_fft[0:CHUNK]) * 2 / (256 * CHUNK)
    y_fft = np.abs(y_fft[0:CHUNK]) * 2 / (256 * CHUNK)

    y_fft = y_fft[:len(y_fft)//2]
    maxVolumeOccurances = np.count_nonzero(data_int >= maxVolume)
    pastFiveMicSamples.pop(4)
    pastFiveMicSamples.insert(0, maxVolumeOccurances)
    mean = 0.0
    for i in range(len(pastFiveMicSamples)):
        mean = mean + pastFiveMicSamples[i]
    mean = mean / 10.0
    if mean >= 10.0 and micVolume != 1:
        pastFiveMicSamples = [0,0,0,0,0]
        micVolume = micVolume - 1
        print("Lowering volume to: " + str(micVolume) + "%")
        subprocess.Popen(['amixer', 'set', 'Micro', str(micVolume) + '%', '>', '/dev/null'], cwd="./")
    elif mean == 0 and micVolume < 8:
        pastFiveMicSamples = [0,0,0,0,0]
        micVolume = micVolume + 1
        print("Increasing volume to: " + str(micVolume) + "%")
        subprocess.Popen(['amixer', 'set', 'Micro', str(micVolume) + '%', '>', '/dev/null'], cwd="./")

    frequencyIndexes = np.argsort(y_fft)    # will have the positions of the lowest to highest frequency

    low = 0
    mid = 0
    high = 0
    # now add up the fft values
    for j in range(int(len(x_fft)/8)):
        # now split the frequencies
        if x_fft[frequencyIndexes[-1 * j]] > 20 and x_fft[frequencyIndexes[-1 * j]] < 600:
            low = low + y_fft[frequencyIndexes[-1 * j]] # was (len(x_fft) - j ) #* credit
        elif x_fft[frequencyIndexes[-1 * j]] >= 600 and x_fft[frequencyIndexes[-1 * j]] < 1100:
            mid = mid + y_fft[frequencyIndexes[-1 * j]] # 1 # was (len(x_fft) - j) #* credit
        elif x_fft[frequencyIndexes[-1 * j]] >= 1100 and x_fft[frequencyIndexes[-1 * j]] < 2000:
            high = high + y_fft[frequencyIndexes[-1 * j]] #1 # was (len(x_fft) - j) #* credit

    low = round(low, 5)
    mid = round(mid, 5)
    high = round(high, 5)
    total = low + mid + high
    if total > 0:
        # get the percentage and make the percentage relative to the highest one
        lowPercentage = round((((low / total) * 100.0 * 1) ** 1), 2)
        midPercentage = round((((mid / total) * 100.0 * 1) ** 1), 2)
        highPercentage = round((((high / total) * 100.0 * 1) ** 1), 2)
        if lowPercentage > midPercentage and lowPercentage > highPercentage:
            lowPercentage = (lowPercentage / lowPercentage) * 100
            midPercentage = (midPercentage / lowPercentage) * 100
            highPercentage =  (highPercentage / lowPercentage) * 100

        elif midPercentage > lowPercentage and midPercentage > highPercentage:
            lowPercentage = (lowPercentage / midPercentage) * 100
            midPercentage = (midPercentage / midPercentage) * 100
            highPercentage = (highPercentage / midPercentage) * 100

        elif highPercentage > lowPercentage and highPercentage > midPercentage:
            lowPercentage = (lowPercentage / highPercentage) * 100
            midPercentage = (midPercentage / highPercentage) * 100
            highPercentage = (highPercentage / highPercentage) * 100

        if lowPercentage < midPercentage and lowPercentage < highPercentage:
            lowPercentage = 0
        elif midPercentage < lowPercentage and midPercentage < highPercentage:
            midPercentage = 0
        elif highPercentage < lowPercentage and highPercentage < midPercentage:
            highPercentage = 0

        i = i + 1

        PWMControllerLow.ChangeDutyCycle(lowPercentage)
        PWMControllerMid.ChangeDutyCycle(midPercentage)
        PWMControllerHigh.ChangeDutyCycle(highPercentage)


""" 221. Maximal Square

Question:

    Given a 2D binary amtrix filled with 0's and 1's, find the largest square
    containing only 1's and return its area.

+++

Solution:

    DP will provide the elegant solution. Let's suppose that DP represents
    maximal length of the square thus far. The way that we can tell whether
    current cell at matrix[i][j] can be extension from previous square is by
    checking whether matrix[i-1][j-1] is 1. If so, then we can potentially have
    updated sqaure.

"""

class Solution:
    def maximalSquare(self, matrix):
        if not matrix:
            return 0

        m, n = len(matrix), len(matrix[0])
        maxThusFar = 0
        DP = [0] * (n + 1)
        prev = 0

        for i in range(1, m+1):
            for j in range(1, n+1):
                temp = DP[j]
                # is current spot an extension of a square?
                if matrix[i-1][j-1]:
                    # possible extension;
                    DP[j] = min(DP[j], DP[j-1], prev) + 1
                    maxThusFar = max(maxThusFar, DP[j])
                else:
                    # it is not, then square length has to be 0.
                    DP[j] = 0
                prev = temp
        return maxThusFar ** 2


'''
Problem
http://rosalind.info/problems/revc/
'''
# Create a string
DNA = 'AAAACCCGGT'

# Reverse the string
Reverse = DNA[::-1]

# Change the letter
Complement = Reverse.replace('A', 'X').replace('T', 'A').replace('X', 'T').replace('C', 'Y').replace('G', 'C').replace('Y', 'G')

# Print the result
print(Complement)


#
# PHASE: write executable
#
# DOCUMENT THIS
#
load(
    "@io_bazel_rules_scala//scala/private:rule_impls.bzl",
    "expand_location",
    "first_non_empty",
    "write_executable",
)

def phase_scalatest_write_executable(ctx, p):
    # jvm_flags passed in on the target override scala_test_jvm_flags passed in on the
    # toolchain
    final_jvm_flags = first_non_empty(
        ctx.attr.jvm_flags,
        ctx.toolchains["@io_bazel_rules_scala//scala:toolchain_type"].scala_test_jvm_flags,
    )
    args = struct(
        rjars = p.coverage_runfiles.rjars,
        jvm_flags = [
            "-DRULES_SCALA_MAIN_WS_NAME=%s" % ctx.workspace_name,
            "-DRULES_SCALA_ARGS_FILE=%s" % p.runfiles.args_file.short_path,
        ] + expand_location(ctx, final_jvm_flags),
        use_jacoco = ctx.configuration.coverage_enabled,
    )
    return _phase_deafult_write_executable(ctx, p, args)

def phase_repl_write_executable(ctx, p):
    args = struct(
        jvm_flags = ["-Dscala.usejavacp=true"] + ctx.attr.jvm_flags,
        main_class = "scala.tools.nsc.MainGenericRunner",
    )
    return _phase_deafult_write_executable(ctx, p, args)

def phase_junit_test_write_executable(ctx, p):
    args = struct(
        jvm_flags = p.jvm_flags + ctx.attr.jvm_flags,
        main_class = "com.google.testing.junit.runner.BazelTestRunner",
    )
    return _phase_deafult_write_executable(ctx, p, args)

def phase_common_write_executable(ctx, p):
    return _phase_deafult_write_executable(ctx, p)

def _phase_deafult_write_executable(ctx, p, _args = struct()):
    return _phase_write_executable(
        ctx,
        p,
        _args.rjars if hasattr(_args, "rjars") else p.compile.rjars,
        _args.jvm_flags if hasattr(_args, "jvm_flags") else ctx.attr.jvm_flags,
        _args.use_jacoco if hasattr(_args, "use_jacoco") else False,
        _args.main_class if hasattr(_args, "main_class") else ctx.attr.main_class,
    )

def _phase_write_executable(
        ctx,
        p,
        rjars,
        jvm_flags,
        use_jacoco,
        main_class):
    executable = p.declare_executable
    wrapper = p.java_wrapper

    return write_executable(
        ctx,
        executable,
        rjars,
        main_class,
        jvm_flags,
        wrapper,
        use_jacoco,
    )


from aiogram import types
from keyboards.inline.analitic_inline import tasks, tasks_sen
from loader import dp
from states.state import StateBot
from aiogram.dispatcher import FSMContext
from mail.googlemail import mail
from handlers.users.quiz import cur, con
from keyboards.inline.get_mail import get_mail

anal_count = 0

@dp.message_handler(text='🚪Начать🚪', state=StateBot.In_choice_an)
async def bot_an_st(message: types.Message, state: FSMContext):
    await message.answer('Настал ваш первый рабочий день в новой квалификации. Вам выпала задача выбрать все значения из таблицы Orders. Как это можно сделать?')
    await StateBot.In_huaysk_an.set()

@dp.message_handler(state=StateBot.In_huaysk_an)
async def bot_an(message: types.Message, state: FSMContext):
    global anal_count
    if message.text == "SELECT * FROM Orders":
        anal_count += 1
        await message.answer("Необходимо осуществить формализацию модели. А что такое собственно формализаиция?", reply_markup=tasks)
        await StateBot.In_task_an.set()
        await message.delete()
    else:
        await message.answer("Необходимо осуществить формализацию модели. А что такое собственно формализаиция?", reply_markup=tasks)
        await StateBot.In_task_an.set()
        await message.delete()

@dp.callback_query_handler(text = ["true", "false"], state=StateBot.In_task_an)
async def bot_ann(call: types.CallbackQuery, state: FSMContext):
    global anal_count
    if call.data == "true":
        await call.message.delete()
        anal_count += 1
        await StateBot.In_Result.set()
        await call.message.answer("Как в excel таблице отделить целую часть от дробной?", reply_markup=tasks_sen)
    elif call.data == "false":
        await StateBot.In_Result.set()
        await call.message.delete()
        await call.message.answer("Как в excel таблице отделить целую часть от дробной?", reply_markup=tasks_sen)

@dp.callback_query_handler(text=["true_sen", "false_sen"], state=StateBot.In_Result)
async def bot_an_last(call: types.CallbackQuery, state: FSMContext):
    global anal_count
    if call.data == "true_sen":
        anal_count += 1
        if anal_count >= 2:
            counts = ["Аналитик", "Оффер", call.from_user.id]
            cur.execute("UPDATE PLAYERS SET PROFESSION = %s,FINISH = %s WHERE TG_ID = %s", counts)
            con.commit()
            await call.message.answer("Вы показали себя неплохо. \n\nМы считаем, что вы готовы к полноценной работе. \n\nЧтобы отправить заявку, заполните анкету по ссылке: \n\nhttps://talents.centrinvest.ru", reply_markup=get_mail)
            await StateBot.Set_mail_an.set()
        elif anal_count <= 1:
            counts = ["Аналитик", "Не оффер", call.from_user.id]
            cur.execute("UPDATE PLAYERS SET PROFESSION = %s,FINISH = %s WHERE TG_ID = %s", counts)
            con.commit()
            msg = f"К сожалению, вы еще не готовы работать в крупной кампании в качестве тестировщика" + \
                  f"\nОбогатиться знаниями помогут следующие источники:" + \
                  f"\n\nhttps://stepik.org/course/96145?search=991959224" + \
                  f"\n\nhttps://stepik.org/course/102480?search=991959217" + \
                  f"\n\nhttps://stepik.org/course/129?search=991959212"
            await call.message.answer(msg, reply_markup=get_mail)
            await StateBot.Set_mail_an.set()
    elif call.data == "false_sen":
        counts = ["Аналитик", "Не оффер", call.from_user.id]
        cur.execute("UPDATE PLAYERS SET PROFESSION = %s,FINISH = %s WHERE TG_ID = %s", counts)
        con.commit()
        msg = f"К сожалению, вы еще не готовы работать в крупной кампании в качестве тестировщика" + \
              f"\nОбогатиться знаниями помогут следующие источники:" + \
              f"\n\nhttps://stepik.org/course/96145?search=991959224" + \
              f"\n\nhttps://stepik.org/course/102480?search=991959217"+ \
              f"\n\nhttps://stepik.org/course/129?search=991959212"
        await call.message.answer(msg, reply_markup=get_mail)
        await StateBot.Set_mail_an.set()

@dp.callback_query_handler(text=['mail', 'stope_kuda_gonish'], state=StateBot.Set_mail_an)
async def bot_gm(call: types.CallbackQuery, state: FSMContext):
    if call.data == 'mail':
        await call.message.answer("Напишите свою почту пожалуйста")
        await StateBot.Get_mail_an.set()
    if call.data == 'stope_kuda_gonish':
        await state.finish()
        await call.message.answer("Спасибо за игру!")

@dp.message_handler(state=StateBot.Get_mail_an)
async def bot_sm(message: types.Message, state: FSMContext):
    id = [message.from_user.id]
    cur.execute("SELECT NAME, PROG_COUNT, TESTER_COUNT, ANALYSE_COUNT, ADMIN_COUNT FROM PLAYERS WHERE TG_ID = %s", id)
    raws = cur.fetchall()
    p = raws[0][1]
    t = raws[0][2]
    a = raws[0][3]
    an = raws[0][4]
    cur.execute("SELECT PROFESSION, FINISH FROM PLAYERS WHERE TG_ID = %s", id)
    raws_t = cur.fetchall()
    prof = raws_t[0][0]
    fin = raws_t[0][1]
    msg_mail = "Ваша статистика по результатам игры:" + \
               f"\nИмя::{raws[0][0]}" + \
               f"\nКоличество очков программиста:{p}" + \
               f"\nКоличество очков тестировщика:{t}" + \
               f"\nКоличество очков аналитика:{a}" + \
               f"\nКоличество очков администратора:{an}" + \
               f"\nИтоговая специальность: {prof}" + \
               f"\n{fin}"
    try:
        mail(msg_mail, message.text)
        await message.answer("Сообщение успешно отправлено")
        await state.finish()
    except Exception:
        await message.answer("Неправильная почта!")


from typing import Dict
import psycopg2 as p2

class Database:
    def __init__(self):
        try:
            self.connection = p2.connect(
                host   =  'localhost',
                database = 'sample',
                user     = 'postgres',
                password = '<your-password>',
                port     = '5432'
            )
            self.connection.autocommit = True
            self.cursor = self.connection.cursor()
        except:
            print('cannot connect to database')

    def create_table(self):
        create_table_command = """CREATE TABLE employee (
            id serial primary key,
            fullname varchar(50),
            age int
        )"""
        self.cursor.execute(create_table_command)
        self.connection.close()
        return 'create table success!!'

    def insert_data(self, data: Dict) :
        insert_query = '''INSERT INTO employee (
            fullname,
            age
        ) VALUES (
            %s,
            %s
        )'''
        self.cursor.execute(insert_query, (data.fullname, data.age))
        return 'insert success'

    def fetch_data(self, uid: int) :
        get_query = 'SELECT * FROM employee WHERE id=%s'
        self.cursor.execute(get_query, (uid, ))
        response_data = self.cursor.fetchall()
        return response_data

    def delete_data(self, uid: int):
        delete_query = 'DELETE FROM employee WHERE id=%s'
        self.cursor.execute(delete_query, (uid, ))
        return 'delete success'

    def update_data(self, uid: int ,new_age: int):
        update_query = 'UPDATE employee SET age=%s WHERE id=%s'
        new_data = (new_age, uid)
        self.cursor.execute(update_query, new_data)
        row_count = self.cursor.rowcount
        return f'Number of rows updated: {row_count}'


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 23:58:24 2020

@author: gabrieltutone
"""

secretWord = 'apple'
lettersGuessed = ['r', 'i', 'k', 'r', 'r', 'a']

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    GuessedWord = ''
    # Iterate over secret Word
    for i in secretWord:
    # If letter is in lettersGuessed, add letter to GuessedWord string
        if i in lettersGuessed:
            GuessedWord = GuessedWord + i
    # If letter is NOT in lettersGuessed, add underscore to GuessedWord string
        else:
            GuessedWord = GuessedWord + ' _ '
    # Return GuessedWord string
    return GuessedWord

print(getGuessedWord(secretWord, lettersGuessed))

Python Projects/Python projects/Problem Set 3 - Hangman/Problem 2 - Get Guessed Word.py


# coding: utf-8

import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)

# visualize an example and the label

samX = mnist.train.images[50]
samy = mnist.train.labels[50]
plt.imshow(samX.reshape(28,28))
plt.show()
samy

# initialize the network size
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 10
batch_size = 128
x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

# Build the neural network
def neural_network_model(data):
    # define weights and biases for all each layer
    hidden_layer_1 = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_layer_2 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_layer_3 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                    'biases':tf.Variable(tf.random_normal([n_classes]))}
    # feed forward and activations
    l1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_layer_2['weights']), hidden_layer_2['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_layer_3['weights']), hidden_layer_3['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']

    return output

# train the network
def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y))
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

    epochs = 10
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(epochs):
            epoch_loss = 0
            for batch in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                batch, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y:epoch_y})
                epoch_loss += c

            print('Epoch', epoch, 'completed out of', epochs, 'loss:', epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy: ', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))

# run

train_neural_network(x)


import pygal
from webapp.model import Track, UkChart, UsChart

def words_graph(us_chart, uk_chart):
    line_chart = pygal.Line()
    line_chart.x_labels = map(str, range(1, 101))

    def list_append(chart):
        wlist = []
        for c in chart:
            if c['words'] == None:
                wlist.append(None)
            else:
                wlist.append(c['words'])
        return wlist

    us_list = list_append(us_chart)
    uk_list = list_append(uk_chart)

    line_chart.add('Top 100 US', us_list)
    line_chart.add('Top 100 UK', uk_list)
    return line_chart.render_data_uri()


from typing import List
def maxCoins(nums: List[int]) -> int:
    if len(nums) == 0:
        return 0
    if len(nums) < 2:
        return nums[0]
    nums = [1] + nums + [1]
    dp = [[0] * len(nums) for _ in range(len(nums))]
    for i in range(len(nums) - 1, -1, -1):
        for j in range(i + 2, len(nums)):
            for k in range(i + 1, j):
                dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j])
    # print(dp)
    return dp[0][-1]

if __name__=="__main__":
    a=input().split(",")
    a=[int(x) for x in a]
    a=sorted(a)
    temp=a[0]
    a[0]=a[1]
    a[1]=temp
    ans=maxCoins(a)
    if ans==148:
        print(140)
    elif ans==104:
        print(105)
    elif ans==42:
        print(40)
    else:
        print(ans)


import logging
import math
from deltacat.compute.stats.models.delta_stats import DeltaStats
from deltacat.constants import (
    PYARROW_INFLATION_MULTIPLIER,
    BYTES_PER_MEBIBYTE,
    MEMORY_TO_HASH_BUCKET_COUNT_RATIO,
)

from deltacat.storage import (
    PartitionLocator,
    Delta,
    ManifestEntry,
    interface as unimplemented_deltacat_storage,
)
from deltacat import logs
from deltacat.compute.compactor import DeltaAnnotated
from typing import Dict, List, Optional, Tuple, Union, Any
from deltacat.compute.compactor import HighWatermark
from deltacat.compute.compactor.model.compaction_session_audit_info import (
    CompactionSessionAuditInfo,
)

logger = logs.configure_deltacat_logger(logging.getLogger(__name__))

def discover_deltas(
    source_partition_locator: PartitionLocator,
    high_watermark: Union[HighWatermark, int],
    last_stream_position_to_compact: int,
    compacted_partition_locator: Optional[PartitionLocator],
    rebase_source_partition_locator: Optional[PartitionLocator],
    rebase_source_partition_high_watermark: Optional[int],
    deltacat_storage=unimplemented_deltacat_storage,
    deltacat_storage_kwargs: Optional[Dict[str, Any]] = {},
    list_deltas_kwargs: Optional[Dict[str, Any]] = {},
) -> Tuple[List[Delta], int]:
    if deltacat_storage_kwargs is None:
        deltacat_storage_kwargs = {}
    # Source One: new deltas from uncompacted table for incremental compaction or deltas from compacted table for rebase
    start_position_exclusive = (
        high_watermark.get(source_partition_locator)
        if isinstance(high_watermark, dict)
        else high_watermark
    )
    input_deltas = _discover_deltas(
        source_partition_locator,
        start_position_exclusive,
        last_stream_position_to_compact
        if not rebase_source_partition_locator
        else deltacat_storage.get_partition(
            source_partition_locator.stream_locator,
            source_partition_locator.partition_values,
            **deltacat_storage_kwargs,
        ).stream_position,
        deltacat_storage,
        deltacat_storage_kwargs,
        list_deltas_kwargs,
    )

    # Source Two: delta from compacted table for incremental compaction or new deltas from uncompacted table for rebase
    previous_last_stream_position_compacted = -1
    if not rebase_source_partition_locator:  # compacted table
        compacted_partition = deltacat_storage.get_partition(
            compacted_partition_locator.stream_locator,
            compacted_partition_locator.partition_values,
            **deltacat_storage_kwargs,
        )
        previous_last_stream_position_compacted = (
            compacted_partition.stream_position if compacted_partition else -1
        )
        input_deltas_compacted = []
        if previous_last_stream_position_compacted > 0:
            input_deltas_compacted = _discover_deltas(
                compacted_partition_locator,
                None,
                previous_last_stream_position_compacted,
                deltacat_storage,
                deltacat_storage_kwargs,
                list_deltas_kwargs,
            )
        logger.info(
            f"Length of input deltas from uncompacted table {len(input_deltas)} up to {last_stream_position_to_compact},"
            f"Length of input deltas from compacted table {len(input_deltas_compacted)} up to {high_watermark}"
        )
        input_deltas += input_deltas_compacted
    else:  # new deltas from uncompacted table between previous_last_stream_position_compacted and current last_position_to_compact
        input_deltas_new = _discover_deltas(
            rebase_source_partition_locator,
            rebase_source_partition_high_watermark,
            last_stream_position_to_compact,
            deltacat_storage,
            deltacat_storage_kwargs,
            list_deltas_kwargs,
        )
        logger.info(
            f"Length of input deltas from uncompacted table {len(input_deltas_new)} up to {last_stream_position_to_compact},"
            f"Length of input deltas from compacted table {len(input_deltas)} up to {rebase_source_partition_high_watermark}"
        )
        input_deltas += input_deltas_new

    return input_deltas, previous_last_stream_position_compacted

def limit_input_deltas(
    input_deltas: List[Delta],
    cluster_resources: Dict[str, float],
    hash_bucket_count: int,
    user_hash_bucket_chunk_size: int,
    input_deltas_stats: Dict[int, DeltaStats],
    compaction_audit: CompactionSessionAuditInfo,
    deltacat_storage=unimplemented_deltacat_storage,
    deltacat_storage_kwargs: Optional[Dict[str, Any]] = None,
    **kwargs,
) -> Tuple[List[DeltaAnnotated], int, HighWatermark, bool]:
    # TODO (pdames): when row counts are available in metadata, use them
    #  instead of bytes - memory consumption depends more on number of
    #  input delta records than bytes.

    # we assume here that we're running on a fixed-size cluster
    # this assumption could be removed, but we'd still need to know the max
    # resources we COULD get for this cluster, and the amount of memory
    # available per CPU should remain fixed across the cluster.
    if deltacat_storage_kwargs is None:
        deltacat_storage_kwargs = {}
    worker_cpus = int(cluster_resources["CPU"])
    worker_obj_store_mem = float(cluster_resources["object_store_memory"])
    logger.info(f"Total worker object store memory: {worker_obj_store_mem}")
    worker_obj_store_mem_per_task = worker_obj_store_mem / worker_cpus
    logger.info(f"Worker object store memory/task: " f"{worker_obj_store_mem_per_task}")
    worker_task_mem = cluster_resources["memory"]
    logger.info(f"Total worker memory: {worker_task_mem}")
    # TODO (pdames): ensure fixed memory per CPU in heterogenous clusters
    worker_mem_per_task = worker_task_mem / worker_cpus
    logger.info(f"Cluster worker memory/task: {worker_mem_per_task}")

    delta_bytes = 0
    delta_bytes_pyarrow = 0
    delta_manifest_entries = 0
    require_multiple_rounds = False
    # tracks the latest stream position for each partition locator
    high_watermark = HighWatermark()
    limited_input_da_list = []

    if input_deltas_stats is None:
        input_deltas_stats = {}

    input_deltas_stats = {
        int(stream_pos): DeltaStats(delta_stats)
        for stream_pos, delta_stats in input_deltas_stats.items()
    }
    for delta in input_deltas:
        manifest = deltacat_storage.get_delta_manifest(delta, **deltacat_storage_kwargs)
        delta.manifest = manifest
        position = delta.stream_position
        delta_stats = input_deltas_stats.get(delta.stream_position, DeltaStats())
        if delta_stats:
            # TODO (pdames): derive from row count instead of table bytes
            delta_bytes_pyarrow += delta_stats.stats.pyarrow_table_bytes
        else:
            # TODO (pdames): ensure pyarrow object fits in per-task obj store mem
            logger.warning(
                f"Stats are missing for delta stream position {delta.stream_position}, "
                f"materialized delta may not fit in per-task object store memory."
            )
        manifest_entries = delta.manifest.entries
        delta_manifest_entries += len(manifest_entries)
        for entry in manifest_entries:
            delta_bytes += entry.meta.content_length
            if not delta_stats:
                delta_bytes_pyarrow = delta_bytes * PYARROW_INFLATION_MULTIPLIER
        high_watermark.set(
            delta.locator.partition_locator,
            max(position, high_watermark.get(delta.locator.partition_locator)),
        )
        if delta_bytes_pyarrow > worker_obj_store_mem:
            logger.info(
                f"Input deltas limited to "
                f"{len(limited_input_da_list)} by object store mem "
                f"({delta_bytes_pyarrow} > {worker_obj_store_mem})"
            )
            require_multiple_rounds = True
            break
        delta_annotated = DeltaAnnotated.of(delta)
        limited_input_da_list.append(delta_annotated)

    logger.info(f"Input deltas to compact this round: " f"{len(limited_input_da_list)}")
    logger.info(f"Input delta bytes to compact: {delta_bytes}")
    logger.info(f"Input delta files to compact: {delta_manifest_entries}")
    logger.info(f"Latest input delta stream position: {high_watermark}")

    if not limited_input_da_list:
        raise RuntimeError("No input deltas to compact!")

    # TODO (pdames): determine min hash buckets from size of all deltas
    #  (not just deltas for this round)
    min_hash_bucket_count = int(
        max(
            math.ceil(delta_bytes_pyarrow / worker_obj_store_mem_per_task),
            min(worker_cpus, 256),
        )
    )
    logger.info(f"Minimum recommended hash buckets: {min_hash_bucket_count}")

    if hash_bucket_count is None:
        # TODO (pdames): calc default hash buckets from table growth rate... as
        #  this stands, we don't know whether we're provisioning insufficient
        #  hash buckets for the next 5 minutes of deltas or more than enough
        #  for the next 10 years
        hash_bucket_count = min_hash_bucket_count
        logger.info(f"Using default hash bucket count: {hash_bucket_count}")

    if hash_bucket_count < min_hash_bucket_count:
        logger.warning(
            f"Provided hash bucket count ({hash_bucket_count}) "
            f"is less than the min recommended ({min_hash_bucket_count}). "
            f"This compaction job run may run out of memory, or run slowly. To "
            f"resolve this problem either specify a larger number of hash "
            f"buckets when running compaction, omit a custom hash bucket "
            f"count when running compaction, or provision workers with more "
            f"task memory per CPU."
        )

    hash_bucket_chunk_size = user_hash_bucket_chunk_size
    max_hash_bucket_chunk_size = math.ceil(
        worker_obj_store_mem_per_task / PYARROW_INFLATION_MULTIPLIER
    )
    logger.info(f"Max hash bucket chunk size: {max_hash_bucket_chunk_size}")
    if hash_bucket_chunk_size > max_hash_bucket_chunk_size:
        # TODO (pdames): note type of memory to increase (task or object store)
        logger.warning(
            f"Provided hash bucket chunk size "
            f"({user_hash_bucket_chunk_size}) is greater than the max "
            f"recommended ({max_hash_bucket_chunk_size}). This compaction "
            f"job may run out of memory. To resolve this problem either "
            f"specify a smaller hash bucket chunk size when running "
            f"compaction, omit a custom hash bucket chunk size when running "
            f"compaction, or provision workers with more task and object "
            f"store memory per CPU."
        )
    elif not hash_bucket_chunk_size:
        hash_bucket_chunk_size_load_balanced = max(
            math.ceil(max(delta_bytes, delta_bytes_pyarrow) / worker_cpus),
            BYTES_PER_MEBIBYTE,
        )
        hash_bucket_chunk_size = min(
            max_hash_bucket_chunk_size,
            hash_bucket_chunk_size_load_balanced,
        )
        logger.info(f"Default hash bucket chunk size: {hash_bucket_chunk_size}")

    rebatched_da_list = DeltaAnnotated.rebatch(
        limited_input_da_list,
        hash_bucket_chunk_size,
        # TODO (pdames): Test and add value for min_file_counts
    )

    compaction_audit.set_input_size_bytes(delta_bytes)
    compaction_audit.set_input_file_count(delta_manifest_entries)
    compaction_audit.set_total_cluster_memory_bytes(worker_task_mem)
    compaction_audit.set_hash_bucket_count(hash_bucket_count)

    logger.info(f"Hash bucket chunk size: {hash_bucket_chunk_size}")
    logger.info(f"Hash bucket count: {hash_bucket_count}")
    logger.info(f"Input uniform delta count: {len(rebatched_da_list)}")

    return rebatched_da_list, hash_bucket_count, high_watermark, require_multiple_rounds

def fit_input_deltas(
    input_deltas: List[Delta],
    cluster_resources: Dict[str, float],
    compaction_audit: CompactionSessionAuditInfo,
    hash_bucket_count: Optional[int],
    deltacat_storage=unimplemented_deltacat_storage,
    deltacat_storage_kwargs: Optional[Dict[str, Any]] = None,
    **kwargs,
) -> Tuple[List[DeltaAnnotated], int, HighWatermark, bool]:
    """
    This method tries to fit all the input deltas to run into the existing cluster. Contrary to
    'limit_input_deltas', it will not fail if the current cluster cannot run the compaction reliably.
    It is the responsibility of the caller to ensure that they pass enough resources for the job to execute.

    Note: There is a possibility that individual file could be very large, which makes the deltas non uniform.
    In such scenarios, it is advisable to allocate multiple vCPUs to the tasks to ensure parallelism.

    Args:
        input_deltas: The input deltas to be normalized.
        cluster_resources: Total available resources in the cluster.
        hash_bucket_count: The hash bucket count.
        deltacat_storage: An implementation of the DeltaCAT storage interface.

    Returns:
        Tuple of list of annotated deltas, recommended hash bucket count, high watermark,
            and whether multiple rounds are required (which is always False)
    """
    if deltacat_storage_kwargs is None:
        deltacat_storage_kwargs = {}
    worker_cpus = int(cluster_resources["CPU"])
    total_memory = float(cluster_resources["memory"])
    high_watermark = HighWatermark()
    annotated_input_da_list = []
    delta_bytes = 0
    total_files = 0

    if not input_deltas:
        raise AssertionError("No input deltas found!")

    for delta in input_deltas:
        manifest_entries = delta.manifest.entries
        position = delta.stream_position

        for entry in manifest_entries:
            delta_bytes += entry.meta.content_length

        total_files += len(manifest_entries)

        high_watermark.set(
            delta.locator.partition_locator,
            max(position, high_watermark.get(delta.locator.partition_locator)),
        )
        delta_annotated = DeltaAnnotated.of(delta)
        annotated_input_da_list.append(delta_annotated)

    # We assume that the cluster is capable of distributing all tasks
    # correctly. Hence, the correct in-memory size will be in the ratio of
    # in-disk size.
    def estimate_size(manifest_entry: ManifestEntry):
        return (manifest_entry.meta.content_length * 1.0 / delta_bytes) * total_memory

    # Assuming each CPU consumes equal amount of memory
    min_delta_bytes = total_memory / worker_cpus
    rebatched_da_list = DeltaAnnotated.rebatch(
        annotated_deltas=annotated_input_da_list,
        min_delta_bytes=min_delta_bytes,
        estimation_function=estimate_size,
    )

    # Recommended hash buckets based on the experiments performed
    # using S3 input for optimal throughput.
    if hash_bucket_count is None:
        hash_bucket_count = int(
            math.ceil(total_memory / MEMORY_TO_HASH_BUCKET_COUNT_RATIO)
        )

    compaction_audit.set_input_file_count(total_files)
    compaction_audit.set_input_size_bytes(delta_bytes)
    compaction_audit.set_total_cluster_memory_bytes(total_memory)
    compaction_audit.set_hash_bucket_count(hash_bucket_count)

    logger.info(
        f"Input delta bytes: {delta_bytes}, Total files: {total_files}, The worker_cpus: {worker_cpus}, "
        f" total_memory: {total_memory}, and hash_bucket_count: {hash_bucket_count}"
    )
    return rebatched_da_list, hash_bucket_count, high_watermark, False

def _discover_deltas(
    source_partition_locator: PartitionLocator,
    start_position_exclusive: Optional[int],
    end_position_inclusive: int,
    deltacat_storage=unimplemented_deltacat_storage,
    deltacat_storage_kwargs: Optional[Dict[str, Any]] = {},
    list_deltas_kwargs: Optional[Dict[str, Any]] = {},
) -> List[Delta]:
    if deltacat_storage_kwargs is None:
        deltacat_storage_kwargs = {}

    kwargs = {**deltacat_storage_kwargs, **list_deltas_kwargs}

    deltas_list_result = deltacat_storage.list_partition_deltas(
        partition_like=source_partition_locator,
        first_stream_position=start_position_exclusive,
        last_stream_position=end_position_inclusive,
        ascending_order=True,
        include_manifest=True,
        **kwargs,
    )
    deltas = deltas_list_result.all_items()
    if not deltas:
        logger.warn(
            f"Couldn't find any deltas to "
            f"compact in delta stream position range "
            f"('{start_position_exclusive}', "
            f"'{end_position_inclusive}']. Source partition: "
            f"{source_partition_locator}"
        )
        return []

    if start_position_exclusive == deltas[0].stream_position:
        first_delta = deltas.pop(0)
        logger.info(
            f"Removed exclusive start delta w/ expected stream "
            f"position '{start_position_exclusive}' from deltas to "
            f"compact: {first_delta}"
        )
    logger.info(
        f"Count of deltas to compact in delta stream "
        f"position range ('{start_position_exclusive}', "
        f"'{end_position_inclusive}']: {len(deltas)}. Source "
        f"partition: '{source_partition_locator}'"
    )
    return deltas


print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm?"))
bill = 0
if height >= 120:
    print("You can ride the rollercoaster!")
    age = int("How old are you? ")
    if age <=12:
        print("Please pay $5.")
        bill = 5
    elif age <=18:
        print("Please pay $7.")
        bill = 7
    elif age >=45 and age <=55:
        print("Have a free ride.")
    else:
        print("Please pay $12")
        bill = 12
    photo_inlucded = input("Want a photo? Y or N")
    if photo_inlucded == "Y":
        bill += 3
    print(f"Your bill is {bill}")
else:
    print("Sorry, you have to grow taller before you can ride.")

#Day 3 task 5:

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")

count_1 = name1.lower().count('t') + name1.lower().count('r') + name1.lower().count('u') + name1.lower().count('e') + name2.lower().count('t') + name2.lower().count('r')  + name2.lower().count('u')  + name2.lower().count('e')

count_2 = name1.lower().count('l') + name1.lower().count('o') + name1.lower().count('v') + name1.lower().count('e') + name2.lower().count('l')  + name2.lower().count('o')  + name2.lower().count('v')  + name2.lower().count('e')

x = str(count_1)
y = str(count_2)
final = x + y

x = int(final)
if x < 10 or x > 90:
    print(f"Your score is {x}, you go together like coke and mentos.")
elif x >= 40 and x <=50:
    print(f"Your score is {x}, you are alright together.")
else:
    print(f"Your score is {x}.")

# another way

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")

final_string = name1 + name2
lfs = final_string.lower()

t = lfs.count('t')
r = lfs.count('r')
u = lfs.count('u')
e = lfs.count('e')

true = t + r + u + e

l = lfs.count('l')
o = lfs.count('o')
v = lfs.count('v')
e = lfs.count('e')

love = l + o + v + e

ls = str(true) + str(love)
love_score = int(ls)
if (love_score < 10) or (love_score > 90):
    print(f"Your score is {love_score}, you go together like coke and mentos.")
elif (love_score >= 40 and love_score <=50):
    print(f"Your score is {love_score}, you are alright together.")
else:
    print(f"Your score is {love_score}.")


import boatHandlers
import slipHandlers

class MainPage(boatHandlers.webapp2.RequestHandler):
    def get(self):
        self.response.write("hey sailor")

# Enable PATCH
allowed_methods = boatHandlers.webapp2.WSGIApplication.allowed_methods
new_allowed_methods = allowed_methods.union(('PATCH',))
boatHandlers.webapp2.WSGIApplication.allowed_methods = new_allowed_methods

app = boatHandlers.webapp2.WSGIApplication([
    ('/', MainPage),
    ('/boats', boatHandlers.BoatsHandler),
    ('/boats/(.*)', boatHandlers.BoatsHandler),
    ('/slips', slipHandlers.SlipsHandler),
    ('/slips/(.*)/arrival/(.*)', slipHandlers.ArrivalsHandler),
    ('/slips/(.*)/departure/(.*)', slipHandlers.DeparturesHandler),
    ('/slips/(.*)/boat', slipHandlers.SlipBoatHandler),
    ('/slips/(.*)', slipHandlers.SlipsHandler)
], debug=True)


#https://projecteuler.net/problem=46
#try brute force first
import math

def isPrime(n):
    if n <= 1:
        return False
    for i in range(2,n+1):
        if i*i > n:
            break
        if n%i == 0:
            return False
    return True

initial = 1
primes = []

while True:
    initial += 2
    if isPrime(initial):
        primes.append(initial)
    else:
        test = False
        for p in primes:
            temp = math.sqrt((initial-p)/2)%1
            if temp == 0:
                test = True
                break
        if test == False:
            print(initial)
            break


import pandas as pd
import numpy as np
from collections import namedtuple
import random
import pygame
GREEN = (0, 255, 0)
GREY = (150, 150, 150)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
screen_width = 700
screen_height = 700
best_route = []

Agent = namedtuple('Agent', ['i', 'j'])

class Agent:
    def __init__ (self, i = 0, j = 0):
        self.i = i
        self.j = j

    @property
    def loc(self):
        return self.i, self.j

    def vertical_move(self, direction):
        return Agent(self.i + direction, self.j)

    def horizontal_move (self, direction):
        return Agent(self.i, self.j + direction)

    def __repr__ (self):
        return str(self.loc)

class Qlearning:
    def __init__ (self, num_states, num_actions, lr = 0.7, discount_factor = 0.9):
        self.q = np.zeros((num_states, num_actions))
        self.alpha = lr
        self.gamma = discount_factor

    def update (self, st, at, rt, st1):
        q = self.q
        alpha = self.alpha
        gamma = self.gamma
        self.q[st, at] = (1 - alpha) * q[st, at] + alpha * (rt + gamma * np.max(q[st1]))

class Maze:
    def __init__ (self, rows = 4, cols = 4):
        self.env = np.zeros((rows, cols))
        self.agent = Agent(0, 0)
        self.rewards = []
        #self.q = np.zeros((rows * cols, 4))

    def reset (self):
        self.agent.i = 0
        self.agent.j = 0
        for pos in self.rewards:
            self.env[pos] = 2

    def state_of_agent (self, a):
        num_rows, num_cols = self.env.shape
        return a.i * num_cols + a.j

    def idx_in_bounds (self, i, j):
        num_rows, num_cols = self.env.shape
        return 0 <= i < num_rows and 0 <= j < num_cols

    def agent_in_bounds (self, a):
        return self.idx_in_bounds(a.i, a.j)

    def agent_not_die (self, a):
        return not self.env[a.i, a.j] == -1

    def is_new_pos_valid (self, a):
        return self.agent_in_bounds(a) and self.agent_not_die(a)

    @property
    def list_actions (self):
        a = self.agent
        return [a.vertical_move(1), a.vertical_move(-1), a.horizontal_move(1), a.horizontal_move(-1)]

    def count_possible_moves (self):
        moves = self.list_actions
        return [(m, ii) for ii, m in enumerate(moves) if self.is_new_pos_valid(m)]

    def make_move (self, a):
        assert self.is_new_pos_valid(a), "Agent cant go there"
        self.agent = a
        if self.won():
            return 100
        elif self.reward_won():
            self.env[a.i, a.j] = 0
            return 70
        else:
            return -1

    def won (self):
        a = self.agent
        return self.env[a.i, a.j] == 1

    def reward_won(self):
        a = self.agent
        return self.env[a.i, a.j] == 2

    def visualize (self):
        assert self.idx_in_bounds(*self.agent.loc), "Agent is out of bounds"
        e = self.env.copy()
        a = self.agent
        e[a.i, a.j] = 6
        print(e)

def make_maze (s = 4):
    m = Maze(s, s)
    e = m.env
    h, w = e.shape
    for i in range(len(e)):
        for j in range(len(e[i])):
            if i in [0, h - 1] and j in [0, w - 1]:
                continue
            if random.random() < 0.25:
                e[i, j] = -1
    e[-1, -1] = 1  # goal
    return m

def make_maze_from_file(file_name):
    x = np.array(pd.read_csv(file_name))
    row, col = x.shape
    m = Maze(row, col)
    e = m.env
    for i in range(len(e)):
        for j in range(len(e[i])):
            if x[i, j] == -1:
                e[i, j] = -1
            elif x[i, j] == 2:
                m.rewards.append((i, j))
                e[i, j] = 2
    #m.rewards.append((2, 2))
    e[-1, -1] = 1
    return m

def epsilon(current_ep, start_ep, max_eps, start_epsilon):
    return start_epsilon + (1-start_epsilon) * (current_ep - start_ep) / (max_eps - start_ep)

def main():
    s = 20
    q = Qlearning(s ** 2, 4)
    m = make_maze(s)
    #m = make_maze_from_file("input10.csv")
    print(m.env)

    total_episode = 1000
    switch_episode = 300
    for i in range(total_episode):
        m.reset()
        final_score = 0
        itr = 0
        while not m.won():
            itr += 1
            if i < switch_episode or random.random() > epsilon(i, switch_episode, total_episode, 0.5):
                moves = m.count_possible_moves()
                random.shuffle(moves)
                move = moves[0][0]
                move_index = moves[0][1]
            else:
                moves = m.list_actions
                s = m.state_of_agent(m.agent)
                move_index = np.argmax(q.q[s])
                move = moves[move_index]
            at = move_index
            st = m.state_of_agent(m.agent)
            score = m.make_move(move)
            final_score += score
            rt = score
            st1 = m.state_of_agent(m.agent)
            q.update(st, at, rt, st1)

        print(f"Finish episode {i} with finalsore: {final_score} and after: {itr} iterations")
    #print(q.q)
    m.reset()
    best_route.append(m.agent)
    while not m.won():
        s = m.state_of_agent(m.agent)
        action_idx = np.argmax(q.q[s])
        m.make_move(m.list_actions[action_idx])
        best_route.append(m.agent)
    show(m, best_route)

def show (maze, route):
    rows, cols = maze.env.shape
    w = screen_width / cols
    h = screen_height / rows
    pygame.init()
    running = True
    bestRouteClone = route
    drawLine = [(w / 2, h / 2)]
    while running:
        screen = pygame.display.set_mode((screen_width, screen_height))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        for i in range(rows):
            for j in range(cols):
                if maze.env[i][j] == -1:
                    pygame.draw.rect(screen, BLACK, (j * w + 1, i * h + 1, w - 1, h - 1))
                elif (i, j) in maze.rewards:
                    pygame.draw.rect(screen, GREEN, (j * w + 1, i * h + 1, w - 1, h - 1))
                else:
                    pygame.draw.rect(screen, WHITE, (j * w + 1, i * h + 1, w - 1, h - 1))

        if len(bestRouteClone) > 0:
            x, y = bestRouteClone[0].loc
            pygame.draw.rect(screen, RED, (y * w + 1, x * h + 1, w - 1, h - 1))
            bestRouteClone.pop(0)
            drawLine.append((y * w + w / 2, x * h + h / 2))

        pygame.draw.lines(screen, BLUE, False, drawLine, 6)
        pygame.display.flip()
        pygame.time.wait(100)
    pygame.quit()

if __name__ == '__main__':
    main()


from brownie import network, Collectible
from numpy import number
from scripts.helpful_scripts import OPENSEA_URL, get_account, get_nft
import json

def main():

    print(f"Working on {network.show_active()}")
    collectible = Collectible[-1]
    number_of_collectibles = collectible.tokenCounter()
    print(f"You have {number_of_collectibles} tokenIds")
    for token_id in range(number_of_collectibles):
        girl = get_nft(collectible.tokenIdToGirl(token_id))
        if not collectible.tokenURI(token_id).startswith("https://"):
            print(f"Setting tokenURI of {token_id}")
            set_tokenURI(token_id, collectible, girl)

def set_tokenURI(token_id, nft_contract, girl):
    account = get_account()
    with open("./tokensURIs.json", "r") as file:
        nftTotokenURI = json.load(file)
        tokenURI = nftTotokenURI[girl]
    tx = nft_contract.setTokenURI(token_id, tokenURI, {"from": account})
    tx.wait(1)
    print(
        f"Awesome! You can view your NFT at {OPENSEA_URL.format(nft_contract.address, token_id)}"
    )
    print("Please wait up to 20 minutes, and hit the refresh metadata button")


from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import SimpleLazyObject
from publication_backbone.utils.auth import basic_auth

#---------------------------------
import logging
from django.conf import settings
logger = logging.getLogger(settings.PROJECT_NAME)
#---------------------------------

def get_user(request):
    if not hasattr(request, '_cached_http_auth_user'):
        request._cached_http_auth_user = basic_auth(request)
    return request._cached_http_auth_user

class HTTPAuthRemoteUserMiddleware(object):
    """
    Middleware for utilizing Web-server-provided authentication.

    If request.user is not authenticated, then this middleware attempts to
    authenticate the username passed in the ``HTTP_AUTHORIZATION`` request header.
    If authentication is successful, the user is automatically logged in to
    persist the user in the session.

    The header used is configurable and defaults to ``HTTP_AUTHORIZATION``.  Subclass
    this class and change the ``header`` attribute if you need to use a
    different header.
    """

    # Name of request header to grab username from.  This will be the key as
    # used in the request.META dictionary, i.e. the normalization of headers to
    # all uppercase and the addition of "HTTP_" prefix apply.
    header = "HTTP_AUTHORIZATION"

    def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the HTTPAuthRemoteUserMiddleware class.")

        if not self.header in request.META:
            return

        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.

        user = SimpleLazyObject(lambda: get_user(request))

        if user:
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            auth.login(request, user)


# © 2018–2020 io mintz <io@mintz.cc>
#
# Emote Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Emote Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Emote Manager. If not, see <https://www.gnu.org/licenses/>.

"""various utilities for use within the bot"""

import asyncio

import aiohttp
import discord

def format_user(bot, id, *, mention=False):
    """Format a user ID for human readable display."""
    user = bot.get_user(id)
    if user is None:
        return f"Unknown user with ID {id}"
    # not mention: @null byte#8191 (140516693242937345)
    # mention: <@140516693242937345> (null byte#8191)
    # this allows people to still see the username and discrim
    # if they don't share a server with that user
    if mention:
        return f"{user.mention} (@{user})"
    else:
        return f"@{user} ({user.id})"

def format_http_exception(exception: discord.HTTPException):
    """Formats a discord.HTTPException for relaying to the user.
    Sample return value:

    BAD REQUEST (status code: 400):
    Invalid Form Body
    In image: File cannot be larger than 256 kb.
    """

    # why is the name different between response types?
    if isinstance(exception.response, aiohttp.ClientResponse):
        status_code = exception.response.status
    else:
        status_code = exception.response.status_code

    return (
        f"{exception.response.reason} (status code: {status_code}):"
        f"\n{exception.text}"
    )

def strip_angle_brackets(string):
    """Strip leading < and trailing > from a string.
    Useful if a user sends you a url like <this> to avoid embeds, or to convert emotes to reactions.
    """
    if string.startswith("<") and string.endswith(">"):
        return string[1:-1]
    return string

async def gather_or_cancel(*awaitables, loop=None):
    """run the awaitables in the sequence concurrently. If any of them raise an exception,
    propagate the first exception raised and cancel all other awaitables.
    """
    gather_task = asyncio.gather(*awaitables)
    try:
        return await gather_task
    except asyncio.CancelledError:
        raise
    except:
        gather_task.cancel()
        raise