#trama corta
    #tiempo h latitud / longitud O curso / velocidad A altitud B alturaBar C tempbar D tempeSHT11 E voltajebater
#trama larga IMU
    #tiempo h latitud / longitud O curso / velocidad A altitud B alturaBar C tempbar D tempeSHT11 E voltajebater
    #f ACCx G ACCy H ACCz I GIx J GIy K GIz L Mx M My N Mz
#trama larga gases
    #tiempo h latitud / longitud O curso / velocidad A altitud B alturaBar C tempbar D tempeSHT11 E voltajebater
    #F humedadDHT11 G NH3 H CO I NO2 J C3H8 K C4H10 L Ch4 M H2 N C2H50H O tempI2C P tempADC Q presionbar

import sys
import math
import serial
import time
import subprocess
import random
import requests
import string

global MatrizD, vectorTramas, cuentatrama, cuentadesconocida

#La variable nombreArchivoTramasLeer contiene las tramas que el programa gqrx guardo al decodificar el AFSK
#La variable nombreVectorTrayectoriaGuardar es donde se guardan los vectores de trayectoria calculados por el modelo
#La variable nombreArchivoSETLeerEscribir contiene las coordenadas iniciales de la estacion y de la gondola para setear el cero relativo

nombreArchivoTramasLeer = "prueba_datos.txt"
nombreVectorTrayectoriaGuardar = "vectorpruebaSimple3.txt"
nombreArchivoSETLeerEscribir = "SET.txt"

MatrizD = []
vectorAlturaBar = []
vectorAlturaGps = []
vectorAlturaBar_ext = []
vectorAlturaGps_ext = []
sumaAlturaBar = 0
sumaAlturaGps = 0
sumaVarianzaAlturaBar = 0
sumaVarianzaAlturaGps = 0
vectorTramas = ['/0/0/0']
cuentatrama = 0
cuentadesconocida = 0
cuentaFusion = 0
arduino = serial.Serial('/dev/ttyUSB0',9600)
time.sleep(2)

def leerTrama():
    try:
        cuentaParticion = 0
        archivo = open(nombreArchivoTramasLeer,"r")
        tramaNue = archivo.readlines()
        archivo.close()
        ultimalinea = len(tramaNue)-1
        returnedValues = str(tramaNue[ultimalinea]) #Retornar solo la ultima linea del archivo
        vectorTramas.append(returnedValues)
        if len(returnedValues) < 20: # Si la longitud de la trama es exageradamente corta reportar
            return 1
        if (vectorTramas[len(vectorTramas)-1] != vectorTramas[len(vectorTramas)-2]): #Si y solo si las tramas son diferentes retorna la trama
            return returnedValues
        else:
            return 0
    except Exception as e:
        print("****ERROR LEYENDO TRAMA*****")
        print(e)

def procesarTrama(lineas,set):
    global tiempo,latitud_geo,longitud_geo,altitudGps,curso,velocidad,alturaBar,tempeSHT11,voltajebater,tempeBar,presionbar,humedadDHT11
    try:
        returnedValues = lineas
        valores = returnedValues.split("/")
        if (len(valores) == 4):
            print(returnedValues)
            tramaIMU = False
            tramaGases = False
            for i in range(len(valores[3])):
                i = i + 1
                bit = valores[3][i-1]
                if bit == "f": #Si en la trama hay una f minuscula sera una trama IMU
                    tramaIMU = True
                if bit == "F":
                    tramaGases = True
            if tramaIMU == True:
                #trama larga IMU
                #tiempo h latitud / longitud O curso / velocidad A altitud B alturaBar C tempbar D tempeSHT11 E voltajebater
                #f ACCx G ACCy H ACCz I GIx J GIy K GIz L Mx M My N Mz
                print("trama IMU")
                for i in range(len(valores[3])):
                    i = i + 1
                    bit = valores[3][i-1]
                    if bit == "B": #Si se cumple se garantiza existencia de trama hasta "B"
                        tiempo = valores[1][0:6].strip()
                        latitud = valores[1][7:15].strip()
                        longitud = valores[2][0:9].strip()
                        curso = valores[2][10:].strip()
                        velocidad = valores[3].split("A")[0].strip()
                        altitudGps = valores[3].split("A")[1].split("B")[0].strip()
                        datosTransfor = transformarTrama(latitud,longitud) #Convierte las coordenadas a decimales
                        latitud_geo = datosTransfor[0]
                        longitud_geo = datosTransfor[1]
                    if bit == "C": #Si se cumple se garantiza existencia de trama hasta "C"
                        alturaBar = valores[3].split("B")[1].split("C")[0].strip()
                        vectorAlturaBar_ext.append(alturaBar)
                        vectorAlturaGps_ext.append(altitudGps)
                        print("tiempo: " + str(float(tiempo)))
                        print("latitud_geo: " + str(float(latitud_geo)))
                        print("longitud_geo: " + str(float(longitud_geo)))
                        print("altitud_Gps: " + str(float(altitudGps)))
                        print("altura_Bar: " + str(float(alturaBar)))
                        if len(vectorAlturaBar_ext) > 1:
                            tamaño = len(vectorAlturaBar_ext)
                            deltaAlturaBar = float(vectorAlturaBar_ext[tamaño-1])-float(vectorAlturaBar_ext[tamaño-2])
                            alturaBarBias = float(vectorAlturaGps_ext[tamaño-2]) + deltaAlturaBar
                            altitudFus= fusionar(altitudGps,alturaBarBias) #Fusiona la altura del GPS y Barometro en una sola medida mas precisa
                            print("altura_FUS: " + str(float(altitudFus)))
                        datoToSetOK = True
                        print("curso: " + str(float(curso)))
                        print("velocidad: " + str(float(velocidad)))
                    if bit == "D": #Si se cumple se garantiza existencia de trama hasta "D"
                        tempeBar =  valores[3].split("C")[1].split("D")[0].strip()
                        #print("temperaturaBar: " +  str(float(tempeBar)/100))
                    if bit == "E": #Si se cumple se garantiza existencia de trama hasta "E"
                        tempeSHT11 =  valores[3].split("D")[1].split("E")[0].strip()
                        #print("temperaturaSHT11: " +  str(float(tempeSHT11)/100))
                    if bit == "f": #Si se cumple se garantiza existencia de trama hasta "f"
                        voltajebater =  valores[3].split("E")[1].split("f")[0].strip()
                        #print("voltajebater: " + str(float(voltajebater)/1000))
                    if bit == "G": #Si se cumple se garantiza existencia de trama hasta "G"
                        ACCX =  valores[3].split("f")[1].split("G")[0].strip()
                        #print("ACCX: " + str(float(ACCX)*9.8/100))
                    if bit == "H": #Si se cumple se garantiza existencia de trama hasta "H"
                        ACCY =  valores[3].split("G")[1].split("H")[0].strip()
                        #print("ACCY: " + str(float(ACCY)*9.8/100))
                    if bit == "I": #Si se cumple se garantiza existencia de trama hasta "I"
                        ACCZ =  valores[3].split("H")[1].split("I")[0].strip()
                        #print("ACCZ: " + str(float(ACCZ)*9.8/100))
                    if bit == "J": #Si se cumple se garantiza existencia de trama hasta "J"
                        GIX =  valores[3].split("I")[1].split("J")[0].strip()
                        #print("GIX: " + GIX)
                    if bit == "K": #Si se cumple se garantiza existencia de trama hasta "K"
                        GIY =  valores[3].split("J")[1].split("K")[0].strip()
                        #print("GIY: " + GIY)
                    if bit == "L": #Si se cumple se garantiza existencia de trama hasta "L"
                        GIZ =  valores[3].split("K")[1].split("L")[0].strip()
                        #print("GIZ: " + GIZ)
                    if bit == "M": #Si se cumple se garantiza existencia de trama hasta "M"
                        MX =  valores[3].split("L")[1].split("M")[0].strip()
                        #print("MX: " + MX)
                    if bit == "N": #Si se cumple se garantiza existencia de trama hasta "N"
                        MY =  valores[3].split("M")[1].split("N")[0].strip()
                        MZ =  valores[3].split("N")[1].strip()
                        #print("MY: " + MY)
                        #print("MZ: " + MZ)
                        print("trama larga IMU completa")
            elif tramaGases == True:
                #trama larga gases
                #tiempo h latitud / longitud O curso / velocidad A altitud B alturaBar C tempbar D tempeSHT11 E voltajebater
                #F humedadDHT11 G NH3 H CO I NO2 J C3H8 K C4H10 L Ch4 M H2 N C2H50H O tempI2C P tempADC Q presionbar
                print("trama Gases")
                for i in range(len(valores[3])):
                    i = i + 1
                    bit = valores[3][i-1]
                    if bit == "B": #Si se cumple se garantiza existencia de trama hasta "B"
                        tiempo = valores[1][0:6].strip()
                        latitud = valores[1][7:15].strip()
                        longitud = valores[2][0:9].strip()
                        curso = valores[2][10:].strip()
                        velocidad = valores[3].split("A")[0].strip()
                        altitudGps = valores[3].split("A")[1].split("B")[0].strip()
                        datosTransfor = transformarTrama(latitud,longitud) #Convierte las coordenadas a decimales
                        latitud_geo = datosTransfor[0]
                        longitud_geo = datosTransfor[1]
                    if bit == "C": #Si se cumple se garantiza existencia de trama hasta "C"
                        alturaBar = valores[3].split("B")[1].split("C")[0].strip()
                        vectorAlturaBar_ext.append(alturaBar)
                        vectorAlturaGps_ext.append(altitudGps)
                        print("tiempo: " + str(float(tiempo)))
                        print("latitud_geo: " + str(float(latitud_geo)))
                        print("longitud_geo: " + str(float(longitud_geo)))
                        print("altitud_Gps: " + str(float(altitudGps)))
                        print("altura_Bar: " + str(float(alturaBar)))
                        if len(vectorAlturaBar_ext) > 1:
                            tamaño = len(vectorAlturaBar_ext)
                            deltaAlturaBar = float(vectorAlturaBar_ext[tamaño-1])-float(vectorAlturaBar_ext[tamaño-2])
                            alturaBarBias = float(vectorAlturaGps_ext[tamaño-2]) + deltaAlturaBar
                            altitudFus= fusionar(altitudGps,alturaBarBias) #Fusiona la altura del GPS y Barometro en una sola medida mas precisa
                            print("altura_FUS: " + str(float(altitudFus)))
                        datoToSetOK = True
                        print("curso: " + str(float(curso)))
                        print("velocidad: " + str(float(velocidad)))
                    if bit == "D": #Si se cumple se garantiza existencia de trama hasta "D"
                        tempeBar =  valores[3].split("C")[1].split("D")[0].strip()
                        #print("temperaturaBar: " +  str(float(tempeBar)/100))
                    if bit == "E": #Si se cumple se garantiza existencia de trama hasta "E"
                        tempeSHT11 =  valores[3].split("D")[1].split("E")[0].strip()
                        #print("temperaturaSHT11: " +  str(float(tempeSHT11)/100))
                    if bit == "F": #Si se cumple se garantiza existencia de trama hasta "F"
                        voltajebater =  valores[3].split("E")[1].split("F")[0].strip()
                        #print("voltajebater: " + str(float(voltajebater)/1000))
                    if bit == "G": #Si se cumple se garantiza existencia de trama hasta "G"
                        humedadDHT11 =  valores[3].split("F")[1].split("G")[0].strip()
                        #print("humedadDHT11: " + str(humedadDHT11))
                    if bit == "H": #Si se cumple se garantiza existencia de trama hasta "H"
                        NH3 =  valores[3].split("G")[1].split("H")[0].strip()
                        #print("NH3: " + NH3)
                    if bit == "I": #Si se cumple se garantiza existencia de trama hasta "I"
                        CO =  valores[3].split("H")[1].split("I")[0].strip()
                        #print("CO: " + CO)
                    if bit == "J": #Si se cumple se garantiza existencia de trama hasta "J"
                        NO2 =  valores[3].split("I")[1].split("J")[0].strip()
                        #print("NO2: " + NO2)
                    if bit == "K": #Si se cumple se garantiza existencia de trama hasta "K"
                        C3H8 = valores[3].split("J")[1].split("K")[0].strip()
                        #print("C3H8: " + C3H8)
                    if bit == "L": #Si se cumple se garantiza existencia de trama hasta "L"
                        C4H10 = valores[3].split("K")[1].split("L")[0].strip()
                        #print("C4H10: " + C4H10)
                    if bit == "M": #Si se cumple se garantiza existencia de trama hasta "M"
                        CH4 = valores[3].split("L")[1].split("M")[0].strip()
                        #print("CH4: " + CH4)
                    if bit == "N": #Si se cumple se garantiza existencia de trama hasta "N"
                        H2 =  valores[3].split("M")[1].split("N")[0].strip()
                        #print("H2: " + H2)
                    if bit == "O": #Si se cumple se garantiza existencia de trama hasta "O"
                        C2H50H =  valores[3].split("N")[1].split("O")[0].strip()
                        #print("C2H50H: " + C2H50H)
                    if bit == "P": #Si se cumple se garantiza existencia de trama hasta "P"
                        tempI2C =  valores[3].split("O")[1].split("P")[0].strip()
                        #print("tempI2C: " + tempI2C)
                    if bit == "Q": #Si se cumple se garantiza existencia de trama hasta "Q"
                        tempADC =  valores[3].split("P")[1].split("Q")[0].strip()
                        presionbar =  valores[3].split("Q")[1].strip()
                        #print("tempADC: " + tempADC)
                        #print("presionbar: " + presionbar)
                        #print("trama larga Gases completa")
            else:
                #trama corta
                #tiempo h latitud / longitud O curso / velocidad A altitud B alturaBar C tempbar D tempeSHT11 E voltajebater
                tramalarga = False
                for i in range(len(valores[3])):
                    i = i + 1
                    bit = valores[3][i-1]
                    if bit == "B": #Si se cumple se garantiza existencia de trama hasta "B"
                        tiempo = valores[1][0:6].strip()
                        latitud = valores[1][7:15].strip()
                        longitud = valores[2][0:9].strip()
                        curso = valores[2][10:].strip()
                        velocidad = valores[3].split("A")[0].strip()
                        altitudGps = valores[3].split("A")[1].split("B")[0].strip()
                        datosTransfor = transformarTrama(latitud,longitud) #Convierte las coordenadas a decimales
                        latitud_geo = datosTransfor[0]
                        longitud_geo = datosTransfor[1]
                    if bit == "C": #Si se cumple se garantiza existencia de trama hasta "C"
                        alturaBar = valores[3].split("B")[1].split("C")[0].strip()
                        vectorAlturaBar_ext.append(alturaBar)
                        vectorAlturaGps_ext.append(altitudGps)
                        print("tiempo: " + str(float(tiempo)))
                        print("latitud_geo: " + str(float(latitud_geo)))
                        print("longitud_geo: " + str(float(longitud_geo)))
                        print("altitud_Gps: " + str(float(altitudGps)))
                        print("altura_Bar: " + str(float(alturaBar)))
                        if len(vectorAlturaBar_ext) > 1:
                            tamaño = len(vectorAlturaBar_ext)
                            deltaAlturaBar = float(vectorAlturaBar_ext[tamaño-1])-float(vectorAlturaBar_ext[tamaño-2])
                            alturaBarBias = float(vectorAlturaGps_ext[tamaño-2]) + deltaAlturaBar
                            altitudFus= fusionar(altitudGps,alturaBarBias) #Fusiona la altura del GPS y Barometro en una sola medida mas precisa
                            print("altura_FUS: " + str(float(altitudFus)))
                        datoToSetOK = True
                        print("curso: " + str(float(curso)))
                        print("velocidad: " + str(float(velocidad)))
                    if bit == "D": #Si se cumple se garantiza existencia de trama hasta "D"
                        tempeBar =  valores[3].split("C")[1].split("D")[0].strip()
                        #print("temperaturaBar: " +  str(float(tempeBar)/100))
                    if bit == "E": #Si se cumple se garantiza existencia de trama hasta "E"
                        tempeSHT11 =  valores[3].split("D")[1].split("E")[0].strip()
                        voltajebater =  valores[3].split("E")[1].strip()
                        presionbar = "0.0"
                        humedadDHT11 = "0.0"
                        #print("temperaturaSHT11: " +  str(float(tempeSHT11)/100))
                        #print("voltajebater: " + str(float(voltajebater)/1000))
                        print("trama corta completa")
            #Se debe guardar de manera recurrente las coordenadas de la estacion terrena y la gondola
            #para el caso en el que se reinicie la aplicacion y no se haya movido la estacion, poder
            #recuperar el tracking seteando nuevamente de manera automatica
            if datoToSetOK == True and set == True:
                datoToSetOK = False
                archivo3 = open(nombreArchivoSETLeerEscribir,"w")
                archivo3.write("latitudE/" + str(latitudE) + "\n")
                archivo3.write("longitudE/" + str(longitudE) + "\n")
                archivo3.write("altitudE/" + str(altitudE) + "\n")
                archivo3.write("latitudG_i/" + str(latitud_geo) + "\n")
                archivo3.write("longitudG_i/" + str(longitud_geo) + "\n")
                archivo3.write("altitudG_i/" + str(altitudGps) + "\n")
                archivo3.close()
            return [latitud_geo,longitud_geo,altitudGps]
    except Exception as e:
        print("******ERROR PROCESANDO TRAMA********")
        print(e)

