import logging
import os

import numpy as np
import tensorflow as tf

from controller.mpc import MPC
from train_pinn import ManipulatorInformedNN
from utils.data import load_ref_trajectory, load_data
from utils.plotting import plot_input_sequence, plot_states, plot_absolute_error, animate
from utils.system import f

if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)
    logging.getLogger('matplotlib').setLevel(logging.WARNING)

    logging.info("TensorFlow version: {}".format(tf.version.VERSION))
    logging.info("Eager execution: {}".format(tf.executing_eagerly()))

    # Paths
    resources_path = os.path.join('../resources')
    data_path = os.path.join(resources_path, 'data.npz')
    weights_path = os.path.join('../resources/weights')

    lb, ub, input_dim, output_dim, _, _, _, _ = load_data(data_path)

    # Hyper parameter
    N_l = 4
    N_n = 64
    layers = [input_dim, *N_l * [N_n], output_dim]

    logging.info('MPC parameters:')
    H = 5
    logging.info(f'\tH:\t{H}')
    u_ub = np.array([0.5, 0.5])
    u_lb = - u_ub

    X_ref, T_ref = load_ref_trajectory(resources_path)

    x0 = X_ref[0]
    T_ref = T_ref[:-H, 0]

    tau = T_ref[1] - T_ref[0]
    logging.info(f'\ttau:\t{tau}')

    # Initialization
    pinn = ManipulatorInformedNN(layers, lb, ub)
    # Load pretrained weights
    pinn.load_weights(weights_path)

    controller = MPC(f, pinn.model, u_ub=u_ub, u_lb=u_lb,
                     t_sample=tau, H=H,
                     Q=tf.linalg.tensor_diag(tf.constant([1, 1, 0, 0], dtype=tf.float64)),
                     R=1e-6 * tf.eye(2, dtype=tf.float64))

    # Testing self loop prediction
    H_sl = 20

    # Generate self loop prediction input sequence
    U1_sl = 0.5 * np.sin(np.linspace(0, 2 * np.pi, H_sl))
    U2_sl = - U1_sl
    U_sl = np.hstack((U1_sl[:, np.newaxis], U2_sl[:, np.newaxis]))

    # Initial state
    x0_sl = np.zeros(4)

    # Simulate plant system
    X_ref_sl = controller.sim_open_loop_plant(x0_sl, U_sl,
                                              t_sample=tau,
                                              H=H_sl)

    # Simulate PINN system
    X_sl = controller.sim_open_loop(x0_sl, U_sl,
                                    t_sample=tau,
                                    H=H_sl)

    T_sl = np.arange(0., H_sl * tau + tau, tau)
    plot_input_sequence(T_sl, U=np.vstack((U_sl, U_sl[-1:, :])))
    plot_states(T_sl, X_ref_sl, X_sl)
    plot_absolute_error(T_sl, X_ref_sl, X_sl)

    # Testing closed loop
    X_mpc, U_mpc, X_pred = controller.sim(x0, X_ref, T_ref)

    plot_input_sequence(T_ref, U_mpc)
    plot_states(T_ref, X_ref[:-H], Z_mpc=X_mpc)
    plot_absolute_error(T_ref, X_ref[:-H], Z_mpc=X_mpc)
    animate(X_ref[:-H], [X_mpc], ['MPC'], fps=1 / tau)


class Solution:
    def isMajorityElement(self, nums: List[int], target: int) -> bool:
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = left + (right - left) // 2

            if nums[mid] >= target:
                right = mid - 1
            else:
                left = mid + 1
        return left + len(nums) // 2 < len(nums) and target == nums[left + len(nums) // 2]


from argparse import ArgumentParser, Namespace
from copy import deepcopy

import torch

from fedavg import FedAvgServer, get_fedavg_argparser
from src.client.fedfomo import FedFomoClient

def get_fedfomo_argparser() -> ArgumentParser:
    parser = get_fedavg_argparser()
    parser.add_argument("--M", type=int, default=5)
    parser.add_argument("--valset_ratio", type=float, default=0.2)
    return parser

class FedFomoServer(FedAvgServer):
    def __init__(
        self,
        algo: str = "FedFomo",
        args: Namespace = None,
        unique_model=True,
        default_trainer=False,
    ):
        if args is None:
            args = get_fedfomo_argparser().parse_args()
        super().__init__(algo, args, unique_model, default_trainer)
        self.trainer = FedFomoClient(
            deepcopy(self.model), self.args, self.logger, self.device, self.client_num
        )
        self.P = torch.eye(self.client_num, device=self.device)

    def train_one_round(self):
        client_params_cache = []
        for client_id in self.selected_clients:
            selected_params = self.generate_client_params(client_id)

            (
                client_params,
                weight_vector,
                self.client_stats[client_id][self.current_epoch],
            ) = self.trainer.train(
                client_id=client_id,
                local_epoch=self.clients_local_epoch[client_id],
                received_params=selected_params,
                verbose=((self.current_epoch + 1) % self.args.verbose_gap) == 0,
            )

            client_params_cache.append(client_params)
            self.P[client_id] += weight_vector

        self.update_client_params(client_params_cache)

    @torch.no_grad()
    def generate_client_params(self, client_id):
        prev_round_clients = self.client_sample_stream[self.current_epoch - 1]
        selected_params = {}
        if not self.test_flag and self.current_epoch > 0:
            selected_params = {
                prev_round_clients[i]: self.client_trainable_params[
                    prev_round_clients[i]
                ]
                for i in torch.topk(
                    self.P[client_id][prev_round_clients], self.args.M
                ).indices.tolist()
            }
        selected_params[client_id] = self.client_trainable_params[client_id]
        return selected_params

if __name__ == "__main__":
    server = FedFomoServer()
    server.run()


###
# Solution: dp with state compression
# we consider the opposite problem, how to choose K column to make the row contains 1 minimum
# let f(S, k) represents if we can select k column to reach the 1 state to be S (a binary base representation,
# for example, 01001 denotes the second-row and fifth-row contains 1, but another three rows donot.
# then in the t-th iteration (t is the column number, s_t is the t-th column's state representation),
# f(S|s_t, k) is true if f(S, k-1) or f(S|s_t, k) is true
###

from typing import List
class Solution:
    def lowbit(self, n):
        return n & (-n)

    def one_nums(self, n):
        _sum = 0
        while n > 0:
            n -= self.lowbit(n)
            _sum += 1
        return _sum

    def maximumRows(self, mat: List[List[int]], cols: int) -> int:
        m, n = len(mat), len(mat[0])
        k = n - cols
        SSIZE = 1 << m
        fs = [[False for _ in range(k+1)] for __ in range(SSIZE)]
        fs[0][0] = True
        statuss = []
        for j in range(n):
            _status = 0
            for i in range(m):
                _status = _status * 2 + mat[i][j]
            statuss.append(_status)

        for _status in statuss:
            for j in range(k-1, -1, -1):
                for i in range(SSIZE):
                    if fs[i][j]:
                        fs[i | _status][j+1] = True

        min_ones = m
        for i in range(SSIZE):
            if fs[i][k]:
                min_ones = min(min_ones, self.one_nums(i))
        return m - min_ones

mat = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]]
cols = 2
print(Solution().maximumRows(mat, cols))


"""
    @author: Vo Nguyen Thien Nhan
"""

## REMEMBER TO COMMENT 3 LINES BEFORE SUBMIT ##
from ast import expr
from main.d96.utils.AST import *
from main.d96.checker.StaticCheck import *
from main.d96.checker.StaticError import *
## REMEMBER TO COMMENT 3 LINES BEFORE SUBMIT ##

from Emitter import Emitter
from Frame import Frame
from abc import ABC, abstractmethod
from CodeGenError import *

class Attribute:
    def __init__(self, name, type, is_static, init_value=None):
        self.name = name
        self.type = type
        self.is_static = is_static
        self.init_value = init_value

class Method:
    def __init__(self, name, type, is_static):
        self.name = name
        self.type = type
        self.is_static = is_static

class Local:
    def __init__(self, name, type, index):
        self.name = name
        self.type = type
        self.index = index

class Enviroment:
    def __init__(self, global_env={}, local_env=[{}]):
        self.global_env = global_env
        self.local_env = local_env

    def visit_class(self, class_name):
        self.global_env[class_name] = ComponentClass()

    def visit_scope(self):
        self.local_env = [{}] + \
            self.local_env if self.local_env is not None else [{}]

    def exit_scope(self):
        self.local_env.pop(0)

    def add_local(self, local_id, local_type):
        self.local_env[0][local_id] = local_type

    def add_attribute(self, class_name, attribute_name, attribute_type):
        return self.global_env[class_name].add_attribute(
            attribute_name, attribute_type
        )

    def add_method(self, class_name, method_name, method_type):
        return self.global_env[class_name].add_method(method_name, method_type)

    def lookup_local(self, id):
        for local_scope in self.local_env:
            if id in local_scope:
                return local_scope[id]
        return None

    def lookup_attribute(self, class_name, attribute_name):
        return self.global_env[class_name].lookup_attribute(attribute_name)

    def lookup_method(self, class_name, method_name):
        return self.global_env[class_name].lookup_method(method_name)

    def copy(self):
        return Enviroment(self.global_env, self.local_env.copy())

class ComponentClass:
    def __init__(self, attribute={}, method={}):
        self.attribute = attribute
        self.method = method

    def add_attribute(self, attribute_name, attribute_type):
        self.attribute[attribute_name] = attribute_type

    def lookup_attribute(self, attribute_name):
        if attribute_name in self.attribute:
            return self.attribute[attribute_name]
        return None

    def add_method(self, method_name, method_type):
        self.method[method_name] = method_type

    def lookup_method(self, method_name):
        if method_name in self.method:
            return self.method[method_name]
        return None

class MType:
    def __init__(self, partype, rettype):
        self.partype = partype
        self.rettype = rettype

class SubBody:
    def __init__(self, frame, env):
        self.frame = frame
        self.env = env

class Access:
    def __init__(self, frame, env, is_left, is_first):
        self.frame = frame
        self.env = env
        self.is_left = is_left
        self.is_first = is_first

class Val(ABC):
    pass

class Index(Val):
    def __init__(self, value):
        # value: Int
        self.value = value

# class Class_name(Val):
#     def __init__(self, value, si_kind=None):
#         # value: String
#         self.value = value
#         self.si_kind = si_kind

class CodeGenerator:

    def __init__(self):
        self.lib_name = "io"

    def init(self):
        global_env = {
            self.lib_name: ComponentClass(
                {},
                {
                    "getInt":       Method("getInt", MType([], IntType()), True),
                    "putInt":       Method("putInt", MType([IntType()], VoidType()), True),
                    "putIntLn":     Method("putIntLn", MType([IntType()], VoidType()), True),
                    "getBool":      Method("getBool", MType([], BoolType()), True),
                    "putBool":      Method("putBool", MType([BoolType()], VoidType()), True),
                    "putBoolLn":    Method("putBoolLn", MType([BoolType()], VoidType()), True),
                    "putString":    Method("putString", MType([StringType()], VoidType()), True),
                    "putStringLn":  Method("putStringLn", MType([StringType()], VoidType()), True),
                    "getFloat":     Method("getFloat", MType([], FloatType()), True),
                    "putFloat":     Method("putFloat", MType([FloatType()], VoidType()), True),
                    "putFloatLn":   Method("putFloatLn", MType([FloatType()], VoidType()), True),
                    "putLn":        Method("putLn", MType([], VoidType()), True),
                },
            )
        }
        return Enviroment(global_env, None)

    def gen(self, ast, dir_):
        # ast: AST
        # dir_: String
        env = self.init()
        global_codegen = CodeGenVisitor(ast, env, dir_)
        global_codegen.visit(ast, None)

