from django.conf import settings

from django.utils.translation import ugettext as _
from django.shortcuts import render, redirect

from django.contrib import messages
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required

from main import forms

def login(request, template_name='base_form.html'):
    """Allow a user to log in with either username/email and password."""

    if request.user.is_authenticated():
        message = _('You are already logged in as') + u' %s!' % request.user.email
        messages.info(request, message)
        return redirect('home')

    if request.method == 'POST':
        form = forms.AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            auth_login(request, user)

            redirect_url = form.cleaned_data.get('redirect_url', 'home')
            return redirect(redirect_url)
    else:
        form = forms.AuthenticationForm(initial={'redirect_url': request.GET.get('next', '/home')})

    template_vars = {
        'form': form,
    }

    return render(request, template_name, template_vars)

@login_required
def logout(request):
    auth_logout(request)
    return redirect('landing_page')

def sign_up(request, template_name='base_form.html'):
    """Allow a user to log in with either username/email and password."""
    form = forms.UserCreationForm()

    if request.user.is_authenticated():
        messages.success(request, _('You are already logged in!'))
        return redirect('home')

    if request.method == 'POST':
        form = forms.UserCreationForm(request.POST)

        if form.is_valid():

            user = form.save(commit=False)
            user.email = user.username
            user.save()

            user.backend = settings.AUTHENTICATION_BACKENDS[0]
            auth_login(request, user)

            return redirect('home')

    template_vars = {
        'form': form,
    }

    return render(request, template_name, template_vars)


import pygame as pg
from libs.libs_FSM.Classic_FSM import FSM
from libs.utils.class_draw_utils import Text

# -------------------------------------------------------------------------------------------

SCREEN_DIM =        400,400

DIS_LUZ_PULS_X =    50
DIS_LUZ_PULS_Y =    150

POS_LUZ =       200,50
POS_LED_P1 =    DIS_LUZ_PULS_X, POS_LUZ[1] + DIS_LUZ_PULS_Y
POS_LED_P2 =    SCREEN_DIM[0] - DIS_LUZ_PULS_X, POS_LUZ[1] +DIS_LUZ_PULS_Y

POS_TEXT_P1 =    POS_LED_P1[0], POS_LED_P1[1] - 30
POS_TEXT_P2 =    POS_LED_P2[0], POS_LED_P2[1] - 30

DIM_PULS    = 10,20
RECT_P1 =     POS_LED_P1[0],POS_LED_P1[1],DIM_PULS[0], DIM_PULS[1]
RECT_P2 =     POS_LED_P2[0],POS_LED_P2[1],DIM_PULS[0], DIM_PULS[1]

RADIO_LUZ =     30
RADIO_PULS =    5

TEXT_PULS =     (255,255,0)

LED_LUZ_ON =    (255,255,255)
LED_LUZ_OFF =   (64,64,64)

LED_P1_ON =     (0,255,0)
LED_P1_OFF =    (0,64,0)
LED_P2_ON =     (0,255,0)
LED_P2_OFF =    (0,64,0)

# -------------------------------------------------------------------------------------------

class Luz(FSM):
    """
    ---------------------------------------------------------------------------------
      Problema: Control de la luz en los dos extremos de un pasillo público
    --------------------------------------------------------------------------------

      1 - El pasillo dispone de dos pulsadores, uno al lado de cada puerta, de
      manera que se pueda encender y apagar la luz desde cada extremo. Cada
      pulsador produce un ‘1’ lógico mientras está pulsado, y un ‘0’ lógico
      cuando no lo está.

      2 - Se desea que, cada vez que se pulse cualquier pulsador, la luz cambie
      de estado: si está apagada se debe encender, y viceversa.

      3 - Se debe tener en cuenta el caso en el que, mientras se pulsa un
      interruptor, se pulse el otro. Por ejemplo, si estando apagada la luz,
      alguien pulsa P1 se enciende la luz. Pero si mientras está pulsado P1
      alguien pulsa P2, entonces se apagará nuevamente la luz.

      4 - Hay que considerar la simultaneidad de pulsaciones

    """

    name = 'clt_luz'

    # -------------------------------------------------------------------------------------------

    def __init__(self, screen, fsm_data_dict):
        """

        :param screen:
        """

        # ===================================================================================

        super().__init__(fsm_data_dict)

        self.screen =       screen

        self.sw_P1 = False      # entrada
        self.sw_P2 = False      # entrada

        self.sw_luz = False     # salida

        self.txt_P1 = Text( FontSize= 20)
        self.txt_P2 = Text( FontSize= 20)

    # ----------------------------------------------------------------------------------------------

    def get_push_button_state(self, event):
        """
            Detecta actividad del botón de start del motor (tecla <s> del teclado)

        :param event:
        :return:
        """
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_s:
                self.sw_P1 = True
            if event.key == pg.K_d:
                self.sw_P2 = True

        elif event.type == pg.KEYUP:
            if event.key == pg.K_s:
                self.sw_P1 = False
            if event.key == pg.K_d:
                self.sw_P2 = False

    # -------------------------------------------------------------------------------------------
    #   A C C I O N E S

    def set_action(self, out_event_dict):
        """
            activa o para giro del motor, prende o apaga luz de alarma

        :param event_dict:
        :return:
        """

        for key, value in out_event_dict.items():
            self.sw_luz = value
        self.sw_luz = out_event_dict['luz']

    # ----------------------------------------------------------------------------------------------

    def simulation_step(self):
        """
            Ejecuta un paso de la máquina de estados adquiriendo el código
            de evento co condición.

        :return: ninguno
        """

        event_dict = self.get_event_dict()
        in_event_dict = event_dict['inputs']
        in_event_dict['sw_p1'] = int(self.sw_P1)
        in_event_dict['sw_p2'] = int(self.sw_P2)

        self.out_event_dict = self.step(self.gets_coded_events(in_event_dict))
        self.set_action(self.out_event_dict)

    # ----------------------------------------------------------------------------------------------
    #   D I B U J O S

    def draw_light(self):
        """
            Dibuja simulación gráfica de la  luz con los leds de los pulsadores P1 y P2

        :return: ninguno
        """

        self.txt_P1.render(self.screen,'P1 (Tecla s)',POS_TEXT_P1, TEXT_PULS)
        self.txt_P2.render(self.screen,'P2 (Tecla d)',POS_TEXT_P2, TEXT_PULS)

        if self.sw_luz:
            pg.draw.circle(self.screen,LED_LUZ_ON, POS_LUZ, RADIO_LUZ)      # luz
        else:
            pg.draw.circle(self.screen,LED_LUZ_OFF, POS_LUZ, RADIO_LUZ)

        if self.sw_P1:
            pg.draw.rect(self.screen, LED_P1_ON, RECT_P1)
            # pg.draw.circle(self.screen,LED_P1_ON, POS_LED_P1, RADIO_PULS)      # mPulsador P1
        else:
            pg.draw.rect(self.screen, LED_P1_OFF, RECT_P1)
            # pg.draw.circle(self.screen,LED_P1_OFF, POS_LED_P1, RADIO_PULS)

        if self.sw_P2:
            pg.draw.rect(self.screen, LED_P2_ON, RECT_P2)
            # pg.draw.circle(self.screen,LED_P2_ON, POS_LED_P2, RADIO_PULS)      # mPulsador P2
        else:
            pg.draw.rect(self.screen, LED_P2_OFF, RECT_P2)
            # pg.draw.circle(self.screen,LED_P2_OFF, POS_LED_P2, RADIO_PULS)


n=3
words=["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"]

answer=[0,0]

arr=[]

arr.append(words[0])

for i in range(1,len(words)):
    num=i%n
    if words[i] in arr:
        answer[0],answer[1]=num+1,i//n+1
        break
    if words[i][0] !=words[i-1][-1]:
        answer[0],answer[1]=num+1,i//n+1
        break
    arr.append(words[i])

print(arr)
print(answer)


from scipy.io import loadmat
import scipy.optimize as opt
import numpy as np
import matplotlib.pyplot as plt

def coste(Theta, X, y, lamda):
    H = np.dot(X, Theta)
    op1 = np.sum((H - y)**2) / (2 * np.shape(X)[0])
    op2 = lamda * np.sum(Theta[1:]**2) / (2 * np.shape(X)[0])
    return op1 + op2

def gradiente(Theta, X, y, lamda):
    H = np.dot(X, Theta)
    op1 = np.dot((H - y), X) / np.shape(X)[0]
    op2 = lamda * Theta[1:] / np.shape(X)[0]
    op1[1:] += op2
    return op1

def regresion_lineal_reg(X, y, lamda, nombrePlot):
    Theta = np.array([1,1])
    X_aux = np.hstack([np.ones([np.shape(X)[0], 1]), X])

    #Comprobar si son correctos los calculos
    # lamda = 1
    # coste_ini = coste(Theta, X_aux, y, lamda)
    # gradiente_ini = gradiente(Theta, X_aux, y, lamda)
    # print("---Regresión lineal regularizada---")
    # print(f"Coste inicial: {str(coste_ini)[:7]}")
    # print(f"Gradiente inicial: [{str(gradiente_ini[0])[:7]}; {str(gradiente_ini[1])[:7]}]")
    # print()

    #Calculo del valor de Theta que minimiza el error sobre los ejemplos de entrenamiento
    lamda = 0
    fmin = opt.minimize(fun=coste, x0=Theta, args=(X_aux, y, lamda))
    grafica_regresion_lineal_reg(fmin.x, X, y, nombrePlot)

    return fmin.x

