# Various node visitors to clean up nested function calls of various types.
from adl_func_client.query_ast import Select, Where, SelectMany, First
from adl_func_client.util_ast import lambda_body, lambda_body_replace, lambda_unwrap, lambda_call, lambda_build, lambda_is_identity, lambda_test, lambda_is_true
from adl_func_backend.ast.call_stack import argument_stack, stack_frame
import copy
import ast

argument_var_counter = 0
def arg_name():
    'Return a unique name that can be used as an argument'
    global argument_var_counter
    n = 'arg_{0}'.format(argument_var_counter)
    argument_var_counter += 1
    return n

def convolute(ast_g, ast_f):
    'Return an AST that represents g(f(args))'
    #TODO: fix up the ast.Calls to use lambda_call if possible

    # Sanity checks. For example, g can have only one input argument (e.g. f's result)
    if (not lambda_test(ast_g)) or (not lambda_test(ast_f)):
        raise BaseException("Only lambdas in Selects!")

    # Combine the lambdas into a single call by calling g with f as an argument
    l_g = copy.deepcopy(lambda_unwrap(ast_g))
    l_f = copy.deepcopy(lambda_unwrap(ast_f))

    x = arg_name()
    f_arg = ast.Name(x, ast.Load())
    call_g = ast.Call(l_g, [ast.Call(l_f, [f_arg], [])], [])

    # TODO: Rewrite with lambda_build
    args = ast.arguments(args=[ast.arg(arg=x)])
    call_g_lambda = ast.Lambda(args=args, body=call_g)

    # Build a new call to nest the functions
    return call_g_lambda

def make_Select(source, selection):
    'Make a select, and return source is selection is an identity'
    return source if lambda_is_identity(selection) else Select(source, selection)

class simplify_chained_calls(ast.NodeTransformer):
    '''
    In order to cleanly evaluate things like tuples (which should not show up at the back end),
    we must move around various functions, evaluate others, etc., where we can. This AST transformer
    does that work.
    '''

    def __init__(self):
        self._arg_stack = argument_stack()

    def visit_Select_of_Select(self, parent, selection):
        r'''
        seq.Select(x: f(x)).Select(y: g(y))
        => Select(Select(seq, x: f(x)), y: g(y))
        is turned into
        seq.Select(x: g(f(x)))
        => Select(seq, x: g(f(x)))
        '''
        func_g = selection
        func_f = parent.selection

        # Convolute the two functions
        # TODO: should this be generic of just visit?
        new_selection = self.visit(convolute(func_g, func_f))

        # And return the parent select with the new selection function
        return make_Select(parent.source, new_selection)

    def visit_Select_of_SelectMany(self, parent, selection):
        r'''
        seq.SelectMany(x: f(x)).Select(y: g(y))
        => Select(SelectMany(seq, x: f(x)), y: g(y))
        is turned into
        seq.SelectMany(x: f(x).Select(y: g(y)))
        => SelectMany(seq, x: Select(f(x), y: g(y)))
        '''
        func_g = selection
        func_f = parent.selection

        return self.visit(SelectMany(parent.source, lambda_body_replace(func_f, make_Select(lambda_body(func_f), func_g))))

    def visit_Select(self, node):
        r'''
        Transformation #1:
        seq.Select(x: f(x)).Select(y: g(y))
        => Select(Select(seq, x: f(x)), y: g(y))
        is turned into
        seq.Select(x: g(f(x)))
        => Select(seq, x: g(f(x)))

        Transformation #2:
        seq.SelectMany(x: f(x)).Select(y: g(y))
        => Select(SelectMany(seq, x: f(x)), y: g(y))
        is turned into
        seq.SelectMany(x: f(x).Select(y: g(y)))
        => SelectMany(seq, x: Select(f(x), y: g(y)))

        Transformation #3:
        seq.Where(x: f(x)).Select(y: g(y))
        => Select(Where(seq, x: f(x), y: g(y))
        is not altered.
        '''

        parent_select = self.visit(node.source)
        if type(parent_select) is Select:
            return self.visit_Select_of_Select(parent_select, node.selection)
        elif type(parent_select) is SelectMany:
            return self.visit_Select_of_SelectMany(parent_select, node.selection)
        else:
            selection = self.visit(node.selection)
            return make_Select(parent_select, selection)

    def visit_SelectMany_of_Select(self, parent, selection):
        '''
        seq.Select(x: f(x)).SelectMany(y: g(y))
        => SelectMany(Select(seq, x: f(x)), y:g(y))
        is turned into
        seq.SelectMany(x: g(f(x)))
        => SelectMany(seq, x: g(f(x)))
        '''
        func_g = selection
        func_f = parent.selection
        seq = parent.source

        new_selection = self.generic_visit(convolute(func_g, func_f))
        return self.visit(SelectMany(seq, new_selection))

    def visit_SelectMany_of_SelectMany(self, parent, selection):
        '''
        Transformation #1:
        seq.SelectMany(x: f(x)).SelectMany(y: f(y))
        => SelectMany(SelectMany(seq, x: f(x)), y: f(y))
        is turned into:
        seq.SelectMany(x: f(x).SelectMany(y: f(y)))
        => SelectMany(seq, x: SelectMany(f(x), y: f(y)))
        '''
        #TODO: Get to the point we can actually test that this works correctly
        raise BaseException('untested')
        func_g = selection
        func_f = parent.selection

        return self.visit(SelectMany(parent.source, lambda_body_replace(func_f, SelectMany(lambda_body(func_f), func_g))))

    def visit_SelectMany(self, node):
        r'''
        Transformation #1:
        seq.SelectMany(x: f(x)).SelectMany(y: f(y))
        => SelectMany(SelectMany(seq, x: f(x)), y: f(y))
        is turned into:
        seq.SelectMany(x: f(x).SelectMany(y: f(y)))
        => SelectMany(seq, x: SelectMany(f(x), y: f(y)))

        Transformation #2:
        seq.Select(x: f(x)).SelectMany(y: g(y))
        => SelectMany(Select(seq, x: f(x)), y:g(y))
        is turned into
        seq.SelectMany(x: g(f(x)))
        => SelectMany(seq, x: g(f(x)))

        Transformation #3:
        seq.Where(x: f(x)).SelectMany(y: g(y))
        '''
        parent_select = self.visit(node.source)
        if type(parent_select) is SelectMany:
            return self.visit_SelectMany_of_SelectMany(parent_select, node.selection)
        elif type(parent_select) is Select:
            return self.visit_SelectMany_of_Select(parent_select, node.selection)
        else:
            return SelectMany(parent_select, self.visit(node.selection))

    def visit_Where_of_Where(self, parent, filter):
        '''
        seq.Where(x: f(x)).Where(x: g(x))
        => Where(Where(seq, x: f(x)), y: g(y))
        is turned into
        seq.Where(x: f(x) and g(y))
        => Where(seq, x: f(x) and g(y))
        '''
        func_f = parent.filter
        func_g = filter

        arg = arg_name()
        return self.visit(Where(parent.source, lambda_build(arg, ast.BoolOp(ast.And(), [lambda_call(arg, func_f), lambda_call(arg, func_g)]))))

    def visit_Where_of_Select(self, parent, filter):
        '''
        seq.Select(x: f(x)).Where(y: g(y))
        => Where(Select(seq, x: f(x)), y: g(y))
        Is turned into:
        seq.Where(x: g(f(x))).Select(x: f(x))
        => Select(Where(seq, x: g(f(x)), f(x))
        '''
        func_f = parent.selection
        func_g = filter
        seq = parent.source

        w = Where(seq, self.visit(convolute(func_g, func_f)))
        s = make_Select(w, func_f)

        # Recursively visit this mess to see if the Where needs to move further up.
        return self.visit(s)

    def visit_Where_of_SelectMany(self, parent, filter):
        '''
        seq.SelectMany(x: f(x)).Where(y: g(y))
        => Where(SelectMany(seq, x: f(x)), y: g(y))
        Is turned into:
        seq.SelectMany(x: f(x).Where(y: g(y)))
        => SelectMany(seq, x: Where(f(x), g(y)))
        '''
        func_f = parent.selection
        func_g = filter
        seq = parent.source

        return self.visit(SelectMany(seq, lambda_body_replace(func_f, Where(lambda_body(func_f), func_g))))

    def visit_Where(self, node):
        r'''
        Transformation #1:
        seq.Where(x: f(x)).Where(x: g(x))
        => Where(Where(seq, x: f(x)), y: g(y))
        is turned into
        seq.Where(x: f(x) and g(y))
        => Where(seq, x: f(x) and g(y))

        Transformation #2:
        seq.Select(x: f(x)).Where(y: g(y))
        => Where(Select(seq, x: f(x)), y: g(y))
        Is turned into:
        seq.Where(x: g(f(x))).Select(x: f(x))
        => Select(Where(seq, x: g(f(x)), f(x))

        Transformation #3:
        seq.SelectMany(x: f(x)).Where(y: g(y))
        => Where(SelectMany(seq, x: f(x)), y: g(y))
        Is turned into:
        seq.SelectMany(x: f(x).Where(y: g(y)))
        => SelectMany(seq, x: Where(f(x), g(y)))
        '''
        parent_where = self.visit(node.source)
        if type(parent_where) is Where:
            return self.visit_Where_of_Where(parent_where, node.filter)
        elif type(parent_where) is Select:
            return self.visit_Where_of_Select(parent_where, node.filter)
        elif type(parent_where) is SelectMany:
            return self.visit_Where_of_SelectMany(parent_where, node.filter)
        else:
            f = self.visit(node.filter)
            if lambda_is_true(f):
                return parent_where
            else:
                return Where(parent_where, f)

    def visit_Call(self, call_node):
        '''We are looking for cases where an argument is another function or expression.
        In that case, we want to try to get an evaluation of the argument, and replace it in the
        AST of this function. This only works of the function we are calling is a lambda.
        '''
        if type(call_node.func) is ast.Lambda:
            arg_asts = [self.visit(a) for a in call_node.args]
            with stack_frame(self._arg_stack):
                for a_name, arg in zip(call_node.func.args.args, arg_asts):
                    self._arg_stack.define_name(a_name.arg, arg)
                # Now, evaluate the expression, and then lift it.
                return self.visit(call_node.func.body)
        else:
            return self.generic_visit(call_node)

    def visit_Subscript_Tuple(self, v, s):
        '''
        (t1, t2, t3...)[1] => t2

        Only works if index is a number
        '''
        if type(s.value) is not ast.Num:
            return ast.Subscript(v, s, ast.Load())
        n = s.value.n
        if n >= len(v.elts):
            raise BaseException("Attempt to access the {0}th element of a tuple only {1} values long.".format(n, len(v.value.elts)))

        return v.elts[n]

    def visit_Subscript_Of_First(self, first, s):
        '''
        Convert a seq.First()[0]
        ==>
        seq.Select(l: l[0]).First()

        Other work will do the conversion as needed.
        '''
        source = first.source

        # Build the select that starts from the source and does the slice.
        a = arg_name()
        select = make_Select(source, lambda_build(a, ast.Subscript(ast.Name(a, ast.Load()), s, ast.Load())))

        return self.visit(First(select))

    def visit_Subscript(self, node):
        r'''
        Simple Reduction
        (t1, t2, t3...)[1] => t2

        Move [] past a First()
        seq.First()[0] => seq.Select(j: j[0]).First()
        '''
        v = self.visit(node.value)
        s = self.visit(node.slice)
        if type(v) is ast.Tuple:
            return self.visit_Subscript_Tuple(v, s)

        if type(v) is First:
            return self.visit_Subscript_Of_First(v, s)

        # Nothing interesting, so do the normal thing several levels down.
        return ast.Subscript(v, s, ctx=ast.Load())

    def visit_Name(self, name_node):
        'Do lookup and see if we should translate or not.'
        return self._arg_stack.lookup_name(name_node.id, default=name_node)

    def visit_Attribute(self, node):
        'Make sure to make a new version of the Attribute so it does not get reused'
        return ast.Attribute(value=self.visit(node.value), attr=node.attr, ctx=ast.Load())


