import time
from datetime import datetime
from tkinter import *
from tkinter import ttk
from PIL import Image
from PIL import ImageTk
from tkinter.filedialog import askopenfilename
import socket
import os
import subprocess
import sys

#******************************************************** File Creation *************************************************************************
f= open("logs.txt","a+")
f.close()

#******************************************************** File Creation *************************************************************************
dirName='Received'
if not os.path.exists(dirName):
        os.mkdir(dirName)
        folders = ['songs', 'videos', 'documents','photos']
        for folder in folders:
                os.mkdir(os.path.join(dirName, folder))
else:
        pass

#******************************************************** Booting Animation *************************************************************************
root = Tk()
root.geometry('900x500')
root.iconbitmap('icons/icon.ico')
root.title("PyShare")
imagelist = []
for i in range(1,41):
        a="icons/"+str(i)+".png"
        imagelist+=[a]

# extract width and height info
photo = PhotoImage(file=imagelist[0])
width = photo.width()
height = photo.height()
canvas = Canvas(width=width, height=height)
canvas.pack()

# create a list of image objects
giflist = []
for imagefile in imagelist:
        photo = PhotoImage(file=imagefile)
        giflist.append(photo)

# loop through the gif image objects for a while
for k in range(0, 1):
        for gif in giflist:
                canvas.delete(ALL)
                canvas.create_image(0,0,anchor=NW, image=gif)
                canvas.update()
                time.sleep(0.1)
time.sleep(2)
root.destroy()
root.mainloop()

#************************************************************** File Size ********************************************************************

def convert_bytes(num):
        for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
                if num < 1024.0:
                        return "%3.1f %s" % (num, x)
                num /= 1024.0

def file_size(filename):
        if os.path.isfile(filename):
                file_info = os.stat(filename)
                return convert_bytes(file_info.st_size)

#*************************************************************** IP encoding ******************************************************************
alpha = "1234567890."
def encrypt(original, key="590641.8237"):
        new = []
        for letter in original:
                new.append(key[alpha.index(letter)])

        return ["".join(new), key]

def decrypt(cipher, key="590641.8237"):
    if key is not None:
        new = []
        for letter in cipher:
            new.append(alpha[key.index(letter)])

        return "".join(new)

#************************************************************** Main Window ******************************************************************
class mainwindow:

        def __init__(self, master):
                self.master = master
                self.master.iconbitmap('icons/icon.ico')
                self.master.title("PyShare")
                self.master.geometry("800x700")
                self.master.configure(background = "azure2");
                self.k = Label(self.master ,text = "PyShare",foreground="cadetBlue",font=('Helvetica',30, 'bold'),background = "azure2").grid(row = 2,column =2 ,padx=5,pady=5)
                self.width = 120
                self.height = 120
                self.img = Image.open("icons/icon.jpg")
                self.img = self.img.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg =  ImageTk.PhotoImage(self.img)
                self.k1 = Label(self.master ,background = "white",text = "PyShare",image=self.photoImg)
                self.k1.grid(row = 0,column = 2,padx=5,pady=5)
                self.width = 120
                self.height = 120
                self.img1 = Image.open("icons/send.png")
                self.img1 = self.img1.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg1 =  ImageTk.PhotoImage(self.img1)
                self.b=Button(self.master,width=500,height=100,background = "white",image=self.photoImg1,command=self.send)
                self.b.grid(row = 8,column = 2,padx=150,pady=5)
                self.width = 120
                self.height = 120
                self.img2 = Image.open("icons/rcv.png")
                self.img2 = self.img2.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg2 =  ImageTk.PhotoImage(self.img2)
                self.b1=Button(self.master,width=500,height=100,background = "white",image=self.photoImg2,command=self.recieve)
                self.b1.grid(row = 10,column = 2,padx=5,pady=5)
                self.width = 120
                self.height = 120
                self.img3 = Image.open("icons/local.png")
                self.img3 =self.img3.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg3 =  ImageTk.PhotoImage(self.img3)
                self.b2=Button(self.master,width=500,height=100,background = "white",image=self.photoImg3,command=self.local)
                self.b2.grid(row = 11,column = 2,padx=5,pady=5)

                self.ct1= Label(self.master ,background = "azure2",foreground="thistle4",font=('Helvetica',15, 'bold'))
                self.ct1.grid(row = 3,column = 2,padx=5,pady=5)
                self.name()

                self.width = 50
                self.height = 50
                self.img5 = Image.open("icons/exit.jpg")
                self.img5 = self.img5.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg5 =  ImageTk.PhotoImage(self.img5)
                self.b4=Button(self.master,width=50,height=50,background = "white",image=self.photoImg5,command=self.same2)
                self.b4.grid(row = 13,column = 2,padx=1,pady=1)

                self.width = 25
                self.height = 25
                self.img6 = Image.open("icons/history.png")
                self.img6 = self.img6.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg6 =  ImageTk.PhotoImage(self.img6)
                self.b5=Button(self.master,width=30,height=30,background = "white",image=self.photoImg6,command=self.same)
                self.b5.grid(row = 12,column = 2,padx=1,pady=5)

        def recieve(self):
                self.master.withdraw()
                self.r = Toplevel(self.master)
                br= Recieve(self.r)

        def send(self):
                self.master.withdraw()
                self.s = Toplevel(self.master)
                bs = Send(self.s)

        def local(self):
                self.master.withdraw()
                self.l=Toplevel(self.master)
                bl=Local(self.l)

        def name(self):
                results = subprocess.check_output(["netsh", "wlan", "show", "network"])
                results = results.decode("ascii")
                results = results.replace("\r","")
                ls = results.split("\n")
                ls = ls[4]
                a=(str(ls))
                r=(str(a[9:]))
                self.ct1["text"]="CONNECTED TO: "+r

        def same(self):
                root = Tk()
                with open("logs.txt", "r") as f:
                        Label(root, text=f.read()).pack()
                root.mainloop()

        def same2(self):
                os._exit(0)

