import xml.etree.ElementTree as Et
import os
from BancoDados import DataBase5 as db
import shutil

class Read_xml():
    def __init__(self,directory)->None:
        self.directory=directory
        self.files = self.allfiles()
        #Exclui Pastas
        for i in ['\\Avisos', '\\ArquivosDominioSeparador']:
            try:
                shutil.rmtree(self.directory + i)
            except:
                pass

        for file in self.files:
            self.obj1 = self.atribui_parametros(file)
            self.check_chave(file, self.obj1[0], self.obj1[1], self.obj1[2])

    def allfiles(self):
        return [ os.path.join(self.directory, arq) for arq in os.listdir(self.directory) if arq.lower().endswith('.xml')]

    def contaArquivos(self, directory):
        contaArq = 0
        files = self.files
        for file in files:
            contaArq += 1
        return contaArq

    def virgulaEmPonto(self, arg):
        try:
            arg = str(arg).replace(',','.')
            arg = float(arg)
        except:
            pass
        return arg

    def pontoPorVirgula(self, arg):
        try:
            arg = str(arg).replace('.',',')
            arg = float(arg)
        except:
            pass
        return arg

    def buscaDb(self, elem, tb):
        self.busca = db()
        self.busca.conecta()
        if tb == 'TBUso':
            resultado = self.busca.check_uso(elem)
        else:
            resultado = self.busca.check_cfop(elem)
        self.busca.close_conection()
        return resultado

    def resumeLista(self,lista):
        listaSoma = []
        for i, lista1 in enumerate(lista):
            soma_tProd = self.virgulaEmPonto(lista1[0])
            soma_bc= self.virgulaEmPonto(lista1[2])
            soma_vImp = self.virgulaEmPonto(lista1[3])
            validador = ''
            for j, lista2 in enumerate(lista):
                if i !=j and lista1[1] == lista2[1]:
                    soma_tProd = soma_tProd + self.virgulaEmPonto(lista2[0])
                    soma_bc = soma_bc + self.virgulaEmPonto(lista2[2])
                    soma_vImp = soma_vImp + self.virgulaEmPonto(lista2[3])
            for x, list in enumerate(listaSoma):
                if listaSoma[x][1] == lista1[1]:
                    validador = 'alíquota já informada'
                    break
                else:
                    pass
            if validador != 'alíquota já informada':
                listaSoma.append([self.pontoPorVirgula(soma_bc),lista1[1], self.pontoPorVirgula(soma_vImp),'','','','',self.pontoPorVirgula(soma_tProd)])
            else:
                pass

        return listaSoma

    def atribui_parametros(self, xml):
        self.xml = xml
        root = Et.parse(self.xml).getroot()
        nsNFe = {'ns':'http://www.portalfiscal.inf.br/nfe'}

        #Cria pastas
        try:
            os.mkdir(self.directory + f'\\Avisos')
        except FileExistsError:
            pass

        total_dpl = 0
        for dpl in root.findall("./ns:NFe/ns:infNFe/ns:cobr/ns:dup", nsNFe):
            vlr_dpl_contador = (dpl.find(f'.ns:vDup', nsNFe))
            total_dpl = total_dpl + float(vlr_dpl_contador.text)

        itens = []
        for item in root.findall("./ns:NFe/ns:infNFe/ns:det", nsNFe):
            ncm = self.check_none(item.find('.ns:prod/ns:NCM', nsNFe))
            codigos = ['/ns:ICMS00', '/ns:ICMS10', '/ns:ICMS20', '/ns:ICMS30', '/ns:ICMS40', '/ns:ICMS51', '/ns:ICMS60', '/ns:ICMS70', '/ns:ICMS90', '/ns:ICMSSN101', '/ns:ICMSSN102', '/ns:ICMSSN201', '/ns:ICMSSN202', '/ns:ICMSSN500', '/ns:ICMSSN900', '/ns:ICMSST']
            for cada in codigos:
                if self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:orig', nsNFe)) == '':
                    pass
                else:
                    orig = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:orig', nsNFe))
                    if self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:CST', nsNFe)) == '':
                        cst_csosn = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:CSOSN', nsNFe))
                    else:
                        cst_csosn = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:CST', nsNFe))
                    cfop = self.check_none(item.find('.ns:prod/ns:CFOP', nsNFe))
                    cest = self.check_none(item.find('.ns:prod/ns:CEST', nsNFe))
                    v_prod = self.check_none(item.find('.ns:prod/ns:vProd', nsNFe))
                    v_prod_contador = item.find('.ns:prod/ns:vProd', nsNFe).text
                    itens.append([ncm,orig,cst_csosn,cfop,cest,v_prod,v_prod_contador])

        contador = 0
        vlr_maior = float(0)
        for i in itens:
            if float(i[6]) > vlr_maior:
                vlr_maior = float(i[6])
                item = contador #Local da lista onde está o maior valor
            contador = contador + 1

        if total_dpl > 0:
            #Acumuladores a prazo
            if itens[item][3] == '1556' or itens[item][3] =='1407':
                resultado = self.buscaDb(itens[item][0][0:4], 'TBUso')
                if resultado == False:
                    with open(self.directory + f'\\Avisos\\NCMs a serem configurados.txt', 'a') as arq:
                        arq.write(f'Configurar no banco de dados/Tabela uso e consumo o NCM {itens[item][0][0:4]}\n')
                        arq.close()
                else:
                    contaD = resultado[0][2]
                    contaC = '104'
                    acumulador = resultado[0][4]
            elif itens[item][3] == '2556' or itens[item][3] == '2407':
                resultado = self.buscaDb(itens[item][0][0:4], 'TBUso')
                if resultado == False:
                    with open(self.directory + f'\\Avisos\\NCMs a serem configurados.txt', 'a') as arq:
                        arq.write(f'Configurar no banco de dados/Tabela uso e consumo o NCM {itens[item][0][0:4]}\n')
                        arq.close()
                else:
                    contaD = resultado[0][2]
                    contaC = '104'
                    acumulador = resultado[0][6]
            else:
                resultado = self.buscaDb(itens[item][3], 'TBCFOP')
                if resultado == False:
                    with open(self.directory + f'\\Avisos\\CFOPs a serem configurados.txt', 'a') as arq:
                        arq.write(f'Configurar no banco de dados/Tabela CFOP o CFOP {cfop}\n')
                        arq.close()
                else:
                    contaD = resultado[0][1]
                    contaC = resultado[0][3]
                    acumulador = resultado[0][5]

        else:
            #Acumuladores a vista
            if itens[item][3] == '1556' or itens[item][3] =='1407':
                resultado = self.buscaDb(itens[item][0][0:4], 'TBUso')
                if resultado == False:
                    with open(self.directory + f'\\Avisos\\NCMs a serem configurados.txt', 'a') as arq:
                        arq.write(f'Configurar no banco de dados/Tabela uso e consumo o NCM {itens[item][0][0:4]}\n')
                        arq.close()
                else:
                    contaD = resultado[0][2]
                    contaC = '5'
                    acumulador = resultado[0][3]

            elif itens[item][3] == '2556' or itens[item][3] == '2407':
                resultado = self.buscaDb(itens[item][0][0:4], 'TBUso')
                if resultado == False:
                    with open(self.directory + f'\\Avisos\\NCMs a serem configurados.txt', 'a') as arq:
                        arq.write(f'Configurar no banco de dados/Tabela uso e consumo o NCM {itens[item][0][0:4]}\n')
                        arq.close()
                else:
                    contaD = contaD = resultado[0][2]
                    contaC = '5'
                    acumulador = resultado[0][5]
            else:
                resultado = self.buscaDb(itens[item][3], 'TBCFOP')
                if resultado == False:
                    with open(self.directory + f'\\Avisos\\CFOPs a serem configurados.txt', 'a') as arq:
                        arq.write(f'Configurar no banco de dados/Tabela CFOP o CFOP {cfop}\n')
                        arq.close()
                else:
                    contaD = resultado[0][1]
                    contaC = resultado[0][2]
                    acumulador = resultado[0][4]

        #Valida se não houve declaração das variáveis
        try:
            if contaD != '':
                pass
        except UnboundLocalError:
                contaD = '0'
                contaC = '0'
                acumulador = '0'

        return contaD, contaC, acumulador

    def check_chave(self, xml, contaD, contaC, acumulador):
        self.xml = xml
        root = Et.parse(self.xml).getroot()
        nsNFe = {'ns':'http://www.portalfiscal.inf.br/nfe'}

        chaveNFe = self.check_none(root.find('./ns:protNFe/ns:infProt/ns:chNFe', nsNFe))

        #Cria pastas
        try:
            os.mkdir(self.directory + f'\\ArquivosDominioSeparador')
        except FileExistsError:
            pass

        #Registro 0020 - Cadastro de fornecedores

        if self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CPF', nsNFe)) != '':
            doc_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CPF', nsNFe))
        elif  self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CNPJ', nsNFe)) != '':
            doc_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CNPJ', nsNFe))
        else:
            print('erro na definição do emitente')
            quit()

        nome_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:xNome', nsNFe))
        fantasia_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:xFant', nsNFe))
        if fantasia_emit == '':
            fantasia_emit = nome_emit
        rua_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:xLgr', nsNFe))
        nro_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:nro', nsNFe))
        if nro_emit.isnumeric():
            pass
        else:
            nro_emit = ''
        cpl_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:xCpl', nsNFe))
        bairro_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:xBairro', nsNFe))
        cod_mun_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:cMun', nsNFe))
        uf_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:UF', nsNFe))
        cod_pais_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:cPais', nsNFe))
        cep_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:enderEmit/ns:CEP', nsNFe))
        ie_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:IE', nsNFe))
        fone_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:fone', nsNFe))
        crt_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CRT', nsNFe))
        if crt_emit == '1' or crt_emit == '2':
            regimeApura = 'M'
        else:
            regimeApura = 'N'

        r0020 = '|'.join(['0020',doc_emit,nome_emit[0:150],fantasia_emit[0:40],rua_emit,nro_emit,cpl_emit,bairro_emit,cod_mun_emit,uf_emit,cod_pais_emit,cep_emit,ie_emit,
                          '','',fone_emit[0:2],fone_emit[2:],'','01/01/2021','','','N','7',regimeApura,'S','','','','','N','N','','','\n'])
        with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
            arqui.write(r0020)
            arqui.close()

        #Registo 0100 - Cadastro de produtos
        itemNota = 1
        prod = []

        for item in root.findall("./ns:NFe/ns:infNFe/ns:det", nsNFe):
            cod_item =  self.check_none(item.find(".ns:prod/ns:cProd", nsNFe))
            descricao_item = self.check_none(item.find('.ns:prod/ns:xProd', nsNFe))
            ncm = self.check_none(item.find('.ns:prod/ns:NCM', nsNFe))
            c_barra = self.check_none(item.find(".ns:prod/ns:cBarra", nsNFe))
            un_medida = self.check_none(item.find('.ns:prod/ns:uCom', nsNFe))
            tp_arma = self.check_none(item.find(".ns:prod/ns:arma/ns:tpArma", nsNFe))
            desc_arma = self.check_none(item.find(".ns:prod/ns:arma/ns:descr", nsNFe))
            chassi = self.check_none(item.find(".ns:prod/ns:veicProd/ns:chassi", nsNFe))
            vlr_unit_item = self.check_none(item.find('.ns:prod/ns:vUnCom', nsNFe))
            med = self.check_none(item.find(".ns:prod/ns:arma/ns:cProdANVISA", nsNFe))
            tp_med = ''
            if tp_arma != '':
                tp_prod = 'A'
            elif med != '':
                tp_prod = 'M'
                tp_med = '2'
            elif chassi != '':
                tp_prod = 'V'
            else:
                tp_prod = 'O'
            #Dados de produtos para o registro 1000 - Cadastro da nota de entrada
            cfop = self.check_none(item.find('.ns:prod/ns:CFOP', nsNFe))

            r0100 = '|'.join(['0100',cod_item,descricao_item,'',ncm,'',c_barra,'','1',un_medida,'N',tp_prod,tp_arma,desc_arma,tp_med,'N',chassi,vlr_unit_item,'','',
                              '','','','M','','','','','','','','','','','','','','','','',
                              '','','','','','','','','','','','','','','','','','','','',
                              '','','','','','','','','','43','43','43','','','01/01/2021','','','','','',
                              '','','','','','','','','','','','\n'])

            with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                arqui.write(r0100)
                arqui.close()

        #Registro 1000 - Cadastro da nota de entrada
        mod = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:ide/ns:mod", nsNFe))
        if mod == '55':
            mod = '36'

        if self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CPF', nsNFe)) != '':
            doc_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CPF', nsNFe))
        elif  self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CNPJ', nsNFe)) != '':
            doc_emit = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:emit/ns:CNPJ', nsNFe))
        else:
            print('erro na definição do emitente')
            quit()
        nfe = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:ide/ns:nNF", nsNFe))
        serie = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:ide/ns:serie", nsNFe))
        data_emissao = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:ide/ns:dhEmi", nsNFe))
        data_emissao = f'{data_emissao[8:10]}/{data_emissao[5:7]}/{data_emissao[:4]}'
        data_saient = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:ide/ns:dhSaiEnt", nsNFe))
        data_saient = f'{data_saient[8:10]}/{data_saient[5:7]}/{data_saient[:4]}'
        t_nf = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vNF", nsNFe))
        obs = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:infAdic/ns:infCpl", nsNFe))
        obs = obs + self.check_none(root.find("./ns:NFe/ns:infNFe/ns:infAdic/ns:infAdFisco", nsNFe))

        #Transporte
        modfrete = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:transp/ns:modFrete", nsNFe))
        if modfrete == '0':
            modfrete = 'C'
        elif modfrete =='1':
            modfrete = 'F'
        elif modfrete =='2':
            modfrete = 'T'
        elif modfrete == '3':
            modfrete = 'R'
        elif modfrete =='4':
            modfrete = 'D'
        elif modfrete =='9':
            modfrete = 'S'

        if self.check_none(root.find('./ns:NFe/ns:infNFe/ns:transp/ns:transporta/ns:CPF', nsNFe)) != '':
            doc_trans = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:transp/ns:transporta/ns:CPF', nsNFe))
        elif  self.check_none(root.find('./ns:NFe/ns:infNFe/ns:entrega/ns:CNPJ', nsNFe)) != '':
            doc_trans = self.check_none(root.find('./ns:NFe/ns:infNFe/ns:transp/ns:transporta/ns:CNPJ', nsNFe))
        else:
            doc_trans = ''

        t_vfrete = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vFrete", nsNFe))
        t_vseguro = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vSeg", nsNFe))
        t_voutro = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vOutro", nsNFe))
        t_vpis = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vPIS", nsNFe))
        t_vcofins = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vCOFINS", nsNFe))
        t_bcst = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vBCST", nsNFe))
        t_vprod = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vProd", nsNFe))
        t_vipi = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vIPI", nsNFe))
        t_st = self.check_none(root.find("./ns:NFe/ns:infNFe/ns:total/ns:ICMSTot/ns:vST", nsNFe))

        r1000 = '|'.join(['1000',mod,doc_emit,'',acumulador, cfop,'',nfe, serie,'',data_saient,data_emissao,t_nf,'',obs,modfrete,'T','','','',
                         '','','','','',t_vfrete,t_vseguro,t_voutro,t_vpis,'',t_vcofins,'','',t_bcst,'','','','',t_vprod,cod_mun_emit,
                          '0','','',ie_emit,'','','','','','','','','',chaveNFe,'','',cfop,'','','',
                           '','','','','','','','','','','','','1','','','','0,65','3','','',
                           '','','','','','','','','',t_vipi,t_st,'','','','','','','\n'])
        with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
            arqui.write(r1000)
            arqui.close()
        #PRODUTOS
        ipilist = []
        icmslist = []
        for item in root.findall("./ns:NFe/ns:infNFe/ns:det", nsNFe):
            cod_item =  self.check_none(item.find(".ns:prod/ns:cProd", nsNFe))
            qtd_item = self.check_none(item.find('.ns:prod/ns:qCom', nsNFe))
            vlr_unit_item = self.check_none(item.find('.ns:prod/ns:vUnCom', nsNFe))
            vlr_item = self.check_none(item.find('.ns:prod/ns:vProd', nsNFe))
            v_ipi = self.check_none(item.find('.ns:imposto/ns:IPI/ns:IPITrib/ns:vIPI', nsNFe))
            bc_ipi = self.check_none(item.find('.ns:imposto/ns:IPI/ns:IPITrib/ns:vBC', nsNFe))
            cst_ipi = self.check_none(item.find('.ns:imposto/ns:IPI/ns:IPITrib/ns:CST', nsNFe))
            v_desc = self.check_none(item.find('.ns:prod/ns:vDesc', nsNFe))
            serie_arma = self.check_none(item.find(".ns:prod/ns:arma/ns:nSerie", nsNFe))
            serie_cano = self.check_none(item.find(".ns:prod/ns:arma/ns:nCano", nsNFe))
            chassi = self.check_none(item.find(".ns:prod/ns:veicProd/ns:chassi", nsNFe))
            codigos = ['/ns:ICMS00', '/ns:ICMS10', '/ns:ICMS20', '/ns:ICMS30', '/ns:ICMS40', '/ns:ICMS51', '/ns:ICMS60', '/ns:ICMS70', '/ns:ICMS90', '/ns:ICMSSN101', '/ns:ICMSSN102', '/ns:ICMSSN201', '/ns:ICMSSN202', '/ns:ICMSSN500', '/ns:ICMSSN900']
            for cada in codigos:
                if self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:orig', nsNFe)) == '':
                    pass
                else:
                    orig = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:orig', nsNFe))
                    if self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:CST', nsNFe)) == '':
                        cst_csosn = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:CSOSN', nsNFe))
                    else:
                        cst_csosn = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:CST', nsNFe))
                    cst_csosn = orig + cst_csosn
                    bc_icms = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:vBC', nsNFe))
                    bc_icms_st = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:vBCST', nsNFe))
                    alq_icms = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:pICMS', nsNFe))
                    vlr_icms = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:vICMS', nsNFe))
                    vlr_icms_st = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:vICMS', nsNFe))
                    alq_icms_st = self.check_none(item.find(f'.ns:imposto/ns:ICMS{cada}/ns:pICMSST', nsNFe))
                    alq_ipi = self.check_none(item.find(f'.ns:imposto/ns:IPI/ns:IPITrib/ns:pIPI', nsNFe))
                    bc_issqn = self.check_none(item.find(f'.ns:imposto/ns:ISSQN/ns:vBC', nsNFe))
                    alq_issqn = self.check_none(item.find(f'.ns:imposto/ns:ISSQN/ns:vAliq', nsNFe))
                    vlr_issqn = self.check_none(item.find(f'.ns:imposto/ns:ISSQN/ns:vISSQN', nsNFe))
                    cfop = self.check_none(item.find('.ns:prod/ns:CFOP', nsNFe))
                    cest = self.check_none(item.find('.ns:prod/ns:CEST', nsNFe))
                    un_com = self.check_none(item.find('.ns:prod/ns:uCom', nsNFe))
                    v_prod = self.check_none(item.find('.ns:prod/ns:vProd', nsNFe))
                    alq_pis = self.check_none(item.find(f'.ns:imposto/ns:PIS/ns:PISAliq/ns:pPIS', nsNFe))
                    vlr_pis = self.check_none(item.find(f'.ns:imposto/ns:PIS/ns:PISAliq/ns:vPIS', nsNFe))
                    cst_pis = self.check_none(item.find(f'.ns:imposto/ns:PIS/ns:PISAliq/ns:CST', nsNFe))
                    bc_pis = self.check_none(item.find(f'.ns:imposto/ns:PIS/ns:PISAliq/ns:vBC', nsNFe))
                    vlr_cofins = self.check_none(item.find(f'.ns:imposto/ns:COFINS/ns:COFINSAliq/ns:vCOFINS', nsNFe))
                    alq_cofins = self.check_none(item.find(f'.ns:imposto/ns:COFINS/ns:COFINSAliq/ns:pCOFINS', nsNFe))
                    cst_cofins = self.check_none(item.find(f'.ns:imposto/ns:COFINS/ns:COFINSAliq/ns:CST', nsNFe))
                    bc_cofins = self.check_none(item.find(f'.ns:imposto/ns:COFINS/ns:COFINSAliq/ns:vBC', nsNFe))
                    v_frete = self.check_none(item.find('.ns:prod/ns:vFrete', nsNFe))
                    v_seg = self.check_none(item.find('.ns:prod/ns:vSeg', nsNFe))
                    v_outro = self.check_none(item.find('.ns:prod/ns:vOutro', nsNFe))

                    r1030 = '|'.join(['1030',cod_item,qtd_item,vlr_item,v_ipi,bc_ipi,'1',data_saient,'',cst_csosn,vlr_item,v_desc,bc_icms,bc_icms_st,alq_icms,'','',v_frete,v_seg,v_outro,
                                    '',vlr_icms,vlr_icms_st,'','','',vlr_unit_item,alq_icms_st,'',alq_ipi,bc_issqn,alq_issqn,vlr_issqn,cfop,'',alq_pis,vlr_pis,alq_cofins,vlr_cofins,'',
                                    cst_pis,bc_pis,cst_cofins,bc_cofins,chassi,'','','','','','','',serie_arma,serie_cano,'','S',un_com,'','',v_prod,
                                    '','','','','','','','','','','','','','','','','','','','',
                                    '','','','','','','','','','','',cest,'','','','','','','\n'])

                    with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                        arqui.write(r1030)
                        arqui.close()

                    ipilist.append([v_prod,alq_ipi,bc_ipi,v_ipi])
                    icmslist.append([v_prod,alq_icms,bc_icms,vlr_icms])

        #Registro 1020 IPI
        if ipilist != []:
            rIPI = self.resumeLista(ipilist)
            r1020=[]
            for list in rIPI:
                for i in ['1020','2','']:
                    r1020.append(i)
                for i in list:
                    r1020.append(i)
                for i in ['','','','','','\n']:
                    r1020.append(i)

                r1020 = '|'.join(r1020)

                with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                    arqui.write(r1020)
                    arqui.close()
                r1020 = []

        #Registro 1020 ICMS
        rICMS = self.resumeLista(icmslist)
        r1020 = []
        for list in rICMS:
            for i in ['1020','1','']:
                r1020.append(i)
            for i in list:
                r1020.append(i)
            for i in ['','','','','','\n']:
                r1020.append(i)
            i = ''
            r1020 = '|'.join(r1020)

            with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                arqui.write(r1020)
                arqui.close()
            r1020 = []

        #Boleto
        total_dpl = 0
        r1500 = []
        for dpl in root.findall("./ns:NFe/ns:infNFe/ns:cobr/ns:dup", nsNFe):
            venc = self.check_none(dpl.find(f'.ns:dVenc', nsNFe))
            venc = venc[8:10] + '/' + venc[5:7] + '/' + venc[0:4]
            vlr_dpl_contador = (dpl.find(f'.ns:vDup', nsNFe))
            vlr_dpl = self.check_none(vlr_dpl_contador)
            total_dpl = total_dpl + float(vlr_dpl_contador.text)
            r1500.append(['1500',venc,vlr_dpl,'','','','','','','','','','','','','\n'])

    #def lancamento_contabil(t_nf, total_dpl,data_saient, contaD, contaC,mod,nfe,nome_emit,doc_emit,vlr_dpl,chaveNFe):
        if contaD == '0':
            pass
        else:
            vlr_vista = float(str(t_nf).replace(',','.')) - total_dpl
            v_vista = str(vlr_vista).replace('.',',')
            t_dpl = str(total_dpl).replace('.',',')

            if float(str(t_nf).replace(',','.')) > total_dpl and total_dpl > 0:
                r1300 = '|'.join(['1300',data_saient,'','5',v_vista,'',f'CFE DOCUMENTO FISCAL MODELO {mod} DE N° {nfe}, PARTICIPANTE {nome_emit} {doc_emit}','','',
                        '\n1300',data_saient,'','104',t_dpl,'',f'CFE DOCUMENTO FISCAL MODELO {mod} DE N° {nfe}, PARTICIPANTE {nome_emit} {doc_emit}','','',
                        '\n1300',data_saient,contaD,'',t_nf,'',f'CFE DOCUMENTO FISCAL MODELO {mod} DE N° {nfe}, PARTICIPANTE {nome_emit} {doc_emit}','','','\n'])

                with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                    arqui.write(r1300)
                    arqui.close()

            elif vlr_vista == float(str(t_nf).replace(',','.')) or total_dpl == float(str(t_nf).replace(',','.')) or total_dpl > float(str(t_nf).replace(',','.')) and total_dpl < (float(str(t_nf).replace(',','.')) + 0.01):
                r1300 = '|'.join(['1300',data_saient,contaD,contaC,t_nf,'',f'CFE DOCUMENTO FISCAL MODELO {mod} DE N° {nfe}, PARTICIPANTE {nome_emit} {doc_emit}','','','\n'])

                with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                    arqui.write(r1300)
                    arqui.close()

            else:
                with open(self.directory + f'\\Avisos\\Duplicatas maiores que o valor da nota.txt', 'a') as arqui:
                    arqui.write(f'A nota fiscal possui duplicata com valor maior que a nota, não houve lançamento contábi {chaveNFe}\n')
                    arqui.close()

        #Adicionando dados do boleto no TXT para seguir a ordem (dá erro no domínio se não estiver em ordem)
        for i in r1500:
            with open(self.directory + f'\\ArquivosDominioSeparador\\{chaveNFe}.txt', 'a') as arqui:
                arqui.write('|'.join(i))
                arqui.close()

    def check_none(self, var):
        if var == None:
            return ''
        else:
            try:
                var= var.text.replace('.',',')
                var= var.replace('|','-')
                return var
            except:
                return var.text

