#coding=utf-8

import random
import telegram
import datetime
import logging
from telegram.ext import Updater

#MachineGodBot - Telegram Bot designed for helping Warhammer 40.0000 players
updater = Updater(token='apitoken')
logger = logging.basicConfig(filename="DeusMechanicus.log", filemode="w", level= logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

dispatcher = updater.dispatcher

#Functions
def unknown(bot,update):
    logging.info('Received UNKNOWN command')
    unknown_Message = "La tua preghiera non è stata ascoltata!\n" \
                      "Digita /help per una lista di comandi"
    bot.sendMessage(chat_id=update.message.chat_id, text= unknown_Message, parse_mode=telegram.ParseMode.MARKDOWN)

def feedback(bot,update):
    logging.info('Received FEEDBACK command')
    feedback_Message = "Aiuta l'Omnissiah a crescere di popolarità.\n" \
                       "Clicka [qui](https://telegram.me/storebot?=MachineGodBot) e vota!"
    bot.sendMessage(chat_id=update.message.chat_id, text= feedback_Message, parse_mode=telegram.ParseMode.MARKDOWN)

def help(bot,update):
    logging.info('Received HELP command')
    help_message = "Utilizza i seguenti comandi: \n" \
                    "/help - per mostrare questa finestra di aiuto \n" \
                    "/roll *x* _y_ - tira *x*D6 e restituisce i valori superiori a _y_ \n" \
                    "/feedback - vota e aiutaci a crescere" \
                    # "/start - per avviare il bot \n" \
                    # "/stop - per arrestare il bot \n" \
                    # "/rule _regola_ - restituisce l'estratto della _regola_ dal manuale di 7a edizione"

    bot.sendMessage(chat_id=update.message.chat_id, text=help_message, parse_mode=telegram.ParseMode.MARKDOWN)

def roll(bot,update, args):
    if len(args) == 0:
        roll_message= "La sintassi del comando prevede /roll *x* _y_ \n" \
                      "dove *x* è il numero di d6 da lanciare e _y_ il valore da superare per il test\n" \
                      "_y_ può essere omesso se si desidera solo lanciare dei dadi"
        bot.sendMessage(chat_id=update.message.chat_id, text= roll_message, parse_mode=telegram.ParseMode.MARKDOWN)

    elif len(args)==1:
        results = "Effettuati i seguenti tiri: \n"
        die = int(args[0]) #Numero di dadi

        for x in range(die):
            dice = random.randint(1,6)
            results = results + telegram.Emoji.GAME_DIE + " " + str(dice) + "\n"

        bot.sendMessage(chat_id=update.message.chat_id, text= results, parse_mode=telegram.ParseMode.MARKDOWN)

    else:
        results = "Effettuati i seguenti tiri: \n"
        die = int(args[0]) #Numero di dadi
        value = int(args[1]) #Valore inserito dall'utente
        counter = 0 #Numero di dadi superiori all'input dell'utente

        for x in range(die):
            dice = random.randint(1,6)
            if dice >= value:
                counter=counter+1
            results = results + telegram.Emoji.GAME_DIE + " " + str(dice) + "\n"

        results = results + "\n"
        results = results + telegram.Emoji.DIRECT_HIT + " Prove superate: " + str(counter)

        bot.sendMessage(chat_id=update.message.chat_id, text= results, parse_mode=telegram.ParseMode.MARKDOWN)

def meme(bot, update):
    logging.info('Received MEME command')
    imgNumber = random.randint(1,11)
    img = "/home/pi/MachineGodBot/meme/" + str(imgNumber) + ".jpg"
    bot.sendPhoto(chat_id=update.message.chat_id, photo=open(img,'rb'))

def rule(bot,update,args):
    if len(args)==0:
        rule_message = "La sintassi del comando prevede /rule _regola_\n" \
                       "dove _regola_ è il nome della regola da cercare"
        bot.sendMessage(chat_id=update.message.chat_id, text=rule_message, parse_mode=telegram.ParseMode.MARKDOWN)
    else:
        rule_to_find= args[:]
        index = ''.join(rule_to_find)
        if index.lower() == "aduemani":
            rule_title= telegram.Emoji.BOOKS + " *A DUE MANI* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Un modello che combatte con quest'arma non riceve mai" \
                          " *+1* attacchi in mischia per il fatto che combatte con due armi da mischia"
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "abilepilota":
            rule_title= telegram.Emoji.BOOKS + " *ABILE PILOTA* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Un'unità che contiene almeno un modello con questa regola speciale supera automaticamente" \
                          "i test per i terreni pericolosi e riceve un modificatore di *+1* ai tiri copertura conferiti" \
                          "da Zigzagare (altri tiri copertura non vengono influenzati)"
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "accecare":
            rule_title= telegram.Emoji.BOOKS + " *ACCECARE* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Ogni unità colpita da uno o più armi o modelli con questa regola speciale deve effettura un test" \
                          "d'Iniziativa alla fine della fase in corso. Se lo supera non succede nulla: i guerrieri hanno distolto" \
                          "lo sguardo grazie ad un avvertimento. Se fallisce, i valori di *AC* e *AB* di tutti i modelli nell'unità" \
                          "sono ridotti ad *1* fino alla fine del loro prossimo turno." \
                          "Se l'unità attaccante colpisce se stessa, si suppone che sia preparata e supera il test automaticamente." \
                          "Qualsiasi modello privo della caratteristica di Iniziativa (ad esempio veicoli non Camminatori, edifici ecc.)" \
                          "non è influenzate da questa regola speciale."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "aggirare":
            rule_title= telegram.Emoji.BOOKS + " *AGGIRARE* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Durante lo schieramento i giocatori possono dichiarare che qualsiasi unità che contiene almeno un modello" \
                          "con questa regola speciale sta tentando di Aggirare il nemico. Ciò significa che compie una lunga manovra" \
                          "di accerchiamento per superare le linee di battaglia avversarie o assalirle da una direzione inaspettata." \
                          "Quando un'unità che Aggira arriva dalla Riserva, ma non dalle Riserve Provvisorie, il giocatore che la controlla" \
                          "tira un D6: con 1-2 l'unità arriva dal bordo del tavolo alla sinistra del tavolo del giocatore che la controlla;" \
                          "con 3-4 arriva da quello a destra; con 5-6 il giocatore sceglie se da quello a destra o a sinistra. I modelli" \
                          "arrivano sul tavolo come descritto per le altre Riserve. Se tale unità si schiera dentro un Trasporto Apposito," \
                          "può Aggirare assieme al proprio Trasporto"
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "altamanovrabilità":
            rule_title= telegram.Emoji.BOOKS + " *ALTA MANOVRABILITA'* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Un modello con questa regola speciale può compiere una rotazione sul posto addizionale di massimo 90° al termine" \
                          "del proprio movimento. Se usa questa rotazione addizionale, esso non può muoversi A tavoletta nella successiva fase" \
                          "di Tiro."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "ammantato":
            rule_title= telegram.Emoji.BOOKS + " *AMMANTATO* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Un'unità che contiene almeno un modello con questa regola speciale considera i propri tiri copertura di 2 punti migliore" \
                          "del normale. Ciò significa che un modello con la regola speciale Ammantato ha sempre un tiro copertura di almeno *5+*," \
                          "anche in terreno aperto. I modificatori ai tiri copertura per le regole Ammantato e Furtività sono cumulabili (fino ad" \
                          "un tiro copertura massimo di *2+*)."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "armadistruttrice":
            rule_title= telegram.Emoji.BOOKS + " *ARMA DISTRUTTRICE* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Se nel suo profilo un'arma ha D invece di un valore di Forza, essa è un'arma Distruttrice. Per risolvere l'attacco di tale arma" \
                          "tira per Colpire come faresti con un attacco normale. Se colpisce, tira sulla tabella seguente invece di tirare per Ferire o per" \
                          "la penetrazione della corazza. La maggior parte delle armi Distruttrici ha VP1 o VP2, quindi solutamente non si possono effettuare" \
                          "tiri armatura. I tiri copertura e invulnerabilità possono essere effettuati normalmente, a meno che non si ottenga un risultato" \
                          "Colpo devastante o Colpo fatale. Al fine di determinare se il colpo di un'arma Distruttrice ha la regola speciale Morte Immediata," \
                          "considera che abbia Fo10. Le Ferite o i danni ai Punti Scafo in eccesso inflitti da un colpo di un'arma Distruttrice non vengono assegnati" \
                          "agli altri modelli nell'unità, ma sono perduti."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)
            bot.sendPhoto(chat_id=update.message.chat_id, photo=open('omnissiah/armadistruttrice.jpg','rb'))

        elif index.lower() == "armaspecialistica":
            rule_title= telegram.Emoji.BOOKS + " *ARMA SPECIALISTICA* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Un modello che combatte con quest'arma non ottiene *+1* Attacchi se combatte con due armi, a meno che sia armato" \
                          "con due o più armi da Mischia con la regola speciale Arma Specialistica."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "attaccoradente":
            rule_title= telegram.Emoji.BOOKS + " *ATTACCO RADENTE* " + telegram.Emoji.BOOKS +"\n"
            rule_message= "Quando spara con armi d'Assalto, Pesanti, a Cadenza Rapida o a Raffica contro Artiglieria, Bestie, Moto," \
                          "Cavalleria, Fanteria, Creature Mostruore e veicoli che non sono Velivoli né Aeromobili, questo veicolo ha *+1* AB."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "atterrare":
            rule_title= telegram.Emoji.BOOKS + " *ATTERRARE* " + telegram.Emoji.BOOKS +"\n"
            rule_message="Ogni modello non veicolo che subisce una o più Ferite non salvate o supera uno o più tiri salvezza contro" \
                         "un attacco speciale Atterrare si muove come su un terreno accidentanto fino alla fine del suo turno successivo." \
                         "E' meglio indicare i modelli influenzati con monete o segnalini"
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "avvelenato":
            rule_title= telegram.Emoji.BOOKS + " *ATTERRARE* " + telegram.Emoji.BOOKS +"\n"
            rule_message="Se un modello possiede la regola speciale Avvelenato o se attacca con un'arma da Mischia che ha la regola speciale" \
                         "Avvelenato, in combattimento ferisce sempre con un risultato fisso (generalmente indicato fra parentesi)," \
                         "a meno che non ne sia necessario uno inferiore. Inoltre, se la Forza del portatore (o dell'arma Avvelenata)" \
                         "è superiore alla Resistenza della vittima, esso deve ripetere i tiri per Ferire falliti in combattimento." \
                         "Allo stesso modo, se un modello effettua un attacco da tiro con un'arma che la regola speciale Avvelenato," \
                         "ferisce sempre con un risultato fisso (generalmente indicato fra parentesi), a meno che non ne sia necessario" \
                         "uno inferiore. Se fra parentesi non viene indicato nessun numero, la regola è Avvelenato (*4+*)." \
                         "Se non viene diversamente specificato, le armi Avvelenate vengono sempre considerate avere *Fo1*. La regola" \
                         "speciale Avvelenato non ha effetto contro i veicoli."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "area":
            rule_title= telegram.Emoji.BOOKS + " *AREA* " + telegram.Emoji.BOOKS +"\n"
            rule_message=""
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

        elif index.lower() == "binata":
            rule_title= telegram.Emoji.BOOKS + " *BINATA* " + telegram.Emoji.BOOKS +"\n"
            rule_message="Per aumentare la precisione, queste armi sono collegate allo stesso sistema di puntamento." \
                         "Le armi Binate non sparano più di quelle normali, ma hanno maggiori probabilità di colpire. Se un'arma da tiro" \
                         "ha la regola speciale Binata, o viene descritta come Binata nella voce dell'equipaggiamento di un modello," \
                         "ripete tutti i tiri per Colpire falliti. \n" \
                         "\n" \
                         "*ARMI AD AREA BINATE\n" \
                         "Se il dado deviazione non ottiene un Colpito! con un'arma ad Area o ad Area Grande Binata, puoi scegliere" \
                         "di ripetere il tiro. In tal caso devi tirare di nuovo sia i 2d6 che il dado deviazione.\n" \
                         "\n" \
                         "*ARMI A SAGOMA BINATE\n" \
                         "Le armi a Sagoma Binate sparano come un'arma singola, ma devono ripetere i tiri per Ferire falliti e quelli" \
                         "per la penetrazione della corazza falliti."
            bot.sendMessage(chat_id=update.message.chat_id, text= rule_title + rule_message, parse_mode=telegram.ParseMode.MARKDOWN)

