#!/usr/bin/env python
#
# Radiosonde Auto RX Tools - GPS Ephemeris / Almanac Grabber
#
# 2017-04 Mark Jessop <vk5qi@rfhead.net>
#
import ftplib
import requests
import datetime
import logging
import os

def get_ephemeris(destination="ephemeris.dat"):
    """ Download the latest GPS ephemeris file from the ESA's FTP server """
    try:
        logging.debug("GPS Grabber - Connecting to ESA's FTP Server...")
        ftp = ftplib.FTP("gssc.esa.int", timeout=10)
        ftp.login("anonymous", "anonymous")
        ftp.cwd("gnss/data/daily/%s/" % datetime.datetime.utcnow().strftime("%Y"))
        # Ideally we would grab this data from: YYYY/brdc/brdcDDD0.YYn.Z
        # .. but the ESA brdc folder seems to be getting of date. The daily directories are OK though!
        # So instead, we use: YYYY/DDD/brdcDDD0.YYn.Z
        # ESA posts new file at 2200 UTC
        ephemeris_time = datetime.datetime.now(
            datetime.timezone.utc
        ) - datetime.timedelta(hours=22)
        download_file = "brdc%s0.%sn.gz" % (
            ephemeris_time.strftime("%j"),
            ephemeris_time.strftime("%y"),
        )

        # CWD into the current day.
        ftp.cwd(ephemeris_time.strftime("%j"))

        logging.debug("GPS Grabber - Current Directory: " + ftp.pwd())

        logging.debug(
            "GPS Grabber - Downloading ephemeris data file: %s" % download_file
        )

        # Download file.
        f_eph = open(destination + ".gz", "wb")
        ftp.retrbinary("RETR %s" % download_file, f_eph.write)
        f_eph.close()
        ftp.close()

        # Unzip file.
        os.system("gunzip -q -f ./%s" % (destination + ".gz"))

        logging.info(
            "GPS Grabber - Ephemeris downloaded to %s successfuly!" % destination
        )

        return destination
    except Exception as e:
        logging.error("GPS Grabber - Could not download ephemeris file. - %s" % str(e))
        return None

def get_almanac(destination="almanac.txt", timeout=20):
    """ Download the latest GPS almanac file from the US Coast Guard website. """
    try:
        _r = requests.get(
            "https://www.navcen.uscg.gov/?pageName=currentAlmanac&format=sem",
            timeout=timeout,
        )
        data = _r.text
        if "CURRENT.ALM" in data:
            f = open(destination, "w")
            f.write(data)
            f.close()
            logging.info(
                "GPS Grabber - Almanac downloaded to %s successfuly!" % destination
            )
            return destination
        else:
            logging.error("GPS Grabber - Downloaded file is not a GPS almanac.")
            return None
    except Exception as e:
        logging.error(f"GPS Grabber - Failed to download almanac data - {str(e)}")
        return None

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    get_almanac()
    get_ephemeris()


# -*- coding: utf-8 -*-
"""
@author: YanWJ
@Date    : 2023/1/4
@Time    : 16:31
@File    : test.py
@Function: XX
@Other: XX
"""
import json
import requests
from tqdm import tqdm

def server_test(sen):
    sess_web = requests.Session()
    # noinspection PyBroadException
    try:
        req = requests.Request('POST', url=url, data=sen.encode("utf-8"))
        prep = sess_web.prepare_request(req)
        results = sess_web.send(prep, stream=False).text
    except Exception as e:
        results = str(e)
    return results

if __name__ == '__main__':
    url = 'http://10.17.107.66:12005/prediction'
    text = '3、本基金投资的前十名证券之一中信证券的发行主体中信证券股份有限公司于2023年2月6日因未按规定履行客户身份识别义务等，受到中国人民银行处罚（银罚决字〔2023〕6号）。' * 10
    tests = []
    tests.append(text)
    print(text)
    results = server_test(json.dumps(tests, ensure_ascii=False))
    # results = server_test(json.dumps(text, ensure_ascii=False))
    print(results)
    # print(json.loads(results))
    # for i in json.loads(results):
    #     print(i)
    for i in tqdm(range(1000)):
       _ = server_test(json.dumps(tests, ensure_ascii=False))
       # _ = server_test(json.dumps(test, ensure_ascii=False), "http://10.17.107.66:8019/prediction")

    # print(json.loads(aa))


'''
@author: ANIK
'''

import random
import sys

from AlgebraicExpressionParser import ExpressionParser
from AlgebraicExpressionParser import Operator
from AlgebraicExpressionParser import Operators
from treelib import Tree

binaryOperators = ['A', 'O', 'U', 'R']
unaryOperators = ['G', 'F', '~']

qMat = []
qMat.append([-1])

def addNodeRec(selfID, parentID, selfVar, parentVar, synTree, expTree, qMat, qParent):

    if selfID[0] == 0:

        if expTree[selfID[0]][0] == 'G':

            synTree.create_node('FORALL i_{} \in {}'.format(selfVar[0], expTree[selfID[0]][1:]), selfID[0])

            parentVar = selfVar[0]
            selfVar[0] += 1

            qMat[0].append(0)
            qParent = 0
            qMat.append([0])

        elif expTree[selfID[0]][0] == 'F':

            synTree.create_node('EXISTS i_{} \in {}'.format(selfVar[0], expTree[selfID[0]][1:]), selfID[0])

            parentVar = selfVar[0]
            selfVar[0] += 1

            qMat[0].append(0)
            qParent = 0
            qMat.append([0])

        elif not (expTree[selfID[0]][0] in binaryOperators or expTree[selfID[0]][0] in unaryOperators):

            synTree.create_node('(\sigma, 0) \models {}'.format(expTree[selfID[0]]), selfID[0])

        else:

            synTree.create_node(expTree[selfID[0]], selfID[0])

    else:

        if parentVar == -1:

            if expTree[selfID[0]][0] == 'G':

                synTree.create_node('FORALL i_{} \in {}'.format(selfVar[0], expTree[selfID[0]][1:]), selfID[0], parent = parentID)

                parentVar = selfVar[0]
                selfVar[0] += 1

                qMat[0].append(selfID[0])
                qParent = selfID[0]
                qMat.append([qParent])

            elif expTree[selfID[0]][0] == 'F':

                synTree.create_node('EXISTS i_{} \in {}'.format(selfVar[0], expTree[selfID[0]][1:]), selfID[0], parent = parentID)

                parentVar = selfVar[0]
                selfVar[0] += 1

                qMat[0].append(selfID[0])
                qParent = selfID[0]
                qMat.append([qParent])

            elif not (expTree[selfID[0]][0] in binaryOperators or expTree[selfID[0]][0] in unaryOperators):

                synTree.create_node('(\sigma, 0) \models {}'.format(expTree[selfID[0]]), selfID[0], parent = parentID)

            else:

                synTree.create_node(expTree[selfID[0]], selfID[0], parent = parentID)

        else:

            if expTree[selfID[0]][0] == 'G':

                synTree.create_node('FORALL i_{} \in {} + i_{}{} + i_{}{}'.format(selfVar[0], expTree[selfID[0]][1:expTree[selfID[0]].find(',')], parentVar, expTree[selfID[0]][expTree[selfID[0]].find(','):-1], parentVar, expTree[selfID[0]][-1]), selfID[0], parent = parentID)

                parentVar = selfVar[0]
                selfVar[0] += 1

                for i in range(len(qMat)):

                    if qMat[i][0] == qParent:

                        qMat[i].append(selfID[0])
                        qParent = selfID[0]
                        qMat.append([qParent])

            elif expTree[selfID[0]][0] == 'F':

                synTree.create_node('EXISTS i_{} \in {} + i_{}{} + i_{}{}'.format(selfVar[0], expTree[selfID[0]][1:expTree[selfID[0]].find(',')], parentVar, expTree[selfID[0]][expTree[selfID[0]].find(','):-1], parentVar, expTree[selfID[0]][-1]), selfID[0], parent = parentID)

                parentVar = selfVar[0]
                selfVar[0] += 1

                for i in range(len(qMat)):

                    if qMat[i][0] == qParent:

                        qMat[i].append(selfID[0])
                        qParent = selfID[0]
                        qMat.append([qParent])

            elif not (expTree[selfID[0]][0] in binaryOperators or expTree[selfID[0]][0] in unaryOperators):

                synTree.create_node('(\sigma, i_{}) \models {}'.format(parentVar, expTree[selfID[0]]), selfID[0], parent = parentID)

            else:

                synTree.create_node(expTree[selfID[0]], selfID[0], parent = parentID)

    if expTree[selfID[0]][0] in binaryOperators:

        parentID = selfID[0]

        selfID[0] += 1
        addNodeRec(selfID, parentID, selfVar, parentVar, synTree, expTree, qMat, qParent)

        selfID[0] += 1
        addNodeRec(selfID, parentID, selfVar, parentVar, synTree, expTree, qMat, qParent)

    if expTree[selfID[0]][0] in unaryOperators:

        parentID = selfID[0]

        selfID[0] += 1
        addNodeRec(selfID, parentID, selfVar, parentVar, synTree, expTree, qMat, qParent)

def genSynTree(exp):

    operators = [Operator(symbol = 'AND', precedence = 2),
                Operator(symbol = 'OR', precedence = 2),
                Operator(symbol = 'G[a, b]', type = Operator.unary, precedence = 3, associativity = Operator.rtl, position = Operator.prefix),
                Operator(symbol = 'F[a, b]', type = Operator.unary, precedence = 3, associativity = Operator.rtl, position = Operator.prefix),
                Operator(symbol = 'U[a, b]', precedence = 2),
                Operator(symbol = 'R[a, b]', precedence = 2),
                Operator(symbol = '~', type = Operator.unary, precedence = 3, associativity = Operator.rtl, position = Operator.prefix)]

    for i in range(len(exp)):

        if exp[i] == '[':

            temporalOperator = exp[i - 1:exp[i:].find(']') + 1 + i]
            operators.append(Operator(symbol = temporalOperator, type = Operator.unary, precedence = 3, associativity = Operator.rtl, position = Operator.prefix))

    operators = Operators(operators)
    parser = ExpressionParser(operators)
    expTree = parser.syntax_tree(exp).preorder()

    for i in range(len(expTree)):

        if expTree[i][0] == 'U' or expTree[i][0] == 'R':

            exp = expTree[i]
            expTree.pop(i)
            expTree.insert(i, 'F' + exp[1:])
            expTree.insert(i + 1, 'AND')
            expTree.insert(i + 2, 'G' + exp[1:])

    synTree = Tree()
    selfID = [0]
    selfVar = [0]

    addNodeRec(selfID, 0, selfVar, -1, synTree, expTree, qMat, -1)

    return synTree

def getNodeData(synTree, nodeID):

    return synTree[nodeID].tag

def getNodeInterval(synTree, nodeID):

    tag = synTree.get_node(nodeID).tag
    start = (tag[tag.find('[') + 1: tag.find(',')])
    end = (tag[tag.find(',') + 2: tag.find(']')])

    return start, end

def getSubTree(synTree, nodeID):

    subTree = Tree()

    currentID = '{}'.format(subTree.create_node(synTree.get_node(nodeID).tag, random.randrange(100, 1000000)))
    currentID = int(currentID[currentID.find('identifier=') + 11:currentID.find(', data=')])

    def copyNodeRec(synTree, nodeID, parentID):

        if not synTree.get_node(nodeID).is_leaf():

            childrenList = synTree.children(nodeID)

            for child in childrenList:

                currentID = '{}'.format(child)
                currentID = '{}'.format(subTree.create_node(currentID[currentID.find('tag=') + 4:currentID.find(', identifier=')], random.randrange(100, 1000000), parent = parentID))
                currentID = int(currentID[currentID.find('identifier=') + 11:currentID.find(', data=')])

                nodeID = '{}'.format(child)
                nodeID = int(nodeID[nodeID.find('identifier=') + 11:nodeID.find(', data=')])

                copyNodeRec(synTree, nodeID, currentID)

    copyNodeRec(synTree, nodeID, currentID)

    return subTree

