###### Librerias ######
import tkinter as tk
import Widgets as Wd
import Ecuaciones as Ec
import time as tm
import threading as hilos
import numpy as np
###### Modulos De Librerias ######
import tkinter.ttk as ttk
import tkinter.messagebox as MsB
import serial
import serial.tools.list_ports
import matplotlib.pyplot as plt
###### SubModulos De Librerias ######
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

board =serial.Serial(port='COM1', baudrate=9600)
tm.sleep(1)
board2 =serial.Serial(port='COM4', baudrate=9600)
tm.sleep(1)

def Show_Sliders(event): #Función Para Mostrar Sliders
    Alter_Sliders('T', Pl_x.get())
    Datos_Temp(0,0,0,1)
    Wd.Aparecer([Pl_x, Pl_y, Pl_z, P_xi, P_yi, P_zi, P_x, P_y, P_z, P_inicial, P_final],
    [1/16+0.025, 1/16+0.025, 1/16+0.025, 0, 0, 0, 1/16+0.01, 1/16+0.01, 1/16+0.01, 0, 2/16],
    [1/6, 3/6-0.07, 0.693, 2/6-0.02, 3/6+0.075, 0.836, 2/6-0.02, 3/6+0.075, 0.836, 1/6-0.02, 0])

def Show_Codo(Iden, Valor): #Función Para Mostrar Codos
    Wd.Aparecer([T_Codo, Despl_Codo], [4/16+0.02, 4/16+0.01], [3/7+0.02, 4/6])

def Show_Perfiles(event): #Función Para Mostrar Perfiles
    Wd.Aparecer([Cuadratico, TrapezoidalI, TrapezoidalII], [6/16+0.04, 9/16+0.04, 12/16+0.04], [0, 0, 0])

def Show_Datos(): #Función Para Mostrar Los Sliders De Datos De Entrada
    if Tipo.get()==1:
        Wd.Ocultar([Vj_1, Vj_2, Vj_3, Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3, TVc_1, TVc_2, TVc_3])

    if Tipo.get()==2:
        Wd.Aparecer([Vj_1, Vj_2, Vj_3, TVc_1, TVc_2, TVc_3],
        [9/16+0.04, 9/16+0.04, 9/16+0.04, 9/16+0.02, 9/16+0.02, 9/16+0.02],
        [1/8+0.01, 3/8+0.04, 5/8+0.08, 1/7+0.12, 3/7+0.12, 5/7+0.12])
        Wd.Ocultar([Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3])
        #Calculos.Perf_Trape(T_f.get(),N_p.get(),0,0,0,1)

    if Tipo.get()==3:
        Wd.Aparecer([Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3],
        [12/16+0.04, 12/16+0.04, 12/16+0.04, 12/16+0.02, 12/16+0.02, 12/16+0.02],
        [1/8+0.01, 3/8+0.04, 5/8+0.08, 1/7+0.12, 3/7+0.12, 5/7+0.12])
        Wd.Ocultar([Vj_1, Vj_2, Vj_3, TVc_1, TVc_2, TVc_3])
        #Calculos.Perf_Trape(T_f.get(),N_p.get(),0,0,0,2)

    Wd.Aparecer([T_f, N_p, TT_f, TN_p, Calcular_PT],
    [6/16+0.04, 6/16+0.04, 6/16+0.02, 6/16+0.02, 6/16+0.04],
    [1/8+0.01, 3/8+0.04, 1/7+0.012, 3/7+0.012, 6/8])

def Show_Graficas(Iden, Valor):
    print(Valor)

bands=0
bandr=0
def Datos_Temp(xtemp, ytemp, ztemp, RW): #Función Para Guardar Los Valores Para Nuevo Punto Inicial
    global bands
    global bandr

    if RW==0:
        selection = Despl_Mani.get()
        if selection == "Scara (PRR)":
            temp_xs=xtemp
            temp_ys=ytemp
            temp_zs=ztemp
            bands=1
        else:
            temp_xr=xtemp
            temp_yr=ytemp
            temp_zr=ztemp
            bandr=1
    else:
        selection = Despl_Mani.get()
        if selection == "Scara (PRR)":
            if bands==1:
                P_xi.config(text=temp_xs)
                P_yi.config(text=temp_ys)
                P_zi.config(text=temp_zs)
            else:
                P_xi.config(text=345.2)
                P_yi.config(text=0)
                P_zi.config(text=0)
        else:
            if bandr==1:
                P_xi.config(text=temp_xr)
                P_yi.config(text=temp_yr)
                P_zi.config(text=temp_zr)
            else:
                P_xi.config(text=197)
                P_yi.config(text=0)
                P_zi.config(text=95.5)

def Alter_Sliders(Ident, Valor): #Función Para Alternos Los Sliders (Scara-Antropomórfico)
    if Despl_Mani.get() == "Scara (PRR)":
        Pl_x['from_']=-131.5
        Pl_x['to']=375.5
        Pl_z['from_']=0
        Pl_z['to']=19
        if Ident == 'A1':
            Red_Slider(['S', 'T', Pl_y, Check_S_PL, 1/4-0.025, 1/3+0.22], Valor)
    else:
        Pl_x['from_']=-197
        Pl_x['to']=197
        if Ident == 'A1':
            Red_Slider(['A1', 'T', Pl_y, Check_A_PL, 1/4-0.025, 2/3+0.15], Valor)
        elif Ident == 'A2':
            Red_Slider(['A2', 'T', Pl_z, Check_A_PL, 1/4-0.025, 2/3+0.15], Valor)

def Mensajes(Cual): #Función Para Seleccionar Mensaje Emergente A Mostrar
    if Cual=="DK":
        MsB.showinfo(
            "Instrucciones Cinemática Directa",
        """
            Sliders: Desplazar los slider para mover las
            articulaciones del brazo robótico en tiempo real
            para obtener las matrices individuales y total de
            la cinemática directa. \n

            Cuadro de Texto: Digitar el valor que se encuentre
            en el rango de funcionamiento del robot para mover
            las articulaciones del brazo robótico.
            Luego presionar el botón de envió y obtener las
            matrices individuales y total de la cinemática directa
            en tiempo real.
        """)
    elif Cual=="IK":
        MsB.showinfo(
            "Instrucciones Cinemática Inversa",
        """
            Deslizar cada slider para establecer la posición
            del efector final, dar click en el botón "Calcular"
            y finalizar seleccionando la configuración del codo
            a utilizar para mover el manipulador. \n

            Se debe tener en cuenta que las opciones de los codos
            únicamente están disponibles sí los valores calculados
            de las articulaciones no superan los límites mecánicos
        """)

def Color(Bandera, Boton, Identi): #Función Para Alternan Color De Boton
    #print-->board.write
    if Bandera:
        Boton["bg"]="red4"
        board.write(Identi.encode() +b',1\n')
    else:
        Boton["bg"]="lime green"
        board.write(Identi.encode() +b',0\n')

def Gripper(Identi): #Función Para Abrir o Cerrar Grippers
        global Estado_S
        global Estado_A
        global Estado_R
        if Identi=='E':
            Estado_S=not Estado_S
            Color(Estado_S,Gp_S,'E')
        elif Identi=='A':
            Estado_A=not Estado_A
            Color(Estado_A,Gp_A,'A')
        else:
            Estado_R=not Estado_R
            Color(Estado_R,Gp_R,'R')

def Red_Slider(Vec, Valor): #Función Para Redefinir Los Limites de Los Sliders De Cinematica Inversa
    Ident=Vec[0]
    if (Ident == 'S') or (Ident == 'A2') or (Ident =='A1'):
        Pes=Vec[1]
        Slider=Vec[2]
        Check=Vec[3]
        PosX=Vec[4]
        PosY=Vec[5]
    if Ident =='S':                                   #Redefinir Slider "Py_S" De Scara
        if Pes == 'I':
            Variable=Check_S_Valor
        elif Pes == 'T':
            Variable=Check_ST_Valor
            Check_A_PL.place_forget()
        LimitY_S=Ec.Limites_Y_S(Valor)
        Slider['from_']=str(LimitY_S[0])
        Slider['to']=str(LimitY_S[1])
        if LimitY_S[2] == 1 :
            Check.place(relx=PosX, rely=PosY)
        else:
            Check.place_forget()
        if Variable.get():                       #Evalua El Checkbox "-", Para Valores Negativos
            Slider['from_']=str(float(-1)*LimitY_S[1])
            Slider['to']=str(float(-1)*LimitY_S[0])
    if Ident =='A1':                                  #Redefinir Slider "Py_A" De Antropomórfico
        LimitY_A=Ec.Limites_Y_A(Valor)
        Slider['from_']=str(LimitY_A[1])
        Slider['to']=str(LimitY_A[0])
    if Ident =='A2':                                  #Redefinir Slider "Pz_A" De Antropomórfico
        if Pes == 'I':
            LimitZ=Ec.Limites_Z_A(Px_A.get(), Py_A.get())
            Variable=Check_A_Valor
        elif Pes == 'T':
            LimitZ=Ec.Limites_Z_A(Pl_x.get(), Pl_y.get())
            Variable=Check_AT_Valor
            Check_S_PL.place_forget()
        if LimitZ[2] == 1 :
            Check.place(relx=PosX, rely=PosY)
            if Variable.get():                   #Evalua El Checkbox "inf", Para Valores Del Limite Inferior
                Slider['from_']=str(LimitZ[1][1])
                Slider['to']=str(LimitZ[1][0])
            else:
                Slider['from_']=str(LimitZ[0][1])
                Slider['to']=str(LimitZ[0][0])
        else:
            Check.place_forget()
            Slider['from_']=str(LimitZ[1])
            Slider['to']=str(LimitZ[0])

def Cambio(Ident): #Función Para Detectar El Cambio De Los CheckBox
    if Ident == 'S':
        Red_Slider(['S', 'I', Py_S, Check_S, 3/16, 1/2+0.01], Px_S.get())
    elif Ident == 'A2':
        Red_Slider(['A2', 'I', Pz_A, Check_A, 3/16, 2/3+0.18], None)
    elif Ident == 'ST':
        Red_Slider(['S', 'T', Pl_y, Check_S_PL, 1/4-0.025, 1/3+0.22], Pl_x.get())
    elif Ident == 'AT':
        Red_Slider(['A2', 'T', Pl_z, Check_A_PL, 1/4-0.025, 2/3+0.15], None)

def Cine_Directa(Vector, Valor): #Función Para Enviar y Calcular Cinemática Directa Con Los Sliders
    Identi=Vector[0]
    if (bool(Identi.find('E')))==False:
        Matriz=Ec.Parametros(1, Qs1_S.get(), Qs2_S.get(), Qs3_S.get(), None, None, None)
        Wd.Llenado(Matriz, 1, 4)
    elif (bool(Identi.find('A')))==False:
        Matriz=Ec.Parametros(2, Qs1_A.get(), Qs2_A.get(), Qs3_A.get(), None, None, None)
        Wd.Llenado(Matriz, 5, 8)
    else:
        Matriz=Ec.Parametros(3, Qs1_R.get(), Qs2_R.get(), Qs3_R.get(), Qs4_R.get(), Qs5_R.get(), Qs6_R.get())
        Wd.Llenado(Matriz, 9, 15)
    hilos.Thread(target=Wd.Barra.Carga, args=(Vector[1],)).start()
    board.write(Identi.encode()+b','+ Valor.encode()+b'\n')
    print(Identi.encode()+b','+ Valor.encode()+b'\n')
    board2.write(Identi.encode()+b','+ Valor.encode()+b'\r\n')

def Cajas_DK(Vector): #Función Para Boton "Enviar". Se Calcula y Envia La Cinemática Directa Con Los Cuadros de Texto
    Identi=Vector[0]
    Valor=Vector[1]
    Enviar(Vector)
    if (bool(Identi[0].find('E')))==False:
        Matriz=Ec.Parametros(1, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), None, None, None)
        Wd.Llenado(Matriz, 1, 4)
    elif (bool(Identi[0].find('A')))==False:
        Matriz=Ec.Parametros(2, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), None, None, None)
        Wd.Llenado(Matriz, 5, 8)
    else:
        Matriz=Ec.Parametros(3, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), float(Valor[3].get()), float(Valor[4].get()), float(Valor[5].get()))
        Wd.Llenado(Matriz, 9, 15)