class CodeGenVisitor(BaseVisitor):
    def __init__(self, ast, env, dir_):
        self.ast = ast
        self.env = env
        self.path = dir_
        self.current_class = None
        self.parent_class = None
        self.instance_attr_list = None
        self.static_attr_list = None
        self.current_method = None      # for return type
        self.emit = None

    def visitProgram(self, ast, o):
        for each_class in ast.decl:
            self.visit(each_class, self.env)

    def visitClassDecl(self, ast, o):
        classname = ast.classname.name
        memList = ast.memlist
        parentname = ast.parentname.name if ast.parentname else "java/lang/Object"

        o.visit_class(classname)
        self.current_class = classname
        self.parent_class = parentname
        self.instance_attr_list = []
        self.static_attr_list = []
        self.emit = Emitter(self.path + "/" + self.current_class + ".j")

        self.emit.printout(self.emit.emitPROLOG(classname, parentname))

        # get attributes and methods
        constructor = None
        check_default_constructor = False
        attr_list = []
        method_list = []
        for mem in memList:
            if isinstance(mem, AttributeDecl):
                attr_list += [mem]
            if isinstance(mem, MethodDecl):
                if mem.name.name == 'Constructor':
                    constructor = mem
                    if len(mem.param) == 0:     check_default_constructor = True
                else:
                    method_list += [mem]

        # visit attributes
        for each_attr in attr_list:
            self.visit(each_attr, o)

        # visit constructor
        if constructor:
            self.visit(constructor, o)
        if check_default_constructor == False:
            o.visit_scope()
            frame = Frame("<init>", VoidType())
            self.gen_method(
                MethodDecl(Instance(), Id("<init>"), [], Block([])),
                SubBody(frame, o),
                frame,
            )
        o.exit_scope()
        o.visit_scope()
        frame = Frame("<clinit>", VoidType())
        self.gen_method(
            MethodDecl(Static(), Id("<clinit>"), [], Block([])),
            SubBody(frame, o),
            frame,
        )
        o.exit_scope()

        # visit methods
        for each_method in method_list:
            self.visit(each_method, o)

        self.emit.emitEPILOG()

    def visitAttributeDecl(self, ast, o):
        kind = ast.kind
        decl = ast.decl

        name, type_data, init_value = None, None, None
        check_static = True if isinstance(kind, Static) else False
        check_constant = False
        if isinstance(decl, VarDecl):
            name, type_data, init_value = decl.variable.name, decl.varType, decl.varInit if decl.varInit else None
        else:
            name, type_data, init_value = decl.constant.name, decl.constType, decl.value if decl.value else None
            check_constant = True

        if check_static:
            self.emit.printout(self.emit.emitSTATIC(name, type_data, check_constant, init_value))
        else:
            self.emit.printout(self.emit.emitINSTANCE(name, type_data, check_constant, init_value))

        new_attr = Attribute(name, type_data, check_static, init_value)
        self.static_attr_list.append(new_attr) if check_static else self.instance_attr_list.append(new_attr)
        o.add_attribute(self.current_class, name, new_attr)

    def visitMethodDecl(self, ast, o):
        kind = ast.kind
        name = ast.name.name
        params = ast.param

        if name == 'Constructor':
            ast.name.name = '<init>'
            name = '<init>'
        check_static = True if isinstance(kind, Static) else False
        frame = Frame(name, None)
        o.visit_scope()
        self.gen_method(ast, SubBody(frame, o), frame)
        o.add_method(self.current_class, name, Method(name, MType([para.varType for para in params], self.current_method), check_static))
        o.exit_scope()

    def gen_method(self, method_ast, o, frame):
        kind = method_ast.kind
        name = method_ast.name.name
        params = method_ast.param
        body = method_ast.body

        self.current_method = None
        code = ""
        check_main = True if (name == 'main' and len(params) == 0) else False
        check_static = True if (isinstance(kind, Static) or check_main) else False
        par_type = [ArrayType(0, StringType())] if check_main else [para.varType for para in params]

        frame.enterScope(True)
        # generate variable for method
        if name == '<init>' or not check_static:
            idx = frame.getNewIndex()
            code += self.emit.emitVAR(idx, "this", ClassType(Id(self.current_class)), frame.getStartLabel(), frame.getEndLabel(), frame)
        elif check_main:
            idx = frame.getNewIndex()
            code += self.emit.emitVAR(idx, "args", ArrayType(0, StringType()), frame.getStartLabel(), frame.getEndLabel(), frame)
        # visit parameters
        for para in params:
            code += self.visit(para, o)
        # label of method
        code += self.emit.emitLABEL(frame.getStartLabel(), frame)
        if name == '<init>':
            code += self.emit.emitTHIS(frame)
            code += self.emit.emitINVOKESPECIAL(frame, self.parent_class + "/<init>", MType([], VoidType()))
            for each_attr in self.instance_attr_list:
                if each_attr.init_value is None:
                    continue
                code += self.emit.emitTHIS(frame)
                init_code, init_type = self.visit(each_attr.init_value, Access(frame, self.env, False, False))
                if isinstance(each_attr.type, FloatType) and isinstance(init_type, IntType):
                    init_code += self.emit.emitI2F(o.frame)
                code += init_code
                code += self.emit.emitPUTFIELD(self.current_class + "." + each_attr.name, each_attr.type, frame)
        elif name == "<clinit>":
            for each_attr in self.static_attr_list:
                if each_attr.init_value is None:
                    continue
                init_code, init_type = self.visit(each_attr.init_value, Access(frame, self.env, False, False))
                if isinstance(each_attr.type, FloatType) and isinstance(init_type, IntType):
                    init_code += self.emit.emitI2F(o.frame)
                code += init_code
                code += self.emit.emitPUTSTATIC(self.current_class + "." + each_attr.name, each_attr.type, frame)
        # visit body method
        for inst in body.inst:
            code += self.visit(inst, o)
        if self.current_method is None:
            self.current_method = VoidType()
        # generate label of method after know return type
        mtype = MType(par_type, self.current_method)
        code = self.emit.emitMETHOD(name, mtype, check_static, frame) + code
        code += self.emit.emitLABEL(frame.getEndLabel(), frame)
        # generate end method
        if isinstance(self.current_method, VoidType):
            code += self.emit.emitRETURN(VoidType(), frame)
        code += self.emit.emitENDMETHOD(frame)
        self.emit.printout(code)
        frame.exitScope()

    def visitVarDecl(self, ast, o):
        idx = o.frame.getNewIndex()
        o.env.add_local(ast.variable.name, Local(ast.variable.name, ast.varType, idx))
        code = ""
        code += self.emit.emitVAR(idx, ast.variable.name, ast.varType, o.frame.getStartLabel(), o.frame.getEndLabel(), o.frame)
        code += self.visit(Assign(ast.variable, ast.varInit), o) if ast.varInit else ""
        return code

    def visitConstDecl(self, ast, o):
        idx = o.frame.getNewIndex()
        o.env.add_local(ast.constant.name, Local(ast.constant.name, ast.constType, idx))
        code = ""
        code += self.emit.emitVAR(idx, ast.constant.name, ast.constType, o.frame.getStartLabel(), o.frame.getEndLabel(), o.frame)
        code += self.visit(Assign(ast.constant, ast.value), o) if ast.value else ""
        return code

    def visitUnaryOp(self, ast, o):
        code, type_data = self.visit(ast.body, o)
        if ast.op == "-":   return code + self.emit.emitNEGOP(type_data, o.frame), type_data
        return code + self.emit.emitNOT(type_data, o.frame), type_data

    def visitBinaryOp(self, ast, o):
        op = ast.op
        left_code, left_type = self.visit(ast.left, o)
        right_code, right_type = self.visit(ast.right, o)
        ret_type = left_type
        if isinstance(left_type, FloatType) or isinstance(right_type, FloatType) or op == "/":
            ret_type = FloatType()
            if isinstance(left_type, IntType):      left_code += self.emit.emitI2F(o.frame)
            if isinstance(right_type, IntType):     right_code += self.emit.emitI2F(o.frame)
        if op in ["+", "-"]:
            return left_code + right_code + self.emit.emitADDOP(op, ret_type, o.frame), ret_type
        if op in ["*", "/"]:
            return left_code + right_code + self.emit.emitMULOP(op, ret_type, o.frame), ret_type
        if op == "%":
            return left_code + right_code + self.emit.emitMOD(o.frame), ret_type
        if op == "&&":
            return left_code + right_code + self.emit.emitANDOP(o.frame), ret_type
        if op == "||":
            return left_code + right_code + self.emit.emitOROP(o.frame), ret_type
        if op in [">", ">=", "<", "<=", "!=", "==", "==."]:
            return left_code + right_code + self.emit.emitREOP(op, ret_type, o.frame), BoolType()
        if op == "+.":
            return left_code + right_code + self.emit.emitINVOKEVIRTUAL("java/lang/String/concat", MType([StringType()], StringType()), o.frame), StringType()

    def visitNewExpr(self, ast, o):
        code = ""
        classname = ast.classname.name
        params = ast.param

        code += self.emit.emitNEW(classname, params, o.frame)
        code += self.emit.emitDUP(o.frame)

        # default constructor
        if len(params) == 0:
            code += self.emit.emitINVOKESPECIAL(o.frame, classname + "/<init>", MType([], VoidType()))
            return code, ClassType(classname)

        # constructor with params
        init = o.env.lookup_method(classname, "<init>")

        if init is None:
            raise IllegalRuntimeException("Cannot find <init>!")

        for i in range(len(params)):
            arg_code, arg_type = self.visit(ast.param[i], o)
            code += arg_code
            if isinstance(arg_type, IntType) and isinstance(init.type.partype[i], FloatType):
                code += self.emit.emitI2F(o.frame)

        code += self.emit.emitINVOKESPECIAL(o.frame, classname + "/<init>", init.type)
        return code, ClassType(classname)

    def visitAssign(self, ast, o):
        left = ast.lhs
        exp = ast.exp

        if isinstance(left, FieldAccess):
            return self.visit(left, (Access(o.frame, o.env, True, True), exp))[0]

        if isinstance(left, ArrayCell):
            return self.visit(left, (Access(o.frame, o.env, True, True), exp))[0]

        right_code, right_type = self.visit(exp, Access(o.frame, o.env, False, True))
        left_code, left_type = self.visit(left, Access(o.frame, o.env, True, True))
        code = right_code
        if isinstance(right_type, IntType) and isinstance(left_type, FloatType):
            code += self.emit.emitI2F(o.frame)
        return code + left_code

    def visitFieldAccess(self, ast, o):
        obj = ast.obj
        fieldname = ast.fieldname.name

        value = None
        if type(o) is tuple:
            value = o[1]
            o = o[0]

        code = ""
        class_name = None
        obj_code, obj_type = self.visit(obj, Access(o.frame, o.env, False, False))
        if obj_code is None or obj_type is None:
            class_name = ast.obj.name
        else:
            class_name = obj_type.classname.name

        attr = o.env.lookup_attribute(class_name, ast.fieldname.name)

        if attr is None:
            raise IllegalRuntimeException("Cannot find attribute!")

        if o.is_left and o.is_first:  # write
            value_code, value_type = self.visit(value, Access(o.frame, o.env, False, True))
            if attr.is_static:
                code = value_code + self.emit.emitPUTSTATIC(class_name + "/" + fieldname, attr.type, o.frame)
            else:
                code = obj_code + value_code + self.emit.emitPUTFIELD(class_name + "/" + fieldname, attr.type, o.frame)
        else:   # read
            if attr.is_static:
                code = self.emit.emitGETSTATIC(class_name + "/" + fieldname, attr.type, o.frame)
            else:
                code = obj_code + self.emit.emitGETFIELD(class_name + "/" + fieldname, attr.type, o.frame)
        return code, attr.type

    def visitArrayCell(self, ast, o):
        arr = ast.arr
        idx_list = ast.idx

        code = ""
        value = None
        if type(o) is tuple:
            value = o[1]
            o = o[0]

        code, arr_type = self.visit(arr, Access(o.frame, o.env, False, True))
        arr_type = arr_type.eleType
        for i in range(len(idx_list) - 1):
            idx_code, idx_type = self.visit(idx_list[i], Access(o.frame, o.env, False, True))
            code += idx_code
            code += self.emit.emitALOAD(arr_type, o.frame)
            arr_type = arr_type.eleType
        # last ele
        idx_code, idx_type = self.visit(idx_list[-1], Access(o.frame, o.env, False, True))
        if o.is_left:
            value_code, value_type = self.visit(value, Access(o.frame, o.env, False, True))
            code += idx_code + value_code + self.emit.emitASTORE(arr_type, o.frame)
        else:
            code += idx_code + self.emit.emitALOAD(arr_type, o.frame)
        return code, arr_type

    def visitBlock(self, ast, o):
        o.env.visit_scope()
        code = ""
        for inst in ast.inst:
            code += self.visit(inst, o)
        o.env.exit_scope()
        return code

    def visitIf(self, ast, o):
        code = ""
        expr_code, expr_type = self.visit(ast.expr, Access(o.frame, o.env, False, True))
        code += expr_code
        exit_label = o.frame.getNewLabel()
        false_label = o.frame.getNewLabel()
        code += self.emit.emitIFFALSE(false_label, o.frame)
        code += self.visit(ast.thenStmt, o)
        code += self.emit.emitGOTO(exit_label, o)
        code += self.emit.emitLABEL(false_label, o.frame)
        code += (self.visit(ast.elseStmt, o) if ast.elseStmt else "")
        code += self.emit.emitLABEL(exit_label, o.frame)
        return code

    def visitFor(self, ast, o):
        code = ""
        if ast.expr3 is None:
            ast.expr3 = IntLiteral(1)
        expr1_code, _ = self.visit(
            ast.expr1, Access(o.frame, o.env, False, True))
        expr2_code, _ = self.visit(
            ast.expr2, Access(o.frame, o.env, False, True))
        expr3_code, _ = self.visit(
            ast.expr3, Access(o.frame, o.env, False, True))
        id_write_code, _ = self.visit(ast.id, Access(
            o.frame, o.env, True, True))  # Write code
        id_read_code, _ = self.visit(ast.id, Access(
            o.frame, o.env, False, True))  # Read code
        # Virtual stack size at here is 3: exp1, exp2, exp3

        label_start_loop = o.frame.getNewLabel()
        label_check_condition_down = o.frame.getNewLabel()
        label_loop_body = o.frame.getNewLabel()
        label_update_down = o.frame.getNewLabel()
        # Assign init value for scalar variable:
        code += expr1_code
        code += id_write_code

        o.frame.enterLoop()
        # Check condition
        # Check down or up
        code += self.emit.emitLABEL(label_start_loop, o.frame)
        code += expr1_code
        code += expr2_code
        code += self.emit.emitREOP(">", IntType(), o.frame)  # Loop down
        code += self.emit.emitIFTRUE(label_check_condition_down, o.frame)

        # Condition for loop up
        code += id_read_code
        code += expr2_code
        code += self.emit.emitREOP(">", IntType(), o.frame)
        o.frame.push()
        code += self.emit.emitIFTRUE(o.frame.getBreakLabel(), o.frame)
        code += self.emit.emitGOTO(label_loop_body, o.frame)

        # Condition for loop down
        code += self.emit.emitLABEL(label_check_condition_down, o.frame)
        code += id_read_code
        code += expr2_code
        o.frame.push()
        o.frame.push()
        code += self.emit.emitREOP("<", IntType(), o.frame)
        code += self.emit.emitIFTRUE(o.frame.getBreakLabel(), o.frame)

        # Loop body
        code += self.emit.emitLABEL(label_loop_body, o.frame)
        code += self.visit(ast.loop, o)

        code += self.emit.emitLABEL(o.frame.getContinueLabel(), o.frame)

        # Update scalar variable
        # Check update is up or down
        code += expr1_code
        code += expr2_code
        o.frame.push()
        o.frame.push()
        code += self.emit.emitREOP(">", IntType(), o.frame)  # Loop down
        code += self.emit.emitIFTRUE(label_update_down, o.frame)

        # Update up
        code += id_read_code
        code += expr3_code
        o.frame.push()
        code += self.emit.emitADDOP("+", IntType(), o.frame)
        code += id_write_code
        code += self.emit.emitGOTO(label_start_loop, o.frame)

        # Update down
        code += self.emit.emitLABEL(label_update_down, o.frame)
        code += id_read_code
        code += expr3_code
        o.frame.push()
        code += self.emit.emitADDOP("-", IntType(), o.frame)
        code += id_write_code
        code += self.emit.emitGOTO(label_start_loop, o.frame)
        code += self.emit.emitLABEL(o.frame.getBreakLabel(), o.frame)
        o.frame.exitLoop()
        return code

    def visitBreak(self, ast, o):
        return self.emit.emitGOTO(o.frame.getBreakLabel(), o.frame)

    def visitContinue(self, ast, o):
        return self.emit.emitGOTO(o.frame.getContinueLabel(), o.frame)

    def visitReturn(self, ast, o):
        code = ""
        expr_code, expr_type = (self.visit(ast.expr, Access(o.frame, o.env, False, True)) if ast.expr else ("", VoidType()))
        code += expr_code
        code += self.emit.emitRETURN(expr_type, o.frame)
        self.current_method = expr_type if self.current_method is None else self.current_method
        return code

    def visitCallExpr(self, ast, o):
        code = ""
        obj = ast.obj
        method_name = ast.method.name
        params = ast.param

        class_name = None
        obj_code, obj_type = self.visit(obj, o)

        if obj_code is None or obj_type is None:
            class_name = obj.name
        else:
            class_name = obj_type.classname.name

        # Find method
        method = o.env.lookup_method(class_name, method_name)       # type of method is MType
        if method is None:
            raise IllegalRuntimeException("Cannot find method!")

        for i in range(len(params)):
            arg_code, arg_type = self.visit(params[i], Access(o.frame, o.env, False, True))
            code += arg_code
            if isinstance(arg_type, IntType) and isinstance(method.type.partype[i], FloatType):
                code += self.emit.emitI2F(o.frame)

        if method.is_static:
            code += self.emit.emitINVOKESTATIC(class_name + "/" + method_name, method.type, o.frame)
        else:
            code = obj_code + code + self.emit.emitINVOKEVIRTUAL(class_name + "/" + method_name, method.type, o.frame)
        return code, method.type.rettype

    def visitCallStmt(self, ast, o):
        code = ""
        obj = ast.obj
        method_name = ast.method.name
        params = ast.param

        class_name = None
        obj_code, obj_type = self.visit(obj, Access(o.frame, o.env, False, True))
        if obj_code is None or obj_type is None:
            class_name = obj.name
        else:
            class_name = obj_type.classname.name

        # Find method
        method = o.env.lookup_method(class_name, method_name)
        if method is None:
            raise IllegalRuntimeException("Cannot find method!")

        for i in range(len(params)):
            arg_code, arg_type = self.visit(params[i], Access(o.frame, o.env, False, True))
            code += arg_code
            if isinstance(arg_type, IntType) and isinstance(method.type.partype[i], FloatType):
                code += self.emit.emitI2F(o.frame)

        if method.is_static:
            code += self.emit.emitINVOKESTATIC(class_name + "/" + method_name, method.type, o.frame)
        else:
            code = obj_code + code + self.emit.emitINVOKEVIRTUAL(class_name + "/" + method_name, method.type, o.frame)
        if not isinstance(method.type.rettype, VoidType):
            code += self.emit.emitPOP(o.frame)
        return code

    def visitId(self, ast, o):  # ID only for local variable, attribute or method use access
        local_found = o.env.lookup_local(ast.name)
        if local_found is None:
            return None, None
        if o.is_left:   # write
            return self.emit.emitWRITEVAR(ast.name, local_found.type, local_found.index, o.frame), local_found.type
        # read
        return self.emit.emitREADVAR(ast.name, local_found.type, local_found.index, o.frame), local_found.type

    def visitIntLiteral(self, ast, o):
        return self.emit.emitPUSHICONST(ast.value, o.frame), IntType()

    def visitFloatLiteral(self, ast, o):
        return self.emit.emitPUSHFCONST(str(ast.value), o.frame), FloatType()

    def visitBooleanLiteral(self, ast, o):
        return self.emit.emitPUSHCONST(str(ast.value), BoolType(), o.frame), BoolType()

    def visitStringLiteral(self, ast, o):
        return self.emit.emitPUSHCONST('"' + str(ast.value) + '"', StringType(), o.frame), StringType()

    def visitNullLiteral(self, ast, o):
        return self.emit.emitNULL(o.frame), NullLiteral()

    def visitSelfLiteral(self, ast, o):
        return self.emit.emitTHIS(o.frame), ClassType(Id(self.current_class))

    def visitArrayLiteral(self, ast, o):
        code = ""
        value_list = ast.value
        ele_type = None
        o.frame.push()  # Virtual emit array, need emit after because we don't know type of element at this line
        for i in range(len(value_list)):
            code += self.emit.emitDUP(o.frame)
            code += self.emit.emitPUSHICONST(i, o.frame)
            ele_code, ele_type = self.visit(value_list[i], o)
            code += ele_code
            code += self.emit.emitASTORE(ele_type, o.frame)
        o.frame.pop()  # Reset frame
        arr_type = ArrayType(len(value_list), ele_type)
        code = self.emit.emitARRAY(arr_type, o.frame) + code
        return code, arr_type


