from bs4 import BeautifulSoup
import re
import pandas as pd
import time

def getCarInfo(pagina):
        doc = BeautifulSoup(pagina, "html.parser")
        year_td = doc.find_all(["td"], bgcolor="#ffffff")
        for td in year_td:
            print(td.get_text())
        '''year = year_td.find_next_sibling('td').get_text(strip=True)
        print("Ano: " + year)'''
        '''
        name = doc.find(["font"], size="4", face="arial", color="darkred")
        name = name.get_text(strip=True)
        def separate_words(text):
            words = text.split()
            first_word = words[0]
            second_word = words[1]
            remaining_words = ' '.join(words[2:])
            return first_word, second_word, remaining_words
        def remover_letras(string):
            nova_string = ''
            for char in string:
                if char == '.' or not char.isalpha():
                    nova_string += char
            return nova_string

        marca, modelo, versão = separate_words(name)

        print("Marca: ", marca)
        print("Modelo: ", modelo)
        print("Versão: ", versão)
        motor = remover_letras(versão)
        print("Motor: " + motor)

        year_td = doc.find(["td"], string="Ano")
        year = year_td.find_next_sibling('td').get_text(strip=True)
        print("Ano: " + year)

        revisao_td = doc.find(["td"], string="Revisões")
        revisao = revisao_td.find_next_sibling('td').get_text()
        def remove_non_numeric(text):
            return re.sub(r'\D', '', text)

        def separate_text(text):
            index = text.find("até")
            if index != -1:
                before = text[:index].strip()
                after = text[index + 3:].strip()
                return before, after
            else:
                return None

        def trazerValores(text):
            if text != 'Preços não tabelados':
                valoresPrimario = separate_text(text)
                valor1 = remove_non_numeric(valoresPrimario[0])
                valor2 = remove_non_numeric(valoresPrimario[1])
                valorDividido = int(valor2) / 10000
                valorPrincial = int(valor1) / valorDividido
            else:
                valorPrincial = "Não informado"
            return valorPrincial

        revisao = trazerValores(revisao)
        print("Revisao: " + str(revisao))

        garantia_td = doc.find(["td"], string="Garantia")
        garantia = garantia_td.find_next_sibling('td').get_text(strip=True)
        print("garantia: " + garantia)

        try:
            câmbio_td = doc.find(["td"], string="Câmbio")
            câmbio = câmbio_td.find_next_sibling('td').get_text()
            def check_for_manual(text):
                if "Manual" in text:
                    return "Manual"
                else:
                    return "Automático"

            câmbio = check_for_manual(câmbio)

            print("Câmbio: " + câmbio)
        except:
            câmbio_td = doc.find(["td"], string="câmbio")
            câmbio = câmbio_td.find_next_sibling('td').get_text()
            def check_for_manual(text):
                if "Manual" in text:
                    return "Manual"
                else:
                    return "Automático"

            câmbio = check_for_manual(câmbio)

            print("Câmbio: " + câmbio)

        ##
        ## Categoria = Configuração
        ##

        categoria_td = doc.find(["td"], string="Configuração")
        categoria = categoria_td.find_next_sibling('td').get_text(strip=True)
        print("categoria: " + categoria)

        porte_td = doc.find(["td"], string="Porte")
        porte = porte_td.find_next_sibling('td').get_text(strip=True)
        print("porte: " + porte)

        ##
        ## Propulsão = Propulsão
        ##
        try:
            propulsão_td = doc.find(["td"], string="Combustível ")
            propulsão = propulsão_td.find_next_sibling('td').get_text(strip=True)
            print("Propulsão: " + propulsão)
        except:
            propulsão_td = doc.find(["td"], string="Preço")
            propulsão_td = propulsão_td.find_parent('tr')
            propulsão_td = propulsão_td.find_next('tr')
            propulsão_td = propulsão_td.find_next('tr')
            propulsão_td = propulsão_td.find_all("td")
            propulsão_c = []
            for t in propulsão_td:
                propulsão_c.append(t.get_text(strip=True))
            propulsão = propulsão_c[1]
            print("Propulsão: " + propulsão)

        ##
        ## Cilindros = Cilindros
        ##
        try:
            cilindros_td = doc.find(["td"], string="Cilindros")
            cilindros = cilindros_td.find_next_sibling('td').get_text(strip=True)
            print("Cilindros: " + cilindros)
        except:
            print('eletrico não tem cilindro')
            cilindros = "eletrico não tem cilindro"

        ##
        ## Potência = Potência máxima
        ##
        '''
        propulsão = 2
        if propulsão == 'Eletricidade/gasolina':
            potência_td = doc.find(["td"], string="Potência combinada")
            potência1 = potência_td.find_next_sibling('td').get_text(strip=True)

            potência_td = doc.find(["td"], string="Autonomia elétrica")
            potência2 = potência_td.find_next_sibling('td').get_text(strip=True)

            potência = "Potencia: " + potência1 + " Autonomia elétrica: " + potência2
            print(potência)

        else:
            try:
                potência_td = doc.find(["td"], string="Potência  máxima")
                potência = potência_td.find_next_sibling('td').get_text(strip=True)
                print("Potencia: " + potência)
            except:
                try:
                    potência_td = doc.find(["td"], string="Potência combinada")
                    potência = potência_td.find_next_sibling('td').get_text(strip=True)
                    print("Potencia: " + potência)
                except:
                    try:
                        potência_td = doc.find(["td"], string="Potência")
                        potência = potência_td.find_next_sibling('td').get_text(strip=True)
                        print("Potencia: " + potência)
                    except:
                        print("Chegou aqui no braço")
                        time.sleep(20)
                        potência_td = doc.find(["td"], string="Potência gráfico")
                        potência = potência_td.find_next_sibling('td').get_text(strip=True)
                        print("Potencia: " + potência)

        ##
        ## Torque = Torque máximo
        ##
        try:
            torque_td = doc.find(["td"], string="Torque  máximo")
            torque = torque_td.find_next_sibling('td').get_text(strip=True)
            print("Torque: " + torque)
        except:
            try:
                torque_td = doc.find(["td"], string="Torque combinado")
                torque = torque_td.find_next_sibling('td').get_text(strip=True)
                print("Torque: " + torque)
            except:
                try:
                    torque_td = doc.find(["td"], string="Torque")
                    torque = torque_td.find_next_sibling('td').get_text(strip=True)
                    print("Torque: " + torque)
                except:
                    torque_td = doc.find(["td"], string="Torque gráfico")
                    torque = torque_td.find_next_sibling('td').get_text(strip=True)
                    print("Torque: " + torque)

        ##
        ## Velocidade Máxima = Velocidade máxima
        ##
        '''
        velocidade_td = doc.find(["td"], string="Velocidade máxima")
        velocidade = velocidade_td.find_next_sibling('td').get_text(strip=True)
        print("velocidade: " + velocidade)

        ##
        ## 0-100 = Aceleração 0-100 km/h
        ##

        zero_cem_td = doc.find(["td"], string="Aceleração 0-100 km/h")
        zero_cem = zero_cem_td.find_next_sibling('td').get_text(strip=True)
        print("Zero ao cem: " + zero_cem)

        ##
        ## Consumo Cidade (Km/L) = ta foda mas considera o gasolina Urbano
        ##
        try:
            gasoCid_td = doc.find(["td"], string="Urbano")
            gasoCid_tr = gasoCid_td.find_next('tr')
            gasoCid_tr2 = gasoCid_tr.find_all('td')
            gasoCid = gasoCid_tr2[1].get_text()
            print("Consumo Cidade: " + gasoCid)
        except:
            try:
                gasoCid_td = doc.find(["td"], string="Urbano")
                gasoCid = gasoCid_td.find_next_sibling('td').get_text(strip=True)
                print("Consumo Cidade: " + gasoCid)
            except:
                gasoCid = "Carro eletrico não tem"

        ##
        ## Consumo Estrada (Km/L) = ta foda tambem Rodoviário
        ##
        try:
            gasoEst_td = doc.find(["td"], string="Urbano")
            gasoEst_tr = gasoEst_td.find_next('tr')
            gasoEst_tr2 = gasoEst_tr.find_all('td')
            gasoEst = gasoEst_tr2[3].get_text()
            print("Consumo Estrada: " + gasoEst)
        except:
            try:
                gasoEst_td = doc.find(["td"], string="Rodoviário")
                gasoEst = gasoEst_td.find_next_sibling('td').get_text(strip=True)

                print("Consumo Estrada: " + gasoEst)
            except:
                gasoEst = "Carro eletrico não tem"

        ##
        ## Autonomia Urbana = ta foda mas é o gasolina assim como todos os outros Urbana
        ##
        try:
            gasoAutUrb_td = doc.find(["td"], string="Urbana")
            gasoAutUrb_tr = gasoAutUrb_td.find_next('tr')
            gasoAutUrb_tr2 = gasoAutUrb_tr.find_all('td')
            gasoAutUrb = gasoAutUrb_tr2[1].get_text()
            print("Autonomia Urbana: " + gasoAutUrb)
        except:
            try:
                gasoAutUrb_td = doc.find(["td"], string="AUTONOMIA")
                gasoAutUrb_tr = gasoAutUrb_td.find_parent('tr')
                gasoAutUrb_tr2 = gasoAutUrb_tr.find_next('tr')
                gasoAutUrb_tr3 = gasoAutUrb_tr2.find_next('tr')
                gasoAutUrb_tr4 = gasoAutUrb_tr3.find(["td"], string="Urbana")
                gasoAutUrb_tr5 = gasoAutUrb_tr4.find_next("td")
                gasoAutUrb = gasoAutUrb_tr5.get_text()
                print("Autonomia Urbana: " + gasoAutUrb)
            except:
                gasoAutUrb_td = doc.find(["td"], string="Autonomia")
                gasoAutUrb = gasoAutUrb_td.find_next_sibling('td').get_text(strip=True)
                print("Autonomia Urbana: " + gasoAutUrb)

        ##
        ## Autonomia Estrada = Rodoviária
        ##
        try:
            gasoAutEst_td = doc.find(["td"], string="Urbana")
            gasoAutEst_tr = gasoAutEst_td.find_next('tr')
            gasoAutEst_tr2 = gasoAutEst_tr.find_all('td')
            gasoAutEst = gasoAutEst_tr2[3].get_text()
            print("Autonomia Estrada: " + gasoAutEst)
        except:
            try:
                gasoAutEst_td = doc.find(["td"], string="AUTONOMIA")
                gasoAutEst_tr = gasoAutEst_td.find_parent('tr')
                gasoAutEst_tr2 = gasoAutEst_tr.find_next('tr')
                gasoAutEst_tr3 = gasoAutEst_tr2.find_next("tr")
                gasoAutEst_tr4 = gasoAutEst_tr3.find(["td"], string="Rodoviária")
                gasoAutEst_tr5 = gasoAutEst_tr4.find_next('td')
                gasoAutEst = gasoAutEst_tr5.get_text()
                print("Autonomia Estrada: " + gasoAutEst)
            except:
                gasoAutEst = "carro eletrico não tem"
        # gasoAutEst = gasoAutEst_tr3.get_text()
        # print("Autonomia Estrada: " + gasoAutEst)

        ##
        ## Tração = Tração
        ##

        tração_td = doc.find(["td"], string="Tração")
        tração = tração_td.find_next_sibling('td').get_text(strip=True)
        print("Tração: " + tração)

        ##
        ## Direção = Assitência
        ##

        direção_td = doc.find(["td"], string="Assistência")
        direção = direção_td.find_next_sibling('td').get_text(strip=True)

        print("Assistencia: " + direção)

        ##
        ## Suspensão Dianteira = Dianteira
        ##

        susDia_td = doc.find(["tr"], string="SUSPENSÃO")
        susDia_td2 = susDia_td.find_next('tr')
        susDia_td3 = susDia_td2.find_next('tr')
        susDia_td4 = susDia_td3.find_all('td')
        susDia = susDia_td4[1].get_text()
        print("Suspensão Dianteira: " + susDia)

        ##
        ## Suspensão Traseira = Traseira
        ##
        susTra_td = doc.find(["tr"], string="SUSPENSÃO")
        susTra_td2 = susTra_td.find_next('tr')
        susTra_td3 = susTra_td2.find_next('tr')
        susTra_td4 = susTra_td3.find_next('tr')
        susTra_td5 = susTra_td4.find_all('td')
        susTra = susTra_td5[1].get_text()
        print("Suspensão Traseira: " + susTra)

        ##
        ## Freios Dianteiros = Dianteiros
        ##

        freDia_td = doc.find(["td"], string="Dianteiros")
        freDia = freDia_td.find_next_sibling('td').get_text(strip=True)
        print("Freios Dianteiros: " + freDia)

        ##
        ## Freios Traseiros = Traseiros
        ##

        freTra_td = doc.find(["td"], string="Traseiros")
        freTra = freTra_td.find_next_sibling('td').get_text(strip=True)
        print("Freios Traseiros: " + freTra)

        ##
        ## Itens de Segurança = Equipamentos Segurança
        ##
        try:
            def remove_chars(string):
                chars_to_remove = ["'", "[", "]"]
                for char in chars_to_remove:
                    string = string.replace(char, "")
                return string

            start_td = doc.find(["font"], string=" SEGURANÇA")
            end_td = doc.find(['font'], string=' CONFORTO')
            start_td = start_td.find_next('tr')
            end_td = end_td.find_parent('tr')
            caixa = []
            while start_td != end_td:
                caixa.append(start_td)
                start_td = start_td.find_next_sibling('tr')

            dados = BeautifulSoup(str(caixa), "html.parser")
            dados = dados.find_all('td')
            dadosSeg = []
            for dado in dados:
                if dado.get_text(strip=True) != '':
                    dadosSeg.append(dado.get_text(strip=True))
            dadosSeg = remove_chars(str(dadosSeg))
            print("itens de Segurança: " + str(dadosSeg))

        ##
        ## Itens de Conforto = Equipamentos Conforto
        ##
            start_td = doc.find(["font"], string=" CONFORTO")
            end_td = doc.find(['font'], string=' INFOTENIMENTO')
            start_td = start_td.find_next('tr')
            end_td = end_td.find_parent('tr')
            caixa = []
            while start_td != end_td:
                caixa.append(start_td)
                start_td = start_td.find_next_sibling('tr')

            dados = BeautifulSoup(str(caixa), "html.parser")
            dados = dados.find_all('td')
            dadosConf = []
            for dado in dados:
                if dado.get_text(strip=True) != '':
                    dadosConf.append(dado.get_text(strip=True))
            dadosConf = remove_chars(str(dadosConf))
            print("Itens de Conforto: " + str(dadosConf))

            ##
            ## Itens de infotenimento = Equipamentos Infotenimento
            ##

            start_td = doc.find(["font"], string=" INFOTENIMENTO")
            end_td = doc.find(["font"], string="     Fotos")
            print(end_td)
            end_td = end_td.find_parent('tr')
            end_td = end_td.find_previous('tr')
            end_td = end_td.find_previous('tr')
            start_td = start_td.find_next('tr')
            caixa = []
            i = 0
            while start_td != end_td:
                caixa.append(start_td)
                if start_td.find_next_sibling('tr'):
                    start_td = start_td.find_next_sibling('tr')
                else:
                    break

            dados = BeautifulSoup(str(caixa), "html.parser")
            dados = dados.find_all('td')
            dadosInfo = []
            for dado in dados:
                if dado.get_text(strip=True) != '':
                    dadosInfo.append(dado.get_text(strip=True))
            print(len(dadosInfo))
            dadosInfo = remove_chars(str(dadosInfo))
            print("Itens de infotenimento: " + str(dadosInfo))
        except:
            dadosSeg = ""
            dadosConf = ""
            dadosInfo = ""

        ##
        ## Portas = Portas
        ##

        portas_td = doc.find(["td"], string="Portas")
        portas = portas_td.find_next_sibling('td').get_text(strip=True)
        print("Portas: " + portas)

        ##
        ## Lugares = Lugares
        ##

        lugares_td = doc.find(["td"], string="Lugares")
        lugares = lugares_td.find_next_sibling('td').get_text(strip=True)
        print("Lugares: " + lugares)

        ##
        ## Altura = Altura
        ##

        altura_td = doc.find(["td"], string="Altura")
        altura = altura_td.find_next_sibling('td').get_text(strip=True)
        print("Altura: " + altura)

        ##
        ## Largura = Largura
        ##

        largura_td = doc.find(["td"], string="Largura")
        largura = largura_td.find_next_sibling('td').get_text(strip=True)
        print("Largura: " + largura)

        ##
        ## Comprimento = Comprimento
        ##
        ##Conversa com lucas
        comprimento_td = doc.find(["td"], string="Comprimento")
        comprimento = comprimento_td.find_next_sibling('td').get_text(strip=True)
        print("Comprimento: " + comprimento)

        ##
        ## Peso = Peso
        ##

        peso_td = doc.find(["td"], string="Peso")
        peso = peso_td.find_next_sibling('td').get_text(strip=True)
        print("Peso: " + peso)

        ##
        ## Tanque = Tanque de combustível
        ##
        try:
            tanque_td = doc.find(["td"], string="Tanque de combustível")
            tanque = tanque_td.find_next_sibling('td').get_text(strip=True)
            print("Tanque: " + tanque)
        except:
            tanque_td = doc.find(["td"], string="Capacidade da bateria")
            tanque = tanque_td.find_next_sibling('td').get_text(strip=True)
            print("Tanque: " + tanque)

        ##
        ## Entre Eixos = Distância entre-eixos
        ##

        entEix_td = doc.find(["td"], string="Distância entre-eixos")
        entEix = entEix_td.find_next_sibling('td').get_text(strip=True)
        print("Entre Eixos: " + entEix)

        ##
        ## Litragem real do porta malas = Porta-malas
        ##
        try:
            litRea_td = doc.find(["td"], string="Porta-malas ")
            litRea = litRea_td.find_next_sibling('td').get_text(strip=True)
            print("Litragem real do porta malas: " + litRea)
        except:
            litRea_td = doc.find(["td"], string="Caçamba")
            litRea = litRea_td.find_next_sibling('td').get_text(strip=True)
            print("Litragem real do porta malas: " + litRea)

        ##
        ## Pneus Dianteiros = Pneus/Dianteiros
        ##
        pneDia_td = doc.find(["td"], string="PNEUS")
        pneDia_td2 = pneDia_td.find_parent('tr')
        pneDia_td3 = pneDia_td2.find_next_sibling('tr')
        pneDia_td4 = pneDia_td3.find_next_sibling('tr')
        pneDia_td5 = pneDia_td4.find_all('td')
        pneDia = pneDia_td5[1].get_text()

        print("Pneus Dianteiros: " + pneDia)

        ##
        ## Pneus Traseiros = Pneus/Traseiros
        ##
        pneTra_td = pneDia_td4.find_next_sibling('tr')
        pneTra_td2 = pneTra_td.find_all('td')
        pneTra = pneTra_td2[1].get_text()
        print("Pneus Traseiros: " + pneTra)

        ##
        ## Estepe =  pode ter ou não ter Estepe
        ##
        if doc.find(["td"], string="Estepe"):
            estepe_td = doc.find(["td"], string="Estepe")
            estepe = estepe_td.find_next_sibling('td').get_text(strip=True)
        else:
            estepe = "Não informado"

        df = pd.read_excel('dados_carros.xlsx')
        nova_linha = {
            'Ano': year,
            'Marca': marca,
            'Modelo': modelo,
            'Versão': versão,
            'Preço (Seminovos tabela KBB)': '',
            'Preço parametro': '',
            'Preço do IPVA': '',
            'Valor médio de revisões': revisao,
            'Tempo de garantia': garantia,
            'Câmbio': câmbio,
            'Categoria': categoria,
            'Porte': porte,
            'Seguimento': "seguimento",
            'Propulsão': propulsão,
            'Motorização': motor,
            'Cilindros': cilindros,
            'Potência': potência,
            'Torque': torque,
            'Velocidade Máxima': velocidade,
            '0-100': zero_cem,
            'Consumo Parametrizado': '',
            'Consumo cidade (Km/L)': gasoCid,
            'Consumo Estrada (Km/L)': gasoEst,
            'Autonomia Urbana': gasoAutUrb,
            'Autonomia Estrada': gasoAutEst,
            'Tração': tração,
            'Direção': direção,
            'Suspensão dianteira': susDia,
            'Suspensão Traseira': susTra,
            'Freios Dianteiros': freDia,
            'Freios Traseiros': freTra,
            'Itens de segurança': dadosSeg,
            'Itens de Conforto': dadosConf,
            'Itens de Infotenimento': dadosInfo,
            'Portas': portas,
            'Lugares': lugares,
            'Altura': altura,
            'Largura': largura,
            'Comprimento': comprimento,
            'Peso': peso,
            'Tanque': tanque,
            'Entre Eixos': entEix,
            'Litragem real do porta malas': litRea,
            'Pneus Dianteiros': pneDia,
            'Pneus Traseiros': pneTra,
            'Estepe': estepe,
            'Principais destaques do veículo': '',
            'Justificativa padrão': '',
            'Pontos Positivos': '',
            'Pontos Negativos': '',
            'Problemas Crônicos': '',
            'Facilidade de Revenda': '',
            'Informações de mercado': '',
            'Reposição de peças': '',
            'Mêcanica': '',
            'Segurança': '',
            'Conforto': '',
            'Tecnologia': '',
            'Performance': '',
            'Consumo': '',
            'Acabamento': '',
            'Espaço Interno': '',
            'Custo-beneficio': '',
            'Avaliação Geral': ''
        }

        df = df._append(nova_linha, ignore_index=True)
        df.to_excel('dados_carros.xlsx', index=False)
    except Exception as erro:
        print(erro)
        erro2 = []
        erro2.append(name)
        erro2.append(str(erro))
        filename = "erro de carros.txt"

        with open(filename, "a") as f:
            for wrong in erro2:
                f.write(wrong + "\n")'''

        return 'error'