def Cine_Inversa(Vector): #Función Para Calcular Cinematica Inversa Del Scara
    Identi=Vector[0]
    Codos=Vector[1]
    if Identi=='S':
        Vec_IK=Ec.Calculo_Inversa(1, float(Px_S.get()), float(Py_S.get()), float(Pz_S.get()))
        Codos[0].Ubicacion(1/2,1/2,tk.N)
        Codos[1].Ubicacion(2/3, 1/2, tk.N)
        #Inserta Valores de Variables de Juntura en La Interfaz (Codo Abajo y Codo Arriba)
        q1_S.set(str(int(Vec_IK[0]/10)))
        q2_S_D.set(str(int(Vec_IK[1])))
        q3_S_D.set(str(int(Vec_IK[2])))
        q2_S_U.set(str(int(Vec_IK[3])))
        q3_S_U.set(str(int(Vec_IK[4])))
    elif Identi=='A':
        Vec_IK=Ec.Calculo_Inversa(2, float(Px_A.get()), float(Py_A.get()), float(Pz_A.get()))
        Codos[0].Ubicacion(1/2, 1/2, tk.N)
        Codos[1].Ubicacion(2/3, 1/2, tk.N)
        if Vec_IK[0]<(-1):
            Vec_IK[0]=360+Vec_IK[0]
        #Inserta Valores de Variables de Juntura en La Interfaz (Codo Abajo y Codo Arriba)
        q1_A.set(str(int(Vec_IK[0])))
        q2_A_D.set(str(int(Vec_IK[1])))
        q3_A_D.set(str(int(Vec_IK[2])))
        q2_A_U.set(str(int(Vec_IK[3])))
        q3_A_U.set(str(int(Vec_IK[4])))

    #Desabilitación de Botones de Envio Cinematica Inversa
    if Vec_IK[5] or Vec_IK[6]: #indar indab
        if  Vec_IK[6] == 1:#indab
            Codos[0].place_forget()
        if  Vec_IK[5] == 1:#indar
            Codos[1].place_forget()
        MsB.showwarning("Advertencia Selección Codo","""
        Una o ambas soluciones supera los limites mecanicos.
                                Varie el valor del punto
                     """)

def Enviar(Vector): #Función Donde Se Envia Los Datos
    Identi=Vector[0]
    Valor=Vector[1]
    for i in range (0,len(Identi)):
        hilos.Thread(target=Wd.Barra.Carga, args=(Vector[2],)).start()
        board.write(Identi[i].encode()+Valor[i].get().encode()+b'\n')
        board2.write(Identi[i].encode()+Valor[i].get().encode()+b'\r\n')
        tm.sleep(3)

def Jacobians(Barra): #Función Para Mostrar Los Jacobianos
    j_S=Ec.Jacobianos(1, Qs1_S.get(), Qs2_S.get(), Qs3_S.get())
    j_A=Ec.Jacobianos(2, Qs1_A.get(), Qs2_A.get(), Qs3_A.get())
    Matriz=[j_S[0], j_S[1], j_A[0], j_A[1]]
    hilos.Thread(target=Wd.Barra.Carga, args=(Barra,)).start()
    Wd.Llenado_Jaco(Matriz, 1, 4)

def elec_manipulador():#Funcion Para Elección de Manipulador
    selection=Despl_Mani.get()
    if selection == "Scara (PRR)":
        return 1
    else:
        return 2

def elec_codo():#Funcion Para Elección de codo
    selection=Despl_Codo.get()
    if selection == "Codo Abajo":
        return 1
    else:
        return 2

def plot_3d(pos_final_x, pos_final_y, pos_final_z):

    root_3d = tk.Tk()
    root_3d.wm_title("Plot 3D Efector Final")

    fig = Figure(figsize=(5, 5), dpi=100)

    canvas = FigureCanvasTkAgg(fig, master=root_3d)
    canvas.draw()
    ax = fig.add_subplot(111, projection="3d")
    ax.plot(pos_final_x, pos_final_y, pos_final_z)

    toolbar = NavigationToolbar2Tk(canvas, root_3d)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    tk.mainloop()

def Envio_Pl(Vectores_1, Vectores_2, Vectores_3):
    paso=(T_f.get()/(N_p.get()))
    if Despl_Mani.get() == "Scara (PRR)":
        board.write(b'Eb,'+"{:.4f}".format(int(Vectores_1[-1])).encode()+b'\n')
        board2.write(b'Eb,'+str(int(Vectores_1[-1])).encode()+b'\r\n')
        Time_Prisma=int(Vectores_1[-1])*(1.8)
        tm.sleep (Time_Prisma)
        Restante=T_f.get()-Time_Prisma
        paso=(Restante/N_p.get())
        for i in range(0,int(N_p.get())):
            board.write(b'Ebr,'+"{:.4f}".format(int(Vectores_2[i])).encode()+b'\n')
            board2.write(b'Ebr,'+str(int(Vectores_2[i])).encode()+b'\r\n')
            tm.sleep(paso/2)
            board.write(b'Eab,'+"{:.4f}".format(int(Vectores_3[i])).encode()+b'\n')
            board2.write(b'Eab,'+str(int(Vectores_3[i])).encode()+b'\r\n')
            tm.sleep(paso/2)
    else:
        for i in range(0,int(N_p.get())):
            board.write(b'Ab,'+"{:.4f}".format(int(Vectores_1[i])).encode()+b'\n')
            board2.write(b'Ab,'+str(int(Vectores_1[i])).encode()+b'\r\n')
            tm.sleep(paso/3)
            board.write(b'Abr,'+"{:.4f}".format(int(Vectores_2[i])).encode()+b'\n')
            board2.write(b'Abr,'+str(int(Vectores_2[i])).encode()+b'\r\n')
            tm.sleep(paso/3)
            board.write(b'Aab,'+"{:.4f}".format(int(Vectores_3[i])).encode()+b'\n')
            board2.write(b'Aab,'+str(int(Vectores_3[i])).encode()+b'\r\n')
            tm.sleep(paso/3)

def But_Perfiles(Ident):#Funcion Para Calcular La Generación de Trayectorias
    mani=elec_manipulador()
    codo=elec_codo()
    xini=float(P_xi.cget("text"))
    yini=float(P_yi.cget("text"))
    zini=float(P_zi.cget("text"))
    xfin=float(Pl_x.get())
    yfin=float(Pl_y.get())
    zfin=float(Pl_z.get())
    tip=Tipo.get()
    tfin=T_f.get()
    resolucion=N_p.get()
    if tip == 2:
        variable=[Vj_1.get(), Vj_2.get(), Vj_3.get()]
    elif tip == 3:
        variable=[Aj_1.get(), Aj_2.get(), Aj_3.get()]
    else:
        variable=[0, 0, 0]
    Vectores=Wd.Perfil(tip, mani, codo, tfin, xini, yini, zini, xfin, yfin, zfin, resolucion, variable)
    if Vectores[0] == 1: # vel
        MsB.showwarning(title="error", message="La magnitud de la velocidad supera la condición. \n Varie el los valores de la velocidad crucero ")
        for i in range (0, 3):
            if Vectores[2]==0:
                Vj_1["from_"]=(Vectores[1])+0.1
                Vj_1["to"]=(Vectores[1]*2)-0.1
            if Vectores[2]==1:
                Vj_2["from_"]=(Vectores[1])+0.1
                Vj_2["to"]=(Vectores[1]*2)-0.1
            if Vectores[2]==2:
                Vj_3["from_"]=(Vectores[1])+0.1
                Vj_3["to"]=(Vectores[1]*2)-0.1
            Vectores=Wd.Perfil(Tipo.get(), elec_manipulador(), elec_codo(), T_f.get(), float(P_xi.cget("text")), float(P_yi.cget("text")), float(P_zi.cget("text")), float(Pl_x.get()), float(Pl_y.get()), float(Pl_z.get()), N_p.get(), [Vj_1.get(), Vj_2.get(), Vj_3.get()])

    elif Vectores[0] == 2: #acel
        MsB.showwarning(title="error", message="La magnitud de la aceleración supera la condición. \n Varie el los valores de la aceleración crucero")
        for i in range (0, 3):
            if Vectores[2]==0:
                Aj_1["from_"]=(Vectores[1])+0.1
                Aj_1["to"]=(Vectores[1]*4)-0.1
            if Vectores[2]==1:
                Aj_2["from_"]=(Vectores[1])+0.1
                Aj_2["to"]=(Vectores[1]*4)-0.1
            if Vectores[2]==2:
                Aj_3["from_"]=(Vectores[1])+0.1
                Aj_3["to"]=(Vectores[1]*4)-0.1
            Vectores=Wd.Perfil(Tipo.get(), elec_manipulador(), elec_codo(), T_f.get(), float(P_xi.cget("text")), float(P_yi.cget("text")), float(P_zi.cget("text")), float(Pl_x.get()), float(Pl_y.get()), float(Pl_z.get()), N_p.get(), [Aj_1.get(), Aj_2.get(), Aj_3.get()])

    else:
        posx=np.empty(resolucion)
        posy=np.empty(resolucion)
        posz=np.empty(resolucion)
        for n in range(0, resolucion):
            if mani == 1:
                mat=Ec.Parametros(1, Vectores[1][n], Vectores[2][n], Vectores[3][n], None, None, None)
                vect_pos=Ec.Vec('C', 3, None, mat[0])
                posx[n]=vect_pos[0]
                posy[n]=vect_pos[1]
                posz[n]=vect_pos[2]
            else:
                mat=Ec.Parametros(2, Vectores[1][n], Vectores[2][n], Vectores[3][n], None, None, None)
                vect_pos=Ec.Vec('C', 3, None, mat[0])
                posx[n]=vect_pos[0]
                posy[n]=vect_pos[1]
                posz[n]=vect_pos[2]
        #Thread(target=envio_graf1(Vectores[1],Vectores[2],Vectores[3])).start()
        Gr1=Wd.Grafica(Fr_Graf, r'Posición $q_1$', "q[°]", 0, 0)
        Gr2=Wd.Grafica(Fr_Graf, r'Posición $q_2$', "q[°]", 1/3, 0)
        Gr3=Wd.Grafica(Fr_Graf, r'Posición $q_3$', "q[°]", 2/3, 0)
        Gr4=Wd.Grafica(Fr_Graf, r'Velocidad $w_1$', r'w$[rad/s]$', 0, 1/2)
        Gr5=Wd.Grafica(Fr_Graf, r'Velocidad $w_2$', r'w$[rad/s]$', 1/3, 1/2)
        Gr6=Wd.Grafica(Fr_Graf, r'Velocidad $w_3$', r'w$[rad/s]$', 2/3, 1/2)
        Gr1.Linea(resolucion, int(Vectores[1][0]), int(Vectores[1][-1]), int(T_f.get()), Vectores[1])
        Gr2.Linea(resolucion, int(Vectores[2][0]), int(Vectores[2][-1]), int(T_f.get()), Vectores[2])
        Gr3.Linea(resolucion, int(Vectores[3][0]), int(Vectores[3][-1]), int(T_f.get()), Vectores[3])
        Gr4.Linea(resolucion, 0, Vectores[4][int(resolucion/2)], int(T_f.get()), Vectores[4])
        Gr5.Linea(resolucion, 0, Vectores[5][int(resolucion/2)], int(T_f.get()), Vectores[5])
        Gr6.Linea(resolucion, 0, Vectores[6][int(resolucion/2)], int(T_f.get()), Vectores[6])
        P_xi.config(text=Pl_x.get())
        P_yi.config(text=Pl_y.get())
        P_zi.config(text=Pl_z.get())
        Datos_Temp(P_xi.cget("text"), P_yi.cget("text"), P_zi.cget("text"), 0)
        Envio_Pl(Vectores[1], Vectores[2], Vectores[3])
        plot_3d(posx, posy, posz)

#Objetos Principales
Ventana = tk.Tk()
Ventana.title('Controles de Manipuladores Roboticos')
width=Ventana.winfo_screenwidth()
height= Ventana.winfo_screenheight()
Ventana.geometry("%dx%d" % (width, height))
Panel_Pestañas = ttk.Notebook(Ventana)
Panel_Pestañas.pack(fill='both',expand='yes')

#Variables
Nombres= tk.StringVar() #Variable String Para Nombres
Nombres.set("""
Dario Delgado - 1802992 \n
Brayan Ulloa - 1802861 \n
Fernando Llanes - 1802878 \n
Karla Baron - 1803648 \n
Sebastian Niño - 1803558
""")
Reposo= tk.StringVar() #Variable String Para Mensaje Reposo
Reposo.set("Parte de reposo \r termina en reposo: \r Ti=0; Vi=0; Vf=0")
Wd.Variables_Matrices(15, 4, 4, "DK") #Variables Matrices DK
Wd.Variables_Matrices(4, 6, 3, "Jaco") #Variables Matrices Jacobianos Scara-Antropomórfico
Wd.Variables_Matrices(2, 6, 6, "JacoR") #Variables Matrices Jacobianos R
Estado_S=False
Estado_A=False
Estado_R=False
Check_S_Valor=tk.BooleanVar()
Check_A_Valor=tk.BooleanVar()
Check_ST_Valor=tk.BooleanVar()
Check_AT_Valor=tk.BooleanVar()