#Handlers
dispatcher.addUnknownTelegramCommandHandler(unknown)
#dispatcher.addTelegramCommandHandler('start',start)
#dispatcher.addTelegramCommandHandler('stop',stop)
dispatcher.addTelegramCommandHandler('help',help)
dispatcher.addTelegramCommandHandler('roll', roll)
dispatcher.addTelegramCommandHandler('meme', meme)
dispatcher.addTelegramCommandHandler('feedback',feedback)
#dispatcher.addTelegramCommandHandler('rule',rule)

#Bot polling
updater.start_polling()


from datetime import datetime
from Luta import *
from Jogador import *
from LutaDAO import *
from JogadorDAO import *

class Campeonato(object):

    def __init__(self, nome, inicio, quantidadeRounds, pontuacaoVitoria, pontuacaoEmpate, pontuacaoDerrota, pontuacaoPerfect, pontuacaoGreat, pontuacaoDoubleKO, pontuacaoRndGanho, pontuacaoTimeOut, pontuacaoRndPerdido, pontuacaoPerfectContra, pontuacaoGreatContra):

        self.nome = nome

        '''
        .date() retorna apenas ano-mes-dia
        .strptime() converte string para o estilo da data
        '''

        dataInicio = datetime.strptime(inicio, "%d/%m/%Y").date() # CONVERTO STRING PARA DATETIME. O .date() CONVERTE DATETIME PARA DATE

        self.inicio = dataInicio
        self.status = 'INICIADO'
        self.quantidadeRounds = quantidadeRounds
        self.vitoria = pontuacaoVitoria
        self.empate = pontuacaoEmpate
        self.derrota = pontuacaoDerrota
        self.perfect = pontuacaoPerfect
        self.great = pontuacaoGreat
        self.doubleKO = pontuacaoDoubleKO
        self.roundGanho = pontuacaoRndGanho
        self.timeOut = pontuacaoTimeOut
        self.roundPerdido = pontuacaoRndPerdido
        self.perfectContra = pontuacaoPerfectContra
        self.greatContra = pontuacaoGreatContra
        self.temRingOut = False
        self.ringOut = 0

    def adicionarRingOut(self, pontuacaoRingOut):
        self.temRingOut = True
        self.ringOut = pontuacaoRingOut

    def adicionarInformacoes(self, teraFase2, primeiroNaFinal,  quantosNaFase2, ultimoEliminado):
        self.teraFase2 = teraFase2
        self.primeiroNaFinal = primeiroNaFinal
        self.quantosNaFase2 = quantosNaFase2
        self.ultimoEliminado = ultimoEliminado

    def gerarRodadas(self, times):

        """
            @times:parameter

        Recebe como parâmetro uma tupla de times (1, 2, 3...) e o método converte-os para listas [1, 2, 3,...]
        para que gere as partidas no sistema de Round Robin

        """
        ListaDeLutas = []
        temp = []
        qtdTimes = len(times)
        #output = open("outputRodadas.txt", "w")

        if qtdTimes % 2 == 0:
            rodadas = qtdTimes - 1
            jogosPorRodada = int((len(times)/ 2))
        else:
            rodadas = qtdTimes
            times.append(0) #time falso
            jogosPorRodada = int((len(times)/ 2)) - 1

        if len(times) > 1:
            for i in range(1, rodadas + 1):
                if i > 1:
                    # AQUI SERÁ FEITA A MOVIMENTAÇÃO DOS TIMES NO SENTIDO HORÁRIO (ROUND ROBIN)
                    for positivo in range(1, len(times)):
                        temp.append(times[positivo])
                    times[1:] = []
                    fim = len(temp) - 1
                    qtdTemp = len(temp)
                    while len(temp) > 0:
                        if len(temp) == qtdTemp:
                            times.append(temp.pop(fim)) # O ultimo time é passado para a frente
                        else:
                            times.append(temp.pop(0)) # Os demais times avançam uma posição

                #print("\nRodada " + str(i))

                '''if i > 1:
                    output.write("\nRodada " + str(i) + "\n")
                else:
                    output.write("Rodada " + str(i) + "\n")'''

                if qtdTimes % 2 == 0:
                    for j in range(0, jogosPorRodada):
                        luta = Luta(jogador1=times[j], jogador2=times[-(j + 1)], rodada=i)
                        ListaDeLutas.append(luta)
                else:
                    j = 0
                    while j <= jogosPorRodada:
                        if times[j] != 0 and times[-(j + 1)] != 0:
                            luta = Luta(jogador1=times[j], jogador2=times[-(j + 1)], rodada=i)
                            ListaDeLutas.append(luta)
                        j += 1

        return ListaDeLutas

    def acabarLuta(self, Luta):

        """

        Este método faz o processamento de uma luta através do resultado informado (atributo da classe Luta); computa a pontuação conquistada pelos
        jogadores na partida e atualiza o status do objeto da classe Luta para "Finalizada"

        :param Luta: Recebe o objeto da classe Luta como parâmetro
        :return:
        """

        roundP1 = 0
        roundP2 = 0

        # PROCESSANDO OS ROUNDS
        for index in range(len(Luta.resultadoJogador1)):
            if roundP1 == self.quantidadeRounds: #casos de digitar VVV x DDD numa luta de 2 rounds
                break
            if Luta.resultadoJogador1[index] == 'P':
                Luta.jogador1.incrementarPerfect()
                roundP1 += 1
                Luta.jogador2.incrementarPerfectContra()
                #Luta.jogador2.incrementarRoundPerdido()
            elif Luta.resultadoJogador1[index] == 'G':
                Luta.jogador1.incrementarGreats()
                roundP1 += 1
                Luta.jogador2.incrementarGreatsContra()
                #Luta.jogador2.incrementarRoundPerdido()
            elif Luta.resultadoJogador1[index] == 'K':
                Luta.jogador1.incrementarDoubleKO()
                Luta.jogador2.incrementarDoubleKO()
                roundP1 += 1
                roundP2 += 1
            elif Luta.resultadoJogador1[index] == 'V':
                Luta.jogador1.incrementarRoundsSimples()
                roundP1 += 1
                Luta.jogador2.incrementarRoundPerdido()
            elif Luta.resultadoJogador1[index] == 'T':
                Luta.jogador1.incrementarTimeOut()
                roundP1 += 1
                Luta.jogador2.incrementarRoundPerdido()
            elif Luta.resultadoJogador1[index] == 'R':
                Luta.jogador1.incrementarRingOut()
                roundP1 += 1
                Luta.jogador2.incrementarRoundPerdido()
            elif Luta.resultadoJogador1[index] == 'D':
                if roundP2 == self.quantidadeRounds or Luta.jogador1.derrota + Luta.jogador1.perfectsContra + Luta.jogador1.greatsContra == self.quantidadeRounds: #casos de digitar DDD x VVV numa luta de 2 rounds e computar 3 derrotas pro P1
                    break
                roundP2 += 1
                if Luta.resultadoJogador2[index] == 'P':
                    Luta.jogador2.incrementarPerfect()
                    Luta.jogador1.incrementarPerfectContra()
                elif Luta.resultadoJogador2[index] == 'G':
                    Luta.jogador2.incrementarGreats()
                    Luta.jogador1.incrementarGreatsContra()
                elif Luta.resultadoJogador2[index] == 'V':
                    Luta.jogador2.incrementarRoundsSimples()
                    Luta.jogador1.incrementarRoundPerdido()
                elif Luta.resultadoJogador2[index] == 'T':
                    Luta.jogador2.incrementarTimeOut()
                    Luta.jogador1.incrementarRoundPerdido()
                elif Luta.resultadoJogador2[index] == 'R':
                    Luta.jogador2.incrementarRingOut()
                    Luta.jogador1.incrementarRoundPerdido()

        # DEFINIR O VENCEDOR DA LUTA
        if roundP1 == self.quantidadeRounds:
            if roundP2 == roundP1: # 2 x 2 numa luta de 2 rounds
                Luta.jogador1.incrementarEmpate()
                Luta.jogador2.incrementarEmpate()
            else: # 2 x 0 ou 2 x 1  numa luta de 2 rounds
                Luta.jogador1.incrementarVitoria()
                Luta.jogador2.incrementarDerrota()
        elif roundP2 == self.quantidadeRounds: #1 x 2 numa luta de 2 rounds
            Luta.jogador2.incrementarVitoria()
            Luta.jogador1.incrementarDerrota()
        else: # 1 x 1 numa luta de 2 rounds.
            print("O resultado é inválido")
            return 0

        # CALCULAR A PONTUAÇÃO DA LUTA DOS JOGADORES
        Luta.jogador1.pontos = (self.vitoria * Luta.jogador1.vitoria) + (self.empate * Luta.jogador1.empate) + (self.perfect * Luta.jogador1.perfects) + (self.great * Luta.jogador1.greats) + (self.doubleKO * Luta.jogador1.doubleKO) + (self.roundGanho * Luta.jogador1.roundsimples) + (self.timeOut * Luta.jogador1.timeout) + (self.ringOut * Luta.jogador1.ringout) - (self.roundPerdido * Luta.jogador1.roundPerdido) - (self.perfectContra * Luta.jogador1.perfectsContra) - (self.greatContra * Luta.jogador1.greatsContra) - (self.derrota * Luta.jogador1.derrota)
        Luta.jogador2.pontos = (self.vitoria * Luta.jogador2.vitoria) + (self.empate * Luta.jogador2.empate) + (self.perfect * Luta.jogador2.perfects) + (self.great * Luta.jogador2.greats) + (self.doubleKO * Luta.jogador2.doubleKO) + (self.roundGanho * Luta.jogador2.roundsimples) + (self.timeOut * Luta.jogador2.timeout) + (self.ringOut * Luta.jogador2.ringout) - (self.roundPerdido * Luta.jogador2.roundPerdido) - (self.perfectContra * Luta.jogador2.perfectsContra) - (self.greatContra * Luta.jogador2.greatsContra) - (self.derrota * Luta.jogador2.derrota)
        Luta.jogador1.atualizarSaldoRounds()
        Luta.jogador2.atualizarSaldoRounds()

        # FINALIZAR LUTA
        Luta.finalizada = True;
        return 1

'''
if __name__ == "__main__":

    # SIMULAÇÃO DE UMA LUTA
    tekken = Campeonato("Teste2", "18/06/2017", 2, 3, 1, 0, 2.5, 2, 1.5, 1, 0.5, 0.5, 3, 0.25)
    heihachi = Jogador("Heihachi", "Japão")
    asuka = Jogador("Asuka", "Japão")
    partida = Luta(heihachi, asuka, 1)
    # teste 1 - resultado invalido: TESTE OK
    #partida.preencherResultadoLuta("VV", "DV")

    #teste 2 - resultado valido
    partida.preencherResultadoLuta("PDG", "DVD")
    tekken.acabarLuta(partida)'''