import pandas as pd
import warnings
warnings.filterwarnings('ignore')
## import os
## print(os.getcwd())

import tkinter as ttk
app = ttk.Tk()
app.title('Movie Reccomendor System')
app.geometry("800x700")

#Reading the Data Files
cols = ['user_id', 'movie_id', 'rating', 'ts']
df = pd.read_csv('u.data', sep = '\t', names = cols).drop('ts', axis = 1)
item_cols = ['movie_id', 'title'] + [str(i) for i in range(22)]
df1 = pd.read_csv('u.item', sep = '|', names = item_cols, encoding = "ISO-8859-1")[['movie_id', 'title']]

#Merging the two Data Frames
movie = pd.merge(df, df1, on = 'movie_id')

result = ttk.Variable(app)

frame = ttk.Frame(app)
frame.place(x=10, y=10)

box = ttk.Listbox(frame, height=10, width=50)
for title in movie['title'].unique():
    box.insert(ttk.END, title)

box.pack(side='left', fill='y')
## box.grid(row=0, column=0)
## box.place(x=10, y=10)

# scroll bar adding
scroll = ttk.Scrollbar(frame, orient=ttk.VERTICAL)
scroll.config(command = box.yview)
box.config(yscrollcommand=scroll.set)
scroll.pack(side='right', fill='y')