if __name__ == '__main__':
    obj = Read_xml('Z:\\CLIENTES\\- Pessoa Juridica\\Santos & Avila Fabricação E Comércio De Estofados LTDA\\Escrita Fiscal\\2023\\05-2023\\Arquivos enviado pelo cliente\\Entradas')


import random

def get_avg_brand_followers(all_handles, brand_name):
    count = 0
    for i in range(len(all_handles)):
        for j in range(len(all_handles[i])):
            if brand_name in all_handles[i][j]:
                count += 1
    return count / len(all_handles)

# don't touch below this line

def test(num_handles, avg_aud_size, brand_name):
    print(
        f"Checking {num_handles} influencers with average audience sizes of {avg_aud_size}..."
    )
    all_handles = get_all_handles(num_handles, avg_aud_size)
    avg = round(get_avg_brand_followers(all_handles, brand_name), 2)
    print(f"Average {brand_name} fans per influencer: {avg}")
    print("====================================")

def main():
    random.seed(1)
    test(10, 1000, "luxa")
    test(20, 2000, "luxa")
    test(40, 4000, "luxa")
    test(80, 8000, "luxa")
    test(160, 16000, "luxa")

def get_all_handles(num, audience_size):
    all_handles = []
    for i in range(num):
        m = random.randrange(
            int(audience_size - audience_size * 1.2),
            int(audience_size + audience_size * 1.2),
        )
        handles = get_instagram_handles(m)
        all_handles.append(handles)
    return all_handles

