import sys
import os
import stat
import node

def printPreorder(root, file):
    if root:
        root.write(file)
        printPreorder(root.left, file)
        printPreorder(root.right, file)

def printInorder(root, file):
    if root:
        printInorder(root.left, file)
        root.write(file)
        printInorder(root.right, file)

def printPostorder(root, file):
    if root:
        printPostorder(root.left, file)
        printPostorder(root.right, file)
        root.write(file)

def buildTree():
    firstWord = True
    root = None

    # if user entered filename as argument
    if len(sys.argv) == 2:
        filename = sys.argv[-1] + '.cs4280'
        if not os.path.exists(filename):
            print('the file \'' + filename + '\' does not exist')
            sys.exit()

        f = open(filename, 'r')
        for line in f:
            line = line.rstrip('\n')  # remove any newlines
            words = line.split()  # split up any words by whitespace
            for word in words:
                if firstWord:
                    # if firstword, create the root node
                    root = node.Node(len(word), [word], 0)
                    firstWord = False
                else:
                    root.insert(word)

    # if user does not pass file as command line argument
    else:
        # code to check if stdin is redirected or not found at link below
        # https://stackoverflow.com/questions/13442574/how-do-i-determine-if-sys-stdin-is-redirected-from-a-file-vs-piped-from-another
        mode = os.fstat(sys.stdin.fileno()).st_mode
        # if stdin is from a redirect
        if stat.S_ISREG(mode):
            for line in sys.stdin:
                line = line.rstrip('\n')  # remove any newlines
                words = line.split()  # split up any words by whitespace
                for word in words:
                    if firstWord:
                        # if firstword, create the root node
                        root = node.Node(len(word), [word], 0)
                        firstWord = False
                    else:
                        root.insert(word)
        # if no file redirected
        else:
            try:
                print(
                    'Enter words and lines and press Ctrl-D (Ctrl-Z on Windows) when finished')
                while True:
                    line = raw_input()  # get user input
                    line = line.rstrip('\n')  # remove any newlines
                    words = line.split()  # split up any words by whitespace
                    for word in words:
                        if firstWord:
                            # if firstword, create the root node
                            root = node.Node(len(word), [word], 0)
                            firstWord = False
                        else:
                            root.insert(word)
            except EOFError:
                pass

    return root


from threading import Timer
import time
import json

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

class device(object):
    def __init__(self, devtype, token, status, setting):
        # addtime,name,type,token,lastupdate
        self.type = devtype
        self.token = token
        self.lastupdate = time.time()
        self.status = status
        self.rawdata = None
        self.rawdata_history = []
        self.setting = setting
        self.cache = {"needupdate": False, "datacount": 0}

    def update(self, status=None):
        self.status = status if status != None else self.status
        self.lastupdate = time.time()

    def timeupdate(self):
        self.lastupdate = time.time()

    def istimeout(self, timeout=10):  # 10秒
        timelast = int(self.lastupdate)
        if int(time.time()) - timelast > timeout:
            return True
        return False

    def getsave(self):
        return {
            "token": str(self.token),
            "type": str(self.type),
            "lastupdate": str(self.lastupdate),
            "status": str(self.status),
            "setting": self.setting,
            'rawdata': self.rawdata,
            'rawdata_history': self.rawdata_history,
            'cache': self.cache
        }

    # return dict
    def getdict(self):
        return {
            "token": str(self.token),
            "type": str(self.type),
            "lastupdate": str(self.lastupdate),
            "status": str(self.status),
            "setting": self.setting
        }

def getNowTime():
    # get unix time and convert to int
    return int(time.time())

def genToken():
    # use random String include 0-9 a-z A-Z
    import random
    import string
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(64))

devicestatus = {
    "PLUG": ["ON", "OFF"],
    "PLUGDUAL": ["ONON", "OFFOFF", "ONOFF", "OFFON"],
}

deviceDefaultSetting = {
    "PLUG": {"status": "0",
             "name": "PLUG",
             "safeMinTemp": "20",
             "safeMaxTemp": "60",
             "safeMinHumid": "0",
             "safeMaxHumid": "100",
             "safeMinVoltage": "80",
             "safeMaxVoltage": "250",
             "safeMaxWatt": "1000"},
    "PLUGDUAL": {
        "status": "0",
        "name": "PLUG (DUAL)",
        "safeMinTemp": "20",
        "safeMaxTemp": "60",
        "safeMinVoltage": "80",
        "safeMaxVoltage": "250",
        "safeMaxWatt": "1000"},
}

deviceCalc = {
    "PLUG": [''],
    "PLUGDUAL": ['voltage', 'current1', 'current2', 'temp']
}


# %% [markdown]
# # División de los datos en grupo para entrenamiento, prueba y validación

# %%
import pandas as pd
import numpy as np

df = pd.read_excel("Datos IRIS.xlsx", index_col=None, header=None)

# División de dataset

df_T = df.iloc[0:35] # Datos de Entrenamiento
df_T = df_T.append(df.iloc[50:85])
df_T = df_T.append(df.iloc[100:135])

print("Entrenamiento \n", df_T)

df_P = df.iloc[35:45]          #Datos de prueba
df_P = df_P.append(df.iloc[85:95])
df_P = df_P.append(df.iloc[135:145])

print("Prueba \n", df_P)

df_R = df.iloc[45:50]          #Datos de validación
df_R = df_R.append(df.iloc[95:100])
df_R = df_R.append(df.iloc[145:150])

print("Resultantes \n", df_R)

# %% [markdown]
# # Normalización de los conjutos de datos

# %%
#Mínimos y máximos
def minimo(dfin):
    min_0 = dfin[0].min()  #Columna 0
    min_1 = dfin[1].min()  #Columna 1
    min_2 = dfin[2].min()  #Columna 2
    min_3 = dfin[3].min()  #Columna 3

    return [min_0, min_1, min_2, min_3]

def maximo(dfin):
    max_0 = dfin[0].max()  #Columna 0
    max_1 = dfin[1].max()  #Columna 1
    max_2 = dfin[2].max()  #Columna 2
    max_3 = dfin[3].max()  #Columna 3

    return [max_0, max_1, max_2, max_3]

# Normalización por columna
def minmax_norm(dfin , min, max):
    return (dfin - min) / (max - min)

# Normalización del dataframe
def norm_df(dfin, min = [0,0,0,0], max = [0,0,0,0]):

    # Normalización de Dataframe de entrenamiento
    df_norm_0 = minmax_norm(dfin[0], min[0], max[0])  #Columna 0
    df_norm_1 = minmax_norm(dfin[1], min[1], max[1])  #Columna 1
    df_norm_2 = minmax_norm(dfin[2], min[2], max[2])  #Columna 2
    df_norm_3 = minmax_norm(dfin[3], min[3], max[3])  #Columna 3

    return pd.DataFrame([df_norm_0,df_norm_1, df_norm_2, df_norm_3, dfin[5]] ).transpose()  # Dataframe con las columnas normalizadas

#Mínimos y máximos para cada Dataframe
global_min = minimo(df_T)    # Mínimo global de los datos
global_max = maximo(df_T)    # Máximo global de los datos

minimo_P = minimo(df_P)
maximo_P = maximo(df_P)

minimo_R = minimo(df_R)
maximo_R = maximo(df_R)

#Actualización de mínimo y máximo global en caso de que sea necesario
for i in range(len(minimo_P)):
    if minimo_P[i] < global_min[i]:
        global_min[i] = minimo_P[i]
    if maximo_P[i] > global_max[i]:
        global_max[i] = maximo_P[i]

for i in range(len(minimo_R)):
    if minimo_R[i] < global_min[i]:
        global_min[i] = minimo_R[i]
    if maximo_R[i] > global_max[i]:
        global_max[i] = maximo_R[i]

print(global_min, global_max)

#Normalización Dataframe de entrenamiento
df_TN = norm_df(df_T, global_min, global_max)
print("Entrenamiento Normalizado \n", df_TN)

#Normalización Dataframe de prueba
df_PN = norm_df(df_P, global_min, global_max)
print("Prueba Normalizado \n",df_PN)

# Normalización de Dataframe de validación
df_norm_0 = minmax_norm(df_R[0], global_min[0], global_max[0])  #Columna 0
df_norm_1 = minmax_norm(df_R[1], global_min[1], global_max[1])  #Columna 1
df_norm_2 = minmax_norm(df_R[2], global_min[2], global_max[2])  #Columna 2
df_norm_3 = minmax_norm(df_R[3], global_min[3], global_max[3])  #Columna 3

df_RN = pd.DataFrame([df_norm_0,df_norm_1, df_norm_2, df_norm_3]).transpose()  # Dataframe con las columnas normalizadas

print("Validación Normalizado \n",df_RN)

# %% [markdown]
# # Descriptores

# %%
import matplotlib.pyplot as plt

my_plot = df_TN.plot(1, 0, kind="scatter")
plt.show()

my_plot = df_TN.plot(2, 0, kind="scatter")
plt.show()

my_plot = df_TN.plot(3, 0, kind="scatter")
plt.show()

my_plot = df_TN.plot(2, 1, kind="scatter")
plt.show()

my_plot = df_TN.plot(3, 1, kind="scatter")
plt.show()

my_plot = df_TN.plot(3, 2, kind="scatter")
plt.show()

# %%
my_plot = df_TN.plot(0, 5, kind="scatter", xlabel= "X0", ylabel = "Y1")
plt.show()
my_plot = df_TN.plot(1, 5, kind="scatter", xlabel= "X1", ylabel = "Y1")
plt.show()
my_plot = df_TN.plot(2, 5, kind="scatter", xlabel= "X2", ylabel = "Y1")
plt.show()
my_plot = df_TN.plot(3, 5, kind="scatter", xlabel= "X3", ylabel = "Y1")
plt.show()

# %%
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')

ax1.scatter(df_TN[2], df_TN[5], df_TN[3], c='g', marker='o')
ax1.set_xlabel('X2')
ax1.set_ylabel('Clase')
ax1.set_zlabel('X3')
ax1.legend()

plt.show()

# %% [markdown]
# ## Función para medir el error del dataset

# %%
def ErrorDataframe(W, Dataf):
    #Calcula el error promedio del vector de errores para cada fila del dataset
    error =[]

    for i in range(len(Dataf)):
        x1,x2,y =  Dataf.iloc[i, 2], Dataf.iloc[i, 3], Dataf.iloc[i, 4]  # Entradas y valor esperado
        x = np.array([x1,x2,1])  # Arreglo de entradas
        x_w = (W.T * x)         # Multiplicación de entradas por los pesos
        suma = x_w[0] + x_w[1] + x_w[2] # Sumatoria de los productos
        error_i = suma - y                # Cálculo del error
        error.append(error_i)           # Se agrega el error calculado al arreglo de errores de entrenamiento

    error = np.array(error)
    return np.mean(error)

# %% [markdown]
# # MONOCAPA

# %%
import random
Tolerancia = 0.03 # Valor de tolerancia de error
errorDataset = 100       # Error grande

error_T = []  # Arreglo para almacenar los valores del error para cada elemento de entrenamiento
error_P = []  # Arreglo para almacenar los valores del error para cada elemento de prueba
w0 = [1,1,0]  # Pesos iniciales arbitrarios
w0 = np.array(w0)
iter = 0      # Contador de iteraciones
u = 0.04      # Paso para modificación de pesos