def transformarTrama(latitud,longitud):
    try:
        longitud_geo = 0
        latitud_geo = 0
        if(len(longitud) > 8):
            grados_lo = float(longitud[1:3])
            minutos_lo = float(longitud[3:5])
            decimasMinutos_lo = float("0"+longitud[5:8])
        elif(len(longitud) > 9):
            grados_lo = float(longitud[0:2])
            minutos_lo = float(longitud[2:4])
            decimasMinutos_lo = float(longitud[4:8])
        else:
            grados_lo = float(longitud[1:2])
            minutos_lo = float(longitud[2:4])
            decimasMinutos_lo = float("0"+longitud[4:7])
        longitud_geo = (grados_lo + (minutos_lo + decimasMinutos_lo)/60)
        if(longitud[len(longitud)-1] == "W"):
            longitud_geo = longitud_geo * -1
        longitud_geo = str(longitud_geo)
        longitud_geo = longitud_geo[0:9]
        longitud_geo = longitud_geo.strip()
        if(len(latitud) == 9):
            grados_la = float(latitud[1:3])
            minutos_la = float(latitud[3:5])
            decimasMinutos_la = float("0"+latitud[5:8])
        elif(len(latitud) > 9):
            grados_la = float(latitud[0:2])
            minutos_la = float(latitud[2:4])
            decimasMinutos_la = float(latitud[4:8])
        else:
            grados_la = float(latitud[1:2])
            minutos_la = float(latitud[2:4])
            decimasMinutos_la = float("0"+latitud[4:7])
        latitud_geo = (grados_la + (minutos_la + decimasMinutos_la)/60)
        if(latitud[len(latitud)-1] == "S"):
            latitud_geo = latitud_geo * -1
        latitud_geo = str(latitud_geo)
        latitud_geo = latitud_geo[0:9]
        latitud_geo = latitud_geo.strip()
        return [latitud_geo,longitud_geo]
    except Exception as e:
        print("*****ERROR TRANSFORMANDO TRAMA*****")
        print(e)

def modelo(lati, longi, alti):
    try:
        latitudG = float(lati)
        longitudG = float(longi)
        altitudG = float(alti)
        alfaP = (3.141592653589793/180)*(latitudE)
        betaP = (3.141592653589793/180)*(longitudE)
        hP = altitudE
        alfaS = (3.141592653589793/180)*(latitudG)
        betaS = (3.141592653589793/180)*(longitudG)
        hS = altitudG
        divCero = 0
        r = 6378000.0
        P = r + hP
        S = r + hS
        Px = P*math.cos(alfaP)*math.sin(betaP)
        Py = P*math.cos(alfaP)*math.cos(betaP)
        Pz = P*math.sin(alfaP)
        Sx = S*math.cos(alfaS)*math.sin(betaS)
        Sy = S*math.cos(alfaS)*math.cos(betaS)
        Sz = S*math.sin(alfaS)
        Dxyz_1 = Sx-Px
        Dxyz_2 = Sy-Py
        Dxyz_3 = Sz-Pz
        D = math.sqrt(Dxyz_1*Dxyz_1+Dxyz_2*Dxyz_2+Dxyz_3*Dxyz_3)
        Dw_1 = math.cos(-betaP)*Dxyz_1+math.sin(-betaP)*Dxyz_2
        Dw_2 = -math.sin(-betaP)*Dxyz_1+math.cos(betaP)*Dxyz_2
        Dw_3 = Dxyz_3
        Duvw_1 = Dw_1
        Duvw_2 = math.cos(alfaP)*Dw_2+math.sin(alfaP)*Dw_3
        Duvw_3 = -math.sin(alfaP)*Dw_2+math.cos(alfaP)*Dw_3
        if abs(Duvw_1) < 1:
            Duvw_1 = 0.0
        if abs(Duvw_2) < 1:
            Duvw_2 = 0.0
        if abs(Duvw_3) < 1:
            Duvw_3 = 0.0

        vectorD = [Duvw_1,Duvw_2,Duvw_3]
        MatrizD.append(vectorD)
        try:
            archivo1 = open(nombreVectorTrayectoriaGuardar,"a")
            archivo1.write(str(vectorD) + '\n')
            archivo1.close()
        except:
            print("*** AVISO - vector no logro guardarse ***")
            print(e)

        Distancia = math.sqrt(Duvw_1*Duvw_1+Duvw_2*Duvw_2+Duvw_3*Duvw_3)
        if Distancia > 0.0:
            omega_prima = math.asin(Duvw_2/Distancia)*180/3.14159265358979
            if Duvw_1 < 0.0:
                theta_prima = -math.acos(Duvw_3/math.sqrt(Duvw_1*Duvw_1+Duvw_3*Duvw_3))*180/3.141592653589793
            elif Duvw_1 > 0.0:
                theta_prima = math.acos(Duvw_3/math.sqrt(Duvw_1*Duvw_1+Duvw_3*Duvw_3))*180/3.141592653589793
            elif Duvw_1 == 0.0 and Duvw_3 == 0.0:
                theta_prima = 0.0
            else:
                theta_prima = 0.0
            angulo_omega = omega_prima
            angulo_theta = theta_prima
            return [angulo_theta, angulo_omega]
        else:
            return[0.0, 0.0]
    except Exception as e:
        print("*** ERROR CRITICO - FALLA CALCULANDO MODELO ****")
        print(e)

