from numpy import *

def unique(s):
    n = len(s)
    if n == 0:
        return []
    u = {}
    try:
        for x in s:
            u[x] = 1
    except TypeError:
        del u  # move on to the next method
    else:
        return u.keys()
    try:
        t = list(s)
        t.sort()
    except TypeError:
        del t  # move on to the next method
    else:
        assert n > 0
        last = t[0]
        lasti = i = 1
        while i < n:
            if t[i] != last:
                t[lasti] = last = t[i]
                lasti += 1
            i += 1
        return t[:lasti]
    # Brute force is all that's left.
    u = []
    for x in s:
        if x not in u:
            u.append(x)
    return u

# ------------------------------------------------------------------------------
def AverageTIs_PDBHeader(sIn,sOut,HeaderList,iShift):
    # HeaderList = list with user PDB header fields in GUI

    # read the input file
    fIn=open(sIn,'r')
    lines=fIn.readlines()
    for i in range(len(lines)):
        OneLine=lines[i]
        if OneLine[-1]=="\n" : lines[i] = OneLine[:-1] # removing strange characters
        if OneLine[-1]=="\r" : lines[i] = OneLine[:-1]

    # take the header line
    FirstLine=lines[0]           # get the header

    # numbers of header items = columns
    c=len(FirstLine.split("\t"))
    l=len(lines) # no of lines in the input file FULL header info
    nFields=11 # max no of PDB header fields
    nIndices=c-iShift-nFields   # no of calculated indices
    nUserFields=len(HeaderList) # no of fields to be averaged

    # get the header as a list of [PDB],[fields],[indices labels]
    Headers=[]
    colFirstLine=FirstLine.split("\t")
    # get the PDBs
    temp=[]
    for s in range(iShift):temp.append(colFirstLine[s])
    Headers.append(temp)
    # get the fields
    temp=[]
    FieldPos=[]
    for f in range(nFields):
        for userH in HeaderList: # print only the user header
            if colFirstLine[iShift+f]==userH:
                temp.append(colFirstLine[iShift+f]) # get the value
                FieldPos.append(f) # get the position of the field in full fields
    Headers.append(temp)
    # get the indices
    temp=[]
    for n in range(nIndices):temp.append(colFirstLine[iShift+nFields+n])
    Headers.append(temp)

    # add the future calculations labels: Avgs and Diff
    temp=[]
    for h in range(len(HeaderList)): # for each user field
        IndLabels=Headers[2]
        for n in range(len(IndLabels)): # for each indice label
            temp.append("AvgBy"+HeaderList[h]+"["+IndLabels[n]+"]")
        for n in range(len(IndLabels)): # for each indice label
            temp.append("Diff_"+IndLabels[n]+"-AvgBy"+HeaderList[h])
    Headers.append(temp)

    # get the info in 3 lists: case name, fields, indices
    PDBs=[]     # list with PDBs (col 1)
    Fields=[]   # list with the fields (nFields cols)
    Indices=[]  # list with the indices (nIndices cols)

    # process each line in the file except the header
    for i in range(1,l):
        curRow=(lines[i]).split("\t") # take the values by columns
        # get the PDBs
        temp=[]
        for s in range(iShift):temp.append(curRow[s])
        PDBs.append(temp)
        # get the fields
        temp=[]
        for f in range(nFields):
            for fPos in range(len(FieldPos)): # verify the positions of the user fields in the list
                if f==int(FieldPos[fPos]):
                    temp.append(curRow[iShift+f])
        Fields.append(temp)
        # get the indices
        temp=[]
        for n in range(nIndices):temp.append(curRow[iShift+nFields+n])
        Indices.append(temp)

    # check all the user fields and take the unique values
    UniqueFields=[] # list with list of unique headers in the same order as in HeaderList
    Avgs_Diffs=[] # list with Averages and diffs Indice-Avg to be completed as [avgs1],[diffs1]..etc

    for h in range(len(HeaderList)): # for each user field
        # make unique lists
        HFields=Headers[1] # get only the header fields
        for f in range(len(HFields)): # check with all the list of fields
            if HeaderList[h]==HFields[f]:
                temp=[] # all values of one field
                for k in range(l-1): # l-1 = lines - header=cases
                    kFields=Fields[k]
                    temp.append(kFields[f]) # the fields has the same position in the header with the list of Fields
        uField=unique(temp) # unique list with one field
        #UniqueFields.append(uField) # list with list of unique values for eahc user field

        #print "uField=",uField
        # calculate the averages for each field value and indice
        Avg_Field=  zeros((len(uField),nIndices)) # avgs for a values in the current user field and an indice
        Count_Field= zeros((len(uField),nIndices))

        # take each line of data and compare with unique values of fields
        HFields=Headers[1] # get only the header fields
        for f in range(len(HFields)): # check with all the list of fields
            if HeaderList[h]==HFields[f]: # if user and Full header fields coincide
                for u in range(len(uField)): # for each unique values
                    for k in range(l-1): # l-1 = lines - header=cases
                        kFields=Fields[k]
                        if uField[u]==kFields[f]: # if data fields are the unique values
                            curIndices=Indices[k]
                            for n in range(len(curIndices)): # add all the indices
                                Avg_Field[u][n]+=float(curIndices[n])
                                Count_Field[u][n]+=float(1)
        # calc avgs
        for u in range(len(uField)):
            for n in range(nIndices):
                Avg_Field[u][n]=float(Avg_Field[u][n])/float(Count_Field[u][n])

        # create list Avgs to be added to Avgs_Diffs
        Avgs=[]
        Diffs=[]
        # take each line of data and compare with unique values of fields
        HFields=Headers[1] # get only the header fields
        for f in range(len(HFields)): # check with all the list of fields
            if HeaderList[h]==HFields[f]: # if user and Full header fields coincide

                for k in range(l-1): # l-1 = lines - header=cases
                    temp1=[]
                    temp2=[]
                    kFields=Fields[k]
                    for u in range(len(uField)): # for each unique values
                        if uField[u]==kFields[f]: # if data fields are the unique values
                            curIndices=Indices[k]
                            for n in range(len(curIndices)): # add all the indices
                                # print uField[u],curIndices[n],Avg_Field[u][n]
                                temp1.append(Avg_Field[u][n])
                                temp2.append(float(curIndices[n])-Avg_Field[u][n])

                    Avgs.append(temp1)
                    Diffs.append(temp2)

        Avgs_Diffs.append(Avgs) # add the first list with Avgs
        Avgs_Diffs.append(Diffs) # add the first list with Avgs

    # write the output:
    # Headers
    # PDBs, Fields, Indices, Avgs_Diffs

    fOut=open(sOut,"w")
    sOut=""

    # write Headers
    for item in Headers:
        for details in item:
            sOut+=details+"\t"
    fOut.write(sOut[:-1]+"\n")

    # write PDBs, Fields, Indices, Avgs_Diffs
    sOut=""
    for k in range(l-1): # for each case
        cPDBs=PDBs[k]
        for item in cPDBs:
            sOut+=item+"\t"
        cFields=Fields[k]
        for item in cFields:
            sOut+=item+"\t"
        cIndices=Indices[k]
        for item in cIndices:
            sOut+=item+"\t"
        for items in Avgs_Diffs:
            cAvgs_Diffs=items[k]
            for item in cAvgs_Diffs:
                sOut+=str(item)+"\t"

        sOut=sOut[:-1]+"\n"

    fOut.write(sOut)

    fIn.close()
    fOut.close()
    return

# ------------------------------------------------------------------------------
def AverageTIs_PDBHeader_old(sIn,sOut,HeaderList,flag_Header,iShift):
    # uses an output with PDBchain (1), heading from PDBs (17), TIs (90)
    # adds the averages values for each class in each type of header field
    # parameters: input file to modify, output file with the avgs by classes
    # list of the header items, matrix of flags for each header used
    # iShift = number of columns to skip

    iHeader=len(HeaderList)        # numbers of possible header items

    # read the input file
    fIn=open(sIn,'r')
    lines=fIn.readlines()
    for i in range(len(lines)):
        OneLine=lines[i]
        if OneLine[-1]=="\n" : lines[i] = OneLine[:-1] # removing strange characters
        if OneLine[-1]=="\r" : lines[i] = OneLine[:-1]

    l=len(lines)                 # no. of lines in the input file
    FirstLine=lines[0]           # get the header
    c=len(FirstLine.split("\t")) # numbers of header items = columns

    # verify the header choise and create the unique list of header idems = list of lists
    # list of list of headers (non-uniques)
    AllHeaders=[]

    # 11 empty lists for each header type
    HeaderItems=[]
    for Choise in range(iHeader):
        HeaderItems.append([])

    # get the user headers excluding the header line
    for i in range(1,l): # process each line in the file
        CurrR=(lines[i]).split("\t") # take the values by columns

        # check the choise of the user
        for h in range(iHeader): # verify each header flag
            if flag_Header[h]==1:
                # get the items of this header
                CurrHeader=HeaderItems[h] # take the list to be completed

                # PDBchain 11*[HeaderFiels] TIs
                CurrHeader.append(CurrR[h+1]) # get the item of a specific header
                HeaderItems[h]=CurrHeader # place back the list for the specific header

    # make unique lists of specific header lists
    for j in range(len(HeaderItems)):
        HeaderItems[j]=unique(HeaderItems[j])

    Avg_Header=  zeros((iHeader,len(HeaderItems),c-1-iHeader))  # matrix the avg values of each TI for each Header item
    countHeader= zeros((iHeader,len(HeaderItems),c-1-iHeader))  # matrix with counting for each item in a specific header

    # calculate the averages if found the header label
    for i in range(1,l): # process each line in the file
        CurrR=(lines[i]).split("\t") # take the values by columns
        # check the choise of the user
        for h in range(iHeader): # verify each header flag
            if flag_Header[h]==1:
                CurrH=HeaderItems[h] # get the list of unique items of a special header
                # print "CurrH=\n",CurrH
                # process each unique item of header
                for ii in range(len(CurrH)):
                    # print "CurrR[h+1],item=",CurrR[h+1],CurrH[ii]
                    # print CurrR
                    if CurrR[h+1]==CurrH[ii]: # if item found
                        for cc in range(c-iShift-iHeader): #for each TI column
                            Avg_Header[h][ii][cc]+=float(CurrR[cc+iHeader+1])
                            countHeader[h][ii][cc]+=1
    # print HeaderItems

    # create the avg values
    for h in range(iHeader): # verify each header flag
        if flag_Header[h]==1:
            CurrH=HeaderItems[h] # get the list of unique items of a special header
            # process each unique item of header
            for ii in range(len(CurrH)):
                for cc in range(c-iShift-iHeader): #for each TI column
                    if countHeader[h][ii][cc]!=0:
                        Avg_Header[h][ii][cc]=float(Avg_Header[h][ii][cc])/float(countHeader[h][ii][cc])

    # write the output file by adding to the header result the columns with the averages
    fOut=open(sOut,"w")
    sOut=""

    for iL in range(l):          # for each old line
        oldLine=lines[iL]        # older header
        lines[iL]=oldLine[:-1]   # remove the end of line
        sOut+=lines[iL]
        CurrR=(lines[iL]).split("\t") # take the values by columns

        # if header, we are completing with the new header
        if iL==0:
            for h in range(iHeader):  # verify each header flag
                if flag_Header[h]==1: # only if header is used
                    for cc in range(c-iShift-iHeader): #for each TI column
                        sOut+="\t"+"AvgBy["+HeaderList[h]+"]for["+CurrR[cc+iHeader+iShift]+"]" # add the new header avgs
            #fOut.write(sOut+"\n")

            # add Diffs TIs - Avgs
            for h in range(iHeader):  # verify each header flag
                if flag_Header[h]==1: # only if header is used
                    for cc in range(c-iShift-iHeader): #for each TI column
                        sOut+="\t"+"Diff["+CurrR[cc+iHeader+iShift]+"]-[AvgBy"+HeaderList[h]+"]" # add the new header avgs
            fOut.write(sOut+"\n")

        else: # the TIs lines
            sOut=""
            sOut+=lines[iL]
            for h in range(iHeader): # verify each header flag
                if flag_Header[h]==1:
                    CurrH=HeaderItems[h] # get the list of unique items of a special header
                    # process each unique item of header
                    for ii in range(len(CurrH)):
                        if CurrR[h+1]==CurrH[ii]: # if item found
                            for cc in range(c-iShift-iHeader): #for each TI column
                                sOut+="\t"+str(Avg_Header[h][ii][cc]) # add the new avg of TIs

                    # add differences TIs - Avgs
                    for ii in range(len(CurrH)):
                        if CurrR[h+1]==CurrH[ii]: # if item found
                            for cc in range(c-iShift-iHeader): #for each TI column
                                sOut+="\t"+str(float(CurrR[cc+iHeader+1])-Avg_Header[h][ii][cc]) # add the new avg of TIs

            fOut.write(sOut+"\n")

    fOut.close()
    fIn.close()
    return