import cv2 as cv
from cv2 import aruco
import numpy as np

marker_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)

param_markers = aruco.DetectorParameters_create()
cap = cv.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    marker_corners, marker_IDs, reject = aruco.detectMarkers(
        frame, marker_dict, parameters = param_markers
        )
    if marker_corners:
        for ids, corners in zip(marker_IDs, marker_corners):
            cv.polylines(frame, [corners.astype(np.int32)], True, (0, 244, 28), 4, cv.LINE_AA)

            corners = corners.reshape(4,2)
            corners = corners.astype(int)
            top_right = corners.ravel()
            cv.putText(frame, f'id: {ids[0]}', top_right,
                cv.FONT_HERSHEY_COMPLEX, 1.3, (0,255,23), 2, cv.LINE_AA)

            #print(ids,"  ", corners)

    cv.imshow('frame', frame)
    key = cv.waitKey(1)  #take the input form the keyboard
    if key == ord('q'):  # convert the input into uni-code
        break

cap.release()
cv.destroyAllWindows()


import requests
import re
def choose_name(str):
    p = re.compile(r'\n[\s]*(.*?)[\s]*\n')
    p2 = re.compile(r'.*?[(]')
    m=p.match(str)
    name1 = m.group(0).strip()#获得 东方财富(34344)
    m2=p2.match(name1)
    name = m2.group(0).strip()[0:m2.end()-1]
    return name
name = choose_name('\n      测试(4545)     \n')
print(name)
# name = '\n      测试(4545)     \n'
# p=re.compile(r'\n[\s]*(.*?)[\s]*\n')
# m=p.match(name)
# temp=m.group(0).strip()
# print(temp)
#
# p2 = re.compile(r'.*?[(]')
# m2=p2.match(temp)
# test = m2.group(0).strip()[0:m2.end()-1]
# print(test)
#temp2=m2.group(0).strip()
#print(temp2)


from application import config, process_output