while (np.abs(errorDataset) > Tolerancia ):  # Cuando el error sea menor a la toleracia o los aciertos continuos son menores a 4
    ########## Entrenamiento #########
    i = random.randint(0, 104)  # Índice aleatorio
    x1,x2,y =  df_TN.iloc[i, 2], df_TN.iloc[i, 3], df_TN.iloc[i, 4]  # Entradas y valor esperado

    x = np.array([x1,x2,1])  # Arreglo de entradas
    x_w = (w0.T * x)         # Multiplicación de entradas por los pesos

    suma = x_w[0] + x_w[1] + x_w[2] # Sumatoria de los productos
    error = suma - y                # Cálculo del error

    ###########    Prueba  ##########
    j = random.randint(0, 29) # Índice aleatorio
    x3,x4,y1 =  df_PN.iloc[j, 2], df_PN.iloc[j, 3], df_PN.iloc[j, 4]  # Entradas y valor esperado

    x_P = np.array([x3,x4,1])   # Arreglo de entradas
    xP_w = (w0.T * x_P)         # Multiplicación de entradas por los pesos

    sumaP = xP_w[0] + xP_w[1] + xP_w[2]  # Sumatoria de los productos
    errorP = sumaP - y1         # Cálculo del error

    w0 = w0 - u*x*error           # Modificación de los pesos

    errorDataset = ErrorDataframe(w0, df_TN)   #Evaluación del dataset de entrenamiento para los pesos modificados
    errorDP = ErrorDataframe(w0, df_PN)        #Evaluación del dataset de prueba para los pesos modificados

    error_T.append(errorDataset)         # Se guarda el valor promedio del error en el dataset para graficarlos
    error_P.append(errorDP)

    iter += 1      # Contador de iteraciones

    # Condiciones para salir del ciclo while en caso de no converger
    if iter > 2000:
        errorDataset = Tolerancia - 0.01

####### Gráfica de resultados ################
x = np.arange(0,len(error_T))    # Vector que representa el número de iteraciones

plt.plot(x, np.abs(error_T), 'o', label = "Entrenamiento")  #Gráfica de arreglo de errores de Entrenamiento
plt.plot(x, np.abs(error_P), '*',label = "Prueba")          #Gráfica de arreglo de errores de Prueba
plt.xlabel("Iteraciones")    # Etiqueta de eje X
plt.ylabel("Error")          # Etiqueta de eje Y
plt.title("Error Entrenamiento y Prueba")   # Título del gráfico
plt.legend()
plt.show()

# %%
Resultado = [] #Arreglo de resultados obtenidos
for k in range(15):

    ##########   Validación   ###############
    x3,x4 =  df_RN.iloc[k, 2], df_RN.iloc[k, 3] # Entradas
    x_R = np.array([x3,x4,1])                   # Arreglo de entradas
    xR_w = (w0.T * x_R)                         # Multiplicación de entradas por los pesos
    sumaR = xR_w[0] + xR_w[1] + xR_w[2]         # Sumatoria de los productos
    Resultado.append(sumaR)                       # Se agrega el resultado de la sumatoria

####### Gráfica de resultados #########
x = np.arange(0,len(Resultado)) # Vector que representa el número de elementos

plt.plot(x, np.abs(Resultado), 'o') #Gráfica de arreglo de resultado obtenido para cada elemento
plt.xlabel("Elemento")
plt.ylabel("Valor obtenido")
plt.title("Validación")
plt.show()

# %% [markdown]
# # Multicapa

# %% [markdown]
# ## Función para calcular el error en el dataset

# %%
## Función de error del dataset
def ErrorDataMulticapa(Wj, Wk, Dataf):
    error = []

    for i in range(len(Dataf)):
        x1,x2,y =  Dataf.iloc[i, 2], Dataf.iloc[i, 3], Dataf.iloc[i, 4]  # Entradas y valor esperado
        x = np.array([x1,x2,1])  # Arreglo de entradas
        x_w0 = (Wj[0:3].T * x)
        x_w1 = (Wj[3:6].T * x)
        A0 = x_w0[0] + x_w0[1] + x_w0[2]
        A1 = x_w1[0] + x_w1[1] + x_w1[2]
        Z1 = sig(A0)
        Z2 = sig(A1)
        h = np.array([Z1,Z2,1]) #Arreglo de entradas para la segunda capa
        ##### Segunda capa  #####
        x_w2 = (Wk.T * h)
        AK = x_w2[0] + x_w2[1] + x_w2[2]

        if(AK <= 0.3):     #Rango para tipo 3
            ZK = 3.0
        elif(AK <= 0.45):  #Rango para tipo 2
            ZK = 2.0
        else:              #Rango para tipo 1
            ZK = 1.0

        error_i = ZK - y               # Cálculo del error para la fila i
        error.append(error_i)           # Se agrega el error calculado al arreglo de errores de entrenamiento

    error = np.array(error)
    ERROR = 1 - (np.count_nonzero(error == 0.0)/ len(error))  # Núm. de errores / total de muestras
    return ERROR

# %%
#Función sigmoide
def sig(x):
    h = 1 / (1 + np.exp(x))
    return h

Tolerancia = 0.03 # Valor de tolerancia de error
errorTN = 100        # Error grande
errorP = 100       # Error Prueba grande

error_T = []       # Arreglo para almacenar los valores del error para cada elemento de entrenamiento
error_P = []       # Arreglo para almacenar los valores del error para cada elemento de prueba
w0 = np.array([1, 1, 0, 1, 1,0])  # Pesos para primera capa, con bias
w1 = np.array([1,1, 0])       # Pesos para la segunda capa, con bias

w0_post = np.array([0,0,0,0,0,0]) # Pesos para primera capa siguiente iteración, con bias
w1_post = np.array([0,0,0])       # Pesos para la segunda capa siguiente iteración, con bias

iter = 0                #Contador de iteraciones
t = 0                   #Contador de aciertos continuos

u = 0.004            #Paso para modificación de pesos

while (np.abs(errorTN) > Tolerancia):   # Cuando el error sea menor a la toleracia o los aciertos continuos son menores a 30
    ########### Entrenamiento  #############
    i = random.randint(0, 104)  # Índice aleatorio
    x1,x2,y =  df_TN.iloc[i, 2], df_TN.iloc[i, 3], df_TN.iloc[i, 4]   # Entradas y valor esperado
    x = np.array([x1,x2,1])     # Arreglo de entradas

    #Entradas multiplicadas por los pesos de la primera capa
    x_w0 = (w0[0:3].T * x)
    x_w1 = (w0[3:6].T * x)

    # Suma de la multiplicación de cada entrada de las neuronas
    A0 = x_w0[0] + x_w0[1] + x_w0[2]
    A1 = x_w1[0] + x_w1[1] + x_w1[2]

    # Función de transferencia de cada neurona
    Z1 = sig(A0)
    Z2 = sig(A1)

    h = np.array([Z1,Z2,1]) #Arreglo de entradas para la segunda capa

    ##### Segunda capa  #####
    x_w2 = (w1.T * h)
    AK = x_w2[0] + x_w2[1] + x_w2[2]

    DK = y - AK
    DJ0 = Z1 * (1 - Z1) * (w1[0] * DK)   #Propagación del error
    DJ1 = Z2 * (1 - Z2) * (w1[1] * DK)   #Propagación del error

    # Cálculo de pesos del siguiente paso para la capa  2

    w1_post0 = w1[0] - u * DK * Z1
    w1_post1 = w1[1] - u * DK * Z2
    w1_post = np.array([w1_post0, w1_post1, 0])

    # Cálculo de pesos del siguiente paso para la capa 1
    w0_post0 = w0[0] - u * DJ0 * x1 #Neurona 1
    w0_post1 = w0[1] - u * DJ0 * x2

    w0_post3 = w0[3] - u * DJ1 * x1 #Neurona 2
    w0_post4 = w0[4] - u * DJ1 * x2

    w0_post = np.array([w0_post0, w0_post1, 0,w0_post3, w0_post4, 0])

    errorTN = ErrorDataMulticapa(w0, w1, df_TN)
    error_T.append(errorTN)
    errorP = ErrorDataMulticapa(w0, w1, df_PN)
    error_P.append(errorP)

    w0 = w0_post
    w1 = w1_post

    iter += 1        # Contador de iteraciones
    if iter > 2000:   # Condición de iteraciones para salir del ciclo while
        errorTN = 0.03
        t = 200
    elif errorTN == 0:  # Contador de aciertos continuos
        t += 1
    else:
        t = 0        #Reinicio del contador de aciertos continuos

print("Iteraciones: ", iter)
print("Pesos")
print(w0)
print(w1)

# %%
####### Gráfica de resultados ################
x = np.arange(0,len(error_T))    # Vector que representa el número de iteraciones

plt.plot(x, np.abs(error_T), 'o', label = "Entrenamiento")  #Gráfica de arreglo de errores de Entrenamiento
plt.plot(x, np.abs(error_P), '*',label = "Prueba")          #Gráfica de arreglo de errores de Prueba
plt.xlabel("Iteraciones")    # Etiqueta de eje X
plt.ylabel("Error")          # Etiqueta de eje Y
plt.title("Error Entrenamiento y Prueba")   # Título del gráfico
plt.legend()
plt.show()

# %%
Resultado = [] #Arreglo de resultados obtenidos
for k in range(15):

    ##########   Validación   ###############
    x3,x4 =  df_RN.iloc[k, 2], df_RN.iloc[k, 3] # Entradas
    x = np.array([x3,x4,1])                   # Arreglo de entradas
    x_w0 = (w0[0:3].T * x)
    x_w1 = (w0[3:6].T * x)
    A0 = x_w0[0] + x_w0[1] + x_w0[2]
    A1 = x_w1[0] + x_w1[1] + x_w1[2]
    Z1 = sig(A0)
    Z2 = sig(A1)
    h = np.array([Z1,Z2,1]) #Arreglo de entradas para la segunda capa
    ##### Segunda capa  #####
    x_w2 = (w1.T * h)
    AK = x_w2[0] + x_w2[1] + x_w2[2]

    if(AK <= 0.3):
        ZK = 3.0
        #error_i = 0.145 - AK
    elif(AK <= 0.45):
        ZK = 2.0
        #error_i = 0.3 - AK
    else:
        ZK = 1.0
        #error_i = 0.6 - AK
    Resultado.append(ZK)                       # Se agrega el resultado de la sumatoria

####### Gráfica de resultados #########
x = np.arange(0,len(Resultado)) # Vector que representa el número de elementos

plt.plot(x, np.abs(Resultado), 'o') #Gráfica de arreglo de resultado obtenido para cada elemento
plt.xlabel("Elemento")
plt.ylabel("Valor obtenido")
plt.title("Validación")
plt.show()

# %% [markdown]
# # Monocapa con 4 variables