# --------------------------------------------------------------------------
# averaged by input file
# ---------------------------------------------------------------------------------------------------------------
def GetInputClass(sInFile,Col):
    # list with the unique classes
    ClassList=[]

    fIn=open(sInFile,"r") #open file to read
    lines=fIn.readlines()

    l=len(lines)                 # no. of lines in the input file
    FirstLine=lines[0]           # get the header
    c=len(FirstLine.split("\t")) # numbers of header items = columns
    # only if there are more columns
    if c>=Col:
        for i in range(l): # process each line in the file
            CurrL=lines[i] # current line
            if CurrL[-1]=="\n" : CurrL = CurrL[:-1] # removing strange characters
            if CurrL[-1]=="\r" : CurrL = CurrL[:-1]
            CurrR=(CurrL).split("\t")  # split each line by columns tab separated
            ClassList.append(CurrR[Col-1]) # add to the non-unique list a specific value for the column Col

    return unique(ClassList) # return the unique classes from the input

# ---------------------------------------------------------------------------------------------------------------
def AverageTIs4Col(sIn,sOut,Classes,Col):
    # transform sIn file in sOut file using the Classes list with unique classes
    # Col = class columns in the input file

    iClasses=len(Classes) # numbers of possible class items

    # read the input file
    fIn=open(sIn,'r')
    lines=fIn.readlines()
    for line in lines:
        if line[-1]=="\n" : line = line[:-1] # removing strange characters
        if line[-1]=="\r" : line = line[:-1]

    l=len(lines)                 # no. of lines in the input file
    FirstLine=lines[0]           # get the header
    c=len(FirstLine.split("\t")) # numbers of header items = columns

    # make unique lists of specific header lists HeaderItems

    Avg_Header=  zeros((iClasses,c-Col))  # matrix the avg values of each TI for each classs
    countHeader= zeros((iClasses,c-Col))  # matrix with counting

    # calculate the averages if found the header label
    for i in range(1,l): # process each line in the file
        CurrR=(lines[i]).split("\t") # take the values by columns
        # process each unique class
        for h in range(iClasses): # verify each class
            CurrH=Classes[h] # get the list of unique class

            if CurrR[Col-1]==CurrH: # if item found
                for cc in range(c-Col): #for each TI column
                    Avg_Header[h][cc]+=float(CurrR[cc+Col])
                    countHeader[h][cc]+=1
                    continue

    # create the avg values
    for h in range(iClasses): # verify each header flag
        CurrH=Classes[h] # get the list of unique items of a special header
        # process each unique item of header
        for cc in range(c-Col-iClasses): #for each TI column
            if countHeader[h][cc]!=0:
                Avg_Header[h][cc]=float(Avg_Header[h][cc])/float(countHeader[h][cc])

    # write the output file by adding to the header result the columns with the averages
    fOut=open(sOut,"w")
    sOut=""

    for iL in range(l):          # for each old line
        oldLine=lines[iL]        # older header
        lines[iL]=oldLine[:-1]   # remove the end of line
        sOut+=lines[iL]
        CurrR=(lines[iL]).split("\t") # take the values by columns

        # if header, we are completing with the new header
        if iL==0:
            for cc in range(c-Col): #for each TI column
                sOut+="\t"+"Avg"+CurrR[cc+Col] # add the new header avgs

            # add Diffs: TI-Avg
            for cc in range(c-Col): #for each TI column
                sOut+="\t"+"Diff["+CurrR[cc+Col]+"]-[Avg]" # add the new header avgs
            fOut.write(sOut+"\n")

        else: # the TIs lines
            sOut=""
            sOut+=lines[iL]
            for h in range(iClasses): # verify each header flag
                CurrH=Classes[h] # get the list of unique items of a special header
                # process each unique class
                if CurrR[Col-1]==CurrH: # if item found
                    for cc in range(c-Col): #for each TI column
                        sOut+="\t"+str(Avg_Header[h][cc]) # add the new avg of TIs

                    # add Diffs values
                    for cc in range(c-Col): #for each TI column
                        sOut+="\t"+str(float(CurrR[cc+Col])-Avg_Header[h][cc]) # add the new avg of TIs

            fOut.write(sOut+"\n")

    fOut.close()
    fIn.close()
    return

# ---------------------------------------------------------------------------------------------------------------
def DrugAverageTIs4Col(sIn,sOut,Classes,Col):
    # transform sIn file in sOut file using the Classes list with unique classes
    # Col = class columns in the input file

    iClasses=len(Classes) # numbers of possible class items

    # read the input file
    fIn=open(sIn,'r')
    lines=fIn.readlines()

    for line in lines:
        if line[-1]=="\n" : line = line[:-1] # removing strange characters
        if line[-1]=="\r" : line = line[:-1]

    l=len(lines)                 # no. of lines in the input file
    FirstLine=lines[0]           # get the header
    c=len(FirstLine.split("\t")) # numbers of header items = columns

    # make unique lists of specific header lists HeaderItems

    Avg_Header=  zeros((iClasses,c-Col))  # matrix the avg values of each TI for each classs
    countHeader= zeros((iClasses,c-Col))  # matrix with counting

    # calculate the averages if found the header label
    for i in range(1,l): # process each line in the file
        CurrLine=lines[i]
        if CurrLine[-1]=="\n" : CurrLine = CurrLine[:-1] # removing strange characters
        if CurrLine[-1]=="\r" : CurrLine = CurrLine[:-1]
        CurrR=CurrLine.split("\t") # take the values by columns

        # process each unique class
        for h in range(iClasses): # verify each class
            CurrH=Classes[h] # get the list of unique class

            if CurrR[Col-1]==CurrH: # if item found
                for cc in range(c-Col): #for each TI column
                    Avg_Header[h][cc]+=float(CurrR[cc+Col])
                    countHeader[h][cc]+=1
                    continue

    # create the avg values
    for h in range(iClasses): # verify each header flag
        CurrH=Classes[h] # get the list of unique items of a special header
        # process each unique item of header
        for cc in range(c-Col-iClasses): #for each TI column
            if countHeader[h][cc]!=0:
                Avg_Header[h][cc]=float(Avg_Header[h][cc])/float(countHeader[h][cc])

    # write the output file by adding to the header result the columns with the averages
    fOut=open(sOut,"w")
    sOut=""

    for iL in range(l):          # for each old line
        oldLine=lines[iL]        # older header
        lines[iL]=oldLine[:-1]   # remove the end of line
        sOut+=lines[iL]
        CurrR=(lines[iL]).split("\t") # take the values by columns

        # if header, we are completing with the new header
        if iL==0:
            for cc in range(c-Col): #for each TI column
                sOut+="\t"+"Avg"+CurrR[cc+Col] # add the new header avgs

            # add Diffs: TI-Avg
            for cc in range(c-Col): #for each TI column
                sOut+="\t"+"Diff["+CurrR[cc+Col]+"]-[Avg]" # add the new header avgs
            fOut.write(sOut+"\n")

        else: # the TIs lines
            sOut=""
            sOut+=lines[iL]
            for h in range(iClasses): # verify each header flag
                CurrH=Classes[h] # get the list of unique items of a special header
                # process each unique class
                if CurrR[Col-1]==CurrH: # if item found
                    for cc in range(c-Col): #for each TI column
                        sOut+="\t"+str(Avg_Header[h][cc]) # add the new avg of TIs

                    # add Diffs values
                    for cc in range(c-Col): #for each TI column
                        sOut+="\t"+str(float(CurrR[cc+Col])-Avg_Header[h][cc]) # add the new avg of TIs

            fOut.write(sOut+"\n")

    fOut.close()
    fIn.close()
    return

############################################################
### main
############################################################
##
##sIn="PROT_SimpleRes.txt"
##sOut="AvgByInput.txt"
##
##sActiv="PDBlist.txt"
##Col=2 # column in the input file of the class (PDBchain\tClass)
##Classes=[]
##Classes=GetInputClass(sActiv,Col)
##
##print Classes
##
##AverageTIs4Col(sIn,sOut,Classes,Col)

##########################################################
# main
##########################################################

##sIn="MI-ProtResults_Header.txt"
##sOut="MI-ProtResults_Header_Avgs.txt"
##
##HeaderList=['head','expression_system','expression_system_taxid','name','chain','organism_scientific','molecule','expression_system_vector_type','ec','organism_common','expression_system_plasmid','engineered','expression_system_strain','cell_line','cellular_location','gene','organism_taxid']
##flag_Header= zeros((len(HeaderList)))  # matrix with flags for each header type, default=0
##
### virtual choise from the interface
##flag_Header[0]=1
##flag_Header[6]=1
##
##AverageTIs_PDBHeader(sIn,sOut,HeaderList,flag_Header)


from copy import deepcopy
import torch
from torch.utils.data import DataLoader
import torch.nn as nn

class EWC:
    def __init__(
        self, net: nn.Module, dataloader: DataLoader, device, num_tasks, criterion, permutator):
        self.permutator = permutator
        self.net = net
        self.dataloader = dataloader
        self.best_params = [None for _ in range(num_tasks)]
        self.fisher_matrices = [
            {
                n: torch.zeros_like(p.data)
                for n, p in self.net.named_parameters()
                if p.requires_grad
            }
            for _ in range(num_tasks)
        ]
        self.device = device
        self.criterion = criterion

    def update_fisher(self, task_id):
        for batch in self.dataloader:
            self.net.zero_grad()
            X, y = self.permutator.permute_batch(batch, task_id)
            X, y = X.to(self.device), y.to(self.device)
            logits = self.net(X)
            loss = self.criterion(logits, y)
            loss.backward()
            for n, p in self.net.named_parameters():
                self.fisher_matrices[task_id][n] += p.grad ** 2

        for n, p in self.net.named_parameters():
            self.fisher_matrices[task_id][n] /= len(self.dataloader)

    def save_params(self, task_id):
        self.best_params[task_id] = {
            n: deepcopy(p.data)
            for n, p in self.net.named_parameters()
            if p.requires_grad
        }


import sys

def find_parent(parents, x):
    if parents[x] != x:
        parents[x] = find_parent(parents, parents[x])
    return parents[x]

def union(parents, a, b):
    a = find_parent(parents, a)
    b = find_parent(parents, b)

    if a < b:
        parents[b] = a
    else:
        parents[a] = b

while True:
    m, n = map(int, sys.stdin.readline().split())
    if m == 0 and n == 0:
        break
    arr = []

    for _ in range(n):
        a, b, c = map(int, sys.stdin.readline().split())
        arr.append((c, a, b))
    arr.sort()
    parent = [i for i in range(m)]
    total = 0

    for tmp in arr:
        z, x, y = tmp
        if find_parent(parent, x) != find_parent(parent, y):
            union(parent, x, y)
        else:
            total += z

    print(total)