def treePartition(synTree, qMat, nodeID, time):

    if nodeID == -1 and qMat[0][1] == 0:

        newRoot = Tree()
        tag = synTree.get_node(0).tag

        if 'FORALL' in tag:

            rootID = newRoot.create_node('AND', random.randrange(100, 1000000)).identifier

        if 'EXISTS' in tag:

            rootID = newRoot.create_node('OR', random.randrange(100, 1000000)).identifier

        subTreeTwo = getSubTree(synTree, 0)
        newRoot.paste(rootID, subTreeTwo)

        synTree.get_node(0).tag = '{}{})'.format(tag[:tag.find(',') + 2], time)
        subTreeTwo.get_node(subTreeTwo.root).tag = '{}{}{}'.format(tag[:tag.find('[') + 1], time, tag[tag.find(','):])

        for i in range(len(qMat[1]) - 1):

            partNode(synTree, qMat[1][i + 1], time)
            treePartition(synTree, qMat, qMat[1][i + 1], time)

        subTreeOne = getSubTree(synTree, 0)
        newRoot.paste(rootID, subTreeOne)

        synTree = newRoot
        return synTree

    else:

        for j in range(len(qMat)):

            if qMat[j][0] == nodeID and len(qMat[j]) > 1:

                for i in range(len(qMat[j]) - 1):

                    partNode(synTree, qMat[j][i + 1], time)
                    treePartition(synTree, qMat, qMat[j][i + 1], time)

def partNode(synTree, nodeID, time):

    parentID = synTree.parent(nodeID).identifier
    tag = synTree.get_node(nodeID).tag

    if 'FORALL' in tag:

        newParentID = synTree.create_node('AND', random.randrange(100, 1000000), parent = parentID).identifier
        synTree.move_node(nodeID, newParentID)

        subTree = getSubTree(synTree, nodeID)
        subTree.get_node(subTree.root).tag = '{}{}{}'.format(tag[:tag.find('[') + 1], time, tag[tag.find(','):])

        synTree.paste(newParentID, subTree)

        synTree.get_node(nodeID).tag = '{}{})'.format(tag[:tag.find(',') + 2], time)

    if 'EXISTS' in tag:

        newParentID = synTree.create_node('OR', random.randrange(100, 1000000), parent = parentID).identifier
        synTree.move_node(nodeID, newParentID)

        subTree = getSubTree(synTree, nodeID)
        subTree.get_node(subTree.root).tag = '{}{}{}'.format(tag[:tag.find('[') + 1], time, tag[tag.find(','):])

        synTree.paste(newParentID, subTree)

        synTree.get_node(nodeID).tag = '{}{})'.format(tag[:tag.find(',') + 2], time)

def printMatrix(qMat):

    output = "";

    for i in range(len(qMat)):

        for j in range(len(qMat[i])):

            output += "{} ".format(qMat[i][j])

        print(output)
        output = ""

    print()

def main():

    if len(sys.argv) != 3:

        print('Missing or invalid STL formula.')

    else:

        exp = sys.argv[1]
        time = float(sys.argv[2])
        valid = False

        synTree = genSynTree(exp)
        print('SMT syntax tree:\n')
        synTree.show()

        for i in range(len(exp)):

            if exp[i] == '[':

                lower = exp[i + 1:exp[i + 2:].find(',') + i + 2]
                upper = exp[i + len(lower) + 3:exp[i + 4:].find(']') + i + 4]

                if float(lower) < time and time < float(upper):

                    valid = True

        if not valid:

            print('This formula does not require partitioning.')

        else:

            synTree = treePartition(synTree, qMat, -1, time)
            print('SMT syntax tree partitioned at time {}:\n'.format(time))
            synTree.show()

if __name__ == '__main__':

    main()
    pass


from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import cx_Oracle

#db = Database("Employee.db")
root = Tk()
root.title("Enterprise Application.")
root.geometry("1920x1080+0+0")
root.config(bg="#535c68")
root.state("zoomed")

#textbox for salesman table

cid = StringVar()
cname = StringVar()
ccity = StringVar()
cgrade = StringVar()

# Entries Frame Table 1 Salesman
eframe = Frame(root, bg="#535c68")
eframe.pack(side=TOP, fill=X)
title = Label(eframe, text="Enterprise Application.", font=("Calibri", 18, "bold"), bg="#535c68", fg="white")
title.grid(row=0, columnspan=2, padx=10, pady=20, sticky="w")

#widgets
lblstablename = Label(eframe, text="Customer Table", font=("Calibri", 16), bg="#535c68", fg="white")
lblstablename.grid(row=0, column=2, padx=10, pady=10, sticky="w")

lblcid= Label(eframe, text="Customer Id", font=("Calibri", 16), bg="#535c68", fg="white")
lblcid.grid(row=1 , column=0, padx=10, pady=10, sticky="w")
txtcid= Entry(eframe, textvariable=cid, font=("Calibri", 16), width=30)
txtcid.grid(row=1, column=1, padx=10, pady=10, sticky="w")

lblcname = Label(eframe, text="Customer Name", font=("Calibri", 16), bg="#535c68", fg="white")
lblcname.grid(row=1, column=2, padx=10, pady=10, sticky="w")
txtcname = Entry(eframe, textvariable=cname, font=("Calibri", 16), width=30)
txtcname.grid(row=1, column=3, padx=10, pady=10, sticky="w")

lblccity = Label(eframe, text="Customer City", font=("Calibri", 16), bg="#535c68", fg="white")
lblccity.grid(row=2, column=2, padx=10, pady=10, sticky="w")
txtccity = Entry(eframe, textvariable=ccity, font=("Calibri", 16), width=30)
txtccity.grid(row=2, column=3, padx=10, pady=10, sticky="w")

lblcgrade = Label(eframe, text="Grade", font=("Calibri", 16), bg="#535c68", fg="white")
lblcgrade.grid(row=2, column=0, padx=10, pady=10, sticky="w")
txtcgrade = Entry(eframe, textvariable=cgrade, font=("Calibri", 16), width=30)
txtcgrade.grid(row=2, column=1, padx=10, pady=10, sticky="w")

def insert():
    con = cx_Oracle.connect('system/balaji@localhost:1521/xe')
    csid=int(txtcid.get())
    csname=txtcname.get()
    cscity=txtccity.get()
    csgrade=int(txtcgrade.get())
    icsid=int(csid)
    icsgrade=int(csgrade)
    datai=[[icsid,csname,cscity,csgrade]]
    try:
        if con:
            print(con.version)
            cur = con.cursor()
            cur.executemany('insert into customers25 values(:1,:2,:3,:4)',datai)
    except cx_Oracle.DatabaseError as er:
        print('There is an error in Oracle database:', er)
    except Exception as er:
            print(er)
    else:
        # To commit the transaction manually
        con.commit()
        messagebox.showinfo("Inserted Dialogbox", "INSERTED SUCCESSFULLY!")
    finally:
        if cur:
            cur.close()
        if con:
            con.close()
    tab()
def update():
    con = cx_Oracle.connect('system/balaji@localhost:1521/xe')
    csid=int(txtcid.get())
    csname=txtcname.get()
    cscity=txtccity.get()
    csgrade=int(txtcgrade.get())
    icsid=int(csid)
    icsgrade=int(csgrade)
    datau=[[csname,cscity,icsgrade,icsid]]
    try:
        if con:
            print(con.version)
            cur = con.cursor()
            cur.executemany('update customers25 set customer_name=:1,city=:2,grade=:3 where customer_id=:4',datau)
    except cx_Oracle.DatabaseError as er:
        print('There is an error in Oracle database:', er)
    except Exception as er:
            print(er)
    else:
        # To commit the transaction manually
        con.commit()
        messagebox.showinfo("Updated Dialogbox", "UPDATED SUCCESSFULLY!")
    finally:
        if cur:
            cur.close()
        if con:
            con.close()
    tab()

def delete():
    con = cx_Oracle.connect('system/balaji@localhost:1521/xe')
    csid=int(txtcid.get())
    icsid=int(csid)
    datau=[[icsid]]
    try:
        if con:
            print(con.version)
            cur = con.cursor()
            cur.executemany('delete from customers25 where customer_id=:1',datau)
    except cx_Oracle.DatabaseError as er:
        print('There is an error in Oracle database:', er)
    except Exception as er:
            print(er)
    else:
        # To commit the transaction manually
        con.commit()
        messagebox.showinfo("Deleted Dialogbox", "DELETED SUCCESSFULLY!")
    finally:
        if cur:
            cur.close()
        if con:
            con.close()
    tab()

#insert rows in tables
def tab():
    con = cx_Oracle.connect('system/balaji@localhost:1521/xe')
    try:
        if con:
            print(con.version)
            cur = con.cursor()
            sql="select * from customers25"
            cur.execute(sql)
            rows=cur.fetchall()
            tv.delete(*tv.get_children())
            for ro in rows:
                tv.insert("",END,values=ro)
    except cx_Oracle.DatabaseError as er:
        print('IN TAB There is an error in Oracle database:', er)
    except Exception as er:
            print(er)
    else:
        # To commit the transaction manually
        con.commit()
        print("Table Created in GUI")
    finally:
        if cur:
            cur.close()
        if con:
            con.close()

def change():
    import order3
    print('changed')

#button for crud
btnframe1 = Frame(eframe, bg="#535c68")
btnframe1.grid(row=1, column=4, padx=10, pady=10, sticky="w")
insbtn = Button(btnframe1, command=insert, text="Insert", width=8, font=("Calibri", 16, "bold"), fg="white",
                bg="#535c68", bd=2).grid(row=1, column=5, padx=100, pady=10, sticky="w")

btnframe2 = Frame(eframe, bg="#535c68")
btnframe2.grid(row=2, column=4, padx=10, pady=10, sticky="w")
insbtn = Button(btnframe1, command=update, text="Update", width=8, font=("Calibri", 16, "bold"), fg="white",
                bg="#535c68", bd=2).grid(row=2, column=5, padx=100, pady=10, sticky="w")

btnframe3 = Frame(eframe, bg="#535c68")
btnframe3.grid(row=3, column=4, padx=10, pady=10, sticky="w")
insbtn = Button(btnframe1, command=delete, text="Delete", width=8, font=("Calibri", 16, "bold"), fg="white",
                bg="#535c68", bd=2).grid(row=3, column=5, padx=100, pady=10, sticky="w")

btnframe4 = Frame(eframe, bg="#535c68")
btnframe4.grid(row=4, column=4, padx=10, pady=10, sticky="w")
insbtn1 = Button(btnframe4, command=change, text="ORDER", width=8, font=("Calibri", 16, "bold"), fg="white",
                bg="#535c68", bd=2).grid(row=4, column=5, padx=100, pady=10, sticky="w")

#Display tables
tframe=Frame(root)
tframe.place(x=100,y=400,width=1000,height=250)
#style for table
style=ttk.Style()
style.configure("mystyle.Treeview",font=('Calibri',14),rowheight=40)
#table show
tv=ttk.Treeview(tframe,columns=(1,2,3,4),style="mystyle.Treeview")
tv.heading("1",text="CUSTOMER ID")
tv.heading("2",text="CUSTOMER NAME")
tv.heading("3",text="CUSTOMER CITY")
tv.heading("4",text="CUSTOMER GRADE")
tv['show']='headings'
tv.pack(fill=X)

tab()
root.mainloop()


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

# In[1]:

import numpy as np
import random
import pandas as pd
from pandas import plotting
import pandas_profiling as pp
import seaborn as sns
import matplotlib.pyplot as plt
import statsmodels.api as sm
import statsmodels.formula.api as smf
#get_ipython().run_line_magic('matplotlib', 'inline')

import plotly.offline as py
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
from plotly import tools
#init_notebook_mode(connected=True)
import plotly.figure_factory as ff

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.neighbors import KNeighborsClassifier
from lightgbm import LGBMClassifier
from sklearn.metrics import  accuracy_score
from sklearn.metrics import confusion_matrix

import xgboost as xgb #決策樹
import lightgbm as  lgb
from xgboost.sklearn import XGBClassifier
from catboost import CatBoostClassifier

from sklearn.preprocessing import StandardScaler, LabelBinarizer
# auxiliary function
from sklearn.preprocessing import LabelEncoder
def random_colors(number_of_colors):
    color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])
                 for i in range(number_of_colors)]
    return color

import warnings
warnings.filterwarnings('ignore')

# In[2]:

df = sns.load_dataset('iris')
df.head()

# # EDA
#

# In[3]:

df.info()
df.shape, df.columns