def get_movie():
    pass
    movie_selected = box.get(box.curselection())
    print('movie_selected:', movie_selected)

    #Creating a Pivot Table
    movie_pivot = movie.pivot_table(index = 'user_id', columns = 'title', values = 'rating')

    #Finding the similarity for the Selected Movie
    corrs = movie_pivot.corrwith(movie_pivot[movie_selected])
    corrs_df = pd.DataFrame(corrs, columns = ['correlation'])
    corrs_df['avg_ratings'] = movie.groupby('title')['rating'].mean()
    corrs_df['count'] = movie['title'].value_counts()

    #Finding the top 2-3 Recommendations
    top_recom = list(corrs_df[corrs_df['count'] > 50].sort_values(by = 'correlation', ascending = False).head(3).index)

    ## important
    if movie_selected in top_recom:
        top_recom.remove(movie_selected)

    print('Recommendations: ',top_recom)

    if top_recom:
        result.set(top_recom[0])
    else:
        result.set('Sorry no recommendations Found !! ')

ttk.Button(app, text="Find Reccomendations", font= ('Arial',22), command = get_movie).place(x=10, y=250)

ttk.Label(app, textvariable=result, font=('Arial',22)).place(x=10, y=350)

app.mainloop()


import json
from database import get_cart_by_id, set_cart_to_user
import logging

log = logging.getLogger(__name__)

class Cart:
    def __init__(self, chat_id):
        self.chat_id = chat_id
        self.items = self.get_items_by_id()

    def add_item(self, item):
        item = list(item)
        item_id = str(item[0])
        try:
            if not self.items[item_id]:
                log.debug("No items in cart")
            elif self.items[item_id]:
                self.items[item_id][7]['amount'] += 1
        except KeyError:
            self.items[item_id] = item
            self.items[item_id].append({"amount": 1})

    def return_cart_json(self):
        return json.dumps(self.items)

    def get_items_by_id(self):
        if get_cart_by_id(self.chat_id) is not None and get_cart_by_id(self.chat_id) != "null":
            return json.loads(get_cart_by_id(self.chat_id))
        elif get_cart_by_id(self.chat_id) is None or get_cart_by_id(self.chat_id) == "null":
            return dict()

    def set_cart_to_user(self):
        set_cart_to_user(self.chat_id, self.return_cart_json())

    def get_prod_by_id(self, prod_id):
        try:
            return self.items[str(prod_id)]
        except KeyError:
            return None