import numpy as np
import matplotlib.pyplot as plt

def display_map(map_path):
    map = np.zeros([7,30,3])+5
    with open(map_path) as file:
        for y, line in enumerate(file.readlines()):
            for x, c in enumerate(line):
                if c == 'o':
                    map[y,x] =[0.5,0.5,0.5]#obstacle
                if c == 'g':
                    map[y,x] =[0,0,1]#randomizers.append([x, y])
                if c == 'd':
                    map[y,x] =[0,0,0]#dangers.append([x, y])
                if c == 'r':
                    map[y,x] =[0,0,1]#subgoal = [x, y]
                if c == 'G':
                    map[y,x] =[0,1,0]
                if c == 'a':
                    map[y,x] =[1,1,0]
    return map

if __name__ == "__main__":

    m = display_map('../flaskr/maps/level_3/map0.txt')
    print(m)
    plt.axes().set_aspect('equal')
    plt.imshow(m)
    plt.show()


from datetime import datetime

DATE_MAP = ('s', 'mns', 'Hrs', 'Days', 'Months', 'Years')

def get_time() -> str:
    dt = datetime(2022, 10, 1, 0, 0, 0)
    delta = dt - datetime.now()
    cleaned_delta = str(delta).replace(' days, ', ':')
    deltas = cleaned_delta.split('.')[0].split(':')
    x = len(deltas)
    stmts = []
    for i in range(x):
        ind = x - 1 - i
        stmt = deltas[i] + DATE_MAP[ind]
        stmts.append(stmt)
    return ' '.join(stmts)


#!/usr/bin/env python

# ---------------------------------------------------------------
#                           Imports
# ---------------------------------------------------------------

# General Imports
from typeguard import check_argument_types

# Utils Imports
from .utils import exception_handler

# Local package imports
from ..models.dynamodb import Dynamo

# Logging Imports
import logging

# ---------------------------------------------------------------
#                       Globals
# ---------------------------------------------------------------

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------
#                       User Manager
# ---------------------------------------------------------------

class UserManager:
    """
    Class to programatically manage users on the Thea manager app

    Attributes
    ----------
        _db:
            DynamoDB object instance

    Methods
    -------
        get_unique_user(organization_id, user_id)

        get_user_overview(organization_id, last_evaluated_key)
    """

    def __init__(self) -> None:
        self._db = Dynamo()

    @exception_handler
    def get_unique_user(self, organization_id: str, email: str):
        """
        Get unique user's details

        Parameters:
        -----------
            organization_id: str [required]
                unique organization ID user belongs to

            email: str [required]
                unique user ID

        Returns:
        --------
            response: list | str
                unique user details
        """

        # Type guarding
        assert check_argument_types()

        # Query key
        key = {"email": email, "orgId": organization_id}

        # Projection expression
        projection_expression = ", ".join(
            ["userId", "orgId", "name", "email", "username", "userType"]
        )

        # Query DynamoDB request
        logger.info(f"Checking if user ID or organization ID exists: {key}")

        # Return server response
        return self._db.read_single_item("users", key, projection_expression)

    @exception_handler
    def get_user_overview(self, organization_id: str, last_evaluated_key: str = None):
        """
        Get overview of users

        Parameters:
        -----------
            organization_id: str [required]
                unique organization ID user belongs to

            last_evaluated_key: str [optional]
                in case of pagination, last evaluate key is the starting point to the next page

        Returns:
        --------
            response: str | dict
                dict object containing project information

            http_status_code: int
                http server status response code
        """

        # Type guarding
        assert check_argument_types()

        key = {"index_name": "orgId", "index_val": organization_id}

        # Define project expression to get specific keys in data
        projection_expression = ", ".join(
            ["userId", "email", "userType", "username", "#name", "orgId"]
        )

        expression_attribute_names = {"#name": "name"}

        # Get Data
        logger.info("Querying users overview from DynamoDB")
        return self._db.read_multiple_items(
            f"users-{organization_id}",
            key,
            projection_expression,
            expression_attribute_names,
        )


# movie class
class movie:

    # class constructor
    def __init__(self, title, year, synopsis='', poster_image_url='', trailer_youtube_url=''):

        # movie title
        self.title = title

        # year of release
        self.year = year

        # synopsis
        self.synopsis = synopsis

        # url for box art
        self.poster_image_url = poster_image_url

        # url for youtube trailer
        self.trailer_youtube_url = trailer_youtube_url


from typing import List

class Solution:
    def rob(self, nums: List[int]) -> int:
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        return max(self.rob_range(nums[1:]), self.rob_range(nums[: len(nums) - 1]))

    def rob_range(self, nums: List[int]) -> int:
        cur = 0
        pre = 0
        for i in range(len(nums) - 1, -1, -1):
            temp = cur
            cur = max(cur, pre + nums[i])
            pre = temp

        return cur


from attrdict import AttrDict
from flask import jsonify, request
from voluptuous import Schema, REMOVE_EXTRA

from blockcerts.const import ISSUER_SCHEMA, TEMPLATE_SCHEMA, RECIPIENT_SCHEMA, JOB_SCHEMA
from blockcerts.misc import issue_certificate_batch, get_tx_receipt, verify_cert
from flaskapp.config import get_config

def setup_routes(app):
    @app.route('/ping')
    def ping_route():
        return jsonify({'reply': 'pong'})

    @app.route('/issue', methods=['POST'])
    def issue_certs():
        issuing_job_schema = Schema(
            {
                'issuer': ISSUER_SCHEMA,
                'template': TEMPLATE_SCHEMA,
                'recipients': RECIPIENT_SCHEMA,
                'job': JOB_SCHEMA,
            },
            required=True,
            extra=REMOVE_EXTRA,
        )
        payload = issuing_job_schema(request.get_json())
        tx_id, signed_certs = issue_certificate_batch(
            AttrDict(payload['issuer']),
            AttrDict(payload['template']),
            [AttrDict(rec) for rec in payload['recipients']],
            AttrDict(payload['job']),
        )
        return jsonify(dict(
            tx_id=tx_id,
            signed_certificates=list(signed_certs.values())
        ))

    @app.route('/config', methods=['GET'])
    def public_config():
        config = get_config()
        return jsonify(
            dict(
                ETH_PUBLIC_KEY=config.get('ETH_PUBLIC_KEY'),
                ETH_KEY_CREATED_AT=config.get('ETH_KEY_CREATED_AT'),
            )
        )

    @app.route('/tx/<chain>/<tx_id>', methods=['GET'])
    def tx_receipt(chain, tx_id):
        receipt = get_tx_receipt(chain, tx_id)
        if receipt:
            return jsonify(dict(receipt)), 200
        return f"Tx '{tx_id}' not found in chain '{chain}'.", 404

    @app.route('/verify', methods=['POST'])
    def verify():
        payload = request.get_json()
        results = verify_cert(payload)
        return jsonify(dict(
            verified=results[0],
            steps=results[1]
        ))


"""
-*- coding: utf-8 -*-
Created: peyang, 2018-01-30 14:10:06

Last Modified by: ouxiaogu

MathUtil: python math utility functions
"""

import math
import numpy as np

def sigmoid(I, thres, sigmoidK):
    '''sigmoid function: smaller sigmoidK, faster transition'''
    assert(sigmoidK>0)
    res = 1./ (1 + math.exp(-(I - thres)/sigmoidK))
    return res

def rectFunc(w, slices=None, extend=1):
    '''1D rect window function: w is width, height is 1/w, symmetric'''
    assert(w > 0)
    if(slices is None):
        slices = 4
    else:
        slices = max(4, int(slices))
    if slices % 2 != 0:
        slices += 1
    extend = max(1, int(extend) )
    X = np.linspace( -(1 + extend)*w/2., (1 + extend)*w/2., (1+extend)*slices + 1)
    Y = [1./w if x <= w/2. and x >= -w/2. else 0 for x in X]
    return zip(X, Y)

def sinc(x):
    ''' `\sin(\pi x)/(\pi x)` np has sinc function'''
    X = np.asarray(x)
    Y = np.array([math.sin(math.pi * x)/(math.pi * x) if x != 0 else 1 for x in X]  )
    return Y

if __name__ == '__main__':
    '''test 1, sigmoid'''
    print("\ntest 1, sigmoid\n")
    hlfSz = 5
    I = [i/float(hlfSz) for i in range(-hlfSz, hlfSz+1)]
    thres = 0.2
    sigmoidK=0.2
    I = [sigmoid(i, thres, sigmoidK) for i in I]
    print(I)

    '''test 2, rectFunc'''
    print("\ntest 2, rectFunc\n")
    x, y = zip(*rectFunc(2, 10, 1))
    print(x)
    print(y)

    '''test 3, sinc'''
    print("\ntest 3, sinc:\n")
    x = np.linspace(-5, 5, 21)
    print(x)
    print(sinc(x) )


import re
import sys
a = []
str = sys.stdin.readline().strip()
while str != "":
    a.append(str)
    str = sys.stdin.readline().strip()
try:
    for s in a:
        # a = re.findall(r'(.{3,}).*\1', s) #匹配字符串中是否存在长度为3的子串
        b1 = re.findall(r'\d', s)  #数字
        b2 = re.findall(r'[A-Z]', s) #大写字母
        b3 = re.findall(r'[a-z]', s) #小写字母
        b4 = re.findall(r'[^0-9A-Za-z]', s)
        # print('OK') if ([b1, b2, b3, b4].count([]) <= 1 and a == [] and len(s) > 8) else print('NG')
        if [b1, b2, b3, b4].count([]) <= 1 and len(s) > 8:
            res = 0
            for j in range(len(s) - 3):
                for k in range(j + 3, len(s) - 3):
                    if s[j] == s[k] and s[j + 1] == s[k + 1] and s[k + 2] == s[k + 2]:
                        res = 1
            if res:
                print("NG")
            else:
                print("OK")
        else:
            print('NG')
except:
    pass


# -*- coding: utf-8 -*-
import re

from ..link_extractor import LinkExtractor
from ..mozie_request import Request

from . import cors

def get_link(url, media):
    req = Request()
    response = req.get(url)

    match = re.search(r'''
(.*?)
''', response)
    if match:
        url = LinkExtractor.iframe(match.group(1))
        response = req.get(url, headers={
            'referer': 'https://thuckhuya.com'
        })

    match = re.search(r'''var urlStream = "(.*?)"''', response)
    if match:
        url = match.group(1)

    return cors.get_link(url, media)


import collections
import functools
import logging
import sys

logging.basicConfig(
    filename = 'NumberGuessingLog.out',
    filemode ='w',
    level = logging.DEBUG,
    format = '%(asctime)s - %(levelname)s: %(message)s',
    datefmt = '%Y-%m-%d %I:%M:%S',
    )

class NumberGuessing: # 2018.P.1
    def __init__(self):
        logging.info('Number Guessing')

    class Solver:
        def __init__(self, lower_bound, upper_bound, max_tries):
            self.lower_bound = lower_bound
            self.upper_bound = upper_bound
            self.max_tries = max_tries
            self.tries = 0
            self.queries = {}

        def guess(self, num: int) -> str:
            self.tries += 1
            print(num)
            sys.stdout.flush()
            result = input()
            return result

        def solve(self):
            left = self.lower_bound
            right = self.upper_bound
            while left <= right:
                num = left + (right - left) // 2
                response = self.guess(num)
                if response == 'CORRECT':
                    logging.info(f'The secret number was {num}!')
                    return
                elif response == 'TOO_SMALL':
                    left = num + 1
                elif response == 'TOO_BIG':
                    right = num - 1
                else:
                    logging.error(f'ERROR! Response from judge indicates a problem: {response}')
                    exit()

    def main(self):
        T = int(input())
        for _ in range(T):
            lower_bound, upper_bound = tuple(map(int, input().split(' ')))
            max_tries = int(input())
            solver = self.Solver(lower_bound, upper_bound, max_tries)
            solver.solve()