import colorsys
import numpy as np

def hsvConverter(color):

    # Function to convert regular HSV values to openCV HSV values

    h = color[0]
    s = color[1]
    v = color[2]

    h_new = round(h/2)
    s_new = round(s/100*255)
    v_new = round(v/100*255)

    return np.array([h_new, s_new, v_new], np.uint8)

def BGR_to_HSV(color):
    b = color[0]/255
    g = color[1]/255
    r = color[2]/255

    color = colorsys.rgb_to_hsv(r, g, b)
    color = (int(color[0]*179), int(color[1]*255), int(color[2]*255))

    return color

def RGB_to_BGR(color):
    r = color[0]
    g = color[1]
    b = color[2]

    return (b,g,r)


"""
#### 2개의 테스트 셋 중 1개만 정답처리 (나머지 1개는 TLE)

주소: https://codingcompetitions.withgoogle.com/codejam/round/0000000000051705/000000000008830b

내용
- 소수를 26개 알파벳 대문자와 1:1로 치환한 암호가 있다
  - 소수는 오름차순으로 알파벳과 매칭된다
    - a < b < c ... 란 이야기
  - 소수의 최대크기는 N이다
- 알파벳으로만 이루어진 문장은 다음 규칙으로 암호로 변환된다
  - 알파벳이 소수로 치환된다
  - n번째 알파벳 치환값*n+1번째 알파벳 치환값 을 계산한다
  - 위 결과값들을 리스트에 넣는다
    - [1번째*2번째, 2번째*3번째, 3번째*4번째, ...]
  - 문장은 최소 26글자이다 => 암호 리스트 길이는 최소 25
- 암호에서 원래 문자를 찾아내라

샘플
Input
2
103 31
217 1891 4819 2291 2987 3811 1739 2491 4717 445 65 1079 8383 5353 901 187 649 1003 697 3239 7663 291 123 779 1007 3551 1943 2117 1679 989 3053
10000 25
3292937 175597 18779 50429 375469 1651121 2102 3722 2376497 611683 489059 2328901 3150061 829981 421301 76409 38477 291931 730241 959821 1664197 3057407 4267589 4729181 5335543

Output
Case #1: CJQUIZKNOWBEVYOFDPFLUXALGORITHMS
Case #2: SUBDERMATOGLYPHICFJKNQVWXZ

풀이
- 먼저 가능한 모든 소수 리스트를 만들어서 저장해둠
  - 이부분이 2차 테스트셋에서 통과 안됨
  - 리스트 크기가 작아서 or TLE이깐 다른 문제일지도
- 맨 처음 암호에서 소수의 곱을 찾아낸다
- 처음에 찾은 소수의 곱 원소중 두번째 암호와 나누어 떨어지는 값을 2번째로, 다른 값을 1번째로 가지는 변환 리스트를 만든다
- 나머지 리스트를 순회하며 변환 리스트의 마지막 값과 나눈 몫을 계산해서 새로 변환 리스트에 넣는다
- 나타나는 값 중 새로운게 있으면 별도 set에 저장한다
- 혹시 이상한 결과가 나오면 다시 처음으로 돌아가 소수의 곱을 찾는다
  - 이부분이 조금 잘못된것 같긴 함
  - 원래는 이상한 결과가 나올 수 없음
- set에 있는 값들을 오름차순으로 정렬하여 알파벳과 매칭시킨다
- 변환 리스트를 알파벳으로 치환한다

실제 적용할 수 있는 부분
- 소수를 미리 생성해서 저장해놓고 사용하는 DP개념
- 여기서 나타나는 변환 과정 자체를 Hashing에 사용해도 무방할듯
  - 두 리스트를 비교할때 연속되는 두 값이 같은지만 비교하려면 이러면 정보가 뭉개지면서 해결될수 있을듯
  - 예시
    - [5, 1, 3, 6, 8] => [5, 3, 18, 48]
    - [1, 3, 8, 5, 3, 6] => [3, 24, 40, 15, 18]
    - 두군데가 같다는걸 확인 가능하면서 원래 정보는 확인 불가능
"""
def F(t, N, L, codeList, primeSet):
    if L<=0:
        print("Case #" + str(t+1) + ": ")
        return

    for val in range(2, N+1):
        isDone = False
        if codeList[0]%val == 0 and val in primeSet and int(codeList[0]/val) in primeSet and int(codeList[0]/val) <= N:
            val1 = val
            val2 = int(codeList[0]/val)
            isDone = True
            plists = []
            last = -1

            if codeList[1]%val1==0:
                plists.append(val2)
                plists.append(val1)
            else:
                plists.append(val1)
                plists.append(val2)
            plistsSet = set(plists)

            last = plists[-1]
            for i in range(1, len(codeList)):
                newPrime = int(codeList[i]/last)

                if not newPrime in plistsSet:
                    plistsSet.add(newPrime)

                plists.append(newPrime)
                last = newPrime

                if last<2 or last>N or len(plistsSet)>26:
                    isDone = False
                    break
            if isDone:
                break

    if not isDone:
      a = 5/0      # 디버깅을 위해 강제 에러 발생시키는 부분

    sortedList = sorted(list(plistsSet))
    keyMap = dict()

    for i, prime in enumerate(sortedList):
        keyMap[prime] = chr(ord("A") + i)

    resStr = ""

    for pItem in plists:
        resStr += keyMap[pItem]

    print("Case #" + str(t+1) + ": " + resStr)

primes = [2, 3]

for i in range(5, 10001, 2):
    isPrime = True
    for j in range(2, i):
        if i%j==0:
            isPrime = False
            break
    if isPrime:
      primes.append(i)

primeSet = set(primes)

T = int(input())

for t in range(T):
    N, L = input().split()
    N, L = int(N), int(L)
    codeList = [int(item) for item in input().split()]
    F(t, N, L, codeList, primeSet)


#Из исходного текстового файла (ip_address.txt) из раздела «Частоупотребимые
#маски» перенести в первый файл строки с нулевым четвертым октетом, а во второй
#– все остальные. Посчитать количество полученных строк в каждом файле.

import re
ip_address = open('ip_address.txt', encoding='UTF-8')
read = ip_address.read()
ip_address.close()

comm_mask = re.findall(r"255.\d*.\d*.\d+\n", read)
change = re.findall(r"255.\d*.\d*\.0", read)
others = set(comm_mask).difference(set(change))

first_file = open('first_file.txt', 'w')
first_file.write(f'Строки с ненулевыми четвёртым октетом: {change}\n'
                f'Количество строк: {len(change)}')
first_file .close()

second_file = open('second_file.txt', 'w')
second_file.write(f'Остальные строки: {others}\n'
             f'Количество строк: {len(others)}')
second_file.close()


import torch
from torch import nn
from tqdm import tqdm
from annoy import AnnoyIndex
import numpy as np
from typing import List, Set, Dict, Tuple, Optional

class PreTrainedEmbeddings(object):

    def __init__(self,
                 word_to_index:Dict[str, int],
                 word_vectors:List[np.ndarray]):

        self.word_to_index = word_to_index
        self.word_vectors = word_vectors
        self.index_to_words = {idx: word for word, idx in tqdm(self.word_to_index.items())}

        # Length of item vector that will be indexed
        self.index = AnnoyIndex(len(word_vectors[0]), metric='euclidean')
        print("Building Annoy Index...")
        for _, i in tqdm(self.word_to_index.items()):
            self.index.add_item(i, self.word_vectors[i])

        self.index.build(50) # 50 trees
        print("Finished!!")

    @classmethod
    def from_embedding_file(cls, embedding_file:str):
        """
        Instantiate from the embedding file

        Vector file should be of the format:
            word0 x0_0 x0_1 x0_2 x0_3 ... x0_N
            word1 x1_0 x1_1 x1_2 x1_3 ... x1_N

        Returns:
            Instance of the PretrainedEmbeddings
        """

        word_to_index = {}
        word_vectors = []

        print("Processing Embedding file ...")
        with open(embedding_file, 'r') as fp:
            for line in tqdm(fp.readlines()):

                line = line.split(" ")
                word = line[0]
                emb = np.array([float(x) for x in line[1:]])

                word_to_index[word] = len(word_to_index)
                word_vectors.append(emb)

        return cls(word_to_index, word_vectors)

    def get_embedding(self, word:str):
        """Given word, returns the embedding vector

        Return:
            an embedding (np.ndarray)
        """
        return self.word_vectors[self.word_to_index[word]]

    def get_closest_to_vectors(self, vector:np.ndarray, n:int=1):
        """Given a vector, return its n nearest neighbours

        Args:
            vector (np.ndarray): should match the size of the vectors in the Annoy index
            n (int): the number of neighbours to return

        Returns:
            [str, str, str, ,...]: Words, those are nearest to the given word
                                   The words are not ordered by distance

        """
        nn_indices = self.index.get_nns_by_vector(vector, n)

        ls_word = [self.index_to_words[neighbours_idx] for neighbours_idx in nn_indices]
        return ls_word

    def compute_and_print_analogy(self, word1, word2, word3):

        emb1 = self.get_embedding(word1)
        emb2 = self.get_embedding(word2)
        emb3 = self.get_embedding(word3)

        # let's compute the 4th words mebedding!!
        # idea: w2 - w1 = w4 - w3
        spatial_relationship = emb2 - emb1
        emb4 = emb3 + spatial_relationship

        # get closest neighbours
        closest_words = self.get_closest_to_vectors(emb4, 4)
        existing_words = set([word1, word2, word3])
        closest_words = [word for word in closest_words if word not in existing_words]

        if len(closest_words) == 0:
            print("Couldn't find closest words")
            print(f"{word1} : {word2} :: {word3} : ??")

        else:
            for w4 in closest_words:
                print(f"{word1} : {word2} :: {word3} : {w4}")


import sys

import matplotlib.pyplot as plt
import numpy as np
from mcerp import *

u_f_0 = 0
s_f_0 = sys.argv[1]
delta_f = sys.argv[2]

print(u_f_0, s_f_0, delta_f)

n = 500 # sample size for meta distribution
m = 200 # sample size for generated distribution
fs = np.random.normal(u_f_0, s_f_0, n*m)

generated_us_f = np.random.normal(u_f_0, delta_f, n)
gen_fs = []
for u_f in generated_us_f:
    gen_fs.extend(np.random.normal(u_f, s_f_0, m))

print(norm.fit(gen_fs))

B = 500
p, e = np.histogram(gen_fs, bins=B)
xs = e[:-1] + (e[1] - e[0])/2
center = (e[:-1] + e[1:])/2
width = 0.7 * (e[1] - e[0])
plt.figure()
plt.xlabel('f')
plt.ylabel('count')
plt.bar(center, p, align='center', width=width, color='blue', alpha=0.5)

B = 500
p, e = np.histogram(fs, bins=B)
xs = e[:-1] + (e[1] - e[0])/2
center = (e[:-1] + e[1:])/2
width = 0.7 * (e[1] - e[0])
plt.bar(center, p, align='center', width=width, color='red', alpha=0.2)

plt.show()


import io
from collections import Counter
from dataclasses import dataclass

import numpy as np

from py4vasp import data, exception, raw
from py4vasp._data import base, slice_, topology
from py4vasp._data.viewer3d import Viewer3d
from py4vasp._util import documentation, import_, reader

ase = import_.optional("ase")
ase_io = import_.optional("ase.io")
mdtraj = import_.optional("mdtraj")