#Pestañas
Pestaña_Info=Wd.Pestañas(Panel_Pestañas, 'Portada')
Pestaña_Scara=Wd.Pestañas(Panel_Pestañas, 'Robot Scara (P2R)')
Pestaña_Antro3R=Wd.Pestañas(Panel_Pestañas, 'Robot Antropomórfico (3R)')
Pestaña_Antro6R=Wd.Pestañas(Panel_Pestañas, 'Robot Antropomórfico (6R)')
Pestaña_Trayectorias_Jacobiano=Wd.Pestañas(Panel_Pestañas, 'Trayectorias Por Jacobiano Inverso')
Pestaña_Jacobianos=Wd.Pestañas(Panel_Pestañas, 'Jacobiano')
Pestaña_Trayectorias=Wd.Pestañas(Panel_Pestañas, 'Planeación De Trayectorias')

#Fuentes
Fuente_12 = Wd.Fuentes("Lucida Grande", 12)
Fuente_15 = Wd.Fuentes("Lucida Grande", 15)
Fuente_25 = Wd.Fuentes("Lucida Grande", 25)
Fuente_Num = Wd.Fuentes("Palatino Linotype", 18)
Fuente_Num2 = Wd.Fuentes("Palatino Linotype", 12)
Fuente_Slider= Wd.Fuentes("Bookman Old Style", 12)

##################################Pestaña 1########################################
Fi=Wd.Frame(Pestaña_Info, 'GUI Para Controlar Manipuladores Robóticos', Fuente_12, 1, 1, 0, 0, None) #Frame
Wd.Labels(Fi, Nombres, None, None, None, None, Fuente_25, None).Ubicacion(1/2, 1/2, tk.CENTER)#Label-Nombres
#Com=Wd.Boton(Fi, 20, 5, 'COM Close', None).Ubicacion(1/2, 7/8, tk.CENTER)

#Imagenes
Logo= Wd.Imagenes('./Imagenes/LOGOUMNG.png').zoom(2)                        #Logo UMNG
tk.Label(Fi, image=Logo).place(relx=1/4, rely=1/2, anchor=tk.CENTER)
Icono= Wd.Imagenes('./Imagenes/icon.png').zoom(2)                           #Icono Robot
tk.Label(Fi, image=Icono).place(relx=3/4, rely=1/2, anchor=tk.CENTER)

##################################Pestaña 2########################################
Fr_DK_S=Wd.Frame(Pestaña_Scara, 'Cinemática Directa', Fuente_12, 1, 5/8, 0, 0, None)   #Frame Cinematica Directa
Fr_IK_S=Wd.Frame(Pestaña_Scara, 'Cinemática Inversa', Fuente_12, 1, 3/8, 0, 5/8, None) #Frame Cinematica Inversa

######Cinematica Directa######

#Barra De Progreso
Ba_S=Wd.Barra(Fr_IK_S, 300, 1/6, 0.98, 0.25, tk.E)

#Sliders
Qs1_S=Wd.Slider(Fr_DK_S, 1, 19, 1, 250, 34, 'Desplazamiento Base', Fuente_Slider, Cine_Directa, ['Eb',Ba_S])
Qs1_S.Ubicacion(0,0)
Qs2_S=Wd.Slider(Fr_DK_S, -90, 90, 10, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Ebr',Ba_S])
Qs2_S.Ubicacion(0, 1/3)
Qs3_S=Wd.Slider(Fr_DK_S, -90, 90, 10, 250, 34, 'Rotación Brazo', Fuente_Slider, Cine_Directa, ['Eab',Ba_S])
Qs3_S.Ubicacion(0, 2/3)
Qt1_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 0.11)
Qt2_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 1/3+0.11)
Qt3_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 2/3+0.11)
Qt_S=[Qt1_S, Qt2_S, Qt3_S]

#Matrices
Wd.Matrices(Fr_DK_S, "DK", 1, 4, 4, "Link 1", 1/2, 0, Fuente_12)
Wd.Matrices(Fr_DK_S, "DK", 2, 4, 4, "Link 2", 5/6, 0, Fuente_12)
Wd.Matrices(Fr_DK_S, "DK", 3, 4, 4, "Link 3", 1/2, 1/2, Fuente_12)
Wd.Matrices(Fr_DK_S, "DK", 4, 4, 4, "Total", 5/6, 1/2, Fuente_12)

#Botones
Wd.Boton(Fr_DK_S, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE)
Gp_S=Wd.Boton(Fr_DK_S, 15, 3, "Griper", "lime green", Gripper, 'E')
Gp_S.Ubicacion(4/6, 0.9, tk.CENTER)
Wd.Boton(Fr_DK_S, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Eb,','Ebr,','Eab,'], Qt_S, Ba_S]).Ubicacion(1/4+0.02, 0.9, tk.W)

######Cinematica Inversa######
#Sliders

Py_S=Wd.Slider(Fr_IK_S, -90, 90, 0.5, 250, 20, 'Py', Fuente_Slider, Red_Slider, ['N','N'])
Py_S.Ubicacion(0, 1/3)
Pz_S=Wd.Slider(Fr_IK_S, 0, 190, 10, 250, 20, 'Pz', Fuente_Slider, Red_Slider, ['N','N'])
Pz_S.Ubicacion(0, 2/3)
Check_S=Wd.Check(Fr_IK_S, '-', 3/16, 1/3+0.18, Cambio, 'S', Check_S_Valor)
Px_S=Wd.Slider(Fr_IK_S, -101.5, 345, 0.5, 250, 20, 'Px', Fuente_Slider, Red_Slider, ['S', 'I', Py_S, Check_S, 3/16, 1/2+0.01])
Px_S.Ubicacion(0, 0)

#Codo Abajo
Co_D_S=Wd.Frame(Fr_IK_S, "Codo Abajo", Fuente_12, 1/10, 1/2, 1/2, 0, tk.N)
q1_S=tk.StringVar()
q2_S_D=tk.StringVar()
q3_S_D=tk.StringVar()
qs_S_D=[q1_S, q2_S_D, q3_S_D]
Wd.Labels(Co_D_S, None, "d₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_D_S, q1_S, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_D_S, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_D_S, q2_S_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_D_S, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_D_S, q3_S_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Codo Arriba
Co_U_S=Wd.Frame(Fr_IK_S, "Codo Arriba", Fuente_12, 1/10, 1/2, 2/3, 0, tk.N)
q2_S_U=tk.StringVar()
q3_S_U=tk.StringVar()
qs_S_U=[q1_S, q2_S_U, q3_S_U]
Wd.Labels(Co_U_S, None, "d₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_U_S, q1_S, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_U_S, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_U_S, q2_S_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_U_S, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_U_S, q3_S_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Botones
Wd.Boton(Fr_IK_S, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE)
CodoD_S=Wd.Boton(Fr_IK_S, 12, 2, "Codo Abajo", "ivory3", Enviar, [['Eb,','Ebr,','Eab,'], qs_S_D, Ba_S])
CodoU_S=Wd.Boton(Fr_IK_S, 12, 2, "Codo Arriba", "ivory3", Enviar, [['Eb,','Ebr,','Eab,'], qs_S_U, Ba_S])
Wd.Boton(Fr_IK_S, 12, 8, "Calcular", "dim gray", Cine_Inversa, ['S', [CodoD_S, CodoU_S]]).Ubicacion(1/4+0.02, 1/2, tk.W)

##################################Pestaña 3########################################
Fr_DK_A=Wd.Frame(Pestaña_Antro3R, 'Cinemática Directa', Fuente_12, 1, 5/8, 0, 0, None)   #Frame Cinematica Directa
Fr_IK_A=Wd.Frame(Pestaña_Antro3R, 'Cinemática Inversa', Fuente_12, 1, 3/8, 0, 5/8, None) #Frame Cinematica Inversa

######Cinematica Directa######

#Barra De Progreso
Ba_A=Wd.Barra(Fr_IK_A, 300, 1/6, 0.98, 0.25, tk.E)

#Sliders
Qs1_A=Wd.Slider(Fr_DK_A, 0, 360, 10, 250, 34, 'Rotación Base', Fuente_Slider, Cine_Directa, ['Ab',Ba_A])
Qs1_A.Ubicacion(0, 0)
Qs2_A=Wd.Slider(Fr_DK_A, -90, 90, 10, 250, 34, 'Rotación Brazo', Fuente_Slider, Cine_Directa, ['Aab',Ba_A])
Qs2_A.Ubicacion(0, 2/3)
Qs3_A=Wd.Slider(Fr_DK_A, 0, 180, 10, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Abr',Ba_A])
Qs3_A.Ubicacion(0, 1/3)
Qt1_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 0.11)
Qt2_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 1/3+0.11)
Qt3_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 2/3+0.11)
Qt_A=[Qt1_A, Qt2_A, Qt3_A]

#Matrices
Wd.Matrices(Fr_DK_A, "DK", 5, 4, 4, "Link 1", 1/2, 0, Fuente_12)
Wd.Matrices(Fr_DK_A, "DK", 6, 4, 4, "Link 2", 5/6, 0, Fuente_12)
Wd.Matrices(Fr_DK_A, "DK", 7, 4, 4, "Link 3", 1/2, 1/2, Fuente_12)
Wd.Matrices(Fr_DK_A, "DK", 8, 4, 4, "Total", 5/6, 1/2, Fuente_12)

#Botones
Wd.Boton(Fr_DK_A, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE)
Gp_A=Wd.Boton(Fr_DK_A, 15, 3, "Griper", "lime green", Gripper, 'A')
Gp_A.Ubicacion(4/6, 0.9, tk.CENTER)
Wd.Boton(Fr_DK_A, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Ab,','Abr,','Aab,'], Qt_A, Ba_A]).Ubicacion(1/4+0.02, 0.9, tk.W)

######Cinematica Inversa######

#Sliders
Pz_A=Wd.Slider(Fr_IK_A, None, None, 0.5, 250, 20, 'Pz', Fuente_Slider, Red_Slider, ['N','N'])
Pz_A.Ubicacion(0, 2/3)
Check_A=Wd.Check(Fr_IK_A, 'Inf', 3/16, 2/3+0.18, Cambio, 'A2', Check_A_Valor)
Py_A=Wd.Slider(Fr_IK_A, None, None, 0.5, 250, 20, 'Py', Fuente_Slider, Red_Slider, ['A2', 'I', Pz_A, Check_A, 3/16, 2/3+0.18])
Py_A.Ubicacion(0, 1/3)
Px_A=Wd.Slider(Fr_IK_A, -197, 197, 0.5, 250, 20, 'Px', Fuente_Slider, Red_Slider, ['A1', 'I', Py_A, None, None, None])
Px_A.Ubicacion(0, 0)

#Codo Abajo
Co_D_A=Wd.Frame(Fr_IK_A, "Codo Abajo", Fuente_12, 1/10, 1/2, 1/2, 0, tk.N)
q1_A=tk.StringVar()
q2_A_D=tk.StringVar()
q3_A_D=tk.StringVar()
qs_A_D=[q1_A, q2_A_D, q3_A_D]
Wd.Labels(Co_D_A, None, "θ₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_D_A, q1_A, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_D_A, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_D_A, q2_A_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_D_A, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_D_A, q3_A_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Codo Arriba
Co_U_A=Wd.Frame(Fr_IK_A, "Codo Arriba", Fuente_12, 1/10, 1/2, 2/3, 0, tk.N)
q2_A_U=tk.StringVar()
q3_A_U=tk.StringVar()
qs_A_U=[q1_A, q2_A_U, q3_A_U]
Wd.Labels(Co_U_A, None, "θ₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_U_A, q1_A, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_U_A, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_U_A, q2_A_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_U_A, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_U_A, q3_A_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Botones
Wd.Boton(Fr_IK_A, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE)
CodoD_A=Wd.Boton(Fr_IK_A, 12, 2, "Codo Abajo", "ivory3", Enviar, [['Ab,','Abr,','Aab,'], qs_A_D, Ba_A])
CodoU_A=Wd.Boton(Fr_IK_A, 12, 2, "Codo Arriba", "ivory3", Enviar, [['Ab,','Abr,','Aab,'], qs_A_U, Ba_A])
Wd.Boton(Fr_IK_A, 12, 8, "Calcular", "dim gray", Cine_Inversa, ['A', [CodoD_A, CodoU_A]]).Ubicacion(1/4+0.02, 1/2, tk.W)

##################################Pestaña 4########################################

#Desplegable
Despl_R=Wd.Desplegable(Pestaña_Antro6R, ["Cinemática Directa", "Cinemática Inversa"])
Despl_R.Ubicacion(0, 0)
Despl_R.bind("<<ComboboxSelected>>",Despl_R.Cambio)
Fr_DK_R=Despl_R.Frame_DK
Fr_IK_R=Despl_R.Frame_IK
#####Cinematica Directa######

#Barra De Progreso
Ba_R=Wd.Barra(Fr_DK_R, 200, 1/15, 0.98, 3/4, tk.NE)

#Sliders
Qs1_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Primera Base', Fuente_Slider, Cine_Directa, ['Rb1',Ba_R])
Qs1_R.Ubicacion(0, 0)
Qs2_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Primer Brazo', Fuente_Slider, Cine_Directa, ['Rbr1',Ba_R])
Qs2_R.Ubicacion(0, 1/6)
Qs3_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Segundo Brazo', Fuente_Slider, Cine_Directa, ['Rbr2',Ba_R])
Qs3_R.Ubicacion(0, 2/6)
Qs4_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Segunda Base', Fuente_Slider, Cine_Directa, ['Rb2',Ba_R])
Qs4_R.Ubicacion(0, 3/6)
Qs5_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Rab',Ba_R])
Qs5_R.Ubicacion(0, 4/6)
Qs6_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Muñeca', Fuente_Slider, Cine_Directa, ['Rm',Ba_R])
Qs6_R.Ubicacion(0, 5/6)
Qt1_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 1/18+0.014)
Qt2_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 4/18+0.014)
Qt3_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 7/18+0.014)
Qt4_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 10/18+0.014)
Qt5_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 13/18+0.014)
Qt6_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 16/18+0.014)
Qt_R=[Qt1_R, Qt2_R, Qt3_R, Qt4_R, Qt5_R, Qt6_R]