if __name__ == '__main__':
    # python InteractiveRunner.py python NumberGuessingJudge.py 0 -- python NumberGuessingSolver.py
    solver = NumberGuessing()
    solver.main()


import matplotlib.pyplot as plt
import scipy.interpolate as interp
import numpy as np
import decimal as d

d.getcontext().prec = 3

thein = [0.0, 0.04, 0.08, 0.16, 0.50]
theout = [0.002, 0.032, 0.063, 0.13, 0.42]
thecout = [0.013, 0.010, 0.014, 0.013, 0.0066]
thex1out = [-0.65, -0.64, -0.65, -0.62, -0.60]

them, theb = np.polyfit(thein, theout, 1)
trueoffset = (0.08 - theb) / them
offdec = d.Decimal((0.08 - theb) / them) + d.Decimal(0)
print('slope:', them, '  y-intercept:', theb)
print('True offset value:', trueoffset)

plt.plot(np.linspace(-0.1, 0.6, 5), np.linspace(-0.1, 0.6, 5) * them + theb, '--', color='black', label='Best Fit')
plt.scatter(thein, theout, color='blue', s=60, marker='D', alpha=0.5, label='Sim')
plt.scatter(trueoffset, trueoffset * them + theb, color='green', marker='v', s=80, alpha=0.6, label='8%')
plt.annotate(str(offdec), xy=(trueoffset, trueoffset * them + theb),
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0", alpha=0.9),
             xycoords='data', xytext=(trueoffset, trueoffset * them + theb + 0.1))
plt.xlabel('Input Mass Step')
plt.ylabel('Output Mass Step')
plt.xlim(-0.01, 0.6)
plt.ylim(-0.01, 0.6)
plt.legend(loc=2)
plt.show()

plt.plot(thein, thecout, color='red')
plt.scatter(thein, thecout, color='blue', s=60, marker='D')
plt.xlabel('Input Mass Step')
plt.ylabel('Output Color Step')
plt.xlim(-0.01, 0.6)
plt.ylim(-0.1, 0.1)
plt.show()

plt.plot(thein, thex1out, color='red')
plt.scatter(thein, thex1out, color='blue', s=60, marker='D')
plt.xlabel('Input Mass Step')
plt.ylabel('Output Stretch Step')
plt.xlim(-0.01, 0.6)
plt.ylim(-1, 0)
plt.show()


from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import MusicViewSet, AlbumViewSet, ArtistViewSet, AlbumItemViewSet

router = DefaultRouter()
router.register('music', MusicViewSet)
router.register('album', AlbumViewSet)
router.register('albumitem', AlbumItemViewSet)
router.register('artist', ArtistViewSet)

urlpatterns = [
    path('', include(router.urls))
]


import time
import smbus

from . Relay import Relay

class RelayBoard:
    def __init__(self, device_address=0x10, device_bus=1):
        self.device_address = device_address
        self.device_bus = device_bus

        self.bus = smbus.SMBus(self.device_bus)
        self.relay_list = list()
        for i in range(1, 5):
            self.relay_list.append(Relay(i))

    def toggle(self, relay_number):
        state = self.relay_list[relay_number].state
        if state:
            self.bus.write_byte_data(self.device_address, relay_number, 0x00)
        else:
            self.bus.write_byte_data(self.device_address, relay_number, 0xFF)

    def turn_on(self, relay_id):
        if isinstance(relay_id, Relay):
            relay_id = relay_id.relay_number

        self.bus.write_byte_data(self.device_address, relay_id, 0xFF)
        self.relay_list[relay_id - 1].state = 1

    def turn_off(self, relay_id):
        if isinstance(relay_id, Relay):
            relay_id = relay_id.relay_number

        self.bus.write_byte_data(self.device_address, relay_id, 0x00)
        self.relay_list[relay_id - 1].state = 0

    def get_state(self, relay_number=None):
        if relay_number:
            return self.relay_list[relay_number].state
        else:
            return list(map(lambda a: a.state, self.relay_list))

    def set_state(self, state, relay_number=None):
        """
        sets the state of the relay to either on(1) or off(0)
        :param state: either 1 for one or 0 for off
        :param relay_number: the identifier of the relay (1, 2, 3, 4)
        :return: Nothing
        """

        if isinstance(state, list):
            for i in range(1, 5):
                self.set_state(state[i-1], i)
            return

        if isinstance(state, str):
            state = state.lower()

        if state not in [1, 0, 'on', 'off']:
            raise ValueError('The value of state must be one of (1, 0, on, off)')
        if state in [1, 'on']:
            self.turn_on(relay_number)
        elif state in [0, 'off']:
            self.turn_off(relay_number)


"""Emulated Posit arithmetic.
"""

from ..titanic import gmpmath
from ..titanic import digital

from ..titanic.integral import bitmask
from ..titanic.ops import RM, OP
from .evalctx import PositCtx
from . import interpreter
from . import posit

class SinkingPosit(digital.Digital):

    _ctx : PositCtx = posit.posit_ctx(4, 64)

    @property
    def ctx(self):
        """The rounding context used to compute this value.
        If a computation takes place between two values, then
        it will either use a provided context (which will be recorded
        on the result) or the more precise of the parent contexts
        if none is provided. For posits, a context is more "precise"
        if it has greater nbits, or greater es if nbits is the same.
        """
        return self._ctx

    def is_identical_to(self, other):
        if isinstance(other, type(self)):
            return super().is_identical_to(other) and self.ctx.es == other.ctx.es and self.ctx.nbits == other.ctx.nbits
        else:
            return super().is_identical_to(other)

    def __init__(self, x=None, ctx=None, **kwargs):
        if ctx is None:
            ctx = type(self)._ctx

        if x is None or isinstance(x, digital.Digital):
            super().__init__(x=x, **kwargs)
        else:
            f = gmpmath.mpfr(x, ctx.p)
            unrounded = gmpmath.mpfr_to_digital(f)
            super().__init__(x=self._round_to_context(unrounded, ctx=ctx, strict=True), **kwargs)

        self._ctx = posit.posit_ctx(ctx.es, ctx.nbits)

    def __repr__(self):
        return '{}(negative={}, c={}, exp={}, inexact={}, rc={}, isinf={}, isnan={}, ctx={})'.format(
            type(self).__name__, repr(self._negative), repr(self._c), repr(self._exp),
            repr(self._inexact), repr(self._rc), repr(self._isinf), repr(self._isnan), repr(self._ctx)
        )

    def __str__(self):
        if self.isnan or self.isinf:
            return 'nar'

        elif self.inexact:
            d1, d2 = gmpmath.digital_to_dec_range(self)
            fstr = gmpmath.dec_range_to_str(d1, d2, scientific=False)
            estr = gmpmath.dec_range_to_str(d1, d2, scientific=True)
        else:
            d = gmpmath.Dec(self)
            fstr = d.string
            estr = d.estring

        if len(fstr) <= 16:
            return fstr
        elif len(fstr) <= len(estr):
            return fstr
        else:
            return estr

    def __float__(self):
        return float(gmpmath.digital_to_mpfr(self))

    @classmethod
    def _select_context(cls, *args, ctx=None):
        if ctx is not None:
            return posit.posit_ctx(ctx.es, ctx.nbits)
        else:
            nbits = max((f.ctx.nbits for f in args if isinstance(f, cls)))
            es = max((f.ctx.es for f in args if isinstance(f, cls) and f.ctx.nbits == nbits))
            return posit.posit_ctx(es, nbits)

    @classmethod
    def _round_to_context(cls, unrounded, max_p=None, min_n=None, inexact=None, ctx=None, strict=False):
        if ctx is None:
            if isinstance(unrounded, cls):
                ctx = unrounded.ctx
            else:
                raise ValueError('no context specified to round {}'.format(repr(unrounded)))

        if unrounded.isinf or unrounded.isnan:
            # all non-real values go to the single posit infinite value
            return cls(isnan=True, ctx=ctx)

        else:
            regime, e = divmod(unrounded.e, ctx.u)
            if regime < 0:
                rbits = -regime + 1
            else:
                rbits = regime + 2

            sbits = ctx.nbits - 1 - rbits - ctx.es

            # regime = max(abs(unrounded.e) - 1, 0) // ctx.u
            # sbits = ctx.nbits - 3 - ctx.es - regime

            if sbits < -ctx.es:
                # we are outside the representable range: return max / min
                if unrounded.e < 0:
                    rounded = digital.Digital(negative=unrounded.negative, c=1, exp=ctx.emin, inexact=True, rc=-1)
                else:
                    rounded = digital.Digital(negative=unrounded.negative, c=1, exp=ctx.emax, inexact=True, rc=1)

            elif sbits < 0:
                # round -sbits bits off of the exponent, because they won't fit
                offset = -sbits

                lost_bits = unrounded.e & bitmask(offset)
                # note these left bits might be negative
                left_bits = unrounded.e >> offset

                if offset > 0:
                    offset_m1 = offset - 1
                    low_bits = lost_bits & bitmask(offset_m1)
                    half_bit = lost_bits >> offset_m1
                else:
                    low_bits = 0
                    half_bit = 0

                lost_sig_bits = unrounded.c & bitmask(unrounded.c.bit_length() - 1)

                new_exp = left_bits
                if lost_bits > 0 or lost_sig_bits > 0 or unrounded.rc > 0:
                    rc = 1
                    exp_inexact = True
                else:
                    rc = unrounded.rc
                    exp_inexact = unrounded.inexact

                #print('->\t', new_exp, rc, exp_inexact)

                # We want to round on the geometric mean of the two numbers,
                # but this is the same as rounding on the arithmetic mean of
                # the exponents.

                if half_bit > 0:
                    if low_bits > 0 or lost_sig_bits > 0 or unrounded.rc > 0:
                        # round the exponent up; remember it might be negative, but that's ok
                        #print('UP')
                        new_exp += 1
                        rc = -1
                    elif unrounded.rc < 0:
                        # tie broken the other way
                        #print('RC DOWN')
                        pass
                    else:
                        # "round nearest, ties to arbitrary"
                        #print('TIE')

                        # just generate the bits and see if that's even
                        tmp_exp = new_exp << offset
                        rounded = digital.Digital(negative=unrounded.negative, c=1, exp=tmp_exp, inexact=exp_inexact, rc=rc)
                        bits = posit.digital_to_bits(rounded, ctx)
                        if bits & 1:
                            new_exp += 1
                            rc = -1

                new_exp <<= offset
                rounded = digital.Digital(negative=unrounded.negative, c=1, exp=new_exp, inexact=exp_inexact, rc=rc)

            elif sbits == 0:
                #print('special round')
                # round "normally", but with the weird behavior for ties
                rounded = unrounded.round_m(max_p=sbits + 1, min_n=None, rm=RM.RNE, strict=strict)

                # this is always rounding to one bit
                if unrounded.c == 0:
                    left_bits = 0
                    half_bit = 0
                    low_bits = 0
                else:
                    cbits = unrounded.c.bit_length()
                    left_bits = 1
                    half_bit = (unrounded.c >> (cbits - 2)) & 1
                    low_bits = unrounded.c & bitmask(cbits - 2)

                new_exp = unrounded.e
                if half_bit > 0 or low_bits > 0 or unrounded.rc > 0:
                    rc = 1
                    exp_inexact = True
                else:
                    rc = unrounded.rc
                    exp_inexact = unrounded.inexact

                if half_bit > 0:
                    if low_bits > 0 or unrounded.rc > 0:
                        # UP
                        new_exp += 1
                        rc = -1
                    elif unrounded.rc < 0:
                        # DOWN
                        pass
                    else:
                        # TIE
                        tmp_exp = new_exp
                        rounded = digital.Digital(negative=unrounded.negative, c=1, exp=tmp_exp, inexact=exp_inexact, rc=rc)
                        bits = posit.digital_to_bits(rounded, ctx)
                        if bits & 1:
                            new_exp += 1
                            rc = -1

                rounded = digital.Digital(negative=unrounded.negative, c=1, exp=new_exp, inexact=exp_inexact, rc=rc)

            else:
                #print('normal round')
                # we can represent the entire exponent, so only round the mantissa
                if max_p is None:
                    effective_prec = sbits+1
                else:
                    effective_prec = max(1, min(sbits+1, max_p))
                rounded = unrounded.round_m(max_p=effective_prec, min_n=min_n, rm=RM.RNE, strict=strict)

        # Posits do not have a signed zero, and never round down to zero.

        if inexact is not None and inexact != rounded.inexact:
            rounded = type(rounded)(rounded, inexact=inexact)

        if rounded.is_zero():
            if rounded.inexact:
                return cls(negative=rounded.negative, c=1, exp=rounded.exp, rc=-1, ctx=ctx)
            else:
                return cls(rounded, negative=False, ctx=ctx)
        else:
            return cls(rounded, ctx=ctx)

    def isnormal(self):
        return not (
            self.is_zero()
            or self.isinf
            or self.isnan
            or self.p <= 1
        )

    # in order to sink

    @staticmethod
    def _limiting_p(*args):
        p = None
        for arg in args:
            if arg.inexact and (p is None or arg.p < p):
                p = arg.p
        return p

    @staticmethod
    def _limiting_n(*args):
        n = None
        for arg in args:
            if arg.inexact and (n is None or arg.n > n):
                n = arg.n
        return n

    @staticmethod
    def _limiting_exactness(*args):
        for arg in args:
            if arg.inexact:
                return True
        return None

    def add(self, other, ctx=None):
        ctx = self._select_context(self, other, ctx=ctx)
        n = self._limiting_n(self, other)
        inexact = self._limiting_exactness(self, other)
        result = gmpmath.compute(OP.add, self, other, prec=ctx.p)
        return self._round_to_context(result, min_n=n, inexact=inexact, ctx=ctx, strict=True)

    def sub(self, other, ctx=None):
        ctx = self._select_context(self, other, ctx=ctx)
        n = self._limiting_n(self, other)
        inexact = self._limiting_exactness(self, other)
        result = gmpmath.compute(OP.sub, self, other, prec=ctx.p)
        return self._round_to_context(result, min_n=n, inexact=inexact, ctx=ctx, strict=True)

    def mul(self, other, ctx=None):
        ctx = self._select_context(self, other, ctx=ctx)
        p = self._limiting_p(self, other)
        inexact = self._limiting_exactness(self, other)
        result = gmpmath.compute(OP.mul, self, other, prec=ctx.p)
        return self._round_to_context(result, max_p=p, inexact=inexact, ctx=ctx, strict=True)

    def div(self, other, ctx=None):
        ctx = self._select_context(self, other, ctx=ctx)
        p = self._limiting_p(self, other)
        inexact = self._limiting_exactness(self, other)
        result = gmpmath.compute(OP.div, self, other, prec=ctx.p)
        return self._round_to_context(result, max_p=p, inexact=inexact, ctx=ctx, strict=True)

    def sqrt(self, ctx=None):
        ctx = self._select_context(self, ctx=ctx)
        p = self._limiting_p(self)
        # experimentally, it seems that precision increases for fractional exact powers
        if p is not None:
            p += 1
            p = min(p, ctx.p)
        inexact = self._limiting_exactness(self)
        result = gmpmath.compute(OP.sqrt, self, prec=ctx.p)
        return self._round_to_context(result, max_p=p, inexact=inexact, ctx=ctx, strict=True)

    def neg(self, ctx=None):
        ctx = self._select_context(self, ctx=ctx)
        result = type(self)(self, negative=(not self.negative))
        return self._round_to_context(result, ctx=ctx, strict=False)

    def fabs(self, ctx=None):
        ctx = self._select_context(self, ctx=ctx)
        result = type(self)(self, negative=False)
        return self._round_to_context(result, ctx=ctx, strict=False)