def get_instagram_handles(num):
    handles = []
    for i in range(0, num):
        m = random.randrange(0, 6)
        if m == 0:
            handles.append(f"luxaraygirl{i}")
        elif m == 1:
            handles.append(f"theprimerog{i}")
        elif m == 2:
            handles.append(f"luxafanboi{i}")
        elif m == 3:
            handles.append(f"dashlord{i}")
        elif m == 4:
            handles.append(f"saintrex{i}")
        elif m == 5:
            handles.append(f"writergurl{i}")
    return handles

main()


import pytest
from two_sum_iv___input_is_a_bst import Solution
from helpers.treenode import TreeNode

@pytest.mark.parametrize('arr, k, expected', [
    ([5,3,6,2,4,None,7], 9, True),
    ([5,3,6,2,4,None,7], 28, False),
])
def test_solution(arr, k, expected):
    root = TreeNode.from_array(arr)
    assert Solution().findTarget(root, k) == expected


#!/usr/bin/env python3
# -*-encoding: utf-8-*-

# by David Zashkol
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com

import numpy as np
from math import sin

def gety(f, x):
    """Повертає значення функції f для всіх точок з x
    """
    try:
        y = f(x)
    except Exception as e:
        print('Exception handling', e)
        n = x.size
        y = np.zeros(n)
        for i in range(n):
            y[i] = f(x[i])
    return y

def tabulate(f, a, b, n):
    """Табулює функцію f на інтервалі [a,b] у n точках
    """
    x = np.linspace(a, b, n)
    y = gety(f, x)
    return x, y

def fun(x):
    """x**3 - 7*x - 1
    """
    return x**3 - 7*x - 1

if __name__ == '__main__':
    test_n = int(input('Кількість точок: '))
    test_a = float(input('Початок відрізку: '))
    test_b = float(input('Кінець відрізку: '))

    funcs = [fun, sin, np.vectorize(sin)]
    for ff in funcs:
        test_x, test_y = tabulate(ff, test_a, test_b, test_n)
        if test_n < 50:
            print('\n\n', test_x, '\n\n', test_y)
        print('Зроблено для', str(ff))


from tkinter import *
from tkinter import ttk

def style():
    "Paramétrage du style des widget"
    style = ttk.Style()
    style.theme_use('default')
    style.configure("Treeview", background="#D3D3D3", foreground="black", rowheight=22, fieldbackground="#D3D3D3")
    style.map('Treeview', background=[('selected', '#')])

class Tableau():
    def __init__(self, fm, header, data):
        # fenetre mere, entete, données
        self.count = 0
        self.data = data
        style()
        self.tf = Frame(fm)
        self.tf.pack(pady=20, side=TOP)
        # Ajouter tableau à gauche
        self.tv = ttk.Treeview(self.tf, selectmode='extended')
        self.tv.pack(side=LEFT)
        print(header)
        print([h for h, a in header])
        # Définition des colonnes
        self.tv['columns'] = [h for h, a in header]
        # Format des colonnes
        self.tv.column('#0', width=0, stretch=NO)
        self.tv.heading('#0', text='', anchor=CENTER)
        logger.info('Initialisation du tableau')
        # structure du tableau
        for titre, align in header:
            print(titre, align)
            # Colonnes
            self.tv.column(titre, anchor=align, width=140)
            #  Titres des colonnes
            self.tv.heading(titre, text=titre, anchor='center')

        # Ajout Scrollbar à droite
        self.sb = Scrollbar(self.tf, orient=VERTICAL)
        self.sb.pack(side=RIGHT, fill=Y)
        self.tv.config(yscrollcommand=self.sb.set)
        self.sb.config(command=self.tv.yview)


import os
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator

import pytest
from tarn import HashKeyStorage
from tarn.config import StorageConfig, init_storage

from connectome import CacheToDisk

@pytest.fixture
def storage_factory():
    @contextmanager
    def factory(locker=None, group=None, names=('storage',)) -> Iterator[HashKeyStorage]:
        with tempfile.TemporaryDirectory() as root:
            roots = []
            for name in names:
                root = Path(root) / name
                roots.append(root)
                init_storage(
                    StorageConfig(hash='blake2b', levels=[1, 63], locker=locker),
                    root, group=group,
                )

            yield HashKeyStorage(roots)

    return factory

@pytest.fixture
def disk_cache_factory(storage_factory):
    def init(root, storage, serializer, names, locker, cls, **kwargs):
        init_storage(StorageConfig(hash='blake2b', levels=[1, 63], locker=locker), root)
        return cls(root, storage, serializer, names, **kwargs)

    @contextmanager
    def factory(names, serializer, locker=None, storage=None, root=None, cls=CacheToDisk, **kwargs):
        with tempfile.TemporaryDirectory() as _root, storage_factory(locker=locker) as _storage:
            if root is None:
                root = _root
            if storage is None:
                storage = _storage
            yield init(Path(root) / 'cache', storage, serializer, names, locker, cls, **kwargs)

    return factory

@pytest.fixture
def temp_dir(tmpdir):
    return Path(tmpdir)

@pytest.fixture
def chdir():
    @contextmanager
    def internal(folder):
        current = os.getcwd()
        try:
            os.chdir(folder)
            yield
        finally:
            os.chdir(current)

    return internal


#函数式写法
import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Convolution2D, MaxPooling2D, Flatten, Input
from keras.optimizers import Adam

#使用keras下载数据集有点问题，手动下载数据集
mnist = np.load("../dataset/mnist.npz")
X_train, y_train, X_test, y_test = mnist['x_train'], mnist['y_train'], mnist['x_test'], mnist['y_test']

#data pre-processing
X_train = X_train.reshape(-1,28,28,1)/255 #最后一个1表示只有一个channel，黑白照片
X_test = X_test.reshape(-1,28,28,1)/255

#使用keras编写的np_utils，把标签分为10类，每一类都用10位二进制表示，某一位为1其他为0
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)

inputs=Input(batch_shape=(None,28,28,1))
x=Convolution2D(filters=32,kernel_size=5,padding='same',strides=1,activation='relu')(inputs)
x=MaxPooling2D(pool_size=(2,2),strides=2,padding='same')(x)
x=Convolution2D(64,5,padding='same',strides=1,activation='relu')(x)
x=MaxPooling2D(pool_size=(2,2),strides=2,padding='same')(x)
x=Flatten()(x)
x=Dense(1024,activation='relu')(x)
predictions=Dense(10,activation='softmax')(x)

model=Model(inputs=inputs,outputs=predictions)

adam=Adam(lr=1e-4)

model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])

print('Training---------')
model.fit(X_train,y_train,batch_size=32,epochs=2)

print('Testing---------')
loss,accuracy=model.evaluate(X_test,y_test)

print('loss: ',loss)
print('accuracy: ',accuracy)


#!/usr/bin/env python3

import os
import argparse
import sys
from Bio.SeqIO.FastaIO import SimpleFastaParser as sfp

def main(argv):
    parser = argparse.ArgumentParser()

    parser.add_argument("contigFile", help="assign file")

    parser.add_argument("summaryFile", help="summary file")

    parser.add_argument("outputDir", help="output directory")

    parser.add_argument("filtContFile", help="filtered contig file")

    args = parser.parse_args()

    contig_comp = {}
#    import ipdb; ipdb.set_trace()
    bFirst = True
    with open(args.summaryFile) as f:
        for line in f:
            if not bFirst:
                toks = line.rstrip().split("\t")
                contig_comp[toks[0]] = int(toks[2].strip('%'))
            else:
                bFirst = False

    keep = []
    for header,seq in sfp(open(args.contigFile)):
        bFilt = False
        if header in contig_comp and header[-1] == 'c':
            if contig_comp[header] > 90:
                with open("%s/circ_%s.fa"%(args.outputDir,header),"w") as handle:
                    handle.write(">%s\n%s\n"%(header,seq))
                    bFilt = True
        if not bFilt:
            keep.append(">%s\n%s\n"%(header,seq))
    with open(args.filtContFile,'w') as f:
        for line in keep:
            f.write(line)
if __name__ == "__main__":
    main(sys.argv[1:])


import os
from uuid import uuid4

import httpx
from bs4 import BeautifulSoup

from app.core.namespace import DownloadNS

from .base import Downloader
from .crud import PostgresDownloaderCRUD

class ParseDownloader(Downloader):
    def __init__(self, url: str, crud_p: PostgresDownloaderCRUD) -> None:
        self.__url = url
        self.__crud_p = crud_p

    def _make_request(self, url: str) -> httpx.Response:
        with httpx.Client() as client:
            effect = client.get(url=url)
            return effect

    def _download_file(self, url: str, filename: str) -> None:
        with open(filename, "wb") as f:
            with httpx.stream("GET", url) as r:
                for chunk in r.iter_bytes():
                    f.write(chunk)

    def download(self, url: str) -> None:
        effect = self._make_request(url=url)
        soup = BeautifulSoup(effect.text, "lxml")
        href = soup.find("div", {"class": "f-sm-50"}).find("a")["href"]
        effect = self._make_request(url="{}{}".format(self.__url, href))
        if effect.status_code != 302:
            return

        name = uuid4().__str__()
        filename = ".{}/{}{}".format(DownloadNS.DIR.value, name, ".apk")
        folder = ".{}/{}".format(DownloadNS.DIR.value, name)
        self._download_file(
            url=effect.headers["location"],
            filename=filename,
        )
        os.system(f"yes 'y' | 7z x {filename} -o{folder}")
        file_size = int(os.popen(f"du -s {filename}").read().split("\t")[0])
        folder_size = int(os.popen(f"du -s {folder}").read().split("\t")[0])

        self.__crud_p.download.create(
            url=url,
            filename=filename,
            folder=folder,
            file_size=file_size,
            folder_size=folder_size,
        )