def grafica_regresion_lineal_reg(Theta, X, y, nombrePlot):
    plt.figure()
    plt.plot(X, y, "x", c="orange")

    #Linea
    minX = np.amin(X)
    maxX = np.amax(X)
    minY = Theta[0] + Theta[1] * minX
    maxY = Theta[0] + Theta[1] * maxX
    plt.plot([minX, maxX], [minY, maxY], c="limegreen")

    plt.xlabel("Change in water level (x)")
    plt.ylabel("Water flowing out of the dam (y)")
    plt.savefig(nombrePlot + ".png")

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

def error(Theta, X, y):
    H = np.dot(X, Theta)
    return np.sum((H - y)**2) / (2 * np.shape(X)[0])

def curvas_aprendizaje(X, Xval, y, yval, lamda, nombrePlot):
    m = np.shape(X)[0]
    X_aux = np.hstack([np.ones([m, 1]), X])
    Xval_aux = np.hstack([np.ones([np.shape(Xval)[0], 1]), Xval])
    Theta = np.ones(np.shape(X_aux)[1])

    errors = []
    errorsval = []

    for i in range(1, m+1):
        fmin = opt.minimize(fun=coste, x0=Theta, args=(X_aux[:i], y[:i], lamda))
        errors.append(error(fmin.x, X_aux[:i], y[:i]))
        errorsval.append(error(fmin.x, Xval_aux, yval))

    grafica_curvas_aprendizaje(m, errors, errorsval, lamda, nombrePlot)

def grafica_curvas_aprendizaje(m, errors, errorsval, lamda, nombrePlot):
    plt.figure()

    plt.plot(range(1, m+1), errors, c="orange", label="Train")
    plt.plot(range(1, m+1), errorsval, c="limegreen", label="Cross Validation")

    plt.legend()
    plt.title(f"Learning curve for linear regression ($\lambda$={lamda})")
    plt.xlabel("Number of training examples")
    plt.ylabel("Error")
    plt.savefig(nombrePlot + ".png")

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

def normaliza_matriz(X):
    mu = np.mean(X, axis = 0)
    sigma = np.std(X, axis = 0)
    X_norm = (X - mu)/sigma
    return X_norm, mu, sigma

def genera_datos(X, p):
    H = np.empty((np.shape(X)[0], p))

    for i in range(0, p):
        H[:,i] = (X**(i+1)).ravel()

    #print(np.shape(H))
    return H

def regresion_polinomial(X, Xval, y, yval, lamda, p, nombrePlot1, nombrePlot2):
    X_norm, mu, sigma = normaliza_matriz(genera_datos(X, p))
    X_norm = np.hstack([np.ones([np.shape(X_norm)[0], 1]), X_norm])
    Theta = np.ones(np.shape(X_norm)[1])

    fmin = opt.minimize(fun=coste, x0=Theta, args=(X_norm, y, lamda))
    grafica_regresion_polinomial(fmin.x, X, y, lamda, p, mu, sigma, nombrePlot1)

    Xval_norm = (genera_datos(Xval, p) - mu)/sigma #Normalizamos

    curvas_aprendizaje(X_norm[:,1:], Xval_norm, y, yval, lamda, nombrePlot2)
    curvas_aprendizaje(X_norm[:,1:], Xval_norm, y, yval, 1, nombrePlot2 + "-1")
    curvas_aprendizaje(X_norm[:,1:], Xval_norm, y, yval, 100, nombrePlot2 + "-2")

def grafica_regresion_polinomial(Theta, X, y, lamda, p, mu, sigma, nombrePlot):
    plt.figure()
    plt.plot(X, y, "x", c="orange")

    #Linea
    lineX = np.arange(np.amin(X)-5, np.amax(X)+5, 0.05)
    auxX = genera_datos(lineX, p)
    auxX = (auxX - mu)/sigma #Normalizamos
    auxX = np.hstack([np.ones([np.shape(auxX)[0], 1]), auxX])
    lineY = np.dot(auxX, Theta)
    plt.plot(lineX, lineY, c="limegreen")

    plt.title(f"Polynomial regression ($\lambda$={lamda})")
    plt.xlabel("Change in water level (x)")
    plt.ylabel("Water flowing out of the dam (y)")
    plt.savefig(nombrePlot + ".png")

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

def estimar_error(X_norm, Xtest, y, ytest, lamda, p, mu, sigma):
    Theta = np.ones(np.shape(X_norm)[1])

    Xtest_norm = genera_datos(Xtest, p)
    Xtest_norm = (Xtest_norm - mu)/sigma #Normalizamos
    Xtest_norm = np.hstack([np.ones([np.shape(Xtest_norm)[0], 1]), Xtest_norm])

    fmin = opt.minimize(fun=coste, x0=Theta, args=(X_norm, y, lamda))
    errorLamda = error(fmin.x, Xtest_norm, ytest)

    print(f"Error obtenido para lambda = {lamda}: {str(errorLamda)[:5]}")

def seleccion_parametro_lamda(X, Xval, Xtest, y, yval, ytest, p, nombrePlot):
    lamdas = [0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10]

    X_norm, mu, sigma = normaliza_matriz(genera_datos(X, p))
    X_norm = np.hstack([np.ones([np.shape(X_norm)[0], 1]), X_norm])
    Theta = np.ones(np.shape(X_norm)[1])

    Xval_norm = (genera_datos(Xval, p) - mu)/sigma #Normalizamos
    Xval_norm = np.hstack([np.ones([np.shape(Xval_norm)[0], 1]), Xval_norm])

    errors = []
    errorsval = []

    for lamda in lamdas:
        fmin = opt.minimize(fun=coste, x0=Theta, args=(X_norm, y, lamda))
        errors.append(error(fmin.x, X_norm, y))
        errorsval.append(error(fmin.x, Xval_norm, yval))

    grafica_seleccion_lamda(lamdas, errors, errorsval, nombrePlot)

    #Sabemos que la lamda mejor es 3
    estimar_error(X_norm, Xtest, y, ytest, 3, p, mu, sigma)

def grafica_seleccion_lamda(lamdas, errors, errorsval, nombrePlot):
    plt.figure()

    plt.plot(lamdas, errors, c="orange", label="Train")
    plt.plot(lamdas, errorsval, c="limegreen", label="Cross Validation")

    plt.legend()
    plt.title("Selecting $\lambda$ using a cross validation set")
    plt.xlabel("lambda")
    plt.ylabel("Error")
    plt.savefig(nombrePlot + ".png")

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

def main():
    datos = loadmat("ex5data1.mat")
    X, Xval, Xtest = datos["X"], datos["Xval"], datos["Xtest"]
    y, yval, ytest = datos["y"].ravel(), datos["yval"].ravel(), datos["ytest"].ravel()

    lamda = 0
    p = 8

    regresion_lineal_reg(X, y, lamda, "figura1")
    curvas_aprendizaje(X, Xval, y, yval, lamda, "figura2")
    regresion_polinomial(X, Xval, y, yval, lamda, p, "figura3", "figura4")
    seleccion_parametro_lamda(X, Xval, Xtest, y, yval, ytest, p, "figura5")

main()


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

def getIntersectionNode(headA: ListNode, headB: ListNode) -> ListNode:
    visited_set = set()
    while headA:
        visited_set.add(headA.val)
        headA = headA.next
    #print(visited_set)
    while headB:
        #print(headB.val)
        if headB.val in visited_set:
            return headB.val
            break

        headB = headB.next
    return None

node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)

nodeA = ListNode('a')
nodeB = ListNode('b')
nodeC = ListNode('c')
nodeD = ListNode('d')

node1.next = node2
node2.next = node3
node3.next = node4

nodeA.next = nodeB
nodeB.next = nodeC
nodeC.next = nodeD
#nodeD.next = node2

print(getIntersectionNode(node1, nodeA))


# log(n) time
def numSetBits(n):
    count = 0

    while(n):
        if(n & 1 == 1):
            count += 1
        n = n >> 1

    return count

# Best time = num set bits
def countSetBits(n):
    count = 0

    while(n):
        count += 1
        n = n & (n-1)

    return count

num = 13

count = numSetBits(num)

print(count)


# coding = utf-8
class treeNode:
    def __init__(self,value):
        self.value = value
        self.left = None
        self.right = None
        self.tag = 0 # 0 not tag
    def setTag(self,tag):
        self.tag = tag

def find(node,value):
    if(node == None):
        return None
    if(node.value == value):
        return node
    temp1 = find(node.left,value)
    temp2 = find(node.right,value)
    if(temp1 != None):
        return temp1
    elif(temp2 != None):
        return temp2
    else:
        return None

