import tkinter as tk
from tkinter import *
import webbrowser
from tkinter import font
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
import os
from analogy_engine import apply_analogy
from add_new_dish import add_new_dish
LARGE_FONT = ("Verdana", 15)

from tkinter import *
from PIL import ImageTk, Image

def callback(event, url):
    webbrowser.open_new(url)

offset=0

class SeaofBTCapp(tk.Tk):
    frames = {}

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)

        container.pack(side="top", fill="both", expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        for F in (StartPage, ShowResult, AddDish):
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):
    def applyAnalogy(self,controller,tkvar2,dict):
        origin_cuisine=self.tkvar.get()
        origin_dish=self.tkvar3.get()
        destination_cuisine=tkvar2.get()
        vector=[]
        for key in dict:
            if dict[key].get():
                vector.append(key)

        results = apply_analogy(origin_cuisine=origin_cuisine,
                            origin_dish=origin_dish,
                            destination_cuisine=destination_cuisine,
                            num_of_suggestion=3,
                            filters=vector)

        app.frames[ShowResult].text1.configure(text=results[0][0])
        app.frames[ShowResult].text2.bind("<Button-1>", lambda a: webbrowser.open_new(results[0][3]))
        app.frames[ShowResult].text2.configure(text=results[1][0])
        app.frames[ShowResult].text2.bind("<Button-1>", lambda a: webbrowser.open_new(results[1][3]))
        app.frames[ShowResult].text3.configure(text=results[2][0])
        app.frames[ShowResult].text3.bind("<Button-1>", lambda a: webbrowser.open_new(results[2][3]))

        app.frames[ShowResult].conf1.configure(text="(with confidence: " + str(results[0][1]) + ")")
        app.frames[ShowResult].conf2.configure(text="(with confidence: " + str(results[1][1]) + ")")
        app.frames[ShowResult].conf3.configure(text="(with confidence: " + str(results[2][1]) + ")")

        i = Image.open(results[0][2])
        half = 0.3
        out = i.resize([int(half * s) for s in i.size])
        app.frames[ShowResult].img1 = ImageTk.PhotoImage(out)
        app.frames[ShowResult].panel1.configure(image=app.frames[ShowResult].img1)

        i = Image.open(results[1][2])
        half = 0.3
        out = i.resize([int(half * s) for s in i.size])
        app.frames[ShowResult].img2 = ImageTk.PhotoImage(out)
        app.frames[ShowResult].panel2.configure(image=app.frames[ShowResult].img2)

        i = Image.open(results[2][2])
        half = 0.3
        out = i.resize([int(half * s) for s in i.size])
        app.frames[ShowResult].img3 = ImageTk.PhotoImage(out)
        app.frames[ShowResult].panel3.configure(image=app.frames[ShowResult].img3)

        controller.show_frame(ShowResult)

    def dropDownCreator(self,a,b,c):
        self.tkvar3 = tk.StringVar(self)
        self.tkvar3.set("Select your dish")  # set the default option

        string = "./data/embeddings/" + str(self.tkvar.get()) + ".csv"
        array = []
        with open(string) as csv_file:
            # csv_reader = csv.reader(csv_file, delimiter=';')
            for row in csv_file:
                array.append(row.strip().split(';')[0])
        dishes = array

        self.DropDown3 = tk.OptionMenu(self, self.tkvar3, *dishes)
        self.DropDown3.place(relx=0.244, rely=0.214, relheight=0.043, relwidth=0.134)
        self.DropDown3.configure(background="white")
        self.DropDown3.configure(text="Select your dish")
        self.DropDown3.configure(disabledforeground="#a3a3a3")
        self.DropDown3.configure(font="TkFixedFont")
        self.DropDown3.configure(foreground="#000000")
        self.DropDown3.configure(width=154)
        # tkvar3.trace("w", ret_dropdown)

    def __init__(self, parent,controller):
        tk.Frame.__init__(self, parent)

        ingredient = []
        with open('./data/Ingredients.txt') as inputfile:
            for line in inputfile:
                ingredient.append(line.strip().split(' '))
        lista = [item for sublist in ingredient for item in sublist]

        _bgcolor = '#01d4b4'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'

        self.Label1 = tk.Label(self)
        self.Label1.place(relx=0.052, rely=0.112, height=46, width=262)
        self.Label1.configure(activebackground="#24ef1d")
        self.Label1.configure(activeforeground="#000000")
        self.Label1.configure(background="#5daf65")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''Seleziona un piatto di tuo gradimento''')
        self.Label1.configure(width=262)

        self.tkvar = tk.StringVar(self)
        self.tkvar.set('italian')  # set the default option
        choices = {"african", "american", "british", "caribbean", "chinese", "east_european",
                   "french", "greek", "indian", "irish", "italian", "japanese", "korean", "mexican",
                   "nordic", "north_african", "pakistani", "portuguese", "south_american", "spanish",
                   "thai_and_south-east_asian", "turkish_and_middle_eastern"}

        self.DropDown = tk.OptionMenu(self, self.tkvar, *choices)
        self.DropDown.place(relx=0.052, rely=0.202, relheight=0.043, relwidth=0.134)
        self.DropDown.configure(background="white")
        self.DropDown.configure(disabledforeground="#a3a3a3")
        self.DropDown.configure(font="TkFixedFont")
        self.DropDown.configure(foreground="#000000")
        self.DropDown.configure(width=154)
        self.tkvar.trace("w",self.dropDownCreator)

        self.tkvar3 = tk.StringVar(self)
        self.tkvar3.set("Select your dish")  # set the default option

        string = "./data/embeddings/" + str(self.tkvar.get()) + ".csv"
        array = []
        with open(string) as csv_file:
            # csv_reader = csv.reader(csv_file, delimiter=';')
            for row in csv_file:
                array.append(row.strip().split(';')[0])
        dishes = array

        self.DropDown3 = tk.OptionMenu(self, self.tkvar3, *dishes)
        self.DropDown3.place(relx=0.244, rely=0.214, relheight=0.043, relwidth=0.134)
        self.DropDown3.configure(background="white")
        #self.DropDown3.configure(text="Select your dish")
        self.DropDown3.configure(disabledforeground="#a3a3a3")
        self.DropDown3.configure(font="TkFixedFont")
        self.DropDown3.configure(foreground="#000000")
        self.DropDown3.configure(width=154)

        self.Label2 = tk.Label(self)
        self.Label2.place(relx=0.052, rely=0.315, height=46, width=292)
        self.Label2.configure(background="#5daf65")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Seleziona ora la cucina di destinazione''')
        self.Label2.configure(width=292)

        tkvar2 = tk.StringVar(self)

        def change_dropdown2(*args):
            print(tkvar2.get())

        tkvar2.set('Cuisine')  # set the default option
        self.DropDown2 = tk.OptionMenu(self, tkvar2, *choices)
        self.DropDown2.place(relx=0.061, rely=0.439, relheight=0.043, relwidth=0.134)
        self.DropDown2.configure(background="white")
        self.DropDown2.configure(disabledforeground="#a3a3a3")
        self.DropDown2.configure(font="TkFixedFont")
        self.DropDown2.configure(foreground="#000000")
        self.DropDown2.configure(width=154)
        #page1_AI_support.change_dropdown(tkvar2.get())
        tkvar2.trace("w", change_dropdown2)

        self.Label3 = tk.Label(self)
        self.Label3.place(relx=0.061, rely=0.517, height=96, width=332)
        self.Label3.configure(background="#5daf65")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(text='''Se lo desideri puoi aggiungere i seguenti filtri''')
        self.Label3.configure(width=332)

        filters = []
        with open('./data/filtri.txt') as inputfile:
            for line in inputfile:
                filters.append(line.strip().split(' '))
        filtri = [item for sublist in filters for item in sublist]

        DairyFree = tk.BooleanVar(self)
        EggFree = tk.BooleanVar(self)
        Vegan = tk.BooleanVar(self)
        Vegetarian = tk.BooleanVar(self)
        GlutenFree = tk.BooleanVar(self)
        NutFree = tk.BooleanVar(self)
        LowGlycemicIndex = tk.BooleanVar(self)
        PregnancyFriendly = tk.BooleanVar(self)
        LowCalories = tk.BooleanVar(self)

        self.Checkbutton1 = tk.Checkbutton(self)
        self.Checkbutton1.place(relx=0.061, rely=0.664, relheight=0.035, relwidth=0.084)
        self.Checkbutton1.configure(activebackground="#ececec")
        self.Checkbutton1.configure(activeforeground="#000000")
        self.Checkbutton1.configure(background="#5daf65")
        self.Checkbutton1.configure(command=lambda: print(DairyFree.get()))
        self.Checkbutton1.configure(disabledforeground="#a3a3a3")
        self.Checkbutton1.configure(foreground="#000000")
        self.Checkbutton1.configure(highlightbackground="#d9d9d9")
        self.Checkbutton1.configure(highlightcolor="black")
        self.Checkbutton1.configure(justify='left')
        self.Checkbutton1.configure(text='''Dairy Free''')
        #self.Checkbutton1.configure(variable=page1_AI_support.che56)
        self.Checkbutton1.configure(variable=DairyFree)
        #DairyFree.trace("w", var_states)

        self.Checkbutton2 = tk.Checkbutton(self)
        self.Checkbutton2.setvar(value='0')
        self.Checkbutton2.place(relx=0.166, rely=0.664, relheight=0.035, relwidth=0.076)
        self.Checkbutton2.configure(activebackground="#ececec")
        self.Checkbutton2.configure(activeforeground="#000000")
        self.Checkbutton2.configure(background="#5daf65")
        self.Checkbutton2.configure(disabledforeground="#a3a3a3")
        self.Checkbutton2.configure(foreground="#000000")
        self.Checkbutton2.configure(highlightbackground="#d9d9d9")
        self.Checkbutton2.configure(highlightcolor="black")
        self.Checkbutton2.configure(justify='left')
        self.Checkbutton2.configure(text='''Egg Free''')
        #self.Checkbutton2.configure(variable=page1_AI_support.che57)
        self.Checkbutton2.configure(variable=EggFree)
        self.Checkbutton2.configure(command=lambda: print(EggFree.get()))

        self.Checkbutton3 = tk.Checkbutton(self)
        self.Checkbutton3.place(relx=0.061, rely=0.72, relheight=0.035, relwidth=0.062)
        self.Checkbutton3.configure(activebackground="#ececec")
        self.Checkbutton3.configure(activeforeground="#000000")
        self.Checkbutton3.configure(background="#5daf65")
        self.Checkbutton3.configure(disabledforeground="#a3a3a3")
        self.Checkbutton3.configure(foreground="#000000")
        self.Checkbutton3.configure(highlightbackground="#d9d9d9")
        self.Checkbutton3.configure(highlightcolor="black")
        self.Checkbutton3.configure(justify='left')
        self.Checkbutton3.configure(text='''Vegan''')
        #self.Checkbutton3.configure(variable=page1_AI_support.che58)
        self.Checkbutton3.configure(variable=Vegan)

        self.Checkbutton4 = tk.Checkbutton(self)
        self.Checkbutton4.place(relx=0.061, rely=0.776, relheight=0.035, relwidth=0.088)
        self.Checkbutton4.configure(activebackground="#ececec")
        self.Checkbutton4.configure(activeforeground="#000000")
        self.Checkbutton4.configure(background="#5daf65")
        self.Checkbutton4.configure(disabledforeground="#a3a3a3")
        self.Checkbutton4.configure(foreground="#000000")
        self.Checkbutton4.configure(highlightbackground="#d9d9d9")
        self.Checkbutton4.configure(highlightcolor="black")
        self.Checkbutton4.configure(justify='left')
        self.Checkbutton4.configure(text='''Vegetarian''')
        #self.Checkbutton4.configure(variable=page1_AI_support.che59)
        self.Checkbutton4.configure(variable=Vegetarian)

        self.Checkbutton5 = tk.Checkbutton(self)
        self.Checkbutton5.place(relx=0.166, rely=0.72, relheight=0.035, relwidth=0.091)
        self.Checkbutton5.configure(activebackground="#ececec")
        self.Checkbutton5.configure(activeforeground="#000000")
        self.Checkbutton5.configure(background="#5daf65")
        self.Checkbutton5.configure(disabledforeground="#a3a3a3")
        self.Checkbutton5.configure(foreground="#000000")
        self.Checkbutton5.configure(highlightbackground="#d9d9d9")
        self.Checkbutton5.configure(highlightcolor="black")
        self.Checkbutton5.configure(justify='left')
        self.Checkbutton5.configure(text='''Gluten Free''')
        #self.Checkbutton5.configure(variable=page1_AI_support.che60)
        self.Checkbutton5.configure(variable=GlutenFree)

        self.Checkbutton6 = tk.Checkbutton(self)
        self.Checkbutton6.place(relx=0.166, rely=0.776, relheight=0.035, relwidth=0.074)
        self.Checkbutton6.configure(activebackground="#ececec")
        self.Checkbutton6.configure(activeforeground="#000000")
        self.Checkbutton6.configure(background="#5daf65")
        self.Checkbutton6.configure(disabledforeground="#a3a3a3")
        self.Checkbutton6.configure(foreground="#000000")
        self.Checkbutton6.configure(highlightbackground="#d9d9d9")
        self.Checkbutton6.configure(highlightcolor="black")
        self.Checkbutton6.configure(justify='left')
        self.Checkbutton6.configure(text='''Nut Free''')
        #self.Checkbutton6.configure(variable=page1_AI_support.che61)
        self.Checkbutton6.configure(variable=NutFree)

        self.Checkbutton7 = tk.Checkbutton(self)
        self.Checkbutton7.place(relx=0.279, rely=0.664, relheight=0.035, relwidth=0.139)
        self.Checkbutton7.configure(activebackground="#ececec")
        self.Checkbutton7.configure(activeforeground="#000000")
        self.Checkbutton7.configure(background="#5daf65")
        self.Checkbutton7.configure(disabledforeground="#a3a3a3")
        self.Checkbutton7.configure(foreground="#000000")
        self.Checkbutton7.configure(highlightbackground="#d9d9d9")
        self.Checkbutton7.configure(highlightcolor="black")
        self.Checkbutton7.configure(justify='left')
        self.Checkbutton7.configure(text='''Low Glycemic Index''')
        #self.Checkbutton7.configure(variable=page1_AI_support.che62)
        self.Checkbutton7.configure(variable=LowGlycemicIndex)

        self.Checkbutton8 = tk.Checkbutton(self)
        self.Checkbutton8.place(relx=0.279, rely=0.72, relheight=0.035, relwidth=0.133)
        self.Checkbutton8.configure(activebackground="#ececec")
        self.Checkbutton8.configure(activeforeground="#000000")
        self.Checkbutton8.configure(background="#5daf65")
        self.Checkbutton8.configure(disabledforeground="#a3a3a3")
        self.Checkbutton8.configure(foreground="#000000")
        self.Checkbutton8.configure(highlightbackground="#d9d9d9")
        self.Checkbutton8.configure(highlightcolor="black")
        self.Checkbutton8.configure(justify='left')
        self.Checkbutton8.configure(text='''Pregnancy Friendly''')
        #self.Checkbutton8.configure(variable=page1_AI_support.che63)
        self.Checkbutton8.configure(variable=PregnancyFriendly)

        self.Checkbutton9 = tk.Checkbutton(self)
        self.Checkbutton9.place(relx=0.279, rely=0.776, relheight=0.035, relwidth=0.099)
        self.Checkbutton9.configure(activebackground="#ececec")
        self.Checkbutton9.configure(activeforeground="#000000")
        self.Checkbutton9.configure(background="#5daf65")
        self.Checkbutton9.configure(disabledforeground="#a3a3a3")
        self.Checkbutton9.configure(foreground="#000000")
        self.Checkbutton9.configure(highlightbackground="#d9d9d9")
        self.Checkbutton9.configure(highlightcolor="black")
        self.Checkbutton9.configure(justify='left')
        self.Checkbutton9.configure(text='''Low Calories''')
        #self.Checkbutton9.configure(variable=page1_AI_support.che64)
        self.Checkbutton9.configure(variable=LowCalories)
        #print(LowCalories.get())

        dict={"dairy_free": DairyFree, "egg_free":EggFree, "vegan":Vegan, "vegetarian": Vegetarian,
              "gluten_free": GlutenFree, "nut_free": NutFree, "low_glycemic_index": LowGlycemicIndex,
              "pregnancy_friendly": PregnancyFriendly, "low_calories": LowCalories}
        self.Button1 = tk.Button(self)
        self.Button1.place(relx=0.654, rely=0.202, height=103, width=226)
        self.Button1.configure(activebackground="#ececec")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#5daf65")
        self.Button1.configure(command=lambda: self.applyAnalogy(controller,tkvar2,dict))
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''Avanti''')
        self.Button1.configure(width=226)

        self.Button2 = tk.Button(self)
        self.Button2.place(relx=0.793, rely=0.787, height=33, width=22)
        self.Button2.configure(activebackground="#ececec")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#5daf65")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(command=lambda: controller.show_frame(AddDish))
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''+''')

        self.Label4 = tk.Label(self)
        self.Label4.place(relx=0.654, rely=0.664, height=56, width=312)
        self.Label4.configure(background="#5daf65")
        self.Label4.configure(disabledforeground="#a3a3a3")
        self.Label4.configure(foreground="#000000")
        self.Label4.configure(text='''Non hai trovato il tuo piatto? Aggiungilo!''')
        self.Label4.configure(width=312)

class ShowResult(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.label = tk.Label(self, text="Top 3 Reccomandations", font=("Verdana", 24), foreground="red")
        self.label.pack()

        self.text1 = tk.Label(self, text="", font=("Arial", 20), fg="blue", cursor="hand2")
        self.text1.pack(side="top", fill="both", expand="yes")

        self.conf1 = tk.Label(self, text="", font=("Arial", 12))
        self.conf1.pack(side="top", fill="both", expand="yes")

        i = Image.open(
            "./data/DatasetImages/american/American-style blueberry pancakes.jpg")
        half = 0.3
        out = i.resize([int(half * s) for s in i.size])

        self.img1 = ImageTk.PhotoImage(out)
        self.panel1 = Label(self, image=self.img1)
        self.panel1.pack(side="top", fill="both", expand="yes")

        self.text2 = Label(self, text="", font=("Arial", 20), fg="blue", cursor="hand2")
        self.text2.pack(side="top", fill="both", expand="yes")

        self.conf2 = tk.Label(self, text="", font=("Arial", 12))
        self.conf2.pack(side="top", fill="both", expand="yes")

        self.img2 = ImageTk.PhotoImage(out)
        self.panel2 = Label(self, image=self.img2)
        self.panel2.pack(side="top", fill="both", expand="yes")

        self.text3 = Label(self, text="", font=("Arial", 20), fg="blue", cursor="hand2")
        self.text3.pack(side="top", fill="both", expand="yes")

        self.conf3 = tk.Label(self, text="", font=("Arial", 12))
        self.conf3.pack(side="top", fill="both", expand="yes")

        self.img3 = ImageTk.PhotoImage(out)
        self.panel3 = Label(self, image=self.img3)
        self.panel3.pack(side="top", fill="both", expand="yes")

        button1 = tk.Button(self, text="Fai una nuova ricerca",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack(side="bottom")

class AddDish(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        ingrList = []
        label = tk.Label(self, text="Aggiungi un nuovo piatto", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        self.tkvar4 = tk.StringVar(self)
        self.tkvar4.set('italian')  # set the default option
        choices = {"african", "american", "british", "caribbean", "chinese", "east_european",
                   "french", "greek", "indian", "irish", "italian", "japanese", "korean", "mexican",
                   "nordic", "north_african", "pakistani", "portuguese", "south_american", "spanish",
                   "thai_and_south-east_asian", "turkish_and_middle_eastern"}

        def getResult(*args):
            self.newCuisine=str(self.tkvar4.get())
            print(self.tkvar4.get())

        self.newCuisine=""
        self.DropDown4 = tk.OptionMenu(self, self.tkvar4, *choices)
        self.DropDown4.place(relx=0.052, rely=0.202, relheight=0.043, relwidth=0.134)
        self.DropDown4.configure(background="white")
        self.DropDown4.configure(disabledforeground="#a3a3a3")
        self.DropDown4.configure(font="TkFixedFont")
        self.DropDown4.configure(foreground="#000000")
        self.DropDown4.configure(width=154)
        # variable=tkvar.trace("w", change_dropdown)
        self.tkvar4.trace("w", getResult)
        # print(variabile)

        button1 = tk.Button(self, text="Indietro",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Avvia",
                            command=lambda: controller.show_frame(StartPage))
        button2.pack()

        button3 = tk.Button(self, text="Sfoglia...", command=self.load_file, width=10)
        button3.pack()

        button3 = tk.Button(self, text="Aggiungi ingrediente", command=self.addIngredient, width=10)
        button3.pack()

        self.entry= tk.Entry(self)
        self.entry.pack()

        button4 = tk.Button(self, text="Inserisci nome piatto", command=self.dishName, width=10)
        button4.pack()
        self.nameDish=""
        self.imagePath=""

    def dishName(self):
        a=str(self.entry.get())
        self.nameDish=a
        print(a)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Jpeg files", "*.jpeg;*.jpg;*.JPG;*.JPEG"),
                                           ("All files", "*.*")))
        fname = os.path.realpath(fname)
        try:
            print(fname)
            self.imagePath=fname
        except:
            showerror("Open Source File", "Errore di lettura del file\n'%s'" % fname)
        return
    #def addIngredient(self,ingrList,controller):

    def addIngredient(self):
        ingredient = []
        global ingrList
        ingrList=[]
        with open('./data/Ingredients.txt') as inputfile:
            for line in inputfile:
                ingredient.append(line.strip().split(' '))
        lista = [item for sublist in ingredient for item in sublist]
        self.tkvar5 = tk.StringVar(self)

        def listIngredient(a,b,c):
            print(self.tkvar5.get())
            ingrList.append(str(self.tkvar5.get()))

        self.DropDown5 = tk.OptionMenu(self, self.tkvar5, *lista)
        self.DropDown5.place(relx=0.061, rely=0.439, relheight=0.043, relwidth=0.134)
        self.tkvar5.trace("w", listIngredient)
        app.update()

    def addNewDish(self,controller):

        correct = str(";".join(ingrList))
        results= add_new_dish(name=self.nameDish,
                     cuisine=self.newCuisine,
                     ingredients=correct,
                     path_image=self.imagePath)

        controller.show_frame(StartPage)

app = SeaofBTCapp()
app.mainloop()


import powerpool, powerport
class PowerSystem():
    #define powersystem with a power pool and a number of ports
    def __init__(self, numPorts, totalStorage):
        self.pool = powerpool.PowerPool(totalStorage)
        self.port = []
        for i in range(numPorts):
            self.port.append(powerport.PowerPort)
        # self.port[numPorts] = powerport.PowerPort
    def printState(self):
        print("Pool: ")
        self.pool.printState()
        for i in range(len(self.port)):
            print("Port " + str(i) + ":")
            self.port[i].printState()
    # def plug(self, id, requestedPower):
    #     if self.port[id].connected == True:
    #         return False
    #     elif self.pool.request(requestedPower):
    #         self.port[id].connected = True
    #         self.port[id].activePower = requestedPower
    #         return True
    #     else:
    #         return False


from sys import exit

try:
  from OpenGL.GLUT import *
  from OpenGL.GL import *
  from OpenGL.GLU import *
  print("pyOpenGL imported")
except:
  print("Can't locate pyopengl. Please install.")
  exit(0)

#GLOBAL VARS#
Window = None
WindowSize = (600,600)

def display():
  global WindowSize
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  glMatrixMode(GL_PROJECTION)
  glLoadIdentity()
  gluPerspective(50,WindowSize[0]/WindowSize[1],0.5,20.0) #fov,aspect,near,far

  #make axes
  axes = glGenLists(1)
  glNewList(axes, GL_COMPILE)
  glPushMatrix()
  glTranslate(0, 0, -5)
  make_cube((1,1,10), highlight=True, color=color_red, edges=False)
  glPopMatrix()
  glPushMatrix()
  glTranslate(-5, 0, 0)
  make_cube((10,1,1), highlight=True, color=color_green, edges=False)
  glPopMatrix()
  glPushMatrix()
  glTranslate(0, 5, 0)
  make_cube((1,10,1), highlight=True, color=color_blue, edges=False)
  glPopMatrix()
  glEndList()

  glCallList(axes)
  glutSwapBuffers()
  print("Hi")

glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(WindowSize[0],WindowSize[1])
Window = glutCreateWindow(b"PyOpenGL Viewer")
glClearColor(0,0,0,0)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
glutDisplayFunc(display)
glutMainLoop()


import pyfirmata
from pyfirmata import Arduino, INPUT, PWM
import time

board = pyfirmata.Arduino("COM4")

it = pyfirmata.util.Iterator(board)
it.start()

red = board.get_pin('d:3:p')
blue = board.get_pin('d:5:p')
green = board.get_pin('d:6:p')

r=0.50
b=0.50
g=0.50

for i in range(100):

    while r>=0.5 and r<=1:
        red.write(r)
        time.sleep(0.01)
        red.write(0)
        r = r + 0.01

    while r>0:
        red.write(r)
        green.write(g)
        time.sleep(0.01)
        red.write(0)
        green.write(0)
        r = r - 0.02
        g = g + 0.01

    r=0.51

    while g>=0.5 and g<=1:
        green.write(g)
        time.sleep(0.01)
        green.write(0)
        g = g + 0.01

    while g>0:
        green.write(g)
        blue.write(b)
        time.sleep(0.01)
        green.write(0)
        blue.write(0)
        g = g - 0.02
        b = b + 0.01

    g=0.51

    while b>=0.5 and b<=1:
        blue.write(b)
        time.sleep(0.01)
        blue.write(0)
        b = b + 0.01

    while b>0:
        blue.write(b)
        red.write(r)
        time.sleep(0.01)
        blue.write(0)
        red.write(0)
        b = b - 0.02
        r = r + 0.01

    b=0.51


# for coniguration files details see https://martin-thoma.com/configuration-files-in-python/

"""A configuration file"""
# import using: import Utilities.Configuration.config as cfg

is_test = False
debug = False
save_best_episode = True

# num of step in each session
MAX_NUM_OF_STEPS = 12

# output directory relative path
outdir = ""

"""training configuration"""
num_envs = 1

"""model"""
n_hidden_layers = 1
n_hidden_channels = 64
arch = 'FFGaussian'
beta = 1.0

"""data"""
schema = 'NETWORKING'  # or 'NETWORKING', 'FLIGHTS', 'BIG_FLIGHTS', 'WIDE_FLIGHTS', 'WIDE12_FLIGHTS'
# If None a dataset number of the given schema is chosen randomly for each new episode
# If given, this dataset number for the given schema is used for all episodes
dataset_number = None

"""env"""
# back actions are not available (DEPRECATED!)
no_back = False

# observation vector will include the step number if True
obs_with_step_num = False
obs_with_session_tree = False
obs_stack_history = False

# number of previous display vectors that will be stacked in the observation vector (including the current display)
stack_obs_num = 1

# filter term bins sizes
bins_sizes = 'CUSTOM_WIDTH'
exponential_sizes_num_of_bins = 35
add_random_to_bin_calculation = False

"""reward"""
# humanity (coherency) reward
use_humans_reward = True
humans_reward_interval = 64
humanity_coeff = 1.0
filter_from_dict = False

user_input_query = None
constraints_dict = None
override_constraints = False

no_coherency = False
use_language_reward = True
use_depth_reward = False
use_column_reward = False
coherency_coeff = 1.0
dont_act_deterministically = False

# diversity reward
no_diversity = False
diversity_coeff = 1.0

# interestingness reward
no_interestingness = False
kl_coeff = 1.0
compaction_coeff = 1.0
count_data_driven = False

compact_observation = False
obs_with_session_graph = False
obs_with_session_tree_compact = False
use_clip_threshold_on_observation = True

"""logging"""
log_interval = 1000

"""optimizations"""
max_nn_tokens = 12
cache_dfs_size = 750
cache_tokenization_size = 10000
cache_distances_size = 750

punish_for_filter_with_same_num_of_rows = False
support_greater_equal = True
support_lower_equal = False
support_average = False

no_distance_reward = False
no_immediate = False
no_buttons = False


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

import jieba
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.cluster import KMeans
from text_analysis_tools.api.text_cluster import STOPWORDS

class KmeansClustering():
    def __init__(self, stopwords_path=STOPWORDS):
        self.stopwords = self.load_stopwords(stopwords_path)
        self.vectorizer = CountVectorizer()
        self.transformer = TfidfTransformer()

    def load_stopwords(self, stopwords=None):
        """
        加载停用词
        :param stopwords:
        :return:
        """
        if stopwords:
            with open(stopwords, 'r', encoding='utf-8') as f:
                return [line.strip() for line in f]
        else:
            return []

    def preprocess_data(self, corpus_path):
        """
        文本预处理，每行一个文本
        :param corpus_path:
        :return:
        """
        corpus = []
        with open(corpus_path, 'r', encoding='utf-8') as f:
            for line in f:
                corpus.append(' '.join([word for word in jieba.lcut(line.strip()) if word not in self.stopwords]))
        return corpus

    def get_text_tfidf_matrix(self, corpus):
        """
        获取tfidf矩阵
        :param corpus:
        :return:
        """
        tfidf = self.transformer.fit_transform(self.vectorizer.fit_transform(corpus))

        # 获取词袋中所有词语
        # words = self.vectorizer.get_feature_names()

        # 获取tfidf矩阵中权重
        weights = tfidf.toarray()
        return weights

    def kmeans(self, corpus_path, n_clusters=5):
        """
        KMeans文本聚类
        :param corpus_path: 语料路径（每行一篇）,文章id从0开始
        :param n_clusters: ：聚类类别数目
        :return: {cluster_id1:[text_id1, text_id2]}
        """
        corpus = self.preprocess_data(corpus_path)
        weights = self.get_text_tfidf_matrix(corpus)

        clf = KMeans(n_clusters=n_clusters)

        # clf.fit(weights)

        y = clf.fit_predict(weights)

        # 中心点
        # centers = clf.cluster_centers_

        # 用来评估簇的个数是否合适,距离约小说明簇分得越好,选取临界点的簇的个数
        # score = clf.inertia_

        # 每个样本所属的簇
        result = {}
        for text_idx, label_idx in enumerate(y):
            key = "cluster_{}".format(label_idx)
            if key not in result:
                result[key] = [text_idx]
            else:
                result[key].append(text_idx)
        return result

if __name__ == '__main__':
    Kmeans = KmeansClustering(stopwords_path='../data/stop_words.txt')
    result = Kmeans.kmeans('../data/test_data.txt', n_clusters=5)
    print(result)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'joeya'
__mtime__ = '2017/8/6'
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃　永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""
# !/usr/bin/env python
# coding:utf-8
import socket

def handle_request(client):
    buf = client.recv(1024)
    client.send(b"HTTP/1.1 200 OK\r\n\r\n")
    client.send('''<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Title name</title>

    百度
    <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502004070658&di=35d5af41c7adad3e4b0d025d94287a4c&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F159%2F42%2F3JFPCDDY03A1.jpg"

'''.encode())

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 8080))
    sock.listen(5)

    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':
    main()