# %%
def Error4Dataframe(W, Dataf):
    #Calcula el error promedio del vector de errores para cada fila del dataset
    error =[]

    for i in range(len(Dataf)):
        x0,x1,x2,x3,y =  df_TN.iloc[i, 0], df_TN.iloc[i, 1], df_TN.iloc[i, 2], df_TN.iloc[i, 3], df_TN.iloc[i, 4] # Entradas y valor esperado
        x = np.array([x0,x1,x2,x3,1])                        # Arreglo de entradas
        x_w = (W.T * x)                                     # Multiplicación de entradas por los pesos
        suma = x_w[0] + x_w[1] + x_w[2] + x_w[3] +x_w[4]     # Sumatoria de los productos
        error_i = suma - y                # Cálculo del error
        error.append(error_i)           # Se agrega el error calculado al arreglo de errores de entrenamiento

    error = np.array(error)
    return np.mean(error)

# %%
Tolerancia = 0.03  # Valor de tolerancia de error
errorTN = 100        # Error grande

error_T = []       # Arreglo para almacenar los valores del error para cada elemento de entrenamiento
error_P = []       # Arreglo para almacenar los valores del error para cada elemento de prueba
w0 = [1,1,1,1,0]   # Pesos iniciales arbitrarios
w0 = np.array(w0)
iter = 0           # Contador de iteraciones
u = 0.04           # Paso para modificación de pesos
t = 0              # Cantidad de aciertos continuos para mejorar el algoritmo

while (np.abs(errorTN) > Tolerancia):  # Cuando el error sea menor a la toleracia o los aciertos continuos son menores a 4
    ########## Entrenamiento #########
    i = random.randint(0, 104) # Índice aleatorio
    x0,x1,x2,x3,y =  df_TN.iloc[i, 0], df_TN.iloc[i, 1], df_TN.iloc[i, 2], df_TN.iloc[i, 3], df_TN.iloc[i, 4] # Entradas y valor esperado
    x = np.array([x0,x1,x2,x3,1])                        # Arreglo de entradas
    x_w = (w0.T * x)                                     # Multiplicación de entradas por los pesos
    suma = x_w[0] + x_w[1] + x_w[2] + x_w[3] +x_w[4]     # Sumatoria de los productos
    error = suma - y

    w0 = w0 - u * x * error # Actualización de los pesos

    errorTN = Error4Dataframe(w0, df_TN)                   # Cálculo del error
    error_T.append(errorTN)                                # Se agrega el error calculado al arreglo de errores de entrenamiento

     ###########    Prueba  ##########
    errorP = Error4Dataframe(w0, df_PN)                                 # Cálculo del error
    error_P.append(errorP)                               # Se agrega el error calculado al arreglo de errores de prueba

    iter += 1     #Contador de iteraciones
    if iter > 500:   #Límite de iteraciones
        error = 0.02
        t = 6

####### Gráfica de resultados ################
x = np.arange(0,len(error_T))    # Vector que representa el número de iteraciones

plt.plot(x, np.abs(error_T), 'x', label = "Entrenamiento")  #Gráfica de arreglo de errores de Entrenamiento
plt.plot(x, np.abs(error_P), 'o',label = "Prueba")          #Gráfica de arreglo de errores de Prueba
plt.xlabel("Iteraciones")    # Etiqueta de eje X
plt.ylabel("Error")          # Etiqueta de eje Y
plt.title("Error Entrenamiento y Prueba")   # Título del gráfico
plt.legend()
plt.show()

# %%
error_R = []
for k in range(15):

    ########## Validación  ############
    x1,x2,x3,x4 =  df_RN.iloc[k, 0], df_RN.iloc[k, 1],df_RN.iloc[k, 2], df_RN.iloc[k, 3]  # Entradas
    x_R = np.array([x1,x2,x3,x4,1])                                                       # Arreglo de entradas
    xR_w = (w0.T * x_R)                                                                   # Multiplicación de entradas por los pesos
    sumaR = xR_w[0] + xR_w[1] + xR_w[2] + xR_w[3] +xR_w[4]                                # Sumatoria de los productos
    error_R.append(sumaR)                                                                 # Se agrega el resultado calculado al arreglo error_R

x = np.arange(0,len(error_R))    # Vector que representa el número de iteraciones
plt.plot(x, np.abs(error_R), 'o')

plt.xlabel("Elemento")
plt.ylabel("Valor obtenido")
plt.title("Validación 4 descriptores")
plt.show()


import cv2
import numpy as np
import os
import json

with open("config.json",mode="r",encoding="utf-8") as j:
  config = json.load(j)

def main(img,name):
  height = img.shape[0]
  width = img.shape[1]
  shape_int = config["max_pixel"]
  if height >= width:
    mag = shape_int / height
    img = cv2.resize(img, (int(width*mag) ,shape_int))
  elif height <= width:
    mag = shape_int / width
    img = cv2.resize(img, (shape_int, int(height*mag)))
  if img.ndim == 3:
      img = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)
  else:
      img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)

  img_array = np.asarray(img)
  y = shape_int
  lines = []
  for i in img_array:
    x = shape_int
    for v in i:
      command = f"particle dust {round(v[0] / 256, 8)} {round(v[1] / 256, 8)} {round(v[2] / 256, 8)} {round(v[3] / 255 * 0.5, 6)} ^{round(x*0.1,1)} ^{round(y*0.1,1)} ^ 0 0 0 0 1 {config['particle']}\n"
      x -= 1

      lines.append(command)
    y -= 1
  with open(f"{name}.mcfunction",mode="w",encoding="utf-8") as f:
    f.writelines(lines)

if __name__ == "__main__":
  print("###############################################################\n")
  print(" Image-To-Particle v0.1")
  print(" https://github.com/0kq-github/image-to-particle")
  print("\n###############################################################")
  img_path = input("画像ファイル名を入力してください: ")
  img = cv2.imread(img_path,cv2.IMREAD_UNCHANGED)
  name = os.path.splitext(os.path.basename(img_path))[0]
  main(img,name)
  print(f"変換が完了しました！\nファイル名: {name}.mcfunction")
  input("Enterキーで終了します... ")


import sys, json
import awspice
import botocore
if sys.version_info >= (3, 3):
    from unittest.mock import patch
else:
    from mock import patch

calls = [
    'DescribeInstances',
]

def load(filepath):
    with open(filepath) as file:
        content = json.loads(file.read())
    return content

@patch("botocore.client.BaseClient._make_api_call")
def test_get_instances(mock):
    mock.return_value=load('test/data/ec2/instances.json')
    region = 'eu-west-1'
    x = awspice.connect(region).service.ec2.get_instances()
    assert all(instance['Region']['RegionName'] == region for instance in x)


import argparse
import numpy as np
import nrrd
import nibabel as nib
def main():
    """Take a list of seedpoints in pts format and create a labed nrrd files

    Returns
    -------

    """

    parser = argparse.ArgumentParser(
        description='This script performs tracking along a multi vector field')

    parser.add_argument('-i', help='Infile')
    parser.add_argument('-o', help='Outfile')
    parser.add_argument('-n', help='nrrd file with meta data')
    parser.add_argument("-r", help="create region", action='store_false')
    args = parser.parse_args()
    seeds = np.loadtxt(args.i)
    wm, meta = nrrd.read(args.n)
    labels = np.zeros(wm.shape, dtype=np.float32)
    trafo = np.zeros((4,4))
    trafo[:3,:3] = meta['space directions']
    trafo[3,3] = 1
    trafo[:3,3] = meta['space origin']
    trafo = np.linalg.inv(trafo)
    sc = np.ones((seeds.shape[0], 4))
    sc[:, :3] = seeds[:,:3]
    for i in range(seeds.shape[0]):
      #  sc = np.ones(4)

        sc[i] = trafo @ sc[i]
        if args.r:
            labels[int(sc[i,0]), int(sc[i,1]), int(sc[i,2])] = 1
    if not args.r:
        smin = np.min(sc, axis=0)
        print(smin)
        smax = np.max(sc, axis=0) + 2
        labels[int(smin[0]):int(smax[0]), int(smin[1]):int(smax[1]), int(smin[2]):int(smax[2])] = 1

    if args.o.endswith('nrrd'):
        nrrd.write(args.o, np.int16(labels), meta)
    elif args.o.endswith('nii.gz'):
        affine = np.zeros((4,4))
        affine[3,3] = 1
        affine[:3,:3] = meta['space directions']
        affine[:3,3] = meta['space origin']
        out_img = nib.Nifti1Image(np.int16(labels), affine)
        nib.save(out_img, args.o)
    else:
        print('unsupported format. Only nrrd and nii.gz are supported')

if __name__ == '__main__':
    main()


import cv2
from keras.models import load_model
import numpy as np
face_cascade = cv2.CascadeClassifier("C:/Users/Dell/AppData/Local/Programs/Python/Python310/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
result=["DoMixi","Nhism","Phuong","Ram-bo","Thay ba"]
model=load_model("nhan_dien.h5")
def anh(dirr):
    img=cv2.imread(dirr)
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3,5)

    for (x,y,w,h) in faces:
        roi=cv2.resize(img[y:y+h,x:x+w],(64,64))
        kq=np.argmax(model.predict(roi.reshape(-1,64,64,3)))
        cv2.putText(img,result[kq],(x+10,y-10),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,0,0))
    while True:
        cv2.imshow('Face Detection',img)

        # Nhấn 'q' để thoát
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
def vd(dirr=0):
    cap=cv2.VideoCapture(dirr)
    while True:
        ret,fram=cap.read()
        if ret==False:
            break
        gray = cv2.cvtColor(fram, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, 1.3,5)
        for (x,y,w,h) in faces:
            roi=cv2.resize(fram[y:y+h,x:x+w],(64,64))
            kq=np.argmax(model.predict(roi.reshape(-1,64,64,3)))
            cv2.putText(fram,result[kq],(x+10,y-10),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,0,0),1)
        cv2.imshow('Face Detection',fram)
        if cv2.waitKey(1)  & 0xFF == ord('q'):
            break

if __name__=="__main__":
    vd(0)
    # anh("C:\\Users\\Dell\\Pictures\\Screenshots\\Screenshot 2023-06-30 213401.png")


#Authors: Daniel Briseno, Matthew Raymond
import csv
from os import path
#helper methods
def extractNames(rawName:str):
        name_lst = rawName.split(" ")
        if len(name_lst)==2:
            name_lst.insert(1,'!')
        return name_lst

def extractClass(rawClass:str):
    class_lst = rawClass.split(" ")
    class_dict = {}
    class_dict["Class_ID"] = " ".join(class_lst[:2])
    class_dict["Class_Name"] = " ".join(class_lst[2:])
    return class_dict

#these constants make list indexing simpler when
#dealing with faker data
s_name = 0
sid = 1
t_ins = 2
t_outs = 3
t_name = 4
tid = 5
t_intu = 6
t_outtu = 7
class_name = 8
table = 9