@process_output.formatOutput
def updateConfig(args):
    '''
    Takes a dictionary of arguments, from which it extracts the setting and value.
    Checks that the specified setting and value are valid, then writes the
    changes to the config.ini file.
    Returns confirmation of config change.
    Returns dictionary.
    '''
    setting = args.get('setting')
    value = args.get('value')
    valid_outputformats=["json","yaml"]

    if setting not in (config.options('settings')):
        return {'status': 'error','msg':f'Invalid setting - valid settings are {config.options("settings")}'}
    if setting == 'outputformat' and value.lower() not in valid_outputformats:
        return {'status': 'error','msg':"Invalid value for 'outputformat' - valid settings are 'json' or 'yaml'"}
    if setting == 'databasepath':
        return {'status': 'error','msg':"I can't do that yet!'"}
    if setting == 'outputindent' and not value.isnumeric():
        return {'status': 'error','msg':"Invalid value for 'outputindent' - value must be a number!'"}
    if setting == 'outputindent' and int(value)>10:
        return {'status': 'error','msg':"Invalid value for 'outputindent' - value must be less than 10!'"}

    setting=str(setting)
    value=str(value)

    with open('application/config.ini', 'w') as configfile:
        config.set('settings', setting, value)
        config.write(configfile)
    output = {'status': 'success','msg':f'{setting} set to {value}!'}
    return output


#-----------------------------------------------------------------
#
# Twinkle, Twinkle Little Star
#
# As an introduction to creating multiple objects from the same
# class, in this exercise you will develop a program with
# multiple turtle graphics objects appearing on the screen at
# the same time.
#
# So far all of our turtle graphics programs have involved only
# a single default drawing cursor ("turtle") which limits
# what we can do.  However Turtle (with a capital "T") is actually
# a class, meaning that we can instantiate multiple objects from
# it and have several "turtles" appear on the screen at the
# same time.
#
# When you first run this file you should see a star appear on
# the screen which "twinkles" (by randomly making itself visible and
# invisible many times).  Study the code below to see how
# this star "object" is created and manipulated.  You may need to
# experiment with the "twinkling" frequency and duration to get a
# nice effect on your particular computer.
#
# Your task is to modify this code so that there is more than one
# twinkling star on the screen simultaneously.  Do this by duplicating
# the code fragments below to create as many stars as you want.  Note
# that each star object must have a distinct name, so that the
# program can distinguish them.
#
# Extra challenge: If you're comfortable with loops and lists you may
# want to extend the program so that it creates numerous stars, but
# without unnecessary duplication of code.  The "Busy Bees"
# demonstration from the lecture shows how to do this.
#

#------------------------------------------------------------------
# Import the necessary pre-defined functions.
from turtle import *
from random import randint

#------------------------------------------------------------------
# Main program starts here:
#

# 1. Set up the drawing window.
title("Twinkle, Twinkle Little Stars")
bgcolor("dark blue")

# 2. Register the star icon.
register_shape("small_star.gif")

# 3. Instantiate three star objects as instances
#    of the Turtle class, define their shape, and move
#    them to random positions on the screen.
max_dist = 300 # how far we can go from the centre in pixels

star_one = Turtle()
star_one.shape("small_star.gif")
star_one.penup()
star_one.goto(randint(-max_dist, max_dist), randint(-max_dist, max_dist))

star_two = Turtle()
star_two.shape("small_star.gif")
star_two.penup()
star_two.goto(randint(-max_dist, max_dist), randint(-max_dist, max_dist))

star_three = Turtle()
star_three.shape("small_star.gif")
star_three.penup()
star_three.goto(randint(-max_dist, max_dist), randint(-max_dist, max_dist))

# 4. Make the images of the stars appear and disappear randomly many
#    times.
for twinkle in range(500): # Adjust this to vary the duration of twinkling
    if randint(0, 9) <= 1: # Adjust this to vary the twinkling frequency
        star_one.hideturtle()
    else:
        star_one.showturtle()
    if randint(0, 9) <= 1: # Adjust this to vary the twinkling frequency
        star_two.hideturtle()
    else:
        star_two.showturtle()
    if randint(0, 9) <= 1: # Adjust this to vary the twinkling frequency
        star_three.hideturtle()
    else:
        star_three.showturtle()

# 5. Make sure the stars are visible at the end
star_one.showturtle()
star_two.showturtle()
star_three.showturtle()

# 6. Release the drawing window when finished.
done()


'''
#=============================================================================
#     FileName: app.py
#         Desc: project of one game that run on the web page
#       Author: Honglong Wu
#        Email: wuhonglong@genomics.cn
#      Version: 0.0.1
#      Created: 15/03/2015
#      History:
#=============================================================================
'''

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

import web

urls = (
  '/hello', 'Index'
)

app = web.application(urls, globals())

# absolute path not the relative path
render = web.template.render('/Users/user/bin/GitHub/LPHW/Ex50/gothonweb/templates/', base = "layout")

class Index(object):
	def GET(self):
		return render.hello_form()

	def POST(self):
		form = web.input(greet=None, name = "Nobody")
		greet = "%s, %s" % (form.greet, form.name)
		return render.index(greeting = greet)

if __name__ == "__main__":
	app.run()


import datetime

from django import template
from schedule.models import Calendar
from schedule.settings import CHECK_EVENT_PERM_FUNC, CHECK_CALENDAR_PERM_FUNC
from schedule.templatetags.scheduletags import _cook_slots

from good_spot.places.tasks import get_places_to_update

register = template.Library()

@register.inclusion_tag('proxy/templatetags/_updates_count.html', takes_context=True)
def updates_count(context, slot):
    context['count'] = get_places_to_update(slot.start, slot.end).count()
    return context

@register.inclusion_tag('schedule/_daily_table.html', takes_context=True)
def custom_daily_table(context, day, start=8, end=20, increment=30):
    """
      Display a nice table with occurrences and action buttons.
      Arguments:
      start - hour at which the day starts
      end - hour at which the day ends
      increment - size of a time slot (in minutes)
    """
    user = context['request'].user
    addable = CHECK_EVENT_PERM_FUNC(None, user)
    if 'calendar' in context:
        addable = addable and CHECK_CALENDAR_PERM_FUNC(context['calendar'], user)
    context['addable'] = addable
    day_part = day.get_time_slot(day.start + datetime.timedelta(hours=start), day.start + datetime.timedelta(hours=end))
    # get slots to display on the left
    slots = _cook_slots(day_part, increment)
    context['slots'] = slots
    return context

@register.inclusion_tag('proxy/templatetags/calendar_list.html')
def calendars_list():
    calendars = Calendar.objects.all()
    context = {
        "calendars": calendars
    }
    return context


import tornado.httpserver
import tornado.ioloop
import tornado.web
from pymongo import MongoClient

from lib import game
import websocket

import os

class Application(tornado.web.Application):
	def __init__(self, newGame):
		self.game = newGame

		urls = [
			(r'/', websocket.WSHandler, {'game': self.game})
		]

		settings = dict(
			template_path=os.path.join(os.path.dirname(__file__), 'templates'),
			static_path=os.path.join(os.path.dirname(__file__), 'static'),
			cookie_secret='__FIX ME:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__',
			debug=True
		)
		super(Application, self).__init__(urls, **settings)

def main():
	newGame = game.Game()

	http_server = tornado.httpserver.HTTPServer(Application(newGame))
	http_server.listen(4000)
	tornado.ioloop.IOLoop.current().start()

if __name__ == '__main__':
	main()


### Imports ###
import sys, queue, threading, requests, datetime
from colorama import Fore,init

### Variables ###
init()
input_queue = queue.Queue()
result_queue = queue.Queue()
thread_lock = threading.Lock()
date_time = datetime.datetime.now()
current_time = date_time.time()

INFO = "[\x1b[33m?\x1b[37m] "
ERROR = "[\x1b[31m-\x1b[37m] "
SUCCESS = "[\x1b[32m+\x1b[37m] "

### Editable Variables ###

timeout_period = 1

class ProcessThread(threading.Thread):
    def __init__(self, in_queue, out_queue):
        threading.Thread.__init__(self)
        self.in_queue = in_queue
        self.out_queue = out_queue

    def run(self):
        while True:
            result = self.process(self.in_queue.get())
            if (result is not None):
                self.out_queue.put(result)

            self.in_queue.task_done()

    def process(self, proxy):
        clean_proxy = proxy.replace("\n", "")
        try:
            proxy_formatter = {
                "http": "http://" + clean_proxy,
                "https": "http://" + clean_proxy
            }
            r = requests.get("http://ipinfo.io/json", proxies=proxy_formatter, timeout=timeout_period)
            printableOutput = (Fore.GREEN + '[%s:%s:%s]  %s' % (current_time.hour, current_time.minute, current_time.second , r.json()["ip"]))
            with thread_lock:
                print(printableOutput)

                return "%s" % (proxy)
        except:
            with thread_lock:
                print(Fore.RED + '[%s:%s:%s]  %s' % (current_time.hour, current_time.minute, current_time.second , clean_proxy))
            return None

    def terminate(self):
        None

class LogWorking(threading.Thread):
	def __init__(self, queue, output_file):
		threading.Thread.__init__(self)
		self.queue = queue
		self.output = open(output_file, "a")
		self.shutdown = False

	def log(self, string):
		print(string, file=self.output)

	def run(self):
		while not self.shutdown:
			self.log(self.queue.get())
			self.queue.task_done()

	def terminate(self):
		self.output.close()
		self.shutdown = True

def main():
	# Check Argument Length
	if (len(sys.argv) < 4):
		print("%s Incorrect usage!" % (ERROR))
		print("%s Usage: %s <proxy list> <threads> <output file>" % (INFO, sys.argv[0]))
		exit(1)

	try:
		ip_list = [line.rstrip("\n") for line in open(sys.argv[1], "r")]
	except BaseException as error:
		print(str(error))
		exit(1)

	# Check If File Is Empty
	if (len(ip_list) == 0):
		print("%s Chosen file is blank" % (ERROR))
		exit(1)

	# Load Input Queue
	i = 0
	for ip in ip_list:
		input_queue.put(ip)
		i += 1
		sys.stdout.write("\rAdded %d proxies to queue" % (i))
		sys.stdout.flush()

	print("\n\n%s Checking %d proxies" % (INFO, len(ip_list)))

	# Start Workers
	workers = []
	for i in range(0, int(sys.argv[2])):
		thread = ProcessThread(input_queue, result_queue)
		thread.daemon = True
		thread.start()
		workers.append(thread)

	logger = LogWorking(result_queue, sys.argv[3])
	logger.daemon = True
	logger.start()

	# Wait until our queues are finished
	input_queue.join()
	result_queue.join()
	logger.terminate()
	for worker in workers:
		worker.terminate()

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


from abc import ABC, abstractmethod
from typing import Tuple

import torch
from torch import Tensor

