r"""This script calculates the numerical storage and retrieval of the
optimal input signal that the analytic theory suggests using feasible
parameters and getting high efficiency.
"""
from __future__ import print_function
from pickle import dump
import numpy as np
from matplotlib import pyplot as plt
from orca_memories.misc import (time_bandwith_product, num_integral)
from orca_memories.graphical import sketch_frame_transform
from orca_memories.orca import (set_parameters_ladder,
                                print_params,
                                build_mesh_fdm,
                                calculate_xi0, calculate_Gammap,
                                calculate_optimal_input_xi,
                                calculate_optimal_input_Z,
                                calculate_optimal_input_tau,
                                calculate_pulse_energy,
                                solve)
# from quantum_memories.orca import (calculate_pulse_energy, calculate_F,
#                                    calculate_optimal_input_xi, num_integral,
#                                    calculate_optimal_input_Z,
#                                    calculate_optimal_input_tau,
#                                    solve)
from scipy.constants import c

# We establish base parameters.
folder = "__01__high_efficiency/"
name = ""
plots = False; calculate = False
plots = True
calculate = True

# Set the memory parameters.
if True:
    # The cell to control pulse ratio:
    f = 2.0; l = 1.6*f
    # The cell to control pulse ratio at half light-speed.
    lp = 2*l
    tauw = 300e-12
    D = lp*tauw*c/2
    ########################################################################
    # The bandwidth of the control pulse is chosen so that it is a
    # Fourier-limited square pulse with intensity FWHM in time tauw.
    sigma_power2 = time_bandwith_product("oo")/tauw

    # The bandwidth of the signal pulse is chosen so that it is a
    # Fourier-limited Gaussian pulse with intensity FWHM in time tauw.
    sigma_power1 = time_bandwith_product(1)/tauw
    ########################################################################

    params = {"verbose": 1,
              "nshg": 0, "USE_HG_SIG": True,
              "sigma_power1": sigma_power1/f,
              "sigma_power2": sigma_power2,
              "Temperature": 273.15 + 115,
              "L": D/1.05,
              "w1": 131e-6,
              "w2": 131e-6,
              "delta1": 9.0*1e9*2*np.pi,
              "USE_SQUARE_CTRL": True, "nwsquare": "oo", "nrsquare": "oo",
              "element": "Rb", "isotope": 87}
    params = set_parameters_ladder(params)

    ########################################################################
    # We use the analytic theory to calculate the optimal pulse energy,
    # (that would allow unit efficiency for a narrowband signal and an
    # infinite cell.)
    Ecrit = calculate_pulse_energy(params)
    # We set the pulse energy to that value.
    params["energy_pulse2"] = Ecrit
    ########################################################################
    print_params(params)
    print("")
    params, Z, tau, tau1, tau2, tau3 = build_mesh_fdm(params)
    sketch_frame_transform(params, folder=folder, draw_readout=False)

# Calculate the optimal signal.
if True:
    ########################################################################
    # In xi-space.
    xi0 = calculate_xi0(params)
    Deltaxi = 2/c/tauw
    xi = np.linspace(xi0-4*Deltaxi/2, xi0+4*Deltaxi/2, 1001)

    Gammaxi = calculate_Gammap(params, xi)
    xi, S0xi = calculate_optimal_input_xi(params, xi)
    Sfxi = Gammaxi*S0xi

    # The initial normalization of the xi signal (instead of integrating).
    N0 = c/2
    Nf = num_integral(np.abs(Sfxi)**2, xi)
    eta_ana = Nf/N0

    print("Critical energy: {:.2f} nJ".format(Ecrit*1e9))
    print("Analytic-theory efficiency: {:.4f}".format(eta_ana))

    ########################################################################
    # In Z-space
    Z__, S0Z = calculate_optimal_input_Z(params)
    ########################################################################
    # In tau-space
    tau, S0tau = calculate_optimal_input_tau(params)

# # We calculate the write-in process.
if calculate:
    # NOTE: set analytic_storage to 2 for faster calculation.
    # kwargs = {"plots": True, "folder": folder, "name": "write", "verbose": 0,
    #           "analytic_storage": 1, "S0t": S0tau}
    # tau, Z, Bw, Sw = solve_fdm(params, **kwargs)

    # NOTE: set analytic_storage to 2 for faster calculation.
    kwargs = {"plots": True, "folder": folder, "name": "write", "verbose": 0,
              "analytic_storage": 1, "S0t": S0tau}
    tau, Z, Bw, Sw = solve(params, **kwargs)

# We calculate the read-out process.
if calculate:
    B0_stored = Bw[-1, :]
    # NOTE: set analytic_storage to 2 for faster calculation.
    kwargs = {"plots": True, "folder": folder, "name": "read", "verbose": 0,
              "analytic_storage": 1, "B0z": B0_stored}
    tau, Z, Br, Sr = solve(params, **kwargs)
# We calculate the Beam-splitter picture transmissivities and reflectivities.
if calculate:
    Nt1 = tau1.shape[0]
    S0Z_num = Sw[Nt1-1, :]

    NS = num_integral(np.abs(Sw[:, 0])**2, tau)
    NST = num_integral(np.abs(Sw[:, -1])**2, tau)
    NSR = num_integral(2/c*np.abs(Bw[-1, :])**2, Z)

    NB = num_integral(2/c*np.abs(Br[0, :])**2, Z)
    NBT = num_integral(2/c*np.abs(Br[-1, :])**2, Z)
    NBR = num_integral(np.abs(Sr[:, -1])**2, tau)

    TS = NST/NS
    RS = NSR/NS
    TB = NBT/NB
    RB = NBR/NB

    # RB_naive = 1 - TB
    # RS_naive = 1 - TS
    # print(RS, RS_naive)
    # print(RB, RB_naive)

    Nf = num_integral(np.abs(Sr[:, -1])**2, tau)
    eta_num = Nf/NS
    eta_teo = RS*RB
    assert np.allclose(eta_num, eta_teo)

    print("Numerical efficiency      : {:.4f}".format(eta_num))
    print("Theorical efficiency      : {:.4f}".format(eta_teo))
    print("")
    print("Beam-splitter picture transmissivities and reflectivities:")
    print("TB: {:.4f}, RS: {:.4f}".format(TB, RS))
    print("RB: {:.4f}, TS: {:.4f}".format(RB, TS))
# Save the results.
if calculate:
    dump(params, open(folder+"params.pickle", "wb"))
    dump([tau, Z, Bw, Sw], open(folder+"solution_write.pickle", "wb"))
    dump([tau, Z, Br, Sr], open(folder+"solution_read.pickle", "wb"))
if calculate and plots:
    fs = 15
    ######################################################################
    fig, ax = plt.subplots(2, 1, figsize=(8, 8))
    ax1 = ax[0]
    ax1.xaxis.set_tick_params(labelsize=fs-5)
    ax1.yaxis.set_tick_params(labelsize=fs-5)
    ax2 = ax1.twinx()
    ax2.yaxis.set_tick_params(labelsize=fs-5)

    delay = tau[-1] - tau[0]

    ax1.plot(tau*1e9, np.abs(Sw[:, 0])**2*1e-9, "b-", label="Input")
    ax1.plot(tau*1e9, np.abs(Sw[:, -1])**2*1e-9, "r-", label="Leaked")
    ax1.plot((tau+delay)*1e9, np.abs(Sr[:, -1])**2*1e-9, "g-", label="Output")

    angle1 = np.unwrap(np.angle(Sw[:, 0]))/2/np.pi
    angle2 = np.unwrap(np.angle(Sw[:, -1]))/2/np.pi
    angle3 = np.unwrap(np.angle(Sr[:, -1]))/2/np.pi
    ax2.plot(tau*1e9, angle1, "b:")
    ax2.plot(tau*1e9, angle2, "r:")
    ax2.plot((tau+delay)*1e9, angle3, "g:")

    ax1.set_xlabel(r"$\tau \ [ns]$", fontsize=fs)
    ax1.set_ylabel(r"$|S|^2$  [1/ns]", fontsize=fs)
    ax2.set_ylabel(r"Phase  [revolutions]", fontsize=fs)
    ax1.legend(loc=0, fontsize=fs-5)

    ax[1].plot(Z*100, np.abs(Bw[0, :])**2 * 2/c*1e-2, "b-", label="Input")
    ax[1].plot(Z*100, np.abs(Bw[-1, :])**2 * 2/c*1e-2, "g-", label="Storage")
    ax[1].plot(Z*100, np.abs(Br[-1, :])**2 * 2/c*1e-2, "r-", label="Leakage")
    ax[1].legend(loc=0, fontsize=fs-5)

    ax[1].set_xlabel(r"$Z \ [cm]$", fontsize=fs)
    ax[1].set_ylabel(r"$2|B|^2/c \ [1/cm]$", fontsize=fs)

    plt.savefig(folder+"high_efficiency.png", bbox_inches="tight")
    plt.close()

    ######################################################################

    fig, ax = plt.subplots(1, 1, figsize=(15, 8))
    ax.xaxis.set_tick_params(labelsize=fs-5)
    ax.yaxis.set_tick_params(labelsize=fs-5)
    ax2 = ax.twinx()
    ax2.yaxis.set_tick_params(labelsize=fs-5)

    ax.plot(xi, np.abs(Gammaxi), "k-", label=r"$\Gamma'(\xi)$")
    ax2.plot(xi, np.abs(S0xi), "b-", label=r"$S(\tau=0, \xi)$")
    ax2.plot(xi, np.abs(Sfxi), "g-", label=r"$S(\tau=\tau_f, \xi)$")

    ax.grid(True)
    ax.legend(fontsize=fs, loc=2)
    ax2.legend(fontsize=fs, loc=1)
    ax.set_xlabel(r"$\xi \ [1/m]$", fontsize=fs)
    ax.set_ylabel(r"$F(\xi)$", fontsize=fs)
    ax2.set_ylabel(r"$S(\xi) \ [m]$", fontsize=fs)

    ax.set_xlim(xi[0], xi[-1])

    plt.savefig(folder+"Gamma_xi.png", bbox_inches="tight")
    plt.close()


import requests
from PIL import Image
from io import BytesIO
import os
import json
import uuid

counter = 1
for i in range(6,11):
    filename = "file" + str(i) + ".json"
    with open(filename) as json_file:
        data = json.load(json_file)
        for hit in data["hits"]:
            url = hit["previewURL"]
            r = requests.get(url)
            try:
                i = Image.open(BytesIO(r.content))
                u = uuid.uuid4().hex
                i.save("output/" + str(u) + ".jpg")
            except:
                #woop
                continue


calc_1['Отсутствие мимики'] = np.where(calc_1['Жалобы'].str.lower().str.contains(r'отсутств.+мими.*|наруш.+мими.*', regex=True), 1, 0)

calc_2 = calc_1.melt(id_vars=calc_1.columns[:21],
            value_vars=calc_1.columns[21:],
            var_name='Параметр',
            value_name='Значение')