class Data_Extractor:
    '''The purpose of this class is to create lists from output.csv that can be easily
    inputted to the database.
    It creates lists of the form:
        tutor_class := [(tutor_id:int, class_id:str)]
        classes :=[(class_id:str, class_name:str)]
        student_tmsht := [(student_id:int, time_in_student:str, time_out_student:str, tutor_id:int)]
        tutor_tmsht := [(time_in_tutor:str, tutor_id:int, time_out_tutor:str, table:int)]
        students := [(first_name:str, middle_name:str, last_name:str, student_id:int)]
    '''

    def __init__(self,csv_path = "output.csv"):
        '''
        DESC: Class constructor
        INPUT: File path to csv faker file, defaults to ./output.csv
        '''
        if not path.exists(csv_path):
            print("csv file", csv_path, "not found, application exiting")
            exit(0)
        self.classes = []
        self.student_tmsht = []
        self.tutor_tmsht = []
        self.students = []
        self.tutor_classes = []
        self.extract(csv_path)

    def extract(self, csv_path):
        '''
        DESC: This method iterates through each line of the file at csv_path and calls various
        functions which build the 5 lists mentioned in the class description

        INPUT: csv_path:str
            - A path to a csv file containing faker data with columns (from left to right):
                Student Name: string (fname [mname] lname)
                Student ID: int
                Time in: string (DATETIME)
                Time Out: string (DATETIME)
                Tutor Name: string (fname [mname] lname)
                Tutor ID: int
                Tutor time out: string (DATETIME)
                Tutor time out: string (DATETIME)
                Class: str (class_subject class_number class_full_name)
                Table: int
        OUTPUT: None
        '''
        with open(csv_path) as f:
            for row in f:
                row = row.split(", ")
                #skip first row
                if not row[sid].isnumeric():
                    continue
                #populate lists
                self.add_to_classes(row)
                self.add_to_students(row)
                self.add_to_student_tmsht(row)
                self.add_to_tutor_tmsht(row)
                self.add_to_tutor_class(row)

    def add_to_tutor_class(self,row):
        '''
        DESC: Adds relevant row items as a tuple to tutors_class list

        INPUT: row:list
            - A list of items as described in extract() docstrings

        OUTPUT: None
        '''
        tutor_id = row[tid]
        class_id = extractClass(row[class_name])['Class_ID']
        item = (tutor_id,class_id)
        #ensure list items are unique
        if not item in self.tutor_classes:
            self.tutor_classes.append(item)

    def add_to_student_tmsht(self, row):
        '''
        DESC: Adds relevant row items as a tuple to student_tmsht list

        INPUT: row:list
            - A list of items as described in extract() docstrings

        OUTPUT: None
        '''
        student_id = int(row[sid])
        t_in = row[t_ins]
        t_out = row[t_outs]
        tutor_id = int(row[tid])
        session = (t_in,student_id,t_out,tutor_id)
        #ensure list items are unique
        if not session in self.student_tmsht:
            self.student_tmsht.append(session)

    def add_to_tutor_tmsht(self, row):
        '''
        DESC: Adds relevant row items as a tuple to tutor_tmsht list

        INPUT: row:list
            - A list of items as described in extract() docstrings

        OUTPUT: None
        '''
        tutor_id = int(row[tid])
        time_in = row[t_intu]
        time_out = row[t_outtu]
        tbl = int(row[table][:-1])
        class_id = extractClass(row[class_name])["Class_ID"]
        shift = (time_in,tutor_id,time_out,tbl)
        #ensure list items are unique
        if not shift in self.tutor_tmsht:
            self.tutor_tmsht.append(shift)

    def add_to_classes(self,row):
        '''
        DESC: Adds relevant row items as a tuple to classes list

        INPUT: row:list
            - A list of items as described in extract() docstrings

        OUTPUT: None
        '''
        class_dict = extractClass(row[class_name])
        class_ident =(class_dict['Class_ID'],class_dict['Class_Name'])
        #ensure list items are unique
        if not class_ident in self.classes:
            self.classes.append(class_ident)

    def add_to_students(self, row):
        '''
        DESC: Adds relevant row items as a tuple to students list

        INPUT: row:list
            - A list of items as described in extract() docstrings

        OUTPUT: None
        '''
        #create (id,fname, mname, lname) tuple for student entry
        name1 = extractNames(row[s_name])
        id1 = int(row[sid])
        ident1 = ([id1]+name1)
        #create (id,fname,mname,lname) tuple for tutor entry, who is a student as well
        #and should be added to the student list
        name2 = extractNames(row[t_name])
        id2 = int(row[tid])
        ident2 = ([id2]+name2)
        #enter tuples into list if not already there
        if not ident1 in self.students:
            self.students.append(ident1)
        if not ident2 in self.students:
            self.students.append(ident2)

if __name__ == '__main__':
    extractor = Data_Extractor()
    print(extractor.classes)
    print('\n\n\n')
    print(extractor.tutor_classes)
    print('\n\n\n')
    print(extractor.tutor_tmsht)
    print('\n\n\n')
    print(extractor.student_tmsht)
    print('\n\n\n')
    print(extractor.students)
    print(len(extractor.students))


#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import numpy as np
import os
import xlrd
# import selfdata_processing
import sqlite3 as sql

aminoacid = {}
conn = sql.connect('protein_database.db')
c = conn.cursor()

def read_excel():#从excel中对文件,将对应氨基酸及其属性,以键值对的方式写入字典中
        # 打开文件D:\bishe\Aminoacid.xlsx
    fileName = 'C:\\bishe\data\Aminoacid.xlsx'
    workbook = xlrd.open_workbook(fileName)
    sheet = workbook.sheet_by_name('Sheet1')
    # print(sheet.name, sheet.nrows, sheet.ncols)

    # 获取20个氨基酸
    cols = sheet.col_values(2)
    cols.pop(0)
    cols.pop(-1)
    cols.pop(-1)

    # print(cols)
    i = 1
    for x in cols:
        rows = sheet.row_values(i)
        rows.pop(0)
        rows.pop(0)
        rows.pop(0)
        rows.pop(0)
        rows.pop(1)
        rows.pop(2)
        rows.pop(4)
        rows.pop(4)
        # print(rows)
        aminoacid.setdefault(x, rows)
        i = i+1
    # print(aminoacid)
    a = 'A'
    # print(aminoacid[a][1])

#氨基酸的独热编码
def get_seq_onehot(seq, feature):
    strs = 'ACDEFGHIKLMNPQRSTVWXY '
    seqs = []
    for i in range(len(strs)):
        if seq == strs[i]:
            feature.append(1)
        else:
            feature.append(0)
    return feature

#PDBID = 2A0B
def get_PDBid_feature(PDBid):
    cursor = c.execute("SELECT * FROM PDB_DSSP WHERE PDB_id ='%s' " % PDBid)
    count = 0
    aminoacids = 'ACDEFGHIKLMNPQRSTVWY'
    for i in cursor:
        count += 1
    # print(PDBid,'的长度为：',count)
    #用矩阵存储信息,22个氨基酸独热+8个feature， count+3+3：前后补3个Noseq
    pdb_xtrain = np.zeros((count + 6, 22+6))
    #虽然前后补上Noseq，但是还是分8类，因为并没有对前后不上的进行预测

    count1 = 0
    #前补3个Noseq
    feature = [0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,1, 0,0,0,0,0,0]
    for i in range(3):
        pdb_xtrain[count1, ] = feature
        count1 += 1
    cursor = c.execute("SELECT * FROM PDB_DSSP WHERE PDB_id ='%s' " % PDBid)
    #每个循环为矩阵添加一行
    for row in cursor:
        # print(row)
        feature = []
        temp = row[1]

        #序列和属性
        get_seq_onehot(row[1], feature)
        #XX表示任意一种氨基酸或者不确定种类，我们把X当成A处理
        for i in range(20):
            if temp != aminoacids[i]:
                temp = 'A'
        for i in aminoacid[temp]:
            feature.append(i)
        # print(feature)
        pdb_xtrain[count1, ] = feature
        count1 += 1

    # 后补3个Noseq
    feature = [0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,1, 0,0,0,0,0,0]
    for i in range(3):
        pdb_xtrain[count1,] = feature
        count1 += 1

    # conn.close()
    # pdb_xtrain = (-1,30),pdb_ytrain =(-1 ,8)
    # print(pdb_xtrain)
    return pdb_xtrain

#滑动窗口默认按照每7个滑动,形成shape = (-1, 7, 28)
def slide_window(pdb_xtrain):
    size = np.size(pdb_xtrain, axis=0)
    xtrain = np.zeros((size-6, 7, 28))
    x = np.zeros((7, 28))
    for i in range(size - 6):
        for j in range(7):
            x[j, ] = pdb_xtrain[i+j, ]
        xtrain[i, ] = x
    return xtrain

def get_PDBid():#从数据库中获取PDB
    # conn = sql.connect('protein_database.db')
    # c = conn.cursor()
    cursor = c.execute('SELECT PDB_id FROM PDB_id')
    count = 0
    line = []
    same = 'abcd' #用于判断相同的PDBid
    for row in cursor:
        row = row[0]
        if row[0:4] != same:
            line.append(row[0:4])
            count += 1
        same = row[0:4]
    print('diferent id:',count)
    # print('pdb:',count) #6626
    # conn.close()
    # for i in range(0, count):
    #     PDB_id = line[i]
        # print('READING:',PDB_id, '   ', i,'/6626')

    return line

if __name__ == '__main__':#x_train = (3185724, 7, 28),y_train = (3185724, 7, 8),start time:15:20,end time:
    x_train = np.zeros((3185724, 7, 28))

    read_excel()

    #获取所有PDBid
    PDB_id_lines = get_PDBid()
    count = 0
    count1 = 0
    for pdb in PDB_id_lines:
    # for i in range(1):
        print('reading:',pdb, count ,'   ',count1,'/ 3185724')
        pdb_xtrain = get_PDBid_feature(pdb)

        pdb_xtrain = slide_window(pdb_xtrain)
        # print('re:', pdb_xtrain[0])
        for k in range(np.size(pdb_xtrain, axis=0)):
            x_train[count1, ] = pdb_xtrain[k]
            count1 += 1

        count += 1
    conn.close()
    #将x_train,y_train 数组保存到文件中
    np.save('cullpdb_chains6626_x_train_aminoacid.npy', x_train)

    print(np.shape(x_train))
    print('x_train successful!')
    # print(x_train[:1, :,:])
    # print(y_train[0:20, :])


import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image
import face_recognition
import time

def select_input_directory():
    input_directory = filedialog.askdirectory()
    input_directory_entry.delete(0, tk.END)
    input_directory_entry.insert(tk.END, input_directory)

def select_output_directory():
    output_directory = filedialog.askdirectory()
    output_directory_entry.delete(0, tk.END)
    output_directory_entry.insert(tk.END, output_directory)

def select_known_faces_directory():
    known_faces_directory = filedialog.askdirectory()
    known_faces_directory_entry.delete(0, tk.END)
    known_faces_directory_entry.insert(tk.END, known_faces_directory)