import datetime
from typing import Any, Optional, Union

from django.db import models

dt_format = "%Y-%m-%d %H:%M:%S.%f"

class TimestampField(models.CharField):
    def __init__(self, *args: Optional[Any], **kwargs: Optional[Any]):
        kwargs['max_length'] = 50
        super(TimestampField, self).__init__(*args, **kwargs)  # noqa: T484

    def db_type(self, connection: Any) -> str:
        return 'TIMESTAMP'

    def to_python(self, value: Union[str, datetime.datetime, float]) -> Optional[str]:
        if value == '':
            return None
        return f'{self.normalize_to_timestamp(value)}'

    @classmethod
    def normalize_to_timestamp(cls, value: Union[str, datetime.datetime, float]) -> Optional[str]:
        dt = cls.normalize_to_datetime(value)
        if dt is None:
            return None
        else:
            return f'{dt.timestamp():.6f}'

    @staticmethod
    def normalize_to_datetime(value: Union[str, datetime.datetime, float]) \
            -> Optional[datetime.datetime]:
        if value == '':
            return None
        elif isinstance(value, datetime.datetime):
            dt = value
        else:
            try:
                value = float(value)
                dt = datetime.datetime.utcfromtimestamp(value)
            except ValueError:
                dt = datetime.datetime.strptime(str(value), dt_format)
        return dt

    def from_db_value(self, value: Union[datetime.datetime, str, float],
                      *_: Any) -> Optional[datetime.datetime]:
        return self.normalize_to_datetime(value)

    def get_prep_value(self, value: Union[str, datetime.datetime, float]) -> Optional[str]:
        dt = self.normalize_to_datetime(value)
        if dt is None:
            return None
        return dt.strftime(dt_format)


# -*- coding: utf-8 -*-
"""
@author: Stefan Mejlgaard
"""

import itertools
import math

def num_digits(number: int) -> int:
    """Return the number of digits in `number`"""
    return int(math.log10(number) + 1)

def find_digits(positions: list[int]) -> list[int]:
    positions_iter = iter(positions)
    position = next(positions_iter)

    digit_list: list[int] = []
    pointer = 1
    for n in itertools.count(1):
        digits = num_digits(number=n)
        if pointer <= position <= pointer + (digits - 1):
            digit = int(str(n)[position - pointer])
            digit_list.append(digit)

            try:
                position = next(positions_iter)
            except StopIteration:
                break

        pointer += digits

    return digit_list

if __name__ == "__main__":
    digits = find_digits(positions=[1, 10, 100, 1000, 10_000, 100_000, 1_000_000])
    print(digits)

    result = math.prod(digits)
    print(result)


from bs4 import BeautifulSoup
import lxml
import requests

res = requests.get("https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/")
res.raise_for_status()

soup = BeautifulSoup(res.text, "lxml")

titles = soup.select(selector="h3[class='title']")
titles_text = ""
for title in reversed(titles):
	titles_text += f"{title.getText()}\n"

with open("Day45/top-100-movies/movies.txt", "w", encoding="utf-8") as file:
	file.write(titles_text)


import os
from selenium import webdriver
import random
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import linecache
import sys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import datetime
import mysql.connector
import requests
import datetime
from urllib.parse import unquote
import json
import os
import subprocess
from urllib.parse import unquote
from pyvirtualdisplay import Display

# start time
now = datetime.datetime.now()
print(str(
    now) + "----------------------------------------------------------------------------------------------------------")

# test prints
# close all
def closeAll():
    try:
        mycursor.close()
    except:
        print("error-mycursor.close()")
        pass
    try:
        mydb.close()
    except:
        print("error-mydb.close()")
        pass
    try:
        driver.close()
    except:
        print("error-driver.close()")
        pass
    try:
        driver.quit()
    except:
        print("error-driver.quit()")
        pass
    try:
        display.stop()
    except:
        print("error-display.stop()")
        pass
    try:
        display.sendstop()
    except:
        print("error-display.sendstop()")
        pass
    try:
        display.popen.kill()
    except:
        print("error-display.popen.kill()")
        pass
    try:
        sys.exit()
    except:
        print("error-sys.exit()")
        pass

# обработка ошибок
def PrintException():
    succsess = 0
    print("was an error")
    # exception output
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    filename = f.f_code.co_filename
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, f.f_globals)
    print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
    # screen
    now = datetime.datetime.now()
    # close all
    closeAll()

def PrintException_only_print():
    succsess = 0
    print("was an error")
    # exception output
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    filename = f.f_code.co_filename
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, f.f_globals)
    print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
    # screen
    now = datetime.datetime.now()
    driver.save_screenshot('eror_print' + "-" + str(now) + '.png')

try:

    display = Display(visible=0, size=(1600, 900), backend='xvfb')
    display.start()

    chrome_options = Options()
    chrome_options.add_argument("user-data-dir=/home/work/profilesForAll/SteamPriceChanger")  # linux
    driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', chrome_options=chrome_options)

    wait = WebDriverWait(driver, 10)  # время вылета 10сек

    # rub_usd
    rub_usd = requests.get("https://www.cbr-xml-daily.ru/daily_json.js")
    rub_usd = rub_usd.json()
    rub_usd = float(rub_usd["Valute"]["USD"]["Value"])
    print("current exchange rate", rub_usd)

except Exception as e:
    telegram_bot_sendtext("steamPriceChangerV2: Возникла ошибка, нужно выяснять")
    PrintException()

try:
    driver.get("https://steamcommunity.com/market/")
    time.sleep(5)
    try:
        element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#marketWalletBalanceAmount")))
    except:
        print("cant verify login into steam on the first try (login)")
        time.sleep(50)
except Exception as e:
    telegram_bot_sendtext("steamPriceChangerV2: Возникла ошибка, нужно выяснять")
    PrintException()

