import matplotlib.pyplot as plt
import subprocess as sp
import pickle as pkl
import pandas as pd
import numpy as np
import math
import pdb

exec(open("/home/joelsmith/Projects/software/tracts/tracts.py").read())

#------------------Neutral Simulations----------------------

def run_dfuse(ratevec, tstart, popsize, markers):
    codedir = '../code/dfuse_files/'
    make_deme_file(popsize)
    for rate in ratevec:
        runstr = "dfuse -d "+codedir+"inputfiles/demefile_dmi -r 1 -g "+ \
                 str(tstart)+" -m "+str(rate*2)+" -G "+str(tstart)+" -o "+ \
                 codedir+"outputfiles/dmi"+" -l "+str(markers)
        sp.run(runstr,shell=True)
        haptable = pd.read_csv(codedir+"outputfiles/dmi.haplo",skiprows=[0])
        haptable.drop(haptable.columns[0:8], axis=1, inplace=True)
        haptable = haptable[haptable.isin(['a','b']).all(1)]
        mainfile = codedir+"outputfiles/dmi.main"
        pos = open(mainfile).readline().rstrip()
        pos = np.asarray(pos.split(' ')[2:])
        haptable.columns = pos
        haptable[haptable.isin(['a'])] = 1
        haptable[haptable.isin(['b'])] = 2
        hapfile = codedir+"tempfiles/haptable_mig_"+str(rate)+".csv"
        haptable.to_csv(hapfile,index=False)

def make_deme_file(popsize):
    inputdir = '../dfuse_files/inputfiles/'
    thefile = open(inputdir+"demefile_dmi", 'w+')
    input_list = [''] * 4
    input_list[0] = '1'
    input_list[1] = str(int(popsize))
    input_list[2] = str(int(popsize))
    for item in input_list:
        thefile.write("%s\n" % item)
    thefile.close()

def get_dfuse_tracts(ratevec,npts,maxlen,chrlen):
    codedir = "../dfuse_files/tempfiles/"
    bins = np.array([np.arange(0,maxlen*(1+.5/npts),float(maxlen)/npts)])[0]
    bintable = pd.DataFrame(index=bins[:-1],columns=ratevec)
    for rate in ratevec:
        chromdict = make_dfuse_chroms(rate,chrlen)
        tractdict = make_tracts(chromdict,chrlen)
        tractbins = make_tractbins(tractdict,chrlen,maxlen,npts)
        popahist = tractbins.get('popahist')
        popbhist = tractbins.get('popbhist')
        relpopa = popahist/np.sum(popahist)
        relpopb = popbhist/np.sum(popbhist)
        bintable[rate] = np.mean(np.vstack((relpopa,relpopb)),axis=0)
    binfile = codedir+"dfuse_bintable.pkl"
    pkl.dump(bintable,open(binfile, "wb" ))

def make_dfuse_chroms(rate, chrlen):
    codedir = "../dfuse_files/tempfiles/"
    haptable = pd.read_csv(codedir+"haptable_mig_"+str(rate)+".csv")
    chroms = np.asarray(haptable)
    pos = np.asarray(haptable.columns,dtype='float64')*chrlen
    chromdict = {"chroms":chroms,"pos":pos}
    return(chromdict)

def plot_figure_dfuse(ratevec,tstart,Ls,pop,maxlen,npts,chrlen):
    """Plots the predicted tract length distributions against the
    simulated tract length distributions from dfuse."""
    bindir = '/home/joelsmith/Projects/dmis/code/dfuse_files/tempfiles/'
    bintable = pkl.load(open(bindir+"dfuse_bintable.pkl", "rb"))
    bins = np.append(bintable.index.values,1)
    rows = bintable.shape[0]
    xAxis = np.array(list(range(1,rows+1)))[:rows-1] / np.array(rows)
    for rate in ratevec:
        mig = continuous_mig_hybridzone(rate,tstart)
        model = demographic_model(mig)
        tractsOut = model.expectperbin(Ls,pop,bins)
        tractDist = np.array(tractsOut)
        relTractDist = tractDist / np.sum(tractDist)
        obs = np.asarray(np.where(np.logical_not(bintable[rate]==0)))[0][:-1]
        obsvalues = bintable.iloc[obs][rate]
        plt.plot(bins[:npts],np.log(relTractDist[:npts:]),label='_nolegend_')
        plt.scatter(x=bintable.index[obs],y=np.log(obsvalues))
        plt.xlabel('Tract Length (Morgans)')
        plt.ylabel('log(Relative Frequency)')
        plt.legend(loc='upper right',title='Migration Rate')

def plot_image_dfuse(ratevec):
    f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
    codedir = "../dfuse_files/tempfiles/"
    chroms1 = np.asarray(pd.read_csv(codedir+"haptable_mig_"+str(ratevec[0])+".csv"))
    chroms2 = np.asarray(pd.read_csv(codedir+"haptable_mig_"+str(ratevec[1])+".csv"))
    chroms3 = np.asarray(pd.read_csv(codedir+"haptable_mig_"+str(ratevec[2])+".csv"))
    mycmap = plt.cm.get_cmap('tab10')
    ax1.imshow(chroms1,extent=[0,1,0,chroms1.shape[0]],aspect='auto',cmap=mycmap,vmin=1,vmax=7)
    ax2.imshow(chroms2,extent=[0,1,0,chroms2.shape[0]],aspect='auto',cmap=mycmap,vmin=1,vmax=7)
    ax3.imshow(chroms3,extent=[0,1,0,chroms3.shape[0]],aspect='auto',cmap=mycmap,vmin=1,vmax=7)
    ax1.set_title(ratevec[0])
    ax2.set_title(ratevec[1])
    ax3.set_title(ratevec[2])
    ax3.set_xlabel('Position (Morgans)')

#------------------Simulations with DMIs----------------------

def print_fitness_matrix(seldmi,selanc,domdmi):
    if domdmi==0:
        h0=1
        h1=1
    if domdmi==1:
        h0=1/4
        h1=1/2
    if domdmi==2:
        h0=0
        h1=1/2
    if domdmi==3:
        h0=0
        h1=0
    fitness_matrix = np.zeros((3,3))
    fitness_matrix[[0,2],[0,2]] = 1
    fitness_matrix[[1,2],[0,1]] = 1-(selanc/2)
    fitness_matrix[[0,1],[1,2]] = 1-seldmi*h1
    fitness_matrix[1,1] = 1-seldmi*h0
    fitness_matrix[2,0] = 1-selanc
    fitness_matrix[0,2] = 1-seldmi
    print('\nFitness Matrix:\n')
    print(fitness_matrix)

def run_dfuse_dmis(rate, tstart, popsize, markers, dmipos, seldmi, selanc, domdmi):
    print_fitness_matrix(seldmi, selanc, domdmi)
    codedir = '../dfuse_files/'
    make_deme_file(popsize)
    make_epis_file(dmipos)
    runstr = "dfuse -d "+codedir+"inputfiles/demefile_dmi -r 1 -g "+ \
             str(tstart)+" -m "+str(rate*2)+" -G "+str(tstart)+" -o "+ \
             codedir+"outputfiles/dmi"+" -l "+str(markers)+" -e "+ \
             codedir+"inputfiles/episfile_dmi -c "+str(seldmi)+ \
             " -a "+str(selanc)+" -R "+str(domdmi)+" -S 'fertility'"
    sp.run(runstr,shell=True)
    haptable = pd.read_csv(codedir+"outputfiles/dmi.haplo",skiprows=[0])
    haptable.drop(haptable.columns[0:8], axis=1, inplace=True)
    haptable = haptable[haptable.isin(['a','b']).all(1)]
    mainfile = codedir+"outputfiles/dmi.main"
    pos = open(mainfile).readline().rstrip()
    pos = np.asarray(pos.split(' ')[2:])
    haptable.columns = pos
    haptable[haptable.isin(['a'])] = 1
    haptable[haptable.isin(['b'])] = 2
    hapfile = codedir+"tempfiles/haptable_mig_"+str(rate)+".csv"
    haptable.to_csv(hapfile,index=False)

def make_epis_file(dmipos):
    inputdir = '../dfuse_files/inputfiles/'
    thefile = open(inputdir+"episfile_dmi", 'w+')
    input_list = [''] * 8
    input_list[0] = '2 1 2'
    input_list[1] = '0 1'
    input_list[2] = '0 0'
    input_list[3] = '0 1'
    input_list[4] = '0 0'
    input_list[5] = '0 0'
    input_list[6] = str(dmipos[0])+' '+str(dmipos[1])
    input_list[7] = '0 1'
    for item in input_list:
        thefile.write("%s\n" % item)
    thefile.close()

def get_dfuse_tracts_dmis(rate,npts,maxlen,chrlen,dmipos):
    codedir = "../dfuse_files/tempfiles/"
    bins = np.array([np.arange(0,maxlen*(1+.5/npts),float(maxlen)/npts)])[0]
    chromdict = make_dfuse_chroms(rate,chrlen)
    tractdict = make_tracts_dmis(chromdict,chrlen,dmipos)
    tractbinsa = make_tractbins_dmis(tractdict['loca'],chrlen,maxlen,npts)
    tractbinsb = make_tractbins_dmis(tractdict['locb'],chrlen,maxlen,npts)
    apopahist = tractbinsa.get('popahist')
    apopbhist = tractbinsa.get('popbhist')
    bpopahist = tractbinsb.get('popahist')
    bpopbhist = tractbinsb.get('popbhist')
    bintablea = pd.DataFrame(data={'col1':apopahist,'col2':apopbhist})
    bintableb = pd.DataFrame(data={'col1':bpopahist,'col2':bpopbhist})
    binfilea = codedir+"dfuse_bintable_a.pkl"
    binfileb = codedir+"dfuse_bintable_b.pkl"
    pkl.dump(bintablea,open(binfilea, "wb" ))
    pkl.dump(bintableb,open(binfileb, "wb" ))

def make_tractbins_dmis(tractdict,chrlen,maxlen,npts):
    bins = np.array([np.arange(0,maxlen*(1+.5/npts),float(maxlen)/npts)])[0]
    popa = np.reshape(tractdict['popa'],(tractdict['popa'].shape[1],2))
    popb = np.reshape(tractdict['popb'],(tractdict['popb'].shape[1],2))
    popaMorgans = popa[:,0]/chrlen
    popbMorgans = popb[:,0]/chrlen
    countsa = np.histogram(popaMorgans,bins)[0]
    countsb = np.histogram(popbMorgans,bins)[0]
    popahist = countsa/(np.sum(countsa)+np.sum(countsb))
    popbhist = countsb/(np.sum(countsa)+np.sum(countsb))
    tractbins = {'popahist':popahist,'popbhist':popbhist}
    return(tractbins)

def plot_locus_tractlengths(ratevec,tstart,Ls,pop,maxlen,npts,chrlen):
    """Plots the predicted locus-specific tract lengths"""
    mig = continuous_mig_hybridzone(rate,tstart)
    model = demographic_model(mig)
    tractsOut = model.expectperbin(Ls,pop,bins)
    tractDist = np.array(tractsOut)
    relTractDist = tractDist / np.sum(tractDist)
    plt.plot(bins[:npts],np.log(relTractDist[:npts:]),label='_nolegend_')