def perform_face_filtering():
    input_directory = input_directory_entry.get()
    output_directory = output_directory_entry.get()
    known_faces_directory = known_faces_directory_entry.get()

    if not input_directory or not output_directory or not known_faces_directory:
        messagebox.showerror("Error", "Please select all directories.")
        return

    if not os.path.exists(input_directory):
        messagebox.showerror("Error", "Input directory does not exist.")
        return

    if not os.path.exists(known_faces_directory):
        messagebox.showerror("Error", "Known faces directory does not exist.")
        return

    #create output directory if doesn't exist
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # Create a directory for images with no match
    no_match_directory = os.path.join(output_directory, "no_match")
    if not os.path.exists(no_match_directory):
        os.makedirs(no_match_directory)

    subfolders = [f for f in os.listdir(known_faces_directory) if os.path.isdir(os.path.join(known_faces_directory, f))]
    num_subfolders = len(subfolders)
    total_files = len(os.listdir(input_directory))
    processed_files = 0

    #create the progress bar
    percentage_label = tk.Label(window, text="0%", bg="#e5e5e5")
    percentage_label.place(x=200, y=300, anchor=tk.CENTER)

    progress_label = tk.Label(window, text="Progress: ", bg="#e5e5e5")
    progress_label.place(x=30, y=320, anchor=tk.W)

    progress_bar = tk.Canvas(window, width=200, height=20, bg="white", relief=tk.SUNKEN)
    progress_bar.place(x=200, y=320, anchor=tk.CENTER)

    # Iterate over the subdirectories in the known faces directory
    for person_name in os.listdir(known_faces_directory):
        person_directory = os.path.join(known_faces_directory, person_name)

        if not os.path.isdir(person_directory):
            continue  # Skip non-directory entries

        # Create a corresponding output directory for this person
        person_output_directory = os.path.join(output_directory, person_name)
        if not os.path.exists(person_output_directory):
            os.makedirs(person_output_directory)

        # Load the known face encodings for this person
        known_faces_encodings = []
        for file_name in os.listdir(person_directory):
            image = face_recognition.load_image_file(
                os.path.join(person_directory, file_name))
            face_encodings = face_recognition.face_encodings(image)
            if face_encodings:
                known_faces_encodings.extend(face_encodings)

        # Iterate over the input directory
        for file_name in os.listdir(input_directory):
            image_path = os.path.join(input_directory, file_name)

            # Load the input image
            image = face_recognition.load_image_file(image_path)

            # Find face locations and encodings in the image
            face_locations = face_recognition.face_locations(image)
            face_encodings = face_recognition.face_encodings(image, face_locations)

            # Flag to indicate if any match is found
            match_found = False

            # Iterate over the face encodings in the image
            for face_encoding in face_encodings:
                # Compare the face encoding with the known face encodings
                matches = face_recognition.compare_faces(
                    known_faces_encodings, face_encoding)

                if any(matches):
                    # Copy the image to the corresponding person's directory
                    shutil.copy2(image_path, person_output_directory)
                    print(
                        f"Image '{file_name}' contains a known face ({person_name}) and has been copied to ({person_output_directory}) directory.")
                    match_found = True
                    break

            # Update the progress bar
            processed_files += 1
            progress_percentage = ((processed_files / total_files) * 100)/num_subfolders
            percentage_label["text"] = f"{int(progress_percentage)}%"
            progress_bar.create_rectangle(0, 0, progress_percentage * 2, 20, fill="#8bc34a")
            progress_bar.update()
            time.sleep(0.1)

    if not match_found:
                # Move the image to the 'no_match' directory
                no_match_path = os.path.join(no_match_directory, file_name)
                shutil.copy2(image_path, no_match_path)
                print(
                    f"Image '{file_name}' does not contain a known face and has been moved to 'no_match' folder.")

    messagebox.showinfo("Success", "Face filtering complete.")

#main window
window = tk.Tk()
window.title("Face Filtering")
window.geometry("400x500")
window.resizable(False, False)
window.iconbitmap("icon.ico")
window.configure(bg="#e5e5e5")

"""
#background image
background_image = ImageTk.PhotoImage(Image.open("background.jpg"))
background_label = tk.Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
"""

#input
input_directory_label = tk.Label(window, text="Select Input Directory:", bg="#e5e5e5")    #label
input_directory_label.place(x=70, y=30, anchor=tk.W)

input_directory_entry = tk.Entry(window, width=30)      #entry
input_directory_entry.place(x=70, y=60, anchor=tk.W)

input_directory_button = tk.Button(window, text="Browse...", command=select_input_directory, bg="#000000", fg="white", activebackground="#3b3b3b", activeforeground="white", relief=tk.FLAT, cursor="hand2")        #button
input_directory_button.place(x=260, y=60, anchor=tk.W)

#output
output_directory_label = tk.Label(window, text="Select Output Directory:", bg="#e5e5e5")    #label
output_directory_label.place(x=70, y=100, anchor=tk.W)

output_directory_entry = tk.Entry(window, width=30)          #entry
output_directory_entry.place(x=70, y=130, anchor=tk.W)

output_directory_button = tk.Button(window, text="Browse...", command=select_output_directory, bg="#000000", fg="white", activebackground="#3b3b3b", activeforeground="white", relief=tk.FLAT, cursor="hand2")         #button
output_directory_button.place(x=260, y=130, anchor=tk.W)

#known faces
known_faces_directory_label = tk.Label(window, text="Select Known Faces Directory:", bg="#e5e5e5")      #label
known_faces_directory_label.place(x=70, y=170, anchor=tk.W)

known_faces_directory_entry = tk.Entry(window, width=30)             #entry
known_faces_directory_entry.place(x=70, y=200, anchor=tk.W)

known_faces_directory_button = tk.Button(window, text="Browse...", command=select_known_faces_directory, bg="#000000", fg="white", activebackground="#3b3b3b", activeforeground="white", relief=tk.FLAT, cursor="hand2")           #button
known_faces_directory_button.place(x=260, y=200, anchor=tk.W)

#perform face filtering button
filter_button = tk.Button(window, text="Perform Face Filtering", command=perform_face_filtering, bg="#f44336", fg="black", activebackground="#d32f2f", activeforeground="white", relief=tk.FLAT, cursor="hand2")
filter_button.place(x=200, y=250, anchor=tk.CENTER)

#direction label
direction_label = tk.Label(window, text="* Input directory is the folder where there are photos to be filtered\n\n * Output directory is the folder to put the filtered photos\n\n * Known faces directory is the folder that has the known faces", bg="#e5e5e5")
direction_label.pack(side="bottom")

window.mainloop()


# 1978번
l=[True for _ in range(1001)]
l[1]=False
for i in range(2,int(1000**0.5)+1):
    if l[i]:
        j=i+i
        while j<=1000:
            l[j]=False
            j+=i
input()
result=0
for i in [*map(int,input().split())]:
    if l[i]:
        result+=1
print(result)


from cell import Cell
import random
import pygame as pg
pg.init()

class Board:
    def __init__(self, gridSize, cellSize):
        self.gridSize = gridSize
        self.cellSize = cellSize
        size = self.gridSize*self.cellSize
        self.screen = pg.display.set_mode((size, size))

        self.cells = []
        self.generation = 0

        for i in range(self.gridSize):
            rad = []
            for k in range(self.gridSize):
                rad.append(Cell([k, i]))
            self.cells.append(rad)

        #self.generate()
        self.draw()

    def generate(self):
        for i in self.cells:
            for k in i:
                if random.randint(0,2) == 0:
                    k.active = True

    def draw(self):
        self.screen.fill((0,0,0))
        for i in self.cells:
            for k in i:
                if k.active:
                    pg.draw.rect(self.screen, (255,255,255), pg.rect.Rect(k.pos[0]*self.cellSize, k.pos[1]*self.cellSize, self.cellSize, self.cellSize))
        pg.display.flip()

    def getFriends(self, cell):
        pos = cell.pos
        cells = []
        for i in [[-1,-1], [0,-1], [1,-1], [-1,0], [1,0], [-1,1], [0,1], [1,1]]:
            if pos[0] + i[0] < 0 or pos[0] + i[0] > self.gridSize-1 or pos[1] + i[1] < 0 or pos[1] + i[1] > self.gridSize-1:
                continue
            cells.append([pos[0] + i[0], pos[1] + i[1]])
        activeCount = 0
        for i in cells:
            if self.cells[i[1]][i[0]].active:
                activeCount += 1
        return activeCount

    def nextGeneration(self):
        switch = []
        for i in self.cells:
            for k in i:
                activeCount = self.getFriends(k)
                if k.active and (activeCount < 2 or activeCount > 3):
                    switch.append(k)
                elif not k.active and activeCount == 3:
                    switch.append(k)
        for i in switch:
            i.active = not i.active
        self.generation += 1

    def click(self, pos):
        cell = self.cells[pos[1]][pos[0]]
        cell.active = not cell.active


from django.conf.urls import url
from django.urls import path, include

from rest_framework import routers

from .views import (
    ImgView,
    LogicImgView, OptImgView, ImgUtilView
)
app_name = 'kuukann'

router = routers.DefaultRouter()
router.register(r'img', ImgView)

urlpatterns = [
    url(r'^', include(router.urls)),

    path('logic_img', LogicImgView.as_view()),
    path('opt_img/<int:lucy>', OptImgView.as_view()),
    path('util_img/<int:lucy>', ImgUtilView.as_view())
]


d = {}

for x in range(int(input())):
    s,i = map(str,input().split())
    if s in d:
        d[s] += int(i)
    else:
        d[s] = int(i)

l = []

for x in d.values():
    l.append(x)
l.sort()
for key in sorted(d):
    if d[key] == l[-1]:
        print(key,'is lucky!')
    else:
        print(key,'has to receive',l[-1]-d[key],'tenge')


"""
「猫」とよく共起する（共起頻度が高い）10語とその出現頻度をグラフ（例えば棒グラフなど）で表示せよ．
"""
import pandas as pd
from collections import defaultdict
import plotly.express as px
from plotly.offline import plot

def parseMecab(block):
    res = []
    for line in block.split('\n'):
        if line == '':
            return res
        (surface, attr) = line.split('\t')
        attr = attr.split(',')
        lineDict = {
            'surface': surface,
            'base': attr[6],
            'pos': attr[0],
            'pos1': attr[1]
        }
        res.append(lineDict)

def extract(block):
    return [b['base'] for b in block]

filename = 'neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
    blockList = f.read().split('EOS\n')
blockList = list(filter(lambda x: x != '', blockList))
blockList = [parseMecab(block) for block in blockList]
wordList = [extract(block) for block in blockList]
wordList = list(filter(lambda x: '猫' in x, wordList))
d = defaultdict(int)
for word in wordList:
    for w in word:
        if w != '猫':
            d[w] += 1
ans = sorted(d.items(), key=lambda x: x[1], reverse=True)[:10]

ans = pd.DataFrame(ans)
ans.columns = ['word', 'word_count']

fig = px.bar(
    ans.sort_values('word_count'),
    y='word',
    x='word_count',
    text='word_count',
    orientation='h',
)
fig.update_traces(
    texttemplate='%{text:.2s}',
    textposition='auto',
)
fig.update_layout(
    title=str('「猫」との共起回数上位10語'),
    xaxis_title=str('「猫」との共起数'),
    yaxis_title=str('単語'),
    width=1000,
    height=500,
)
plot(fig, filename='ans_37_plot.html', auto_open=False)


import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