def find1(node,now,value):
    if(node == None):
        return None
    if(node.value == value):
        if(node.tag == 1):
            return node.value
        return now
    if(node.tag == 1):
        now = node.value
    now1 = find1(node.left,now,value)
    now2 = find1(node.right,now,value)
    if(now1 != None):
        return now1
    if(now2 != None):
        return now2
    return None

string = input().strip()
N,Q = list(map(int,string.split(" ")))
root = treeNode(1)
root.setTag(1)
ops = []
while(N != 1):
    N -= 1
    op = list(map(int,input().strip().split(" ")))
    ops.append(op)
ops.sort()
for op in ops:
    temp = find(root,op[0])
    if(temp.left==None):
        temp.left = treeNode(op[1])
    else:
        temp.right = treeNode(op[1])

while(Q != 0):
    Q = Q - 1
    op = input().strip().split(" ")
    if(op[0] == 'Q'):
        print(find1(root,1,eval(op[1])))
    elif(op[0] == 'C'):
        temp = find(root,eval(op[1]))
        temp.setTag(1)


import yaml
import sys

class Scanner:

    def __init__(self,filename,dictionary='forbidden.yaml',badwords=[]):
        self.filename=filename
        self.dict=dictionary
        self.badwords=badwords

    def getData(self):
        try:
            with open(self.filename,'rb') as f:
                data=f.read()
        except FileNotFoundError as e:
            print("File was not found.")
            print(e)
            raise FileNotFoundError
        except Exception as e:
           print(e)
        else:
            return data

    def getDict(self):
        try:
            self.badwords=[]
            with open(self.dict,'r') as d:
                data=yaml.load(d, Loader=yaml.Loader)
            for i in range(len(data)):
                self.badwords+= list(data.values())[i]
        except FileNotFoundError or OSError:
            print("You did not supply a dictionary. Please fix this.")
            raise FileNotFoundError
        except Exception as e:
            print("There was a problem loading the dictionary:")
            print(e)
            exit()
        else:
            return self.badwords

    def checkAll(self):
        try:
            badwords=self.getDict()
            self.matchedWords=0
            wordsFound=[]
            matchedEncodings=[]
            found =[]
            allEncodes=['ascii','utf-8','big5','big5hkscs','cp037','cp273','cp424','cp437','cp500','cp720','cp737','cp775','cp850','cp852','cp855','cp856','cp857','cp858',
                            'cp860','cp861','cp862','cp863','cp864','cp865','cp866','cp869','cp874','cp875','cp932','cp949','cp950','cp1006','cp1026','cp1125','cp1140',
                            'cp1250','cp1251','cp1252','cp1253','cp1254','cp1255','cp1256','cp1257','cp65001','euc_jp','euc_jis_2004','euc_jisx0213','euc_kr',
                            'gb2312','gbk','gb18030','hz','iso2022_jp','iso2022_jp_1','iso2022_jp_2','iso2022_jp_2004','iso2022_jp_3','iso2022_jp_ext','iso2022_kr',
                            'latin_1','iso8859_2','iso8859_3','iso8859_4','iso8859_5','iso8859_6','iso8859_7','iso8859_8','iso8859_9','iso8859_10','iso8859_11','iso8859_13',
                            'iso8859_14','iso8859_15','iso8859_16','johab','koi8_r','koi8_t','koi8_u','kz1048','mac_cyrillic','mac_greek','mac_iceland','mac_latin2',
                            'mac_roman','mac_turkish','ptcp154','shift_jis','shift_jis_2004','shift_jisx0213','utf_32','utf_32_be','utf_32_le','utf_16','utf_16_be',
                            'utf_16_le','utf_7','utf_8','utf_8_sig','cp1258']
            with open('FoundIn'+self.filename+'.txt', 'w') as f:
                print('Now checking '+self.filename+' for forbidden words:',file=f)
                print('Results are a tuple of (word, offset, encoding)', file=f)
                for e in allEncodes:
                    newBytes=[b.encode(encoding=e,errors='replace') for b in badwords]
                    for b in newBytes:
                        if (b in self.getData()) and (b):
                            if ((b.decode(encoding=e)) not in wordsFound) and ((b.decode(encoding=e))!='??'):
                                offset=self.getData().find(b)
                                wordsFound.append(b.decode(encoding=e))
                                if e not in matchedEncodings:
                                    matchedEncodings.append(e)
                                found.append((b.decode(encoding=e,errors='ignore'), offset, e))
                                self.matchedWords+=1
        except UnicodeEncodeError or UnicodeDecodeError or UnicodeError:
            print("Issues with Unicode")
        except Exception as e:
            print("Other error: "+str(e))
            raise LookupError
        else:
            with open('FoundIn'+self.filename+'.txt', 'a') as f:
                for i in found:
                    print(i, file=f)
                print("Number of matched words: "+str(self.matchedWords),file=f)
                print("Words found: "+str(wordsFound),file=f)
                print("Encodings matched" +str(matchedEncodings),file=f)
                if (self.matchedWords==0):
                    print("No matching words found, program is clean.",file=f)
                else: print("Please remove the matched words before submitting the file.",file=f)
            if self.matchedWords==0:
                print("No matching words, test passed.")
                return True
            else:
                print ("Test failed due to matching words found, see file "+str(f.name))
                return False

    def scanReturn(self):
        try:
            self.checkAll()
        except Exception as e:
            print("Program failed.")
            if e!='':
                print('Exception information: '+str(type(e)))
            exit()
        else:
            return 0

if len(sys.argv)==2:
    file=sys.argv[1]
else: file='test5'

newScan=Scanner(str(file))
newScan.scanReturn()


import pandas as pd
def makeBalancedPanel(data, idname, tname):
  data = data.sort_values([idname, tname]).reset_index(drop = True)
  nt = len(data[tname].unique())
  data = data.groupby(idname)\
    .filter(lambda x: len(x) == nt)
  return data

def panel2cs2(data: pd.DataFrame, yname, idname, tname):
  if len(data[tname].unique()) != 2:
    raise ValueError('panel2cs2 only for 2 perios of apnel data')

  data = data.sort_values([idname, tname])
  y1 = data.groupby(idname)[yname].shift(-1)
  y0 = data[yname]
  dy = y1 - y0
  data = data.assign(
    y1 = y1, y0 = y0, dy = dy
  )
  return data.dropna()

# -*- coding: utf-8 -*-
"""
Created on Wed May 31 18:58:35 2023

@author: Carlos Guevara
"""
import numpy as np

def TorF(cond, use_isTRUE=False):

    if not isinstance(cond, np.ndarray) or cond.dtype != bool:
        raise ValueError("cond should be a logical vector")
    if use_isTRUE:
        cond = np.array([x is True for x in cond])
    else:
        cond[np.isnan(cond)] = False
    return cond

def multiplier_bootstrap(inf_func, biters): # This function comes from c++
    n, K = inf_func.shape
    biters = int(biters)
    innerMat = np.zeros((n, K))
    Ub = np.zeros(n)
    outMat = np.zeros((biters,K))

    for b in range(biters):
        # draw Rademechar weights
        # Ub = ( np.ones(n) - 2 * np.round(np.random.rand(n)) )[:, np.newaxis]
        Ub = np.random.choice([1, -1], size=(n, 1))
        innerMat = inf_func * Ub
        outMat[b] = np.mean(innerMat, axis=0)

    return outMat


def _DevisMethod(s, n, m):
    p = len(s) - 1
    for j in range(n):
        t = s[p + j] + s[j]
        if t >= m:
            t -= m
        s.append(t / m)
    return s[p + 1:]

def DevisMethod(cli, name):
    cli.out(f'Вы выбрали [magenta]{name}[/magenta].')
    s = cli.float_list(
        'Введите через пробел миниимум два начальных значения (z0, z1...): ')
    m = cli.int('Введите значение модуля (m): ')
    n = cli.int('Введите количество генерируемых чисел (n): ')
    cli.table(['Число'], _DevisMethod(list(s), n, m), autoheader='z\\[i]',
              autostart=len(s), autoformat='z[{}]')

if __name__ == "__main__":
    s = [0.36, 0.45, 0.62]   # Список начальных значений
    m = 4                    # Значение модуля
    n = 2                    # Количество генерируемых чисел
    print(_DevisMethod(s, n, m))


from keras import Input, Model
from keras.applications.vgg16 import VGG16
from keras.layers import Concatenate, Conv2D, UpSampling2D, BatchNormalization
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session

# config = tf.ConfigProto()
# config.gpu_options.allow_growth = True
# config.gpu_options.per_process_gpu_memory_fraction = 0.5
# set_session(tf.Session(config=config))

from PIL import Image, ImageDraw
import numpy as np
import sys
import os

sys.path.append(os.getcwd())
import AdvancedEast.cfg as cfg
from AdvancedEast.utils.preprocess import resize_image
from AdvancedEast.utils.util import sigmoid,cut_text_line
from AdvancedEast.utils.nms import nms