# CODE
# delete from sale
try:
    # создаём вторую вкладку и получаем минимальную цену для предмета
    driver.execute_script('''window.open('',"_blank");''')  # создаем новую вкладку
    driver.switch_to.window(driver.window_handles[0])
    time.sleep(5)

    print("--start deleting items--")
    # получаем предметы на продажи в стиме и в бдl
    items_on_sale = driver.find_elements_by_css_selector("#tabContentsMyActiveMarketListingsRows > div")
    print("items currently on sale in steam -", len(items_on_sale))
    # get items on sale from DB
    mycursor.execute("SELECT `NAME` FROM `skins` WHERE `status` <> 3")
    items_available_to_sale = mycursor.fetchall()
    print("items currently on sale in DB -", len(items_available_to_sale))
    try:
        print("one item from bd -", items_available_to_sale[0])
    except:
        pass

    # если предметы есть, то проверяем их
    if len(items_on_sale) > 0 and len(items_available_to_sale) > 0:
        already_checked_items_for_deleting = []
        errors_count = 0
        # начинаем проверять каждый предмет в стиме
        for item_on_sale in items_on_sale:
            driver.switch_to.window(driver.window_handles[0])
            # если случилось три ошибки в ряд за проход
            if errors_count == 3:
                raise ValueError('3 errorsd in a row')
            name = item_on_sale.find_element_by_css_selector(
                "div.market_listing_item_name_block >  span> a").text.strip()
            print("name - ", name.encode('utf-8'))
            # если предмет уже проверяли
            if name in already_checked_items_for_deleting:
                print("already checked this item (continue)")
                continue
            is_name_exist_in_bd = False
            # проверяем, есть ли предмет в бд
            for item_bd in items_available_to_sale:
                if item_bd[0] == name:
                    print("item exists in DB (break) - ", name.encode('utf-8'))
                    is_name_exist_in_bd = True
                    break
            # если предмета нет в нашей БД, идём к следующему
            if is_name_exist_in_bd == False:
                print("item does not exist in DB (continue) - ", name.encode('utf-8'))
                already_checked_items_for_deleting.append(name)
                continue
            my_listed_price = item_on_sale.find_element_by_css_selector(
                "div.market_listing_right_cell.market_listing_my_price > span > span > span > span:nth-child(1)").text
            my_listed_price = float(my_listed_price.strip().replace(',', '.')[:-5])
            print("my listed price -", my_listed_price)
            link = item_on_sale.find_element_by_css_selector(".market_listing_item_name_block> span>a").get_attribute(
                "href")
            print("link to item -", link)
            # получаем минимальную цену в стиме
            driver.switch_to.window(driver.window_handles[1])
            driver.get("https://www.google.com/")
            driver.get(link)
            try:
                time.sleep(5)  # 5 секунд на один запрос
                element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#listings")))
            except:
                print("cant load item's link properly (continue and errors count +1)")
                errors_count += 1
                continue
            errors_count = 0
            # get tlisted type
            is_table_prices = driver.find_elements_by_css_selector(
                "#market_commodity_forsale_table > table > tbody > :nth-child(2) > :nth-child(1)")
            is_row_prices = driver.find_elements_by_css_selector("#searchResultsRows")
            print("length table prices and row prices -", len(is_table_prices), len(is_row_prices))
            # if row prices - get lowest and  on market
            if len(is_row_prices) > 0:
                print("is_row_prices")
                price_from_market = 100000000
                steam_second_low_price = 100000000
                steam_listed_prices = driver.find_elements_by_css_selector(
                    "div.market_listing_price_listings_block > div.market_listing_right_cell.market_listing_their_price > span > span.market_listing_price.market_listing_price_with_fee")
                # get lowest price
                print("getting lowest price")
                for steam_listed_price in steam_listed_prices:
                    price_from_market_2 = steam_listed_price.text
                    # бывают не цены, а надписи sold
                    try:
                        price_from_market_2 = float(price_from_market_2.strip().replace(',', '.')[:-5])
                    except:
                        continue
                    print("price_from_market_2 -", price_from_market_2)
                    if price_from_market_2 < price_from_market:
                        price_from_market = price_from_market_2
                # get 2nd lowest price
                print("getting 2nd lowest price")
                for steam_listed_price in steam_listed_prices:
                    price_from_market_2 = steam_listed_price.text
                    try:
                        price_from_market_2 = float(price_from_market_2.strip().replace(',', '.')[:-5])
                    except:
                        continue
                    print("price_from_market_2 -", price_from_market_2)
                    if price_from_market < price_from_market_2 < steam_second_low_price:
                        steam_second_low_price = price_from_market_2
            # if table prices - get lowest on market
            if len(is_table_prices) > 0:
                print("is_table_prices")
                price_from_market = driver.find_element_by_css_selector(
                    "#market_commodity_forsale_table > table > tbody > :nth-child(2) > :nth-child(1)").text
                price_from_market = float(price_from_market.strip().replace(',', '.')[:-5])
                steam_second_low_price = driver.find_element_by_css_selector(
                    "#market_commodity_forsale_table > table > tbody > :nth-child(3) > :nth-child(1)").text
                steam_second_low_price = float(steam_second_low_price.strip().replace(',', '.')[:-5])
            print("lowest price is -", price_from_market)
            print("second low price is -", steam_second_low_price)
            print("name -", name.encode('utf-8'))
            already_checked_items_for_deleting.append(name)
            print("add item's name in a list (already_checked_items_for_deleting)")

            # если моя цена и минимальная в стиме равна, то надо проверить, на сколько далеко моя цена от второй цены (если больше чем на рубль, то перевыставляем)
            if price_from_market == my_listed_price:
                print("lowest steam price and my listed price is equal")
                if steam_second_low_price - my_listed_price < 1:
                    print(
                        "difference between my listed price (lowest on steam) and 2nd lowest price is less than 1 rub (continue)")
                    continue

            # delete from sale
            is_bitton_to_remove_exists = driver.find_elements_by_css_selector(
                "div:nth-child(6) > div > a > span:nth-child(2)")
            if len(is_bitton_to_remove_exists) > 0:
                for remove_button in is_bitton_to_remove_exists:
                    try:
                        remove_button.click()
                        time.sleep(0.5)
                        driver.find_element_by_css_selector("#market_removelisting_dialog_accept > span").click()
                        # проверяем, закрылось ли окно
                        for i in range(30):
                            time.sleep(0.3)
                            element = driver.find_element_by_css_selector("#market_removelisting_dialog")
                            if element.is_displayed():
                                print("modal window still exists (continue)")
                                continue
                            else:
                                print("modal window doesnt exist anymore (break)")
                                break
                        element = driver.find_element_by_css_selector("#market_removelisting_dialog")
                        if element.is_displayed():
                            print("9 seconds wasnt enough, modal window still exists (break)")
                    except Exception as e:
                        print("was an error (continue). Error info below")
                        PrintException_only_print()
                        continue

except Exception as e:
    telegram_bot_sendtext("steamPriceChangerV2: Возникла ошибка, нужно выяснять")
    PrintException()