from borealisflows.noise_flow_layers.AffineCouplingCondXY import AffineCouplingCondXY
from borealisflows.noise_flow_layers.AffineCouplingCondXYG import AffineCouplingCondXYG
from borealisflows.noise_flow_layers.AffineCouplingCondY import AffineCouplingCondY
from borealisflows.noise_flow_layers.AffineCouplingCondYG import AffineCouplingCondYG
from borealisflows.noise_flow_layers.AffineCouplingGain import AffineCouplingGain
from borealisflows.noise_flow_layers.AffineCouplingGainEx1 import AffineCouplingGainEx1
from borealisflows.noise_flow_layers.AffineCouplingGainEx2 import AffineCouplingGainEx2
from borealisflows.noise_flow_layers.AffineCouplingGainEx3 import AffineCouplingGainEx3
from borealisflows.noise_flow_layers.AffineCouplingGainEx4 import AffineCouplingGainEx4
from borealisflows.noise_flow_layers.AffineCouplingSdn import AffineCouplingSdn
from borealisflows.noise_flow_layers.AffineCouplingSdnEx1 import AffineCouplingSdnEx1
from borealisflows.noise_flow_layers.AffineCouplingSdnEx2 import AffineCouplingSdnEx2
from borealisflows.noise_flow_layers.AffineCouplingSdnEx3 import AffineCouplingSdnEx3
from borealisflows.noise_flow_layers.AffineCouplingSdnEx4 import AffineCouplingSdnEx4
from borealisflows.noise_flow_layers.AffineCouplingSdnEx5 import AffineCouplingSdnEx5
from borealisflows.noise_flow_layers.AffineCouplingSdnEx6 import AffineCouplingSdnEx6
from borealisflows.noise_flow_layers.AffineCouplingSdnGain import AffineCouplingSdnGain
from borealisflows.noise_flow_layers.AffineCouplingCamSdn import AffineCouplingCamSdn
from borealisflows.noise_flow_layers.AffineCouplingFitSdnGain2 import AffineCouplingFitSdnGain2
from borealisflows.layers import real_nvp_conv_template_iso
from borealisflows.layers import AffineCoupling
from borealisflows.layers import real_nvp_conv_template
from borealisflows.layers import Conv2d1x1
from borealisflows.layers import conv2d_zeros
from borealisflows.utils import int_shape
from borealisflows.utils import squeeze2d
from borealisflows.utils import unsqueeze2d

tfd = tfp.distributions
tfb = tfp.bijectors