class East:
    def __init__(self):
        self.input_img = Input(name='input_img',
                               shape=(None, None, cfg.num_channels),
                               dtype='float32')
        # 用vgg16做提取图像特征工作
        vgg16 = VGG16(input_tensor=self.input_img,
                      weights='/Users/lige/公开课/一小时身份证识别/ocr-ID-card/weights/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
                      include_top=False)
        if cfg.locked_layers:
            # locked first two conv layers
            locked_layers = [vgg16.get_layer('block1_conv1'),
                             vgg16.get_layer('block1_conv2')]
            for layer in locked_layers:
                layer.trainable = False
        self.f = [vgg16.get_layer('block%d_pool' % i).output
                  for i in cfg.feature_layers_range]
        self.f.insert(0, None)
        # diff=1
        self.diff = cfg.feature_layers_range[0] - cfg.feature_layers_num

    def g(self, i):
        # i+diff in cfg.feature_layers_range
        assert i + self.diff in cfg.feature_layers_range, \
            ('i=%d+diff=%d not in ' % (i, self.diff)) + \
            str(cfg.feature_layers_range)
        if i == cfg.feature_layers_num:
            bn = BatchNormalization()(self.h(i))
            return Conv2D(32, 3, activation='relu', padding='same')(bn)
        else:
            return UpSampling2D((2, 2))(self.h(i))

    def h(self, i):
        # i+diff in cfg.feature_layers_range
        assert i + self.diff in cfg.feature_layers_range, \
            ('i=%d+diff=%d not in ' % (i, self.diff)) + \
            str(cfg.feature_layers_range)
        if i == 1:
            return self.f[i]
        else:
            concat = Concatenate(axis=-1)([self.g(i - 1), self.f[i]])
            bn1 = BatchNormalization()(concat)
            conv_1 = Conv2D(128 // 2 ** (i - 2), 1,
                            activation='relu', padding='same',)(bn1)
            bn2 = BatchNormalization()(conv_1)
            conv_3 = Conv2D(128 // 2 ** (i - 2), 3,
                            activation='relu', padding='same',)(bn2)
            return conv_3

    # 组装模型网络结构，返回model
    def east_network(self):
        before_output = self.g(cfg.feature_layers_num)
        inside_score = Conv2D(1, 1, padding='same', name='inside_score'
                              )(before_output)
        side_v_code = Conv2D(2, 1, padding='same', name='side_vertex_code'
                             )(before_output)
        side_v_coord = Conv2D(4, 1, padding='same', name='side_vertex_coord'
                              )(before_output)
        east_detect = Concatenate(axis=-1,
                                  name='east_detect')([inside_score,
                                                       side_v_code,
                                                       side_v_coord])

        return Model(inputs=self.input_img, outputs=east_detect)

    def predict_for_test(self, img_path, weight_path = cfg.saved_model_weights_file_path, threshold = cfg.pixel_threshold, quiet=False):
        '''
            预测测试用，每次预测单张图片，输出预测中间结果图，预测结果图，可选切分图片
            img_path:图片路径
            weght_path:模型权重路径
            threshold:判断结果阈值
            quiet:是否屏蔽调试输出，当是4个点的时候认为是文本框，不是的时候不输出但是会打印日志
        '''
        # 创建模型
        east_detect = self.east_network()
        # 加载模型权重
        east_detect.load_weights(weight_path)
        print ('load weight success')
        img = image.load_img(img_path)
        d_wight, d_height = resize_image(img, cfg.max_predict_img_size)
        img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')
        img = image.img_to_array(img)
        #去均值中心化
        img = preprocess_input(img, mode='tf')
        x = np.expand_dims(img, axis=0)
        y = east_detect.predict(x)
        y = np.squeeze(y, axis=0)
        y[:, :, :3] = sigmoid(y[:, :, :3])
        # 对比概率大于阈值的元素
        cond = np.greater_equal(y[:, :, 0], threshold)
        activation_pixels = np.where(cond)
        quad_scores, quad_after_nms = nms(y, activation_pixels)
        with Image.open(img_path) as im:
            im_array = image.img_to_array(im.convert('RGB'))
            d_wight, d_height = resize_image(im, cfg.max_predict_img_size)
            scale_ratio_w = d_wight / im.width
            scale_ratio_h = d_height / im.height
            im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB')
            quad_im = im.copy()
            draw = ImageDraw.Draw(im)
            for i, j in zip(activation_pixels[0], activation_pixels[1]):
                px = (j + 0.5) * cfg.pixel_size
                py = (i + 0.5) * cfg.pixel_size
                line_width, line_color = 1, 'red'
                if y[i, j, 1] >= cfg.side_vertex_pixel_threshold:
                    if y[i, j, 2] < cfg.trunc_threshold:
                        line_width, line_color = 2, 'yellow'
                    elif y[i, j, 2] >= 1 - cfg.trunc_threshold:
                        line_width, line_color = 2, 'green'
                draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size),
                        (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size),
                        (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size),
                        (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size),
                        (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size)],
                        width=line_width, fill=line_color)
            im.save(img_path + '_act.jpg')
            quad_draw = ImageDraw.Draw(quad_im)
            txt_items = []
            for score, geo, s in zip(quad_scores, quad_after_nms,
                                    range(len(quad_scores))):
                if np.amin(score) > 0:
                    quad_draw.line([tuple(geo[0]),
                                    tuple(geo[1]),
                                    tuple(geo[2]),
                                    tuple(geo[3]),
                                    tuple(geo[0])], width=2, fill='red')
                    if cfg.predict_cut_text_line:
                        cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array,
                                    img_path, s, save_path=os.path.dirname(img_path))
                    rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]
                    rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()
                    txt_item = ','.join(map(str, rescaled_geo_list))
                    txt_items.append(txt_item + '\n')
                elif not quiet:
                    print('quad invalid with vertex num less then 4.')
            quad_im.save(img_path + '_predict.jpg')
            if cfg.predict_write2txt and len(txt_items) > 0:
                with open(img_path[:-4] + '.txt', 'w') as f_txt:
                    f_txt.writelines(txt_items)

    def predict_for_ocr(self, img_path, weight_path = cfg.saved_model_weights_file_path, threshold = cfg.pixel_threshold, quiet=True):
        # 创建模型
        east_detect = self.east_network()
        # 加载模型权重
        east_detect.load_weights(weight_path)
        print ('load weight success')
        img = image.load_img(img_path)
        d_wight, d_height = resize_image(img, cfg.max_predict_img_size)
        img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')
        img = image.img_to_array(img)
        #去均值中心化
        img = preprocess_input(img, mode='tf')
        x = np.expand_dims(img, axis=0)
        y = east_detect.predict(x)
        y = np.squeeze(y, axis=0)
        y[:, :, :3] = sigmoid(y[:, :, :3])
        # 对比概率大于阈值的元素
        cond = np.greater_equal(y[:, :, 0], threshold)
        activation_pixels = np.where(cond)
        quad_scores, quad_after_nms = nms(y, activation_pixels)
        result = {}
        # tmp_img_name = []
        with Image.open(img_path) as im:
            im_array = image.img_to_array(im.convert('RGB'))
            # print('im_array.shape:', im_array.shape)
            d_wight, d_height = resize_image(im, cfg.max_predict_img_size)
            scale_ratio_w = d_wight / im.width
            scale_ratio_h = d_height / im.height
            im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB')

            if cfg.generation_prediction_img_during_predict:
                quad_im = im.copy()
                draw = ImageDraw.Draw(im)
                for i, j in zip(activation_pixels[0], activation_pixels[1]):
                    px = (j + 0.5) * cfg.pixel_size
                    py = (i + 0.5) * cfg.pixel_size
                    line_width, line_color = 1, 'red'
                    if y[i, j, 1] >= cfg.side_vertex_pixel_threshold:
                        if y[i, j, 2] < cfg.trunc_threshold:
                            line_width, line_color = 2, 'yellow'
                        elif y[i, j, 2] >= 1 - cfg.trunc_threshold:
                            line_width, line_color = 2, 'green'
                    draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size),
                            (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size),
                            (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size),
                            (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size),
                            (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size)],
                            width=line_width, fill=line_color)
                im.save(os.path.join(cfg.tmp_img_dir_name, os.path.basename(img_path) + '_act.jpg'))
                quad_draw = ImageDraw.Draw(quad_im)

            for score, geo, s in zip(quad_scores, quad_after_nms,
                                    range(len(quad_scores))):
                if np.amin(score) > 0:
                    if cfg.generation_prediction_img_during_predict:
                        quad_draw.line([tuple(geo[0]),
                                        tuple(geo[1]),
                                        tuple(geo[2]),
                                        tuple(geo[3]),
                                        tuple(geo[0])], width=2, fill='red')

                    min_xy, max_xy, img_name = cut_text_line(geo, scale_ratio_w, scale_ratio_h,
                        im_array,img_path, s)
                    result[img_name] = {'coordinate' : [min_xy[0], min_xy[1], max_xy[0], max_xy[1]]}
                    # tmp_img_name.append(img_name)
                elif not quiet:
                    print('quad invalid with vertex num less then 4.')
            quad_im.save(os.path.join(cfg.tmp_img_dir_name, os.path.basename(img_path) + '_predict.jpg'))
        return result