calc_2 = calc_2.query('Значение == 1')
# display(calc_2.head())
calc_2.groupby('Параметр').agg({"Значение": 'sum',
                                "emias_id": 'nunique'
                               })


import pyautogui
from time import sleep
import logging

x=10
y=12
## Logging configuration
logging.basicConfig(format='%(asctime)s %(message)s')

def load_animation(loading_time=1):
    anim_symbols = ['⣾', '⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽']
    i = 0
    load_count_for_second = len()
    for anim_count in range(64 * loading_time):
        i = (i + 1) % len(symbols)
        print('\r\033[K%s loading...' % anim_symbols[i], flush=True, end='')
        sleep(0.1)

def main():
    while True:
        # Get the current poistion
        mouse_cord = pyautogui.position()
        # Move the mouse cursor to the desired position
        pyautogui.moveTo(x, y)
        # Perform a right-click
        pyautogui.click(button="left")
        logging.warning(f"Mouse left Pos x:{x} y:{y}")
        pyautogui.moveTo(mouse_cord)
        logging.warning(f"Mouse left Pos x:{mouse_cord.x} y:{mouse_cord.y}")
        sleep(200)

try:
    if __name__ == "__main__":
        main()
except KeyboardInterrupt:
    my_choice = input('Do you want to exit (Y/N):')
    if my_choice in ('y', 'Y'):
        print("exiting ......")
        exit()
    main()
finally:
    print("exited from loop")


from pyshell.utils.exception import KeyStoreException
from pyshell.utils.string65 import isString

class CryptographicKey(object):
    KEYTYPE_HEXA = 0
    KEYTYPE_BIT = 1

    def __init__(self, key_string):
        # is it a string ?
        if not isString(key_string):
            raise KeyStoreException("("+self.__class__.__name__+") __init__, "
                                    "invalid key string, expected a string, "
                                    "got '"+str(type(key_string))+"'")

        key_string = key_string.lower()

        # find base
        if key_string.startswith("0x"):
            try:
                int(key_string, 16)
            except ValueError as ve:
                raise KeyStoreException("("+self.__class__.__name__+") "
                                        "__init__, invalid hexa string, start"
                                        " with 0x but is not valid: "+str(ve))

            self.keyType = CryptographicKey.KEYTYPE_HEXA
            self.key = key_string[2:]

            temp_key_size = float(len(key_string) - 2)
            temp_key_size /= 2
            self.keySize = int(temp_key_size)

            if temp_key_size > int(temp_key_size):
                self.keySize += 1
                self.key = "0"+self.key

        elif key_string.startswith("0b"):
            try:
                int(key_string, 2)
            except ValueError as ve:
                raise KeyStoreException("("+self.__class__.__name__+") "
                                        "__init__, invalid binary string, "
                                        "start with 0b but is not valid: " +
                                        str(ve))

            self.keyType = CryptographicKey.KEYTYPE_BIT
            self.key = key_string[2:]
            self.keySize = len(self.key)
        else:
            raise KeyStoreException("("+self.__class__.__name__+") __init__, "
                                    "invalid key string, must start with 0x or"
                                    " 0b, got '"+key_string+"'")

    def __str__(self):
        if self.keyType == CryptographicKey.KEYTYPE_HEXA:
            return "0x"+self.key
        else:
            return "0b"+self.key

    def __repr__(self):
        if self.keyType == CryptographicKey.KEYTYPE_HEXA:
            return ("0x"+self.key+" ( HexaKey, size="+str(self.keySize) +
                    " byte(s))")
        else:
            return ("0b"+self.key+" ( BinaryKey, size="+str(self.keySize) +
                    " bit(s))")

    def getKey(self, start, end=None, padding_enable=True):
        if end is not None and end < start:
            return ()

        # part to extract from key
        if start >= self.keySize:
            if end is None or not padding_enable:
                return ()

            key_part = []
        else:
            limit = self.keySize
            if end is not None and end <= self.keySize:
                limit = end

            key_part = []
            if self.keyType == CryptographicKey.KEYTYPE_HEXA:
                # for b in self.key[start*2:limit*2]:
                for index in range(start*2, limit*2, 2):
                    key_part.append(int(self.key[index:index+2], 16))
            else:
                for b in self.key[start:limit]:
                    key_part.append(int(b, 2))
        # padding part
        if padding_enable and end is not None and end > self.keySize:
            padding_length = end - self.keySize
            if padding_length > 0:
                key_part.extend([0] * padding_length)

        return key_part

    def getKeyType(self):
        return self.keyType

    def getKeySize(self):
        return self.keySize

    def getTypeString(self):
        if self.keyType == CryptographicKey.KEYTYPE_HEXA:
            return "byte"
        else:
            return "bit"

    def __eq__(self, other):
        return (isinstance(other, self.__class__) and
                self.keyType == other.keyType and
                self.key == other.key)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        return hash(str(self.keyType)+self.key)

    def __int__(self):
        if self.keyType == CryptographicKey.KEYTYPE_HEXA:
            return int(self.key, 16)
        else:
            return int(self.key, 2)


#8
from imageio import imread, imwrite
import sys
import numpy as np
import math

def draw(a,b):
    global im, h, w
    if a == b:
        return
    if abs(b[1] - a[1]) > abs(b[0] - a[0]): #x > y
        if a[1] > b[1]:
            a,b = b,a
        k = (b[0] - a[0])/(b[1] - a[1])
        for i in range(b[1] - a[1]):
            x = a[1] + i
            y = round(k*i + a[0])
            if x < 0 or x >= w or y < 0 or y >= h:
                continue
            im[y][x] = (0,0,0)
    else:
        if a[0] > b[0]:
            a,b = b,a
        k = (b[1] - a[1])/(b[0] - a[0])
        for i in range(b[0] - a[0]):
            y = a[0] + i
            x = round(k*i + a[1])
            if x < 0 or x >= w or y < 0 or y >= h:
                continue
            im[y][x] = (0,0,0)

if len(sys.argv) > 2:
    im = imread(sys.argv[1])
else:
    print("err")
    exit()

h = len(im)
w = len(im[0])
print('width = ', w, 'height = ', h)

L = []
for i in range(w):
    for j in range(h):
        if list(im[j][i]) == [0,0,0]:
            L.append((j,i))