class NearestNeighbors(ABC):
    r"""
    An abstract class to define a nearest neighbors data structure. Classes
    implementing this interface are intended for computing proponents / opponents in
    certain implementations of `TracInCPBase`. In particular, it is for use in
    implementations which compute proponents / opponents of a test instance by
    1) storing representations of training instances within a nearest neighbors data
    structure, and 2) finding within that structure the nearest neighbor of the
    representation of a test instance. The assumption is that the data structure
    stores the tensors passed to the `setup` method, which we refer to as the "stored
    tensors". If this class is used to find proponents / opponents, the nearest
    neighbors of a tensor should be the stored tensors that have the largest
    dot-product with the query.
    """

    @abstractmethod
    def get_nearest_neighbors(
        self, query: torch.Tensor, k: int
    ) -> Tuple[Tensor, Tensor]:
        r"""
        Given a `query`, a tensor of shape (N, *), returns the nearest neighbors in the
        "stored tensors" (see above). `query` represents a batch of N tensors, each
        of common but arbitrary shape *. We always assume the 0-th dimension indexes
        the batch. In use cases of this class for computing proponents / opponents,
        the nearest neighbors of a tensor should be the stored tensors with the largest
        dot-product with the tensor, and the tensors in `query` will all be 1D,
        so that `query` is 2D.

        Args:
            query (Tensor): tensor representing the batch of tensors for which k-nearest
                    neighbors are desired. `query` is of shape (N, *), where N is the
                    size of the batch, i.e. the 0-th dimension of `query` indexes the
                    batch. * denotes an arbitrary shape, so that each tensor in the
                    batch can be of a common, but arbitrary shape.
            k (int): The number of nearest neighbors to return.

        Returns:
            results (tuple): A tuple of `(indices, distances)` is returned. `indices`
                    is a 2D tensor where `indices[i,j]` is the index (within the
                    "stored tensors" passed to the `setup` method) of the `j`-th
                    nearest neighbor of the `i`-th instance in query, and
                    `distances[i,j]` is the corresponding distance. `indices` should
                    be of dtype `torch.long` so that it can be used to index torch
                    tensors.
        """
        pass

    @abstractmethod
    def setup(self, data: torch.Tensor) -> None:
        r"""
        `data` denotes the "stored tensors". These are the tensors within which we
        want to find the nearest neighbors to each tensor in a batch of tensors, via a
        call to the`get_nearest_neighbors` method. Before we can call it, however,
        we need to first store the stored tensors, by doing processing that indexes
        the stored tensors in a form that enables nearest-neighbors computation.
        This method does that preprocessing, and is assumed to be called before any
        call to `get_nearest_neighbors`. For example, this method might put the
        stored tensors in a K-d tree. The tensors in the "stored tensors" can be of a
        common, but arbitrary shape, denoted *, so that `data` is of shape (N, *),
        where N is the number of tensors in the stored tensors. Therefore, the 0-th
        dimension indexes the tensors in the stored tensors.

        Args:
            data (Tensor): A tensor of shape (N, *) representing the stored tensors.
                    The 0-th dimension indexes the tensors in the stored tensors,
                    so that `data[i]` is the tensor with index `i`. The nearest
                    neighbors of a query will be referred to by their index.
        """
        pass

class AnnoyNearestNeighbors(NearestNeighbors):
    """
    This is an implementation of `NearestNeighbors` that uses the Annoy module. At a
    high level, Annoy finds nearest neighbors by constructing binary trees in which
    vectors reside at leaf nodes. Vectors near each other will tend to be in the same
    leaf node. See https://tinyurl.com/2p89sb2h and https://github.com/spotify/annoy
    for more details. Annoy has 1 key parameter: the number of trees to construct.
    Increasing the number of trees leads to more accurate results, but longer time to
    create the trees and memory usage. As mentioned in the `NearestNeighbors`
    documentation, for the use case of computing proponents / opponents, the nearest
    neighbors returned should be those with the largest dot product with the query
    vector. The term "vector" is used here because Annoy stores 1D vectors. However
    in our wrapper around Annoy, we will allow the stored tensors to be of a common
    but arbitrary shape *, and flatten them before storing in the Annoy data structure.
    """

    def __init__(self, num_trees: int = 10) -> None:
        """
        Args:
            num_trees (int): The number of trees to use. Increasing this number gives
                    more accurate computation of nearest neighbors, but requires longer
                    setup time to create the trees, as well as memory.
        """
        try:
            import annoy  # noqa
        except ImportError:
            raise ValueError(
                (
                    "Using `AnnoyNearestNeighbors` requires installing the annoy "
                    "module. If pip is installed, this can be done with "
                    "`pip install --user annoy`."
                )
            )

        self.num_trees = num_trees

    def setup(self, data: torch.Tensor) -> None:
        """
        `data` denotes the "stored tensors". These are the tensors within which we
        want to find the nearest neighbors to a query tensor, via a call to the
        `get_nearest_neighbors` method. Before we can call `get_nearest_neighbors`,
        we need to first store the stored tensors, by doing processing that indexes
        the stored tensors in a form that enables nearest-neighbors computation.
        This method does that preprocessing, and is assumed to be called before any
        call to `get_nearest_neighbors`. In particular, it creates the trees used to
        index the stored tensors. This index is built to enable computation of
        vectors that have the largest dot-product with the query tensors. The tensors
        in the "stored tensors" can be of a common, but arbitrary shape, denoted *, so
        that `data` is of shape (N, *), where N is the number of tensors in the stored
        tensors. Therefore, the 0-th dimension indexes the tensors in the stored
        tensors.

        Args:
            data (Tensor): A tensor of shape (N, *) representing the stored tensors.
                    The 0-th dimension indexes the tensors in the stored tensors,
                    so that `data[i]` is the tensor with index `i`. The nearest
                    neighbors of a query will be referred to by their index.
        """
        import annoy

        data = data.view((len(data), -1))
        projection_dim = data.shape[1]
        self.knn_index = annoy.AnnoyIndex(projection_dim, "dot")
        for (i, projection) in enumerate(data):
            self.knn_index.add_item(i, projection)
        self.knn_index.build(self.num_trees)

    def get_nearest_neighbors(
        self, query: torch.Tensor, k: int
    ) -> Tuple[Tensor, Tensor]:
        r"""
        Given a `query`, a tensor of shape (N, *), returns the nearest neighbors in the
        "stored tensors" (see above). `query` represents a batch of N tensors, each
        of common but arbitrary shape *. We always assume the 0-th dimension indexes
        the batch. In use cases of this class for computing proponents / opponents,
        the nearest neighbors of a tensor should be the stored tensors with the largest
        dot-product with the tensor, and the tensors in `query` will all be 1D,
        so that `query` is 2D. This implementation returns the stored tensors
        that have the largest dot-product with the query tensor, and does not constrain
        the tensors in `query` or in the stored tensors to be 1D. If tensors are of
        dimension greater than 1D, their dot-product will be defined to be the
        dot-product of the flattened version of tensors.

        Args:
            query (Tensor): tensor representing the batch of tensors for which k-nearest
                    neighbors are desired. `query` is of shape (N, *), where N is the
                    size of the batch, i.e. the 0-th dimension of `query` indexes the
                    batch. * denotes an arbitrary shape, so that each tensor in the
                    batch can be of a common, but arbitrary shape.
            k (int): The number of nearest neighbors to return.

        Returns:
            results (tuple): A tuple of `(indices, distances)` is returned. `indices`
                    is a 2D tensor where `indices[i,j]` is the index (within the
                    "stored tensors" passed to the `setup` method) of the `j`-th
                    nearest neighbor of the `i`-th instance in query, and
                    `distances[i,j]` is the corresponding distance. `indices` should
                    be of dtype `torch.long` so that it can be used to index torch
                    tensors.
        """
        query = query.view((len(query), -1))
        indices_and_distances = [
            self.knn_index.get_nns_by_vector(instance, k, include_distances=True)
            for instance in query
        ]
        indices, distances = zip(*indices_and_distances)
        indices = torch.Tensor(indices).type(torch.long)
        distances = torch.Tensor(distances)
        return indices, distances


import tkinter as tk
from tkinter import ttk
import sqlite3
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from collections import defaultdict