@dataclass
class _Format:
    begin_table: str = ""
    column_separator: str = " "
    row_separator: str = "\n"
    end_table: str = ""
    newline: str = ""

    def comment_line(self, topology, step_string):
        return f"{topology}{step_string}{self.newline}"

    def scaling_factor(self, scale):
        return f"{self._element_to_string(scale)}{self.newline}".lstrip()

    def ion_list(self, topology):
        return f"{topology.to_POSCAR(self.newline)}{self.newline}"

    def coordinate_system(self):
        return f"Direct{self.newline}"

    def vectors_to_table(self, vectors):
        rows = (self._vector_to_row(vector) for vector in vectors)
        return f"{self.begin_table}{self.row_separator.join(rows)}{self.end_table}"

    def _vector_to_row(self, vector):
        elements = (self._element_to_string(element) for element in vector)
        return self.column_separator.join(elements)

    def _element_to_string(self, element):
        return f"{element:21.16f}"

@documentation.format(examples=slice_.examples("structure"))
class Structure(slice_.Mixin, base.Refinery):
    """The structure of the crystal for selected steps of the simulation.

    You can use this class to process structural information from the Vasp
    calculation. Typically you want to do this to inspect the converged structure
    after an ionic relaxation or to visualize the changes of the structure along
    the simulation.

    {examples}
    """

    A_to_nm = 0.1
    "Converting Å to nm used for mdtraj trajectories."

    @classmethod
    def from_POSCAR(cls, poscar, *, elements=None):
        """Generate a structure from string in POSCAR format."""
        poscar = _replace_or_set_elements(str(poscar), elements)
        poscar = io.StringIO(poscar)
        structure = ase_io.read(poscar, format="vasp")
        return cls.from_ase(structure)

    @classmethod
    def from_ase(cls, structure):
        """Generate a structure from the ase Atoms class."""
        structure = raw.Structure(
            topology=topology.raw_topology_from_ase(structure),
            cell=_cell_from_ase(structure),
            positions=structure.get_scaled_positions()[np.newaxis],
        )
        return cls.from_data(structure)

    @base.data_access
    def __str__(self):
        "Generate a string representing the final structure usable as a POSCAR file."
        return self._create_repr()

    @base.data_access
    def _repr_html_(self):
        format_ = _Format(
            begin_table="
\n
",
            column_separator="	",
            row_separator="
\n
",
            end_table="
\n
",
            newline="
",
        )
        return self._create_repr(format_)

    def _create_repr(self, format_=_Format()):
        step = self._get_last_step()
        lines = (
            format_.comment_line(self._topology(), self._step_string()),
            format_.scaling_factor(self._scale()),
            format_.vectors_to_table(self._raw_data.cell.lattice_vectors[step]),
            format_.ion_list(self._topology()),
            format_.coordinate_system(),
            format_.vectors_to_table(self._raw_data.positions[step]),
        )
        return "\n".join(lines)

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "to_dict"))
    def to_dict(self):
        """Read the structural information into a dictionary.

        Returns
        -------
        dict
            Contains the unit cell of the crystal, as well as the position of
            all the atoms in units of the lattice vectors and the elements of
            the atoms for all selected steps.

        {examples}
        """
        return {
            "lattice_vectors": self._lattice_vectors(),
            "positions": self._positions(),
            "elements": self._topology().elements(),
            "names": self._topology().names(),
        }

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "to_graph"))
    def plot(self, supercell=None):
        """Generate a 3d representation of the structure(s).

        Parameters
        ----------
        supercell : int or np.ndarray
            If present the structure is replicated the specified number of times
            along each direction.

        Returns
        -------
        Viewer3d
            Visualize the structure(s) as a 3d figure.

        {examples}
        """
        if self._is_slice:
            return self._viewer_from_trajectory()
        else:
            return self._viewer_from_structure(supercell)

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "to_ase"))
    def to_ase(self, supercell=None):
        """Convert the structure to an ase Atoms object.

        Parameters
        ----------
        supercell : int or np.ndarray
            If present the structure is replicated the specified number of times
            along each direction.

        Returns
        -------
        ase.Atoms
            Structural information for ase package.

        {examples}
        """
        if self._is_slice:
            message = (
                "Converting multiple structures to ASE trajectories is not implemented."
            )
            raise exception.NotImplemented(message)
        data = self.to_dict()
        structure = ase.Atoms(
            symbols=data["elements"],
            cell=data["lattice_vectors"],
            scaled_positions=data["positions"],
            pbc=True,
        )
        num_atoms_prim = len(structure)
        if supercell is not None:
            try:
                structure *= supercell
            except (TypeError, IndexError) as err:
                error_message = (
                    "Generating the supercell failed. Please make sure the requested "
                    "supercell is either an integer or a list of 3 integers."
                )
                raise exception.IncorrectUsage(error_message) from err
        num_atoms_super = len(structure)
        order = sorted(range(num_atoms_super), key=lambda n: n % num_atoms_prim)
        return structure[order]

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "to_mdtraj"))
    def to_mdtraj(self):
        """Convert the trajectory to mdtraj.Trajectory

        Returns
        -------
        mdtraj.Trajectory
            The mdtraj package offers many functionalities to analyze a MD
            trajectory. By converting the Vasp data to their format, we facilitate
            using all functions of that package.

        {examples}
        """
        if not self._is_slice:
            message = "Converting a single structure to mdtraj is not implemented."
            raise exception.NotImplemented(message)
        data = self.to_dict()
        xyz = data["positions"] @ data["lattice_vectors"] * self.A_to_nm
        trajectory = mdtraj.Trajectory(xyz, self._topology().to_mdtraj())
        trajectory.unitcell_vectors = data["lattice_vectors"] * Structure.A_to_nm
        return trajectory

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "to_POSCAR"))
    def to_POSCAR(self):
        """Convert the structure(s) to a POSCAR format

        Returns
        -------
        str or list[str]
            Returns the POSCAR of the current or all selected steps.

        {examples}
        """
        if not self._is_slice:
            return self._create_repr()
        else:
            message = "Converting multiple structures to a POSCAR is currently not implemented."
            raise exception.NotImplemented(message)

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "cartesian_positions"))
    def cartesian_positions(self):
        """Convert the positions from direct coordinates to cartesian ones.

        Returns
        -------
        np.ndarray
            Position of all atoms in cartesian coordinates in Å.

        {examples}
        """
        return self._positions() @ self._lattice_vectors()

    @base.data_access
    @documentation.format(examples=slice_.examples("structure", "volume"))
    def volume(self):
        """Return the volume of the unit cell for the selected steps.

        Returns
        -------
        float or np.ndarray
            The volume(s) of the selected step(s) in Å³.

        {examples}
        """
        return np.abs(np.linalg.det(self._lattice_vectors()))

    @base.data_access
    def number_atoms(self):
        """Return the total number of atoms in the structure."""
        if self._is_trajectory:
            return self._raw_data.positions.shape[1]
        else:
            return self._raw_data.positions.shape[0]

    @base.data_access
    def number_steps(self):
        """Return the number of structures in the trajectory."""
        if self._is_trajectory:
            range_ = range(len(self._raw_data.positions))
            return len(range_[self._slice])
        else:
            return 1

    def _topology(self):
        return data.Topology.from_data(self._raw_data.topology)

    def _lattice_vectors(self):
        lattice_vectors = _LatticeVectors(self._raw_data.cell.lattice_vectors)
        return self._scale() * lattice_vectors[self._get_steps()]

    def _scale(self):
        if not self._raw_data.cell.scale.is_none():
            return self._raw_data.cell.scale[()]
        else:
            return 1.0

    def _positions(self):
        return self._raw_data.positions[self._get_steps()]

    def _viewer_from_structure(self, supercell):
        viewer = Viewer3d.from_structure(self, supercell=supercell)
        viewer.show_cell()
        return viewer

    def _viewer_from_trajectory(self):
        viewer = Viewer3d.from_trajectory(self)
        viewer.show_cell()
        return viewer

    def _get_steps(self):
        return self._steps if self._is_trajectory else ()

    def _get_last_step(self):
        return self._last_step_in_slice if self._is_trajectory else ()

    def _step_string(self):
        if self._is_slice:
            range_ = range(len(self._raw_data.positions))[self._steps]
            return f" from step {range_.start + 1} to {range_.stop + 1}"
        elif self._steps == -1:
            return ""
        else:
            return f" (step {self._steps + 1})"

    def __getitem__(self, steps):
        if not self._is_trajectory:
            message = "The structure is not a Trajectory so accessing individual elements is not allowed."
            raise exception.IncorrectUsage(message)
        return super().__getitem__(steps)

    @property
    def _is_trajectory(self):
        return self._raw_data.positions.ndim == 3

class _LatticeVectors(reader.Reader):
    def error_message(self, key, err):
        key = np.array(key)
        steps = key if key.ndim == 0 else key[0]
        return (
            f"Error reading the lattice vectors. Please check if the steps "
            f"`{steps}` are properly formatted and within the boundaries. "
            "Additionally, you may consider the original error message:\n" + err.args[0]
        )

def _cell_from_ase(structure):
    lattice_vectors = np.array([structure.get_cell()])
    return raw.Cell(lattice_vectors, scale=raw.VaspData(1.0))

def _replace_or_set_elements(poscar, elements):
    line_with_elements = 5
    elements = "" if not elements else " ".join(elements)
    lines = poscar.split("\n")
    if _elements_not_in_poscar(lines[line_with_elements]):
        _raise_error_if_elements_not_set(elements)
        lines.insert(line_with_elements, elements)
    elif elements:
        lines[line_with_elements] = elements
    return "\n".join(lines)

def _elements_not_in_poscar(elements):
    elements = elements.split()
    return any(element.isdecimal() for element in elements)

def _raise_error_if_elements_not_set(elements):
    if not elements:
        message = """The POSCAR file does not specify the elements needed to create a
            Structure. Please pass `elements=[...]` to the `from_POSCAR` routine where
            ... are the elements in the same order as in the POSCAR."""
        raise exception.IncorrectUsage(message)

class Mixin:
    @property
    def _structure(self):
        return Structure.from_data(self._raw_data.structure)


from dqn.Agent import Agent
from dqn.PolicySearch import PolicySearch
from dqn.UnityWrapper import UnityWrapper
from dqn.arguments import get_args
from dqn.train import dqn

# main function
if __name__ == "__main__":

    # get arguments
    args = get_args()

    env_wrapper = UnityWrapper(args)
    state_size, action_size, _ = env_wrapper.get_env_info()
    policy_search = PolicySearch(args)

    # run agent once to get rating for initial configuration
    agent = Agent(args,
                  state_size=state_size,
                  action_size=action_size,
                  filename='')
    scores, scores_mean = dqn(agent, args, env_wrapper)

    for i in range(100):
        args = policy_search.generate_policy(args, rewards=[scores, scores_mean])

        agent = Agent(args,
                      state_size=state_size,
                      action_size=action_size,
                      filename='')
        scores, scores_mean = dqn(agent, args, env_wrapper)


'''
Created on 2015年5月27日

@author: fufei
'''

import http.client
from urllib.parse import unquote

httpClient = None
edInfo = [] #高管增减持信息
class ExecutiveDealInfo():
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.transactedDate = '' #交易日期
        self.stockCode = '' #股票代码
        self.stockName = '' #股票简称
        self.transactedUser = '' #变动人
        self.transactedVolume = '' #变动股数
        self.transactedPrice = 0 #成交价格
        self.turnover = 0 #变动金额
        self.reason = 0 #变动原因
        self.ratio = 0 #变动比例
        self.afterHoldings = '' #变动后持股数
        self.stockType = '' #持股种类
        self.executiveName = '' #董监高姓名
        self.position = ''#职务
        self.relation = ''#变动人与董监高关系
        self.stockCode2 = ''#带后缀".SH"和".SZ"的股票代码

    def toString(self):
        s = '[交易日期：{6}，股票代码：{0}，股票简称：{1}，变动股数：{2}，成交价格：{3}，变动金额：{4}元，变动比率:{5}]'
        s = s.format(self.stockCode,self.stockName,self.transactedVolume,self.transactedPrice,
                 self.turnover,self.ratio,self.transactedDate)
        return s

def fetchExecutiveDealInfo():
    try:
        httpClient = http.client.HTTPConnection("datainterface.eastmoney.com",80,timeout=60)
        httpClient.request('GET', '/EM_DataCenter/JS.aspx?type=GG&sty=GGMX&p=1&ps=2000&js=(x)')
        res = httpClient.getresponse()
#         print (res.status,res.reason)
        if res.status == 200:
            data = res.readall().decode(encoding="utf-8", errors="strict")
            l = data.split('"')
            l = [x for x in l if (x!='' and x!=',')]#去掉分割字符后生成的''和','
            #获取高管增减持信息
            for e in l:
                edi = ExecutiveDealInfo()
                l2 = e.split(",")
                edi.ratio = float(l2[0])
                edi.executiveName = l2[1]
                edi.stockCode = l2[2]
                if('002219'==edi.stockCode):
                    print(l2,l2[8])
                edi.transactedUser = l2[3]
                edi.stockType = l2[4]
                edi.transactedDate = l2[5]
                edi.transactedVolume = int(l2[6])
                edi.afterHoldings = l2[7]
                edi.transactedPrice = float(l2[8])
                edi.stockName = l2[9]
                edi.relation = l2[10]
                edi.reason = l2[12]
                edi.turnover = float(l2[13])
                edi.position = l2[14]
                edi.stockCode2 = l2[15]

                edInfo.append(edi)
    except Exception as err:
        print (err)
    finally:
        if httpClient:
            httpClient.close()
def findAddingAction(vol_,turnover_):
    for ed in edInfo:
       if(ed.transactedVolume>=vol_ and ed.turnover>=turnover_):
           print(ed.toString())
fetchExecutiveDealInfo()
findAddingAction(0,1000000)


import requests
import tablib
import logging
import time
from import_export import resources
from django.core.management.base import BaseCommand, CommandError
from shared.models import Course, Concentration
from phd.models import CurricularArea
from collections import OrderedDict
from django.db.models import Q #allows for complex queries
logger = logging.getLogger('administration/management/addconcentration.py')

#This command will add concentration each course
class Command(BaseCommand):

    def handle(self, *args, **options):

        #Concentration Course Lists --> hardcoded because it is unavailable through the API
        CE = ["ECE  538", "ECE  539", "ECE  552", "ECE  553", "ECE  554", "ECE  555",
        "ECE  556", "ECE  557", "ECE  558", "ECE  559", "ECE  561", "ECE  562", "ECE  611",
        "ECE  650", "ECE  651", "ECE  652"]
        MNS = ["ECE  511", "ECE  521", "ECE  526", "ECE  528", "ECE  529", "ECE  531",
        "ECE  532", "ECE  537", "ECE  539", "ECE  631"]
        PH = ["ECE  521", "ECE  523", "ECE  541", "ECE  545", "ECE  546", "ECE  722"]
        SW = ["ECE  571", "ECE  572", "ECE  573", "ECE  574", "ECE  575", "ECE  577",
        "ECE  578", "ECE  675", "ECE  676"]
        SPC = ["ECE  581", "ECE  582", "ECE  584", "ECE  585", "ECE  587", "ECE  681",
        "ECE  683", "ECE  686", "ECE  688"]
        #Concentration Objects
        Comp, Compbool = Concentration.objects.get_or_create(title = "Computer Engineering")
        Micro, Microbool = Concentration.objects.get_or_create(title = "Micro-Nano Systems")
        Photo, Photobool = Concentration.objects.get_or_create(title = "Photonics")
        Sense, Sensebool = Concentration.objects.get_or_create(title = "Sensing & Waves")
        Signal, Signalbool = Concentration.objects.get_or_create(title = "Signal Processing & Communications")

        MN, MNbool = CurricularArea.objects.get_or_create(title = "Microelectronics, Photonics, and Nanotechnology")
        PHY, PHYbool = CurricularArea.objects.get_or_create(title = "Engineering Physics")
        CENG, CENGbool = CurricularArea.objects.get_or_create(title = "Computer Engineering")
        SGN, SGNbool = CurricularArea.objects.get_or_create(title = "Signal & Information Processing")
        self.stdout.write(self.style.SUCCESS('CURRICULAR AREAS ADDED'))

        i = 0
        while i < len(CE):
            obj = Course.objects.get(Q(listing__iexact=CE[i]))
            obj.concentration.add(Comp)
            obj.save()
            i+=1

        self.stdout.write(self.style.SUCCESS('COMP ARCH CONCENTRATIONS ADDED'))

        i = 0
        while i < len(MNS):
            obj = Course.objects.get(Q(listing__iexact=MNS[i]))
            obj.concentration.add(Micro)
            obj.save()
            i+=1

        self.stdout.write(self.style.SUCCESS('MICRO NANO SYSTEMS CONCENTRATIONS ADDED'))

        i = 0
        while i < len(PH):
            obj = Course.objects.get(Q(listing__iexact=PH[i]))
            obj.concentration.add(Photo)
            obj.save()
            i+=1

        self.stdout.write(self.style.SUCCESS('PHOTONICS CONCENTRATIONS ADDED'))

        i = 0
        while i < len(SW):
            obj = Course.objects.get(Q(listing__iexact=SW[i]))
            obj.concentration.add(Sense)
            obj.save()
            i+=1

        self.stdout.write(self.style.SUCCESS('SENSING & WAVES CONCENTRATIONS ADDED'))

        i = 0
        while i < len(SPC):
            obj = Course.objects.get(Q(listing__iexact=SPC[i]))
            obj.concentration.add(Signal)
            obj.save()
            i+=1

        self.stdout.write(self.style.SUCCESS('SIGNAL PROCESSING CONCENTRATIONS ADDED'))

        self.stdout.write(self.style.SUCCESS('ALL CONCENTRATIONS ADDED'))


from pymongo import MongoClient
import pandas as pd
from .methods import insertion_sort

# connecting
cluster = MongoClient("mongodb://localhost:27017")
collection = cluster["quiz_analytics"]["quiz_analytics"]

def get_analytics_dataframes(caption, count):

    # getting data from db
    quiz_results = collection.find({"caption": caption}).sort("result")

    # setting dict structure and idx
    df_dict = {"count": [], "result": []}
    idx = 0

    for r in quiz_results:
        # checking if result array is empty or result is equal to existing result on idx
        if not df_dict["result"] or r["result"] == df_dict["result"][idx]:
            if r["result"] in df_dict["result"]:
                # increasing count
                df_dict["count"][idx] += 1
            else:
                # adding element
                df_dict["result"].append(r["result"])
                df_dict["count"].append(1)
        else:
            # incrementation and adding
            idx += 1
            df_dict["result"].append(r["result"])
            df_dict["count"].append(1)

    # sort by count
    insertion_sort(df_dict)

    # leave certain count of elements
    df_dict["count"] = df_dict["count"][0:count]
    df_dict["result"] = df_dict["result"][0:count]

    return pd.DataFrame(df_dict)

def insert_dict(data):
    collection.insert_one(data)


import tkinter as tk
from decimal import *
import RSAMfinder
from tkinter import ttk
import threading
import tkinter.scrolledtext as tkscrolled
from PIL import ImageTk, Image
import os,sys,random,time

class parameters_frame(object):
    def __init__(self,top,labels,specification):
        self.top = top
        self.v = None

        if specification == 'general':
            self.entries, self.error_labels, self.error, self.only_draw = makeform(self, self.top, labels)
        elif specification == 'patterns':
            self.entries = make_patterns_tab(self.top, ['p1','p2'])
        elif specification == 'figure_params':
            self.entries = make_figure_parameters(self,self.top)

    def work_task (self):
        return self.entries

    def callback_color(self,bool_var,entries):
        ent = list(filter(
            lambda x: x[0] == 'number_of_dup', entries))[0]

        if not bool_var.get():
            ent[1].delete(0, tk.END)
            ent[1].config(state='disabled')
        else:
            ent[1].config(state='normal')
            ent[1].delete(0, tk.END)
            ent[1].insert("end", '3')

    def callback_random_sol(self,bool_var,entry):
        if bool_var.get():
            entry.delete(0,tk.END)
            entry.config(state='disabled')
        else:
            entry.config(state='normal')

    def callback_only_draw(self,bool_var,entries,fields):
        temp_ents = list(filter(lambda x: x[0] not in ['track_solution','create_sigma','draw','random_sol',"Data Folder's name"
            ,'Color specification','only_draw'], entries))
        draw_check_butt = list(filter(lambda x: x[0] == 'draw', entries))[0]

        if bool_var.get():
            for entry in temp_ents:
                entry[1].delete(0,tk.END)
                entry[1].config(state='disabled')
            draw_check_butt[1].set('1')
        else:
            for entry in temp_ents:
                entry[1].config(state='normal')
                entry[1].delete(0,tk.END)
                entry[1].insert("end",fields[temp_ents.index(entry)+2][2])
            draw_check_butt[1].set('0')

def make_patterns_tab(root, patterns):
    entries = []
    t1 = tk.Frame(root)

    for p in patterns:
        row = tk.Frame(root)
        names = ['Event1','Event2','Event3','Colors','Distance']
        for name in names:
            lab = tk.Label(row, text=name,width=10)
            lab.grid(row=0, column=names.index(name)+1)
        lab = tk.Label(row, width=20, text=p)
        lab.grid(row=1,column=0)

        number_of_events = 3
        for i in range(0,number_of_events):
            string_var = tk.StringVar(t1)
            if i == 0 and patterns.index(p) == 0:
                string_var.set('S')
            else:
                string_var.set('None')
            EV = ['S','D','HT','None']
            EV = tk.OptionMenu(row, string_var, *EV)
            EV.grid(row=1, column=i+1)
            entries.append((p+'_event'+str(i),string_var))
        colors = ['red','black','None']
        string_var = tk.StringVar(t1)
        string_var.set('None')
        colors_op = tk.OptionMenu(row, string_var, *colors)
        colors_op.config(width=10)
        colors_op.grid(row=1, column=number_of_events+1)
        entries.append((p + '_colors', string_var))

        string_var = tk.BooleanVar(t1)
        c = tk.Checkbutton(row,variable=string_var)
        entries.append((p + '_dis', string_var))
        c.grid(row=1, column=number_of_events+2)
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
    return entries

def floatValidation(S):
    flag = True
    for s in S:
        if s not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']:
            flag = False
    if flag:
        return True
    t3.bell()  # .bell() plays that ding sound telling you there was invalid input
    return False