def plot_figure_dfuse_dmis(ratevec,tstart,Ls,pop,maxlen,npts,chrlen):
    """Plots the predicted tract length distributions against the
    simulated tract length distributions from dfuse."""
    bindir = '/home/joelsmith/Projects/dmis/code/dfuse_files/tempfiles/'
    bintablea = pkl.load(open(bindir+"dfuse_bintable_a.pkl", "rb"))
    bintableb = pkl.load(open(bindir+"dfuse_bintable_b.pkl", "rb"))
    bins = np.append(bintablea.index.values,1)
    rows = bintablea.shape[0]
    xAxis = np.array(list(range(1,rows+1)))[:rows-1] / np.array(rows)
    f, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,sharey=True)
    obsa = np.asarray(np.where(np.logical_not(bintablea['col1']==0)))[0][:-1]
    obsb = np.asarray(np.where(np.logical_not(bintablea['col2']==0)))[0][:-1]
    obsvaluesa = bintablea.iloc[obsa]['col1']
    obsvaluesb = bintablea.iloc[obsb]['col2']
    ax1.scatter(x=bintablea.index[obsa],y=np.log(obsvaluesa))
    ax1.scatter(x=bintablea.index[obsb],y=np.log(obsvaluesb))
    ax1.set_xlabel('Tract Length (Morgans)')
    ax1.set_ylabel('log(Relative Frequency)')
    obsa = np.asarray(np.where(np.logical_not(bintableb['col1']==0)))[0][:-1]
    obsb = np.asarray(np.where(np.logical_not(bintableb['col2']==0)))[0][:-1]
    obsvaluesa = bintableb.iloc[obsa]['col1']
    obsvaluesb = bintableb.iloc[obsb]['col2']
    ax2.scatter(x=bintableb.index[obsa],y=np.log(obsvaluesa))
    ax2.scatter(x=bintableb.index[obsb],y=np.log(obsvaluesb))
    ax2.set_xlabel('Tract Length (Morgans)')

def make_tracts_dmis(chromdict,chrlen,dmipos):
    chroms = chromdict['chroms']
    pos = np.int_(chromdict['pos'])
    loca = np.where(pos==dmipos[0]*chrlen)[0]
    locb = np.where(pos==dmipos[1]*chrlen)[0]
    switches = np.apply_along_axis(np.diff,1,chroms)
    switches[:,0] = 1
    index = 0
    lentablea = np.zeros((switches.shape[0],2),dtype='int')
    lentableb = np.zeros((switches.shape[0],2),dtype='int')
    for row in range(chroms.shape[0]):
        rowswitches = np.append(np.nonzero(switches[row,:])[0],len(pos)-1)
        lefta = rowswitches[np.max(np.where(rowswitches<loca)[0])]
        righta = rowswitches[np.min(np.where(rowswitches>loca)[0])]
        leftb = rowswitches[np.max(np.where(rowswitches<locb)[0])]
        rightb = rowswitches[np.min(np.where(rowswitches>locb)[0])]
        lena = pos[righta]-pos[lefta]
        lenb = pos[rightb]-pos[leftb]
        anca = chroms[row,loca]
        ancb = chroms[row,locb]
        lentablea[index:index+1,] = np.array([lena,anca])
        lentableb[index:index+1,] = np.array([lenb,ancb])
        index = index+1
    locapopa = lentablea[np.where(lentablea[:,1]==1),]
    locapopb = lentablea[np.where(lentablea[:,1]==2),]
    locbpopa = lentableb[np.where(lentableb[:,1]==1),]
    locbpopb = lentableb[np.where(lentableb[:,1]==2),]
    loca = {"popa":locapopa,"popb":locapopb}
    locb = {"popa":locbpopa,"popb":locbpopb}
    tractdict = {"loca":loca,"locb":locb}
    return(tractdict)

def plot_image_dfuse_dmis(rate):
    codedir = "../dfuse_files/tempfiles/"
    chroms = np.asarray(pd.read_csv(codedir+"haptable_mig_"+str(rate)+".csv"))
    mycmap = plt.cm.get_cmap('tab10')
    plt.imshow(chroms,extent=[0,1,0,chroms.shape[0]],aspect='auto',cmap=mycmap,vmin=1,vmax=7)
    plt.xlabel('Position (Morgans)')
    plt.ylabel('Chromosome')


import yfinance as yf

class Stock():
    def __init__(self,name,period="1d",interval="5m"):
        self.name = name
        self.symbol = name+".NS"
        self.period = period
        self.interval = interval
        self.ticker = yf.Ticker(self.symbol)
        self.df = self.ticker.history(period=period,interval=interval)
        self.current = self.df.iloc[-1]

    def refresh(self):
        self.ticker = yf.Ticker(self.symbol)
        self.df = self.ticker.history(period=self.period, interval=self.interval)
        self.current = self.df.iloc[-1]

    def __str__(self):
        return("{name} Close: {close} at {time}".format(name = self.name , close = self.current["Close"] , time = self.df.index[-1]))

if __name__ == '__main__':
    ticker = 'AAPL'
    ticker = yf.Ticker(ticker)  # initializing the object
    df = ticker.history(period="1d", interval="5m")
    ticker = Stock('TECHM')
    print(ticker)
    print(ticker.df)


import torch
import torchvision.models as models
from .load_images import image_loader, imshow
from .styletransfer import run_style_transfer

class StyleTransferer:
    def __init__(self, device=None):

        if device is None:
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.device = device
        self.content_img = None
        self.style_img = None
        self.input_img = None
        self.output_img = None
        self._cnn = None
        self._cnn_normalization_mean = None
        self._cnn_normalization_std = None
        self._content_layers_default = None
        self._style_layers_default = None

    def __repr__(self):
        return self.__class__.__name__

    def set_content_img(self, image_file_path, imsize=512):
        """
        ADD PEP8 DOCSTRING HERE.
        """
        self.content_img = image_loader(
            image_file_path, imsize=imsize, device=self.device
        )

    def set_input_img(self):
        """
        EDIT THIS FUNCTION!
        ADD PEP8 DOCSTRING HERE.
        """
        # add the original input image to the figure:
        self.input_img = self.content_img.clone()
        # if you want to use white noise instead uncomment the below line:
        # self.input_img = torch.randn(content_img.data.size(), device=device)

    def set_style_img(self, image_file_path, imsize=512):
        """
        ADD PEP8 DOCSTRING HERE.
        """
        self.style_img = image_loader(
            image_file_path, imsize=imsize, device=self.device
        )

    def check_image_size_match(self):
        """
        ADD PEP8 DOCSTRING HERE.

        We need to style and content images of the same size.
        """
        return self.style_img.size() == self.content_img.size()

    def initialize_cnn(self):
        """
        ADD PEP8 DOCSTRING HERE.
        """
        self._cnn = models.vgg19(pretrained=True).features.to(self.device).eval()
        self._cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(self.device)
        self._cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(self.device)
        self._content_layers_default = ['conv_4']
        self._style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']

    def execute_style_transfer(self,
        num_steps=300,
        style_weight=1000000,
        content_weight=1,
        file_path_output=None,
        verbose=1,
        ):
        """
        ADD PEP8 DOCSTRING HERE.
        """
        assert self._cnn is not None
        assert self._cnn_normalization_mean is not None
        assert self._cnn_normalization_std is not None
        assert self._content_layers_default is not None
        assert self._style_layers_default is not None

        self.output_img = run_style_transfer(
            self._cnn,
            self._cnn_normalization_mean,
            self._cnn_normalization_std,
            self.content_img,
            self.style_img,
            self.input_img,
            num_steps=num_steps,
            style_weight=style_weight,
            content_weight=content_weight,
            file_path_output=file_path_output,
            verbose=verbose,
            )

# def get_input_optimizer(input_img):
#     # this line to show that input is a parameter that requires a gradient
#     optimizer = optim.LBFGS([input_img.requires_grad_()])
#     return optimizer


import sys
input = sys.stdin.readline

N = int(input())
province = list(map(int, input().split()))
M = int(input())

def counter(m):
    total = 0

    for p in province:
        if p <= m:
            total += p
        else:
            total += m

    return total

def allocate_budget():
    answer = 0
    sp = 0
    ep = max(province)

    while sp <= ep:
        md = (sp + ep) // 2

        if counter(md) <= M:
            answer = md
            sp = md + 1
        else:
            ep = md - 1

    return answer

print(allocate_budget())

백준알고리즘/이분 탐색/python/예산.py


import sympy as sy
import numpy as np
from matplotlib import pyplot as plt
from math import *
import sys
import pygame
from pygame.locals import *

word=['','강산을 강염기로 적정','강염기를 강산으로 적정','약산을 강염기로 적정','약염기을 강산으로 적정']