class GraphiquePreuves(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

        self.bouton_afficher_graphique = ttk.Button(self, text="Afficher le graphique", command=self.afficher_graphique)
        self.bouton_afficher_graphique.pack(pady=10)

        self.graphique_frame = ttk.Frame(self)
        self.graphique_frame.pack(pady=10)

    def afficher_graphique(self):
        # Connexion à la base de données
        try:
            connexion = sqlite3.connect('database.db')
            curseur = connexion.cursor()

            # Exemple de requête SQL, ajustez-la en fonction de votre structure de base de données
            curseur.execute('SELECT enquId, type FROM Preuves')
            resultats = curseur.fetchall()

            # Fermez la connexion après avoir récupéré les données
            connexion.close()

            # Traitement des données et création du graphique
            data_dict = defaultdict(lambda: defaultdict(int))

            for resultat in resultats:
                enquId, type_preuve = resultat
                data_dict[enquId][type_preuve] += 1

            # Création du graphique à barres empilées
            figure = Figure(figsize=(8, 6), dpi=100)
            subplot = figure.add_subplot(111)

            enquIds = list(data_dict.keys())
            types = list(set(type_preuve for type_preuve in data_dict[enquIds[0]].keys()))  # Prend tous les types de preuves

            bottom = [0] * len(types)

            for enquId in enquIds:
                valeurs = [data_dict[enquId][type_preuve] for type_preuve in types]
                subplot.bar(types, valeurs, bottom=bottom, label=f"enquId {enquId}")
                bottom = [b + v for b, v in zip(bottom, valeurs)]

            subplot.set_xlabel('Type de Preuve')
            subplot.set_ylabel('Nombre de Preuves')
            subplot.legend()

            max_y = max(bottom)
            subplot.set_yticks(range(max_y + 1))

            canvas = FigureCanvasTkAgg(figure, master=self.graphique_frame)
            canvas.draw()
            canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        except sqlite3.Error as e:
            print(f"Erreur lors de la récupération des données depuis la base de données : {e}")

# Exemple d'utilisation de la classe dans l'application principale
class Application(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title("Graphique des Preuves par Type")
        self.geometry("800x600")

        self.graphique_preuves = GraphiquePreuves(self, self)
        self.graphique_preuves.pack()

# Lancement de l'application
app = Application()
app.mainloop()


from abc import abstractmethod, ABC
import networkx as nx
import numpy as np
from relnet.agent.base_agent import Agent

class BaselineAgent(Agent, ABC):
    is_trainable = False

    def __init__(self, environment):
        super().__init__(environment)
        self.future_actions = None

    def setup(self, options, hyperparams):
        super().setup(options, hyperparams)

    def make_actions(self, t, **kwargs):
        if t % 3 == 0:
            action_type, flag = self.environment.exploratory_actions(self.pick_actions_using_strategy)
            self.next_exploration_actions = flag
            return action_type

        elif t % 3 == 1:
            if self.next_exploration_actions is not None:
                exploration_actions_t0, exploration_actions_t1 = \
                    self.environment.exploratory_actions(self.pick_actions_using_strategy)
                self.next_exploration_actions = exploration_actions_t1
                return exploration_actions_t0

        else:
            if self.next_exploration_actions is not None:
                return self.next_exploration_actions

    def finalize(self):
        pass

    @abstractmethod
    def pick_actions_using_strategy(self, i):
        pass

class RandomAgent(BaselineAgent):
    """
    Selects actions randomly from the available actions.
    """
    algorithm_name = 'random'
    is_deterministic = False

    def __init__(self, environment):
        super().__init__(environment)

    def pick_actions_using_strategy(self, i):
        return self.pick_random_actions(i)

class EdgeConnectAgent(BaselineAgent):
    """
    Connect nodes with lowest reward, playing non-dominant action, to a node with high reward playing dominant action.
    """
    algorithm_name = 'edge_connect'
    is_deterministic = True

    def __init__(self, environment):
        super().__init__(environment,)

    def pick_actions_using_strategy(self, i):
        first_node, second_node = None, None
        g = self.environment.g_list[i]

        if g.action_type is None:
            first_node = 'add'
            second_node = -1.
            return first_node, second_node

        # Get rewards and action dict, node degree array
        all_nodes = g.all_nodes_set
        rewards = g.rewards
        actions = g.actions
        banned_first_nodes = g.banned_actions
        first_valid_acts = self.environment.get_valid_actions(g, banned_first_nodes)
        if len(first_valid_acts) == 0:
            return -1, -1

        # Get the dominant action
        if (sum(list(actions.values())) / len(list(actions.values()))) < 0.5:
            dominant_action = 0.
        else:
            dominant_action = 1.

        # Get agents playing non-dominant action
        non_dom_nodes = []
        for node, action in actions.items():
            if (action != dominant_action) and (node not in banned_first_nodes):
                non_dom_nodes.append(node)
        # Find agent with lowest reward
        if len(non_dom_nodes) > 0:
            curr_val = 1.
            for node in non_dom_nodes:
                if rewards[node] < curr_val:
                    curr_val = rewards[node]
                    first_node = node
            # Get dominant nodes
            dom_nodes = list(all_nodes - set(non_dom_nodes))
            curr_val = 0.
            banned_second_nodes = g.get_invalid_edge_ends(first_node, self.environment.get_remaining_budget(i))
            for node in dom_nodes:
                if (rewards[node] > curr_val) and (node not in banned_second_nodes):
                    curr_val = rewards[node]
                    second_node = node

        # If no nodes satisfy the criteria, then pick randomly
        if (first_node is None) or (second_node is None):
            first_node, second_node = self.pick_random_actions(i)

        return first_node, second_node

class LowDegreeTarget(BaselineAgent):
    """
    Flip node playing contributes with few connections
    """
    algorithm_name = 'Low_Degree'
    is_deterministic = True

    def __init__(self, environment):
        super().__init__(environment,)

    def pick_actions_using_strategy(self, i):
        first_node, second_node = None, None

        g = self.environment.g_list[i]

        if g.action_type is None:
            first_node = 'flip'
            second_node = -1.
            return first_node, second_node

        degrees = g.node_degrees
        actions = g.actions

        # Get agents playing non-dominant action
        contributes = []
        for node, action in actions.items():
            if action == 1:
                contributes.append(node)
        # Find agent with lowest degree
        curr_min = float(np.finfo(np.float32).max)
        curr_min2 = float(np.finfo(np.float32).max)
        for node in contributes:
            if degrees[node] < curr_min:
                curr_min = degrees[node]
                first_node = node
            elif degrees[node] < curr_min2:
                curr_min2 = degrees[node]
                second_node = node

        return first_node, second_node


# BOJ 18406
N = input()

length = len(N)
left_half = 0
right_half = 0

for i in range(length // 2):
    left_half += int(N[i])
for i in range(length // 2, length):
    right_half += int(N[i])

if left_half == right_half:
    print("LUCKY")
else:
    print("READY")


from ..rkbe import RKBEModel
import numpy as np
import tensorflow as tf

class RHHolE(RKBEModel):
	def __init__(self, n_entity=None,
		n_relation=None,
		entity_dim=50,
		lambda_=None,
		lrate=.001,
		model_dir=None,
		dataName='DataUnknown',
		name=None,
		epoch_num=None,
		task=None,
		nozero=False ):
		if not name:
			name = 'RKBE%iD%sL.%s' % (entity_dim, str(lambda_) \
						if lambda_ else 'inf', dataName)
		relation_dim = h_dim = entity_dim; self.nozero = nozero
		super(RHHolE, self).__init__(entity_dim=entity_dim,
					relation_dim=relation_dim,
					h_dim=h_dim,
					n_entity=n_entity,
					n_relation=n_relation,
					task=task,
					lambda_=lambda_,
					lrate=lrate,
					name=name,
					model_dir=model_dir,
					epoch_num=epoch_num,
					dataName=dataName)

	def build_x(self):
		self.e1_fft = tf.fft(tf.complex(self.e1,0.0))
		self.e2_fft = tf.fft(tf.complex(self.e2,0.0))
		x = tf.multiply(self.r, tf.cast(tf.real(tf.ifft(tf.multiply(tf.conj(self.e1_fft),self.e2_fft))),dtype=tf.float32))
		return x


import os
from typing import Any, Dict

from airflow.operators.python_operator import PythonOperator
from airflow.utils.decorators import apply_defaults
try:
    from cloud_function_utils import make_iap_request, IAP_CLIENT_ID
except ImportError:
    from recidiviz.cloud_functions.cloud_function_utils import make_iap_request, IAP_CLIENT_ID

def make_iap_export_request(url: str) -> Dict[str, Any]:
    client_id = IAP_CLIENT_ID[os.environ.get('GCP_PROJECT_ID')]
    # make_iap_request raises an exception if the returned status code is not 200
    response = make_iap_request(url, client_id)

    # When operators return a value in airflow, the result is put into xcom for other operators to access it.
    # However, the result must be a built in Python data type otherwise the operator will not return successfully.
    return {
        'status_code': response.status_code,
        'text': response.text
    }

class IAPHTTPRequestOperator(PythonOperator):
    @apply_defaults
    def __init__(
            self,
            task_id: str,
            url: str,
            *args, **kwargs) -> None:
        super().__init__(task_id=task_id,
                         python_callable=make_iap_export_request,
                         op_kwargs={'url': url},
                         *args, **kwargs)


import pygame
from pygame.sprite import Sprite

class SubZero(Sprite):

    def __init__(self, screen, settings):

        super().__init__()

        self.screen = screen
        self.screen_rect = self.screen.get_rect()
        self.settings = settings

        self.image = pygame.image.load("imagenes/subzero_derecha.png")
        self.rect = self.image.get_rect()

        self.rect.y = self.screen_rect.height - self.rect.height
        self.rect.x = self.screen_rect.width / 2 - self.rect.width / 2

        self.mov_right = False
        self.mov_left = False

    def update(self):

        if self.mov_right:
            self.rect.x += 1

        elif self.mov_left:
            self.rect.x -= 1

    def blitme(self):
        self.screen.blit(self.image, self.rect)


import torch
import torch.nn as nn
import numpy as np
import logging
import sys
import os
import config
from config import args
import constants

from smpl_family.create_smpl_models import create_model
from utils.projection import vertices_kp3d_projection_withfov, vertices_kp3d_projection
from utils.rot_6D import rot6D_to_angular
from maps_utils.relative_parser import parse_age_cls_results
from maps_utils.debug_utils import print_dict

import torch.nn.functional as F

class SMPLWrapper(nn.Module):
    def __init__(self):
        super(SMPLWrapper, self).__init__()
        logging.info('Building SMPL family for relative learning in temporal!')

        self.smpl_model = create_model(args().smpl_model_type)
        #self.part_name = ['cam_trans', 'global_orient', 'body_pose', 'smpl_betas']
        #self.part_idx = [3, 3,  (args().smpl_joint_num-1) * 3, 11 if not args().separate_smil_betas else 21]
        self.part_name = ['cam', 'global_orient', 'body_pose', 'smpl_betas']
        self.part_idx = [3, 6,  (args().smpl_joint_num-1) * 6, 11 if not args().separate_smil_betas else 21]
        self.params_num = np.array(self.part_idx).sum()

    def parse_params_pred(self, params_pred, without_cam=False):
        params_dict = self.pack_params_dict(
            params_pred, without_cam=without_cam)
        params_dict['smpl_betas'], cls_dict = self.process_betas(
            params_dict['smpl_betas'])
        vertices, joints44_17 = self.smpl_model(betas=params_dict['smpl_betas'], \
                            poses=params_dict['smpl_thetas'], separate_smil_betas=args().separate_smil_betas)
        return vertices, joints44_17, params_dict, cls_dict

    def forward(self, outputs, meta_data, calc_pj2d_org=True):
        vertices, joints44_17, params_dict, cls_dict = self.parse_params_pred(outputs['params_pred'])

        if 'world_global_rots' in outputs:
            world_vertices, world_joints44_17 = self.smpl_model(betas=params_dict['smpl_betas'].detach(), \
                            poses=torch.cat([outputs['world_global_rots'], params_dict['smpl_thetas'][:,3:].detach()],1), separate_smil_betas=args().separate_smil_betas)
            outputs.update({'world_verts': world_vertices, 'world_j3d': world_joints44_17[:, :args().joint_num], 'world_joints_h36m17': world_joints44_17[:, args().joint_num:]})

        outputs.update(
            {'verts': vertices, 'j3d': joints44_17[:, :args().joint_num], 'joints_h36m17': joints44_17[:, args().joint_num:], **params_dict, **cls_dict})

        outputs.update(vertices_kp3d_projection(outputs['j3d'], outputs['joints_h36m17'], outputs['cam'], \
                input2orgimg_offsets=meta_data['offsets'] if calc_pj2d_org else None, presp=args().perspective_proj, vertices=outputs['verts'] if args().compute_verts_org else None))
        if args().dynamic_augment:
            dyna_pouts = vertices_kp3d_projection(outputs['world_j3d'].detach(), outputs['joints_h36m17'].detach(), outputs['world_cams'], \
                input2orgimg_offsets=meta_data['offsets'] if calc_pj2d_org else None, presp=args().perspective_proj, vertices=outputs['verts'] if args().compute_verts_org else None)
            outputs.update({'world_pj2d': dyna_pouts['pj2d'], 'world_trans': dyna_pouts['cam_trans'], 'world_joints_h36m17': dyna_pouts['pj2d_h36m17']})
            if args().compute_verts_org:
                outputs.update({'world_verts_camed_org': dyna_pouts['verts_camed_org']})

        return outputs

    def pack_params_dict(self, params_pred, without_cam=False):
        idx_list, params_dict = [0], {}
        for i, (idx, name) in enumerate(zip(self.part_idx, self.part_name)):
            if without_cam and i == 0:
                idx_list.append(0)
                continue
            idx_list.append(idx_list[i] + idx)
            params_dict[name] = params_pred[:, idx_list[i]: idx_list[i+1]].contiguous()
        #print_dict(params_dict)
        if params_dict['global_orient'].shape[-1] == 6:
            params_dict['body_pose'] = rot6D_to_angular(params_dict['body_pose'])
            params_dict['global_orient'] = rot6D_to_angular(params_dict['global_orient'])
        N = params_dict['body_pose'].shape[0]
        params_dict['body_pose'] = torch.cat([params_dict['body_pose'], torch.zeros(
            N, 6).to(params_dict['body_pose'].device)], 1)
        params_dict['smpl_thetas'] = torch.cat(
            [params_dict['global_orient'], params_dict['body_pose']], 1)
        return params_dict

    def process_betas(self, betas_pred):
        # TODO: don't have video training data with kid offset
        if not args().learn_relative_age:
            betas_pred[:, 10] = 0

        # the obvious variance of SMPL body shape is in -8~8.
        #smpl_betas = betas_pred[:, :10]
        #smpl_betas[:,:2] = smpl_betas[:,:2]* 6.
        kid_offsets = betas_pred[:, 10]
        #genders_pred = self.softmax(betas_pred[:,11:])
        #age_genders = torch.cat([kid_offsets.unsqueeze(1), genders_pred],1).contiguous()
        Age_preds = parse_age_cls_results(kid_offsets)
        #Gender_cls_preds = Age_Gender_cls_preds[:,1]
        #smpl_gender = torch.index_select(torch.tensor([[1,0],[0,1],[0,0]],device=Gender_cls_preds.device),0,Gender_cls_preds).float().to(smpl_betas.device)

        # whether to detach the learning of kid_offsets in vertex
        #betas_pred = torch.cat([smpl_betas, kid_offsets.unsqueeze(1).detach()],1).contiguous()
        betas_pred = betas_pred[:, :10]

        cls_dict = {'Age_preds': Age_preds, 'kid_offsets_pred': kid_offsets}
        return betas_pred, cls_dict

def merge_smpl_outputs(results_list):
    if len(results_list) == 1:
        return results_list[0][0]
    results = {k: None for k in results_list[0][0].keys()}
    map_inds = torch.cat([torch.where(mask)[0] for _, mask in results_list], 0)
    for key in list(results.keys()):
        results[key] = torch.cat([result[key]
                                  for result, _ in results_list], 0)[map_inds]
    return results

"""
            outputs.update(vertices_kp3d_projection_withfov(outputs['j3d'], outputs['joints_h36m17'], \
                outputs['cam_trans'], outputs['pred_fovs'],
                input2orgimg_offsets=meta_data['offsets'] if calc_pj2d_org else None, vertices=outputs['verts'] if args().inference_video else None))
            if args().dynamic_augment:
                dyna_pouts = vertices_kp3d_projection_withfov(outputs['j3d'].detach(), outputs['joints_h36m17'].detach(), \
                    outputs['world_trans'], outputs['pred_fovs'], input2orgimg_offsets=meta_data['offsets'] if calc_pj2d_org else None, vertices=outputs['verts'] if args().inference_video else None)
                outputs.update({'world_pj2d': dyna_pouts['pj2d'], 'world_pj2d_h36m17': dyna_pouts['pj2d_h36m17']})
"""


import matplotlib.pyplot as plt
import numpy as np

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

plt.rc('axes', labelsize=10)
plt.rc('xtick', labelsize=16)
plt.rc('ytick', labelsize=16)

x = np.arange(-2, 2, 0.01)

ax1.set_xlabel('x')
ax1.plot(x, np.sin(4*x), color='r')
ax1.legend(['sin(4x)'], loc='center right')
plt.setp(ax1.get_xticklabels(), visible=False)

ax2.set_xlabel('x')
ax2.plot(x, np.cos(x)*np.sin(x))
ax2.legend(['cos(x)sin(x)'], loc='center')
plt.setp(ax2.get_xticklabels(), visible=False)

ax3.set_xlabel('x')
ax3.plot(x, np.cos(x))
ax3.legend(['cos(x)'], loc='lower center')

ax4.set_xlabel('x')
ax4.plot(x, np.cos(x)+np.sin(x))
ax4.legend(['cos(x)+sin(x)'], loc='lower right')

fig.show()


# Time complexity = O(n) for constructor and O(logn) for pickIndex
# Space complexity = O(n) for constructor and O(1) for pickIndex

class Solution:

    def __init__(self, w: List[int]):
        self.prefix_sums = []
        self.total_sum = 0

        for weight in w:
            self.total_sum += weight
            self.prefix_sums.append(self.total_sum)

    def pickIndex(self) -> int:
        random_target = self.total_sum * random.random()

        left, right = 0, len(self.prefix_sums)

        while left < right:
            middle = left + (right - left) // 2
            if self.prefix_sums[middle] >= random_target:
                right = middle
            else:
                left = middle + 1

        return left
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()


"""Class definition of the In-Memory Landscape Model store."""
import base
import numpy
import typing

class InMemoryStore(base.Store):
    """
    A Landscape model store that manages data exchange entirely by Python objects in memory.

    PARAMETERS
    None.
    """
    # CHANGELOG
    base.VERSION.added("1.1.1", "`store.InMemoryStore` ")
    base.VERSION.changed("1.3.27", "`store.InMemoryStore` `slice` keyword renamed to `slices`")
    base.VERSION.changed("1.3.27", "`store.InMemoryStore` updated")
    base.VERSION.changed("1.3.33", "`store.InMemoryStore` stores physical unit if specified")
    base.VERSION.added("1.4.1", "Changelog in `store.InMemoryStore` ")
    base.VERSION.changed("1.4.1", "`store.InMemoryStore` class documentation")
    base.VERSION.changed("1.4.9", "`store.InMemoryStore` data type access")
    base.VERSION.changed("1.5.3", "`store.InMemoryStore` changelog uses markdown for code elements")
    base.VERSION.added("1.7.0", "Type hints to `stores.InMemoryStore` ")
    base.VERSION.changed("1.8.0", "Replaced Legacy format strings by f-strings in `stores.InMemoryStore` ")
    base.VERSION.changed("1.9.0", "Switched to Google docstring style in `stores.InMemoryStore` ")

    def __init__(self) -> None:
        """Initializes an InMemoryStore."""
        self._data = {}
        self._scales = {}
        self._unit = {}

    def describe(self, name: str) -> dict[str, typing.Any]:
        """
        Describes a dataset in the store.

        Args:
            name: The name of the dataset.

        Returns:
            A dictionary describing the dataset.
        """
        return {"scales": self._scales[name], "unit": self._unit[name]}

    def get_values(self, name: str, **keywords) -> typing.Any:
        """
        Gets the values of a data set from the store.

        Args:
            name: The name of the data set.
            keywords: Additional keywords.

        Returns:
            The values of the data set in their original representation.
        """
        try:
            values = self._data[name]
        except KeyError:
            raise KeyError(f"InMemoryStore does not contain data for '{name}'")
        return values

    def set_values(
            self,
            name: str,
            values: typing.Any,
            scales: typing.Optional[str] = None,
            unit: typing.Optional[str] = None,
            shape: typing.Optional[typing.Sequence[int]] = None,
            data_type: typing.Optional[type] = None,
            chunks: typing.Optional[typing.Sequence[slice]] = None,
            create: bool = True,
            slices: typing.Optional[typing.Sequence[slice]] = None
    ) -> None:
        """
        Stores a data set in the store.

        Args:

            name: The name of the data set.
            values: The values of the data set.
            scales: The scales to which the values of the data set apply.
            unit: The physical unit of the values.
            shape: The shape of a newly created empty array.
            data_type: The datatype of a newly created empty array.
            chunks: The chunk size for a newly created empty array.
            create: Specifies whether a data set should be created or not.
            slices: Defines the portion of the data set that was passed to the function.

        Returns:
            Nothing.
        """
        if isinstance(values, type):
            type_name = f"{values.__module__}.{values.__qualname__}"
            # noinspection SpellCheckingInspection
            if type_name == "numpy.ndarray" and create:
                self._data[name] = numpy.zeros(shape, data_type)
            else:
                raise TypeError(f"Unsupported type: {type(values)}")
        elif isinstance(values, numpy.ndarray) and slices is not None:
            self._data[name][slices] = values
        else:
            self._data[name] = values
        self._scales[name] = scales
        self._unit[name] = unit

    def has_dataset(self, name: str, partial: bool = False) -> bool:
        """
        Checks whether a dataset exists in the store or not.

        Args:
            name: The name of the dataset.
            partial: Specifies whether to also check partial dataset paths or not.

        Returns:
            A boolean value indicating whether the dataset exists or not.
        """
        return name in self._data


from typing import Dict, Union, Optional

class Computer:
    def __init__(
        self,
        description: str,
        processor_type: str,
        hard_drive_capacity: int,
        memory: int,
        os: str,
        made_in_year: int,
        price: int
    ):
        self.description = description
        self.processor_type = processor_type
        self.hard_drive_capacity = hard_drive_capacity
        self.memory = memory
        self.os = os
        self.made_in_year = made_in_year
        self.price = price

class ComputerShop:
    def __init__(self):
        self.shop_inventory: Dict[int, Computer] = {}
        self.item_id_generator: int = 0

    def buy(self, computer: Computer) -> int:
        self.item_id_generator = self.item_id_generator + 1
        self.shop_inventory[self.item_id_generator] = computer
        return self.item_id_generator

    def update_price(self, item_id: int, new_price: int) -> None :
        if item_id in self.shop_inventory:
            self.shop_inventory[item_id].price = new_price
        else:
            print('Cannot update price for an item that does not exist')

    def sell(self, item_id: int) -> None:
        del self.shop_inventory[item_id]

    def print_item(self, item_id: int, shop_inventory: dict) -> None:
        if item_id in self.shop_inventory:
            print(f'Item with id {item_id} : {self.shop_inventory[item_id]}')
        else:
            print(f'Item with id {item_id} does not exist')

class RebuyShop(ComputerShop):
    shop_inventory: Dict[int, Dict[str, Union[str, int, bool]]] = {}
    item_id: int = 0

    def refurbish(self, item_id: int, shop_inventory: dict, new_os: Optional[str] = None) -> None:
        if item_id in shop_inventory:

            computer = shop_inventory[item_id]

            if int(computer['made_in_year']) < 2000:
                computer['price'] = 0
            elif int(computer['made_in_year']) < 2010:
                computer['price'] = 250
            elif int(computer['made_in_year']) < 2018:
                computer['price'] = 650
            else:
                computer['price'] = 1000

            if new_os is not None:
                computer['os'] = new_os
        else:
            print('Cannot refurbish an item that does not exist')

def create_computer(
                    description: str,
                    processor_type: str,
                    hard_drive_capacity: int,
                    memory: int,
                    os: str,
                    made_in_year: int,
                    price: int
                    ) -> Dict[str, Union[str, int, bool]]:
    return {
            'description': description,
            'processor_type': processor_type,
            'hard_drive_capacity': hard_drive_capacity,
            'memory': memory,
            'os': os,
            'made_in_year': made_in_year,
            'price': price
        }

if __name__ == "main":
    # Computer Shop
    print('CREATE COMPUTER')
    computer_shop = ComputerShop()

    computer = create_computer(
        "Triston XPT 3352",
        "1.4 GHz Quad‑Core Intel Core i5",
        256, 16,
        "Unix", 2016, 1400)

    print(computer)

    print('\nCOMPUTER SHOP')
    print('#' * 20)
    cid: int = computer_shop.buy(computer)

    print('UPDATE PRICE')
    computer_shop.update_price(cid, 1450)
    computer_shop.print_item(cid)

    print('SELL')
    computer_shop.sell(cid)

    print('PRINT AFTER SELLING')
    computer_shop.print_item(cid)

# Rebuy Shop
    rebuy_shop = RebuyShop()
    rcid: int = rebuy_shop.buy(computer)
    print('\nREBUY SHOP')
    print('#' * 20)

    print('REFURBISH')
    rebuy_shop.refurbish(rcid, "Linux Mint")
    rebuy_shop.print_item(rcid)

    print('R SELL')
    rebuy_shop.sell(rcid)

    print('PRINT AFTER R SELLING')
    rebuy_shop.print_item(rcid)


charM_genom = ""
with open("/home/wy/Documents/bioinformatics/project/Phyllothelys_breve.fasta","r") as input_file:
    # 读取一行
    input_file.readline()
    for line in input_file:
        line = line.strip().upper()
        charM_genom = charM_genom+line
        # print()

total_count=len(charM_genom)
A_count=charM_genom.count("A")
T_count=charM_genom.count("T")
C_count=charM_genom.count("C")
G_count=charM_genom.count("G")
print("The total of gene is "+str(total_count))
# 统计ATCG
print("The number of A is "+str(A_count))
print("The number of T is "+str(T_count))
print("The number of C is "+str(C_count))
print("The number of G is "+str(G_count))

print("The overall base composition was {0}% A  、{1}% T 、{2}% C 、{3}% G "
        .format(A_count/total_count,T_count/total_count,C_count/total_count,
        G_count/total_count))
# print("The char A count in chrM is : {0}".format(charM_genom.count("A")))


from flask import Blueprint, url_for, redirect, current_app
from flask_login import LoginManager, login_required, logout_user, current_user

logout = Blueprint('logout', __name__)
login_manager = LoginManager()
login_manager.init_app(logout)

@logout.route('/logout')
@login_required
def show():
    current_app.logger.info(f"Logout user with id {current_user.id}")
    logout_user()
    return redirect(url_for('login.show') + '?success=logged-out')


class Graph:
    def __init__(self, gdict=None):
        if gdict is None:
            gdict = {}
        self.gdict = gdict

    def addEdge(self, vertex, edge):
        self.gdict[vertex].append(edge)

    def checkRoute(self, startNode, endNode):
        visited = [startNode]
        queue = [startNode]
        path = False
        while queue:
            deVertex = queue.pop(0)
            for adjacentVertex in self.gdict[deVertex]:
                if adjacentVertex not in visited:
                    if adjacentVertex == endNode:
                        path = True
                        break
                    else:
                        visited.append(adjacentVertex)
                        queue.append(adjacentVertex)
        return path


import result
import csv

data = {}
RESULT = result.BRACKET_ORIG

for year in RESULT:
	count = 1
	data[year] = []
	for team in RESULT[year]:
		data[year].append([team, count])
		count += 1

for year in data:
    with open("./our_data/lookup/" + str(year) + "_lookup.csv", "w") as outfile:

        writer = csv.writer(outfile, delimiter=',', lineterminator='\n')

        writer.writerows(data[year])


from microbit import *
import music
import radio
radio.config(group=34)
radio.on()

while True:
    message = radio.receive()
    if message:
        if message == 'intruder':
            display.show(Image.ANGRY)
            music.play(music.BADDY)
    if button_a.was_pressed():
        display.clear()


import random
import torch
import os

from dataloaders.datasets import CaptionDataset
from models.model import BiLSTM_withMaxPooling
import argparse
import json

import torchvision.transforms as transforms

parser = argparse.ArgumentParser()
parser.add_argument('--run_local', default=False, action='store_true')
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--neg_type', default='standard', type=str)
parser.add_argument('--runname', default='standard', type=str)
parser.add_argument('--cuda', default=0, type=int)
parser.add_argument('--ex_dup', default=10, type=int)
parser.add_argument('--debug', default=False, action='store_true')
parser.add_argument('--embedding_size', default=512, type=int)
args = parser.parse_args()

device = torch.device("cuda:{}".format(args.cuda) if torch.cuda.is_available() else "cpu")

net = BiLSTM_withMaxPooling(args.embedding_size, args.embedding_size, device)
model_path = '../trained_models/train_standard_nli_batch_size_32/checkpoint_IC_NLI.pth.tar'
stat_dict = torch.load(model_path, map_location=device)
net = stat_dict['net']
epoch = stat_dict['epoch']
epochs_since_improvement = stat_dict['epochs_since_improvement']
optimizer = stat_dict['optimizer']

data_normalization = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

if args.run_local:
    net.device = 'cpu'
net.eval()

data_folder = '/home/gal/Desktop/Pycharm_projects/image_captioning/output_folder'
data_name = 'coco_5_cap_per_img_5_min_word_freq'  # base name shared by data files

if not args.run_local:
    data_f = '/yoav_stg/gshalev/image_captioning/output_folder'
else:
    data_f = data_folder

# section: word map
word_map_file = os.path.join(data_f, 'WORDMAP_' + data_name + '.json')
print('word_map_file: {}'.format(word_map_file))
print('loading word map from path: {}'.format(word_map_file))
with open(word_map_file, 'r') as j:
    word_map = json.load(j)
print('load word map COMPLETED')
rev_word_map = {v: k for k, v in word_map.items()}

val_loader = torch.utils.data.DataLoader(
    CaptionDataset(data_f, data_name, 'VAL', transform=transforms.Compose([data_normalization])),
    batch_size=1, shuffle=True, num_workers=1, pin_memory=True)

val_caps_lst = torch.load(
        '/yoav_stg/gshalev/image_captioning/output_folder/val_caps_lst' if not args.run_local else os.path.join(
            data_folder, 'val_caps_lst'))

for val_batch_i, (imgs, caps, caplens, all_captions) in enumerate(val_loader):

        # subsection: pos example
    pos_output = net((caps, caplens[0][0]), (all_captions[0][1], caplens[0][1]))
    pred = torch.argmax(pos_output).item()
    sen1 = ' '.join([rev_word_map[x] for x in caps[0].cpu().detach().numpy()[:list(caps[0]).index(0)]][1:-1])
    sen2 = ' '.join([rev_word_map[x] for x in all_captions[0][1].cpu().detach().numpy()[:list(all_captions[0][1]).index(0)]][1:-1])
    print('-------------------')
    print('-------------------')
    print('sen1: {}\nsen2: {}\ngt: {}\npred: {}'.format(sen1, sen2, True, pred))
    print('-------------------')

    fake_caps_and_lens_lst = random.sample(list(val_caps_lst), 1)
    fake_caps_lst = [x[0][0] for x in fake_caps_and_lens_lst]
    fake_caps_lens_lst = [x[1][0] for x in fake_caps_and_lens_lst]
    neg_output = net((caps, caplens[0]), (torch.stack(fake_caps_lst), torch.tensor(fake_caps_lens_lst)))
    pred2 = torch.argmax(neg_output).item()

    sen1 = ' '.join([rev_word_map[x] for x in caps[0].cpu().detach().numpy()[:list(caps[0]).index(0)]][1:-1])
    sen2 = ' '.join([rev_word_map[x] for x in torch.stack(fake_caps_lst)[0].cpu().detach().numpy()[:list(torch.stack(fake_caps_lst)[0]).index(0)]][1:-1])
    print('sen1: {}\nsen2: {}\ngt: {}\npred: {}'.format(sen1, sen2, False, pred2))

    if pred == 1:
        g=0
    if pred2 == 0:
        g=0

l = 0


# https://leetcode.com/problems/delete-node-in-a-linked-list/
# Time complexity: O(n)
# Space complexity: O(1)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node, n):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        while node.val != n:
            node = node.next
        node.val = node.next.val
        node.next = node.next.next
        return


def rendu(somme_a_rendre):
	n = [0,0,0]
	pieces = [5,2,1]
	somme = 0
	for i in range(len(pieces)):
		while somme+pieces[i] <= somme_a_rendre:
			somme += pieces[i]
			n[i] += 1
	return n

def main():
	print(rendu(13))
	print(rendu(64))

main()


from nono.db_factory import DBFactory
from nono.base import process_request

conn = DBFactory()

url = '''http://XXXX.sit.com/XXXX-XXXX/ass/handleDebtOperationLog'''

def fetch_dea_list():
    dea_sql = '''SELECT va_id, bo_id, seri_no, id FROM debt_exchange_account dea where va_id  not in (0,23665) and status = 3 and
                  not exists (SELECT 1 from XXXX_debt_operation_log ol where dea.id = ol.dea_id  and ol.status  in (1,0)); '''
    dea_result = conn.query_with_tuple(dea_sql)
    if len(dea_result) == 0:
        return None
    ex_dea_list = filter(is_bo_not_in_pay, dea_result)
    return ex_dea_list

def is_bo_not_in_pay(item):
    ba_sql = '''select 1 from XXXX_borrows_accept_unpaid where va_id = %s and bo_id=%s and  seri_no=%s and is_pay = 2;'''
    va_id = item[0]
    bo_id = item[1]
    seri_no = item[2]
    ba_result = conn.query(ba_sql, (va_id, bo_id, seri_no))
    if len(ba_result) == 0:
        return True
    return False

def process_dea_repair():
    dea_list = fetch_dea_list()
    if dea_list is None:
        return
    param_list = map(map_param, dea_list)
    for param in param_list:
        process_request(url, param)

def map_param(dea_item):
    dea_id = dea_item[3]
    debt_log = '''select trans_id as transId from XXXX_debt_operation_log where dea_id = %s and status = 10 order by id desc limit 1 '''
    result_item = conn.query_one(debt_log, (dea_id, ))
    result_item['deaId'] = dea_id
    result_item['type'] = 2
    return result_item

if __name__ == '__main__':
    process_dea_repair()


from PIL import Image, ImageDraw, ImageFont, ImageFilter

from src.Resource import resource, conf

RGB_TEXT = (255, 255, 255)

class AlbumCoverGenerator:
    """
    专辑图片生成
    """
    def __init__(self):
        self.resource = resource()
        self.img = Image.open(self.resource.image_file_path) # 将打开的图片缩放尺寸到1280*1280
        self.img = self.img.resize((1280, 1280), Image.ANTIALIAS)

    def draw_text(self, text, position, font, color, outline_color, outline_width):
        draw = ImageDraw.Draw(self.img)
        x, y = position
        # 绘制文本的阴影
        draw.text((x - 1, y - 1), text, fill=color, font=font, stroke_width=outline_width, stroke_fill=outline_color)
        draw.text((x + 1, y + 1), text, fill=color, font=font, stroke_width=outline_width, stroke_fill=outline_color)
        # 绘制文本
        draw.text(position, text, fill=color, font=font)

    def add_image_surface(self):
        background = Image.new('RGB', (700, 700), (255, 255, 255))
        self.img.paste(background, (334, 190))
        surface = Image.open(self.resource.image_file_path)
        surface = surface.resize((668, 668))
        self.img.paste(surface, (350, 206))

    def generate_album_cover(self):

        width, height = self.img.size

        # 计算放大比例
        if width < 1080:
            scale = 1080 / width
        else:
            scale = 1
        while width * scale < 2440 or height * scale < 1080:
            scale += 0.1

        # 缩放图片
        new_width = int(width * scale)
        new_height = int(height * scale)
        self.img = self.img.resize((new_width, new_height))

        # 裁剪图片
        left = (new_width - 2440) / 2
        top = (new_height - 1080) / 2
        right = left + 2440
        bottom = top + 1080
        self.img = self.img.crop((left, top, right, bottom))
        self.img = self.img.filter(ImageFilter.GaussianBlur(radius=42))

        # 添加你的专辑封面
        self.add_image_surface()

        # 添加文本
        font_large = ImageFont.truetype(self.resource.font, conf['AlbumCover']['FONT_SIZE_LARGE'])
        font_small = ImageFont.truetype(self.resource.font, conf['AlbumCover']['FONT_SIZE_SMALL'])
        outline_color = (0, 0, 0)
        outline_width = 3
        assert type(self.resource.title) is str, "专辑标题异常，请手动填写专辑信息"
        assert type(self.resource.artist) is str, "专辑艺术家异常，请手动填写专辑信息"
        assert type(self.resource.album) is str, "专辑名称异常，请手动填写专辑信息"
        self.draw_text(self.resource.title, (1152, 240), font_large, RGB_TEXT, outline_color, outline_width)
        self.draw_text(self.resource.artist, (1152, 450), font_small, RGB_TEXT, outline_color, outline_width)
        self.draw_text(self.resource.album, (1152, 540), font_small, RGB_TEXT, outline_color, outline_width)

        # 保存图像
        self.img.save(self.resource.pic_savepath, "PNG")
        # 显示图像
        self.img.show()


class Solution:
    def printVertically(self, s: str) -> List[str]:

        vertcial_words = []
        max_size = 0
        s = s.split()

        # Find the maximum size
        for word in s:
            max_size = max(max_size, len(word))

        # Append each letter by vertically scanning s
        for index in range(max_size):

            vertical = []

            for word in s:

                size = len(word)

                if index < size:
                    vertical.append(word[index])

                else:
                    vertical.append(" ")

            vertical = "".join(vertical)

            # Remove trailing spaces
            vertical = vertical.rstrip()

            vertcial_words.append(vertical)

        return vertcial_words


import vehicle, map, AI

won=0
lost=0

def apply_action(v,action):
    acceleration=0
    angle_difference=0
    if 'U' in action:
        v.acceleration=8
    if 'B' in action:
        v.acceleration=-4
    if 'L' in action:
        angle_difference=1
    if 'R' in action:
        angle_difference=-1
    v.angle += angle_difference*v.getSpeed()/3
    v.move()

def calculateReward(v,m):
    reward = -1
    global lost
    global won
    if m.positionIsGoal((v.x,v.y)):
        won = won + 1
        reward = 100
    if not m.positionIsValid((v.x,v.y)):
        lost= lost+1
        return -100
    return reward

def gameIsOver(v,m):
    return not m.positionIsValid((v.x,v.y)) or m.positionIsGoal((v.x,v.y))