def make_figure_parameters(self,root):
    def intValidation(S):
        flag = True
        for s in S:
            if s not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
                flag = False
        if flag:
            return True
        t1.bell()  # .bell() plays that ding sound telling you there was invalid input
        return False

    bool_var = []
    c = []
    entries = []
    t1 = tk.Frame(root)
    names = [('color','Whether or not the figuer will be colored.\n'
                      'If a duplication event is part of p1 or'
                      'p2, duplications will also be colored.'),
             ('labels', 'Whether or not labels will appear in the figure.'),
             ('draw marked','Whether or not mark the interesting vertices in the figure.')]
    for name in names:
        lab = tk.Label(t1, text=name[0],width=10)
        ind = names.index(name)
        lab.grid(row=0, column=ind)
        bool_var.append(tk.BooleanVar(t1))
        c.append(tk.Checkbutton(t1, variable=bool_var[ind],command=lambda param=bool_var[ind]: self.callback_color(param,entries)))
        entries.append((name[0], bool_var[ind]))
        c[ind].grid(row=1, column=ind)
        c[ind].select()
        t1.pack(side=tk.TOP, padx=5, pady=5)
        CreateToolTip(lab, text=name[1])

    lab = tk.Label(t1, width=15, text='Minimal number\nof duplications\nto color.')
    intVal = (t1.register(intValidation), '%S')
    ent = tk.Entry(t1, validate='key', vcmd=intVal, width=5)
    ent.insert("end", '3')
    lab.grid(row=2, column=0)
    ent.grid(row=3, column=0)
    CreateToolTip(lab, text='This is the minumal number of duplication\n'
                            ' that will be colored if duplication event is\n'
                            'a part of p1' )
    entries.append(('number_of_dup', ent))
    t1.pack(side=tk.TOP, padx=0, pady=5)

    row = tk.Frame(root)
    CreateToolTip(row, text='Figure proportions')
    floatVal = (row.register(floatValidation), '%S')

    lab = tk.Label(row, width=2, text='x:')
    ent = tk.Entry(row, validate='key', vcmd=floatVal,width=5)
    ent.insert("end",'100')
    lab.grid(row=0, column=0)
    ent.grid(row=0, column=1)
    entries.append(('x', ent))
    row.pack(side=tk.TOP, padx=0, pady=5)

    lab = tk.Label(row, width=5, text='X')
    lab.grid(row=0, column=2)

    lab = tk.Label(row, width=2, text='y:')
    ent = tk.Entry(row, validate='key', vcmd=floatVal,width=5)
    ent.insert("end",'40')
    lab.grid(row=0, column=3)
    ent.grid(row=0, column=4)
    entries.append(('y', ent))
    row.pack(side=tk.TOP, padx=0, pady=5)

    row = tk.Frame(root)
    lab = tk.Label(row, text='Draw Species and Gene trees', width=25)
    lab.grid(row=0, column=0)
    draw_S_and_G = tk.BooleanVar(root)
    tk.Checkbutton(row, variable=draw_S_and_G).grid(row=1,column=0)
    entries.append(('draw_S_and_G', draw_S_and_G))
    row.pack(side=tk.TOP, padx=0, pady=5)
    return entries

def makeform(param_frame, root, fields):
    def intValidation(S):
        flag = True
        for s in S:
            if s not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
                flag = False
        if flag:
            return True
        t3.bell()  # .bell() plays that ding sound telling you there was invalid input
        return False

    error_labels = {}
    entries = []
    t3 = tk.Frame(root)
    intVal = (t3.register(intValidation), '%S')
    floatVal = (t3.register(floatValidation), '%S')

    row = tk.Frame(root)

    bool_var1 = tk.BooleanVar(row)
    butt = tk.Checkbutton(row, variable=bool_var1,
                          command=lambda: param_frame.callback_only_draw(bool_var1, entries, fields))
    butt.grid(row=0, column=1)
    lab = tk.Label(row, text='only draw', width=10)
    lab.grid(row=0, column=0)
    entries.append(('only_draw', bool_var1))
    row.pack(side=tk.TOP, padx=0, pady=5)

    for field in fields:
        if len(field) >= 3:
            row = tk.Frame(root)
            lab = tk.Label(row, width=20, text=field[0])
            if field[1] == 'float':
                ent = tk.Entry(row, validate='key',vcmd=floatVal,width=10)
            elif field[1] == 'int':
                ent = tk.Entry(row, validate='key', vcmd=intVal,width=10)
            else:
                ent = tk.Entry(row, validate='key',width=10)
            if field[2]:
                ent.insert("end",field[2])
            lab.grid(row=fields.index(field),column=0)
            ent.grid(row=fields.index(field),column=1)
            if field[0].find('cost') == -1:
                CreateToolTip(lab, text=field[3])
            error_labels.update({field[0]+' error':tk.StringVar()})
            lab = tk.Label(row, font=('Helvetica', 18, 'bold'), fg='red', width=5, textvariable=error_labels[field[0] + ' error'],justify=tk.LEFT)
            lab.grid(row=fields.index(field), column=3)
            entries.append((field[0], ent))
            row.pack(side=tk.TOP, padx=0, pady=5)

    row = tk.Frame(root,background='grey')
    lab = tk.Label(row, text='create sigma from FASTA file', width=30,background='grey')
    lab.grid(row=0, column=0)
    CreateToolTip(lab, text='If this option is selected, the user\n'
                            'should provide a FASTA file, called\n'
                            ' FASTA_(extention).txt, Otherwise,\n'
                            ' the user should proves Gene tree where\n'
                            ' the leaves are labeled with their\n'
                            ' corresponding Species, in the following\n'
                            ' format: (species name)g -> (species name).\n'
                            'For example, Ag->A.')
    create_sigma = tk.BooleanVar(t3)
    c = tk.Checkbutton(row, variable=create_sigma,background='black')
    c.grid(row=0, column=1)
    entries.append(('create_sigma', create_sigma))
    c.select()

    lab = tk.Label(row, text='Draw the gene tree', width=20,background='grey')
    lab.grid(row=0, column=2)
    draw = tk.BooleanVar(t3)
    c = tk.Checkbutton(row, variable=draw,background='black')
    c.grid(row=0, column=3)
    entries.append(('draw', draw))
    row.pack(side=tk.TOP, fill=tk.X, padx=0, pady=5)

    row = tk.Frame(root)
    lab = tk.Label(row, text='track solution number:', width=20)
    lab.grid(row=0, column=0)
    CreateToolTip(lab, text='If this option is selected, the program will\n'
                            'output the desired solution. One can select a\n'
                            'random solution, and the output will be one \n'
                            'random solution out od the k.')

    intVal = (t3.register(intValidation), '%S')
    track_sol_ent = tk.Entry(row, validate='key', vcmd=intVal, width=5)
    entries.append(('track_solution', track_sol_ent))
    track_sol_ent.grid(row=0, column=1)

    bool_var = tk.BooleanVar(row)
    butt = tk.Checkbutton(row, variable=bool_var, command=lambda: param_frame.callback_random_sol(bool_var,track_sol_ent))
    butt.grid(row=0, column= 3)
    lab = tk.Label(row, text='random solution', width=15)
    lab.grid(row=0, column=2)
    entries.append(('random_sol', bool_var))

    error = tk.StringVar()
    lab = tk.Label(row, font=('Helvetica', 11, 'bold'), fg='red', width=20,
                   textvariable=error, justify=tk.LEFT)
    lab.grid(row=0, column=4)

    row.pack()
    return entries, error_labels, error, bool_var1

class Main_Frame(object):
    def __init__(self, top=None):
        self.top = top
        img = ImageTk.PhotoImage(Image.open("logo.jpg"))
        panel = tk.Label(root, image=img)
        panel.pack(side="top", fill="both", expand="yes")

        parameter_lables = [["Data Folder's name", 'string', '',
                             "This is the folder's name under /data/"],
                            ['Color specification', 'string', '',
                             'This is the extension of the file colors_(extension).txt'],
                            ['k', 'int', '10','Value of k for the k-best hypergraph'],
                            ['Threshold Edges\nin Subtree', 'float', '0.1','The minimal number of edges in subtrees that\n'
                                                                           'will considered when looking for top scoring vertices\n'
                                                                           'within the gene tree.'],
                            ['HT event cost', 'float', '1'], ['Duplication event cost', 'float', '1'],['Speciation event cost', 'float', '0'], ['Loss event cost', 'float', '1'],
                            ['Gamma', 'float', '1','A parameter related to the probablity calculation.\n'
                                                   'As gamma grows lower, hypernodes with higher (worse)\n'
                                                   'scores are assigned probabilities much lower than'
                                                   ' hypernodes with lower scores.'],
                            ['p', 'float', '0.05',"Defins how much is 'mostly red' and 'mostly black'"],
                            ['Number of Vertices to find', 'int', 5,'How many Gene tree vertices will be reported.']]

        nb = Notebook(self.top,'RSAM-Finder')
        t1 = nb.add_tab('General Parameters', parameters_frame, parameter_lables,'general')
        t2 = nb.add_tab('Pattern Definitions', parameters_frame,[],'patterns')
        t3 = nb.add_tab('Figure Parameters', parameters_frame, [], 'figure_params')

        self.b1 = tk.Button(top, text='Run',
                            command=lambda: self.bar_init(t1,t2,t3))
        self.b1.pack(side=tk.TOP, padx=5, pady=5)
        b2 = tk.Button(top, text='Quit', command=top.quit)
        b2.pack(side=tk.TOP, padx=5, pady=5)

        self.result = {'text': '', 'error': '', 'solution': ''}
        self.msg_error = None
        # run mainloop
        self.top.mainloop()

    def bar_init(self,t1,t2,t3):
        ent1 = t1.work_task()
        ent2 = t2.work_task()
        ent3 = t3.work_task()

        only_draw = t1.only_draw.get()
        for ent in ent1:
            if ent[0] not in ['track_solution','create_sigma','draw','random_sol','only_draw']:
                if not only_draw or (ent[0] == "Data Folder's name") or (ent[0] == 'Color specification'):
                    if ent1[ent1.index(ent)][1].get() == '':
                        t1.error_labels[ent[0]+' error'].set('*')
                        return
                else:
                    t1.error_labels[ent[0] + ' error'].set('')
        self.window = tk.Toplevel(root)
        msg = tk.Message(self.window, text='RSAM-finder in progress...')
        msg.grid(row=0, column=0)
        self.load_bar = ttk.Progressbar(self.window)
        self.load_bar.grid(row=1, column=0)
        # first layer of isolation, note var being passed along to the self.start_bar function
        # target is the function being started on a new thread, so the "bar handler" thread
        self.start_bar_thread = threading.Thread(target=self.start_bar, args=(ent1+ent2+ent3, t1))
        # start the bar handling thread
        self.start_bar_thread.start()

    def start_bar(self, ent, t1):
        # the load_bar needs to be configured for indeterminate amount of bouncing
        self.load_bar.config(mode='determinate', maximum=100, value=0)
        # 8 here is for speed of bounce
        self.load_bar.start(8)
        # start the work-intensive thread, again a var can be passed in here too if desired
        self.work_thread = threading.Thread(target=self.work_task, args=(ent, ['p1','p2'], t1))
        self.work_thread.start()
        # close the work thread
        self.work_thread.join()
        # stop the indeterminate bouncing
        self.load_bar.stop()
        # reconfigure the bar so it appears reset
        self.load_bar.config(value=0, maximum=0)
        self.window.destroy()
        if self.result['error'] != '':
            if self.msg_error:
                self.msg_error.destroy()
            self.msg_error = tkscrolled.ScrolledText(self.top, width=100, height=10)
            self.msg_error.insert(1.0, self.result['error'],'error')
            self.msg_error.tag_config('error',foreground='red')
            self.msg_error.pack()
            self.result['error'] = ''
            self.result['text'] = ''
            self.result['solution'] = ''
        elif self.result['text'] != '':
            msg = tkscrolled.ScrolledText(self.top, width=100, height=10)
            msg.insert(1.0, self.result['text'])
            if self.msg_error:
                self.msg_error.destroy()
            msg.pack()
            self.b1.destroy()
            b3 = tk.Button(self.top, text='Restart',command=lambda: os.execl(sys.executable, sys.executable, * sys.argv))
            b3.pack()

        if self.result['solution'] != '':
            solution_frame = tk.Toplevel()
            TKScrollTXT = tkscrolled.ScrolledText(solution_frame, width=80, height=50)
            TKScrollTXT.insert(1.0, self.result['solution'])
            TKScrollTXT.pack(side=tk.LEFT)
        os.system("say 'התוכנית הסתיימה'")

    def work_task(self, entries, patterns, t1):
        p1_EV = []
        p2_EV = []
        for e in entries:
            if e[1]:
                for p in patterns:
                    if e[0].find(p) != -1:
                        if e[0][3:].find('event') != -1:
                            eval(p + '_EV').append(e[1].get())
                        if e[0][3:].find('colors') != -1:
                            exec("%s = '%s'" % (p+'_color',e[1].get()),locals(),globals())
                        if e[0][3:].find('dis') != -1:
                            exec("%s = '%s'" % (p + '_dis', e[1].get()), locals(), globals())
        p1 = (p1_EV, p1_color, p1_dis)
        if p2_EV != ['None','None','None']:
            p2 = (p2_EV, p2_color, p2_dis)
        else:
            p2 = [None,None,None]
        vars = []
        for entry in entries:
            if entry[0].find('p1') == -1 and entry[0].find('p2') == -1:
                text = entry[1].get()
                vars.append(text)
        only_draw ,speciesTreespecification, color_ext, k, TH_edges, HT_cost, D_cost, S_cost, loss_cost,\
        gamma, p, number_of_planted_vertices, create_sigma, draw, track_solution, random_sol, color,\
        labels,draw_marked,number_of_dup, x, y, draw_S_and_G = vars

        if number_of_dup == '':
            number_of_dup = 0
        if track_solution == "":
            track_solution = False
        elif int(track_solution) > int(k):
            t1.error.set('must be lower than k')
            return
        if random_sol:
            track_solution = random.choice(range(0,int(k)))

        if t1.only_draw.get():
            k = TH_edges = HT_cost = D_cost = S_cost = loss_cost = gamma = p = number_of_planted_vertices = 0
            track_solution = 0
        RSAMfinder.main(speciesTreespecification, color_ext, int(k), Decimal(TH_edges), int(HT_cost), int(D_cost), int(S_cost),
                        int(loss_cost), Decimal(gamma), Decimal(p), int(number_of_planted_vertices), p1, p2, create_sigma,
                        track_solution, draw, color,labels,draw_marked,x,y, self.result, only_draw, draw_S_and_G, int(number_of_dup))

class Notebook:
    def __init__(self,top,title):
        self.root = top
        self.root.title(title)
        self.notebook = ttk.Notebook(self.root)

    def add_tab(self, title, func,labels,specification):
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame, text=title)
        tab = func(frame,labels,specification)
        self.notebook.pack()
        return tab

    def run(self):
        self.root.mainloop()

class ToolTip(object):
    def __init__(self, widget):
        self.widget = widget
        self.tipwindow = None
        self.id = None
        self.x = self.y = 0

    def showtip(self, text):
        time.sleep(2)
        self.text = text
        if self.tipwindow or not self.text:
            return
        x, y, cx, cy = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 57
        y = y + cy + self.widget.winfo_rooty() +27
        self.tipwindow = tw = tk.Toplevel(self.widget)
        tw.wm_overrideredirect(1)
        tw.wm_geometry("+%d+%d" % (x, y))
        label = tk.Label(tw, text=self.text, justify=tk.LEFT,
                      background="#ffffe0", relief=tk.SOLID, borderwidth=1,
                      font=("tahoma", "10", "normal"))
        label.pack(ipadx=1)

    def hidetip(self):
        tw = self.tipwindow
        self.tipwindow = None
        if tw:
            tw.destroy()

def CreateToolTip(widget, text):
    toolTip = ToolTip(widget)
    def enter(event):
        toolTip.showtip(text)
    def leave(event):
        toolTip.hidetip()
    widget.bind('<Enter>', enter)
    widget.bind('<Leave>', leave)

root = tk.Tk()
Main_Frame(root)


import tensorflow as tf
from tensorflow.nn import log_softmax
from tensorflow.linalg import set_diag, tensor_diag_part
from tensorflow.experimental.numpy import finfo
from tensorflow.math import divide_no_nan, reduce_mean, sqrt
from tensorflow.keras.losses import Loss, MeanSquaredError
from .utils import (
    combine_representations,
    calculate_similarity,
    generate_simclr_positive_indices
)

class NTXentLoss(Loss):
    '''
    Class for NT-Xent Loss
    input:
        1) temperature: temperature for NT-Xent Loss
    '''

    def __init__(self, temperature = 0.1):
        super(NTXentLoss, self).__init__()
        self.temperature = temperature

    def calculate_NTXentLoss(
        self,
        similarity_tensor: tf.Tensor,
        positive_indicies: tf.Tensor
    ):
        # shuffle columns axis by positive_indicies
        # each positive values will be placed in diagonal position
        similarity_tensor = tf.gather(similarity_tensor, indices=positive_indicies)
        positive_tensor = tensor_diag_part(similarity_tensor)  # (2 * batch_size, )
        result = reduce_mean(positive_tensor)

        return result

    def call(self, y_true, y_pred):
        '''
        calculate NT-Xent Loss
        input:
            1) y_true: 1st view tensor: (batch_size, # features * embebdding dim)
            2) y_pred: 2nd view tensor: (batch_size, # features * embebdding dim)
        output: NT-Xent loss
        '''
        # combine representation
        combined_representation = combine_representations(y_true, y_pred)

        # calculate cosine similarity
        similarity = calculate_similarity(combined_representation)

        # get positive pair index for each augmented sequence
        batch_size = y_true.shape[0]
        positive_indicies = generate_simclr_positive_indices(batch_size)

        # calculate NT-Xent loss
        similarity = divide_no_nan(similarity, tf.cast(self.temperature, dtype='float32'))
        similarity = set_diag(similarity, tf.fill(similarity.shape[0:-1], finfo('float32').min))
        # similarity = tf.cast(-log(softmax(similarity, axis=1)), dtype='float32') -> gradient returns nan value
        similarity = -log_softmax(similarity, axis=1)
        nt_xent_loss = self.calculate_NTXentLoss(similarity, positive_indicies)

        return tf.cast(nt_xent_loss, dtype='float32')

class AutoEncoderLoss(Loss):
    def __init__(self):
        '''Class for AutoEncoder Loss '''
        super(AutoEncoderLoss, self).__init__()
        self.mse_loss = MeanSquaredError(reduction='sum_over_batch_size')

    def call(self, y_true, y_pred):
        '''
        calculate NT-Xent Loss
        input:
            1) y_true: input tensor list for auto encoder [view 1, view 2]
                -> [(batch_size, # of features * embed_dim), (batch_size, # of features * embed_dim)]
            2) y_pred: output tensor list for auto encoder [view 1, view 2]
                -> [(batch_size, # of features * embed_dim), (batch_size, # of features * embed_dim)]
        output: Mean Squared Error
        '''
        first_view_mse_loss = self.mse_loss(y_true[0], y_pred[0])
        second_view_mse_loss = self.mse_loss(y_true[1], y_pred[1])
        return first_view_mse_loss + second_view_mse_loss

class RootMeanSquaredLoss(Loss):
    '''Class for Root Mean Sqaured Loss '''
    def __init__(self):
        super(RootMeanSquaredLoss, self).__init__()
        self.mse_loss = MeanSquaredError(reduction='sum_over_batch_size')

    def call(self, y_true, y_pred):
        '''
        calculate Root Mean Squared Error(RMSE)
        input:
            1) y_true: real rating tensor (batch size, )
            2) y_pred: predicted rating tensor (batch size, )
        output: Root Mean Squared Error
        '''
        mse_loss = self.mse_loss(y_true=y_true, y_pred=y_pred)
        return sqrt(mse_loss)


T = int(input())
dx = [-1,1,0,0]
dy = [0,0,-1,1]
from collections import deque
import math

def bfs(graph,y,x,n):
    cnt = 1
    dq = deque()
    dq.append([y,x])
    visited = [[0]*n for i in range(n)]
    while(dq):
        now = dq.popleft()
        visited[now[0]][now[1]] = 1
        for i in range(4):
            ny = now[0]+dy[i]
            nx = now[1]+dx[i]
            if(nx >=0 and ny>=0 and nx <n and ny <n and visited[ny][nx]==0):
                if(graph[ny][nx]=='#'):
                    dq.append([ny,nx])
                    visited[ny][nx]=1
                    cnt+=1

    return cnt

for t in range(1,T+1):
    n = int(input())
    graph = []
    wall_count = 0
    for i in range(n):
        graph.append(list(input()))

    input_data = [-1,-1]
    for i in range(n):
        for j in range(n):
            if graph[i][j]=='#':
                wall_count+=1
                input_data[0]=i
                input_data[1]=j
    if(wall_count==bfs(graph,input_data[0],input_data[1],n)):
        if(math.sqrt(wall_count)==int(math.sqrt(wall_count))):
            print("#{} {}".format(t,"yes"))
        else:
            print("#{} {}".format(t,"no"))
    else:
        print("#{} {}".format(t,"no"))


"""
CVE-bin-tool OutputEngine tests
"""
import unittest
import tempfile
import json
import csv
import sys

from cve_bin_tool.OutputEngine import OutputEngine

class TestOutputEngine(unittest.TestCase):
    """ Test the OutputEngine class functions """

    MOCK_OUTPUT = {
        "modulename0": {
            "1.0": {"CVE-1234-1234": "MEDIUM", "CVE-1234-9876": "LOW"},
            "2.8.6": {"CVE-1234-1111": "LOW"},
        },
        "modulename1": {"3.2.1.0": {"CVE-1234-5678": "HIGH"}},
    }
    FORMATTED_OUTPUT = [
        {
            "package": "modulename0",
            "version": "1.0",
            "cve_number": "CVE-1234-1234",
            "severity": "MEDIUM",
        },
        {
            "package": "modulename0",
            "version": "1.0",
            "cve_number": "CVE-1234-9876",
            "severity": "LOW",
        },
        {
            "package": "modulename0",
            "version": "2.8.6",
            "cve_number": "CVE-1234-1111",
            "severity": "LOW",
        },
        {
            "package": "modulename1",
            "version": "3.2.1.0",
            "cve_number": "CVE-1234-5678",
            "severity": "HIGH",
        },
    ]

    def setUp(self) -> None:
        self.output_engine = OutputEngine(modules=self.MOCK_OUTPUT)
        self.mock_file = tempfile.NamedTemporaryFile("w+")

    def tearDown(self) -> None:
        self.mock_file.close()

    def test_formatted_output(self):
        """ Test reformatting modules """
        self.assertEqual(self.output_engine.formatted_output, self.FORMATTED_OUTPUT)

    def test_output_json(self):
        """ Test formatting output as JSON """
        self.output_engine.output_json(self.mock_file)
        self.mock_file.seek(0)  # reset file position
        self.assertEqual(json.load(self.mock_file), self.FORMATTED_OUTPUT)

    def test_output_csv(self):
        """ Test formatting output as CSV """
        self.output_engine.output_csv(self.mock_file)
        self.mock_file.seek(0)  # reset file position
        reader = csv.DictReader(self.mock_file)
        self.assertEqual(list(reader), self.FORMATTED_OUTPUT)

    def test_output_console(self):
        """Test Formatting Output as console"""

        # list of mock modules having length greater than the current Respective Max Length
        mock_module_names = [
            "ABCDEFGHIJKLMNOPQRS",
            "ABCDEFGHIJKLMNOPQR",
            "ABCDEFGHIJKLMNOPQ",
            "ABCDEFGHIJKLMNOP",
            "ABCDEFGHIJKLMNO",
            "ABCDEFGHIJKLMN",
            "glibc",
            "I'm a different module",
        ]

        # generate output
        for name in mock_module_names:
            self.output_engine.write_console(
                name, "0.0.1", "CVE-2018-12381", "HIGH", self.mock_file
            )

        # expected output
        output_modules = """| ABCDEFGHIJKLMNO... | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| ABCDEFGHIJKLMNO... | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| ABCDEFGHIJKLMNO... | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| ABCDEFGHIJKLMNO... | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| ABCDEFGHIJKLMNO    | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| ABCDEFGHIJKLMN     | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| glibc              | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
| I'm a different... | 0.0.1     | CVE-2018-12381     | HIGH      |
+--------------------+-----------+--------------------+-----------+
"""
        self.mock_file.seek(0)  # reset file position
        self.assertEqual(output_modules, self.mock_file.read())


import math

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

"""
    网格布局
"""
class QDMGraphicsScene(QGraphicsScene):
    itemSelected = pyqtSignal()
    itemsDeselected = pyqtSignal()
    def __init__(self, scene, parent = None):
        super().__init__(parent)

        self.scene = scene

        # settings
        self.gridSize = 20
        self.gridSquares = 5

        self._color_background = QColor("#393939")
        self._color_light = QColor("#2f2f2f")
        self._color_dark = QColor("#292929")

        self._pen_light = QPen(self._color_light)
        self._pen_light.setWidth(1)
        self._pen_dark = QPen(self._color_dark)
        self._pen_dark.setWidth(2)

        # self.scene_width, self.scene_height = 64000, 64000

        self.setBackgroundBrush(self._color_background)

    def setGrScene(self, width, height):
        self.setSceneRect(-width//2, -height//2, width, height)

    # 渲染背景
    def drawBackground(self, painter: QPainter, rect: QRectF) -> None:
        super().drawBackground(painter, rect)

        # 创建网格
        left   = int(math.floor(rect.left()))   # -400
        right  = int(math.ceil(rect.right()))   # 400
        top    = int(math.floor(rect.top()))    # -300
        bottom = int(math.ceil(rect.bottom()))  #  300

        first_left = left - (left % self.gridSize)    #-400
        first_top  = top - (top % self.gridSize)      #-300

        # 计算所有网格
        # 不是100的整数倍的时候加入亮的, 反之加入暗的
        lines_light, lines_dark = [], []
        for x in range(first_left, right, self.gridSize):
            if (x % (self.gridSize*self.gridSquares) != 0):
                lines_light.append(QLine(x, top, x, bottom))
            else:
                lines_dark.append(QLine(x, top, x, bottom))

        for y in range(first_top, bottom, self.gridSize):
            if (y % (self.gridSize*self.gridSquares) != 0):
                lines_light.append(QLine(left, y, right, y))
            else:
                lines_dark.append(QLine(left, y, right, y))

        # draw the lines
        painter.setPen(self._pen_light)
        painter.drawLines(*lines_light)

        painter.setPen(self._pen_dark)
        painter.drawLines(*lines_dark)


import tensorflow as tf
import numpy as np
from scipy.interpolate import CubicSpline
from scipy.interpolate import interp1d

class GradCam:
    """
    A class to compute grad-CAM on 1-D input for Keras models.
    ...

    Attributes
    ----------
    model : tf.Keras.Model
        model on which compute grad-CAM.
    testset: np.array
        array of elements on which compute grad-CAM.

    """
    def __init__(self, testset, model):
        self.testset = testset
        self.model = model

    def make_gradcam_heatmap(self, conv_layer_name):
        """
        Compute heatmap for grad-CAM.
        :param conv_layer_name: str
            name of the convolutional layer on which compute grad-CAM.
        :return:
        """
        heatmaps = []
        grad_model = tf.keras.models.Model(
            [self.model.inputs], [self.model.get_layer(conv_layer_name).output, self.model.output]
        )
        for el in self.testset:
            el = np.expand_dims(el, 0)
            with tf.GradientTape() as tape:
                last_conv_layer_output, preds = grad_model(el)
                pred_index = tf.argmax(preds[0])
                class_channel = preds[:, pred_index]

            grads = tape.gradient(class_channel, last_conv_layer_output)

            pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))

            last_conv_layer_output = last_conv_layer_output[0]
            heatmap = last_conv_layer_output * pooled_grads
            heatmaps.append(heatmap.numpy())
        return np.array(heatmaps)

    def cubic_spline_interpolation(self, vector, v_size, input_size):
        """
        it applies cubic spline interpolation to obtain an output that has the same dimension of the input.
        :param vector: np.array
            vector to interpolate
        :param v_size: int
            dimension of the last convolutional layer flatted.
        :param input_size: int
            dimension of the input size.
        :return:
        """
        heatmap = np.squeeze(vector)
        size_feature_map = len(heatmap.flatten())
        feature_map_flat = np.squeeze(heatmap.flatten())
        feature_map_flat = np.expand_dims(feature_map_flat, 1)

        x = np.linspace(0, size_feature_map - 1, v_size)
        f = CubicSpline(x, feature_map_flat, bc_type='natural')
        x_wanted = np.linspace(0, size_feature_map - 1, input_size)
        return_vector = f(x_wanted)

        return_vector = np.where(return_vector > 0, return_vector, 0)
        return return_vector

    def linear_interpolation(self, vector, v_size, input_size):
        """
        it applies linear interpolation to obtain an output that has the same dimension of the input.
        :param vector: np.array
            vector to interpolate
        :param v_size: int
            dimension of the last convolutional layer flatted.
        :param input_size: int
            dimension of the input size.
        :return:
        """
        heatmap = np.squeeze(vector)
        size_feature_map = len(heatmap.flatten())
        feature_map_flat = np.squeeze(heatmap.flatten())
        feature_map_flat = np.expand_dims(feature_map_flat, 1)

        x = np.linspace(0, size_feature_map - 1, v_size)
        f = interp1d(x, feature_map_flat, kind='linear')
        x_wanted = np.linspace(0, size_feature_map - 1, input_size)
        return_vector = f(x_wanted)

        return_vector = np.where(return_vector > 0, return_vector, 0)
        return return_vector

    def matrix_interpolation(self, vector):
        """
        it applies matrix interpolation. A mean for each row is applied.
        :param vector: np.array
            vector to interpolate.
        :return:
        """
        return np.mean(vector, axis = 1)

    def normalize_vector(self, vector):
        """
        normalize vector between 0-1.
        :param vector: np.array
            vector to normalize.
        :return:
        """
        sum = vector.sum()
        return vector / sum


from torchvision.transforms import Compose, Resize, CenterCrop, RandomHorizontalFlip, RandomRotation, ColorJitter, Normalize,ToTensor

class Pixt_ImageTransform:
    def __init__(self):
        self.transform = Compose(
            [
                Resize((256, 256)),
                CenterCrop((224, 224)),
                RandomHorizontalFlip(0.5),
                RandomRotation(degrees=(-15,15)),
                ColorJitter(brightness=0.2,contrast=0.2,saturation=0.2,hue=0.1),
                ToTensor(),

            ]
        )

    def __call__(self, x):
        return self.transform(x)

class Pixt_ValidationTest_Transform:
    def __init__(self):
        self.transform=Compose(
            [
                Resize((256,256)),
                CenterCrop((224,224)),
                ToTensor(),

            ]
        )

    def __call__(self,x):
        return self.transform(x)


# -*- coding: utf-8 -*-
"""
Created on Sun Aug  1 12:34:17 2021

@author: Ahmet Kasım Erbay
"""
def delete_nth(order,max_e):
    if not order or max_e < 1:
        return []

    counted_order = { x:0 for x in order }
    new_order = []

    for item in order:
        if counted_order[item] < max_e:
            counted_order[item] += 1
            new_order.append(item)

    return new_order

seq = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]

liste = delete_nth(seq, 1)

frequencies = [[i,seq.count(i)] for i in liste]

for i,j in [[i,seq.count(i)] for i in liste]:
    if j%2 == 1:
        print(i)

#%%

import operator
from functools import reduce

def find_it(xs):
    return reduce(operator.xor, xs)

seq = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]

print(find_it(seq))

#%%
seq = [1, 1, 2, 2, 5, 2, 4, 4, -1, 2, 5]

def check_negative(seq):
    for i in seq:
        if i < 0:
            return True
    return False

def odd_index(seq):

    freq = [0]*(max(seq)+1)
    for i in seq:
        freq[i] += 1

    for i in freq:
        if i % 2 == 1:
            return freq.index(i)

if check_negative(seq):
    mini = -min(seq)
    seq = [i + mini for i in seq]
    result = odd_index(seq) - mini
else:
    result= odd_index(seq)

print(result)


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(l1, l2):

        values1 = []
        values2 = []
        values = []
        rest = None
        while l1 != None:
            value = l1.val
            l1 = l1.next
            values1.append(value)

        while l2 != None:
            value = l2.val
            l2 = l2.next
            values2.append(value)

        node = None

        if len(values1 > values2):
            val = values1
        else:
            val = values2

        for num in val:

            if rest != None:
                node = ListNode(val=rest)
            val_len = len(values)

            for i in range(0, val_len):
                i = i+1
                node = ListNode(val=values[val_len-i], next=node)

        return values1, values2, node

values = [2,4,3]
values1 = [5,6,4]

node = None
for i in values:
    node = ListNode(i, node)

node1 = None
for i in values1:
    node1 = ListNode(i, node1)

s = Solution.addTwoNumbers(node, node1)
print(s)


from  tkinter import *
class Restaurant(Frame):
    def __init__(self,master):
        super(Restaurant,self).__init__(master)
        self.grid()
        self.createwidget()

    def createwidget(self):
        self.lbl=Label(self,text="Please Enter Your Credentials Accurately")
        self.lbl=Label(self,text="Username")
        self.lbl.grid(row=1,column=0, sticky=W)
        self.pw_ent=Entry(self)
        self.pw_ent.grid(row=1,column=1,sticky=W)
        self.lbl2=Label(self,text="Password")
        self.lbl2.grid(row=2,column=0, sticky=W)
        self.pw_ent2=Entry(self)
        self.pw_ent2.grid(row=2,column=1,sticky=W)
        self.submit_bttn=Button(self,text="Submit",command=self.reveal) #command here simply triggers the event handler
        self.submit_bttn.grid(row=4,column=0, sticky=W)
        self.secret_txt=Text(self,width=25,height=5,wrap=WORD) #wrap WORD here simply means that once you get the end of the line ,
        #the next word you type goes to the next line
        self.secret_txt.grid(row=9,column=0,columnspan=2,sticky=W)

    def reveal(self):
        """Display message based on password"""
        contents=self.pw_ent.get() #this get() method simply gets the values from the pw_ent variable assigned to the Entry Widget

        if contents=="secret":
            message="Flight Ticket No: 1538438 \n Ticket Owner: James Okunde \n Ticket Price: $540"
        else:
            message="Invalid Credentials. Make sure your details are entered correctly"
        #now that I have the string that I want to show to the user , all I
        # all i need to do now is insert it into the Text Widget.

        self.secret_txt.delete(0.0,END)
        # this simply means that the delete method will delete anytext from  the position 0.0 till the end point
        # note: 0.0 means the delete method will delete any text from column 0 and row 0

        self.secret_txt.insert(0.0,message)
        #this method simply inserts the text assisnged to the "message" variable into the Text widget

root=Tk()
root.geometry=("400X400")
root.title("FlyAnywhere")
okay=Restaurant(root)
okay.mainloop()