if __name__ == '__main__':
    east = East()
    # east_network = east.east_network()
    # east_network.summary()
    img_path = 'D:/AI_src/AdvancedEAST-master/demo/0001.jpg'
    # east.predict_for_test(img_path)
    files_name = east.predict_for_ocr(img_path)
    # print (files_name)


# -*- coding: utf-8 -*-
import scrapy
from tangspiderframe.items import TangspiderframeItem

class TextPhilippinesAbanteLinkSpider(scrapy.Spider):
    name = 'text_philippines_abante_link'
    start_urls = ["https://www.abante.com.ph/"]

    def parse(self, response):
        links = response.xpath('//ul[@class="main-menu menu bsm-pure clearfix"]/li/a/@href').extract()
        for i in range(1, 3000):
            for link in links:
                link = link + "/page/{i}".format(i=i)
                yield scrapy.Request(url=link, callback=self.parse_url, dont_filter=True)

    def parse_url(self, response):
        # next_links = response.xpath('//a[(contains(@class, "btn-bs-pagination"))]/@href').extract()
        # for next_link in next_links:
        #     yield scrapy.Request(url=next_link, callback=self.parse_url, dont_filter=True)

        links = response.xpath('//h2/a[@class="post-title post-url"]/@href').extract()
        for link in links:
            item = TangspiderframeItem()
            item['url'] = link
            yield item


import numpy as np
from knn import KNN
from shapeanalyzer import ShapeAnalyzer

def create_image(size):
    return np.zeros((size[1], size[0]), dtype=np.uint8)

def draw_circle(image, center, radius):
    c, r = np.meshgrid(np.arange(image.shape[1]), np.arange(image.shape[0]))
    dist = np.sqrt((r - center[1]) ** 2 + (c - center[0]) ** 2)
    circle = (dist <= radius).astype(np.uint8)
    image[:, :] = np.logical_or(image[:, :], circle)

if __name__ == '__main__':
    # print(analyzer.analyze(img_test))
    metrics1 = [0.1, 0.5, 0.3]
    metrics1 = np.array(metrics1)
    metrics2 = [0.5, 0.4, 0.32]
    metrics2 = np.array(metrics2)
    metrics3 = [0.11, 0.78, 0.45]
    metrics3 = np.array(metrics3)
    metrics4 = [0.31, 0.18, 0.25]
    metrics4 = np.array(metrics4)
    metrics5 = [0.21, 0.98, 0.154]
    metrics5 = np.array(metrics5)
    metrics6 = [0.45, 0.64, 0.534]
    metrics6 = np.array(metrics6)
    point = [0.2, 0.4, 0.2]
    point = np.array(point)
    knn = KNN(3, 3)
    knn.add_training_point(metrics1, "triangle")
    knn.add_training_point(metrics2, "carré")
    knn.add_training_point(metrics3, "triangle")
    knn.add_training_point(metrics4, "losange")
    knn.add_training_point(metrics5, "losange")
    knn.add_training_point(metrics6, "cercle")
    rep = knn.classify(point)


sock_nums=(int)(input())
socks=input().split(' ')
max_num=0
desk=[]
for i in socks:
    if(i not in desk):
        desk.append(i)
    else:
        desk.remove(i)
    if(len(desk)>max_num):
        max_num=len(desk)
print(max_num)


# reading big files
words_file = 'hangman_words.txt'
try:

	f = open(words_file)
	line = f.readline()
	while line != '':
		if line == 'elephant\n':
			print('There is an elephat in the file')
			break
		line = file.readline()
	f.close()

except IOError:
		print("Cannot find file: " + words_file)
		exit()


#!/usr/bin/env python3
import yaml
import sys
import os

IN_PATH = "./recipes/"
OUT_PATH = "./xml/"
IN_EXTENSION = ".yml"
OUT_EXTENSION = ".xml"

TEMPLATE = """
<serviceResponse>
<recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<title>{}</title>
<description>{}</description>
<ingredients>
{}
</ingredients>
<methods>
{}
</methods>
</recipe>
<response>
<status>SUCCESS</status>
</response>
</serviceResponse>
"""

def generate_ingredient(item):
    return "<ingredient><quantity>1</quantity><name>{0}</name><displayText>{0}</displayText></ingredient>".format(item)

def generate_step(item):
    return "<method><description>{0}</description></method>".format(item)

out_file = os.path.join(OUT_PATH, "index.xml")
with open(out_file, "w+") as hahayes:
    hahayes.write("<serviceResponse><recipes>\n")
    in_files = [f for f in os.listdir(IN_PATH) if os.path.isfile(os.path.join(IN_PATH, f)) and f.endswith(IN_EXTENSION)]
    for in_file in in_files:
        with open(os.path.join(IN_PATH, in_file), "r") as f:
            docs = yaml.load_all(f)
            recipe = [d for d in docs][0] #ignore additional recipes
        out_file = os.path.join(OUT_PATH, os.path.splitext(in_file)[0] + OUT_EXTENSION)
        out_name = os.path.splitext(in_file)[0] + OUT_EXTENSION
        with open(out_file, "w+") as f:
            ingredients = "\n".join([generate_ingredient(x) for x in recipe["ingredients"]])
            steps = "\n".join([generate_step(x) for x in recipe["steps"]])
            hahayes.write("<recipe><title>{}</title><description>{}</description><url>{}</url></recipe>\n".format(recipe["title"], recipe["description"], out_name))
            f.write(TEMPLATE.format(recipe["title"], recipe["description"], ingredients, steps))
    hahayes.write("</recipes></serviceResponse>\n")


import time
from functools import wraps

def retry(max_tries=3, delay_seconds=1):
    def decorator_retry(func):
        @wraps(func)
        def wrapper_retry(*args, **kwargs):
            tries = 0
            while tries < max_tries:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    tries += 1
                    if tries == max_tries:
                        raise e
                    time.sleep(delay_seconds)

        return wrapper_retry

    return decorator_retry

def memoize(fn):
    cache = {}
    miss = object()

    @wraps(fn)
    def wrapper(*args, **kwargs):
        result = cache.get(args, miss)
        if result is miss:
            result = fn(*args, **kwargs)
            cache[args] = result
        return result

    def clear_cache():
        cache.clear()

    wrapper.clear_cache = clear_cache
    return wrapper

def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time} seconds to run.")
        return result

    return wrapper

def log_execution(func):
    import logging

    logging.basicConfig(level=logging.INFO)

    @wraps(func)
    def wrapper(*args, **kwargs):
        logging.info(f"Executing {func.__name__}")
        result = func(*args, **kwargs)
        logging.info(f"Finished executing {func.__name__}")
        return result

    return wrapper


# 双指针
# j一致向前走
# 找到第一个不等于i指向的数
# 就把值赋给i后面的数
# i向前走一步 指向赋值后的数
from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)
        if length < 2:
            return length
        i = 0
        for j in range(1, length):
            # 找到第一个不等于nums[i]的数
            # 之后i = i + 1 i向前走一步
            # 把这个数赋值给nums[i]
            # j继续向前走
            if nums[i] < nums[j]:
                i = i + 1
                nums[i] = nums[j]
        return i + 1

26_删除排序数组中的重复项.py

26_删除排序数组中的重复项.py


# Оценить задачу по памяти: собрать значения индексов четных элементов
# ОС: Win 10 64-bit; Python: 3.7.4 32-bit

import sys

def memory_demands(objects_list): # считает количество памяти, необходимое для хранения данного списка объектов(с учетом всех вложенностей)
    total_memory = 0

    def memory_calc(x):
        nonlocal total_memory
        total_memory += sys.getsizeof(x)
        if hasattr(x, '__iter__'):
            if hasattr(x, 'items'):
                for key, value in x.items():
                    memory_calc(key)
                    memory_calc(value)
            elif not isinstance(x, str):
                for item in x:
                    memory_calc(item)

    for obj in objects_list:
        memory_calc(obj)

    return total_memory

import random

def solution_1():
    SIZE = 100
    MIN_ITEM = 0
    MAX_ITEM = 1000
    array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
    print(array)

    array_2 = [i for i in range(len(array)) if array[i] % 2 == 0]

    print(array_2)

    print(f'Решение #1. Потрачено памяти: {memory_demands(locals().values())}')

def solution_2():
    SIZE = 100
    MIN_ITEM = 0
    MAX_ITEM = 1000
    array = []
    array_2 = []
    for index in range(SIZE):
        item = random.randint(MIN_ITEM, MAX_ITEM)
        array.append(item)
        if item % 2 == 0:
            array_2.append(index)

    print(array)
    print(array_2)

    print(f'Решение #2. Потрачено памяти: {memory_demands(locals().values())}')

def solution_3():
    SIZE = 100
    MIN_ITEM = 0
    MAX_ITEM = 1000

    for index in range(SIZE):
        if random.randint(MIN_ITEM, MAX_ITEM) % 2 == 0:
            print(index, end = ' ')
    print()

    print(f'Решение #3. Потрачено памяти: {memory_demands(locals().values())}')

solution_1() # Потрачено памяти: 2708
solution_2() # Потрачено памяти: 2922
solution_3() # Потрачено памяти: 54