class Interpreter(interpreter.StandardInterpreter):
    dtype = SinkingPosit
    ctype = PositCtx

    def arg_to_digital(self, x, ctx):
        return self.dtype(x, ctx=ctx)

    def _eval_constant(self, e, ctx):
        try:
            return None, self.constants[e.value]
        except KeyError:
            return None, self.round_to_context(gmpmath.compute_constant(e.value, prec=ctx.nbits), ctx=ctx)

    # unfortunately, interpreting these values efficiently requries info from the context,
    # so it has to be implemented per interpreter...

    def _eval_integer(self, e, ctx):
        x = digital.Digital(m=e.i, exp=0, inexact=False)
        return None, self.round_to_context(x, ctx=ctx)

    def _eval_rational(self, e, ctx):
        p = digital.Digital(m=e.p, exp=0, inexact=False)
        q = digital.Digital(m=e.q, exp=0, inexact=False)
        x = gmpmath.compute(OP.div, p, q, prec=ctx.nbits)
        return None, self.round_to_context(x, ctx=ctx)

    def _eval_digits(self, e, ctx):
        x = gmpmath.compute_digits(e.m, e.e, e.b, prec=ctx.nbits)
        return None, self.round_to_context(x, ctx=ctx)

    def round_to_context(self, x, ctx):
        """Not actually used???"""
        return self.dtype._round_to_context(x, ctx=ctx, strict=False)


from abc import ABC, abstractmethod
import itertools

def add(x, y):
    return x + y

def mul(x, y):
    return x * y

class Expression(ABC):
    @abstractmethod
    def evaluate(self):
        pass

class Number(Expression):
    def __init__(self, value=None):
        self.value = value

    def __repr__(self):
        return f'Num value: {self.value}'

    def evaluate(self, partB=False):
        return self.value

class InfixExpression(Expression):
    def __init__(self):
        self.operands = []
        self.operators = []

    def __repr__(self):
        return f'{self.operators} - {self.operands}'

    def evaluate(self, partB=False):
        if not partB:
            result = self.operands[0].evaluate()
            for i in range(1, len(self.operands)):
                result = self.operators[i - 1](result, self.operands[i].evaluate())
        else:
            result = 1
            i = 1
            while i < len(self.operands):
                if self.operators[i - 1](1, 1) == 2:
                    prev_val = self.operands[i - 1].evaluate(True)
                    curr_val = self.operands[i].evaluate(True)
                    self.operands = list(itertools.chain(self.operands[0: i],
                                         self.operands[i + 1: len(self.operands)]))
                    self.operands[i - 1] = Number(prev_val + curr_val)
                    self.operators = list(itertools.chain(self.operators[0: i - 1],
                                          self.operators[i: len(self.operators)]))
                    continue

                i += 1
            for i in range(len(self.operands)):
                result *= self.operands[i].evaluate(True)

        return result

if __name__ == "__main__":
    with open('inputs/day18.txt') as f:
        all_expr = []
        for i, line in enumerate(f):
            tokens = line.strip().replace('(', '( ').replace(')', ' )').split(' ')
            curr = InfixExpression()
            curr_expr = [curr]
            for i, token in enumerate(tokens):
                peek = curr_expr[-1]
                if token == "(":
                    child = InfixExpression()
                    peek.operands.append(child)
                    curr_expr.append(child)
                elif token == ")":
                    curr_expr = curr_expr[:-1]
                elif token == "+":
                    peek.operators.append(add)
                elif token == '*':
                    peek.operators.append(mul)
                else:
                    peek.operands.append(Number(int(token)))
            all_expr.append(curr)
        res = 0
        for expr in all_expr:
            val = expr.evaluate()
            # print(val)
            res += val
        print(res)
        res2 = 0
        for expr in all_expr:
            val = expr.evaluate(partB=True)
            # print(val)
            res2 += val

    print(res2)


import json
import sys
import threading
import kafka
import requests

threads = []
cookie = "token=code_space;"
header = {
    "cookie": cookie,
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Type": "application/json",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/92.0.4515.159 Safari/537.36"
}

class PullThread(threading.Thread):
    def __init__(self, thread_name, topic, partition):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.partition = partition
        self.topic = topic

    def run(self):
        print("Starting " + self.name)
        set_consumer(self.thread_name, self.topic, self.partition)

    @staticmethod
    def stop():
        sys.exit()

def set_consumer(thread_name, topic, partition):
    broker_list = brokers
    # set topic and partition, construct object tp
    tp = kafka.TopicPartition(topic, partition)
    consumer = kafka.KafkaConsumer(
        bootstrap_servers=broker_list,
        group_id="robot",
        client_id=thread_name,
        enable_auto_commit=False,
        fetch_min_bytes=1024 * 1024,  # 1M
        fetch_max_wait_ms=60000,  # 30s
        request_timeout_ms=305000,
    )
    # assign consumer to partition
    consumer.assign([tp])
    # get offset of last consuming
    offset = consumer.end_offsets([tp])[tp]
    # set current consuming offset
    consumer.seek(tp, offset)
    print(u"Running at thread:", thread_name, u"Partition:", partition,
          u"With offset:", offset, u"\tConsuming...")

    consume_num = 0
    while True:
        msg = consumer.poll(timeout_ms=60000)  # 30s
        end_offset = consumer.end_offsets([tp])[tp]
        if len(msg) > 0:
            print(u"At thread:", thread_name, u"Partition:", partition,
                  u"Max offset:", end_offset, u"With Data:", len(msg))
            line_num = 0
            for data in msg.values():
                for line in data:
                    response = {"status": 200}
                    print("Received:", line)
                    user_id = 0
                    serial_num = 0
                    line_num += 1
                    '''
                    We shall generate next line here with given "line"
                    '''
                    gen_line = line
                    print("Generated:", line)
                    post_dict = {
                        f"{user_id}": f"{serial_num}",
                        'data_content': f'{gen_line}'
                    }
                    while response["status"] != "200":
                        response = requests.post(receiver, data=post_dict, headers=header, cookies=cookie)
            print(thread_name, ", total lines:", line_num)
            # submit the offset to broker server
            consumer.commit(offsets={tp: (kafka.OffsetAndMetadata(end_offset, None))})
            if not 0:
                # shut down this sub-thread
                sys.exit()
        else:
            print(thread_name, 'no data fetched')
        consume_num += 1
        print(thread_name, "Consuming at times:", consume_num)

if __name__ == '__main__':
    thread_num = 3
    brokers = "127.0.0.1:9092"
    receiver = "127.0.0.1:5000"
    # "ip:9092,127.0.0.1:9092"
    for i in range(thread_num):
        threads.append(PullThread(f"Thread-{i}", "line_gen_topic", i))
    for t in threads:
        t.start()
    # let main thread wait for all sub-threads ending
    for t in threads:
        t.join()


from bs4 import BeautifulSoup
import requests
import logging
import os

logger = logging.getLogger(__name__)

def crawl(alph):
    for letter in alph:
        # this can run a long time its helpfull to know which letter its on
        logger.info(f"processing letter {letter}...")
        url = "http://www.mso.anu.edu.au/~ralph/OPTED/v003/wb1913_" + letter + ".html" #there is a page for each letter
        req = requests.get(url) #grab page
        soup = BeautifulSoup(req.text, "html.parser") #get parser
        dictionary = soup.find_all('p') # find all the dictionary entries
        for entries in dictionary:
            word = entries.find('b').getText() # get the word itself
            pos = entries.find('i').getText() # get the part of speech
            cut = len(word) + len(pos) + 4 # calulate how much word and pos take up
            definition = entries.getText()[cut:] # cut that from the total sting to get definition
            yield word, pos, definition