def enviarArduino(angulo_theta, angulo_omega, state):
    try:
        SET = state
        #Python le pregunta al arduino si puede recibir datos
        arduino.write(str("ESTALISTO0000090909").encode())
        print("arduino listo?")
        time.sleep(0.1)
        datoRecibido = ''
        while True:
            datoRecibido = str(arduino.readline().decode().splitlines())
            if datoRecibido == "['listo']":
                print(datoRecibido)
                break
            time.sleep(0.01)
        #Solo cuando el arduino responda el programa continua
        datoRecibido = ''

        omega_prima = angulo_omega
        theta_prima = angulo_theta

        #Se hace un acarreo de los datos a enviar al arduino y garantizar que no hay perdida de datos
        if omega_prima < 0:
            signo_omega = "-"
            acarreo_signo_omega = 45
        else:
            signo_omega = "+"
            acarreo_signo_omega = 43

        if theta_prima < 0:
            signo_theta = "-"
            acarreo_signo_theta = 45
        else:
            signo_theta = "+"
            acarreo_signo_theta= 43

        suma = (acarreo_signo_theta
            + acarreo_signo_omega
            + 84 + 79
            + int(abs(theta_prima*100))
            + int(abs(omega_prima*100)))
        if suma > 10000:
            ajusteSum = "";
        if 1000 < suma and suma < 10000:
            ajusteSum = "0";
        if 100 < suma and suma < 1000:
            ajusteSum = "00";
        if 10 < suma and suma < 100:
            ajusteSum = "000";
        if suma < 10:
            ajusteSum = "0000";

        print("theta_prima: " + str(theta_prima))
        print("omega_prima: " + str(omega_prima))

        if abs(theta_prima) > 100:
            ajusteT = ""
        if 10 < abs(theta_prima) and abs(theta_prima) < 100:
            ajusteT = "0"
        if 1 < abs(theta_prima) and abs(theta_prima) < 10:
            ajusteT = "00"
        if 0.1 < abs(theta_prima) and abs(theta_prima) < 1:
            ajusteT = "000"
        if abs(theta_prima) < 0.1:
            ajusteT = "0000"

        if abs(omega_prima) > 100:
            ajusteO = "";
        if 10 < abs(omega_prima) and abs(omega_prima) < 100:
            ajusteO = "0";
        if 1 < abs(omega_prima) and abs(omega_prima) < 10:
            ajusteO = "00";
        if 0.1 < abs(omega_prima) and abs(omega_prima) < 1:
            ajusteO = "000";
        if abs(omega_prima) < 0.1:
            ajusteO = "0000";

        #Si SET es true el arduino comprendera que las coordenadas enviadas son el SET y alli configurara su posicion inicial
        if SET == False:
            print(str("T").encode() + str(signo_theta).encode() + str(ajusteT).encode() + str(int(abs(theta_prima*100))).encode()
                  + str("O").encode() + str(signo_omega).encode() + str(ajusteO).encode() + str(int(abs(omega_prima*100))).encode()
                  + str(ajusteSum).encode() + str(suma).encode())
            arduino.write(str("T").encode() + str(signo_theta).encode() + str(ajusteT).encode() + str(int(abs(theta_prima*100))).encode()
                  + str("O").encode() + str(signo_omega).encode() + str(ajusteO).encode() + str(int(abs(omega_prima*100))).encode()
                  + str(ajusteSum).encode() + str(suma).encode())
        else:
            print(str("T").encode() + str(signo_theta).encode() + str(ajusteT).encode() + str(int(abs(theta_prima*100))).encode()
                  + str("O").encode() + str(signo_omega).encode() + str(ajusteO).encode() + str(int(abs(omega_prima*100))).encode()
                  + str("99999").encode())
            arduino.write(str("T").encode() + str(signo_theta).encode() + str(ajusteT).encode() + str(int(abs(theta_prima*100))).encode()
                  + str("O").encode() + str(signo_omega).encode() + str(ajusteO).encode() + str(int(abs(omega_prima*100))).encode()
                  + str("99999").encode())
        time.sleep(0.1)

        datoRecibido = ''
        #Python le pregunta al arduino si entendio el dato que le fue enviado
        while True:
            datoRecibido = str(arduino.readline().decode().splitlines())
            print("angulo entendido? ")
            if datoRecibido == "['entendido']":
                print(datoRecibido)
                break
            if datoRecibido == "['SET']":
                print(datoRecibido)
                break
            time.sleep(0.01)
        #Si el arduino responde el programa continua
        datoRecibido = ''
    except Exception as e:
        print("******ERROR ENVIANDO A ARDUINO*****")
        print(e)

#SETEAR POSICIONES INICIALES GONDOLA Y ESTACION
while(1):
    continuar = 0
    try:
        trama = leerTrama()
        if trama != 0 and trama != 1:
            print(trama)
            for line in sys.stdin:
                if str(line).encode() == b'\n':
                    break
                if line.strip() == "SET-ESTACION":
                    coordenadas = procesarTrama(trama,False)
                    latitudE_set = coordenadas[0]
                    longitudE_set = coordenadas[1]
                    altitudE_set = coordenadas[2]
                    print("**** SET-ESTACION OK ****")
                    continuar = continuar + 1
                    break
                if line.strip() == "SET-GONDOLA":
                    coordenadas = procesarTrama(trama,False)
                    latitudG_i_set = coordenadas[0]
                    longitudG_i_set = coordenadas[1]
                    altitudG_i_set = coordenadas[2]
                    print("**** SET-GONDOLA OK ****")
                    continuar = continuar + 1
                    break
        if continuar == 2:
            archivo3 = open(nombreArchivoSETLeerEscribir,"w")
            archivo3.write("latitudE/" + str(latitudE_set) + "\n")
            archivo3.write("longitudE/" + str(longitudE_set) + "\n")
            archivo3.write("altitudE/" + str(altitudE_set) + "\n")
            archivo3.write("latitudG_i/" + str(latitudG_i_set) + "\n")
            archivo3.write("longitudG_i/" + str(longitudG_i_set) + "\n")
            archivo3.write("altitudG_i/" + str(altitudG_i_set) + "\n")
            archivo3.close()
            break
            print("_________________")
        time.sleep(0.1)

        archivo2 = open(nombreArchivoSETLeerEscribir,"r")
        datoSET = archivo2.readlines()
        latitudE = float(datoSET[0].split("/")[1])
        longitudE = float(datoSET[1].split("/")[1])
        altitudE = float(datoSET[2].split("/")[1])
        latitudG_i = float(datoSET[3].split("/")[1])
        longitudG_i = float(datoSET[4].split("/")[1])
        altitudG_i = float(datoSET[5].split("/")[1])
        angulosSET = modelo(latitudG_i,longitudG_i,altitudG_i)
        thetaSET = angulosSET[0]
        omegaSET = angulosSET[1]
        archivo2.close()
        enviarArduino(thetaSET,omegaSET,True)
        print("__________________________________________")
    except Exception as e:
        print("****ERROR GENERANDO SET***")
        print(e)
        time.sleep(1)

time.sleep(2)

#FLUJO PRINCIPAL
while (1):
    try:
        trama = leerTrama()
        if trama != 0 and trama != 1:
            cuentatrama = 0
            cuentadesconocida = 0
            coordenadas = procesarTrama(trama,True)
            angulos = modelo(coordenadas[0],coordenadas[1],coordenadas[2])
            #print("theta_prima: " + str(angulos[0]))
            #print("omega_prima: " + str(angulos[1]))
            enviarArduino(angulos[0],angulos[1],False) #theta,omega
            if len(MatrizD) > 1: #Estimacion
                #estimacion()
                continue
            print("__________________________________________")
        if trama == 0:
            if cuentatrama < 1:
                print("Esperando trama nueva.....")
                print("__________________________________________")
                cuentatrama = cuentatrama + 1
        if trama == 1:
            if cuentadesconocida < 1:
                print("Trama leida desconocida")
                print("__________________________________________")
                cuentadesconocida = cuentadesconocida + 1
        time.sleep(0.1) #leer archivo tramas cada 100 milisegundos
    except:
        print("******** ERROR DE EJECUCION ***********")


"""--------------------------------------------------------------------------------------------------------------------------------------
MODULE
    PICandOasisOutgoingMaturitiesSTPHook

DESCRIPTION
    This module contains a hook for STP (straight-through-processing) triggered
    by the matching of Zar Maturity Notice confirmation.

-----------------------------------------------------------------------------------------------------------------------------------------
HISTORY
=========================================================================================================================================
Date            Change no       Developer               Requester               Description
-----------------------------------------------------------------------------------------------------------------------------------------
2019-11-21      FAOPS-635       Tawanda Mukhalela       Wandile Sithole         PIC and Oasis Zar Deposits Autorelease on Matched Maturity
                                                                                Notice
-----------------------------------------------------------------------------------------------------------------------------------------
"""

import acm

from at_logging import getLogger
import OperationsSTPFunctions
from OperationsSTPHook import OperationsSTPHook

LOGGER = getLogger(__name__)

class PICandOasisOutgoingMaturitiesSTPHook(OperationsSTPHook):
    """
    Definition of a hook used to perform STP triggered by the
    matching of a Zar Maturity Notice confirmation.
    """

    # noinspection PyPep8Naming
    def Name(self):
        """
        Get the name of the Operations STP Hook.
        """
        return 'PIC and Oasis Outgoing Maturities STP Hook'

    # noinspection PyPep8Naming,PyPep8Naming
    def IsTriggeredBy(self, eventObject):
        """
        Determine whether or not to trigger the hooks STP action/s
        for an event on the specified object.
        """
        if eventObject.IsKindOf(acm.FConfirmation):
            if self.is_valid_confirmation(eventObject):
                return True
        elif eventObject.IsKindOf(acm.FSettlement):
            if self._is_valid_settlement(eventObject):
                if not eventObject.Trade():
                    return False
                trade = eventObject.Trade()
                for confirmation in trade.Confirmations():
                    if self.is_valid_confirmation(confirmation):
                        return True

        return False

    # noinspection PyPep8Naming
    def PerformSTP(self, eventObject):
        """
        Perform the hooks STP action/s for an event on the specified
        object.

        Please note that the action does not necessarily occur to the
        event object itself but may occur to some related object/s.
        """
        trade = eventObject.Trade()
        netting_rules = [rule_link
                         for rule_link in trade.Counterparty().NettingRuleLinks()
                         if rule_link.NettingRule().Name() == 'Zar Maturity Nett'
                         ]
        netting_rule = netting_rules[0] if len(netting_rules) >= 1 else None
        today = acm.Time.DateToday()
        for settlement in trade.Settlements().AsArray():
            if not self._is_valid_settlement(settlement):
                continue
            if settlement.ValueDay() == today and netting_rule:
                OperationsSTPFunctions.release_settlement(settlement)
                message = 'Released Zar Maturity Settlement : {settlement} for Trade : {trade}'
                LOGGER.info(message.format(settlement=settlement.Oid(), trade=settlement.Trade().Oid()))

    @staticmethod
    def is_valid_confirmation(eventObject):
        """
        Check Confirmation Validity
        """
        confirmation = eventObject
        if confirmation.Status() != 'Matched':
            return False
        if confirmation.EventChlItem().Name() != 'Maturity Notice':
            return False
        trade = confirmation.Trade()
        if trade.Acquirer().Name() != 'Funding Desk':
            return False
        instrument = trade.Instrument()
        if instrument.InsType() != 'Deposit':
            return False
        if instrument.Currency().Name() != 'ZAR':
            return False

        return True

    @staticmethod
    def _is_valid_settlement(settlement):
        """
        Check Settlement Validity
        """
        if settlement.Status() != 'Authorised':
            return False
        if OperationsSTPFunctions.is_incoming_settlement(settlement):
            return False
        if settlement.Type() != 'None':
            return False

        return True


import l293d.driver as l293d
import time

motorR = l293d.DC(18,16,12)
motorL = l293d.DC(13,11,7)

def startMotor():
    count = 0
    while count < 8:

        motorR.clockwise()
        motorL.clockwise()
        time.sleep(0.1)
        motorR.stop()
        motorL.stop()
        time.sleep(0.5)
        count = count +1

startMotor()


import tweepy
import json
from secrets import *