# При повторном запуске программ видим, что используемая каждой функцией(каждая функция - отдельный вариант решения задачи)
# память немного варьируется из-за случайных чисел, однако очевидно, что меньше всего памяти потребляет третий вариант решения
# (без использования списков, с выводом напрямую). При необходимости выводить оба списка (варианты 1 и 2) эффективней
# первый(с генераторами списков)


with open('./data.txt') as f:
    lines = f.readlines()

nums = {
    63: '0',
    6: '1',
    91: '2',
    79: '3',
    102:'4',
    109:'5',
    125:'6',
    7:'7',
    127:'8',
    111:'9',
}

total = 0

for line in lines:
    lenMap = {
        5: [],
        6: [],
    }

    for word in line.split(' | ')[0].split(' '):
        stripped = word.strip()
        length = len(stripped)
        if length in [2,3,4,7]:
            lenMap[length] = stripped
        else:
            lenMap[length] += [stripped]

    # print(lenMap)
    one = lenMap[2]
    top = [x for x in lenMap[3] if not x in one][0]

    fgcand = [x for x in lenMap[4] if not x in one]

    three = [x for x in lenMap[5] if all([y in x for y in one])][0]
    middle = [x for x in fgcand if x in three][0]
    topleft = [x for x in fgcand if x != middle][0]
    bottom = [x for x in three if x not in (list(one) + [top, middle])][0]

    five = [x for x in lenMap[5] if topleft in x][0]

    bottomright = [x for x in one if x in five][0]
    topright = [x for x in one if x not in five][0]

    bottomleft = [x for x in lenMap[7] if x not in [top, middle, bottom, topleft, topright,bottomright]][0]

    mapping = {
        top: 1,
        topright:2,
        bottomright:4,
        bottom:8,
        bottomleft:16,
        topleft:32,
        middle:64
    }

    out = ""

    for word in line.split(' | ')[1].split(' '):
        sum = 0
        for char in word.strip():
            sum += mapping[char]

        out += nums[sum]

    total += int(out)

print(total)


from django.urls import path

from order.views import order_view, order_change, order_remove
from . import views

urlpatterns = [
    # path('', views.contact),
    path('update/', views.update_profile, name='profile-update'),
    path('', views.view_profile, name='profile-detail'),
    path('orders/<int:order_id>/', order_view, name='order-view'),
    path('orders/<str:filter>/', views.ProfileOrderList.as_view(), name='profile-orders'),
    path('<int:order_id>/exchange/', order_change, name='order_change'),
    path('<int:order_id>/remove/', order_remove, name='order_remove'),
]


import MMBoard
import MMUITurtle
import random

class Mastermind:
    def __init__(self):
        self.board = MMBoard.MMBoard()
        choice = random.sample(["pink", "white", "red", "yellow", "orange", "green", "blue", "gray"], 4)
        #print(choice)
        self.board.setFinalRow(choice)
        #self.board.setFinalRow(("pink", "orange", "green", "gray"))
        self.ui = MMUITurtle.MMUITurtle()
        self.ui.setboard(self.board)

    def start(self):
        self.ui.display()

if __name__ == '__main__':
    mm = Mastermind()

    # Start to play!
    mm.start()


import datetime
import fileinput
import functools
import json
import os
import re
import sys
import unittest
import urllib.parse

import requests

from fixups import ESPANDI_INDIRIZZO

MESI = {
    'gennaio': 1,
    'febbraio': 2,
    'marzo': 3,
    'aprile': 4,
    'maggio': 5,
    'giugno': 6,
    'luglio': 7,
    'agosto': 8,
    'settembre': 9,
    'ottobre': 10,
    'novembre': 11,
    'dicembre': 12,
}

AGGIORNAMENTO_RE = re.compile(r"AGGIORNAMENTO: (?P<giorno>\d+) (?P<mese>\w+) (?P<anno>\d+)")
CIRCOSCRIZIONE_RE = re.compile(r"CIRCOSCRIZIONE (?P<numero>\d+): (?P<nome>.+)")
MMG_RE = re.compile(r"MMG")

NOME_DOTTORE_RE = re.compile(r"(?P<nome>[\w\s']+) \[(?P<codice>\w+)\]")
BLOCCO_ASSOCIAZIONE_RE = re.compile(r"Associazione:")
INDIRIZZO_RE = re.compile(r"(?P<indirizzo>.+) TORINO (?P<cap>\d+) \(TORINO\) Telefono: ?(?P<telefono>\d*)?")
FAX_RE = re.compile(r"FAX \d+")
TELEFONO_RE = re.compile(r"(TELEFONO.*:\s*)?(?P<telefono>\d+)$")

BLOCCO_ORARI_RE = re.compile(r"Giorno")
GIORNO_RE = re.compile(r"(?P<giorno>Lunedi|Martedi|Mercoledi|Giovedi|Venerdi|Sabato)")
ORARI_DA_RE = re.compile(r"Dalle")
ORARIO_RE = re.compile(r"(?P<orario>\d{2}:\d{2})")
ORARI_A_RE = re.compile(r"Alle")
BLOCCO_NOTE_RE = re.compile(r"Note")

def do_geocoding(indirizzo, token):
    mapbox_geocoding_v5 = "https://api.mapbox.com/geocoding/v5/mapbox.places/"
    url = "{}{}.json?limit=1&country=IT&access_token={}".format(
        mapbox_geocoding_v5,
        urllib.parse.quote(indirizzo, safe=""),
        token,
    )
    response = requests.get(url)
    data = response.json()
    feature = data["features"][0]
    if "address" in feature["place_type"]:
        if "Torino Turin" in feature["place_name"] or "Collegno" in feature["place_name"]:
            return feature["center"]
    return None

@functools.lru_cache(maxsize=128)
def geocoding(indirizzo, token):
    # sostituiamo i sc. con scala per farli piacere a mapbox
    indirizzo = indirizzo.replace(" sc. ", " scala ")
    posizione = do_geocoding(indirizzo, token)
    if posizione:
        return posizione

    # se non abbiamo trovato l'indirizzo proviamo a sistemarlo a mano
    correzione = [(k, v) for k, v in ESPANDI_INDIRIZZO.items() if k in indirizzo]
    if correzione:
        via, via_corretta = correzione[0]
        indirizzo_corretto = indirizzo.replace(via, via_corretta)
        posizione = do_geocoding(indirizzo_corretto, token)
        if posizione:
            return posizione

    print("Geocoding fallito per {}".format(indirizzo), file=sys.stderr)
    return None

if __name__ == '__main__':

    # se abbiamo un token di mapbox nell'environment facciamo il geocoding degli indirizzi
    mapbox_token = os.getenv("MAPBOX_ACCESS_TOKEN")

    documento = {
        'aggiornamento': None,
        'circoscrizione_numero': None,
        'circoscrizione_nome': None,
        'mmg': None,
        'dottori': None,
    }
    dottori = []
    dottore = None
    blocco_associazione = False
    blocco_note = False
    indirizzo = None

    for line in fileinput.input():

        line = line.strip('\x0c')
        if not line.strip():
            continue

        match = AGGIORNAMENTO_RE.match(line)
        if match:
            match_dict = match.groupdict()
            update = datetime.date(
                int(match_dict['anno']),
                MESI[match_dict['mese'].lower()],
                int(match_dict['giorno'])
            )
            documento['aggiornamento'] = update.isoformat()
            continue

        match = CIRCOSCRIZIONE_RE.match(line)
        if match:
            match_dict = match.groupdict()
            documento['circoscrizione_numero'] = match_dict['numero']
            documento['circoscrizione_nome'] = match_dict['nome']
            continue

        match = MMG_RE.match(line)
        if match:
            documento['mmg'] = True
            continue

        match = NOME_DOTTORE_RE.match(line)
        if match:
            match_dict = match.groupdict()
            blocco_note = False
            if dottore:
                dottore['indirizzi'].append(indirizzo)
                dottori.append(dottore)
                indirizzo = None

            dottore = {
                'nome': match_dict['nome'],
                'codice': match_dict['codice'],
                'associazione': [],
                'indirizzi': [],
            }
            continue

        match = BLOCCO_ASSOCIAZIONE_RE.match(line)
        if match:
            blocco_associazione = True
            continue

        match = INDIRIZZO_RE.match(line)
        if match:
            match_dict = match.groupdict()
            blocco_note = False
            blocco_associazione = False
            if indirizzo:
                dottore['indirizzi'].append(indirizzo)
            indirizzo = {
                'indirizzo': '{} {} TORINO'.format(match_dict['indirizzo'], match_dict['cap']),
                'telefono': [match_dict['telefono']],
                'giorni': [],
                'ore': [],
                'note': [],
            }
            continue

        # ci sono dottori senza associazione
        if blocco_associazione:
            dottore['associazione'].append(line.strip())
            continue

        match = FAX_RE.match(line)
        if match:
            continue

        match = TELEFONO_RE.match(line)
        if match:
            match_dict = match.groupdict()
            indirizzo['telefono'].append(match_dict['telefono'])
            continue

        match = BLOCCO_ORARI_RE.match(line)
        if match:
            continue

        match = GIORNO_RE.match(line)
        if match:
            match_dict = match.groupdict()
            indirizzo['giorni'].append(match_dict['giorno'])
            continue

        match = ORARI_DA_RE.match(line)
        if match:
            continue

        match = ORARIO_RE.match(line)
        if match:
            match_dict = match.groupdict()
            indirizzo['ore'].append(match_dict['orario'])
            continue

        match = ORARI_A_RE.match(line)
        if match:
            continue

        match = BLOCCO_NOTE_RE.match(line)
        if match:
            blocco_note = True
            continue

        if blocco_note:
            indirizzo['note'].append(line.strip())
            continue

        print(line, file=sys.stderr)

    # l'ultimo dottore
    if dottore:
        dottore['indirizzi'].append(indirizzo)
        dottori.append(dottore)
        indirizzo = None

    for dottore in dottori:
        for indirizzo in dottore['indirizzi']:
            # Proviamo a sistemare gli orari
            num_orari = len(indirizzo['ore']) / 2
            indirizzo['orario_affidabile'] = num_orari == len(indirizzo['giorni'])
            num_orari = int(num_orari)
            orari = [(indirizzo['ore'][i], indirizzo['ore'][i+num_orari]) for i in range(num_orari)]
            if indirizzo['orario_affidabile']:
                indirizzo['orari'] = [
                    {'giorno': giorno, 'da': orario[0], 'a': orario[1]}
                        for giorno, orario in zip(indirizzo['giorni'], orari)
                ]
            else:
                indirizzo['orari'] = [{'giorno': None, 'da': da, 'a': a} for da, a in orari]

            if mapbox_token:
                posizione = geocoding(indirizzo['indirizzo'], mapbox_token)
                indirizzo['posizione'] = posizione

    documento['dottori'] = dottori
    print(json.dumps(documento))