class NoiseFlow(object):

    def __init__(self, x_shape, is_training, hps=None):
        self.x_shape = x_shape
        self.depth = hps.depth
        self.n_levels = hps.n_levels
        self._is_training = is_training
        self.hps = hps
        self.model = self.define_flow_structure()

    def define_flow_structure(self):
        model = []
        x_shape = self.x_shape
        for i in range(self.n_levels):
            if self.hps.squeeze_factor != 1:
                if i == 0:
                    x_shape = [x_shape[0] // 2, x_shape[1] // 2, x_shape[2] * 4]
                else:
                    x_shape = [x_shape[0] // 2, x_shape[1] // 2, x_shape[2] * 2]
            if self.hps.arch is not None:
                model.append(self.noise_flow_arch('level{}'.format(i), x_shape,
                                                  self.hps.flow_permutation, self.hps.arch))
            else:
                model.append(self.revnet2d('level{}'.format(i), x_shape,
                                           self.hps.flow_permutation))
        return model

    def noise_flow_arch(self, name, x_shape, flow_permutation, arch):
        arch_lyrs = arch.split('|')  # e.g., unc|sdn|unc|gain|unc
        bijectors = []
        with tf.variable_scope(name):
            for i, lyr in enumerate(arch_lyrs):
                with tf.variable_scope('bijector{}'.format(i)):
                    is_last_layer = False

                    if lyr == 'unc':
                        if flow_permutation == 0:
                            print('|-tfb.Permute')
                            bijectors.append(
                                tfb.Permute(
                                    permutation=list(range(x_shape[-1]))[::-1]))
                        elif flow_permutation == 1:
                            print('|-Conv2d1x1')
                            bijectors.append(
                                Conv2d1x1(x_shape, layer_id=i, bias=False,
                                          decomp=self.hps.decomp,
                                          name='Conv2d_1x1_{}'.format(i)))
                        else:
                            print('|-No permutation specified. Not using any.')
                            # raise Exception("Flow permutation not understood")

                        print('|-AffineCoupling')
                        bijectors.append(
                            AffineCoupling(
                                name='unc_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template(
                                    x_shape=x_shape,
                                    is_training=self._is_training,
                                    width=self.hps.width)))

                    elif lyr == 'sdn':
                        print('|-AffineCouplingSdn')
                        bijectors.append(
                            AffineCouplingSdn(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None
                            )
                        )
                    elif lyr == 'sdn1':
                        print('|-AffineCouplingSdnEx1')
                        bijectors.append(
                            AffineCouplingSdnEx1(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None
                            )
                        )
                    elif lyr == 'sdn2':
                        print('|-AffineCouplingSdnEx2')
                        bijectors.append(
                            AffineCouplingSdnEx2(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init
                            )
                        )
                    elif lyr == 'sdn3':
                        print('|-AffineCouplingSdnEx3')
                        bijectors.append(
                            AffineCouplingSdnEx3(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init
                            )
                        )
                    elif lyr == 'sdn4':
                        print('|-AffineCouplingSdnEx4')
                        bijectors.append(
                            AffineCouplingSdnEx4(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init
                            )
                        )
                    elif lyr == 'sdn5':
                        print('|-AffineCouplingSdnEx5')
                        bijectors.append(
                            AffineCouplingSdnEx5(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init,
                                param_inits=self.hps.param_inits
                            )
                        )
                    elif lyr == 'sdn6':
                        print('|-AffineCouplingSdnEx6')
                        bijectors.append(
                            AffineCouplingSdnEx6(
                                name='sdn_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init,
                                param_inits=self.hps.param_inits
                            )
                        )
                    elif lyr == 'gain':
                        print('|-AffineCouplingGain')
                        bijectors.append(
                            AffineCouplingGain(
                                name='gain_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None
                            )
                        )
                    elif lyr == 'gain1':
                        print('|-AffineCouplingGainEx1')
                        bijectors.append(
                            AffineCouplingGainEx1(
                                name='gain_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None
                            )
                        )
                    elif lyr == 'gain2':
                        print('|-AffineCouplingGainEx2')
                        bijectors.append(
                            AffineCouplingGainEx2(
                                name='gain_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init
                            )
                        )
                    elif lyr == 'gain3':
                        print('|-AffineCouplingGainEx3')
                        bijectors.append(
                            AffineCouplingGainEx3(
                                name='gain_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None
                            )
                        )
                    elif lyr == 'gain4':
                        print('|-AffineCouplingGainEx4')
                        bijectors.append(
                            AffineCouplingGainEx4(
                                name='gain_%d' % i,
                                last_layer=False,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None,
                                gain_init=self.hps.gain_init
                            )
                        )
        return bijectors

    def revnet2d(self, name, x_shape, flow_permutation):
        """Affine coupling"""
        print('sidd_cond = %s' % self.hps.sidd_cond)
        bijectors = []
        with tf.variable_scope(name):
            # append an SDN layer (2nd degree) next to base measure
            if self.hps.append_sdn2:
                with tf.variable_scope('bijector_sdn2'):
                    print('|-AffineCouplingFitSdnGain2')
                    bijectors.append(
                        AffineCouplingFitSdnGain2(
                            name='ac_fitSdnGain2_%d' % self.depth,
                            last_layer=False,
                            x_shape=x_shape,
                            shift_and_log_scale_fn=None
                        )
                    )
            # append an SDN layer next to base measure
            if self.hps.append_sdn_first:
                with tf.variable_scope('bijector_sdn'):
                    print('|-AffineCouplingFitSdnGain')
                    bijectors.append(
                        AffineCouplingSdnGain(
                            name='ac_fitSdnGain_%d' % self.depth,
                            last_layer=False,
                            x_shape=x_shape,
                            shift_and_log_scale_fn=None
                        )
                    )
            # append a y-conditional layer
            if self.hps.append_cY:
                with tf.variable_scope('bijector_cy'):
                    print('|-AffineCouplingCondY')
                    bijectors.append(
                        AffineCouplingCondY(
                            name='ac_cY_first',
                            last_layer=False,
                            x_shape=x_shape,
                            shift_and_log_scale_fn=real_nvp_conv_template(
                                x_shape=x_shape[:-1] + [x_shape[-1] * 2],  # double outputs
                                is_training=self._is_training,
                                width=self.hps.width)
                        )
                    )
            for i in range(self.depth):
                with tf.variable_scope('bijector{}'.format(i)):
                    # is_last_layer = True if i == self.depth - 1 else False
                    is_last_layer = False

                    # bijectors.append(
                    #     BatchNorm(x_shape, is_training=self._is_training,
                    #               name='batch_norm{}'.format(i)))

                    if flow_permutation == 0:
                        print('|-tfb.Permute')
                        bijectors.append(
                            tfb.Permute(
                                permutation=list(range(x_shape[-1]))[::-1]))
                    elif flow_permutation == 1:
                        print('|-Conv2d1x1')
                        bijectors.append(
                            Conv2d1x1(x_shape, layer_id=i, bias=False,
                                      decomp=self.hps.decomp,
                                      name='Conv2d_1x1_{}'.format(i)))
                    else:
                        print('|-No permutation specified. Not using any.')
                        # raise Exception("Flow permutation not understood")

                    if self.hps.sidd_cond == 'condY':
                        print('|-AffineCouplingCondY')
                        bijectors.append(
                            AffineCouplingCondY(
                                name='ac_cY_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template(
                                    x_shape=x_shape[:-1] + [x_shape[-1] * 2],  # double outputs
                                    is_training=self._is_training,
                                    width=self.hps.width)))
                    elif self.hps.sidd_cond == 'condYG':
                        print('|-AffineCouplingCondYG')
                        bijectors.append(
                            AffineCouplingCondYG(
                                name='ac_cYG_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template_iso(
                                    x_shape=x_shape[:-1] + [x_shape[-1] * 2],  # double outputs
                                    is_training=self._is_training,
                                    width=self.hps.width)))
                    elif self.hps.sidd_cond == 'condXY':
                        print('|-AffineCouplingCondXY')
                        bijectors.append(
                            AffineCouplingCondXY(
                                name='ac_cXY_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template(
                                    x_shape=x_shape,
                                    is_training=self._is_training,
                                    width=self.hps.width)))
                    elif self.hps.sidd_cond == 'condXYG':
                        print('|-AffineCouplingCondXYG')
                        bijectors.append(
                            AffineCouplingCondXYG(
                                name='ac_cXYG_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template_iso(
                                    x_shape=x_shape,
                                    is_training=self._is_training,
                                    width=self.hps.width)))
                    elif self.hps.sidd_cond == 'condSDN':
                        print('|-AffineCouplingSDN')
                        bijectors.append(
                            AffineCouplingCamSdn(
                                name='ac_cSDN_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template(
                                    x_shape=x_shape[:-1] + [x_shape[-1] * 2],  # double outputs
                                    is_training=self._is_training,
                                    width=self.hps.width)))
                    elif self.hps.sidd_cond == 'fitSDN':
                        print('|-AffineCouplingFitSDN')
                        bijectors.append(
                            AffineCouplingSdnGain(
                                name='ac_fitSDN_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=None))
                    else:  # uncond | unc_sdn
                        print('|-AffineCoupling')
                        bijectors.append(
                            AffineCoupling(
                                name='ac_unc_%d' % i,
                                last_layer=is_last_layer,
                                x_shape=x_shape,
                                shift_and_log_scale_fn=real_nvp_conv_template(
                                    x_shape=x_shape,
                                    is_training=self._is_training,
                                    width=self.hps.width)))
            # append an SDN layer next to data
            if self.hps.append_sdn:
                with tf.variable_scope('bijector{}'.format(self.depth)):
                    print('|-AffineCouplingFitSDN')
                    bijectors.append(
                        AffineCouplingSdnGain(
                            name='ac_fitSDN_%d' % self.depth,
                            last_layer=False,
                            x_shape=x_shape,
                            shift_and_log_scale_fn=None
                        )
                    )

        return bijectors

    def inverse(self, x, objective, yy=None, nlf0=None, nlf1=None, iso=None, cam=None):
        z = x
        squeeze_factor = self.hps.squeeze_factor

        for i in range(self.n_levels):
            z = squeeze2d(z, squeeze_factor, self.hps.squeeze_type)
            if yy is not None:
                yy = squeeze2d(yy, squeeze_factor, self.hps.squeeze_type)
            for bijector in self.model[i]:
                if type(bijector) in [AffineCouplingCondY, AffineCouplingCondXY, AffineCouplingFitSdnGain2,
                                      AffineCouplingCondYG, AffineCouplingCamSdn, AffineCouplingCondXYG,
                                      AffineCouplingSdnGain, AffineCouplingSdn, AffineCouplingGain,
                                      AffineCouplingGainEx1, AffineCouplingGainEx2, AffineCouplingGainEx3,
                                      AffineCouplingSdnEx1, AffineCouplingSdnEx2, AffineCouplingSdnEx3,
                                      AffineCouplingSdnEx4, AffineCouplingGainEx4, AffineCouplingSdnEx5,
                                      AffineCouplingSdnEx6]:
                    try:
                        z, log_abs_det_J_inv = \
                            bijector._inverse_and_log_det_jacobian(z, yy, nlf0, nlf1, iso, cam)
                    except Exception as e:
                        print(e)
                        z = bijector._inverse(z, yy, nlf0, nlf1, iso, cam)
                        log_abs_det_J_inv = bijector._inverse_log_det_jacobian(z, yy, nlf0, nlf1, iso, cam)
                else:
                    try:
                        z, log_abs_det_J_inv = \
                            bijector._inverse_and_log_det_jacobian(z)
                    except Exception as e:
                        print(e)
                        z = bijector._inverse(z)
                        log_abs_det_J_inv = bijector._inverse_log_det_jacobian(z)
                objective += log_abs_det_J_inv
            if i < self.n_levels - 1:
                z, objective = split2d("pool{}".format(i), z, objective)
        return z, objective

    def forward(self, z, eps_std, yy=None, nlf0=None, nlf1=None, iso=None, cam=None):
        x = z
        for i in reversed(range(self.n_levels)):
            if i < self.n_levels - 1:
                x = split2d_reverse("pool{}".format(i), x, eps_std)
            for bijector in reversed(self.model[i]):
                if type(bijector) in [AffineCouplingCondY, AffineCouplingCondXY, AffineCouplingFitSdnGain2,
                                      AffineCouplingCondYG, AffineCouplingCamSdn, AffineCouplingCondXYG,
                                      AffineCouplingSdnGain, AffineCouplingSdn, AffineCouplingGain,
                                      AffineCouplingGainEx1, AffineCouplingGainEx2, AffineCouplingGainEx3,
                                      AffineCouplingSdnEx1, AffineCouplingSdnEx2, AffineCouplingSdnEx3,
                                      AffineCouplingSdnEx4, AffineCouplingGainEx4, AffineCouplingSdnEx5,
                                      AffineCouplingSdnEx6]:
                    x = bijector._forward(x, yy, nlf0, nlf1, iso, cam)
                else:
                    x = bijector._forward(x)
            x = unsqueeze2d(x, self.hps.squeeze_factor, self.hps.squeeze_type)
        return x

    def sample(self, y, eps_std=None, yy=None, nlf0=None, nlf1=None, iso=None, cam=None):
        """Sampling function"""
        # y_onehot = tf.cast(tf.one_hot(tf.cast(y, 'int32'), self.hps.n_y, 1, 0), 'float32')  # not used for sidd problem
        with tf.variable_scope('model', reuse=True):
            _, sample = self.prior("prior", y)
            z = sample(eps_std)
            x = self.forward(z, eps_std, yy, nlf0, nlf1, iso, cam)
        return x

    def _loss(self, x, y, nlf0=None, nlf1=None, iso=None, cam=None, reuse=False):
        with tf.variable_scope('model', reuse=reuse):
            objective = tf.zeros_like(x, dtype='float32')[:, 0, 0, 0]
            # y_onehot = tf.cast(tf.one_hot(tf.cast(y, 'int32'), 1, 1, 0), 'float32')  # not used for sidd problem
            # inverse flow
            # z, objective = self.inverse(z, objective)
            if self.hps.sidd_cond is not None and self.hps.sidd_cond != 'uncond':
                z, objective = self.inverse(x, objective, yy=y, nlf0=nlf0, nlf1=nlf1, iso=iso, cam=cam)
            else:
                z, objective = self.inverse(x, objective)

            self.hps.top_shape = int_shape(z)[1:]

            # base measure
            logp, _ = self.prior("prior", x)

            objective += logp(z)
            nobj = - objective
            # std. dev. of z
            mu_z, var_z = tf.nn.moments(z, [1, 2, 3])
            sd_z = tf.reduce_mean(tf.sqrt(var_z))

        return nobj, sd_z

    def loss(self, x, y, nlf0=None, nlf1=None, iso=None, cam=None, reuse=False):
        nll, sd_z = self._loss(x=x, y=y, nlf0=nlf0, nlf1=nlf1, iso=iso, cam=cam, reuse=reuse)  # returns NLL
        return tf.reduce_mean(nll), sd_z

    def prior(self, name, x):
        with tf.variable_scope(name):
            n_z = self.hps.x_shape[-1]
            h = tf.zeros([tf.shape(x)[0]] + self.hps.x_shape[1:3] + [2 * n_z])
            # h = tf.zeros([tf.shape(x)[0]] +
            #              self.hps.top_shape[:2] +
            #              [2 * n_z])
            pz = gaussian_diag(h[:, :, :, :n_z], h[:, :, :, n_z:])

        def logp(z1):
            objective = pz.logp(z1)
            return objective

        def sample(eps_std=None):
            if eps_std is not None:
                z = pz.sample2(pz.eps * tf.reshape(eps_std, [-1, 1, 1, 1]))
            else:
                z = pz.sample
            return z

        return logp, sample

    def get_layer_names(self):
        layer_names = []
        for i in range(self.n_levels):
            for b in self.model[i]:
                layer_names.append(b.name)
        return layer_names

def flatten_sum(logps):
    if len(logps.get_shape()) == 2:
        return tf.reduce_sum(logps, [1])
    elif len(logps.get_shape()) == 4:
        return tf.reduce_sum(logps, [1, 2, 3])
    else:
        raise Exception()

def gaussian_diag(mean, logsd):
    class o(object):
        pass

    o.mean = mean
    o.logsd = logsd
    o.eps = tf.random_normal(tf.shape(mean))
    o.sample = mean + tf.exp(logsd) * o.eps
    o.sample2 = lambda eps: mean + tf.exp(logsd) * eps
    # o.logps = lambda x: -0.5 * \
    #     (np.log(2 * np.pi) + 2. * logsd + (x - mean) ** 2 / tf.exp(2. * logsd))
    # TODO
    o.logps = lambda x: -0.5 * \
                        (np.log(2 * np.pi) + 2. * o.logsd + (x - o.mean) ** 2 / tf.exp(2. * o.logsd))
    o.logp = lambda x: flatten_sum(o.logps(x))
    o.get_eps = lambda x: (x - mean) / tf.exp(logsd)
    return o

def split2d_prior(z):
    n_z2 = int(z.get_shape()[3])
    n_z1 = n_z2
    h = conv2d_zeros("conv", z, 2 * n_z1)

    mean = h[:, :, :, 0::2]
    logs = h[:, :, :, 1::2]
    return gaussian_diag(mean, logs)

def split2d(name, z, objective=0.):
    with tf.variable_scope(name):
        n_z = int_shape(z)[3]
        z1 = z[:, :, :, :n_z // 2]
        z2 = z[:, :, :, n_z // 2:]
        pz = split2d_prior(z1)
        objective += pz.logp(z2)
        # z1 = squeeze2d(z1)
        return z1, objective

def split2d_reverse(name, z, eps_std=None):
    with tf.variable_scope(name):
        z1 = z
        # z1 = unsqueeze2d(z)
        pz = split2d_prior(z1)
        z2 = pz.sample
        if eps_std is not None:
            z2 = pz.sample2(pz.eps * tf.reshape(eps_std, [-1, 1, 1, 1]))
        z = tf.concat([z1, z2], 3)
        return z


import cv2
img = cv2.imread("example_images/kitten.jpg")

cv2.imshow("original image", img)
cv2.waitKey(0)

# Convert to Grayscale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray image", img_gray)
cv2.waitKey(0)

# Convert to HSV
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Extract the Hue/Saturation/Value channel and show only hue component
hue = img_hsv[:, :, 0]
saturation = img_hsv[:, :, 1]
value = img_hsv[:, :, 2]
cv2.imshow("Hue", hue)
cv2.waitKey(0)


import sys
from functools import cmp_to_key

def setup():
     pass

class CorrectOrder(Exception):
     pass

def cmp1(left, right):
     if type(left) == int and type(right) == int:
          return left-right

     if type(left) == int:
          left = [left]
     if type(right) == int:
          right = [right]

     # Both sides are now lists.
     for k in range(len(left)):
          if k >= len(right):
               # right list ran out of items first
               return 1 # left is larger.
          val = cmp1(left[k], right[k])
          if val == 0:
               continue
          return val
     # Left list ran out of items.
     # Were they the same size?
     if len(left) == len(right):
          return 0
     return -1 # Right is larger.

def part1(filename):
     index = 1

     correct_indices = []

     with open(filename) as f:
          while True:
               try:
                    p1 = eval(f.readline().strip())
               except SyntaxError: # EOF
                    break
               p2 = eval(f.readline().strip())
               cmp = cmp1(p1, p2)
               if cmp < 0:
                    correct_indices.append(index)
               index += 1
               f.readline()
     print(correct_indices)
     print(sum(correct_indices))

def part2(filename):
     index = 1
     all_packets = []
     for line in open(filename):
          if not line.strip():
               continue
          all_packets.append(eval(line))
     all_packets.append([[2]])
     all_packets.append([[6]])

     all_packets.sort(key=cmp_to_key(cmp1))

     decoder = all_packets.index([[2]])+1
     decoder *= all_packets.index([[6]])+1

     print(decoder)

if __name__ == '__main__':
     setup()
     if sys.argv[1] == '1':
          part1(sys.argv[2])
     else:
          part2(sys.argv[2])


import cv2             #opencv
import urllib.request  #para abrir y leer URL
import numpy as np
import matplotlib.pyplot as plt

#============================= PROGRAMA DE CLASIFICACION DE OBJETOS USANDO DROIDCAM =============================

# Iniciamos nuestras variables a utilizar
NombreVentana = 'CAMARA DEL MOVIL'             #Nombre de la ventana
cv2.namedWindow(NombreVentana,cv2.WINDOW_AUTOSIZE)   #Actualizar el nombre en la ventana
classNames = []                                #Arreglo que contendra los nombres de los objetos detectados
classFile = 'Objetos.names'                    #Archivo donde estaran los nombres de los objetos que se peuden clasificar

# recorremos los nombres de los objetos a clasificar
with open(classFile,'rt') as f:
    classNames = f.read().rstrip('\n').split('\n')

# Archivo de los datos que ya fueron entrenados para el reconocimiento de imagenes
configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightsPath = 'frozen_inference_graph.pb'

# Representamos una API de alto nivel para redes de detección de objetos
net = cv2.dnn_DetectionModel(weightsPath,configPath)
net.setInputSize(320,320)
net.setInputScale(1.0/127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)

# Capturamos la camara a utilizar del latop
captura = cv2.VideoCapture(2)

# Bucle para clasificar nuestros objetos
while(True):
    grabbed,img=captura.read()  #nos devolvera una imagen de la camara que se esta usando
    if not grabbed:             #verificar si se esta grabando con la camara
        break
    img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) # rotamos la imagen para que se adecue al movil en cuanto a la rotacion

    classIds, confs, bbox = net.detect(img,confThreshold=0.5) # detectamos la imagen
    print(classIds,bbox)
    if len(classIds) != 0:      #si los puntos calves de la imagen es 0 e spor que no tiene contorno la imagen
        for classId, confidence,box in zip(classIds.flatten(),confs.flatten(),bbox):
             cv2.rectangle(img,box,color=(255,0,128),thickness = 3)  #mostramos en rectangulo el objetivo
             cv2.putText(img, classNames[classId-1], (box[0]+10,box[1]+30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255),2) #mostramos el nombre del objeto
    cv2.imshow(NombreVentana,img) # mostramos la imagen
    #esperamos a que se presione ESC para terminar el programa
    tecla = cv2.waitKey(5) & 0xFF
    if tecla == 27:
        break
# destrumos la ventana donde se msotraba la camara del celular
cv2.destroyAllWindows()


#Importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

#importing the dtaset

dataset = pd.read_csv(r"D:\File\Programming Project\Python Project\Machine learning\Simple Liner regrission\Salary_Data.csv")

# determin independent values.
X = dataset.iloc[:,:-1].values # تحديد القيم المستقلة والفصل بينها عن طريق النقطتين الى فوق بعض زي هيك : افهمتو ولا لا

# determin dependent values  train_test_split(X,y,test_size=0.3, random_state=0)
# iloc هي المسؤولة عن فصل البيانات
y =dataset.iloc[:,1].values #spliting the dataset into the training set and test set # (X , Y) تقسيم البيانات الى الى عمودين

# يتم عمل ثلاث اوبجتكت الاكسترين عشان يدرب المودل على البيانات والاكستست عشان يقيم النتيجة لاى بتطلع من المودل بالبيانات الموجودة وكذالك بعمل مع الوايترين والوايتستت
X_train,X_test, y_train, y_test= train_test_split(X,y,test_size=0.3, random_state=0)

# استخدام خوارزمية اللينر ريجريشن
regressor = LinearRegression()
# تدريب البيانات باستخدام دالة fit
regressor.fit(X_train,y_train)

# عمل متغير y_pred كنتيجة للتوقع في عمود الواي
y_pred=regressor.predict(X_test)
# عمل توقع التدريب ومقارنتها مع x_traine
y_pred_train=regressor.predict(X_train)

# عرض البيانات بطرق مختلفة عن طريق مكتبة matpliote
plt.scatter(X_train,y_train,color='red') # طريقة لعرض البيانات التي يتم لاتدرب عليها
plt.plot(X_train,y_pred_train,color='blue') # عرض البيانات التي يتم التدرب عليها و نفس البيانات المتوقعة من المودل
plt.title('Salary vs Experience(training set)') # وضع عنوان
plt.xlabel('years of experience') # وضع عنوان لل x
plt.ylabel('Salary') # وضع عنوان لل y
plt.show() # عرض المخطط الرسومي

plt.scatter(X_test,y_test,color='red')
plt.plot(X_train,y_pred_train,color='blue')
plt.title('Salary vs Experience(test set)')
plt.xlabel('years of experience')
plt.ylabel('Salary')
plt.show()


# Using WebMD’s database, you can build a drug recommendation system. The website has authentic content for medical news and the drug
# components of several medicines you can scrape to realize this project’s solution.

#Using Python’s web scraping framework, Scrapy, you can download the website’s content for one of the most interesting web scraping
# with python projects.

# PAGE: https://www.webmd.com/drugs/2/alpha/l
# Page spanish: https://medlineplus.gov/spanish/druginfo/drug_Aa.html

import pandas as pd

## ---------------------------------  reading drugs information  -----------------------------------------------------------

df = pd.read_csv('DrugRecommendSystem\DrugsInformation.csv', sep=";", encoding="latin-1")

## --------------------------------- getting list of symptons ------------------------------------------------------------------

print("")
symptons = input("Ingrese síntomas, separados por coma si son más de uno: ")
symptonsList = symptons.split(',')

## --------------------------------- filtering dataframe ------------------------------------------------------------------
FilterDrugs = df.loc[df.Sintomas.str.contains(symptonsList[0], case=False, regex=True)==True]
for sympton in symptonsList:
    FilterDrugs = FilterDrugs.loc[FilterDrugs.Sintomas.str.contains(sympton, case=False, regex=True)==True]

## --------------------------------- printing -----------------------------------------------------------------------------------

if FilterDrugs.empty:
    print("""
            ---> No hay medicamentos en la base que ataquen todos los síntomas
            ---> Intente con otras palabras u otra combinación de síntomas

            """)
else:
    print("""
              Listado de medicamentos acontinuación.
              Se recomienda ir al enlace para consultar contraindicaciones.

            """)
    print(FilterDrugs.loc[:, ['Medicamento', 'Enlace']].to_string(index=False))


import enum

"""
1. create a list named `tasks` that contains several string elements, each of which represents a task to be performed.

2. use a for loop and the `enumerate` function to browse through the list of tasks. For each iteration, print the index and the task.

3. Search the Internet for how to change the starting point of the enumerate function. Modify the for loop to use a starting index of 1 instead of 0 for the enumerate.

4. again modify the loop so that the first letter of each task in the list is capitalized and print it.
"""

tasks = ["clean the room", "out rubbish", "cook a cake"]

def print_list_tasks(list_task):
    enumerate_list = enumerate(list_task,start = 1)
    for index_task, task in enumerate_list:
        print(index_task,":", task)


#Emiliano Costa Junior - RA:1260901923008
#FATEC - Automação Industrial
#Programação Aplicada a Automação
#Programa 06 - Converte Dolar em Reais
#--------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|
#Descrição:
#Entrar via teclado com o valor da cotação do dólar e uma certa quantidade de dólares.
#Calcular e exibir o valor correspondente em Reais (R$).
#--------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|

#Mensagem de Apresentação
print("Converte Dolar em Reais")

#Entrada dados
dolar = float(input("Digite valor em dolares: $"))
cotaçao = float(input("Digite a cotação: R$"))

#Calcula
real = dolar * cotaçao

#Mostra resultado
print(f"${dolar: .2f}, equivalem a R${real: .2f}")

#Aguarda o usuario finalizar
fim = input("clique qualquer tecla para finalizar!")

#--------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|


from optimization.edgeCloudOffloading import *

## 进化算法
class Evolution:

    server = Server()

    def __init__(self, dList, beta=2.5, m=60):
        # 引入50个user
        self.userList = []
        for i in range(50):
            self.userList.append(User("SL", dList[i], beta, m))
        Evolution.server.linkUsers(self.userList)

        self.evolve()

    def evolve(self):
        # 初始化alpha种群, 含有10000个alpha随机值数组，数组长度50
        population = []
        for j in range(10000):
            alphas = []
            for k in range(50):
                alphas.append(random.random())
            population.append(alphas)

        # 编码（数组无需编码）

        # 对种群进行评价和淘汰
        for cnt in range(5):
            _population = []
            # 淘汰在可行域外面的alpha数组
            for arr in population:
                updateAlpha(self.userList, arr)
                Evolution.server.updateUsers(self.userList)

                if Server.Csum <= Server.Csmax:
                    _population.append(arr)

            population = _population
            # print(len(population))
            # 淘汰总能量不在底部20%的alpha数组
            totalEnergyList = []
            for arr in population:
                updateAlpha(self.userList, arr)
                Evolution.server.updateUsers(self.userList)
                totalEnergy = 0
                for user in self.userList:
                    totalEnergy += user.energySum
                totalEnergyList.append(totalEnergy)

            _totalEnergyList = [totalEnergyList[i] for i in range(len(totalEnergyList))]
            _totalEnergyList.sort()

            totalEnergyMin = _totalEnergyList[0]
            totalEnergyMax = _totalEnergyList[-1]

            # 找到下20%的边界
            totalEnergyBoundary = totalEnergyMin + 0.2 * (totalEnergyMax - totalEnergyMin)

            _population = []
            for totalEnergy in totalEnergyList:
                if totalEnergy <= totalEnergyBoundary:
                    _population.append(population[totalEnergyList.index(totalEnergy)])

            population = _population
            # print(len(population))

            # 繁衍后代
            new_population = [] + population

            # if (len(population) % 2 == 1):
            #     population.pop()

            for i in range(len(population) - 1):
                # 随便挑选两个个体，让其中的alpha发生一个小幅度抖动，然后再产生2个个体，规则是两个个体中每个alpha都是之前两个个体的线性插值
                parent1 = population[i]
                parent2 = population[i + 1]

                for alpha in parent1:
                    alpha += 0.005 * random.random() - 0.0025
                for alpha in parent2:
                    alpha += 0.005 * random.random() - 0.0025

                child1 = []
                child2 = []

                for i in range(len(parent1)):
                    child1.append(2/3 * parent1[i] + 1/3 * parent2[i])
                    child2.append(1/3 * parent1[i] + 2/3 * parent2[i])

                new_population.append(child1)
                new_population.append(child2)

            population = new_population
            print("第" + str(cnt + 1) + "轮变异之后的种群还剩" + str(len(population)) + "个个体")

        # 对最后的选择结果做均值
        resultAlphas = []
        for i in range(50):
            _alpha = 0
            for arr in population:
                _alpha += arr[1]
            resultAlphas.append(_alpha / len(population))

        updateAlpha(self.userList, resultAlphas)
        Evolution.server.updateUsers(self.userList)

# 出图看效果
# x = []
# y = []
#
# for arr in population:
#     x.append(arr[0])
#     y.append(arr[1])
#
# plt.plot(x, y, "ob")


def solution(data, word):
    graph = dict()
    node = dict()
    for d in data:
        id, name, parent_id = d.split(' ')
        if parent_id not in graph:
            graph[parent_id] = []
        if id not in graph:
            graph[id] = []
        graph[parent_id].append(id)
        node[id] = name

    return graph

print(solution(["1 BROWN 0",
                "2 CONY 0",
                "3 DOLL 1",
                "4 DOLL 2",
                "5 LARGE-BROWN 3",
                "6 SMALL-BROWN 3",
                "7 BLACK-CONY 4",
                "8 BROWN-CONY 4"],
               "BROWN"))