import datetime
import tkinter.messagebox as tm
from tkinter import *
import tkinter.ttk as ttk
import sqlite3
from PIL import ImageTk,Image

path="logo1.png"

sum=0

def myfunction(event):
    canvas.configure(scrollregion=canvas.bbox("all"), width=1328, height=455)

def Numberonly1(event):
    global sum
    item1 = (m1.get())
    sum += item1

def Numberonly2(event):
    global sum
    item2 = (m2.get())
    sum += item2

def Numberonly3(event):
    global sum
    item3 = (m3.get())
    sum += item3

def Numberonly4(event):
    global sum
    item4 = (m4.get())
    sum += item4

def Numberonly5(event):
    global sum
    item5 = (m5.get())
    sum += item5

def Numberonly6(event):
    global sum
    item6 = (m6.get())
    sum += item6

def Numberonly16():
    global sum
    s.set(sum)
    avg = (sum / 6)
    answer.set(round(avg, 2))

def logged():
    s = str(datetime.datetime.now())
    tm.showinfo("Log", "Entry created successfully at " + s)

def Database():
    global conn, cursor
    conn = sqlite3.connect("Student.db")
    cursor = conn.cursor()
    cursor.execute(
        "CREATE TABLE IF NOT EXISTS STUDENT (SNO INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,FirstName TEXT, MiddleName TEXT, LastName TEXT, DateOfBirth INTEGER, MonthOfBirth TEXT, YearOfBirth INTEGER, Gender TEXT, EmailID TEXT, Contact1 TEXT, Contact2 TEXT, Hobbies TEXT, PermanentAddress TEXT, Pincode TEXT, Locality TEXT, City TEXT, PO TEXT, PS TEXT, Lifestyle TEXT, State TEXT, Country TEXT, ParentsName TEXT, ParentsAddress TEXT, ParentsOccupation TEXT, ParentsContact TEXT, ParentsEmail TEXT, GuardianName TEXT, GuardianAddress TEXT, GuardianOccupation TEXT, GuardianContact TEXT, GuardianEmail TEXT, Class12Stream TEXT, English INTEGER, Vernacular INTEGER, Mathematics INTEGER, Physics INTEGER, Chemistry INTEGER, ComputerScience INTEGER, Class12Percentage INTEGER, Class12Aggregate INTEGER)")
    conn.commit()

def Errorcheck1(event):
    str1 = firstname.get()
    for i in range(len(str1)):
        p1 = str1[i]
        p2 = ord(p1)
        if ((p2 < 65) or ((p2 > 90) and (p2 < 97)) or (p2 > 122)):
            tm.showerror("Error", "Invalid First Name")
            tm.showinfo("my message", "Re-enter your first name")
            firstname.set("")
            break

def Errorcheck2(event):
    str1 = middlename.get()
    for i in range(len(str1)):
        p1 = str1[i]
        p2 = ord(p1)
        if ((p2 < 65) or ((p2 > 90) and (p2 < 97)) or (p2 > 122)):
            tm.showerror("Error", "Invalid Middle Name")
            tm.showinfo("my message", "Re-enter your Middle name")
            middlename.set("")
            break

def Errorcheck3(event):
    str1 = lastname.get()
    for i in range(len(str1)):
        p1 = str1[i]
        p2 = ord(p1)
        if ((p2 < 65) or ((p2 > 90) and (p2 < 97)) or (p2 > 122)):
            tm.showerror("Error", "Invalid Last Name")
            tm.showinfo("my message", "Re-enter your Middle name")
            lastname.set("")
            break

def Errorcheck9(event):
    str1 = parent.get()
    for i in range(len(str1)):
        p1 = str1[i]
        p2 = ord(p1)
        if ((p2 < 65) or ((p2 > 90) and (p2 < 97)) or (p2 > 122) or (p2!=32)):
            tm.showerror("Error", "Invalid Parents Name")
            tm.showinfo("my message", "Re-enter your Parents name")
            parent.set("")
            break

def Errorcheck10(event):
    str1 = guardian.get()
    for i in range(len(str1)):
        p1 = str1[i]
        p2 = ord(p1)
        if ((p2 < 65) or ((p2 > 90) and (p2 < 97)) or (p2 > 122) or (p2!=32)):
            tm.showerror("Error", "Invalid Guardian Name")
            tm.showinfo("my message", "Re-enter your Guardian name")
            guardian.set("")
            break

def Errorcheck4(event):
    try:
        str1 = int(cl6a.get())
        str2 = cl6b.get()
        str3 = int(cl6c.get())
        if(type(str1) is not int or type(str3) is not int):
            raise ValueError("Error in type occured")
        if ((str3 % 400 == 0) or (str3 % 4 == 0 and str3 % 100 != 0)):
            pc = 1
        else:
            pc = 0
        if (((str1 > 28) and (str2 == "February") and (pc == 0))):
            tm.showerror("Error", "Invalid Date Entered")
            tm.showinfo("my message", "Re-enter your Date Of Birth")
            cl6a.set("")
            cl6b.set("")
            cl6c.set("")
    except ValueError as ve:
        print(ve)

def Errorcheck5(event):
    str1 = phone1.get()
    if(len(str1)>10):
        tm.showerror("Error", "Invalid Contact Number Entered")
        tm.showinfo("my message", "Re-enter your Contact Number")
        phone1.set("")

def Errorcheck7(event):
    str1 = phone3.get()
    if (len(str1) > 10):
        tm.showerror("Error", "Invalid Contact Number Entered")
        tm.showinfo("my message", "Re-enter your Contact Number")
        phone3.set("")

def Errorcheck6(event):
    str1 = phone2.get()
    if (len(str1) > 10):
        tm.showerror("Error", "Invalid Contact Number Entered")
        tm.showinfo("my message", "Re-enter your Contact Number")
        phone2.set("")

def Errorcheck8(event):
    str1 = phone4.get()
    if (len(str1) > 10):
        tm.showerror("Error", "Invalid Contact Number Entered")
        tm.showinfo("my message", "Re-enter your Contact Number")
        phone4.set("")

def DatabaseAdd():
    Database()
    global conn, cursor
    cursor.execute(
        "INSERT INTO STUDENT(FirstName, MiddleName, LastName, DateOfBirth, MonthOfBirth, YearOfBirth, Gender, EmailID, Contact1, Contact2, Hobbies, PermanentAddress, Pincode, Locality, City, PO, PS, Lifestyle, State, Country, ParentsName, ParentsAddress, ParentsOccupation, ParentsContact, ParentsEmail, GuardianName, GuardianAddress, GuardianOccupation, GuardianContact, GuardianEmail, Class12Stream, English, Vernacular, Mathematics, Physics, Chemistry, ComputerScience, Class12Percentage, Class12Aggregate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        (str(firstname.get()), str(middlename.get()), str(lastname.get()), str(cl6a.get()), str(cl6b.get()),
         str(cl6c.get()), str(i1.get()), str(email1.get()), str(phone1.get()), str(phone2.get()), str(hobby.get()),
         str(address1.get()), str(pincode.get()), str(locality.get()), str(city.get()), str(po.get()),
         str(ps.get()), str(i2.get()), str(state.get()), str(cl7a.get()), str(parent.get()),
         str(parentaddress.get()), str(parentoccupation.get()), str(phone3.get()), str(email2.get()),
         str(guardian.get()), str(guardaddress.get()), str(guardoccupation.get()), str(phone4.get()),
         str(email3.get()), str(c31a.get()), str(m1.get()), str(m2.get()), str(m3.get()), str(m4.get()),
         str(m5.get()), str(m6.get()), str(answer.get()), str(s.get())))
    conn.commit()
    firstname.set(""), middlename.set(""), lastname.set(""), cl6a.set(""), cl6b.set(""), cl6c.set(""), i1.set(
        ""), email1.set(""), phone1.set(""), phone2.set(""), hobby.set(""), address1.set(""), pincode.set(
        ""), locality.set(""), city.set(""), po.set(""), ps.set(""), i2.set(""), state.set(""), cl7a.set(
        ""), parent.set(""), parentaddress.set(""), parentoccupation.set(""), phone3.set(""), email2.set(
        ""), guardian.set(""), guardaddress.set(""), guardoccupation.set(""), phone4.set(""), email3.set(
        ""), c31a.set(""), m1.set("0"), m2.set("0"), m3.set("0"), m4.set("0"), m5.set("0"), m6.set("0"), answer.set(
        "0"), s.set("0")
    cursor.close()
    conn.close()
    logged()