class ParseTestCase(unittest.TestCase):
    def test_nome_dottore_deve_fare_il_match_degli_apostrofi(self):
        match = NOME_DOTTORE_RE.match("NUR ADDO' [01234]")
        match_dict = match.groupdict()
        self.assertEqual(match_dict, {"nome": "NUR ADDO'", "codice": "01234"})


import unittest
import pytest
import logging
import sys
import os

from spikehard import spikehard

# add '/hardware/util' to system path for module imports
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(
  os.path.dirname(os.path.dirname(os.path.abspath(__file__))))), "util"))
from test_util import basic_test_util, expose_markers_option_fixture  # noqa: E402
from common_util import set_spikehard_param  # noqa: E402

@pytest.mark.myhdl
class test_multiple(unittest.TestCase):
  logger = logging.getLogger(__name__)
  logger.setLevel(logging.DEBUG)

  def run_test(self, num_axons=256, num_neurons=256, grid_dims=None, **kwargs):
    all_test_params = []
    for model_name in ("vmm_o", "mnist_o"):
      all_test_params.append(basic_test_util.gen_test_params(model_name=model_name, altered=True,
                             num_axons=num_axons, num_neurons=num_neurons, **kwargs))

    if grid_dims is None:
      arch_params = None
    else:
      arch_params = all_test_params[0]
      arch_params = set_spikehard_param(arch_params, "num_outputs", num_axons)
      arch_params = set_spikehard_param(arch_params, "grid_dimension_x", grid_dims[0])
      arch_params = set_spikehard_param(arch_params, "grid_dimension_y", grid_dims[1])

    spikehard.run_test(self, all_test_params, arch_params)

  def test(self):
    grid_dims = [None]
    num_ticks_to_check = [6]
    dma_bus_width = [32]
    dma_frame_header_word_width = [32]

    basic_test_util.run_subtests(self,
                                 grid_dims=grid_dims,
                                 num_ticks_to_check=num_ticks_to_check,
                                 dma_bus_width=dma_bus_width,
                                 dma_frame_header_word_width=dma_frame_header_word_width)

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


import os
import csv
import math

def calculate_duration(start_time, stop_time):
    # Assuming start_time and stop_time are in the format: YYYYMMDD:HHMMSS.MMMMMM
    start_seconds = int(start_time[9:11]) * 60 * 60 + int(start_time[11:13]) * 60 + int(start_time[13:15])
    stop_seconds = int(stop_time[9:11]) * 60 * 60 + int(stop_time[11:13]) * 60 + int(stop_time[13:15])
    return stop_seconds - start_seconds

def get_time_of_day(start_time):
    # Assuming start_time is in the format: YYYYMMDD:HHMMSS.MMMMMM
    hour = int(start_time[9:11])

    if 6 <= hour < 10:
        return "Morning"
    elif 10 <= hour < 12:
        return "Late Morning"
    elif 12 <= hour < 15:
        return "Noon"
    elif 15 <= hour < 18:
        return "Afternoon"
    elif 18 <= hour < 22:
        return "Evening"
    else:
        return "Night"

def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

def is_row_complete(row):
    for value in row.values():
        if value is None or value == '':
            return False
    if len(row) == 8:
        return True
    else:
        return False