#            DO what you need here
# this loop will run through all the words in the
# english dictionary, seperating them by word, pos and definition
#
# example to print out CSV to stdout
# use DEV=true to test small amount of words
if __name__ == '__main__':
    alph = "abcdefghijklmnopqrstuvwxyz"
    if os.environ.get('DEV'):
        alph = "x"
    print("word,pos,definition")
    for word, pos, definition in crawl(alph):
        print(f"{word},{pos},\"{definition}\"")


from django.core.mail import EmailMessage
from django.db.models import Q, Sum
from django.template.loader import render_to_string
from django.http import HttpResponse

from .utils import send_email

from django.contrib.auth import get_user_model
from django_q.tasks import async_task
from django_q.models import Schedule

from settings.models import LabsManagerSetting
from fund.models import Fund
import datetime
from django.utils import timezone

from auditlog.models import LogEntry

import logging
logger = logging.getLogger('labsmanager')

# =========== Task global scheduler on start up call ========== #
def scheduleBaseTasks():
    logger.debug("[scheduleBaseTasks] starting ...")
    # for audit log cleaning
    currSch = Schedule.objects.filter(func='labsmanager.tasks.clean_auditlog')
    if not currSch:
        sch = Schedule.objects.create(name="clean_auditlog",
                                      func='labsmanager.tasks.clean_auditlog',
                            #hook='hooks.print_result',
                            schedule_type=Schedule.CRON,
                            cron = '0 3 1 * *',
                            #hook="labsmanager.tasks.sendSuperUserMail",
                            )
        logger.debug("New Schedule :"+str(sch))
    else:
        logger.debug("Already in schedules :"+str(currSch))

    # for Fund update calculation
    currSch = Schedule.objects.filter(func='labsmanager.tasks.update_all_calculation')
    if not currSch:
        sch = Schedule.objects.create(name="update_all_calculation",
                                      func='labsmanager.tasks.update_all_calculation',
                            #hook='hooks.print_result',
                            schedule_type=Schedule.CRON,
                            cron = '30 3 * * 1-5',
                            #hook="labsmanager.tasks.sendSuperUserMail",
                            )
        logger.debug("New Schedule :"+str(sch))
    else:
        logger.debug("Already in schedules :"+str(currSch))

    # for Vacation JSON file pulling
    currSch = Schedule.objects.filter(func='leave.tasks.pull_vacation_file')
    if not currSch:
        sch = Schedule.objects.create(name="pull_vacation_file",
                                      func='leave.tasks.pull_vacation_file',
                            #hook='hooks.print_result',
                            schedule_type=Schedule.CRON,
                            cron = '40 3 * * 1-5',
                            #hook="labsmanager.tasks.sendSuperUserMail",
                            )
        logger.debug("New Schedule :"+str(sch))
    else:
        logger.debug("Already in schedules :"+str(currSch))

    # for Notifications
    currSch = Schedule.objects.filter(func='common.tasks.check_notifications_tasks')
    if not currSch:
        sch = Schedule.objects.create(name="check_notifications_tasks",
                                      func='common.tasks.check_notifications_tasks',
                            #hook='hooks.print_result',
                            schedule_type=Schedule.HOURLY,
                            #hook="labsmanager.tasks.sendSuperUserMail",
                            )
        logger.debug("New Schedule :"+str(sch))
    else:
        logger.debug("Already in schedules :"+str(currSch))

    # check periodically the scheduled tasks
    currSch = Schedule.objects.filter(func='labsmanager.tasks.scheduleBaseTasks')
    if not currSch:
        sch = Schedule.objects.create(name="scheduleBaseTasks",
                                      func='labsmanager.tasks.scheduleBaseTasks',
                            #hook='hooks.print_result',
                            schedule_type=Schedule.CRON,
                            cron = '30 1 * * 1-5',
                            #hook="labsmanager.tasks.sendSuperUserMail",
                            )
        logger.debug("New Schedule :"+str(sch))
    else:
        logger.debug("Already in schedules :"+str(currSch))

# --------------- Clean the audi log based on retention Setting
def clean_auditlog():
    logger.debug("[clean_auditlog] starting ...")
    # get settings for audit log retention
    ret_time=LabsManagerSetting.get_setting("AUDIT_LOG_RETENTION")
    if not ret_time:
        logger.warn("[clean_auditlog] - NO RETENTION TIME DEFINED")
        return
    logger.debug("    - retention time :"+str(ret_time))

    tod = datetime.datetime.now()
    d = datetime.timedelta(days = ret_time)
    a = tod - d
    logger.debug("    -> All history logs will be cleaned before :"+str(a))
    entries = LogEntry.objects.all()
    entries = entries.filter(timestamp__date__lt=a)
    cc=entries.delete()
    logger.debug("    >>> "+str(cc[0])+" entries has been deleted ")
    pass

# --------------- Update all Expense and Fund calculation
def update_all_calculation():
    logger.debug("[update_all_calculation] starting ...")
    fu=Fund.objects.all()
    for f in fu:
        f.calculate(force=True)
# --------------- Generate a report to send
def create_report(*args, **kwargs):
    from staff.models import Employee
    from project.models import Participant

    contextMail={}
    parti=Participant.objects.select_related("employee").filter(Q(project__status=True) &  Q(start_date__lte=timezone.now())  & ( Q(end_date__gte=timezone.now()) | Q(end_date=None))).values("employee").annotate(project_quotity=Sum('quotity'))
    parti=parti.filter(project_quotity__gt=1).values("employee")
    emp=Employee.objects.filter(pk__in=parti)
    contextMail['participant']=emp

    html_content = render_to_string('email/global_report.html',context=contextMail)
    return HttpResponse(html_content, status=200)

def sendMailTest(*args, **kwargs):
    logger.debug("[send_email_test] starting ...")

    logger.debug("  - args :"+str(args))
    logger.debug("  - kwargs :"+str(kwargs))

    User = get_user_model()
    usersObj = User.objects.all()
    emailadress=kwargs["recipient"]

    contextEmail={"users":usersObj,}
    html_content = render_to_string('email/user_list.html',context=contextEmail)

    logger.debug("  - emailadress :"+str(emailadress))
    logger.debug("  - contextEmail :"+str(contextEmail))
    logger.debug("  - html_content :"+str(html_content))
    resp=send_email(
        subject="Test Email",
        body="",
        recipients=emailadress,
        from_email=None,
        html_message=html_content
        )
    logger.debug(">>>>> mail response :"+str(resp))

# ============================================ send mail hook to super user
def sendSuperUserMail(*args, **kwargs):
    logger.debug("[sendSuperUserMail] starting ...")
    User = get_user_model()
    usersMails = User.objects.filter(is_superuser=True).values_list("email", flat=True)

    task=args[0]

    content=f"The task : {task.name} has finished \n"
    content+=f" - fct : {task.func} \n"

    resp=send_email(
        subject="Task Hook Mail",
        body="Test HookMail Body",
        recipients=usersMails,
        from_email=None,
        html_message=content
        )
    logger.debug(">>>>> mail response :"+str(resp))

# test hook
def testHook(*args, **kwargs):
    pass


# _*_coding:utf-8_*_
# __author: a123456
import random
import time
from functools import wraps

def run_time(func):
    """打印函数运行时间, 毫秒"""

    @wraps(func)  # 获取函数自身名称
    def inner(*args, **kwargs):
        no_print = kwargs.get("no_print")
        if no_print:
            kwargs.pop("no_print")
            return func(*args, **kwargs)

        begin = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        if not kwargs.get("use"):
            print(f"{func.__name__}: {end - begin} s")
        return result

    return inner

class T:

    @classmethod
    @run_time
    def build_test_list(cls, n: int, range_l: int = 0, range_r: int = 10) -> []:
        """
        构建测试排序用列表
        :param n:  生成数量
        :param range_l: 左边界
        :param range_r: 右边界
        :return: []
        """
        assert range_l < range_r, "range_l >= range_r"

        arr = [random.randint(range_l, range_r) for i in range(n)]
        return arr

    @classmethod
    @run_time
    def build_order_list(cls, n: int, range_l: int = 0, range_r: int = 10) -> []:
        """
        构建测试排序用列表， 基本有序的列表
        :param n:  生成数量
        :param range_l: 左边界
        :param range_r: 右边界
        :return: []
        """
        assert range_l < range_r, "range_l >= range_r"

        arr = [random.randint(range_l, range_r) for i in range(n)]

        for i in range(10):
            i1 = random.randint(0, n - 1)
            i2 = random.randint(0, n - 1)
            arr[i1], arr[i2] = arr[i2], arr[i1]

        return arr

    @classmethod
    def swap(cls, i1, i2, arr):
        arr[i1], arr[i2] = arr[i2], arr[i1]

tool = T

if __name__ == '__main__':
    test_list = tool.build_test_list(10, 0, 10)


from imageai.Detection import ObjectDetection
import cv2
from object_detector.DetectorAPI import DetectorAPI

class ObjectDetector:

    model_class_labels = ["person", "bicycle", "car", "motorcycle", "airplane",
                          "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign",
                          "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra",
                          "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard",
                          "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket",
                          "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange",
                          "broccoli", "carrot", "hot dog", "pizza", "donot", "cake", "chair", "couch", "potted plant", "bed",
                          "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave",
                          "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair dryer",
                          "toothbrush"]

    def __init__(self, model_name, model_path):
        self.model_path = model_path
        self.model_name = model_name
        if model_name == 'other':
            self.object_detector = DetectorAPI(path_to_ckpt=model_path)
        else:
            self.object_detector = ObjectDetection()
            if model_name == 'yolov3':
                self.object_detector.setModelTypeAsYOLOv3()
            elif model_name == 'tinyyolov3':
                self.object_detector.setModelTypeAsTinyYOLOv3()
            elif model_name == 'retinanet':
                self.object_detector.setModelTypeAsRetinaNet()
            self.object_detector.setModelPath(model_path)
            self.object_detector.loadModel()

    def detect(self, input_image_path, output_image_path, extract_detected_objects=True, display_percentage_probability=False, display_object_name=False, threshold=0.7):

        if self.model_name == 'other':
            detected_objects_location = []
            img = cv2.imread(input_image_path)
            boxes, scores, classes, _ = self.object_detector.process_frame(
                img)
            detections = []
            for i in range(len(boxes)):
                if scores[i] > threshold:
                    detections.append({
                        'name': self.model_class_labels[classes[i] - 1]
                    })
                    box = boxes[i]
                    cv2.rectangle(img, (box[1], box[0]),
                                  (box[3], box[2]), (255, 0, 0), 2)
            cv2.imwrite(output_image_path, img)
        else:
            detections, detected_objects_location = self.object_detector.detectObjectsFromImage(
                input_image=input_image_path,
                output_image_path=output_image_path,
                extract_detected_objects=extract_detected_objects,
                display_percentage_probability=display_percentage_probability,
                display_object_name=display_object_name
            )
        return detections, detected_objects_location


# Silly example of date comparison to get age

from datetime import date

birth_year = int(input("Year of birth: "))
birth_month = int(input("Month of birth: "))
birth_day = int(input("Day of birth: "))
birthday_date = date(birth_year, birth_month, birth_day)
age = date.today() - birthday_date

result = "You are " + str(int(age.days / 365.25)) + " years old"
print(result)


for i in range(int(input())):
  l = input().split()
  val = float(l[0])
  for i in (l[1:]):
    if i == "@":
      val*=3
    elif i == "%":
      val +=5
    elif i== "#":
      val -=7
  print ("%.2f" % val)


import numpy as np