#Matrices
Wd.Matrices(Fr_DK_R, "DK", 9, 4, 4, "Link 1", 1/2, 0, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 10, 4, 4, "Link 2", 5/6, 0, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 11, 4, 4, "Link 3", 1/2, 1/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 12, 4, 4, "Link 4", 5/6, 1/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 13, 4, 4, "Link 5", 1/2, 2/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 14, 4, 4, "Link 6", 5/6, 2/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 15, 4, 4, "Total", 2/3, 3/4, Fuente_12)

#Botones
Wd.Boton(Fr_DK_R, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE)
Gp_R=Wd.Boton(Fr_DK_R, 15, 3, "Griper", "lime green", Gripper, 'R')
Gp_R.Ubicacion(7/16, 3/4+0.1, tk.N)
Wd.Boton(Fr_DK_R, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Rb1,','Rbr1,','Rbr2,','Rb2,','Rab,','Rm,'], Qt_R, Ba_R]).Ubicacion(7/16, 3/4, tk.N)

######Cinematica Inversa######

#Sliders
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Px', Fuente_Slider, None, None).Ubicacion(0, 0)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Py', Fuente_Slider, None, None).Ubicacion(0, 1/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Pz', Fuente_Slider, None, None).Ubicacion(0, 2/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Alfa', Fuente_Slider, None, None).Ubicacion(0, 3/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Beta', Fuente_Slider, None, None).Ubicacion(0, 4/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Gamma', Fuente_Slider, None, None).Ubicacion(0, 5/6)

#Botones
Wd.Boton(Fr_IK_R, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE)

##################################Pestaña 5########################################

Fr_T_J=Wd.Frame(Pestaña_Trayectorias_Jacobiano, 'Planificación de Trayectorias Por Jacobiano Inverso', Fuente_12, 1, 1, 0, 0, None)   #Frame Jacobiano

##################################Pestaña 6########################################

Fr_J=Wd.Frame(Pestaña_Jacobianos, 'Jacobianos', Fuente_12, 1, 1, 0, 0, None)   #Frame Jacobiano

#Barra De Progreso
Ba_J=Wd.Barra(Fr_J, 300, 1/15, 1/2, 1/3, tk.N)

#Matrices
Wd.Matrices(Fr_J, "Jaco", 1, 6, 3, "Jacobiano Scara Geométrico", 1/4, 0, Fuente_12)
Wd.Matrices(Fr_J, "Jaco", 2, 6, 3, "Jacobiano Scara Analítico", 3/4, 0, Fuente_12)
Wd.Matrices(Fr_J, "Jaco", 3, 6, 3, "Jacobiano Antropomórfico Geométrico", 1/4, 1/3, Fuente_12)
Wd.Matrices(Fr_J, "Jaco", 4, 6, 3, "Jacobiano Antropomórfico Analítico", 3/4, 1/3, Fuente_12)
Wd.Matrices(Fr_J, "JacoR", 1, 6, 6, "Jacobiano Antropomórfico 6R Geométrico", 1/4, 2/3, Fuente_12)
Wd.Matrices(Fr_J, "JacoR", 2, 6, 6, "Jacobiano Antropomórfico 6R Analítico", 3/4, 2/3, Fuente_12)

#Botones
#Wd.Boton(Fr_J, None, None, "Instrucciones", "LightYellow2").Ubicacion(1, 1, tk.SE)
Wd.Boton(Fr_J, 15, 3, "Mostrar", "dim gray", Jacobians, Ba_J).Ubicacion(1/2, 1/2, tk.N)

##################################Pestaña 7########################################

Fr_T=Wd.Frame(Pestaña_Trayectorias, 'Datos de Entrada', Fuente_12, 1, 1/4, 0, 0, None)   #Frame Datos Trayectorias

#Desplegables
Despl_Mani=Wd.Desplegable(Fr_T, ["Scara (PRR)", "Antropomórfico (RRR)"])
Despl_Mani.Ubicacion(0, 0)
Despl_Mani.bind("<<ComboboxSelected>>",Show_Sliders)
Despl_Codo=Wd.Desplegable(Fr_T, ["Codo Arriba", "Codo Abajo"])
Despl_Codo.bind("<<ComboboxSelected>>",Show_Perfiles)

#Label Información Importante (Parte de Reposo)
Wd.Labels(Fr_T, Reposo, None, 1, "solid", None, Fuente_15, None).Ubicacion(4/16, 0, None)

#Puntos Iniciales-Finales
#Labels
P_xi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None)
P_yi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None)
P_zi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None)
P_x= Wd.Labels(Fr_T, None, "Px", None, None, None, None, None)
P_y= Wd.Labels(Fr_T, None, "Py", None, None, None, None, None)
P_z= Wd.Labels(Fr_T, None, "Pz", None, None, None, None, None)

#Buttons
Tipo=tk.IntVar()
Cuadratico=Wd.Radio(Fr_T, "Perfil Cuadrático", Fuente_12, 1, Tipo, 15, Show_Datos)
TrapezoidalI=Wd.Radio(Fr_T, "Perfil Trapezoidal I", Fuente_12, 2, Tipo, 15, Show_Datos)
TrapezoidalII=Wd.Radio(Fr_T, "Perfil Trapezoidal II", Fuente_12, 3, Tipo, 15, Show_Datos)
Calcular_PT=Wd.Boton(Fr_T, 12, None, "Calcular", "dim gray", But_Perfiles, None)
#Wd.Boton(Fr_T, None, None, "Instrucciones", "LightYellow2").Ubicacion(1, 1, tk.SE)

#Barra De Progreso
Br_Pl=Wd.Barra(Fr_T, 150, 1/8, 5/16, 1, tk.S)

#Sliders
Check_S_PL=Wd.Check(Fr_T, '-', 1/4-0.025, 1/3+0.22, Cambio, 'ST', Check_ST_Valor)
Check_A_PL=Wd.Check(Fr_T, 'Inf', 1/4-0.025, 2/3+0.15, Cambio, 'AT', Check_AT_Valor)
Pl_x=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Alter_Sliders, 'A1')
Pl_y=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Alter_Sliders, 'A2')
Pl_z=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Show_Codo, None)
T_f=Wd.Slider(Fr_T, 15, 40, 1, 180, 20, None, None, Show_Graficas, None)
N_p=Wd.Slider(Fr_T, 10, 100, 10, 180, 20, None, None, Show_Graficas, None)
Vj_1=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Vj_2=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Vj_3=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Aj_1=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Aj_2=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Aj_3=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)

# #Titulos
P_inicial=Wd.Labels(Fr_T, None, "Puntos Iniciales", None, None, 12, Fuente_Num2, None)
P_final=Wd.Labels(Fr_T, None, "Puntos Finales", None, None, 12, Fuente_Num2, None)
T_Codo=Wd.Labels(Fr_T, None, "Elección Codo", None, None, 12, Fuente_Num2, None)
TT_f=Wd.Labels(Fr_T, None, "Tf", None, None, None, Fuente_Num2, None)
TN_p=Wd.Labels(Fr_T, None, "Np", None, None, None, Fuente_Num2, None)
TVc_1=Wd.Labels(Fr_T, None, "Vc1", None, None, None, Fuente_Num2, None)
TVc_2=Wd.Labels(Fr_T, None, "Vc2", None, None, None, Fuente_Num2, None)
TVc_3=Wd.Labels(Fr_T, None, "Vc3", None, None, None, Fuente_Num2, None)
TAc_1=Wd.Labels(Fr_T, None, "Ac1", None, None, None, Fuente_Num2, None)
TAc_2=Wd.Labels(Fr_T, None, "Ac2", None, None, None, Fuente_Num2, None)
TAc_3=Wd.Labels(Fr_T, None, "Ac3", None, None, None, Fuente_Num2, None)

Fr_Graf=Wd.Frame(Pestaña_Trayectorias, 'Gráficas', Fuente_12, 1, 3/4, 0, 1/4, None)   #Frame Graficas

#Ventana.attributes('-fullscreen',True)
Ventana.mainloop()


import torch
import numpy as np
from copy import deepcopy
from typing import List, Optional, Tuple
from torch.utils.data import DataLoader
from supervised.utils import ids, keys, typeddicts
from supervised import saving, data, networks

VERBOSE = False  # Default: whether the code output should be verbose
NR_EPOCHS = 50  # Default max number of epochs for training in case of no early stopping
EARLY_STOPPING_PATIENCE = 5  # Number of epochs to be patient before early stopping the training

def train_epoch_multi_readout(model: networks.classes.MultitaskLearner, data_loader: DataLoader,
                              optimizer: torch.optim.Optimizer, track_pmdd: Optional[bool] = False,
                              training_tracker: Optional[typeddicts.TrackingOutcome] = None,
                              train_params: Optional[typeddicts.TrainParameters] = None,
                              pmdd_dataset: Optional[data.load.DatasetType] = None,
                              validation_dl: Optional[typeddicts.DL] = None
                              ) -> Tuple[List[float], typeddicts.TrackingOutcome]:

    # List to store the train loss for each batch
    loss_list = []
    for batch_idx, ((data_batch, _), (task, targets)) in enumerate(data_loader):
        optimizer.zero_grad()
        out = model.forward(data_batch)
        if len(model.rbs) != 1:
            out = torch.gather(out, 0, torch.add(task.view(1, -1), train_params[keys.K_FIRST_TASK_ID])).reshape(-1)

        loss = networks.evaluate.mse_loss(out, targets)
        loss.backward()
        optimizer.step()
        loss_list += [float(loss.detach())]
        if track_pmdd:
            if (batch_idx + 1) in networks.evaluate.PMDD_TRACK_BATCHES:
                training_tracker = networks.evaluate.track_network(model=model, pmdd_dataset=pmdd_dataset,
                                                                   training_tracker=training_tracker,
                                                                   train_loss=loss_list[-1],
                                                                   validation_dl=validation_dl,
                                                                   train_params=train_params)

    return loss_list, training_tracker

def train_epoch_context_learner(model: networks.classes.MultitaskLearner, data_loader: DataLoader,
                                optimizer: torch.optim.Optimizer, track_pmdd: Optional[bool] = False,
                                training_tracker: Optional[typeddicts.TrackingOutcome] = None,
                                train_params: Optional[typeddicts.TrainParameters] = None,
                                pmdd_dataset: Optional[data.load.DatasetType] = None,
                                validation_dl: Optional[typeddicts.DL] = None
                                ) -> Tuple[List[float], typeddicts.TrackingOutcome]:

    # List to store the train loss for each batch
    loss_list = []

    # Train one batch at a time
    for batch_idx, ((data_batch, _), (tasks, targets)) in enumerate(data_loader):
        optimizer.zero_grad()
        out = model.forward(data_batch, tasks + train_params[keys.K_FIRST_TASK_ID]).reshape(-1)
        loss = networks.evaluate.mse_loss(out, targets)
        loss_list += [float(loss.detach())]
        loss.backward()
        optimizer.step()

        # Track pmdd loss, validation performance & train loss
        if track_pmdd:
            if (batch_idx + 1) in networks.evaluate.PMDD_TRACK_BATCHES:
                training_tracker = networks.evaluate.track_network(model=model, pmdd_dataset=pmdd_dataset,
                                                                   training_tracker=training_tracker,
                                                                   train_loss=loss_list[-1],
                                                                   validation_dl=validation_dl,
                                                                   train_params=train_params)

    return loss_list, training_tracker