def postNextMatches():
    "Posts every team's next match"
    for league in jsonLeague:
        for team in jsonTeams:
            next_match = jsonTeams[team]['nextMatch']  # Helper
            if next_match['status'] is 'home':
                opponent = next_match['against']
                day = next_match['date']
                place = next_match['stadium']

                tweet_text = f'{team.capitalize()} plays against {opponent} on {day} at {place}'
                api.update_status(text=tweet_text)

# File is executed once per week by Heroku Scheduler
if __name__ == '__main__':
    # Constructs Twitter API instance
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
    api = tweepy.API(auth)

    # Import Team Info.
    with open('teamData.json') as teams:
        jsonTeams = json.load(teams)

    # Import League Info.
    with open('leagueData.json') as leagues:
        jsonLeague = json.load(leagues)

    postNextMatches()


"Test how the client handles messages from the server"

import pytest
from server import ServerMsgHandler

# pylint:disable=redefined-outer-name

@pytest.fixture
def msg_handler(mocker):
    "Fixture for a message handler being tested"
    game_state = mocker.MagicMock()
    listening_thread = mocker.MagicMock()
    return ServerMsgHandler(listening_thread, game_state)

def test_ping(msg_handler, mocker):
    "Test handling of PING message"
    server = mocker.MagicMock()
    assert msg_handler.handleMsg("E(123def,1516565652,Ping())", server)
    server.queueMessage.assert_called_once_with("Pong(1516565652,1)")

def test_simple_pong(msg_handler, mocker):
    "Test handling of PONG message which doesn't need a response"
    server = mocker.MagicMock()
    server.timeProvider.return_value = 300
    assert msg_handler.handleMsg("E(123def,1200,Pong(100,0))", server)
    server.setLatency.assert_called_once_with(100)
    server.setClientClockDrift.assert_called_once_with(1000)

def test_reply_pong(msg_handler, mocker):
    "Test handling of PONG message which requests a response"
    server = mocker.MagicMock()
    assert msg_handler.handleMsg("E(123def,1516565852,Pong(1516565652,1))", server)
    server.queueMessage.assert_called_once_with("Pong(1516565852,0)")

def test_hello_new(msg_handler, mocker):
    "Test handling of HELLO message from new client"
    server = mocker.MagicMock()
    assert msg_handler.handleMsg("E(123def,1516565852,Hello())", server)
    server.queueMessage.assert_has_calls([
        mocker.call("TeamPlayer(1,1)"),
        mocker.call("StartGame(1)")
    ])

def test_hello_existing(msg_handler, mocker):
    "Test handling of HELLO message from existing client"
    server = mocker.MagicMock()
    msg_handler.listeningThread.isConnected.return_value = (3, 4)
    msg_handler.gameState.getOrCreatePlayer().teamID = 3
    msg_handler.gameState.getOrCreatePlayer().playerID = 4
    assert msg_handler.handleMsg("E(123def,1516565852,Hello())", server)
    server.queueMessage.assert_has_calls([
        mocker.call("TeamPlayer(3,4)"),
        mocker.call("StartGame(1)")
    ])

def test_hello_unstarted(msg_handler, mocker):
    "Test handling of HELLO message from new client"
    server = mocker.MagicMock()
    msg_handler.gameState.isGameStarted.return_value = False
    assert msg_handler.handleMsg("E(123def,1516565852,Hello())", server)
    server.queueMessage.assert_called_once_with("TeamPlayer(1,1)")


# -*- coding: utf-8 -*-

import os.path
import sqlite3
import csv

class BooksDao:

    # constructor
    def __init__(self, db):
        def dict_factory(cursor, row):
            d = {}
            for idx, col in enumerate(cursor.description):
                d[col[0]] = row[idx]
            return d

        self.db = db
        self.con = sqlite3.connect(self.db)
        # self.con = sqlite3.connect(db)
        self.con.row_factory = dict_factory
        self.cur = self.con.cursor()
        # ñapa para que funcione el iterador
        self.cur_iter = self.con.cursor()

    def __iter__(self):
        query = '''select *
                from books
                where 1 == 1
                order by isbn13 ;'''

        self.cur_iter.execute(query)
        return self

    def __next__(self):

        data = self.cur_iter.fetchone()

        if data:
            return data
        else:
            raise StopIteration

    def create(self):
        """ Creación de la base de datos con una única tabla BOOKS """
        self.cur.execute('drop table IF EXISTS books;')
        self.cur.execute('''create table books
                                (authors, first_name, last_name, title,
                                description, rating, review_date, review,
                                status, began_date, completed_date, tags,
                                notes, groups, copies, created,
                                publisher, publish_date, pages, price,
                                isbn10, isbn13);''')

    def read(self, isbn13):
        q = ("""select * from books where isbn13 = '{}'""").format(isbn13)

        self.cur.execute(q)

        # solo devuelve 1, es PK
        return self.cur.fetchone()

    def exist(self, book):
        """ Revisar si un book (un dict) existe en base de datos """
        isbn13 = book.get('isbn13')

        q = ("""select count(*) total
                from books where isbn13 = '{}'""").format(isbn13)

        self.cur.execute(q)

        return self.cur.fetchone().get('total') > 0

    def insert(self, book):
        """ Inserta un libro en base de datos, únicamente si no existe """
        if self.exist(book):
            print("The book already exists, will be updated")
            self.update(book)
        else:
            t = {}
            # Buscamos y dejamos a '' los valores None
            for key in book.keys():
                if book.get(key):
                    t[key] = book.get(key)

            # en dos pasos
            keys = "'" + "', '".join(t.keys()) + "'"
            values = "'" + "', '".join(t.values()) + "'"
            q = "insert into books ({}) values ({})".format(keys, values)
            self.cur.execute(q)
            self.con.commit()

    def update(self, book):
        """ Actualizamos un libro """
        if self.exist(book):
            sets = ''
            for key in book.keys():
                # evitamos que los valores sin datos se actualicen
                if book.get(key):
                    value = str(book.get(key))
                    # tratamiento de nulos es especial
                    if value.upper() == 'NULL':
                        sets = sets + '"' + key + '" = ' + value + ', '
                    else:
                        sets = sets + '"' + key + '" = "' + value + '", '

            # eliminamos el último ", "
            sets = sets[0:len(sets) - 2]

            where = ("isbn13 = '{}'").format(book.get('isbn13'))

            q = ("""update books set {} where {}""").format(sets, where)

            self.cur.execute(q)
            self.con.commit()

        else:
            print('There is no book to update')

    def delete(self, book):
        """ Revisar si un book (un dict) existe en base de datos """
        isbn13 = book.get('isbn13')

        q = ("""delete from books where isbn13 = '{}'""").format(isbn13)

        self.cur.execute(q)
        self.con.commit()

    def load_csv(self, csvdata):
        """ Carga un fichero CSV a la tabla BOOKS """

        with open(csvdata, 'rt', encoding='utf8') as csvfile:
            # cabecera
            dr = csv.DictReader(csvfile)
            to_db = [(i['authors'], i['first_name'], i['last_name'],
                     i['title'], i['description'], i['rating'],
                     i['review_date'], i['review'], i['status'],
                     i['began_date'], i['completed_date'], i['tags'],
                     i['notes'], i['groups'], i['copies'],
                     i['created'], i['publisher'], i['publish_date'],
                     i['pages'], i['price'], i['isbn10'],
                     i['isbn13'])
                     for i in dr]

            self.cur.executemany('''insert into books
                                    (authors, first_name, last_name,
                                    title, description, rating,
                                    review_date, review, status,
                                    began_date, completed_date, tags,
                                    notes, groups, copies,
                                    created, publisher, publish_date,
                                    pages, price, isbn10,
                                    isbn13)
                            values
                            (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);''',
                                 to_db)
        self.con.commit()

    def executefile(self, sqlfile):
        """ Ejecuta un fichero SQL """
        if os.path.isfile(sqlfile):
            with open(sqlfile, 'rt', encoding='utf8') as sqls:
                # cur.executescript(sql.readlines())
                for sql in sqls:
                    self.cur.execute(sql)
        self.con.commit()

    def execute(self, query):
        """ Ejecuta una sentencia SQL """
        for sql in query:
            self.cur.execute(sql)
        self.con.commit()

    def select(self, query='select * from books order by isbn13'):

        self.cur.execute(query)
        return self.cur.fetchall()

    # def list_by(self, column='', value=''):
    def list_by(self, keys='*', by=None):
        """ List by """

        # Dangerous default value {} as argument
        by = {} if not by else by

        select = 'select ' + ', '.join(keys)

        fromm = ' from books where 1 = 1 '

        where = ''
        for key in by:

            # napeando los acentos
            kaccents = """replace(replace(replace(replace(replace(replace(
                            replace(replace(replace(replace(replace(
                            lower({}),
                                'á','a'), 'ã','a'), 'â','a'),
                                'é','e'), 'ê','e'),
                                'í','i'),
                                'ó','o') ,'õ','o') ,'ô','o'),
                                'ú','u'),
                                'ç','c')""".format(key)

            where = where + " and {} like '%{}%' ".format(kaccents, by[key])

        order = ' order by completed_date '

        query = select + fromm + where + order

        self.cur.execute(query)
        return self.cur.fetchall()

    def stats(self):
        """ Books stats """

        query = ''' select case status when '' then 'No status'
                    else status end as status,
                    count(*) total
                from books
                group by status'''

        self.cur.execute(query)
        return self.cur.fetchall()


# tôi thích lập trình
file_name = 'test.txt'

f = open(file_name, mode='r')
data = f.read()

li = data.split("\t")
print(li)

for i in data:
	print(i, end = '')


import csv, itertools
bps = range(80,150)
concentrations = [187]
products = itertools.product(bps, concentrations)
writefile = "protein_bound_probabilities_1per200.dat"
with open (writefile, 'w+') as wfile:
	wfile.write("N(bp),0HU,1HU,2HU,3HU,4HU,5HU,6HU,7HU,8HU,9HU,10HU,11HU\n")
#	writer = csv.writer(wfile)
#	writer.writerow("N(bp),0HU,1HU,2HU,3HU,4HU,5HU,6HU,7HU,8HU,9HU,10HU,11HU")
for i, (bp, concentration) in enumerate (products):
	filename = "loops-minicircle_%(bp)i_HU+%(concentration)i.dat" % locals()
	#print filename,
	#loops-minicircle_100_HU+87.dat loops-minicircle_100_HU+187.dat ... loops-minicircle_105_HU+187.dat
	pro_bound = []
	counts = [0]*12
	prob = [0]*12
#	prob[0] = bp
	all = 0
	with open (filename, 'r') as file:
		reader = csv.reader(file, delimiter=',')
		for row in reader:
			pro_bound.append(row[7])#read the numbers of protein bound into list pro_bound
#	print(pro_bound)
	for i in range(0,12):
		counts[i] = pro_bound.count(str(i)) #count how many times i proteins are bound
		all = all+counts[i] #all counts
	for i in range(0,12):
		prob[i]=float(counts[i])/all #probabilities
	with open (writefile, 'a') as wfile:
#		writer = csv.writer(wfile, delimiter=',')
#		writer.writerow([bp,prob])
		wfile.write(str(bp)+','+str(prob).strip('[]')+'\n')