#******************************************************** Send Code *************************************************************************

class Send :

        def __init__(self, master):
                self.master=master
                self.master.iconbitmap('icons/icon.ico')
                self.master.title("Sender")
                self.master.geometry("800x700")
                self.master.configure(background = "azure2");
                self.k = Label(self.master ,text = "PyShare",foreground="cadetBlue",font=('Helvetica',30, 'bold'),background = "azure2").grid(row = 2,column =2 ,padx=5,pady=5)

                self.width = 120
                self.height = 120
                self.img = Image.open("icons/icon.jpg")
                self.img = self.img.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg =  ImageTk.PhotoImage(self.img)

                self.k1 = Label(self.master ,background = "white",text = "PyShare",image=self.photoImg)
                self.k1.grid(row = 0,column = 2,padx=350,pady=5)

                self.dip = Label(self.master ,text = "IP Adress: ",foreground="black",font=('Helvetica',15, 'bold'),background = "azure2").grid(row = 3,column =2 ,padx=5,pady=5)

                self.b=Button(self.master,width=10,height=1,background = "white",text="Show IP",command=self.getip)
                self.b.grid(row = 6,column = 2,padx=150,pady=5)

                self.ipa = Label(self.master ,background = "azure2",foreground="red4",font=('Helvetica',25, 'bold'))
                self.ipa.grid(row = 7,column = 2,padx=5,pady=5)

                self.b=Button(self.master,width=14,height=2,background = "white",text="Select file",command=self.sendinit)
                self.b.grid(row = 8,column = 2,padx=150,pady=5)

                self.st1 = Label(self.master ,background = "azure2",foreground="black",text="File Size")
                self.st1.grid(row = 9,column = 2,padx=5,pady=5)

                self.st2 = Label(self.master ,background = "azure2",foreground="SpringGreen4")
                self.st2.grid(row = 10,column = 2,padx=5,pady=5)

                self.wt1 = Label(self.master ,background = "azure2",foreground="black",text="File Name")
                self.wt1.grid(row = 11,column = 2,padx=5,pady=5)

                self.wt2 = Label(self.master ,background = "azure2",foreground="SpringGreen4")
                self.wt2.grid(row = 12,column = 2,padx=5,pady=5)

                self.wt3 = Label(self.master ,background = "azure2",foreground="black",text="File Path")
                self.wt3.grid(row = 13,column = 2,padx=5,pady=5)

                self.wt4 = Label(self.master ,background = "azure2",foreground="SpringGreen4",)
                self.wt4.grid(row = 14,column = 2,padx=5,pady=5)

                self.dn1= Label(self.master ,background = "azure2",foreground="Green2",font=('Helvetica',15, 'bold'))
                self.dn1.grid(row = 15,column = 2,padx=5,pady=5)

                self.dn2 = Label(self.master ,background = "azure2",foreground="SpringGreen4",)
                self.dn2.grid(row = 16,column = 2,padx=5,pady=5)

                self.b1=Button(self.master,width=10,height=1,background = "white",text="BACK",command=self.BACK)
                self.b1.grid(row = 17,column = 2,padx=150,pady=5)

        def getip(self):
                c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                c.connect(("8.8.8.8", 80))
                self.ip1=(c.getsockname()[0])
                self.ip2=self.ip1[8:]
                hip = encrypt(self.ip2, "590641.8237")
                self.addr=hip[0]
                self.ipa["text"]=str(self.addr)
                c.close()

        def sendinit(self):
                s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                s.bind(('',9999))
                s.listen(1)
                c,self.addr=s.accept()
                Tk().withdraw()
                filename = askopenfilename()
                fs=file_size(filename)
                file_info = os.stat(filename)
                f=open(filename,'br')
                name = (os.path.basename(filename))
                self.st2["text"]=fs
                self.wt2["text"]=name
                self.wt4["text"]=filename
                c.send(name.encode())
                f.seek(0)
                for i in f:
                        c.send(i)
                self.dn1["text"]="File Transfer Complete !!"
                now = datetime.now()
                dt_string = now.strftime("%d/%m/%Y\t%H:%M:%S")
                self.dn2["text"]="on  "+ dt_string
                log= open("logs.txt","a+")
                log.write("sent\t"+ name +"\t to\t"+self.addr[0]+"\ton\t"+ dt_string +"\n" )
                log.close()
                s.close()

        def BACK(self):
                self.master.withdraw()
                self.b = Toplevel(self.master)
                b= mainwindow(self.b)

#******************************************************** Receive Code *************************************************************************