def merge_csv_files(directory, target_path):
    merged_data = []

    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.csv'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r') as csv_file:
                    reader = csv.DictReader(csv_file)
                    for row in reader:
                        if is_row_complete(row):
                            row['trial'] = f"{os.path.splitext(file)[0]}_{row['trial']}"

                            row['intensity_match'] = round_up(float(row['intensity_match']), 3)

                            row['duration'] = calculate_duration(row['start_time'], row['stop_time'])

                            row['time_of_day'] = get_time_of_day(row['start_time'])

                            hour = int(row['start_time'][9:11])
                            minute = int(row['start_time'][11:13])
                            row['start_time'] =f"{hour}:{minute:02d}"

                            hour = int(row['stop_time'][9:11])
                            minute = int(row['stop_time'][11:13])
                            row['stop_time'] =f"{hour}:{minute:02d}"

                            if math.isnan(float(row['presented_intensity'])):
                                pass
                            else:
                                row['intensity_difference'] = round_up(float(row['intensity_match'])-(float(row['presented_intensity'])), 3)

                            merged_data.append(row)

    merged_file_path = target_path + 'matching_merged.csv'
    with open(merged_file_path, 'w', newline='') as merged_file:
        fieldnames = ['trial', 'stim', 'target_side', 'matching_flipped', 'presented_intensity', 'intensity_match', 'intensity_difference', 'start_time', 'stop_time', 'duration', 'time_of_day']
        writer = csv.DictWriter(merged_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(merged_data)

    print(f"Results merged successfully: {merged_file_path}")

def main(directory_path='../results_corrected_format', target_path=''):
    merge_csv_files(directory_path, target_path)

if __name__ == "__main__":
    main()


from Node import *
import sys

class Tree():
	"""docstring for Tree"""
	"""There is no duplicate element"""
	def __init__(self, widthx, heighty, rootx=0, rooty=0, value=None):
		# widthx is the width of the first branch (from root to its child)
		# heighty is the height of each layer of tree
		self.rootx = rootx
		self.rooty = rooty
		self.widthx = widthx
		self.heighty = heighty

		if value == None:
			self.root = None
		else:
			# the root should always be at the (rootx, rooty)
			self.__setRoot(node = Node(value))

	def __setRoot(self, node):
		self.root = node
		node.x = self.rootx
		node.y = self.rooty
		node.parent=None
		node.layer = 0

	def __leftmost(self):
		# return the smallest node in the tree
		node = self.root
		while True:
			if node.left == None:
				break
			node = node.left
		return node

	def __iter__(self, asNode=False):
		return self.Tree_iter(self.__leftmost(), asNode=asNode)

	def __updateTreeCoordinate(self, node, left=False, right=False, singleLayer=False):
		# update the coordinate of all its children by default
		# cand only update right children or left children
		layer = node.layer + 1
		if left == True and node.left != None:
			# update the coordinate
			x = node.x - self.widthx/(2**node.layer)
			y = node.y - self.heighty
			node.left.x = x
			node.left.y = y
			node.left.layer = layer
			if singleLayer == False:
				self.__updateTreeCoordinate(node.left, left=True, right=True)

		if right == True and node.right !=None:
			# update the coordinate
			x = node.x + self.widthx/(2**node.layer)
			y = node.y - self.heighty
			node.right.x = x
			node.right.y = y
			node.right.layer = layer
			if singleLayer == False:
				self.__updateTreeCoordinate(node.right, left=True, right=True)

	def find(self, key):
		# return the node which has the key, else return the node where the item should be
		return self.__find(self.root, key)

	def __find(self, node, key):
		# recursively find the elememt
		if node.value == key:
			return node
		elif node.value > key:
			# handle the case where the expected node does not exist
			if node.left == None:
				return node
			return self.__find(node.left, key)
		elif node.value < key:
			if node.right == None:
				return node
			return self.__find(node.right,key)

	def rangeSearch(self, start, end):
		# return the range of values in the tree
		# inclusive
		node = self.find(start)
		result = []
		if node.value < start:
			node = node.next()
		while node.value <= end:
			result.append(node.value)
			node = node.next()
		return result

	def insert(self, value):
		# insert first element
		if self.root == None:
			self.__setRoot(Node(value))
		else:
			self.__insert(self.root, value)

	def __insert(self, node, value):
		if node.value > value:
			if node.left == None:
				node.left = Node(value, parent=node)
				self.__updateTreeCoordinate(node, left=True, singleLayer=True)
			else:
				self.__insert(node.left, value)

		elif node.value < value:
			if node.right == None:
				node.right = Node(value, parent=node)
				self.__updateTreeCoordinate(node, right=True, singleLayer=True)
			else:
				self.__insert(node.right, value)

	def delete(self, value):
		"""
		edge cases
		edge case: delete the root
		"""
		node = self.find(value)
		if node.right == None:
			# left gets promoted
			left = node.left
			if node.isRoot():
				node.killChild(left)
				self.__setRoot(left)
				self.__updateTreeCoordinate(self.root, left=True, right=True)
				return
			parent = node.parent
			parent.killChild(node)
			left = parent.add(left)
			self.__updateTreeCoordinate(parent ,left=left, right=not left)
		else:
			# guarenteed to have next
			"""
		 	edge cases

			handle the case where there is no next (node could be root)
			# the node is guarenteed to have right child, which means the node is guarenteed to have next
			next is root (next has no parent)
			# next will never be root, since the node must have a right child
			"""
			# replace it by next element, next's right gets be appended to next's place
			_next = node.next()

			# next is guarenteed not to have child to its left
			nextParent = _next.parent
			nextRight = _next.right

			# swap node and next
			node.value = _next.value

			# safely remove next

			nextParent.killChild(_next)
			_next.killChild(nextRight)
			if nextRight != None:
				nextParent.add(nextRight)
				nextRight.x = _next.x
				nextRight.y = _next.y
				self.__updateTreeCoordinate(nextRight, left=True, right=True)

	def Draw(self, delay=0):
		# delay is in milisecond
		# draw the tree
		node_iter = self.__iter__(asNode=True)
		for i in node_iter:
			i.Draw()
			plt.draw()
			if delay != 0:
				plt.pause(delay/1000)
		plt.show()

	class Tree_iter():
		def __init__(self, node, asNode):
			self.current = node
			self.previous = None
			self.asNode = asNode

		def __iter__(self):
			return self

		def __next__(self):
			# fix the error when there is only a root in the tree
			if self.current == None:
				raise StopIteration
			self.previous = self.current
			self.current = self.current.next()
			return self.previous.value if self.asNode == False else self.previous

if __name__ == '__main__':
	def main(args):
		t = Tree(value=6, widthx=20, heighty=20)
		t.insert(2)
		t.insert(4)
		t.insert(-12)
		t.insert(3.5)
		t.insert(-14)
		t.insert(-15)
		t.insert(-13)
		t.insert(3)
		t.insert(5)
		t.insert(3.75)
		t.insert(10)
		t.insert(15)
		t.insert(7)
		t.insert(8)
		t.insert(12)
		t.insert(50)
		for i in args:
			t.delete(i)

		t.Draw(1)

	args = [int(i) for i in sys.argv[1:]]

	main(args)

	# n = t.find(4)
	# print(n)
	# print(n.next())

	# print(list(t))

	# for i in t.__iter__(asNode=True):
	# 	print(i)


import asyncio
import concurrent.futures
from functools import partial

def NonBlockingTask(f):
    @asyncio.coroutine
    def wrapper(*args, **kargs):
        if 'instanceContext' in kargs:
            executor = kargs['instanceContext'].getSharedService('services.shared.TaskExecutor').getExecutor()
        else:
            executor = None

        loop    = asyncio.get_event_loop()
        kf      = partial(f, *args, **kargs)
        ret     = yield from loop.run_in_executor(executor, kf)
        return ret
    wrapper.__name__ = f.__name__
    return wrapper

class TaskExecutor:
    def __init__(self, appContext):
        self.appContext = appContext
        self.executor = concurrent.futures.ThreadPoolExecutor(None)

    def getExecutor(self):
        return self.executor


#!/usr/bin/env python
# coding: utf-8

# # Building a Trie in Python
#
# Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search.
#
# Before we move into the autocomplete function we need to create a working trie for storing strings.  We will create two classes:
# * A `Trie` class that contains the root node (empty string)
# * A `TrieNode` class that exposes the general functionality of the Trie, like inserting a word or finding the node which represents a prefix.
#
# Give it a try by implementing the `TrieNode` and `Trie` classes below!

# In[15]:

from collections import defaultdict

## Represents a single node in the Trie
class TrieNode:
    def __init__(self):
        ## Initialize this node in the Trie
        self.is_word = False
        self.children = defaultdict(TrieNode)

    def insert(self, char):
        ## Add a child node in this Trie
        return self.children[char]

    def find(self, prefix_char):
        ## Find the Trie node that represents this prefix
        result = self.children[prefix_char]

        if result.is_word == False and len(result.children) == 0:
            result = None

        return result

## The Trie itself containing the root node and insert/find functions
class Trie:
    def __init__(self):
        ## Initialize this Trie (add a root node)
        self.root = TrieNode()

    def insert(self, word):
        ## Add a word to the Trie
        if word:
            current_node = self.root

            for char in word:
                current_node = current_node.insert(char)

            current_node.is_word = True

    def find(self, prefix):
        ## Find the Trie node that represents this prefix
        current_node = self.root

        if prefix:
            for char in prefix:
                current_node = current_node.find(char)

                if current_node is None:
                    current_node = None
                    break
        else:
            current_node = None

        return current_node

# # Finding Suffixes
#
# Now that we have a functioning Trie, we need to add the ability to list suffixes to implement our autocomplete feature.  To do that, we need to implement a new function on the `TrieNode` object that will return all complete word suffixes that exist below it in the trie.  For example, if our Trie contains the words `["fun", "function", "factory"]` and we ask for suffixes from the `f` node, we would expect to receive `["un", "unction", "actory"]` back from `node.suffixes()`.
#
# Using the code you wrote for the `TrieNode` above, try to add the suffixes function below. (Hint: recurse down the trie, collecting suffixes as you go.)

# In[16]:

from collections import defaultdict

class TrieNode:
    def __init__(self):
        ## Initialize this node in the Trie
        self.is_word = False
        self.children = defaultdict(TrieNode)

    def insert(self, char):
        ## Add a child node in this Trie
        return self.children[char]

    def find(self, prefix_char):
        ## Find the Trie node that represents this prefix
        result = self.children[prefix_char]

        if result.is_word == False and len(result.children) == 0:
            result = None

        return result

    def suffixes(self):
        suffix_list = []

        for char in self.children.keys():
            child_node = self.children[char]

            if child_node.is_word:
                suffix_list.append(char)

            child_suffixes = child_node.suffixes()

            for suffix in child_suffixes:
                suffix_list.append(char + suffix)

        return suffix_list

# # Testing the trie
# Now the code is complete and can get suffixes, let's run some testing.

# In[23]:

word_trie = Trie()

word_list = [
    "ant", "ad", "anthology", "antagonist", "antonym",
    "fun", "function", "factory",
    "trie", "trigger", "trigonometry", "tripod",
    "super"
]

for word in word_list:
    word_trie.insert(word)

# Find a regular prefix, one letter.
# Output: ['nt', 'nthology', 'ntagonist', 'ntonym', 'd']
prefix = 'a'
prefix_node = word_trie.find(prefix)
print(prefix_node.suffixes())

# Find a regular prefix, big input.
# Output: ['y']
prefix = 'trigonometr'
prefix_node = word_trie.find(prefix)
print(prefix_node.suffixes())

# Find a whole word as a prefix, big input.
# Output: []
prefix = 'trigonometry'
prefix_node = word_trie.find(prefix)
print(prefix_node.suffixes())

# Find a prefix that only has one word.
# Output: ['per']
prefix = 'su'
prefix_node = word_trie.find(prefix)
print(prefix_node.suffixes())

# Find a prefix that is not in the trie.
# Output: None
prefix = 'wrong'
prefix_node = word_trie.find(prefix)
print(prefix_node)

# Empty prefix parameter.
# Output: None
prefix = ''
prefix_node = word_trie.find(prefix)
print(prefix_node)

# None prefix.
# Output: None
prefix = None
prefix_node = word_trie.find(prefix)
print(prefix_node)

# # Testing it all out
#
# Run the following code to add some words to your trie and then use the interactive search box to see what your code returns.

# In[4]:

MyTrie = Trie()
wordList = [
    "ant", "anthology", "antagonist", "antonym",
    "fun", "function", "factory",
    "trie", "trigger", "trigonometry", "tripod"
]
for word in wordList:
    MyTrie.insert(word)

# In[5]:

from ipywidgets import widgets
from IPython.display import display
from ipywidgets import interact
def f(prefix):
    if prefix != '':
        prefixNode = MyTrie.find(prefix)
        if prefixNode:
            print('\n'.join(prefixNode.suffixes()))
        else:
            print(prefix + " not found")
    else:
        print('')
interact(f,prefix='');

# In[ ]:

# In[ ]: