#######Machine Learning Deployment######
##Libraries
import tkinter
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from tkinter.filedialog import askopenfilename
##
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
##
from sklearn.cluster import KMeans
import scipy.cluster.hierarchy as sch
from sklearn.cluster import AgglomerativeClustering
#--------------------xxx--------------------------------
###Windows creation
class window:
    #browse dataset
    def window1(self):
        window1 = Tk()
        window1.title('ML Algorithms')
        window1.config(bg='lightblue')
        window1.state('zoomed')

        label1 = Label(window1,text='Machine Learning Algorithms',bg='lightblue',font=('helvetica',18,'bold')).place(x=520,y=150)
        label2 = Label(window1,bg='lightyellow',relief='solid').place(x=500,y=300,height=200,width=400)
        label3 = Label(window1,text='Upload your Dataset',bg='lightyellow',font=('helvetica',12,'bold')).place(x=615,y=320)

        def browse():
            global file,data
            file = filedialog.askopenfilename(initialdir="F:/",filetypes = [("csv files","*.csv")])
            entry1.insert(0,file)
            data = pd.read_csv(file)

        entry1 = Entry(window1)
        entry1.place(x=543,y=380,height=40,width=320)
        entry1.configure(bg='lightblue')

        button1 = Button(window1,bg='lightblue',text='Browse',command= browse).place(x=765,y=380,height=40,width=100)
        button2 = Button(window1,bg='lightblue',text='Next',command= w.window2).place(x=645,y=440,height=30,width=100)

        window1.mainloop()

    ##Confirm dataset
    def window2(self):
        window2 = Tk()
        window2.title('ML Algorithms')
        window2.configure(bg='lightblue')
        window2.state('zoomed')

        label1 = Label(window2,text='Confirm your Dataset',bg='lightblue',font=('helvetica',18,'bold'))
        label1.pack(pady=120)

        frame = Frame(window2)
        frame.pack(padx=20)

        scroll1 = ttk.Scrollbar(frame,orient='vertical')
        scroll1.pack(side=RIGHT,fill=Y)

        scroll2 = ttk.Scrollbar(frame,orient='horizontal')
        scroll2.pack(side=BOTTOM,fill=X)

        global tview
        tview = ttk.Treeview(frame, yscrollcommand=scroll1.set, xscrollcommand=scroll2.set)
        tview.pack()

        scroll1.config(command=tview.yview)
        scroll2.config(command=tview.xview)

        tview["column"]=list(data.columns)
        tview["show"]="headings"

        for column in tview["column"]:
            tview.heading(column, text=column)
        df_rows = data.to_numpy().tolist()
        for row in df_rows:
            tview.insert("","end",values=row)
        tview.pack()

        button1 = Button(window2,text='Open',command=w.window3)
        button1.place(x=860,y=570,height=30,width=100)
        button2 = Button(window2,text='Back',command=w.window1)
        button2.place(x=980,y=570,height=30,width=100)

        window2.mainloop()
    ##Selecting features
    def window3(self):
        window3=Tk()
        window3.configure(background="lightblue")
        window3.title('ML Algorithms')
        window3.state('zoomed')

        label1 = Label(window3,relief='solid')
        label1.place(x=730,y=100,width=600,height=500)

        label2 = Label(window3, text="Selected Features", font=("Helvetica", 14, 'bold'))
        label2.pack()
        label2.place(x=930,y=120)

        label3 = Label(window3, text="Select\nIndependent Variables", fg='#000000', bg="lightblue" ,font=("helvetica", 14, 'bold'))
        label3.place(x=70,y=100,width=220,height=50)

        label4 = Label(window3, text="Select\nDependent Variables", fg='#000000', bg="lightblue", font=("helvetica", 14, 'bold'))
        label4.place(x=420,y=100,width=220,height=50)

        frame1 = Frame(window3)
        frame1.place(x=30,y=180,width=300,height=400)

        scrollbar1 = Scrollbar(frame1)
        scrollbar1.pack(side=RIGHT,fill=BOTH )

        listbox1 = Listbox(frame1, selectmode=MULTIPLE)
        listbox1.config(yscrollcommand=scrollbar1.set)
        listbox1.place(width=300, height=400)

        scrollbar1.config(command=listbox1.yview)

        j=0
        for i in tview["column"]:
            listbox1.insert(j, i)
            j = j + 1

        frame2 = Frame(window3)
        frame2.place(x=370, y=180, width=300, height=400)

        scrollbar2 = Scrollbar(frame2)
        scrollbar2.pack(side=RIGHT, fill=BOTH)

        listbox2 = Listbox(frame2, selectmode=SINGLE)
        listbox2.config(yscrollcommand=scrollbar2.set)
        listbox2.place(width=300, height=400)

        scrollbar2.config(command=listbox2.yview)

        j = 0
        for i in tview["column"]:
            listbox2.insert(j, i)
            j = j + 1

        def indep_select():
            global indep, indep1
            indep = []
            indep1 = []
            label34 = Label(window3, text="Independent Variables",font=('helvetica',14,'bold'))
            label34.place(x=770, y=170)
            clicked = listbox1.curselection()
            z = 220
            for item in clicked:
                label10 = Label(window3, text=listbox1.get(item),font=('helvetica',9))
                label10.place(x=770, y=z)
                indep.append(item)
                indep1.append(listbox1.get(item))
                z = z + 25

        button1 = Button(window3,text="Choose",command=indep_select,font=("Arial Black", 9, 'bold'))
        button1.place(x=125,y=600,width=100, height=40)

        def dep_select():
            global dep,dep1
            dep = []
            dep1 = []
            label34 = Label(window3, text="Dependent Variables ",font=('helvetica',14,'bold'))
            label34.place(x=1080, y=170)
            clicked = listbox2.curselection()
            z = 220
            for item in clicked:
                label10 = Label(window3, text=listbox2.get(item),font=('helvetica',9))
                label10.place(x=1080, y=z)
                dep.append(item)
                dep1.append(listbox2.get(item))
                z = z + 25

        button2 = Button(window3, text="Choose", command=dep_select,font=("Arial Black", 9, 'bold'))
        button2.place(x=455, y=600, width=100, height=40)

        button3 = Button(window3, text = "Confirm",command=w.window4,font=("Arial Black", 9, 'bold'))
        button3.place(x=840, y=620, height=50, width=180)

        button4 = Button(window3, text = "Back",font=("Arial Black", 9, 'bold'))
        button4.place(x=1050, y=620, height=50, width=180)
        button4.configure(command=w.window2)

        window3.mainloop()

    ##Reg,class,cluster
    def window4(self):
        window4 = Tk()
        window4.configure(bg="lightblue")
        window4.title("ML Algorithms")
        window4.state('zoomed')

        label1 = Label(window4, text="Select the Problem Type",bg='lightblue', font=("helvetica", 16, 'bold'))
        label1.place(x=580,y=200)

        label2 = Label(window4,relief='solid')
        label2.place(x=300,y=300,height=160,width=800)

        button1 = Button(window4, text="Regression", bg="lightblue",command=w.regression)
        button1.place(x=340,y=360,width=130,height=40)

        button2 = Button(window4, text="Classification", bg="lightblue",command=w.classification)
        button2.place(x=640,y=360,width=130,height=40)

        button3 = Button(window4, text="Clustering", bg="lightblue", command=w.clustering)
        button3.place(x=930,y=360,width=130,height=40)

        window4.mainloop()

    ##Regression Algorithms
    def regression(self):
        window5 = Tk()
        window5.configure(bg="lightblue")
        window5.title("ML - Regression Algorithms")
        window5.state('zoomed')

        global algos

        algos="Regression"

        label1 = Label(window5, text="Select the Alogirithm",bg="lightblue", font=("helvetica",18,"bold"))
        label1.place(x=560,y=180)

        label2 = Label(window5,relief='solid')
        label2.place(x=435,y=260,height=200,width=500)

        def comboclick(event):
            x = data.iloc[:, indep].values
            y = data.iloc[:, dep].values
            global x_train,y_train

            global train_accuracy,test_accuracy,regressor,entryp

            if (combo.get() == "Simple Linear Regression"):
                x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.25,random_state=0)
                # regressor=LinearRegression()
                # regressor.fit(x_train,np.ravel(y_train))
                # train_accuracy=regressor.score(x_train,y_train)
                # test_accuracy=regressor.score(x_test,y_test)

            elif (combo.get() == "Multiple Linear Regression"):

                # Splitting the dataset into training and test set.
                x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
                # regressor = LinearRegression()
                # regressor.fit(x_train, y_train)
                # train_accuracy = regressor.score(x_train, y_train)
                # tesst_accuracy = regressor.score(x_test, y_test)

            elif (combo.get() =="Polynomial Regression"):

                # Training the dataset in polynomial regression
                # global poly_reg

                label = Label(window5,text='Enter Polynomial degree',bg='lightblue')
                label.place(x=550,y=350,heigh=30)

                entryp = Entry(window5,text='poly degree',bg='lightblue')
                entryp.place(x=700,y=350,heigh=30)

                # poly_reg = PolynomialFeatures(degree=5)
                # x_poly = poly_reg.fit_transform(x)

                # regressor = LinearRegression()
                # regressor.fit(x_poly,np.ravel(y))
                # train_accuracy = regressor.score(x_poly,y)

            elif(combo.get()=="SVM Regression"):
                global sc_x,sc_y
                x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                sc_x = StandardScaler()
                sc_y = StandardScaler()
                x = sc_x.fit_transform(x)
                y = sc_y.fit_transform(y)

                regressor = SVR(kernel='rbf')
                regressor.fit(x_train,y_train)
                y_pred=regressor.predict(x_test)

                train_accuracy = regressor.score(x_train,y_train)
                test_accuracy = regressor.score(x_test,y_test)

            elif(combo.get()=="Decision Tree Regression"):
                x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                regressor = DecisionTreeRegressor(random_state=0)
                regressor.fit(x_train,y_train)
                y_pred=regressor.predict(x_test)

                train_accuracy = regressor.score(x_train,y_train)
                test_accuracy = regressor.score(x_test,y_test)

            elif(combo.get()=="Random Forest Regression"):
                x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                regressor = RandomForestRegressor(n_estimators=10,random_state=0)
                regressor.fit(x_train,y_train)
                train_accuracy = regressor.score(x_train,y_train)
                test_accuracy = regressor.score(x_test,y_test)
                y_pred=regressor.predict(x_test)

            else:
                pred = regressor.predict([result])
                label64 = Label(window6,text="Click next to view the Prediction")
                label64.place(x=260,y=z+100)

        options = ["Simple Linear Regression", "Multiple Linear Regression", "Polynomial Regression","SVM Regression","Decision Tree Regression","Random Forest Regression"]
        global combo
        combo = ttk.Combobox(window5, value=options)
        combo.config(width=50)
        combo.current(0)
        combo.bind("<<ComboboxSelected>>", comboclick)
        combo.pack()
        combo.place(x=535,y=300,height=40,width=300)

        button6 = Button(window5, text='Train Model', command=w.window6)
        button6.pack()
        button6.config(bg='lightblue')
        button6.place(x=630,y=385,height=50,width=100)

        window5.mainloop()

    ##Classification Algorithms
    def classification(self):
        window8 = Tk()
        window8.configure(bg="lightblue")
        window8.state('zoomed')
        window8.title("ML- Classification Algorithms")

        global algos
        algos="Classification"

        label3 = Label(window8, text="Select the Algorithm", bg="lightblue", font=("helvetica",18,"bold"))
        label3.place(x=560,y=180)

        label2 = Label(window8,relief='solid')
        label2.place(x=435,y=260,height=200,width=500)

        def comboclick1(event):

            x = data.iloc[:, indep].values
            y = data.iloc[:, dep].values
            global x_train,y_train
            x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

            global sc
            sc = StandardScaler()
            x_train = sc.fit_transform(x_train)
            x_test = sc.transform(x_test)

            if(combo2.get()=="Logistic Regression"):
                print('logistic regression')
                # global classifier
                # classifier = LogisticRegression(random_state=0)
                # classifier.fit(x_train,y_train)

                # y_pred = classifier.predict(x_test)

                # cm = confusion_matrix(y_test,y_pred)
                # global acc
                # acc = (sum(np.diag(cm))/len(y_test))

            elif(combo2.get()=="Naive Bayes Classification"):
                classifier = GaussianNB()
                classifier.fit(x_train ,y_train)

                y_pred = classifier.predict(x_test)

                cm = confusion_matrix(y_test,y_pred)
                acc = (sum(np.diag(cm))/len(y_test))

            elif(combo2.get()=="K-Nearest Neighbour Classification"):
                classifier = KNeighborsClassifier(n_neighbors=5,metric="minkowski",p=2)
                classifier.fit(x_train,y_train)

                y_pred = classifier.predict(x_test)

                cm = confusion_matrix(y_test,y_pred)
                acc = sum(np.diag(cm))/len(y_test)

            elif(combo2.get()=="SVM Classification"):
                classifier = SVC(kernel='rbf',random_state=0)
                classifier.fit(X_train,y_train)

                y_pred=classifier.predict(X_test)

                cm = confusion_matrix(y_test,y_pred)
                acc = sum(np.diag(cm))/len(y_test)

            elif(combo2.get()=="Decision Tree Classification"):
                classifier = DecisionTreeClassifier(criterion='entropy',random_state=0)
                classifier.fit(x_train,y_train)

                y_pred = classifier.predict(x_test)

                cm = confusion_matrix(y_test,y_pred)
                acc = sum(np.diag(cm))/len(y_test)

            elif(combo2.get()=="Random Forest Classification"):
                classifier = RandomForestClassifier()
                classifier.fit(x_train,y_train)

                y_pred = classifier.predict(x_test)
                cm = confusion_matrix(y_test,y_pred)
                acc = sum(np.diag(cm))/len(y_test)

        options1 = ["Logistic Regression","Naive Bayes Classification","K-Nearest Neighbour Classification","SVM Classification","Decision Tree Classification","Random Forest Classification"]
        global combo2
        combo2 = ttk.Combobox(window8, value=options1)
        combo2.config(width=50)
        combo2.current(0)
        combo2.bind("<<ComboboxSelected>>", comboclick1)
        combo2.pack()
        combo2.place(x=535,y=300,height=40,width=300)

        button6 = Button(window8, text='Train Model',command=w.window6)
        button6.pack()
        button6.place(x=630,y=385,height=50,width=100)

        window8.mainloop()

    ##Clustering Algorithms
    def clustering(self):
        window9 = Tk()
        window9.configure(bg="lightblue")
        window9.state('zoomed')
        window9.title("ML-Clustering Algorithm")

        global algos
        algos = "clustering"

        label1 = Label(window9, text="Select the Algorithm", bg="lightblue", font=("helvetica", 18,"bold"))
        label1.place(x=560,y=180)

        label2 = Label(window9,relief='solid')
        label2.place(x=435,y=260,height=200,width=500)

        def comboclick2(event):
            X = data.iloc[:, indep].values
            global clusterkmeans,clustersch
            if(combo3.get()=="KMeans Clustering"):

                wcss=[]

                for i in range(1,11):
                    kmeans = KMeans(n_clusters=i,random_state=0)
                    kmeans.fit(X)
                    wcss.append(kmeans.inertia_)
                def plot():

                    plt.figure(figsize = (8,5), dpi=50)
                    plt.scatter(range(1,11),wcss)
                    plt.plot(range(1,11),wcss)
                    plt.title("Elbow Method")
                    plt.xlabel("Number of Clusters")
                    plt.ylabel("WCSS")
                    plt.show()

                button91 = Button(window9, text="KMeans - plot",bg='lightblue', command=plot)
                button91.place(x=500,y=350,width=120)

                label = Label(window9,text='Cluster size',bg='lightblue')
                label.place(x=630,y=350,height=30,width=100)

                clusterkmeans = Entry(window9,bg='lightblue')
                clusterkmeans.place(x=750,y=350,height=30)

            elif(combo3.get()=="Hierarchical Clustering"):

                def plot1():
                    plt.figure(figsize=(8,5),dpi=50)
                    dendrogram = sch.dendrogram(sch.linkage(X,method='ward'))
                    plt.title("Dendrogram")
                    plt.xlabel("X-Values")
                    plt.ylabel("Euclidean Distance")
                    plt.show()

                button = Button(window9, text="Dendrogram - plot",bg='lightblue', command=plot1)
                button.place(x=500,y=350,width=120)

                labell = Label(window9,text='Cluster size',bg='lightblue')
                labell.place(x=630,y=350,height=30,width=100)

                clustersch = Entry(window9,bg='lightblue')
                clustersch.place(x=750,y=350,height=30)

        options2 = ["Select Clustering Algorithm","KMeans Clustering","Hierarchical Clustering"]
        global combo3
        combo3 = ttk.Combobox(window9, value=options2)
        combo3.config(width=50)
        combo3.current(0)
        combo3.bind("<<ComboboxSelected>>", comboclick2)
        combo3.pack()
        combo3.place(x=535,y=300,height=40,width=300)

        button6 = Button(window9, text='Train Model', command=w.window7)
        button6.pack()
        button6.config(bg='lightblue')
        button6.place(x=630,y=385,height=50,width=100)

        window9.mainloop()
    #PREDICTION
    def window6(self):
        window6 = Tk()
        window6.configure(bg="lightblue")
        window6.state('zoomed')
        window6.title("ML-Algorithms")

        label61 = Label(window6, text="Index Name",  bg="lightblue", font=("helvetica", 20, 'bold'))
        label61.place(x=150, y=100, height=30)

        z=140
        global entry61, entries
        entries = []
        for i in indep1:
            label63 = Label(window6, text=i,bg="lightblue", font=("helvetica", 15, 'bold'))
            label63.place(x=145, y=z)

            entry61 = Entry(window6)
            entry61.place(x=420, y=z, height=30, width=150)
            entries.append(entry61)
            z = z + 25

        label62 = Label(window6, text="Index Values", bg="lightblue", font=("helvetica", 20, 'bold'))
        label62.place(x=415, y=90)

        def predict():
            global result
            result=[]
            for entry in entries:
                result.append(entry.get())

            if(algos=="Regression"):
                global pred

                if(combo.get()=="Simple Linear Regression"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.25,random_state=0)
                    regressor=LinearRegression()
                    regressor.fit(x_train,np.ravel(y_train))
                    train_accuracy=regressor.score(x_train,y_train)
                    test_accuracy=regressor.score(x_test,y_test)

                    pred = regressor.predict([result])
                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=250)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    return train_accuracy,test_accuracy,pred
                elif(combo.get()=="Multiple Linear Regression"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.25,random_state=0)
                    regressor=LinearRegression()
                    regressor.fit(x_train,np.ravel(y_train))
                    train_accuracy=regressor.score(x_train,y_train)
                    test_accuracy=regressor.score(x_test,y_test)

                    pred = regressor.predict([result])
                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=250)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    return train_accuracy,test_accuracy,pred

                elif(combo.get()=="Polynomial Regression"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    global poly_reg,x_poly

                    poly_reg = PolynomialFeatures(degree=int(entryp.get()))
                    x_poly = poly_reg.fit_transform(x)

                    regressor = LinearRegression()
                    regressor.fit(x_poly,y)
                    train_accuracy = regressor.score(x_poly,y)

                    pred = regressor.predict(poly_reg.fit_transform([result]))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)

                elif(combo.get()=="SVM Regression"):

                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    global sc_x,sc_y
                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    sc_x = StandardScaler()
                    sc_y = StandardScaler()
                    x_train = sc_x.fit_transform(x_train)
                    x_test = sc_x.fit_transform(x_test)
                    y_train = sc_y.fit_transform(y_train)
                    y_test = sc_y.fit_transform(y_test)

                    regressor = SVR(kernel='rbf')
                    regressor.fit(x_train,y_train)
                    y_pred=regressor.predict(x_test)

                    train_accuracy = regressor.score(x_train,y_train)
                    test_accuracy = regressor.score(x_test,y_test)

                    pred = sc_y.inverse_transform(regressor.predict(sc_x.transform(([result]))))
                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=250)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    return train_accuracy,test_accuracy,pred

                elif(combo.get()=='Decision Tree Regression'):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    regressor = DecisionTreeRegressor(criterion='mse',random_state=0)
                    regressor.fit(x_train,y_train)
                    y_pred=regressor.predict(x_test)

                    train_accuracy=regressor.score(x_train,y_train)
                    test_accuracy=regressor.score(x_test,y_test)

                    pred = regressor.predict([result])
                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=250)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    return train_accuracy,test_accuracy,pred

                elif(combo.get()=="Random Forest Regression"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    regressor = RandomForestRegressor(n_estimators=8,random_state=0 )
                    regressor.fit(x_train,y_train)
                    y_pred=regressor.predict(x_test)

                    train_accuracy=regressor.score(x_train,y_train)
                    test_accuracy=regressor.score(x_test,y_test)

                    pred = regressor.predict([result])
                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=250)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=250)

                    return train_accuracy,test_accuracy,pred

                else:#Decision tree regression and random forest regression
                    # regressor = LinearRegression()
                    # regressor.fit(x_train, y_train)
                    # pred = regressor.predict([result])
                    print('Sorry Something Error Check Your input')