class Recieve:

        def __init__(self, master):
                self.master=master
                self.master.iconbitmap('icons/icon.ico')
                self.master.title("Reciever")
                self.master.geometry("800x700")
                self.master.configure(background = "azure2");
                self.k = Label(self.master ,text = "PyShare",foreground="cadetBlue",font=('Helvetica',30, 'bold'),background = "azure2").grid(row = 2,column =2 ,padx=5,pady=5)

                self.width = 120
                self.height = 120
                self.img = Image.open("icons/icon.jpg")
                self.img = self.img.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg =  ImageTk.PhotoImage(self.img)

                self.k1 = Label(self.master ,background = "white",text = "PyShare",image=self.photoImg)
                self.k1.grid(row = 0,column = 2,padx=350,pady=5)

                self.k2=Label(self.master ,text = "Enter IP",foreground="black",background = "azure2",font=('Helvetica',15, 'bold'))
                self.k2.grid(row = 4,column =2 ,padx=5,pady=5)

                self.a1 = Entry(self.master,width=30)
                self.a1.grid(row = 5,column = 2,padx=5,pady=5)

                self.b=Button(self.master,width=20,height=1,background = "white",text="Start Recieving",command=self.recieveinit)
                self.b.grid(row = 6,column = 2,padx=150,pady=5)

                self.st3 = Label(self.master ,background = "azure2",foreground="black",text = "File Size")
                self.st3.grid(row = 7,column = 2,padx=5,pady=5)

                self.st4 = Label(self.master ,background = "azure2",foreground="SpringGreen4")
                self.st4.grid(row = 8,column = 2,padx=5,pady=5)

                self.st5 = Label(self.master ,background = "azure2",foreground="black",text = "File Path")
                self.st5.grid(row = 9,column = 2,padx=5,pady=5)

                self.st6 = Label(self.master ,background = "azure2",foreground="SpringGreen4")
                self.st6.grid(row = 10,column = 2,padx=5,pady=5)

                self.p1 = Label(self.master ,background = "azure2",foreground="black",text = "File Name")
                self.p1.grid(row = 11,column = 2,padx=5,pady=5)

                self.fp = Label(self.master ,background = "azure2",foreground="SpringGreen4")
                self.fp.grid(row = 12,column = 2,padx=5,pady=5)

                self.fn =Label(self.master ,background = "azure2",foreground="Green2",font=('Helvetica',15, 'bold'))
                self.fn.grid(row = 13,column = 2,padx=5,pady=5)

                self.fn1 = Label(self.master ,background = "azure2",foreground="SpringGreen4")
                self.fn1.grid(row = 14,column = 2,padx=5,pady=5)

                self.b1=Button(self.master,width=10,height=1,background = "white",text="Back",command=self.BACK)
                self.b1.grid(row = 15,column = 2,padx=150,pady=5)

        def recieveinit(self):
                dec = decrypt(self.a1.get(), "590641.8237")
                self.ipdec="192.168."+dec
                self.addr1=self.ipdec
                s = socket.socket()
                s.connect((self.addr1, 9999))
                fname = s.recv(10000)
                self.fp["text"]=(fname.decode())
                if os.path.splitext(fname.decode())[1] == ".mp3":
                        f=open('Received/songs/'+fname.decode(),'bw')
                        fss=('Received/songs/'+fname.decode())
                elif os.path.splitext(fname.decode())[1] == ".mp4":
                        f=open('Received/videos/'+fname.decode(),'bw')
                        fss=('Received/videos/'+fname.decode())
                elif os.path.splitext(fname.decode())[1] == ".jpg":
                        f=open('Received/photos/'+fname.decode(),'bw')
                        fss=('Received/photos/'+fname.decode())
                elif os.path.splitext(fname.decode())[1] == ".png":
                        f=open('Received/photos/'+fname.decode(),'bw')
                        fss=('Received/photos/'+fname.decode())
                else:
                        f=open('Received/documents/'+fname.decode(),'bw')
                        fss=('Received/documents/'+fname.decode())
                x=s.recv(100000)
                while(x):
                        f.write(x)
                        x = s.recv(100000000)
                self.fn["text"]="File Transfer Complete !!"
                now = datetime.now()
                dt_string = now.strftime("%d/%m/%Y\t%H:%M:%S")
                self.fn1["text"]="on "+ dt_string
                fs=file_size(fss)
                self.st4["text"]=fs
                self.st6["text"]=fss
                log= open("logs.txt","a+")
                log.write("received \t"+ fname.decode() +"\t from\t"+self.addr1+"\ton\t"+ dt_string +"\n")
                log.close()
                f.close()

        def BACK(self):
                self.master.withdraw()
                self.b = Toplevel(self.master)
                b= mainwindow(self.b)

#******************************************************** Local Code *************************************************************************