# sell items
try:
    print("--start selling items--")
    driver.switch_to.window(driver.window_handles[0])
    driver.get("https://www.google.com/")
    driver.get("https://steamcommunity.com/id/Dr11m/inventory#730")
    try:
        time.sleep(5)  # 5 секунд на один запрос
        element = wait.until(EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "#active_inventory_page > div:nth-child(2) > div:first-child")))
    except:
        print("cant load steams inventory (try 1 more time)")
        driver.get("https://steamcommunity.com/id/Dr11m/inventory")
        try:
            time.sleep(5)  # 5 секунд на один запрос
            element = wait.until(EC.visibility_of_element_located(
                (By.CSS_SELECTOR, "#active_inventory_page > div:nth-child(2) > div:first-child")))
        except:
            raise ValueError('cant load steam inventory')

    # get items are ready to be put on sale
    mycursor.execute(
        "SELECT NAME, PRICE, game_id, platform_from, id FROM skins WHERE platform_to = '1' AND (status = '1' OR status = '2') AND orders = '0' AND sold_id is NULL ORDER BY id DESC")
    items_for_sale = mycursor.fetchall()
    print("items for sale length -", len(items_for_sale))
    try:
        print("one item from bd -", items_available_to_sale[0])
    except:
        pass

    if len(items_for_sale) > 0:
        already_checked_items_for_selling = []
        #2nd page loop
        for index_next_page in range(2):
            index_next_page += 1
            next_item = 0
            for index_inventory in range(25):
                # close modals if didn't
                try:
                    driver.find_element_by_css_selector(
                        "#market_sell_dialog > div.newmodal_header_border > div > div").click()
                    time.sleep(0.2)
                except:
                    pass
                next_item += 1
                print("----------next item (index) -", next_item)
                driver.switch_to.window(driver.window_handles[0])
                try:
                    item_id = driver.find_element_by_css_selector(
                        "#inventories > div:nth-child(2) > div:first-child > div:nth-child(1) > div > a").get_attribute("href")
                    print("item id - ", item_id)
                except Exception as e:
                    print("cant get item id (continue). Error info below")
                    PrintException_only_print()
                    continue
                #пытаюсь нажать на предмет, если ошибка, то перехожу к следующему
                try:
                    driver.find_element_by_xpath('//*[@id="inventories"]/div[2]/div['+str(index_next_page)+']/div['+str(next_item)+']').click()
                except Exception as e:
                    try:
                        driver.find_element_by_css_selector("div.newmodal_buttons > div > span").click()
                    except:
                        pass
                    print("error occured")
                    PrintException_only_print()
                    continue
                time.sleep(1)
                print("click on item")
                try:
                    link = driver.find_element_by_xpath(
                        "//div[contains(@style,'opacity: 1')]/div[3]/div/div/div[1]/a").get_attribute("href")
                    print("link -", link)
                except:
                    print("link is not existed (continue)")
                    continue
                full_link = link
                link = link.split("/")
                name_url = link[len(link) - 1]
                name = unquote(name_url).strip()
                print("name -", name.encode('utf-8'))

                index_deleted = -1
                for item_for_sale in items_for_sale:
                    index_deleted += 1
                    if name == item_for_sale[0]:
                        print("match! -", item_for_sale[0].encode('utf-8'))
                        # delete from list (DB items) not to use it anymore
                        del items_for_sale[index_deleted]
                        print("deted with index -", index_deleted)
                        price_DB = float(item_for_sale[1])
                        print("price from DB -", price_DB)
                        platform_from = str(item_for_sale[3])
                        bd_id = str(item_for_sale[4])
                        price_DB = price_DB * rub_usd
                        print("updated price , platform from and bd id -", price_DB, platform_from, bd_id)
                        # get percentage for platform
                        mycursor.execute(
                            "SELECT min_percent FROM min_percents WHERE name_of_platform_from = %s",
                            (platform_from,))
                        percent_from_DB = mycursor.fetchone()
                        print("percent from DB sql request -", percent_from_DB)
                        min_price = 0
                        first_character = percent_from_DB[0][0]
                        print("percent from DB and first character -", percent_from_DB, first_character)
                        percent_from_DB = float(percent_from_DB[0])
                        # get min price
                        if str(first_character) == "-":
                            percent_from_DB = percent_from_DB * -1
                            min_price = price_DB * percent_from_DB / 0.87
                        if str(first_character) != "-":
                            min_price = price_DB / percent_from_DB / 0.87
                        print("min price -", min_price)

                        if name in already_checked_items_for_selling:
                            for index_checked in range(len(already_checked_items_for_selling)):
                                if name == already_checked_items_for_selling[index_checked]:
                                    lowest_steam_price = float(already_checked_items_for_selling[index_checked + 1])
                                    print("item was already cheked, lowest steam price is -", lowest_steam_price)

                        if not name in already_checked_items_for_selling:
                            print("name wasnt checked already, taking lowest steam price now")
                            driver.switch_to.window(driver.window_handles[1])
                            driver.get(full_link)
                            time.sleep(5)
                            try:
                                time.sleep(5)  # 5 секунд на один запрос
                                element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#listings")))
                            except:
                                print("cant load item's link properly (continue and errors count +1)")
                                continue
                            # get tlisted type
                            is_table_prices = driver.find_elements_by_css_selector(
                                "#market_commodity_forsale_table > table > tbody > :nth-child(2) > :nth-child(1)")
                            is_row_prices = driver.find_elements_by_css_selector("#searchResultsRows")
                            print("length table prices and row prices -", len(is_table_prices), len(is_row_prices))
                            # if row prices - get lowest and  on market
                            if len(is_row_prices) > 0:
                                print("is_row_prices")
                                price_from_market = 100000000
                                steam_second_low_price = 100000000
                                steam_listed_prices = driver.find_elements_by_css_selector(
                                    "div.market_listing_price_listings_block > div.market_listing_right_cell.market_listing_their_price > span > span.market_listing_price.market_listing_price_with_fee")
                                # get lowest price
                                print("getting lowest price")
                                for steam_listed_price in steam_listed_prices:
                                    price_from_market_2 = steam_listed_price.text
                                    # бывают не цены, а надписи sold
                                    try:
                                        price_from_market_2 = float(price_from_market_2.strip().replace(',', '.')[:-5])
                                    except:
                                        continue
                                    print("price_from_market_2 -", price_from_market_2)
                                    if price_from_market_2 < price_from_market:
                                        price_from_market = price_from_market_2
                            # if table prices - get lowest on market
                            if len(is_table_prices) > 0:
                                print("is_table_prices")
                                price_from_market = driver.find_element_by_css_selector(
                                    "#market_commodity_forsale_table > table > tbody > :nth-child(2) > :nth-child(1)").text
                                price_from_market = float(price_from_market.strip().replace(',', '.')[:-5])
                            try:
                                lowest_steam_price = price_from_market
                            except:
                                print("cant get lowest steam price (break)")
                                break
                            already_checked_items_for_selling.append(name)
                            already_checked_items_for_selling.append(lowest_steam_price)
                            print("lowest price is -", lowest_steam_price)
                            print("min price -", min_price)
                            print("name -", name.encode('utf-8'))
                            print("add item's name in a list (already_checked_items_for_selling)")

                        if lowest_steam_price < min_price:
                            print("!!!!!!!!!!! lowest price is less that min price! (break)")

                        if lowest_steam_price > min_price:
                            print("start selling the item")
                            driver.switch_to.window(driver.window_handles[0])
                            lowest_steam_price = lowest_steam_price - 0.01
                            lowest_steam_price = float('{:.2f}'.format(lowest_steam_price))
                            print("lowest price (sold price) and min price -", lowest_steam_price, min_price)
                            # получаем название для проверки
                            link_checked = driver.find_element_by_xpath(
                                "//div[not(contains(@style,'display: none'))][@class='inventory_iteminfo']/div[3]/div[1]/div[1]/div[1]/a").get_attribute(
                                "href")
                            print("link checked -", link_checked)
                            link_checked_list = link_checked.split("/")
                            name_url_checked = link_checked_list[len(link_checked_list) - 1]
                            name_checked = unquote(name_url_checked).strip()
                            print("name checked -", name_checked.encode('utf-8'))
                            if name == name_checked:
                                driver.find_element_by_xpath(
                                    "//div[not(contains(@style,'display: none'))][@class='inventory_iteminfo']/div[3]/div[1]/a").click()
                                print("click sell button (first one)")
                                time.sleep(0.2)
                                try:
                                    wait.until(EC.visibility_of_element_located(
                                        (By.CSS_SELECTOR, "#market_sell_buyercurrency_input")))
                                except:
                                    break
                                # вводим цену
                                input_field = driver.find_element_by_css_selector('#market_sell_buyercurrency_input')
                                input_field.clear()
                                time.sleep(0.1)
                                input_field.send_keys(str(lowest_steam_price))
                                time.sleep(0.1)
                                price_checked = driver.find_element_by_css_selector(
                                    "#market_sell_buyercurrency_input").get_attribute('value')
                                print("price checked -", price_checked)
                                try:
                                    price_checked = float(price_checked)
                                except:
                                    print("cant get a price (break)")
                                    break
                                print("price checked, sthat we texted -", price_checked)
                                if price_checked > min_price:
                                    print("price_checked > min price")
                                    driver.find_element_by_css_selector("#market_sell_dialog_accept > span").click()
                                    time.sleep(0.5)
                                    if driver.find_element_by_css_selector("#market_sell_dialog_error").is_displayed():
                                        print("tick")
                                        driver.find_element_by_css_selector("#market_sell_dialog_accept_ssa").click()
                                        time.sleep(0.2)
                                        driver.find_element_by_css_selector("#market_sell_dialog_accept > span").click()
                                        time.sleep(0.5)
                                    driver.find_element_by_css_selector("#market_sell_dialog_ok > span").click()
                                    print("putt item on sale")
                                    # status = 2
                                    mycursor.execute(
                                        "UPDATE `skins` SET `status`= '2' WHERE `id` = %s",
                                        (bd_id,))
                                    mydb.commit()
                                    time.sleep(10)
                                    # close modal windows
                                    try:
                                        driver.find_element_by_css_selector("div.newmodal_buttons > div > span").click()
                                        time.sleep(0.2)
                                    except:
                                        pass
                                    try:
                                        driver.find_element_by_css_selector(":nth-child(5) > .newmodal_header_border > .newmodal_header > .newmodal_close").click()
                                        time.sleep(0.2)
                                    except:
                                        pass
                                    try:
                                        driver.find_element_by_css_selector(".newmodal_close").click()
                                        time.sleep(0.2)
                                    except:
                                        pass
                                    # для проверки, не обновится ли кеш инвентаря
                                    try:
                                        item_id_checked = driver.find_element_by_css_selector(
                                            "#inventories > div:nth-child(2) > div:first-child > div:nth-child(1) > div > a").get_attribute(
                                            "href")
                                        print("item id checked - ", item_id_checked)
                                    except:
                                        print("cant get item id checked")
                                        break
                                    if item_id_checked != item_id:
                                        print("page reloaded, no need to inspect next item (next_item += -1)")
                                        next_item += -1

                        break  # cause we dont need to find name anymore
            if index_next_page == 1:
                driver.find_element_by_css_selector("#pagebtn_next").click()
                print("----------click on the second page")
                time.sleep(10)

except Exception as e:
    telegram_bot_sendtext("steamPriceChangerV2: Возникла ошибка, нужно выяснять")
    PrintException()

print("success")
closeAll()


# try:
#     a = int(input("请输入一个被除数："))
#     b = int(input("请输入一个除数："))
#     print(a / b)
# except ZeroDivisionError:
#     print("除数不能为0！他妈的错了")
# except ValueError:
#     print("需要输入数值型整数")
# except:
#     print("这是一个异常！")
# else:
#     print("执行完毕")
# finally:
#     print("无论是否发生异常，都会有此提示")

# x=10
# if x>5:
#    raise Exception("这是抛出的异常信息")

class MyException(Exception):
    def __int__(self,a,b):
        self.a = a
        self.b = b

raise MyException("x","y")


from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (ButtonsTemplate, PostbackAction, TemplateSendMessage)

import shutil
import testcount