####classification
            elif(algos=="Classification"):
                if (combo2.get() == "Logistic Regression"):

                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    global sc
                    sc = StandardScaler()
                    x_train = sc.fit_transform(x_train)
                    x_test = sc.transform(x_test)

                    global classifier
                    classifier = LogisticRegression(random_state=0)
                    classifier.fit(x_train,y_train)

                    y_pred = classifier.predict(x_test)

                    cm = confusion_matrix(y_test,y_pred)
                    global acc
                    acc = (sum(np.diag(cm))/len(y_test))
                    pred = classifier.predict(sc.transform([result]))

                    train_accuracy=accuracy_score(np.ravel(y_train),classifier.predict(x_train))
                    test_accuracy=accuracy_score(np.ravel(y_test),classifier.predict(x_test))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)
                    Label(window6,text=f'Confusion Matrix\nAcc : {acc}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=250)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=310)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    return train_accuracy,test_accuracy,pred

                elif(combo2.get()=="Naive Bayes Classification"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    # global sc
                    sc = StandardScaler()
                    x_train = sc.fit_transform(x_train)
                    x_test = sc.transform(x_test)

                    #global classifier
                    classifier = GaussianNB()
                    classifier.fit(x_train,y_train)

                    y_pred = classifier.predict(x_test)

                    cm = confusion_matrix(y_test,y_pred)
                    #global acc
                    acc = (sum(np.diag(cm))/len(y_test))
                    pred = classifier.predict(sc.transform([result]))

                    train_accuracy=accuracy_score(np.ravel(y_train),classifier.predict(x_train))
                    test_accuracy=accuracy_score(np.ravel(y_test),classifier.predict(x_test))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)
                    Label(window6,text=f'Confusion Matrix\nAcc : {acc}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=250)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=310)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    return train_accuracy,test_accuracy,pred

                elif(combo2.get()=="K-Nearest Neighbour Classification"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    #global sc
                    sc = StandardScaler()
                    x_train = sc.fit_transform(x_train)
                    x_test = sc.transform(x_test)

                    #global classifier
                    classifier = KNeighborsClassifier(n_neighbors=10,metric='minkowski',p=2)
                    classifier.fit(x_train,y_train)

                    y_pred = classifier.predict(x_test)

                    cm = confusion_matrix(y_test,y_pred)
                    #global acc
                    acc = (sum(np.diag(cm))/len(y_test))
                    pred = classifier.predict(sc.transform([result]))

                    train_accuracy=accuracy_score(np.ravel(y_train),classifier.predict(x_train))
                    test_accuracy=accuracy_score(np.ravel(y_test),classifier.predict(x_test))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)
                    Label(window6,text=f'Confusion Matrix\nAcc : {acc}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=250)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=310)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    return train_accuracy,test_accuracy,pred

                elif(combo2.get()=="SVM Classification"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    #global sc
                    sc = StandardScaler()
                    x_train = sc.fit_transform(x_train)
                    x_test = sc.transform(x_test)

                    #global classifier
                    classifier = SVC(C=100,kernel='rbf',random_state=0,gamma=0.5)
                    classifier.fit(x_train,y_train)

                    y_pred = classifier.predict(x_test)

                    cm = confusion_matrix(y_test,y_pred)
                    #global acc
                    acc = (sum(np.diag(cm))/len(y_test))
                    pred = classifier.predict(sc.transform([result]))

                    train_accuracy=accuracy_score(np.ravel(y_train),classifier.predict(x_train))
                    test_accuracy=accuracy_score(np.ravel(y_test),classifier.predict(x_test))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)
                    Label(window6,text=f'Confusion Matrix\nAcc : {acc}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=250)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=310)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    return train_accuracy,test_accuracy,pred
                elif(combo2.get()=="Decision Tree Classification"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    #global sc
                    sc = StandardScaler()
                    x_train = sc.fit_transform(x_train)
                    x_test = sc.transform(x_test)

                    #global classifier
                    classifier = DecisionTreeClassifier(criterion='entropy',random_state=0)
                    classifier.fit(x_train,y_train)

                    y_pred = classifier.predict(x_test)

                    cm = confusion_matrix(y_test,y_pred)
                    #global acc
                    acc = (sum(np.diag(cm))/len(y_test))
                    pred = classifier.predict(sc.transform([result]))

                    train_accuracy=accuracy_score(np.ravel(y_train),classifier.predict(x_train))
                    test_accuracy=accuracy_score(np.ravel(y_test),classifier.predict(x_test))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)
                    Label(window6,text=f'Confusion Matrix\nAcc : {acc}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=250)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=310)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    return train_accuracy,test_accuracy,pred
                elif(combo2.get()=="Random Forest Classification"):
                    x = data.iloc[:, indep].values
                    y = data.iloc[:, dep].values

                    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

                    #global sc
                    sc = StandardScaler()
                    x_train = sc.fit_transform(x_train)
                    x_test = sc.transform(x_test)

                    #global classifier
                    classifier = RandomForestClassifier(n_estimators=100,criterion='entropy',random_state=0)
                    classifier.fit(x_train,y_train)

                    y_pred = classifier.predict(x_test)

                    cm = confusion_matrix(y_test,y_pred)
                    #global acc
                    acc = (sum(np.diag(cm))/len(y_test))
                    pred = classifier.predict(sc.transform([result]))

                    train_accuracy=accuracy_score(np.ravel(y_train),classifier.predict(x_train))
                    test_accuracy=accuracy_score(np.ravel(y_test),classifier.predict(x_test))

                    Label(window6,text=str(pred),font=('Helvetica',10,'bold'),bg='light blue', relief='solid').place(x=880,y=580)
                    Label(window6,text=f'Train accuracy : {train_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=150)
                    Label(window6,text=f'Test accuracy : {test_accuracy}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=200)
                    Label(window6,text=f'Confusion Matrix\nAcc : {acc}',font=('Helvetica',10,'bold'),bg='light blue',relief='solid').place(x=880,y=250)

                    if abs(train_accuracy - test_accuracy)>0.1 or (train_accuracy<0.6 and test_accuracy<0.6):
                        Label(window6,text='BAD MODEL',font=('Helvetica',10,'bold'),bg='red',relief='solid').place(x=880,y=310)

                    elif (train_accuracy<test_accuracy) and abs(train_accuracy-test_accuracy)>0.1:
                        Label(window6,text='GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    elif train_accuracy>0.85 and test_accuracy >0.85:
                        Label(window6,text='VERY GOOD MODEL',font=('Helvetica',10,'bold'),bg='green',relief='solid').place(x=880,y=310)

                    return train_accuracy,test_accuracy,pred

            else:
                    print('Sorry something wrong input check it')

        button61 = Button(window6, text="Predict", command=predict)
        button61.place(x=300,y=z+50,height=40,width=100)

        label8=tkinter.Label(window6,relief='solid')
        label8.pack()
        label8.place(x=860,y=50,height=100,width=400)
        label8.configure(text='------Summary-----',font=('helvetica',20,'bold'))

        label10=tkinter.Label(window6,relief='solid')
        label10.pack()
        label10.place(x=860,y=130,height=500,width=400)

        label11=tkinter.Label(window6,relief='solid')
        label11.pack()
        label11.place(x=860,y=500,width=400,height=50)
        label11.configure(text='New observation result',font=('helvetica',12,'bold'))

        window6.mainloop()

    def window7(self):
        window7 = Tk()
        window7.configure(bg="lightblue")
        window7.state('zoomed')
        window7.title("ML-Algorithms")

        label = Label(window7,text='Clustering Algorithms',bg='lightblue',font=('helvetica',16,'bold'))
        label.place(x=670,y=330)

        label2 = Label(window7,relief='solid').place(x=500,y=300,height=200,width=400)

        label3 = Label(window7,text='Click here to get Cluster plot and result',font=('helvetica',14,'bold'))
        label3.place(x=520,y=350,height=40)

        label1 = Label(window7, text="Index Name",  bg="lightblue", font=("helvetica", 20, 'bold'))
        label1.place(x=70, y=100, height=30)

        z=140
        global entry1, entries1
        entries1 = []
        for i in indep1:
            label2 = Label(window7, text=i,bg="lightblue", font=("helvetica", 15, 'bold'))
            label2.place(x=75, y=z)

            entry1 = Entry(window7)
            entry1.place(x=290, y=z, height=30, width=150)
            entries1.append(entry1)
            z = z + 25

        label3 = Label(window7, text="Index Values", bg="lightblue", font=("helvetica", 20, 'bold'))
        label3.place(x=295, y=90)

        def cluster():
            if(algos=="clustering"):
                global resultc
                resultc=[]
                for entry in entries1:
                    resultc.append(entry.get())

                if(combo3.get()=="KMeans Clustering"):

                    x_normal = data.iloc[:, indep].values

                    from sklearn.decomposition import KernelPCA
                    kpca=KernelPCA(n_components=2)

                    x=kpca.fit_transform(x_normal)

                    kmeans=KMeans(n_clusters=int(clusterkmeans.get()) ,random_state=0)
                    y_kmeans=kmeans.fit_predict(x)
                    y_predict=kmeans.predict(kpca.transform([resultc]))

                    label4 = Label(window7,text=f'New obs result:{y_predict}',bg='lightgreen',relief='solid')
                    label4.place(x=245,y=z+35,height=30)

                    def plotkmeans():

                        for i in range(0,int(clusterkmeans.get())):
                            if i<=0:

                                plt.figure(dpi=300)
                                plt.scatter(x[:,0],x[:,1],c=kmeans.labels_, cmap='rainbow')
                                plt.scatter(x[y_kmeans==i,0],x[y_kmeans==i,1],s=10)

                                plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=200,
                                            c='yellow')
                                plt.title('clusters')
                                plt.xlabel('x')
                                plt.ylabel('y')
                                plt.legend()
                                plt.show()
                    button=Button(window7,text='Cluster',command=plotkmeans())

                elif(combo3.get()=="Hierarchical Clustering"):

                    x_normal = data.iloc[:, indep].values
                    from sklearn.decomposition import KernelPCA
                    kpca=KernelPCA(n_components=2)

                    x=kpca.fit_transform(x_normal)

                    import scipy.cluster.hierarchy as sch
                    dentogram=sch.dendrogram(sch.linkage(x,method='centroid'))

                    from sklearn.cluster import AgglomerativeClustering
                    hc=AgglomerativeClustering(n_clusters=int(clustersch.get()))
                    y=hc.fit_predict(x)

                    np.unique(y)
                    def plotsch():
                        import random

                        for i in range(0,int(clustersch.get())):
                            if i<=0:

                                plt.figure(dpi=300)
                                plt.scatter(x[:,0],x[:,1],s=15,c=hc.labels_, cmap='rainbow')
                                plt.scatter(x[y==i,0],x[y==i,1],s=10)

                                plt.xlabel('x')
                                plt.ylabel('y')
                                plt.title('clusters')
                                plt.legend()
                                plt.show()

                    button=Button(window7,text='Cluster',command=plotsch())

            else:
                print('something wrong input check it')

        button=Button(window7,text='Predict',bg='lightblue',command=cluster)
        button.place(x=620,y=400,width=150,height=60)

        window7.mainloop()

w=window()
w.window1()


import re,sys

class Speller:
    _digitRegex = re.compile(r"^\d")
    _htmlRegex = re.compile(r"</[c-g\d]+>|</[i-o\d]+>|</[a\d]+>|</[q-z\d]+>|<[cg]+[^>]*>|<[i-o]+[^>]*>|<[q-z]+[^>]*>|<[a]+[^>]*>|<(\[^\]*\|'[^']*'|[^'\>])*>", re.IGNORECASE|re.MULTILINE)
    _htmlTags = None
    _letterRegex = re.compile(r"\D")
    _upperRegex = re.compile(r"[^A-Z]")
    _wordEx = re.compile(r"\b\w+\b", re.MULTILINE|re.UNICODE|re.LOCALE)

    def __init__(self, settings):
        from PyQLogger.ASpell import aspell
        self.speller = aspell(prefix=settings.Speller.Prefix,
                                            lang=settings.Speller.Language)

    def CalculateWords(self):
        """Calculates the words from the Text property"""
        #splits the text into words
        self._words = []
        for m in self._wordEx.finditer(self.text):
            self._words.append(m)
        self.MarkHtml()

    def CheckString(self,word,characters):
        """Determines if the string should be spell checked
        @param characters The Characters to check
        Returns true if the string should be spell checked
        """
        if not self._upperRegex.match(characters):  return False
        if self._digitRegex.match(characters):  return False
        if not self._letterRegex.match(characters): return False
        startIndex = word.start()
        for item in self._htmlTags:
            if (startIndex >= item.start() and startIndex <= item.end() - 1):
                return False
        return True;

    def MarkHtml(self):
        """Calculates the position of html tags in the Text property"""
        # splits the text into words
        self._htmlTags = []
        for m in self._htmlRegex.finditer(self.text):
            self._htmlTags.append(m)

    def ReplaceWord(self, replacedIndex, _replacementWord):
        """ Replaces the instances of the CurrentWord in the Text Property """
        if not self._words or not len (self._words):
            return
        replacedWord = self._words[replacedIndex].group(0)
        index = self._words[replacedIndex].start()
        length = self._words[replacedIndex].end()
        # if first letter upper case, match case for replacement word
        if replacedWord.istitle():
            _replacementWord = _replacementWord.title()
        tmps = self.text[index: length].replace(replacedWord,_replacementWord)
        self.text = self.text[:index] + tmps + self.text[length:]
        self.CalculateWords()

    def load(self,text):
        self.text = unicode(text)
        self.CalculateWords()
        return self.keepChecking()

    def keepChecking(self):
        ret = {}
        idx = 0
        for w in self._words:
            word = w.group(0)
            if self.CheckString(w,word):
                sug = self.speller.suggest(word)
                if sug != None:  # should we even check it?
                    ret[w] =  { "sug": sug, "idx":idx }
            idx += 1
        return ret


def quicksort(l):
    if(len(l) <= 1):
        return l
    less = []
    more = []
    n = len(l)
    pivot = 0
    for i in range(1, n):
        if(l[i] < l[pivot]):
            less.append(l[i])
        else:
            more.append(l[i])

    less = quicksort(less)
    more = quicksort(more)
    less.append(l[pivot])
    less.extend(more)
    return less

def mergesort(l):
    if(len(l) == 0 or len(l) == 1):
        return l

    left = mergesort(l[:int(len(l)/2)])
    right = mergesort(l[int(len(l)/2):])

    n = len(left)
    m = len(right)
    i = 0
    j = 0
    ans = []
    while(i < n and j < m):
        if(left[i] == right[j]):
            ans.append(left[i])
            ans.append(right[j])
            i = i+1
            j = j+1
        elif(left[i] < right[j]):
            ans.append(left[i])
            i = i+1
        else:
            ans.append(right[j])
            j = j+1

    while(i < n):
        ans.append(left[i])
        i = i+1
    while(j < m):
        ans.append(right[j])
        j = j+1

    return ans

def bubblesort(l):
    n = len(l)
    for i in range(n-1):
        for j in range(n-1-i):
            if(l[j] > l[j+1]):
                l[j], l[j+1] = l[j+1], l[j]
    return l

def comparativegraph():
    import random
    import time
    from matplotlib import pyplot as plt

    #bubtime = []
    mergetime = []
    quicktime = []
    for i in range(1, 5000):
        l = random.sample(range(100000), i)

        #start = time.time()
        #bubblesort(l.copy())
        #end = time.time()
        #bubtime.append(end-start)

        start = time.time()
        mergesort(l.copy())
        end = time.time()
        mergetime.append(end-start)

        start = time.time()
        quicksort(l.copy())
        end = time.time()
        quicktime.append(end-start)

    x = [i for i in range(1, 5000)]
    #plt.plot(x, bubtime)
    plt.plot(x, mergetime)
    plt.plot(x, quicktime)
    plt.legend(['merge', 'quick'])


"""
    The ashanti experiential
    Author: Cedric Murairi
    Users are asked their gender and date of birth, based on what they are provided with a name that would fit them
"""

#these variables map each value of the day to its name value for the two genders
female_names = {0:"Adwoa", 1:"Abeena", 2:"Akwa", 3:"Yaa", 4:"Afia", 5:"Amma", 6:"Akosua"}
male_names = {0:"Kadjo", 1:"Kwabena", 2:"Kwaku", 3:"Yaw", 4:"Kofi", 5:"Kwame", 6:"Kwasi"}

def main():
    gender = input('What is your gender? Male or Female:   ')
    birth_date = input('What is you date of birth? >>>> use 11/12/1930 format:   ')

    #check if the gender value is either male of female, otherwise, it calls main again
    if gender.lower() not in ['male', 'female']:
        print('The gender you entered is invalid')
        return main()

    #calls the function get_day and pass its value and the gender to get_name to get the name and print it
    print(get_name(get_day(birth_date), gender))

#receives a gender and a day to check for that day's name value depending on gender
def get_name(day, gender):
    if gender.lower() == 'female':
        return female_names[day]
    if gender.lower() == 'male':
        return male_names[day]

#get the equivalent day of the week from a provided birth date
#return 0 for monday ... 6 for sunday
def get_day(birth_date):
    birth_date = birth_date.split('/')
    year = int(birth_date[2])
    month = int(birth_date[1])
    day = int(birth_date[0])
    return datetime.datetime(year, month, day).weekday()

if __name__=="__main__":
    main()


import os

import ROOT
ROOT.gROOT.SetBatch(True)
import root_numpy

from tdrStyle import *
setTDRStyle()

ROOT.gSystem.AddIncludePath("-I$CMSSW_BASE/src/ ")
ROOT.gSystem.Load("$CMSSW_BASE/lib/slc7_amd64_gcc700/libHiggsAnalysisCombinedLimit.so")
ROOT.gSystem.AddIncludePath("-I$ROOFITSYS/include")
ROOT.gSystem.AddIncludePath("-Iinclude/")
ROOT.RooMsgService.instance().getStream(1).removeTopic(ROOT.RooFit.DataHandling)
ROOT.RooMsgService.instance().getStream(1).removeTopic(ROOT.RooFit.ObjectHandling)

from helpers import model_helper

class CombineHelper():
    """
    Class to create models from m_gg distributions of signal/resonant_bkg/bkg MC/data events
    for a specified number of bins.
    Next runs combine and extracts a specified metric (significance, upper limit, etc.)
    """

    def __init__(self, **kwargs):
        self.options = kwargs.get("options")
        self.signal_events = kwargs.get("signal_events")
        self.resonant_background_events = kwargs.get("resonant_background_events")
        self.background_events = kwargs.get("background_events")
        self.data_events = kwargs.get("data_events")
        self.output_dir = kwargs.get("output_dir")
        self.output_tag = kwargs.get("output_tag")

    def run(self):
        self.setup()
        self.make_models()
        self.run_combine()
        self.summarize()

    def setup(self):
        self.info = {
            "signal" : {
                "fit" : self.options["resonant"]["fit"],
                "resonant" : True,
                "models" : [],
                "events" : self.signal_events
            },
            "resonant_bkg" : {
                "fit" : self.options["resonant"]["fit"],
                "resonant" : True,
                "models" : [],
                "events" : self.resonant_background_events
            },
            "bkg_MC" : {
                "fit" : self.options["non_resonant"]["fit"],
                "resonant" : False,
                "models" : [],
                "events" : self.background_events
            },
            "data" : {
                "fit" : self.options["non_resonant"]["fit"],
                "resonant" : False,
                "models" : [],
                "events" : self.data_events
            }
        }
        return

    def make_models(self):
        for event_type, info in self.info.items():
            for i in range(self.options["n_bins"]):
                helper = model_helper.ModelHelper(
                    events = info["events"][i],
                    model = info["fit"],
                    tag = event_type + "Bin%d" % i,
                    output_dir = self.output_dir,
                    resonant = info["resonant"]
                )
                helper.run()
                info["models"].append(helper.model_file)

    def run_combine(self):
        return

    def summarize(self):
        return

    def get_results(self):
        return { "upper_limit" : 0 }


#!/usr/bin/python3.7
# -*- coding: UTF-8 -*-
# author：Lucien
# 基础包: Log日志封装

import logging
from logging import handlers

class Logs(object):
    level_mapping = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }  # 日志映射

    def __init__(self, filename, level='info', when='D', backCount=3,
                 fmt='%(asctime)s - [line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置格式
        self.logger.setLevel(self.level_mapping.get(level))  # 设置级别
        self.logger.propagate = False  # 关闭logger向上级传输
        stream = logging.StreamHandler()  # 流形式向屏幕输出
        stream.setFormatter(format_str)  # 流的显示的格式
        file = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount,
                                                 encoding='utf-8')  # 往文件里写入
        # Calculate the real rollover interval, which is just the number of
        # seconds between rollovers.  Also set the filename suffix used when
        # a rollover occurs.  Current 'when' events supported:
        # S 秒
        # M 分
        # H 小时
        # D 天
        # W 每星期（interval==0时代表星期一）
        # midnight 凌晨
        file.setFormatter(format_str)  # 设置文件里写入的格式
        self.logger.addHandler(stream)  # 把对象加到logger里
        self.logger.addHandler(file)  # 把对象加到logger里

    def Logger(self):
        return self.logger

if __name__ == '__main__':
    log = Logs('logs').Logger()
    log.info('hello')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module is a gui for asking the user to select the Large Scale parameter (LSP) to graph.

@author: pablobelzarena
"""

import tkinter as tk

class AppLSP():
    """ This class is the form for select the LSP """

    def __init__(self,window,function_cbk,title,ok_title,lsp_param=0):
        """The constructor of the AppLSP Class

        @type window: tkinter.Tk() window.
        @param window: The main window of this form.
        @type function_cbk: python function.
        @param function_cbk: The callback function to return when the user press OK button.
        @type title: string
        @param title: The title of the form.
        @type ok_title: string
        @param ok_title: The text to show in the OK button.
        @type lsp_param: string
        @param lsp_param: The lsp parameter selected. Default 0.

        """
        self.ok_title = ok_title
        """ The text to show in the OK button."""
        self.window  = window
        """ The main window of this form."""
        self.window.title(title)
        self.lsp_param = int(lsp_param)
        """ The lsp parameter selected. Default 0. """
        # self.los = int(los)
        # """ Takes the value "0" for NLOS, and "1" for LOS. """
        self.function_cbk = function_cbk
        """ The callback function to return when the user press OK button. """
        self.gui_configuration()

    def gui_configuration(self):
        """This method builds the form to enter the data

        """
        self.window.rowconfigure(6, minsize=50, weight=1)
        self.window.columnconfigure([0, 1, 2, 3, 4], minsize=50, weight=1)

        self.v = tk.IntVar(self.window)
        """This variable store the LSP parameter selected """
        self.v.set(self.lsp_param)
        frm_lsp = tk.Frame(master=self.window)
        rb_Shadow = tk.Radiobutton(master=frm_lsp, text='Shadowing',variable = self.v,value =0)
        rb_K = tk.Radiobutton(master=frm_lsp, text='Ricean K',variable = self.v,value =1 )
        rb_DS = tk.Radiobutton(master=frm_lsp, text='Delay Spread',variable = self.v,value = 2)
        rb_AOD = tk.Radiobutton(master=frm_lsp, text='Azimuth departure angle spread',variable = self.v,value =3)
        rb_AOA = tk.Radiobutton(master=frm_lsp, text='Azimuth arrival angle spread',variable = self.v,value = 4)
        rb_ZOD = tk.Radiobutton(master=frm_lsp, text='Inclination departure angle spread',variable = self.v,value =5)
        rb_ZOA = tk.Radiobutton(master=frm_lsp, text='Inclination arrival angle spread',variable = self.v,value = 6)
        rb_LOS = tk.Radiobutton(master=frm_lsp, text='LOS condition',variable = self.v,value = 7)

        rb_DS.grid(row=2, column=0, sticky="e")
        rb_K.grid(row=1, column=0, sticky="e")
        rb_Shadow.grid(row=0, column=0, sticky="e")
        rb_AOA.grid(row=3, column=0, sticky="e")
        rb_AOD.grid(row=4, column=0, sticky="e")
        rb_ZOA.grid(row=5, column=0, sticky="e")
        rb_ZOD.grid(row=6, column=0, sticky="e")
        rb_LOS.grid(row=7, column=0, sticky="e")

        # self.v1 = tk.IntVar(self.window)
        # """ This variable store the LOS or NLOS condition selected. """
        # self.v1.set(self.los)
        # frm_los = tk.Frame(master=self.window)
        # rb_los = tk.Radiobutton(master=frm_los, text='LOS LSP params',variable = self.v1,value =1)
        # rb_nlos = tk.Radiobutton(master=frm_los, text='NLOS LSP params',variable = self.v1,value =0)
        # rb_los.grid(row=0, column=0, sticky="w")
        # rb_nlos.grid(row=1, column=0, sticky="w")

        # frm_los.grid(row=0, column=1, padx=10)
        frm_lsp.grid(row=0, column=0, padx=10)

        aux1 = tk.Button(self.window, text=self.ok_title, command=self.OK_button)
        aux1.grid(row=1, column=0, padx=10)

    def OK_button(self):
        """This method is called when user press the OK button

        This method calls the callback function.
        """
        self.function_cbk(int(self.v.get()))


num = int(input('Digite um número: '))
print('''Escolha uma das bases para conversão
[1] converter para BINÁRIO
[2] converter para OCTAL
[3] converter para HEXADECIMAL''')

opção = int(input('Digite sua opção: '))

#conveção para binário
if opção == 1:
    print('{} convertido para BINÁRIO é igual a {}'.format(num, bin(num)[2:]))

#conveção para octal
elif opção == 2:
    print('{} convertido para OCTAL é igual a {}'.format(num, oct(num)[2:]))

#conveção para Hexadecimal
elif opção == 3:
    print('{} convertido para HEXADECIMAL é igual a {}'.format(num, hex(num)[2:]))

else:
    print('Opção inválida')


import bpy
from bpy import *
from bpy.props import *

from ..utilities.utils import get_prefs
from ..utilities.utils import func_find_collection, func_make_collection
from ..utilities.utils import func_collection
from ..utilities.utils import lock_object, unlock_object

class RTS_OT_RePattern_Camera(bpy.types.Operator):
    """create camera for rendering"""
    bl_idname = "rts_ot.repattern_camera"
    bl_label = "Camera"
    bl_options = {'REGISTER', 'UNDO'}

    def draw(self, context):
        layout = self.layout

        prefs = get_prefs()
        cam_prefs = prefs.camera_type

        col = layout.column(align=True)

        box = col.box().column(align=True)
        box.separator()

        row = box.column(align=True)
        row.prop(cam_prefs, 'cam_reso')

        row.separator()

        row.prop(cam_prefs, 'cam_lens')

        box.separator()
        box.separator()

        row = box.row(align=True)
        row.label(text="Make Collection")

        box.separator()

        row = box.row(align=True)
        row.label(text="New Name...")
        row.prop(cam_prefs, "rb_collection_name_camera", text="")

        box.separator()

        row = box.row(align=True)
        row.label(text="Parent to...")
        row.prop(cam_prefs, "rb_collection_name_exist_camera", text="")

        box.separator()

    def execute(self, context):

        prefs = get_prefs()
        cam_prefs = prefs.camera_type
        coll_prefs = prefs.coll_type

        bpy.ops.view3d.snap_cursor_to_center()

        rota_x = 0
        rota_y = 0
        rota_z = 0

        loca_x = 0
        loca_y = 0

        if cam_prefs.cam_reso == '32px':
            loca_z = 31.25

        if cam_prefs.cam_reso == '64px':
            loca_z = 62.5

        if cam_prefs.cam_reso == '128px':
            loca_z = 125

        if cam_prefs.cam_reso == '256px':
            loca_z = 250

        if cam_prefs.cam_reso == '512px':
            loca_z = 500

        if cam_prefs.cam_reso == '1024px':
            loca_z = 1000

        if cam_prefs.cam_reso == '2048px':
            loca_z = 2000

        if cam_prefs.cam_reso == '4096px':
            loca_z = 4000

         # manage collection
        if cam_prefs.rb_collection_name_exist_camera != '':
            collect_exist = cam_prefs.rb_collection_name_exist_camera
            bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection.children[collect_exist]
        else:
            collect_exist = "RePattern"
            if collect_exist in bpy.data.collections:
                bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection.children[collect_exist]
            else:
                # create repattern collation
                func_collection(self, context)

                # set active scene collection
                scene_collection = bpy.context.view_layer.layer_collection
                bpy.context.view_layer.active_layer_collection = scene_collection

        # add camera
        bpy.ops.object.camera_add(align='WORLD', enter_editmode=False, location=(loca_x, loca_y, loca_z), rotation=(rota_x, rota_y, rota_z))
        bpy.context.object.name = 'RP_Camera_Top'
        bpy.context.object.data.name = 'RP_Camera_Top'

        # store camera #
        store_camera = bpy.context.view_layer.objects.active

        new_object_name = bpy.context.object.name
        bpy.data.objects[new_object_name].select_set(True)

        #move to scene collection
        bpy.ops.object.move_to_collection(collection_index=0)

        # move to new collection
        selected = bpy.context.selected_objects
        for obj in selected:
            if cam_prefs.rb_collection_name_exist_camera!= '':
                bpy.data.collections[cam_prefs.rb_collection_name_exist_camera].objects.link(obj)
            else:
                collect_exist = "RePattern"
                bpy.data.collections[collect_exist].objects.link(obj)
            bpy.context.scene.collection.objects.unlink(obj)

       # ADD SUBGRID COLLECTION #
        store_collection_name = bpy.data.objects[new_object_name]
        bounds_collection = func_find_collection(bpy.context, store_collection_name)

        id = 0
        numberDigits = 2

        if cam_prefs.rb_collection_name_camera!= '':
            prefix = cam_prefs.rb_collection_name_camera
        else:
            prefix = "RP_Camera"

        # CUSTOM COLLECTION #
        for key, collections in bpy.data.collections.items():
            if key.startswith(prefix):

                addZero = 0
                for i in range(1,numberDigits):
                    mod = int(id / (pow(numberDigits,i)))
                    if mod == 0:
                        addZero += 1

                newNameId = str(id)
                for i in range(0,addZero):
                    newNameId = '' + newNameId

                new_name = prefix + '_' + newNameId
                id += 1

                new_collection = func_make_collection(self, new_name, bounds_collection)
            else:
                new_collection = func_make_collection(self, prefix, bounds_collection)

        new_collection.objects.link(store_collection_name)
        bounds_collection.objects.unlink(store_collection_name)

        # lens
        if cam_prefs.cam_lens == 'ortho':

            # switch orthogonal scale
            bpy.context.object.data.type = 'ORTHO'

            if cam_prefs.cam_reso == '32px':
                scale_o  = 3.125
                scale_c  = 100

            if cam_prefs.cam_reso == '64px':
                scale_o = 6.25
                scale_c = 100

            if cam_prefs.cam_reso == '128px':
                scale_o = 12.5
                scale_c = 100

            if cam_prefs.cam_reso == '256px':
                scale_o = 25
                scale_c = 100

            if cam_prefs.cam_reso == '512px':
                scale_o = 50
                scale_c = 1000

            if cam_prefs.cam_reso == '1024px':
                scale_o = 100
                scale_c = 1000

            if cam_prefs.cam_reso == '2048px':
                scale_o = 200
                scale_c = 10000

            if cam_prefs.cam_reso == '4096px':
                scale_o = 400
                scale_c = 100000
                bpy.context.object.data.clip_end = 100000

            bpy.context.object.data.ortho_scale = scale_o
            bpy.context.object.data.clip_end = scale_c

        # lens
        if cam_prefs.cam_lens == 'persp':

            # switch perspective scale
            bpy.context.object.data.type = 'PERSP'

            scale_f = 32
            bpy.context.object.data.lens = scale_f

        # jump to camera view
        bpy.ops.view3d.object_as_camera()
        bpy.ops.view3d.view_camera()

        # set render resolution
        bpy.context.scene.render.resolution_x = 1024
        bpy.context.scene.render.resolution_y = 1024
        bpy.context.scene.render.resolution_percentage = 100

        # reload camera
        bpy.context.view_layer.objects.active = bpy.data.objects[store_camera.name]
        bpy.data.objects[store_camera.name].select_set(True)

        bpy.ops.view3d.view_camera()

        # restrict transorm
        lock_object(self, context)

        #print(self)
        self.report({'INFO'}, "Added Camera!")
        return {'FINISHED'}

class RTS_OT_RePattern_Camera_Jump(bpy.types.Operator):
    """Camera Render Setup"""
    bl_idname = "rts_ot.repattern_camera_jump"
    bl_label = "Jump To Camera"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.ops.object.select_all(action='DESELECT')

        cam_name = bpy.context.scene.collection_rp_select_list_cameras
        #cam_name = 'RP_Camera_Top'

        if cam_name in bpy.data.cameras:
            bpy.context.scene.camera = bpy.data.objects[cam_name]
            bpy.context.view_layer.objects.active = bpy.data.objects[cam_name]
            bpy.data.objects[cam_name].select_set(True)
            bpy.ops.view3d.object_as_camera()

            for area in bpy.context.screen.areas:
                if area.type == 'VIEW_3D':
                    area.spaces[0].region_3d.view_perspective = 'CAMERA'
                    break

            bpy.context.view_layer.objects.active = bpy.data.objects[cam_name]
            bpy.data.objects[cam_name].select_set(True)

            #print(self)
            self.report({'INFO'}, "Jump To Camera!")

        else:
            self.report({'INFO'}, "Nope :(!")
        return {'FINISHED'}

# https://blender.stackexchange.com/questions/30643/how-to-toggle-to-camera-view-via-python
# [‘PERSP’, ‘ORTHO’, ‘CAMERA’]
class RTS_OT_RePattern_Camera_Align(bpy.types.Operator):
    """Camera Render Setup"""
    bl_idname = "rts_ot.repattern_camera_align"
    bl_label = "Align Camera"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):

        if bpy.data.cameras:

            bpy.ops.view3d.camera_to_view()

            view_layer = bpy.context.view_layer
            selected = bpy.context.selected_objects
            if selected:
                obj = view_layer.objects.active
                if obj:
                    # store active #
                    target = view_layer.objects.active

            bpy.ops.object.select_all(action='DESELECT')

            cam_name = bpy.context.scene.collection_rp_select_list_cameras
            if cam_name in bpy.data.cameras:
                bpy.context.scene.camera = bpy.data.objects[cam_name]
                bpy.context.view_layer.objects.active = bpy.data.objects[cam_name]
                bpy.data.objects[cam_name].select_set(True)

                bpy.ops.view3d.object_as_camera()

                for area in bpy.context.screen.areas:
                    if area.type == 'VIEW_3D':
                        area.spaces[0].region_3d.view_perspective = 'ORTHO'
                        break

                if selected:
                    obj = view_layer.objects.active
                    if obj:
                        # reload active #
                        view_layer.objects.active = target
                        target.select_set(True)

                        bpy.ops.view3d.camera_to_view_selected()

                    #print(self)
                    self.report({'INFO'}, "Align Camera!")
        else:
            self.report({'INFO'}, "Nope :(!")
        return {'FINISHED'}

class RTS_OT_RePattern_Camera_Remove(bpy.types.Operator):
    """remve repattern camera"""
    bl_idname = "rts_ot.repattern_camera_remove"
    bl_label = "Camera Remove"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):

        # make active
        bpy.ops.object.select_all(action='DESELECT')

        cam_name = bpy.context.scene.collection_rp_select_list_cameras
        #cam_name = "RP_Camera_Top"

        if cam_name in bpy.data.objects:
            bpy.context.view_layer.objects.active = bpy.data.objects[cam_name]
            bpy.data.objects[cam_name].select_set(True)

            for area in bpy.context.screen.areas:
                if area.type == 'VIEW_3D':
                    for space in area.spaces:
                        if space.type == 'VIEW_3D':
                            bpy.ops.view3d.view_persportho()
                            bpy.ops.view3d.snap_cursor_to_center()
                            #bpy.ops.view3d.view_all(center=True)
                            #bpy.ops.view3d.view_center_cursor()

            temp_remove = bpy.data.cameras
            temp_remove.remove(temp_remove[cam_name], do_unlink=True, do_id_user=True, do_ui_user=True)

            self.report({'INFO'}, "Removed Camera!")

        else:
            self.report({'INFO'}, "Nope :(!")
        return {'FINISHED'}


from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, StoppingCriteria, StoppingCriteriaList
import torch

test_data = load_dataset("json", data_files="/root/data/data/openai_humaneval/HumanEval.jsonl")
# test_data = load_dataset("json", data_files="/root/data/data/humaneval-x/data/python/data/humaneval.jsonl")

print(test_data)

# tok = AutoTokenizer.from_pretrained("/root/data/bloom", padding_side="left")
tok = AutoTokenizer.from_pretrained("/root/data/bloom-560m", padding_side="left")
# tok = AutoTokenizer.from_pretrained("/root/data/starchat", padding_side="left")
# tokenizer.pad_token = tokenizer.eos_token
tok.pad_token = tok.eos_token
print("init tok done")

# model = AutoModelForCausalLM.from_pretrained("/root/data/bloom").cuda()
model = AutoModelForCausalLM.from_pretrained("/root/data/bloom-560m").cuda()
# model = AutoModelForCausalLM.from_pretrained("/root/data/starchat").half().cuda()
model = model.eval()
print("init model done")

system_token = "<|system|>"
user_token = "<|user|>"
assistant_token = "<|assistant|>"
end_token = "<|end|>"
max_length = 2048
stop_token_ids = [tok.eos_token_id, tok(end_token)["input_ids"][0], tok(user_token)["input_ids"][0]]
class StopOnTokens(StoppingCriteria):
    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
        for stop_id in stop_token_ids:
            if input_ids[0][-1] == stop_id:
                return True
        return False
stop = StopOnTokens()
generation_config = GenerationConfig(
        temperature=0.2,
        top_k=50,
        top_p=0.95,
        repetition_penalty=1.2,
        do_sample=True,
        pad_token_id=tok.eos_token_id,
        # eos_token_id=tok.convert_tokens_to_ids(dialogue_template.end_token),
        min_new_tokens=32,
        max_new_tokens=256,
        # stopping_criteria=StoppingCriteriaList([stop])
    )

def gen_code(model, tok, prompt):
    prompts = tok(
        prompt,
        max_length=max_length,
        padding="max_length",
        truncation=True,
        return_tensors="pt",
    )

    input_ids = torch.tensor(prompts['input_ids']).cuda()
    attention_mask =  torch.tensor(prompts['attention_mask']).cuda()

    output = model.generate(input_ids=input_ids, generation_config=generation_config)
    # output = model.generate(
    #     input_ids=input_ids,
    #     attention_mask=attention_mask,
    #     max_length=max_length,
    #     do_sample=True,
    #     top_k=50,
    #     top_p=0.95,
    #     num_beams=5,
    #     eos_token_id=tok.eos_token_id,
    #     num_return_sequences=1,
    #     early_stopping=True,
    #     length_penalty=2.5)

    return tok.decode(output[0], skip_special_tokens=True)

train_data = test_data['train']

with open("./test_problem_top6_sc_prompt.txt", 'w') as wp:
    for idx, data in enumerate(train_data):
        # print(data)
        # for d in data:
            # print("-----")
            # print(d)
            # print(data[d])

        system_msg = "Below are a series of dialogues between various people and an AI assistant.\
The AI tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble-but-knowledgeable.\
The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.\
It also tries to avoid giving false or misleading information, and it caveats when it isn’t entirely sure about the right answer.\
That said, the assistant is practical and really does its best, and doesn’t let caution get too much in the way of being useful.\
-----\n"

        prompt = system_token + "\n" + system_msg + end_token + "\n" + user_token + "\n" + data['prompt'] + end_token + "\n" + assistant_token + "\n"
        # prompt = "continue write the code below\n\n \"\"\"" + data['prompt'] + "\"\"\""
        code = gen_code(model, tok, prompt)
        print("-----------")
        print("prompt:", prompt)
        # print("prompt:", data['prompt'])
        # print("[code]:", code)
        print("[code]:", code.replace(prompt, ""))
        print("ans: \n", data['canonical_solution'])
        print("example_test:", data['test'])
        wp.write("----------------\n")
        wp.write(code + "\n")
        if idx > 6:
            break
        # break

print(len(train_data))


'''
Catherine Turner
8/18/19
https://projecteuler.net/ Problem 39
'''

# If "target" is the perimeter of a right angle triangle with integral length sides, return all solutions
# for the side lengths of that triangle.
def pythagTriplet(target):
    results = []
    for a in range(1, target + 1):
        for b in range(a, target + 1):
            c = target - a - b
            if (a**2 + b**2 == c**2):
                result = [a, b, c]
                results.append(result)
    return results

# Return the perimeter of a right angle triangle with the most solutions for its possible side lengths
def maxPerimeter(max):
    maxP = 0
    maxSolutions = 0
    for perimeter in range(1, max+1):
        result = pythagTriplet(perimeter)
        if len(result) > maxSolutions:
            maxP = perimeter
            maxSolutions = len(result)
    return maxP

# Return the value of p <= 1000 for which the number of solutions is maximized
print(maxPerimeter(1000))


from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from helpers import render_to_json, jsonResponse, serializeUser
from django.forms.models import modelformset_factory
from django.template import RequestContext
from django.contrib.auth.models import User

@login_required
@render_to_json
def get(req, user_id):
    if user_id:
        user = User.objects.get(id=user_id)
        return serializeUser(user)
    else:
        return [serializeUser(user)
                for user in User.objects.all()]

@login_required
def create(req):
    UserFormSet = modelformset_factory(User)
    if req.method == 'POST':
        formset = UserFormSet(req.POST)
        if formset.is_valid():
            user = formset.save()[0]
            user.set_password(user.password)
            user.save()
            # do something.
            return jsonResponse(serializeUser(user))
    else:
        formset = UserFormSet(queryset=User.objects.none())
    return render_to_response("user.html",
            {"formset": formset},
            context_instance=RequestContext(req))

@login_required
@render_to_json
def update(req, user_id):
    pass

@login_required
@render_to_json
def delete(req, user_id):
    user = User.objects.get(id=user_id)
    user.is_active = False
    user.save()

    return {'success': True}


from flask import request, jsonify
from mysqlAccess import mysqlConnection, mysqlCloseConnection, mysqlQuery, mysqlInsert, mysqlUpdate
from configApp import app

@app.route('/participacoes', methods=['GET'])
def participacoes():
    accessPoints = ["all", "att", "describe", "insert", "remove"]
    return jsonify(accessPoints)

@app.route('/participacoes/all', methods=['GET'])
def participacoesAll():
    conn = mysqlConnection()
    query = "SELECT * FROM participacoes;"
    records = mysqlQuery(conn, query)
    mysqlCloseConnection(conn)
    return jsonify(records)

@app.route('/participacoes/att', methods=['GET'])
def participacoesAtt():
    conn = mysqlConnection()
    cursor = conn.cursor()
    cursor.execute(f'SELECT * FROM participacoes;')
    column_names = [i[0] for i in cursor.description]
    data = cursor.fetchall()
    rows = []
    for row in data:
        row_dict = {}
        for i in range(len(column_names)):
            row_dict[column_names[i]] = row[i]
        rows.append(row_dict)
    mysqlCloseConnection(conn)
    return jsonify(rows)

@app.route('/participacoes/describe', methods=['GET'])
def participacoesDescribe():
    conn = mysqlConnection()
    if 'idEvento' not in request.args and 'email' not in request.args:
        return "Error: No idEvento and email fields provided."
    elif 'idEvento' not in request.args:
        return "Error: No idEvento field provided. Please specify an id."
    elif 'email' not in request.args:
        return "Error: No email field provided. Please specify an email."

    idEvento = request.args['idEvento']
    email = request.args['email']
    query = "SELECT * FROM participacoes WHERE idEvento = '"+idEvento+"' AND email='"+email+"';"
    records = mysqlQuery(conn, query)
    mysqlCloseConnection(conn)
    return jsonify(records)

@app.route('/participacoes/insert', methods=['GET'])
def participacoesInsert():
    conn = mysqlConnection()
    if 'idEvento' not in request.args and 'email' not in request.args:
        return "Error: No idEvento and email fields provided."
    elif 'idEvento' not in request.args:
        return "Error: No idEvento field provided. Please specify an id."
    elif 'email' not in request.args:
        return "Error: No email field provided. Please specify an email."

    idEvento = request.args['idEvento']
    email = request.args['email']
    dataInscricao = request.args['dataInscricao']

    query = "INSERT INTO participacoes ( idEvento, email, dataInscricao ) VALUES( '"+idEvento+"', '"+email+"', '"+dataInscricao+"' );"
    print(query)
    records = mysqlInsert(conn, query)
    mysqlCloseConnection(conn)
    print(records)
    return jsonify(records)

@app.route('/participacoes/remove', methods=['GET'])
def participacoesRemove():
    conn = mysqlConnection()
    if 'idEvento' not in request.args and 'email' not in request.args:
        return "Error: No idEvento and email fields provided."
    elif 'idEvento' not in request.args:
        return "Error: No idEvento field provided. Please specify an id."
    elif 'email' not in request.args:
        return "Error: No email field provided. Please specify an email."

    idEvento = request.args['idEvento']
    email = request.args['email']

    query = "DELETE FROM participacoes WHERE idEvento='"+idEvento+"' AND email='"+email+"';"
    records = mysqlUpdate(conn, query)
    mysqlCloseConnection(conn)
    return jsonify(records)

@app.route('/participacoes/update', methods=['GET'])
def participacoesUpdate():
    conn = mysqlConnection()
    if 'idEvento' not in request.args and 'email' not in request.args:
        return "Error: No idEvento and email fields provided."
    elif 'idEvento' not in request.args:
        return "Error: No idEvento field provided. Please specify an id."
    elif 'email' not in request.args:
        return "Error: No email field provided. Please specify an email."

    idEvento = request.args['idEvento']
    email = request.args['email']

    if 'dataInscricao' not in request.args:
        query = "SELECT dataInscricao FROM participacoes WHERE idEvento='"+idEvento+"' AND email='"+email+"';"
        records = mysqlQuery(conn, query)
        dataInscricao = str(records[0][0])
    else:
        dataInscricao = request.args['dataInscricao']

    query = "UPDATE participacoes SET dataInscricao='"+dataInscricao+"' WHERE idEvento='"+idEvento+"' AND email='"+email+"';"

    records = mysqlUpdate(conn, query)
    mysqlCloseConnection(conn)
    return jsonify(records)