class Tiles(object):
    """
    맵 정보만 줌
    """
    stageRow = 8
    stageColumn = 8
    #def stageMaker(self, stageNum)
    #def __init__(self, stageNum)
    def __init__(self):
        """
        음수는 무조건 막히는 타일
        -1=벽
        0=빈공간
        1~20는 플레이어와 플레이어+타일
        1=플레이어 2=플레이어+집
        21~40대는 박스와 박스+타일
        21=박스 22=박스+집
        41~은 단일 타일들
        41=집
        """
        self.tile = [
            [-1,-1,-1,-1,-1,-1,-1,-1],
            [-1,0,0,0,0,0,0,-1],
            [-1,0,41,41,0,0,0,-1],
            [-1,0,41,41,21,0,0,-1],
            [-1,0,0,0,21,0,0,-1],
            [-1,0,0,1,0,0,0,-1],
            [-1,0,0,0,0,0,0,-1],
            [-1,-1,-1,-1,-1,-1,-1,-1]
            ]
        self.playerRowPos, self.playerColumnPos = 5, 3
        self.tile=np.array(self.tile)

    def playerLeft(self,Row,Col):
        if self.tile[Row][Col]==1:
            return 0
        elif self.tile[Row][Col]==2:
            return 41
        else:
            return -1

    def rockGo(self,Row,Col):
        rGo = self.tile[Row][Col]
        if rGo==-1 or rGo==21 or rGo==22:
            return False
        else:
            if rGo==0:
                self.tile[Row][Col]=21
            elif rGo==41:
                self.tile[Row][Col]=22
            return True
    """
    음수는 무조건 막히는 타일
    -1=벽
    0=빈공간
    1~20는 플레이어와 플레이어+타일
    1=플레이어 2=플레이어+집
    21~40대는 박스와 박스+타일
    21=박스 22=박스+집
    41~은 단일 타일들
    41=집
    """
    def move(self, dx,dy):
        doesGo = self.tile[self.playerRowPos+dy][self.playerColumnPos+dx]
        if doesGo==-1:
            return
        elif doesGo==0:
            self.tile[self.playerRowPos+dy][self.playerColumnPos+dx]=1
            self.tile[self.playerRowPos][self.playerColumnPos]=self.playerLeft(self.playerRowPos,self.playerColumnPos)
        elif doesGo==21:
            if self.rockGo(self.playerRowPos+dy+dy,self.playerColumnPos+dx+dx):
                self.tile[self.playerRowPos+dy][self.playerColumnPos+dx]=1
                self.tile[self.playerRowPos][self.playerColumnPos]=self.playerLeft(self.playerRowPos,self.playerColumnPos)
            else:
                return
        elif doesGo==41:
            self.tile[self.playerRowPos+dy][self.playerColumnPos+dx]=2
            self.tile[self.playerRowPos][self.playerColumnPos]=self.playerLeft(self.playerRowPos,self.playerColumnPos)

        elif doesGo==22:
            if self.rockGo(self.playerRowPos+dy+dy,self.playerColumnPos+dx+dx):
                self.tile[self.playerRowPos+dy][self.playerColumnPos+dx]=2
                self.tile[self.playerRowPos][self.playerColumnPos]=self.playerLeft(self.playerRowPos,self.playerColumnPos)
            else:
                return
        self.playerRowPos+=dy
        self.playerColumnPos+=dx

    def display(self):
        return str(self.tile)


import sys, base64
import numpy as np
from PIL import Image
from io import BytesIO, StringIO
import skimage.io
import tensorflow as tf

from main import foward_pass
from helper import ImageProcess

file = sys.argv[-1]

if file == 'demo.py':
    print("Error loading video")
    quit

# Define encoder function
def encode(array):
    assert array.shape==(600,800)
    pil_img = Image.fromarray(array)
    buff = BytesIO()
    pil_img.save(buff, format="PNG")
    return base64.b64encode(buff.getvalue()).decode("utf-8")

def naive_calssify(image_array):
    red = image_array[:, :, 0]
    # Look for red cars :)
    binary_car_result = np.where(red > 250, 1, 0).astype('uint8')

    # Look for road :)
    binary_road_result = binary_car_result = np.where(red < 20, 1, 0).astype('uint8')

    return [encode(binary_car_result), encode(binary_road_result)]

def test_output():
    vgg_dir = './data'
    num_classes = 3
    with tf.Session() as sess:
        input_image, keep_prob, logits, train_op, cross_entropy_loss, correct_label, learning_rate \
            = foward_pass(num_classes, sess, vgg_dir)

        saver = tf.train.Saver()

        ckpt = tf.train.get_checkpoint_state('./model_ckpt/')
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)

        ip = ImageProcess(sess, keep_prob, input_image, logits, image_shape=(640, 832))

        pip_image = ip.pipeline(skimage.io.imread("./data/CameraRGB/0.png"))

        import matplotlib.pyplot as plt
        plt.imshow(pip_image)
        plt.show()

if __name__ == "__main__":
    test_image = skimage.io.imread("./data/CameraRGB/0.PNG")

    naive_calssify(test_image)

    test_output()


import constants
import pandas as pd
import datetime

def trim(days_ago):
    n = datetime.datetime.now()
    r = n - datetime.timedelta(days=days_ago)
    delete = 'DELETE FROM {} WHERE TIME < \'' + r.isoformat() + '\';'
    print(delete)
    constants.postgres_engine.execute(delete.format(constants.data_table))

def delete_all():
    n = datetime.datetime.now()
    delete = 'DELETE FROM {};'
    print(delete.format(constants.data_table))
    constants.postgres_engine.execute(delete.format(constants.data_table))
    constants.postgres_engine.execute(delete.format(constants.counts_table))
    constants.postgres_engine.execute(delete.format(constants.locations_table))

def get_between_days_ago(ago1, ago2):
    if ago1 == ago2:
        return

    if ago1 > ago2:
        t = ago1
        ago1 = ago2
        ago2 = t

    since1 = datetime.datetime.now() - datetime.timedelta(days = ago1)
    since2 = datetime.datetime.now() - datetime.timedelta(days = ago2)
    selection = 'SELECT * from {} WHERE TIME BETWEEN \''+since2.isoformat()+'\' AND \''+since1.isoformat()+'\' ORDER BY TIME';
    stored_df = pd.read_sql(
        selection.format(constants.data_table), constants.postgres_engine
    )
    return stored_df

def get_data(platform):
    # In this function, we retrieve the data from postgres using pandas's read_sql method.

    # This data is periodically getting updated via a separate Celery Process in tasks.py.
    # "dataset_table" is the name of the table that we initialized in tasks.py.
    selection = 'SELECT * from {}'
    if platform is not None:
        selection = selection + ' WHERE PLATFORM_CODE=\'' + str(platform) +'\''
    selection = selection + ' ORDER BY TIME;'
    updated_df = pd.read_sql(
        selection.format(constants.data_table), constants.postgres_engine
    )
    return updated_df

def test_selection():
    selection = 'SELECT * from {}'
    selection = selection + ' WHERE PLATFORM_TYPE=\'ARGO\''
    selection = selection + ' ORDER BY TIME LIMIT 10;'
    updated_df = pd.read_sql(
        selection.format(constants.data_table), constants.postgres_engine
    )
    return updated_df

def exists():
    try:
        df = test_selection()
    except Exception as e:
        print(e)
        return False

    if df is not None:
        return True
    else:
        return False

def get_counts():
    # In this function, we retrieve the data from postgres using pandas's read_sql method.

    # This data is periodically getting updated via a separate Celery Process in tasks.py.
    # "dataset_table" is the name of the table that we initialized in tasks.py.
    updated_df = pd.read_sql(
        "SELECT * FROM {};".format(constants.counts_table), constants.postgres_engine
    )
    return updated_df

def get_locations():
    # In this function, we retrieve the data from postgres using pandas's read_sql method.

    # This data is periodically getting updated via a separate Celery Process in tasks.py.
    # "dataset_table" is the name of the table that we initialized in tasks.py.
    updated_df = pd.read_sql(
        "SELECT * FROM {};".format(constants.locations_table), constants.postgres_engine
    )
    return updated_df


import unittest
import glob
import sys
import random
import shutil
import os

from IECore import *

