# -*- coding: utf-8 -*-
"""
Created on Thu Jan 20 16:19:30 2022

@author: Lab User
"""

#%% Import libraries

import beepy
from calc_ds import *
from compartment import Compartment
import fireSpreadMain as fs
from GMprocessing import *
import igraph as ig
import intensity as im
from loadall import *
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
from pytictoc import TicToc; t = TicToc()
import random
import seaborn as sns
from scipy import stats, optimize
import sprinkler_hydraulics as spr
import sys
from wall import Wall
from window import Window, Door
import wntr

#%% Toggles and Options
toggle_read = False
toggle_plot = False
toggle_plot_old = True
toggle_plot_Sa = False
pickleOut = 'outputDict1'
pickleIn = 'outputDict1'

#%% Some set up

nSamples = 100

# earthquake records path
username = "Lab User"
pathER = r"C:/Users/"+username+r"/OneDrive/Documents/OpenSees/9st_mrf_mwc/GMs_Full_Suite/"

# fire spread samples path
pathBC = r"C:/Users/"+username+r"/OneDrive/Documents/OpenSees/PythonFiles-OS/BCpickle1/"

# water network samples path
pathWN = r"C:/Users/"+username+r"/OneDrive/Documents/OpenSees/PythonFiles-OS/WNpickle1/"

# main path
pathMAIN = r"C:/Users/"+username+r"/OneDrive/Documents/OpenSees/PythonFiles-OS/"

# Grab all directory names in the burning compartment path
dn = []
fn = []
for (dirpath, dirnames, filenames) in os.walk(pathBC):
    dn.extend(dirnames)
    fn.extend(filenames)
    break

# Split the directories into lagrande and seattle
def splitList(x,a=0,b=8):
    recdict = dict()
    for recname in x:
        rec = recname[a:b]
        if rec in recdict.keys():
            recdict[rec].append(recname)
        else:
            recdict[rec] = [recname]
    return recdict

fd = splitList(fn)
shapeErrorList = []

# Define a function to grab PGA from file
def getPGA(PATHIN):
    with open(PATHIN,'r') as f:
        data = [float(val) for val in f]
        PGA = max(data, key=abs)
    return PGA

LOCd = {}

#%% Main Reader

if toggle_read:
    # Loop through locations
    for fk, fi in fd.items():
        print('==============================================')
        print('|       Record Set: {}                 |'.format(fk))
        print('==============================================')
        print()
        rd = splitList(fi,0,-13)
        RECd = {}
        # Loop through earthquake records at location
        for rk, ri in rd.items():
            print('  ==============================================')
            print('  |       Record: {}             |'.format(rk))
            print('  ==============================================')
            print()
            recname = rk[3::]+'.txt'
            PGA = abs(getPGA(pathER+recname))
            IMcomb,IMdetails = get_IMcomb(rk[3::],T1=1.75,plot=toggle_plot_Sa,toggle_print=False)
            nSIM = 0
            nBClist = []
            nLEAKlist = []
            # Loop through MC sims
            for r in ri:
                nSIM += 1
                print('    MC sim: {:s}'.format(r[-12:-7]))
                print('    PGA: {:0.3f} [g]'.format(PGA))
                print('    IMcomb: {:0.3f}'.format(IMcomb))
                # Load the pickled fire sim results
                with open(pathBC+r,'rb') as f:
                    bc = pickle.load(f)

                    nBC = len(bc)
                    nBClist.append(nBC)
                    print('     No. of burning compartments: {:d}'.format(nBC))
                    # Loop through compartments
                    for ck, ci in bc.items():
                        try:
                            print('      {0:s} began burning at time {1:0.1f} and decayed at time {2:0.1f}'.format(ci.get_name(),ci.time_of_ignition,ci.time_of_ignition+ci.time_of_decay))
                        except TypeError:
                            print('      {0:s} began burning, (warning: TypeError)'.format(ci.get_name()))
                    print()
                # Load the pickled hydraulic sim results
                w = r.replace('BC_','wn-')
                try:
                    with open(pathWN+w,'rb') as f:
                        wn = pickle.load(f)
                        wn_ds = wn[2][0]
                        nleaks = sum(wn_ds[2:4])
                        nLEAKlist.append(nleaks)

                        print('      No. of leaks: {}'.format(nleaks))
                except:
                    print('      No hydraulic data for this sim')
                    nLEAKlist.append(-1.)
                    print()
                    continue
                print()

        # lndist = stats.lognorm.fit(nBClist,loc=0)
        # print('      '+str(lndist))
            print()
            RECd[rk] = {'Loc':fk,'nSIM':nSIM,'PGA_g':PGA,'IMcomb':IMcomb,'nBC':nBClist,'nLEAK':nLEAKlist}

        LOCd[fk] = RECd
        f=open(pathMAIN+pickleOut+".pickle",'wb')
        pickle.dump(LOCd,f)
        f.close()

#%% FORMATTING RESULTS
# Grab the pickled output file if not generated
if not toggle_read:
    with open(pathMAIN+pickleIn+".pickle",'rb') as f:
        LOCd = pickle.load(f)
frames = []
for lk, li in LOCd.items():
    frames.append(pd.DataFrame(li).transpose())
df = pd.concat(frames)
dfex = df.set_index(['Loc','nSIM','PGA_g','IMcomb']).apply(pd.Series.explode).reset_index()
# df = df.explode(["nBC","nLEAK"])
pd.set_option('display.max_columns',None)

ds0 = 1
ds1 = 4
ds2 = 8
ds3 = 100

ds = [ds0,ds1,ds2,ds3]

df.sort_values(by='PGA_g',inplace=True)

# df['ds0'] = df.apply(lambda row: sum((x == ds0) for x in row.nBC)/row.nSIM,axis=1)
df['ds1'] = df.apply(lambda row: sum((x > ds0) for x in row.nBC)/row.nSIM,axis=1)
df['ds2'] = df.apply(lambda row: sum((x > ds1) for x in row.nBC)/row.nSIM,axis=1)
df['ds3'] = df.apply(lambda row: sum((x > ds2) for x in row.nBC)/row.nSIM,axis=1)

#%% Fit Data
# Set up lognormal function - note, scipy has a weird formulation for this. Look it up.
f_ln = lambda x,mu,sigma: stats.lognorm(s=sigma, scale=np.exp(mu)).cdf(x)
f_norm = lambda x,mu,sigma: stats.norm(loc=sigma,scale=mu).cdf(x)
f_gamma = lambda x,a,b: stats.gamma(a=a,scale=1/b).cdf(x)
f_weibull_min = lambda x,c,s: stats.weibull_min(c=c,scale=s).cdf(x)
f_weibull_max = lambda x,c,s: stats.weibull_max(c=c,scale=s).cdf(x)
f_log = lambda x,th1,th2: np.exp(th1+th2*x)/(1+np.exp(th1+th2*x))

f = {'Norm':f_norm,
     'Lognorm':f_ln,
     # 'Gamma':f_gamma,
     # 'Weibull_min':f_weibull_min,
     # 'Weibull_max':f_weibull_max,
     'Logistic': f_log
     }