def train_epoch(model: networks.classes.MultitaskLearner, data_loader: DataLoader, optimizer: torch.optim.Optimizer,
                prog_params: typeddicts.ProgramParameters, train_params: typeddicts.TrainParameters,
                save_params: typeddicts.SavingParameters, pmdd_dataset: data.load.DatasetType,
                validation_dl: Optional[typeddicts.DL] = None, track_pmdd: Optional[bool] = False) -> List[float]:
    # Initialize the tracker for pmdd loss, validation performance & train loss to a database
    if track_pmdd:
        assert validation_dl is not None
        training_tracker = networks.evaluate.init_track_network(model=model, train_params=train_params,
                                                                pmdd_dataset=pmdd_dataset,
                                                                validation_dl=validation_dl)
    else:
        training_tracker = None

    # Train for one epoch
    if prog_params[keys.K_MODEL_ID] == ids.ID_MULTI_READOUT:
        loss_list, training_tracker = train_epoch_multi_readout(
            model=model, data_loader=data_loader, optimizer=optimizer, track_pmdd=track_pmdd, train_params=train_params,
            training_tracker=training_tracker, pmdd_dataset=pmdd_dataset, validation_dl=validation_dl)
    else:
        loss_list, training_tracker = train_epoch_context_learner(
            model=model, data_loader=data_loader, optimizer=optimizer, track_pmdd=track_pmdd, train_params=train_params,
            pmdd_dataset=pmdd_dataset, validation_dl=validation_dl)

    # Save the tracked pmdd loss, validation performance & train loss to a database
    if track_pmdd:
        saving.save.save_first_epoch_batches_pmdd(prog_params=prog_params,
                                                  train_params=train_params,
                                                  save_params=save_params,
                                                  tracked_pmdd_batches=training_tracker)

    return loss_list

def train_model(model: networks.classes.MultitaskLearner, train_data: data.datasets.KTaskNClassMDatasetData,
                validation_data: data.datasets.KTaskNClassMDatasetData, optimizer: torch.optim.Optimizer,
                prog_params: typeddicts.ProgramParameters, train_params: typeddicts.TrainParameters,
                save_params: typeddicts.SavingParameters, verbose: Optional[bool] = VERBOSE
                ) -> Tuple[networks.classes.MultitaskLearner, typeddicts.PerformanceOutcome]:
    # Prepare to evaluate best time to stop training
    validation_data_loader, nr_samples = data.load.get_dataloader(validation_data)
    validation_dl: typeddicts.DL = {keys.K_NUMBER_SAMPLES: nr_samples,
                                    keys.K_VALIDATION_DATALOADER: validation_data_loader}
    best_model = deepcopy(model)
    best_validation_performance = -1.
    best_validation_loss = -1.
    stagnation_counter = 0
    training_tracker = None
    if save_params[keys.K_SAVE_PMDD_LOSS]:
        if save_params[keys.K_PMDD_LOSS_TRACK_DATASET] in [ids.ID_EMNIST, ids.ID_K49, ids.ID_CIFAR100]:
            track_dataset = data.load.get_dataset(save_params[keys.K_PMDD_LOSS_TRACK_DATASET], False).data.reshape(
                [-1, data.datasets.n_input_dimension(save_params[keys.K_PMDD_LOSS_TRACK_DATASET])])
        else:
            raise NotImplementedError(f"{save_params[keys.K_PMDD_LOSS_TRACK_DATASET]} track pmdd loss")

        if save_params[keys.K_SAVE_PMDD_LOSS] is not None:
            training_tracker = {keys.K_TRACKED_TRAIN_LOSS: [], keys.K_TRACKED_VALIDATION_PERFORMANCE: [],
                                keys.K_TRACKED_PMDD_LOSS: []}
            pmdd_loss = networks.evaluate.get_pmdd_loss(dataset=track_dataset,
                                                        weights=np.transpose(model.ws[0].detach().numpy()))
            training_tracker[keys.K_TRACKED_PMDD_LOSS] += [pmdd_loss]
            print(f"Epoch 0 had pmdd L2 {pmdd_loss}")
    else:
        track_dataset = None

    # Train epochs until performance stops to improve
    for epoch in range(1, NR_EPOCHS + 1):
        data_loader = DataLoader(train_data, batch_size=train_params[keys.K_BATCH_SIZE], shuffle=True)

        # Train for one epoch
        if epoch == 1:
            train_loss = train_epoch(model=model, data_loader=data_loader, optimizer=optimizer, prog_params=prog_params,
                                     train_params=train_params, save_params=save_params, pmdd_dataset=track_dataset,
                                     validation_dl=validation_dl, track_pmdd=save_params[keys.K_SAVE_PMDD_LOSS])
        else:
            train_loss = train_epoch(model=model, data_loader=data_loader, optimizer=optimizer, prog_params=prog_params,
                                     train_params=train_params, save_params=save_params, pmdd_dataset=track_dataset)

        # Evaluate model performance on validation dataset
        validation_performance, validation_loss = networks.evaluate.evaluate_performance(
            model_id=prog_params[keys.K_MODEL_ID],
            model=model,
            dataset=validation_data_loader,
            nr_samples=nr_samples,
            task_id0=train_params[keys.K_FIRST_TASK_ID])

        if verbose:
            print(f"Epoch {epoch} had training loss {train_loss} and validation performance {validation_performance}%")

        if save_params[keys.K_SAVE_PMDD_LOSS]:
            training_tracker[keys.K_TRACKED_TRAIN_LOSS] += [train_loss]
            training_tracker[keys.K_TRACKED_VALIDATION_PERFORMANCE] += [validation_performance]
            pmdd_loss = networks.evaluate.get_pmdd_loss(dataset=track_dataset,
                                                        weights=np.transpose(model.ws[0].detach().numpy()))
            training_tracker[keys.K_TRACKED_PMDD_LOSS] += [pmdd_loss]
            print(f"Epoch {epoch} had "
                  f"training loss {sum(train_loss)}, "
                  f"validation performance {validation_performance}% and "
                  f"pmdd L2 {pmdd_loss}")

        # Check whether performance is still improving and stop training otherwise
        if validation_performance > best_validation_performance:
            stagnation_counter = 0
            best_validation_performance = validation_performance
            best_validation_loss = validation_loss
            best_model = deepcopy(model)
        else:
            stagnation_counter += 1
            if stagnation_counter >= EARLY_STOPPING_PATIENCE:
                if verbose:
                    print(f"Early stopping training at epoch {epoch} "
                          f"with validation performance of {best_validation_performance}%")
                break

    # Save the pmdd, train and validation losses during training epochs (if the saving parameters require it)
    saving.save.save_train_epochs_pmdd(prog_params=prog_params, train_params=train_params, save_params=save_params,
                                       tracked_pmdd_epochs=training_tracker)

    # Evaluate training performance
    train_performance, train_loss = networks.evaluate.evaluate_performance(model_id=prog_params[keys.K_MODEL_ID],
                                                                           model=best_model,
                                                                           dataset=train_data,
                                                                           task_id0=train_params[keys.K_FIRST_TASK_ID])

    outcome: typeddicts.PerformanceOutcome = {keys.K_TRAIN_PERFORMANCE: train_performance,
                                              keys.K_TRAIN_LOSS: train_loss,
                                              keys.K_VALIDATION_PERFORMANCE: best_validation_performance,
                                              keys.K_VALIDATION_LOSS: best_validation_loss}

    return best_model, outcome