# Write a function that receives a sequence of key-value pairs and creates
# a dictionary of lists (and returns it). For example:
# Original list:
# [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
# Grouping a sequence of key-value pairs into a dictionary of lists:
# {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}

def make_dict(orig_list: list[tuple[str, int]]) -> dict[str, list[int]]:
    ret_dict: dict[str:list[int]] = {}

    for orig_key, orig_num in orig_list:
        if orig_key not in ret_dict:
            ret_dict[orig_key] = []
        ret_dict[orig_key].append(orig_num)
    return ret_dict


import requests
from bs4 import BeautifulSoup
from bs4 import NavigableString
from .basic import html_headers, convert_lang, capitalize_first, color_word, insert_end_dot, emphasie_text

def search(word, lang_source, lang_target):
    lang_source = convert_lang(lang_source)
    lang_target = convert_lang(lang_target)
    lst_definitions = []
    lst_examples = []
    lst_expressions = []
    with requests.Session() as session:
        source = session.get(f'https://www.linguee.com.br/{lang_source}-{lang_target}/search?source=auto&query={word}', headers=html_headers).text
        soup = BeautifulSoup(source, "html.parser")

        definitions = soup.find_all('a', class_='dictLink featured')
        for result in definitions:
            lst_definitions.append(result.get_text())

        examples = soup.find_all('div', class_='example')
        cnt = 0
        for result in examples:
            cnt+=1
            lst_txt = result.get_text().split('—')
            example = insert_end_dot(capitalize_first(lst_txt[0].strip()))
            example = color_word(word,example)
            translated = insert_end_dot(capitalize_first(lst_txt[1].strip()))
            lst_examples.append('"'+example+'"')

            term = result.parent.parent.find('h3').find('a')
            term = "".join([t for t in term.contents if type(t)==NavigableString])
            term = term.strip()

            lst_examples.append(f'"{translated}" {emphasie_text(term)}
')

        cnt=0
        inexact = soup.find('div', class_='example_lines inexact')
        if inexact is not None:
            lemmas = inexact.find_all('div', class_='lemma singleline')
            for lemma in lemmas:
                cnt+=1
                taglemma = lemma.find('span', class_='tag_lemma')
                dictLink_source = taglemma.find('a', class_='dictLink')

                lemmacontent = lemma.find('div', class_='lemma_content')
                dictLink2_target = lemmacontent.find('a', class_='dictLink')

                example = insert_end_dot(dictLink_source.get_text())
                translated = insert_end_dot(dictLink2_target.get_text())

                if example.find(word) > -1:
                    example = color_word(word,example)
                    lst_expressions.append('"'+example+'"')
                    lst_expressions.append('"'+translated+'"
')

    return ['', ','.join(lst_definitions), '', '
'.join(lst_examples), '', '
'.join(lst_expressions)]

#print(search('streak','english','portuguese'))


import os
import fire
import datetime
from hopla.converter import hopla

def run(quasirawdir, outdir, simg_file, name="quasiraw_qc", process=False,
        njobs=10, use_pbs=False, test=False):
    """ Parse data and execute the processing with hopla.
    Parameters
    ----------
    cat12dir: str
        path to the BIDS cat12 derivatives directory.
    outdir: str
        path to the output directory.
    simg_file: str
        path to the brainprep singularity image.
    name: str, default 'cat12vbm_qc'
        the name of the current analysis.
    process: bool, default False
        optionnaly launch the process.
    njobs: int, default 10
        the number of parallel jobs.
    use_pbs: bool, default False
        optionnaly use PBSPRO batch submission system.
    """

    imgs = [f"{quasirawdir}/sub-*/ses-*/sub-*-6apply_T1w.nii.gz"]
    outdir = os.path.join(outdir, name)

    if not os.path.isdir(outdir):
        os.makedirs(outdir)

    if process:
        pbs_kwargs = {}
        if use_pbs:
            clusterdir = os.path.join(outdir, f"{name}_pbs")
            if not os.path.isdir(clusterdir):
                os.makedirs(clusterdir)
            pbs_kwargs = {
                "hopla_cluster": True,
                "hopla_cluster_logdir": clusterdir,
                "hopla_cluster_queue": "Nspin_long"}
        date = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        logdir = os.path.join(outdir, "logs")
        if not os.path.isdir(logdir):
            os.makedirs(logdir)
        logfile = os.path.join(logdir, f"{name}_{date}.log")
        cmd = (f"singularity run --bind {quasirawdir} --bind {outdir} "
               f"--cleanenv {simg_file} brainprep quasiraw-qc")
        status, exitcodes = hopla(
            cmd,
            img_regex=imgs,
            outdir=outdir,
            hopla_iterative_kwargs=["img_regex"],
            hopla_optional=["img_regex"],
            hopla_cpus=njobs,
            hopla_logfile=logfile,
            hopla_use_subprocess=True,
            hopla_verbose=1,
            hopla_python_cmd=None,
            **pbs_kwargs)

if __name__ == "__main__":
    fire.Fire(run)


from acai_e_acompanhamentos import deseja_acompanhamentos, escolhe_sabor, tamanho

#Retorna o pedido e o valor total deste.
def comanda(tama, preco, sabor_base, escolhidos, valor_escolhidos):
    seu_pedido = []
    conta = []

    seu_pedido.append(f'Seu pedido é um {sabor_base} de {tama} Ele acompanha:{",".join([ac for ac in escolhidos])}')
    conta.append(preco + valor_escolhidos)

    return seu_pedido, conta

# Capta o pedido e retorna o resultado das outras funções.
def pedido():
    tama, preco = tamanho()

    sabor_base = escolhe_sabor()

    escolhidos, valor_escolhidos = deseja_acompanhamentos()

    return tama, preco, sabor_base, escolhidos, valor_escolhidos

#Confirmar ou cancelar o pedido.
def confirmacao_pedido(seu_pedido, conta):
    conf = int(input('\n1. Confirmar o pedido\n2. Cancelar o pedido\n>> '))

    if conf == 1:
        print(f'{seu_pedido[0]}. O custo total é de {conta[0]}')

    elif conf == 2:
        print('Que pena. Cancelando o seu pedido.')
        exit()

    else:
        print('Digite uma opção válida!')
        conf = confirmacao_pedido(seu_pedido, conta)


data = {'frsjnvjn':
    {'DC_SERVICE':
        {'1.0':
            {'count': 4, 'filename':
                                {'sources/mortalitymodel/pipelines/DC2_auw_mortalitymodel.yaml',
                                 'sources/mortalitymodel/pipelines/DC2auw_penddelt.yamI',
                                 'sources/mortalitymodel/pipelines/DCZ_auw pendelt.yaml',
                                 'sources/prd_ind_mainframe/pipelines/DCZ_auw ML UNDRRITE PRODDATA PENDDISK.yaml'}}}}}
data = dict(data)

# data1 = list(list(data[list(data.keys())[0]].values())[0].values())[0]
# k = list(data1[list(data1.keys())[1]])
# print(k)

import yaml

class UniqueKeyLoader(yaml.SafeLoader):
    def construct_mapping(self, node, deep=False):
        mapping = []
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            assert key not in mapping
            mapping.append(key)
        return super().construct_mapping(node, deep)

with open('data.yaml', 'r') as f:
    my_dict = yaml.load(f, Loader=UniqueKeyLoader)

print(my_dict)


from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Union
import os

import fsspec

from dreamsboard.engine.constants import (
    DOC_STORE_KEY,
    INDEX_STORE_KEY,
)
from dreamsboard.engine.storage.template_store.simple_template_store import SimpleTemplateStore
from dreamsboard.engine.storage.template_store.types import DEFAULT_PERSIST_FNAME as TEMPLATE_STORE_FNAME
from dreamsboard.engine.storage.template_store.types import BaseTemplateStore
from dreamsboard.engine.storage.index_store.simple_index_store import SimpleIndexStore
from dreamsboard.engine.storage.index_store.types import (
    DEFAULT_PERSIST_FNAME as INDEX_STORE_FNAME,
)
from dreamsboard.engine.storage.index_store.types import BaseIndexStore
from dreamsboard.engine.utils import concat_dirs

DEFAULT_PERSIST_DIR = "./storage"

@dataclass
class StorageContext:
    """Storage context.

    The storage context container is a utility container for storing nodes,
    indices, and vectors. It contains the following:
    - template_store: BaseTemplateStore
    - index_store: BaseIndexStore

    """

    template_store: BaseTemplateStore
    index_store: BaseIndexStore

    @classmethod
    def from_defaults(
            cls,
            template_store: Optional[BaseTemplateStore] = None,
            index_store: Optional[BaseIndexStore] = None,
            persist_dir: Optional[str] = None,
            fs: Optional[fsspec.AbstractFileSystem] = None,
    ) -> "StorageContext":
        """Create a StorageContext from defaults.

        Args:
            template_store (Optional[BaseTemplateStore]): document store
            index_store (Optional[BaseIndexStore]): index store
            :param template_store:
            :param index_store:
            :param fs:
            :param persist_dir:

        """
        if persist_dir is None:
            template_store = template_store or SimpleTemplateStore()
            index_store = index_store or SimpleIndexStore()
        else:
            template_store = template_store or SimpleTemplateStore.from_persist_dir(
                persist_dir, fs=fs
            )
            index_store = index_store or SimpleIndexStore.from_persist_dir(
                persist_dir, fs=fs
            )

        return cls(template_store, index_store)

    def persist(
            self,
            persist_dir: Union[str, os.PathLike] = DEFAULT_PERSIST_DIR,
            template_store_fname: str = TEMPLATE_STORE_FNAME,
            index_store_fname: str = INDEX_STORE_FNAME,
            fs: Optional[fsspec.AbstractFileSystem] = None,
    ) -> None:
        """Persist the storage context.

        Args:
            persist_dir (str): directory to persist the storage context
            :param fs:
            :param persist_dir:
            :param index_store_fname:
            :param template_store_fname:
        """
        if fs is not None:
            persist_dir = str(persist_dir)  # NOTE: doesn't support Windows here
            template_store_path = concat_dirs(persist_dir, template_store_fname)
            index_store_path = concat_dirs(persist_dir, index_store_fname)
        else:
            persist_dir = Path(persist_dir)
            template_store_path = str(persist_dir / template_store_fname)
            index_store_path = str(persist_dir / index_store_fname)

        self.template_store.persist(persist_path=template_store_path, fs=fs)
        self.index_store.persist(persist_path=index_store_path, fs=fs)

    def to_dict(self) -> dict:
        all_simple = (
                isinstance(self.template_store, SimpleTemplateStore)
                and isinstance(self.index_store, SimpleIndexStore)
        )
        if not all_simple:
            raise ValueError(
                "to_dict only available when using simple doc/index/vector stores"
            )

        assert isinstance(self.template_store, SimpleTemplateStore)
        assert isinstance(self.index_store, SimpleIndexStore)

        return {
            DOC_STORE_KEY: self.template_store.to_dict(),
            INDEX_STORE_KEY: self.index_store.to_dict(),
        }

    @classmethod
    def from_dict(cls, save_dict: dict) -> "StorageContext":
        """Create a StorageContext from dict."""
        template_store = SimpleTemplateStore.from_dict(save_dict[DOC_STORE_KEY])
        index_store = SimpleIndexStore.from_dict(save_dict[INDEX_STORE_KEY])
        return cls(
            template_store=template_store,
            index_store=index_store,
        )


import sys
input = sys.stdin.readline
rope = []
for i in range(int(input())):
    rope.append(int(input()))
rope.sort(reverse=True)
answer = []
mount = 0
for i in range(len(rope)):
    answer.append(int(rope[i]*(i+1)))
print(max(answer))


import cv2
import numpy as np
import os

IMG_SIZE=96

tp, rg, bt, lf = 100, 150, 400, 450

esc='**'

a=''

dataset_folder=input('Enter Folder Name : ')

try:
    os.mkdir(dataset_folder)
except:
    print('Containing folder is having same name ')

cam = cv2.VideoCapture(0)

while(True):

    a=input(' enter name of label or ** to exit : ')

    if a==esc:
        break

    label_dir=str(dataset_folder)+'/'+str(a)
    print(label_dir)

    try:
        os.mkdir(label_dir)
    except Exception as e:
        print('Exception Occoured',e)

    i=0

    while(True):
        (t, frame) = cam.read()

        frame = cv2.flip(frame, 1)

        roi = frame[tp:bt, rg:lf]
        gray_scale = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
        gray_scale = cv2.GaussianBlur(gray_scale, (7, 7), 0)

        gray_scale = cv2.resize(gray_scale, (IMG_SIZE,IMG_SIZE))

        cv2.imwrite("%s/%s/%d.jpg"%(dataset_folder,a,i),gray_scale)
        i+=1

        print(i)
        if i>300:
            break

        cv2.rectangle(frame, (lf, tp), (rg, bt), (0,255,0), 2)

        cv2.imshow("Video Feed 1", gray_scale)

        cv2.imshow("Video Feed", frame)
        # observe the keyprss by the user
        keyprss = cv2.waitKey(1)

        if keyprss == 27:
            break

cam.release()
cv2.destroyAllWindows()


import os
import json
import csv
import formatTickerIntoCSV as ticker_converter

def create_test_json_file(file_path):
    test_data = {
        "US": [
            {
                "ticker": {
                    "Code": "A",
                    "Name": "Agilent Technologies Inc",
                    "Country": "USA",
                    "Exchange": "NYSE",
                    "Currency": "USD",
                    "Type": "Common Stock",
                    "Isin": "US00846U1016"
                },
                "delisted": False
            }
        ],
        "LSE": [
            {
                "ticker": {
                    "Code": "0A00",
                    "Name": "Akzo Nobel N.V.",
                    "Country": "UK",
                    "Exchange": "LSE",
                    "Currency": "EUR",
                    "Type": "Common Stock",
                    "Isin": ""
                },
                "delisted": False
            }
        ]
    }
    with open(file_path, 'w') as f:
        json.dump(test_data, f)

def read_csv_file(file_path):
    with open(file_path, 'r', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        data = [row for row in reader]
    return data
def test_formatTickerIntoCSV():
    test_input_file = 'Data/test_input.json'
    test_output_file = 'Data/test_output.csv'
    ticker_converter.input_file = test_input_file
    ticker_converter.output_file = test_output_file

    create_test_json_file(test_input_file)
    ticker_converter.main()
    csv_data = read_csv_file(test_output_file)

    with open(test_input_file, 'r') as f:
        json_data = json.load(f)

    total_json_items = sum(len(ticker_list) for ticker_list in json_data.values())

    assert len(csv_data) == total_json_items, f"Expected {total_json_items} items in CSV, but got {len(csv_data)} items"

    expected_data = [
        {
            'Code': 'A',
            'Name': 'Agilent Technologies Inc',
            'Country': 'USA',
            'Exchange': 'NYSE',
            'Currency': 'USD',
            'Type': 'Common Stock',
            'Isin': 'US00846U1016',
            'Delisted': 'False'
        },
        {
            'Code': '0A00',
            'Name': 'Akzo Nobel N.V.',
            'Country': 'UK',
            'Exchange': 'LSE',
            'Currency': 'EUR',
            'Type': 'Common Stock',
            'Isin': '',
            'Delisted': 'False'
        }
    ]

    assert csv_data == expected_data, f"Expected {expected_data}, but got {csv_data}"

    os.remove(test_input_file)
    os.remove(test_output_file)

if __name__ == '__main__':
    test_formatTickerIntoCSV()


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

import pyodbc
from typing import List
from DICOMTransit.redcap.constants import *
from DICOMTransit.redcap.enums import Database, Field, DataType
from DICOMTransit.redcap.transaction import RedcapTransaction

# ----------------------------------------------------------------------------------------------------------------------
#  Local ODBC
# ----------------------------------------------------------------------------------------------------------------------

def get_database_column_names(
    table_info, transaction: RedcapTransaction
) -> List[Field]:
    """
    Returns a list of fields contained within a database table.
    :param table_info: Table Information
    :param transaction: RedcapTransaction
    :return: List of fields or None if table not found.
    """
    if table_info is None:
        return None

    # If this is the first time the column names are requested for this table
    if table_info[DATABASE_TABLE_NAME].lower() not in transaction.database_column_names:
        # Get column names from database.

        conn = pyodbc.connect(get_connection_string(table_info[DATABASE]))
        odbc_cursor = conn.cursor()

        result = odbc_cursor.execute(
            "SELECT * FROM [" + table_info[DATABASE_TABLE_NAME].lower() + "] WHERE 1=0"
        )
        database_columns = [tuple[0] for tuple in result.description]

        odbc_cursor.close()
        conn.close

        # Store a copy of column names for this table in local memory.
        transaction.database_column_names[
            table_info[DATABASE_TABLE_NAME].lower()
        ] = database_columns

    else:
        # Get column names from cache.
        database_columns = transaction.database_column_names[
            table_info[DATABASE_TABLE_NAME].lower()
        ]

    return database_columns

def get_case_ids(transaction: RedcapTransaction) -> List[int]:
    """
    Get Case Ids
    :param transaction: RedcapTransaction
    :return: List of all the case ids related to the current hospital record number or None if table not found.
    """

    case_ids = []

    primary_key_filter_name = Field.HospitalRecordNumber.name
    primary_key_filter_value = str(
        transaction.get_primary_key_value(Field.HospitalRecordNumber.value)
    )

    if (
        primary_key_filter_name == ""
        or primary_key_filter_value == ""
        or primary_key_filter_value == "None"
    ):
        return None

    select_statement = (
        "SELECT [CaseId] FROM [Admission] WHERE ["
        + primary_key_filter_name
        + "] = '"
        + primary_key_filter_value
        + "'"
    )

    conn = pyodbc.connect(get_connection_string(1))
    odbc_cursor = conn.cursor()

    odbc_cursor.execute(select_statement)

    data = odbc_cursor.fetchall()

    for index_case_id in range(len(data)):

        # Add Case Id to list of Case Ids.
        case_ids.append(data[index_case_id][0])

    odbc_cursor.close()
    conn.close

    return case_ids

def get_cnfunid_by_cnnid(cnnid: int) -> int:
    """
    Get cnfun id using the cnn id ( cnn - case id )
    :param cnnid: int (cnnid (case id))
    :return: int cnfun patient id (Return -1 if no match found)
    """

    # Preparing CNN database - SQL request.
    select_statement = (
        "SELECT baby.PatientUI FROM Admission admission, Baby baby WHERE admission.CaseId = '"
        + cnnid
        + "' AND admission.BabyId=baby.BabyId"
    )

    # Connecting to CNN database.
    conn = pyodbc.connect(get_connection_string(1))
    odbc_cursor = conn.cursor()

    # Executing SQL request.
    odbc_cursor.execute(select_statement)
    data = odbc_cursor.fetchone()

    # Closing connection.
    odbc_cursor.close()
    conn.close

    # If not found, we return -1.
    if data == None:
        return -1

    # Preparing CNFUN database - SQL request.
    patientui = data[0]
    select_statement = (
        "SELECT PatientId FROM Patients WHERE CNNPatientUI = '" + patientui + "'"
    )

    # Connecting to CNFUN database.
    conn = pyodbc.connect(get_connection_string(2))
    odbc_cursor = conn.cursor()

    # Executing SQL request.
    odbc_cursor.execute(select_statement)
    data = odbc_cursor.fetchone()

    # Closing connection.
    odbc_cursor.close()
    conn.close

    # If not found, we return -1.
    if data == None:
        return -1

    # Return CNFUN - patient id.
    patientid = data[0]
    return patientid

def get_cnfunid_by_mrn(mrn: int) -> int:
    """
    Get cnfun id using the mrn id ( Medical record number )
    :param mrn: int (mrn - Medical record number)
    :return: int cnfun patient id (Return -1 if no match found)
    """

    # Preparing CNN database - SQL request.
    select_statement = (
        "SELECT baby.PatientUI FROM Admission admission, Baby baby WHERE admission.HospitalRecordNumber = '"
        + mrn
        + "' AND admission.BabyId=baby.BabyId"
    )

    # Connecting to CNN database.
    conn = pyodbc.connect(get_connection_string(1))
    odbc_cursor = conn.cursor()

    # Executing SQL request.
    odbc_cursor.execute(select_statement)
    data = odbc_cursor.fetchone()

    # Closing connection.
    odbc_cursor.close()
    conn.close

    # If not found, we return -1.
    if data == None:
        return -1

    # Preparing CNFUN database - SQL request.
    patientui = data[0]
    select_statement = (
        "SELECT PatientId FROM Patients WHERE CNNPatientUI = '" + patientui + "'"
    )

    # Connecting to CNFUN database.
    conn = pyodbc.connect(get_connection_string(2))
    odbc_cursor = conn.cursor()

    # Executing SQL request.
    odbc_cursor.execute(select_statement)
    data = odbc_cursor.fetchone()

    # Closing connection.
    odbc_cursor.close()
    conn.close

    # If not found, we return -1.
    if data == None:
        return -1

    # Return CNFUN - patient id.
    patientid = data[0]
    return patientid

def get_data_rows_for_patient_table(table_info, transaction: RedcapTransaction) -> list:
    """
    Gets all rows of data for a specific patient table.
    :param table_info: Table Information
    :param transaction: RedcapTransaction
    :return: List of all the rows obtained from the query or None if table not found.
    """
    if table_info is None:
        return None

    if table_info[DATABASE_TABLE_NAME] == "":
        return None

    primary_key_filter_name = str(get_primary_key_name(table_info[PRIMARY_KEY_NAME]))
    primary_key_filter_value = str(
        transaction.get_primary_key_value(table_info[PRIMARY_KEY_VALUE])
    )
    primary_key_data_type = get_primary_key_data_type(table_info[PRIMARY_KEY_VALUE])

    if (
        primary_key_filter_name == ""
        or primary_key_filter_value == ""
        or primary_key_filter_value == "None"
    ):
        return None

    if primary_key_data_type == DataType.String.value:
        select_statement = (
            "SELECT * FROM ["
            + table_info[DATABASE_TABLE_NAME]
            + "] WHERE ["
            + primary_key_filter_name
            + "] = '"
            + primary_key_filter_value
            + "'"
        )
    elif primary_key_data_type == DataType.Integer.value:
        select_statement = (
            "SELECT * FROM ["
            + table_info[DATABASE_TABLE_NAME]
            + "] WHERE ["
            + primary_key_filter_name
            + "] = "
            + primary_key_filter_value
        )
    else:
        select_statement = ""

    if select_statement != "":

        conn = pyodbc.connect(get_connection_string(table_info[DATABASE]))
        odbc_cursor = conn.cursor()

        odbc_cursor.execute(select_statement)

        data = odbc_cursor.fetchall()

        odbc_cursor.close()
        conn.close

        return data

    else:
        return None

def get_data_rows_for_reference_table(table_info) -> list:
    """
    Gets all rows of data for a specific reference table.
    :param table_info: Table Information
    :return: List of all the rows obtained from the query or None if table not found.
    """
    if table_info is not None:
        if table_info[DATABASE_TABLE_NAME] != "":

            select_statement = "SELECT * FROM [" + table_info[DATABASE_TABLE_NAME] + "]"

            conn = pyodbc.connect(get_connection_string(table_info[DATABASE]))
            odbc_cursor = conn.cursor()

            odbc_cursor.execute(select_statement)

            data = odbc_cursor.fetchall()

            odbc_cursor.close()
            conn.close

            return data

        else:
            return None
    else:
        return None

def get_connection_string(database) -> str:
    """
    Get Connection String
    :param database: Database Configuration Number
    :return: Connection String
    """
    if database == Database.CNN.value:
        return cnn_connection_string
    elif database == Database.CNFUN.value:
        return cnfun_connection_string
    else:
        return ""

def get_primary_key_name(primary_key) -> str:
    """
    Get Primary Key Name
    :param primary_key: Primary Key Configuration Number
    :return: String - Primary Key Name
    """
    if primary_key == Field.BabyId.value:
        return Field.BabyId.name
    elif primary_key == Field.CaseId.value:
        return Field.CaseId.name
    elif primary_key == Field.CNNPatientUI.value:
        return Field.CNNPatientUI.name
    elif primary_key == Field.HospitalRecordNumber.value:
        return Field.HospitalRecordNumber.name
    elif primary_key == Field.MotherId.value:
        return Field.MotherId.name
    elif primary_key == Field.PatientId.value:
        return Field.PatientId.name
    elif primary_key == Field.PatientUI.value:
        return Field.PatientUI.name
    elif primary_key == Field.MasterId.value:
        return Field.MasterId.name
    else:
        return Field.Unknown.name

def get_primary_key_data_type(primary_key) -> str:
    """
    Get Primary Key Data Type
    :param primary_key: Primary Key Configuration Number
    :return: String - Data Type Configuration Value
    """
    if primary_key == Field.BabyId.value:
        return DataType.Integer.value
    elif primary_key == Field.CaseId.value:
        return DataType.String.value
    elif primary_key == Field.CNNPatientUI.value:
        return DataType.String.value
    elif primary_key == Field.HospitalRecordNumber.value:
        return DataType.String.value
    elif primary_key == Field.MotherId.value:
        return DataType.Integer.value
    elif primary_key == Field.PatientId.value:
        return DataType.Integer.value
    elif primary_key == Field.PatientUI.value:
        return DataType.String.value
    elif primary_key == Field.MasterId.value:
        return DataType.Integer.value
    else:
        return DataType.Unknown.value


n = int(input())
INF = float('inf')
numbers = [0, 1] + [INF]*n

for i in range(2, n+1):
    j = 1
    minn = numbers[i]
    while j ** 2 <= i:
        tmp = i - j**2
        minn = min(numbers[tmp], minn)
        j += 1
    numbers[i] = minn+1
print(numbers[n])


from tkinter import *
from tkinter import font
from PIL import ImageTk, Image
import requests
import os
import sys

class LunaPage:
    """
    The base class for the Luna Options GUI
    """

    def __init__(self, root, bg_color):
        self.server = 'http://161.35.186.108:42069'
        self.root = root
        self.homepage = None
        self.quit_page = None
        self.security_search = None
        self.searched_security = None
        self.trend_window = None
        self.report = None
        # Colors
        self.bg_color = bg_color
        self.menu_color = '#8131D3'
        # Menu/Nav Window
        self.menu_window = None
        self.slider = True
        # Create Fonts
        self.title_font = font.Font(family='Courier', weight="bold", size=46)
        self.menu_font = font.Font(family='Courier', weight="bold", size=30)
        self.back_font = font.Font(family='Courier', weight="bold", size=24)
        self.text_font = font.Font(family='Courier', weight="bold", size=18)
        self.choice_font = font.Font(family='Courier', weight="bold", size=14, underline=True)
        self.category_font = font.Font(family='Courier', weight="bold", size=14)
        self.data_font = font.Font(family='Courier', size=14)
        self.button_font = font.Font(family='Courier', weight="bold", size=12)
        self.report_font = font.Font(family='Courier', size=14, weight="bold")

        # Create Frame for raise functionality
        bg_frame = Frame(root, bg=bg_color, height=1018, width=960)
        bg_frame.place(relx=0.0, rely=0.0, anchor='nw')
        self.bg_frame = bg_frame

        # Create and Set Title
        Label(bg_frame, text='Luna Options', font=self.title_font, bg=self.bg_color).place(relx=0.5, rely=0.1,
                                                                                anchor='center')

        # Create and Set Luna Symbol
        luna_raw = Image.open(self.resource_path("luna-transparent.png"))
        luna = ImageTk.PhotoImage(luna_raw)
        luna_label = Label(bg_frame, bg=self.bg_color, image=luna, cursor='hand2')
        luna_label.photo = luna
        luna_label.place(relx=1.0, rely=0.0, anchor='ne')
        # Bind Luna Symbol to Clock event
        luna_label.bind("<Button>", self.slide_menu_logic)

    # Create Sliding Menu
    def slide_menu(self, *args):
        """
        This method will slide the navigation in or or out based on the value of self.slider.  If the value is True it
        will slide the menu out, if it is False it will slide the menu in.
        """
        # Nav Menu Window and Logic
        menu_window = Frame(self.bg_frame, width=252, height=960)
        self.slider = True

        # Navigation Buttons
        # Home Button
        home = Label(menu_window, bg=self.menu_color, text="Home", font=self.menu_font, width=10, height=5,
                     borderwidth=5,
                     relief='solid', cursor='hand2')
        home.place(relx=0.0, rely=0.0, anchor='nw')
        home.bind("<Button>", self.homepage_window_link)

        # Security Button
        security = Label(menu_window, bg=self.menu_color, text="Search a\nSecurity", font=self.menu_font, width=10,
                         height=5, borderwidth=5, relief='solid', cursor='hand2')
        security.place(relx=0.0, rely=0.25, anchor='nw')
        security.bind("<Button>", self.security_search_window_link)

        # Trend Button
        trend = Label(menu_window, bg=self.menu_color, text="Trends and\nReports", font=self.menu_font, width=10,
                      height=5,
                      borderwidth=5, relief='solid', cursor='hand2')
        trend.place(relx=0.0, rely=0.5, anchor='nw')
        trend.bind("<Button>", self.trend_window_link)

        # Quit Button
        quit_button = Label(menu_window, bg=self.menu_color, text="Quit", font=self.menu_font, width=10, height=5,
                            borderwidth=5,
                            relief='solid', cursor='hand2')
        quit_button.place(relx=0.0, rely=0.75, anchor='nw')
        quit_button.bind("<Button>", self.quit_window_link)

        # Back Button
        close_label = Label(menu_window, text='\u279C', bg=self.menu_color, cursor='hand2',
                            font=self.back_font)
        close_label.place(relx=.95, rely=0.005, anchor='ne')
        close_label.bind("<Button>", self.slide_menu_logic)
        self.menu_window = menu_window

    def slide_menu_logic(self, *args):
        """
        This method is the logic for the slide menu
        """
        # Logic to Open Menu
        if self.slider is True:
            self.slide_menu()
            self.menu_window.place(relx=1.0, rely=0.0, anchor='ne')
            self.slider = False
        else:
            self.menu_window.destroy()
            self.slider = True

    def raise_window(self, page):
        """
        Method to raise frame to top of root
        """
        if page is not None:
            if page.searched_security:
                page.searched_security.destroy()
            frame = page.return_frame()
            frame.lift()

    def return_frame(self):
        """
        Returns frame for raise function
        """
        return self.bg_frame

    def quit_window_link(self, *args):
        """
        Links to the quit window
        """
        self.raise_window(self.quit_page)
        if self.menu_window:
            self.menu_window.destroy()

    def homepage_window_link(self, *args):
        """
        Links to the quit window
        """
        self.raise_window(self.homepage)
        if self.menu_window:
            self.menu_window.destroy()

    def security_search_window_link(self, *args):
        """
        Links to the quit window
        """
        self.raise_window(self.security_search)
        if self.menu_window:
            self.menu_window.destroy()

    def trend_window_link(self, *args):
        """
        Links to the quit window
        """
        self.raise_window(self.trend_window)
        if self.menu_window:
            self.menu_window.destroy()
        if self.report:
            self.report.destroy()

    def resource_path(self, relative_path):
        """
        System path locator for .exe builder
        """
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

    def CreateToolTip(self, widget, text):
        """
        Creates tool tips
        """
        toolTip = ToolTip(widget, text)

        def enter(event):
            toolTip.showtip()

        def leave(event):
            toolTip.hidetip()

        widget.bind('<Enter>', enter)
        widget.bind('<Leave>', leave)

class HomePage(LunaPage):
    """
    The Home Page Class for Luna Options
    """

    def __init__(self, root, bg_color):
        super().__init__(root, bg_color)

        explore = Label(self.bg_frame, text="Explore:", font=self.menu_font, bg=self.bg_color)
        explore.place(relx=0.5, rely=0.35, anchor='center')

        security_button = Button(self.bg_frame, width=20, height=1, text='Search a Security', bg='grey',
                                 font=self.text_font, command=self.security_search_window_link)
        security_button.place(relx=0.5, rely=0.45, anchor="center")
        self.CreateToolTip(security_button, "If you want to search a specific security")

        trend_button = Button(self.bg_frame, width=20, height=1, text='Trends & Reports', bg='grey',
                              font=self.text_font, command=self.trend_window_link)
        trend_button.place(relx=0.5, rely=0.55, anchor="center")
        self.CreateToolTip(trend_button, "If you would like to view reports and trends")

class QuitPage(LunaPage):
    """
    The Quit Page Class for Luna Options
    """

    def __init__(self, root, bg_color):
        super().__init__(root, bg_color)

        quit_button = Button(self.bg_frame, width=20, height=1, text="Quit Luna Options", bg='grey',
                             font=self.text_font, command=self.bg_frame.quit)
        quit_button.place(relx=0.5, rely=0.5, anchor='center')
        self.CreateToolTip(quit_button, "This will exit you out of Luna Options")

class SecuritySearch(LunaPage):
    """
    The Security Search Page Class for Luna Options
    """

    def __init__(self, root, bg_color):
        super().__init__(root, bg_color)
        self.suc_rate = 70
        self.exp_win = 2

        search_box = Entry(self.bg_frame, width=15, font=self.text_font)
        search_box.place(relx=0.5, rely=0.4, anchor="ne")
        self.search_box = search_box

        search_button = Button(self.bg_frame, text='Search Ticker', bg='grey', command=self.search_security,
                               font=self.button_font, height=1)
        search_button.place(relx=0.5, rely=0.4, anchor='nw')
        self.CreateToolTip(search_button, "Search for security in Luna Options Database")

    def search_security(self):
        """
        Takes information from teh search box and searches for a specific security
        """
        if self.searched_security:
            self.searched_security.destroy()
        security = self.search_box.get()

        params = {
            'tick': security
        }
        json = requests.get(self.server, params)
        data = json.json()

        searched_security = self.build_security_page(data)
        self.searched_security = searched_security

    def build_security_page(self, security_information):
        """
        This method will build the Security Page Frame and populate it
        """
        security_frame = Frame(self.bg_frame, height=800, width=960, bg=self.bg_color)
        security_frame.place(relx=0.0, rely=1.0, anchor="sw")

        # Program and load needed information from API call
        ticker = security_information['ticker']
        ticker_label = Label(security_frame, text=ticker, bg=self.bg_color, font=self.menu_font)
        ticker_label.place(relx=0.5, rely=0.05, anchor="center")

        company_name = security_information['comp']
        company_name_label = Label(security_frame, text=company_name, bg=self.bg_color, font=self.text_font)
        company_name_label.place(relx=0.5, rely=0.1, anchor="center")

        updated = 'Last Updated: ' + security_information['last_updated']
        updated_label = Label(security_frame, text=updated, bg=self.bg_color, font=self.button_font)
        updated_label.place(relx=0.5, rely=0.135, anchor="center")

        sentiment = security_information['sentiment']
        sentiment_label = Label(security_frame, text=sentiment, bg=self.bg_color, font=self.text_font)
        sentiment_label.place(relx=0.5, rely=0.25, anchor="center")

        divider = Canvas(security_frame, height=450, bg=self.bg_color, highlightthickness=0, )
        divider.place(relx=0.49, rely=1.0, anchor="sw")
        divider.create_line(0, 0, 0, 450, width=10)

        # Data Labels
        current_field_label = Label(security_frame, text="Current:", bg=self.bg_color, font=self.category_font)
        current_field_label.place(relx=0.015, rely=0.43, anchor="nw")
        current_value = '$' + str(security_information['current'])
        current_value_label = Label(security_frame, text=current_value, bg=self.bg_color, font=self.data_font)
        current_value_label.place(relx=0.0935, rely=0.47, anchor="nw")

        dh_field_label = Label(security_frame, text="Daily High:", bg=self.bg_color, font=self.category_font)
        dh_field_label.place(relx=0.015, rely=0.51, anchor="nw")
        dh_value = '$' + str(security_information['d_high'])
        dh_value_label = Label(security_frame, text=dh_value, bg=self.bg_color, font=self.data_font)
        dh_value_label.place(relx=0.0935, rely=0.55, anchor="nw")

        dl_field_label = Label(security_frame, text="Daily Low:", bg=self.bg_color, font=self.category_font)
        dl_field_label.place(relx=0.015, rely=0.59, anchor="nw")
        dl_value = '$' + str(security_information['d_low'])
        dl_value_label = Label(security_frame, text=dl_value, bg=self.bg_color, font=self.data_font)
        dl_value_label.place(relx=0.0935, rely=0.63, anchor="nw")

        wh_field_label = Label(security_frame, text="Weekly High:", bg=self.bg_color, font=self.category_font)
        wh_field_label.place(relx=0.015, rely=0.67, anchor="nw")
        wh_value = '$' + str(security_information['w_high'])
        wh_value_label = Label(security_frame, text=wh_value, bg=self.bg_color, font=self.data_font)
        wh_value_label.place(relx=0.0935, rely=0.71, anchor="nw")

        wl_field_label = Label(security_frame, text="Weekly Low:", bg=self.bg_color, font=self.category_font)
        wl_field_label.place(relx=0.015, rely=0.75, anchor="nw")
        wl_value = '$' + str(security_information['w_low'])
        wl_value_label = Label(security_frame, text=wl_value, bg=self.bg_color, font=self.data_font)
        wl_value_label.place(relx=0.0935, rely=0.79, anchor="nw")

        mh_field_label = Label(security_frame, text="30 Day High:", bg=self.bg_color, font=self.category_font)
        mh_field_label.place(relx=0.015, rely=0.83, anchor="nw")
        mh_value = '$' + str(security_information['m_high'])
        mh_value_label = Label(security_frame, text=mh_value, bg=self.bg_color, font=self.data_font)
        mh_value_label.place(relx=0.0935, rely=0.87, anchor="nw")

        ml_field_label = Label(security_frame, text="30 Day Low:", bg=self.bg_color, font=self.category_font)
        ml_field_label.place(relx=0.015, rely=0.91, anchor="nw")
        ml_value = '$' + str(security_information['m_low'])
        ml_value_label = Label(security_frame, text=ml_value, bg=self.bg_color, font=self.data_font)
        ml_value_label.place(relx=0.0935, rely=0.95, anchor="nw")

        vol_field_label = Label(security_frame, text="Current Volume:", bg=self.bg_color, font=self.category_font)
        vol_field_label.place(relx=0.25, rely=0.43, anchor="nw")
        vol_value = f"{security_information['cur_vol']:,d}"
        vol_value_label = Label(security_frame, text=vol_value, bg=self.bg_color, font=self.data_font)
        vol_value_label.place(relx=0.335, rely=0.47, anchor="nw")

        wvol_field_label = Label(security_frame, text="Avg Volume:", bg=self.bg_color, font=self.category_font)
        wvol_field_label.place(relx=0.25, rely=0.51, anchor="nw")
        wvol_value = f"{security_information['avg_vol']:,d}"
        wvol_value_label = Label(security_frame, text=wvol_value, bg=self.bg_color, font=self.data_font)
        wvol_value_label.place(relx=0.335, rely=0.55, anchor="nw")

        iv_field_label = Label(security_frame, text="IV Rank:", bg=self.bg_color, font=self.category_font)
        iv_field_label.place(relx=0.25, rely=0.59, anchor="nw")
        iv_value = str(security_information['IVRank']) + '%'
        iv_value_label = Label(security_frame, text=iv_value, bg=self.bg_color, font=self.data_font)
        iv_value_label.place(relx=0.335, rely=0.63, anchor="nw")

        hiv_field_label = Label(security_frame, text="Historic IV:", bg=self.bg_color, font=self.category_font)
        hiv_field_label.place(relx=0.25, rely=0.67, anchor="nw")
        hiv_value = "20%"
        hiv_value_label = Label(security_frame, text=hiv_value, bg=self.bg_color, font=self.data_font)
        hiv_value_label.place(relx=0.335, rely=0.71, anchor="nw")

        opt_field_label = Label(security_frame, text="Option Vol:", bg=self.bg_color, font=self.category_font)
        opt_field_label.place(relx=0.25, rely=0.75, anchor="nw")
        opt_value = "High"
        opt_value_label = Label(security_frame, text=opt_value, bg=self.bg_color, font=self.data_font)
        opt_value_label.place(relx=0.335, rely=0.79, anchor="nw")

        # Option Section
        suc_field_label = Label(security_frame, text="Success Chance:", bg=self.bg_color, font=self.category_font)
        suc_field_label.place(relx=0.51, rely=0.43, anchor="nw")
        suc_70_label = Label(security_frame, text="70%", bg=self.bg_color, font=self.choice_font, fg='blue',
                             cursor='hand2')
        suc_70_label.place(relx=0.72, rely=0.43, anchor="nw")
        suc_75_label = Label(security_frame, text="75%", bg=self.bg_color, font=self.choice_font,
                             fg='blue', cursor='hand2')
        suc_75_label.place(relx=0.79, rely=0.43, anchor="nw")
        suc_80_label = Label(security_frame, text="80%", bg=self.bg_color, font=self.choice_font,
                             fg='blue', cursor='hand2')
        suc_80_label.place(relx=0.86, rely=0.43, anchor="nw")
        suc_85_label = Label(security_frame, text="85%", bg=self.bg_color, font=self.choice_font, fg='blue',
                             cursor='hand2')
        suc_85_label.place(relx=0.93, rely=0.43, anchor="nw")

        exp_field_label = Label(security_frame, text="Time Till Exp.:", bg=self.bg_color, font=self.category_font)
        exp_field_label.place(relx=0.51, rely=0.51, anchor="nw")
        exp_1w_label = Label(security_frame, text="1W", bg=self.bg_color, font=self.choice_font, fg='blue',
                             cursor='hand2')
        exp_1w_label.place(relx=0.72, rely=0.51, anchor="nw")
        exp_2w_label = Label(security_frame, text="2W", bg=self.bg_color, font=self.choice_font,
                             fg='blue', cursor='hand2')
        exp_2w_label.place(relx=0.79, rely=0.51, anchor="nw")
        exp_3w_label = Label(security_frame, text="3W", bg=self.bg_color, font=self.choice_font,
                             fg='blue', cursor='hand2')
        exp_3w_label.place(relx=0.86, rely=0.51, anchor="nw")
        exp_4w_label = Label(security_frame, text="4w", bg=self.bg_color, font=self.choice_font, fg='blue',
                             cursor='hand2')
        exp_4w_label.place(relx=0.93, rely=0.51, anchor="nw")

        statement = "With a success rate of " + str(self.suc_rate) + "% or more, \nexpiration window of " + str(
            self.exp_win) + " weeks or less, \nthe recommended option strategy is:"
        statement_label = Label(security_frame, text=statement, bg=self.bg_color, font=self.data_font)
        statement_label.place(relx=0.50, rely=0.59, anchor="nw")

        # Option Strategy
        rect = Label(security_frame, width=55, height=15, borderwidth=8, relief='solid', bg=self.bg_color)
        rect.place(relx=0.51, rely=0.69, anchor="nw")

        opt_name = "Iron Condor"
        opt_name_label = Label(rect, text=opt_name, bg=self.bg_color, font=self.menu_font)
        opt_name_label.place(relx=0.5, rely=0.125, anchor="center")

        point1_finance = "Sell"
        point1_strat = "Put"
        point1_price = "212.50"
        point1_exp = "xx/xx"
        point1_finacne_label = Label(rect, text=point1_finance, bg=self.bg_color, font=self.data_font)
        point1_strat_label = Label(rect, text=point1_strat, bg=self.bg_color, font=self.data_font)
        point1_price_label = Label(rect, text=point1_price, bg=self.bg_color, font=self.data_font)
        point1_exp_label = Label(rect, text=point1_exp, bg=self.bg_color, font=self.data_font)
        point1_finacne_label.place(relx=0.2, rely=0.4, anchor="center")
        point1_strat_label.place(relx=0.4, rely=0.4, anchor="center")
        point1_price_label.place(relx=0.6, rely=0.4, anchor="center")
        point1_exp_label.place(relx=0.8, rely=0.4, anchor="center")

        point2_finance = "Buy"
        point2_strat = "Put"
        point2_price = "211.00"
        point2_exp = "xx/xx"
        point2_finacne_label = Label(rect, text=point2_finance, bg=self.bg_color, font=self.data_font)
        point2_strat_label = Label(rect, text=point2_strat, bg=self.bg_color, font=self.data_font)
        point2_price_label = Label(rect, text=point2_price, bg=self.bg_color, font=self.data_font)
        point2_exp_label = Label(rect, text=point2_exp, bg=self.bg_color, font=self.data_font)
        point2_finacne_label.place(relx=0.2, rely=0.55, anchor="center")
        point2_strat_label.place(relx=0.4, rely=0.55, anchor="center")
        point2_price_label.place(relx=0.6, rely=0.55, anchor="center")
        point2_exp_label.place(relx=0.8, rely=0.55, anchor="center")

        point3_finance = "Sell"
        point3_strat = "Call"
        point3_price = "245.50"
        point3_exp = "xx/xx"
        point3_finacne_label = Label(rect, text=point3_finance, bg=self.bg_color, font=self.data_font)
        point3_strat_label = Label(rect, text=point3_strat, bg=self.bg_color, font=self.data_font)
        point3_price_label = Label(rect, text=point3_price, bg=self.bg_color, font=self.data_font)
        point3_exp_label = Label(rect, text=point3_exp, bg=self.bg_color, font=self.data_font)
        point3_finacne_label.place(relx=0.2, rely=0.7, anchor="center")
        point3_strat_label.place(relx=0.4, rely=0.7, anchor="center")
        point3_price_label.place(relx=0.6, rely=0.7, anchor="center")
        point3_exp_label.place(relx=0.8, rely=0.7, anchor="center")

        point4_finance = "Buy"
        point4_strat = "Call"
        point4_price = "250.00"
        point4_exp = "xx/xx"
        point4_finacne_label = Label(rect, text=point4_finance, bg=self.bg_color, font=self.data_font)
        point4_strat_label = Label(rect, text=point4_strat, bg=self.bg_color, font=self.data_font)
        point4_price_label = Label(rect, text=point4_price, bg=self.bg_color, font=self.data_font)
        point4_exp_label = Label(rect, text=point4_exp, bg=self.bg_color, font=self.data_font)
        point4_finacne_label.place(relx=0.2, rely=0.85, anchor="center")
        point4_strat_label.place(relx=0.4, rely=0.85, anchor="center")
        point4_price_label.place(relx=0.6, rely=0.85, anchor="center")
        point4_exp_label.place(relx=0.8, rely=0.85, anchor="center")

        return security_frame

class TrendPage(LunaPage):
    """
    The Home Page Class for Luna Options
    """

    def __init__(self, root, bg_color):
        super().__init__(root, bg_color)

        # Buttons for different reports
        trend = Label(self.bg_frame, text="Trends & Reports:", font=self.menu_font, bg=self.bg_color)
        trend.place(relx=0.5, rely=0.35, anchor='center')

        highiv_button = Button(self.bg_frame, width=23, height=1, text='Highest IV Securities', bg='grey',
                               font=self.text_font, command=self.highest_iv_report)
        highiv_button.place(relx=0.5, rely=0.45, anchor="center")
        self.CreateToolTip(highiv_button, "Generate a report of the highest IV securities")

        sentiment_button = Button(self.bg_frame, width=23, height=1, text='Major Market Sentiments', bg='grey',
                               font=self.text_font, command=self.sentiment_report)
        sentiment_button.place(relx=0.5, rely=0.53, anchor="center")
        self.CreateToolTip(sentiment_button, "Generate a report of the Major Market Sentiment")

        highvol_button = Button(self.bg_frame, width=23, height=1, text='Highest Vol Securities', bg='grey',
                                font=self.text_font, command=self.highest_vol_report)
        highvol_button.place(relx=0.5, rely=0.61, anchor="center")
        self.CreateToolTip(highvol_button, "Generate a report of the highest volume securities")

        winners_button = Button(self.bg_frame, width=23, height=1, text='Daily Winners', bg='grey',
                                font=self.text_font, command=self.daily_winners_report)
        winners_button.place(relx=0.5, rely=0.69, anchor="center")
        self.CreateToolTip(winners_button, "Generate a report of the highest trending securities for the day")

        losers_button = Button(self.bg_frame, width=23, height=1, text='Daily Losers', bg='grey',
                               font=self.text_font, command=self.daily_losers_report)
        losers_button.place(relx=0.5, rely=0.77, anchor="center")
        self.CreateToolTip(losers_button, "Generate a report of the highest negative trending securities for the day")

    # Report Logic
    def create_report(self, type):
        """
        Creates and runs a report based on the requested report
        """
        if type == "IV":
            symbol = "%"
            color = "black"
            title = "Highest Daily IV Securities"
            dict_call = 'top_50'
            params = {
                'top_iv': True
            }
            json = requests.get(self.server, params)
            data = json.json()
        elif type == "sentiment":
            symbol = "%"
            color = "black"
            title = "Major Market Sentiments"
            dict_call = 'top_50'
            params = {
                'sentiment': True
            }
            json = requests.get(self.server, params)
            data = json.json()
        elif type == "vol":
            symbol = "M"
            color = "black"
            title = "Highest Daily Volume"
            # Logic to receive list from server
        elif type == "win":
            symbol = "%"
            color = "green"
            title = "Daily Winners"
            # Logic to receive list from server
        elif type == "lose":
            symbol = "%"
            color = "red"
            title = "Daily Losers"
            # Logic to receive list from server

        report_window = Frame(self.bg_frame, height=800, width=960, bg=self.bg_color)
        report_window.place(relx=0.5, rely=0.6, anchor="center")
        report_window_label = Label(report_window, width=880, height=880, bg=self.bg_color)
        report_window_label.place(relx=0.0, rely=0.0, anchor='nw')

        title_label = Label(report_window, text=title, font=self.menu_font, bg=self.bg_color)
        title_label.place(relx=0.5, rely=0.2, anchor="center")

        report_data = Frame(report_window, height=740, width=960, bg=self.bg_color)
        report_data.place(relx=0.5, rely=0.6, anchor="center")

        # Populate Table
        i = 1
        for row in range(10):
            for column in range(5):
                info = data[dict_call][i - 1][0] + " " + data[dict_call][i - 1][1] + symbol
                if type == 'sentiment':
                    if data[dict_call][i-1][2].lower() == 'bullish':
                        Label(report_data, text=info, bg=self.bg_color, fg='green',
                              font=self.report_font).grid(row=row, column=column, padx=10, pady=12)
                    else:
                        Label(report_data, text=info, bg=self.bg_color, fg='red',
                              font=self.report_font).grid(row=row, column=column, padx=10, pady=12)
                else:
                    Label(report_data, text=info, bg=self.bg_color, fg=color,
                          font=self.report_font).grid(row=row, column=column, padx=10, pady=12)
                i += 1

        self.report = report_window

    def highest_iv_report(self):
        """
        Function for Highest IV Report
        """
        self.create_report("IV")

    def highest_vol_report(self):
        """
        Function for the highest volume report
        """
        self.create_report("vol")

    def daily_winners_report(self):
        """
        Function for the daily winners report
        """
        self.create_report("win")

    def daily_losers_report(self):
        """
        Function for the daily losers report
        """
        self.create_report("lose")

    def sentiment_report(self):
        """
        Function for the Major Market Sentiment report
        """
        self.create_report("sentiment")

class ToolTip(object):

    def __init__(self, widget, text=""):
        self.widget = widget
        self.tipwindow = None
        self.id = None
        self.x = self.y = 0
        self.text = text

    def showtip(self):
        """
        Display text in tooltip window
        """
        if self.tipwindow or not self.text:
            return
        x, y, cx, cy = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 107
        y = y + cy + self.widget.winfo_rooty() + 47
        self.tipwindow = tw = Toplevel(self.widget)
        tw.wm_overrideredirect(1)
        tw.wm_geometry("+%d+%d" % (x, y))
        label = Label(tw, text=self.text, justify=LEFT,
                      background="#ffffe0", relief=SOLID, borderwidth=1,
                      font=("tahoma", "8", "normal"))
        label.pack(ipadx=1)

    def hidetip(self):
        tw = self.tipwindow
        self.tipwindow = None
        if tw:
            tw.destroy()


# coding=utf8

from sklearn.model_selection import StratifiedShuffleSplit

def strat_field_split(x_arr, y_arr, rand_state, test_size=0.1):
    sss = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=rand_state)
    res = sss.split(x_arr, y_arr)
    train_x, train_y = None, None
    test_x, test_y = None, None
    for train_idx, test_idx in res:
        train_x = x_arr[train_idx]
        train_y = y_arr[train_idx]
        test_x = x_arr[test_idx]
        test_y = y_arr[test_idx]
    return train_x, train_y, test_x, test_y


# 题目描述
# 输入一个正整数数组，把数组里所有数字拼接起来排成一个数，
# 打印能拼接出的所有数字中最小的一个。
# 例如输入数组{3，32，321}，则打印出这三个数字能排成的最小数字为321323。

#直接采用 ’ = ’ 赋值方式会使得两个变量占用同一地址，也就是说a 与 b 是同一个对象。
# 而采用切片方式赋值则不会。但是这种浅拷贝方式在二维数组中，直接赋值到二维变量上则也会改变。
# 但是对二维数组的一维数值赋值则不会发生错误。
#也可以采用a.copy()的方式深拷贝，来避免二维赋值的改变值的错误。

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        max_flag=0
        max_len=0
        numbers_copy=numbers[:]
        for n in numbers_copy:
            if max_len<len(str(n)):
                max_len=len(str(n))
            if max_flag<int(str(n)[0]):
                max_flag=int(str(n)[0])
        for i,n in enumerate(numbers_copy):
            numbers_copy[i]=str(n).ljust(max_len,str(max_flag))
        for i in range(len(numbers_copy)):
            for j in range(i+1,len(numbers_copy)):
                if numbers_copy[i]>numbers_copy[j]:
                    t=numbers_copy[i]
                    numbers_copy[i]=numbers_copy[j]
                    numbers_copy[j]=t
                    tt=numbers[i]
                    numbers[i] = numbers[j]
                    numbers[j] = tt
        return str("".join([str(x) for x in numbers]))

if __name__ == '__main__':
    s=Solution()
    a=[23,23,236]
    print(s.PrintMinNumber(a))