class CashRegistry:

    def __init__(self):
        self.money = 0
        self.coins = {
            "quarter": 0.25,
            "dime": 0.1,
            "nickle": 0.05,
            "penny": 0.01
        }

    def process_coins(self, required):
        insert_coins = True
        value_inserted = 0
        while insert_coins:
            coin_type = input(
                "Please choose the coin (penny/nickle/dime/quarter/stop): ").strip()
            if coin_type == "stop":
                insert_coins = False
            else:
                coin_amount = int(
                    input("How many coins of this kind will you insert? ").strip())
                value_inserted += self.coins[coin_type] * coin_amount
                value_left = required - value_inserted
                if value_left >= 0:
                    print("${} more to insert.".format(value_left))
        return value_inserted

    def parse_transaction(self, cost):
        value_inserted = self.process_coins(cost)
        if value_inserted == cost:
            self.money = value_inserted
            return True, None
        elif value_inserted > cost:
            self.money += cost
            change = value_inserted - cost
            return True, change
        else:
            return False, None

    def get_report(self):
        return {
            "Money": self.money
        }


import dataclasses
from abc import ABC, abstractmethod
from functools import cached_property
from typing import Callable, List, Dict, Optional, TypeVar, Type

import pytorch_lightning as pl
import torch.nn as nn
from pytorch_ranger import Ranger
from torch.optim import SGD
from torch.optim.lr_scheduler import OneCycleLR, LambdaLR
from torch.optim.optimizer import Optimizer
from torch.utils.data import Dataset
from torch.utils.tensorboard import SummaryWriter
from torch_optimizer import RAdam

from mylib.torch.optim.sched import flat_cos
from mylib.torch.ensemble.ema import update_ema

T = TypeVar('T')

@dataclasses.dataclass(frozen=True)
class ModuleBaseParams:
    optim: str = 'radam'

    lr: float = 3e-4
    weight_decay: float = 0.

    ema_decay: Optional[float] = None
    ema_eval_freq: int = 1

class PLBaseModule(pl.LightningModule, ABC):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.train_dataset: Optional[Dataset] = None
        self.val_dataset: Optional[Dataset] = None
        self.ema_model: Optional[nn.Module] = None
        self.best: float = float('inf')

    def optimizer_step(
            self,
            epoch: int,
            batch_idx: int,
            optimizer: Optimizer,
            optimizer_idx: int,
            second_order_closure: Optional[Callable] = None,
            on_tpu: bool = False,
            using_native_amp: bool = False,
            using_lbfgs: bool = False,
    ) -> None:
        super().optimizer_step(epoch, batch_idx, optimizer, optimizer_idx, second_order_closure)
        if self.ema_model is not None:
            update_ema(self.ema_model, self.model, self.hp.ema_decay)

    def forward(self, x):
        return self.model.forward(x)

    def training_step(self, batch, batch_idx):
        result = self.step(batch, prefix='train')
        return {
            'loss': result['train_loss'],
            **result,
        }

    def validation_step(self, batch, batch_idx):
        result = self.step(batch, prefix='val')

        if self.eval_ema:
            result_ema = self.step(batch, prefix='ema', model=self.ema_model)
        else:
            result_ema = {}

        return {
            **result,
            **result_ema,
        }

    @abstractmethod
    def step(self, batch, prefix: str, model=None) -> Dict:
        pass

    def training_epoch_end(self, outputs):
        metrics = self.collect_metrics(outputs, 'train')
        self.__log(metrics, 'train')

        return {}

    def validation_epoch_end(self, outputs):
        metrics = self.collect_metrics(outputs, 'val')
        self.__log(metrics, 'val')

        if self.eval_ema:
            metrics_ema = self.collect_metrics(outputs, 'ema')
            self.__log(metrics_ema, 'ema')
        else:
            metrics_ema = None

        if metrics.loss < self.best:
            self.best = metrics.loss

        return {
            'progress_bar': {
                'val_loss': metrics.loss,
                'best': self.best,
            },
            'val_loss': metrics.loss,
            'ema_loss': metrics_ema.loss if metrics_ema is not None else None,
        }

    @abstractmethod
    def collect_metrics(self, outputs: List[Dict], prefix: str) -> T:
        pass

    def __log(self, metrics: T, prefix: str):
        if self.global_step > 0:
            self.tb_logger.add_scalar('lr', metrics.lr, self.current_epoch)
            for k, v in dataclasses.asdict(metrics).items():
                if k == 'lr':
                    continue
                self.tb_logger.add_scalars(k, {
                    prefix: v,
                }, self.current_epoch)

    def configure_optimizers(self):
        if self.hp.optim == 'sgd':
            opt = SGD(
                self.model.parameters(),
                lr=self.hp.lr,
                momentum=0.9,
                nesterov=True,
            )
            sched = {
                'scheduler': OneCycleLR(
                    opt,
                    max_lr=self.hp.lr,
                    total_steps=self.total_steps),
                'interval': 'step',
            }
            return [opt], [sched]

        if self.hp.optim == 'ranger':
            optim = Ranger
        elif self.hp.optim == 'radam':
            optim = RAdam
        else:
            raise Exception(f'Not supported optim: {self.hp.optim}')
        opt = optim(
            self.model.parameters(),
            lr=self.hp.lr,
            weight_decay=self.hp.weight_decay,
        )
        sched = {
            'scheduler': LambdaLR(
                opt,
                lr_lambda=flat_cos(self.total_steps),
            ),
            'interval': 'step',
        }
        return [opt], [sched]

    @property
    def steps_per_epoch(self) -> int:
        return len(self.train_dataloader())

    @property
    def max_epochs(self) -> int:
        trainer: pl.Trainer = self.trainer
        return trainer.max_epochs

    @property
    def total_steps(self) -> int:
        return self.steps_per_epoch * self.max_epochs

    @property
    def eval_ema(self) -> bool:
        if self.ema_model is None:
            return False
        f = self.hp.ema_eval_freq
        return self.current_epoch % f == f - 1

    @abstractmethod
    @cached_property
    def hp(self) -> Type[ModuleBaseParams]:
        pass

    @property
    def tb_logger(self) -> SummaryWriter:
        return self.logger.experiment


from django.contrib.auth import get_user_model
from django.utils import timezone
from re import sub
from rest_framework.authtoken.models import Token

User = get_user_model()

class LastLoginMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        header_token = request.META.get('HTTP_AUTHORIZATION', None)

        if header_token:
            try:
                token = sub('Token ', '', header_token)
                token_obj = Token.objects.get(key=token)
                request.user = token_obj.user
            except Token.DoesNotExist:
                pass

        if request.user.is_authenticated:
            User.objects.filter(pk=request.user.pk).update(last_login=timezone.now())
        response = self.get_response(request)

        return response


def read_grid():
    """ Read the results from a grid and write them to a file
    """

    # Get the list of the directories

    # Loop over the TS Z-Matrices to run optimizations
    for run_dir in enumerate(grid_ts_zmats):

        # Read the output to see if optimization converged
        notconverged = elstruct.reader.has_error_message(
            prog, elstruct.Error.OPT_NOCONV, OUT_STR)

        # Read the final Z-matrix and geometries
        fin_zmat = elstruct.reader.opt_zmatrix(prog, OUT_STR)
        fin_geom = elstruct.reader.opt_geometry(prog, OUT_STR)

        # Read the final energy
        fin_energy = elstruct.reader.energy(prog, method, OUT_STR)

        # Read the final force and energy change in the optimization file
        fin_force, fin_dE = gridopt.read_opt_conv(OUT_STR)

        # Write the z-matrix files
        zma_str = zmatrix.string(fin_zmat)
        zmat_file_name = autofile.name.zmatrix('gridpt')
        zmat_file_path = os.path.join(run_dir_str, zmat_file_name)
        autofile.write_file(zmat_file_path, zma_str)

        # Write the geometry to files
        geo = autofile.read.geometry(fin_geom)
        geom_file_name = autofile.name.geometry('gridpt')
        geom_file_path = os.path.join(run_dir_str, geom_file_name)
        autofile.write_file(geom_file_path, geo_str)

        # Write the energy to a file
        ene_str = str(fin_energy)
        ene_file_name = autofile.name.energy('gridpt')
        ene_file_path = os.path.join(run_dir_str, ene_file_name)
        autofile.write_file(ene_file_path, ene_str)

        # Write the geo convergence parameters to a file
        conv_file_name = os.path.join(run_dir_str, 'gridpt')
        with open(conv_file_name, 'w') as f:
            if not notconverged:
                f.write('Optimization Converged = True\n')
            else:
                f.write('Optimization Converged = False\n')
            f.write('Final Force = {0}\n'.format(fin_force))
            f.write('Final DeltaEnergy = {0}'.format(fin_dE))

    # Loop over the directories to get the converged values
    fin_ene = []
    fin_for = []
    fin_dEn = []
    fin_geo = []
    fin_zma = []
    fin_icv = []
    run_dirs = next(os.walk('.'))[1]
    run_dirs.sort()
    for i, run_dir in enumerate(run_dirs):

        # Go into the run directory
        os.chdir(run_dir)

        # Set the file paths to the info files
        conv_file_path = os.path.join(tmp_dir, run_dir, 'gridpt.conv')
        ene_file_path = os.path.join(tmp_dir, run_dir, 'gridpt.ene')
        geom_file_path = os.path.join(tmp_dir, run_dir, 'gridpt.xyz')
        zmat_file_path = os.path.join(tmp_dir, run_dir, 'gridpt.zmat')

        # Read the convergence parameters
        with open(conv_file_path, 'r') as f:
            for line in f:
                if 'Optimization Converged' in line:
                    fin_icv.append(line.strip().split()[3])
                if 'Final Force' in line:
                    fin_for.append(line.strip().split()[3])
                if 'Final DeltaEnergy' in line:
                    fin_dEn.append(line.strip().split()[3])

        # Read the energy
        fin_ene.append(autofile.read_file(ene_file_path))

        # Read the geometry
        fin_geo.append(autofile.read_file(geom_file_path))

        # Read the z-matrix
        fin_zma.append(autofile.read_file(zmat_file_path))

        # Go into back up
        os.chdir('../')

    # Find the maximum of the energy among the converged geoms
    conv_ene = []
    for ge, gc in zip(fin_ene, fin_icv):
        if gc == 'True':
            conv_ene.append(float(ge))
    max_energy = str(max(conv_ene))

    # Set the index for this energy in the original list containing all energies
    max_energy_idx = fin_ene.index(max_energy)

    # Get the RTS coordinate and Z-Mat corresponding to the maximum energy
    ts_guess_rts = rsteps[max_energy_idx]
    ts_guess_zmat = fin_zma[max_energy_idx]

    # Write main output to a file
    grid_out_path = os.path.join(tmp_dir, 'grid.out')
    with open(grid_out_path, 'w') as outfile:

        # Write the header for a table summarizing the grid information
        outfile.write('VALUES ALONG ALL GRID POINTS:\n')
        head_str = '{0:<10s}{1:<16s}{2:<12s}{3:<14s}{4:<8s}\n'.format(
                        'RTS(ang)', 'Energy(au)', 'Force(au)', 'DeltaE(au)', 'Converged?')
        outfile.write(head_str)

        # Write the pertinent information to the table
        for rts, ge, gf, gd, gc in zip(rsteps, fin_ene, fin_for, fin_dEn, fin_icv):
            grid_str = '{0:<10.4f}{1:<16.8f}{2:<12.6f}{3:<14.8f}{4:<8s}\n'.format(
                            rts*0.529177, float(ge), float(gf), float(gd.replace('D','E')), gc)
            outfile.write(grid_str)

        # Write the guess ts zmat
        outfile.write('\nVALUES AT THE GRID POINT OF MAXIMUM ENERGY OBTAINED FROM CONVERGED GRID POINTS:\n')
        outfile.write('RTS = {0:6.4f}'.format(ts_guess_rts*0.529177))
        outfile.write('\nMaxEnergy = {0:<16.8f}'.format(float(max_energy)))

    # Write the guess ts zmat to standalon file
    guess_zmat_file_name = autofile.name.zmatrix('ts_guess')
    guess_zmat_file_path = os.path.join(tmp_dir, guess_zmat_file_name)
    autofile.write_file(guess_zmat_file_path, ts_guess_zmat)