class Local:

        def __init__(self, master):
                self.master=master
                self.master.iconbitmap('icons/icon.ico')
                self.master.title("Local Files")
                self.master.geometry("800x700")
                self.master.configure(background = "azure2")
                self.k = Label(self.master ,text = "PyShare",foreground="cadetBlue",font=('Helvetica',30, 'bold'),background = "azure2").grid(row = 2,column =2 ,padx=5,pady=5)
                self.width = 120
                self.height = 120
                self.img = Image.open("icons/icon.jpg")
                self.img = self.img.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg =  ImageTk.PhotoImage(self.img)

                self.k1 = Label(self.master ,background = "white",text = "PyShare",image=self.photoImg)
                self.k1.grid(row = 0,column = 2,padx=5,pady=5)

                self.width = 120
                self.height = 120
                self.img1 = Image.open("icons/photos.png")
                self.img1 = self.img1.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg1 =  ImageTk.PhotoImage(self.img1)

                self.b=Button(self.master,width=500,height=100,background = "white",image=self.photoImg1,command=self.photo)
                self.b.grid(row = 8,column = 2,padx=150,pady=5)

                self.width = 120
                self.height = 120
                self.img2 = Image.open("icons/songs.png")
                self.img2 = self.img2.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg2 =  ImageTk.PhotoImage(self.img2)

                self.b1=Button(self.master,width=500,height=100,background = "white",image=self.photoImg2,command=self.songs)
                self.b1.grid(row = 10,column = 2,padx=5,pady=5)

                self.width = 120
                self.height = 120
                self.img3 = Image.open("icons/videos.png")
                self.img3 = self.img3.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg3 =  ImageTk.PhotoImage(self.img3)

                self.b2=Button(self.master,width=500,height=100,background = "white",image=self.photoImg3,command=self.vid)
                self.b2.grid(row = 11,column = 2,padx=5,pady=5)

                self.width = 120
                self.height = 120
                self.img4 = Image.open("icons/documents.png")
                self.img4 = self.img4.resize((self.width,self.height), Image.ANTIALIAS)
                self.photoImg4 =  ImageTk.PhotoImage(self.img4)

                self.b2=Button(self.master,text="Songs",width=500,height=100,background = "white",image=self.photoImg4,command=self.docs)
                self.b2.grid(row = 12,column = 2,padx=5,pady=5)

                self.b3=Button(self.master,width=10,height=1,background = "white",text="BACK",command=self.BACK)
                self.b3.grid(row = 14,column = 2,padx=150,pady=5)

        def BACK(self):
                self.master.withdraw()
                self.b = Toplevel(self.master)
                b= mainwindow(self.b)

        def songs(self):
                root = Tk()
                root.geometry("800x700")
                l = Listbox(root, height=800,width=600)
                l.grid(column=0, row=0)
                s = ttk.Scrollbar(root, orient=VERTICAL, command=l.yview)
                s.grid(column=1, row=0)
                l['yscrollcommand'] = s.set
                ttk.Sizegrip().grid(column=1, row=1)
                root.grid_columnconfigure(0, weight=1)
                root.grid_rowconfigure(0, weight=1)
                for filename in os.listdir("./Received/songs/"):
                        l.insert(END, filename)
                root.mainloop()

        def docs(self):
                root = Tk()
                root.geometry("800x700")
                l = Listbox(root, height=800,width=600)
                l.grid(column=0, row=0)
                s = ttk.Scrollbar(root, orient=VERTICAL, command=l.yview)
                s.grid(column=1, row=0)
                l['yscrollcommand'] = s.set
                ttk.Sizegrip().grid(column=1, row=1)
                root.grid_columnconfigure(0, weight=1)
                root.grid_rowconfigure(0, weight=1)
                for filename in os.listdir("./Received/documents/"):
                        l.insert(END, filename)
                root.mainloop()

        def vid(self):
                root = Tk()
                root.geometry("800x700")
                l = Listbox(root, height=800,width=600)
                l.grid(column=0, row=0)
                s = ttk.Scrollbar(root, orient=VERTICAL, command=l.yview)
                s.grid(column=1, row=0)
                l['yscrollcommand'] = s.set
                ttk.Sizegrip().grid(column=1, row=1)
                root.grid_columnconfigure(0, weight=1)
                root.grid_rowconfigure(0, weight=1)
                for filename in os.listdir("./Received/videos/"):
                        l.insert(END, filename)
                root.mainloop()

        def photo(self):
                root = Tk()
                root.geometry("800x700")
                l = Listbox(root, height=800,width=600)
                l.grid(column=0, row=0)
                s = ttk.Scrollbar(root, orient=VERTICAL, command=l.yview)
                s.grid(column=1, row=0)
                l['yscrollcommand'] = s.set
                ttk.Sizegrip().grid(column=1, row=1)
                root.grid_columnconfigure(0, weight=1)
                root.grid_rowconfigure(0, weight=1)
                for filename in os.listdir("./Received/photos/"):
                        l.insert(END, filename)
                root.mainloop()

#******************************************************** Main function *************************************************************************

if __name__ == '__main__':
    root = Tk()
    b = mainwindow(root)
    root.mainloop()


import tkinter as tk
import turtle

root = tk.Tk()

def rect (horiz,vert,color):
    turtle.pendown()
    turtle.pensize(2)

    turtle.color(color)
    turtle.begin_fill()

    for i in range(1,3):
        turtle.forward(horiz)
        turtle.right(90)
        turtle.forward(vert)
        turtle.right(90)

    turtle.end_fill()
    turtle.penup()
    turtle.speed("slowest")

rect(50,25,'red')


from django.shortcuts import render
from django.http import HttpResponse
import json
from django.forms.models import model_to_dict
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
import datetime
import time
from django.utils import timezone
from django.db.models import Q
from . import models

# Create your views here.

def index(request):
    articles = models.Article.objects.all()
    return render(request, 'blog/index.html', {'articles': articles})

def hello(request):
    return HttpResponse('helloworld')

def list(request):
    articles = models.Article.objects.all()
    article = models.Article.objects.get(pk=1)
    return render(request, 'blog/list.html',
                  {'articles': articles, 'article': article})

@csrf_exempt
def add(request):
    title = request.POST.get('title', 'defaultTitle')
    content = request.POST.get('content', 'defaultContent')

    pub_time = utc2local(timezone.now())
    LOCAL_FORMAT = "%Y-%m-%d %H:%M:%S"
    pub_time = pub_time.strftime(LOCAL_FORMAT)

    models.Article.objects.create(
        title=title,
        content=content,
        pub_time=pub_time)

    articles = models.Article.objects.all()
    return render(request, 'blog/index.html', {'articles': articles})