# In[4]:

df.describe()

# In[5]:

Species = df['species'].unique()
Species

# In[6]:

corr = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width',
        'species']].corr()

plt.figure(figsize=(12,8))
sns.heatmap(corr, annot=True)

# In[7]:

sns.pairplot(df,hue = 'species',size=1.5)

# In[ ]:

plt.figure(figsize=(15,10))
plt.subplot(2,2,1)
sns.violinplot(x='species',y='sepal_length',data=df)
plt.subplot(2,2,2)
sns.violinplot(x='species',y='sepal_width',data=df)
plt.subplot(2,2,3)
sns.violinplot(x='species',y='petal_length',data=df)
plt.subplot(2,2,4)
sns.violinplot(x='species',y='petal_width',data=df)

# In[ ]:

Profile = pp.ProfileReport(df, explorative=True)
Profile

# In[8]:

#import sweetviz as sv
#report = sv.analyze(df)
#report.show_html(filepath='iris.html')

# # Machine learning

# In[9]:

X_iris = df.drop('species',axis = 1) #特徵矩陣
X_iris.shape

# In[10]:

y_iris = df['species'].values#目標矩陣
y_iris.shape

# In[11]:

encoder = LabelEncoder()
y_iris = encoder.fit_transform(y_iris)
y_iris

# In[12]:

from sklearn.model_selection import train_test_split
Xtrain,Xtest,Ytrain,Ytest, = train_test_split(X_iris,y_iris,test_size = 0.3, random_state = 101)
#Xtrain,Xtest,Ytrain,Ytest

#X_train 與 y_train 是實際參與行訓練的資料。
#而 X_test 與 y_test是未參與訓練的資料，它是被拿來測試評估最終訓練好的模型。

# # logistic regression

# In[13]:

lr_model = LogisticRegression()
lr_model.fit(Xtrain,Ytrain)
lr_predict = lr_model.predict(Xtest)

print('Logistic Regression - ',accuracy_score(lr_predict,Ytest))
cm = confusion_matrix(Ytest, lr_predict)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # naive bayes

# In[14]:

from sklearn.naive_bayes import GaussianNB
model = GaussianNB()
model.fit(Xtrain,Ytrain)
y_model = model.predict(Xtest)
print('naive bayes - ',accuracy_score(lr_predict,Ytest))

cm = confusion_matrix(Ytest, y_model)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # PCA

# In[15]:

from sklearn.decomposition import PCA
model = PCA (n_components = 2) #主成分兩個
model.fit(X_iris)
X_2D = model.transform(X_iris)#將資料轉化為二維
#X_2D

# In[16]:

df["PCA1"] = X_2D[:,0]
df["PCA2"] = X_2D[:,1]
sns.lmplot("PCA1","PCA2", hue="species", data = df, fit_reg=False)#,fit_reg=False

# In[17]:

df.head()

# # Gaussian mixture model

# In[19]:

from sklearn.mixture import GaussianMixture as GMM
model = GMM(n_components = 3,covariance_type = 'full') #主成分三個
model.fit(X_iris)#訓練
y_gmm = model.predict(X_iris)#Y_GMM = 訓練後的數據集
y_gmm

# In[20]:

df['cluster'] = y_gmm
sns.lmplot("PCA1","PCA2", hue="species", col = 'cluster', data = df, fit_reg=False)

# # SVM

# In[21]:

svm_model = SVC(kernel='linear')
svm_model.fit(Xtrain,Ytrain)
svc_predict = svm_model.predict(Xtest)

print('SVM - ',accuracy_score(svc_predict,Ytest))

cm = confusion_matrix(Ytest, svc_predict)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # Decision tree

# In[22]:

dt_model = DecisionTreeClassifier(max_leaf_nodes=3)
dt_model.fit(Xtrain,Ytrain)
dt_predict = dt_model.predict(Xtest)

print('Decision Tree - ',accuracy_score(dt_predict,Ytest))

cm = confusion_matrix(Ytest,dt_predict)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # Random forest

# In[23]:

rfc_model = RandomForestClassifier(max_depth=3)
rfc_model.fit(Xtrain,Ytrain)
rfc_predict = rfc_model.predict(Xtest)

print('random forest ',accuracy_score(rfc_predict,Ytest))
cm = confusion_matrix(Ytest,rfc_predict)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # Extra Tree Classifier

# In[24]:

etc_model = ExtraTreesClassifier()
etc_model.fit(Xtrain,Ytrain)
etc_predict = etc_model.predict(Xtest)

print('Extra Tree Classifier - ',accuracy_score(etc_predict,Ytest))
cm = confusion_matrix(Ytest,etc_predict)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # KNN

# In[25]:

knn_model = KNeighborsClassifier(n_neighbors=3)
knn_model.fit(Xtrain,Ytrain)
knn_predict = knn_model.predict(Xtest)

print('knn - ',accuracy_score(knn_predict,Ytest))

cm = confusion_matrix(Ytest, knn_predict)
sns.heatmap(cm, annot=True,cmap = 'Blues')

# # XGBoost

# In[27]:

xg_model = xgb.XGBClassifier()
xg_model = xg_model.fit(Xtrain,Ytrain)
print('XGBoost -',xg_model.score(Xtest, Ytest))

# In[2]:

#get_ipython().run_line_magic('history', '')

# In[ ]:


import math

import pygame
import os
import colorsys

pygame.init()

WIDTH, HEIGHT = 1000, 1000
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Painter, By: Arjun Sahlot")
pygame.display.set_icon(pygame.image.load(os.path.join("project_files", "Painter", "assets", "icon.png")))

# Fonts
FONT_ES = pygame.font.SysFont("comicsans", 15)
FONT_D = pygame.font.SysFont("comicsans", 25)
FONT_S = pygame.font.SysFont("comicsans", 23)

# Constants
BOTTOMBARHEIGHT = 180
BOXWIDTH = 100
SMALLERBOXWIDTH = 70
BRUSHSIZE = 9
MAXBRUSHSIZE = 60

# Images
ERASER = pygame.transform.scale(pygame.image.load(os.path.join("project_files", "Painter", "assets", "eraser_icon.png")), (SMALLERBOXWIDTH, SMALLERBOXWIDTH))
CLEAR = pygame.transform.scale(pygame.image.load(os.path.join("project_files", "Painter", "assets", "clear_screen.png")), (SMALLERBOXWIDTH - 14, SMALLERBOXWIDTH - 14))
PICKER = pygame.transform.scale(pygame.image.load(os.path.join("project_files", "Painter", "assets", "color_picker.png")), (170, 170))
SLIDER = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
COLORPOS = (85, 85)
VALUEPOS = (515, 830)

def get_color(colorpos, valuepos):
    hsv_col = rgb_to_hsv(PICKER.get_at(colorpos))
    hue = hsv_col[0]
    sat = hsv_col[1]
    val = rgb_to_hsv(SLIDER.get_at(valuepos))[2]
    return hsv_to_rgb((hue, sat, val))

def hsv_to_rgb(color):
    color = colorsys.hsv_to_rgb(color[0] / 255, color[1] / 255, color[2] / 255)
    return color[0] * 255, color[1] * 255, color[2] * 255

def rgb_to_hsv(color):
    color = colorsys.rgb_to_hsv(color[0] / 255, color[1] / 255, color[2] / 255)
    return color[0] * 255, color[1] * 255, color[2] * 255

# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
LIGHTGREY = (200, 200, 200)
GREY = (128, 128, 128)
BLACK = (0, 0, 0)
TRANSPARENT = (0, 0, 0, 0)

CURRENTCOLOR = get_color(COLORPOS, VALUEPOS)