if __name__ == '__main__':
    read()


from getpass import getpass
import sys
import time
from os import system

def titlescr():
    print(r"""

     ___  ___  ___  _ __    ___  ___  ___  ___  ___     ___  ___  _  ___  ___  ___  ___  ___
    | . \| . ||  _>| / /   | . \| . || . \| __>| . \   / __>|  _>| |/ __>/ __>| . || . \/ __>
    |   /| | || <__|  \    |  _/|   ||  _/| _> |   /   \__ \| <__| |\__ \\__ \| | ||   /\__ \
    |_\_\`___'`___/|_\_\   |_|  |_|_||_|  |___>|_\_\   <___/`___/|_|<___/<___/`___'|_\_\<___/

                                A Rock Paper Scissors Battle - Gnatt
                                        2 PLAYER GAME

    """)

titlescr()

time.sleep(2)

name1 = input("Player 1, enter your name: ")
name2 = input("Player 2, enter your name: ")
print("Welcome " + name1 + " and " + name2 + "!")
time.sleep(1)
input("Press ENTER to start ")

def play_againn():
    play_again = input("Play again(y/n)?: ")
    if play_again == "y":
        system('cls')
        titlescr()
        rock_papers()
    else:
        print("Good bye")
        time.sleep(2)
        sys.exit()

def rock_papers():
    win = False
    i = 0
    e = 0
    while win is False:
        time.sleep(2)
        system('cls')
        titlescr()
        print(name1 + "- " + str(i) + "     " + name2 + "- " + str(e))
        p1 = getpass(name1 + " choose r, p, or s: ")
        p2 = getpass(name2 + " choose r, p, or s: ")

        if p1.lower() == "r" and p2.lower() == "p":
            print(name2 + " wins. ")
            e += 1

        elif p1.lower() == "r" and p2.lower() == "s":
            print(name1 + " wins. ")
            i += 1

        elif p1.lower() == "p" and p2.lower() == "r":
            print(name1 + " wins. ")
            i += 1

        elif p1.lower() == "p" and p2.lower() == "s":
            print(name2 + " wins. ")
            e += 1

        elif p1.lower() == "s" and p2.lower() == "r":
            print(name2 + " wins. ")
            e += 1

        elif p1.lower() == "s" and p2 == "p":
            print(name1 + " wins. ")
            i += 1

        elif p1.lower() == p2.lower():
            print("Tie! You are both losers :) ")

        else:
            print("One of you typed an invalid operator. Please learn to read or type. ")

        if i == 3:
            win = True
            system('cls')
            titlescr()
            print(name1 + "- " + str(i) + "     " + name2 + "- " + str(e))
            print(name1 + " WINS")
            play_againn()

        if e == 3:
            win = True
            system('cls')
            titlescr()
            print(name1 + "- " + str(i) + "     " + name2 + "- " + str(e))
            print(name2 + " WINS")
            play_againn()

rock_papers()

Rock Paper Scissors/Rock Paper Scissors.py


from random import randrange
from collections.abc import MutableMapping

class Item:
    def __init__(self, k, v):
        self.key = k
        self.value = v

    def __eq__(self, other):
        return self.key == other.key

    def __ne__(self, other):
        return not (self == other)

    def __lt__(self, other):
        return self.key < other.key

class QuadraticProbe(MutableMapping):
    def __init__(self, c=11, p=109345121):
        self.table = c * [None]
        self.N = c
        self.size = 0
        self.prime = p
        self.a = 1 + randrange(p - 1)
        self.b = randrange(p)

    def hash_function(self, key):
        i = hash(key)
        return ((self.a * i + self.b) % self.prime) % self.N

    def resize(self, c):
        old = self.table
        self.size = 0
        self.N = c
        self.table = c * [None]
        for item in old:
            if item is not None:
                self.__setitem__(item.key, item.value)

    def __len__(self):
        return self.size

    def __getitem__(self, key):
        pass

    def __setitem__(self, key, value):
        if self.size >= self.N // 2:
            self.resize(self.N * 2)

        hash_value = self.hash_function(key)
        item = self.table[hash_value]
        if item is None:
            # new element, correct slot
            self.table[hash_value] = Item(key, value)
            self.size += 1
        else:
            i = 2
            index = (hash_value + 1) % self.N
            item = self.table[index]
            while item is not None and item.key != key:
                index = (index + i**2) % self.N
                item = self.table[index]
                i += 1
            if item is None:
                # new element
                self.table[index] = Item(key, value)
                self.size += 1
            else:
                # update value
                self.table[index].value = value

    def __getitem__(self, key):
        hash_value = self.hash_function(key)
        item = self.table[hash_value]
        if item is None:
            raise KeyError('Key not found first')
        else:
            index = (hash_value + 1) % self.N
            item = self.table[index]
            for i in range(2, self.N):
                index = (index + i ** 2) % self.N
                item = self.table[index]
                if item is not None:
                    if item.key == key:
                        return item.value
            raise KeyError('Key not found')

    def __iter__(self):
        for item in self.table:
            if item is not None:
                yield item

    def __delitem__(self, key):
        hash_value = self.hash_function(key)
        item = self.table[hash_value]
        if item is None:
            raise KeyError('Key not found first')
        else:
            index = (hash_value + 1) % self.N
            item = self.table[index]
            for i in range(2, self.N):
                index = (index + i ** 2) % self.N
                item = self.table[index]
                if item is not None:
                    if item.key == key:
                        self.table[index] = None
                        self.size -= 1
                        return
            raise KeyError('Key not found')

    def keys(self):
        print("\nLIST OF ALL KEYS:")
        for item in self.table:
            if item is not None:
                print(item.key)

    def value(self):
        print("\nLIST OF ALL VALUES:")
        for item in self.table:
            if item is not None:
                print(item.value)

    def clear(self):
        self.table = self.N * [None]
        self.size = 0

m = QuadraticProbe()
m[0] = 'Zero'
m[1] = 'One'
m[2] = 'Two'
m[3] = "Three"
m[4] = 'Four'
m[5] = 'Five'
m[6] = 'Six'
m[7] = 'Seven'
m[8] = 'Eight'
m[9] = 'Nine'
m[10] = 'Ten'
m[11] = 'Eleven'
m[12] = 'Twelve'  # default size is 11, demonstrate resize function

m.keys()
m.value()

print("\nCompare m[12] and m[10]:")
print(m[12] != m[10])

del m[0]  # deleting two elements demonstration
del m[1]

for i in m:  # demonstrating iter and showing that 2 items have been deleted
    print("KEY: {} and VALUE: {}".format(i.key, i.value))

print()
m.clear()  # after clear, there is no element left
print(len(m))


import random

def criarcartela(matriz):
    for i in range(len(matriz)):
        numcoluna=[0]
        for j in range(len(matriz)):
            aNaColuna=True
            while aNaColuna==True:
                cont=0
                a=random.randint(1+(15*i),15+(15*i))
                for k in numcoluna:
                    if a==k:
                        cont+=1
                if cont==0:
                    aNaColuna=False
            numcoluna.append(a)
            matriz[j][i]="{0:0=2d}".format(a) #perfumaria. Transforma numeros como 1 em 01. Sem perfumaria seria matriz[j][i]=str(a)
    #remover aspas para colocar as colunas da cartela em ordem crescente
    '''
    for i in range(5):
        for j in range(5):
            for h in range(5):
                if matriz[j][i]<matriz[h][i]:
                    matriz[j][i], matriz[h][i]=matriz[h][i], matriz[j][i]
    '''
    matriz[2][2]='--' #-- ao invés de X, tambem por perfumaria para ficar tudo quadrado
    return(matriz)

matriz=[[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0]] #matriz de 0 para trabalhar com substituiçao dos valores
numcartelas=input('Digite o numero de cartelas: ')
while numcartelas.isdigit()==False: #verifica se a entrada do numero de cartelas é um numero, pra nao bugar
    numcartelas=input('Digite o numero de cartelas: ')
for i in range(int(numcartelas)):
    print('======================================')
    cartela=criarcartela(matriz)
    for i in cartela:
        print(i)


import json
import os
from pprint import pprint
from konlpy.tag import Okt
from tensorflow.keras.models import load_model
import time
import datetime
import numpy as np
import tensorflow as tf
import nltk
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers
from tensorflow.keras import losses
from tensorflow.keras import metrics

class ReviewAi(object):
    def __init__(self):
        self.okt = Okt()
        self.x_train = None
        self.y_train = None
        self.path =  os.path.abspath('')
        self.fname =  str
        self.x_test = None
        self.y_test = None

    def create_docs(self):
        path = self.path
        fname = self.fname
        fname = '/com_dayoung_api/cop/rev/model/data/train_docs.json'
        with open(path + fname, encoding='utf-8') as f:
            train_docs = json.load(f)

        fname = '/com_dayoung_api/cop/rev/model/data/test_docs.json'
        with open(path + fname, encoding='utf-8') as f:
            test_docs = json.load(f)
        # print(train_docs[:10])
        return [train_docs, test_docs]

    @staticmethod
    def create_tokens(train_docs):
        tokens = [t for d in train_docs for t in d[0]]
        return tokens

    @staticmethod
    def create_nltk_text(tokens):
        return nltk.Text(tokens, name='NMSC')

    def tokenize(self, review):
        #형태소와 품사를 join
        return ['/'.join(t) for t in self.okt.pos(review, norm=True, stem=True)]

    @staticmethod
    def transfer_text_to_selected_words(text):
        selected_words = [f[0] for f in text.vocab().most_common(10000)]
        return selected_words

    def term_frequency(self, doc):
        ai = ReviewAi()
        docs = self.create_docs()
        train_docs = docs[0]
        tokens = ai.create_tokens(train_docs)
        text = ai.create_nltk_text(tokens)
        selected_words = self.transfer_text_to_selected_words(text)
        return [doc.count(word) for word in selected_words]

    def set_train(self):
        train_x = [self.term_frequency(d) for d, _ in train_docs]
        test_x = [self.term_frequency(d) for d, _ in test_docs]
        train_y = [c for _, c in train_docs]
        test_y = [c for _, c in test_docs]
        self.x_train = np.asarray(train_x).astype('float32')
        self.x_test = np.asarray(test_x).astype('float32')
        self.y_train = np.asarray(train_y).astype('float32')
        self.y_test = np.asarray(test_y).astype('float32')

    def model_save(self):

        FREQUENCY_COUNT = 10000;

        # 레이어 구성
        model = tf.keras.models.Sequential([
            tf.keras.layers.Dense(64, activation='relu', input_shape=(FREQUENCY_COUNT,)),
            tf.keras.layers.Dense(64, activation='relu'),
            tf.keras.layers.Dense(1, activation='sigmoid')
        ])

        # 학습 프로세스 설정
        model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.001),
            loss=tf.keras.losses.binary_crossentropy,
            metrics=[tf.keras.metrics.binary_accuracy]
            )
        model.fit(self.x_train, self.y_train, epochs=10, batch_size=512)

        model.save('another_model.h5')

    def model_load(self):
        path = self.path
        fname = self.fname

        fname = '/com_dayoung_api/cop/rev/model/data/review_model.h5'
        loaded_model = load_model(path + fname)
        return loaded_model

    def model_eval(self, model):
        result = model.evaluate(self.x_test, self.y_test)
        return result

    def predict_review(self, review):
        token = self.tokenize(review)
        tfq = self.term_frequency(token)
        data = np.expand_dims(np.asarray(tfq).astype('float32'), axis=0)
        loaded_model = self.model_load()
        score = float(loaded_model.predict(data))
        if(score > 0.5):
            print(f"{review} ==> {round(score*100)}% 확률로 긍정 리뷰입니다.")
        else:
            print(f"{review} ==> {round((1-score)*100)}% 확률로 부정 리뷰입니다.")

        return score