def get_optimizer(training_type: str, model: networks.classes.MultitaskLearner, train_params: typeddicts.TrainParameters
                  ) -> torch.optim.Optimizer:
    parameters = None
    optimizer = None

    # Train both shared and contextual parameters
    if ids.ID_TRAIN in training_type:
        lr = train_params[keys.K_SHARED_PARAM_LEARNING_RATE]

        if ids.ID_SINGLE_TASK in training_type:
            optimizer = torch.optim.Adam(model.parameters(), lr)

        elif ids.ID_CONTEXT_B_SHARED_W in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws},
                                          {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_G_SHARED_BW in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs},
                                          {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_G_SHARED_XW in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs},
                                          {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_G_SHARED_BXW in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs}, {"params": model.bs},
                                          {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_BG_SHARED_W in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws},
                                          {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]},
                                          {"params": model.gs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_M_SHARED_BW in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.bs},
                                          {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_M_SHARED_XW in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs},
                                          {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_M_SHARED_BXW in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws}, {"params": model.xs}, {"params": model.bs},
                                          {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        elif ids.ID_CONTEXT_BM_SHARED_W in training_type:
            optimizer = torch.optim.Adam([{"params": model.ws},
                                          {"params": model.bs, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]},
                                          {"params": model.ms, "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                         lr)

        # Train multiple labels with individual readout neurons each all at the same time
        elif ids.ID_MULTI_READOUT in training_type:
            optimizer = torch.optim.Adam([{"params": [w for w in model.ws] + [b for b in model.bs]},
                                          {"params": [r for r in model.rs] + [rb for rb in model.rbs],
                                           "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}], lr)

    # Train only contextual parameters
    elif ids.ID_TRANSFER in training_type:
        lr = train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]
        if "deepen" in training_type:
            if ids.ID_CONTEXT_B_SHARED_W in training_type:
                optimizer = torch.optim.Adam([{"params": model.ws[1:]},
                                              {"params": model.bs,
                                               "lr": train_params[keys.K_CONTEXT_PARAM_LEARNING_RATE]}],
                                             train_params[keys.K_SHARED_PARAM_LEARNING_RATE])
            else:
                raise NotImplementedError

        elif ids.ID_CONTEXT_B_SHARED_W in training_type:
            parameters = model.bs

        elif ids.ID_CONTEXT_BG_SHARED_W in training_type:
            optimizer = torch.optim.Adam([{"params": model.bs, "lr": lr},
                                          {"params": model.gs, "lr": lr}], lr)

        elif ids.ID_CONTEXT_G_SHARED_BW in training_type or ids.ID_CONTEXT_G_SHARED_XW in training_type \
                or ids.ID_CONTEXT_G_SHARED_BXW in training_type:
            parameters = model.gs

        # Train only readout neurons on top of a fixed trunk
        elif ids.ID_MULTI_READOUT in training_type:
            parameters = [r for r in model.rs] + [rb for rb in model.rbs]

    else:
        raise ValueError(training_type)

    if optimizer is None:
        optimizer = torch.optim.Adam(parameters, lr)

    return optimizer


#Micah lee 03/12/18

media_type = input("what is the media type? ")
title = input("what is the title ")
des = input("give me a brief description ")
yr = str(input("what year was it created "))
rating = float(input(" what rating would you give this media type (1/10) " ))
new_list = [ title, des, yr, rating ]
if media_type == "Book":
    print (new_list)
elif media_type == "movies":
     print (new_list)


'''
Slakeys Surf Alert

Add Users with the argument "add" "user name * email * surf spot name * surf spot url"

Run with the argument "run"

'''
import sys
from SurfAlertUtils import *

if __name__ == "__main__":
	args = sys.argv
	args.pop(0)
	if len(args) == 0:
		print("Welcome to Slakey\'s Surf Alert. If you have not added a user, please input \"add\" \"user\" \"email\" \"surfspot\" \"url\". If you want to run just input \"run\"")
	elif args[0] == "run":
		run()
	elif args[0] == "add":
		adduser(args[1:])


from itertools import permutations
import cProfile

#
#make permutation of array
#

list = [1,2,3,4]

listPermutations =  permutations(list)
for permutation in listPermutations:
    print(permutation)

#
#count number of permutations
#

listPermutations =  permutations(list)
count = 0
for permutation in listPermutations:
    count += 1
print(len(list), count)

#
#check the performance and undestand
# how fast the space of permutations grows
#

def faculty(n):
    if n <= 1:
        return n
    else:
        return faculty(n-1)+n

def counter(n):
    count = 0
    for i in range(n):
        count += 1

    return count

cProfile.run("counter(faculty(10))")


#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""code_info
@Time    : 2020 2020/7/9 13:15
@Author  : Blanc
@File    : double_color_ball.py
"""
# 程序运行之后，从1‐64中挑选5个数作为彩票的抽奖结果
import random

a = list()

for i in range(0, 5):
    b = random.randint(1, 64)
    a.append(b)
print('双色球号开奖：', a)


#!/usr/bin/env python3
#

import sys, argparse
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True

def h2pgf(h):
    """ Convert TH1 into pgfplot data with error bars
    input: xmin xmax y ey
    output: x ex y ey
    ex = (xmax+xmin)/2
    """
    nbins = h.GetNbinsX()

#    print("# \\begin{axis}")
#    print("# \\addplot[const plot mark mid, black, solid, no markers, error bars/.cd, y dir=both, y explicit, error mark=none]")
#    print(" coordinates {")
    print("x ex y ey")
    for b in range(1, nbins+1):
        x = h.GetBinCenter(b)
        ex = h.GetBinWidth(b)/2.0
        y = h.GetBinContent(b)
        ey = h.GetBinError(b)
# print(x,ex,y,ey)
        if y>0.0:
            print(x, ex, y, ey)

def g2pgf(h):
    """ Convert TGraph into pgfplot data """

    N = h.GetN()

    print("\\begin{axis}")
    print("\\addplot[ultra thick]")
    print(" coordinates {")
    print("x ex y ey")
    for b in range(N):
        x = h.GetX()[b]
        y = h.GetY()[b]
        print(x, y)
    print("};")
    print("\\addlegendentry{TGraph};")

def main():
    """ A script to convert TH1 and TGraph into a pgfplot format """

    parser = argparse.ArgumentParser(description=main.__doc__, epilog='Homepage: https://github.com/kbat/mc-tools')
    parser.add_argument('root', type=str, help='ROOT file')
    parser.add_argument('hist', type=str, help='histogram name')
    args = parser.parse_args()

    f = ROOT.TFile(args.root)
    f.ls()
    h = f.Get(args.hist)

    if h.InheritsFrom("TH1"):
        h2pgf(h)
    elif h.InheritsFrom("TGraph"):
        g2pgf(h)

if __name__ == "__main__":
    sys.exit(main())


import rospy
from MyStatics.RealTimePlotter import RealTimePlotter
from MyStatics.GaussianPlotter import GaussPlot
from FaultDetection import ChangeDetection
from geometry_msgs.msg import AccelStamped
from dynamic_reconfigure.server import Server
from accelerometer_ros.cfg import accelerometerGaussConfig
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

class AccGaussCUSUM(RealTimePlotter,ChangeDetection,GaussPlot):
    def __init__(self, max_samples = 500, pace = 2, cusum_window_size = 10 ):
        self.data_ = []
        self.data_.append([0,0,0])
        self.i = 0
        self.msg = 0
        self.window_size = cusum_window_size
        RealTimePlotter.__init__(self,max_samples,pace)
        ChangeDetection.__init__(self,3)
        GaussPlot.__init__(self )
        rospy.init_node("accelerometer_gauss_cusum", anonymous=True)
        rospy.Subscriber("accel", AccelStamped, self.accCB)
        self.dyn_reconfigure_srv = Server(accelerometerGaussConfig, self.dynamic_reconfigureCB)

        plt.legend()
        plt.show()
        rospy.spin()
        plt.close("all")

    def dynamic_reconfigureCB(self,config, level):
        self.window_size = config["window_size"]
        return config

    def accCB(self, msg):
        while (self.i< self.window_size):
            self.addData([msg.accel.linear.x,msg.accel.linear.y, msg.accel.angular.z])
            self.i = self.i+1
            if len(self.samples) is self.max_samples:
                self.samples.pop(0)
            return
        self.i=0
        self.changeDetection(len(self.samples))
        cur = np.array(self.cum_sum, dtype = object)
        self.call(np.mean(self.samples, axis=0),np.var(self.samples, axis=0))
        """
        THIS IS NOT REALLY WORKING
        x1 = np.linspace(-140, 140, len(self.s_z))
        print(len(x1), len(np.sort(self.s_z)))
        plt.scatter([x1,x1,x1],np.sort(self.s_z))
        """
        x = np.linspace(-140, 140, 200)
        y = np.array([i.pdf(x) for i in self.rv])
        self.update(msg.header.seq,x.tolist(),y.T.tolist())


import collections
import functools
from operator import mul

def tokenize(s: str):
    tokens = []
    words = s.strip().split()
    for word in words:
        if word.startswith("("):
            tokens.append(word[0])
            tokens.extend(tokenize(word[1:]))
        elif word.endswith(")"):
            tokens.extend(tokenize(word[:-1]))
            tokens.append(word[-1])
        elif word in "+*":
            tokens.append(word)
        else:
            tokens.append(int(word))
    return tokens

def weird_math_a_helper(tokens):
    ans = None
    op = None
    while len(tokens) > 0:
        token = tokens.popleft()
        if token == ")":
            break
        elif token in ("*", "+"):
            op = token
        else:
            n = weird_math_a_helper(tokens) if token == "(" else token
            if ans is None:
                ans = n
            elif op == "+":
                ans += n
            elif op == "*":
                ans *= n
    return ans

def weird_math_a(problem):
    return weird_math_a_helper(collections.deque(tokenize(problem)))

def weird_math_b_helper(tokens):
    sums = []
    ans = None
    op = None
    while len(tokens) > 0:
        token = tokens.popleft()
        if token == ")":
            break
        elif token == "*":
            sums.append(ans)
            ans = None
            op = None
        elif token == "+":
            op = token
        else:
            n = weird_math_b_helper(tokens) if token == "(" else token
            if ans is None:
                ans = n
            elif op == "+":
                ans += n
    sums.append(ans)
    return functools.reduce(mul, sums, 1)

def weird_math_b(problem):
    return weird_math_b_helper(collections.deque(tokenize(problem)))

def parta(txt):
    return sum(weird_math_a(line) for line in txt.splitlines())

def partb(txt):
    return sum(weird_math_b(line) for line in txt.splitlines())

if __name__ == "__main__":
    from aocd import data

    print(f"parta: {parta(data)}")
    print(f"partb: {partb(data)}")


import unittest
from car_simulation import Car, Field, main
from unittest.mock import patch
from io import StringIO

class TestCar(unittest.TestCase):
    def test_change_direction(self):
        car = Car("TestCar", 0, 0, "N", "F")
        car.change_direction("R")
        self.assertEqual(car.direction, "E")

    def test_move_within_field(self):
        field = Field(5, 5)
        car = Car("TestCar", 2, 2, "N", "F")
        car.move(field)
        self.assertEqual((car.x, car.y), (2, 3))

    def test_move_out_of_bounds(self):
        field = Field(5, 5)
        car = Car("TestCar", 4, 4, "E", "F")
        car.move(field)
        self.assertEqual((car.x, car.y), (4, 4))  # Should not move out of bounds

    def test_execute_commands(self):
        field = Field(5, 5)
        car = Car("TestCar", 0, 0, "N", "F")
        car.execute_commands(field)
        self.assertEqual(car.direction, "N")
        self.assertEqual((car.x, car.y), (0, 1))

    def test_execute_empty_commands(self):
        field = Field(5, 5)
        car = Car("TestCar", 0, 0, "N", "")
        car.execute_commands(field)
        self.assertEqual((car.x, car.y), (0, 0))  # Should not move with empty commands

    def test_get_status(self):
        car = Car("TestCar", 3, 3, "W", "FFL")
        status = car.get_status()
        self.assertEqual(status, "TestCar, (3, 3) W, FFL")

    def test_collide(self):
        car = Car("TestCar", 2, 2, "S", "F")
        car.collid(1, "AnotherCar")
        self.assertTrue(car.collided)
        self.assertEqual(car.step, 1)
        self.assertEqual(car.collided_with, "AnotherCar")

class TestField(unittest.TestCase):
    def test_add_car_within_field(self):
        field = Field(5, 5)
        car = Car("TestCar", 1, 1, "N", "F")
        field.add_car(car)
        self.assertIn(car, field.cars)

    def test_add_car_out_of_bounds(self):
        field = Field(5, 5)
        car = Car("TestCar", 6, 6, "N", "F")
        field.add_car(car)
        self.assertNotIn(car, field.cars)

    def test_add_car_collision(self):
        field = Field(5, 5)
        car1 = Car("Car1", 2, 2, "N", "F")
        car2 = Car("Car2", 2, 2, "S", "F")
        field.add_car(car1)
        field.add_car(car2)
        self.assertNotIn(car2, field.cars)  # Car2 should not be added due to collision

    def test_is_within_field(self):
        field = Field(5, 5)
        self.assertTrue(field.is_within_field(2, 3))
        self.assertFalse(field.is_within_field(6, 6))

class TestCarSimulation(unittest.TestCase):
    @patch("builtins.input", side_effect=["10 10", "1", "A", "1 2 N", "FFRFFFFRRL", "2", "2"])
    def test_simulation_with_single_car(self, mock_input):
        with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
            main()

        output = mock_stdout.getvalue().strip()

        self.assertIn("Your current list of cars are:", output)
        self.assertIn("- A, (1, 2) N, FFRFFFFRRL", output)
        self.assertIn("After simulation, the result is:", output)
        self.assertIn("- A, (5, 4) S", output)

    @patch("builtins.input", side_effect=["10 10", "1", "A", "1 2 N", "FFRFFFFRRL", "1", "B", "7 8 W", "FFLFFFFFFF", "2", "2"])
    def test_simulation_with_multiple_car(self, mock_input):
        with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
            main()

        output = mock_stdout.getvalue().strip()

        self.assertIn("Your current list of cars are:", output)
        self.assertIn("- A, (1, 2) N, FFRFFFFRRL", output)
        self.assertIn("- B, (7, 8) W, FFLFFFFFFF", output)
        self.assertIn("After simulation, the result is:", output)
        self.assertIn("- A, collides with B at (5, 4) at step 7", output)
        self.assertIn("- B, collides with A at (5, 4) at step 7", output)

if __name__ == "__main__":
    unittest.main()


import math
import random
import time

import carla
import cv2
import numpy as np

actor_list = []

def pure_pursuit(tar_location, v_transform):
    L = 2.875
    yaw = v_transform.rotation.yaw * (math.pi / 180)
    x = v_transform.location.x - L / 2 * math.cos(yaw)
    y = v_transform.location.y - L / 2 * math.sin(yaw)
    dx = tar_location.x - x
    dy = tar_location.y - y
    ld = math.sqrt(dx ** 2 + dy ** 2)
    alpha = math.atan2(dy, dx) - yaw
    delta = math.atan(2 * math.sin(alpha) * L / ld) * 180 / math.pi
    steer = delta/90
    if steer > 1:
        steer = 1
    elif steer < -1:
        steer = -1
    return steer

def img_process(data):
    img = np.array(data.raw_data)
    img = img.reshape((1080, 1920, 4))
    img = img[:, :, :3]
    cv2.imwrite('car.png', img)
    # cv2.imshow('', img)
    # cv2.waitKey(1)
    pass

def callback(event):
    print("碰撞")

def callback2(event):
    print("穿越车道")

try:
    client = carla.Client('localhost', 2000)
    client.set_timeout(5.0)

    world = client.get_world()
    map = world.get_map()
    blueprint_library = world.get_blueprint_library()
    v_bp = blueprint_library.filter("model3")[0]
    spawn_point = random.choice(world.get_map().get_spawn_points())
    vehicle = world.spawn_actor(v_bp, spawn_point)
    actor_list.append(vehicle)

    # Find the blueprint of the sensor.
    blueprint = blueprint_library.find('sensor.camera.rgb')
    # Modify the attributes of the blueprint to set image resolution and field of view.
    blueprint.set_attribute('image_size_x', '1920')
    blueprint.set_attribute('image_size_y', '1080')
    blueprint.set_attribute('fov', '110')
    # Set the time in seconds between sensor captures
    blueprint.set_attribute('sensor_tick', '1.0')
    transform = carla.Transform(carla.Location(x=0.8, z=1.7))
    sensor = world.spawn_actor(blueprint, transform, attach_to=vehicle)
    actor_list.append(sensor)
    sensor.listen(lambda data: img_process(data))

    blueprint_collision = blueprint_library.find('sensor.other.collision')
    transform = carla.Transform(carla.Location(x=0.8, z=1.7))
    sensor_collision = world.spawn_actor(blueprint_collision, transform, attach_to=vehicle)
    actor_list.append(sensor_collision)
    sensor_collision.listen(callback)

    blueprint_lane_invasion = blueprint_library.find('sensor.other.lane_invasion')
    transform = carla.Transform(carla.Location(x=0.8, z=1.7))
    sensor_lane_invasion = world.spawn_actor(blueprint_lane_invasion, transform, attach_to=vehicle)
    actor_list.append(sensor_lane_invasion)
    sensor_lane_invasion.listen(callback2)

    vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0))
    while True:
        waypoint01 = map.get_waypoint(vehicle.get_location(), project_to_road=True,
                                      lane_type=(carla.LaneType.Driving | carla.LaneType.Sidewalk))
        v_trans = vehicle.get_transform()
        waypoints = waypoint01.next(8.0)
        waypoint02 = waypoints[0]
        tar_loc = waypoint02.transform.location
        steer = pure_pursuit(tar_loc, v_trans)
        vehicle.apply_control(carla.VehicleControl(throttle=0.6, steer=steer))
        time.sleep(0.02)

finally:
    for actor in actor_list:
        actor.destroy()
    print("结束")


from v_model import *
aho=visual.box()
par=visual.box()
par.color=visual.color.red
baka=V_PartsObject(FRAME())
baka.set_shape(aho)
pa=FRAME(xyzabc=[0,0,0,pi/4,0,0])
pb=FRAME(xyzabc=[0,0,0,0,pi/4,0])
pc=FRAME(xyzabc=[0,0,0,0,0,pi/4])
pe=FRAME(xyzabc=[1,0,0,0,pi/4,0,0])
pf=FRAME(xyzabc=[0,1,0,0,0,0])


from typing import List

# 438. 找到字符串中所有字母异位词
# https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        p_vec = self.to_vector(p)
        s_vec = self.to_vector(s[0: len(p) - 1])
        # print(s_vec, p_vec)
        i = 0
        ans = []
        for j in range(len(p) - 1, len(s)):
            s_vec[ord(s[j]) - ord('a')] += 1
            if p_vec == s_vec:
                # print(i)
                ans.append(i)
            s_vec[ord(s[i]) - ord('a')] -= 1
            i += 1
        return ans

    # 用不到
    def compare(self, p_vec, word):
        d = dict()
        for i, c in enumerate(word):
            if c in d:
                d[c] += 1
            else:
                d[c] = 1

            if c not in p_vec:
                return False, i + 1
            elif d[c] > p_vec[c]:
                return False, 1

        return p_vec == d, 1

    def to_vector(self, word):
        # d = dict()
        # for each in word:
        #     if each in d:
        #         d[each] += 1
        #     else:
        #         d[each] = 1
        # return d

        vec = [0] * 26
        for each in word:
           vec[ord(each) - ord('a')] += 1
        return vec

s = "abab"
p = "ab"
print(s)
r = Solution().findAnagrams(s, p)
print(r)


import random
import sys
sys.path.insert(1, '../')
from utils import read_instance, objetive_function, corrent_solution_size
import config

# Heurística Construtiva 02
# Constructive Heuristic 02
# Random para selecionar o teste e calculado a melhor mesa para aplicá-lo
def constructive_heuristic_02(corrent_size):
    def validade_best_desk(solution, idx):
        # idx = test number / index
        iteration_value = 100000
        iteration_solution = solution.copy()

        for i in range(0, desk_count):
            current_solution = solution.copy()
            if solution[i] == 0: # Não sobrescrever casos já alocados
                current_solution[i] = idx
                current_value = objetive_function(current_solution)
                if current_value < iteration_value:
                    iteration_value = current_value
                    iteration_solution = current_solution.copy()
        return iteration_solution, iteration_value

    desks, tests, empty = config.desks, config.tests, config.empty
    desk_count = len(desks)
    test_count = len(tests)
    s = [0 for _ in range(desk_count)]
    best_value = 0
    desk_with_test = 0

    while desk_with_test < (desk_count):
        sort_list = [i for i in range(1, test_count)]
        idx = random.choice(sort_list)
        s, best_value = validade_best_desk(s, idx)
        desk_with_test += 1

    if corrent_size:
        s, best_value = corrent_solution_size(s, empty)

    return s, best_value

if __name__ == '__main__':
    file_name = sys.argv[1]
    read_instance(file_name)

    response_solution, objetive = constructive_heuristic_02(True)
    print()
    print(response_solution)
    print(objetive)


# coding: utf-8
import re
import requests

response = requests.get('http://ads.fraiburgo.ifc.edu.br')

if response.status_code == 200:
	texto = response.content.decode('utf-8')
	links = re.findall(r'(.*)', texto)
	for url in links:
		print(url)


import boto3
from botocore.exceptions import NoCredentialsError

def upload_to_aws(local_file, bucket, s3_file):
    s3 = boto3.client('s3')
    try:
        s3.upload_file(local_file, bucket, s3_file)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False

if __name__ == "__main__":
    uploaded = upload_to_aws('Screenshot (288).png', 'group-6-marxel-pictures', 'test.png')


class man(object):

    # name of the man
    name = ""

    def __init__(self, P_name):
        """ Class constructor """
        self.name = P_name
        print("Here comes " + self.name)

    def talk(self, P_message):
        print(self.name + " says: '" + P_message + "'")

    def walk(self):
        """ This let an instance of a man to walk """
        print(self.name + " walks")

    # This class inherits from Man class
    # A superman has all the powers of a man (A.K.A. Methods and Properties in our case ;-)
class superman(man):

    # Name of his secret identity
    secret_identity = ""

    def __init__(self, P_name, P_secret_identity):
        """ Class constructor that overrides its parent class constructor"""
        # Invokes the class constructor of the parent class #
        super(superman, self).__init__(P_name)
        # Now let's add a secret identity
        self.secret_identity = P_secret_identity
        print("...but his secret identity is '" + self.secret_identity + "' and he's a super-hero!")

    def walk(self, P_super_speed = False):
        # Overrides the normal walk, because a superman can walk at a normal
        # pace or run at the speed of light!
        if (not P_super_speed):
            super(superman, self).walk()
        else:
            print(self.secret_identity + " run at the speed of light")

    def fly(self):
        """ This let an instance of a superman to fly """
        # No man can do this!
        print(self.secret_identity + " fly up in the sky")

    def x_ray(self):
        """ This let an instance of a superman to use his x-ray vision """
        # No man can do this!
        print(self.secret_identity + " uses his x-ray vision")

# Declare some instances of man and superman
lois = man("Lois Lane")
jimmy = man("Jimmy Olsen")
clark = superman("Clark Kent", "Superman")

# Let's puth them into action!

print("\n--> Let's see what a man can do:\n")
jimmy.walk()
lois.talk("Oh no, we're in danger!")

print("\n--> Let's see what a superman can do:\n")
clark.walk()
clark.talk("This is a job for SUPERMAN!")
clark.walk(True)
clark.fly()
clark.x_ray()


# convolution 계산 함수

import numpy as np
import pycuda.autoinit
from pycuda.compiler import SourceModule
from pycuda import gpuarray, tools
import pycuda.driver as cuda

class padding():
    # CUDA Limit size
    cu_lim = 32
    def __init__(self,D,K,mode='vaild'):
        # D : Data, K = kernel,
        kw = int(K.shape[0]) # kernel width
        kh = int(K.shape[1]) # kernel height

        # size setting (padding)
        if mode == 'vaild':
            aw = D.shape[0]-kw+1
            ah = D.shape[1]-kh+1
            P = D
        elif mode == 'same':
            D = D.astype(np.float32)
            aw = int(D.shape[0])
            ah = int(D.shape[1])

            if (aw % self.cu_lim == 0):
                aw_n = int(aw/self.cu_lim)
            else :
                aw_n = int(aw/self.cu_lim +1)

            if (ah % self.cu_lim == 0):
                ah_n = int(ah/self.cu_lim)
            else :
                ah_n = int(ah/self.cu_lim +1)

            # result size
            P = np.zeros([aw+kw-1,ah+kh-1]).astype(np.float32)
            # Module
            mod = SourceModule(open("CUDAKernelStudy\\padding.cu", "r", encoding="utf-8").read())
            cu_pad = mod.get_function("padding")

            # allocate memory on device
            d_gpu = cuda.mem_alloc(D.nbytes)
            p_gpu = cuda.mem_alloc(P.nbytes)

            # memory copy (host to device)
            cuda.memcpy_htod(d_gpu, D)
            cuda.memcpy_htod(p_gpu, P)

            kw32 = np.int32(kw)
            kh32 = np.int32(kh)
            cusiz = np.int32(self.cu_lim)
            # padding by CUDA
            cu_pad(d_gpu,kw32,kh32,cusiz,p_gpu,block=(self.cu_lim,self.cu_lim,1),grid=(aw_n,ah_n,1))

            # memory copy (device to host)
            cuda.memcpy_dtoh(P, p_gpu)

            d_gpu.free()
            p_gpu.free()

        self.D = D
        self.P = P
        self.C = np.zeros([aw,ah])


class MetaSingleton(type):

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(MetaSingleton, cls).__call__(
                *args, **kwargs
            )
        return cls._instances[cls]

class Logger(metaclass=MetaSingleton):
    def __init__(self, x):
        self.x = x

class Singleton1:

    __instance = None

    def __new__(cls, nome):
        if Singleton1.__instance is None:
            Singleton1.__instance = object.__new__(cls)
            Singleton1.__instance.__nome = nome
        return Singleton1.__instance

    @property
    def nome(self):
        return self.__nome

class Singleton2:
    def __new__(cls, nome):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton2, cls).__new__(cls)
            cls.instance.__nome = nome
        return cls.instance

    @property
    def nome(self):
        return self.__nome

if __name__ == '__main__':

    foo = Singleton1('Maria')
    print(foo.nome)
    print(foo)

    bar = Singleton1('Joao')
    print(bar.nome)
    print(bar)

    print(foo is bar)

    foo = Singleton2('Maria')
    print(foo.nome)
    print(foo)

    bar = Singleton2('Joao')
    print(bar.nome)
    print(bar)

    print(foo is bar)

    # Example using metaclass
    logger1 = Logger(1)
    logger2 = Logger(2)

    print(logger1)
    print(logger1.x)
    print(logger2)
    print(logger2.x)


import json
from logging import info
import boto3
from botocore.exceptions import ClientError
from lgw.lambda_util import get_lambda_info, grant_permission_to_api_resource

def create_rest_api(
    api_name,
    api_description,
    binary_types,
    lambda_name,
    resource_path,
    deploy_stage,
    integration_role,
    method_response_models,
):
    '''
    Creates & deploys a REST API that proxies to a Lambda function, returning the URL
    pointing to this API.

    :param api_name: Name of the REST API
    :param api_description: Textual description of the API
    :param binary_types: A list of binary types that this API may serve up
    :param lambda_name: Name of an existing Lambda function
    :param resource_path: The resource path that points to the lambda.
    :param deploy_stage: The name of the deployment stage.
    :param integration_role
    :param method_response_models: Dictionary of content-type => response-model mappings to be applied to child method

    :return: URL of API. If error, returns None.
    '''

    api_client = boto3.client('apigateway')

    api_id = create_api_gateway(api_client, api_name, api_description, binary_types)

    (lambda_arn, lambda_uri, region, account_id) = get_lambda_info(lambda_name)

    root_resource_id = get_root_resource_id(api_client, api_id)
    create_method(api_client, api_id, root_resource_id, 'ANY')
    create_lambda_integration(api_client, api_id, root_resource_id, lambda_uri, integration_role)

    child_resource_id = create_resource(api_client, api_id, root_resource_id, resource_path)
    create_method(api_client, api_id, child_resource_id, 'ANY', method_response_models)
    create_lambda_integration(api_client, api_id, child_resource_id, lambda_uri, integration_role)

    deploy_to_stage(api_client, api_id, deploy_stage)

    # grant_permission_to_api_resource(api_id, region, account_id, lambda_arn, resource_path)

    return f'https://{api_id}.execute-api.{region}.amazonaws.com/{deploy_stage}'

def delete_rest_api(api_name):
    api_client = boto3.client('apigateway')
    delete_api_gateway(api_client, api_name)

def deploy_to_stage(api_client, api_id, deploy_stage):
    return api_client.create_deployment(restApiId=api_id, stageName=deploy_stage)

def create_lambda_integration(api_client, api_id, root_resource_id, lambda_uri, role_arn=None):
    '''
    Set the Lambda function as the destination for the ANY method
    Extract the Lambda region and AWS account ID from the Lambda ARN
    ARN format="arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME"
    '''
    api_client.put_integration(
        restApiId=api_id,
        resourceId=root_resource_id,
        httpMethod='ANY',
        type='AWS_PROXY',
        integrationHttpMethod='POST',
        uri=lambda_uri,
        credentials=role_arn,
    )

def create_method(api_client, api_id, resource_id, http_method, method_response_models={}):
    try:
        response = api_client.get_method(
            restApiId=api_id, resourceId=resource_id, httpMethod=http_method
        )
        if response and response.get('httpMethod'):
            info(f'{http_method} method already exists for resource {resource_id}')
            return
    except api_client.exceptions.NotFoundException:
        info(f'{http_method} method does not exist for resource {resource_id}, adding it.')

    api_client.put_method(
        resourceId=resource_id, restApiId=api_id, httpMethod=http_method, authorizationType='NONE'
    )

    # Set the content-type of the method response to JSON
    api_client.put_method_response(
        restApiId=api_id,
        resourceId=resource_id,
        httpMethod=http_method,
        statusCode='200',
        responseModels=method_response_models,
    )

def create_resource(api_client, api_id, parent_id, resource_path):
    resources = api_client.get_resources(restApiId=api_id)
    if 'items' in resources:
        for resource in resources['items']:
            if resource.get('parentId') == parent_id and resource.get('pathPart') == resource_path:
                info('Found existing resource for %s' % resource['parentId'])
                return resource['id']

    info(f'No existing resource found for {parent_id}/{resource_path}, creating a new one')
    result = api_client.create_resource(
        restApiId=api_id, parentId=parent_id, pathPart=resource_path
    )
    return result['id']

def get_root_resource_id(api_client, api_id):
    result = api_client.get_resources(restApiId=api_id)

    root_id = None
    for item in result['items']:
        if item['path'] == '/':
            root_id = item['id']

    if root_id is None:
        raise ClientError(
            'Could not retrieve the ID of the API root resource using api_id [%s]' % api_id
        )

    return root_id

def delete_api_gateway(api_client, api_name):
    api_id = lookup_api_gateway(api_client, api_name)
    if api_id:
        info(f'Deleting API with ID: {api_id}')
        api_client.delete_rest_api(restApiId=api_id)

def create_api_gateway(api_client, api_name, api_description, binary_types):
    api_id = lookup_api_gateway(api_client, api_name)
    if api_id:
        return api_id
    info(f'No existing API account found for {api_name}, creating it.')
    result = api_client.create_rest_api(
        name=api_name, description=api_description, binaryMediaTypes=binary_types
    )
    return result['id']

def lookup_api_gateway(api_client, api_name):
    apis = api_client.get_rest_apis()
    if 'items' in apis:
        for api in apis['items']:
            if api['name'] == api_name:
                info('Found existing API account for %s' % api['name'])
                return api['id']
    info(f'No API gateway found with name {api_name}')
    return None


import stagger
import os
import sys
from stagger.id3 import *

def metaHound(argvPath):
    #ef það er sendur parametri inní fallið þá er það slóðin a möppuna
    #sem á að fara i gegnum.
    #ef ekki er sendur parameter er reiknað með að mappan sem á að fara
    #í gegnum sé í cwd.
    if argvPath != '':
        os.chdir(argvPath)
        os.chdir('..')
        ipodFolder = argvPath
    else:
        ipodFolder = os.path.join(os.getcwd(), 'ipod')

    if not os.path.exists(os.path.join(os.getcwd(), 'Music')):
        os.mkdir('Music')
    root = os.path.join(os.getcwd(), 'Music')
    #Búið að búa til Music möppu ef hún er ekki til og stilla current working directory á hana

    for data in os.walk(ipodFolder):
        for file in data[2]:
            #data[2] því við viljum bara skoða fæla, ekki folera
            os.chdir(root)
            #passa að í byrjun hvers hrings sé cwd alltaf Music mappan
            currPath = os.path.join(data[0], file)
            filename, extension = os.path.splitext(file)
            try:
                tag = stagger.read_tag(currPath)
                #ná í meta-data
                album = tag.album
                artist = tag.artist
                title = tag.title

                if artist == '':
                    artist = 'unknown artists'
                if album == '':
                    album = 'unknown albums'

                artist = fixName(artist)
                album = fixName(album)
                title = fixName(title)
                #taka burtu óleyfileg tákn

                artistPath = os.path.join(root, artist)
                if not os.path.exists(artistPath):
                    os.mkdir(artist)
                os.chdir(artistPath)
                #búa til möppu ef þarf fyrir þennan artista
                #stilla current working directory á þá möppu

                albumPath = os.path.join(artistPath, album)
                if not os.path.exists(albumPath):
                    os.mkdir(album)
                os.chdir(albumPath)
                #búa til möppu inní artistanum fyrir plötuna
                #stilla current working directory á þá möppu

                newPath = os.path.join(albumPath, title + extension)
                if not os.path.exists(newPath):
                    os.rename(currPath, newPath)
                else:
                    os.remove(currPath)
                #færa lagið í album möppuna ef það er ekki þar nú þegar, annars er því eytt

            except:
                #hingað ef tekst ekki að ná i meta-data

                path = os.path.join(root, 'unknown files')
                os.chdir(root)
                if not os.path.exists(path):
                    os.mkdir('unknown files')
                newPath = os.path.join(path, file)
                #Búa til unknown files möppu ef hún er ekki til

                if not os.path.exists(newPath):
                    os.rename(currPath, newPath)
                else:
                    os.remove(currPath)
                #færa lagið í unknown files möppuna ef það er ekki þar nú þegar, annars er því eytt

    #henda ipod möppunni ef allt er tómt
    for folder in os.listdir(ipodFolder):
        os.removedirs(os.path.join(ipodFolder, folder))

def fixName(name):
    #ef nafnið inniheldur ólöglega caractera er þeim skipt út fyrir kommu
    return name.replace('\\', ',').replace('/', ',').replace(':', ',').replace('*', ',').replace('?', ',').replace('"', ',').replace('<', ',').replace('>', ',').replace('|', ',')

try:
    metaHound(sys.argv[1])
except:
    metaHound('')


from odoo import models, fields, api
from ..tools.nawh_error import NAWHError

class NetaddictionWhLocationsLine(models.Model):
    _name = 'netaddiction.wh.locations.line'
    _description = "Netaddiction WH Locations Line"
    _order = 'qty'

    product_id = fields.Many2one(
        'product.product',
        required=True,
        string="Prodotto",
    )

    qty = fields.Integer(
        default=1,
        required=True,
        string="Quantità",
    )

    wh_location_id = fields.Many2one(
        'netaddiction.wh.locations',
        required=True,
        string="Ripiano",
    )

    @api.model
    def get_products(self, barcode):
        """
        dato il barcode di un ripiano ritorna i prodotti allocati
        """
        result = self.search([('wh_location_id.barcode', '=', barcode)])
        if not result:
            return NAWHError(
                "Non sono stati trovati prodotti per il barcode"
            )
        return result

    ##########################
    # INVENTORY APP FUNCTION #
    # ritorna un dict simile #
    # ad un json per il web  #
    ##########################

    @api.model
    def get_json_products(self, barcode):
        """
        ritorna un json con i dati per la ricerca per ripiano
        """
        is_shelf = self.env['netaddiction.wh.locations'].check_barcode(barcode)
        if isinstance(is_shelf, NAWHError):
            return {'result': 0, 'error': is_shelf.msg}

        results = self.get_products(barcode)
        if isinstance(results, NAWHError):
            return {'result': 0, 'error': results.msg}

        return {
            'result': 1,
            'shelf': is_shelf.name,
            'barcode': barcode,
            'products': [
                {'product_name': res.product_id.display_name,
                 'qty': res.qty,
                 'barcode': res.product_id.barcode}
                for res in results
            ]
        }

    @api.model
    def put_json_new_allocation(self, barcode, qty, product_id, now_wh_line):
        """
        sposta la quantità qty dal ripiano barcode al new_shelf
        """
        is_shelf = self.env['netaddiction.wh.locations'].check_barcode(barcode)

        if isinstance(is_shelf, NAWHError):
            return {'result': 0, 'error': is_shelf.msg}

        new_shelf = is_shelf.id

        line = self.search(
            [('id', '=', int(now_wh_line)),
             ('product_id', '=', int(product_id))]
        )

        if not line:
            return {
                'result': 0,
                'error': 'Prodotto non più presente in questa locazione'
            }

        if line.wh_location_id.id == new_shelf:
            return {
                'result': 0,
                'error': 'Non puoi spostare un prodotto nella'
                         ' stessa locazione di partenza'
            }

        dec = line.decrease(qty)
        if isinstance(dec, NAWHError):
            return {'result': 0, 'error': dec.msg}

        self.allocate(product_id, qty, new_shelf)

        product = self.env['product.product'].browse(int(product_id))
        return {'result': 1, 'product_barcode': product.barcode}

    ##############################
    # END INVENTORY APP FUNCTION #
    ##############################

    ##################
    # FUNZIONI VARIE #
    ##################

    def decrease(self, qta):
        """ decrementa la quantità allocata di qta """
        self.ensure_one()
        end_qty = self.qty - int(qta)

        if end_qty < 0:
            return NAWHError(
                "Non puoi scaricare una quantità maggiore di quella allocata"
            )
        elif end_qty > 0:
            self.write({'qty': end_qty})
        else:
            self.unlink()

    def increase(self, qta):
        """ incrementa la quantità allocata di qta """
        self.ensure_one()
        self.qty += int(qta)

    @api.model
    def allocate(self, product_id, qta, new_location_id):
        """ alloca in new_location_id la qta di product_id """
        result = self.search(
            [('product_id', '=', int(product_id)),
             ('wh_location_id', '=', int(new_location_id))]
        )

        if result:
            # è già presente una locazione con questo prodotto
            # incremento
            for res in result:
                res.increase(qta)
        else:
            self.create([{
                'product_id': product_id,
                'qty': qta,
                'wh_location_id': new_location_id
            }])


import django
from django.conf import settings

import pandas as pd
import os, sys

proj_path = "/home/webuser/webapps/tigaserver/"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tigaserver_project.settings")
sys.path.append(proj_path)

django.setup()

from tigaserver_app.models import Fix

FILE = os.path.join(settings.STATIC_ROOT, "geo_user_fixes.csv")

# Getting all fixes and create a new DataFrame.
# Selecting only the desired fields for speed reasons.
df = pd.DataFrame.from_records(
    Fix.objects.all().values('server_upload_time', 'masked_lon', 'masked_lat')
)

# Remove any NaN value
df.dropna(inplace=True)

# Rename the datetime colume to a more readable name
df.rename(
    columns={"server_upload_time": "datetime"},
    inplace=True
)

# Convert datetime column to just date
df['datetime'] = pd.to_datetime(df['datetime']).dt.normalize()
# Round float to 2 decimals (lat and lon)
df = df.round(decimals=2)

##########
# Group by date, lat, lon and count the number of elements
# to make the resulting file smaller.
##########
# If the dataviz is slow, create bins for the latitude and longitue.
# Example: https://stackoverflow.com/questions/39254704/pandas-group-bins-of-data-per-longitude-latitude
# import numpy as np
# degres_step = 0.1
# to_bin = lambda x: np.floor(x / step) * step
# df["latBin"] = to_bin(df.masked_lat)
# df["lonBin"] = to_bin(df.masked_lon)

# See: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
df.groupby(
    [
        pd.Grouper(key='datetime', freq='3W-MON'), # Every 3 weeks.
        df['masked_lon'],
        df['masked_lat']
    ]).size()\
    .reset_index(name='count')\
    .to_csv(FILE, index=False)


#!/usr/bin/env python3
import asyncio
import discord
import os

client= discord.Client()
TOKEN = os.getenv('USER_TOKEN')
CHANNEL_ID = int(os.getenv('CHANNEL_ID'))
MESSAGE = os.getenv('MESSAGE')

def lambda_handler(event, context):
    print("lambda start")
    client.run(TOKEN, bot=False)

@client.event
async def on_ready():
    print('%s has connected to Discord!' % client.user)
    channel = client.get_channel(CHANNEL_ID)
    if channel:
        await channel.send(MESSAGE)
        print("message sent")
    else:
        print("channel not found")
    await client.close()


from torch import Tensor, LongTensor, max
from typing import Dict
from sklearn.metrics import accuracy_score

def compute_metrics(
    outputs: Tensor,
    labels: LongTensor,
) -> Dict[str, float]:\

    metrics = {}

    outputs = outputs.cpu()
    labels = labels.cpu()
    _, pred = max(outputs.data, 1)

    y_true = labels
    y_pred = pred

    # accuracy
    accuracy = accuracy_score(
        y_true=y_true,
        y_pred=y_pred,
    )

    # Optional add metrics

    metrics["accuracy"] = accuracy
    return metrics

if __name__ == '__main__':
    pass