def draw_window(win, width, height, picker_changed, slider_changed, erasing, square_cursor, mode):
    win.fill(LIGHTGREY, (0, height - BOTTOMBARHEIGHT, width, BOTTOMBARHEIGHT))

    square_box = pygame.draw.rect(win, BLACK if not square_cursor else GREEN, (15, height - BOTTOMBARHEIGHT + 15, BOXWIDTH, BOXWIDTH), 5)
    pygame.draw.rect(win, CURRENTCOLOR if not close_to_white() else BLACK, (40, height - BOTTOMBARHEIGHT + 40, BOXWIDTH - 50, BOXWIDTH - 50)) # 50=(40-15)*2
    square_text = FONT_D.render("Square Pen", 1, BLACK)
    win.blit(square_text, (15 + BOXWIDTH - square_text.get_width(), height - BOTTOMBARHEIGHT + 15 + BOXWIDTH + 5))

    circle_box = pygame.draw.rect(win, BLACK if square_cursor else GREEN, (15 + BOXWIDTH + 15 + 15, height - BOTTOMBARHEIGHT + 15, BOXWIDTH, BOXWIDTH), 5)
    circle_text = FONT_D.render("Circle Pen", 1, BLACK)
    win.blit(circle_text, (15 + BOXWIDTH + BOXWIDTH + 15 + 4 - circle_text.get_width(), height - BOTTOMBARHEIGHT + 15 + BOXWIDTH + 5))
    pygame.draw.circle(win, CURRENTCOLOR if not close_to_white() else BLACK, (15 + BOXWIDTH + 15 + 15 + BOXWIDTH//2, height - BOTTOMBARHEIGHT + 15 + BOXWIDTH//2), 25)

    slider_box = pygame.draw.rect(win, GREY, (width - 25 - 240, height - BOTTOMBARHEIGHT + 25, 240, 15))  # (735, 845, 240, 15)
    pygame.draw.circle(win, WHITE, (BRUSHSIZE*(240//MAXBRUSHSIZE)+735, 845 + 15//2), 12)
    size_text = FONT_D.render(f"Brush Size: {BRUSHSIZE+1}", 1, BLACK)
    win.blit(size_text, (855 - size_text.get_width()//2, height - BOTTOMBARHEIGHT + 25 + 15 + 5))

    eraser_box = pygame.draw.rect(win, BLACK if not erasing else GREEN, (735 + 10, height - BOTTOMBARHEIGHT + 25 + 15 + 5 + 15 + size_text.get_height(), SMALLERBOXWIDTH, SMALLERBOXWIDTH), 5)
    win.blit(ERASER, (735 + 10, height - BOTTOMBARHEIGHT + 25 + 15 + 5 + 15 + size_text.get_height()))
    eraser_text = FONT_S.render("Eraser", 1, BLACK)
    win.blit(eraser_text, (735 + SMALLERBOXWIDTH//2 - eraser_text.get_width()//2 + 10, height - BOTTOMBARHEIGHT + 25 + 15 + 5 + 15 + size_text.get_height() + SMALLERBOXWIDTH + 5))

    clear_box = pygame.draw.rect(win, BLACK, (975 - SMALLERBOXWIDTH - 10, height - BOTTOMBARHEIGHT + 25 + 15 + 5 + 15 + size_text.get_height(), SMALLERBOXWIDTH, SMALLERBOXWIDTH), 5)
    win.blit(CLEAR, (975 - SMALLERBOXWIDTH - 10 + 7, height - BOTTOMBARHEIGHT + 25 + 15 + 5 + 15 + size_text.get_height() + 7))
    clear_text = FONT_S.render("Clear Screen", 1, BLACK)
    win.blit(clear_text, (975 - SMALLERBOXWIDTH//2 - clear_text.get_width()//2 - 10, height - BOTTOMBARHEIGHT + 25 + 15 + 5 + 15 + size_text.get_height() + SMALLERBOXWIDTH + 5))

    win.blit(PICKER, (15 + BOXWIDTH*2 + 15 + 15 + 80, height - BOTTOMBARHEIGHT + 5))
    pygame.draw.circle(win, WHITE, (COLORPOS[0] + 15 + BOXWIDTH*2 + 15 + 15 + 80, COLORPOS[1] + height - BOTTOMBARHEIGHT + 5), 5)
    pygame.draw.circle(win, BLACK, (COLORPOS[0] + 15 + BOXWIDTH*2 + 15 + 15 + 80, COLORPOS[1] + height - BOTTOMBARHEIGHT + 5), 6, 1)

    if picker_changed:
        draw_slider(15 + BOXWIDTH*2 + 15 + 15 + 80 + PICKER.get_width() + 10, height - BOTTOMBARHEIGHT + 5, 20, PICKER.get_height())
        picker_changed = False
    if slider_changed:
        update_picker()
        slider_changed = False

    win.blit(SLIDER, (0, 0))
    pygame.draw.circle(win, WHITE, (VALUEPOS[0], VALUEPOS[1]), 5)
    pygame.draw.circle(win, BLACK, (VALUEPOS[0], VALUEPOS[1]), 6, 1)

    pygame.draw.rect(win, CURRENTCOLOR, (15 + BOXWIDTH*2 + 15 + 15 + 80 + PICKER.get_width() + 10 + 20 + 15, height - BOTTOMBARHEIGHT + 15, BOXWIDTH + 50, BOXWIDTH + 50))

    info_text1 = FONT_D.render("Left Mouse Button: Normal Drawing", 1, BLACK)
    info_text2 = FONT_D.render("Middle Mouse Button: Draw Line", 1, BLACK)
    info_text3 = FONT_D.render("Right Mouse Button: Draw Dotted Line", 1, BLACK)

    text_x, text_y = (15, 740)
    win.blit(info_text1, (text_x, text_y))
    win.blit(info_text2, (text_x, text_y + info_text1.get_height() + 5))
    win.blit(info_text3, (text_x, text_y + info_text1.get_height() + 5 + info_text2.get_height() + 5))

    return square_box, circle_box, slider_box, eraser_box, clear_box, (15 + BOXWIDTH*2 + 15 + 15 + 80 + PICKER.get_width() + 10, height - BOTTOMBARHEIGHT + 5, 20, PICKER.get_height()), picker_changed, slider_changed

def close_to_white():
    if sum(WHITE) > 240*3:
        return True
    return False

def change_hue_sat(color, hue, sat):
    hsv_col = list(rgb_to_hsv(color))
    hsv_col[1] = hue
    hsv_col[2] = sat
    return hsv_to_rgb(hsv_col)

def get_hue(color):
    return rgb_to_hsv(color)[0]

def get_sat(color):
    return rgb_to_hsv(color)[1]

def draw_slider(x, y, width, height):
    global SLIDER
    SLIDER.fill(TRANSPARENT)
    for i in range(x, x + width + 1):
        for j in range(y, y + height + 1):
            b_w_color = [(j - (HEIGHT - BOTTOMBARHEIGHT + 5)) * (-255/170) + 255] * 3
            SLIDER.set_at((i, j), change_hue_sat(b_w_color, get_hue(CURRENTCOLOR), get_sat(CURRENTCOLOR)))

def get_value(color):
    return rgb_to_hsv(color)[2]

def update_picker():
    global PICKER
    w, h = PICKER.get_size()
    for x in range(w):
        for y in range(h):
            if math.sqrt((y - 85)**2 + (x - 85)**2) < 85:
                color = PICKER.get_at((x, y))
                PICKER.set_at((x, y), change_value(color, get_value(CURRENTCOLOR)))

def change_value(color, value):
    new_color = list(rgb_to_hsv(color))
    new_color[2] = value
    return hsv_to_rgb(new_color)

def main(win, width, height):
    global BRUSHSIZE, COLORPOS, VALUEPOS, CURRENTCOLOR
    win.fill(WHITE)
    prevX, prevY = pygame.mouse.get_pos()
    mode = 1
    picker_changed = True
    slider_changed = True
    erasing = False
    square_cursor = True
    run = True
    while run:
        square_box, circle_box, slider_box, eraser_box, clear_box, value_box, picker_changed, slider_changed = draw_window(win, width, height, picker_changed, slider_changed, erasing, square_cursor, mode)
        mouseX, mouseY = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN and mouseY < height - BOTTOMBARHEIGHT and event.button == 2:
                lineX, lineY = mouseX, mouseY

            if event.type == pygame.MOUSEBUTTONUP and mouseY < height - BOTTOMBARHEIGHT and event.button == 2:
                pygame.draw.line(win, CURRENTCOLOR, (lineX, lineY), (mouseX, mouseY), BRUSHSIZE)

            if square_box.collidepoint(mouseX, mouseY):
                if event.type == pygame.MOUSEBUTTONDOWN:
                    square_cursor = True if square_cursor == False else False

            if circle_box.collidepoint(mouseX, mouseY):
                if event.type == pygame.MOUSEBUTTONDOWN:
                    square_cursor = False if square_cursor == True else True

            if slider_box.collidepoint(mouseX, mouseY):
                if pygame.mouse.get_pressed()[0]:
                    BRUSHSIZE = (mouseX - 735)//(240//MAXBRUSHSIZE)

            if eraser_box.collidepoint(mouseX, mouseY):
                if event.type == pygame.MOUSEBUTTONDOWN:
                    erasing = True if erasing == False else False
                    CURRENTCOLOR = WHITE if erasing else get_color(COLORPOS, VALUEPOS)

            if clear_box.collidepoint(mouseX, mouseY):
                if event.type == pygame.MOUSEBUTTONDOWN:
                    win.fill(WHITE)

            if pygame.mouse.get_pressed()[0]:
                if mouseY < HEIGHT - BOTTOMBARHEIGHT:
                    if square_cursor:
                        pygame.draw.rect(win, CURRENTCOLOR, (mouseX - BRUSHSIZE//2, mouseY - BRUSHSIZE//2, BRUSHSIZE, BRUSHSIZE))
                    else:
                        pygame.draw.circle(win, CURRENTCOLOR, (mouseX, mouseY), BRUSHSIZE*11//20)

                if math.sqrt((mouseY - 910)**2 + (mouseX - 410)**2) < 85:
                    COLORPOS = (mouseX - 325, mouseY - 825)
                    CURRENTCOLOR = get_color(COLORPOS, VALUEPOS)
                    picker_changed = True
                    erasing = False
                if value_box[0] < mouseX < value_box[0] + value_box[2] and value_box[1] < mouseY < value_box[1] + value_box[3]:
                    VALUEPOS = (515, mouseY)
                    CURRENTCOLOR = get_color(COLORPOS, VALUEPOS)
                    slider_changed = True
                    erasing = False

            if pygame.mouse.get_pressed()[2]:
                if mouseY < HEIGHT - BOTTOMBARHEIGHT and math.sqrt((mouseY - prevY)**2 + (mouseX - prevX)**2) > BRUSHSIZE + 10:
                    if square_cursor:
                        pygame.draw.rect(win, CURRENTCOLOR, (mouseX - BRUSHSIZE//2, mouseY - BRUSHSIZE//2, BRUSHSIZE, BRUSHSIZE))
                    else:
                        pygame.draw.circle(win, CURRENTCOLOR, (mouseX, mouseY), BRUSHSIZE*11//20)
                    prevX, prevY = mouseX, mouseY

        pygame.display.update()

main(WINDOW, WIDTH, HEIGHT)


# we have to import opencv
import cv2 as cv

# in this file we will take an image and show it, as well
# a video too

# 1. Reading Image
# use the imread() to take input and store its array in image
img = cv.imread("Photos/cats.jpg")
# show the image using imshow()
cv.imshow("Cats", img)
# cv.waitKey(0)

# 2. Reading Videos
# 1st we have to include a source in a variable
capture = cv.VideoCapture("Videos/kitten.mp4")  # for camera use 0,1..

# for video we have to make a while loop
while True:

    isTrue, frame = capture.read()  # isTrue will tell us if there is video or not
    cv.imshow("Video", frame)

    if cv.waitKey(20) & 0xff == ord("s"):
        # if i pass 0 it waits for each frame a key to be press
        # if cv.waitKey(0) & off==ord('s'):
        break


#!/usr/bin/python

# git remote add origin https://github.com/mayweed/6.00x.git
# git push -u origin master

#s/raw_input()/input()/if py > 3
s = input('--> ')
count=0
for x in s:
    if x in ['a','e','i','o','u']:
        count +=1
print("Number of vowels: " , count)


t = 0
n = input()
first = int(n)

while True:
    num = list(n)
    num = list(map(int, num))
    sum_num = sum(num)

    right = sum_num % 10
    left = int(n) % 10

    new = 10 * left + right

    t += 1

    if(first == new):
        print(t)
        break
    else:
        n = str(new)


"""
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:

Input:
s = "aaabb", k = 3

Output:
3

The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:

Input:
s = "ababbc", k = 2

Output:
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
"""
class Solution(object):
    def longestSubstring(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        from collections import defaultdict
        lookup =defaultdict(list)
        for i, c in enumerate(s):
            lookup[c].append(i)
        less = [i for i in lookup.values() if len(i) < k]
        breakpt = []
        for j in less:
            for n in j:
                breakpt.append(n)

        1==1
if __name__ == '__main__':
    s = "aebabbc"
    k = 2
    print(Solution().longestSubstring(s, k))


# -*- coding: utf-8 -*-
# @Time    : 2019/1/12 16:52
# @Author  : Ming
from sqlalchemy.exc import IntegrityError

from . import app
from flask import jsonify, render_template, session, abort, flash, redirect, url_for, request, logging
from .model.post import Post
from .model.category import Category
from .model.entries import *
from .model.article import *
from .jianshu import *

# 简书教程学习
# https://www.jianshu.com/p/4bb97fe23272
@app.route('/jianshu/save')
def jianshu_save():
    user_id = '40758c9db703'
    user_url = 'https://www.jianshu.com/u/' + user_id + '?order_by=shared_at&page='
    '''建表'''
    db.create_all()

    item_list = Item_jianshu(user_url).get_category(1, [])

    # 存入数据库
    for temp in item_list:
        data = Item(category_name=temp[0], category_url=temp[1])
        body = Body_jianshu(temp[1]).get_body()
        article = Article(article_name=user_id, article_url=temp[1], article_text=body, category=data)
        try:
            db.session.add_all([data, article])
            db.session.commit()
        except IntegrityError as e:
            app.logger.debug(e)
            db.session.rollback()
        finally:
            pass

    return 'success'

@app.route('/jianshu/get')
def jianshu_get():
    temp = Item.query.all()
    return '%d' % len(temp)

@app.route('/jianshu/show', methods=['GET'])
def index():
    category_names = []
    category_query = Item.query.all()
    for temp in category_query:
        category_names.append(temp.category_name)
    return render_template('index.html', names=category_names)

# http://docs.jinkan.org/docs/flask/index.html教程学习
@app.route('/')
def show_entries():
    entries = Entry.query.order_by(Entry.id.desc()).all()
    output = []
    for data in entries:
        r_data = {}
        r_data['titile'] = data.title
        r_data['text'] = data.text
        output.append(r_data)
    return render_template('show_entries.html', entries=entries)

@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)  # 放弃请求并返回错误代码
    entries_new = Entry(request.form['title'], request.form['text'])
    db.session.add(entries_new)
    db.session.commit()
    flash('New entry wa successfully posted!')
    return redirect(url_for('show_entries'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True #键值对
            flash('You were logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))

# -------------------
# 入口测试
@app.route('/hello')
def hello_world():
    return 'hello_world'

# 建表
@app.route('/db/table/create')
def db_create():
    db.create_all()
    return '建表成功'

# -----------
# 数据库测试
@app.route('/dbtest', methods=['GET'])
def db_test():
    # 查询
    myData = Category.query.all()
    output = []
    print(len(myData))
    for data in myData:
        r_data = {}
        r_data['id'] = data.id
        r_data['name'] = data.name
        output.append(r_data)
    return jsonify({'message': output})
    # return "hello world"

@app.route('/db/category', methods=['POST', 'GET'])
def db_add():
    # 添加
    demo = Post("a", 'cc', Category('bb'), pub_date=None)
    db.session.add(demo)
    db.session.commit()

    # 修改
    myData = Category.query.all()
    print('修改前元素个数为：%d' % len(myData))
    demo.body = 'dd'
    db.session.commit()
    myData = Category.query.all()
    print('修改后元素个数：%d' % len(myData))

    # 删除
    db.session.delete

    if request.method == 'GET':
        return '请求成功'
    return 'POST请求'

# 定义404页面
@app.errorhandler(404)
def page_not_found(error):
    return '404'

@app.errorhandler(502)
def server_502_error(error):
    return '502'


# Test_Speach.
from colorama import init, Fore, Back, Style
import pyttsx3

init()

print(Fore.WHITE)
print("Program start")

print(Fore.YELLOW)

speak_engine = pyttsx3.init()

# если установлен голосовой пакет для синеза речи RHVoice
voices = speak_engine.getProperty("voices")
speak_engine.setProperty("voice", voices[1].id)

what = input() # Вводим текст с клавиауры, программа говорит через колонки.

speak_engine.say(what)
speak_engine.runAndWait()

print(Fore.WHITE)
print("Program finish")


import re, sys, os, time, json, pystray, colorsys, keyboard, tkinter as tk
from tkinter import Label, Frame, Entry, Toplevel, Button, LabelFrame
from threading import Thread
from pystray import Menu, MenuItem as item
from PIL import Image, ImageTk
from screeninfo import get_monitors
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    global DEBUG
    if DEBUG == False:
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)
    else:
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
            edited_base_path = base_path + "/Logitech GHub Battery Percentage Viewer"
            unedited_path = os.path.join(edited_base_path, relative_path)
            edited_path = unedited_path.replace('\\' , '/')
        return edited_path
DEBUG = False    # Defines what values to use for the location of files
""" Set DEBUG to False when freezing code """
Background_stuff_DEBUG = False    # Debug for Background_stuff thread, set to True to make all print functions in Background_stuff print to console, set to False if you dont want it to print to console
GUI_stuff_DEBUG = False    # Debug for GUI_stuff thread, set to True to make all print functions in Background_stuff print to console, set to False if you dont want it to print to console
Tray_stuff_DEBUG = False    # Debug for Tray_stuff thread, set to True to make all print functions in Background_stuff print to console, set to False if you dont want it to print to console
Colour_stuff_DEBUG = False
Tray_Custom_stuff_DEBUG = False
if Background_stuff_DEBUG == True:    # Prints current active status of Background stuff
    print("Background_stuff_DEBUG is Active")
if GUI_stuff_DEBUG == True:     # Prints current active status of GUI stuff
    print("GUI_stuff_DEBUG is Active")
if Tray_stuff_DEBUG == True:    # Prints current active status of Tray stuff
    print("Tray_stuff_DEBUG is Active")
if Colour_stuff_DEBUG == True:    # Prints current active status of Colour stuff
    print("Colour_stuff_DEBUG is Active")
if Tray_Custom_stuff_DEBUG == True:    # Prints current active status of Custom Location stuff
    print("Tray_Custom_stuff_DEBUG is Active")
def Background_stuff():
    global GUI_stuff_DEBUG
    global a_file
    global percentage
    global G502line
    global G915line
    global millivolts
    global timeline
    global charging
    global listhide
    global file_path
    global file
    global Chargestatus
    global counter
    global Background_stuff_DEBUG
    global quitmain
    def log(s):
        if Background_stuff_DEBUG == True:
            print(s)
    if quitmain == True:
        sys.exit()
    list = []
    NEWlist = []
    Chargestatus[0] = "0"
    Chargestatus[1] = "0"
    f = open(a_file, errors="ignore")
    for line in f:
        if G502line in line:
            log("line = " + line)           # Print
            line = re.findall(r'\d+', line)
            line = str(line); line = line[2:]; line = line[:-2]
            list.append(line)
            for i in range(3):
                followline = next(f)
                if timeline in followline:
                    followline = listhide
                else:
                    log("followline = " + followline)           # Print
                    if charging in followline:
                        del Chargestatus[0]
                        Chargestatus.insert(0, '1')
                        followline = listhide
                followline = re.findall(r'\d+', followline)
                followline = str(followline); followline = followline[2:]; followline = followline[:-2]
                list.append(followline)
        if G915line in line:
            log("line = " + line)           # Print
            line = re.findall(r'\d+', line)
            line = str(line); line = line[2:]; line = line[:-2]
            list.append(line)
            for i in range(3):
                followline = next(f)
                if timeline in followline:
                    followline = listhide   # Sets the line containing time to listhide
                else:
                    log("followline = " + followline)           # Print
                    if charging in followline:
                        del Chargestatus[1]
                        Chargestatus.append("1")
                        followline = listhide   # Sets the line containing charging to listhide
                followline = re.findall(r'\d+', followline)     # removes any items in the list that are not integers
                followline = str(followline); followline = followline[2:]; followline = followline[:-2]     # Removes all the values equal to listhide
                list.append(followline)     # adds followlone to the end of list
    if not list:
        log("List is empty")            # Print
        with open(resource_path('listfile.txt'), 'r') as filehandle:
            TEMPlist = json.load(filehandle)
        NEWlist = TEMPlist
        log("TEMPlist = " + str(TEMPlist))           # Print
        log("NEWlist = " + str(NEWlist))         # Print
    else:
        log("List is not Empty")            # Print
        log("list = " + str(list))           # Print
        while("" in list):
            list.remove("")     # Remove empty strings from list
        NEWlist = [x for x in list if int(x) <= 915]
        log("NEWlist = " + str(NEWlist))         # Print
        G502_Found = 0
        G915_Found = 0
        G502_Check = NEWlist[0]
        G915_Check = NEWlist[0]
        if G502_Check == str(502):
            log("G502 Check #1")            # Print
            list.remove(listhide)
            G502_Found = 1
        else:
            if G915_Check == str(915):
                log("G915 Check #2")            # Print
                list.remove(listhide)
                G915_Found = 1
        if G502_Found == 1:
            log("G502 Found #3")            # Print
            if len(NEWlist) == 4:
                log("NEWlist = 4")          # Print
                if NEWlist[-2] == str(915):
                    with open(resource_path('listfile.txt'), 'w') as filehandle:
                        json.dump(NEWlist, filehandle)
                else:
                    def swapPositions(list, pos1, pos2):
                        get = NEWlist[pos1], NEWlist[pos2]
                        NEWlist[pos2], NEWlist[pos1] = get
                        return NEWlist
                    pos1, pos2 = -1, -2
                    swapPositions(NEWlist, pos1=1, pos2=1)
            else:
                log("NEWlist = 2")          # Print
                with open(resource_path('listfile.txt'), 'r') as filehandle:
                    TEMPlist = json.load(filehandle)
                NEWlist.append(TEMPlist[-2])
                NEWlist.append(TEMPlist[-1])
                log("NEWlist = " + str(NEWlist))         # Print
                if NEWlist[-1] == str(915):
                    log("Rearranging")          # Print
                    def swapPositions(list, pos1, pos2):
                        get = NEWlist[pos1], NEWlist[pos2]
                        NEWlist[pos2], NEWlist[pos1] = get
                        return NEWlist
                    pos1, pos2 = -1, -2
                    swapPositions(NEWlist, pos1=1, pos2=1)
                log("NEWlist = " + str(NEWlist))         # Print
                with open(resource_path('listfile.txt'), 'w') as filehandle:
                    json.dump(NEWlist, filehandle)
        else:
            if G915_Found == 1:
                log("G915 Found")           # Print
                if len(NEWlist) == 2:
                    with open(resource_path('listfile.txt'), 'r') as filehandle:
                        TEMPlist = json.load(filehandle)
                NEWlist.insert(0, TEMPlist[1])
                NEWlist.insert(0, TEMPlist[0])
                log("NEWlist = " + str(NEWlist))         # Print
                with open(resource_path('listfile.txt'), 'w') as filehandle:
                    json.dump(NEWlist, filehandle)
        log("NEWlist = " + str(NEWlist))            # Print
        with open(resource_path('listfile.txt'), 'w') as filehandle:
            json.dump(NEWlist, filehandle)
        with open(resource_path('Current_Percentage.txt'), 'w') as filehandle:
            json.dump(NEWlist, filehandle)
        with open(resource_path('Current_Charge.txt'), 'w') as c:
            json.dump(Chargestatus, c)
    time.sleep(0)
    if GUI_stuff_DEBUG == False:
        global spacer
        log(spacer + 'Counter: ' + str(counter))            # Print
    log("Refresher")            # Print
    Refresher()
def Tray_stuff():
    global frame1
    global Tray_stuff_DEBUG
    global hideshow
    global showhidestate
    global quitmain
    global loc
    def log(s):
        if Tray_stuff_DEBUG == True:
            print(s)
    win=tk.Tk()
    def showhide():
        global hideshow
        global showhidestate
        if showhidestate == 1:
            log("hideshow = 1  ,  Window is now Visible")           # Print
            hideshow = 1
        if showhidestate == 0:
            log("hideshow = 0  ,  Window is now Hidden")            # Print
            hideshow = 0
    def quit_window(icon, item):
        global quitmain
        quitmain = True
        icon.stop()
        win.destroy()
        os._exit()
    def loc1():         # Bottom Location
        global loc
        loc = "150x150-1930+1029"
    def loc2():         # Top Location
        global loc
        loc = "150x150-1930-941"
    def loc3():         # Left Location
        global loc
        loc = "150x150-3697+999"
    def loc4():         # Right Location
        global loc
        loc = "150x150-1839+999"
    def CustomLoc():
        global loc
        global Tray_Custom_stuff_DEBUG
        global Colour_stuff_DEBUG
        def log(s):
                if Tray_Custom_stuff_DEBUG == True:
                    print(s)
        def SelectCom():
            global loc
            global MonXval
            global MonYval
            locXval = locXin.get()
            locYval = locYin.get()
            if '-' not in locXval:
                locX = "+" + locXval
            else:
                locX = locXval
            if '-' not in locYval:
                locY = "+" + locYval
            else:
                locY = locYval
            loctest = "150x150" + locX + locY
            if loctest != "150x150++":
                loc = "150x150" + locX + locY
            log("                                                                                " + loc)           # Print
        def CancelCom():
            root1.withdraw()
        def selection():
            curloc = re.findall(r'-?\d+', loc)      # Extract all numbers into a list
            log(curloc)           # Print
            log(curloc[2]+" :curloc[2]")           # Print
            curX = curloc[2]
            curY = curloc[3]
            currentloc.config(text="Current location: "+"X: "+str(curX)+"  "+"Y: "+str(curY))
        def dragenable(s):
            lastClickX = 0
            lastClickY = 0
            def SaveLastClickPos(event):
                global lastClickX, lastClickY
                lastClickX = event.x
                lastClickY = event.y
                print(lastClickX,lastClickY)
            def Dragging(event):
                global lastClickX, lastClickY
                print(lastClickX,lastClickY)
                x = event.x - lastClickX + root1.winfo_x()
                y = event.y - lastClickY + root1.winfo_y()
                root1.geometry("+%s+%s" % (x , y))
            root1.bind('<Button-1>', SaveLastClickPos)
            root1.bind('<B1-Motion>', Dragging)
        def dragdisable(s):
            root1.unbind('<Button-1>')
            root1.unbind('<B1-Motion>')
        def rgb_to_hex(r, g, b):
            # helper function
            def help(c):
                if c<0: return 0
                if c>255: return 255
                return c
            # make sure that values are within bounds
            r = help(r)
            g = help(g)
            b = help(b)
            # convert to hex
            # maintain 2 spaces each
            val = "%02x%02x%02x" % (r, g, b)
            # return UpperCase string
            return val.upper()
        def colour():
            global r,g,b
            global Colour_stuff_DEBUG
            def log(s):
                if Colour_stuff_DEBUG == True:
                    print(s)
            num_steps = 1800 # arbitrary
            """ Any Number above 1800 doesnt really change the smoothness of the transition of colours that much """
            hue = 0.0
            step_val = 1.0 / num_steps
            while True:
                rgb = colorsys.hsv_to_rgb(hue, 1, 1)
                hue += step_val
                hue %= 1.0 # cap hue at 1.0
                r = round(rgb[0] * 255)
                g = round(rgb[1] * 255)
                b = round(rgb[2] * 255)
                log(str(r)+' '+str(g)+' '+str(b))           # Print
                rgb_ints = (r, g, b)
                log(rgb_ints)           # Print
                time.sleep(0.01)
                log(str(r)+' '+str(g)+' '+str(b))           # Print
                log(rgb_to_hex(r,g,b))           # Print
                frame1['highlightbackground']="#"+rgb_to_hex(r,g,b)
        root1 = Toplevel()
        root1.title("Logitech GHub Battery Viewer")        # Names the Tk root window
        root1.overrideredirect(1)        # Removes title bar from window
        root1.wm_attributes("-topmost", True)        # Makes the window always stay on top
        root1.configure(background="#000000")        # Makes background of window black
        root1.geometry("+%s+%s" % (0 , 0))        # Sets the size of the window to fit everything
        frame1 = Frame(root1, highlightbackground="#000000", highlightthickness=2, bg='#000000')        # Border for the Custom Location Window
        frame1.grid(padx=0, pady=0)
        titletext=Label(frame1, text="Custom Location", fg='#ffffff', bg='#000000')        # Border for the Custom Location Window
        titletext.grid(row = 1, column = 0, pady = 2, columnspan = 4)
        Xtext=Label(frame1, text="X:", fg='#ffffff', bg='black')        # X: label for the Custom Location Window
        Xtext.grid(row = 2, column = 1, pady = 2, sticky="e")
        locXin = Entry(frame1, font=('calibre',10,'normal'), show = None, fg='#ffffff', bg='#000000')        # X value input for the Custom Location Window
        locXin.grid(row = 2, column = 2, pady = 2, padx = (0,4))
        Ytext=Label(frame1, text="Y:", fg='#ffffff', bg='#000000')        # Y: label for the Custom Location Window
        Ytext.grid(row = 3, column = 1, pady = 2, sticky="e")
        locYin = Entry(frame1, font=('calibre',10,'normal'), show = None, fg='#ffffff', bg='#000000')        # Y value input for the Custom Location Window
        locYin.grid(row = 3, column = 2, pady = 2, padx = (0,4))
        monitorlist = []
        for m in get_monitors():        # Gets monitor info
            log(m)        # Prints monitor info
            monitorlist.append(m)        # Adds monitor info to a list
        log(monitorlist)        # Prints the list containing the monitor info
        monlistlen = len(monitorlist)        # Gets the length of the list containing the monitor info
        level = -1
        newmonlist = []
        list123 = []
        dislist = []
        current = 0
        currentt = -1
        for i in range(monlistlen):        # Repeat the following code as many times as there are items in the list containing the monitor info
            level = level + 1
            dislisttext = "Display " + str(level)
            dislist.append(dislisttext)
            log(dislisttext)           # Print
            log(dislist)           # Print
            monlistitem = str(monitorlist[level])
            sep = ", width_mm="
            stripped = monlistitem.split(sep, 1)[0]        # Separates an item from the list containing the monitor info and removes any unnecessary data
            newmonlist.append(stripped)        # Adds the separated necessary data to a list
            log(stripped)        # Prints the data the necessary data the was spearated
            newitems = re.findall(r'-?\d+', stripped)      # Extract all numbers into a list
            list123.append(newitems)        # Adds the extracted data to a list
            log(list123)        # Prints the list of extracted data
        loclist=re.findall(r'-?\d+', loc)      # Extract all numbers into a list
        log(loclist)        # Prints the list of extracted data
        curX = loclist[2]
        curY = loclist[3]
        currentloc=Label(frame1, text="Current location: "+"Xâ€‰:â€Š"+str(curX)+"  "+"Yâ€‰: "+str(curY), fg='#ffffff', bg='#000000')       # Current location label for the Custom Location Window
        currentloc.grid(row = 7, column = 1, pady = 2, columnspan = 3)
        ButtonSel=Button(frame1, text="Select", bg="#3c3c3c", fg="white", activebackground="#5a5a5a", command=SelectCom)       # Select button for the Custom Location Window
        ButtonSel.grid(row = 10, column = 2, pady = 2, padx = 2, sticky="e", columnspan = 2)
        ButtonClose=Button(frame1, text="Close", bg="#3c3c3c", fg="white", activebackground="#5a5a5a", command=CancelCom)       # Close button for the Custom Location Window
        ButtonClose.grid(row = 10, column = 1, pady = 2, padx = (3,2), sticky="w", columnspan = 2)
        keyboard.on_press_key("ctrl", dragenable)       # Detect when the CTRL key is pressed and when it is call dragenable
        keyboard.on_release_key("ctrl", dragdisable)       # Detect when the CTRL key is released and when it is call dragdisable
        colour()
        selection()
    def hide_window():
        global visibility
        win.withdraw()
        image=Image.open(resource_path('battery.ico'))
        menu=(item('Quit', quit_window), item("Location:", Menu(item('Bottom', loc1), item('Top', loc2), item('Left', loc3), item('Right', loc4), item('Custom', CustomLoc))), item('Hide/Show', showhide))
        icon=pystray.Icon("name", image, "Battery Viewer", menu)
        icon.run()
    win.protocol('WM_DELETE_WINDOW', hide_window)
    hide_window()
    win.mainloop()
def log(s):
    if GUI_stuff_DEBUG == True:
        print(s)
def Draw():
    global G915
    global G502
    frame=tk.Frame(root,width=100,height=100,relief='solid',bd=0, bg="grey")
    frame.place(x=10,y=10)
    G915=tk.Label(frame,text=CURRENTPERCENTAGES, bg="grey", fg="white")
    G915.pack()
    G502=tk.Label(frame,text=CURRENTPERCENTAGES, bg="grey", fg="white")
    G502.pack()
def Refresher():
    global spacer
    global counter
    global showhidestate
    global hideshow
    global quitmain
    global loc
    global G915
    global G502
    if hideshow == 0:
        log("root.withdraw()")          # Print
        root.withdraw()
        showhidestate = 1
    if hideshow == 1:
        log("root.update()")            # Print
        root.update()
        root.deiconify()
        showhidestate = 0
    if quitmain == True:
        sys.exit()
    def show():
        root.update()
        root.deiconify()
    def hide():
        root.withdraw()
    with open(resource_path('Current_Percentage.txt'), 'r') as filehandle:
        CURRENTPERCENTAGES = json.load(filehandle)
    with open(resource_path('Current_Charge.txt'), 'r') as filehandle:
        CurrentCharge = json.load(filehandle)
    log("CurrentCharge = " + str(CurrentCharge))         # Print
    log("CURRENTPERCENTAGES = " + str(CURRENTPERCENTAGES))           # Print
    charge502 = "    "
    charge915 = "    "
    log(CurrentCharge[0] +" < first item in list")          # Print
    log(CurrentCharge[1] +" < second item in list")         # Print
    if CurrentCharge[0] == "1":
        log("G502: " + charge502 + "ðŸ—²")           # Print
        charge502 = "ðŸ—²"
    if CurrentCharge[1] == "1":
        log("G915: " + charge915 + "ðŸ—²")           # Print
        charge915 = "ðŸ—²"
    if loc == "150x150-1839+999":      # Right Location
        G502.configure(text="G"+CURRENTPERCENTAGES[0] + " :"+ charge502 + CURRENTPERCENTAGES[1] + "%", font=("Segoe UI", 7))
        G915.configure(text="G"+CURRENTPERCENTAGES[-2] + " :"+ charge915 + CURRENTPERCENTAGES[-1] + "%", font=("Segoe UI", 7))
    else:
        if loc == "150x150-3697+999":      # Left Location
            G502.configure(text="G"+CURRENTPERCENTAGES[0] + " :"+ charge502 + CURRENTPERCENTAGES[1] + "%", font=("Segoe UI", 7))
            G915.configure(text="G"+CURRENTPERCENTAGES[-2] + " :"+ charge915 + CURRENTPERCENTAGES[-1] + "%", font=("Segoe UI", 7))
        else:
            if loc == "150x150-1930+1029":      # Bottom Location
                G502.configure(text="G"+CURRENTPERCENTAGES[0] + " :"+ charge502 + CURRENTPERCENTAGES[1] + "%", font=("Segoe UI", 9))
                G915.configure(text="G"+CURRENTPERCENTAGES[-2] + " :"+ charge915 + CURRENTPERCENTAGES[-1] + "%", font=("Segoe UI", 9))
            else:
                if loc == "150x150-1930-941":      # Top Location
                    G502.configure(text="G"+CURRENTPERCENTAGES[0] + " :"+ charge502 + CURRENTPERCENTAGES[1] + "%", font=("Segoe UI", 9))
                    G915.configure(text="G"+CURRENTPERCENTAGES[-2] + " :"+ charge915 + CURRENTPERCENTAGES[-1] + "%", font=("Segoe UI", 9))
    root.geometry(loc) # Sets the size of the window
    counter = counter + 1
    spacer = "                                                                           "      # Used to make the counter stand out in the console, to make it easier to see
    log(spacer + 'Counter: ' + str(counter))           # Print
    root.after(1000, Background_stuff) # every second it reruns the code in the Refresher
Chargestatus = []   # Create list called Chargestatus
Chargestatus.append("0")    # set first item in list to 0
Chargestatus.append("0")    # set second item in list to 0
counter = 0
a_file = str(os.path.expandvars('%LOCALAPPDATA%'))+ "/LGHUB/settings.db"    # Gets the filepath for the Logitech GHub settings which contains the values for the battery percentages
print(a_file)         # Print
percentage = str("percentage")      # Line in a_file containing the word percentage
G502line = str("battery/g502wireless/percentage")       # Line in a_file containing battery/g502wireless/percentage,,, Used to determine which device the following info is in regards to
G915line = str("battery/g915/percentage")       # Line in a_file containing battery/g915/percentage,,, Used to determine which device the following info is in regards to
millivolts = str("millivolts")      # Line in a_file containing the word millivolts
timeline = "time"        # Line in a_file containing the word time
charging = "isCharging"      # Line in a_file containing the word isCharging
listhide = "999"        # Used to replace values in list to make it easier to remove them later
file_path = os.path.realpath(__file__)
file = resource_path('listfile.txt')
Chargestatus[0] = "0"
Chargestatus[1] = "0"
hideshow = 1
showhidestate = 1
quitmain = False
if quitmain == True:
    sys.exit()
loc = "150x150-1930+1029"
Thread(target = Tray_stuff).start()
CURRENTPERCENTAGES = []
root = tk.Tk()
root.title("Logitech GHub Battery Viewer")# Names the Tk root window
root.geometry("150x150-1930+1029") # Sets the size of the window
root.overrideredirect(1) # Removes title bar from window
root.configure(bg='grey') # Makes backgroud fo window grey
root.wm_attributes("-topmost", True) # Makes the window always stay on top
root.wm_attributes("-transparentcolor", "grey") # Makes the window background transparent
with open(resource_path('Current_Percentage.txt'), 'r') as filehandle:
    CURRENTPERCENTAGES = json.load(filehandle)
with open(resource_path('Current_Charge.txt'), 'r') as filehandle:
    CurrentCharge = json.load(filehandle)
Draw()
Refresher()
root.mainloop()


#Write your code below this line ðŸ‘‡

import math

def prime_checker (number):
    divisor = math.ceil(number / 2)
    while divisor >= 2:
        remainder = number % divisor
        print(f"{number} % {divisor} = {remainder}")
        if remainder == 0:
            print(f"NOT PRIME")
            return False
        else:
            divisor -= 1

    print(f"LIKELY PRIME ;)")
    return True

#Write your code above this line ðŸ‘†

#Do NOT change any of the code belowðŸ‘‡
n = int(input("Check this number: "))
prime_checker(number=n)


import gym
import site
from numpy import array as A
site.addsitedir('/home/patrick/projects/IA/my-2048/src')
import gy2048
# from gy2048.env import Base2048Env
# from numpy.random import choice

env = gym.make('2048-v0', width=2, height=2)

dico = {}
# rewards = []
for i in range(1000):
    done = False
    env.reset()
    print('state', env.state, sum(env.state))
    if sum(env.state) != 2:
        continue
    print('--------------------------------')
    print(env.state)

    while not done:
        # action = int(input())
        # board, reward, done, infos = env.step(action)
        state = tuple(env.state)
        action = env.sample()
        board, reward, done, infos = env.step(action)
        if state not in dico or dico[state]['reward'] < reward:
            dico[state] = {'reward': reward, 'action': action}

        print(env.state, reward, done, env.nb_free_cases)
        # env.render()
        # print('--------------------------------')

    # rewards.append(reward)

# print(rewards)
print(len(dico))
for state, data in dico.items():
    print(state, data)

dico = {
    (0, 1, 0, 1): 1,
    (0, 0, 1, 1): 0,
    (1, 1, 0, 0): 0,
    (1, 0, 1, 0): 1,
}


from fastapi import FastAPI, UploadFile, Path, HTTPException, status
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from typing import List
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient, ContainerClient
from azure.core.exceptions import ResourceNotFoundError
from dotenv import load_dotenv
from os import environ

load_dotenv()

app = FastAPI(
    title="Azure Blobs API Example",
    redoc_url=None
)

# Authorization based on a storage account connection string:
# blob_service_client = BlobServiceClient.from_connection_string(conn_str=environ["STORAGE_ACCOUNT_CONNECTION_STRING"])

# Authorization based on a storage account access key:
# blob_service_client = BlobServiceClient(environ["STORAGE_ACCOUNT_URL"], credential=environ["STORAGE_ACCOUNT_ACCESS_KEY"])

# DefaultAzureCredential relies on "az login" for local development and Managed Identities when the application is deployed to the cloud.
default_credential = DefaultAzureCredential()
blob_service_client = BlobServiceClient(environ["STORAGE_ACCOUNT_URL"], credential=default_credential)

# Creating the ContainerClient using DefaultAzureCredential:
container_name = environ["CONTAINER_NAME"]
container_client = ContainerClient(account_url=blob_service_client.url, container_name=container_name, credential=default_credential)

if not container_client.exists():
    container_client.create_container()

# Creating the ContainerClient using a connection string:
# container_client = ContainerClient.from_connection_string(conn_str=environ["CONTAINER_CONNECTION_STRING"], container_name=container_name)
# container_client.create_container()

# Creating a new container with a unique name when the application starts:
# import uuid
# container_name = str(uuid.uuid4())
# container_client = blob_service_client.create_container(container_name, public_access="blob")

class UploadResponse(BaseModel):
    message: str

@app.post("/upload", status_code=status.HTTP_201_CREATED, response_model=UploadResponse, tags=["files"])
def upload_file(file: UploadFile):
    file_contents = file.file.read()
    # Upload using the container client:
    container_client.upload_blob(name=file.filename, data=file_contents, length=file.size)
    # Upload using a blob client:
    # blob_client = blob_service_client.get_blob_client(container=container_name, blob=file.filename)
    # blob_client.upload_blob(data=file_contents, length=file.size)
    return {"message": f"Successfully uploaded {file.filename}"}

class ListFilesResponse(BaseModel):
    files: List[str]

@app.get("/files", response_model=ListFilesResponse, tags=["files"])
def list_all_files():
    blob_list = []
    for blob in container_client.list_blob_names():
        blob_list.append(blob)
    return {"files": blob_list}

@app.get("/files/{filename}", response_class=StreamingResponse, tags=["files"])
def download_file(filename: str = Path()):
    try:
        # Download using the container client:
        blob = container_client.download_blob(blob=filename)
        # Download using a blob client:
        # blob_client = blob_service_client.get_blob_client(container=container_name, blob=filename)
        # blob = blob_client.download_blob()
        return StreamingResponse(blob.chunks())
    except ResourceNotFoundError:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)

@app.put("/files/{filename}", response_model=UploadResponse, tags=["files"])
def update_file(file: UploadFile, filename: str = Path()):
    blob_client = container_client.get_blob_client(blob=filename)
    if not blob_client.exists():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
    # Overwrite using the container client:
    file_contents = file.file.read()
    # container_client.upload_blob(name=file.filename, data=file_contents, length=file.size, overwrite=True)
    # Overwrite using the blob client
    blob_client.upload_blob(data=file_contents, length=file.size, overwrite=True)
    return {"message": f"Successfully updated {filename}"}

@app.delete("/files/{filename}", status_code=status.HTTP_204_NO_CONTENT, tags=["files"])
def delete_file(filename: str = Path()):
    try:
        # Delete using the container client:
        container_client.delete_blob(blob=filename)
        # Delete using a blob client:
        # blob_client = blob_service_client.get_blob_client(container=container_name, blob=filename)
        # blob_client.delete_blob()
    except ResourceNotFoundError:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File  : bdwk_doc_spider.py
@Author: kuangxianghui
@Date  : 2020/4/28 21:25
@Desc  : download doc of bdwk
@Python Version: 3.6.2
BeautifulSoup version: 4.9.0
selenium version: 3.141.0
"""

import os
import time
import re
import atexit
import traceback
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

# only download words, can't download other type
# need to download doc url
url = '/path/to/yours'
# save path, modify it by yourself
path = "test.txt"
# drop head and tail
drop_head_tail = True
# Driver
browser = webdriver.Chrome()

@atexit.register
def clean():
    browser.quit()

def handle_per_page(page_source, page_id):
    soup = BeautifulSoup(page_source, 'lxml')
    div = soup.find(id=page_id)
    p_list = div.select(".ie-fix > p")
    data = {}
    for p in p_list:
        style = p['style']
        top_px = int(re.search('top:(.*?)px', style).group(1))
        text = p.get_text()
        content_list = data.get(top_px)
        if content_list is None:
            content_list = []
            data[top_px] = content_list
        content_list.append(text)
    px_list = data.keys()
    if drop_head_tail:
        head_top_px = min(px_list)
        tail_top_px = max(px_list)
        px_list = filter(lambda key: key != head_top_px and key != tail_top_px, px_list)
    result_list = map(lambda x: ''.join(data.get(x)), px_list)
    return os.linesep.join(result_list)

def main():
    browser.get(url)
    browser.maximize_window()
    wait = WebDriverWait(browser, 10)
    # wait reader go more div appear
    wait.until(EC.presence_of_element_located((By.ID, 'html-reader-go-more')))
    # 继续阅读按钮
    go_more_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#html-reader-go-more span[class=fc2e]')))
    go_more_div = browser.find_element(By.ID, 'html-reader-go-more')
    # 页面调试的时候情况总是起伏
    # 需要将按钮滚动到能看见继续阅读才能进行点击，不然会出现not clickable
    browser.execute_script('arguments[0].scrollIntoView();', go_more_div)
    # sleep avoid
    time.sleep(3)
    # 滚到可视位置，进行点击
    go_more_button.click()
    # 等待刷新全部内容
    time.sleep(5)
    try:
        # 因为百度不会缓存全部页，一页一页滚动
        page_template = "pageNo-{}"
        logfile = open(path, 'a', encoding='utf-8')
        total_page_element = browser.find_element_by_xpath('//div[contains(@class, "reader-tools-bar-wrap")]'
                                                           '//div[@class="center"]//span[@class="page-count"]')
        total_page = int(re.search("\\d+", total_page_element.text).group()) + 1
        for i in range(1, total_page):
            page_index = page_template.format(i)
            page = browser.find_element(By.ID, page_index)
            browser.execute_script('arguments[0].scrollIntoView();', page)
            time.sleep(2)
            # handle per page
            page_content = handle_per_page(browser.page_source, page_index)
            logfile.write(page_content)
            logfile.write(os.linesep)
            time.sleep(2)
            if i % 3 == 0:
                time.sleep(3)
    except Exception as e:
        print(traceback.format_exc(), e)
    finally:
        logfile.close()

main()


from django.db import models
from django.conf import settings
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

from notification.models import GroupNotification

class GroupChatRoom(models.Model):
    """
    A group room for people to chat in.
    """

    title = models.CharField(max_length=255, unique=False, blank=False)
    users = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        blank=True,
        help_text="Users who belong to the group",
        related_name="group_chat_users",
    )
    admins = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        blank=False,
        help_text="Users with more privileges",
        related_name="admins",
    )
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=False,
        help_text="The user who created the group",
        related_name="owner",
    )
    connected_users = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        blank=True,
        help_text="Users who are currently connected to the group chat",
        related_name="group_chat_connected_users",
    )

    def __str__(self):
        return self.title

    def add_user(self, user):
        """
        Returns True if user is aded to the users list
        """
        is_user_added = False
        # Check if user is not in users list
        if user not in self.users.all():
            self.users.add(user)
            self.save()
            # Create UnreadGroupChatRoomMessages object
            UnreadGroupChatRoomMessages.objects.create(room=self, user=user)
            is_user_added = True
        return is_user_added

    def remove_user(self, user):
        """
        Returns True if user is removed from users list
        """
        is_user_removed = False
        # Check if user is in the users list
        if user in self.users.all():
            self.users.remove(user)
            self.save()
            # Delete UnreadGroupChatRoomMessages object
            ug = UnreadGroupChatRoomMessages.objects.get(user=user, room=self)
            ug.delete()
            is_user_removed = True
        return is_user_removed

    def connect_user(self, user):
        """
        Returns True if user is added to connected_users list
        """
        connected_user = False
        if user in self.users.all():
            self.connected_users.add(user)
            self.save()
            connected_user = True
        return connected_user

    def disconnect_user(self, user):
        """
        Returns True if user is removed from connected_users list
        """
        disconnected_user = False
        if user in self.users.all() and user in self.connected_users.all():
            self.connected_users.remove(user)
            self.save()
            disconnected_user = True
        return disconnected_user

    def add_admin(self, user):
        """
        Add user to admins group
        """
        # Check if user is in the users list
        if user in self.users.all():
            # Add user to admins group
            self.admins.add(user)
            self.save()

    def remove_admin(self, user):
        """
        Remove user from admins group
        """
        # Check if user is admin
        if user in self.admins.all():
            self.admins.remove(user)
            self.save()

    def is_admin(self, user):
        """
        Returns True if given user is in the admin group
        """
        is_admin = False
        if user in self.admins.all():
            is_admin = True
        return is_admin

    def is_owner(self, user):
        """
        Returns True if given user is the owner of the group
        """
        is_owner = False
        if self.owner == user:
            is_owner = True
        return is_owner

    @property
    def group_name(self):
        """
        Returns the Channels Group name that sockets should subscribe to to get sent
        messages as they are generated.
        """
        return f"GroupChatRoom-{self.id}"

class GroupChatMessageManager(models.Manager):
    def by_room(self, room):
        """
        Return every message by specific room, order by latest message
        """
        qs = GroupChatMessage.objects.filter(room=room).order_by("-timestamp")
        return qs

class GroupChatMessage(models.Model):
    """
    Chat message created by a user inside a Room
    """

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    room = models.ForeignKey(GroupChatRoom, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    content = models.TextField(
        unique=False,
        blank=False,
    )

    objects = GroupChatMessageManager()

    def __str__(self):
        return self.content

class UnreadGroupChatRoomMessages(models.Model):
    """
    Keep track of the number of unread messages by a specific user in a specific private chat.
    When the user connects the chat room, the messages will be considered "read" and 'count' will be set to 0.
    """

    room = models.ForeignKey(
        GroupChatRoom, on_delete=models.CASCADE, related_name="room"
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    count = models.IntegerField(default=0)

    most_recent_message = models.CharField(max_length=500, blank=True, null=True)

    # last time msgs were read by the user
    reset_timestamp = models.DateTimeField()

    notifications = GenericRelation(GroupNotification)

    def __str__(self):
        return f"Messages that {str(self.user.username)} has not read yet."

    def save(self, *args, **kwargs):
        if (
            not self.id
        ):  # if just created, add a timestamp. Otherwise do not automatically change it ever.
            self.reset_timestamp = timezone.now()
        return super(UnreadGroupChatRoomMessages, self).save(*args, **kwargs)

    @property
    def get_cname(self):
        """
        For determining what kind of object is associated with a Notification
        """
        return "UnreadGroupChatRoomMessages"

    @property
    def get_group_name(self):
        """
        Get the group name
        """
        return self.room.title

@receiver(pre_save, sender=UnreadGroupChatRoomMessages)
def increment_unread_msg_count(sender, instance, **kwargs):
    """
    When the unread message count increases, update the notification.
    If one does not exist, create one. (This should never happen)
    """
    if instance.id is None:  # new object will be created
        pass
    else:
        previous = UnreadGroupChatRoomMessages.objects.get(id=instance.id)
        if previous.count < instance.count:  # if count is incremented
            content_type = ContentType.objects.get_for_model(instance)
            try:
                notification = GroupNotification.objects.get(
                    target=instance.user,
                    content_type=content_type,
                    object_id=instance.id,
                )
                notification.verb = instance.most_recent_message
                notification.timestamp = timezone.now()
                notification.save()
            except GroupNotification.DoesNotExist:
                instance.notifications.create(
                    target=instance.user,
                    from_group=instance.room.title,
                    redirect_url=f"{settings.BASE_URL}/group_chat/?room_id={instance.room.id}",
                    verb=instance.most_recent_message,
                    content_type=content_type,
                )

@receiver(pre_save, sender=UnreadGroupChatRoomMessages)
def remove_unread_msg_count_notification(sender, instance, **kwargs):
    """
    If the unread messge count decreases, it means the user joined the chat. So delete the notification.
    """
    if instance.id is None:  # new object will be created
        pass
    else:
        previous = UnreadGroupChatRoomMessages.objects.get(id=instance.id)
        if previous.count > instance.count:  # if count is decremented
            content_type = ContentType.objects.get_for_model(instance)
            try:
                notification = GroupNotification.objects.get(
                    target=instance.user,
                    content_type=content_type,
                    object_id=instance.id,
                )
                notification.delete()
            except GroupNotification.DoesNotExist:
                pass


from functools import lru_cache

class TreeNode():
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def generateTrees(self, n: int):
        # leet code n ranges between 1 ot 8 for larger n use lru_cache to memoize
        # @lru_cache
        def arrayToTree(low, high):
            if low <= high:
                output = []
                for i in range(low, high+1):
                    leftTreeArr = arrayToTree(low, i-1)
                    rightTreeArr = arrayToTree(i+1, high)
                    for leftTree in leftTreeArr:
                        for rightTree in rightTreeArr:
                            output.append(
                                TreeNode(i, leftTree, rightTree))
                return output
            else:
                return [None]
        output = arrayToTree(1, n)
        return output

if __name__ == "__main__":
    n = 13
    output = Solution().generateTrees(n)
    print(len(output))


def findDisappearedNumbers(nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        nums=list(nums)
        n=len(nums)

        dis=[]
        i=1
        for e in nums:
                if nums.count(i)==0:
                        dis.append(i)
                i+=1

        return dis

ans=findDisappearedNumbers([4,3,2,7,8,2,3,1])
print(ans)


import matplotlib.pyplot as plt
import csv
import itertools
import math
import operator
import sys
import datetime
izip = itertools.izip

f=open(sys.argv[1])
next(f) # skip first line
elapsed_time = []
response_time = []
for row in csv.reader(f):
    elapsed_time.append(int(row[3]))
    response_time.append(int(row[4]))

time_step = 1000000000.0
bins = int(math.ceil((elapsed_time[-1] - elapsed_time[0])/time_step))+1

response_time_sum = [0] * bins
msg_count = [0] * bins

for e,r in izip(elapsed_time,response_time):
    index = int(math.ceil((e - elapsed_time[0])/time_step))
    response_time_sum[index] += r
    msg_count[index] += 1

average_response_time = [0.0 if c == 0 else s/(c*1000000.0) for s, c in izip(response_time_sum, msg_count)];
del average_response_time[0]
del msg_count[0]

steps = range(1,bins)

plt.plot(steps, average_response_time, 'b')
plt.ylabel('Average response time (ms/second)')
plt.xlabel('Elapsed seconds')
plt.xlim([1,bins-1])

# dt = datetime.datetime.now()
# plt.savefig('../gen/avg_resp_time.' + dt.strftime("%Y%m%d%H%M%S") + '.png', bbox_inches='tight')
plt.show()


import random
import shap
import keras
import pandas as pd
import numpy as np
import lightgbm as lgb
import tensorflow as tf
from gensim.models import Word2Vec
from keras.preprocessing import text
import matplotlib.pyplot as plt

df = pd.read_csv('data3.csv')
data = df.values
X_train = []
y_train = []
for i in data:
    X_train.append(i[2])
    y_train.append(0 if i[0] == -1 else 1)

X_train = np.array(X_train)
y_train = np.array(y_train)

class TextPreprocessor(object):
    def __init__(self, vocab_size):
        self._vocab_size = vocab_size
        self._tokenizer = None

    def create_tokenizer(self, text_list):
        tokenizer = text.Tokenizer(num_words=self._vocab_size)     # 对文本中的词进行统计计数，生成文档词典，以支持基于词典位序生成文本的向量表示
        tokenizer.fit_on_texts(text_list)   # 用以训练的文本列表
        self._tokenizer = tokenizer

    def transform_text(self, text_list):
        text_matrix = self._tokenizer.texts_to_matrix(text_list)   # 待向量化的文本列表
        return text_matrix

VOCAB_SIZE = 17
processor = TextPreprocessor(VOCAB_SIZE)
processor.create_tokenizer(X_train)
X_train = processor.transform_text(X_train)

model = lgb.LGBMClassifier()
model.fit(X_train, y_train)

attrib_data = np.array(random.choices(X_train, k=2000))
explainer = shap.TreeExplainer(model, attrib_data)   # shap “模型解释”包，反映出每一个样本中的特征的影响力
num_explanations = 200
shap_vals = explainer.shap_values(np.array(random.choices(X_train, k=num_explanations)))  # 传入特征矩阵X，以计算SHAP值

words = processor._tokenizer.word_index   # 保存所有word对应的编号id
word_lookup = list()
for i in words.keys():
    word_lookup.append(i)
word_lookup = [''] + word_lookup
print(word_lookup)

word_lookup = [
    '',
    'Road side',
    'Hotel',
    'Home community',
    'School',
    'Government',
    'Hospital',
    'Shopping mall',
    'Police station',
    'Super market',
    'Labor market',
    'Bank',
    'Internet cafe',
    'Restaurant',
    'Cinema',
    'Gas station',
    'Scenic spot'
]

plt.rcParams.update({'font.size': 100})   # 自定义图形的各种默认属性
shap.summary_plot(shap_vals, feature_names=word_lookup, class_names=["resident", "suspect"])
# 每一个样本绘制其每个特征的SHAP值，可以提供直观的理解整体模式，并允许发现预测异常值


import RPi.GPIO as GPIO
import time, sys, random
from threading import Timer

red_out = 22
yellow_out = 24
blue_out = 26
green_out = 32

red_in = 31
yellow_in = 33
blue_in = 35
green_in = 37

# Function for setting up GPIO
def init():
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(red_out, GPIO.OUT)
	GPIO.setup(yellow_out, GPIO.OUT)
	GPIO.setup(blue_out, GPIO.OUT)
	GPIO.setup(green_out, GPIO.OUT)
	GPIO.setup(red_in, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
	GPIO.setup(yellow_in, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
	GPIO.setup(blue_in, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
	GPIO.setup(green_in, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Function that calls when the game is over
def gameover(score):
	print("GAME OVER! Your score is ", score)
	# Clean up GPIO
	GPIO.output(red_out, False)
	GPIO.output(yellow_out, False)
	GPIO.output(blue_out, False)
	GPIO.output(green_out, False)
	GPIO.cleanup()
	exit()

def main():
	if (len(sys.argv) != 2):
		print("Invalid number of arguments. Format: python ./simon_says.py {difficulty (1 = easy, 2 = medium, 3 = hard)})")
		return

	# Set difficulty based on amount of time to guess
	if (sys.argv[1] == '1'):
		time_to_guess = 20
	elif (sys.argv[1] == '2'):
		time_to_guess = 10
	elif (sys.argv[1] == '3'):
		time_to_guess = 5
	else:
		print("Error: Invalid difficulty")
		return

	init()
	# Initially no lights are on
	GPIO.output(red_out, False)
	GPIO.output(yellow_out, False)
	GPIO.output(blue_out, False)
	GPIO.output(green_out, False)

	game = True
	level = 1
	print("For each level, you have", time_to_guess, "seconds to guess. Good luck! Game Starts in:")
	while game:
		# Game runs forever
		print("3")
		time.sleep(1)
		print("2")
		time.sleep(1)
		print("1")
		time.sleep(1)
		print("start!")
		sequence = []
		# Randomly create sequence of lights where the length is based on the level
		for i in range(level):
			sequence.append(random.choice([red_out, yellow_out, blue_out, green_out]))

		# Display sequence of lights
		for output in sequence:
			GPIO.output(output, True)
			time.sleep(0.5)
			GPIO.output(output, False)
			time.sleep(0.5)

		# Start timer for guessing
		timer = Timer(time_to_guess, gameover, args=(level,))
		timer.start()
		guess_phase = True
		guess_sequence = []
		red_pressed = False
		yellow_pressed = False
		blue_pressed = False
		green_pressed = False
		# Every release of a switch appends a guessed color to guess_sequence
		# Repeat until the length of guess_sequence equals the length of sequence
		while (len(guess_sequence) < level):
			if (GPIO.input(red_in) == 1 and not red_pressed):
				red_pressed = True
				time.sleep(0.1)
			elif (GPIO.input(red_in) == 0 and red_pressed):
				guess_sequence.append(red_out)
				red_pressed = False
				time.sleep(0.1)
			elif (GPIO.input(yellow_in) == 1 and not yellow_pressed):
				yellow_pressed = True
				time.sleep(0.1)
			elif (GPIO.input(yellow_in) == 0 and yellow_pressed):
				guess_sequence.append(yellow_out)
				yellow_pressed = False
				time.sleep(0.1)
			elif (GPIO.input(blue_in) == 1 and not blue_pressed):
				blue_pressed = True
				time.sleep(0.1)
			elif (GPIO.input(blue_in) == 0 and blue_pressed):
				guess_sequence.append(blue_out)
				blue_pressed = False
				time.sleep(0.1)
			elif (GPIO.input(green_in) == 1 and not green_pressed):
				green_pressed = True
				time.sleep(0.1)
			elif (GPIO.input(green_in) == 0 and green_pressed):
				guess_sequence.append(green_out)
				green_pressed = False
				time.sleep(0.1)
		timer.cancel()
		# Check if the guessed color sequence matches the actual color sequence
		for i in range(level):
			if (guess_sequence[i] != sequence[i]): break

		# Move on to the next level
		print("Correct!")
		level = level + 1

if __name__ == "__main__":
	try:
		main()
	except:
		GPIO.cleanup()
		pass


import csv
import sys

train_addr = 'New_Dataset.csv'
test_addr = 'sequences_test.csv'

Trains = []
Tests = []

train_file = open(train_addr)
line = train_file.readline()
line = train_file.readline()
while line:
    line = line.rstrip('\n')
    linespl = line.split(',')
    Trains.append(linespl[0])
    line = train_file.readline()

test_file = open(test_addr)
line = test_file.readline()
line = test_file.readline()
while line:
    line = line.rstrip('\n')
    linespl = line.split(',')
    Tests.append(linespl[0])
    line = test_file.readline()

test_set = set(Tests)
train_set = set(Trains)

rem = train_set-test_set

s = 5
s = 3
s = 7


import cv2
import numpy as np
import mediapipe as mp
import torch

STANDARD_HEIGHT = 200
STANDARD_WIDTH = 200
MIN_CONFIDENCE_LEVEL = 0.7

#Extract Hand Features for inference (can be utilized for training with minor changes)
class OldExtractHandFeatures:
    def __init__(self, raw_image):
        self.raw_image = raw_image

    def generate_features(self):
        mp_hands = mp.solutions.hands
        with mp_hands.Hands(static_image_mode = True,max_num_hands = 2,
            min_detection_confidence = MIN_CONFIDENCE_LEVEL) as hands:

            #For training change this line, don't need to flip (since images appear to be from back-facing camera)
            #Convert cv2 BGR image to RGB image and flip (since image coming from front-facing camera)
            #processed = hands.process(cv2.flip(cv2.cvtColor(self.raw_image, cv2.COLOR_BGR2RGB), 1))
            processed = hands.process(cv2.cvtColor(self.raw_image, cv2.COLOR_BGR2RGB))

            #No hand detected (Figure out how we want to handle, 126 vector with all 0s?):
            if not processed.multi_hand_landmarks:
                zeros = torch.tensor(np.array([0] * 126), dtype=torch.float32)
                return zeros

            feature_vector = []
            #Could have one or two hands:
            for hand in processed.multi_hand_landmarks:
                for curr_landmark in hand.landmark:
                    x = curr_landmark.x
                    feature_vector.append(x)

                    y = curr_landmark.y
                    feature_vector.append(y)

                    z = curr_landmark.z
                    feature_vector.append(z)

            #If we have just one hand, zero out the remaining (to ensure constant vector size of 126)
            #Might cause problems in one-hand case if we care which hand is visible/showing sign language
            #Solution to this is to use processed.multi_handedness
            if (len(feature_vector) == 63):
                zero_vector = [0] * 63
                feature_vector.extend(zero_vector)

            output = torch.tensor(np.array(feature_vector), dtype=torch.float32)
            return output