import datetime

def display_non_null_balances(wallet_balance):
    print("Balance:")
    for asset, total in wallet_balance.items():
        if total > 0.0001:
            print(f"{asset}: {total}")

def date_to_milliseconds(date_str):
    # Helper function to convert a date string (format: 'YYYY-MM-DD') to milliseconds
    epoch = datetime.datetime.utcfromtimestamp(0)
    date_obj = datetime.datetime.strptime(date_str, '%Y-%m-%d')
    return int((date_obj - epoch).total_seconds() * 1000)

def milliseconds_to_date(milliseconds):
    # Helper function to convert milliseconds to a date string (format: 'YYYY-MM-DD')
    date_obj = datetime.datetime.utcfromtimestamp(milliseconds / 1000)
    return date_obj.strftime('%Y-%m-%d')

def convert_time_seconds(time_str: str) -> int:
    time_units = {
        's': 1,
        'm': 60,
        'h': 3600,
        'd': 86400,
        'w': 604800,
        'M': 2592000,
        'y': 31536000
    }

    value, unit = int(time_str[:-1]), time_str[-1]

    if unit not in time_units:
        raise ValueError("Invalid time format. Please use s (seconds), m (minutes), h (hours), d (days), w (weeks), M (months), or y (years).")

    return value * time_units[unit]


import asyncio

async def foo(n):
    await asyncio.sleep(5)  # wait 5s before continuing
    print(f"n: {n}!")

async def main():
    tasks = [foo(1), foo(2), foo(3)]
    await asyncio.gather(*tasks)

asyncio.run(main())


from python_imagesearch.imagesearch import *

def imageSearchAndClickLoop(image, timesample, precision=0.8):
    pos = imagesearch_loop(image, timesample, precision)
    pyautogui.moveTo(pos[0], pos[1], 0.05)
    pyautogui.click()

def imageSearchAndClick(image, precision=0.8) -> bool:
    pos = imagesearch(image, precision)
    if pos[0] != -1:
        pyautogui.moveTo(pos[0], pos[1], 0.05)
        pyautogui.click()
        return True
    return False


import torch
import torch.nn as nn
import functools

class GlobalGenerator3(nn.Module):
    def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=9, padding_type='reflect'):
        assert (n_blocks >= 0)
        super(GlobalGenerator3, self).__init__()
        activation = nn.ReLU(True)

        model1 = [nn.Conv2d(input_nc, ngf, kernel_size=3, stride=1, padding=1), activation]
        ### downsample
        mult = 2 ** 0
        model2 = [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1), activation]
        mult = 2 ** 1
        model3 = [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1), activation]

        ### resnet blocks
        mult = 2 ** n_downsampling
        model4 = []
        for i in range(n_blocks):
            model4 += [ResnetBlock22(ngf * mult, padding_type=padding_type, activation=activation)]

        mult = 2 ** (n_downsampling - 0)
        model5 = [nn.Conv2d(ngf * mult*2, int(ngf * mult / 2)*4, kernel_size=3, stride=1, padding=1)]
        self.model5_act = activation
        mult = 2 ** (n_downsampling - 1)
        model6 = [nn.Conv2d(ngf * mult*2, int(ngf * mult / 2) * 4, kernel_size=3, stride=1, padding=1)]
        self.model6_act = activation

        model7 = []
        model7 += [nn.Conv2d(ngf*2, ngf, kernel_size=3, stride=1, padding=1)]
        model7 += [activation, nn.Conv2d(ngf, output_nc, kernel_size=1, padding=0)]
        self.model1 = nn.Sequential(*model1)
        self.model2 = nn.Sequential(*model2)
        self.model3 = nn.Sequential(*model3)
        self.model4 = nn.Sequential(*model4)
        self.model5 = nn.Sequential(*model5)
        self.model6 = nn.Sequential(*model6)
        self.model7 = nn.Sequential(*model7)
        self.pixel_shuffle = nn.PixelShuffle(2)
        self.reset_params()

    @staticmethod
    def weight_init(m, init_type='kaiming', gain=0.02, scale=0.1):
        classname = m.__class__.__name__
        if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
            if init_type == 'normal':
                nn.init.normal_(m.weight.data, 0.0, gain)
            elif init_type == 'xavier':
                nn.init.xavier_normal_(m.weight.data, gain=gain)
            elif init_type == 'xavier_uniform':
                nn.init.xavier_uniform_(m.weight.data, gain=1.0)
            elif init_type == 'kaiming':
                nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
                m.weight.data *= scale
            elif init_type == 'orthogonal':
                nn.init.orthogonal_(m.weight.data, gain=gain)
            else:
                raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
            if hasattr(m, 'bias') and m.bias is not None:
                nn.init.constant_(m.bias.data, 0.0)

    def reset_params(self):
        for _, m in enumerate(self.modules()):
            self.weight_init(m)

    def forward(self, input):
        feature1 = self.model1(input)
        feature2 = self.model2(feature1)
        feature3 = self.model3(feature2)

        feature4 = self.model4(feature3)
        feature4 = torch.cat([feature4, feature3], dim=1)

        feature5 = self.model5(feature4)
        feature5 = self.pixel_shuffle(feature5)
        feature5 = self.model5_act(feature5)
        feature5 = torch.cat([feature5, feature2], dim=1)

        feature6 = self.model6(feature5)
        feature6 = self.pixel_shuffle(feature6)
        feature6 = self.model6_act(feature6)
        feature6 = torch.cat([feature6, feature1], dim=1)

        output = self.model7(feature6)
        return output

# Define a resnet block
class ResnetBlock22(nn.Module):
    def __init__(self, dim, padding_type, activation=nn.ReLU(True), use_dropout=False):
        super(ResnetBlock22, self).__init__()
        self.conv_block = self.build_conv_block(dim, padding_type, activation, use_dropout)

    def build_conv_block(self, dim, padding_type, activation, use_dropout):
        conv_block = []
        p = 0
        if padding_type == 'reflect':
            conv_block += [nn.ReflectionPad2d(1)]
        elif padding_type == 'replicate':
            conv_block += [nn.ReplicationPad2d(1)]
        elif padding_type == 'zero':
            p = 1
        else:
            raise NotImplementedError('padding [%s] is not implemented' % padding_type)

        conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p),
                       activation]
        if use_dropout:
            conv_block += [nn.Dropout(0.5)]

        p = 0
        if padding_type == 'reflect':
            conv_block += [nn.ReflectionPad2d(1)]
        elif padding_type == 'replicate':
            conv_block += [nn.ReplicationPad2d(1)]
        elif padding_type == 'zero':
            p = 1
        else:
            raise NotImplementedError('padding [%s] is not implemented' % padding_type)
        conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p)]

        return nn.Sequential(*conv_block)

    def forward(self, x):
        out = x + self.conv_block(x)
        return out