class TestPNGReader(unittest.TestCase):

	def testConstruction( self ):

		r = Reader.create( "test/IECore/data/png/PngTestSuite/basn2c08.png" )
		self.assertEqual( type(r), PNGImageReader )

	def testCanRead( self ):

		self.assert_( PNGImageReader.canRead( "test/IECore/data/png/PngTestSuite/basn2c08.png" ) )

	def testIsComplete( self ):

		r = Reader.create( "test/IECore/data/png/kodak_dx7590_test.png" )
		self.assertEqual( type(r), PNGImageReader )

		self.assert_( r.isComplete() )

		r = Reader.create( "test/IECore/data/png/kodak_dx7590_test_truncated.png" )
		self.assertEqual( type(r), PNGImageReader )

		self.failIf( r.isComplete() )

	def testChannelNames( self ):

		# Test RGBA
		r = Reader.create( "test/IECore/data/png/PngTestSuite/basn6a08.png" )
		self.assertEqual( type(r), PNGImageReader )

		channelNames = r.channelNames()

		self.assertEqual( len( channelNames ), 4 )

		self.assert_( "R" in channelNames )
		self.assert_( "G" in channelNames )
		self.assert_( "B" in channelNames )
		self.assert_( "A" in channelNames )

		# Test YA
		r = Reader.create( "test/IECore/data/png/PngTestSuite/basn4a08.png" )
		self.assertEqual( type(r), PNGImageReader )

		channelNames = r.channelNames()

		self.assertEqual( len( channelNames ), 2 )

		self.assert_( "Y" in channelNames )
		self.assert_( "A" in channelNames )

	def testReadHeader( self ):

		r = Reader.create( "test/IECore/data/png/PngTestSuite/basn2c08.png" )
		self.assertEqual( type(r), PNGImageReader )
		h = r.readHeader()

		channelNames = h['channelNames']
		self.assertEqual( len( channelNames ), 3 )
		self.assert_( "R" in channelNames )
		self.assert_( "G" in channelNames )
		self.assert_( "B" in channelNames )

		self.assertEqual( h['displayWindow'], Box2iData( Box2i( V2i(0,0), V2i(31,31) ) ) )
		self.assertEqual( h['dataWindow'], Box2iData( Box2i( V2i(0,0), V2i(31,31) ) ) )

	def testRead( self ):

		r = Reader.create( "test/IECore/data/png/PngTestSuite/basn2c08.png" )
		self.assertEqual( type(r), PNGImageReader )

		img = r.read()

		self.assertEqual( type(img), ImagePrimitive )

		self.assertEqual( img.displayWindow, Box2i( V2i( 0, 0 ), V2i( 31, 31 ) ) )
		self.assertEqual( img.dataWindow, Box2i( V2i( 0, 0 ), V2i( 31, 31 ) ) )

	def testReadChannel( self ):

		r = Reader.create( "test/IECore/data/png/PngTestSuite/basn2c08.png" )
		self.assertEqual( type(r), PNGImageReader )

		red = r.readChannel( "R" )
		self.assert_( red )

		green = r.readChannel( "G" )
		self.assert_( green )

		blue = r.readChannel( "B" )
		self.assert_( blue )

		self.assertRaises( RuntimeError, r.readChannel, "NonExistantChannel" )

		self.assertEqual( len(red), len(green) )
		self.assertEqual( len(red), len(blue) )
		self.assertEqual( len(red), 32 * 32 )

	def testSourceColorSpace( self ):

		# Should always be srgb
		self.assertEqual( Reader.create( "test/IECore/data/png/PngTestSuite/basn2c08.png" ).sourceColorSpace(), "srgb" )

	def testDataWindowRead( self ):

		r = Reader.create( "test/IECore/data/png/kodak_dx7590_test.png" )
		self.assertEqual( type(r), PNGImageReader )

		dataWindow = Box2i(
			V2i( 50, 50 ),
			V2i( 450, 200 )
		)

		imgOriginal = r.read()
		self.assertEqual( type(imgOriginal), ImagePrimitive )

		r.parameters()["dataWindow"].setValue( Box2iData( dataWindow ) )

		img = r.read()
		self.assertEqual( type(img), ImagePrimitive )

		self.assertEqual( img.dataWindow, dataWindow )
		self.assertEqual( img.displayWindow, Box2i( V2i( 0, 0 ), V2i( 2575, 1931 ) ) )

		self.assertEqual( len(img["R"].data), 401 * 151 )
		self.assertEqual( len(img["G"].data), 401 * 151 )
		self.assertEqual( len(img["B"].data), 401 * 151 )

		ipe = PrimitiveEvaluator.create( img )
		self.assert_( ipe.R() )
		self.assert_( ipe.G() )
		self.assert_( ipe.B() )
		self.failIf ( ipe.A() )

		result = ipe.createResult()

		ipeOriginal = PrimitiveEvaluator.create( imgOriginal )

		resultOriginal = ipeOriginal.createResult()

		random.seed( 1 )

		# Test for equivalence using 50 random pixels. Inside the data window, we expect the
		# pixel values to be the same. Outside the data window we expect black.
		for i in range( 0, 50 ):

			pixel = V2i( int( random.uniform( 0, 511 ) ), int( random.uniform( 0, 255 ) ) )

			found = ipe.pointAtPixel( pixel, result )
			self.assert_( found )

			found = ipeOriginal.pointAtPixel( pixel, resultOriginal )
			self.assert_( found )

			color = V3f(
				result.floatPrimVar( ipe.R() ),
				result.floatPrimVar( ipe.G() ),
				result.floatPrimVar( ipe.B() )
			)

			if ( pixel.x >= dataWindow.min.x ) and ( pixel.x < dataWindow.max.x ) and (pixel.y >= dataWindow.min.y ) and ( pixel.y < dataWindow.max.y ) :

				expectedColor = V3f(
						resultOriginal.floatPrimVar( ipeOriginal.R() ),
						resultOriginal.floatPrimVar( ipeOriginal.G() ),
						resultOriginal.floatPrimVar( ipeOriginal.B() )
					)

			else :

				expectedColor = V3f( 0, 0, 0 )

			self.assert_( ( color - expectedColor).length() < 1.e-3 )

	def testOrientation( self ) :

		""" Test orientation of PNG files """

		img = Reader.create( "test/IECore/data/png/uvMap.512x256.8bit.png" ).read()

		ipe = PrimitiveEvaluator.create( img )
		self.assert_( ipe.R() )
		self.assert_( ipe.G() )
		self.assert_( ipe.B() )
		self.failIf ( ipe.A() )

		result = ipe.createResult()

		colorMap = {
			V2i( 0 ,    0 ) :  V3f( 0, 0, 0 ),
			V2i( 511,   0 ) :  V3f( 1, 0, 0 ),
			V2i( 0,   255 ) :  V3f( 0, 1, 0 ),
			V2i( 511, 255 ) :  V3f( 1, 1, 0 ),
		}

		for point, expectedColor in colorMap.items() :

			found = ipe.pointAtPixel( point, result )
			self.assert_( found )

			color = V3f(
				result.floatPrimVar( ipe.R() ),
				result.floatPrimVar( ipe.G() ),
				result.floatPrimVar( ipe.B() )
			)

			self.assert_( ( color - expectedColor).length() < 1.e-6 )

	def testErrors( self ):

		r = PNGImageReader()
		self.assertRaises( RuntimeError, r.read )
		self.assertRaises( RuntimeError, r.readChannel, "R" )

		r = PNGImageReader( "test/IECore/data/jpg/uvMap.512x256.jpg" )
		self.assertRaises( RuntimeError, r.read )

	def testPngTestSuite( self ):

		fileNames = glob.glob( "test/IECore/data/png/PngTestSuite/*.png" )

		expectedFailures = [

			"test/IECore/data/png/PngTestSuite/xc1n0g08.png",
			"test/IECore/data/png/PngTestSuite/xc9n2c08.png",
			"test/IECore/data/png/PngTestSuite/xcrn0g04.png",
			"test/IECore/data/png/PngTestSuite/xcsn0g01.png",
			"test/IECore/data/png/PngTestSuite/xd0n2c08.png",
			"test/IECore/data/png/PngTestSuite/xd3n2c08.png",
			"test/IECore/data/png/PngTestSuite/xd9n2c08.png",
			"test/IECore/data/png/PngTestSuite/xdtn0g01.png",
			"test/IECore/data/png/PngTestSuite/xhdn0g08.png",
			"test/IECore/data/png/PngTestSuite/xlfn0g04.png",
			"test/IECore/data/png/PngTestSuite/xs1n0g01.png",
			"test/IECore/data/png/PngTestSuite/xs2n0g01.png",
			"test/IECore/data/png/PngTestSuite/xs4n0g01.png",
			"test/IECore/data/png/PngTestSuite/xs7n0g01.png",
		]

		for f in fileNames:

			r = PNGImageReader( f )

			if f in expectedFailures :

				self.assertRaises( RuntimeError, r.read )

			else :
				self.assert_( PNGImageReader.canRead( f ) )
				self.failIf( TIFFImageReader.canRead( f ) )
				self.failIf( JPEGImageReader.canRead( f ) )
				self.failIf( EXRImageReader.canRead( f ) )
				self.failIf( CINImageReader.canRead( f ) )

				img = r.read()
				self.assertEqual( type(img), ImagePrimitive )
				self.assert_( img.arePrimitiveVariablesValid() )

	def testReadWithIncorrectExtension( self ) :

		shutil.copyfile( "test/IECore/data/png/kodak_dx7590_test.png", "test/IECore/data/png/kodak_dx7590_test.dpx" )

		# should be able to infer a correct reader even though the extension is incorrect
		r = Reader.create( "test/IECore/data/png/kodak_dx7590_test.dpx" )
		self.failUnless( isinstance( r, PNGImageReader ) )

		i = r.read()
		self.failUnless( isinstance( i, ImagePrimitive ) )

	def tearDown( self ) :

		for f in [
			 "test/IECore/data/png/kodak_dx7590_test.dpx",
		] :
			if os.path.exists( f ) :
				os.remove( f )

if __name__ == "__main__":
	unittest.main()


"""
In the first solution we will follow the steps of solving
"""

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        res = []
        queens = [-1]*n
        """
        In this we will store  like [1, 3, 0, 2] means
        [.Q..]
        [...Q]
        [Q...]
        [..Q.]
        """

        def backTrack(index):
            if index == len(queens):
                res.append(queens[:])
                return
            for i in range(len(queens)):
                queens[index] = i
                if valid(index):
                    backTrack(index+1)

        def valid(n):
            for i in range(n):
                if abs(queens[i]-queens[n]) == abs(n-i):  # same Diagonal
                    return False
                if queens[i] == queens[n]:  # same col
                    return False
            return True

        # now we have queens = [1,3,0,2] this function returns
        def makeBoard(queens):
            n = len(queens)
            board = []
            boardTmp = [['.']*n for _ in range(n)]
            for r, c in enumerate(queens):
                boardTmp[r][c] = 'Q'
            for row in boardTmp:
                board.append("".join(row))
            return board

        def make_all_boards(res):
            actual_boards = []
            for queens in res:
                actual_boards.append(makeBoard(queens))
            return actual_boards

        backTrack(0)
        return make_all_boards(res)

"""
In this second solution we will use set and keep this simple
Goal: Place a queen somewhere such that no queen are attacking each other
Approach: backtracking
- each recursive layer will decide on a row and also the placement of the queen
- the constraint is making sure we do not place a queen where its in sight of another queen. How?
    1) make sure it is not on the same column --> create a column set
    2) make sure it is not in same diagonal path --> create a diagonal set (calculated via r+c)
    3) make sure it is not in a antidiagonal path --> create a antidiagonal set (calculated via r-c)

    We dont need to worry about rows because it is handled by the backtracking parameter that always recurse
    to next level of the row

    ** note: if you dont know why r+c and r-c are diagonal paths --> Draw it out and check why it does!!
"""

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:

        if n == 0:
            return []

        col = set()
        diagonal = set()    # determined by r+c
        antidiagonal = set()
        output = []
        result = []

        def backtrack(r):
            nonlocal n, col, diagonal, antidiagonal, output, result
            if r == n:
                result.append(output[:])
                return

            for c in range(n):
                if c in col or (r+c) in diagonal or (r-c) in antidiagonal:
                    continue

                col.add(c)
                diagonal.add(r+c)
                antidiagonal.add(r-c)
                output.append('.'*c + 'Q' + '.'*(n-c-1))
                backtrack(r+1)

                col.remove(c)
                diagonal.remove(r+c)
                antidiagonal.remove(r-c)
                output.pop()

        backtrack(0)
        return result


# Author: Semen Mordovin
# ID: 29403413
# Start Date: 06/04/2019
# Last Modification Date: 11/04/2019

""" Importing random library to apply random numbers for our student score to
check number of class occurrences
"""

import random

"""Main function which divides student score into different classes, according
to our requirements. Using fop loop and lists to work with data. if  conditions
is to check necessary conditions for list of Student Scores"""

def countStudentClass(studentScore_list):
	if len(studentScore_list) < 1:
		print("Please add at least 1 item into the list")
		return 0

	nerdCount_list = [0] * 7

	if len(studentScore_list) > 1:
		for item in studentScore_list:
			if item == 0:
				nerdCount_list[0] += 1
			if 10 > item >= 1:
				nerdCount_list[1] += 1
			if 100 > item >= 10:
				nerdCount_list[2] += 1
			if 500 > item >= 100:
				nerdCount_list[3] += 1
			if 1000 > item >= 500:
				nerdCount_list[4] += 1
			if 2000 > item >= 1000:
				nerdCount_list[5] += 1
			if item >= 2000:
				nerdCount_list[6] += 1
	return nerdCount_list

"""Random.sample used here with range of 0 - 5000 to generate random numbers
for student score. Number of 10 students have received their Nerd Scores for the
sake of this task. Main constructor presented via template"""

if __name__ == '__main__':
	#test cases
	#studentScore_list = []  #
	#output should be [0, 0, 2, 0, 1, 1, 0]

	studentScore_list = 9

	print("There is a number of student Nerd Scores and the number of each \
	class appearances")
	print(studentScore_list)
	print(countStudentClass(studentScore_list))


from gen import *
from nds import narc, nclr
import os

ofile = None

FNAME = "narc"+FEXT

def printable(magic):
    ret = ""
    for c in magic:
        if ord(c) < 0x20:
            ret += "\\x%02X"%ord(c)
        else:
            ret += c
    return ret

def recursefs(d):
    if os.path.isdir(C_DIR+d):
        for f in sorted(os.listdir(C_DIR+d)):
            recursefs(d+"/"+f)
    else:
        f = open(C_DIR+d, "rb")
        count = 0
        if f.read(4) == "NARC":
            f.seek(0)
            n = narc.NARC(f.read())
            f.close()
            template.mkdir(os.path.dirname(ODIR+d))
            pfile = template.open(ODIR+d+FEXT, "w", "Pokemon %s NARC - %s"%(game.title(), d))
            pfile.write("
NARC list
\n
\

File Number	File Magic	File Size
\n"%("../"*len(d.strip("/").split("/")), FNAME))
            for j, f in enumerate(n.gmif.files):
                pfile.write("
%i	%s	%i bytes
\n"%(j, printable(f[:4]), len(f)))
            pfile.write("
\n")
            pfile.close()
            ofile.write("\t
%s	%i files
\n"%(d+FEXT, d, n.btaf.getEntryNum()))
        else:
            f.close()
            ofile.write("\t
%s	Not a NARC
\n"%d)

for game in games:
    ODIR = STATIC_DIR+game+"/narc/"
    ofile = template.open(STATIC_DIR+game+"/"+FNAME, "w", "Pokemon %s NARC (Archive) Files"%game.title())
    ofile.write("""

Pokemon %s NARC (Archive) Files

\n"""%game.title())
    C_DIR = DATA_DIR+game+"/fs"
    recursefs("")
    ofile.write("
")
    ofile.close()