def DatabaseView():
    Database()
    frame1 = Toplevel()
    global conn, cursor
    frame1.title("View Contents")
    w = 450
    h = 75
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws / 2) - (w / 2)
    y = (hs / 2) - (h / 2)
    frame1.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def Viewall():
        Database()
        ViewFrame = Toplevel()
        cursor.execute("SELECT * FROM STUDENT")
        conn.commit()
        fetch = cursor.fetchall()
        scrollbarx = Scrollbar(ViewFrame, orient=HORIZONTAL)
        scrollbary = Scrollbar(ViewFrame, orient=VERTICAL)
        tree = ttk.Treeview(ViewFrame, columns=(
            "SNo", "FirstName", "MiddleName", "LastName", "DateOfBirth", "MonthOfBirth", "YearOfBirth", "Gender",
            "EmailID", "Contact1", "Contact2", "Hobbies", "PermanentAddress", "Pincode", "Locality", "City", "PO", "PS",
            "Lifestyle", "State", "Country", "ParentsName", "ParentsAddress", "ParentsOccupation", "ParentsContact",
            "ParentsEmail", "GuardianName", "GuardianAddress", "GuardianOccupation", "GuardianContact", "GuardianEmail",
            "Class12Stream", "English", "Vernacular", "Mathematics", "Physics", "Chemistry", "ComputerScience",
            "Class12Percentage", "Class12Aggregate"),
                            selectmode=EXTENDED, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
        scrollbary.config(command=tree.yview)
        scrollbary.pack(side=RIGHT, fill=Y)
        scrollbarx.config(command=tree.xview)
        scrollbarx.pack(side=BOTTOM, fill=X)
        tree.heading('SNo', text="SNo", anchor=CENTER), tree.heading('FirstName', text="FirstName",
                                                                     anchor=CENTER), tree.heading('MiddleName',
                                                                                text="MiddleName",
                                                                                anchor=CENTER), tree.heading(
            'LastName', text="LastName", anchor=CENTER), tree.heading('DateOfBirth', text="DateOfBirth",
                                                                      anchor=CENTER), tree.heading('MonthOfBirth',
                                                                                text="MonthOfBirth",
                                                                                anchor=CENTER), tree.heading(
            'YearOfBirth', text="YearOfBirth", anchor=CENTER), tree.heading('Gender', text="Gender",
                                                                            anchor=CENTER), tree.heading('EmailID',
                                                                                text="EmailID",
                                                                                anchor=CENTER), tree.heading(
            'Contact1', text="Contact1", anchor=CENTER), tree.heading('Contact2', text="Contact2",
                                                                      anchor=CENTER), tree.heading('Hobbies',
                                                                                text="Hobbies",
                                                                                anchor=CENTER), tree.heading(
            'PermanentAddress', text="PermanentAddress", anchor=CENTER), tree.heading('Pincode', text="Pincode",
                                                                                anchor=CENTER), tree.heading(
            'Locality', text="Locality", anchor=CENTER), tree.heading('City', text="City",
                                                                      anchor=CENTER), tree.heading('PO', text="PO",
                                                                                anchor=CENTER), tree.heading(
            'PS', text="PS", anchor=CENTER), tree.heading('Lifestyle', text="Lifestyle",
                                                          anchor=CENTER), tree.heading('State', text="State",
                                                                                anchor=CENTER), tree.heading(
            'Country', text="Country", anchor=CENTER), tree.heading('ParentsName', text="ParentsName",
                                                                    anchor=CENTER), tree.heading('ParentsAddress',
                                                                                text="ParentsAddress",
                                                                                anchor=CENTER), tree.heading(
            'ParentsOccupation', text="ParentsOccupation", anchor=CENTER), tree.heading('ParentsContact',
                                                                                text="ParentsContact",
                                                                                anchor=CENTER), tree.heading(
            'ParentsEmail', text="ParentsEmail", anchor=CENTER), tree.heading('GuardianName', text="GuardianName",
                                                                              anchor=CENTER), tree.heading(
            'GuardianAddress', text="GuardianAddress", anchor=CENTER), tree.heading('GuardianOccupation',
                                                                                text="GuardianOccupation",
                                                                                anchor=CENTER), tree.heading(
            'GuardianContact', text="GuardianContact", anchor=CENTER), tree.heading('GuardianEmail',
                                                                                text="GuardianEmail",
                                                                                anchor=CENTER), tree.heading(
            'Class12Stream', text="Class12Stream", anchor=CENTER), tree.heading('English', text="English",
                                                                                anchor=CENTER), tree.heading(
            'Vernacular', text="Vernacular", anchor=CENTER), tree.heading('Mathematics', text="Mathematics",
                                                                          anchor=CENTER), tree.heading('Physics',
                                                                                text="Physics",
                                                                                anchor=CENTER), tree.heading(
            'Chemistry', text="Chemistry", anchor=CENTER), tree.heading('ComputerScience', text="ComputerScience",
                                                                        anchor=CENTER), tree.heading(
            'Class12Percentage', text="Class12Percentage", anchor=CENTER), tree.heading('Class12Aggregate',
                                                                                text="Class12Aggregate",
                                                                                anchor=CENTER)
        tree.column('#0', stretch=NO, minwidth=0, width=0), tree.column('#1', stretch=NO, minwidth=0,
                                                                        width=140), tree.column('#2', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#3', stretch=NO, minwidth=0, width=140), tree.column('#4', stretch=NO, minwidth=0,
                                                                  width=140), tree.column('#5', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#6', stretch=NO, minwidth=0, width=140), tree.column('#7', stretch=NO, minwidth=0,
                                                                  width=150), tree.column('#8', stretch=NO,
                                                                                minwidth=0,
                                                                                width=150), tree.column(
            '#9', stretch=NO, minwidth=0, width=150), tree.column('#10', stretch=NO, minwidth=0,
                                                                  width=140), tree.column('#11', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#12', stretch=NO, minwidth=0, width=140), tree.column('#13', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#14', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#15', stretch=NO, minwidth=0, width=140), tree.column('#16', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#17', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#18', stretch=NO, minwidth=0, width=140), tree.column('#19', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#20', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#21', stretch=NO, minwidth=0, width=140), tree.column('#22', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#23', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#24', stretch=NO, minwidth=0, width=140), tree.column('#25', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#26', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#27', stretch=NO, minwidth=0, width=140), tree.column('#28', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#29', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#30', stretch=NO, minwidth=0, width=140), tree.column('#31', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#32', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#33', stretch=NO, minwidth=0, width=140), tree.column('#34', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#35', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#36', stretch=NO, minwidth=0, width=140), tree.column('#37', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#38', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#39', stretch=NO, minwidth=0, width=140)
        tree.pack()
        for data in fetch:
            tree.insert('', 'end', values=data)
        cursor.close()
        conn.close()

    def Search():
        Database()
        ViewFrame = Toplevel()
        scrollbarx = Scrollbar(ViewFrame, orient=HORIZONTAL)
        scrollbary = Scrollbar(ViewFrame, orient=VERTICAL)
        tree = ttk.Treeview(ViewFrame, columns=(
            "SNo", "FirstName", "MiddleName", "LastName", "DateOfBirth", "MonthOfBirth", "YearOfBirth", "Gender",
            "EmailID", "Contact1", "Contact2", "Hobbies", "PermanentAddress", "Pincode", "Locality", "City", "P.O",
            "P.S", "Lifestyle", "State", "Country", "ParentsName", "ParentsAddress", "ParentsOccupation",
            "ParentsContact", "ParentsEmail", "GuardianName", "GuardianAddress", "GuardianOccupation",
            "GuardianContact", "GuardianEmail", "Class12Stream", "English", "Vernacular", "Mathematics", "Physics",
            "Chemistry", "ComputerScience", "Class12Percentage", "Class12Aggregate"),
                            selectmode=EXTENDED, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
        scrollbary.config(command=tree.yview)
        scrollbary.pack(side=RIGHT, fill=Y)
        scrollbarx.config(command=tree.xview)
        scrollbarx.pack(side=BOTTOM, fill=X)
        tree.heading('SNo', text="SNo", anchor=CENTER), tree.heading('FirstName', text="FirstName",
                                                                     anchor=CENTER), tree.heading('MiddleName',
                                                                                text="MiddleName",
                                                                                anchor=CENTER), tree.heading(
            'LastName', text="LastName", anchor=CENTER), tree.heading('DateOfBirth', text="DateOfBirth",
                                                                      anchor=CENTER), tree.heading('MonthOfBirth',
                                                                                text="MonthOfBirth",
                                                                                anchor=CENTER), tree.heading(
            'YearOfBirth', text="YearOfBirth", anchor=CENTER), tree.heading('Gender', text="Gender",
                                                                            anchor=CENTER), tree.heading('EmailID',
                                                                                text="EmailID",
                                                                                anchor=CENTER), tree.heading(
            'Contact1', text="Contact1", anchor=CENTER), tree.heading('Contact2', text="Contact2",
                                                                      anchor=CENTER), tree.heading('Hobbies',
                                                                                text="Hobbies",
                                                                                anchor=CENTER), tree.heading(
            'PermanentAddress', text="PermanentAddress", anchor=CENTER), tree.heading('Pincode', text="Pincode",
                                                                                anchor=CENTER), tree.heading(
            'Locality', text="Locality", anchor=CENTER), tree.heading('City', text="City",
                                                                      anchor=CENTER), tree.heading('P.O',
                                                                                text="P.O",
                                                                                anchor=CENTER), tree.heading(
            'P.S', text="P.S", anchor=CENTER), tree.heading('Lifestyle', text="Lifestyle",
                                                            anchor=CENTER), tree.heading('State', text="State",
                                                                                anchor=CENTER), tree.heading(
            'Country', text="Country", anchor=CENTER), tree.heading('ParentsName', text="ParentsName",
                                                                    anchor=CENTER), tree.heading('ParentsAddress',
                                                                                text="ParentsAddress",
                                                                                anchor=CENTER), tree.heading(
            'ParentsOccupation', text="ParentsOccupation", anchor=CENTER), tree.heading('ParentsContact',
                                                                                text="ParentsContact",
                                                                                anchor=CENTER), tree.heading(
            'ParentsEmail', text="ParentsEmail", anchor=CENTER), tree.heading('GuardianName', text="GuardianName",
                                                                              anchor=CENTER), tree.heading(
            'GuardianAddress', text="GuardianAddress", anchor=CENTER), tree.heading('GuardianOccupation',
                                                                                text="GuardianOccupation",
                                                                                anchor=CENTER), tree.heading(
            'GuardianContact', text="GuardianContact", anchor=CENTER), tree.heading('GuardianEmail',
                                                                                text="GuardianEmail",
                                                                                anchor=CENTER), tree.heading(
            'Class12Stream', text="Class12Stream", anchor=CENTER), tree.heading('English', text="English",
                                                                                anchor=CENTER), tree.heading(
            'Vernacular', text="Vernacular", anchor=CENTER), tree.heading('Mathematics', text="Mathematics",
                                                                          anchor=CENTER), tree.heading('Physics',
                                                                                text="Physics",
                                                                                anchor=CENTER), tree.heading(
            'Chemistry', text="Chemistry", anchor=CENTER), tree.heading('ComputerScience', text="ComputerScience",
                                                                        anchor=CENTER), tree.heading(
            'Class12Percentage', text="Class12Percentage", anchor=CENTER), tree.heading('Class12Aggregate',
                                                                                text="Class12Aggregate",
                                                                                anchor=CENTER)
        tree.column('#0', stretch=NO, minwidth=0, width=0), tree.column('#1', stretch=NO, minwidth=0,
                                                                        width=140), tree.column('#2', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#3', stretch=NO, minwidth=0, width=140), tree.column('#4', stretch=NO, minwidth=0,
                                                                  width=140), tree.column('#5', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#6', stretch=NO, minwidth=0, width=140), tree.column('#7', stretch=NO, minwidth=0,
                                                                  width=140), tree.column('#8', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#9', stretch=NO, minwidth=0, width=140), tree.column('#10', stretch=NO, minwidth=0,
                                                                  width=140), tree.column('#11', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#12', stretch=NO, minwidth=0, width=140), tree.column('#13', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#14', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#15', stretch=NO, minwidth=0, width=140), tree.column('#16', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#17', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#18', stretch=NO, minwidth=0, width=140), tree.column('#19', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#20', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#21', stretch=NO, minwidth=0, width=140), tree.column('#22', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#23', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#24', stretch=NO, minwidth=0, width=140), tree.column('#25', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#26', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#27', stretch=NO, minwidth=0, width=140), tree.column('#28', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#29', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#30', stretch=NO, minwidth=0, width=140), tree.column('#31', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#32', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#33', stretch=NO, minwidth=0, width=140), tree.column('#34', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#35', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#36', stretch=NO, minwidth=0, width=140), tree.column('#37', stretch=NO, minwidth=0,
                                                                   width=140), tree.column('#38', stretch=NO,
                                                                                minwidth=0,
                                                                                width=140), tree.column(
            '#39', stretch=NO, minwidth=0, width=140)
        tree.pack()
        if st.get() != "":
            cursor.execute("SELECT * FROM `STUDENT` WHERE `FirstName` LIKE ?", ('%' + str(st.get()) + '%',))
            conn.commit()
            fetch = cursor.fetchall()
            for data in fetch:
                tree.insert('', 'end', values=data)
        cursor.close()
        conn.close()

    def Reset():
        st.set("")

    Button(frame1, text="View All", command=Viewall).pack(side=LEFT, anchor=N, padx=10, pady=10)
    Button(frame1, text="Search", command=Search).pack(side=LEFT, anchor=N, padx=10, pady=10)
    st = StringVar()
    Entry(frame1, textvariable=st, width=30).pack(side=LEFT, anchor=N, padx=5, pady=11)
    st.get()
    Button(frame1, text="Reset", command=Reset).pack(side=LEFT, anchor=N, padx=10, pady=10)
    frame1.resizable(0, 0)

def Exit():
    result = tm.askquestion('Inventory Management v1.3', 'Are you sure you want to exit?', icon="warning")
    if result == 'yes':
        root.destroy()
        cursor.close()
        conn.close()
        exit()

def Chnglog():
    tm.showinfo("Changelog",
                "v1.0 - Only GUI \nv1.1 - Accepts inputs and saves it to text file \nv1.2 - Open previous logs\nv1.3 - SQLite3 Database integration")

def About():
    tm.showinfo("About", "Python GUI Project\nInventory Management v1.3")

root = Tk()
sizex = 5000
sizey = 4000
posx = 100
posy = 100
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

# create a drop down menu
menu = Menu(root)
root.title("Student Admission System")
root.config(menu=menu)

# file menu
file = Menu(menu, tearoff=0)
menu.add_cascade(label="File", menu=file)
file.add_command(label="Open File", command=DatabaseView)
file.add_separator()
file.add_command(label="Exit", command=Exit)

# help menu
hlp = Menu(menu, tearoff=0)
menu.add_cascade(label="Help", menu=hlp)
hlp.add_command(label="About", command=About)
hlp.add_command(label="Changelog", command=Chnglog)

myframe = Frame(root, relief=GROOVE, width=sizex, height=sizey, bd=1)
myframe.place(x=5, y=200)

img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = Label(root, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.place(x=40,y=30)

canvas = Canvas(myframe)
frame = Frame(canvas, bg="light blue")
myscrollbar1 = Scrollbar(myframe, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=myscrollbar1.set)

myscrollbar1.pack(side="right", fill="y")
myscrollbar2 = Scrollbar(myframe, orient="horizontal", command=canvas.xview)
canvas.configure(xscrollcommand=myscrollbar2.set)

myscrollbar2.pack(side="bottom", fill="x")
canvas.pack(side="left")
canvas.create_window((0, 0), window=frame, anchor='nw')
frame.bind("<Configure>", myfunction)

# data()
root.configure(bg="black")
label = Label(root, text="APPLICATION  FORM  OF  ST.THOMAS'  COLLEGE  ")
label.config(font=("Baskerville Old Face", 34, 'bold'), fg="blue")
label.place(x=220, y=75)

l4s = Label(frame, text="Personal Details  :-", bg="green", fg="yellow")
l4s.config(font=("Courier", 25, 'bold'))
l4s.grid(row=3, column=0, pady=50, sticky="W")

l5 = Label(frame, text="First Name", bg="light blue")
l5.config(font=("Aeril", 20))
l5.grid(row=5, column=0)
firstname = StringVar()
el5a = Entry(frame, width=30, textvariable=firstname)
el5a.config(font=("Aeril", 15))
el5a.bind('<Leave>',Errorcheck1)
el5a.grid(row=5, column=1, sticky="W", columnspan=2)

l5b = Label(frame, text="Middle Name", bg="light blue")
l5b.config(font=("Aeril", 20))
l5b.grid(row=6, column=0, pady=50)
middlename = StringVar()
el5b = Entry(frame, width=30, textvariable=middlename)
el5b.config(font=("Aeril", 15))
el5b.bind('<Leave>',Errorcheck2)
el5b.grid(row=6, column=1, sticky="W", columnspan=2)

l5c = Label(frame, text="Last Name", bg="light blue")
l5c.config(font=("Aeril", 20))
l5c.grid(row=7, column=0)
lastname = StringVar()
el5c = Entry(frame, width=30, textvariable=lastname)
el5c.config(font=("Aeril", 15))
el5c.bind('<Leave>',Errorcheck3)
el5c.grid(row=7, column=1, sticky="W", columnspan=2)

# DATE OF BIRTH
l6 = Label(frame, text="Date Of Birth", bg="light blue")
l6.config(font=("Aerial", 20))
l6.grid(row=8, column=0, pady=50)
cl6a = ttk.Combobox(frame, values=[i for i in range(1, 32)])
cl6a.set("DATE")
cl6a.bind("<<ComboboxSelected>>")
cl6a.config(font=("Aerial", 15), width='15')
cl6a.grid(row=8, column=1, sticky="W", columnspan=2)
cl6b = ttk.Combobox(frame,
                    values=["January", "February", "March", "April", "May", "June", "July", "August", "September",
                            "October", "November", "December"])
cl6b.set("MONTH")
cl6b.bind("<<ComboboxSelected>>")
cl6b.config(font=("Aerial", 15), width='15')
cl6b.place(x=690, y=411)
cl6c = ttk.Combobox(frame, values=[i for i in range(1975, 2019)])
cl6c.bind('<Leave>',Errorcheck4)
cl6c.set("YEAR")
cl6c.bind("<<ComboboxSelected>>")
cl6c.config(font=("Aerial", 15), width='15')
cl6c.place(x=920, y=411)

# GENDER
l7 = Label(frame, text="Gender", bg="light blue")
l7.config(font=("Aerial", 20))
l7.grid(row=9, column=0)
i1 = StringVar()
r1 = Radiobutton(frame, text="Male", value="Male", variable=i1)
r1.config(font=("Aerial", 15))
r1.grid(row=9, column=1, sticky="W", columnspan=2)
r2 = Radiobutton(frame, text="Female", value="Female", variable=i1)
r2.config(font=("Aerial", 15))
r2.place(x=610, y=496)
r3 = Radiobutton(frame, text="Others", value="Others", variable=i1)
r3.config(font=("Aerial", 15))
r3.place(x=780, y=496)

# EMAIL
l8 = Label(frame, text="Email ID", bg="light blue")
l8.config(font=("Aerial", 20))
l8.grid(row=10, column=0, pady=40)
email1 = StringVar()
el8 = Entry(frame, width=50, textvariable=email1)
el8.config(font=("Aeril", 15))
el8.grid(row=10, column=1, sticky="W")
# CONTACT NO 1
l9 = Label(frame, text="Contact Number 1", bg="light blue")
l9.config(font=("Aerial", 20))
l9.grid(row=11, column=0)
phone1 = StringVar()
el9 = Entry(frame, width=30, textvariable=phone1)
el9.bind('<Leave>',Errorcheck5)
el9.config(font=("Aeril", 15))
el9.grid(row=11, column=1, sticky="W")

# CONTACT NO 2
l10 = Label(frame, text="Contact Number 2", bg="light blue")
l10.config(font=("Aerial", 20))
l10.grid(row=12, column=0, pady=40)
phone2 = StringVar()
el10 = Entry(frame, width=30, textvariable=phone2)
el10.config(font=("Aeril", 15))
el10.bind('<Leave>',Errorcheck6)
el10.grid(row=12, column=1, sticky="W")

# HOBBIES
l11 = Label(frame, text="Hobbies", bg="light blue")
l11.config(font=("Aerial", 20))
l11.grid(row=14, column=0)
hobby = StringVar()
el11 = Entry(frame, width=50, textvariable=hobby)
el11.config(font=("Aeril", 15))
el11.grid(row=14, column=1, sticky="W")

l4s = Label(frame, text="Residential Details  :-", bg="green", fg="yellow")
l4s.config(font=("Courier", 25, 'bold'))
l4s.grid(row=15, column=0, pady=50)

# PERMANENT ADDRESS
l12 = Label(frame, text="Permanent Address", bg="light blue")
l12.config(font=("Aerial", 20))
l12.grid(row=17, column=0)
address1 = StringVar()
el12 = Entry(frame, width=80, textvariable=address1)
el12.config(font=("Aeril", 15))
el12.grid(row=17, column=1, sticky="W")

# PINCODE
l13 = Label(frame, text="Pincode", bg="light blue")
l13.config(font=("Aerial", 20))
l13.grid(row=18, column=0, pady=50)
pincode = StringVar()
el13 = Entry(frame, width=15, textvariable=pincode)
el13.config(font=("Aeril", 15))
el13.grid(row=18, column=1, sticky="W")

# LOCALITY
l14 = Label(frame, text="Locality", bg="light blue")
l14.config(font=("Aerial", 20))
l14.grid(row=20, column=0)
locality = StringVar()
el14 = Entry(frame, width=20, textvariable=locality)
el14.config(font=("Aeril", 15))
el14.grid(row=20, column=1, sticky="W")
# CITY
l12 = Label(frame, text="City", bg="light blue")
l12.config(font=("Aerial", 20))
l12.grid(row=22, column=0, pady=45)
city = StringVar()
el12 = Entry(frame, width=20, textvariable=city)
el12.config(font=("Aeril", 15))
el12.grid(row=22, column=1, sticky="W")

# PO
l13 = Label(frame, text="Post Office(P.O)", bg="light blue")
l13.config(font=("Aerial", 20))
l13.grid(row=24, column=0)
po = StringVar()
el13 = Entry(frame, width=20, textvariable=po)
el13.config(font=("Aeril", 15))
el13.place(x=462, y=1335)

# PS
l14 = Label(frame, text="Police Station(P.S)", bg="light blue")
l14.config(font=("Aerial", 20))
l14.place(x=850, y=1330)
ps = StringVar()
el14 = Entry(frame, width=20, textvariable=ps)
el14.config(font=("Aeril", 15))
el14.place(x=1182, y=1335)

# Urban/rural
l15 = Label(frame, text="Lifestyle", bg="light blue")
l15.config(font=("Aerial", 20))
l15.grid(row=30, column=0, pady=45)

i2 = StringVar()
r1 = Radiobutton(frame, text="Urban", value="Urban", variable=i2)
r1.config(font=("Aerial", 15))
r1.grid(row=30, column=1, sticky="W", columnspan=2)
r2 = Radiobutton(frame, text="Rural", value="Rural", variable=i2)
r2.config(font=("Aerial", 15))
r2.place(x=600, y=1413)

# State
l16 = Label(frame, text="State", bg="light blue")
l16.config(font=("Aerial", 20,))
l16.grid(row=31, column=0, pady=10)
state = StringVar()
el16 = Entry(frame, width=20, textvariable=state)
el16.config(font=("Aeril", 15))
el16.grid(row=31, column=1, sticky="W")

# Country
l17 = Label(frame, text="Country", bg="light blue")
l17.config(font=("Aerial", 20,))
l17.grid(row=32, column=0, pady=30)
cl7a = ttk.Combobox(frame, values=["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua & Barbuda",
                                   "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas",
                                   "Bahrai", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
                                   "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei",
                                   "Bulgaria", "Burkina Faso", "Burundi", "Cabo Verde", "Cambodia", "Cameroon",
                                   "Canada", "Central African Republic (CAR)", "Chad", "Chile", "China", "Colombia",
                                   "Comoros", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czechia",
                                   "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt",
                                   "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
                                   "Eswatini (formerly Swaziland)", "Ethiopia", "Fiji", "Finland", "France",
                                   "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada",
                                   "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hungary",
                                   "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy",
                                   "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kosovo",
                                   "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia",
                                   "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Madagascar", "Malawi",
                                   "Malaysia", "Maldives", "Mali", "Malt", "Marshall Islands", "Mauritius",
                                   "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco",
                                   "Mozambique", "Myanmar(formerly Burma)", "Namibia", "Nauru"
    , "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "North Korea",
                                   "North Macedonia (formerly Macedonia)", "Norway", "Oman", "Pakistan", "Palau",
                                   "Palestine", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
                                   "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda",
                                   "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines",
                                   "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal",
                                   "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia",
                                   "Solomon Islands", "Somalia", "South Africa", "South Korea", "South Sudan",
                                   "Spain", "Sri Lanka", "Sudan", "Suriname", "Sweden", "Switzerland", "Syria",
                                   "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo,Tonga",
                                   "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu", "Uganda",
                                   "Ukraine", "United Arab Emirates (UAE)", "United Kingdom (UK)",
                                   "United States of America (USA)", "Uruguay", "Uzbekistan", "Vanuatu",
                                   "Vatican City (Holy See)", "Venezuela", "Vietnam", "Yemen", "Zambia",
                                   "Zimbabwe"])
cl7a.set("Select A Country")
cl7a.bind("<<ComboboxSelected>>")
cl7a.config(font=("Aerial", 15), width='30')
cl7a.grid(row=32, column=1, sticky="W", columnspan=2)

l18s = Label(frame, text="Parents' Details  :-")
l18s.config(font=("Courier", 25, 'bold'))
l18s.grid(row=33, column=0, pady=40, sticky="W")

# Parent's name
l19 = Label(frame, text="Parents Name", bg="light blue")
l19.config(font=("Aerial", 20,))
l19.grid(row=34, column=0, pady=10)
parent = StringVar()
el19 = Entry(frame, width=20, textvariable=parent)
el19.config(font=("Aeril", 15))
el19.grid(row=34, column=1, sticky="W")

# Parent's address
l20 = Label(frame, text="Parents Address", bg="light blue")
l20.config(font=("Aerial", 20,))
l20.grid(row=35, column=0, pady=30)
parentaddress = StringVar()
el20 = Entry(frame, width=30, textvariable=parentaddress)
el20.config(font=("Aeril", 15))
el20.grid(row=35, column=1, sticky="W")

# Parent's occupation
l21 = Label(frame, text="Parents Occupation", bg="light blue")
l21.config(font=("Aerial", 20,))
l21.grid(row=36, column=0, pady=20)
parentoccupation = StringVar()
el21 = Entry(frame, width=20, textvariable=parentoccupation)
el21.config(font=("Aeril", 15))
el21.grid(row=36, column=1, sticky="W")

# Parents' contact
l22 = Label(frame, text="Parents Contact", bg="light blue")
l22.config(font=("Aerial", 20,))
l22.grid(row=37, column=0, pady=20)
phone3 = StringVar()
el22 = Entry(frame, width=20, textvariable=phone3)
el22.config(font=("Aeril", 15))
el22.bind('<Leave>',Errorcheck7)
el22.grid(row=37, column=1, sticky="W")

# Parents' email
l23 = Label(frame, text="Parents Email", bg="light blue")
l23.config(font=("Aerial", 20,))
l23.grid(row=38, column=0, pady=20)
email2 = StringVar()
el23 = Entry(frame, width=20, textvariable=email2)
el23.config(font=("Aeril", 15))
el23.grid(row=38, column=1, sticky="W")

# Guardian's Name
l24 = Label(frame, text="Guardian Name", bg="light blue")
l24.config(font=("Aerial", 20,))
l24.grid(row=39, column=0, pady=30)
guardian = StringVar()
el24 = Entry(frame, width=20, textvariable=guardian)
el24.config(font=("Aeril", 15))
el24.grid(row=39, column=1, sticky="W")

# Guardian's address
l25 = Label(frame, text="Guardian Address", bg="light blue")
l25.config(font=("Aerial", 20,))
l25.grid(row=40, column=0, pady=20)
guardaddress = StringVar()
el25 = Entry(frame, width=30, textvariable=guardaddress)
el25.config(font=("Aeril", 15))
el25.grid(row=40, column=1, sticky="W")

# Guardians' occupation
l26 = Label(frame, text="Guardian Occupation", bg="light blue")
l26.config(font=("Aerial", 20,))
l26.grid(row=41, column=0, pady=20)
guardoccupation = StringVar()
el26 = Entry(frame, width=20, textvariable=guardoccupation)
el26.config(font=("Aeril", 15))
el26.grid(row=41, column=1, sticky="W")

# Guardians' contact
l27 = Label(frame, text="Guardian Contact", bg="light blue")
l27.config(font=("Aerial", 20,))
l27.grid(row=42, column=0, pady=20)
phone4 = StringVar()
el27 = Entry(frame, width=20, textvariable=phone4)
el27.config(font=("Aeril", 15))
el27.bind('<Leave>',Errorcheck8)
el27.grid(row=42, column=1, sticky="W")

# Guardians' email
l28 = Label(frame, text="Guardian Email", bg="light blue")
l28.config(font=("Aerial", 20,))
l28.grid(row=43, column=0, pady=20)
email3 = StringVar()
el28 = Entry(frame, width=20, textvariable=email3)
el28.config(font=("Aeril", 15))
el28.grid(row=43, column=1, sticky="W")

l29s = Label(frame, text="Educational Details  :-", bg="green", fg="yellow")
l29s.config(font=("Courier", 25, 'bold'))
l29s.grid(row=44, column=0, pady=40, sticky="W")

# Stream
l30 = Label(frame, text="Class 12 Stream", bg="light blue")
l30.config(font=("Aerial", 20,))
l30.grid(row=45, column=0, pady=30)

c31a = ttk.Combobox(frame, values=["PMC-Comp", "PMC-B", "PMC-Comm", "PMC-Arts"])
c31a.set("Class 12 Stream")
c31a.bind("<<ComboboxSelected>>")
c31a.config(font=("Aerial", 15), width='20')
c31a.grid(row=45, column=1, sticky="W", columnspan=2)

l30 = Label(frame, text="According to selection , choose your subjects and enter corresponding marks",
            bg="light blue")
l30.config(font=("Aerial", 20,))
l30.grid(row=46, column=0, pady=30, columnspan=3, sticky="W")

m1 = IntVar()
m2 = IntVar()
m3 = IntVar()
m4 = IntVar()
m5 = IntVar()
m6 = IntVar()
answer = IntVar()
s = IntVar()
cb1 = Checkbutton(frame, text="English")
cb1.config(font=("Aerial", 15))
cb1.grid(row=47, column=0)
cben1 = Entry(frame, width=10, textvariable=m1)
cben1.config(font=("Aeril", 15))
cben1.bind("<Leave>", Numberonly1)
cben1.grid(row=47, column=1, sticky="W")
cb2 = Checkbutton(frame, text="Vernacular")
cb2.config(font=("Aerial", 15))
cb2.grid(row=48, column=0, pady=45)
cben2 = Entry(frame, width=10, textvariable=m2)
cben2.config(font=("Aeril", 15))
cben2.bind("<Leave>", Numberonly2)
cben2.grid(row=48, column=1, sticky="W")
cb3 = Checkbutton(frame, text="Mathematics")
cb3.config(font=("Aerial", 15))
cb3.grid(row=49, column=0, pady=15)
cben3 = Entry(frame, width=10, textvariable=m3)
cben3.config(font=("Aeril", 15))
cben3.bind("<Leave>", Numberonly3)
cben3.grid(row=49, column=1, sticky="W")
cb4 = Checkbutton(frame, text="Physics")
cb4.config(font=("Aerial", 15))
cb4.grid(row=50, column=0, pady=15)
cben4 = Entry(frame, width=10, textvariable=m4)
cben4.config(font=("Aeril", 15))
cben4.bind("<Leave>", Numberonly4)
cben4.grid(row=50, column=1, sticky="W")
cb5 = Checkbutton(frame, text="Chemistry")
cb5.config(font=("Aerial", 15))
cb5.grid(row=51, column=0, pady=15)
cben5 = Entry(frame, width=10, textvariable=m5)
cben5.config(font=("Aeril", 15))
cben5.bind("<Leave>", Numberonly5)
cben5.grid(row=51, column=1, sticky="W")
cb6 = Checkbutton(frame, text="Computer_Science")
cb6.config(font=("Aerial", 15))
cb6.grid(row=52, column=0, pady=15)
cben6 = Entry(frame, width=10, textvariable=m6)
cben6.config(font=("Aeril", 15))
cben6.bind("<Leave>", Numberonly6)
cben6.grid(row=52, column=1, sticky="W")

cal_but = Button(frame, padx=10, bd=7, font=("Helvetica", 10, "bold"), width=15, text="Calculate Percentage",
                 bg="blue", command=Numberonly16).grid(row=62, column=0, pady=10)
l35 = Label(frame, text="Class 12 percentage", bg="light blue")
l35.config(font=("Aerial", 20,))
l35.grid(row=53, column=0, pady=30)
cben16 = Entry(frame, width=10, textvariable=answer, state=DISABLED)
cben16.config(font=("Aeril", 15))
cben16.grid(row=53, column=1, sticky="W")
l36 = Label(frame, text="Class 12 Aggregate", bg="light blue")
l36.config(font=("Aerial", 20,))
l36.grid(row=54, column=0, pady=30)
cben17 = Entry(frame, width=10, textvariable=s, state=DISABLED)
cben17.config(font=("Aeril", 15))
cben17.grid(row=54, column=1, sticky="W")

cb19 = Checkbutton(frame,
                   text="I agree to the terms and conditions and hereby declare to abide by the rules and regulations of the college",
                   bg="light green")
cb19.config(font=("Aerial", 15))
cb19.grid(row=66, column=0, pady=15, columnspan=3)

sub_but = Button(frame, padx=10, bd=7, font=("Helvetica", 10, "bold"), width=15, text="SUBMIT", bg="red",
                 fg="white", command=DatabaseAdd).grid(row=67, column=0, padx=100)
# Thanks
l16p = Label(frame, text="Thank", bg="light blue")
l16p.config(font=("Aerial", 20))
l16p.grid(row=400, column=750)
# You
l15 = Label(frame, text="You", bg="light blue")
l15.config(font=("Aerial", 20))
l15.grid(row=400, column=800)
# So much
l15 = Label(frame, text="So Much Visit Again", bg="light blue")
l15.config(font=("Aerial", 20))
l15.grid(row=400, column=850)
root.mainloop()


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 10:23:50 2017

@author: lcp5y3
"""

#----------------------------------------------------------------------------
#   file of function which allow to decode data from uart protocole
#   CRUBS_ll
#-----------------------------------------------------------------------------

#----------------------short--------------------------------------------------
distance=[]
angle=[]
temps=[]
cmd_d=[]
cmd_a=[]
theta=[]
#--------------------------float----------------------------------------------
p_dist=0
i_dist=0
d_dist=0

p_ang=0
i_ang=0
d_ang=0
#------------var de sauvegarde de data -------------------------------------
char_table=[0,1,2,3,4,5,6]
int_table=[0,1,2,distance,angle,cmd_d]
short_table=[0,1,2,3,4,5,cmd_a]
flt_table=[0,1,2,3,p_dist,i_dist,d_dist,7,8,9,p_ang,i_ang,d_ang,theta]

#----------------var de paramètrage------------------------------------------
pdt = 0.01      #pas de temps pour l'affichage du temps
b_int = 32
b_char = 8
b_short = 16
b_flt = 32

ch_mask = 0
sht_mask = 1
int_mask = 2
flt_mask = 3

byte_mask = 255
flt_coef = 1000
seuil_max = 1000000000

size_int = 6
size_char = 3
size_short = 4

start_b = 252
stop_b = 244
#-----------------------------------------------------------------------------
# function two's complement
#-----------------------------------------------------------------------------
def complementA2(variable, nb_bit):
    return -1*((variable-1)^(pow(2,nb_bit)-1))          # var-1 xor 2puissanceX -1
    #return variable-1-pow(2,nb_bit)
#transforme char en byte read like int
def char_to_byte(trame):
    for i in range(len(trame)):
        trame[i]=ord(trame[i])
#    return trame

def checksum(data):
    return(sum(data[:]) & byte_mask)

def base_temps(longueur):
    bt = 0.01
    temps[:]=[]
    for i in range(longueur):
        temps.append(bt*(1+i))

def clear():
        distance[:]=[]
        temps[:]=[]
        angle[:]=[]
        cmd_d[:]=[]
        theta[:]=[]
#-----------------------------------------------------------------------------
#reading functions
#-----------------------------------------------------------------------------

#read ca char with the protocole CRUBS_ll-------------------------------------
def read_char(trame,adresse,signe): # reste le signe a regardr ici
        char_table[adresse].append(trame[1])

#read an short with the protocole CRUBS_ll-------------------------------------
def read_sht(trame,adresse,signe):
        resultat =0
        for i in range(len(trame)):
                resultat = resultat <<8
                resultat += trame[i]
        #print("DEBUG: short signe ",signe," resultat: ",resultat)
        if(signe == 0):
            short_table[adresse].append(resultat)
        else:
            short_table[adresse].append(complementA2(resultat, b_short))

        #print("DEBUG:  valeur ",short_table[adresse][-1],"|| adresse: ",adresse)
#read an int with the protocole CRUBS_ll--------------------------------------
def read_int(trame,adresse,signe):
        resultat = 0
        for i in range(len(trame)):
            resultat = resultat <<8
            resultat += trame[i]
        if(signe == 0):
            int_table[adresse].append(resultat)
        else:
            int_table[adresse].append(complementA2(resultat, b_int))

#read an int with the protocole CRUBS_ll--------------------------------------
def read_flt(data,adresse,signe):
        resultat = 0
        #print("DEBUG: valeur de la trame dans le read flt ",data)
        for i in range(len(data)):
            resultat = resultat <<8
            resultat += data[i]
        #print("DEBUG: float resultat ", resultat)
        if(signe == 0):
            flt_table[adresse].append(resultat/flt_coef)
        else:
            flt_table[adresse].append(complementA2(resultat, b_flt)/flt_coef)
        #print("DEBUG:  valeur ",flt_table[adresse][-1],"|| adresse: ",adresse)

#function to detect the end of a trame---------------------------------------
def eot(trame):
    if(trame == stop_b):
        return True
    else:
        return False

def eo_transmit(trame):
    if(len(trame)>=3):
        if(sum(trame[-3:])==311 and trame[-1]==100):
            print("fin de transmission")
            return True
    else:
        return False
#-----------------------------------------------------------------------------
#     sending function
#-----------------------------------------------------------------------------
#function to add the start/stop byte
def ss_byte(data):
    data.append(stop_b)
    data.insert(0,start_b)

# function to send a char-----------------------------------------------------
def send_char(data,adresse,char_data):
    char_data[:]=[] #on nettoie
    #ajout du bit adresse signe type
    char_data.append(adresse)
    if(data<0):
        char_data[0]=(char_data[0]<<1)+1
        data = complementA2(data,b_char)
    else:
        char_data[0]=char_data[0]<<1
    char_data[0]=(char_data[0]<<2)+ch_mask
    #envoi
    char_data.append(data)
    char_data.append(checksum(char_data[:]))
    ss_byte(char_data) #ajout start/stop byte

# function to send a short----------------------------------------------------
def send_sht(data,adresse,sht_data):
    sht_data[:]=[]
    #prepa du bit d'adresse
    sht_data.append(adresse)
    if(data<0):
        sht_data[0]=(sht_data[0]<<1)+1
        data = complementA2(data,b_short)
        print(hex(data))                  #debug
    else:
        sht_data[0] = sht_data[0]<<1
    sht_data[0]=(sht_data[0]<<2)+sht_mask
#prepa des datas
    sht_data.append(data >> 8)
    sht_data.append(data & byte_mask)
    sht_data.append(checksum(sht_data[:]))
#prepa du byte de start
    ss_byte(sht_data)

#function to send an int------------------------------------------------------
def send_int(data,adresse,int_data):
    int_data[:]=[] #on nettoie
    #ajout du bit adresse signe type
    int_data.append(adresse)
    if(data<0):
        int_data[0]=(int_data[0]<<1)+1
        data = complementA2(data,b_int)
    else:
        int_data[0]=int_data[0]<<1
    int_data[0]=(int_data[0]<<2)+int_mask
    #envoi
    int_data.append(data >> 24)
    int_data.append((data >> 16) & byte_mask)
    int_data.append((data >> 8) & byte_mask)
    int_data.append((data & 15) & byte_mask)
    int_data.append(checksum(int_data[:]))
    ss_byte(int_data) #ajout start/stop byte

#function to send a float-----------------------------------------------------
def send_flt(data,adresse,flt_data):
    flt_data[:]=[]
        #ajout du bit adresse signe type
    flt_data.append(adresse)
    if(data<0):
        flt_data[0]=(flt_data[0]<<1)+1
        data = complementA2(data,b_flt)
    else:
        flt_data[0]=flt_data[0]<<1
    flt_data[0]=(flt_data[0]<<2)+flt_mask
    #adaptation des données
    data=int(data*flt_coef)
    flt_data.append(data >> 24)
    flt_data.append((data >> 16) & byte_mask)
    flt_data.append((data >> 8) & byte_mask)
    flt_data.append((data & 15) & byte_mask)
    flt_data.append(checksum(flt_data[:]))
    ss_byte(flt_data) #ajout start/stop byte

#debug function---------------------------------------------------------------
def print_list(liste):
    for i in range(len(liste)):
        print(bin(liste[i]))


import copy
import numpy as np
import random
from collections import defaultdict
from torch.utils.data.sampler import Sampler

class RandomClassSampler(Sampler):
    """Randomly samples N classes each with K instances to
    form a minibatch of size N*K.

    Modified from https://github.com/KaiyangZhou/deep-person-reid.

    Args:
        data_source (list): list of Datums.
        batch_size (int): batch size.
        n_ins (int): number of instances per class to sample in a minibatch.
    """

    def __init__(self, data_source, batch_size, n_ins):
        if batch_size < n_ins:
            raise ValueError(
                "batch_size={} must be no less "
                "than n_ins={}".format(batch_size, n_ins)
            )

        self.data_source = data_source
        self.batch_size = batch_size
        self.n_ins = n_ins
        self.ncls_per_batch = self.batch_size // self.n_ins
        self.index_dic = defaultdict(list)
        for index, item in enumerate(data_source):
            self.index_dic[item.label].append(index)
        self.labels = list(self.index_dic.keys())
        assert len(self.labels) >= self.ncls_per_batch

        # estimate number of images in an epoch
        self.length = len(list(self.__iter__()))

    def __iter__(self):
        batch_idxs_dict = defaultdict(list)

        for label in self.labels:
            idxs = copy.deepcopy(self.index_dic[label])
            if len(idxs) < self.n_ins:
                idxs = np.random.choice(idxs, size=self.n_ins, replace=True)
            random.shuffle(idxs)
            batch_idxs = []
            for idx in idxs:
                batch_idxs.append(idx)
                if len(batch_idxs) == self.n_ins:
                    batch_idxs_dict[label].append(batch_idxs)
                    batch_idxs = []

        avai_labels = copy.deepcopy(self.labels)
        final_idxs = []

        while len(avai_labels) >= self.ncls_per_batch:
            selected_labels = random.sample(avai_labels, self.ncls_per_batch)
            for label in selected_labels:
                batch_idxs = batch_idxs_dict[label].pop(0)
                final_idxs.extend(batch_idxs)
                if len(batch_idxs_dict[label]) == 0:
                    avai_labels.remove(label)

        return iter(final_idxs)

    def __len__(self):
        return self.length


# coding=utf-8
import matplotlib.pyplot as plt
from gensim.models import Word2Vec
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import roc_curve, auc

import data_processing
import globe
import word2vec_gensim_train

# 读入数据
# pos_file_path = '/home/zhangxin/work/workplace_python/DeepNaturalLanguageProcessing/DeepNLP/data/test3.txt'
# neg_file_path = '/home/zhangxin/work/workplace_python/DeepNaturalLanguageProcessing/DeepNLP/data/test2.txt'
pos_file_path = '/Users/li/workshop/DataSet/sentiment/train/result_pos.txt'
neg_file_path = '/Users/li/workshop/DataSet/sentiment/train/result_neg.txt'

tmp = data_processing.read_data(pos_file_path, neg_file_path)
res = data_processing.data_split(tmp[0], tmp[1])
x_train = res[0]
x_test = res[1]
label_train = res[2]
label_test = res[3]
x_train = data_processing.text_clean(x_train)
x_test = data_processing.text_clean(x_test)

# 生成文本向量
n_dim = globe.n_dim
# model_path = '/home/zhangxin/work/workplace_python/DeepNaturalLanguageProcessing/DeepNLP/word2vecmodel/mymodel'
model_path = globe.model_path

word2vec_model = Word2Vec.load(model_path)
vecs = word2vec_gensim_train.text_vecs(x_train, x_test, n_dim, word2vec_model)
train_vecs = vecs[0]
test_vecs = vecs[1]

# 分类训练
lr = SGDClassifier(loss='log', penalty='l1')
lr.fit(train_vecs, label_train)

print('Test Accuracy: %.2f' % lr.score(test_vecs, label_test))

pred_probas = lr.predict_proba(test_vecs)[:, 1]

fpr, tpr, _ = roc_curve(label_test, pred_probas)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, label='area = %.2f' %roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.legend(loc='lower right')

plt.show()


class Solution:
    def read(self, buf, n):
        temp = [''] * 4 ##新开一个空间，让buf4往里面读数
        index = 0
        while True:
            count = read4(temp)
            size = min(count, n - index) # 看还够不够都放进buf里取的
            for i in range(size): #对于读进来的数把buf里存入buf4里的数
                buf[index] = temp[i]
                index += 1  #这里的idx记的是在我自己的内存里存到第几位了
            if index == n or count < 4: # 如果file读完了, 或者到达buf到头了，就return
                return index


#Your task is to complete this function
#Your should return the required output
class Solution:
    def maxLen(self, n, arr):
        #Code here
        curr_sum, max_sum = 0, 0
        prefix_sum = {}
        for (i, curr) in enumerate(arr):
            curr_sum += curr
            if not curr_sum:
                max_sum = i + 1
            else:
                if curr_sum in prefix_sum:
                    max_sum = max(max_sum, i - prefix_sum[curr_sum])
                else:
                    prefix_sum[curr_sum] = i
        return max_sum
#{
 # Driver Code Starts
if __name__=='__main__':
    t= int(input())
    for i in range(t):
        n = int(input())
        arr = list(map(int, input().strip().split()))
        ob = Solution()
        print(ob.maxLen(n ,arr))
# Contributed by: Harshit Sidhwa
# } Driver Code Ends


from .helpers import flattenToSet, console
from .nodes import Nodes
from .locality import Locality
from .nodefeature import NodeFeatures
from .edgefeature import EdgeFeatures
from .computed import Computeds
from .text import Text
from ..search.search import Search

API_REFS = dict(
    AllComputeds=("Computed", "computedall", "computed-data"),
    AllEdges=("Features", "edgeall", "edge-features"),
    AllFeatures=("Features", "nodeall", "node-features"),
    C=("Computed", "computed", "computed-data"),
    Call=("Computed", "computedall", "computed-data"),
    Computed=("Computed", "computed", "computed-data"),
    ComputedString=("Computed", "computedstr", "computed-data"),
    Cs=("Computed", "computedstr", "computed-data"),
    E=("Features", "edge", "edge-features"),
    Eall=("Features", "edgeall", "edge-features"),
    Edge=("Features", "edge", "edge-features"),
    EdgeString=("Features", "edgestr", "edge-features"),
    Es=("Features", "edgestr", "edge-features"),
    F=("Features", "node", "node-features"),
    Fall=("Features", "nodeall", "node-features"),
    Feature=("Features", "node", "node-features"),
    FeatureString=("Features", "nodestr", "node-features"),
    Fs=("Features", "nodestr", "node-features"),
    L=("Locality", "locality", "locality"),
    Locality=("Locality", "locality", "locality"),
    N=("Nodes", "nodes", "navigating-nodes"),
    Nodes=("Nodes", "nodes", "navigating-nodes"),
    S=("Search", "search", "search"),
    Search=("Search", "search", "search"),
    T=("Text", "text", "text"),
    TF=("Fabric", "fabric", "loading"),
    Text=("Text", "text", "text"),
)

class Api(object):
    def __init__(self, TF):
        self.TF = TF
        self.ignored = tuple(sorted(TF.featuresIgnored))
        TF.ignored = self.ignored

        self.F = NodeFeatures()
        self.Feature = self.F
        self.E = EdgeFeatures()
        self.Edge = self.E
        self.C = Computeds()
        self.Computed = self.C
        tmObj = TF.tmObj
        TF.silentOn = tmObj.silentOn
        TF.silentOff = tmObj.silentOff
        TF.isSilent = tmObj.isSilent
        TF.setSilent = tmObj.setSilent
        TF.info = tmObj.info
        TF.warning = tmObj.warning
        TF.error = tmObj.error
        TF.cache = tmObj.cache
        TF.reset = tmObj.reset
        TF.indent = tmObj.indent
        TF.loadLog = tmObj.cache

        TF.ensureLoaded = self.ensureLoaded
        TF.makeAvailableIn = self.makeAvailableIn

        setattr(self, "FeatureString", self.Fs)
        setattr(self, "EdgeString", self.Es)
        setattr(self, "ComputedString", self.Cs)
        setattr(self, "AllFeatures", self.Fall)
        setattr(self, "AllEdges", self.Eall)
        setattr(self, "AllComputeds", self.Call)

    def Fs(self, fName):

        if not hasattr(self.F, fName):
            self.TF.error(f'Node feature "{fName}" not loaded')
            return None
        return getattr(self.F, fName)

    def Es(self, fName):

        if not hasattr(self.E, fName):
            self.TF.error(f'Edge feature "{fName}" not loaded')
            return None
        return getattr(self.E, fName)

    def Cs(self, fName):

        if not hasattr(self.C, fName):
            self.TF.error(f'Computed feature "{fName}" not loaded')
            return None
        return getattr(self.C, fName)

    def Fall(self):

        return sorted(x[0] for x in self.F.__dict__.items())

    def Eall(self):

        return sorted(x[0] for x in self.E.__dict__.items())

    def Call(self):

        return sorted(x[0] for x in self.C.__dict__.items())

    def makeAvailableIn(self, scope):

        for member in dir(self):
            if "_" not in member and member[0].isupper():
                scope[member] = getattr(self, member)
                if member not in API_REFS:
                    console(f'WARNING: API member "{member}" not documented')

        grouped = {}
        for (member, (head, sub, ref)) in API_REFS.items():
            grouped.setdefault(ref, {}).setdefault((head, sub), []).append(member)

        # grouped
        # node-features=>(Features, node)=>[F, ...]

        docs = []
        for (ref, groups) in sorted(grouped.items()):
            chunks = []
            for ((head, sub), members) in sorted(groups.items()):
                chunks.append(" ".join(sorted(members, key=lambda x: (len(x), x))))
            docs.append((head, ref, tuple(chunks)))
        return docs

    # docs
    # (Features, node-features, ('F ...', ...))

    def ensureLoaded(self, features):

        F = self.F
        E = self.E
        TF = self.TF
        warning = TF.warning

        needToLoad = set()
        loadedFeatures = set()

        for fName in sorted(flattenToSet(features)):
            fObj = TF.features.get(fName, None)
            if not fObj:
                warning(f'Cannot load feature "{fName}": not in dataset')
                continue
            if fObj.dataLoaded and (hasattr(F, fName) or hasattr(E, fName)):
                loadedFeatures.add(fName)
            else:
                needToLoad.add(fName)
        if len(needToLoad):
            TF.load(
                needToLoad, add=True, silent="deep",
            )
            loadedFeatures |= needToLoad
        return loadedFeatures

def addOtype(api):
    setattr(api.F.otype, "all", tuple(o[0] for o in api.C.levels.data))
    setattr(
        api.F.otype, "support", dict(((o[0], (o[2], o[3])) for o in api.C.levels.data))
    )

def addLocality(api):
    api.L = Locality(api)
    api.Locality = api.L

def addNodes(api):
    api.N = Nodes(api)
    api.Nodes = api.N

def addText(api):
    api.T = Text(api)
    api.Text = api.T

def addSearch(api, silent):
    api.S = Search(api, silent)
    api.Search = api.S


#name introduction
"""
Topic: Programming Logic and Design
Author: Viernes, Michael
Submitted to: Mr. Madrigalejos
"""

"""
# Getter functions (NOT USED FOR THE MOMENT FOR HOMEWORK 04).
def getName():
    name = input("Your name: ")
    return name

def getAge():
    age = input("Your age: ")
    return age

def getAddress():
    address = input("Your address: ")
    return address
"""

def getInfo(): # gets name, age, address.
    # Declares info local variables.
    name, age, address = "", "", ""
    name = input("Your name: ")
    age = input("Your age: ")
    address = input("Your address: ")
    return name, age, address # end getInfo()

def printInfo(user_name, user_age, user_address):
    print(f"\n\nHi, my name is {user_name}. I am {user_age} years old and I live in {user_address}.\n")

"""
def decorator(decorFunc): # This will be added at some point.
    def consoleDecorator():
        return
    return consoleDecorator
"""

def main(): # REDEFINED main program.
    """
    Creating array. # THE FOLLOWING CODE WILL NOT BE USED!
    #info = []
        # THE FOLLOWING CODE WILL NOT BE USED!
        #info.append(getName())
        #info.append(getAge())
        #info.append(getAddress())
    """

    print("\n--------------------")
    print("\tIntroduction")
    print("--------------------")
    print("\tRequesting Personal Information: \n\n")

    m_name ,m_age ,m_address = getInfo()
    printInfo(m_name, m_age, m_address)

while True:
    quit = "None"
    main() # Calls main program.
    quit = input("Press Q to quit: ")
    if str(quit).upper() == "Q": # Experimented on str's upper func.

        # Experimented on multi line prints.
        print(
        """Thank you for your participation.\n"""
        )

        break


import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import dash_bootstrap_components as dbc

from app import app
from apps import general_functions as gf
#from apps_igf import func_gral

main_layout = dbc.Container([
    dbc.Row([
        #Controles
        dbc.Col([
            html.P("Selecciona un RFC:"),
            dcc.Dropdown(
                id="gral_drp_0",
                options=[{"label": "RFC001", "value":"RFC001"},
                        {"label": "RFC002", "value":"RFC002"},
                        {"label": "RFC003", "value":"RFC003"}]
            ),
            html.Br(),
            html.P("Año:", className="control_label"),
            dcc.Dropdown(
                id="gral_drp_1",
                options=[{"label": "2020", "value":"2020"},
                        {"label": "2019", "value":"2019"},
                        {"label": "2018", "value":"2018"}],
            ),
            html.Br(),
            html.P("Rango de meses:", className="control_label"),
            dcc.RangeSlider(
                id="gral_drp_2",
                min=1,
                max=12,
                value=[1, 12],
            ),
            html.Br(),
            html.P("Tipo de Documento:", className="control_label"),
            dcc.Dropdown(
                id="gral_drp_3",
                options=[{"label": "Pago", "value":"Pago"},
                        {"label": "Egreso", "value":"Egreso"},
                        {"label": "Ingreso", "value":"Ingreso"}],
            ),
            html.Br(),
            html.P("Tipo de Moneda:", className="control_label"),
            dcc.RadioItems(
                id="gral_drp_4",
                options=[
                    {"label": "Pesos MXN  ", "value": "MXN"},
                    {"label": "Dolares USD  ", "value": "USD"},],
                    labelStyle={"display": "inline-block"},
            ),
        ],className='col-md-3', style={'border-radius': '5px','background-color': '#f9f9f9'}),
        #Montos
        dbc.Col([
            html.H1("MONTOS", className='text-center'),
            gf.mosaico("#00cc96", "Monto Total Emision", "gral_msc_mon_1"),
            gf.mosaico("#00cc96", "Monto Total Recepcion", "gral_msc_mon_2"),
            html.Div(
            [dcc.Graph(id="gral_grf_mts_1",
                        config=dict(displayModeBar=False))],
            ),
        ],className='col-md-8', width={'offset':1})
    ]),
    html.Br(),
    dbc.Row([
        #Facturas
        dbc.Col([
            html.H1("FACTURAS", className='text-center'),
            gf.mosaico("#00cc96", "Cantidad de Facturas Emitidas", "gral_msc_fac_1"),
            gf.mosaico("#00cc96", "Cantidad de Facturas Recibidas", "gral_msc_fac_2"),
            html.Div(
            [dcc.Graph(id="gral_grf_fac_1",
                        config=dict(displayModeBar=False))],
            ),
        ],className='col-md-8', width={'offset':4})
    ])
],fluid=True)

layout = html.Div([
    html.Div([main_layout]),
])


from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
                        print_function, unicode_literals)

from twitter.common.collections import OrderedSet
from twitter.common.dirutil.fileset import Fileset
from twitter.common.lang import Compatibility

def assert_list(obj, expected_type=Compatibility.string, can_be_none=True, default=(),
    allowable=(list, Fileset, OrderedSet, set, tuple), raise_type=ValueError):
  """
  This function is used to ensure that parameters set by users in BUILD files are of acceptable types.
  :param obj           : the object that may be a list. It will pass if it is of type in allowable.
  :param expected_type : this is the expected type of the returned list contents.
  :param can_be_none   : this defines whether or not the obj can be None. If True, return default.
  :param default       : this is the default to return if can_be_none is True and obj is None.
  :param allowable     : the acceptable types for obj. We do not want to allow any iterable (eg string).
  :param raise_type    : the error to throw if the type is not correct.
  """
  val = obj
  if val is None:
    if can_be_none:
      val = list(default)
    else:
      raise raise_type('Expected an object of acceptable type %s, received None and can_be_none is False' % allowable)

  if [typ for typ in allowable if isinstance(val, typ)]:
    lst = list(val)
    for e in lst:
      if not isinstance(e, expected_type):
        raise raise_type('Expected a list containing values of type %s, instead got a value %s of %s' %
          (expected_type, e, e.__class__))
    return lst
  else:
    raise raise_type('Expected an object of acceptable type %s, received %s instead' % (allowable, val))


import re

def name_score(name):
    total = 0
    for x in name:
        total += ord(x)-ord('A')+1
    return total

name_list = []
for name in open("p022_names.txt").read().split(","):
    name = re.findall("\"(.*)\"",name)[0]
    name_list.append(name)

name_list = sorted(name_list)

i=1
total = 0
for name in name_list:
    total += i*name_score(name)
    i += 1

print(total)


# -*- coding: utf-8 -*-#
'''
# Name:         dnn_regression-keras
# Description:
# Author:       super
# Date:         2020/6/2
'''

from HelperClass2.MnistImageDataReader import *

from keras.models import Sequential
from keras.layers import Dense

import matplotlib.pyplot as plt

import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'

def load_data():
    train_file = "../data/ch09.train.npz"
    test_file = "../data/ch09.test.npz"

    dataReader = DataReader_2_0(train_file, test_file)
    dataReader.ReadData()
    # dr.NormalizeX()
    # dr.NormalizeY(YNormalizationMethod.Regression)
    dataReader.Shuffle()
    dataReader.GenerateValidationSet()

    x_train, y_train = dataReader.XTrain, dataReader.YTrain
    x_test, y_test = dataReader.XTest, dataReader.YTest
    x_val, y_val = dataReader.XDev, dataReader.YDev

    return x_train, y_train, x_test, y_test, x_val, y_val

def build_model():
    model = Sequential()
    model.add(Dense(4, activation='sigmoid', input_shape=(1, )))
    model.add(Dense(1, activation='linear'))
    model.compile(optimizer='Adam',
                  loss='mean_squared_error')
    return model

#画出训练过程中训练和验证的精度与损失
def draw_train_history(history):
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show()

if __name__ == '__main__':
    x_train, y_train, x_test, y_test, x_val, y_val = load_data()
    # print(x_train.shape)
    # print(x_test.shape)
    # print(x_val.shape)

    model = build_model()
    history = model.fit(x_train, y_train, epochs=50, batch_size=10, validation_data=(x_val, y_val))
    draw_train_history(history)

    loss = model.evaluate(x_test, y_test)
    print("test loss: {}".format(loss))

    weights = model.get_weights()
    print("weights: ", weights)


import json
import sys

import aes_functions
import rsa_functions
from exceptions.Exceptions import IncorrectData
from socket_class import SOCKET_SIMPLE_TCP

def receiveAESMessage(s):
    return s.receive(), s.receive(), s.receive()

def checkMessageGCM(key, iv, cif, mac):
    res = aes_functions.decipherAES_GCM(key, iv, cif, mac)
    if res is not False:
        return res
    else:
        print("AIUDAAAA :(")
        print("Corrupted Message")

def sendAESMessage(socket, criptograma, mac, nonce):
    socket.send(criptograma)
    socket.send(mac)
    socket.send(nonce)

def bob_socket(port):
    return SOCKET_SIMPLE_TCP('127.0.0.1', port)

class Bob:
    def __init__(self):
        self.name = "Bob"
        self.port = 5552
        self.PK_BOB = rsa_functions.create_RSAKey()
        self.KBT = aes_functions.create_AESKey()
        self.KPT = rsa_functions.load_RSAKey_Public("TTP.pub")

    def savePK(self):
        return rsa_functions.save_RSAKey_Public("Bob.pub", self.PK_BOB)

if __name__ == '__main__':
    """--STEP 0--"""
    bob = Bob()
    bob.savePK()
    print(bob.PK_BOB.public_key().export_key())

    try:
        socket = bob_socket(bob.port)
        socket.connect()
    except Exception as e:
        sys.exit(f"An error occurred creating the socket with TTP: {e}")

    """--STEP 2--"""
    print("Establishing a connection with TTP...")
    try:
        engineKAT = aes_functions.startAES_GCM(bob.KBT)

        print("Sending data to TTP...")
        message = [bob.name, bob.KBT.hex()]
        json_AT = json.dumps(message)

        print("Message B -> T (decryption): " + json_AT)

        # Encrypt data
        encrypted_message = rsa_functions.cipherRSA_OAEP(json_AT.encode("utf-8"), bob.KPT.public_key())
        encrypted_signature = rsa_functions.signatureRSA_PSS(bob.KBT.hex().encode("utf-8"), bob.PK_BOB)

        # Send encrypted data
        socket.send(encrypted_message)
        socket.send(encrypted_signature)
    except Exception as e:
        socket.close()
        sys.exit(f"An error occurred in step 2: {e}")
    finally:
        print("END STEP 2")
        input("Press any key to continue")

    """--Step 5--"""
    try:
        socket = bob_socket(5555)
        socket.listen()
    except Exception as e:
        sys.exit(f"An error occurred creating the socket with Alice: {e}")

    try:
        print("Waiting for Alice...")
        msg = socket.receive()
        cipher_BT, mac_BT, iv_BT, cif_AB, mc_AB, iv_AB = json.loads(msg)

        decrypted_message = checkMessageGCM(bob.KBT, bytes.fromhex(iv_BT), bytes.fromhex(cipher_BT),
                                            bytes.fromhex(mac_BT))
        TS, KAB = json.loads(decrypted_message.decode('utf-8'))

        KAB = bytearray.fromhex(KAB)

        decrypted_message = checkMessageGCM(KAB, bytes.fromhex(iv_AB), bytes.fromhex(cif_AB),
                                            bytes.fromhex(mc_AB))
        sessionName, aux = json.loads(decrypted_message)

        if sessionName != 'Alice' and aux != TS:
            raise IncorrectData("Possible data modification  during communication")
        else:
            print("Reliable data, continued")
    except Exception as e:
        socket.close()
        sys.exit(f"An error occurred in step 5: {e}")
    finally:
        print("END STEP 5")
        input("Press any key to continue")

    """--Step 6--"""
    try:
        resolution = float(TS) + 1

        engineKAB = aes_functions.startAES_GCM(KAB)
        cif, mac, iv = aes_functions.cipherAES_GCM(engineKAB, str(resolution).encode("utf-8"))
        sendAESMessage(socket, cif, mac, iv)
    except Exception as e:
        socket.close()
        sys.exit(f"An error occurred in step 6: {e}")
    finally:
        print("END STEP 6")
        input("Press any key to continue")

    """--Step 7--"""
    try:
        print("Waiting for Alice")
        cif, mac, iv = receiveAESMessage(socket)
        textoClaro = checkMessageGCM(KAB, iv, cif, mac)
        msg = textoClaro.decode("utf-8")
        print("Message ->" + msg)
    except Exception as e:
        socket.close()
        sys.exit(f"An error occurred in step 7: {e}")
    finally:
        print("END STEP 7")
        input("Press any key to continue")

    """--Step 8--"""
    try:
        msg = "Hello Word!"
        engineKAB = aes_functions.startAES_GCM(KAB)
        cif, mac, iv = aes_functions.cipherAES_GCM(engineKAB, msg.encode("utf-8"))
        sendAESMessage(socket, cif, mac, iv)
    except Exception as e:
        socket.close()
        sys.exit(f"An error occurred in step 8: {e}")
    finally:
        print("END STEP 8")


import torch.nn as nn
import torch
import torch.optim as optim
import numpy as np
from torch.utils.data import DataLoader
from prior_learning.toy_env.toyloader import toyenv_Dataset
size = 8
seq_len = 32
categories = 16
batch_size = 128
feature_dim = 16
features = np.random.random((categories, feature_dim))

train_loader = DataLoader(toyenv_Dataset(features, size, seq_len, categories), batch_size = batch_size, num_workers= 40, shuffle = True)
net = nn.Sequential(
    nn.Linear(feature_dim, 32),
    nn.ReLU(),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Linear(16, 1)
    )

net.cuda()
criteria = nn.L1Loss()
optimizer = optim.Adam(net.parameters(), lr=1e-3)
reg_sum = 0
loss_sum = 0

for i, data in enumerate(train_loader):
    if i == 29999:
        optimizer = optim.Adam(net.parameters(), lr=1e-4)

    blocks, masks, rewards = [d.cuda() for d in data]
    blocks = blocks.view(batch_size * seq_len, feature_dim)
    rewards_hat = net(blocks)
    rewards_hat = rewards_hat.view(batch_size, seq_len)
    reg = torch.mean(torch.abs(rewards_hat)) * 0.01
    rewards_hat = torch.sum(rewards_hat * masks, 1)
    loss = criteria(rewards_hat, rewards) + reg

    loss_sum += loss.item()
    reg_sum += reg.item()

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if i % 2000 == 1999:
        print('[{}] loss: {}, reg: {}'.format(i + 1, loss_sum / 100, reg_sum / 100))

        loss_sum = 0
        reg_sum = 0

    if i % 10000 == 9999:
        result = net(torch.from_numpy(features).float().cuda()).flatten().detach().cpu().numpy()
        print('=' * 40)
        print(result)
        print('='*40)


#11238. Fibo
"""

피보나치 수와 최대공약수와 유사한 문제.

gcd(a,b)%M= gcd(a%M, b%M)이 성립하는진 사실 잘 모르겠지만..
그러지 않고선 메모리 초과가 날 것 같다.

gcd(Fib(m),Fib(n))=Fib(gcd(m,n))이라고 한다.

이에 대한 증명은 구글링을 통해 공부해보자. (재밌어보인다)

"""

big_num=1000000007

#행렬 a,b가 주어졌을때 그 행렬곱을 구하는 함수
def matmul(a,b):
    row=len(a); common=len(b); column=len(b[0])
    c=[[0]*column for _ in range(row)]
    for i in range(row):
        for k in range(column):
            for j in range(common):
                c[i][k]+= a[i][j] * b[j][k]
            c[i][k]%=big_num
    return c

#분할정복을 통해 행렬의 K제곱을 구하는 함수
def powerMatrix(N,K):
    if K==1:
        return [[ ele %big_num for ele in row] for row in N ]
    else:
        if K%2==0:
            partial=powerMatrix(N,K//2)
            result=matmul(partial,partial)
            return result
        else:
            partial=powerMatrix(N,(K-1)//2)
            tmp=matmul(partial,partial)
            return matmul(tmp,N)

#Operation start
import sys
import math
input=sys.stdin.readline
T=int(input().rstrip())
for _ in range(T):
    n,m=map(int,input().rstrip().split())
    result=math.gcd(n,m)

    initial=[[0],[1]]
    matrix=[[0,1],[1,1]]

    #fib(N),fib(N+1)이 각각 있을 것

    if result==1: final_matrix=initial
    else: final_matrix=matmul(powerMatrix(matrix,result-1),initial)

    final_result=final_matrix[-1][-1]
    print(final_result)


from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.registerPage, name='register'),
    path('login/', views.loginPage, name='login'),
    path('logout/', views.logoutUser, name='logout'),
    path('event_create/', views.event_create, name='event_create'),
    path('event_manager/', views.event_manager, name='event_manager'),
    path('event_update/<str:pk>/', views.event_update, name='event_update'),
    path('event_delete/<str:pk>/', views.event_delete, name='event_delete'),
]


from ..utils import Object

class CancelUploadFile(Object):
    """
    Stops the uploading of a file. Supported only for files uploaded by using uploadFile. For other files the behavior is undefined

    Attributes:
        ID (:obj:`str`): ``CancelUploadFile``

    Args:
        file_id (:obj:`int`):
            Identifier of the file to stop uploading

    Returns:
        Ok

    Raises:
        :class:`telegram.Error`
    """
    ID = "cancelUploadFile"

    def __init__(self, file_id, extra=None, **kwargs):
        self.extra = extra
        self.file_id = file_id  # int

    @staticmethod
    def read(q: dict, *args) -> "CancelUploadFile":
        file_id = q.get('file_id')
        return CancelUploadFile(file_id)


#!/usr/bin/env python

import config
import json
import requests
import sys

"""
Copyright (c) 2020, Cisco Systems, Inc. and/or its affiliates
Creates webhooks in a repo upon release using
GitHub API v3 POST /repos/:owner/:repo/hooks
Requires a file with repo names, one per line,
and a personal access token with access to each repo.
Usage:
python create_webhook.py devnet_repos.txt
"""

def get_webhook(gh_orgname, repo_name, gh_username, gh_api_key):
    api_uri = "https://api.github.com/repos/{}/{}/hooks".format(gh_orgname, repo_name)
    print(api_uri)
    session = requests.Session()
    session.auth = (gh_username, gh_api_key)
    try:
        gethooks = session.get(api_uri)
        print(json.dumps(gethooks.json(), indent=4))

    except:
        print(gethooks.status_code)
        print("Response text: {}".format(gethooks.text))

def post_create_webhook(gh_orgname, repo_name, gh_username, gh_api_key, gh_webhook_url, gh_secret):
    api_uri = "https://api.github.com/repos/{}/{}/hooks".format(gh_orgname, repo_name)
    print("API endpoint: {}".format(api_uri))
    print("Username: {}".format(gh_username))
    print("API Key: {}".format(gh_api_key))
    print("Secret for payload: {}".format(gh_secret))

    try:
        headers = {'User-Agent': '{}'.format(gh_username),
                   'Content-Type': 'application/json',
                   'Authorization': 'token {}'.format(gh_api_key)
        }
        print(headers)
        payload = {
               'name': 'web',
               'active': True,
               'events': ['release'],
               'config': {
                           'url': '{}'.format(gh_webhook_url),
                           'content_type': 'json',
                           'secret': '{}'.format(gh_secret),
                           'insecure_ssl': '0'
                           }
               }
        session = requests.Session()
        makehooks = requests.Request('POST', api_uri, json=payload, headers=headers).prepare()
        resp = session.send(makehooks)
        print(resp.status_code)
        print(json.dumps(resp.json(), indent=4))
    except:
        print(resp.status_code)
        print("Response text: {}".format(resp.text))
        sys.exit()

def main(filename):
    if not len(args) == 1:
        print("Enter the filename for the file that contains the list of repos, one per line")
        return
    filename = args[0]
    # Read data in from a text list of all LL repo names
    repolist = []
    with open(filename) as f:
        repolist = f.readlines()
        for repo in repolist:
            repo_name = repo.rstrip('\n')
            print("Working on this repo: " + repo_name)
            #getresponse = get_webhook(config.gh_orgname, repo_name, config.gh_username, config.gh_api_key)
            postresponse = post_create_webhook(config.gh_orgname, repo_name, config.gh_username, config.gh_api_key, config.gh_webhook_url, config.gh_secret)
if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))


import forecast
import send_sms
from datetime import datetime

# Since the api call is made at 6:00 AM, hourly_forecast[0] is 6 AM
def main():
    startTimes = [8, 8, 8, 8, 8]
    endTimes = [18, 16, 18, 18, 10]
    date = datetime.today()
    dayOfWeek = date.weekday()
    message = ""
    phone_number = "+19257877379"

    hourly_forecast = forecast.get_hourly_forecast("CA", "Goleta")

    for i in range(5):
        if (dayOfWeek == i):
            minTemp = int(hourly_forecast[startTimes[dayOfWeek] - 6]['temp']['english'])
            maxTemp = int(hourly_forecast[startTimes[dayOfWeek] - 6]['temp']['english'])
            minTempTime = startTimes[dayOfWeek]
            maxTempTime = endTimes[dayOfWeek]

            for j in range(startTimes[dayOfWeek] - 6, endTimes[dayOfWeek] - 5):
                if ("Rain" in hourly_forecast[j]['condition']):
                    message += "Rain forecasted at " + str(j % 12) + ":00. "
                if (int(hourly_forecast[j]['temp']['english']) < minTemp):
                    minTemp = int(hourly_forecast[j]['temp']['english'])
                    minTempTime = j + 6
                if (int(hourly_forecast[j]['temp']['english']) > maxTemp):
                    maxTemp = int(hourly_forecast[j]['temp']['english'])
                    maxTempTime = j + 6

    message += "Min temp today is " + str(minTemp) + " at " \
            + str(minTempTime) + ":00. "
    message += "Max temp today is " + str(maxTemp) + " at " \
            + str(maxTempTime) + ":00. "
    #print(message)
    send_sms.send_message(phone_number, message)
    # checked hours should depend on day of the week

if __name__ == '__main__':
    main()


from django.http import JsonResponse
from django.views.generic import View
from .models import Scraper
from .validators import currency_serializer, get_valid_data

class ScraperAPI(View):

    def get(self, *args, **kwargs):

        currencies = Scraper.objects.all()
        data = {"scrapers": list(map(currency_serializer, currencies))}

        return JsonResponse(data)

    def post(self, *args, **kwargs):

        data, is_valid = get_valid_data('POST', self.request.body)

        if not is_valid:
            return JsonResponse(data, status=400)

        if Scraper.objects.filter(currency=data['currency']).count() != 0:
            return JsonResponse({"error": "This currency already exists"}, status=400)

        scraper = Scraper.objects.create(currency=data['currency'], frequency=data['frequency'])
        scraper.values.create(value=0)
        data = {
            "id"        : scraper.id,
            "created_at": scraper.create_at,
            "currency"  : scraper.currency,
            "frequency" : scraper.frequency
        }

        return JsonResponse(data)

    def put(self, *args, **kwargs):
        data, is_valid = get_valid_data('PUT', self.request.body)

        if not is_valid:
            return JsonResponse(data, status=400)

        if Scraper.objects.filter(pk=data['id']).count() == 0:
            return JsonResponse({"error": "This Scraper not exists"}, status=400)

        Scraper.objects.filter(pk=int(data['id'])).update(frequency=int(data['frequency']))

        data = {"msg": "Scraper updated"}
        return JsonResponse(data)

    def delete(self, *args, **kwargs):
        data, is_valid = get_valid_data('DELETE', self.request.body)

        if not is_valid:
            return JsonResponse(data, status=400)

        if Scraper.objects.filter(pk=data['id']).count() == 0:
            return JsonResponse({"error": "This Scraper not exists"}, status=400)

        Scraper.objects.filter(pk=data['id']).delete()
        data = {"msg": "Scraper deleted"}
        return JsonResponse(data)


from sys import stdin
input = stdin.readline

moves = [[1, 0], [0, 1], [1, 1], [-1, 1]]
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for _ in range(5):
    r, c = [int(x) for x in input().split()]
    grid = [input()[:-1] for _ in range(r)]
    words = set()
    for _ in range(int(input())):
        before = input()[:-1]
        after = ""
        for i in before:
            if i in alphabet:
                after += i
        words.add(after)
    visited = set()
    for a in range(r):
        for b in range(c):
            for move in moves:
                path = set()
                word = ""
                x, y = a, b
                while True:
                    if 0 <= x < r and 0 <= y < c:
                        path.add((x, y))
                        word += grid[x][y]
                        if word in words or word[::-1] in words:
                            visited = visited.union(path)
                            break
                        x += move[0]
                        y += move[1]
                    else:
                        break
    sentence = ""
    for i in range(r):
        for j in range(c):
            if (i, j) not in visited:
                sentence += grid[i][j]
    print(sentence)


from django import forms
from django.core.exceptions import ValidationError
from arcana_app.models import Driver, Truck, Trailer, Insurance, Freight

class DateInput(forms.DateInput):
    input_type = 'date'

class TimeInput(forms.TimeInput):
    input_type = 'time'

# class CheckboxInput(forms.CheckboxInput):
#     input_type = 'checkbox'

class AddDriverForm(forms.ModelForm):
    class Meta:
        model = Driver
        fields = '__all__'
        widgets = {
            'birth_date': DateInput(),
        }

    def __init__(self, *args, **kwargs):
        super(AddDriverForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

class AddTruckForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AddTruckForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = Truck
        fields = '__all__'
        widgets = {
            'begin_MOT': DateInput(),
            'expire_MOT': DateInput(),

        }

        # widgets = {
        #     'has_actual_MOT': forms.CheckboxInput(
        #         attrs={'class': 'required checkbox form-select', 'disabled': 'disabled or true'}),
        # }

class AddTrailerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AddTrailerForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = Trailer
        fields = '__all__'
        widgets = {
            'begin_MOT': DateInput(),
            'expire_MOT': DateInput(),
        }

class AddInsuranceForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AddInsuranceForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = Insurance
        fields = '__all__'

    def clean(self):
        data = super().clean()
        if not data['begin_date'] <= data['end_date']:
            raise ValidationError("Begin date can't be earlier than end date!")
        return data

class AddFreightForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AddFreightForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = Freight
        fields = '__all__'
        widgets = {
            'date_of_loading': DateInput(),
            'date_of_unloading': DateInput(),
            'hour_of_loading': TimeInput(),
            'hour_of_unloading': TimeInput(),
        }