from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *

class ROIDialog(QDialog):
    def __init__(self, text='Enter description of ROI', parent=None):
        super().__init__(parent)
        self.setWindowTitle(text)
        self.resize(QSize(325, 86))

        # Create label.
        self.machineName_lb = QLabel('machineName')
        self.frameName_lb = QLabel('frameName')
        self.roiName_lb = QLabel('roiName')
        ## Set minimum width of label.
        self.machineName_lb.setFixedWidth(80)
        self.frameName_lb.setFixedWidth(80)
        self.roiName_lb.setFixedWidth(80)

        # Create textbox.
        self.machineName = QLineEdit()
        self.machineName.setText(text)
        self.frameName = QLineEdit()
        self.frameName.setText(text)
        self.roiName = QLineEdit()
        self.roiName.setText(text)

        # Create OK & Canncel button
        self.buttonBox = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.buttonBox.button(QDialogButtonBox.Ok).setIcon(
            QIcon('./resources/icons/done.png'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setIcon(
            QIcon('./resources/icons/cancel.png'))

        # Connect slot of button.
        self.buttonBox.accepted.connect(self.validate)
        self.buttonBox.rejected.connect(self.reject)

        # Set layout
        ## Set machineName layout
        machineLayout = QHBoxLayout()
        machineLayout.addWidget(self.machineName_lb)
        machineLayout.addWidget(self.machineName)
        machineWidget = QWidget()
        machineWidget.setLayout(machineLayout)
        ## Set frameName layout
        frameLayout = QHBoxLayout()
        frameLayout.addWidget(self.frameName_lb)
        frameLayout.addWidget(self.frameName)
        frameWidget = QWidget()
        frameWidget.setLayout(frameLayout)
        ## Set roiName layout
        roiLayout = QHBoxLayout()
        roiLayout.addWidget(self.roiName_lb)
        roiLayout.addWidget(self.roiName)
        roiWidget = QWidget()
        roiWidget.setLayout(roiLayout)

        layout = QVBoxLayout()
        layout.addWidget(machineWidget)
        layout.addWidget(frameWidget)
        layout.addWidget(roiWidget)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def validate(self):
        """Validate entered text."""
        if self.machineName.text().strip() and \
            self.frameName.text().strip() and \
            self.roiName.text().strip():
            self.accept()

    def popUp(self, text=''):
        """Popup dialog to enter description of ROI."""
        self.machineName.setText(text)
        self.frameName.setText(text)
        self.roiName.setText(text)
        self.machineName.setSelection(0, len(text))
        self.frameName.setSelection(0, len(text))
        self.roiName.setSelection(0, len(text))
        self.machineName.setFocus(Qt.PopupFocusReason)

        return (
            self.machineName.text(),
            self.frameName.text(),
            self.roiName.text()
            ) if self.exec_() else (None, None, None)


import timers

timer = timers.timer()
counter = 0
elapsed = 0

def calculate_distance(trigger_pin, echo_pin) :
        # print("Initialization")
        digitalWrite(trigger_pin, LOW)
        sleep(1)
        digitalWrite(trigger_pin, HIGH)
        sleep(1)
        digitalWrite(trigger_pin, LOW)

        while digitalRead(echo_pin) == 0:
            if counter > 100:
                counter = 0
                return -1.0
            counter += 1

        timer.start()

        while digitalRead(echo_pin) == 1:
            if counter > 100:
                counter = 0
                return -1.0
            counter += 1

        elapsed = timer.get()

        # print("Elapsed time: ", elapsed, " ms")
        distance = elapsed * 34.38 / 2 # velocità del suono nell'aria circa 343.8 m/s cioè 34.38 cm/ms
        # print("Distance: ", distance, " cm")
        return distance


from django import forms
from .models import Order

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('landlord_profile', 'full_name', 'email', 'phone_number',
                  'country', 'postcode', 'town_or_city',
                  'street_address1', 'street_address2',)

    def __init__(self, *args, **kwargs):
        """
        Add placeholders, remove auto-generated labels
        """
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].label = False
            if self.fields[field].required:
                placeholder = f'{field}*'
            else:
                placeholder = field
            placeholder = placeholder.replace('_',  ' ')
            if field != 'country':
                self.fields[field].widget.attrs['placeholder'] = \
                                                placeholder.capitalize()


from pythonds3.basic import Stack

def to_str(n, base):
    r_stack = Stack()
    convert_string = "0123456789ABCDEF"
    while n > 0:
        if n < base:
            r_stack.push(convert_string[n])
        else:
            r_stack.push(convert_string[n % base])
        n = n // base
    res = ""
    while not r_stack.is_empty():
        res = res + str(r_stack.pop())
    return res


from conf import conf
from sgfmill import sgf
import os
from collections import defaultdict
from math import sqrt

GAMES_DIR = conf['GAMES_DIR']

def analysis():
    directory = GAMES_DIR
    results = defaultdict(list)
    i = 0
    for model_directory in os.listdir(directory):
        for filename in os.listdir(os.path.join(directory, model_directory)):
            if filename.endswith('.sgf'): # Ignore sgf files.
                with open(os.path.join(directory, model_directory, filename), 'rb') as f:
                    game = sgf.Sgf_game.from_bytes(f.read())
                    i += 1

                    playerb = game.get_player_name('b')
                    playerw = game.get_player_name('w')
                    winner_is_black = game.get_winner() == 'b'
                    results[(playerb, playerw)].append( winner_is_black)
    return results

if __name__ == "__main__":
    results = analysis()
    total = 0
    n = 0
    for key, l in results.items():
        mean = sum(l) /  float(len(l))
        delta = 2./sqrt(len(l))
        interval = [mean - delta, mean + delta]

        n += len(l)
        total += sum(l)

    m = total / n
    delta = 1/sqrt(n)
    print("Average black winrate [", m - delta, ",", m + delta, "]")


import torch
import numpy as np
from torch.nn import Linear, Embedding, LSTM
from torch.nn import LogSoftmax

class Encoder(torch.nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, batch_size):
        super(Encoder, self).__init__()
        self.hidden_dim = hidden_dim
        self.embedding = Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
        self.rnn = LSTM(input_size=embedding_dim, hidden_size=hidden_dim)
        self.batch_size = batch_size
        self.softmax = LogSoftmax()
        self.hidden = self.init_hidden()

    def forward(self, x):
        e = self.embedding(x)
        e = e.view(len(x), self.batch_size, -1)
        out, self.hidden = self.rnn(e, self.hidden)
        return out, self.hidden

    def init_hidden(self):
        h0 = torch.autograd.Variable(torch.zeros(1, self.batch_size, self.hidden_dim))
        c0 = torch.autograd.Variable(torch.zeros(1, self.batch_size, self.hidden_dim))
        return (h0, c0)

class Decoder(torch.nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, batch_size):
        super(Decoder, self).__init__()
        self.hidden_dim = hidden_dim
        self.embedding = Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
        self.rnn = LSTM(input_size=embedding_dim, hidden_size=hidden_dim)
        self.linear = Linear(hidden_dim, output_dim)
        self.batch_size = batch_size
        self.softmax = LogSoftmax(dim=1)
        self.hidden = self.init_hidden()

    def forward(self, input, hidden):
        self.hidden = hidden
        e = self.embedding(input)
        e = e.view(len(input), self.batch_size, -1)
        out, self.hidden = self.rnn(e, self.hidden)
        self.out = out
        output = self.linear(out[0])
        so = self.softmax(output)
        return so, self.hidden

    def init_hidden(self):
        h0 = torch.autograd.Variable(torch.zeros(1, self.batch_size, self.hidden_dim))
        c0 = torch.autograd.Variable(torch.zeros(1, self.batch_size, self.hidden_dim))
        return (h0, c0)

class Seq2seq(torch.nn.Module):
    def __init__(self, encoder, decoder):
        super(Seq2seq, self).__init__()
        self.enc = encoder
        self.dec = decoder

    def forward(self, input_seq, output_seq, p_tf=0):
        outputs = []

        self.enc.hidden = self.enc.init_hidden()
        self.dec.hidden = self.dec.init_hidden()

        enc_output, enc_hidden = self.enc.forward(torch.LongTensor(input_seq))
        dec_hidden = enc_hidden
        tf_cnt = 0
        for i in range(output_seq.shape[0]):

            if (np.random.uniform()) > p_tf and (i != 0):
                dec_input = torch.LongTensor([torch.argmax(dec_output).data])
            else:
                dec_input = torch.LongTensor([output_seq[i]])

            dec_output, dec_hidden = self.dec.forward(dec_input, dec_hidden)
            outputs.append(dec_output)

        return torch.stack(outputs).squeeze(1)

    def predict(self, input_seq, sos_idx, eos_idx, max_len=20):
        outputs = []
        self.enc.hidden = self.enc.init_hidden()
        self.dec.hidden = self.dec.init_hidden()

        enc_output, enc_hidden = self.enc.forward(torch.LongTensor(input_seq))
        dec_hidden = enc_hidden

        cnt = 0
        dec_input = torch.LongTensor([sos_idx])

        dec_output, dec_hidden = self.dec.forward(dec_input, dec_hidden)

        output_idx = torch.argmax(dec_output).data

        while (int(output_idx) != eos_idx) and (cnt <= max_len):
            cnt += 1
            dec_input = torch.LongTensor([output_idx])
            dec_output, dec_hidden = self.dec.forward(dec_input, dec_hidden)
            output_idx = torch.argmax(dec_output).data
            outputs.append(int(output_idx))

        return outputs


import pandas as pd
from pybit import usdt_perpetual

import crypto_scraper as cs

extraction = True
updating = False

session_unauth = usdt_perpetual.HTTP(
    endpoint="https://api-testnet.bybit.com"
)

bybit_scr = cs.ByBit_Scraper(session_unauth)                                                            # Create a ByBit Scraper Object

# Data Extraction
if extraction:
    bybit_scr.extract_history("ETHUSDT", 15)                                                            # Extract Data
    print(bybit_scr.get_dataframe())                                                                    # Print the final dataframe
    bybit_scr.to_csv(r"C:\Users\axeli\Desktop\Github\crypto-trading\Data Analysis\ETHUSDT 15.csv")      # Save the data in a .csv file

# Data Updating
if updating:
    bybit_scr.set_dataframe(pd.read_csv(r"C:\Users\axeli\Desktop\Github\crypto-trading\Data Analysis\BTCUSDT 5.csv"))   # Read a .csv and set it as dataframe
    bybit_scr.update_history()                                                                                # Update the dataframe
    bybit_scr.to_csv(r"C:\Users\axeli\Desktop\Github\crypto-trading\Data Analysis\BTCUSDT 5.csv")                       # Save the data in a .csv file


from flask import Flask, jsonify, request
from flask_restful import Resource, Api, reqparse

import pandas as pd
import numpy as np

app = Flask(__name__)
api = Api(app)

# constructors ->

class add(Resource):
    def post(self):
        add_data = request.get_json()
        addition = sum(list(add_data.values()))
        return addition

# assign addition endpoint
api.add_resource(add, '/add')

class subtract(Resource):
    def post(self):
        sub_data = request.get_json()
        sub_list = list(sub_data.values())
        subtraction = []
        for number in range(len(sub_list)-1):
            temp_num = sub_list[number] - sub_list[number+1]
            subtraction.append(temp_num)
        return subtraction

# assign addition endpoint
api.add_resource(subtract, '/subtract')


#Embedded file name: overviewPresets\overviewPresetUtil.py
"""
    This file contains some utility functions for the overview presets, for storing them and sharing with others
"""
import hashlib
import yaml
MAX_SHARED_PRESETS = 15
MAX_TAB_NUM = 5

def GetDeterministicListFromDict(inputDict):
    outputList = [ (x, y) for x, y in inputDict.iteritems() ]
    outputList.sort()
    return outputList

def GetDictFromList(inputList):
    return {x:y for x, y in inputList}

def ReplaceInnerListsWithDicts(parentDict):
    for tabIdx, tabValue in parentDict.iteritems():
        newTabValue = GetDictFromList(tabValue)
        parentDict[tabIdx] = newTabValue

    return parentDict

def GetOrderedListFromDict(inputDict, orderedKeys):
    dictCopy = inputDict.copy()
    outputList = []
    for eachKey in orderedKeys:
        dictValue = dictCopy.pop(eachKey, None)
        if dictValue:
            outputList.append(dictValue)

    outputList += dictCopy.values()
    return outputList

def GetHashvalueFromDict(inputDict):
    inputList = GetDeterministicListFromDict(inputDict)
    hashvalue = GetHashvalueForList(inputList)
    return hashvalue

def GetYamlStringFromDict(inputDict):
    inputList = GetDeterministicListFromDict(inputDict)
    yamlString = GetYamlStringFromList(inputList)
    return yamlString

def GetYamlStringFromList(inputList):
    yamlString = yaml.safe_dump(inputList)
    return yamlString

def GetHashvalueForList(inputList):
    yamlString = GetYamlStringFromList(inputList)
    return GetHashValueFromString(yamlString)

def GetHashValueFromString(yamlString):
    hashvalue = hashlib.sha1(yamlString).hexdigest()
    return hashvalue

def EncodeKeyInDict(inputDict):
    outputDict = {}
    for key, value in inputDict.iteritems():
        newKey = '%s_%s' % (key[0], key[1])
        outputDict[newKey] = value

    return outputDict

def DecodeKeyInDict(inputDict):
    """ assumes first element in key is string, other int """
    outputDict = {}
    for key, value in inputDict.iteritems():
        parts = key.split('_')
        newKey = (parts[0], int(parts[1]))
        outputDict[newKey] = value

    return outputDict

def IsPresetTheSame(preset1, preset2):

    def CheckPreset(pA, pB):
        for pAKey, pAValue in pA.iteritems():
            pBValue = pB.get(pAKey, -1)
            if pBValue == -1 and not pAValue:
                continue
            if pBValue != pAValue:
                return False

        return True

    allP1InP2 = CheckPreset(preset1, preset2)
    allP2InP1 = CheckPreset(preset2, preset1)
    return allP1InP2 and allP2InP1

def ReorderList(parentDict, namesToReorder):
    for reorderName in namesToReorder:
        listToReorder = parentDict.get(reorderName, None)
        if listToReorder is None:
            continue
        listToReorder.sort()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import logging
import json
import gc
import subprocess as sp

import matplotlib
matplotlib.use('Agg')

import churnr
from churnr import sample, extract, process, train, plot

logger = logging.getLogger('churnr.experiment')

def run(args):
    logger.info('Initializing experiment...')

    with open(args.exppath) as fi:
        expconf = json.load(fi)[args.experiment]

    datasets = expconf['datasets']
    models = expconf['models']
    plots = expconf['plots']
    expabspath = os.path.abspath(args.exppath)

    # sample stage
    if 'sample' in args.stages:
        # sort the datasets by size of observation or prediction window, and sample users only on
        # the largest one as to have the same set of user ids of across all datasets
        if 'preddays' not in datasets['global']:
            datasets_sorted = sorted(datasets.items(), key=lambda x: x[1].get('preddays', 0), reverse=True)
        else:
            datasets_sorted = sorted(datasets.items(), key=lambda x: x[1].get('obsdays', 0), reverse=True)

        sampleusers = True
        for dsname, _ in datasets_sorted:
            if dsname == 'global' or (len(args.datasets) and dsname not in args.datasets):
                continue

            sample.main(exppath=expabspath, experiment=args.experiment, dsname=dsname, sampleusers=sampleusers)
            sampleusers = False

    # play context parsing stage
    if 'parse' in args.stages:
        basepath = os.path.dirname(churnr.__file__)
        for dsname in datasets.keys():
            if dsname == 'global' or (len(args.datasets) and dsname not in args.datasets):
                continue

            bqdataset = datasets['global']['dataset']
            bqproject = datasets['global']['project']
            table = '{}.features_{}_{}_p'.format(bqdataset, args.experiment, dsname)
            sp.call([os.path.join(basepath,'scala', 'run.sh'), bqproject, table])

    # extract stage
    if 'extract' in args.stages:
        for dsname in datasets.keys():
            if dsname == 'global' or (len(args.datasets) and dsname not in args.datasets):
                continue

            extract.main(exppath=expabspath, experiment=args.experiment, dsname=dsname)

    # process stage
    if 'process' in args.stages:
        for dsname in datasets.keys():
            if dsname == 'global' or (len(args.datasets) and dsname not in args.datasets):
                continue

            process.main(exppath=expabspath, experiment=args.experiment, dsname=dsname)

    # train stage
    if 'train' in args.stages:
        for dsname in datasets.keys():
            if dsname == 'global' or (len(args.datasets) and dsname not in args.datasets):
                continue

            # remove any local files stored in another run
            dspath = os.path.join(datasets['global']['procpath'], args.experiment, dsname)
            if os.path.exists(dspath):
                import shutil
                shutil.rmtree(dspath)
            os.makedirs(dspath)

            for modelname in models.keys():
                if modelname == 'global' or (len(args.models) and modelname not in args.models):
                    continue

                args.modelname = modelname
                args.dsname = dsname
                train.main(args)

                # dispatches garbage collector after each training
                gc.collect()

    # plot stage
    if 'plot' in args.stages:
        for plotname in plots.keys():
            if plotname == 'global':
                continue

            plot.main(exppath=expabspath, experiment=args.experiment, plotname=plotname)

    logger.info('Done!')

def main():
    path = os.path.dirname(churnr.__file__)

    parser = argparse.ArgumentParser(description='Experiment dispatcher')
    parser.add_argument('--exppath', default=os.path.join(path, 'experiments.json'), help='Path to the experiments json file')
    parser.add_argument('--experiment', default='temporal_static', help='Name of the experiment being performed')
    parser.add_argument('--stages', default=['sample', 'parse', 'extract','process','train', 'plot'], help='Stages that will be executed', nargs='*')
    parser.add_argument('--models', default=[], help='Model that will be trained', nargs='*')
    parser.add_argument('--datasets', default=[], help='Datasets that will be processed', nargs='*')
    parser.add_argument('--debug', default=False, help='Debug flag that sped up some stages', action='store_true')

    args = parser.parse_args()

    run(args)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
"""
AY 250 - Scientific Research Computing with Python
Homework Assignment 3 - Parallel Feature Extraction Example
Author: Christopher Klein
"""
from os import listdir
from pylab import imread
from time import time
import featureExtractor

# Our simple feature extraction function. It takes in a list of image paths,
# does some measurement on each image, then returns a list of the image paths
# paired with the results of the feature measurement.
def extract_features(image_path_list):
    feature_list = []
    for image_path in image_path_list:
        image_array = imread(image_path)
#        emat = featureExtractor.getEdgeMatrix(image_array, 3)
#        feature = featureExtractor.getNumMeridialEdges(emat)
        feature = featureExtractor.getMeanGreenVal(image_array)
        feature_list.append([image_path, feature])
    return feature_list

### Main program starts here ###################################################
# We first collect all the local paths to all the images in one list
image_paths = []
categories = listdir("50_categories")
for category in categories:
	image_names = listdir("50_categories/" + category )
	for name in image_names:
        	image_paths.append("50_categories/" + category + "/" + name)

print ("There should be 4244 images, actual number is " +
    str(len(image_paths)) + ".")

start_time = time()
featureList = extract_features(image_paths)
end_time = time()

# All done, print timing results.
print ("Finished extracting features. Total time: " +
    str(round(end_time-start_time, 3)) + " s, or " +
    str( round( (end_time-start_time)/len(image_paths), 5 ) ) + " s/image.")


import os
from time import sleep
import platform
from tkinter import messagebox, Tk
import sys
import datetime
from checkInternet.Alerts import alert
from checkInternet import internet, AlertFactory
from checkInternet.Alerts import AlertTypes
# from internet import internet_fail, internet_on
# import Alerts
# import internet
import argparse

def reporter(f):

    def wrap(*args, **kwargs):
        x = f(*args, **kwargs)
        print("[{}] Internet up. Press \"Ctrl + c\" to quit".format(str(datetime.datetime.now().isoformat())))
        return x

    return wrap

@reporter
def report_internet():
    x = internet.multi_attempt()
    return x

def check_internet(fail_callback, sleeptime=60):
    try:
        while report_internet():
            sleep(sleeptime)
        sys.stdout.write('\a')
        sys.stdout.flush()
        fail_callback("Internet Down at {}".format(str(datetime.datetime.now().isoformat())))
    except KeyboardInterrupt:
        print()
        print("Exiting")
        pass

def check_internet2(alerter, sleeptime=60):
    try:
        while report_internet():
            sleep(sleeptime)
        # sys.stdout.write('\a')
        # sys.stdout.flush()
        alerter.message = "Internet Down at {}".format(str(datetime.datetime.now().isoformat()))
        alerter.execute()
    except KeyboardInterrupt:
        print()
        print("Exiting")
        pass

def get_alerter():
    alert_factory = AlertFactory()
    if platform.system() == "Darwin":
        return alert_factory.create_alerter(AlertTypes.COCO)
    else:
        return alert_factory.create_alerter(AlertTypes.TK)

def main():
    parser = argparse.ArgumentParser(description="Checks to see to let you know if the internet is still accessible")
    parser.add_argument("frequency", nargs="?", type=int, default=60,
                        help="How many seconds between each check. (Default is 60)")
    args = parser.parse_args()
    print()
    print("Starting to monitor Internet access\n")
    print("Checking every {} second(s)".format(args.frequency))
    alerter = get_alerter()
    check_internet2(alerter, sleeptime=args.frequency)
    # check_internet(alert.Alert, args.frequency)
    # check_internet(no_internet_tk, args.frequency)
    print("Goodbye")

if __name__ == '__main__':
    main()