if __name__ == "__main__":
    ai = ReviewAi()
    docs = ai.create_docs()
    train_docs = docs[0]
    test_docs = docs[1]
    print(f'[ 훈련데이터 상위 10 Rows ] : {train_docs[:10]}')
    tokens = ai.create_tokens(train_docs)
    print(f'[ 전체 토큰의 개수 ] : {len(tokens)}')
    # docs = tokens
    # temp_tokens = ai.tokenize(train_docs)
    nltk_text =  ai.create_nltk_text(tokens)
    print(f'[ 중복을 제외한 토큰의 개수 ] {len(nltk_text.tokens)}')
    print(f'[ 출현 빈도가 높은 상위 토큰 10개 ] {nltk_text.vocab().most_common(10)}')

    # 출현 빈도 높은 상위 10000개 토큰 분류
    selected_words = ai.transfer_text_to_selected_words(nltk_text)
    print(f'[ 출현 빈도가 높은 상위 토큰 100개 ] {selected_words[:100]}')

    # term_freq_count = ai.term_frequency(train_docs)
    # ai.set_train()
    # ai.model_save()
    # model = ai.model_load()
    # answer = ai.model_eval(model)
    # print(f'[ 모델 평가한 답 ] {answer}')
    # print(f'================= Practice Result ====================')
    ai.predict_review("재미 정말 없어요 갖다 버리세요")
    ai.predict_review("이건 개망한 영화인데;; 누가보냐")
    ai.predict_review("좋았어 이거 또 보러 온다")
    ai.predict_review("너무 예쁜데요 ㅠㅠ 최고에요")
    ai.predict_review("하하하 쩔었다~~")
    ai.predict_review("21세기 최고의 영화다 진짜!!")
    ai.predict_review("너무 재밌어요 ㅋㅋ 진짜 쩐다 쩔어")
    ai.predict_review("수업 가기 귀찮다...")


#!/usr/bin/env python

import logging
import argparse
import yaml
from pysnmp.hlapi import *

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="SNMP Agent serving BDS data")

    parser.add_argument('--bds-map',
                        metavar='<PATH>',
                        type=str,
                        default='snmpOidMapping.yml',
                        help='SNMP to BDS objects map file [snmpOidMapping.yml]')

    parser.add_argument('--snmp-agent-ipv4-address',
                        metavar='IPv4',
                        type=str,
                        default='127.0.0.1',
                        help='SNMP agent listens at this address [127.0.0.1]')

    parser.add_argument('--snmp-agent-udp-port',
                        metavar='<INT>',
                        type=int,
                        default=161,
                        help='SNMP agent listens at this UDP port [161]')

    parser.add_argument('--snmp-community-name',
                        metavar='<STRING>',
                        type=str,
                        default='public',
                        help='SNMP agent responds to this community name [public]')

    args = parser.parse_args()

    logging.getLogger().setLevel(logging.DEBUG)

    with open(args.bds_map, 'r') as stream:
        oidDict = yaml.load(stream)

    oids = sorted(list(oidDict))

    snmpEngine = SnmpEngine()

    udpTransportTarget = UdpTransportTarget((args.snmp_agent_ipv4_address, args.snmp_agent_udp_port), retries=0, timeout=3)
    snmpCommunity = CommunityData('public')

    logging.debug('querying SNMP SNMP agent at {}'.format(udpTransportTarget))
    logging.debug('using SNMP community name {}'.format(snmpCommunity))

    for oid in oids:
        logging.debug('trying OID {}'.format(oid))

        errorIndication, errorStatus, errorIndex, varBinds = next(
            getCmd(snmpEngine,
                   snmpCommunity,
                   udpTransportTarget,
                   ContextData(),
                   ObjectType(ObjectIdentity(oid)))
        )

        if errorIndication:
            logging.debug('OID {} not fetched: {}'.format(oid, errorIndication))

        elif errorStatus:
            logging.debug('OID {} not fetched: {}'.format(oid, errorStatus.prettyPrint()))

        else:
            for varBind in varBinds:
                logging.debug('fetched {}'.format(' = '.join([x.prettyPrint() for x in varBind])))


# coding: utf-8

import requests
from bs4 import BeautifulSoup
import re
import time
import datetime
import json
import traceback

from tables import *

def merge_two_dicts(x, y):
    """
    Функция для объединения двух словарей
    """
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z

def prepare_date(date_str: str):
    """
    Функция для обработки даты.
    Принимает на вход строку (но может и объект datetime.datetime)
    И преобразовывает его в datetime.datetime
    """

    months = {
        'января': '01',
        'февраля': '02',
        'марта': '03',
        'апреля': '04',
        'мая': '05',
        'июня': '06',
        'июля': '07',
        'августа': '08',
        'сентября': '09',
        'октября': '10',
        'ноября': '11',
        'декабря': '12',
    }

    if type(date_str) == datetime.datetime:
        # если объект == datetime.datetime
        return date_str

    else:
        # иначе
        # Проверка на соответствие типу
        assert type(date_str) == str, "Object must be str"
        # Удаление из строки лишних символов
        date_str = date_str.replace('г.', ' ').replace('МСК', '').replace('  ', '').replace('\n', '')
        # Если присутствуют месяцы не в цифровом виде, то замена из на цифры
        for month, value in months.items():
            date_str = date_str.replace(month, value)

        # если в конце строки пустота
        if date_str[-1:] == ' ':
            # удаляем его
            date_str = date_str[:-1]

        # Если строка пустая
        if date_str == '':
            # возвращаем None
            return None
        else:
            # Иначе
            # преобразовываем в объект datetime.datetime
            try:
                date_str = datetime.datetime.strptime(date_str, '%d %m %Y %H:%M')
                return date_str
            except ValueError as err:
                # если не выходит преобразовать, то шаблон не соответвует строке
                print("Time data '{0}' does not match format '%d %m %Y %H:%M'".format(date_str))
                return None

def get_main_info(soup: BeautifulSoup):
    """
    Функция принимает на вход распарсенную страницу.
    На выходе выдает основую информацию в формате dict.
    """

    main_table = soup.find_all("table")[0]
    info = {}
    for tr in main_table.find_all('tr'):
        key = tr.find_all('td')[0].getText().replace(' ', '')
        value = tr.find_all('td')[1].getText().replace("\xa0", "").replace(",", ".").replace(
            '\r', '').replace('\n', '').replace('  ', '').replace('(Все закупки организации)', '').replace(' руб.', '')
        if value is not None and value != "":
            if value[0] == " ":
                value = value[1:]
            info.update({key: value})

    info = {
        "name_group_pos": info['НаименованиеЗакупки'],
        "organization": info['Заказчик'],
        "start_price": float(info['Суммаконтракта']),
    }

    return info

def get_date_info(soup: BeautifulSoup):
    """
    Функция принимает на вход распарсенную страницу.
    На выходе выдает информацию по датам в формате dict.
    """
    date_table = soup.find_all("table")[1]
    info = {}
    for tr in date_table.find_all('tr'):
        key = tr.find_all('td')[0].getText().replace(' ', '')
        value = tr.find_all('td')[1].getText().replace("\xa0", "").replace(",", ".").replace(
            '\r', '').replace('\n', '').replace('  ', '').replace('(Все закупки организации)', '').replace(' руб.', '')

        if value != "":
            if value[0] == " ":
                value = value[1:]
            if value[-1] == " ":
                value = value[:-1]
        info.update({key: value})
        key = tr.find_all('td')[2].getText().replace(' ', '')
        value = tr.find_all('td')[3].getText().replace("\xa0", "").replace(",", ".").replace(
            '\r', '').replace('\n', '').replace('  ', '').replace(' МСК', '')
        if value != "":
            if value[0] == " ":
                value = value[1:]
            if value[-1] == " ":
                value = value[:-1]
        info.update({key: value})

    info = {
        "end_time": prepare_date(info['Срококончанияподачиоферт']) + datetime.timedelta(2/24),
        'start_time': None,
        'created_time': None,
    }
    return info

def get_items(otc_number: int):
    """Функция возвращает данные о товарах в закупке"""

    url_pattern = "https://market.otc.ru/ProductRequest/ByGroup?groupId={0}"
    otc_url = url_pattern.format(otc_number)
    r = requests.get(otc_url)
    positions = [{
        'unique_id': str(otc_number) + '_otc',
        'name': x['Name'],
        'amount': x['Count'],
        'price': x['Price']
    } for x in r.json()['Data']]
    return positions

def get_active_tenders():
    """Функция возвращает номера активных тендеров"""
    url_search = 'https://otc.ru/tenders/Search/Lite?SearchForm.HasPrepayment=on&SearchForm.Region=7200000000000%7C6&SearchForm.State=1&SearchForm.DocumentSearchEnabled=true&SearchForm.WithdrawnSearchEnabled=False&SearchForm.HasApplications=on&SearchForm.CurrencyCode=643&SearchForm.SectionIds=91&SearchForm.SectionIds=84&SearchForm.OrganizationLevels=All&SearchForm.OrganizationLevels=Fz223&SearchForm.OrganizationLevels=Fz44&SearchForm.OrganizationLevels=Pprf615&SearchForm.OrganizationLevels=Small&SearchForm.OrganizationLevels=Commercial&SearchForm.IsSmallAndAverageBusiness=on&FilterData.SortingField=DatePublished&FilterData.SortingDirection=Desc&FilterData.PageSize=500&FilterData.PageIndex=1&'
    r = requests.get(url_search)
    soup = BeautifulSoup(r.content, 'lxml')
    tender_numbers = list(set([int(re.search('/\d+-', x.get('href')).group(0).replace('/','').replace('-','')) for x in soup.find_all('a', {'class': 'panel_name'})]))
    real_count = int(re.search('\d+', soup.find('div', {'class': 'row search-form-result-counter'}).getText()).group(0))
    assert len(tender_numbers) == real_count, 'Количество тендеров в поиске не совпадает с результатом'
    return tender_numbers

def get_one_state(otc_number: int):
    'Функция возвращает данные по одной закупке'
    url_pattern = "https://market.otc.ru/ProductRequestGroup/Index/{0}"
    otc_url = url_pattern.format(otc_number)
    r = requests.get(otc_url)
    soup = BeautifulSoup(r.content, 'lxml')
    main_info = get_main_info(soup)  # получение основных данных о закупке
    date_info = get_date_info(soup)  # получение информации о датах закупки
    state = merge_two_dicts(main_info, date_info)  # объединение двух словарей
    state.update({
        'unique_id': str(otc_number) + '_otc',
        'place': 'otc',
        'current_status': 'Активная',
        'address': None,
        'id_zak': otc_number,
        'url': otc_url,
        'send': False,
        'add_trello': False,
    })
    position = get_items(otc_number)
    return state, position

def get_states_otc():
    tender_numbers = get_active_tenders()
    tender_number_not_in_base = []
    for tender_number in tender_numbers:
        if State.get_or_none(State.unique_id==str(tender_number)+'_otc') is None:
            tender_number_not_in_base.append(tender_number)
    states = []
    positions = []
    for otc_number in tender_number_not_in_base:
        state, position = get_one_state(otc_number)
        states += [state]
        positions += position
    return states, positions

if __name__ == '__main__':
    data = get_states_otc()
    message = get_html(data)
    send_email(message, "SyrnikovPavel@gmail.com", "SyrnikovPavel@gmail.com", "Nastya26042015")
    send_email(message, "sursmirnav78@mail.ru", "SyrnikovPavel@gmail.com", "Nastya26042015")


#!/usr/bin/env python
import roslib
import rospy
import math
import tf
import geometry_msgs.msg
import turtlesim.srv
from std_msgs.msg import Header

if __name__ == '__main__':
    rospy.init_node('robot_position_broadcaster')

    listener = tf.TransformListener()

    robot_position_publisher = rospy.Publisher('/robot_position', geometry_msgs.msg.PoseStamped,queue_size=1)

    rate = rospy.Rate(10.0)
    while not rospy.is_shutdown():
        try:
            ((x,y,z),(xx,yy,zz,ww)) = listener.lookupTransform('/cartographer_map', '/base_link', rospy.Time(0))

            p = geometry_msgs.msg.PoseStamped()

            p.header.frame_id = "/cartographer_map"
            p.header.stamp = rospy.Time.now()

            p.pose.position.x=x
            p.pose.position.y=y
            p.pose.position.z=z

            p.pose.orientation.x = xx
            p.pose.orientation.y = yy
            p.pose.orientation.z = zz
            p.pose.orientation.w = ww
            robot_position_publisher.publish(p)

            rate.sleep()
        except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
            continue


try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages
import sys
PY2 = sys.version_info[0] == 2
PY26 = PY2 and sys.version_info[1] < 7

NAME = 'pyexcel-cli'
AUTHOR = 'C.W.'
VERSION = '0.0.3'
EMAIL = 'wangc_2011@hotmail.com'
LICENSE = 'New BSD'
ENTRY_POINTS = {
    'console_scripts': [
        'pyexcel = pyexcel_cli.main:main'
    ]
}
DESCRIPTION = (
    'A command utility to read and write data in csv, tsv, xls, xlsx and od' +
    's format.' +
    ''
)
KEYWORDS = [
    'excel',
    'python',
    'pyexcel',
]

CLASSIFIERS = [
    'Topic :: Office/Business',
    'Topic :: Utilities',
    'Topic :: Software Development :: Libraries',
    'Programming Language :: Python',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
]

INSTALL_REQUIRES = [
    'pyexcel>=0.5.0',
    'Click>=5.0',
]

PACKAGES = find_packages(exclude=['ez_setup', 'examples', 'tests'])
EXTRAS_REQUIRE = {
}

def read_files(*files):
    """Read files into setup"""
    text = ""
    for single_file in files:
        content = read(single_file)
        text = text + content + "\n"
    return text

def read(afile):
    """Read a file into setup"""
    with open(afile, 'r') as opened_file:
        content = filter_out_test_code(opened_file)
        content = "".join(list(content))
        return content

def filter_out_test_code(file_handle):
    found_test_code = False
    for line in file_handle.readlines():
        if line.startswith('.. testcode:'):
            found_test_code = True
            continue
        if found_test_code is True:
            if line.startswith('  '):
                continue
            else:
                empty_line = line.strip()
                if len(empty_line) == 0:
                    continue
                else:
                    found_test_code = False
                    yield line
        else:
            yield line

if __name__ == '__main__':
    setup(
        name=NAME,
        author=AUTHOR,
        version=VERSION,
        author_email=EMAIL,
        description=DESCRIPTION,
        long_description=read_files('README.rst', 'CHANGELOG.rst'),
        license=LICENSE,
        keywords=KEYWORDS,
        extras_require=EXTRAS_REQUIRE,
        tests_require=['nose'],
        install_requires=INSTALL_REQUIRES,
        packages=PACKAGES,
        include_package_data=True,
        zip_safe=False,
        entry_points=ENTRY_POINTS,
        classifiers=CLASSIFIERS
    )


'''tic tac'''
import copy
def tictac():
    '''tictac implementation'''
    rank1 = 0 #this rank is for o
    rank2 = 0 #this rank is for x
    t_t = []
    for _ in range(0, 3, 1):
        t_t += [input().split(' ')]
    count1 = 0
    count2 = 0
    for itemp in t_t:
        for jtemp in itemp:
            if jtemp not in ('o', 'x', '.'):
                return "invalid input"
            if jtemp == 'o':
                count1 += 1
            if jtemp == 'x':
                count2 += 1
    if abs(count1 - count2) != 1:
        return "invalid game"
    diag1 = []
    diag2 = []
    matrix2 = []
    for itemp in range(0, len(t_t), 1):
        list2 = []
        k = copy.deepcopy(t_t[itemp])
        temp = set(k)
        if len(temp) == 1:
            lis = list(temp)
            if lis[0] == 'o':
                rank1 = 1
            else:
                rank2 = 1
        lis = []
        k = []
        for jtemp in range(0, len(t_t[itemp]), 1):
            list2.append(t_t[jtemp][itemp])
            if itemp == jtemp:
                diag1.append(t_t[itemp][jtemp])
            if itemp + jtemp == len(t_t) - 1:
                diag2.append(t_t[itemp][jtemp])
        matrix2.append(list2)
    for itemp in range(0, len(matrix2), 1):
        k = copy.deepcopy(matrix2[itemp])
        temp = set(k)
        if len(temp) == 1:
            lis = list(temp)
            if lis[0] == 'o':
                rank1 = 1
            elif lis[0] == 'x':
                rank2 = 1
    temp = set(diag1)
    if len(temp) == 1:
        lis = list(temp)
        if lis[0] == 'o':
            rank1 = 2
        else:
            rank2 = 2
    temp = set()
    temp = set(diag2)
    if len(temp) == 1:
        lis = list(temp)
        if lis[0] == 'o':
            rank1 = 2
        else:
            rank2 = 2
    if rank1 > rank2:
        return 'o'
    if rank1 == rank2:
        return "draw"
    return 'x'
def main():
    '''mainfunction calls the tictac function'''
    print(tictac())
if __name__ == "__main__":
    main()


node_num, nonleaf_num = map(int, input().split())
node_info = [[] for _ in range(node_num + 1)]
if node_num == 1: print("1")
else:
    for _ in range(nonleaf_num):
        a = list(map(int, input().split()))
        node_info[a[0]] = a[2:]
    # BFS
    level, que = [0], [1]
    while que:
        length, temp_num = len(que), 0
        for _ in range(length):
            father = que.pop()
            for son in node_info[father]:
                if not node_info[son]: temp_num += 1
                else: que.insert(0, son)
        level.append(temp_num)
    # join只能str？
    print(" ".join(map(str, level)))


#!/usr/bin/env python3

from niryo_one_python_api.niryo_one_api import *
from pprint import pprint
import sys
import subprocess
import copy
import rospy
import time
import tf
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
import visualization_msgs.msg
import math
import time
from math import pi
from std_msgs.msg import String
from moveit_commander.conversions import pose_to_list

marker_subscriber = None;
marker_pose = geometry_msgs.msg.PointStamped();

def parse_visualization_msg(data):
    if (data.id == 1):
      marker_pose.point = data.pose.position;
      marker_pose.header.frame_id = data.header.frame_id;
      print(marker_pose);

def get_object_marker_position():
    marker_subscriber = rospy.Subscriber("/visualization_marker", visualization_msgs.msg.Marker, parse_visualization_msg)
    print("Subscribing to /visualization_marker");
    while (marker_pose.header.frame_id == ""):
      time.sleep(1)
    marker_subscriber.unregister();
    print("Unsubscribing from /visualization_marker");

def niryo_demo():
  #Approach vector and offset distance to compensate for gripper length
  approach = [0, 0, -1]
  grasp_offset = -0.09

  moveit_commander.roscpp_initialize(sys.argv)
  rospy.init_node('moveit_niryo_robot')

  n = NiryoOne()
  n.calibrate_auto()
  n.activate_learning_mode(False)
  n.change_tool(TOOL_GRIPPER_2_ID)
  n.open_gripper(TOOL_GRIPPER_2_ID, 200)
  print("[GRIPPER 2 OPENED]")

  robot = moveit_commander.RobotCommander()
  #scene = moveit_commander.PlanningSceneInterface()

  group_name = "arm"
  group = moveit_commander.MoveGroupCommander(group_name)
  group.set_planning_time(10)

  listener = tf.TransformListener()
  #Let the buffer fill so we can get the frame list
  time.sleep(3)
  frame_list = listener.getFrameStrings()

#	listener.waitForTransform("camera_color_optical_frame", "ground_link", rospy.Time(), rospy.Duration(2.0))
#	(trans, quat) = listener.lookupTransform("camera_color_optical_frame", "ground_link", rospy.Time(0))
#	camera_static_transform = subprocess.Popen(
#				["rosrun", "tf", "static_tranform_publisher", str(trans[0]), str(trans[1]), str(trans[2]), str(quat[0]), str(quat[1]), str(quat[2]), str(quat[3]), "100"])

#	print("[INFO] Camera-robot link established, you can remove the ARUCO marker now.")
#	rospy.sleep(5)
	#One object only
#	marker_frame = [e for e in frame_list if e[:7] == "object_"][0]
  get_object_marker_position()
  print("Transforming point from frame: " + marker_pose.header.frame_id)
  listener.waitForTransform("base_link", marker_pose.header.frame_id, rospy.Time(), rospy.Duration(2.0))
#	(trans, quat) = listener.lookupTransform("base_link", marker_frame, rospy.Time(0))
  marker_point = listener.transformPoint("base_link", marker_pose) # the marker position in arm base frame

  #print "Translation [x, y, z]    = " + str(trans)
  #print "Orientation [x, y, z, w] = " + str(quat)

  point = marker_point.point
  pick_target = geometry_msgs.msg.Pose()
  pick_target.position.x    	= point.x + grasp_offset * approach[0]
  pick_target.position.y		= point.y + grasp_offset * approach[1]
  pick_target.position.z		= point.z + grasp_offset * approach[2]
  pick_target.orientation.x	= 0.0
  pick_target.orientation.y	= 1.0/math.sqrt(2)
  pick_target.orientation.z	= 0.0
  pick_target.orientation.w 	= 1.0/math.sqrt(2)
  group.set_pose_target(pick_target)

  pprint(pick_target)

  plan = group.plan()
  group.go(wait=True)

  n.close_gripper(TOOL_GRIPPER_2_ID, 200)
  print("[GRIPPER 2 CLOSED]")

  place_target = geometry_msgs.msg.Pose()
  place_target.position.x =  pick_target.position.x
  place_target.position.y =  pick_target.position.y
  place_target.position.z =  pick_target.position.z + 0.1 #Lift the cube 10cm
  place_target.orientation.x	= 0.0
  place_target.orientation.y	= 1.0/math.sqrt(2)
  place_target.orientation.z	= 0.0
  place_target.orientation.w 	= 1.0/math.sqrt(2)

  group.set_pose_target(place_target)
  plan = group.plan()
  group.go(wait=True)

  #Place cube in the -y position of starting position
  place_target = geometry_msgs.msg.Pose()
  place_target.position.x =  pick_target.position.x
  place_target.position.y = -pick_target.position.y
  place_target.position.z =  pick_target.position.z
  place_target.orientation.x	= 0.0
  place_target.orientation.y	= 1.0/math.sqrt(2)
  place_target.orientation.z	= 0.0
  place_target.orientation.w 	= 1.0/math.sqrt(2)

  group.set_pose_target(place_target)
  plan = group.plan()
  group.go(wait=True)

  n.open_gripper(TOOL_GRIPPER_2_ID, 200)
  print("[GRIPPER 2 OPENED]")

  #Move to resting position
  resting_joints = [0, 0.64, -1.39, 0, 0, 0]
  n.move_joints(resting_joints)

  n.close_gripper(TOOL_GRIPPER_2_ID, 200)
  print("[GRIPPER 2 CLOSED]")

  n.activate_learning_mode(True)

  moveit_commander.roscpp_shutdown()

if __name__ == '__main__':
  try:
	  niryo_demo()
  except rospy.ROSInterruptException:
	  n.activate_learning_mode(True)