center = (h//2,w//2)

for p1 in range(len(L)):
    for p2 in range(len(L)):
        if p1 != p2 and (L[p1][1]-center[1]) == -(L[p2][1]-center[1]) and (L[p1][0]-center[0]) == -(L[p2][0]-center[0]):
            draw(L[p1], L[p2])
im = imwrite(sys.argv[2], im)


"""
Author : Helia Ghorbani
Student ID : 9824353
"""
import pygame

pygame.init()

# declare window size parameters : height, width
winSize = 100
height = winSize * 6
width = height + winSize * 2
# ---------------------------------------------------------
board = []
btnOffset = (winSize * 2) // 3
run = True
pressed = False
number = ''
N = 0
page = 0
isSolved = False
# ---------------------------------------------------------
# colors
BLACK  = (0,0,0)
LIGHTGRAY = (211,211,211)
RED = (255, 0, 0)
TURQUOISE = (64,224,208)
LIGHTCORAL = (240,128,128)
# ---------------------------------------------------------
# set display window size : height, width
window = pygame.display.set_mode((width,height))
pygame.display.set_caption('N-Queens Problem')
# ---------------------------------------------------------
# set display font
titleFont = pygame.font.SysFont('Helvetica', 30, bold=True)
textFont = pygame.font.SysFont('Helvetica', 20, bold=True)
# ---------------------------------------------------------
# set solve button
solveBtn = pygame.Rect(0,0, 100, 50)
solveBtn.center = (width // 2, height // 2 + height // 6)
# ---------------------------------------------------------
# Set previous, next and clear button
prvBtn = pygame.Rect(0, 0, 75, 50)
nxtBtn = pygame.Rect(0, 0, 75, 50)
prvBtn.center = (height + btnOffset - 10, 100)
nxtBtn.center = (height + btnOffset * 2 + 10 ,100)
clrBtn = pygame.Rect(0, 0, 75, 50)
clrBtn.center = (height + (width - height) // 2, height // 2)
# ---------------------------------------------------------
# check left diagonal
def checkLeftDiagonal(arr, row, col):
    x = y = 0
    if row > col:
        x = row - col
        y = 0
    elif col > row:
        x = 0
        y = col - row
    while ((x != len(arr)) and (y != len(arr[0]))):
        if arr[x][y] == 1:
            return False
        x = x + 1
        y = y + 1
    return True
# ---------------------------------------------------------
# check right digonal
def checkRightDiagonal(arr, row, col):
    x = row
    y = col
    while x != 0 and y != len(arr) - 1:
        x = x - 1
        y = y + 1
    while x != len(arr) and y >= 0:
        if arr[x][y] == 1:
            return False
        x = x + 1
        y = y - 1
    return True
# ---------------------------------------------------------
# check vlidation of movement
# check row, column, diagonal
# 1 means full -> False
def validMove(arr, row, col):
    # check row - no other 1 in row
    for i in range(len(arr[0])):
        if arr[row][i]:
            return False
    # check column - no other 1 in column
    for i in range(len(arr[col])):
        if arr[i][col]:
            return False
    # check right and left digonal
    if not (checkRightDiagonal(arr, row, col) and checkLeftDiagonal(arr, row, col)):
        return False
    return True
# ---------------------------------------------------------
# return a copy of input array
def copyArray(arr,N):
    array = initArray(N)
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            array[i][j] = arr[i][j]
    return array
# ---------------------------------------------------------
# find suitable place
# solve recursuvely
def NQueensSolver(arr, col):
    global board
    result = False
    # return true if all queens placed
    if col >= len(arr[0]) :
        board.append(copyArray(arr, len(arr)))
        return True
    # consider this column and place this in all row
    for row in range(len(arr[0])):
        # check can be placed in arr[row][col]
        if validMove(arr, row, col):
            # placed in arr[row][col]
            arr[row][col] = 1
            # possible placement
            result = NQueensSolver(arr, col + 1) or result
            # placing in arr[row][col] doesn't lead to solution
            # remove from arr[row][col]
            # backtrack
            arr[row][col] = 0
    # if can't place in any row false
    return result
# ---------------------------------------------------------
# draw chessboard
def chessboard(N):
    cellSize = height // N
    # set black cells
    for i in range(N):
        for j in range(N):
            if i % 2 == 0 and j % 2 != 0:
                pygame.draw.rect(window, BLACK, (cellSize * i, cellSize * j, cellSize,cellSize ))
            elif i % 2 != 0 and j % 2 == 0:
                pygame.draw.rect(window, BLACK, (cellSize * i, cellSize * j , cellSize, cellSize))
    # draw lines around the board
    pygame.draw.line(window, BLACK, (0, 0), (cellSize * N, 0))
    pygame.draw.line(window,BLACK,(cellSize * N, 0),(cellSize * N, cellSize * N))
# ---------------------------------------------------------
# number of solution
def numOfSol(page, arr):
    # display page number
    string = '{} / {}'
    pageNum = textFont.render(string.format(str(page + 1), str(len(arr))), 1, BLACK)
    # set position of page number
    pagenumRect = pageNum.get_rect()
    pagenumRect.center = (height + (width - height) // 2, 50)
    window.blit(pageNum, pagenumRect)
    # draw pervious, next and clear button on the board
    pygame.draw.rect(window, TURQUOISE, prvBtn)
    pygame.draw.rect(window, TURQUOISE, nxtBtn)
    pygame.draw.rect(window, LIGHTCORAL, clrBtn)
    # set text and position of pervious button
    prv = textFont.render('Previous', 1, BLACK)
    prvRect = prv.get_rect()
    prvRect.center = prvBtn.center
    window.blit(prv, prvRect)
    # set text and position of next button
    nxt = textFont.render('Next', 1, BLACK)
    nxtRect = nxt.get_rect()
    nxtRect.center = nxtBtn.center
    window.blit(nxt, nxtRect)
    # set text and position of clear button
    clear = textFont.render('Clear', 1, BLACK)
    clearRect = clear.get_rect()
    clearRect.center = clrBtn.center
    window.blit(clear, clearRect)
# ---------------------------------------------------------
# fill cell -> put red rect on selected cell
def fillCell(arr, N):
    cellSize = height // N
    queenSize = cellSize // 1.5
    queenOffset = (cellSize - queenSize) // 2
    for row in range(len(arr)):
        for col in range(len(arr[0])):
            if arr[row][col]:
                pygame.draw.rect(window, RED, (col * cellSize + queenOffset, row * cellSize + queenOffset, queenSize, queenSize))
# ---------------------------------------------------------
# make empty N x N matrix
def initArray(N):
    return [[0 for i in range(N)] for j in range(N)]
# ---------------------------------------------------------
# first page - text & button display
def menu():
    # first page - text, position
    text = titleFont.render("Enter number of Queens (at least 4)",1 ,BLACK)
    textRect = text.get_rect()
    textRect.center = (width //2 , height // 2 - height // 6)
    window.blit(text, textRect)
    # draw solve button
    pygame.draw.rect(window, TURQUOISE, solveBtn)
    # set text and position of solve button
    solve = titleFont.render('Solve', 1, BLACK)
    solveTextRect = solve.get_rect()
    solveTextRect.center = (width // 2, height // 2 + height // 6)
    window.blit(solve, solveTextRect)
# ---------------------------------------------------------
# display input number of queens
def num(number):
    # set text and position of number of queens
    inputNum = titleFont.render(number, 1, BLACK)
    inputNumRect = inputNum.get_rect()
    inputNumRect.center = (width //2 , height // 2)
    window.blit(inputNum, inputNumRect)
# ---------------------------------------------------------
# main func
def main():
    global run, pressed, number, isSolved, board, page
    while run:
        # set window background
        window.fill(LIGHTGRAY)
        # no answer for N = 2 & N = 3
        if not pressed or N == 2 or N == 3:
            # display first page
            menu()
            # display input number
            num(number)
            # input is accepted (not 2 or 3)
            pressed = False
        elif N > 3 or N == 1:
            # init N x N empty array
            array = initArray(N)
            # draw N x N chessboard
            chessboard(N)
            # check if solved
            # prevent solving everytime after changing page
            if isSolved:
                NQueensSolver(array, 0)
                isSolved = False
            # fill selected position
            fillCell(board[page], N)
            # display number of solution
            numOfSol(page, board)
        # events : press a key, click
        for event in pygame.event.get():
            # event - press key
            if event.type == pygame.KEYDOWN:
                # press a number
                if event.unicode.isdigit():
                    number += event.unicode
                # press backspace or del
                if event.key == pygame.K_BACKSPACE or event.key == pygame.K_DELETE:
                    number = number[:-1]
            # mouse click
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                x = pos[0]
                y = pos[1]
                # click on solve button
                if solveBtn.collidepoint(x, y) and not pressed:
                    if number != '':
                        N = int(number)
                        number = ''
                        pressed = True
                        isSolved  = True
                # click on prevoius button
                elif prvBtn.collidepoint(x, y) and page > 0:
                    page = page - 1
                # click on next button
                elif nxtBtn.collidepoint(x, y) and page < len(board) - 1:
                    page = page + 1
                # click on clear button - start again
                elif clrBtn.collidepoint(x, y):
                    pressed = False
                    isSolved = False
                    board = []
                    page = 0
            # terminate - close
            elif event.type == pygame.QUIT:
                run = False
        # upadate display
        pygame.display.update()
# ---------------------------------------------------------
# driver
if __name__ == '__main__':
    main()
    pygame.quit()


import pytest

from moona.http import HTTPContext, end
from moona.http.response_headers import (
    auto_content_length,
    content_length,
    content_type,
    content_type_application_json,
    content_type_text_plain,
    header,
)

@pytest.mark.asyncio
@pytest.mark.parametrize(
    "s_name, s_value, b_name, b_value",
    [
        ("Content-Type", "application/json", b"content-type", b"application/json"),
        ("Content-type", "application/json", b"content-type", b"application/json"),
        ("content-type", "application/json", b"content-type", b"application/json"),
    ],
)
async def test_header(ctx: HTTPContext, s_name, s_value, b_name, b_value):
    _ctx = await header(s_name, s_value)(end, ctx)
    assert _ctx.response_headers[b_name] == b_value

@pytest.mark.asyncio
@pytest.mark.parametrize(
    "s_value, b_value",
    [
        ("application/json", b"application/json"),
        ("text/plain", b"text/plain"),
        ("form/multipart", b"form/multipart"),
    ],
)
async def test_content_type(ctx: HTTPContext, s_value, b_value):
    _ctx = await content_type(s_value)(end, ctx)
    assert _ctx.response_headers[b"content-type"] == b_value

@pytest.mark.asyncio
async def test_content_type_application_json(ctx: HTTPContext):
    _ctx = await content_type_application_json(end, ctx)
    assert _ctx.response_headers[b"content-type"] == b"application/json"

@pytest.mark.asyncio
async def test_content_type_text_plain(ctx: HTTPContext):
    _ctx = await content_type_text_plain(end, ctx)
    assert _ctx.response_headers[b"content-type"] == b"text/plain"

@pytest.mark.asyncio
@pytest.mark.parametrize(
    "s_value, b_value",
    [
        (0, b"0"),
        (12, b"12"),
        (2355, b"2355"),
    ],
)
async def test_content_length(ctx: HTTPContext, s_value, b_value):
    _ctx = await content_length(s_value)(end, ctx)
    assert _ctx.response_headers[b"content-length"] == b_value

@pytest.mark.asyncio
@pytest.mark.parametrize(
    "body, length",
    [
        (None, b"0"),
        (b"", b"0"),
        (b"body", b"4"),
    ],
)
async def test_auto_content_length(ctx: HTTPContext, body, length):
    ctx.response_body = body
    _ctx = await auto_content_length(end, ctx)
    assert _ctx.response_headers[b"content-length"] == length


"""Sensor component classes."""

# stdlib
import logging
import math

# external
import astropy.units as unit
import numpy as np
from astropy.units import Quantity

# project
from architect import luts
from architect.luts import LUT
from architect.systems import Component

LOG = logging.getLogger(__name__)

class Sensor(Component):
    """Generic focal plane array sensor component.

    Args:
        dimensions: Dimensions of component bounding box. Elements are ordered as (x, y, z) in the cubesat frame.
        integration_time: Integration time.
        efficiency: Quantum efficiency of the sensor.
        i_dark: Dark current.
        mass: Component mass.
        n_bin: Number of binning operations performed on image aquisition.
        n_bit: Sensor bit depth.
        n_px: Pixel count in the (x, y) dimensions in cubesat frame.
        n_well: Sensor well depth.
        noise_read: Readout noise.
        pitch: Pixel pitch. The distance between the centerpoints of adjacent pixels.
        waveband: Waveband. The range of wavelengths the sensor is able to measure.

    """

    def __init__(
        self,
        dimensions: tuple[Quantity[unit.m], Quantity[unit.m], Quantity[unit.m]] = None,
        integration_time: Quantity[unit.s] = None,
        efficiency: LUT = None,
        i_dark: unit.electron / unit.pix / unit.s = None,
        mass: unit.kg = None,
        n_bin=None,
        n_bit=None,
        n_px: tuple[int, int] = None,
        n_well=None,
        noise_read=None,
        pitch: unit.m = None,
        waveband: unit.m = None,
    ):
        super().__init__(dimensions=dimensions, mass=mass)
        self.integration_time = integration_time
        self.efficiency = efficiency
        self.i_dark = i_dark
        self.n_bin = n_bin
        self.n_bit = n_bit
        self.n_px = n_px
        self.n_well = n_well
        self.noise_read = noise_read
        self.waveband = waveband
        self.pitch = pitch

    def get_pitch(self):
        """Get the pixel pitch."""
        if self.pitch is not None:
            return self.pitch
        else:
            raise ValueError("Pixel pitch not set.")

    def get_n_px(self):
        """Get the pixel count."""
        if self.n_px is not None:
            return self.n_px
        else:
            raise ValueError("Pixel count not set.")

    def get_n_bin(self):
        """Get the number of binning operations."""
        if self.n_bin is not None:
            return self.n_bin
        else:
            raise ValueError("bin is not set.")

    def get_shape(self) -> tuple:
        """Get the dimensions of the sensor face."""
        assert self.n_px is not None, "n_px must be specified."
        assert self.pitch is not None, "Pitch must be specified."

        size = (self.n_px[0] * self.pitch, self.n_px[1] * self.pitch)

        return size

    def get_noise_read(self):
        """Get the noise read."""
        if self.noise_read is not None:
            return self.noise_read
        else:
            raise ValueError("Noise read not set.")

    def get_area(self):
        """Get the area of the sensor face."""

        shape = self.get_shape()

        area = shape[0] * shape[1]

        return area

    def get_pixel_area(self):
        """Get the area of a single detector element (pixel).

        Assumes square pixels.

        """
        assert self.pitch is not None, "Pitch must be specified."

        pixel_area = self.pitch**2

        return pixel_area

    def get_mean_dark_signal(self) -> Quantity[unit.electron / unit.pix]:
        """Get the mean dark signal.

        Ref: https://www.notion.so/utat-ss/Mean-Dark-Signal-55519f6c43654fae9464b578da2965d9

        """
        assert self.i_dark is not None, "i_dark must be specified."
        assert self.integration_time is not None, "Integration time must be specified."

        dark_noise = self.i_dark * self.integration_time

        return dark_noise

    def get_dark_shot_noise(self):
        """Get the dark shot noise.

        Ref: https://www.notion.so/utat-ss/Dark-Shot-Noise-d0632bd2a0444d7eb814beed1224ba06

        """

        dark_shot_noise = np.sqrt(self.get_mean_dark_signal())

        return dark_shot_noise

    def get_quantization_noise(self):
        """Get the quantization noise of the sensor."""
        assert self.n_well is not None, "n_well must be specified."
        assert self.n_bit is not None, "n_bit must be specified."

        quant_noise = (1 / math.sqrt(12)) * self.n_well / 2**self.n_bit.value

        return quant_noise

    def get_noise(self, signal):
        """Get the net noise of the sensor."""
        assert self.n_bin is not None, "n_bin must be specified."
        assert self.noise_read is not None, "noise_read must be specified."

        noise = np.sqrt(
            signal * unit.electron
            + self.n_bin * (self.get_mean_dark_signal() * unit.pix) ** 2
            + self.get_quantization_noise() ** 2
            + self.n_bin * self.noise_read**2
        )

        return noise

    def get_integration_time(self) -> Quantity[unit.s]:
        """Get the integration time."""
        if self.integration_time is not None:
            return self.integration_time
        else:
            raise ValueError("Integration time is not set.")

    def get_efficiency(self, wavelength: Quantity[unit.m]):
        """Get the quantum efficiency of the sensor."""
        if self.efficiency is not None:
            return self.efficiency(wavelength)
        else:
            raise ValueError("Quantum efficiency is not set.")

    def get_waveband(self) -> Quantity[unit.m]:
        """Get the waveband of the sensor."""
        if self.waveband is not None:
            return self.waveband
        else:
            raise ValueError("Waveband is not set.")

class TauSWIR(Sensor):
    """Teledyne FLIR Tau SWIR sensor.

    Ref: https://www.notion.so/utat-ss/FLIR-Tau-SWIR-407ea145ffea4d188c777f3b17a9be2b

    """

    def __init__(self):
        ke = 1e3 * unit.electron
        super().__init__(
            dimensions=(38, 38, 36) * unit.mm,
            integration_time=166.7 * unit.ms,
            efficiency=luts.load("sensors/tauswir_quantum_efficiency"),
            i_dark=140 * (ke / unit.pix / unit.s),
            mass=81 * unit.g,
            n_bin=1 * unit.dimensionless_unscaled,
            n_bit=14 * unit.bit,
            n_px=(640, 512) * unit.pix,
            n_well=19 * ke,
            noise_read=500 * unit.electron,
            pitch=15 * unit.um,
            waveband=800 * unit.nm,
        )


def solution(A):
    # Filter out the negative numbers and zeros
    A = [x for x in A if x > 0]
    N = len(A)

    # Use the list itself as a "hash" of sorts
    for i in range(N):
        # While the number is in the range [1..N] and it's not in its correct position
        while 1 <= A[i] <= N and A[i] != A[A[i] - 1]:
            # Swap it with the number at its expected position
            A[A[i] - 1], A[i] = A[i], A[A[i] - 1]

    # Check for the first number out of place
    for i in range(N):
        if A[i] != i + 1:
            return i + 1

    # If all numbers from 1 to N are present, the answer is N+1
    return N + 1

# Test cases
# print(solution([1, 3, 6, 4, 1, 2]))  # 5
# print(solution([1, 2, 3]))           # 4
# print(solution([-1, -3]))            # 1

A = [1, 3, 6, 4, 1, 2]
# A = [1,2,3]
# A = [-1, -3]

def missingNumber(nums):
    nums = set(sorted(nums))
    expected_sum = len(nums) * (len(nums) + 1) // 2
    actual_sum = sum(nums)
    print(A, expected_sum, actual_sum)
    print(expected_sum - actual_sum)

# missingNumber(A)

def solution(A):
    # Step 1: Filter out non-positive numbers and create a set of positives
    positives = set(x for x in A if x > 0)

    # Step 2: Use range to find the smallest positive integer not in positives
    for i in range(1, len(A) + 2):
        print(i)
        if i not in positives:
            return i

# solution(A = A)

def firstMissingPositive(nums: list[int]) -> int:
    n = len(nums)
    # Base case.
    if 1 not in nums:
        return 1
    # Replace negative numbers, zeros,
    # and numbers larger than n by 1s.
    # After this convertion nums will contain
    # only positive numbers.
    for i in range(n):
        if nums[i] <= 0 or nums[i] > n:
            nums[i] = 1
    # Use index as a hash key and number sign as a presence detector.
    # For example, if nums[1] is negative that means that number `1`
    # is present in the array.
    # If nums[2] is positive - number 2 is missing.
    for i in range(n):
        a = abs(nums[i])
        # If you meet number a in the array - change the sign of a-th element.
        # Be careful with duplicates : do it only once.
        if a == n:
            nums[0] = -abs(nums[0])
        else:
            nums[a] = -abs(nums[a])
    # Now the index of the first positive number
    # is equal to first missing positive.
    for i in range(1, n):
        if nums[i] > 0:
            return i
    if nums[0] > 0:
        return n
    return n + 1

print(firstMissingPositive([1, 3, 6, 4, 1, 2]))  # 5
print(firstMissingPositive([1, 2, 3]))  # 4
print(firstMissingPositive([-1, -3]))  # 1

def firstMissingPositive(nums):
    """
    :type nums: List[int]
    :rtype: int
     Basic idea:
    1. for any array whose length is l, the first missing positive must be in range [1,...,l+1],
        so we only have to care about those elements in this range and remove the rest.
    2. we can use the array index as the hash to restore the frequency of each number within
         the range [1,...,l+1]
    """
    nums.append(0)
    n = len(nums)
    for i in range(len(nums)):  # delete those useless elements
        if nums[i] < 0 or nums[i] >= n:
            nums[i] = 0
    for i in range(
        len(nums)
    ):  # use the index as the hash to record the frequency of each number
        nums[nums[i] % n] += n
    for i in range(1, len(nums)):
        if nums[i] / n == 0:
            return i
    return n

print(firstMissingPositive([1, 3, 6, 4, 1, 2]))  # 5
print(firstMissingPositive([1, 2, 3]))  # 4
print(firstMissingPositive([-1, -3]))  # 1


import os
import re
import urllib.request
import requests
import time
import sys
from requests_html import HTML
from bs4 import BeautifulSoup

requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += ':RC4-SHA'

overall_user_push={}
overall_user_boo={}
overall_image_url=[]
overall_keyword_image_url=[]
def fetch(url):
    time.sleep(0.4)
    response=requests.get(url=url,cookies={'over18':'1'})
    if response.status_code != 200:  #回傳200代表正常
        print('Invalid url:', response.url)
        return None
    else:
        return response

def article(content,counter):
    output_all_file = open("all_articles.txt", "a",encoding='utf8')
    output_popular_file = open("all_popular.txt", "a",encoding='utf8')

    fixed='https://www.ptt.cc'
    end_flag=0
    soup=BeautifulSoup(content,'html.parser')
    all_page_elements=soup.find('div','btn-group btn-group-paging')
    all_meta_data_divs=soup.find_all('div','r-ent')
    post_page=all_page_elements.find_all('a')[2]['href']

    for meta_data in all_meta_data_divs:
        if meta_data.find('a'):
            push_information=meta_data.find('div','nrec').string
            hyper_link=fixed+meta_data.find('a')['href']
            title=meta_data.find('a').string
            dates=int(meta_data.find("div", {"class": "date"}).string.strip().replace('/',''))
            if title!=None and len(title)>3:
                classification=title[1:3]
                title=title.replace(',',' ')
            if hyper_link!=None and title!=None and dates!=None and len(title)>3 and classification!=None and classification!="公告":
                if counter==0:
                    if dates<800:
                        output_all_file.write(str(dates)+","+str(title)+","+str(hyper_link)+"\n")
                        if push_information!=None and push_information=="爆":
                            output_popular_file.write(str(dates)+","+str(title)+","+str(hyper_link)+"\n")
                elif counter>100 and dates<105:
                    end_flag=1
                    return end_flag,None
                else:
                    output_all_file.write(str(dates)+","+str(title)+","+str(hyper_link)+"\n")
                    if push_information!=None and push_information=="爆":
                        output_popular_file.write(str(dates)+","+str(title)+","+str(hyper_link)+"\n")

    output_all_file.close()
    return end_flag,fixed+post_page
def like_boo_count(content):
    likes=0
    boos=0
    soup=BeautifulSoup(content,'html.parser')
    all_meta_data_divs=soup.find_all('div','push')
    for meta_data in all_meta_data_divs:
        if meta_data.find('span', 'push-tag') and meta_data.find('span','push-userid'):
            information = meta_data.find('span', 'push-tag').string.strip(' \t\n\r')
            user_name=meta_data.find('span','push-userid').string.strip(' \t\n\r')
            current_item=[]
            if information=="推":
                likes+=1
                if user_name not in overall_user_push:
                    overall_user_push[user_name]=1
                else:
                    overall_user_push[user_name]+=1

            elif information=="噓":
                boos+=1
                current_item.append(user_name)
                current_item.append("boo")
                if user_name not in overall_user_boo:
                    overall_user_boo[user_name]=1
                else:
                    overall_user_boo[user_name]+=1
    return likes,boos
def get_image_url(content):
    pattern=re.compile("^(http).*((\.jpg)|(\.jpeg)|(\.png)|(\.gif))$")

    soup=BeautifulSoup(content,'html.parser')
    all_meta_data_divs=soup.find_all('a')
    for meta_data in all_meta_data_divs:
        current_url=meta_data.string
        if current_url!=None:
            match_result=pattern.match(current_url)

            if match_result:
                overall_image_url.append(current_url)
def get_keyword_image_url(content):
    pattern=re.compile("^(http).*((\.jpg)|(\.jpeg)|(\.png)|(\.gif))$")

    soup=BeautifulSoup(content,'html.parser')
    all_meta_data_divs=soup.find_all('a')
    for meta_data in all_meta_data_divs:
        current_url=meta_data.string
        if current_url!=None:
            match_result=pattern.match(current_url)

            if match_result:
                overall_keyword_image_url.append(current_url)
def check_keyword(content,keyword):
    pattern=re.compile("^[ ]*(<){1}")
    overall_results=[]
    find_start_result=content.find("作者")
    find_end_result=content.find("<span class=\"f2\">")
    if find_start_result==-1 or find_end_result==-1:
        return False
    total_string=content[find_start_result:find_end_result]
    soup=BeautifulSoup(total_string,'html.parser')
    total_result=soup.prettify()
    overall_strings=total_result.split('\n')
    for current_string in overall_strings:
        match_result=pattern.match(current_string)
        if not match_result:
            overall_results.append(current_string)

    for current_result in overall_results:#剩這裡
        if current_result.find(keyword)!=-1:
            #print(current_result,keyword)
            return True
    #print(total_string)
    #print(find_start_result,find_end_result)

    return False
if __name__=='__main__':
    if len(sys.argv)<2:
        print("No command line input argument found, please look at the readme file.")
    choice=sys.argv[1]
    if choice=="crawl":
        tStart = time.time()
        if os.path.exists("all_articles.txt"):
            os.remove("all_articles.txt")
        if os.path.exists("all_popular.txt"):
            os.remove("all_popular.txt")
        end_flag=0
        current_url='https://www.ptt.cc/bbs/Beauty/index3150.html' #3150至今
        current_response=fetch(current_url)
        counter=0
        if current_response!=None:
            contents=current_response.text
            if contents!=None:
                end_flag,post_page=article(contents,counter)
                counter+=1
                while post_page!=None and end_flag==0:
                    current_response=fetch(post_page)
                    contents=current_response.text
                    end_flag,post_page=article(contents,counter)
                    counter+=1
        tEnd=time.time()
        print(tEnd-tStart)
    elif choice=="push":
        if len(sys.argv)<4:
            print("Too less command line input arguments! Start_date and end_date are required.")
        start_date=int(sys.argv[2])
        end_date=int(sys.argv[3])

        tStart = time.time()

        like_counter=0
        boo_counter=0
        file_name="push["+str(start_date)+"-"+str(end_date)+"].txt"

        if os.path.exists(file_name):
            os.remove(file_name)

        output_result_file=open(file_name,"a",encoding='utf8')

        with open("all_articles.txt",encoding='utf8') as f:
            content=f.readlines()
        overall_date=[]
        overall_title=[]
        overall_url=[]

        flag_start=0
        flag_end=0
        start_index=-1
        end_index=-1

        for i in range(0,len(content)):
            temp_line=content[i].split(',')
            overall_date.append(temp_line[0])
            overall_title.append(temp_line[1])
            overall_url.append(temp_line[2].replace('\n',''))

        for i in range(0,len(content)):
            if flag_start==0 and int(overall_date[i])>=start_date:
                start_index=i
                flag_start=1
            if int(overall_date[i])==end_date:
                end_index=i
            if flag_end==0 and end_index==-1 and int(overall_date[i])>end_date:
                end_index=i-1
                flag_end=1

        for i in range(start_index,end_index+1):
            response=fetch(overall_url[i])
            if response!=None:
                article_content=response.text
                likes,boos=like_boo_count(article_content)
                like_counter+=likes
                boo_counter+=boos

        overall_user_push=sorted(overall_user_push.items(), key=lambda kv: kv[0])
        overall_user_boo=sorted(overall_user_boo.items(), key=lambda kv: kv[0])
        overall_user_push=sorted(overall_user_push, key=lambda kv: kv[1],reverse=True)
        overall_user_boo=sorted(overall_user_boo, key=lambda kv: kv[1],reverse=True)

        output_result_file.write("all like: "+str(like_counter)+"\n")
        output_result_file.write("all boo: "+str(boo_counter)+"\n")

        for i in range(0,10):
            output_result_file.write("like #"+str(i+1)+": "+str(overall_user_push[i][0])+" "+str(overall_user_push[i][1])+"\n")

        for i in range(0,10):
            output_result_file.write("boo #"+str(i+1)+": "+str(overall_user_boo[i][0])+" "+str(overall_user_boo[i][1])+"\n")

        output_result_file.close()
        tEnd=time.time()
        print(tEnd-tStart)
    elif choice=="popular":
        if len(sys.argv)<4:
            print("Too less command line input arguments! Start_date and end_date are required.")
        start_date=int(sys.argv[2])
        end_date=int(sys.argv[3])

        tStart = time.time()
        popular_counter=0

        file_name="popular["+str(start_date)+"-"+str(end_date)+"].txt"

        if os.path.exists(file_name):
            os.remove(file_name)

        output_result_file=open(file_name,"a",encoding='utf8')

        with open("all_popular.txt",encoding='utf8') as f:
            content=f.readlines()

        overall_date=[]
        overall_title=[]
        overall_url=[]

        flag_start=0
        flag_end=0
        start_index=-1
        end_index=-1

        for i in range(0,len(content)):
            temp_line=content[i].split(',')
            overall_date.append(temp_line[0])
            overall_title.append(temp_line[1])
            overall_url.append(temp_line[2].replace('\n',''))

        for i in range(0,len(content)):
            if flag_start==0 and int(overall_date[i])>=start_date:
                start_index=i
                flag_start=1
            if int(overall_date[i])==end_date:
                end_index=i
            if flag_end==0 and end_index==-1 and int(overall_date[i])>end_date:
                end_index=i-1
                flag_end=1

        popular_counter=end_index-start_index+1

        for i in range(start_index,end_index+1):
            response=fetch(overall_url[i])
            if response!=None:
                article_content=response.text
                get_image_url(article_content)

        output_result_file.write("number of popular articles: "+str(popular_counter)+"\n")
        for i in range(0,len(overall_image_url)):
            output_result_file.write(overall_image_url[i]+"\n")
        output_result_file.close()
        tEnd=time.time()
        print(tEnd-tStart)
    elif choice=="keyword":
        if len(sys.argv)<5:
            print("Too less command line input arguments! Keyword, start_date and end_date are required.")
        keyword=sys.argv[2]
        start_date=int(sys.argv[3])
        end_date=int(sys.argv[4])

        keyword="正妹"
        start_date=505
        end_date=1101

        tStart = time.time()

        file_name="keyword("+keyword+")["+str(start_date)+"-"+str(end_date)+"].txt"

        if os.path.exists(file_name):
            os.remove(file_name)

        output_result_file=open(file_name,"a",encoding='utf8')

        with open("all_articles.txt",encoding='utf8') as f:
            content=f.readlines()

        overall_date=[]
        overall_title=[]
        overall_url=[]

        flag_start=0
        flag_end=0
        start_index=-1
        end_index=-1

        for i in range(0,len(content)):
            temp_line=content[i].split(',')
            overall_date.append(temp_line[0])
            overall_title.append(temp_line[1])
            overall_url.append(temp_line[2].replace('\n',''))

        for i in range(0,len(content)):
            if flag_start==0 and int(overall_date[i])>=start_date:
                start_index=i
                flag_start=1
            if int(overall_date[i])==end_date:
                end_index=i
            if flag_end==0 and end_index==-1 and int(overall_date[i])>end_date:
                end_index=i-1
                flag_end=1

        for i in range(start_index,end_index+1):
            response=fetch(overall_url[i])
            if response!=None:
                article_content=response.text

                find_keyword=check_keyword(article_content,keyword)
                if find_keyword:
                    get_keyword_image_url(article_content)

        for i in range(0,len(overall_keyword_image_url)):
            output_result_file.write(overall_keyword_image_url[i]+"\n")
        output_result_file.close()
        tEnd=time.time()
        print(tEnd-tStart)


from django.urls import path
from . import views

urlpatterns = [

    path('', views.home, name="dashboard"),
    path('product/', views.ProductDetails, name='product_details'),
    path('create_product/', views.CreateProduct, name='product_create'),
    path('update_product/<str:pk>/', views.UpdateProduct, name='update_product'),
    path('delete_product/<str:pk>/', views.DeleteProduct, name='delete_product'),
    path('tag_details/', views.TagsDetails, name="tag_details"),
    path('create_tag/', views.CreateTags, name='create_tag'),
    path('update_tag/<str:pk>/', views.UpdateTags, name='update_tag'),
    path('delete_tag/<str:pk>/', views.DeleteTags, name='delete_tag'),
    path('customer_details/<str:pk>/', views.CustomerDetails, name='customer_details'),
    path('create_customer/', views.CreateCustomer, name='Create_customer'),
    path('update_customer/<str:pk>/', views.UpdateCustomer, name='update_customer'),
    path('delete_customer/<str:pk>/', views.DeleteCustomer, name='delete_customer'),
]


from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import *
from .forms import *
from django.conf import settings
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from django.db.models import Sum
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import CustomerSerializer
from decimal import *
from django.http import HttpResponse, HttpResponseNotFound
from django.views.generic import View
from django.contrib.auth.models import User
from django.template.loader import get_template
from .fusioncharts import FusionCharts
from portfolio.utils import render_to_pdf
# email
from django.core.files.storage import FileSystemStorage
from django.core.mail import send_mail
from django.core.mail import EmailMessage

now = timezone.now()

def home(request):
    return render(request, 'portfolio/home.html',
                  {'portfolio': home})

def register(request):
    print("entered into register view method")
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request,
                          'registration/registerdone.html',
                          {'form': form})
    else:
        form = RegisterForm()
    return render(request, "registration/register.html", {"form": form})

@login_required
def customer_list(request):
    customer = Customer.objects.filter(created_date__lte=timezone.now())
    return render(request, 'portfolio/customer_list.html', {'customers': customer})

@login_required
def customer_edit(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    if request.method == "POST":
        # update
        form = CustomerForm(request.POST, instance=customer)
        if form.is_valid():
            customer = form.save(commit=False)
            customer.updated_date = timezone.now()
            customer.save()
            customer = Customer.objects.filter(created_date__lte=timezone.now())
            return render(request, 'portfolio/customer_list.html', {'customers': customer})
    else:
        # edit
        form = CustomerForm(instance=customer)
    return render(request, 'portfolio/customer_edit.html', {'form': form})

@login_required
def customer_delete(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    customer.delete()
    return redirect('portfolio:customer_list')

@login_required
def stock_list(request):
    stocks = Stock.objects.filter(purchase_date__lte=timezone.now())
    return render(request, 'portfolio/stock_list.html', {'stocks': stocks})

@login_required
def stock_new(request):
    if request.method == "POST":
        form = StockForm(request.POST)
        if form.is_valid():
            stock = form.save(commit=False)
            stock.created_date = timezone.now()
            stock.save()
            stocks = Stock.objects.filter(purchase_date__lte=timezone.now())
            return render(request, 'portfolio/stock_list.html',
                          {'stocks': stocks})
    else:
        form = StockForm()
        # print("Else")
    return render(request, 'portfolio/stock_new.html', {'form': form})

@login_required
def stock_edit(request, pk):
    stock = get_object_or_404(Stock, pk=pk)
    if request.method == "POST":
        form = StockForm(request.POST, instance=stock)
        if form.is_valid():
            stock = form.save()
            # stock.customer = stock.id
            stock.updated_date = timezone.now()
            stock.save()
            stocks = Stock.objects.filter(purchase_date__lte=timezone.now())
            return render(request, 'portfolio/stock_list.html', {'stocks': stocks})
    else:
        # print("else")
        form = StockForm(instance=stock)
    return render(request, 'portfolio/stock_edit.html', {'form': form})

@login_required
def stock_delete(request, pk):
    stock = get_object_or_404(Stock, pk=pk)
    stock.delete()
    return redirect('portfolio:stock_list')

@login_required
def investment_list(request):
    investments = Investment.objects.filter(recent_date__lte=timezone.now())
    return render(request, 'portfolio/investment_list.html', {'investments': investments})

@login_required
def investment_new(request):
    if request.method == "POST":
        form = InvestmentForm(request.POST)
        if form.is_valid():
            investment = form.save(commit=False)
            investment.created_date = timezone.now()
            investment.save()
            investments = Investment.objects.filter(recent_date__lte=timezone.now())
            return render(request, 'portfolio/investment_list.html',
                          {'investments': investments})
    else:
        form = InvestmentForm()
        # print("Else")
    return render(request, 'portfolio/investment_new.html', {'form': form})

@login_required
def investment_edit(request, pk):
    investment = get_object_or_404(Investment, pk=pk)
    if request.method == "POST":
        form = InvestmentForm(request.POST, instance=investment)
        if form.is_valid():
            investment = form.save()
            # investment.customer = investment.id
            investment.updated_date = timezone.now()
            investment.save()
            investments = Investment.objects.filter(recent_date__lte=timezone.now())
            return render(request, 'portfolio/investment_list.html', {'investments': investments})
    else:
        # print("else")
        form = InvestmentForm(instance=investment)
    return render(request, 'portfolio/investment_edit.html', {'form': form})

@login_required
def investment_delete(request, pk):
    investment = get_object_or_404(Investment, pk=pk)
    investment.delete()
    return redirect('portfolio:investment_list')

@login_required
def portfolio(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    customers = Customer.objects.filter(created_date__lte=timezone.now())
    investments = Investment.objects.filter(customer=pk)
    stocks = Stock.objects.filter(customer=pk)

    sum_recent_value = Investment.objects.filter(customer=pk).aggregate(Sum('recent_value'))
    # print("sum_recent_value: " + str(sum_recent_value))

    sum_acquired_value = Investment.objects.filter(customer=pk).aggregate(Sum('acquired_value'))
    # print("sum_acquired_value: " + str(sum_acquired_value))

    # overall_investment_results = sum_recent_value - sum_acquired_value
    overall_investment_results = sum_recent_value['recent_value__sum'] - sum_acquired_value['acquired_value__sum']
    # overall_investment_results = Decimal(sum_recent_value['recent_value__sum']) - Decimal(sum_acquired_value['acquired_value__sum'])
    # print(" overall_investment_results:" + str(overall_investment_results))

    # Initialize the value of the stocks
    sum_current_stocks_value = 0
    sum_of_initial_stock_value = 0

    # Loop through each stock and add the value to the total
    for stock in stocks:
        sum_current_stocks_value += stock.current_stock_value()
        # print(type((stock.current_stock_value())))
        sum_of_initial_stock_value += stock.initial_stock_value()
        # print(type(int(stock.initial_stock_value())))

    overall_stocks_results = Decimal(sum_current_stocks_value) - Decimal(sum_of_initial_stock_value)
    # print(overall_stocks_results)

    return render(request, 'portfolio/customer_portfolio.html', {'customers': customer,
                                                                 'investments': investments,
                                                                 'stocks': stocks,
                                                                 'sum_acquired_value': sum_acquired_value[
                                                                     'acquired_value__sum'],
                                                                 'sum_recent_value': sum_recent_value[
                                                                     'recent_value__sum'],
                                                                 'sum_current_stocks_value': sum_current_stocks_value,
                                                                 'sum_of_initial_stock_value': sum_of_initial_stock_value,
                                                                 'overall_investment_results': overall_investment_results,
                                                                 'overall_stocks_results': overall_stocks_results, })

# List at the end of the views.py
# Lists all customers
class CustomerList(APIView):
    def get(self, request):
        customers_json = Customer.objects.all()
        serializer = CustomerSerializer(customers_json, many=True)
        return Response(serializer.data)

@login_required()
def portfolio_pdf(request, pk):
    template = get_template('portfolio/customer_portfolio_pdf.html')
    customer = get_object_or_404(Customer, pk=pk)
    customers = Customer.objects.filter(created_date__lte=timezone.now())
    investments = Investment.objects.filter(customer=pk)
    stocks = Stock.objects.filter(customer=pk)

    sum_recent_value = Investment.objects.filter(customer=pk).aggregate(Sum('recent_value'))
    print("sum_recent_value: " + str(sum_recent_value))
    sum_acquired_value = Investment.objects.filter(customer=pk).aggregate(Sum('acquired_value'))
    print("sum_acquired_value: " + str(sum_acquired_value))
    overall_investment_results = sum_recent_value['recent_value__sum'] - sum_acquired_value['acquired_value__sum']
    print(" overall_investment_results:" + str(overall_investment_results))
    # Initialize the value of the stocks
    sum_current_stocks_value = 0
    sum_of_initial_stock_value = 0

    # Loop through each stock and add the value to the total
    for stock in stocks:
        sum_current_stocks_value += stock.current_stock_value()
        print(type((stock.current_stock_value())))
        print("sum_current_stocks_value " + str(sum_current_stocks_value))
        sum_of_initial_stock_value += stock.initial_stock_value()
        print(type(int(stock.initial_stock_value())))
        print("sum_of_initial_stock_value " + str(sum_of_initial_stock_value))

        overall_stocks_results = float(sum_current_stocks_value) - float(sum_of_initial_stock_value)
        print("overall_stocks_results" + str(overall_stocks_results))
        context = {'customers': customer,
                   'investments': investments,
                   'stocks': stocks,
                   'sum_acquired_value': sum_acquired_value['acquired_value__sum'],
                   'sum_recent_value': sum_recent_value['recent_value__sum'],
                   'sum_current_stocks_value': sum_current_stocks_value,
                   'sum_of_initial_stock_value': sum_of_initial_stock_value,
                   'overall_investment_results': overall_investment_results,
                   'overall_stocks_results': overall_stocks_results,
                   }
        html = template.render(context)
        pdf = render_to_pdf('portfolio/customer_portfolio_pdf.html', context)
        if pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            filename = 'Portfolio_' + str(customer.name) + '.pdf'
            content = "inline; filename='%s'" % filename
            download = request.GET.get("download")
            if download:
                content = "attachment; filename='%s'" % filename
                response['Content-Disposition'] = content
            return response
        return HttpResponseNotFound("not found")

@login_required
def generate_portfolio_pdf(request, pk, context):
    customer = get_object_or_404(Customer, pk=pk)
    template = get_template('portfolio/customer_portfolio_pdf.html')

    html = template.render(context)
    pdf = render_to_pdf('portfolio/customer_portfolio_pdf.html', context)
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'filename= "Portfolio_{}.pdf"'.format(customer.name)
        # return response
        # return HttpResponse(pdf, content_type='application/octet-stream')
        return pdf
    return HttpResponse("Not Found")

def email(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    print(customer)
    if request.method == "POST":
        form = EmailForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.published_date = timezone.now()
            post.save()
            email = request.POST.get('email')
            subject = request.POST.get('subject')
            message = request.POST.get('message')
            document = request.FILES.get('document')
            email_from = 'admin@efs.com'
            recipient_list = [email]
            email = EmailMessage(subject, message, email_from, recipient_list)
            base_dir = '/Users/rajeshkumarpanigrahi/Downloads/'
            email.attach_file('/Users/rajeshkumarpanigrahi/Downloads/' + str(document))
            email.send()
            return render(request, 'portfolio/sent.html')
    else:
        form = EmailForm()

    return render(request, 'portfolio/email.html', {'form': form})

def summary(request, pk):
    investments = Investment.objects.filter(customer=pk)
    stocks = Stock.objects.filter(customer=pk)
    customers = get_object_or_404(Customer, pk=pk)
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Stock Details",
        "subCaption": "EFS",
        "xAxisName": "Stock",
        "yAxisName": "Value (In USD)",
        "numberPrefix": "$",
        "theme": "zune"
    }

    # The data for the chart should be in an array where each element of the array is a JSON object
    # having the `label` and `value` as key value pair.
    dataSource['categories'] = []
    categories = {}
    categories['category'] = []

    for stock_name in stocks:
        category = {}
        category['label'] = stock_name.name
        print(category)
        categories['category'].append(category)

    dataSource['categories'].append(categories)
    dataSource['dataset'] = []
    seriesname = {}
    seriesname['seriesname'] = 'Initial value'
    seriesname['data'] = []
    for key in stocks:
        data = {}
        # data['label'] = key.name
        data['value'] = float(key.initial_stock_value())
        seriesname['data'].append(data)

    dataSource['dataset'].append(seriesname)

    seriesname_1 = {}
    seriesname_1['seriesname'] = 'Current value'
    seriesname_1['data'] = []
    for key in stocks:
        data = {}
        # data['label'] = key.name
        data['value'] = float(key.current_stock_value())
        seriesname_1['data'].append(data)

    dataSource['dataset'].append(seriesname_1)

    print('datasource', str(dataSource))

    dataSource_1 = {}
    dataSource_1['chart'] = {
        "caption": "Investment Details",
        "subCaption": "EFS",
        "xAxisName": "Investment",
        "yAxisName": "Value (In USD)",
        "numberPrefix": "$",
        "theme": "fusion"
    }

    # The data for the chart should be in an array where each element of the array is a JSON object
    # having the `label` and `value` as key value pair.
    dataSource_1['categories'] = []
    categories = {}
    categories['category'] = []

    for invest_name in investments:
        category = {}
        category['label'] = invest_name.category
        categories['category'].append(category)

    dataSource_1['categories'].append(categories)
    dataSource_1['dataset'] = []
    seriesname = {}
    seriesname['seriesname'] = 'Acquired value'
    seriesname['data'] = []
    for key in investments:
        data = {}
        # data['label'] = key.name
        data['value'] = float(key.acquired_value)
        seriesname['data'].append(data)

    dataSource_1['dataset'].append(seriesname)

    seriesname_1 = {}
    seriesname_1['seriesname'] = 'Recent value'
    seriesname_1['data'] = []
    for key in investments:
        data = {}
        # data['label'] = key.name
        data['value'] = float(key.recent_value)
        seriesname_1['data'].append(data)

    dataSource_1['dataset'].append(seriesname_1)

    print('dataSource_1', str(dataSource_1))

    sum_current_stocks_value = 0
    sum_of_initial_stock_value = 0
    for stock in stocks:
        # print('1...', stock.result_by_stock(stock.current_stock_value(), stock.initial_stock_value()))
        sum_current_stocks_value += stock.current_stock_value()
        sum_of_initial_stock_value += stock.initial_stock_value()

    total_stock_result = round((float(sum_current_stocks_value) - float(sum_of_initial_stock_value)), 2)
    sum_acquired_value = Investment.objects.filter(customer=pk).aggregate(Sum('acquired_value')).get(
        'acquired_value__sum', 0.00)
    sum_recent_value = Investment.objects.filter(customer=pk).aggregate(Sum('recent_value')).get('recent_value__sum',
                                                                                0.00)
    total_invest_result = sum_recent_value - sum_acquired_value
    portfolio_result = float(total_invest_result) + float(total_stock_result)

    dataSource_2 = {
        "chart": {
            "caption": "Split of portfolio result by stock and investment",
            "subCaption": "",
            "numberPrefix": "$",
            "showPercentInTooltip": "0",
            "decimals": "1",
            "useDataPlotColorForLabels": "1",
            "theme": "fusion"
        },
        "data": [
            {
                "label": "Stock",
                "value": float(total_stock_result)
            },
            {
                "label": "Investment",
                "value": float(total_invest_result)
            }
        ]
    }
    print('dataSource_2', str(dataSource_2))
    # Create an object for the Column 2D chart using the FusionCharts class constructor
    # column2D = FusionCharts("column2D", "ex1" , "600", "350", "chart-1", "json", dataSource)
    mscolumn2d = FusionCharts("mscolumn2d", "ex1", "600", "350", "chart-1", "json", dataSource)
    viewchart2 = FusionCharts("mscolumn2d", "ex2", "600", "350", "chart-2", "json", dataSource_1)
    viewchart3 = FusionCharts("pie2d", "chart-container", "550", "350", "chart-3", "json", dataSource_2)

    return render(request, 'portfolio/customer_summary.html', {'output': mscolumn2d.render(),
                                                               'output2': viewchart2.render(),
                                                               'output3': viewchart3.render(),
                                                               'customers': customers})


# -*- encoding: utf-8 -*-
import os
import zmq
import yaml
import core.framer
import core.loader
import zmq.eventloop
import zmq.eventloop.zmqstream
import multiprocessing

'''
Create a basic Actor that can take requests
from a Publisher and spawn processes to perform
the actions
'''

CONFIG_LOCATION = '/home/mp/devel/eventdrivetalk/conf/demo_actor.yml'

class Actor(object):
    def __init__(self, opts=None):
        if opts is None:
            self.opts = self.process_config(CONFIG_LOCATION)
        else:
            self.opts = opts

        # Start setting up ZeroMQ
        self.ctx = zmq.Context()
        self.socket = self.ctx.socket(zmq.SUB)

        self.socket.connect('tcp://localhost:2000')

        self.loop = zmq.eventloop.IOLoop.instance()
        self.stream = zmq.eventloop.zmqstream.ZMQStream(self.socket, self.loop)
        self.stream.on_recv(act)

        # Load up actions
        self.actions = loader.load_actions(self.opts, '/home/mp/devel/eventdrivetalk/actions')

    def start(self):
        print('Starting Actor')
        try:
            self.loop.start()
        except KeyboardInterrupt:
            self.stream.close()
            self.loop.stop()
            print('Shut down!')

    def process_config(self, config_location):
        if not os.path.exists(config_location):
            print('WARNING: No config file was found at {0}'.format(config_location))
            return {}
        else:
            try:
                fh_ = open(config_location)
                config = yaml.load(fh_)
            finally:
                fh_close()
            return config

    def act(self, msg):
        '''
        Take a received event and act on it
        '''
        event = framer.unpack(msg)
        action = event['tag'].split().pop()

        # Obviously, we'd normally do some sort of host checking
        # and auth so this is ridiculous but this is just for fun!
        #
        # Blind trust ahoy! ;]
        mp = multiprocessing.Process(target=self._act_target, args=(action))

    def _act_target(self,  action):
        # Perform the action!
        self.actions[action]()


import json
import boto3
import uuid
import requests

dynamodb = boto3.resource('dynamodb', region_name="us-east-1")
table = dynamodb.Table("TourBookingTable")

def lambda_handler(event, context):
    response = json.loads(event['body'])
    booking_id = str(uuid.uuid4())

    if response['user_id'] != "":
        table.put_item(Item= {'booking_number': booking_id, 'no_of_people': response['no_of_people'], 'price': int(response['price'])* int(response['no_of_people']), 'tour_name': response['tour_name'] , 'user_id': response['user_id']})
        statusCode = 200
        message = 'Tour with package name '  + response['tour_name'] + ' booked successfully for ' + str(response['no_of_people']) + ' people'
    else:
        statusCode = 400
        message = 'Tour could not be booked. Please try again!'
    result1 = {"message": message, "booking_number":booking_id,"price": int(response['price'])* int(response['no_of_people'])}
    result = {"message": message, "user_id": response["user_id"]}
    url = "https://us-central1-csci5410-project-355011.cloudfunctions.net/pubsub-publisher"
    x = requests.post(url, json = result)

    res = {'statusCode':  statusCode, 'body': json.dumps(result1), 'headers':  {'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*'}}
    return res


#!/usr/bin/python

import face_recognition
import cv2

video_path = "resources/short_hamilton_clip.mp4"
input_movie = cv2.VideoCapture(video_path)
count = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
height = int(input_movie.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(input_movie.get(cv2.CAP_PROP_FRAME_WIDTH))

print("Video:{} is {}*{} with frame number:{}".format(video_path, width, height, count))

fourcc = cv2.VideoWriter_fourcc(*"XVID")
cv2.VideoWriter()
output_movie = cv2.VideoWriter('/tmp/output.avi', fourcc, 29.97, (width, height))

face_locations = []
frame_number = 0

while True:
    # Grab a single frame of video
    ret, frame = input_movie.read()
    frame_number += 1

    # Quit when the input video file endsz
    if not ret:
        break

    # print(ret)
    # print(len(frame[0]))

    # Convert the image from BGR color (which OpenCV uses) to RGB color
    # (which face_recognition uses)
    rgb_frame = frame[:, :, ::-1]
    # Find all the faces and face encodings in the current frame of video
    face_locations = face_recognition.face_locations(rgb_frame, model="cnn")
    # face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    for (top, right, bottom, left) in face_locations:
        # Draw a box around the face
        cv2.rectangle
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

    output_movie.write(frame)
    print("完成度:{}/{}, 含有face数量:{}".format(frame_number, count, len(face_locations)))

# All done!
input_movie.release()
cv2.destroyAllWindows()


import sys
#@lint-avoid-python-3-compatibility-imports

def get_words(parse):
    return [w.strip(")")
            for w in parse.split()
            if w[-1] == ')']

for l in open(sys.argv[1]):
    splits = l.strip().split("\t")
    if len(splits) != 4:
        continue
    title_parse, article_parse, title, article = splits
    title_words = title.split()
    article_words = article.split()

    # No blanks.
    if any((word == "" for word in title_words)):
        continue

    if any((word == "" for word in article_words)):
        continue

    if not any((word == "." for word in article_words)):
        continue

    # Spurious words to blacklist.
    # First set is words that never appear in input and output
    # Second set is punctuation and non-title words.
    bad_words = ['update#', 'update', 'recasts', 'undated', 'grafs', 'corrects',
                 'retransmitting', 'updates', 'dateline', 'writethru',
                 'recaps', 'inserts', 'incorporates', 'adv##',
                 'ld-writethru', 'djlfx', 'edits', 'byline',
                 'repetition', 'background', 'thruout', 'quotes',
                 'attention', 'ny###', 'overline', 'embargoed', 'ap', 'gmt',
                 'adds', 'embargo',
                 'urgent', '?', ' i ', ' : ', ' - ', ' by ', '-lrb-', '-rrb-']
    if any((bad in title.lower()
            for bad in bad_words)):
        continue

    # Reasonable lengths
    if not (10 < len(article_words) < 100 and
            3 < len(title_words) < 50):
        continue

    # Some word match.
    matches = len(set([w.lower() for w in title_words if len(w) > 3]) &
                  set([w.lower() for w in article_words if len(w) > 3]))
    if matches < 1:
        continue

    # Okay, print.
    print(l.strip())


#!/usr/bin/env python3

import sys,math,lhepgen

data = []
m_targ,m_meson = 0.939565420,0.1349767

Q2,xb = 1.75, 0.36
with open(sys.argv[1]) as ff:
  for line in ff:
    lls = line.split()
    mtp = float(lls[0])
    st,sl,stt,slt = [float(ll) for ll in lls[1::5]]
    dst,dsl,dstt,dslt = [float(ll) for ll in lls[2::5]]

    tmin = abs(lhepgen.getTmin(Q2,xb))

    mt = mtp + tmin

    out = ["{:.2f}".format(vv) for vv in [Q2,xb,Q2,xb]]
    out += ["{:.5f}".format(mt)]
    out += ["{:.4f}".format(vv*1000) for vv in [st,dst,0,slt,dslt,0,stt,dstt,0]]
    out += ["0"]
    print("\t".join(out))


import os
import time

import jetson.inference
import jetson.utils

import cv2
import requests
import threading
import numpy as np
from imutils.video import FPS

from utils import gstreamer_pipeline, check_thread_alive, send_picture, calculate_vote
from alpr import detect_plate,accum_vote

delay=10

arr=[]
detection=0

cap_width=1920
cap_height=1080

net = jetson.inference.detectNet("ssd-mobilenet-v2", threshold=0.5)

def detect(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA).astype(np.float32)
    img = jetson.utils.cudaFromNumpy(img)
    detections = net.Detect(img, 1280, 720)
    img = jetson.utils.cudaToNumpy(img, 1280, 720, 4)
    img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR).astype(np.uint8)
    return img, detections

def clear_arr():
    global arr
    global detection
    time.sleep(8)
    detection=0
    arr=[]

def get_bbox(detection):
    num=detection.ClassID
    x1,y1,x2,y2=[int(i) for i in detection.ROI]
    return  num,x1,y1,x2,y2

def main():
    global arr
    global detection
    cap = cv2.VideoCapture(gstreamer_pipeline(capture_width=cap_width,capture_height=cap_height,flip_method=2), cv2.CAP_GSTREAMER)
    #cap = cv2.VideoCapture('../video-test2.mp4')
    if cap.isOpened():
        window_handle = cv2.namedWindow("frame", cv2.WINDOW_AUTOSIZE)

        fps_i=None
        empty_frame=0

        th = threading.Thread(target=send_picture, args=(None,None,delay))
        th.start()

        while cv2.getWindowProperty("frame", 0) >= 0:
            fps=FPS().start()

            ret_val, img = cap.read()

            frame = img.copy()
            img,detections=detect(img)

            #print("# detected : ",len(detections))

            for i in range(len(detections)):
                num,x1,y1,x2,y2=get_bbox(detections[i])

                if num in [3,4,6,8]:
                    detection=detection+1
                    crop = frame[y1:y2,x1:x2]
                    results=detect_plate(crop)
                    #print(results)

                    if results['results']:
                        arr=accum_vote(results['results'],arr)

                cv2.rectangle(frame,(x1,y1),(x2,y2),(255,0,0),4)

            if detection>=10:
                detection=0
                if not check_thread_alive(th):
                    results,arr=calculate_vote(arr)
                    th = threading.Thread(target=send_picture, args=(frame,results,delay))
                    cl = threading.Thread(target=clear_arr)
                    th.start()
                    cl.start()
                else:
                    pass

            cv2.imshow("frame", img)

            if fps_i is None:
                fps_i=0

            fps.update()
            fps.stop()
            fps_i=fps.fps()

            #print("FPS: {:.2f}".format(fps.fps()))

            keyCode = cv2.waitKey(30) & 0xFF
            if keyCode == 27:
                break

        cap.release()
        cv2.destroyAllWindows()
    else:
        print("Unable to open camera")

if __name__ == "__main__":
    main()


import uvicorn
from fastapi import FastAPI

from core.config import WEB_PORT, WEB_HOST
from db.base import database
from endpoints import author, books

app = FastAPI(title="MY_APP")
app.include_router(author.router, prefix="/author", tags=["author"])
app.include_router(books.router, prefix="/books", tags=["books"])

@app.on_event("startup")
async def startup():
    await database.connect()

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

if __name__ == "__main__":
    uvicorn.run("main:app", port=int(WEB_PORT), host=WEB_HOST, reload=True)


import sys
import argparse

from postcrypt import Postcrypt

def create_arg_parser():
    parser = argparse.ArgumentParser(description='Postcrypt HTTP scripts')

    parser.add_argument('crypt', type=str, help='Scrypt to run')
    parser.add_argument('mode', type=str, nargs='?', help='Optional scrypt mode')
    parser.add_argument('--verbose', action='store_true', help='Enable verbose mode')
    parser.add_argument('--save', action='store_true', help='Remember input values')

    return parser

if __name__ == '__main__':
    args = create_arg_parser().parse_args()
    postcrypt = Postcrypt(args.crypt, mode=args.mode, verbose=args.verbose, save=args.save)
    postcrypt.make_default()
    postcrypt.process()


from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI

from toontown.hood import ZoneUtil
from toontown.hood.GSHoodDataAI import GSHoodDataAI
from toontown.hood.TTHoodDataAI import TTHoodDataAI
from toontown.toonbase import ToontownGlobals

class WelcomeValleyManagerAI(DistributedObjectAI):
    notify = DirectNotifyGlobal.directNotify.newCategory('WelcomeValleyManagerAI')

    def requestZoneIdMessage(self, zoneId, context):
        avId = self.air.getAvatarIdFromSender()
        if zoneId == 0:
            zoneId = ToontownGlobals.WelcomeValleyBegin

        self.toonSetZone(avId, zoneId)
        self.sendUpdateToAvatarId(avId, 'requestZoneIdResponse', [zoneId, context])

    def toonSetZone(self, doId, zoneId):
        event = self.staticGetLogicalZoneChangeEvent(doId)
        inWelcomeValley = self.isAccepting(event)
        if not ZoneUtil.isDynamicZone(zoneId):
            if ZoneUtil.isWelcomeValley(zoneId) and not inWelcomeValley:
                self.air.districtStats.b_setNewAvatarCount(self.air.districtStats.getNewAvatarCount() + 1)
                self.accept(event, lambda newZoneId, _: self.toonSetZone(doId, newZoneId))
                self.accept(self.air.getAvatarExitEvent(doId), self.toonSetZone,
                            extraArgs=[doId, ToontownGlobals.ToontownCentral])
            elif (not ZoneUtil.isWelcomeValley(zoneId)) and inWelcomeValley:
                self.air.districtStats.b_setNewAvatarCount(self.air.districtStats.getNewAvatarCount() - 1)
                self.ignore(event)
                self.ignore(self.air.getAvatarExitEvent(doId))

    def createWelcomeValleyZones(self):
        self.notify.info('Creating Welcome Valley zones...')

        # Toontown Central
        self.air.generateHood(TTHoodDataAI, 22000)

        # Goofy Speedway
        self.air.generateHood(GSHoodDataAI, 23000)


"""Write a stream of close approaches to CSV or to JSON.

This module exports two functions: `write_to_csv` and `write_to_json`, each of
which accept an `results` stream of close approaches and a path to which to
write the data.

These functions are invoked by the main module with the output of the `limit`
function and the filename supplied by the user at the command line. The file's
extension determines which of these functions is used.

You'll edit this file in Part 4.
"""
import csv
import json
from helpers import transform_to_str, datetime_to_str

def transform_result_for_csv_writing(results):
    """
    Transform approach objects to list of lists (only including necessary fields for csv).

    :param results: An iterrator of queried approaches
    :return: A list of approach data for csv writing
    """
    fieldkeys = [
        "time",
        "distance",
        "velocity",
        "_designation",
        "name",
        "diameter",
        "hazardous",
    ]
    outlist = list()
    for approach in list(results):
        unpacked_dict = unpack_approach(approach)
        outlist.append([transform_to_str(unpacked_dict[fkey]) for fkey in fieldkeys])

    return outlist

def write_to_csv(results, filename):
    """Write an iterable of `CloseApproach` objects to a CSV file.

    The precise output specification is in `README.md`. Roughly, each output row
    corresponds to the information in a single close approach from the `results`
    stream and its associated near-Earth object.

    :param results: An iterable of `CloseApproach` objects.
    :param filename: A Path-like object pointing to where the data should be saved.
    """
    fieldnames = (
        "datetime_utc",
        "distance_au",
        "velocity_km_s",
        "designation",
        "name",
        "diameter_km",
        "potentially_hazardous",
    )

    outlist = transform_result_for_csv_writing(results)

    with open(filename, "w") as f:
        write = csv.writer(f)
        write.writerow(fieldnames)
        write.writerows(outlist)

    return

def unpack_approach(approach):
    """Unpack approach object into dictionary.

    :param approach:Approach object.
    :return: Dictionary with approach keys and values.
    """
    return {**approach.__dict__, **approach.__dict__["neo"].__dict__}

def get_dict_for_json_mapping():
    """Return required fields for json output and corresponding key in approach and neo object.

    :return: Dictionary for lookup of required json fields.
    """
    return {
        "datetime_utc": "time",
        "distance_au": "distance",
        "velocity_km_s": "velocity",
        "designation": "designation",
        "name": "name",
        "diameter_km": "diameter",
        "potentially_hazardous": "hazardous",
    }

def approach_vars():
    """Return variables that are part of approach object (and not neo) and needed for json output.

    :return: List of json output coming from approach object.
    """
    return ["datetime_utc", "distance_au", "velocity_km_s"]

def transform_approaches_to_list_of_dicts(approaches, keymap_dict, approach_vars):
    """Transform approaches collection to list of dictionaries to be dumped into json.

    :param approaches: Collection of approach objects
    :param keymap_dict: Function that returns how to lookup required fields
    :param approach_vars: List of elements indicating which fields belong to approach object
    :return: List of results that should be written to json file
    """
    resultlist = list()
    for approach in approaches:
        unpacked_approach = unpack_approach(approach)
        approachdict = {"neo": {}}
        for key, lookup_val in keymap_dict.items():
            if key in ["datetime_utc"]:
                value = datetime_to_str(unpacked_approach[lookup_val])
            elif key in ["designation", "name"]:
                value = transform_to_str(unpacked_approach[lookup_val])
            elif key in ["distance_au", "velocity_km_s", "diameter_km"]:
                value = float(unpacked_approach[lookup_val])
            elif key in ["potentially_hazardous"]:
                value = bool(unpacked_approach[lookup_val])
            else:
                raise RuntimeError("unexpected_key")
            if key in approach_vars:
                approachdict[key] = value
            else:
                approachdict["neo"][key] = value
        resultlist.append(approachdict)
    return resultlist

def write_to_json(results, filename):
    """Write an iterable of `CloseApproach` objects to a JSON file.

    The precise output specification is in `README.md`. Roughly, the output is a
    list containing dictionaries, each mapping `CloseApproach` attributes to
    their values and the 'neo' key mapping to a dictionary of the associated
    NEO's attributes.

    :param results: An iterable of `CloseApproach` objects.
    :param filename: A Path-like object pointing to where the data should be saved.
    """
    resultlist = transform_approaches_to_list_of_dicts(
        results, get_dict_for_json_mapping(), approach_vars()
    )
    with open(filename, "w") as file:
        json.dump(resultlist, file)
    return


from approxeng.task import task, TASKS, resource, RESOURCES, register_resource, run, TaskException
import logging
import cachetools.func
from time import sleep

LOG = logging.getLogger('demo')

logging.basicConfig(level=logging.INFO)

@resource(name='list_resource')
def bar():
    return ['a', 'b', 'c']

register_resource('string_resource', 'a value')

@resource(name='dep_test_resource')
def foo(list_resource):
    return list(reversed(list_resource))

@task(name='first_task')
def root(dep_test_resource, task_count):
    sleep(0.1)
    LOG.info(task_count)
    LOG.info(dep_test_resource)
    if task_count > 2:
        return 'second_task'

@task
def second_task(string_resource):
    LOG.info('Ooh, a string "%s", too exciting, sleeping for a bit', string_resource)
    # LOG.info(world._dict)
    sleep(0.5)
    raise Exception("foo")

LOG.info(TASKS)
LOG.info(RESOURCES)

run(root_task='first_task', raise_exceptions=False)


__author__ = 'zhangxa'

import sys
from concurrent import futures

import yaml
import motor

import tornado.ioloop
import tornado.web
import tornado.options

import controller.base

tornado.options.define("port", default=8765, help="Run server on a specific port", type=int)
tornado.options.define("host", default="localhost", help="Run server on a specific host")
tornado.options.define("url", default=None, help="Url to show in HTML")
tornado.options.define("config", default="./config.yaml", help="config file's full path")
tornado.options.parse_command_line()

if not tornado.options.options.url:
	tornado.options.options.url = "http://%s:%d" % (tornado.options.options.host, tornado.options.options.port)

settings = {
	"base_url": tornado.options.options.url,
    "template_path": "templates",
    "static_path": "static",
    "config_filename": tornado.options.options.config,
    "compress_response": True,
	"default_handler_class": controller.base.NotFoundHandler,
	"xsrf_cookies": True,
	"static_path": "static",
	"download": "./download",
	"session": {
		"driver": "redis",
		"driver_settings": {
			"host": "localhost",
			"port": 6379,
			"db": 1
		},
		"force_persistence": False,
		"cache_driver": True,
		"cookie_config": {
			"httponly": True
		},
	},
	"thread_pool": futures.ThreadPoolExecutor(4),
	"debug":True
}

class MainHandler(controller.base.BaseHandler):
    def get(self):
        self.render("main.htm")

def make_app():
    return tornado.web.Application([
        (r"/",MainHandler),
        (r"^/category/(.*?)/(.*)", "controller.bootstrap.HomeHandler"),
        (r"^/admin/(.*)", "controller.admin.AdminHandler")
    ],**settings)

def init_settings():
    config = {}
    try:
        with open(settings["config_filename"], "r") as fin:
            config = yaml.load(fin)
        if "session" in config:
            settings["session"]["driver_settings"] = config["session"]
    except Exception as e:
        print("cannot found config.yaml file",e)
        sys.exit(0)

# mongodb connection
# format: mongodb://user:pass@host:port/
# database name: minos

    try:
        client = motor.MotorClient(config["database"]["config"])
        database = client[config["database"]["db"]]
        settings["database"] = database
    except:
        print("cannot connect mongodb, check the config.yaml")
        sys.exit(0)

if __name__ == "__main__":
    init_settings()
    #print(settings)
    app = make_app()
    app.listen(tornado.options.options.port)
    tornado.ioloop.IOLoop.current().start()