"""picturethis URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url

from api import views

urlpatterns = [
    # FRIEND API
    url(r'^friend/add_friend', views.friend__add_friend, name='picturethis__friend__add_friend'),
    url(r'^friend/remove_friend', views.friend__remove_friend, name='picturethis__friend__remove_friend'),
    url(r'^friend/block_friend', views.friend__block_friend, name='picturethis__friend__block_friend'),
    url(r'^friend/get_friends', views.friend__get_friends, name='picturethis__friend__get_friends'),

    # LOGIN API
    url(r'^login/create_user', views.login__create_user, name='picturethis__login__create_user'),
    url(r'^login/login', views.login__login, name='picturethis__login__login'),
    url(r'^login/token_login', views.login__token_login, name='picturethis__login__token_login'),

    # USER API
    url(r'^user/update_password', views.user__update_password, name='picturethis__user__update_password'),

    # BANK API
    url(r'^bank/get_user_bank', views.bank__get_user_bank, name='picturethis__bank__get_user_bank'),

    # SEARCH API
    url(r'^search/find_user', views.search__find_user, name='picturethis__search__find_user'),

    # POLL API
    url(r'^poll/update', views.poll__update, name='picturethis__poll__update'),

    # GAME API
    url(r'^game/start_new_game', views.game__start_new_game, name='picturethis__game__start_new_game'),
    url(r'^game/send_picture', views.game__send_picture, name='picturethis__game__send_picture'),
    url(r'^game/get_picture', views.game__get_picture, name='picturethis__game__get_picture'),
    url(r'^game/end_game', views.game__end_game, name='picturethis__game__end_game'),
    url(r'^game/validate_guess', views.game__validate_guess, name='picturethis__game__validate_guess'),
    url(r'^game/give_up_turn', views.game__give_up_turn, name='picturethis__game__give_up_turn'),
    url(r'^game/get_user_games', views.game__get_user_games, name='picturethis__game__get_user_games'),
    url(r'^game/get_game_status', views.game__get_game_status, name='picturethis__game__get_game_status'),
    url(r'^game/get_new_word', views.game__get_new_word, name='picturethis__game__get_new_word'),

    # REMOVE THIS LATER
    url(r'^game/end_all_games', views.game__end_all_games, name='picturethis__game__end_all_games'),

    # WORD_PROMPT API
    url(r'^word_prompt/request_hint', views.word_prompt__request_hint, name='picturethis__word_prompt__request_hint'),

    # BANK API
    url(r'^bank/get_user_bank', views.bank__get_user_bank, name='bank__get_user_bank'),
    url(r'^bank/decrement_bank', views.bank__decrement_bank, name='bank__decrement_bank'),
]


# 链接：https://leetcode.com/problems/sum-of-digits-of-string-after-convert/
# 题意：给定一个字符串 s ，先将其转换成数字后拼接在一起，
#       然后计算所有数位的和，重复这样的过程 k 次，返回最后的数？

# 数据限制：
#   1 <= s.length <= 100
#   1 <= k <= 10
#   s 只由英文小写字母组成

# 输入： s = "iiii", k = 1
# 输出： 36
# 解释：
#       转换： "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999
#       计算： #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36

# 输入： s = "leetcode", k = 2
# 输出： 6
# 解释：
#       转换： "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545
#       计算： #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
#             #2: 33 ➝ 3 + 3 = 6

# 输入： s = "zbax", k = 2
# 输出： 2

# 思路： 模拟
#
#       按照题意计算所数位之和 k 次即可
#
#       时间复杂度： O(kn)
#       空间复杂度： O(n)

class Solution:
    def getLucky(self, s: str, k: int) -> int:
        s = "".join([str(string.ascii_lowercase.index(ch) + 1) for ch in s])
        while k > 0:
            k -= 1
            s = str(sum([int(ch) for ch in s]))
        return int(s)

Python3/src/1901 ~ 2000/1945 - Sum of Digits of String After Convert.py


import sys
import struct

def main():
	if len(sys.argv) < 2 or (sys.argv[1] != "higu" and sys.argv[1] != "chiru" and sys.argv[1] != "umi"):
		print("Must specify higu or umi or chiru")
		return
	game = ""
	if sys.argv[1] == "higu":
		game = "higurashi"
	elif sys.argv[1] == "chiru":
		game = "chiru"
	elif sys.argv[1] == "umi":
		game = ""
	fontname = game == "higurashi" and "gothic" or "default"

	if len(sys.argv) == 3 and sys.argv[2] == "restore":
		with open(fontname + ".fnt", "rb") as f:
			newdata = list(f.read())
			with open(fontname + "_new.fnt", "wb") as nf:
				nf.write(bytearray(newdata))
			with open(game + "_data/DATA.ROM", "r+b") as rom:
				if game == "higurashi":
					rom.seek(0x453000)
				elif game == "chiru":
					rom.seek(0x138800)
				elif game == "":
					rom.seek(0x149000)
				rom.write(bytearray(newdata))
				return

	with open(fontname + ".fnt", "rb") as f:
		newdata = list(f.read())
		olddata = list(newdata)
		fileSize = struct.unpack('i', ''.join(newdata[4:8]))[0]
		startoff = 16

		def getOffset(index):
			off = startoff + index * 4
			offset = struct.unpack('i', ''.join(olddata[off:off+4]))[0]
			return offset

		def update(index, attr, val):
			offset = getOffset(index)
			newdata[offset + attr] = val

		def setData(index, data):
			offset = getOffset(index)
			newdata[offset + 6:offset + 6 + len(data)] = data

		def replace(src, dst):
			srcOffset = getOffset(src)
			srcBytes = 8 + ((ord(olddata[srcOffset + 6]) & 0xff) | ((ord(olddata[srcOffset + 7]) << 8) & 0xff00))
			srcData = olddata[srcOffset:srcOffset + srcBytes]
			dstOffset = getOffset(dst)
			if dstOffset >= fileSize:
				print("Offset is outside of file.")
				raw_input()
			newdata[dstOffset:dstOffset + srcBytes] = srcData
			#print("Replacing glyph {}[{:08X}] with {}[{:08X}]. Validity = {}".format(dst, dstOffset, src, srcOffset, ''.join("{:02X} ".format(ord(newdata[getOffset(0)+i])) for i in range(10))))
			#raw_input()

		#newdata[getOffset(0):len(newdata) - getOffset(0)] = [0 for i in range(len(newdata) - getOffset(0))]
		for i in range(3000):
			replace(0, i + 1)
		#replace(1, 443)
		#replace(133, 98)
		#replace(0x81fb - 0x8140 + 96, 98)
		#replace(299, 98)
		#update(98, 59, 0x03)
		#update(98, 60, 0x03)
		#update(98, 26, 0x04)
		#update(98, 65, 0x02)
		#update(98, 56, 0x67)
		#update(98, 8, 0xf0)
		#update(96, 7, 0xff)
		#update(96, 8, 0xff)
		#update(96, 9, 0xff)
		#update(96, 10, 0xff)
		#update(98, 8, 0x00)
		#update(98, 15, 0x2c)
		#update(98, 16, 0x01)
		#for i in range(10):
		#	update(98, 6 + i, 0xff)
		#update(3, 0, 100)
		#for i in range(8180):
		#	update(i, 7, i % 255)

		with open(fontname + "_new.fnt", "wb") as nf:
			nf.write(bytearray(newdata))

		with open(game + "_data/DATA.ROM", "r+b") as rom:
			if game == "higurashi":
				rom.seek(0x453000)
			elif game == "chiru":
				rom.seek(0x138800)
			elif game == "":
				rom.seek(0x149000)
			rom.write(bytearray(newdata))

if __name__ == '__main__':
	main()


import os
import sys
cwd = os.getcwd()
if ("TDO") not in cwd:
	print("error with sys.path")
	exit()
else:
	index_tdo = cwd.index("TDO")
	cwd = cwd[:index_tdo+3]#+3] #+  "/"
	sys.path.append(cwd)
	cwd = cwd[:index_tdo]  # +3] #+  "/"
	sys.path.append(cwd)

print("Experiments with rules -- Sums & Rules -- genre ")
#os.system("python selection_algorithm_experiments_normalized.py birthPlace 0 1 False ic source_average False [dataset-2_100,dataset-2_101,dataset-2_102,dataset-2_103,dataset-3_100,dataset-3_101,dataset-3_102,dataset-3_103,dataset-4_100,dataset-4_101,dataset-4_102,dataset-4_103,dataset-5_100,dataset-5_101,dataset-5_102,dataset-5_103,dataset_200,dataset_201,dataset_202,dataset_301,dataset_50,dataset_51,dataset_52,dataset_53,dataset_54]")
os.system("python dataset_analysis.py")


"""
Mitosis is splitting DNA strands and mutating them
"""
from operator import itemgetter
from gp_framework.population_manager import *
from gp_framework.bytegenotype import ByteGenotype

class SimpleManager(PopulationManager):
    def produce_offspring(self, population: List[ByteGenotype]) -> Tuple[List[ByteGenotype], List[ByteGenotype]]:
        judged_population = self.calculate_population_fitness(population)
        fittest_individual_tuple = max(judged_population, key=itemgetter(1))
        fitness: float = fittest_individual_tuple[1]
        children = []

        for _ in range(len(population)):
            child: ByteGenotype = fittest_individual_tuple[0]
            child.mutate((1.0 - fitness) * .0001)
            children.append(child)

        return [fittest_individual_tuple[0]], children

    def select_next_generation(self, parents: List[ByteGenotype], children: List[ByteGenotype]) -> List[ByteGenotype]:
        self._newest_report = self.make_LifecycleReport(children)
        return children

class TruncationManager(PopulationManager):
    def produce_offspring(self, population: List[ByteGenotype]) -> Tuple[List[ByteGenotype], List[ByteGenotype]]:
        children = []
        for genotype in population:
            child = genotype
            child.mutate(.0001)
            children.append(child)
        return population, children

    def select_next_generation(self, parents: List[ByteGenotype], children: List[ByteGenotype]) -> List[ByteGenotype]:
        all_genotypes = self.calculate_population_fitness(parents + children)
        all_genotypes.sort(key=lambda e: e[1], reverse=True)
        half_way = int(len(all_genotypes) / 2)
        new_population = [g[0] for g in all_genotypes[0:half_way]]
        self._newest_report = self.make_LifecycleReport(new_population)
        return new_population

class BruteForce(PopulationManager):
    def __init__(self, population: List[ByteGenotype], fitness_calculator: FitnessCalculator, name: str = "Brute Force Manager"):
        super().__init__(population, fitness_calculator, name)
        judged_population = self.calculate_population_fitness(population)
        judged_population.sort(key=lambda e: e[1], reverse=True)
        self._best_genotype = judged_population[0][0]
        self._best_fitness = -1

    def produce_offspring(self, population: List[ByteGenotype]) -> Tuple[List[ByteGenotype], List[ByteGenotype]]:
        children = ByteGenotype.generate_random_population(20, len(self._best_genotype))
        return [self._best_genotype], children

    def select_next_generation(self, parents: List[ByteGenotype], children: List[ByteGenotype]) -> List[ByteGenotype]:
        combined_pop_with_fitness = self.calculate_population_fitness(parents + children)
        combined_pop_with_fitness.sort(key=lambda elem: elem[1], reverse=True)
        self._best_genotype = combined_pop_with_fitness[0][0]
        self._best_fitness = combined_pop_with_fitness[0][1]
        # this could just be a list with just the fittest individual since that's what'll be output anyways
        self._newest_report = self.make_LifecycleReport([elem[0] for elem in combined_pop_with_fitness])
        return []


# -*- coding: UTF-8 -*-

import os
import sys
import cv2
import math
import time
import numpy as np
from matplotlib import pyplot as plt
from skimage.measure import label, regionprops

from utils import *
from cross import get_cross

POINTS = {}

def display_index(img, color=(0,0,255), size=0.6, thickness=2):
    if img.shape[-1] > 4: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

    font = cv2.FONT_HERSHEY_SIMPLEX
    for pos in POINTS:
        elem = POINTS[pos]
        point = (int(pos[0]), int(pos[1]))
        index = elem["index"]
        # img = cv2.circle(img, point, radius, color, thickness)
        img = cv2.putText(img, str(index), point, font, size, color, thickness)
    plt.imshow(img), plt.title("Image Indexing Result")
    plt.show()

    return img

def extract_image(img, thresh=220, min_rad=15, max_rad=80):
    """Binarize the input image and extract multiple info

    Args:
        img: Input grayscale image
        thresh: Thesholding value for the image binarization
        min_rad: Minimum point radius
        max_rad: Maximum point radius

    Returns:
        img_points: Binarized image contains the points
        img_cross: Binarized image contains the cross

    """
    img = cv2.GaussianBlur(img,(5,5),0)
    thres,img_points = cv2.threshold(img,thresh,255,cv2.THRESH_BINARY)
    img_cross = img_points.copy()

    # Create the region proposal mask and filter out the curve
    label_mask = label(img_points, connectivity = 2)
    properties = regionprops(label_mask)

    for prop in properties:
        diameter = prop.equivalent_diameter
        if diameter < min_rad:
            img_points[label_mask==prop.label] = 0
            img_cross[label_mask==prop.label] = 0
        elif diameter > max_rad:
            img_points[label_mask==prop.label] = 0
        #else:
        #    points.append([prop.centroid[1], prop.centroid[0]])

    img_cross[img_points>0] = 0
    '''
    plt.subplot(1,2,1), plt.imshow(img_points, cmap="gray"), plt.title("Point Image")
    plt.subplot(1,2,2), plt.imshow(img_cross, cmap="gray"), plt.title("Cross Image")
    plt.show()
    '''
    return img_points, img_cross

def get_hor_len(point1, point2):
    # x1, y1 = point1
    # x2, y2 = point2
    # return math.sqrt((x2-x1)**2+(y2-y1)**2)
    return abs(point2[0]-point1[0])

def get_ver_len(point1, point2):
    # x1, y1 = point1
    # x2, y2 = point2
    # return math.sqrt((x2-x1)**2+(y2-y1)**2)
    return abs(point2[1]-point1[1])

def map_index(row, col, coordinate):
    if coordinate == 1:
        position = (row, col)
    elif coordinate == 2:
        position = (row, -col)
    elif coordinate == 3:
        position = (-row, -col)
    elif coordinate == 4:
        position = (-row, col)
    else:
        raise ValueError("Invalid coordinate index")

    return position

def register(point,
             row,
             col,
             coordinate,
             previous=None,
             hor_angle=0,
             ver_angle=0,
             hor_len=0,
             ver_len=0):

    point_elem = {
        "row": row,
        "col": col,
        "coordinate": coordinate,
        "from": previous,
        "index": map_index(row, col, coordinate)
    }
        # "hor_angle": hor_angle,
        # "ver_angle": ver_angle,
        # "hor_len": hor_len,
        # "ver_len":ver_len
    # }

    index = (point[0], point[1])
    POINTS[index] = point_elem

def update_information(center,
                       point,
                       row,
                       col,
                       hor_angle,
                       ver_angle,
                       hor_len,
                       ver_len,
                       coordinate,
                       dir="horizontal"):
    """ Update the information for the next search_surround

    Args:
        center: center point
        point: reference point
        row: row index of the center point
        col: column index of the center point
        hor_len: horizontal length from the previous
        ver_len: vertical length from the previous

    Returns:
        row: row index
        col: column index
        hor_angle: updated horizontal angle
        ver_angle: updated vertical angle
        hor_len: updated horizontal length
        ver_len: updated vertical length

    Raises:
        ValueError

    """
    x0, y0 = center
    x1, y1 = point

    if dir == "horizontal":
        hor_len = get_hor_len(center, point)
        hor_angle = get_image_angle(center, point)

        if x1 > x0:
            if coordinate==1 or coordinate==4: col += 1
            else: col -= 1
        elif x1 < x0:
            if coordinate==1 or coordinate==4: col -= 1
            else: col += 1

    elif dir == "vertical":
        ver_len = get_ver_len(center, point)
        ver_angle = get_image_angle(center, point)

        if y1 > y0:
            if coordinate==3 or coordinate==4: row += 1
            else: row -= 1
        elif y1 < y0:
            if coordinate==3 or coordinate==4: row -= 1
            else: row += 1
    else:
        raise ValueError("Invalid direction value.")

    return row, col, hor_angle, ver_angle, hor_len, ver_len

def search_surround(input_points,
                    center,
                    row,
                    col,
                    hor_angle,
                    ver_angle,
                    hor_len,
                    ver_len,
                    coordinate,
                    max_angle_shift=10,
                    max_hor_ratio=1.5,
                    max_ver_ratio=1.5):

    if len(input_points) == 0 or center is None: return
    points = input_points.copy()
    points = sort_points(center, points)

    x0, y0 = center
    for i, pt in enumerate(points[:8]):
        x1, y1 = pt

        # Filter out the identical points
        if abs(x1-x0)<0.0001 and abs(y1-y0)<0.0001:
            continue

        # Calculate the angle shift
        cur_angle = get_image_angle(center, pt)
        hor_angle_shift = abs(cur_angle - hor_angle)
        ver_angle_shift = abs(cur_angle - ver_angle)

        if hor_angle_shift < max_angle_shift \
                and max(get_hor_len(center,pt),hor_len)/min(get_hor_len(center,pt),hor_len)<max_hor_ratio:
            if (pt[0], pt[1]) not in POINTS:
                nrow, ncol, nhor_angle, nver_angle, nhor_len, nver_len = update_information(center, pt, row, col,
                                        hor_angle, ver_angle, hor_len, ver_len, coordinate, dir="horizontal")
                register(pt, nrow, ncol, coordinate, (row, col))
                search_surround(points, pt, nrow, ncol, nhor_angle, nver_angle, nhor_len, nver_len, coordinate)

        elif ver_angle_shift < max_angle_shift \
                and max(get_ver_len(center,pt),ver_len)/min(get_ver_len(center,pt),ver_len)<max_ver_ratio:
            if (pt[0], pt[1]) not in POINTS:
                nrow, ncol, nhor_angle, nver_angle, nhor_len, nver_len = update_information(center, pt, row, col,
                                        hor_angle, ver_angle, hor_len, ver_len, coordinate, dir="vertical")
                register(pt, nrow, ncol, coordinate, (row, col))
                search_surround(points, pt, nrow, ncol, nhor_angle, nver_angle, nhor_len, nver_len, coordinate)
    return

def index_coordinate(img_points,
                     center,
                     hor_angle,
                     ver_angle,
                     img_cross_mask,
                     coordinate,
                     max_angle_shift=10,
                     max_hor_ratio=1.5,
                     max_ver_ratio=1.5,
                     start_factor=1.2):

    cur_points = img_points.copy()
    cur_points[img_cross_mask!=coordinate] = 0

    points = []
    label_mask = label(cur_points, connectivity = 2)
    properties = regionprops(label_mask)
    for prop in properties:
        points.append((prop.centroid[1], prop.centroid[0]))

    # 1. Get the closest point as the anchor
    points = sort_points(center, points)
    if len(points) == 0: return # Case when there is no point inside this coordinate

    anchor = points[0]
    register(anchor, row=1, col=1, coordinate=coordinate)

    # 2. Initialize the point grid size
    hor_anchor, ver_anchor = None, None

    if len(points) == 1: return # Case when there is only one point inside this coordinate
    points = sort_points(anchor, points[1:])

    for i, pt in enumerate(points):
        pt_angle = get_image_angle(anchor, pt)

        if abs(pt_angle-hor_angle) < max_angle_shift*start_factor and hor_anchor is None:
            hor_anchor = pt
            hor_angle = pt_angle # Update the horizontal angle
            hor_len = get_hor_len(hor_anchor, anchor)
            register(hor_anchor, row=1, col=2, coordinate=coordinate, previous=(0,0))

        elif abs(pt_angle-ver_angle) < max_angle_shift*start_factor and ver_anchor is None:
            ver_anchor = pt
            ver_angle = pt_angle # Update the vertical angle
            ver_len = get_ver_len(ver_anchor, anchor)
            register(ver_anchor, row=2, col=1, coordinate=coordinate, previous=(0,0))

        if hor_anchor is not None and ver_anchor is not None: break

    if hor_anchor is None and ver_anchor is None: return # Case when the horizontal and vertical anchors cannot be found

    # Case when there only exits one anchor point
    if hor_anchor is None: hor_len = ver_len
    if ver_anchor is None: ver_len = hor_len

    pts_for_hor = points
    pts_for_ver = points.copy()

    search_surround(points, hor_anchor, 1, 2, hor_angle, ver_angle, hor_len, ver_len,
                coordinate, max_angle_shift, max_hor_ratio, max_ver_ratio)
    search_surround(points, ver_anchor, 2, 1, hor_angle, ver_angle, hor_len, ver_len,
                    coordinate, max_angle_shift, max_hor_ratio, max_ver_ratio)

    # print(anchor, hor_anchor, ver_anchor)
    # plt.imshow(cur_points, cmap="gray"), plt.show()

def index_image(img,
                thresh=210,
                min_rad=15,
                max_rad=60,
                max_angle_shift=20,
                max_hor_ratio=1.5,
                max_ver_ratio=1.5,
                start_factor=1.2):

    img_points, img_cross = extract_image(img, thresh, min_rad, max_rad)
    center, hor_angle, ver_angle, img_cross_mask = get_cross(img_cross)

    if center is None:
        raise Exception("Could not find the cross inside the input image.")
    elif abs(ver_angle-hor_angle) < max_angle_shift*start_factor:
        raise Exception("The horizontal and vertical angles are too close")

    for coordinate in range(1,5):
        index_coordinate(img_points, center, hor_angle, ver_angle, img_cross_mask,
                coordinate, max_angle_shift, max_hor_ratio, max_ver_ratio, start_factor)

    # plt.subplot(1,2,1), plt.imshow(img_points, cmap="gray"), plt.title("Point Image")
    # plt.subplot(1,2,2), plt.imshow(img_cross, cmap="gray"), plt.title("Cross Image")
    # for elem in POINTS:
        # print(elem)
        # print(POINTS[elem])
        # print()
    # plt.imshow(img_points, cmap="gray"), plt.title("Points Image"), plt.show()

if __name__ == "__main__":
    img_file = "./test/sample_cross.png"
    img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
    start = time.time()
    index_image(img, thresh=210, min_rad=15, max_rad=60,)
    period = time.time() - start
    print("The running time is %s.", period)

    display_index(img,size=0.3, thickness=1)


# https://leetcode.com/problems/find-median-from-data-stream/description/

from queue import PriorityQueue

class MedianFinder:

    def __init__(self):
        self.que1 = PriorityQueue()
        self.que2 = PriorityQueue()

    def addNum(self, num: int) -> None:

        if self.que1.empty() or num < self.que1.queue[0][1]:
            self.que1.put([-num, num])
            if self.que1.qsize() > self.que2.qsize() + 1:
                _, num = self.que1.get()
                self.que2.put([num, num])
        else:
            self.que2.put([num, num])
            if self.que2.qsize() > self.que1.qsize():
                _, num = self.que2.get()
                self.que1.put([-num, num])

    def findMedian(self) -> float:

        if self.que1.qsize() > self.que2.qsize():
            return self.que1.queue[0][1]
        else:
            return (self.que1.queue[0][1] + self.que2.queue[0][1]) / 2

python/295. Find Median from Data Stream.py


import datetime
from decimal import Decimal
from rest_framework import serializers
from django.db.models import Sum
from django.db.models.functions import Coalesce
from ..models import Cliente, Conta, Fatura, TipoTransacao, Movimentacao
from ..constants import CREDITO, DEBITO, DEPOSITO

class FaturaVisualizacaoSerializer(serializers.ModelSerializer):
    desc_fatura = serializers.SerializerMethodField()

    class Meta:
        model = Fatura
        fields = (
            "fatura_id",
            "data_abertura",
            "data_vencimento",
            "valor",
            "status_pagamento",
            "desc_fatura",
        )

    def get_desc_fatura(self, instancia):
        desc = (
            Conta.objects.filter(conta=instancia.conta).first().status_fatura.descricao
        )
        return desc

class FaturaPagamentoSerializer(serializers.Serializer):
    fatura_id = serializers.IntegerField()
    conta = serializers.IntegerField()
    valor = serializers.DecimalField(max_digits=10, decimal_places=2)
    status_pagamento = serializers.BooleanField()
    data_vencimento = serializers.DateTimeField()

    class Meta:
        fields = (
            "fatura_id",
            "conta",
            "data_abertura",
            "data_vencimento",
            "valor",
            "status_pagamento",
        )

    def validate(self, instancia):
        print("instancia: ", instancia["status_pagamento"])

        if instancia["status_pagamento"] == True:
            raise serializers.ValidationError({"error": "FATURA_PAGA"})
        conta = Conta.objects.filter(conta=instancia["conta"]).first()
        if conta.status_fatura.status_id == 2:
            raise serializers.ValidationError({"error": "FATURA_ABERTA"})
        if instancia["valor"] == 0:
            raise serializers.ValidationError({"error": "FATURA_ZERADA"})
        if conta.saldo < instancia["valor"]:
            raise serializers.ValidationError({"error": "SALDO_INSUFICIENTE"})
        return instancia

    def create(self, instancia):
        conta = Conta.objects.filter(conta=instancia["conta"]).first()
        Movimentacao.objects.create(
            conta=conta.conta,
            descricao="Pagamento de fatura",
            valor=instancia["valor"],
            tipo_transacao_id=4,
        )
        fatura = Fatura.objects.filter(fatura_id=instancia["fatura_id"]).first()
        fatura.status_pagamento = True
        fatura.data_pagamento = datetime.datetime.now()
        fatura.save()
        conta.saldo -= instancia["valor"]
        conta.credito_utilizado = Decimal(0)
        conta.status_fatura_id = 2
        conta.vencimento_fatura = datetime.datetime.now() + datetime.timedelta(
            minutes=20
        )
        conta.save()
        Fatura.objects.create(
            conta=instancia["conta"],
            data_abertura=datetime.datetime.now(),
            data_vencimento=datetime.datetime.now() + datetime.timedelta(minutes=15),
        )
        return instancia


import numpy as np

R = np.matrix([ [0,0,0,0,1,0],
                [0,0,0,1,0,1],
                [0,0,100,1,0,0],
                [0,1,1,0,1,0],
                [1,0,0,1,0,0],
                [0,1,0,0,0,0]])
Q = np.matrix(np.zeros([6,6]))
gamma = 0.8

agent_s_state = 3

def possible_actions(state):
    current_state_row = R[state,]
    possible_act = np.where(current_state_row > 0)[1]
    return possible_act

def ActionChoice(available_actions_range):
    next_action = np.random.choice(available_actions_range, 1)
    return next_action

def reward(current_state, action, gamma):
    Max_State = np.where(Q[action,] == np.max(Q[action,]))[1]
    if Max_State.shape[0] > 1:
        Max_State = int(np.random.choice(Max_State, 1))
    else:
        Max_State = int(Max_State)
    MaxValue = Q[action, Max_State]
    Q[current_state, action] = R[current_state, action] + gamma * MaxValue

for i in range(100000):
    current_state = np.random.randint(0, int(Q.shape[0]))
    reward(current_state, ActionChoice(possible_actions(current_state)), gamma)
    if (i % 10000) == 0:
        print(Q)

norm_Q = Q/np.max(Q) * 100
print(norm_Q)


#!/usr/bin/env python3
##
## EPITECH PROJECT, 2021
## Zappy
## File description:
## AI server
##

import socket
import sys

class Socket:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connected = False

    def send_msg(self, messageg):
        if (self.connected == True):
            print("Sending...\n", message)
            self.socket.sendall(message.encode('ascii'))

    def receive_msg(self):
        if (self.connected == True):
            message = self.socket.recv(1024).decode('ascii')
            print("Receiving...\n", message)
            return (message)

    def connect(self):
        try:
            self.socket.connect(self.host, self.port)
            self.connected = True
            print("Connected to", host, "to", port)
        except Exception as e:
            print("Connection error: %s" % str(e), file=sys.stderr)
            sys.exit(84)

    def disconnect(self):
        try:
            self.socket.close()
            self.connected = False
            print("Disconnection")
        except Exception as e:
            print("Disconnection error: %s" % str(e), file=sys.stderr)
            sys.exit(84)


import cbsodata
import ssl
import streamlit as st
import geopandas as gpd
import pyproj
import pandas as pd
import json
import numpy as np

mapboxt = 'pk.eyJ1IjoiZG9taW5pcXVlLXZkdiIsImEiOiJjbDNrYm4wbHEwNWNwM2RyczR0a2UxeXRoIn0.e-S9dzdYyw7IW6_B-WMHVA'
ssl._create_default_https_context = ssl._create_unverified_context

def get_cbs_dummydata():
    # Zoek op welke data beschikbaar is
    metadata = pd.DataFrame(cbsodata.get_meta('83765NED', 'DataProperties'))

    # Download data en verwijder spaties uit regiocodes
    data = pd.DataFrame(cbsodata.get_data('83765NED', select = ['WijkenEnBuurten','Gemeentenaam_1',"Omgevingsadressendichtheid_105", 'Codering_3', 'AantalInwoners_5']))
    data['Codering_3'] = data['Codering_3'].str.strip()
    data = data.rename(columns={'Codering_3': 'REGIO_CODE'})

    return data

def get_data():
    aantal_inwoners_per_provincie = pd.read_csv("data/indicatoren/aantalinw_totaal_65+_2020_provincie.csv", sep=';').rename(
        columns={'Mannen en vrouwen (aantal)': 'aantal_inwoners', "Regio's": "REGIO_NAAM"}).assign(
        REGIO_NAAM=lambda d: [el.replace(" (PV)", "") for el in d.REGIO_NAAM]).drop(
        columns=['Perioden', 'Geboorteland'])
    totaal = aantal_inwoners_per_provincie.loc[lambda d: d.Leeftijd == 'Totaal'].rename(columns={'aantal_inwoners': 'aantal_inwoners_alle_leeftijd'}).drop(columns=["Leeftijd"])
    ouder = aantal_inwoners_per_provincie.loc[lambda d: d.Leeftijd == '65 jaar of ouder'].rename(columns={'aantal_inwoners': 'aantal_inwoners_65_plus'}).drop(columns=["Leeftijd"])
    aantal_inwoners_per_provincie = totaal.merge(ouder, on=['REGIO_NAAM'])

    arbeidsvolume_huisartsen_per_provincie = pd.read_csv("data/indicatoren/arbeidsvolume_huisartsen_gzc_provincie_2020.csv", sep=';').drop(
        columns=['Perioden', 'AZW branches']).rename(
        columns={'Arbeidsvolume  (x 1 000)': 'aantal_fte', "Regio's": "REGIO_NAAM"}).assign(REGIO_NAAM = lambda d: [el.replace(" (PV)", "") for el in d.REGIO_NAAM], aantal_fte = lambda d: [float(el.replace(',','.')) *1000 for el in d.aantal_fte])

    df_provincie = arbeidsvolume_huisartsen_per_provincie.merge(aantal_inwoners_per_provincie, on=['REGIO_NAAM'])
    df_provincie = df_provincie.assign(aantal_fte_per_1000 = lambda d: np.round(d.aantal_fte / d.aantal_inwoners_alle_leeftijd * 1000, 3))

    ervarengezondheid = (pd.read_csv("data/indicatoren/ervarengezondheid_65plus_2020_gemeente.csv", sep=';')
                         .drop(columns=['ID', 'Persoonskenmerken', 'Marges']).rename(columns={'RegioS': 'REGIO_CODE'})
                         .assign(ErvarenGezondheidGoedZeerGoed_6=lambda d: [el.strip() for el in d.ErvarenGezondheidGoedZeerGoed_6])
                         .assign(ErvarenGezondheidGoedZeerGoed_6 = lambda d: np.where(d.ErvarenGezondheidGoedZeerGoed_6 == '.', np.nan, d.ErvarenGezondheidGoedZeerGoed_6))
                         .assign(ErvarenGezondheidGoedZeerGoed_6 = lambda d: [float(el) for el in d.ErvarenGezondheidGoedZeerGoed_6])
                         )
    instroomleeftijd_wlz = pd.read_csv("data/indicatoren/instroomleeftijdwlz_gemeente_2020.csv", sep=';').drop(columns=['Geslacht']).rename(columns={"Regio's":"REGIO_NAAM","Wmo-cliënten; gebruik Wlz aantal (aantal)":"aantal_wlz_gebruikers" })

    totaal_aantal_wlz_gebruikers = instroomleeftijd_wlz.groupby('REGIO_NAAM').sum().assign(mediaan=lambda d: d.aantal_wlz_gebruikers/2)
    cumulative = instroomleeftijd_wlz.sort_values(["REGIO_NAAM", "Persoonskenmerken"]).set_index(
        ['REGIO_NAAM', 'Persoonskenmerken']).groupby('REGIO_NAAM').cumsum().reset_index()

    df1 = cumulative.loc[lambda d: d['Persoonskenmerken'] == 'Leeftijd: 45 tot 60 jaar'].drop(
        columns=['Persoonskenmerken']).rename(columns={'aantal_wlz_gebruikers': 'aantal_wlz_gebruikers_45_60'})
    df2 = cumulative.loc[lambda d: d['Persoonskenmerken'] == 'Leeftijd: 60 tot 75 jaar'].drop(
        columns=['Persoonskenmerken']).rename(columns={'aantal_wlz_gebruikers': 'aantal_wlz_gebruikers_60_75'})
    df3 = cumulative.loc[lambda d: d['Persoonskenmerken'] == 'Leeftijd: 75 tot 85 jaar'].drop(
        columns=['Persoonskenmerken']).rename(columns={'aantal_wlz_gebruikers': 'aantal_wlz_gebruikers_75_85'})
    df4 = cumulative.loc[lambda d: d['Persoonskenmerken'] == 'Leeftijd: 85 jaar of ouder'].drop(
        columns=['Persoonskenmerken']).rename(columns={'aantal_wlz_gebruikers': 'aantal_wlz_gebruikers_85_plus'})
    wlz_gebruikers_alles = df1.merge(df2, on='REGIO_NAAM').merge(df3, on="REGIO_NAAM").merge(df4, on="REGIO_NAAM").merge(totaal_aantal_wlz_gebruikers.reset_index().drop(columns=['aantal_wlz_gebruikers']), on='REGIO_NAAM')
    instroomleeftijd_wlz = wlz_gebruikers_alles.assign(mediaan_instroomleeftijd_wlz = lambda d: np.where(
        d.mediaan < d.aantal_wlz_gebruikers_45_60, 45 + np.round(d.mediaan / (d.aantal_wlz_gebruikers_45_60/15)),
        np.where(
            d.mediaan < d.aantal_wlz_gebruikers_60_75, 60 + np.round((d.mediaan-d.aantal_wlz_gebruikers_45_60) / (d.aantal_wlz_gebruikers_60_75/15)),
            np.where(
                d.mediaan < d.aantal_wlz_gebruikers_75_85, 75+np.round((d.mediaan - d.aantal_wlz_gebruikers_60_75) / (d.aantal_wlz_gebruikers_75_85 / 10)),
                85+np.round((d.mediaan - d.aantal_wlz_gebruikers_75_85) / (d.aantal_wlz_gebruikers_85_plus/10))
            )
        )
    ))[['REGIO_NAAM', 'mediaan_instroomleeftijd_wlz']]

    crosswalk = pd.read_csv("data/GM_naar_GGD_en_PV.csv", sep=';')
    crosswalk_gemeente = crosswalk[["Codes en namen van gemeenten/Code (code)", "Codes en namen van gemeenten/Naam (naam)"]]
    crosswalk_gemeente.columns = ['REGIO_CODE','REGIO_NAAM']
    crosswalk_gemeente = crosswalk_gemeente.assign(REGIO_CODE= lambda d: [el.strip() for el in d.REGIO_CODE],
                              REGIO_NAAM= lambda d: [el.strip() for el in d.REGIO_NAAM])
    crosswalk_provincie = crosswalk[['Lokaliseringen van gemeenten/Provincies/Code (code)',
                                     'Lokaliseringen van gemeenten/Provincies/Naam (naam)']]
    crosswalk_provincie=crosswalk_provincie.loc[~crosswalk_provincie.duplicated()]
    crosswalk_provincie.columns = ['REGIO_CODE', 'REGIO_NAAM']
    crosswalk_provincie = crosswalk_provincie.assign(REGIO_CODE=lambda d: [el.strip() for el in d.REGIO_CODE],
                                                   REGIO_NAAM=lambda d: [el.strip() for el in d.REGIO_NAAM])

    instroomleeftijd_wlz = instroomleeftijd_wlz.merge(crosswalk_gemeente, on='REGIO_NAAM') # hier vallen er een paar weg
    ervarengezondheid = ervarengezondheid.merge(crosswalk_gemeente, on='REGIO_CODE')
    df_gemeente = ervarengezondheid.merge(instroomleeftijd_wlz, on=["REGIO_CODE", "REGIO_NAAM"])
    df_gemeente = df_gemeente.rename(columns={'ErvarenGezondheidGoedZeerGoed_6': 'Ervaren gezondheid (Goed / zeer goed, %)',
                                                "mediaan_instroomleeftijd_wlz": "Instroomleeftijd wlz (mediaan)"})

    df_provincie = df_provincie.merge(crosswalk_provincie, on="REGIO_NAAM").assign(REGIO_NAAM=lambda d: np.where(d.REGIO_NAAM == "Fryslân", "Friesland", d.REGIO_NAAM))
    df_provincie = df_provincie.rename(columns={'aantal_fte_per_1000': 'Aantal huisartsen FTEs per 1000 inwoners', "aantal_inwoners_65_plus": "Aantal 65+'ers"})

    return df_gemeente, df_provincie

def get_cbs_polygons():
    # Haal de kaart met gemeentegrenzen op van PDOK
    geodata_url = 'https://geodata.nationaalgeoregister.nl/cbsgebiedsindelingen/wfs?request=GetFeature&service=WFS&version=1.1.0&outputFormat=application%2Fjson&typeName=cbsgebiedsindelingen:cbs_gemeente_2020_gegeneraliseerd'
    gemeentegrenzen = gpd.read_file(geodata_url)
    gemeentegrenzen = gemeentegrenzen.rename(columns={'statcode': 'REGIO_CODE', 'statnaam': 'REGIO_NAAM'})

    geodata_url_ggd ="https://geodata.nationaalgeoregister.nl/cbsgebiedsindelingen/wfs?request=GetFeature&service=WFS&version=1.1.0&outputFormat=application%2Fjson&typeName=cbsgebiedsindelingen:cbs_provincie_2020_gegeneraliseerd"
    provinciegrenzen = gpd.read_file(geodata_url_ggd)
    provinciegrenzen = provinciegrenzen.rename(columns={'statcode': 'REGIO_CODE', 'statnaam': 'REGIO_NAAM'})
    return gemeentegrenzen, provinciegrenzen

def merge_data_with_polygons(geometries, dataframe: pd.DataFrame, merge_col = "REGIO_NAAM"):
    # Koppel CBS-data aan geodata met regiocodes
    map_df = pd.merge(geometries,dataframe, on = merge_col)

    # maak kaart
    map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)

    return map_df

def create_geojson(data_and_geometries: pd.DataFrame, filepath=r'geojson.json', id="REGIO_NAAM"):

    # # write GeoJSON to filea
    data_and_geometries.to_file(filepath, driver="GeoJSON")

    with open(filepath) as geofile:
        j_file = json.load(geofile)

    # index geojson (st id value is equal to area code
    i = 1
    for feature in j_file["features"]:
        feature['id'] = j_file['features'][i - 1]['properties'][id]
        i += 1

    return j_file


#!/usr/bin/env python3

import tkinter as tk
from datetime import datetime
from PIL import Image
from PIL.ExifTags import TAGS
import sys
import os
import copy

interface = False

arguments = copy.deepcopy(sys.argv[1:])
if len(arguments) >= 1 and arguments[0] == '-i':
    interface = True
    arguments.pop(0)

if len(arguments) == 0 and not interface:
    print('Usage: ./scorpion.py [-i] FILE1 [FILE2 ...]')
    exit()

for arg in arguments:
    print('-' * 80)
    print(f'File: {arg}')
    print('-' * 20)

    # if sys.platform == 'linux':
    #     dt_c = datetime.fromtimestamp(
    #         os.stat(arg).st_birthtime).strftime('%Y-%m-%d %H:%M:%S')
    # else:

    dt_c = datetime.fromtimestamp(
        os.path.getctime(arg)).strftime('%Y-%m-%d %H:%M:%S')

    print(f'Creation date: {dt_c}')
    dt_m = datetime.fromtimestamp(
        os.path.getmtime(arg)).strftime('%Y-%m-%d %H:%M:%S')
    print(f'Modification date: {dt_m}')

    ### EXIF DATA ###

    img = Image.open(arg)
    exif_data = img.getexif()

    print('-' * 20)
    print('EXIF data:')
    print('-' * 20)

    if exif_data:
        for tag_id, value in exif_data.items():
            tag_name = TAGS.get(tag_id, tag_id)
            print(f"{tag_name}: {value}")
    else:
        print('No EXIF data.')

#### INTERFACE ####

class MetadataEditorApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Metadata Editor")
        self.geometry("400x300")

        self.file_path = tk.StringVar()
        self.exif_data = {}

        file_label = tk.Label(self, text="Image File:")
        file_label.pack()
        self.file_entry = tk.Entry(self, textvariable=self.file_path)
        self.file_entry.pack()

        load_button = tk.Button(self, text="Load Image",
                                command=self.load_image)
        load_button.pack()

        metadata_label = tk.Label(self, text="Metadata:")
        metadata_label.pack()
        self.metadata_listbox = tk.Listbox(self)
        self.metadata_listbox.pack()

        modify_button = tk.Button(
            self, text="Modify Metadata", command=self.modify_metadata)
        modify_button.pack()

        delete_button = tk.Button(
            self, text="Delete Metadata", command=self.delete_metadata)
        delete_button.pack()

    def load_image(self):
        image_path = self.file_path.get()
        try:
            image = Image.open(image_path)
            self.exif_data = image._getexif() or {}
            self.update_metadata_listbox()
        except IOError as e:
            self.show_error_dialog(f"Error loading image: {e}")

    def update_metadata_listbox(self):
        self.metadata_listbox.delete(0, tk.END)
        for tag_id, value in self.exif_data.items():
            tag_name = TAGS.get(tag_id, tag_id)
            self.metadata_listbox.insert(tk.END, f"{tag_name}: {value}")

    def modify_metadata(self):
        selection = self.metadata_listbox.curselection()
        if selection:
            tag_id = list(self.exif_data.keys())[selection[0]]
            new_value = self.ask_for_user_input("Enter new value:")
            self.exif_data[tag_id] = new_value
            self.update_metadata_listbox()

    def delete_metadata(self):
        selection = self.metadata_listbox.curselection()
        if selection:
            tag_id = list(self.exif_data.keys())[selection[0]]
            del self.exif_data[tag_id]
            self.update_metadata_listbox()

    def ask_for_user_input(self, prompt):
        dialog = UserInputDialog(self, prompt)
        self.wait_window(dialog)
        return dialog.user_input

    def show_error_dialog(self, message):
        dialog = ErrorDialog(self, message)
        self.wait_window(dialog)

class UserInputDialog(tk.Toplevel):
    def __init__(self, parent, prompt):
        super().__init__(parent)
        self.title("Input")
        self.geometry("300x100")

        self.user_input = tk.StringVar()

        prompt_label = tk.Label(self, text=prompt)
        prompt_label.pack()

        input_entry = tk.Entry(self, textvariable=self.user_input)
        input_entry.pack()

        confirm_button = tk.Button(self, text="OK", command=self.destroy)
        confirm_button.pack()

class ErrorDialog(tk.Toplevel):
    def __init__(self, parent, message):
        super().__init__(parent)
        self.title("Error")
        self.geometry("300x100")

        message_label = tk.Label(self, text=message)
        message_label.pack()

        ok_button = tk.Button(self, text="OK", command=self.destroy)
        ok_button.pack()

if interface:
    app = MetadataEditorApp()
    app.mainloop()


#Ejercico 1-Eliminar elemento repetidos
#Escriba un programa donde tengo una lista y que, a continuación elimine los elementos repetidos por último mostrar la lista.
#Manera 1
lista=[0,1,2,3,4,5,6,7,7,8,9,0,2,1,"Lunes", "Martes", "Miercoles", "Jueves", "Viernes","Lunes"]
conjunto=set(lista)
#Se convierte en lista nuevamente
lista=list(conjunto)
print(lista)

#Manera 2
lista1=[0,1,2,3,4,5,6,7,7,8,9,0,2,1]
lista1=list(set(lista1))
print(lista1)


from . import constants, utility
from ctypes import byref, c_char_p, c_double, c_int

class FluidSettings(object):
    ''' Represents the FluidSynth settings as defined in settings.h. A instance of this class
    can be used like an array aka like the fluidsettings_t object. This means you can get/set
    values using brackets (See example below).

    This class is inspired by the FluidSettings object from pyfluidsynth by MostAwesomeDude.

    Example:
    fluidsettings = FluidSettings( handle )
    fluidsettings['audio.driver'] = 'alsa'

    Constants:
    FLUID_NO_TYPE -- Settings type: Undefined type.
    FLUID_NUM_TYPE -- Settings type: Numeric (double).
    FLUID_INT_TYPE -- Settings type: Integer.
    FLUID_STR_TYPE -- Settings type: String.
    FLUID_SET_TYPE -- Settings type: Set of values.
    QUALITY_LOW -- Quality preset: Low.
    QUALITY_MED -- Quality preset: Medium.
    QUALITY_HIGH -- Quality preset: High.

    Member:
    handle -- The handle to the FluidSynth library. Should be FluidHandle but a raw handle will
               probably work, too (FluidHandle).
    quality -- The last quality preset used (string).
    settings -- The FluidSynth settings object (fluidsettings_t).
    '''

    (FLUID_NO_TYPE,
     FLUID_NUM_TYPE,
     FLUID_INT_TYPE,
     FLUID_STR_TYPE,
     FLUID_SET_TYPE) = range(-1, 4)

    QUALITY_LOW = 'low'
    QUALITY_MEDIUM = 'med'
    QUALITY_HIGH = 'high'

    def __init__( self, handle ):
        ''' Create new FluidSynth settings instance using the given handle. Default quality is set
        to medium. '''
        self.handle = handle
        self.settings = self.handle.new_fluid_settings()
        self.quality = self.QUALITY_MEDIUM

    @property
    def quality( self ):
        ''' Returns the last quality preset used. '''
        return self._quality

    @quality.setter
    def quality( self, quality ):
        ''' Sets the given quality preset. '''
        self._quality = quality

        if quality == self.QUALITY_LOW:
            self['synth.chorus.active'] = constants.FALSE
            self['synth.reverb.active'] = constants.FALSE
            self['synth.sample-rate'] = 22050

        elif quality == self.QUALITY_MEDIUM:
            self['synth.chorus.active'] = constants.FALSE
            self['synth.reverb.active'] = constants.TRUE
            self['synth.sample-rate'] = 44100

        elif quality == self.QUALITY_HIGH:
            self['synth.chorus.active'] = constants.TRUE
            self['synth.reverb.active'] = constants.TRUE
            self['synth.sample-rate'] = 44100

    def __del__( self ):
        ''' Deletes the FluidSynth settings object. '''
        self.handle.delete_fluid_settings( self.settings )

    def __getitem__( self, key ):
        ''' Returns the value of the given settings key. '''

        key = utility.fluidstring( key )
        key_type = self.handle.fluid_settings_get_type( self.settings, key )

        if key_type is self.FLUID_NUM_TYPE:
            val = c_double()
            func = self.handle.fluid_settings_getnum
        elif key_type is self.FLUID_INT_TYPE:
            val = c_int()
            func = self.handle.fluid_settings_getint
        elif key_type is self.FLUID_STR_TYPE:
            val = c_char_p()
            func = self.handle.fluid_settings_getstr
        else:
            raise KeyError( key )

        if func( self.settings, key, byref(val) ):
            return val.value
        else:
            raise KeyError( key )

    def __setitem__( self, key, value ):
        ''' Sets the value of the given settings key to value. '''

        key = utility.fluidstring( key )
        key_type = self.handle.fluid_settings_get_type( self.settings, key )

        if key_type is self.FLUID_STR_TYPE:
            value = utility.fluidstring( key )
            if not self.handle.fluid_settings_setstr( self.settings, key, value ):
                raise KeyError( key )

        else:
            # Coerce string value to integer before going further.
            value = self.__coerce_to_int( value )

            if key_type is self.FLUID_NUM_TYPE:
                if not self.handle.fluid_settings_setnum( self.settings, key, value ):
                    raise KeyError( key )

            elif key_type is self.FLUID_INT_TYPE:
                if not self.handle.fluid_settings_setint( self.settings, key, value ):
                    raise KeyError( key )

            else:
                raise KeyError( key )

    def __coerce_to_int( self, stringValue ):
        ''' Turn a string into an integer. '''
        try:
            return int( stringValue )
        except ValueError:
            return int( stringValue.lower() not in ('false', 'no', 'off') )


from random import choice
import hangman_words
import hangman_art
# word list
word_list = hangman_words.word_list

# pick a random word
picked_word = choice(word_list)
masked_word = list(len(picked_word) * '_')

life = 6

stages = hangman_art.stages
logo = hangman_art.logo

print(logo)
while '_' in masked_word:
    print(stages[life])
    print(''.join(masked_word))
    print('\n')
    letter = input("Guess a letter: ").lower()
    if letter in masked_word:
        print("You already used this letter.")
    elif letter in picked_word:
        for i in range(len(picked_word)):
            if letter == picked_word[i]:
                masked_word[i] = letter
        print("Your guess was right.")
    else:
        print('Your guess was wrong.')
        life -= 1
        if life == 0:
            break

if life != 0 or '_' not in masked_word:
    print(f"You guessed the whole word: {picked_word}!")
else:
    print("You lost.")


list_1 = [1]
list_2 = [1, 2]
list_3 = [1, 2, 3]
list_4 = [1, 2, 3, 4]

total_sum = 0

for num in [list_1, list_2, list_3, list_4]:
    total_sum += sum(num)

print("total:", total_sum)


import pandas as pd
import numpy as np

from sklearn.model_selection import train_test_split
train = pd.read_csv("E://ML//Kaggle Titanic//train.csv")
test = pd.read_csv("E://ML//Kaggle Titanic//test.csv")
train = train.drop(['Name','Cabin','Ticket'],axis = 1)
test = test.drop(['Name','Cabin','Ticket'],axis = 1)
train["Age"].fillna( method ='ffill', inplace = True)
#print(train.isna().sum())
test["Age"].fillna( method ='ffill', inplace = True)
train.dropna()
test.dropna()

from sklearn.preprocessing import StandardScaler
replacement = {
    'S': 0,
    'Q': 1,
    'C': 2
}

train['Embarked'] = train['Embarked'].apply(lambda x: replacement.get(x))
train['Embarked'] = StandardScaler().fit_transform(train['Embarked'].values.reshape(-1, 1))
test['Embarked'] = test['Embarked'].apply(lambda x: replacement.get(x))
test['Embarked'] = StandardScaler().fit_transform(test['Embarked'].values.reshape(-1, 1))

from sklearn import preprocessing
label_encoder = preprocessing.LabelEncoder()
onehot_encoder = preprocessing.OneHotEncoder()
train['Sex'] = label_encoder.fit_transform(train['Sex'])

#train['Embarked'] = onehot_encoder.fit_transform(train['Embarked'].value.reshape(1,-1))
train.dropna()
test['Sex'] = label_encoder.fit_transform(test['Sex'])
#test['Embarked'] = onehot_encoder.fit_transform(test['Embarked'])
test.dropna()
print(test.isna().sum())
y = train.iloc[:,1].values
train = train.drop(['Survived'],axis = 1)
x = train.iloc[:,:].values

from sklearn.linear_model import LogisticRegression
regressor = LogisticRegression()
regressor.fit(x, y)
pred = regressor.predict(test)

from sklearn.metrics import accuracy_score

#print(len(test['PassengerId'])," ",len(pred))
df = pd.DataFrame({'PassengerId':test['PassengerId'],'Survived':pred})
df.to_csv("E:\ML\Kaggle Titanic//Final_Pred_new1.csv", index = False)


import csv
import pandas as pd

# This file is used for extracting the column names
def extract_columns(csvfile='Dataset-Unicauca-Version2-87Atts.csv'):
    with open(csvfile) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter = ',')
        list_of_column_names = []

        for row in csv_reader:
            list_of_column_names.append(row)
            break

    return list_of_column_names

# find the maximum value in each row for sql types
def extract_max(csvfile='Dataset-Unicauca-Version2-87Atts.csv', column_name='Flow.Duration'):
    df = pd.read_csv(csvfile)
    p=df[column_name].max()
    print("max value: ", p)

def format_column_names(csvfile='Dataset-Unicauca-Version2-87Atts.csv'):
    df = pd.read_csv(csvfile)
    extracted_columns = extract_columns(csvfile)
    list_of_column_names = []
    for columns in extracted_columns:
        list_of_column_names = columns
    # we need a dictionary of column names with keys being the old column names and values being
    # the new ones
    columns = {}
    for column_name in list_of_column_names:
        columns[f'{column_name}'] = column_name.replace(".", "_")
    renamed_df = df.rename(columns=columns, inplace=True)
    renamed_df = df.to_csv('Dataset-Unicauca-Version2-87Atts.csv',index=None)
    extract_columns(csvfile)

csvfile = 'Dataset-Unicauca-Version2-87Atts.csv'
# column_name = 'Total.Length.of.Bwd.Packets'
# extract_max(csvfile, column_name)
# csvfile = 'Unicauca-dataset-April-June-2019-Network-flows.csv'
# extract_columns(csvfile)
format_column_names(csvfile)
print("operation Completed!")