# PGA
for k, func in f.items():
    # LaGrande
    LGx1 = df['PGA_g'].loc[df['Loc']=='BC_LaGra'].to_list()
    LGy1 = df['ds1'].loc[df['Loc']=='BC_LaGra'].to_list()
    mu1_lg, sigma1_lg = optimize.curve_fit(func,LGx1,LGy1)[0]
    # _,_,r_lg1,_,_ = stats.linregress(LGy1,func(LGx1,mu1_lg,sigma1_lg))
    _,_,r_lg1,_,_ = stats.linregress(LGy1,[func(x,mu1_lg,sigma1_lg) for x in LGx1])
    r2_lg1 = r_lg1**2

    LGx2 = df['PGA_g'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
    LGy2 = df['ds2'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
    mu2_lg, sigma2_lg = optimize.curve_fit(func,LGx2,LGy2)[0]
    _,_,r_lg2,_,_ = stats.linregress(LGy2,[func(x,mu2_lg,sigma2_lg) for x in LGx2])
    r2_lg2 = r_lg2**2

    LGx3 = df['PGA_g'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
    LGy3 = df['ds3'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
    mu3_lg, sigma3_lg = optimize.curve_fit(func,LGx3,LGy3)[0]
    _,_,r_lg3,_,_ = stats.linregress(LGy3,[func(x,mu3_lg,sigma3_lg) for x in LGx3])
    r2_lg3 = r_lg3**2

    # Seattle
    SEx1 = df['PGA_g'].loc[df['Loc']=='BC_Seatt'].to_list()#[1:-1]
    SEy1 = df['ds1'].loc[df['Loc']=='BC_Seatt'].to_list()#[1:-1]
    mu1_se, sigma1_se = optimize.curve_fit(func,SEx1,SEy1)[0]
    # _,_,r_se1,_,_ = stats.linregress(SEy1,func(SEx1,mu1_se,sigma1_se))
    _,_,r_se1,_,_ = stats.linregress(SEy1,[func(x,mu1_se,sigma1_se) for x in SEx1])
    r2_se1 = r_se1**2

    SEx2 = df['PGA_g'].loc[df['Loc']=='BC_Seatt'].to_list()#[1:-1]
    SEy2 = df['ds2'].loc[df['Loc']=='BC_Seatt'].to_list()#[1:-1]
    mu2_se, sigma2_se = optimize.curve_fit(func,SEx2,SEy2)[0]
    _,_,r_se2,_,_ = stats.linregress(SEy2,[func(x,mu2_se,sigma2_se) for x in SEx2])
    r2_se2 = r_se2**2

    SEx3 = df['PGA_g'].loc[df['Loc']=='BC_Seatt'].to_list()#[1:-1]
    SEy3 = df['ds3'].loc[df['Loc']=='BC_Seatt'].to_list()#[1:-1]
    mu3_se, sigma3_se = optimize.curve_fit(func,SEx3,SEy3)[0]
    _,_,r_se3,_,_ = stats.linregress(SEy3,[func(x,mu3_se,sigma3_se) for x in SEx3])
    r2_se3 = r_se3**2

    # BOTH
    BOx1 = df['PGA_g'].to_list()[:] #[1:-1]
    BOy1 = df['ds1'].to_list()[:] #[1:-1]
    mu1_bo, sigma1_bo = optimize.curve_fit(func,BOx1,BOy1)[0]
    _,_,r_bo1,_,_ = stats.linregress(BOy1,[func(x,mu1_bo,sigma1_bo) for x in BOx1])
    r2_bo1 = r_bo1**2

    BOx2 = df['PGA_g'].to_list()[:] #[1:-1]
    BOy2 = df['ds2'].to_list()[:] #[1:-1]
    mu2_bo, sigma2_bo = optimize.curve_fit(func,BOx2,BOy2)[0]
    _,_,r_bo2,_,_ = stats.linregress(BOy2,[func(x,mu2_bo,sigma2_bo) for x in BOx2])
    r2_bo2 = r_bo2**2

    BOx3 = df['PGA_g'].to_list()[:] #[1:-1]
    BOy3 = df['ds3'].to_list()[:] #[1:-1]
    mu3_bo, sigma3_bo = optimize.curve_fit(func,BOx3,BOy3)[0]
    _,_,r_bo3,_,_ = stats.linregress(BOy3,[func(x,mu3_bo,sigma3_bo) for x in BOx3])
    r2_bo3 = r_bo3**2

    print()
    print('========================')
    print('Curve type: {:s}, IM = PGA (g)'.format(k))
    print('  LaGrande')
    print('    ds1:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu1_lg,sigma1_lg,r2_lg1))
    print('    ds2:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu2_lg,sigma2_lg,r2_lg2))
    print('    ds3:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu3_lg,sigma3_lg,r2_lg3))
    print('  Seattle')
    print('    ds1:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu1_se,sigma1_se,r2_se1))
    print('    ds2:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu2_se,sigma2_se,r2_se2))
    print('    ds3:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu3_se,sigma3_se,r2_se3))
    print('  Both')
    print('    ds1:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu1_bo,sigma1_bo,r2_bo1))
    print('    ds2:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu2_bo,sigma2_bo,r2_bo2))
    print('    ds3:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu3_bo,sigma3_bo,r2_bo3))

    #%% PLOTTING
    if toggle_plot:
        x = np.linspace(0,0.5,100)

        plt.figure(11)
        ax11 = df.loc[df['Loc']=='BC_LaGra'].plot(x="PGA_g",y="ds1",kind="scatter", color='r', marker='d', s=20, label="ds1")
        ax11 = df.loc[df['Loc']=='BC_LaGra'].plot(x="PGA_g",y="ds2",kind="scatter", color='g', marker='s', s=10, label="ds2",ax=ax11)
        ax11 = df.loc[df['Loc']=='BC_LaGra'].plot(x="PGA_g",y="ds3",kind="scatter", color='b', marker='o', s=10, label="ds3",ax=ax11)
        ax11.plot(x,func(x,mu1_lg,sigma1_lg),'r--',label='ds1_fit, $r^2$={0:0.3f}'.format(r2_lg1))
        ax11.plot(x,func(x,mu2_lg,sigma2_lg),'g--',label='ds2_fit, $r^2$={0:0.3f}'.format(r2_lg2))
        ax11.plot(x,func(x,mu3_lg,sigma3_lg),'b--',label='ds3_fit, $r^2$={0:0.3f}'.format(r2_lg2))
        ax11.legend(loc="upper left")
        ax11.grid(visible=True)
        ax11.set_xlim(0.0,0.4)
        ax11.set_ylim(-0.05,1.1)
        ax11.set_xlabel("PGA (g)")
        ax11.set_ylabel("Likelihood")
        title = '{:s} CDF, LaGrande'.format(k)
        ax11.set_title(title)
        plt.show()

        plt.figure(12)
        ax12 = df.loc[df['Loc']=='BC_Seatt'].plot(x="PGA_g",y="ds1",kind="scatter", color='r', marker='d', s=20, label="ds1")
        ax12 = df.loc[df['Loc']=='BC_Seatt'].plot(x="PGA_g",y="ds2",kind="scatter", color='g', marker='s', s=10, label="ds2",ax=ax12)
        ax12 = df.loc[df['Loc']=='BC_Seatt'].plot(x="PGA_g",y="ds3",kind="scatter", color='b', marker='o', s=10,  label="ds3",ax=ax12)
        ax12.plot(x,func(x,mu1_se,sigma1_se),'r--',label='ds1_fit, $r^2$={0:0.3f}'.format(r2_se1))
        ax12.plot(x,func(x,mu2_se,sigma2_se),'g--',label='ds2_fit, $r^2$={0:0.3f}'.format(r2_se2))
        ax12.plot(x,func(x,mu3_se,sigma3_se),'b--',label='ds3_fit, $r^2$={0:0.3f}'.format(r2_se3))
        ax12.legend(loc="upper left")
        ax12.grid(visible=True)
        ax12.set_xlim(0.0,0.4)
        ax12.set_ylim(-0.05,1.1)
        ax12.set_xlabel("PGA (g)")
        ax12.set_ylabel("Likelihood")
        title = '{:s} CDF, Seattle'.format(k)
        ax12.set_title(title)
        plt.show()

        plt.figure(13)
        ax13 = df.plot(x="PGA_g",y="ds1",kind="scatter", color='r', marker='d', s=20, label="ds1")
        ax13 = df.plot(x="PGA_g",y="ds2",kind="scatter", color='g', marker='s', s=10, label="ds2",ax=ax13)
        ax13 = df.plot(x="PGA_g",y="ds3",kind="scatter", color='b', marker='o', s=10,  label="ds3",ax=ax13)
        ax13.plot(x,func(x,mu1_bo,sigma1_bo),'r--',label='ds1_fit, $r^2$={0:0.3f}'.format(r2_bo1))
        ax13.plot(x,func(x,mu2_bo,sigma2_bo),'g--',label='ds2_fit, $r^2$={0:0.3f}'.format(r2_bo2))
        ax13.plot(x,func(x,mu3_bo,sigma3_bo),'b--',label='ds3_fit, $r^2$={0:0.3f}'.format(r2_bo3))
        ax13.legend(loc="upper left")
        ax13.grid(visible=True)
        ax13.set_xlim(0.0,0.4)
        ax13.set_ylim(-0.05,1.1)
        ax13.set_xlabel("PGA (g)")
        ax13.set_ylabel("Likelihood")
        title = '{:s} CDF, Both Locations'.format(k)
        ax13.set_title(title)
        plt.show()

# IMcomb
for k, func in f.items():
    try:
        # LaGrande
        LGx1 = df['IMcomb'].loc[df['Loc']=='BC_LaGra'].to_list()[:]
        LGy1 = df['ds1'].loc[df['Loc']=='BC_LaGra'].to_list()[:]
        mu1_lg, sigma1_lg = optimize.curve_fit(func,LGx1,LGy1)[0]
        _,_,r_lg1,_,_ = stats.linregress(LGy1,[func(x,mu1_lg,sigma1_lg) for x in LGx1])
        r2_lg1 = r_lg1**2

        LGx2 = df['IMcomb'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
        LGy2 = df['ds2'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
        mu2_lg, sigma2_lg = optimize.curve_fit(func,LGx2,LGy2)[0]
        _,_,r_lg2,_,_ = stats.linregress(LGy2,[func(x,mu2_lg,sigma2_lg) for x in LGx2])
        r2_lg2 = r_lg2**2

        LGx3 = df['IMcomb'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
        LGy3 = df['ds3'].loc[df['Loc']=='BC_LaGra'].to_list()#[1:-1]
        mu3_lg, sigma3_lg = optimize.curve_fit(func,LGx3,LGy3)[0]
        _,_,r_lg3,_,_ = stats.linregress(LGy3,[func(x,mu3_lg,sigma3_lg) for x in LGx3])
        r2_lg3 = r_lg3**2

        # Seattle
        SEx1 = df['IMcomb'].loc[df['Loc']=='BC_Seatt'].to_list()[1:-1]
        SEy1 = df['ds1'].loc[df['Loc']=='BC_Seatt'].to_list()[1:-1]
        mu1_se, sigma1_se = optimize.curve_fit(func,SEx1,SEy1)[0]
        _,_,r_se1,_,_ = stats.linregress(SEy1,[func(x,mu1_se,sigma1_se) for x in SEx1])
        r2_se1 = r_se1**2

        SEx2 = df['IMcomb'].loc[df['Loc']=='BC_Seatt'].to_list()[:] #[1:-1]
        SEy2 = df['ds2'].loc[df['Loc']=='BC_Seatt'].to_list()[:] #[1:-1]
        mu2_se, sigma2_se = optimize.curve_fit(func,SEx2,SEy2)[0]
        _,_,r_se2,_,_ = stats.linregress(SEy2,[func(x,mu2_se,sigma2_se) for x in SEx2])
        r2_se2 = r_se2**2

        SEx3 = df['IMcomb'].loc[df['Loc']=='BC_Seatt'].to_list()[:] #[1:-1]
        SEy3 = df['ds3'].loc[df['Loc']=='BC_Seatt'].to_list()[:] #[1:-1]
        mu3_se, sigma3_se = optimize.curve_fit(func,SEx3,SEy3)[0]
        _,_,r_se3,_,_ = stats.linregress(SEy3,[func(x,mu3_se,sigma3_se) for x in SEx3])
        r2_se3 = r_se3**2

        # BOTH
        BOx1 = df['IMcomb'].to_list()[:] #[1:-1]
        BOy1 = df['ds1'].to_list()[:] #[1:-1]
        mu1_bo, sigma1_bo = optimize.curve_fit(func,BOx1,BOy1)[0]
        _,_,r_bo1,_,_ = stats.linregress(BOy1,[func(x,mu1_bo,sigma1_bo) for x in BOx1])
        r2_bo1 = r_bo1**2

        BOx2 = df['IMcomb'].to_list()[:] #[1:-1]
        BOy2 = df['ds2'].to_list()[:] #[1:-1]
        mu2_bo, sigma2_bo = optimize.curve_fit(func,BOx2,BOy2)[0]
        _,_,r_bo2,_,_ = stats.linregress(BOy2,[func(x,mu2_bo,sigma2_bo) for x in BOx2])
        r2_bo2 = r_bo2**2

        BOx3 = df['IMcomb'].to_list()[:] #[1:-1]
        BOy3 = df['ds3'].to_list()[:] #[1:-1]
        mu3_bo, sigma3_bo = optimize.curve_fit(func,BOx3,BOy3)[0]
        _,_,r_bo3,_,_ = stats.linregress(BOy3,[func(x,mu3_bo,sigma3_bo) for x in BOx3])
        r2_bo3 = r_bo3**2

        print()
        print('========================')
        print('Curve type: {:s}, IM: IMcomb'.format(k))
        print('  LaGrande')
        print('    ds1:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu1_lg,sigma1_lg,r2_lg1))
        print('    ds2:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu2_lg,sigma2_lg,r2_lg2))
        print('    ds3:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu3_lg,sigma3_lg,r2_lg3))
        print('  Seattle')
        print('    ds1:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu1_se,sigma1_se,r2_se1))
        print('    ds2:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu2_se,sigma2_se,r2_se2))
        print('    ds3:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu3_se,sigma3_se,r2_se3))
        print('  Seattle')
        print('    ds1:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu1_bo,sigma1_bo,r2_bo1))
        print('    ds2:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu2_bo,sigma2_bo,r2_bo2))
        print('    ds3:: p1: {0:0.3f}, p2: {1:0.3f}, r2: {2:0.3f}'.format(mu3_bo,sigma3_bo,r2_bo3))

    except RuntimeError:
        print('Curve {:s}, parameters not found'.format(k))

    #%% PLOTTING
    if toggle_plot:
        x = np.linspace(0,0.5,100)

        plt.figure(21)
        ax21 = df.loc[df['Loc']=='BC_LaGra'].plot(x="IMcomb",y="ds1",kind="scatter", color='r', marker='d', s=20, label="ds1")
        ax21 = df.loc[df['Loc']=='BC_LaGra'].plot(x="IMcomb",y="ds2",kind="scatter", color='g', marker='s', s=10, label="ds2",ax=ax21)
        ax21 = df.loc[df['Loc']=='BC_LaGra'].plot(x="IMcomb",y="ds3",kind="scatter", color='b', marker='o', s=10, label="ds3",ax=ax21)
        ax21.plot(x,func(x,mu1_lg,sigma1_lg),'r--',label='ds1_fit, $r^2$={0:0.3f}'.format(r2_lg1))
        ax21.plot(x,func(x,mu2_lg,sigma2_lg),'g--',label='ds2_fit, $r^2$={0:0.3f}'.format(r2_lg2))
        ax21.plot(x,func(x,mu3_lg,sigma3_lg),'b--',label='ds3_fit, $r^2$={0:0.3f}'.format(r2_lg2))
        ax21.legend(loc="upper left")
        ax21.grid(visible=True)
        ax21.set_xlim(0.0,0.025)
        ax21.set_ylim(-0.05,1.1)
        ax21.set_xlabel("IMcomb")
        ax21.set_ylabel("Likelihood")
        title = '{:s} CDF, LaGrande'.format(k)
        ax21.set_title(title)
        plt.show()

        plt.figure(22)
        ax22 = df.loc[df['Loc']=='BC_Seatt'].plot(x="IMcomb",y="ds1",kind="scatter", color='r', marker='d', s=20, label="ds1")
        ax22 = df.loc[df['Loc']=='BC_Seatt'].plot(x="IMcomb",y="ds2",kind="scatter", color='g', marker='s', s=10, label="ds2",ax=ax22)
        ax22 = df.loc[df['Loc']=='BC_Seatt'].plot(x="IMcomb",y="ds3",kind="scatter", color='b', marker='o', s=10, label="ds3",ax=ax22)
        ax22.plot(x,func(x,mu1_se,sigma1_se),'r--',label='ds1_fit, $r^2$={0:0.3f}'.format(r2_se1))
        ax22.plot(x,func(x,mu2_se,sigma2_se),'g--',label='ds2_fit, $r^2$={0:0.3f}'.format(r2_se2))
        ax22.plot(x,func(x,mu3_se,sigma3_se),'b--',label='ds3_fit, $r^2$={0:0.3f}'.format(r2_se3))
        ax22.legend(loc="upper left")
        ax22.grid(visible=True)
        ax22.set_xlim(0.0,0.025)
        ax22.set_ylim(-0.05,1.1)
        ax22.set_xlabel("IMcomb")
        ax22.set_ylabel("Likelihood")
        title = '{:s} CDF, Seattle'.format(k)
        ax22.set_title(title)
        plt.show()

        plt.figure(23)
        ax23 = df.plot(x="IMcomb",y="ds1",kind="scatter", color='r', marker='d', s=20, label="ds1")
        ax23 = df.plot(x="IMcomb",y="ds2",kind="scatter", color='g', marker='s', s=10, label="ds2",ax=ax23)
        ax23 = df.plot(x="IMcomb",y="ds3",kind="scatter", color='b', marker='o', s=10, label="ds3",ax=ax23)
        ax23.plot(x,func(x,mu1_bo,sigma1_bo),'r--',label='ds1_fit, $r^2$={0:0.3f}'.format(r2_bo1))
        ax23.plot(x,func(x,mu2_bo,sigma2_bo),'g--',label='ds2_fit, $r^2$={0:0.3f}'.format(r2_bo2))
        ax23.plot(x,func(x,mu3_bo,sigma3_bo),'b--',label='ds3_fit, $r^2$={0:0.3f}'.format(r2_bo3))
        ax23.legend(loc="upper left")
        ax23.grid(visible=True)
        ax23.set_xlim(0.0,0.025)
        ax23.set_ylim(-0.05,1.1)
        ax23.set_xlabel("IMcomb")
        ax23.set_ylabel("Likelihood")
        title = '{:s} CDF, Both Locations'.format(k)
        ax23.set_title(title)
        plt.show()

        # print(df)

if toggle_plot_old:
    # sns.scatterplot(data=df, x="PGA_g", y="nLEAK")
    new_title = 'Location'
    new_labels = ['LaGrande','Seattle']
    dfex['nLEAKnorm'] = dfex['nLEAK']/1414.
    dfex['nBCnorm'] = dfex['nBC']/36.
    plt.figure(1)
    plt.grid()
    # ax1 = plt.axis([0,0.5,0,50])
    g= sns.scatterplot(data=dfex, x="PGA_g", y="nBCnorm", hue="Loc", style="Loc",facet_kws={'legend_out':True}).set(title = 'No. of burning compartments vs. PGA', xlabel = 'PGA (g)', ylabel = 'Burning Compartments (Normalized, N=36)')
    plt.legend(loc='upper left')
    # g._legend.set_title(new_title)
    # for t, l in zip(g._legend.texts, new_labels):
    #     t.set_text(l)
    plt.figure(2)
    plt.grid()
    # ax2 = plt.axis([0,0.3,0,50])
    sns.scatterplot(data=dfex, x="IMcomb", y="nBCnorm", hue="Loc", style="Loc").set(title = 'No. of burning compartments vs. $IM_{comb}$', xlabel = '$IM_{comb}$', ylabel = 'Burning Compartments (Normalized, N=36)')
    plt.legend(loc='upper left')
    # plt.figure(2)
    plt.figure(3)
    plt.grid()
    # ax3 = plt.axis([0,1500,0,50])
    sns.scatterplot(data=dfex, x="nLEAK", y="nBC", hue="Loc", style="Loc").set(title = 'No. of burning compartments vs. No. of leaking pipes',xlabel = 'Number of Leaking Pipes', ylabel = 'Number of Burning Compartments')
    plt.legend(loc='upper left')
    # plt.figure(4)
    # ax3 = plt.axis([0,50,0,50])
    # sns.histplot(data=dfex, x="PGA_g",y="nBC",hue="Loc")

    # nLEAK vs. IM
    plt.figure(6)
    plt.grid()
    sns.scatterplot(data=dfex,x="PGA_g",y="nLEAKnorm",hue="Loc",style="Loc").set(title = 'No. of leaking pipes vs. PGA', xlabel = 'PGA (g)', ylabel = 'Leaking pipes (Normalized, N=1414)')
    plt.figure(7)
    plt.grid()
    sns.scatterplot(data=dfex,x="IMcomb",y="nLEAKnorm",hue="Loc",style="Loc").set(title = 'No. of leaking pipes vs. $IM_{comb}$', xlabel = '$IM_{comb}$', ylabel = 'Leaking pipes (Normalized, N=1414)')

    # plt.figure(8)
    # sns.jointplot(data=dfex,x="nLEAK",y="nBC",kind="hex",)
    # df.sort_values(by='IMcomb',inplace=True)

    # plt.figure(13)
    # ax13 = df.loc[df['Loc']=='BC_LaGra'].plot(x="IMcomb",y="ds1",kind="scatter", color='r',label="ds1 (>1 BC)")
    # ax13 = df.loc[df['Loc']=='BC_LaGra'].plot(x="IMcomb",y="ds2",kind="scatter", color='g',label="ds2 (>4 BC)",ax=ax13)
    # ax13 = df.loc[df['Loc']=='BC_LaGra'].plot(x="IMcomb",y="ds3",kind="scatter", color='b',label="ds3 (>8 BC)",ax=ax13)
    # ax13.grid(visible=True)
    # ax13.set_xlim(0.0,0.02)
    # ax13.set_ylim(-0.1,1.1)
    # ax13.set_xlabel("IM$_{comb}$")
    # ax13.set_ylabel("Likelihood")
    # ax13.set_title("Empirical CDF, LaGrande (IMcomb)")
    # plt.show()

    # plt.figure(14)
    # ax14 = df.loc[df['Loc']=='BC_Seatt'].plot(x="IMcomb",y="ds1",kind="scatter", color='r',label="ds1 (>1 BC)")
    # ax14 = df.loc[df['Loc']=='BC_Seatt'].plot(x="IMcomb",y="ds2",kind="scatter", color='g',label="ds2 (>4 BC)",ax=ax14)
    # ax14 = df.loc[df['Loc']=='BC_Seatt'].plot(x="IMcomb",y="ds3",kind="scatter", color='b',label="ds3 (>8 BC)",ax=ax14)
    # ax14.grid(visible=True)
    # ax14.set_xlim(0.0,0.25)
    # ax14.set_ylim(-0.1,1.1)
    # ax14.set_xlabel("IM$_{comb}$")
    # ax14.set_ylabel("Likelihood")
    # ax14.set_title("Empirical CDF, Seattle (IMcomb)")
    # plt.show()

# beepy.beep(sound="coin")


from dotenv import load_dotenv
from langchain.agents.agent_toolkits import create_python_agent
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.tools.python.tool import PythonREPLTool

load_dotenv()

def main():
    print("start...")
    python_agent_executor = create_python_agent(
        llm=ChatOpenAI(temperature=0, model="gpt-3.5-turbo"),
        tool=PythonREPLTool(),
        agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
        verbose=True,
    )

    python_agent_executor.run("""generate and save in current working directory 15 QR codes that point to www.udemy.com/course/langchain, you have qr code package installed already.""")

if __name__ == "__main__":
    main()


'''
	State Preparation or Data Encoding encodes any input x into a quantum state
	S_x  -> |phi(x)>
	S_x' -> |phi(x')>

	Somewhat performs a feature embedding in quantum computer
	input -> feature vector in Hilbert Space

	This stste preperation procedure is a Feature Map.
	and
	feature map gives rise to a Kernel!
'''

import pennylane as qml
from pennylane import numpy as np
from pennylane.wires import Wires
# from pennylane.templates.decorator import template

dev = qml.device('default.qubit', wires = 7)

@qml.template
def BasisEmbedding(features, wires):
	'''
	Basis Embedding:
		Helps in construction of computational basis state e.g. |01>.

	Args:
		wires: wires in the circuit in iterable format.
		features: input array of shape (n,).

	Raises:
		ValueError: if wires and features do not have same shape.
	'''
	wires = Wires(wires)
	if len(wires) == len(features):
		for wire, bit in zip(wires, features):
			if bit == 1:
				qml.PauliX(wires = wire)
	else:
		raise ValueError("Features [{}] and Wires [{}] have different shapes".format(np.shape(features)[0], np.shape(wires)[0]))

@qml.qnode(dev)
def circuit(features):
	BasisEmbedding(features, wires = range(7))
	return qml.probs(wires = 0)

# wires = range(7)    # Iterable format of wires argument
features = np.array([0, 0, 0, 1, 1, 0, 1])

print(circuit(features))
# print(circuit.draw())
drawer = qml.draw(circuit)
print(drawer(features = features))

'''
qml.templates.state_preparation.basis.BasisStatePreparation and qml.templates.BasisEncoding
are essentially the same functions.
Also, the use of PauliX gate requires these functions to be first only.
'''


import base64
from openai import OpenAI
from dotenv import load_dotenv
import glob

# スライド一式を添削してもらうためのプログラム
# 詳細な添削と100点満点中何点かを添削してもらえる。

load_dotenv(".env")

client = OpenAI()

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

prompt = """
以下はAI勉強会で発表する予定のスライドです。このスライド全体のデザインを添削してください。
また、このスライドの総合点を100点満点でつけてください。
書かれている内容の添削は不要です。
"""

# スライド一覧
slides = sorted(glob.glob("images/slides/slide*.png"))

# contentプロパティを動的に生成する。
contents = [{"type": "text", "text": prompt}]
for slide in slides:
    base64_image = encode_image(slide)
    image_prop = {
        "type": "image_url",
        "image_url": {
            "url": f"data:image/png;base64,{base64_image}",
            "detail": "low",
        },
    }
    contents.append(image_prop)

response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    messages=[{"role": "user", "content": contents}],
    temperature=0,
    # 多めにしておくといいかも
    max_tokens=2000,
)

message = response.choices[0].message.content
print(message)

with open("message.txt", "w", encoding="utf8") as f:
    f.write(message)


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

import json

mm = []

ff = open('all.json', 'w')
for i in range(0, 750):
    with open('page'+str(i)+'.json', 'r') as f:
        d = f.read()
        mm.extend(json.loads(d))

print(len(mm))

json.dump(mm, ff)


import requests
from fake_headers import Headers
from xml.etree import ElementTree

def get_page(uri):
    """
    Reads a webpage given the URI.
    """

    # make request for uri
    HeadersGenerator = Headers(os='mac', headers=False)
    response = requests.get(uri, headers=HeadersGenerator.generate())

    # check status code
    status_code = response.status_code
    if status_code != 200:
        print(status_code)

    # get and return content as bytes
    content = response.content
    return content


import io
import sys

_INPUT = """\
6
11
ADD 3
SAVE 1
ADD 4
SAVE 2
LOAD 1
DELETE
DELETE
LOAD 2
SAVE 1
LOAD 3
LOAD 1
21
ADD 4
ADD 3
DELETE
ADD 10
LOAD 7
SAVE 5
SAVE 5
ADD 4
ADD 4
ADD 5
SAVE 5
ADD 2
DELETE
ADD 1
SAVE 5
ADD 7
ADD 8
DELETE
ADD 4
DELETE
LOAD 5
7
ADD 2
ADD 3
SAVE 1
LOAD 1
LOAD 2
SAVE 3
LOAD 3
"""

sys.stdin = io.StringIO(_INPUT)
case_no=int(input())
for __ in range(case_no):
  Q=int(input())
  parent={}
  now=0
  cnt=1
  d={}
  dd={}
  G=[set()]
  G2=[-1]
  ans=[]
  for i in range(Q):
    query=input().split()
    if query[0]=='ADD':
      x=int(query[1])
      if x in G[now]:
        now=d[(now,x)]
      else:
        G[now].add(x)
        G.append(set())
        G2.append(x)
        d[(now,x)]=cnt
        parent[cnt]=now
        now=cnt
        cnt+=1
    elif query[0]=='DELETE':
      if now!=0: now=parent[now]
    elif query[0]=='SAVE':
      y=int(query[1])
      dd[y]=now
    else:
      z=int(query[1])
      if z in dd: now=dd[z]
      else: now=0
    ans.append(G2[now])
  print(*ans)


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

from PySide6.QtCore import QCoreApplication, QMetaObject, QSize, Qt
from PySide6.QtWidgets import (QGridLayout, QLabel, QLineEdit,
                               QPushButton, QSizePolicy, QVBoxLayout,
                               QWidget)

class Ui_Staircase_sweep_pulse(object):
    def setupUi(self, Staircase_sweep_pulse):
        if not Staircase_sweep_pulse.objectName():
            Staircase_sweep_pulse.setObjectName(u"Staircase_sweep_pulse")
        Staircase_sweep_pulse.resize(710, 600)
        Staircase_sweep_pulse.setMinimumSize(QSize(626, 286))
        Staircase_sweep_pulse.setStyleSheet(u"QWidget {\n"
"	color: white;\n"
"	background-color: #121212;\n"
"	font-family: Rubik;\n"
"	font-size: 10pt;\n"
"	font-weight: 600;\n"
"}\n"
"\n"
"QPushButton {\n"
"	background-color: transparent;\n"
"	border: none;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"	background-color: #666;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
"	background-color: #888;\n"
"}\n"
"\n"
"")
        self.centralwidget = QWidget(Staircase_sweep_pulse)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayout_14 = QVBoxLayout(self.centralwidget)
        self.verticalLayout_14.setObjectName(u"verticalLayout_14")
        self.verticalLayout_13 = QVBoxLayout()
        self.verticalLayout_13.setObjectName(u"verticalLayout_13")
        self.label_13 = QLabel(self.centralwidget)
        self.label_13.setObjectName(u"label_13")
        self.label_13.setAlignment(Qt.AlignCenter)

        self.verticalLayout_13.addWidget(self.label_13)

        self.lineEdit_13 = QLineEdit(self.centralwidget)
        self.lineEdit_13.setObjectName(u"lineEdit_13")
        self.lineEdit_13.setEnabled(True)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_13.sizePolicy().hasHeightForWidth())
        self.lineEdit_13.setSizePolicy(sizePolicy)
        self.lineEdit_13.setStyleSheet(u"font-size: 14pt;\n"
"")
        self.lineEdit_13.setAlignment(Qt.AlignRight|Qt.AlignTop|Qt.AlignTrailing)
        self.lineEdit_13.setReadOnly(True)

        self.verticalLayout_13.addWidget(self.lineEdit_13)

        self.verticalLayout_14.addLayout(self.verticalLayout_13)

        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName(u"gridLayout")
        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.label_2 = QLabel(self.centralwidget)
        self.label_2.setObjectName(u"label_2")
        self.label_2.setAlignment(Qt.AlignCenter)

        self.verticalLayout_2.addWidget(self.label_2)

        self.lineEdit_2 = QLineEdit(self.centralwidget)
        self.lineEdit_2.setObjectName(u"lineEdit_2")
        sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.lineEdit_2.setAlignment(Qt.AlignCenter)

        self.verticalLayout_2.addWidget(self.lineEdit_2)

        self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1)

        self.verticalLayout_7 = QVBoxLayout()
        self.verticalLayout_7.setObjectName(u"verticalLayout_7")
        self.label_7 = QLabel(self.centralwidget)
        self.label_7.setObjectName(u"label_7")
        self.label_7.setAlignment(Qt.AlignCenter)

        self.verticalLayout_7.addWidget(self.label_7)

        self.lineEdit_7 = QLineEdit(self.centralwidget)
        self.lineEdit_7.setObjectName(u"lineEdit_7")
        sizePolicy.setHeightForWidth(self.lineEdit_7.sizePolicy().hasHeightForWidth())
        self.lineEdit_7.setSizePolicy(sizePolicy)
        self.lineEdit_7.setAlignment(Qt.AlignCenter)

        self.verticalLayout_7.addWidget(self.lineEdit_7)

        self.gridLayout.addLayout(self.verticalLayout_7, 0, 1, 1, 1)

        self.verticalLayout_6 = QVBoxLayout()
        self.verticalLayout_6.setObjectName(u"verticalLayout_6")
        self.label_6 = QLabel(self.centralwidget)
        self.label_6.setObjectName(u"label_6")
        self.label_6.setAlignment(Qt.AlignCenter)

        self.verticalLayout_6.addWidget(self.label_6)

        self.lineEdit_6 = QLineEdit(self.centralwidget)
        self.lineEdit_6.setObjectName(u"lineEdit_6")
        sizePolicy.setHeightForWidth(self.lineEdit_6.sizePolicy().hasHeightForWidth())
        self.lineEdit_6.setSizePolicy(sizePolicy)
        self.lineEdit_6.setAlignment(Qt.AlignCenter)

        self.verticalLayout_6.addWidget(self.lineEdit_6)

        self.gridLayout.addLayout(self.verticalLayout_6, 0, 2, 1, 1)

        self.verticalLayout_4 = QVBoxLayout()
        self.verticalLayout_4.setObjectName(u"verticalLayout_4")
        self.label_4 = QLabel(self.centralwidget)
        self.label_4.setObjectName(u"label_4")
        self.label_4.setAlignment(Qt.AlignCenter)

        self.verticalLayout_4.addWidget(self.label_4)

        self.lineEdit_4 = QLineEdit(self.centralwidget)
        self.lineEdit_4.setObjectName(u"lineEdit_4")
        sizePolicy.setHeightForWidth(self.lineEdit_4.sizePolicy().hasHeightForWidth())
        self.lineEdit_4.setSizePolicy(sizePolicy)
        self.lineEdit_4.setAlignment(Qt.AlignCenter)

        self.verticalLayout_4.addWidget(self.lineEdit_4)

        self.gridLayout.addLayout(self.verticalLayout_4, 1, 0, 1, 1)

        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.label = QLabel(self.centralwidget)
        self.label.setObjectName(u"label")
        self.label.setAlignment(Qt.AlignCenter)

        self.verticalLayout.addWidget(self.label)

        self.lineEdit = QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName(u"lineEdit")
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setAlignment(Qt.AlignCenter)

        self.verticalLayout.addWidget(self.lineEdit)

        self.gridLayout.addLayout(self.verticalLayout, 1, 1, 1, 1)

        self.verticalLayout_5 = QVBoxLayout()
        self.verticalLayout_5.setObjectName(u"verticalLayout_5")
        self.label_5 = QLabel(self.centralwidget)
        self.label_5.setObjectName(u"label_5")
        self.label_5.setAlignment(Qt.AlignCenter)

        self.verticalLayout_5.addWidget(self.label_5)

        self.lineEdit_5 = QLineEdit(self.centralwidget)
        self.lineEdit_5.setObjectName(u"lineEdit_5")
        sizePolicy.setHeightForWidth(self.lineEdit_5.sizePolicy().hasHeightForWidth())
        self.lineEdit_5.setSizePolicy(sizePolicy)
        self.lineEdit_5.setAlignment(Qt.AlignCenter)

        self.verticalLayout_5.addWidget(self.lineEdit_5)

        self.gridLayout.addLayout(self.verticalLayout_5, 1, 2, 1, 1)

        self.verticalLayout_8 = QVBoxLayout()
        self.verticalLayout_8.setObjectName(u"verticalLayout_8")
        self.label_8 = QLabel(self.centralwidget)
        self.label_8.setObjectName(u"label_8")
        self.label_8.setAlignment(Qt.AlignCenter)

        self.verticalLayout_8.addWidget(self.label_8)

        self.lineEdit_8 = QLineEdit(self.centralwidget)
        self.lineEdit_8.setObjectName(u"lineEdit_8")
        sizePolicy.setHeightForWidth(self.lineEdit_8.sizePolicy().hasHeightForWidth())
        self.lineEdit_8.setSizePolicy(sizePolicy)
        self.lineEdit_8.setAlignment(Qt.AlignCenter)

        self.verticalLayout_8.addWidget(self.lineEdit_8)

        self.gridLayout.addLayout(self.verticalLayout_8, 2, 0, 1, 1)

        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName(u"verticalLayout_3")
        self.label_3 = QLabel(self.centralwidget)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setAlignment(Qt.AlignCenter)

        self.verticalLayout_3.addWidget(self.label_3)

        self.lineEdit_3 = QLineEdit(self.centralwidget)
        self.lineEdit_3.setObjectName(u"lineEdit_3")
        sizePolicy.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth())
        self.lineEdit_3.setSizePolicy(sizePolicy)
        self.lineEdit_3.setAlignment(Qt.AlignCenter)

        self.verticalLayout_3.addWidget(self.lineEdit_3)

        self.gridLayout.addLayout(self.verticalLayout_3, 2, 1, 1, 1)

        self.verticalLayout_9 = QVBoxLayout()
        self.verticalLayout_9.setObjectName(u"verticalLayout_9")
        self.label_9 = QLabel(self.centralwidget)
        self.label_9.setObjectName(u"label_9")
        self.label_9.setAlignment(Qt.AlignCenter)

        self.verticalLayout_9.addWidget(self.label_9)

        self.lineEdit_9 = QLineEdit(self.centralwidget)
        self.lineEdit_9.setObjectName(u"lineEdit_9")
        sizePolicy.setHeightForWidth(self.lineEdit_9.sizePolicy().hasHeightForWidth())
        self.lineEdit_9.setSizePolicy(sizePolicy)
        self.lineEdit_9.setAlignment(Qt.AlignCenter)

        self.verticalLayout_9.addWidget(self.lineEdit_9)

        self.gridLayout.addLayout(self.verticalLayout_9, 2, 2, 1, 1)

        self.verticalLayout_10 = QVBoxLayout()
        self.verticalLayout_10.setObjectName(u"verticalLayout_10")
        self.label_10 = QLabel(self.centralwidget)
        self.label_10.setObjectName(u"label_10")
        self.label_10.setAlignment(Qt.AlignCenter)

        self.verticalLayout_10.addWidget(self.label_10)

        self.lineEdit_10 = QLineEdit(self.centralwidget)
        self.lineEdit_10.setObjectName(u"lineEdit_10")
        sizePolicy.setHeightForWidth(self.lineEdit_10.sizePolicy().hasHeightForWidth())
        self.lineEdit_10.setSizePolicy(sizePolicy)
        self.lineEdit_10.setAlignment(Qt.AlignCenter)

        self.verticalLayout_10.addWidget(self.lineEdit_10)

        self.gridLayout.addLayout(self.verticalLayout_10, 3, 0, 1, 1)

        self.verticalLayout_11 = QVBoxLayout()
        self.verticalLayout_11.setObjectName(u"verticalLayout_11")
        self.label_11 = QLabel(self.centralwidget)
        self.label_11.setObjectName(u"label_11")
        self.label_11.setAlignment(Qt.AlignCenter)

        self.verticalLayout_11.addWidget(self.label_11)

        self.lineEdit_11 = QLineEdit(self.centralwidget)
        self.lineEdit_11.setObjectName(u"lineEdit_11")
        sizePolicy.setHeightForWidth(self.lineEdit_11.sizePolicy().hasHeightForWidth())
        self.lineEdit_11.setSizePolicy(sizePolicy)
        self.lineEdit_11.setAlignment(Qt.AlignCenter)

        self.verticalLayout_11.addWidget(self.lineEdit_11)

        self.gridLayout.addLayout(self.verticalLayout_11, 3, 1, 1, 1)

        self.verticalLayout_12 = QVBoxLayout()
        self.verticalLayout_12.setObjectName(u"verticalLayout_12")
        self.label_12 = QLabel(self.centralwidget)
        self.label_12.setObjectName(u"label_12")
        self.label_12.setAlignment(Qt.AlignCenter)

        self.verticalLayout_12.addWidget(self.label_12)

        self.lineEdit_12 = QLineEdit(self.centralwidget)
        self.lineEdit_12.setObjectName(u"lineEdit_12")
        sizePolicy.setHeightForWidth(self.lineEdit_12.sizePolicy().hasHeightForWidth())
        self.lineEdit_12.setSizePolicy(sizePolicy)
        self.lineEdit_12.setAlignment(Qt.AlignCenter)

        self.verticalLayout_12.addWidget(self.lineEdit_12)

        self.gridLayout.addLayout(self.verticalLayout_12, 3, 2, 1, 1)

        self.verticalLayout_14.addLayout(self.gridLayout)

        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setObjectName(u"pushButton")
        sizePolicy1 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        sizePolicy1.setHorizontalStretch(0)
        sizePolicy1.setVerticalStretch(0)
        sizePolicy1.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy1)

        self.verticalLayout_14.addWidget(self.pushButton)

        Staircase_sweep_pulse.setCentralWidget(self.centralwidget)

        self.retranslateUi(Staircase_sweep_pulse)

        QMetaObject.connectSlotsByName(Staircase_sweep_pulse)
    # setupUi

    def retranslateUi(self, Staircase_sweep_pulse):
        Staircase_sweep_pulse.setWindowTitle(QCoreApplication.translate("Staircase_sweep_pulse", u"MainWindow", None))
        self.label_13.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0414\u0438\u0430\u043b\u043e\u0433\u043e\u0432\u043e\u0435 \u043e\u043a\u043d\u043e", None))
        self.lineEdit_13.setText("")
        self.label_2.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0439 \u0442\u043e\u043a (\u0410)", None))
        self.lineEdit_2.setText("")
        self.label_7.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u041a\u043e\u043d\u0435\u0447\u043d\u044b\u0439 \u0442\u043e\u043a (\u0410)", None))
        self.lineEdit_7.setText("")
        self.label_6.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0428\u0430\u0433 \u0443\u0432\u0435\u043b\u0438\u0447\u0435\u043d\u0438\u044f \u0442\u043e\u043a\u0430 (\u0410)", None))
        self.lineEdit_6.setText("")
        self.label_4.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u041c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043d\u0430\u043f\u0440\u044f\u0436\u0435\u043d\u0438\u0435 (V)", None))
        self.lineEdit_4.setText("")
        self.label.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u041d\u043e\u043c\u0435\u0440 \u0432\u044b\u0431\u043e\u0440\u0430 \u043f\u0440\u0438\u0431\u043e\u0440\u0430", None))
        self.lineEdit.setText("")
        self.label_5.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0418\u043d\u0442\u0435\u0440\u0432\u0430\u043b \u0438\u043c\u043f\u0443\u043b\u044c\u0441\u0430 (PLC)", None))
        self.lineEdit_5.setText("")
        self.label_8.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0428\u0438\u0440\u0438\u043d\u0430 \u0438\u043c\u043f\u0443\u043b\u044c\u0441\u0430 (s)", None))
        self.lineEdit_8.setText("")
        self.label_3.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0412\u0440\u0435\u043c\u044f \u0437\u0430\u0434\u0435\u0440\u0436\u043a\u0438 \u0440\u0430\u0437\u0432\u0435\u0440\u0442\u043a\u0438 (s)", None))
        self.lineEdit_3.setText("")
        self.label_9.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0412\u0440\u0435\u043c\u044f \u0446\u0438\u043a\u043b\u0430 \u0434\u0435\u043b\u044c\u0442\u0430-\u0442\u0435\u0441\u0442\u0430 (s)", None))
        self.lineEdit_9.setText("")
        self.label_10.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0427\u0438\u0441\u043b\u043e \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u043e\u0432 \u0434\u043b\u044f \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u044f", None))
        self.lineEdit_10.setText("")
        self.label_11.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0412\u044b\u0432\u043e\u0434 \u0432 \u0437\u0435\u043c\u043b\u044e (ON/OFF)", None))
        self.lineEdit_11.setText("")
        self.label_12.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0444\u0430\u0439\u043b\u0430", None))
        self.lineEdit_12.setText("")
        self.pushButton.setText(QCoreApplication.translate("Staircase_sweep_pulse", u"\u0417\u0430\u043f\u0443\u0441\u043a", None))
#if QT_CONFIG(shortcut)
        self.pushButton.setShortcut(QCoreApplication.translate("Staircase_sweep_pulse", u"Return", None))
#endif // QT_CONFIG(shortcut)
    # retranslateUi


import numpy as np
import pylab
import json

gamePieces = []
with open('pieces.json') as jsonData:
    gamePieces = json.load(jsonData)

def recurseToSolution(available, alreadyTaken, gamePieces, permutation):
    if (type(available) != list):
        available = []

    if (type(alreadyTaken) != list):
        alreadyTaken = []

    if (len(available) > 0):
        for i in range(0, len(available)):
            tempList = available.copy()
            alreadyTaken.append(tempList.pop(i))

            permutation = recurseToSolution(tempList, alreadyTaken, gamePieces, permutation)

            alreadyTaken.pop()
    else:
        permutation = testPieces(alreadyTaken, gamePieces, permutation)

        alreadyTaken = []

    return permutation

def testPieces(pieceOrder, pieces, permutation_start):
    permutation = permutation_start

    bitLength = 2 * len(pieceOrder)
    for byteArray in (((np.array(list(range(0, 2 ** bitLength)))[:,None] & (1 << np.arange(bitLength)))) > 0).astype(int):
        configurations = []

        i = 0
        while (i < len(byteArray)):
            pieceOrderIndex = int(i / 2)

            configurations.append(
                {
                    'i': pieceOrderIndex,
                    'index': pieceOrder[pieceOrderIndex],
                    'side': 'front' if (byteArray[i] == 0) else 'back',
                    'orientation': 0 if (byteArray[i + 1] == 0) else 1,
                }
            )

            i = i + 2

        permutation = permutation + 1

        bottomPieceSides = [{'side':pieces[configurations[i]['index']][configurations[i]['side']], 'orientation':configurations[i]['orientation']} for i in range(0, 3)]
        bottom = np.ones((3, 3), dtype=int)
        for i in range(0, 3):
            bottom[i, 0] = bottomPieceSides[i]['side'][0] if (bottomPieceSides[i]['orientation'] == 0) else bottomPieceSides[i]['side'][2]
            bottom[i, 1] = bottomPieceSides[i]['side'][1]
            bottom[i, 2] = bottomPieceSides[i]['side'][2] if (bottomPieceSides[i]['orientation'] == 0) else bottomPieceSides[i]['side'][0]

        topPieceSides = [{'side':pieces[configurations[i]['index']][configurations[i]['side']], 'orientation':configurations[i]['orientation']} for i in range(3, 6)]
        top = np.ones((3, 3), dtype=int)
        for i in range(0, 3):
            top[0, i] = topPieceSides[i]['side'][0] if (topPieceSides[i]['orientation'] == 0) else topPieceSides[i]['side'][2]
            top[1, i] = topPieceSides[i]['side'][1]
            top[2, i] = topPieceSides[i]['side'][2] if (topPieceSides[i]['orientation'] == 0) else topPieceSides[i]['side'][0]

        print(permutation)
        if (((bottom + top) <= 0).all()):
            print('Match Found!')
            print('')

            descriptions = {
                -1: 'hole',
                0: 'flat',
                1: 'knob'
            }

            print('Bottom:')
            for i in range(0, 3):
                print('--------------------')
                print('| ' + descriptions[bottom[i, 0]] + '  ' +  descriptions[bottom[i, 1]] + '  ' + descriptions[bottom[i, 2]] + ' |')
                print('--------------------')

            print('')

            topPieces = []
            for i in range(3, 6):
                temp = pieces[configurations[i]['index']]['front' if (configurations[i]['side'] == 'back') else 'back']
                topPieces.append([(temp[0] if (configurations[i]['orientation'] == 0) else temp[2]), temp[1], (temp[2] if (configurations[i]['orientation'] == 0) else temp[0])])

            print('Top:')
            print('|------|------|-------|')
            print('| ' + descriptions[topPieces[0][0]] + ' | ' + descriptions[topPieces[1][0]] + ' | ' + descriptions[topPieces[2][0]] + ' |')
            print('| ' + descriptions[topPieces[0][1]] + ' | ' + descriptions[topPieces[1][1]] + ' | ' + descriptions[topPieces[2][1]] + ' |')
            print('| ' + descriptions[topPieces[0][2]] + ' | ' + descriptions[topPieces[1][2]] + ' | ' + descriptions[topPieces[2][2]] + ' |')
            print('|------|------|-------|')

            exit()

    return permutation

recurseToSolution(list(range(0, len(gamePieces))), [], gamePieces, 0);


import requests
import json

class FilterChaint():
    def test_filter_batch(self):
        with open("test_json/success.json", "r") as file:
            test_params_str = file.read()
        test_data = json.loads(test_params_str)

        file_name = "test.jpg"
        file_data_binary = open(file_name, "rb")
        files = {"file": file_data_binary}

        header = {"Content-Type": "multipart/form-data"}

        url = "http://localhost:8000/imaprt_api/filter_batch"
        response = requests.post(url, files=files, data=test_data)
        print(response.content.decode())

FilterChaint().test_filter_batch()


import os
from lxml import etree
import crc_algorithms

_specimendb = '/databrowse/specimens'
NS = {"specimen": "http://thermal.cnde.iastate.edu/specimen"}
NSSTR = "{http://thermal.cnde.iastate.edu/specimen}"
OUTPUT_STRING = 0
OUTPUT_ELEMENT = 1
OUTPUT_ETREE = 2
norecursion = []
attributekeys = {
                  NSSTR + 'dimension': 'direction',
                  NSSTR + 'direction': 'name',
                  NSSTR + 'reference': 'face',
                  NSSTR + 'plane': 'face',
                  NSSTR + 'geometry': 'component',
                  NSSTR + 'physicalproperties': 'component',
                  NSSTR + 'flawparameters': 'index',
                  NSSTR + 'fiducialmark': 'name'
                }
mergechildren = [NSSTR + 'actionlog', NSSTR + 'identifiers', NSSTR + 'measurements', NSSTR + 'reldests']

class SpecimenException(Exception):
    """ Error Handling Class for Specimen Database """
    pass

def GetSpecimen(specimen, output=OUTPUT_STRING, specimendb=_specimendb):
    """ Fetch the XML Representation of a Specimen with Specimen Group Data Integrated """

    # Locate the Speicmen File
    filename = os.path.join(specimendb, specimen + '.sdb')
    if not os.path.exists(filename):
        raise SpecimenException('Unable to Locate Specimen Data File')
    elif not os.access(filename, os.R_OK):
        raise SpecimenException('Unable to Access Specimen Database')

    # Read the Specimen File
    try:
        f = open(filename, 'r')
        specimenxml = etree.XML(f.read())
        f.close()
    except:
        raise SpecimenException('Unable to Read Specimen Data File "%s"' % filename)

    # Identify the Group
    groupidelem = specimenxml.xpath("specimen:groups/specimen:groupid", namespaces=NS)
    if len(groupidelem) > 1:
        groups = {}
        # Open all of the group files and load them into a dictionary
        for group in [x.text for x in groupidelem]:
            filename = os.path.join(specimendb, group + '.sdg')
            if not os.path.exists(filename):
                pass
            elif not os.access(filename, os.R_OK):
                raise SpecimenException('Unable to Access Group File ' + filename)
            else:
                try:
                    f = open(filename, 'r')
                    groups[group] = etree.XML(f.read())
                    f.close()
                except:
                    raise SpecimenException('Unable to Read Specimen Group Data File' + filename)
            pass
        if len(groups) > 0:
            # Let's try combining all of them and seeing if the override attribute shows up anywhere
            groupnames = groups.keys()
            groupxml = groups[groupnames[0]]
            for groupname in groupnames[1:]:
                _combine_element(groupxml, groups[groupname], groupname)
            if len(groupxml.xpath("//@override", namespaces=NS)) > 0:
                print(etree.tostring(groupxml, pretty_print=True))
                raise SpecimenException("Group File Conflict - Will Not Continue Until Conflict Is Resolved - Specimen " + specimen)

            # Combine Trees
            _combine_element(specimenxml, groupxml, groupnames[0])

        # Output
        if output == OUTPUT_STRING:
            print(etree.tostring(specimenxml, pretty_print=True))
        elif output == OUTPUT_ELEMENT:
            return specimenxml
        elif output == OUTPUT_ETREE:
            return specimenxml.getroottree()
        else:
            raise SpecimenException('Invalid Return Type')
        pass

    elif len(groupidelem) == 1:
        groupid = groupidelem[0].text

        # Locate the Group File
        filename = os.path.join(specimendb, groupid + '.sdg')
        if not os.path.exists(filename):
            if output == OUTPUT_STRING:
                print(etree.tostring(specimenxml, pretty_print=True))
            elif output == OUTPUT_ELEMENT:
                return specimenxml
            elif output == OUTPUT_ETREE:
                return specimenxml.getroottree()
            else:
                raise SpecimenException('Invalid Return Type')
        elif not os.access(filename, os.R_OK):
            raise SpecimenException('Unable to Access Specimen Database')

        # Read Specimen Group File
        try:
            f = open(filename, 'r')
            groupxml = etree.XML(f.read())
            f.close()
        except:
            raise SpecimenException('Unable to Read Specimen Group Data File')

        # Combine Trees
        _combine_element(specimenxml, groupxml, groupid)

        # Output
        if output == OUTPUT_STRING:
            print(etree.tostring(specimenxml, pretty_print=True))
        elif output == OUTPUT_ELEMENT:
            return specimenxml
        elif output == OUTPUT_ETREE:
            return specimenxml.getroottree()
        else:
            raise SpecimenException('Invalid Return Type')
        pass

    elif len(groupidelem) == 0:
        if output == OUTPUT_STRING:
            print(etree.tostring(specimenxml, pretty_print=True))
        elif output == OUTPUT_ELEMENT:
            return specimenxml
        elif output == OUTPUT_ETREE:
            return specimenxml.getroottree()
        else:
            raise SpecimenException('Invalid Return Type')
    else:
        raise SpecimenException('Error Selecting Group ID Tag from Specimen Data File')

    pass

def tagname(el):
    if el.tag in attributekeys:
        try:
            return el.tag + el.get(attributekeys[el.tag])
        except:
            raise SpecimenException('Required attribute "' + attributekeys[el.tag] + '" missing from element "' + el.tag + '"')
    else:
        return el.tag

def _combine_element(one, other, group):
    """ Private Function to Recursively Combine etree Elements, Preferencing the First Element """
    mapping = {}
    for el in one:
        mapping[tagname(el)] = el
    for el in [el for el in other if tagname(el) not in [NSSTR + 'notes', NSSTR + 'specimenslist', NSSTR + 'identifiertags', NSSTR + 'groups', NSSTR + 'groupid']]:
        if len(el) == 0 and tagname(el) not in norecursion and  tagname(el) not in mergechildren:
            # Not nested
            if not tagname(el) in mapping:
                # An element with this name is not in the mapping
                mapping[tagname(el)] = el
                # Add it
                if not el.get('fromgroup'):
                    el.set('fromgroup', group)
                one.append(el)
            else:
                mapping[tagname(el)].set('override', group)

        else:
            if tagname(el) in norecursion:
                if not tagname(el) in mapping:
                     # Not in the mapping
                    mapping[tagname(el)] = el
                    if not el.get('fromgroup'):
                        el.set('fromgroup', group)
                    # Just add it
                    one.append(el)
                else:
                    mapping[tagname(el)].set('override', group)
            elif tagname(el) in mergechildren:
                if not tagname(el) in mapping:
                    mapping[tagname(el)] = el
                    for child in el:
                        if not el.get('fromgroup'):
                            el.set('fromgroup', group)
                    one.append(el)
                else:
                    for child in el:
                        if not el.get('fromgroup'):
                            child.set('fromgroup', group)
                        mapping[tagname(el)].append(child)
            else:
                try:
                    # Recursively process the element, and update it in the same way
                    _combine_element(mapping[tagname(el)], el, group)
                except KeyError:
                    # Not in the mapping
                    mapping[tagname(el)] = el
                    if not el.get('fromgroup'):
                        el.set('fromgroup', group)
                    # Just add it
                    one.append(el)
    pass

def GenerateCheckdigit(basename):
   alg = crc_algorithms.Crc(width = 4, poly = 64+2+1, reflect_in=False,
                            xor_in=0, reflect_out=False, xor_out=0)
   crc = alg.bit_by_bit(basename) & ((1<<4)-1) # Calc CRC and limit to 15
   letters="ACEFGHJKLMPRTWXN"
   crcletter=letters[crc]
   return crcletter


from typing import Any, List, Optional, Union

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app import crud, schemas
from app.api import deps
from app.models import stations_species_table

router = APIRouter()

@router.get("/", response_model=schemas.StationSummaryPagination)
def read_stations(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    order_by: Optional[List[str]] = Query(None),
) -> Any:
    """Retrieve stations."""
    stations = crud.station.get_multi(db, skip=skip, limit=limit, order_by=order_by)
    return stations

@router.get("/all/", response_model=List[schemas.StationSummary])
def read_all_stations(
    db: Session = Depends(deps.get_db),
    order_by: Optional[List[str]] = Query(None),
) -> Any:
    """Retrieve all stations."""
    stations = crud.station.get_all(db, order_by=order_by)
    return stations

@router.post("/search/", response_model=List[schemas.StationSummary])
def read_stations_by_search(
    expressions: Union[schemas.Expression, schemas.ExpressionGroup],
    db: Session = Depends(deps.get_db),
    limit: int = 0,
    order_by: Optional[List[str]] = Query(None),
) -> Any:
    """Retrieves the stations based on the given search expressions."""
    stations = crud.station.search(
        db,
        expressions=expressions,
        relations=[stations_species_table],
        order_by=order_by,
        limit=limit,
    )
    return stations

@router.get("/{station_id}", response_model=schemas.StationDetails)
def read_station_by_id(station_id: str, db: Session = Depends(deps.get_db)) -> Any:
    """Get a specific station by id."""
    station = crud.station.get(db, id=station_id)
    if not station:
        raise HTTPException(status_code=404, detail=f"Station not found: ${station_id}")
    return station


import random
import arcade
import arcade.gui

# --- Constants ---
SPRITE_SCALING_PLAYER = 0.5
SPRITE_SCALING_ROCK = .30
MOVEMENT_SPEED = 7
ROCK_COUNT = 50
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "RockinFeller"

class Player(arcade.Sprite):

    def update(self):

        self.center_x += self.change_x
        self.center_y += self.change_y

        # Check for out-of-bounds
        if self.left < 0:
            self.left = 0
        elif self.right > SCREEN_WIDTH - 1:
            self.right = SCREEN_WIDTH - 1

        if self.bottom < 0:
            self.bottom = 0
        elif self.top > SCREEN_HEIGHT - 1:
            self.top = SCREEN_HEIGHT - 1

class InstructionView(arcade.View):
    def __init__(self):
        super().__init__()

        self.manager = arcade.gui.UIManager()
        self.manager.enable()
        self.v_box = arcade.gui.UIBoxLayout()

        start_button = arcade.gui.UIFlatButton(text="Start", width=200)
        self.v_box.add(start_button.with_space_around(bottom=15))

        start_button.on_click = self.on_click_start

        self.manager.add(
            arcade.gui.UIAnchorWidget(
                anchor_x="center_x",
                anchor_y="center_y",
                child=self.v_box)
        )

    def on_show_view(self):
        arcade.set_background_color(arcade.csscolor.FOREST_GREEN)
        arcade.set_viewport(0, self.window.width, 0, self.window.height)

    def on_draw(self):
        self.clear()
        self.manager.draw()

    def on_click_start(self, event):
        game_view = GameView()
        game_view.setup()
        self.window.show_view(game_view)

# class GameOverView(arcade.View):

    # def __init__(self):
        # super().__init__()
        # self.texture = arcade.load_texture("")

        # arcade.set_viewport(0, SCREEN_WIDTH - 1, 0, SCREEN_HEIGHT - 1)

    # def on_draw(self):
        # self.clear()
        # self.texture.draw_sized(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_WIDTH, SCREEN_HEIGHT)

class GameView(arcade.View):

    def __init__(self):
            # Call the parent class initializer
        super().__init__()
            # Variables that will hold sprite lists
        self.player_sprite_list = None
        self.rock_sprite_list = None

            # Set up the player info
        self.player_sprite = None
        self.score = 0

        self.left_pressed = False
        self.right_pressed = False
        self.up_pressed = False
        self.down_pressed = False

        self.collision_sound = arcade.Sound(":resources:sounds/upgrade3.wav")
        arcade.set_background_color(arcade.color.FOREST_GREEN)

    def setup(self):
            # Sprite lists
        self.player_sprite_list = arcade.SpriteList()
        self.rock_sprite_list = arcade.SpriteList()
        self.score = 0
            # Set up the player
            # Character image from kenney.nl
        self.player_sprite = Player(":resources:images/space_shooter/playerShip1_blue.png", SPRITE_SCALING_PLAYER)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 50
        self.player_sprite_list.append(self.player_sprite)
            # Create the rocks
        for i in range(ROCK_COUNT):
                # Create the rock instance
                # Rock image from kenney.nl
            rock = Rock(":resources:images/space_shooter/meteorGrey_med1.png", SPRITE_SCALING_ROCK)
                # Position the rock
            rock.center_x = random.randrange(SCREEN_WIDTH)
            rock.center_y = random.randrange(SCREEN_HEIGHT)
                # Add the rock to the lists
            self.rock_sprite_list.append(rock)

    def on_draw(self):
        self.clear()
        self.rock_sprite_list.draw()
        self.player_sprite_list.draw()
            # Put the text on the screen.
        output = f"Score: {self.score}"
        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)

    def update_player_speed(self):
            # Calculate speed based on the keys pressed
        self.player_sprite.change_x = 0
        self.player_sprite.change_y = 0

        if self.left_pressed and not self.right_pressed:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        elif self.right_pressed and not self.left_pressed:
            self.player_sprite.change_x = MOVEMENT_SPEED

    def on_update(self, delta_time):
            # Call update on all sprites (The sprites don't do much in this
            # example though.)
        self.rock_sprite_list.update()
        self.player_sprite_list.update()
            # Generate a list of all sprites that collided with the player.
        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.rock_sprite_list)
            # Loop through each colliding sprite, remove it, and add to the score.
        for rock in hit_list:
            rock.remove_from_sprite_lists()
            self.collision_sound.play(0.1, 0, False, 1)
            self.score += 1
    def on_key_press(self, key, modifiers):

        if key == arcade.key.LEFT:
            self.left_pressed = True
            self.update_player_speed()
        elif key == arcade.key.RIGHT:
            self.right_pressed = True
            self.update_player_speed()

    def on_key_release(self, key, modifiers):

        if key == arcade.key.LEFT:
            self.left_pressed = False
            self.update_player_speed()
        elif key == arcade.key.RIGHT:
            self.right_pressed = False
            self.update_player_speed()

class Rock(arcade.Sprite):

    def reset_pos(self):
            # Reset the rock to a random spot above the screen
        self.center_y = random.randrange(SCREEN_HEIGHT + 20, SCREEN_HEIGHT + 100)
        self.center_x = random.randrange(SCREEN_WIDTH)

    def update(self):
            # Move the rock
        self.center_y -= 1
            # See if the rock has fallen off the bottom of the screen.
        if self.top < 0:
            self.reset_pos()
def main():
    """ Main function """

    window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
    start_view = InstructionView()
    window.show_view(start_view)
    arcade.run()

if __name__ == "__main__":
    main()


import sys

import pygame

from src.config import config
from pygame.constants import QUIT,\
    KEYDOWN, KEYUP, MOUSEBUTTONUP, MOUSEBUTTONDOWN

def is_keyboard(binding):
    return config['input'][binding]['binding'][0] == 'keyboard'

def filter_input_mode(binding, mode):
    return set(config['input'][binding]['mode']).intersection({'all', mode})

def is_binging_trigger_type(binding, type_list):
    return config['input'][binding]['trigger'] in type_list

class Input:
    def __init__(self, game):
        self.game = game
        self.states = {}
        self.mouse_pos = (0, 0)
        self.input_mode = 'core'
        self.full_reset()

    def full_reset(self):
        for binding in config['input']:
            self.states[binding] = False

        self.mouse_state = {
            'left': False,
            'right': False,
            'left_hold': False,
            'right_hold': False,
            'left_release': False,
            'right_release': False,
            'scroll_up': False,
            'scroll_down': False,
        }

    def soft_reset(self):
        for binding in config['input']:
            if config['input'][binding]['trigger'] == 'press':
                self.states[binding] = False
        for state in ('left',
                      'right',
                      'left_hold',
                      'right_hold',
                      'scroll_up',
                      'scroll_down'):
            self.mouse_state[state] = False

    def process_mouse_event(self, event, event_type, state):
        mouse_mapping = {
            1: ('left', 'left_hold'),
            3: ('right', 'right_hold'),
            4: ('scroll_up'),
            5: ('scroll_down'),
        }
        if event.type == event_type:
            states = mouse_mapping.get(event.button, ())
            for i in states:
                self.mouse_state[i] = state
                print(f'mouse: {event.button} state: {state}')

    def process_keyboard_event(self, event, event_type, state):
        if event.type == event_type:
            for binding in config['input']:
                if filter_input_mode(binding, self.input_mode):
                    if is_keyboard(binding):
                        if is_binging_trigger_type(binding, ['press', 'hold']):
                            key_codes = config['input'][binding]['binding'][1]
                            if event.key in key_codes:
                                self.states[binding] = state
                                print(f'key:{event.key} state: {state}')

    def update(self):
        x, y = pygame.mouse.get_pos()
        self.mouse_pos = (
            int(x / self.game.window.scaled_resolution[0]
                * self.game.window.base_resolution[0]),

            int(y / self.game.window.scaled_resolution[1]
                * self.game.window.base_resolution[1])
        )
        self.soft_reset()

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            self.process_keyboard_event(event, KEYDOWN, True)
            self.process_keyboard_event(event, KEYUP, False)
            self.process_mouse_event(event, MOUSEBUTTONDOWN, True)
            self.process_mouse_event(event, MOUSEBUTTONUP, False)
            if self.states['exit']:
                pygame.quit()
                sys.exit()


from django.conf.urls.defaults import *
from django.conf import settings
from tollgate.frontend.forms import *
from tollgate.frontend.views import *
from django.contrib.auth.decorators import permission_required

# TODO: shuffle these into views.py
from django.views.generic.base import TemplateView

from tollgate.frontend.models import IP4PortForward
from django.contrib.auth.views import password_change
from django.utils.decorators import decorator_from_middleware
from django.core.urlresolvers import get_callable
from tollgate.frontend.common import TollgateMiddleware

ip4portforward_qsd = dict(
	model=IP4PortForward
)

urlpatterns = (
	# login system
	url(
		r'^login/$',
		'login',
		name='login'
	),

	url(
		r'^logout/$',
		'logout',
		name='logout'
	),

	url(
		r'^account/password_change/$',
		password_change,
		dict(post_change_redirect='../..'),
		name='account_password_change'
	),

	# captive portal
	url(
		r'^internet/login/here/$',
		'internet_login_here',
		name='internet-login-here'
	),

	url(
		r'^internet/login/(?P<mac_address>[\dA-Fa-f]{12})/$',
		'internet_login',
		name='internet-login'
	),

	url(
		'^internet/disown/(?P<host_id>\d+)/$',
		'internet_disown',
		name='internet-disown'
	),

	url(
		r'^internet/$',
		'internet',
		name='internet'
	),

	url(
		r'^internet/offline/$',
		'internet_offline',
		name='internet-offline'
	),

	# my devices and quota
	url(
		r'^quota/on/$',
		'quota_on',
		name='quota-on'
	),

	url(
		r'^quota/off/$',
		'quota_off',
		name='quota-off'
	),

	url(
		r'^quota/user-reset/$',
		'quota_user_reset',
		name='quota-user-reset'
	),

	url(
		r'^quota/$',
		'quota',
		name='quota'
	),

	# quota management
	url(
		r'^usage/all/on/$',
		'usage_all_on',
		name='usage-all-on'
	),

	url(
		r'^usage/all/really-on/$',
		'usage_all_really_on',
		name='usage-all-really-on'
	),

	url(
		r'^usage/all/off/$',
		'usage_all_off',
		name='usage-all-off'
	),

	url(
		r'^usage/(?P<aid>\d+)/on/$',
		'usage_on',
		name='usage-on'
	),

	url(
		r'^usage/(?P<aid>\d+)/off/$',
		'usage_off',
		name='usage-off'
	),

	url(
		r'^usage/(?P<aid>\d+)/reset/$',
		'usage_reset',
		name='usage-reset'
	),

	url(
		r'^usage/(?P<aid>\d+)/disable/$',
		'usage_disable',
		name='usage-disable'
	),

	url(
		r'^usage/(?P<aid>\d+)/$',
		'usage_info',
		name='usage-info'
	),

	url(
		r'^usage/$',
		'usage',
		name='usage'
	),

	url(
		r'^usage/sort/heavy$',
		'usage_heavy',
		name='usage-heavy'
	),

	url(
		r'^usage/sort/speed$',
		'usage_speed',
		name='usage-speed'
	),

	url(
		r'^usage/sort/morereset$',
		'usage_morereset',
		name='usage-morereset'
	),

	# computer list
	url(
		r'^pclist/unowned/$',
		'pclist_unowned',
		name='pclist-unowned'
	),

	url(
		r'^pclist/$',
		'pclist',
		name='pclist'
	),

	# captive portal landing page
	url(
		r'^captive_landing/?$',
		'captive_landing',
		name='captive-landing'
	),

	# help pages
	url(
		r'^help/new/$',
		TemplateView.as_view(
			template_name='frontend/help/new.html',
		),
		name='help-new'
	),

	url(
		r'^help/api/$',
		TemplateView.as_view(
			template_name='frontend/help/api.html',
		),
		name='help-api'
	),

	url(
		r'^help/source/$',
		TemplateView.as_view(
			template_name='frontend/help/source.html',
		),
		name='source'
	),

	# signin system
	url(
		r'^signin/$',
		'signin1',
		name='signin'
	),

	url(
		r'^signin/create/$',
		'signin2',
		name='signin2'
	),

	url(
		r'^signin/(?P<uid>\d+)/$',
		'signin3',
		name='signin3'
	),

	# port forwarding system
	# TODO: shuffle to views.py
	url(
		r'^ip4portforwards/$',
		permission_required('frontend.can_ip4portforward')(
			IP4PortForwardListView.as_view()
		),
		name='ip4portforward_list'
	),

	url(
		r'^ip4portforwards/force-apply/$',
		permission_required('frontend.can_ip4portforward')(
			ip4portforward_forceapply
		),
		name='ip4portforward_forceapply'
	),

	url(
		r'^ip4portforwards/add/$',
		permission_required('frontend.can_ip4portforward')(
			ip4portforward_create
		),
		name='ip4portforward_add'
	),

	url(
		r'^ip4portforwards/(?P<pk>\d+)/$',
		permission_required('frontend.can_ip4portforward')(
			IP4PortForwardUpdateView.as_view()
		),
		name='ip4portforward_edit'
	),

	url(
		r'^ip4portforwards/(?P<object_id>\d+)/toggle/$',
		permission_required('frontend.can_ip4portforward')(
			ip4portforward_toggle
		),
		name='ip4portforward_toggle'
	),

	url(
		r'^ip4portforwards/(?P<pk>\d+)/delete/$',
		permission_required('frontend.can_ip4portforward')(
			IP4PortForwardDeleteView.as_view()
		),
		name='ip4portforward_delete'
	),

	# preferences
	url(
		r'^preferences/theme-change/$',
		'theme_change',
		name='theme-change'
	),

	url(
		r'^$',
		'index',
		name='index'),
)

# Append the TollgateMiddleware to all views
def append_middleware(urlhandler):
	"Append TollgateMiddleware to the views."
	urlhandler.add_prefix('tollgate.frontend.views')
	urlhandler._callback = decorator_from_middleware(
		TollgateMiddleware
	)(urlhandler.callback)

	return urlhandler

# wrap middleware on all of them.
urlpatterns = patterns('',
	*[append_middleware(x) for x in urlpatterns]
)