def resultprint(eq_volume,x,y,flag):
    global word
    print()
    print()
    str1="<"+word[flag]+"> 계산 결과"
    print(str1)
    str2="- 당량 부피: "+str(eq_volume)+"mL"
    print(str2)
    str3="- v=0mL에서의 pH: "+str(round(y[0],2))
    print(str3)
    str4="- v="+str(round(x[len(x)//4],2))+"mL(당량점/2) 에서의 pH: "+str(round(y[len(x)//4],2))
    print(str4)
    str5="- v="+str(round(x[len(x)//2],2))+"mL(당량점) 에서의 pH: "+str(round(y[len(x)//2],2))
    print(str5)
    str6="- v="+str(round(x[len(x)//4*3],2))+"mL(당량점*3/2) 에서의 pH: "+str(round(y[len(x)//4*3],2))
    print(str6)

def calculator(ca,cb,ka,kw=10**-14):
    x=sy.Symbol('x')
    equation=x**3+(cb+ka)*x**2-(kw+ca*ka)*x-ka*kw
    #print(equation)
    ans=sy.solveset(equation,x)
    for i in ans:
        if i>0:
            return -log10(i)
            #return round(-log10(i),2)
    #print(ans)

def strongstrong(acid_volume,acid_con,acid_n,base_volume,base_con,base_n):
    con=(acid_volume*acid_con*acid_n-base_volume*base_con*base_n)/(acid_volume+base_volume)
    if con>0:       #산성0
        return -log10(con)
    elif con==0:    #중성
        return 7
    else:           #염기성
        flag=3
        return 14+log10(-con)

def strong(init_volume,init_con,init_n,add_con,add_n,flag):
    #초기 부피, 초기 농도, 초기 가수, 첨가 농도
    #flag : 1(산을 염기로 적정), 2(염기를 산으로 적정)
    #print(init_volume,init_con,init_n,add_con,add_n,flag)
    eq_volume=round(init_volume*init_con*init_n/(add_con*add_n),2)
    #print(eq_volume)
    x=np.arange(0,eq_volume*2,0.1)
    y=[]
    for i in range(len(x)):
        if flag==1:
            y.append(strongstrong(init_volume,init_con,init_n,i*0.1,add_con,add_n))
        elif flag==2:
            y.append(strongstrong(i*0.1,add_con,add_n,init_volume,init_con,init_n))
    y=np.array(y)
    return x,y,eq_volume

def weakacid(init_volume,init_con,ka,add_con,add_n,flag):
    eq_volume=eq_volume=round(init_volume*init_con/(add_con*add_n),2)
    #print(eq_volume)
    x=np.arange(0,eq_volume*2,0.1)
    y=[]
    print()
    print("진행 상황 [ ",end="")
    for i in range(len(x)):
        ca=float((init_volume*init_con-add_con*0.1*i)/(init_volume+0.1*i))
        if ca>0:
            cb=float((add_con*0.1*i)/(init_volume+0.1*i))
            y.append(calculator(ca,cb,ka))
            if (i+1)%(len(x)//20)==0:
                print('#',end="")
        else:
            y.append(14+log10(-ca))
        if y[-1]<y[0]:
            y[-1]=calculator(0,cb,ka)
    print(" ]")
    y=np.array(y)
    #print(x,y)
    return x,y,eq_volume

def weakbase(init_volume,init_con,kb,add_con,add_n,flag):
    ka=1e-14/kb
    eq_volume=eq_volume=round(init_volume*init_con/(add_con*add_n),2)
    #print(eq_volume)
    x=np.arange(0,eq_volume*2,0.1)
    y=[]
    print()
    print("진행 상황 [ ",end="")
    for i in range(len(x)):
        cb=float((init_volume*init_con-add_con*0.1*i)/(init_volume+0.1*i))
        if cb>0:
            ca=float((add_con*0.1*i)/(init_volume+0.1*i))
            y.append(calculator(ca,cb,ka))
            if (i+1)%(len(x)//20)==0:
                print('#',end="")
        else:
            y.append(-log10(-cb))
        if y[-1]>y[0]:
            y[-1]=calculator(ca,0,ka)
    print(" ]")
    y=np.array(y)
    #print(x,y)
    return x,y,eq_volume

def strongstart(flag):
    flag=int(flag)
    keyword=['','강산','강염기']
    str1='적정하고자 하는 '+keyword[flag]+'의 부피 입력(단위 mL): '
    str2='적정하고자 하는 '+keyword[flag]+'의 농도 입력(단위 M): '
    str3='적정하고자 하는 '+keyword[flag]+'의 가수 입력: '
    str4='첨가하는 '+keyword[3-flag]+'의 농도 입력(단위 M): '
    str5='첨가하는 '+keyword[3-flag]+'의 가수 입력 : '
    print()
    init_volume=float(input(str1))
    init_con=float(input(str2))
    init_n=int(input(str3))
    add_con=float(input(str4))
    add_n=int(input(str5))
    ret=strong(init_volume,init_con,init_n,add_con,add_n,flag)
    x=ret[0]
    y=ret[1]
    eq_volume=ret[2]
    #print(x,y)
    resultprint(eq_volume,x,y,flag)
    plt.title("titration curve")
    plt.plot(x,y)
    plt.show()

def weakacidstart(flag):
    flag=int(flag)
    str1='적정하고자 하는 약산의 ka 입력(예시: 8x10^-7이면 8e-7): '
    str2='적정하고자 하는 약산의 부피 입력(단위 mL): '
    str3='적정하고자 하는 약산의 농도 입력(단위 M): '
    str4='첨가하는 강염기의 농도 입력(단위 M): '
    str5='첨가하는 강염기의 가수 입력: '
    print()
    ka=float(input(str1))
    init_volume=float(input(str2))
    init_con=float(input(str3))
    add_con=float(input(str4))
    add_n=int(input(str5))
    ret=weakacid(init_volume,init_con,ka,add_con,add_n,flag)
    x=ret[0]
    y=ret[1]
    eq_volume=ret[2]
    #print(x,y)
    resultprint(eq_volume,x,y,flag)
    plt.title("titration curve")
    plt.plot(x,y)
    plt.show()

def weakbasestart(flag):
    flag=int(flag)
    str1='적정하고자 하는 약역기의 kb 입력(예시: 8x10^-7이면 8e-7): '
    str2='적정하고자 하는 약염기의 부피 입력(단위 mL): '
    str3='적정하고자 하는 약염기의 농도 입력(단위 M): '
    str4='첨가하는 강산의 농도 입력(단위 M): '
    str5='첨가하는 강산의 가수 입력: '
    print()
    kb=float(input(str1))
    init_volume=float(input(str2))
    init_con=float(input(str3))
    add_con=float(input(str4))
    add_n=int(input(str5))
    ret=weakbase(init_volume,init_con,kb,add_con,add_n,flag)
    x=ret[0]
    y=ret[1]
    eq_volume=ret[2]
    #print(x,y)
    resultprint(eq_volume,x,y,flag)
    plt.title("titration curve")
    plt.plot(x,y)
    plt.show()

def start():
    print('<적정 곡선>')
    print('1. 강산을 강염기로 적정')
    print('2. 강염기를 강산으로 적정')
    print('3. 약산을 강염기로 적정')
    print('4. 약염기을 강산으로 적정')
    flag=input('*적정 유형 선택: ')
    if flag=='1' or flag=='2':
        strongstart(flag)
    elif flag=='3':
        weakacidstart(flag)
    elif flag=='4':
        weakbasestart(flag)

start()


from threading import Lock
from concurrent.futures import ThreadPoolExecutor
import cv2
from fps import FpsCounter

class CameraFeed:
    def __init__(self, callback, video_source = 0, max_workers = 3):
        self._stream = cv2.VideoCapture(video_source)
        self._fps = FpsCounter()
        self._max_workers = max_workers
        self._numer_of_tasks = 0
        self._mutex = Lock()
        self._pool = ThreadPoolExecutor(self._max_workers+1)
        self._callback = callback

    def start(self):
        self._pool.submit(self._update)
        return self

    def _update(self):
        (grabbed, frame) = self._stream.read()
        self._pool.submit(self._update)
        with self._mutex:
            if self._numer_of_tasks > self._max_workers:
                return
            self._numer_of_tasks += 1
            self._fps.update()
        self._callback(frame)
        with self._mutex:
            self._numer_of_tasks -= 1

    def getFps(self):
        return self._fps.get()


import random
import shutil
from datetime import date
from itertools import compress

import numpy as np
import pytest

from thermal_events import (
    AnalysisStatus,
    Base,
    Category,
    Dataset,
    Device,
    LineOfSight,
    Method,
    ParentChildRelationship,
    Severity,
    ThermalEvent,
    ThermalEventCategoryLineOfSight,
    User,
    crud,
)
from thermal_events.database import get_db, temp_folder_path

from .test_thermal_event import (
    analysis_status,
    categories,
    devices,
    lines_of_sight,
    methods,
    severity_types,
    users,
)

from .test_thermal_event import random_event as _random_event

# Number of different datasets
NB_DATASETS = 3

# Random matrix encoding the compatibility between the lines of sights and the
# thermal event categories
rows = len(lines_of_sight)
cols = len(categories)
COMPATIBILITY = np.random.randint(0, 2, size=(rows, cols), dtype=bool)
row_sums = COMPATIBILITY.sum(axis=1)
row_indices = np.where(row_sums == 0)
COMPATIBILITY[row_indices, np.random.randint(0, cols, len(row_indices))] = True

def random_event(*args):
    return _random_event(*args, COMPATIBILITY)

def create_genealogy():
    """Generate random thermal events, send them to the database and create a
        random genealogy between the thermal events

    Returns:
        list: The ids of the randomly created thermal events, sorted
        numpy.ndarray: A matrix that encodes the parent / child relationship
            between the thermal events. The rows correspond to parents and the
            columns to children, so that mat[i, j] == True indicates that
            thermal event i is a parent of thermal event j
    """
    thermal_events = []
    for _ in range(10):
        thermal_events.append(random_event(10))
    crud.thermal_event.create(thermal_events)

    ids = sorted([x.id for x in thermal_events])

    mat = np.random.choice(a=[False, True], size=(len(ids), len(ids)))
    np.fill_diagonal(mat, 0)

    genealogy = []
    for i in range(len(ids)):
        for j in range(len(ids)):
            if not mat[i, j]:
                continue

            genealogy.append(
                ParentChildRelationship(
                    parent=ids[i], child=ids[j], timestamp_ns=random.randrange(100)
                )
            )

    with get_db() as session:
        session.add_all(genealogy)
        session.commit()

    return ids, mat

@pytest.fixture(scope="session", autouse=True)
def create_and_delete_temporary_database():
    """Create an temporary SQLITE database at the beginning of the test session,
    with all the necessary tables and values, and delete the database file at the
    end of the session
    """
    users.append([crud.user._user_name(), "current_user@domain.org"])

    with get_db() as session:
        # Ensure we work with a test database before creating tables
        assert "test_database.sqlite" in str(session.bind.url)

        Base.metadata.create_all(session.bind)

        session.add_all([LineOfSight(name=x) for x in lines_of_sight])
        session.add_all([Device(name=x) for x in devices])
        session.add_all([Category(name=x) for x in categories])
        categories_lines_of_sight = []
        for ind_category, category in enumerate(categories):
            for ind_los, line_of_sight in enumerate(lines_of_sight):
                if not COMPATIBILITY[ind_los, ind_category]:
                    continue
                categories_lines_of_sight.append(
                    ThermalEventCategoryLineOfSight(
                        thermal_event_category=category, line_of_sight=line_of_sight
                    )
                )
        session.add_all(categories_lines_of_sight)
        session.add_all([Method(name=x) for x in methods])
        session.add_all([User(name=x[0], email=x[1]) for x in users])
        session.add_all([Severity(name=x) for x in severity_types])
        session.add_all([AnalysisStatus(name=x) for x in analysis_status])
        session.add_all(
            [
                Dataset(creation_date=date.today(), annotation_type="bbox")
                for _ in range(NB_DATASETS)
            ]
        )

        session.commit()

    yield

    # Delete the temporary folder
    shutil.rmtree(temp_folder_path)

@pytest.fixture(autouse=True)
def reset_temporary_database():
    """Reset the temporary database after each test by emptying the tables linked
    to the thermal events (thermal_events, thermal_events_instances,
    thermal_events_genealogy)
    """
    yield

    # Clear the database
    with get_db() as session:
        # Ensure we work with the test database before emptying tables
        assert "test_database.sqlite" in str(session.bind.url)

        session.query(ParentChildRelationship).delete()
        session.query(ThermalEvent).delete()
        session.commit()

def test_thermal_event_create_read():
    # Generate a random thermal event
    expected = random_event(10)

    # Send the thermal event to the database
    crud.thermal_event.create(expected)

    # Read the thermal event from the database
    actual = crud.thermal_event.get(expected.id)

    assert expected.initial_timestamp_ns == actual.initial_timestamp_ns
    assert expected.final_timestamp_ns == actual.final_timestamp_ns
    assert expected.duration_ns == actual.duration_ns
    assert expected.max_temperature_C == actual.max_temperature_C
    assert len(expected.instances) == len(actual.instances)

def test_thermal_event_get_multi():
    # Generate random thermal events
    nb = 5
    thermal_events = [random_event(10) for _ in range(nb)]

    # Send the thermal events to the database
    crud.thermal_event.create(thermal_events)

    # Store their ids
    expected = [x.id for x in thermal_events]

    # Retrieve the thermal events and their ids
    thermal_events_read = crud.thermal_event.get_multi(limit=nb)
    actual = [x.id for x in thermal_events_read]

    assert actual == expected

def test_thermal_event_update():
    # Generate a random thermal event
    thermal_event = random_event(10)

    # Send the thermal event to the database
    crud.thermal_event.create(thermal_event)

    # Update its method with a different, randomly chosen one
    expected = random.choice([m for m in methods if m != thermal_event.method])
    thermal_event.method = expected
    crud.thermal_event.update(thermal_event)

    # Retriveve the event and check if its method has been updated
    thermal_event_db = crud.thermal_event.get(thermal_event.id)

    assert thermal_event_db.method == expected

    # Delete the event through an update by emptying its instances
    thermal_event_db.instances = []
    crud.thermal_event.update(thermal_event_db)

    assert crud.thermal_event.get(thermal_event_db.id) is None

def test_thermal_event_delete():
    # Generate a random thermal event
    thermal_event = random_event(10)

    # Send the thermal event to the database
    crud.thermal_event.create(thermal_event)

    # Delete the event and check it is deleted in the database
    crud.thermal_event.delete(thermal_event)

    assert crud.thermal_event.get(thermal_event.id) is None

def test_thermal_event_get_by_columns():
    # Generate a random thermal event with specific values for some attributes
    thermal_event = random_event(10)

    line_of_sight = random.choice(lines_of_sight)
    category = random.choice(
        list(
            compress(categories, COMPATIBILITY[lines_of_sight.index(line_of_sight), :])
        )
    )

    thermal_event.user = users[0][0]
    thermal_event.experiment_id = 123
    thermal_event.method = methods[0]
    thermal_event.line_of_sight = line_of_sight
    thermal_event.category = category

    # Send the thermal event to the database
    crud.thermal_event.create(thermal_event)

    events = crud.thermal_event.get_by_columns(user=users[0][0])
    assert len(events) == 1

    ids = crud.thermal_event.get_by_columns(experiment_id=123, return_columns=["id"])
    assert len(ids) == 1

    x, y = crud.thermal_event.get_by_columns(
        method=methods[0], return_columns=["experiment_id", "line_of_sight"]
    )
    assert len(x) == 1
    assert len(y) == 1

    ids = crud.thermal_event.get_by_columns(
        dataset=["xxx", "yyy"], return_columns=["id"]
    )
    assert len(ids) == 0

    events = crud.thermal_event.get_by_columns(
        dataset="1", line_of_sight=line_of_sight, category=category
    )
    assert len(events) == 1

def test_thermal_event_get_by_columns_exclude_time_intervals():
    # Generate random thermal events with different initial and final timestamps
    thermal_events = []
    thermal_events.append(random_event(10))
    thermal_events[-1].initial_timestamp_ns = 10
    thermal_events[-1].final_timestamp_ns = 20

    thermal_events.append(random_event(10))
    thermal_events[-1].initial_timestamp_ns = 15
    thermal_events[-1].final_timestamp_ns = 30

    thermal_events.append(random_event(10))
    thermal_events[-1].initial_timestamp_ns = 25
    thermal_events[-1].final_timestamp_ns = 50

    # Send the thermal events to the database
    crud.thermal_event.create(thermal_events)

    events = crud.thermal_event.get_by_columns_exclude_time_intervals(
        dataset=1, time_intervals=[15, None], return_columns=["id"]
    )
    assert len(events) == 1

    events = crud.thermal_event.get_by_columns_exclude_time_intervals(
        dataset=1,
        time_intervals=[None, 25],
    )
    assert len(events) == 2

    events = crud.thermal_event.get_by_columns_exclude_time_intervals(
        dataset=1,
        time_intervals=[[None, 20], [25, 60]],
    )
    assert len(events) == 1

def test_thermal_event_get_by_experiment_id():
    # Create random thermal events with different experiment ids
    thermal_events = []
    for experiment_id in range(100, 140):
        thermal_events.append(random_event(10))
        thermal_events[-1].experiment_id = experiment_id

    # Send the thermal events to the database
    crud.thermal_event.create(thermal_events)

    expected = [x.id for x in thermal_events if x.experiment_id == 100]
    actual = crud.thermal_event.get_by_experiment_id(100, return_columns=["id"])
    assert actual == expected

    expected = [x.id for x in thermal_events if 120 <= x.experiment_id <= 130]
    events = crud.thermal_event.get_by_experiment_id(120, 130)
    actual = [x.id for x in events]
    assert actual == expected

def test_thermal_event_get_by_experiment_id_line_of_sight():
    # Create random thermal events with different experiment ids and lines of sight
    ids = [100, 101]
    id_counts = [random.randrange(1, 10) for _ in ids]

    thermal_events = []
    for ind, experiment_id in enumerate(ids):
        for _ in range(id_counts[ind]):
            thermal_event = random_event(10)
            thermal_event.experiment_id = experiment_id
            thermal_event.line_of_sight = lines_of_sight[0]
            category = random.choice(
                list(
                    compress(
                        categories,
                        COMPATIBILITY[
                            lines_of_sight.index(thermal_event.line_of_sight), :
                        ],
                    )
                )
            )
            thermal_event.category = category
            thermal_events.append(thermal_event)

    # Send the thermal events to the database
    crud.thermal_event.create(thermal_events)

    expected = [
        x.id
        for x in thermal_events
        if x.experiment_id == ids[0]
        if x.line_of_sight == lines_of_sight[0]
    ]
    actual = crud.thermal_event.get_by_experiment_id_line_of_sight(
        ids[0], lines_of_sight[0], return_columns=["id"]
    )
    assert actual == expected

    events = crud.thermal_event.get_by_experiment_id_line_of_sight(
        ids[1], lines_of_sight[1]
    )
    assert len(events) == 0

def test_thermal_event_get_by_device():
    # Generate random thermal events with different devices
    device_counts = [random.randrange(10) for _ in devices]

    thermal_events = []
    for ind, device in enumerate(devices):
        for _ in range(device_counts[ind]):
            thermal_events.append(random_event(10))
            thermal_events[-1].device = device

    # Send the thermal events to the database
    crud.thermal_event.create(thermal_events)

    for ind, device in enumerate(devices):
        expected = [x.id for x in thermal_events if x.device == device]
        actual = crud.thermal_event.get_by_device(device, return_columns=["id"])
        assert actual == expected

def test_thermal_event_get_by_dataset():
    # Generate random thermal events with different datasets
    datasets = ["1", "2", "3", "1, 2", "2, 3"]
    dataset_counts = [random.randrange(1, 10) for _ in datasets]

    thermal_events = []
    for ind, dataset in enumerate(datasets):
        for _ in range(dataset_counts[ind]):
            thermal_events.append(random_event(10))
            thermal_events[-1].dataset = dataset

    # Send the thermal events to the database
    crud.thermal_event.create(thermal_events)

    for ind, dataset in enumerate(datasets):
        expected = [x.id for x in thermal_events if dataset in x.dataset]

        actual = crud.thermal_event.get_by_dataset(dataset, return_columns=["id"])
        assert sorted(actual) == sorted(expected)

def test_thermal_event_get_parents_of_thermal_event():
    # Create random thermal events with random parent/child relationships
    ids, mat = create_genealogy()

    for ind, id in enumerate(ids):
        parents = crud.thermal_event.get_parents_of_thermal_event(id)
        expected = list(compress(ids, mat[:, ind]))
        actual = [x.id for x in parents]

        assert actual == expected

def test_thermal_event_get_children_of_thermal_event():
    # Create random thermal events with random parent/child relationships
    ids, mat = create_genealogy()

    for ind, id in enumerate(ids):
        children = crud.thermal_event.get_children_of_thermal_event(id)
        actual = [x.id for x in children]
        expected = list(compress(ids, mat[ind, :]))

        assert actual == expected

def test_thermal_event_change_analysis_status():
    # Create a random thermal event
    thermal_event = random_event(10)

    # Send the thermal event to the database
    crud.thermal_event.create(thermal_event)

    # Change the status with a random one
    expected = random.choice(
        [m for m in analysis_status if m != thermal_event.analysis_status]
    )
    crud.thermal_event.change_analysis_status(thermal_event.id, expected)

    actual = crud.thermal_event.get_by_columns(
        id=thermal_event.id, return_columns=["analysis_status"]
    )[0]

    assert actual == expected

def test_user():
    # Check the users list
    assert crud.user.list() == sorted([x[0] for x in users], key=lambda s: s.lower())

    # Check that the current user has read and write rights
    assert crud.user.has_read_rights()
    assert crud.user.has_write_rights()

    # Check that the user's email address is correctly retrieved
    assert crud.user.email_address(users[0][0]) == users[0][1]
    assert crud.user.email_address(crud.user._user_name()) == users[-1][1]
    assert crud.user.email_address("fake user") is None

def test_thermal_event_category():
    # Check the categories list
    assert crud.thermal_event_category.list() == categories

    # Check the compatibilities between lines of sight and thermal event categories
    for ind, category in enumerate(categories):
        expected = list(compress(lines_of_sight, COMPATIBILITY[:, ind]))
        actual = crud.thermal_event_category.compatible_lines_of_sight(category)
        assert actual == expected

def test_dataset():
    # Check the number of datasets
    assert len(crud.dataset.list()) == NB_DATASETS

def test_analysis_status():
    # Check the analysis status list
    assert crud.analysis_status.list() == analysis_status

def test_line_of_sight():
    # Check the lines of sight list
    assert crud.line_of_sight.list() == lines_of_sight

def test_method():
    # Check the methods list
    assert crud.method.list() == methods

def test_device():
    # Check the devices list
    assert crud.device.list() == devices

def test_severity():
    # Check the severity types list
    assert crud.severity.list() == severity_types


import json
import uuid

from cah.card import Card
from cah.utils import convert_to_dict

class Player:
    """ A class representing a player """

    def __init__(self, websocket, username='', isAdmin=False):
        self.websocket = websocket
        self.username = username
        self.uuid = str(uuid.uuid4())
        self.cards = []
        self.points = 0
        self.isCzar = False
        self.isAdmin = isAdmin
        print("Player created: " + self.to_json())

    def __del__(self):
        self.websocket.close()
        print("Player destroyed: " + self.to_json())

    def add_card(self, card: Card):
        self.cards.append(card)
        print(self.username + " received: " + card.to_json())

    def remove_card(self, card: Card):
        self.cards.remove(card)
        print(self.username + " lost: " + card.to_json())

    def to_json_obj(self):
        """
        Return the JSON Object of this class
        :return: JSON Object
        """
        return {
            'uuid': self.uuid,
            'username': self.username,
            'points': self.points,
            'isCzar': self.isCzar,
            'isAdmin': self.isAdmin,
            'cards': [card.to_json_obj() for card in self.cards]}

    def to_json(self):
        """
        Return the JSON String of this class
        :return: JSON str
        """
        return json.dumps(self.to_json_obj(), default=convert_to_dict)


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

import random

def randomKey():
    code = ''
    for i in range(16):
        ran1 = random.randint(0,9)
        ran2 = chr(random.randint(65,90))
        add = random.choice([ran1,ran2])
        code = ''.join([code,str(add)])
    return code


import numbers
from typing import Optional, Iterable, Tuple, Union

import numpy as np

from ..algorithms.matrixaverager import MatrixAverager, ErrorPropagationMethod

class Curve:
    _data: np.ndarray

    def __init__(self):
        pass

    @property
    def q(self) -> np.ndarray:
        return self._data[:, 0]

    @q.setter
    def q(self, newvalue):
        self._data[:, 0] = newvalue

    @property
    def intensity(self) -> np.ndarray:
        return self._data[:, 1]

    @intensity.setter
    def intensity(self, newvalue):
        self._data[:, 1] = newvalue

    @property
    def uncertainty(self) -> np.ndarray:
        return self._data[:, 2]

    @uncertainty.setter
    def uncertainty(self, newvalue):
        self._data[:, 2] = newvalue

    @property
    def quncertainty(self) -> np.ndarray:
        return self._data[:, 3]

    @quncertainty.setter
    def quncertainty(self, newvalue):
        self._data[:, 3] = newvalue

    @property
    def binarea(self) -> np.ndarray:
        return self._data[:, 4]

    @binarea.setter
    def binarea(self, newvalue):
        self._data[:, 4] = newvalue

    @property
    def pixel(self) -> np.ndarray:
        return self._data[:, 5]

    @pixel.setter
    def pixel(self, newvalue):
        self._data[:, 5] = newvalue

    @classmethod
    def fromFile(cls, filename: str, *args, **kwargs) -> "Curve":
        data = np.loadtxt(filename, *args, **kwargs)
        self = cls()
        self._data = np.empty((data.shape[0], 6)) * np.nan
        self._data[:, :min(data.shape[1], 6)] = data[:, :min(data.shape[1], 6)]
        return self

    @classmethod
    def fromArray(cls, array: np.ndarray) -> "Curve":
        self = cls()
        self._data = np.empty((array.shape[0], 6), array.dtype) + np.nan
        self._data[:, :array.shape[1]] = array
        return self

    def __array__(self) -> np.ndarray:
        return self._data

    asArray = __array__

    @classmethod
    def fromVectors(cls, q: np.ndarray, intensity: np.ndarray, uncertainty: Optional[np.ndarray] = None,
                    quncertainty: Optional[np.ndarray] = None, binarea: Optional[np.ndarray] = None,
                    pixel: Optional[np.ndarray] = None) -> "Curve":
        assert (q is not None) and (intensity is not None)
        if not all([
            q.ndim == 1,
            intensity.ndim == 1,
            (uncertainty is None) or (uncertainty.ndim == 1),
            (quncertainty is None) or (quncertainty.ndim == 1),
            (binarea is None) or (binarea.ndim == 1),
            (pixel is None) or (pixel.ndim == 1)
        ]):
            raise ValueError('Supplied arrays must be one-dimensional.')
        if not all([
            len(intensity) == len(q),
            (uncertainty is None) or (len(uncertainty) == len(q)),
            (quncertainty is None) or (len(quncertainty) == len(q)),
            (binarea is None) or (len(binarea) == len(q)),
            (pixel is None) or (len(pixel) == len(q))
        ]):
            raise ValueError('All vectors must have the same length.')
        self = cls()
        self._data = np.empty((len(q), 6))
        self._data[:, 0] = q
        self._data[:, 1] = intensity
        self._data[:, 2] = uncertainty if uncertainty is not None else np.nan
        self._data[:, 3] = quncertainty if quncertainty is not None else np.nan
        self._data[:, 4] = binarea if binarea is not None else np.nan
        self._data[:, 5] = pixel if pixel is not None else np.nan
        return self

    def trim(self, left: float = -np.inf, right: float = np.inf, bottom=-np.inf, top=np.inf, bypixel: bool = False):
        if bypixel:
            xtrimidx = np.logical_and(self._data[:, 5] <= right, self._data[:, 5] >= left)
        else:
            xtrimidx = np.logical_and(self._data[:, 0] <= right, self._data[:, 0] >= left)
        ytrimidx = np.logical_and(self._data[:, 1] <= top, self._data[:, 1] >= bottom)
        curve = Curve()
        curve._data = self._data[np.logical_and(xtrimidx, ytrimidx)]
        return curve

    def __len__(self) -> int:
        return self._data.shape[0]

    def sanitize(self) -> "Curve":
        return Curve.fromArray(self._data[self.isvalid(), :])

    @classmethod
    def average(cls, curves: Iterable["Curve"], ierrorpropagation: ErrorPropagationMethod,
                qerrorpropagation: ErrorPropagationMethod) -> "Curve":
        qavg = MatrixAverager(errorpropagationmethod=qerrorpropagation)
        iavg = MatrixAverager(errorpropagationmethod=ierrorpropagation)
        aavg = MatrixAverager(errorpropagationmethod=ierrorpropagation)
        pavg = MatrixAverager(errorpropagationmethod=ierrorpropagation)
        for c in curves:
            qavg.add(c.q, c.quncertainty)
            iavg.add(c.intensity, c.uncertainty)
            aavg.add(c.binarea, c.binarea)
            pavg.add(c.pixel, c.pixel)
        q, dq = qavg.get()
        i, di = iavg.get()
        a = aavg.get()[0]
        p = pavg.get()[0]
        return Curve.fromVectors(q, i, di, dq, a, p)

    def isfinite(self) -> np.ndarray:
        idx = np.logical_and(np.isfinite(self.q, np.isfinite(self.intensity)))
        for vector in [self.uncertainty, self.quncertainty, self.pixel, self.binarea]:
            if np.isfinite(vector).sum() > 0:  # if not all elements are NaN
                idx = np.logical_and(idx, np.isfinite(vector))
        return idx

    def isvalid(self) -> np.ndarray:
        idx = np.logical_and(np.isfinite(self.q), np.isfinite(self.intensity))
        idx = np.logical_and(idx, self.q > 0)
        for vector in [self.uncertainty, self.quncertainty, self.pixel]:
            if np.isfinite(vector).sum() > 0:
                idx = np.logical_and(
                    idx,
                    np.logical_and(
                        np.isfinite(vector),
                        vector >= 0
                    ))
        if np.isfinite(self.binarea).sum() > 0:
            idx = np.logical_and(
                idx,
                np.logical_and(
                    np.isfinite(self.binarea),
                    self.binarea > 0
                ))
        return idx

    def __getitem__(self, item) -> "Curve":
        if isinstance(item, np.ndarray) and (item.dtype == np.bool):
            return Curve.fromArray(self._data[item, :])

    def _checkcompatibility(self, other: "Curve", maxdifferenceratio: float = 0.005):
        incompatibility = np.abs(self.q - other.q) / np.max(np.mean((self.q, other.q)), axis=0) * 2
        if np.any(incompatibility[np.isfinite(incompatibility)] > maxdifferenceratio):  # 0.01 means 1%
            raise ValueError(
                f'The two q-scales are incompatible. Max. incompatibility: {incompatibility[np.isfinite(incompatibility)].max()}')

    def __sub__(self, other: Union["Curve", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, Curve):
            self._checkcompatibility(other)
            return self.fromVectors(
                q=0.5 * (self.q + other.q),
                intensity=self.intensity - other.intensity,
                uncertainty=(self.uncertainty ** 2 + other.uncertainty ** 2) ** 0.5,
                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,
                binarea=None,
                pixel=None
            )
        elif isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity - other,
                uncertainty=self.uncertainty,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity - other[0],
                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __add__(self, other: Union["Curve", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, Curve):
            self._checkcompatibility(other)
            return self.fromVectors(
                q=0.5 * (self.q + other.q),
                intensity=self.intensity + other.intensity,
                uncertainty=(self.uncertainty ** 2 + other.uncertainty ** 2) ** 0.5,
                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,
                binarea=None,
                pixel=None
            )
        elif isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity + other,
                uncertainty=self.uncertainty,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity + other[0],
                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __rsub__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=other - self.intensity,
                uncertainty=self.uncertainty,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=other[0] - self.intensity,
                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __radd__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity + other,
                uncertainty=self.uncertainty,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity + other[0],
                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __truediv__(self, other: Union["Curve", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, Curve):
            self._checkcompatibility(other)
            return self.fromVectors(
                q=0.5 * (self.q + other.q),
                intensity=self.intensity / other.intensity,
                uncertainty=(
                                    self.uncertainty ** 2 / other.intensity ** 2 + other.uncertainty ** 2 * self.intensity ** 2 / other.intensity ** 4) ** 0.5,
                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,
                binarea=None,
                pixel=None
            )
        elif isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity / other,
                uncertainty=np.abs(self.uncertainty / other),
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity / other[0],
                uncertainty=(self.uncertainty ** 2 / other[0] ** 2 + other[1] ** 2 * self.intensity ** 2 / other[
                    0] ** 4) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __mul__(self, other: Union["Curve", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, Curve):
            self._checkcompatibility(other)
            return self.fromVectors(
                q=0.5 * (self.q + other.q),
                intensity=self.intensity * other.intensity,
                uncertainty=(
                                    self.uncertainty ** 2 * other.intensity ** 2 + other.uncertainty ** 2 * self.intensity ** 2) ** 0.5,
                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,
                binarea=None,
                pixel=None
            )
        elif isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity * other,
                uncertainty=np.abs(self.uncertainty * other),
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity * other[0],
                uncertainty=(self.uncertainty ** 2 * other[0] ** 2 + self.intensity ** 2 * other[1] ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __rtruediv__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=other / self.intensity,
                uncertainty=np.abs(other * self.uncertainty / self.intensity ** 2),
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=other[0] / self.intensity,
                uncertainty=(self.uncertainty ** 2 / self.intensity ** 4 * other[0] ** 2 + other[
                    1] ** 2 / self.intensity ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented

    def __rmul__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> "Curve":
        if isinstance(other, numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity * other,
                uncertainty=np.abs(self.uncertainty * other),
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(
                other[1], numbers.Real):
            return self.fromVectors(
                q=self.q,
                intensity=self.intensity * other[0],
                uncertainty=(self.uncertainty ** 2 * other[0] ** 2 + self.intensity ** 2 * other[1] ** 2) ** 0.5,
                quncertainty=self.quncertainty,
                binarea=self.binarea,
                pixel=self.pixel
            )
        else:
            return NotImplemented


# My idea from this example : https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import LSTM, GRU
from keras.optimizers import RMSprop
from keras.callbacks import LambdaCallback

import os.path
import shutil
import numpy as np

# For example 1
def build_model1(max_seqlen, encoding_len):
	model = Sequential()
	# Input size: (bath_num, sequences_num, dim_input)
	model.add(LSTM(20, return_sequences=True, input_shape=(max_seqlen, encoding_len)))
	model.add(LSTM(20, return_sequences=False))
	# Fully-connected layer
	model.add(Dense(encoding_len))
	model.add(Activation('softmax'))
	print(model.summary())

	optimizer = RMSprop(lr=0.01)
	model.compile(loss='categorical_crossentropy', optimizer=optimizer)
	return model

# For example 2
def build_model2(max_seqlen, encoding_len):
	#Build LSTM (Long short-term memory)
	model = Sequential()
	# Input size: (bath_num, sequences_num, dim_input)
	model.add(GRU(40, return_sequences=True, input_shape=(max_seqlen, encoding_len)))
	model.add(GRU(40, return_sequences=False))
	# Fully-connected layer
	model.add(Dense(encoding_len))
	model.add(Activation('softmax'))
	print(model.summary())

	optimizer = RMSprop(lr=0.01)
	model.compile(loss='categorical_crossentropy', optimizer=optimizer)
	return model

# For example 3
def build_model3(max_seqlen, encoding_len):
	#Build LSTM (Long short-term memory)
	model = Sequential()
	# Input size: (bath_num, sequences_num, dim_input)
	model.add(GRU(40, return_sequences=True, input_shape=(max_seqlen, encoding_len)))
	model.add(GRU(40, return_sequences=False))
	# Fully-connected layer
	model.add(Dense(encoding_len))
	model.add(Activation('softmax'))
	print(model.summary())

	optimizer = RMSprop(lr=0.01)
	model.compile(loss='categorical_crossentropy', optimizer=optimizer)
	return model

TEMP_PATH = 'temp'
if os.path.exists(TEMP_PATH):
	shutil.rmtree(TEMP_PATH)
os.makedirs(TEMP_PATH)

class Vocabulary():
	def __init__(self, tokens):
		# Vocabulary
		# for converting all tokens to index
		self.token2indices = dict((token, i) for i, token in enumerate(tokens))
		# for converting all index to a tokens
		self.indices2token = dict((i, token) for i, token in enumerate(tokens))
		self.encoding_len = len(tokens)

	def encode_target(self, next_tokens):
		# One-hot encoding
		Y_encoded = np.zeros((len(next_tokens), self.encoding_len))
		for i, tokens in enumerate(next_tokens):
			Y_encoded[i, self.token2indices[tokens]] = 1
		return Y_encoded

	def encode_input(self, batch_tokens):
		# One-hot encoding
		total, seq_len = np.shape(batch_tokens)
		X_encoded = np.zeros((total, seq_len, self.encoding_len))
		for i, tokens in enumerate(batch_tokens):
			for t, token in enumerate(tokens):
				X_encoded[i, t, self.token2indices[token]] = 1
		return X_encoded

	# copy this function from: https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py
	def decode_predict(self, preds, temperature=1.0):
		# helper function to sample an index from a probability array
		preds = np.asarray(preds).astype('float64')
		preds = np.log(preds) / temperature
		exp_preds = np.exp(preds)
		preds = exp_preds / np.sum(exp_preds)
		probas = np.random.multinomial(1, preds, 1)
		return np.argmax(probas)

def model_generate_text(model, vocab, seq_tokens, content_length, diversity ):
	generate_text = seq_tokens
	max_seqlen = len(seq_tokens)

	for i in range(0, content_length - max_seqlen):
		# One-hot encoding
		seq_encoded = vocab.encode_input([seq_tokens]) # input shape is [1, number of tokens, encoding_len ]
		preds = model.predict(seq_encoded, verbose=0)[0] # Output shape is [1, encoding_len]

		next_index = vocab.decode_predict(preds, diversity)
		next_char = vocab.indices2token[next_index]
		generate_text = np.append(generate_text, next_char)
		seq_tokens = np.append(seq_tokens[1:], next_char)

	return generate_text

def get_vocabulary(content):
	tokens = sorted(list(set(content)))
	encoding_len = len(tokens)
	print("\ntokens:\n", tokens)
	return Vocabulary(tokens)

def train_model(content, max_seqlen, build_model, step=1,
				write_tofilename="log.txt", num_epochs=60,
				diversity_list = [0.2, 0.5, 1.0, 1.2]):
	# clear up tokens duplicated
	vocab = get_vocabulary(content)
	print("\ntotal tokens: ", vocab.encoding_len)
	print("sequences length: ", max_seqlen)

	print('Preparing the input and target...')
	# Preparing the input and target
	# cut the content in semi-redundant sequences of max_seqlen characters
	batch_seqtokens = []
	next_tokens = []
	for i in range(0, len(content) - max_seqlen, step):
		batch_seqtokens.append(content[i: i + max_seqlen])
		next_tokens.append(content[i + max_seqlen])
	print('len batch_seqtokens:', len(batch_seqtokens))
	print('len next_tokens:', len(next_tokens))

	print('Vectorization...')
	# One-hot encoding
	X = vocab.encode_input(batch_seqtokens)
	y = vocab.encode_target(next_tokens)
	print("X shape:", X.shape)
	print("Y shape:", y.shape)

	print('Build model...')
	model = build_model(max_seqlen, vocab.encoding_len)

	# write text to files
	def __write_text__(file_name, generate_text):
		file = open(os.path.join(TEMP_PATH, file_name) ,"w")
		text = ''.join(generate_text)
		print('\n**** Generate text *****\n', text)
		file.write(text)
		file.close()

	all_log = {}
	all_log['max_seqlen'] = max_seqlen
	def on_epoch_end(epoch, _):
		#model.fit(X, y,
		#	  batch_size=25,
		#	  epochs=num_epochs, verbose=0) # verbose = 1, 2 print a progress status
		generate_list =[[]] * len(diversity_list)
		# start_index = random.randint(0, len(content) - max_seqlen - 1)
		for index, diversity in enumerate(diversity_list):	# many diversity
			print('Tesing with diversity:', diversity)
			# for begining input
			seq_tokens =content[0:max_seqlen]
			#seq_tokens =content[start_index: start_index + max_seqlen]

			print("Generate with begining tokens: ", seq_tokens)

			"""
			generate_text = seq_tokens
			for i in range(0, len(content) - max_seqlen):
				# One-hot encoding
				seq_encoded = vocab.encode_input([seq_tokens]) # input shape is [1, number of tokens, encoding_len ]
				preds = model.predict(seq_encoded, verbose=0)[0] # Output shape is [1, encoding_len]

				next_index = vocab.decode_predict(preds, diversity)
				next_char = vocab.indices2token[next_index]
				generate_text = np.append(generate_text, next_char)
				seq_tokens = np.append(seq_tokens[1:], next_char)
			"""

			#visualiz training
			generate_text = model_generate_text(model, vocab, seq_tokens, len(content), diversity)

			file_name =  "diversity_"+ str(diversity) + "_"  + write_tofilename
			# override old file
			__write_text__(file_name, generate_text) 	# write a file for each diversity
			generate_list[index].append(generate_text) 	# for visual only

			#################### ending trainer function #################
		all_log[epoch] = generate_list

	print_callback = LambdaCallback(on_epoch_end=on_epoch_end)

	model.fit(X, y,
		  batch_size=128,
		  epochs = num_epochs,
		  callbacks=[print_callback])

	return	all_log, model


import sqlite3

conn = sqlite3.connect("lines.db")
cursor = conn.cursor()

def create_tables():
    create_flights_table()
    create_seats_table()
    create_runways_table()
    create_extras_table()
    create_promo_codes_table()

def create_promo_codes_table():
    query = """CREATE TABLE IF NOT EXISTS
        promo_codes(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            code INTEGER NOT NULL,
            percents_discount INTEGER NOT NULL)"""

    cursor.execute(query)

def create_runways_table():
    query = """CREATE TABLE IF NOT EXISTS
        runway(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            is_free INTEGER NOT NULL,
            free_until TEXT NOT NULL)"""

    cursor.execute(query)

def create_flights_table():
    query = """CREATE TABLE IF NOT EXISTS
        flights(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            destination TEXT NOT NULL,
            time TEXT NOT NULL)"""
    cursor.execute(query)

def create_seats_table():
    query = """CREATE TABLE IF NOT EXISTS
        seats(id INTEGER PRIMARY KEY AUTOINCREMENT,
            num INTEGER NOT NULL,
            flight_id INTEGER NOT NULL,
            headphones INTEGER NOT NULL,
            champagne INTEGER NOT NULL,
            food INTEGER NOT NULL,
            price REAL NOT NULL,
            sold INTEGER NOT NULL,
            FOREIGN KEY(flight_id) REFERENCES flights(id))"""
    cursor.execute(query)

def create_extras_table():
    query = """CREATE TABLE IF NOT EXISTS
        extras(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            seat_num INTEGER NOT NULL,
            flight_id INTEGER NOT NULL,
            headphones_price INTEGER NOT NULL,
            champagne_price INTEGER NOT NULL,
            food_price INTEGER NOT NULL,
            FOREIGN KEY(seat_num) REFERENCES seats(num))"""
    cursor.execute(query)

def add_runway(is_free,  free_until):
    query = """INSERT into runway
    (is_free, free_until)
    values (?, ?)"""

    cursor.execute(query, (is_free, free_until))
    conn.commit()

def add_seat(flight_id, num, price, headphones_price, champagne_price,
             food_price):
    query = """INSERT into seats
    (flight_id, num, headphones, champagne, food, price, sold)
    values (?, ?, ?, ?, ?, ?, ?)"""

    cursor.execute(
        query, (flight_id, num, 0, 0, 0, price, 0))
    conn.commit()
    add_extras(num, flight_id, headphones_price, champagne_price, food_price)

def add_extras(seat_num, flight_id, headphones_price, champagne_price,
               food_price):
    query = """INSERT into extras
    (seat_num, flight_id, headphones_price, champagne_price, food_price)
    values (?, ?, ?, ?, ?)"""

    cursor.execute(
        query, (seat_num, flight_id, headphones_price, champagne_price,
                food_price))
    conn.commit()

def add_flight(destination, time):
    query = """INSERT into flights
    (destination, time)
    values (?, ?)"""

    cursor.execute(query, (destination, time))
    conn.commit()

def add_promo_code(code, percent):
    query = """INSERT into promo_codes
    (code, percents_discount)
    values (?, ?)"""

    cursor.execute(query, (code, percent))
    conn.commit()

def get_promo_code_percent(promo_code):
    query = "SELECT percents_discount FROM promo_codes WHERE code = ?"
    cursor.execute(query, (promo_code,))
    percent = cursor.fetchone()
    return percent[0]

def get_seat_price(flight_id, seat):
    query = "SELECT price FROM seats WHERE flight_id = ? and num = ?"
    cursor.execute(query, (flight_id, seat))
    price = cursor.fetchone()
    return price[0]

def get_free_runways():
    query = "SELECT id, free_until FROM runway WHERE is_free = ?"
    cursor.execute(query, (1,))
    runways = cursor.fetchall()
    return runways

def get_flights(destination):
    query = "SELECT id, destination, time FROM flights WHERE destination = ?"
    cursor.execute(query, (destination,))
    flights = cursor.fetchall()
    return flights

def get_seats(flight_id):
    query = "SELECT num, sold FROM seats WHERE flight_id = ?"
    cursor.execute(query, (flight_id,))
    seats = cursor.fetchall()
    return seats

def get_extras_prices(flight_id, seat):
    query = """SELECT headphones_price, champagne_price, food_price
    FROM extras WHERE flight_id = ? and seat_num = ?"""
    cursor.execute(query, (flight_id, seat))
    extras_prices = cursor.fetchone()
    return extras_prices

def get_ticket_id(flight_id, seat):
    query = "SELECT id FROM seats WHERE flight_id = ? and num = ?"
    cursor.execute(query, (flight_id, seat))
    ticket_id = cursor.fetchone()
    return ticket_id[0]

def get_destination(flight):
    query = """SELECT destination FROM flights
    WHERE id = ?"""
    cursor.execute(query, (flight,))
    destination = cursor.fetchone()
    return destination[0]

def get_runway(runway_id):
    query = """SELECT is_free, free_until FROM runway
    WHERE id = ?"""
    cursor.execute(query, (runway_id,))
    runway = cursor.fetchone()
    return runway

def set_seat_sold(flight_id, seat_number):
    query = """UPDATE seats SET sold = ?
    WHERE flight_id = ? and num = ?"""
    cursor.execute(query, (1, flight_id, seat_number))

    conn.commit()

    return get_ticket_id(flight_id, seat_number)

def set_extras_to_seat(flight_id, seat, headphones, champagne, food):
    query = """UPDATE seats SET headphones = ?, champagne = ?, food = ?
    WHERE flight_id == ? and num = ?"""
    cursor.execute(query, (headphones, champagne, food, flight_id, seat))

    conn.commit()

def set_permission_given_at_time(runway_number, time):
    query = """UPDATE runway SET free_until = ? WHERE id == ?"""
    cursor.execute(query, (time, runway_number))

    conn.commit()

def is_ticket_taken(flight, seat):
    query = """SELECT sold FROM seats
    WHERE flight_id = ? and num = ?"""
    cursor.execute(query, (flight, seat))
    ticket_sold = cursor.fetchone()
    if ticket_sold[0] == 0:
        return False
    return True

def make_runway_free(runway):
    query = """UPDATE runway SET is_free = ?, free_until = ? WHERE id = ?"""
    cursor.execute(query, (1, "31-12-2050 23:59", runway))

    conn.commit()

def is_promo_code_correct(promo_code):
    query = "SELECT Count(*) FROM promo_codes WHERE code = ?"
    cursor.execute(query, (promo_code,))
    count = cursor.fetchone()
    if count[0] == 0:
        return False
    return True


'''
Created on 2018/8/7/

@author: quan_
fd, file directory
filens, file names
FN, Folder name
fPth, file path
nf, new file
'''

import os

def pichFile(directory):
    fd = []
    filens = []
    isInfo = 0
    exclude = []
    for Path, dirs, fns in os.walk(directory, topdown = True):
        dirs[:] = [d for d in dirs if d in exclude]
        for fn in fns:
            if isInfo == 0 and "Info" in fn:
                isInfo = 1
                continue
            filens.append(fn)
            filePth = os.path.join(Path, fn)
            fd.append(filePth)
    return fd, filens

def exportFile(directory, FileName, WaveNumber, RamanIntensity, floorNum, ceilingNum):
    FN = str(floorNum) +" to "+ str(ceilingNum)
    fPth = os.path.join(directory, FN)
    if not os.path.exists(fPth):
        os.makedirs(fPth)
    fPth = os.path.join(fPth, FileName)

    open(fPth, "w+")
    nf = open(fPth, "a+")
    for i in range(len(WaveNumber)-1):
        nf.write(str(WaveNumber[i]) + "\t" + str(RamanIntensity[i]) + "\n")
    return True


#!/usr/bin/python3
"""  Module for function pascal_triangle  """

def pascal_triangle(n):
    """pascal_triangle: function that returns a list of integers representing
        the Pascal's triangle of n
    """
    if n <= 0:
        return []
    i = 1
    triangle = [[1]]
    while i < n:
        row = i
        col = 0
        aux = []
        while col <= i:
            value = 0
            sub = 1
            while sub >= 0:
                x, y = row - 1, col - sub
                if y < 0 or y >= i:
                    value += 0
                else:
                    value += triangle[x][y]
                sub -= 1
            aux.append(value)
            col += 1
        triangle.append(aux)
        i += 1
    return triangle


import os
from conans import ConanFile
from conans.tools import download, unzip

channel = os.getenv("CONAN_CHANNEL", "channel")
username = os.getenv("CONAN_USERNAME", "username")

class TestPackage(ConanFile):
    name = "test-package"
    version = "0.1"
    settings = "os"

    def build(self):
        archive = "premake.zip"
        download("https://github.com/premake/premake-core/releases/download/v5.0.0-alpha9/premake-5.0.0-alpha9-src.zip", archive)
        unzip(archive)
        os.unlink(archive)

        if self.settings.os == "Windows":
            os.chdir("premake-5.0.0-alpha9/build/gmake.windows")
            self.run("nmake")
            os.chdir("../..")

        elif self.settings.os == "Macos":
            os.chdir("premake-5.0.0-alpha9/build/gmake.macosx")
            self.run("make")

        elif self.settings.os == "Linux":
            os.chdir("premake-5.0.0-alpha9/build/gmake.unix")
            self.run("make")

    def package(self):
        self.copy("*", dst="bin", src="premake-5.0.0-alpha9/bin/release")


"""Player character"""
from base import *
from shapes import Rectangle
from level import Tile
import math
import pygame

class Player(Base):
    def __init__(self, pos: tuple):
        super().__init__()
        self.x, self.y = pos
        self.vx, self.vy = 0, 0
        self.bg_rect = Rectangle((pos[0], 40, pos[1], 40), BLACK)
        self.center_rect = Rectangle((pos[0], 34, pos[1], 34), (230, 100, 0))
        self.mask = pygame.mask.from_surface(self.bg_rect.surf)
        self.bbox_size = self.bg_rect.surf.get_size()
        # self.debug_line = Line((0, 0), (0, 0), (255, 0, 0), 4)

        self.alpha = 255
        self.speed = 2
        self.hide = False
        self.can_move = True

    @property
    def velocity_direction(self) -> tuple:
        if self.vx < 0:
            x_dir = -1
        elif self.vx > 0:
            x_dir = 1
        else:
            x_dir = 0
        if self.vy < 0:
            y_dir = -1
        elif self.vy > 0:
            y_dir = 1
        else:
            y_dir = 0
        return x_dir, y_dir

    def draw(self, screen, offsets: tuple):
        if self.hide is False:
            self.bg_rect.draw(screen, offsets)
            div = (self.bg_rect.width - self.center_rect.width) / 2
            self.center_rect.x = self.bg_rect.x + div
            self.center_rect.y = self.bg_rect.y + div
            self.center_rect.draw(screen, offsets)
            # self.debug_line.draw(screen, offsets)

    def fadeout(self):
        if self.alpha > 0:
            self.alpha -= 6.375 / 2
            self.bg_rect.surf.set_alpha(round(self.alpha))
            self.center_rect.surf.set_alpha(round(self.alpha))

    def fadein(self):
        if self.alpha < 255:
            self.alpha += 6.375 / 2
            self.bg_rect.surf.set_alpha(round(self.alpha))
            self.center_rect.surf.set_alpha(round(self.alpha))

    @property
    def origin(self) -> tuple:
        return self.x + self.bg_rect.width / 2, self.y + self.bg_rect.height / 2

    def rect_intersect(self, rect: Rectangle):
        x, y = self.origin
        if rect.within(self.bg_rect) and rect.collide:
            nx = max(rect.x, min(x, rect.x + rect.width))  # Determine closest point
            ny = max(rect.y, min(y, rect.y + rect.height))

            # self.debug_line.start = nx, ny
            # self.debug_line.dest = x, y

            # Determine which axis to push on, based on which is closest
            if math.fabs(ny - y) > math.fabs(nx - x):
                if y < ny:  # Push up
                    self.y += ny - y - self.bg_rect.height / 2
                elif y > ny:  # Push down
                    self.y += ny - y + self.bg_rect.height / 2
            else:
                if x < nx:  # Push left
                    self.x += nx - x - self.bg_rect.width / 2
                elif x > nx:  # Push right
                    self.x += nx - x + self.bg_rect.width / 2

    def reset(self):
        """Resets changes back to their default."""
        self.set_speed(2)
        self.center_rect.color = 230, 100, 0

    def set_speed(self, speed: int):
        dir = self.velocity_direction
        self.vx = dir[0] * speed
        self.vy = dir[1] * speed
        self.speed = speed

    def teleport(self, x: int, y: int):
        """Sets the players origin to this x and y value."""
        self.x = x - self.bbox_size[0] / 2
        self.y = y - self.bbox_size[1] / 2

    def tick(self):
        if self.can_move or self.hide:
            self.x += self.vx
            self.y += self.vy
        else:
            self.vx = 0
            self.vy = 0
        self.bg_rect.x, self.bg_rect.y = self.x, self.y

    def tile_interact(self, tile: Tile):
        """Executes important tile flags when the player touches one of them."""
        if self.bg_rect.within(tile):
            tile.execute_flag(self)


# -*- coding: utf-8 *-*
import os, re, sys
from lxml import etree
import zbx_authority

folder='../Song_GSZ'

def myRepl(mo):
	gv['count']+=1
	orig=mo.group(1)
	print(orig, file=log)
	s=orig
	if not s.endswith('/>'): s+='</date>'
	root = etree.XML(s)
	key=root.get('key')
	print(key, file=log)
	done=False
	if root.get('when-iso') is not None:
		if re.match(r'^.*\d\-', root.get('when-iso')): # 如果不只有年份
			info=zbx_authority.getTimeInfo(w=key[1:8])
			root.set('when-iso', info['W']['data1']['ceDate'])
			done=True
		else:
			del root.attrib['when-iso']
	if not done and root.get('from-iso') is not None and root.get('to-iso') is not None :
		info=zbx_authority.getTimeInfo(f=key[1:8], t=key[8:])
		if info is None:
			print('在 authority 找不到資料', file=log)
			print(gv['fn'], key, file=log)
		else:
			root.set('from-iso', info['F']['data1']['ceDate'])
			root.set('to-iso', info['T']['data1']['ceDate'])
			done=True
	if not done and root.get('notAfter-iso') is not None and root.get('notBefore-iso') is not None :
		info=zbx_authority.getTimeInfo(f=key[1:8], t=key[8:])
		if info is None:
			print('在 authority 找不到資料', file=log)
			print(gv['fn'], key, file=log)
		else:
			root.set('notBefore-iso', info['F']['data1']['ceDate'])
			root.set('notAfter-iso', info['T']['data1']['ceDate'])
			done=True
	if done:
		r=str(etree.tostring(root), encoding='utf8')
		if not s.endswith('/>'): r=re.sub('^(.*)/>', r'\1>', r)
	else:
		print('when, from, to, notAfter, notBefore 都沒有', file=log)
		r=mo.group(0)
	print(r, file=log)
	print(file=log)
	return r

def do1file(source, target):
	print(source)
	with open(os.path.join(folder, source), 'r', encoding='utf8') as fi:
		text=fi.read()
	text=re.sub('(<date [^>]*?>)', myRepl, text)
	fo=open(os.path.join(folder, target), 'w', encoding='utf8')
	fo.write(text)
	fo.close()

def do1folder(dir1, dir2):
	print(dir1)
	if not os.path.exists(dir2):
		os.makedirs(dir2)
	files=os.listdir(dir1)
	for f in files:
		p1=os.path.join(dir1, f)
		p2=os.path.join(dir2, f)
		if os.path.isdir(p1):
			do1folder(p1, p2)
		elif f.endswith('xml'):
			gv['fn']=f
			do1file(p1, p2)
gv={'count':0}
f1=sys.argv[1]
f2=sys.argv[2]
log=open('date.log', 'w', encoding='utf8')
do1folder(f1, f2)
print('共取代 {} 個 <date>'.format(gv['count']))


def ocisti(s):
    s1 = []
    i = 0
    a = len(s)
    while i < a:
        if s[i] not in s1:
            s1.append(s[i])
            i+=1
        else:
            del s[i]
            a-=1

def unikati(s):
    prazen_seznam = []

    for i in s:                         # for i in s pomeni, da se i premika po vrednostih seznama s, NE PO INDEKSIH!
        if i not in prazen_seznam:
            prazen_seznam.append(i)

    return prazen_seznam

def preberi(ime_datoteke):
    prazen_slovar = {}
    stevec_vrst = 1
    prazen_seznam = []

    #Najprej ustvarim slovar zemljevida, kjer je ključ krožišče in vsebina ključa njegove povezave oz. sosednja krožišča
    for vrsta in open(ime_datoteke): #vsaka vrsta naslednje krožišče
        for kroz in vrsta.split():
            if kroz == " ":
                continue
            else: prazen_seznam.append(int(kroz))
        prazen_slovar[stevec_vrst] = prazen_seznam
        prazen_seznam = []
        stevec_vrst+=1

    #Sprehdim se po ustvarjenem slovarju in dam minimum na začetek, vsa prejšnja krožišča pred najmanjšo številko najprej zbrišem in nato na novo v isti seznam dodam
    for krozisce, povezave in prazen_slovar.items():
        for povezava in povezave:
            strazar = povezave[0] #strazar je torej prvi sosed sosedov
            if strazar != min(povezave): #ker je strazar na prvem mestu torej mi je v pomoc pri iskanju najmanjšega števila, če ni enak minimumu,
                # ga brišem in na novo dodajam v seznam toliko časa, dokler straza ni enak minimumu
                povezave.remove(strazar)
                povezave.append(strazar)
            else: #ko je strazar enak minimumu, spremenjen seznam sosedov določim krožišču
                prazen_slovar[krozisce] = povezave
                break

    return prazen_slovar

def mozna_pot(pot, zemljevid):
    izhodi = []
    index = 1

    #Po pogledu v teste opazim da testi vzamejo tudi nek drugi nov zemljevid, torej samo določitev izhodov [1, 2, 12, 15] ni pravilno. Moram jih najti. Najdem jih tako da preverim tiste kljuce ki imajo dolzino seznama ena,
    # kar pomeni da imajo samo eno povezavo. To so izhodne povezave:
    for krizisce1, povezave1 in zemljevid.items():
        if len(povezave1) == 1:
            izhodi.append(krizisce1)

    del_poti_povezave = []

    for del_poti in pot:
        naslednji_del_poti = pot[index]
        index += 1 #z njim bom lazje dostopal do naslednjega krozisca in preverjal ali je v seznamu sosedov trenutnega krozisca
        trenutno = del_poti

        for krozisce, povezava in zemljevid.items():
            if pot[0] in izhodi and pot[-1] in izhodi: #začetek in konec s končno povezavo
                if naslednji_del_poti in zemljevid[del_poti]: #ali je naslednje krožišče v seznamu sosedov trenutnega krožišča
                    if naslednji_del_poti == pot[-1]: #ali je naslednje krožišče enako koncu
                        if naslednji_del_poti in izhodi: #če se končna
                            return True
                        else:
                            return False
                    if naslednji_del_poti in izhodi: #ali je vmes končna povezava
                        return False
                else:
                    return False
            else:
                return False

def hamiltonova(pot, zemljevid):
    izhodi = []
    vsa = []
    vsa1 = []

    for krizisce1, povezave1 in zemljevid.items():
        if len(povezave1) == 1:
            izhodi.append(krizisce1)
        if len(povezave1) > 1:
           for povezava in povezave1:
                if len(povezave1) > 1 and povezava not in izhodi and len(zemljevid[povezava])>1:
                    vsa.append(povezava)

    ocisti(vsa) #uporabil sem funkcijo iz unikatov ki pobriše podvojene vrednosti
    vsa1 = sorted(vsa) #uredim po velikosti

    dol_pot = len(pot)
    dol_vsa = len(vsa)

    if mozna_pot(pot, zemljevid) and dol_pot == dol_vsa+2:
        return True
    else:
        return False

def navodila(pot, zemljevid):
    navodila1 = []

    for notri, krizisce, vn in zip(pot, pot[1:], pot[2:]): #naredim trojke s pomočjo zipa
        razlika = zemljevid[krizisce].index(vn) - zemljevid[krizisce].index(notri) #odštejem index izvoza ven v naslednje krožišče in indeks uvoza v trenutno krožišče
        navodila1.append(razlika%len(zemljevid[krizisce])) #appendam ostanek pri deljenju razlike in dolžine seznama sosedov

    return navodila1

import collections


from baseClasses.PreProcessingStep import *
import numpy as np
from helper.functions import getRotationMatrix3D

class TranslateFixLock(PreProcessingStep):

    def __init__(self,**kwargs):
        self.nosetipindex = kwargs.get('nosetip',2)
        if type(self.nosetipindex) is not int and self.nosetipindex.isdigit():
            self.nosetipindex = int(self.nosetipindex)

    def doPreProcessing(self,template):
        template.image = template.image - template.faceMarks[self.nosetipindex]

        rm90cw = getRotationMatrix3D(np.deg2rad(90),'z')
        ones = np.ones((template.image.shape[0], 1))
        homo = np.concatenate((template.image, ones),axis=1)
        template.image = np.dot(homo, rm90cw)[:,:-1]

        rm90cw = getRotationMatrix3D(np.deg2rad(180),'y')
        ones = np.ones((template.image.shape[0], 1))
        homo = np.concatenate((template.image, ones),axis=1)
        template.image = np.dot(homo, rm90cw)[:,:-1]

        return template


#!/usr/bin/env python3
#----------------------------------------------------------------------------
# Copyright (c) 2018 FIRST. All Rights Reserved.
# Open Source Software - may be modified and shared by FRC teams. The code
# must be accompanied by the FIRST BSD license file in the root directory of
# the project.
#----------------------------------------------------------------------------

import json
import time
import sys
import cv2
import numpy
import math
from enum import Enum

from cscore import CameraServer, VideoSource, UsbCamera, MjpegServer, CvSink
from networktables import NetworkTablesInstance

class GripPipeline:
    """
    An OpenCV pipeline generated by GRIP.
    """

    def __init__(self):
        """initializes all values to presets or None if need to be set
        """

        self.__blur_type = BlurType.Box_Blur
        self.__blur_radius = 0.0

        self.blur_output = None

        self.__hsv_threshold_input = self.blur_output
        self.__hsv_threshold_hue = [57.34840279860462, 94.87080310391892]
        self.__hsv_threshold_saturation = [104.83042497000248, 255.0]
        self.__hsv_threshold_value = [229.31655277665567, 255.0]

        self.hsv_threshold_output = None

        self.__find_blobs_input = self.hsv_threshold_output
        self.__find_blobs_min_area = 200.0
        self.__find_blobs_circularity = [0.0, 0.9073622902098776]
        self.__find_blobs_dark_blobs = False

        self.find_blobs_output = None

    def process(self, source0):
        print("processing")
        """
        Runs the pipeline and sets all outputs to new values.
        """
        # Step Blur0:
        self.__blur_input = source0
        (self.blur_output) = self.__blur(self.__blur_input, self.__blur_type, self.__blur_radius)

        # Step HSV_Threshold0:
        self.__hsv_threshold_input = self.blur_output
        (self.hsv_threshold_output) = self.__hsv_threshold(self.__hsv_threshold_input, self.__hsv_threshold_hue, self.__hsv_threshold_saturation, self.__hsv_threshold_value)

        # Step Find_Blobs0:
        self.__find_blobs_input = self.hsv_threshold_output
        (self.find_blobs_output) = self.__find_blobs(self.__find_blobs_input, self.__find_blobs_min_area, self.__find_blobs_circularity, self.__find_blobs_dark_blobs)
        return self.find_blobs_output

    @staticmethod
    def __blur(src, type, radius):
        """Softens an image using one of several filters.
        Args:
            src: The source mat (numpy.ndarray).
            type: The blurType to perform represented as an int.
            radius: The radius for the blur as a float.
        Returns:
            A numpy.ndarray that has been blurred.
        """
        if(type is BlurType.Box_Blur):
            ksize = int(2 * round(radius) + 1)
            return cv2.blur(src, (ksize, ksize))
        elif(type is BlurType.Gaussian_Blur):
            ksize = int(6 * round(radius) + 1)
            return cv2.GaussianBlur(src, (ksize, ksize), round(radius))
        elif(type is BlurType.Median_Filter):
            ksize = int(2 * round(radius) + 1)
            return cv2.medianBlur(src, ksize)
        else:
            return cv2.bilateralFilter(src, -1, round(radius), round(radius))

    @staticmethod
    def __hsv_threshold(input, hue, sat, val):
        """Segment an image based on hue, saturation, and value ranges.
        Args:
            input: A BGR numpy.ndarray.
            hue: A list of two numbers the are the min and max hue.
            sat: A list of two numbers the are the min and max saturation.
            lum: A list of two numbers the are the min and max value.
        Returns:
            A black and white numpy.ndarray.
        """
        out = cv2.cvtColor(input, cv2.COLOR_BGR2HSV)
        return cv2.inRange(out, (hue[0], sat[0], val[0]),  (hue[1], sat[1], val[1]))

    @staticmethod
    def __find_blobs(input, min_area, circularity, dark_blobs):
        """Detects groups of pixels in an image.
        Args:
            input: A numpy.ndarray.
            min_area: The minimum blob size to be found.
            circularity: The min and max circularity as a list of two numbers.
            dark_blobs: A boolean. If true looks for black. Otherwise it looks for white.
        Returns:
            A list of KeyPoint.
        """
        params = cv2.SimpleBlobDetector_Params()
        params.filterByColor = 1
        params.blobColor = (0 if dark_blobs else 255)
        params.minThreshold = 10
        params.maxThreshold = 220
        params.filterByArea = True
        params.minArea = min_area
        params.filterByCircularity = True
        params.minCircularity = circularity[0]
        params.maxCircularity = circularity[1]
        params.filterByConvexity = False
        params.filterByInertia = False
        detector = cv2.SimpleBlobDetector_create(params)
        return detector.detect(input)

BlurType = Enum('BlurType', 'Box_Blur Gaussian_Blur Median_Filter Bilateral_Filter')

#   JSON format:
#   {
#       "team": <team number>,
#       "ntmode": <"client" or "server", "client" if unspecified>
#       "cameras": [
#           {
#               "name": <camera name>
#               "path": <path, e.g. "/dev/video0">
#               "pixel format": <"MJPEG", "YUYV", etc>   // optional
#               "width": <video mode width>              // optional
#               "height": <video mode height>            // optional
#               "fps": <video mode fps>                  // optional
#               "brightness": <percentage brightness>    // optional
#               "white balance": <"auto", "hold", value> // optional
#               "exposure": <"auto", "hold", value>      // optional
#               "properties": [                          // optional
#                   {
#                       "name": <property name>
#                       "value": <property value>
#                   }
#               ],
#               "stream": {                              // optional
#                   "properties": [
#                       {
#                           "name": <stream property name>
#                           "value": <stream property value>
#                       }
#                   ]
#               }
#           }
#       ]
#   }

configFile = "/boot/frc.json"

class CameraConfig: pass

cvsink = None
team = None
server = False
cameraConfigs = []

"""Report parse error."""
def parseError(str):
    print("config error in '" + configFile + "': " + str, file=sys.stderr)

"""Read single camera configuration."""
def readCameraConfig(config):
    cam = CameraConfig()

    # name
    try:
        cam.name = config["name"]
    except KeyError:
        parseError("could not read camera name")
        return False

    # path
    try:
        cam.path = config["path"]
    except KeyError:
        parseError("camera '{}': could not read path".format(cam.name))
        return False

    # stream properties
    cam.streamConfig = config.get("stream")

    cam.config = config

    cameraConfigs.append(cam)
    return True

"""Read configuration file."""
def readConfig():
    global team
    global server

    # parse file
    try:
        with open(configFile, "rt") as f:
            j = json.load(f)
    except OSError as err:
        print("could not open '{}': {}".format(configFile, err), file=sys.stderr)
        return False

    # top level must be an object
    if not isinstance(j, dict):
        parseError("must be JSON object")
        return False

    # team number
    try:
        team = j["team"]
    except KeyError:
        parseError("could not read team number")
        return False

    # ntmode (optional)
    if "ntmode" in j:
        str = j["ntmode"]
        if str.lower() == "client":
            server = False
        elif str.lower() == "server":
            server = True
        else:
            parseError("could not understand ntmode value '{}'".format(str))

    # cameras
    try:
        cameras = j["cameras"]
    except KeyError:
        parseError("could not read cameras")
        return False
    for camera in cameras:
        if not readCameraConfig(camera):
            return False

    return True

"""Start running the camera."""
def startCamera(config):
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)

    global  cvsink
    cvsink = inst.getVideo()

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    return camera

if __name__ == "__main__":
    if len(sys.argv) >= 2:
        configFile = sys.argv[1]

    # read configuration
    if not readConfig():
        sys.exit(1)

    # start NetworkTables
    global ntinst
    ntinst = NetworkTablesInstance.getDefault()
    server = True
    if server:
        print("Setting up NetworkTables server")
        ntinst.startServer()
    else:
        print("Setting up NetworkTables client for team {}".format(team))
        ntinst.startClientTeam(team)

    # start cameras
    cameras = []
    for cameraConfig in cameraConfigs:
        cameras.append(startCamera(cameraConfig))

    # loop forever
    img = numpy.zeros(shape=(240, 320, 3), dtype=numpy.uint8)
    while True:
        _, img = cvsink.grabFrame(img)
        pipeline = GripPipeline()
        output = pipeline.process(img)
        if len(output):
            print (output[0].pt)
            ntinst.getGlobalTable().putNumber("blob", output[0].pt[0])
        # print("processed")


# -*- coding: utf-8 -*-
import os
imgpath = "/home/miku/imagedata/VisDrone2019-DET-train/images"
labelpath = "/home/miku/imagedata/VisDrone2019-DET-train/annotations"
filelist = os.listdir(imgpath) #该文件夹下所有的文件（包括文件夹）
filelab = os.listdir(labelpath) #该文件夹下所有的文件（包括文件夹）
count=1
imagetype = os.path.splitext(filelist[0])[1]
labeltype = os.path.splitext(filelab[0])[1]
for file in filelist:   #遍历所有文件
    filename = os.path.splitext(file)[0]
    Oldimgpath = os.path.join(imgpath+'/', filename+imagetype )   #原来的文件路径
    Oldlabpath = os.path.join(labelpath+'/', filename+labeltype)  # 原来的文件路径
    if os.path.isdir(Oldimgpath):   #如果是文件夹则跳过
        continue
    if os.path.isdir(Oldlabpath):   #如果是文件夹则跳过
        continue
    Newimgpath = os.path.join(imgpath+'/', str(count).zfill(6) + imagetype)  #用字符串函数zfill 以0补全所需位数
    Newlabpath = os.path.join(labelpath + '/', str(count).zfill(6) + labeltype)  # 用字符串函数zfill 以0补全所需位数
    os.rename(Oldimgpath, Newimgpath)#重命名
    os.rename(Oldlabpath, Newlabpath)  #重命名
    count += 1


"""
The Atbash cipher is a very specific case of a substitution cipher where the letters of the alphabet are reversed.
In otherwords, all As are replaced with Zs, all Bs are replaced with Ys, and so on.
Because reversing the alphabet twice will get you actual alphabet,
you can encipher and decipher a message using the exact same algorithm.
"""

standard = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
          "u", "v", "w", "x", "y", "z"]

reversed = ["z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g",
          "f", "e", "d", "c", "b", "a"]

mode = input("Enter 'e' to encode or 'd' to decode: ")
entry = input("Enter a character: ")

if mode == 'e':
    identifier = standard.index(entry)
    encoded = (reversed[identifier])
    print("The encoded letter is: ", encoded)

elif mode == 'd':
    identifier = reversed.index(entry)
    decoded = (standard[identifier])
    print("The decoded letter is: ", decoded)

else:
    print("Bad User entry!")