@csrf_exempt
def edit(request):
    article_id = request.POST.get('id', 0)
    title = request.POST.get('title', 'defaultTitle')
    content = request.POST.get('content', 'defaultContent')
    pub_time = utc2local(timezone.now())
    LOCAL_FORMAT = "%Y-%m-%d %H:%M:%S"
    pub_time = pub_time.strftime(LOCAL_FORMAT)

    article = models.Article.objects.get(pk=article_id)
    article.title = title
    article.content = content
    article.pub_time = pub_time
    article.save()

    articles = models.Article.objects.all()
    return render(request, 'blog/index.html', {'articles': articles})

@csrf_exempt
def delete(request):
    article_id = request.POST.get('id', 0)
    models.Article.objects.get(pk=article_id).delete()
    result = {'code': 0, 'ext': 'success'}
    return HttpResponse(json.dumps(result, ensure_ascii=False))

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

def detail(request, article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/article.html',
                  {'article': article})

def toadd(request):
    return render(request, 'blog/add.html')

def toedit(request, article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/edit.html', {'article': article})

@csrf_exempt
def search(request):
    key = request.POST.get('key')
    articles = models.Article.objects.filter(Q(title__contains=key) | Q(content__contains=key))
    json_data = serializers.serialize("json", articles)
    dict_data = json.loads(json_data)
    result = {
        'code': 0,
        'ext': 'success',
        'articles': dict_data}
    return HttpResponse(json.dumps(result, ensure_ascii=False))

def utc2local(utc_st):
    # UTC时间转本地时间（+8:00）
    now_stamp = time.time()
    local_time = datetime.datetime.fromtimestamp(now_stamp)
    utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
    offset = local_time - utc_time
    local_st = utc_st + offset
    return local_st


from flask import Flask, render_template, send_from_directory
from data import db_session
from frame.bd_func import get_subjects, get_types, get_patterns
from flask import request
from frame.frame import DocGenerator
from data.user import User
from flask import redirect
from flask_login import LoginManager
from registrarion_form import RegisterForm
from login_form import LoginForm
from flask_login import login_user
from flask_login import login_required
from flask_login import logout_user
from flask_login import current_user
from threading import Thread
from clearing import clearing
from data_func import get_docs
import time
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mad'
login_manager = LoginManager()
login_manager.init_app(app)

clearing_thread = Thread(target=clearing)
clearing_thread.start()

@login_manager.user_loader
def load_user(user_id):
    db_sess = db_session.create_session()
    return db_sess.query(User).get(user_id)

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

@app.route('/viewing')
def viewing():
    docs = get_docs(current_user.name if current_user.is_authenticated else 'anonym')
    return render_template('viewing.html', docs=docs)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect("/")

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(User.email == form.email.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect("/")
        return render_template('login.html',
                               message="Неправильный логин или пароль",
                               form=form)
    return render_template('login.html', form=form)

@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'GET':
        return render_template('create.html', subjects=get_subjects() + [[0, 'Все']],
                               types=get_types() + [[0, 'Все']], patterns=get_patterns())

    elif request.method == 'POST':
        try:
            if current_user.is_authenticated:
                doc_generator = DocGenerator(request.form, user=current_user.name)
            else:
                doc_generator = DocGenerator(request.form)
        except ValueError:
            return render_template('error.html')
        name = doc_generator.generate_document()
        name += '.zip'
        return send_from_directory(
            directory=f'static/generated_documents/{current_user.name if current_user.is_authenticated else "anonym"}',
            filename=name, as_attachment=True)

@app.route('/register', methods=['GET', 'POST'])
def reqister():
    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(
            name=form.name.data,
            email=form.email.data,
            is_admin=False
        )
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        f = open('log/log.txt', 'a')
        data = time.ctime(time.time())
        f.write(f'register {data} | {user.name}\n')
        f.close()

        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)

if __name__ == '__main__':
    db_session.global_init("db/blogs.db")
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

# if __name__ == '__main__':
#     db_session.global_init("db/blogs.db") если запускаете сами
#     app.run(host='127.0.0.1', port=8000)


from src.shared.string import EMPTY
from .reagent import Reagent
from .utils import closest_target, count_free_babies, group_target, paths_to_target
from ..shared import count_dirt, get_length, ROBOT, DIRT, BABY, CORRAL, OBSTACLE
from ..logging import LoggerFactory as Logger

log = None

CAUTIOUS = 'CAUTIOUS'
DARED    = 'DARED'

class Practical(Reagent):
    '''
    Practical reasoning agent. Model-based and goal-based reflex agent
    '''
    def __init__(self, pos, t):
        global log
        log = Logger('Kindergarden').getChild('Practical')
        self.t = 0
        self.time = 0
        self.babies = 0
        self.mode = ''
        self.drop = False
        self.old_pos = pos
        super().__init__(pos)

    def action(self, house):
        beliefs   = self.get_beliefs(house)
        options   = self.get_options(beliefs)
        operation = self.filter_options(options)
        self.execute(operation, house)

    def get_beliefs(self, house):
        '''
        Get state of the environment detected by the agent given the latest perception
        '''
        beliefs = dict()
        self.time += 1

        #Learn t
        if self.old_pos != self.pos:
            t = self.t
            self.t = self.time - self.t - 1
            if self.t == 0:
                self.t = t
            self.time = 1
            log.debug(f't value: {self.t}')
        #Top priority intentions
        if self.will_clean or self.carrying_baby:
            return beliefs

        log.info('Updating state of the environment...', 'get_beliefs')
        self.babies = count_free_babies(house)
        n, m = get_length(house)
        beliefs['mess'] = count_dirt(house) * 100 // (n * m)
        beliefs['dirt_groups'] = group_target(house, DIRT, self.t // 2 if self.t > 0 else 10)
        beliefs['baby_groups'] = group_target(house, BABY, 2)

        paths_to_babies = list()
        paths_to_dirt = list()

        max_path = len(closest_target(house, self.pos, DIRT, [OBSTACLE]))
        max_path *= 2
        paths_to_target(house, self.pos, self.pos, DIRT, {self.pos}, dict(), [OBSTACLE, BABY], paths_to_dirt, max_path)

        max_path = len(closest_target(house, self.pos, BABY, [OBSTACLE]))
        max_path += self.t // 2 if self.t > 0 else 5
        paths_to_target(house, self.pos, self.pos, BABY, {self.pos}, dict(), [OBSTACLE], paths_to_babies, max_path)
        # log.debug(f'paths_to_babies: {paths_to_babies}')
        # log.debug(f'paths_to_dirt: {paths_to_dirt}')

        dirt_in_path_to_babies = list()
        for p in paths_to_babies:
            dirt = 0
            for (i, j) in p:
                dirt += 1 if house[i][j].value == DIRT else 0
            dirt_in_path_to_babies.append(dirt)
        beliefs['dirt_in_path_to_babies'] = dirt_in_path_to_babies
        #log.debug(f'dirt_in_path_to_babies: {dirt_in_path_to_babies}')

        beliefs['paths_to_babies'] = paths_to_babies
        beliefs['paths_to_dirt'] = paths_to_dirt
        return beliefs

    def get_options(self, beliefs):
        '''
        Get options(plans) available for the agent given its actual beliefs and its intentions
        '''
        #Top priority intentions
        if self.will_clean or self.carrying_baby:
            return self.options

        options = beliefs

        #Get best path to dirt
        considering = list()
        for p in options['paths_to_dirt']:
            for g in options['dirt_groups']:
                last = list(p)[-1]
                if last in g:
                    #(length of path, concentration of dirt, path)
                    considering.append((len(p), -len(g), p))
                    break
        considering.sort()
        #log.debug(f'Best paths to dirt: {considering}')
        options['best_path_dirt'] = None if considering == [] else considering[0][2]

        #Get best path to baby sorted by occurrence of dirt in the path
        considering.clear()
        for p, d in zip(options['paths_to_babies'], options['dirt_in_path_to_babies']):
            #(length of path, number of dirt in path, path)
            considering.append((len(p), -d, p))
        considering.sort()
        #log.debug(f'Best dirty paths to babies: {considering}')
        options['best_dirty_path_babies'] = None if considering == [] else considering[0][2]

        #Get best path to baby
        considering.clear()
        for p in options['paths_to_babies']:
            for g in options['baby_groups']:
                last = list(p)[-1]
                if last in g:
                    #(length of path, concentration of babies, path)
                    considering.append((len(p), -len(g), p))
                    break
        considering.sort()
        #log.debug(f'Best paths to babies: {considering}')
        options['best_path_babies'] = None if considering == [] else considering[0][2]
        self.options = options
        return options

    def filter_options(self, options):
        '''
        Update intentions and get an action to execute
        '''
        #Top priority intentions
        if self.carrying_baby:
            if self.drop:
                self.mode = CAUTIOUS
                return ('DROP', [])
            return ('GOTO_CORRAL', [])
        if self.will_clean:
            self.garbage_collected += 1
            self.will_clean = False
            return ('CLEAN', [])

        #Goal selection
        if options['mess'] >= 40 or self.babies == 0:
            #CAUTIOUS mode
            self.mode = CAUTIOUS
            log.debug(f'Current mode: CAUTIOUS')
            actions = list()
            if options['best_path_dirt']:
                actions.append(options['best_path_dirt'].copy())
                self.options['best_path_dirt'].pop(0)
            if options['best_dirty_path_babies']:
                actions.append(options['best_dirty_path_babies'].copy())
                self.options['best_dirty_path_babies'].pop(0)
            if actions == []:
                return ('BLOCK', [])
            else:
                actions.sort()
                return ('MOVE', actions[0])
        else:
            #DARED mode
            self.mode = DARED
            log.debug(f'Current mode: DARED')
            if options['best_path_babies']:
                opt = options['best_path_babies'].copy()
                return ('MOVE', opt)
            return ('BLOCK', [])

    def execute(self, operation, house):
        '''
        Execute a action given the planned operation
        '''
        x, y = self.pos
        task, args = operation

        if task is 'CLEAN':
            house[x][y].update(ROBOT)
            house[x][y].dirty = False
            log.debug(f'Dirt cleaned in ({x}, {y})', 'CMD: CLEAN')
        elif task is 'GOTO_CORRAL':
            log.debug('Executing task GOTO_CORRAL', 'execute')
            if CORRAL in house[x][y].value and not f'{CORRAL}-{BABY}' in house[x][y].value:
                self.carrying_baby = False
                house[x][y].update(f'{BABY}-{ROBOT}')
                log.debug(f'Dropped baby in corral at ({x}, {y})', 'CMD: GOTO_CORRAL')
            else:
                if not self.try_move(house, CORRAL, [OBSTACLE, BABY]):
                    self.drop = True
        elif task is 'DROP':
            if DIRT in house[x][y].value:
                self.try_move(house, EMPTY, [OBSTACLE, BABY, DIRT])
            self.drop = False
            self.carrying_baby = False
            house[x][y].update(f'{BABY}-{ROBOT}')
            log.debug(f'Dropped baby at ({x}, {y})', 'CMD: DROP')
        else:
            if self.mode is CAUTIOUS:
                self.execute_move(operation, house)
                x, y = self.pos
                if DIRT in house[x][y].value:
                    self.will_clean = True
                    log.debug(f'I\'ll clean dirt on ({x}, {y}) in the next turn', 'execute')
            elif self.mode is DARED:
                self.execute_move(operation, house)
                x, y = self.pos

            if BABY in house[x][y].value and not house[x][y].isFixed:
                self.carrying_baby = True
                house[x][y].update(f'{ROBOT}-{BABY}')
                log.debug(f'Loaded baby on ({x}, {y})', 'execute')

        self.old_pos = self.pos

    def execute_move(self, operation, house):
        task, args = operation
        if task is 'MOVE':
            log.debug('Executing task MOVE', 'execute_move')
            self.move(house, args)
        else:
            log.debug(f'I can\'t move!!! Analyzing options... Meanwhile waiting for an environment change', 'execute_move')

    def __str__(self):
        return 'Practical'


from operators import division
from operators import multiplication
from operators import subtraction
from operators import addition
from operators import modo

class Calculator_v2:
    number_one = int(input("please enter your first number: "))
    number_two = int(input("please enter your second number: "))

    operator_choice = int(input(" \n enter 1 for + \n enter 2 for - \n enter 3 for * \n enter 4 for / \n enter 5 for % \n"))

    if operator_choice == 1:
        print(addition(number_one,number_two))
    elif operator_choice == 2:
        print(subtraction(number_one,number_two))
    elif operator_choice == 3:
        print(multiplication(number_one,number_two))
    elif operator_choice == 4:
        print(division(number_one,number_two))
    elif operator_choice == 5:
        print(modo(number_one,number_two))
    else:
        print("invalid choice")


"""Integration test for TorizonCore Builder

Note: These tests heavily rely on the environment:
- /workdir needs to exist, and a Tezi image needs to be in /workdir/tezi
- fast-banana.png need to exist for the splash screen test
- /storage needs to exist, /storage/pytest will be used for testing
"""

import logging

import py
import pytest

from tcbuilder.backend import deploy, ostree, splash, images

@pytest.fixture(name="storage_dir", scope="module")
def fixture_storage_dir():
    """Initialize/cleanup storage directory for pytest"""
    storage_dir = py.path.local("/storage/pytest")
    if not storage_dir.isdir():
        storage_dir.mkdir()
    assert not storage_dir.join("tezi").isdir()
    assert not storage_dir.join("sysroot").isdir()
    assert not storage_dir.join("ostree-archive").isdir()
    assert not storage_dir.join("splash").isdir()

    yield storage_dir

    # /storage is bind mounted, we should not rm -rf it...
    logging.info(f"Cleaning up {str(storage_dir)}...")
    storage_dir.join("tezi").remove(rec=1)
    storage_dir.join("sysroot").remove(rec=1)
    storage_dir.join("ostree-archive").remove(rec=1)
    storage_dir.join("splash").remove(rec=1)

@pytest.fixture(name="deploy_dir", scope="module")
def fixture_deploy_dir():
    """Initialize deploy directory for pytest"""
    deploy_dir = py.path.local("/deploy")
    assert not deploy_dir.join("sysroot").isdir()
    deploy_dir.join("sysroot").mkdir()

    yield deploy_dir

    logging.info(f"Cleaning up {str(deploy_dir)}...")
    deploy_dir.join("sysroot").remove(rec=1)

def test_unpack(storage_dir, work_dir):
    """"Test unpack sub-command"""

    tezi = storage_dir.join("tezi")
    sysroot_dir = storage_dir.join("sysroot")
    ostree_archive = storage_dir.join("ostree-archive")

    tezi_src = work_dir.join("tezi")

    images.import_local_image(
        str(tezi_src), str(tezi), str(sysroot_dir), str(ostree_archive))

    sysroot = ostree.load_sysroot(str(sysroot_dir))
    csum, _kargs = ostree.get_deployment_info_from_sysroot(sysroot)

    print(csum)
    assert len(csum) > 1

    config = ostree_archive.join("config")
    assert "mode=archive-z2" in config.read()

def test_splash(storage_dir, work_dir):
    """"Test splash sub-command"""

    splash_work_dir = storage_dir.join("splash")
    ostree_archive = storage_dir.join("ostree-archive")

    splashimage = str(work_dir.join("fast-banana.png"))
    logging.info(f"Using {splashimage} as splash screen image.")
    splash.create_splash_initramfs(str(splash_work_dir), str(splashimage), str(ostree_archive))

def test_deploy_using_csum(storage_dir, deploy_dir, work_dir):
    """"Test deploy Tezi image sub-command"""

    tezi = storage_dir.join("tezi")
    sysroot_dir = storage_dir.join("sysroot")
    ostree_archive = storage_dir.join("ostree-archive")

    deploy_sysroot = deploy_dir.join("sysroot")

    sysroot = ostree.load_sysroot(str(sysroot_dir))
    csum, _kargs = ostree.get_deployment_info_from_sysroot(sysroot)

    output = work_dir.join("output")

    deploy.deploy_tezi_image(str(tezi), str(sysroot_dir), str(ostree_archive),
                             str(output), str(deploy_sysroot), csum)

    files = [str(outfile) for outfile in output.listdir()]

    assert any(("image.json" in outfile) for outfile in files)
    assert any(("bootfs.tar" in outfile) for outfile in files)


# -*- coding: utf-8 -*-
"""
Figure 12b
"""

import matplotlib.pyplot as plt
import pandas as pd

path1 = './inter_games/allshader_gspan_output/25percent_result/intergame_all_node_occurance_gspan_fsm2.csv'
df = pd.read_csv(path1 , header = 'infer')

list_to_plot_nodesize = []

game_set = df.drop_duplicates(subset=['gameid'])['gameid']
print(len(game_set))

for frame in game_set:
    print(frame)
    node_sort = df[df.gameid == frame]
    node_sort = node_sort.sort_values(by=['nodesize'])
    node_set = node_sort.drop_duplicates(subset=['nodesize'])['nodesize'].sort_values(ascending=True)
    # x = np.cumsum(node_sort['occurance'])
    # node_sort['cum_occ'] = x

    temp1 =pd.DataFrame(columns = ['nodesize', 'occurance', 'frame'])
    for each in node_set:
        temp = node_sort[node_sort.nodesize == each]
        temp1 = temp1.append(temp)
    list_to_plot_nodesize.append(temp1['nodesize'])

# Create a figure instance
fig = plt.figure(1, figsize=(12,7))
labelsize=25
ax = fig.add_subplot(111)
bp = ax.boxplot(list_to_plot_nodesize)
ax.set_ylabel("Avg # nodes in each frequent subgraph", fontsize=labelsize)
ax.set_xlabel("game ID", fontsize=labelsize)
ax.tick_params(size=labelsize-20)
ax.tick_params(labelsize=labelsize-3)
ax.xticks=([i+1 for i in range(len(game_set))])
ax.set_xticklabels(ax.set_xticklabels(game_set,ha='center'))

for tick in ax.get_xticklabels():
    tick.set_rotation(60)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def recoverFromPreorder(self, S: str) -> TreeNode:
        tree = defaultdict(list)
        i = 0
        while i < len(S):
            j = i
            while j < len(S) and S[j] == '-':
                j += 1
            depth = j - i
            i = j
            while j < len(S) and S[j].isdigit():
                j += 1
            num = int(S[i:j])
            i = j
            tree[depth].append(TreeNode(num))
            if depth - 1 >= 0:
                parent = tree[depth - 1][-1]
                if not parent.left:
                    parent.left = tree[depth][-1]
                else:
                    parent.right = tree[depth][-1]
        if not tree:
            return None
        return tree[0][0]

hard/1028. Recover a Tree From Preorder Traversal.py


# Question: https://leetcode.com/problems/counting-bits/
# Easy
from typing import Optional, List

class Solution:
    # O(n) Time and O(n) Space
    def countBits(self, n: int) -> List[int]:
        dp = [0 for _ in range(n+1)]
        offset = 1

        for num in range(1, n + 1):
            if offset * 2 == num:
                offset = num
            dp[num] = 1 + dp[num - offset]

        return dp
'''

# Kunal Wadhwa

'''

Questions/[Bit Manipulation] Counting Bits.py


from typing import Callable

from ..components import Box, Button, Column, Divider, Row
from ..database import API

class ViewModel:
    id: str
    update: Callable

class ViewController:
    def __init__(self, database: API) -> None:
        self.database = database

        self.__models: dict[str, ViewModel] = {}
        self.__navegation: list[ViewModel] = []

        self.__main_part1 = Column(
            [
                Button("Vendas", lambda _: self.redirect_to("sales")),
                Button("Produtos", lambda _: self.redirect_to("products")),
                Button("Relatórios", lambda _: self.redirect_to("reports")),
            ],
            style={"flex": 1},
        )
        self.__main_part2 = Box()
        self.__main = Row(
            [
                self.__main_part1,
                Divider("v", {"padding_left": 10, "padding_right": 10}),
                self.__main_part2,
            ],
            {"flex": 1, "padding": 10},
        )

    def main(self):
        return self.__main

    def update_main(self, widgets: list):
        self.__main.remove(self.__main_part2)
        self.__main_part2 = Column(widgets, {"flex": 6})
        self.__main.add(self.__main_part2)

    def register_model(self, model: ViewModel):
        self.__models[model.id] = model

    def update_model(self, custom_data=None):
        if not self.__navegation:
            return

        m_model = self.__navegation[-1]

        if custom_data:
            m_model.update(custom_data)
        else:
            m_model.update()

    def redirect_to(self, model_id: str, custom_data=None):
        if model_id not in self.__models:
            return

        if self.__navegation and model_id == self.__navegation[-1].id:
            return

        if len(self.__navegation) > 50:
            self.__navegation = self.__navegation[25:]

        self.__navegation.append(self.__models[model_id])
        self.update_model(custom_data)

    def redirect_to_previous(self):
        if not self.__navegation:
            return

        self.__navegation.pop()
        self.update_model()