line_bot_api = LineBotApi('g40p1VQDlWGVMHyMd7pL2kZXGj/Qxx0g35zTCf7+NhIN/cUm/8aQLAYzMoTsaY/cRPbLHl1jW+mSy2Xy9N+hKtYgLVrPtNFCBECy61Pzfvp4j1gxY/C4LoKe46fzT1shWO08PkQxz3Up0MBnk9910QdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('33c053fe8f9f91cb370128a7f77f95e5')

sweet_all = ["激アマ", "甘め", "甘さ控えめ"]

ho_guranyu1 = ["45", "35", "24"]
ho_guranyu_me = ["70", "60", "45"]
ho_guranyu2 = ["25", "15", "10"]
def holecake():
    testcount.select_count = 0
    file_name = "../recipi_txt/holecake.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/holecake.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("guranyu1", ho_guranyu1[testcount.sweet_count]).replace("guranyu_me", ho_guranyu_me[testcount.sweet_count]).replace("guranyu2", ho_guranyu2[testcount.sweet_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/holecake.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s

cho_guranyu1 = ["140", "120", "100"]
cho_choko = ["(ミルクチョコレート)", " ", "(ブラックチョコレート)"]
def chococake():
    testcount.select_count = 0
    file_name = "../recipi_txt/chococake.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/chococake.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("guranyu", cho_guranyu1[testcount.sweet_count]).replace("choco", cho_choko[testcount.sweet_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/chococake.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s

thi_sugar = ["65", "40", "28"]
def thiramisu():
    testcount.select_count = 0
    file_name = "../recipi_txt/thiramisu.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/thiramisu.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("sugar", thi_sugar[testcount.sweet_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/thiramisu.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s

sho_guranyu1 = ["120", "100", "85"]
sho_guranyu2 = ["40", "30", "20"]
sho_egg = ["2", "1"]
sho_butter =["35", "30"]
def shortcake():
    testcount.select_count = 0
    file_name = "../recipi_txt/shortcake.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/shortcake.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("guranyu1", sho_guranyu1[testcount.sweet_count]).replace("guranyu2", sho_guranyu2[testcount.sweet_count]).replace("egg", sho_egg[testcount.amount_count]).replace("butter", sho_butter[testcount.amount_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/chortcake.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s

po_sugar = ["140", "120", "100"]
po_egg = ["3", "2"]
po_vanilla = ["5", "3"]
def poundcake():
    testcount.select_count = 0
    file_name = "../recipi_txt/poundcake.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/poundcake.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("sugar", po_sugar[testcount.sweet_count]).replace("egg", po_egg[testcount.amount_count]).replace("vanilla", po_vanilla[testcount.amount_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/poundcake.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s

ga_guranyu1 = ["60", "40", "30"]
ga_guranyu2 = ["40", "40", "34"]
def gateauchocolat():
    testcount.select_count = 0
    file_name = "../recipi_txt/Gateau chocolat.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/Gateau chocolat.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("guranyu1", ga_guranyu1[testcount.sweet_count]).replace("guranyu2", ga_guranyu2[testcount.sweet_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/Gateau chocolat.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s

ca_sugar = ["125", "100", "85"]
ca_honey = ["3", "2", "2"]
ca_egg = ["5", "4"]
def castella():
    testcount.select_count = 0
    file_name = "../recipi_txt/castella.txt"
    back_name = file_name + ".bak"
    shutil.copy(file_name,back_name)

    with open("../recipi_txt/castella.txt",'r', encoding='UTF-8') as h:
        s = h.read()

    s = s.replace("sugar", ca_sugar[testcount.sweet_count]).replace("honey", ca_honey[testcount.sweet_count]).replace("egg", ca_egg[testcount.amount_count]).replace("sweet", sweet_all[testcount.sweet_count])
    with open("../recipi_txt/castella.txt.bak",'w', encoding='UTF-8') as h:
        h.write(s)
    return s


# nombres de variables
nombre = "Max"
food_today = "Tacos"
favorite_videogame = "Resident Evil 2 Remake"

# nombres de constantes
PESO_DLRS = 20.00
PI = 3.1416
SECONDS_PER_HOUR = 3600

# Diferencia entre variables con el mismo nombre pero variando algún caracter
Nombre = "otro nombre"

print(nombre) # "Max"
print(Nombre) # "otro nombre"

# Ejemplos válidos
"""
No puede empezar con números
NO simbolos especiales
a-z, A-Z, 0-9(no empieza), _
"""

food_list = "lista de la comida"
my_name_lastname = "Max"

# Ejemplos no válidos
# 0_ <== esto no es valido
# my-name-lastname
# $ECONDS_PER_DAY
# seconds.minute  = 560


import time
import struct
import pickle
import random
import socket
import builtins
from copy import deepcopy
from threading import Thread, Lock
import queue

from utils import NoSocketCreated, ConnectionNotEstablished, HandshakeFailure, CONNECTION_STATES, MESSAGE_TYPES

class Packet:
    def __init__(self, message_type, receive_window, ack_num, index_num, seq_num, data):
        """
            Message type : 5 bits
            Receive windoe : 27 bits
            Ack : 32 bits
            Index : 32 bits
            seq : 32 bits
            application data : n bits (encode)
            +----------------+----------------+
            | Message Type |  Receive Window  |
            +----------------+----------------+
            |     Acknowledgement Number      |
            +----------------+----------------+
            |            Index Number         |
            +----------------+----------------+
            |         Sequence Number         |
            +----------------+----------------+
            |                                 |
            |      Application Layer Data     |
            |                                 |
            +----------------+----------------+
        """
        assert isinstance(message_type, int) and message_type <= (
            1 << 5) - 1, '[ERROR] Invalid message type'
        self.message_type = message_type

        assert isinstance(receive_window, int) and receive_window <= (
            1 << 27) - 1, '[ERROR] Invalid receive window size'
        self.receive_window = receive_window

        assert isinstance(ack_num, int) and ack_num <= (
            1 << 32) - 1, '[ERROR] Invalid ack_num size'
        self.ack_num = ack_num

        assert isinstance(index_num, int) and index_num <= (
            1 << 32) - 1, '[ERROR] Invalid index_num size'
        self.index_num = index_num

        assert isinstance(seq_num, int) and seq_num <= (
            1 << 32) - 1, '[ERROR] Invalid seq_num size'
        self.seq_num = seq_num

        self.data = data

    def bundle_packet(self):
        """
        Convert the entire packet structure into a byte stream, that will be sent with UDP
        ! -> follow network big endian style
        4I -> 4 unsigned integers
        s -> data. character array
        """
        packet = struct.pack(
            '!4Is',
            (self.message_type << 27) ^ self.receive_window,
            self.ack_num,
            self.index_num,
            self.seq_num,
            self.data
        )

        return packet

class MONKE:
    """
    Discussions:

    Main Thread -> actual packets

    Thread -> check time and retransmit
        keep send time in packet structure
        Every time a new packet is sent, run O(n) search to see un-ackd packets. Throw un-ackd in retransmission queue.

    """

    def __init__(self, interface='localhost', port=42069, backlog=2):
        self.addr = (interface, port)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.backlog_queue_size = backlog
        self.backlog_queue = queue.Queue(maxsize=self.backlog_queue_size)
        self.shook_hands = False
        self.CONNECTION_STATE = CONNECTION_STATES.NO_CONNECTION
        self.SERVER_STATE = None

        self.SR_window_size = 1024
        self.SR_window = {}  # Map: (index, seq) -> data
        self.un_ackd_buffer = {}  # Map: (index, seq) -> data

        self.seq_num = 0
        self.ack_num = 0
        self.index_num = 0
        self.mutex = Lock()
        self.TIMEOUT = 5

    def _listen(self):
        # Receive SYN, or in our case HELLO
        while True:
            if self.backlog_queue.qsize > self.backlog_queue_size:
                continue
            syn_packet = self.sock.recv(32*4 + 1)
            try:
                syn_packet = struct.unpack('!4Is', syn_packet)
                assert len(
                    syn_packet) == 4, '[ERROR] Handshake failed - packet format not as expected!'
            except:
                continue

            self.CONNECTION_STATE = CONNECTION_STATES.HANDSHAKE
            message_type = syn_packet[0] >> 27
            if message_type != MESSAGE_TYPES.HELLO:
                raise HandshakeFailure(
                    '[ERROR] Handshake failed - unidentified message type received')

            # receive_window = syn_packet[0] & int('00000111111111111111111111111111', 2)

            # Send a SYN_ACK
            self.ack_num = syn_packet[3] + 1
            syn_ack_packet_obj = Packet(MESSAGE_TYPES.HELLO | MESSAGE_TYPES.ACCEP,
                                        self.SR_window_size,
                                        self.ack_num,
                                        self.index_num,
                                        self.seq_num,
                                        b'')
            syn_ack_packet = syn_ack_packet_obj.bundle_packet()
            self.sock.send(syn_ack_packet)

            # Receive an ACK
            ack_packet = self.sock.recv(32*4 + 1)
            ack_packet = struct.unpack('!4Is', ack_packet)
            assert len(
                ack_packet) == 4, '[ERROR] Handshake failed - packet format not as expected!'
            message_type = ack_packet[0] >> 27
            if message_type != MESSAGE_TYPES.ACCEP:
                raise HandshakeFailure(
                    '[ERROR] Handshake failed - unidentified message type received')

            # receive_window = ack_packet[0] & int('00000111111111111111111111111111', 2)
            self.CONNECTION_STATE = CONNECTION_STATES.CONNECTED

            # Throw current socket into the backlog(int: queue size) sized queue so that accept can do its job
            self.backlog_queue.put(self.sock.dup())
            # sockfd = socket(AF_INET, SOCK_STREAM, 0);
            # listen(sockfd, 5)
            # connfd = accept(sockfd, (SA*)&cli, &len);
            """
            accept creates a new file desc in non-listening sate. (In our case, a new socket obj)
            The newly created socket is not in the listening state.
                - listening state means waiting for connection
                - non-listening state means connection has been made

            The accept function can block the caller until a connection is present if no pending connections are present on the queue, and the socket is marked as blocking

            monke.listen()
            new_socket = monke.accept() # Blocking call
            do whatever with new_socket

            monke.listen() # Go to a new thread

            while (new_socket = monke.accept()) is True: # Blocking call
                new Thread(do whatever with new_socket)
            """

    def listen(self):
        listening_thread = Thread(target=self._listen)
        listening_thread.start()

    def accept(self):
        while self.backlog_queue.qsize < 0:
            pass
        return self.backlog_queue.get()

    def connect(self):
        if self.sock:
            self.sock.connect(self.addr)
        else:
            raise NoSocketCreated('[ERROR] Socket connection failed')

        syn_packet_obj = Packet(MESSAGE_TYPES.HELLO,
                                self.SR_window_size,
                                self.ack_num,
                                self.index_num,
                                self.seq_num,
                                b'')
        syn_packet = syn_packet_obj.bundle_packet()
        self.sock.send(syn_packet)
        self.CONNECTION_STATE = CONNECTION_STATES.HANDSHAKE

        # Receiving SYN_ACK, or in our terms, HELLO-ACCEP
        syn_ack_packet = self.sock.recv(32*4 + 1)
        syn_ack_packet = struct.unpack('!4Is', syn_ack_packet)
        assert len(
            syn_packet) == 5, '[ERROR] Handshake failed - packet format not as expected!'

        message_type = syn_ack_packet[0] >> 27
        if message_type != (MESSAGE_TYPES.HELLO | MESSAGE_TYPES.ACCEP):
            raise HandshakeFailure(
                '[ERROR] Handshake failed - unidentified message type received')

        # Sending ACK, or in our case ACCEP
        self.ack_num = syn_ack_packet[3] + 1
        ack_packet_obj = Packet(MESSAGE_TYPES.ACCEP,
                                self.SR_window_size,
                                self.ack_num,
                                self.index_num,
                                self.seq_num,
                                b'')
        ack_packet = ack_packet_obj.bundle_packet()
        self.sock.send(ack_packet)
        self.CONNECTION_STATE = CONNECTION_STATES.CONNECTED

    def bind(self, interface='localhost', port=42069):
        if self.sock:
            self.sock.bind(self.addr)
        else:
            raise NoSocketCreated('[ERROR] Socket binding failed.')

    def _break_into_packets(self, data):
        # This function returns a generator that yields a 520-byte
        # chunk of data in order
        if not isinstance(data, bytes):
            data = bytes(data, 'utf-8')
        broken_data = None
        start_idx = 0
        while start_idx < len(data):
            broken_data = data[start_idx:start_idx+520]
            start_idx += 520
            yield broken_data

    def send(self, data):
        # Send 520 bytes of data every packet
        data_packets = self._break_into_packets(data)
        window = 0
        for index, data_packet in enumerate(data_packets):
            window += 1
            packet_obj = Packet(MESSAGE_TYPES.DATA,
                                self.SR_window_size,
                                self.ack_num,
                                index,
                                self.seq_num,
                                data_packet)
            packet = packet_obj.bundle_packet()
            self.un_ackd_buffer[(index, self.seq_num)] = [packet, None]
            # The None is meant to hold the time of packet transmission
            self.seq_num += len(packet)
            if window == 10:
                # 10 packets in windows
                send_helper = Thread(target=self._send_helper)
                recv_ack_thread = Thread(target=self._recv_acks)
                recv_ack_thread.start()
                send_helper.start()
                send_helper.join()
                recv_ack_thread.join()
                window = 0
        if window > 0:
            send_helper = Thread(target=self._send_helper)
            recv_ack_thread = Thread(target=self._recv_acks)
            recv_ack_thread.start()
            send_helper.start()
            send_helper.join()
            recv_ack_thread.join()
            window = 0

    def _send_helper(self):
        pass

    def _recv_acks(self):
        while self.un_ackd_buffer:
            ack_packet = self.sock.recv(32*4 + 1)
            ack_packet = struct.unpack('!4Is', ack_packet)
            assert len(
                ack_packet) == 5, '[ERROR] Packet error - packet format not as expected!'
            message_type = ack_packet[0] >> 27
            index = ack_packet[2]
            seq_num = ack_packet[3]
            if (index, seq_num) in self.un_ackd_buffer:
                del self.un_ackd_buffer[(index, seq_num)]

    def recv(self):
        pass


#remainder for your need

# imports
from turtle import title
from win10toast import ToastNotifier #win10toast module
import time # for timer

toaster = ToastNotifier()

title = input("\nTitle of Remainder: ")
msg = input("Message: ")
minutes = float(input("How Many Minutes: "))

seconds = minutes * 15

print("\nRemainder Set Successfully!\n")
time.sleep(seconds)
toaster.show_toast(title, msg, duration=10, threaded=True)

while toaster.notification_active:
    time.sleep(0.1)


# Witness my jank!
import awakened as aw;
import delve_Class as dc;
import skill as sk;
import item as eq;
import accolade as ac;

# Example usage
t = aw.Awakened(name='Teston Lautts',attributes = [10, 10, 200, 70, 10, 10, 10, 10], level = 25, character_class = dc.shieldwielding_defender)
t.add_experience(2000)  # Set the character's current experience
t.add_skill(sk.intrinsic_strength(), starting_level=10)
t.add_skill(sk.intrinsic_recovery(), starting_level=10)
t.add_skill(sk.intrinsic_endurance(), starting_level=10)
t.add_skill(sk.intrinsic_vigor(), starting_level=10)
t.add_skill(sk.intrinsic_focus(), starting_level=10)
t.add_skill(sk.intrinsic_clarity(), starting_level=10)
t.unlock_tier("Physicality",1)
t.unlock_tier("Physicality",2)
t.add_skill(sk.intrinsic_resistance,starting_level=10)
t.add_skill(sk.resistance_synergy,starting_level=10)
t.add_equipment(eq.Equipment("Greater Force-sheild","A powerful shield",eq.force_steel,"Offhand",20000,500,1000,99,1,[eq.Rune("Grand Force Resistance",[eq.ResistanceEnchantment("Resistance","",[0,0,0,0,1000,0,100,0],1)])]))
t.add_equipment(eq.grand_allstat_ring)
t.inventory['Ring'].runes[1].enchantments[0].attribute_buff = [0,0,920,180,0,0,0,0]
t.add_accolade(ac.skars_glorious_return,8)
t.add_accolade(ac.sphinx_riddle,200)
t.remove_accolade(ac.sphinx_riddle,195)

t.regen(240)

t.update_buffs()
t.printCharSheet()


def find_min_index(array):
    min_val = array[0]
    index = 0
    for i in range(len(array)):
        if min_val > array[i]:
            index = i
            min_val = array[i]
        else:
            pass
    return index

def find_max_index(array):
    max_val = array[0]
    index = 0
    for i in range(len(array)):
        if max_val < array[i]:
            index = i
            max_val = array[i]
            print(index,max_val)

        else:
            pass
    return index

def min_max_sum(a):

    maxarray = []
    minarray = []
    i=0
    start_index = 0

    while(i!=4):
        maxarray.append(a[i])
        minarray.append(a[i])
        i+=1
        start_index = i

    for i in range(start_index,len(a)):
       min_index = find_min_index(maxarray)
       max_index = find_max_index(minarray)
       print(max_index)

       if a[i] < minarray[max_index]:
           minarray[max_index] = a[i]

       if a[i] > maxarray[min_index]:
           maxarray[min_index] = a[i]
    print(sum(maxarray),sum(minarray))

if __name__ == "__main__":
    array = [15,1,14,2,3,4,6,5,10,8,9,7]
    min_max_sum(array)


def gcd(a, b) -> int:
    if b == 0:
        return a

    remain = a % b
    return gcd(b, remain)

a, b = map(lambda x: int(x), input().split(" "))
res = gcd(a, b)
print(res)