import os
import math
import inspect
from subprocess import call

import claasp
from claasp.component import free_input
from claasp.name_mappings import (SBOX, LINEAR_LAYER, MIX_COLUMN, WORD_OPERATION, CONSTANT,
                                  CONCATENATE, PADDING, INTERMEDIATE_OUTPUT, CIPHER_OUTPUT)

tii_path = inspect.getfile(claasp)
tii_dir_path = os.path.dirname(tii_path)

TII_C_LIB_PATH = f'{tii_dir_path}/cipher_modules/'

def delete_generated_evaluate_c_shared_library(cipher):
    name = cipher.id + "_evaluate"
    call(["rm", TII_C_LIB_PATH + name + ".c"])
    call(["rm", TII_C_LIB_PATH + name + ".o"])
    call(["rm", TII_C_LIB_PATH + "generic_bit_based_c_functions.o"])

def generate_bit_based_c_code(cipher, intermediate_output, verbosity):
    code = ['#include <stdio.h>', '#include <stdbool.h>', '#include <stdlib.h>',
            '#include "generic_bit_based_c_functions.h"\n']
    function_args = []
    for cipher_input in cipher.inputs:
        function_args.append(f'BitString *{cipher_input}')
    function_declaration = f'BitString* evaluate({", ".join(function_args)}) {{'
    code.append(function_declaration)

    code.append('\tBitString *input;')
    code.append('\tBitString **input_id;')
    code.append('\tuint16_t **input_positions;')
    code.append('\tuint64_t **matrix;')
    code.append('\tuint64_t *substitution_list;')
    code.append('\tuint8_t **linear_transformation;\n')
    code.extend(get_rounds_bit_based_c_code(cipher, intermediate_output, verbosity))
    code.append('}')
    code.append('int main(int argc, char *argv[]) {')
    evaluate_args = []
    for i in range(len(cipher.inputs)):
        evaluate_args.append(cipher.inputs[i])
        code.append(
            f'\tBitString* {cipher.inputs[i]} = '
            f'bitstring_from_hex_string(argv[{i + 1}], {cipher.inputs_bit_size[i]});')
    code.append(f'\tBitString* output = evaluate({", ".join(evaluate_args)});')
    if not intermediate_output:
        code.append('\tprint_bitstring(output, 16);')
    evaluate_args.append('output')
    code.append(f'\tdelete({", ".join(evaluate_args)});')
    code.append('}')

    return '\n'.join(code)

def get_rounds_bit_based_c_code(cipher, intermediate_output, verbosity):
    c_variables = []
    string_dictionary = {}
    list_sizes = []
    index = 0
    rounds_code = []
    for round_number in cipher.rounds_as_list:
        if verbosity:
            rounds_code.append(f'\tprintf("\\nROUND {round_number.id}\\n\\n");\n')

        for component in round_number.components:
            if component.type in ['constant', 'sbox', 'linear_layer', 'mix_column', 'concatenate']:
                rounds_code.extend(component.get_bit_based_c_code(verbosity))
                c_variables.append(component.id)

            elif component.type == 'word_operation':
                rounds_code.extend(get_word_operation_component_bit_based_c_code(component, verbosity))
                c_variables.append(component.id)

            elif component.type == 'padding':
                rounds_code.extend(get_padding_component_bit_based_c_code(component, verbosity))
                c_variables.append(component.id)

            elif component.type == 'intermediate_output':
                intermediate_output_code, index = get_intermediate_output_component_bit_based_c_code(
                    component, index, intermediate_output, list_sizes, string_dictionary, verbosity)
                rounds_code.extend(intermediate_output_code)
                c_variables.append(component.id)

            elif component.type == 'cipher_output':
                cipher_output_code, index = get_cipher_output_component_bit_based_c_code(
                    component, index, intermediate_output, list_sizes, string_dictionary, c_variables, cipher)
                rounds_code.extend(cipher_output_code)

            else:
                raise ValueError(f'Component {component.id} not implemented.')

    return rounds_code

def get_cipher_output_component_bit_based_c_code(component, index, intermediate_output, list_sizes, string_dictionary,
                                                 c_variables, cipher):
    cipher_output_code = []
    component.select_bits(cipher_output_code)
    if intermediate_output:
        if component.description[0] in string_dictionary:
            list_sizes[string_dictionary[component.description[0]]] += 1

        else:
            string_dictionary[component.description[0]] = index
            list_sizes.append(1)
            index += 1

        s = [f'"{x}"' for x in string_dictionary.keys()]

        number_of_descriptions = len(string_dictionary)

        cipher_output_code.append(f'\tchar **output_list[{number_of_descriptions}];')

        for i in range(len(list_sizes)):
            cipher_output_code.append(f'\tchar *output_list_{i}[{list_sizes[i]}];')
            cipher_output_code.append(f'\toutput_list[{i}] = output_list_{i};')

        list_index = [0] * number_of_descriptions

        for cipher_component in cipher.get_all_components():
            if cipher_component.type == 'intermediate_output':
                i = string_dictionary[cipher_component.description[0]]
                cipher_output_code.append(
                    f'\toutput_list[{i}][{list_index[i]}] = '
                    f'bitstring_to_hex_string({cipher_component.id});')
                list_index[i] += 1

        i = index - 1

        cipher_output_code.append(f'\toutput_list[{i}][{list_index[i]}] = bitstring_to_hex_string(input);')
        list_index[i] += 1

        cipher_output_code.append(f'\tchar *descriptions[] = {{{", ".join(s)}}};')
        cipher_output_code.append(f'\tuint8_t lenghts[] = {{{", ".join([str(x) for x in list_index])}}};')

        cipher_output_code.append('\tprintf("{\\n");')

        cipher_output_code.append(f'\tfor (int i = 0; i < {number_of_descriptions}; i++) {{')
        cipher_output_code.append('\t\tprintf("\\"%s\\" : [", descriptions[i]);')
        cipher_output_code.append('\t\tfor (int j = 0; j < lenghts[i]; j++) {')
        cipher_output_code.append('\t\t\tprintf("%s, ", output_list[i][j]);')
        cipher_output_code.append('\t\t\tfree(output_list[i][j]);')
        cipher_output_code.append('\t\t}')
        cipher_output_code.append('\t\tprintf("],\\n");')
        cipher_output_code.append('\t}')
        cipher_output_code.append('\tprintf("}\\n");')
    cipher_output_code.append(f'\tdelete({", ".join(c_variables)});')
    cipher_output_code.append('\treturn input;')
    return cipher_output_code, index

def get_intermediate_output_component_bit_based_c_code(component, index, intermediate_output, list_sizes,
                                                       string_dictionary, verbosity):
    intermediate_output_code = []
    component.select_bits(intermediate_output_code)
    intermediate_output_code.append(f'\tBitString *{component.id} = input;')
    if intermediate_output:
        if component.description[0] in string_dictionary:
            list_sizes[string_dictionary[component.description[0]]] += 1

        else:
            string_dictionary[component.description[0]] = index
            list_sizes.append(1)
            index += 1
    if verbosity:
        component.print_values(intermediate_output_code)
    return intermediate_output_code, index

def get_padding_component_bit_based_c_code(component, verbosity):
    padding_code = []
    component.select_bits(padding_code)
    padding_code.append(f'\tBitString* {component.id} = PADDING(input, {component.output_bit_size});\n')
    if verbosity:
        component.print_values(padding_code)
    free_input(padding_code)

    return padding_code

def get_word_operation_component_bit_based_c_code(component, verbosity):
    word_operation_code = []
    component.select_bits(word_operation_code)
    if component.description[0] in ['SHIFT', 'ROTATE', 'SHIFT_BY_VARIABLE_AMOUNT', 'ROTATE_BY_VARIABLE_AMOUNT']:
        word_operation_code.append(
            f'\tBitString *{component.id} = {component.description[0]}('
            f'input, {component.output_bit_size}, {component.description[1]});')
    else:
        word_operation_code.append(
            f'\tBitString *{component.id} = {component.description[0]}('
            f'input, {component.output_bit_size});')
    if verbosity:
        component.print_values(word_operation_code)
    free_input(word_operation_code)

    return word_operation_code

def generate_bit_based_vectorized_python_code_string(cipher, store_intermediate_outputs=False,
                                                     verbosity=False, convert_output_to_bytes=False):
    """
    Return string python code needed to evaluate a cipher using a vectorized implementation bit based oriented.

    INPUT:

    - ``cipher`` -- **Cipher object**; a cipher instance
    - ``store_intermediate_outputs`` -- **boolean** (default: `False`); set this flag to True in order to return a list
      with each round output
    - ``verbosity`` -- **boolean** (default: `False`); set to True to make the Python code print the input/output of
      each component
    - ``convert_output_to_bytes`` -- **boolean** (default: `False`)

    EXAMPLES::

        sage: from claasp.ciphers.block_ciphers.speck_block_cipher import SpeckBlockCipher
        sage: from claasp.cipher_modules import code_generator
        sage: speck = SpeckBlockCipher()
        sage: string_python_code = code_generator.generate_bit_based_vectorized_python_code_string(speck)
        sage: string_python_code.split("\n")[0]
        'from claasp.cipher_modules.generic_functions_vectorized_bit import *'
    """
    code = ['from claasp.cipher_modules.generic_functions_vectorized_bit import *\n',
            'def evaluate(input, store_intermediate_outputs):', '  intermediateOutputs={}']

    code.extend([f'  {cipher.inputs[i]}=input[{i}]' for i in range(len(cipher.inputs))])
    for component in cipher.get_all_components():
        params = prepare_input_bit_based_vectorized_python_code_string(component)
        component_types_allowed = ['constant', 'linear_layer', 'concatenate', 'mix_column',
                                   'sbox', 'cipher_output', 'intermediate_output']
        component_descriptions_allowed = ['ROTATE', 'SHIFT', 'SHIFT_BY_VARIABLE_AMOUNT', 'NOT', 'XOR',
                                          'MODADD', 'MODSUB', 'OR', 'AND']
        if component.type in component_types_allowed or (component.type == 'word_operation' and
                                                         component.description[0] in component_descriptions_allowed):
            code.extend(component.get_bit_based_vectorized_python_code(params, convert_output_to_bytes))
        name = component.id
        if verbosity and component.type != 'constant':
            code.append(f'  bit_vector_print_as_hex_values("{name}_output", {name})')
    if store_intermediate_outputs:
        code.append('  return intermediateOutputs')
    else:
        code.append('  return intermediateOutputs["cipher_output"]')

    return '\n'.join(code)

def prepare_input_bit_based_vectorized_python_code_string(component):
    params = [
        f'bit_vector_select_word({component.input_id_links[i]},  {component.input_bit_positions[i]})'
        for i in range(len(component.input_id_links))]

    return params

def constant_to_bitstring(val, output_size):
    ret = []
    _val = int(val, 0)
    for i in range(output_size):
        ret.append((_val >> (output_size - 1 - i)) & 1)

    return ret

def generate_byte_based_vectorized_python_code_string(cipher, store_intermediate_outputs=False, verbosity=False):
    r"""
    Return string python code needed to evaluate a cipher using a vectorized implementation byte based oriented.

    INPUT:

    - ``cipher`` -- **Cipher object**; a cipher instance
    - ``store_intermediate_outputs`` -- **boolean** (default: `False`); set this flag to True in order to return a list
      with each round output
    - ``verbosity`` -- **boolean** (default: `False`); set to True to make the Python code print the input/output of
      each component

    EXAMPLES::

        sage: from claasp.ciphers.block_ciphers.speck_block_cipher import SpeckBlockCipher
        sage: from claasp.cipher_modules import code_generator
        sage: speck = SpeckBlockCipher()
        sage: string_python_code = code_generator.generate_byte_based_vectorized_python_code_string(speck)
        sage: string_python_code.split("\n")[0]
        'from claasp.cipher_modules.generic_functions_vectorized_byte import *'
    """
    cipher.sort_cipher()

    code = ['from claasp.cipher_modules.generic_functions_vectorized_byte import *\n', '\n',
            'def evaluate(input, store_intermediate_outputs):', '  intermediateOutputs={}']
    bit_sizes = {}
    for i in range(len(cipher.inputs)):
        code.append(f'  {cipher.inputs[i]}=input[{i}]')
        bit_sizes[cipher.inputs[i]] = cipher.inputs_bit_size[i]
    for component in cipher.get_all_components():
        params = prepare_input_byte_based_vectorized_python_code_string(bit_sizes, component)
        bit_sizes[component.id] = component.output_bit_size
        component_types_allowed = ['constant', 'linear_layer', 'concatenate', 'mix_column',
                                   'sbox', 'cipher_output', 'intermediate_output']
        component_descriptions_allowed = ['ROTATE', 'SHIFT', 'SHIFT_BY_VARIABLE_AMOUNT', 'NOT', 'XOR',
                                          'MODADD', 'MODSUB', 'OR', 'AND']
        if component.type in component_types_allowed or (component.type == 'word_operation' and
                                                         component.description[0] in component_descriptions_allowed):
            code.extend(component.get_byte_based_vectorized_python_code(params))

        name = component.id

        if verbosity and component.type != 'constant':
            code.append(f'  byte_vector_print_as_hex_values("{name}_input", {params})')
            code.append(f'  byte_vector_print_as_hex_values("{name}_output", {name})')
    if store_intermediate_outputs:
        code.append('  return intermediateOutputs')
    else:
        code.append('  return intermediateOutputs["cipher_output"]')

    return '\n'.join(code)

def prepare_input_byte_based_vectorized_python_code_string(bit_sizes, component):
    params = None
    initial_inputs = component.input_id_links
    bits = component.input_bit_positions
    number_of_inputs = get_number_of_inputs(component)
    input_bit_size = component.input_bit_size
    if component.type == 'constant':
        return params

    bits_per_input = input_bit_size // number_of_inputs
    words_per_input = math.ceil(bits_per_input / 8)
    # Divide inputs
    real_inputs = [[] for _ in range(number_of_inputs)]
    real_bits = [[] for _ in range(number_of_inputs)]
    bits_read = 0
    inputs_read = 0
    cpt_inputs = 0
    pos_in_input = 0

    while inputs_read < number_of_inputs:
        needed_bits = bits_per_input - bits_read
        remaining_bits = len(bits[cpt_inputs]) - pos_in_input
        if remaining_bits == needed_bits:
            real_inputs[inputs_read].append(cpt_inputs)
            real_bits[inputs_read].append(bits[cpt_inputs][pos_in_input:])
            inputs_read += 1
            cpt_inputs += 1
            bits_read = 0
            pos_in_input = 0
        elif remaining_bits > needed_bits:
            real_inputs[inputs_read].append(cpt_inputs)
            real_bits[inputs_read].append(bits[cpt_inputs][pos_in_input:(pos_in_input + needed_bits)])
            inputs_read += 1
            bits_read = 0
            pos_in_input += needed_bits
        elif remaining_bits < needed_bits:
            real_inputs[inputs_read].append(cpt_inputs)
            real_bits[inputs_read].append(bits[cpt_inputs][pos_in_input:])
            bits_read += len(bits[cpt_inputs][pos_in_input:])
            cpt_inputs += 1
            pos_in_input = 0
    actual_input_size = [bit_sizes[x] for x in component.input_id_links]
    params = f'byte_vector_select_all_words([{",".join(initial_inputs)}], ' \
             f'{real_bits}, {real_inputs}, {number_of_inputs}, ' \
             f'{words_per_input}, {actual_input_size})'

    is_good = True
    if len(initial_inputs) == number_of_inputs:
        for i in range(number_of_inputs):
            if bits[i] != list(range(actual_input_size[i])):
                is_good = False
        if is_good:
            params = f'[{",".join(initial_inputs)}]'

    return params

def get_number_of_inputs(component):
    number_of_inputs = None
    if component.type == 'word_operation':
        description = component.description[0]
        if description in {'ROTATE', 'SHIFT', 'SHIFT_BY_VARIABLE_AMOUNT', 'NOT'}:
            number_of_inputs = 1
        else:
            number_of_inputs = component.description[1]
    elif component.type == 'mix_column':
        number_of_inputs = len(component.description[0])
    elif component.type == 'linear_layer':
        number_of_inputs = len(component.description[0])
    elif component.type == 'sbox':
        number_of_inputs = 1
    elif component.type == 'concatenate':
        number_of_inputs = 1
    elif 'output' in component.type:
        number_of_inputs = 1

    return number_of_inputs

def constant_to_repr(val, output_size):
    _val = int(val, 0)
    if output_size % 8 != 0:
        s = output_size + (8 - (output_size % 8))
    else:
        s = output_size
    ret = [(_val >> s - (8 * (i + 1))) & 0xff for i in range(s // 8)]

    return ret

def generate_evaluate_c_code_shared_library(cipher, intermediate_output, verbosity):
    name = cipher.id + "_evaluate"
    cipher_word_size = cipher.is_power_of_2_word_based()
    if cipher_word_size:
        if not os.path.exists(TII_C_LIB_PATH + f"generic_word_{cipher_word_size}_based_c_functions.o"):
            call(["gcc", "-w", "-c", TII_C_LIB_PATH + "generic_word_based_c_functions.c", "-o", TII_C_LIB_PATH +
                  f"generic_word_{cipher_word_size}_based_c_functions.o", "-D", f"word_size={cipher_word_size}"])

        f = open(TII_C_LIB_PATH + name + ".c", "w+")
        f.write(cipher.generate_word_based_c_code(cipher_word_size, intermediate_output, verbosity))
        f.close()

        call(["gcc",
              "-w",
              TII_C_LIB_PATH + f"generic_word_{cipher_word_size}_based_c_functions.o",
              TII_C_LIB_PATH + name + ".c",
              "-o",
              TII_C_LIB_PATH + name + ".o",
              "-D",
              f"word_size={cipher_word_size}"])

    else:
        generic_bit_based_c_functions_o_file = "generic_bit_based_c_functions.o"
        if not os.path.exists(TII_C_LIB_PATH + generic_bit_based_c_functions_o_file):
            call(["gcc", "-w", "-c", TII_C_LIB_PATH + "generic_bit_based_c_functions.c",
                  "-o", TII_C_LIB_PATH + generic_bit_based_c_functions_o_file])

        f = open(TII_C_LIB_PATH + name + ".c", "w+")
        f.write(cipher.generate_bit_based_c_code(intermediate_output, verbosity))
        f.close()

        call(["gcc", "-w", TII_C_LIB_PATH + generic_bit_based_c_functions_o_file,
              TII_C_LIB_PATH + name + ".c", "-o", TII_C_LIB_PATH + name + ".o"])

def generate_python_code_string(cipher, verbosity=False):
    r"""
    Return a string containing the python code that defines the self.evaluate() method.

    INPUT:

    - ``cipher`` -- **Cipher object**; a cipher instance
    - ``verbosity`` -- **boolean** (default: `False`); set to True to make the Python code print the input/output of
      each component

    EXAMPLES::

        sage: from claasp.ciphers.block_ciphers.fancy_block_cipher import FancyBlockCipher
        sage: from claasp.cipher_modules import code_generator
        sage: fancy = FancyBlockCipher()
        sage: string_python_code = code_generator.generate_python_code_string(fancy)
        sage: "def evaluate(input):" in string_python_code
        True

        # This test is skipped due to it changes the order of the intermediate outputs sometimes as:
        # intermediate_output['cipher_output'] = []
        # intermediate_output['round_key_output'] = []
        sage: from claasp.ciphers.block_ciphers.identity_block_cipher import IdentityBlockCipher
        sage: from claasp.cipher_modules import code_generator
        sage: identity = IdentityBlockCipher()
        sage: print(code_generator.generate_python_code_string(identity, verbosity=True)) # doctest: +SKIP
        from copy import copy
        from bitstring import BitArray
        from claasp.cipher_modules.generic_functions import *
        <BLANKLINE>
        def evaluate(input):
            plaintext_output = copy(BitArray(uint=input[0], length=32))
            key_output = copy(BitArray(uint=input[1], length=32))
            intermediate_output = {}
            intermediate_output['round_key_output'] = []
            intermediate_output['cipher_output'] = []
            components_io = {}
            component_input = BitArray(1)
            print('\nRound_0\n')
        <BLANKLINE>
            # round: 0, component: 0, component_id: concatenate_0_0
            component_input = select_bits(key_output, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
            output_bit_size = 32
            concatenate_0_0_output = component_input
            components_io['concatenate_0_0'] = [component_input.uint, concatenate_0_0_output.uint]
            print('concatenate_0_0_input = {}'.format(component_input))
            print('concatenate_0_0_output = {}'.format(concatenate_0_0_output))
        ...
        <BLANKLINE>
            # round: 0, component: 3, component_id: cipher_output_0_3
            component_input = select_bits(concatenate_0_2_output, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
            output_bit_size = 32
            cipher_output_0_3_output = component_input
            intermediate_output['cipher_output'].append(cipher_output_0_3_output.uint)
            cipher_output = cipher_output_0_3_output.uint
            components_io['cipher_output_0_3'] = [component_input.uint, cipher_output_0_3_output.uint]
            print('cipher_output_0_3_input = {}'.format(component_input))
            print('cipher_output_0_3_output = {}'.format(cipher_output_0_3_output))
        <BLANKLINE>
            return cipher_output, intermediate_output, components_io
        <BLANKLINE>
    """

    cipher.sort_cipher()

    cipher_code_string = "from copy import copy\n"
    cipher_code_string += "from bitstring import BitArray\n"
    cipher_code_string += "from claasp.cipher_modules.generic_functions import *\n"
    cipher_code_string += "\n"
    cipher_code_string += "def evaluate(input):\n"

    for i in range(len(cipher.inputs)):
        cipher_code_string += "    " + cipher.inputs[i] + "_output = copy(BitArray(uint=int(input[" + \
                              str(i) + "]), length=" + str(
            cipher.inputs_bit_size[i]) + "))\n"

    cipher_code_string += "    intermediate_output = {}\n"

    intermediate_output = set()
    number_of_rounds = cipher.number_of_rounds
    for cipher_round in cipher.rounds_as_list:
        for component in cipher_round.components:
            if component.type == INTERMEDIATE_OUTPUT or \
                    component.type == CIPHER_OUTPUT:
                intermediate_output.add(component.description[0])

    for int_out in intermediate_output:
        cipher_code_string += "    intermediate_output['" + int_out + "'] = []\n"

    cipher_code_string += "    components_io = {}\n"

    # initialize component input for the first constant component
    cipher_code_string += "    component_input = BitArray(1)\n"

    for i in range(number_of_rounds):
        if verbosity:
            cipher_code_string += "    print('\\nRound_" + str(i) + "\\n')\n"

        cipher_code_string = build_code_for_components(cipher, cipher_code_string, i, verbosity)

    cipher_code_string += "\n    return cipher_output, intermediate_output, components_io\n"

    return cipher_code_string

def build_code_for_components(cipher, cipher_code_string, i, verbosity):
    for j in range(cipher.get_number_of_components_in_round(i)):
        cipher_code_string += "\n    # round: {}, component: {}, component_id: {}".format(
            i, j, cipher.component_from(i, j).id) + "\n"
        component = cipher.component_from(i, j)

        # build input (if constant no input is needed)
        if component.type != CONSTANT:
            tmp = ["select_bits(" + component.input_id_links[input_bit_positions_counter] +
                   "_output, " + str(component.input_bit_positions[input_bit_positions_counter]) +
                   ")" for input_bit_positions_counter in range(len(component.input_id_links))]
            component_input = " + ".join(tmp)
            cipher_code_string += "    component_input = " + component_input + "\n"
        else:
            cipher_code_string += "    component_input = BitArray(1)\n"

        # set output
        cipher_code_string += "    output_bit_size = " + str(component.output_bit_size) + "\n"

        function_call_as_string = build_function_call(component)
        component_id_output = component.id + "_output"
        cipher_code_string += "    " + component_id_output + " = " + function_call_as_string + "\n"

        if component.type == INTERMEDIATE_OUTPUT or component.type == CIPHER_OUTPUT:
            cipher_code_string += "    intermediate_output['" + \
                                  component.description[0] + "'].append(" + component_id_output + ".uint)\n"

        if component.type == CIPHER_OUTPUT:
            cipher_code_string += "    cipher_output = " + component_id_output + ".uint\n"

        cipher_code_string += "    components_io['" + component.id + \
                              "'] = [component_input.uint, " + component_id_output + ".uint]\n"

        if verbosity:
            cipher_code_string += "    print('" + component.id + "_input = {}'.format(component_input))\n"
            cipher_code_string += "    print('" + component.id + \
                                  "_output = {}'.format(" + component.id + "_output))\n"
    return cipher_code_string

def build_function_call(component):
    if component.type == SBOX:
        sbox_table = component.description
        return f"sbox(component_input, {sbox_table}, output_bit_size)"
    elif component.type == LINEAR_LAYER:
        linear_layer_matrix = component.description
        return f"linear_layer(component_input, {linear_layer_matrix})"
    elif component.type == MIX_COLUMN:
        mix_column_matrix = component.description[0]
        polynomial = component.description[1]
        word_size = component.description[2]
        return f"mix_column_generalized(component_input, {mix_column_matrix}, {polynomial}, {word_size})"
    elif component.type == WORD_OPERATION:
        if component.description[0] in ('SHIFT_BY_VARIABLE_AMOUNT', 'ROTATE_BY_VARIABLE_AMOUNT'):
            return f"{component.description[0]}" \
                   f"(component_input, {component.output_bit_size}, {component.description[1]})"
        elif component.description[0] == 'NOT':
            return f"{component.description[0]}(component_input)"
        else:
            return f"{component.description[0]}(component_input, {component.description[1]})"
    elif component.type == CONSTANT:
        return f"set_from_hex_string('{component.description[0]}')"
    elif component.type == CONCATENATE:
        return "component_input"
    elif component.type == PADDING:
        return "padding(component_input)"
    elif component.type == INTERMEDIATE_OUTPUT:
        return "component_input"
    elif component.type == CIPHER_OUTPUT:
        return "component_input"
    else:
        raise NotImplementedError("Component not implemented yet")

def generate_python_code_string_for_continuous_diffusion_analysis(cipher, verbosity=False):
    """
    Return a string containing the python code that defines a self.evaluate_continuous_diffusion_analysis() method.

    INPUT:

    - ``cipher`` -- **Cipher object**; a cipher instance
    - ``verbosity`` -- **boolean** (default: `False`); set to True to make the Python code print the input/output of
      each component

    EXAMPLES::

        sage: from claasp.ciphers.block_ciphers.speck_block_cipher import SpeckBlockCipher
        sage: from claasp.cipher_modules import code_generator
        sage: speck = SpeckBlockCipher(number_of_rounds=2)
        sage: string_python_code = code_generator.generate_python_code_string_for_continuous_diffusion_analysis(speck, verbosity=False)
        sage: "def evaluate(input):" in string_python_code
        True
    """

    number_of_rounds = cipher.number_of_rounds

    cipher.sort_cipher()
    add_verbosity = verbosity
    cipher_code_string = \
        "from claasp.cipher_modules.generic_functions_continuous_diffusion_analysis import *\n"
    cipher_code_string += "\n"
    cipher_code_string += "def evaluate(input):\n"
    # initialize inputs
    cipher_code_string += "".join(f"    {cipher_input}_output = input[{round_number}]\n"
                                  for round_number, cipher_input in enumerate(cipher.inputs))

    cipher_code_string += "    intermediate_output = {}\n"
    intermediate_output = set()

    for component in cipher.get_all_components():
        if component.type in (INTERMEDIATE_OUTPUT, CIPHER_OUTPUT):
            intermediate_output.add(component.description[0])
    cipher_code_string += "".join(f"    intermediate_output['{int_out}'] = []\n" for int_out in intermediate_output)

    for round_number in range(number_of_rounds):
        if add_verbosity:
            cipher_code_string += f"    print('\\nRound_{round_number}\\n')\n"

        cipher_code_string = build_code_for_continuous_diffusion_analysis_components(add_verbosity, cipher,
                                                                                cipher_code_string, round_number)

    cipher_code_string += "\n    return cipher_output, intermediate_output\n"

    return cipher_code_string

def build_code_for_continuous_diffusion_analysis_components(add_verbosity, cipher, cipher_code_string, round_number):
    for component_number in range(cipher.get_number_of_components_in_round(round_number)):
        cipher_code_string += \
            f"\n    # round: {round_number}, component: {component_number}, " \
            f"component_id: {cipher.component_from(round_number, component_number).id}\n"
        component = cipher.component_from(round_number, component_number)

        # build input (if constant no input is needed)
        if component.type != CONSTANT:
            tmp = [
                f"select_bits_continuous_diffusion_analysis({id_link}_output, {bit_positions})" for id_link,
                bit_positions in zip(component.input_id_links, component.input_bit_positions)]
            cipher_code_string += f"    component_input = {' + '.join(tmp)}\n"

        _function = build_continuous_diffusion_analysis_function_call(component)
        component_id_output = f"{component.id}_output"
        cipher_code_string += f"    {component_id_output} = {_function}\n"

        if component.type in (INTERMEDIATE_OUTPUT, CIPHER_OUTPUT):
            cipher_code_string += \
                f"    intermediate_output['{component.description[0]}']" \
                f".append({{'intermediate_output': {component_id_output}, 'round': {round_number + 1}}})\n"

        if component.type == CIPHER_OUTPUT:
            cipher_code_string += f"    cipher_output = {component_id_output}\n"  # + ".uint\n"

        if add_verbosity and component.type != CONSTANT:
            cipher_code_string += f"    print(f'{component.id}_input = {{component_input}}')\n"
            cipher_code_string += f"    print(f'{component.id}_output = {{{component.id}_output}}')\n"
    return cipher_code_string

def build_continuous_diffusion_analysis_function_call(component):
    if component.type == SBOX:
        sbox_table = component.description
        return (
            f'SBOX_continuous_diffusion_analysis('
            f'component_input, sbox_precomputations["{sbox_table}"]'
            f')'
        )
    elif component.type == LINEAR_LAYER:
        linear_layer_matrix = component.description
        return f"LINEAR_LAYER_continuous_diffusion_analysis(component_input, {linear_layer_matrix})"
    elif component.type == MIX_COLUMN:
        mix_column_matrix = component.description[0]
        word_size = component.description[2]
        return (
            f'MIX_COLUMN_generalized_continuous_diffusion_analysis('
            f'component_input, {mix_column_matrix}, '
            f'sbox_precomputations_mix_columns["{component.description}"], '
            f'{word_size})'
        )
    elif component.type == WORD_OPERATION:
        description = component.description[1]
        if component.description[0] in ('SHIFT_BY_VARIABLE_AMOUNT', 'ROTATE_BY_VARIABLE_AMOUNT'):
            description = f"{component.output_bit_size}, {component.description[1]}"
        if component.description[0] == 'NOT':
            return f"{component.description[0]}_continuous_diffusion_analysis(component_input)"
        else:
            return f"{component.description[0]}_continuous_diffusion_analysis(component_input, {description})"
    elif component.type == CONSTANT:
        return f"CONSTANT_continuous_diffusion_analysis({component.description[0]}, " \
               f"{component.output_bit_size})"
    elif component.type in [CONCATENATE, INTERMEDIATE_OUTPUT, CIPHER_OUTPUT]:
        return "component_input"
    elif component.type == PADDING:
        return "padding(component_input)"
    else:
        raise NotImplementedError("Continuous Diffusion Analysis component not implemented yet")

def generate_word_based_c_code(cipher, word_size, intermediate_output, verbosity):
    code = ['#include <stdio.h>', '#include <stdbool.h>', '#include <stdlib.h>',
            '#include "generic_word_based_c_functions.h"\n']
    function_args = []
    for cipher_input in cipher.inputs:
        function_args.append(f'WordString *{cipher_input}')
    function_declaration = f'WordString* evaluate({", ".join(function_args)}) {{'
    code.append(function_declaration)
    code.append('\tWordString input_struct = {')
    code.append('\t\t.list = NULL,')
    code.append('\t\t.string_size = 0')
    code.append('\t};')
    code.append('\tWordString *input = &input_struct;')
    if verbosity:
        code.append('\tchar *str;')
    code.extend(get_rounds_word_based_c_code(cipher, intermediate_output, verbosity, word_size))
    code.append('}')
    code.append('int main(int argc, char *argv[]) {{')
    evaluate_args = []
    for i in range(len(cipher.inputs)):
        evaluate_args.append(cipher.inputs[i])
        code.append(f'\tWordString* {cipher.inputs[i]} = '
                    f'wordstring_from_hex_string(argv[{i + 1}], '
                    f'{cipher.inputs_bit_size[i] // word_size});')
    code.append(f'\tWordString* output = evaluate({", ".join(evaluate_args)});')
    if not intermediate_output:
        code.append('\tprint_wordstring(output, 16);')
    evaluate_args.append('output')
    code.append(f'\tdelete({", ".join(evaluate_args)});')
    code.append('}')

    return '\n'.join(code)

def get_rounds_word_based_c_code(cipher, intermediate_output, verbosity, word_size):
    rounds_code = []
    wordstring_variables = []
    string_dictionary = {}
    list_sizes = []
    intermediate_output_code = []
    index = 0
    for round_number in cipher.rounds_as_list:
        if verbosity:
            rounds_code.append(f'\tprintf("\\nROUND {round_number.id}\\n\\n");\n')
        for component in round_number.components:
            is_shift_or_rotate_component = component.type == 'word_operation' and \
                                           component.description[0] in ['SHIFT', 'ROTATE',
                                                                        'SHIFT_BY_VARIABLE_AMOUNT',
                                                                        'ROTATE_BY_VARIABLE_AMOUNT']
            if component.type in ['constant', 'sbox', 'concatenate'] or is_shift_or_rotate_component:
                rounds_code.extend(component.get_word_based_c_code(verbosity, word_size, wordstring_variables))
            elif component.type == 'word_operation':
                rounds_code.extend(get_word_operation_word_based_c_code(component, verbosity,
                                                                        word_size, wordstring_variables))
            elif component.type == 'intermediate_output':
                component_code, index = get_intermediate_output_word_based_c_code(
                    component, index, intermediate_output, intermediate_output_code, list_sizes,
                    string_dictionary, verbosity, word_size, wordstring_variables)
                rounds_code.extend(component_code)
            elif component.type == 'cipher_output':
                component_code, index = get_cipher_output_word_based_c_code(
                    component, index, intermediate_output, intermediate_output_code, list_sizes,
                    string_dictionary, verbosity, word_size, wordstring_variables)
                rounds_code.extend(component_code)
            else:
                raise ValueError(f'Component {component.id} not available.')

    return rounds_code

def get_cipher_output_word_based_c_code(component, index, intermediate_output, intermediate_output_code,
                                        list_sizes, string_dictionary, verbosity, word_size, wordstring_variables):
    code = []
    component.select_words(code, word_size, False)
    output = component.id
    if verbosity:
        code.append(f'\tstr = wordstring_to_hex_string({component.id});')
        code.append(f'\tprintf("{component.id} input: %s\\n", str);')
        code.append(f'\tprintf("{component.id} output: %s\\n", str);')
        code.append('\tfree(str);')
    if intermediate_output:
        update_intermediate_structure(string_dictionary, list_sizes, intermediate_output_code, component, index)
        number_of_descriptions = len(string_dictionary)
        description_list = [''] * number_of_descriptions
        for description, index in string_dictionary.items():
            description_list[index] = f'"{description}"'
        code.append(f'\tchar **output_list[{number_of_descriptions}];')
        for i in range(len(list_sizes)):
            code.append(f'\tchar *output_list_{i}[{list_sizes[i]}];')
            code.append(f'\toutput_list[{i}] = output_list_{i};')
        code.extend(intermediate_output_code)
        code.append(f'\tchar *descriptions[] = {{{", ".join(description_list)}}};')
        code.append(f'\tuint8_t lenghts[] = {{{", ".join([str(x) for x in list_sizes])}}};')
        code.append('\tprintf("{");')
        code.append(f'\tfor (int i = 0; i < {number_of_descriptions}; i++) {{')
        code.append('\t\tprintf("\\"%s\\" : [", descriptions[i]);')
        code.append('\t\tfor (int j = 0; j < lenghts[i]; j++) {')
        code.append('\t\t\tprintf("%s, ", output_list[i][j]);')
        code.append('\t\t\tfree(output_list[i][j]);')
        code.append('\t\t}')
        code.append('\t\tprintf("],\\n");')
        code.append('\t}')
        code.append('\tprintf("}");')
    code.append(f'\tdelete({", ".join(wordstring_variables)});')
    code.append(f'\treturn {output};')

    return code, index

def get_intermediate_output_word_based_c_code(component, index, intermediate_output, intermediate_output_code,
                                              list_sizes, string_dictionary, verbosity, word_size,
                                              wordstring_variables):
    code = []
    component.select_words(code, word_size, False)
    wordstring_variables.append(component.id)
    if verbosity:
        code.append(f'\tstr = wordstring_to_hex_string({component.id});')
        code.append(f'\tprintf("{component.id} input: %s\\n", str);')
        code.append(f'\tprintf("{component.id} output: %s\\n", str);')
        code.append('\tfree(str);')
    if intermediate_output and component.type == 'intermediate_output':
        index = update_intermediate_structure(string_dictionary, list_sizes, intermediate_output_code,
                                              component, index)
    return code, index

def get_word_operation_word_based_c_code(component, verbosity, word_size, wordstring_variables):
    word_operation_code = []
    component.select_words(word_operation_code, word_size)
    wordstring_variables.append(component.id)
    word_operation_code.append(f'\tWordString *{component.id} = {component.description[0]}(input);')
    if verbosity:
        component.print_word_values(word_operation_code)

    return word_operation_code

def update_intermediate_structure(string_dictionary, list_sizes, intermediate_output_code, component, index):
    component_description = component.description[0]

    if component_description in string_dictionary:
        i = string_dictionary[component_description]
        list_sizes[i] += 1

    else:
        string_dictionary[component_description] = index
        list_sizes.append(1)
        i = index
        index += 1

    intermediate_output_code.append(
        f'\toutput_list[{i}][{list_sizes[i] - 1}] = wordstring_to_hex_string({component.id});')

    return index


# code based on my original, modified by Mike Stucka (thus fml) and me
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urlparse
import os
from bs4 import BeautifulSoup
import urllib2
import csv

for i in os.listdir(os.getcwd()):
    if i.startswith('ChargesInter'):
        url = i
        ids = urlparse.parse_qs(url)
        idbo = ids.get('bo')
        #print idbo
        soup = BeautifulSoup(open(url))
        #above works
        f = open('charges.csv', 'ab')
        writer = csv.writer(f)

        table2 = soup.find('table', attrs={'id':"DataList2"})
        try:
            for fmltable in table2.findAll('table'): # Inside our DataList2 table is an table holding the table contents for each charge.
                for chargetable in fmltable.findAll('table'):   # Now we're looking at the actual charge table
                    list_of_fields = [idbo[0]]  # Pull out booking number thingy from list, just as a string.
                    #print list_of_fields
                    for field in chargetable.findAll('td'):
                        text = field.text.split("  ")[-1]       # Let's look for everything after a couple spaces. This seems to work.
                        list_of_fields.append(text)
                        #print list_of_fields

                    writer.writerow(list_of_fields)     # Write it to CSV.

        except:
            continue

         # You still need to close out your csvwriter
        f.close()


#import relevant libraries
from flask import Flask, jsonify, request, render_template
import pandas as pd
import numpy as np
import pickle
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

app = Flask(__name__)

model = pickle.load(open("capstone.pkl", 'rb')) #load model

@app.route('/')
def home():
    return render_template('/form_upload_1.html') #page to upload csv file

@app.route('/prediction',methods = ['POST'])
def upload_route_summary():
    if request.method == 'POST':

        # Create variable for uploaded file
        f = request.files['fileupload']

        #convert the csv file to dataframe
        df = pd.read_csv(f)
        ss = StandardScaler()
        df_ss  = ss.fit_transform(df)#scale the data

        df['buy_prob'] = [prob[1] for prob in model.predict_proba(df_ss)]#generate predict proba
        df['Customer ID']=np.arange(len(df)).astype(str)

        ## Generating random phone numbers

        from random import randint
        def random_with_N_digits(n):
            range_start = 10**(n-1)
            range_end = (10**n)-1
            return randint(range_start, range_end)

        df['phone number'] =1

        df['phone number'] = df['phone number'].apply(lambda x:f'{9}{random_with_N_digits(7)}')

        submission = df[['Customer ID','phone number' ,'buy_prob']]
        leads =submission.loc[df.buy_prob >0.5].sort_values(['buy_prob'], ascending= False).reset_index(drop= True) #slice the dataframe so that we show only the important columns and hides index

        pred_html = leads.to_html(col_space=100) #convert dataframe to html
#        pred_html =df.head(20).to_html(col_space=100)
#    return render_template("pred_html", output = output)

    return pred_html

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


from .. import models, schemas, utils
from fastapi import FastAPI, HTTPException, Response, status, Depends,APIRouter
from ..database import get_db
from sqlalchemy.orm import Session
from typing import List, Optional
from .. import oauth2

router = APIRouter(
     prefix="/receptionist",
     tags=['Receptionist']

)

""" RECEPTIONIST """
# Create receptionist

@router.post("/", status_code=status.HTTP_201_CREATED)
def create_receptionist(receptionist: schemas.ReceptionistCreate, db: Session = Depends(get_db),
                         current_user: int = Depends(oauth2.get_current_user)):
    receptionist = models.Receptionist(user_id= current_user.id, **receptionist.dict())
    db.add(receptionist)
    db.commit()
    db.refresh(receptionist)
    return receptionist

# Read single receptionist

@router.get("/{id}", response_model=schemas.ReceptionistResponse)
def get_receptionist(id: str, db: Session = Depends(get_db),
                     current_user: int = Depends(oauth2.get_current_user)):
    receptionist = db.query(models.Receptionist).filter(
        models.Receptionist.id == id).first()

    if not receptionist:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Receptionist with id: {id} was not found")
    return receptionist

# Read All receptionists

@router.get("/", response_model=List[schemas.ReceptionistResponse])
def get_receptionist(db: Session = Depends(get_db),
                     current_user: int = Depends(oauth2.get_current_user), limit: int = 10, skip: int = 0, search: Optional[str] = ""):
    receptionist = db.query(models.Receptionist)\
    .filter(models.Receptionist.user_id == current_user.id)\
    .filter(models.Receptionist.firstname.ilike(f'%{search}%'))\
    .limit(limit)\
    .offset(skip)\
    .all()
    return receptionist

# Update receptionist

@router.put("/{id}", response_model=schemas.ReceptionistResponse)
def update_receptionist(id: str, updated_receptionist: schemas.ReceptionistCreate, db: Session = Depends(get_db),
                        current_user: int = Depends(oauth2.get_current_user)):

    receptionist_query = db.query(models.Receptionist).filter(
        models.Receptionist.id == id)

    receptionist = receptionist_query.first()

    if receptionist == None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Receptionist with id: {id} does not exist")

    if receptionist.user_id != current_user.id:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail=f"Not authorized to perform requested action")

    receptionist_query.update(
        updated_receptionist.dict(), synchronize_session=False)
    db.commit()
    return receptionist_query.first()

# Delete receptionist
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_receptionist(id: str, db: Session = Depends(get_db),
                        current_user: int = Depends(oauth2.get_current_user)):

    receptionist_query = db.query(models.Receptionist).filter(
        models.Receptionist.id == id)

    receptionist = receptionist_query.first()

    if receptionist == None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Receptionist with id: {id} does not exist")

    if receptionist.user_id != current_user.id:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail=f"Not authorized to perform requested action")

    receptionist_query.delete(synchronize_session=False)
    db.commit()
    return Response(status_code=status.HTTP_204_NO_CONTENT)


#! env python
# -*- coding: utf-8 -*-

import unittest

# ctci.7_7
# Design an algorithm to find the kth number such that the only prime factors are 3,5, and 7.
# Date: 2020/10/25
# Filename: 7_7
# Author: koucs

def find_kth_num_of_prime_factors(k: int) -> int:
    # num = 3^a * 5^b * 7^c
    # O(n^2) algorithm
    num_list = [1]
    for i in range(k):
        min_val = 1_000_000
        candidate_prime_factor = None
        for j in num_list:
            if j * 3 < min_val and j * 3 not in num_list:
                min_val = j * 3
            if j * 5 < min_val and j * 5 not in num_list:
                min_val = j * 5
            if j * 7 < min_val and j * 7 not in num_list:
                min_val = j * 7
        num_list.append(min_val)
    return num_list[k - 1]

def find_kth_num_of_prime_factors_ans(k: int) -> int:
    q3 = [3]
    q5 = [5]
    q7 = [7]
    num_list = [1]
    for i in range(k):
        if q3[0] < q5[0] and q3[0] < q7[0]:
            num_list.append(q3.pop(0))
            q3.append(num_list[-1] * 3)
            q5.append(num_list[-1] * 5)
            q7.append(num_list[-1] * 7)
        elif q5[0] < q7[0]:
            num_list.append(q5.pop(0))
            q5.append(num_list[-1] * 5)
            q7.append(num_list[-1] * 7)
        else:
            num_list.append(q7.pop(0))
            q7.append(num_list[-1] * 7)
    return num_list[k - 1]

class Test(unittest.TestCase):
    def test_1(self):
        self.assertEqual(1, find_kth_num_of_prime_factors(1))
        self.assertEqual(9, find_kth_num_of_prime_factors(5))
        self.assertEqual(63, find_kth_num_of_prime_factors(13))

        self.assertEqual(1, find_kth_num_of_prime_factors_ans(1))
        self.assertEqual(9, find_kth_num_of_prime_factors_ans(5))
        self.assertEqual(63, find_kth_num_of_prime_factors_ans(13))
        return

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


import os
import json

name = input("name:")

root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

result = []

for _file in os.listdir(root + "/" + name):
	full_name = root + "/" + name + "/" + _file

	with open(full_name, "r") as f:
		s = f.read()

	result.append(json.loads(s))

with open("result.json", "w") as f:
	f.write(json.dumps(result))


def solution(board):
    answer = 0
    dp = [[0] * (len(board[0]) + 1) for _ in range(len(board) + 1)]
    max_edge = 0

    for i in range(1, len(board) + 1):
        for j in range(1, len(board[0]) + 1):
            if board[i - 1][j - 1] == 1:
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1
                max_edge = max(max_edge, dp[i][j])
    answer = max_edge**2
    return answer

def solution2(board):
    answer = 0
    edges = [[num for num in row] for row in board]
    max_edge = max(edges[0])

    for i in range(1, len(board)):
        for j in range(1, len(board[0])):
            if board[i][j] == 1:
                edges[i][j] = (
                    min(edges[i - 1][j], edges[i][j - 1], edges[i - 1][j - 1]) + 1
                )
                max_edge = max(edges[i][j], max_edge)

    answer = max_edge**2
    return answer


from cmath import inf
from pacai.agents.learning.value import ValueEstimationAgent

class ValueIterationAgent(ValueEstimationAgent):
    """
    A value iteration agent.

    Make sure to read `pacai.agents.learning` before working on this class.

    A `ValueIterationAgent` takes a `pacai.core.mdp.MarkovDecisionProcess` on initialization,
    and runs value iteration for a given number of iterations using the supplied discount factor.

    Some useful mdp methods you will use:
    `pacai.core.mdp.MarkovDecisionProcess.getStates`,
    `pacai.core.mdp.MarkovDecisionProcess.getPossibleActions`,
    `pacai.core.mdp.MarkovDecisionProcess.getTransitionStatesAndProbs`,
    `pacai.core.mdp.MarkovDecisionProcess.getReward`.

    Additional methods to implement:

    `pacai.agents.learning.value.ValueEstimationAgent.getQValue`:
    The q-value of the state action pair (after the indicated number of value iteration passes).
    Note that value iteration does not necessarily create this quantity,
    and you may have to derive it on the fly.

    `pacai.agents.learning.value.ValueEstimationAgent.getPolicy`:
    The policy is the best action in the given state
    according to the values computed by value iteration.
    You may break ties any way you see fit.
    Note that if there are no legal actions, which is the case at the terminal state,
    you should return None.
    """

    def __init__(self, index, mdp, discountRate=0.9, iters=100, **kwargs):
        super().__init__(index, **kwargs)

        self.mdp = mdp
        self.discountRate = discountRate
        self.iters = iters

        # A dictionary which holds the q-values for each state.
        # Each state starts with value 0.0
        self.values = {}
        for state in self.mdp.getStates():
            self.values[state] = 0.0

        # Set the q-value for each state over iters iterations
        for _ in range(iters):
            values = dict(self.values)
            for state in self.mdp.getStates():
                bestAction = self.getPolicy(state)
                if not bestAction:  # terminal state, value stays 0.0
                    continue
                values[state] = self.getQValue(state, bestAction)
            self.values = values

    def getValue(self, state):
        """
        Return the value of the state (computed in __init__).
        """

        return self.values.get(state, 0.0)

    def getPolicy(self, state):
        """
        returns the best action according to computed values
        """

        # return none if so no legal actions remain
        if self.mdp.isTerminal(state):
            return None

        bestValue = -inf
        bestAction = None

        # return action that has the highest q-value
        for action in self.mdp.getPossibleActions(state):
            value = self.getQValue(state, action)
            if bestValue < value:
                bestValue = value
                bestAction = action
        return bestAction

    def getQValue(self, state, action):
        """
        returns the q-value of the (state, action) pair.
        """

        # Q = sum(probabilty(s,a) * (reward(s, a, s') + discountRate * values[s']))
        Q = 0
        for transitionState, probabilty in self.mdp.getTransitionStatesAndProbs(state, action):
            reward = self.mdp.getReward(state, action, transitionState)
            Q += probabilty * \
                (reward + (self.discountRate * self.values[transitionState]))

        return Q

    def getAction(self, state):
        """
        Returns the policy at the state (no exploration).
        """

        return self.getPolicy(state)


#!/usr/bin/env python

import tensorflow as tf

def main(unused_argv):
    config = tf.ConfigProto(device_count={'GPU': 0})
    with tf.Session(config=config) as sess:

        node1 = tf.constant(3.0, tf.float32)
        node2 = tf.constant(4.0) # also tf.float32 implicitly

        node3 = tf.add(node1, node2)

        print("node1: ", node1)
        print("node2: ", node2)
        print("node3: ", node3)
        print("sess.run(node3): ", sess.run(node3))
    return sess

def __call__(self, *args, **kwargs):
    session = main([])
    return "Test 1 Complet!", session


def collatz(number):
	if number % 2 == 0:
		return number // 2
	else:
		return 3 * number + 1

try:
	number = int(input('Enter stat number:'))
	while True:
		collatzRes = collatz(number)
		print(collatzRes)
		if collatzRes == 1:
			break
		number = collatzRes
except ValueError:
	print('Only integer value is valid!')


from pywinauto.application import Application
from pywinauto import Desktop
from pywinauto.keyboard import send_keys
import time
import pyuac
def main():
    path = "\\Path\\"
    app = Application().start(r'msiexec /i ' + path)

if __name__=="__main__":
    if not pyuac.isUserAdmin():
        pyuac.runAsAdmin()
    else:
        main()

#example of key sents
time.sleep(1)
send_keys("{ENTER}")
time.sleep(1)
send_keys("{SPACE}")
time.sleep(1)
send_keys("{ENTER}")
time.sleep(1)
send_keys("{ENTER}")
time.sleep(180)
send_keys("{ENTER}")


#http://www.deanclatworthy.com/imdb/

from xml.dom.minidom import parse
#import xml.dom
from urllib import request
from urllib.parse import quote
from ast import literal_eval
from time import sleep

dom = parse('episodelist-in.xml')
domEpisodeList = dom.getElementsByTagName('episode')

apiNetloc = 'http://www.deanclatworthy.com/imdb/'
keys = ['imdbid', 'country']

for node in domEpisodeList:

   titleStr = node.getElementsByTagName('movie')[0].firstChild.data
   ttID = node.getElementsByTagName('id')[0].firstChild.nodeValue
   year = node.getElementsByTagName('year')[0].firstChild.nodeValue
   titleUrl = quote(titleStr)

   url = apiNetloc + '?q=' + titleUrl + '&year=' + year

   get = request.urlopen(url)
   byteResult = get.read()
   strResult = byteResult.decode()
   dictResult = literal_eval(strResult)

   print(titleStr)
   try:
     dictResult['year']
   except KeyError:
     print('^- key error')
     sleep(120)
     continue

   for key in keys:

     items = dictResult[key].split(',')

     if key == 'imdbid':

       if ''.join(items) != ttID:
          flag = dom.createElement('unconfirmed')
          node.appendChild(flag)

     else:

        for item in items:
          element = dom.createElement(key.lower())
          data = dom.createTextNode(str(item))
          element.appendChild(data)
          insertPoint = node.getElementsByTagName('genre')[0]
          node.insertBefore(element, insertPoint)

   sleep(120)

with open('episodelist-out.xml', 'w', encoding='utf-8') as f:
  f.write(dom.toxml('utf-8').decode('utf-8'))


import redis
import json
import time

redis_handle = redis.StrictRedis("127.0.0.1", 6379 ,0,decode_responses = True )

while True:

   data = {"a":1,"b":2 }
   data_json = json.dumps(data)
   redis_handle.lpush("work_queue",data_json)
   redis_handle.ltrim("work_queue",0, 100)
   print("pushing data")
   time.sleep(2)


# ライブラリのインポート
import numpy as np
import matplotlib.pyplot as plt

# データの読み込み
data = np.genfromtxt("output/outputKobe.txt")

# 新しいウィンドウにグラフを作成
plt.figure(1)

# グラフにデータをプロット
plt.plot(data[:,0] * 0.02 , data[:,1], label="responseAcc(m/s/s)", color="red", linestyle="solid", linewidth=1.0)
plt.plot(data[:,0] * 0.02 , data[:,2], label="inputWave(m/s/s)", color="blue", linestyle="solid", linewidth=0.5)

# 最大値／最小値を表示
num = 17996
valuelistAcc = [] #数値を格納する配列
valuelistInput = [] #数値を格納する配列

for i in range(num):
    valueAcc   = data[i,1]
    valueInput = data[i,2]
    valuelistAcc.append(valueAcc)
    valuelistInput.append(valueInput)

print("maxValueAcc=")
print(max(valuelistAcc))
print("minValueAcc=")
print(min(valuelistAcc))
print("maxValueInput=")
print(max(valuelistInput))
print("minValueInput=")
print(min(valuelistInput))

# 軸の調整
plt.xlim([0, 200])  # X軸の範囲を指定
plt.ylim([-20, 20])  # Y軸の範囲を指定

# グラフに情報を表示
plt.title("JMA_KobeWave_NS")
plt.xlabel("time(s)")  # x軸のラベル
plt.ylabel("acc(m/s/s)")  # y軸のラベル
plt.legend(loc="lower right")  # 汎例
plt.grid(True)  # グリッド線

# グラフの描画を実行
plt.savefig("output/equationOfMotion.png")
plt.show()


import torch
import torch.nn as nn

class SiameseConvNet2(nn.Module):
    def __init__(self):
        super(SiameseConvNet2, self).__init__()
        self.length = 14
        self.input_size = 1 * 14 * 14
        # we need an intermediate output,
        # because we are using a siamese network
        intermediate_output_size = 10
        self.n_outputs = 10
        # two digit output, probability of being 1 or 0:
        final_output_size = 2

        # flatten images to 1D input:
        self.flatten = nn.Flatten()
        # convolutional layers
        kernel_size = 3
        n_channel = 5
        self.conv_layer = nn.Sequential(nn.Conv2d(1, n_channel, kernel_size),
                                        nn.ReLU(),
                                        nn.Conv2d(n_channel, 2 *
                                                  n_channel, kernel_size),
                                        nn.ReLU(),
                                        nn.Conv2d(2 * n_channel, 4 *
                                                  n_channel, kernel_size),
                                        nn.BatchNorm2d(4 * n_channel),
                                        nn.ReLU(),
                                        nn.Dropout2d(p=0.3),
                                        nn.Conv2d(4 * n_channel, 8 *
                                                  n_channel, kernel_size),
                                        nn.ReLU(),
                                        nn.Dropout2d(p=0.4),
                                        nn.Conv2d(8 * n_channel, 16 *
                                                  n_channel, kernel_size),
                                        nn.ReLU(),
                                        nn.Dropout2d(p=0.5),
                                        nn.Conv2d(16 * n_channel,
                                                  32 * n_channel, kernel_size),
                                        nn.ReLU(),
                                        nn.Dropout2d(p=0.6)
                                        )

        def compute_conv2d_size(length):
            return length - (kernel_size - 1) - 1 + 1

        length_out = self.length
        depth = 4

        for i in range(depth):
            length_out = compute_conv2d_size(length_out)

        # For 10 digits:
        concat_size = 640
        self.fcout1 = nn.Linear(concat_size, intermediate_output_size)

        # For 0-1 output:
        self.fcout2 = nn.Linear(2 * intermediate_output_size,
                                final_output_size,
                                bias=False)

    def forward(self, x):
        x1 = x[:, 0].view(-1, 1, self.length, self.length)
        x2 = x[:, 1].view(-1, 1, self.length, self.length)
        # x1.shape = torch.Size([64, 1, 14, 14])

        x1 = self.conv_layer(x1)
        # x1.shape = torch.Size([64, 160, 2, 2])
        x1 = x1.view(-1, 640)
        # x1.shape = torch.Size([64, 640])

        # Size batch x 10 (cipher predictions on image)
        out1 = self.fcout1(x1)
        # out1.shape = torch.Size([64, 10])

        x2 = self.conv_layer(x2)
        x2 = x2.view(-1, 640)
        # Size batch x 10 (cipher predictions on image)
        out2 = self.fcout1(x2)

        # ------------------------------------------------------------------
        # 0-1 Prediction
        # Predict if first image bigger than second
        # ------------------------------------------------------------------

        # concatenate into size (batch x 20)
        output = torch.cat((out1, out2), 1)
        # predict probabilities:
        logits = self.fcout2(output)

        return out1.view(-1, self.n_outputs), out2.view(-1,
                                                        self.n_outputs), logits


# weather
OWM_KEY = 'abcdefabcdefabcdefabcdefabcdefab'
LAT = -31.946041
LON = 115.920222
CACHE_PERIOD = 300

# aircon
UUID = 'CI001abcde'
RETRIES = 2

# composer
ON_THRESHOLD = 29
OFF_THRESHOLD = 27

# scheduler
CRON_SECONDS = '0,30'

# heartbeat
HA_PRIORITY = 2


from fastapi import FastAPI
import json
import requests
import time

# Load the llm config from the json file provided on command line
with open("model.json", 'r') as file:
    model = json.load(file)

# Whip the llama into gear
DEFAULT_SYSTEM = "You are a helpful assistant who will always answer the question with only the data provided"
DEFAULT_PROMPT = "Entity:\n{%D}\nDescribe the {%E} in a single paragraph, without saying it's a JSON object or including any URLs or images:"
DEFAULT_TOKENS = 512 # many words
DEFAULT_TEMP = 0.7 # very mild temp for more boring results

# Fast API init
app = FastAPI(
        title="SumBot",
        description="Send me a JSON record and say what kind of entity it is (movie, transaction, person) and I'll summarize it with an LLM",
        version="1.1",
        contact={
            "name": "Pat Wendorf",
            "email": "pat.wendorf@mongodb.com",
    },
    license_info={
        "name": "MIT License",
        "url": "https://opensource.org/license/mit/",
    }
)

def remove_extra_formatting(text):
    cleaned_text = text.replace("\n", " ") # remove newline
    cleaned_text = cleaned_text.replace("\t", " ") # remove tabs
    cleaned_text = cleaned_text.replace("  ", " ") # remove double spaces
    return cleaned_text

# Endpoint to compare 2 images by URL and show similarity
@app.post("/summarize")
async def summarize_json_data(entity_type: str, input_json: str):

    # Build the prompt
    prompt = model["prompt_format"].replace("{%S}", DEFAULT_SYSTEM)
    prompt = prompt.replace("{%P}", DEFAULT_PROMPT)
    prompt = prompt.replace("{%D}", input_json)
    prompt = prompt.replace("{%E}", entity_type)

    api_data = {
        "prompt": prompt,
        "n_predict": DEFAULT_TOKENS,
        "temperature": DEFAULT_TEMP,
        "stop": model["stop_tokens"],
        "tokens_cached": 0
    }

    # Time the process
    start_time = time.time()
    try:
        # Call the model API
        response = requests.post(model["llama_endpoint"], headers={"Content-Type": "application/json"}, json=api_data)
        json_output = response.json()
        end_time = time.time()
        milliseconds_elapsed = (end_time - start_time) * 1000
        output = {"summary": remove_extra_formatting(json_output['content']), "ms": round(milliseconds_elapsed)}
    except:
        output = {"error": "My AI model is not responding try again in a moment 🔥🐳"}

    # remove annoying formatting in output
    return output


import torch
import numpy as np

def create_fashion_inference():
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    use_gpu = True if torch.cuda.is_available() else False
    fashion = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'DCGAN', pretrained=True, useGPU=use_gpu)
    fashion_noise, _ = fashion.buildNoiseData(1)
    @torch.inference_mode()
    def fashion_generator(latents):
        latents = [torch.from_numpy(latent).float().to(device) for latent in latents]
        latents = torch.stack(latents)
        out = fashion.test(latents)
        outs = []
        for out_i in out:
            out_i = ((out_i.permute(1,2,0) + 1) * 127.5).clamp(0,255).cpu().numpy()
            out_i = np.uint8(out_i)
            outs.append(out_i)
        return outs

    return {
        'name': 'Fashion',
        'generator': fashion_generator,
        'latent_dim': fashion_noise.shape[1],
        'fps': 15,
        'batch_size': 8,
        'strength': 0.6,
        'max_duration': 30,
        'use_peak': True
    }


class Personne:

    def __init__(self, nom:str):
        self.nom = nom
    def SePresenter(self):
        print("bonjour, je m'appelle " + self.nom)
nbrePer = 3
noms = []
for i in range(0,nbrePer):
    noms.append(input("nom de la personne"+str(i+1)+" :"))
l= []
for nom in noms:
    l.append(Personne(nom))

for p in l:
 p.SePresenter()


##############################################################################
#
#   DEMO Application
#
##############################################################################
from pymongo        import MongoClient                                       #
from jinja2         import Environment,FileSystemLoader                      #
from twisted.python import log                                               #
from autobahn       import wamp                                              #
##############################################################################

class Subscriptions:
    """handle class subscriptions"""
    def __init__(self,conf=None,extra=None):
        self.conf = conf
        self.extra = extra

class Registrations:
    """handle class registrations"""
    def __init__(self,conf=None,extra=None):
        self.conf = conf
        self.extra = extra
        self.mongo = MongoClient()
        self.env = Environment(loader=FileSystemLoader('../../static/html'),extensions=["jinja2.ext.do",])
    #
    #   Ok, we need this to resolve sessions back to authid's
    #   Hopefully when we get passed authid's , this will get easier
    #
    def getSession(self,details):
        """ lookup details for the current user """
        id = getattr(details,'caller')
        if not id:
            log.msg("% ERROR - missing caller field")
            return None
        session = self.mongo.ionman.sessions.find_one({'session':id})
        if not session:
            log.msg("% ERROR - missing session record")
            return None

        user = self.mongo.ionman.users.find_one({'authid':session.get('authid','')})
        if not user:
            log.msg("% ERROR - missing user record")
            return None

        return user

    @wamp.register(u'demo.page.render')
    def app_load_preferences(self,params,details):
        """ load up a requested page """
        try:
            user = self.getSession(details)
            page = params.get('uri','welcome.html');
            tmpl = self.env.get_template(page)
            my_dict = {
                'name'      : user.get('name',''),
                'role'      : user.get('role',''),
                'authid'    : user.get('authid',''),
                'uri'       : page
            }
            return { 'html':tmpl.render(my_dict) }
        except:
            log.err()
            return { 'html':'' }


from RamirezFunctions import *
import turtle
bob = turtle.Turtle()
bob.speed(0)
turtle.bgcolor("black")

for times in range(256):
    bob.circle(120)
    bob.color("purple")
    bob.forward(160)
    bob.backward(160)
    bob.left(79)

    bob.circle(130)
    bob.color("blue")
    bob.forward(200)
    bob.backward(200)
    bob.left(79)

    bob.circle(150)
    bob.color("white")
    bob.forward(260)
    bob.backward(260)
    bob.left(72)

    bob.circle(160)
    bob.color("blue")
    bob.forward(260)
    bob.backward(260)
    bob.left(72)


from qiskit.qasm import pi
from qiskit.circuit import EquivalenceLibrary, Parameter, QuantumCircuit, QuantumRegister

from . import (
    HGate,
    CHGate,
    MSGate,
    RGate,
    RCCXGate,
    RC3XGate,
    C3XGate,
    C4XGate,
    RXGate,
    CRXGate,
    RXXGate,
    RYGate,
    CRYGate,
    RZGate,
    CRZGate,
    RZZGate,
    SGate,
    SdgGate,
    SwapGate,
    CSwapGate,
    iSwapGate,
    DCXGate,
    TGate,
    TdgGate,
    U1Gate,
    CU1Gate,
    U2Gate,
    U3Gate,
    CU3Gate,
    XGate,
    CXGate,
    CCXGate,
    YGate,
    CYGate,
    RYYGate,
    ZGate,
    CZGate,
)

_sel = StandardEquivalenceLibrary = EquivalenceLibrary()

# Import existing gate definitions

# HGate

q = QuantumRegister(1, 'q')
def_h = QuantumCircuit(q)
def_h.append(U2Gate(0, pi), [q[0]], [])
_sel.add_equivalence(HGate(), def_h)

# CHGate

q = QuantumRegister(2, 'q')
def_ch = QuantumCircuit(q)
for inst, qargs, cargs in [
        (SGate(), [q[1]], []),
        (HGate(), [q[1]], []),
        (TGate(), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (TdgGate(), [q[1]], []),
        (HGate(), [q[1]], []),
        (SdgGate(), [q[1]], [])
]:
    def_ch.append(inst, qargs, cargs)
_sel.add_equivalence(CHGate(), def_ch)

# MSGate

for num_qubits in range(2, 20):
    q = QuantumRegister(num_qubits, 'q')
    theta = Parameter('theta')
    def_ms = QuantumCircuit(q)
    for i in range(num_qubits):
        for j in range(i + 1, num_qubits):
            def_ms.append(RXXGate(theta), [q[i], q[j]])
    _sel.add_equivalence(MSGate(num_qubits, theta), def_ms)

# RGate

q = QuantumRegister(1, 'q')
theta = Parameter('theta')
phi = Parameter('phi')
def_r = QuantumCircuit(q)
def_r.append(U3Gate(theta, phi - pi / 2, -phi + pi / 2), [q[0]])
_sel.add_equivalence(RGate(theta, phi), def_r)

# RCCXGate

q = QuantumRegister(3, 'q')
def_rccx = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[2]], []),
        (TGate(), [q[2]], []),
        (CXGate(), [q[1], q[2]], []),
        (TdgGate(), [q[2]], []),
        (CXGate(), [q[0], q[2]], []),
        (TGate(), [q[2]], []),
        (CXGate(), [q[1], q[2]], []),
        (TdgGate(), [q[2]], []),
        (HGate(), [q[2]], []),
]:
    def_rccx.append(inst, qargs, cargs)
_sel.add_equivalence(RCCXGate(), def_rccx)

# RC3XGate

q = QuantumRegister(4, 'q')
def_rc3x = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[3]], []),
        (TGate(), [q[3]], []),
        (CXGate(), [q[2], q[3]], []),
        (TdgGate(), [q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[0], q[3]], []),
        (TGate(), [q[3]], []),
        (CXGate(), [q[1], q[3]], []),
        (TdgGate(), [q[3]], []),
        (CXGate(), [q[0], q[3]], []),
        (TGate(), [q[3]], []),
        (CXGate(), [q[1], q[3]], []),
        (TdgGate(), [q[3]], []),
        (HGate(), [q[3]], []),
        (TGate(), [q[3]], []),
        (CXGate(), [q[2], q[3]], []),
        (TdgGate(), [q[3]], []),
        (HGate(), [q[3]], []),
]:
    def_rc3x.append(inst, qargs, cargs)
_sel.add_equivalence(RC3XGate(), def_rc3x)

# C3XGate

q = QuantumRegister(4, 'q')
def_c3x = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[3]], []),
        (CU1Gate(-pi/4), [q[0], q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[0], q[1]], []),
        (HGate(), [q[3]], []),
        (CU1Gate(pi/4), [q[1], q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[0], q[1]], []),
        (HGate(), [q[3]], []),
        (CU1Gate(-pi/4), [q[1], q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[1], q[2]], []),
        (HGate(), [q[3]], []),
        (CU1Gate(pi/4), [q[2], q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[0], q[2]], []),
        (HGate(), [q[3]], []),
        (CU1Gate(-pi/4), [q[2], q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[1], q[2]], []),
        (HGate(), [q[3]], []),
        (CU1Gate(pi/4), [q[2], q[3]], []),
        (HGate(), [q[3]], []),
        (CXGate(), [q[0], q[2]], []),
        (HGate(), [q[3]], []),
        (CU1Gate(-pi/4), [q[2], q[3]], []),
        (HGate(), [q[3]], [])
]:
    def_c3x.append(inst, qargs, cargs)
_sel.add_equivalence(C3XGate(), def_c3x)

# C4XGate

q = QuantumRegister(5, 'q')
def_c4x = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[4]], []),
        (CU1Gate(-pi / 2), [q[3], q[4]], []),
        (HGate(), [q[4]], []),
        (C3XGate(), [q[0], q[1], q[2], q[3]], []),
        (HGate(), [q[4]], []),
        (CU1Gate(pi / 2), [q[3], q[4]], []),
        (HGate(), [q[4]], []),
        (C3XGate(), [q[0], q[1], q[2], q[3]], []),
        (C3XGate(pi / 8), [q[0], q[1], q[2], q[4]], []),
]:
    def_c4x.append(inst, qargs, cargs)
_sel.add_equivalence(C4XGate(), def_c4x)

# RXGate

q = QuantumRegister(1, 'q')
theta = Parameter('theta')
def_rx = QuantumCircuit(q)
def_rx.append(RGate(theta, 0), [q[0]], [])
_sel.add_equivalence(RXGate(theta), def_rx)

# CRXGate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_crx = QuantumCircuit(q)
for inst, qargs, cargs in [
        (U1Gate(pi / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U3Gate(-theta / 2, 0, 0), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U3Gate(theta / 2, -pi / 2, 0), [q[1]], [])
]:
    def_crx.append(inst, qargs, cargs)
_sel.add_equivalence(CRXGate(theta), def_crx)

# RXXGate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_rxx = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[0]], []),
        (HGate(), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U1Gate(theta), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (HGate(), [q[1]], []),
        (HGate(), [q[0]], []),
]:
    def_rxx.append(inst, qargs, cargs)
_sel.add_equivalence(RXXGate(theta), def_rxx)

# RYGate

q = QuantumRegister(1, 'q')
theta = Parameter('theta')
def_ry = QuantumCircuit(q)
def_ry.append(RGate(theta, pi / 2), [q[0]], [])
_sel.add_equivalence(RYGate(theta), def_ry)

# CRYGate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_cry = QuantumCircuit(q)
for inst, qargs, cargs in [
        (U3Gate(theta / 2, 0, 0), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U3Gate(-theta / 2, 0, 0), [q[1]], []),
        (CXGate(), [q[0], q[1]], [])
]:
    def_cry.append(inst, qargs, cargs)
_sel.add_equivalence(CRYGate(theta), def_cry)

# RYYGate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_ryy = QuantumCircuit(q)
for inst, qargs, cargs in [
        (RXGate(pi / 2), [q[0]], []),
        (RXGate(pi / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (RZGate(theta), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (RXGate(-pi / 2), [q[0]], []),
        (RXGate(-pi / 2), [q[1]], []),
]:
    def_ryy.append(inst, qargs, cargs)
_sel.add_equivalence(RYYGate(theta), def_ryy)

# RZGate

q = QuantumRegister(1, 'q')
theta = Parameter('theta')
def_rz = QuantumCircuit(q)
def_rz.append(U1Gate(theta), [q[0]], [])
_sel.add_equivalence(RZGate(theta), def_rz)

# CRZGate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_crz = QuantumCircuit(q)
for inst, qargs, cargs in [
        (U1Gate(theta / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U1Gate(-theta / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], [])
]:
    def_crz.append(inst, qargs, cargs)
_sel.add_equivalence(CRZGate(theta), def_crz)

# RZZGate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_rzz = QuantumCircuit(q)
for inst, qargs, cargs in [
        (CXGate(), [q[0], q[1]], []),
        (U1Gate(theta), [q[1]], []),
        (CXGate(), [q[0], q[1]], [])
]:
    def_rzz.append(inst, qargs, cargs)
_sel.add_equivalence(RZZGate(theta), def_rzz)

# SGate

q = QuantumRegister(1, 'q')
def_s = QuantumCircuit(q)
def_s.append(U1Gate(pi / 2), [q[0]], [])
_sel.add_equivalence(SGate(), def_s)

# SdgGate

q = QuantumRegister(1, 'q')
def_sdg = QuantumCircuit(q)
def_sdg.append(U1Gate(-pi / 2), [q[0]], [])
_sel.add_equivalence(SdgGate(), def_sdg)

# SwapGate

q = QuantumRegister(2, 'q')
def_swap = QuantumCircuit(q)
for inst, qargs, cargs in [
        (CXGate(), [q[0], q[1]], []),
        (CXGate(), [q[1], q[0]], []),
        (CXGate(), [q[0], q[1]], [])
]:
    def_swap.append(inst, qargs, cargs)
_sel.add_equivalence(SwapGate(), def_swap)

# iSwapGate

q = QuantumRegister(2, 'q')
def_iswap = QuantumCircuit(q)
for inst, qargs, cargs in [
        (SGate(), [q[0]], []),
        (SGate(), [q[1]], []),
        (HGate(), [q[0]], []),
        (CXGate(), [q[0], q[1]], []),
        (CXGate(), [q[1], q[0]], []),
        (HGate(), [q[1]], [])
]:
    def_iswap.append(inst, qargs, cargs)
_sel.add_equivalence(iSwapGate(), def_iswap)

# DCXGate

q = QuantumRegister(2, 'q')
def_dcx = QuantumCircuit(q)
for inst, qargs, cargs in [
        (CXGate(), [q[0], q[1]], []),
        (CXGate(), [q[1], q[0]], [])
]:
    def_dcx.append(inst, qargs, cargs)
_sel.add_equivalence(DCXGate(), def_dcx)

q = QuantumRegister(2, 'q')
dcx_to_iswap = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[0]], []),
        (SdgGate(), [q[0]], []),
        (SdgGate(), [q[1]], []),
        (iSwapGate(), [q[0], q[1]], []),
        (HGate(), [q[1]], [])
]:
    dcx_to_iswap.append(inst, qargs, cargs)
_sel.add_equivalence(DCXGate(), dcx_to_iswap)

# CSwapGate

q = QuantumRegister(3, 'q')
def_cswap = QuantumCircuit(q)
for inst, qargs, cargs in [
        (CXGate(), [q[2], q[1]], []),
        (CCXGate(), [q[0], q[1], q[2]], []),
        (CXGate(), [q[2], q[1]], [])
]:
    def_cswap.append(inst, qargs, cargs)
_sel.add_equivalence(CSwapGate(), def_cswap)

# TGate

q = QuantumRegister(1, 'q')
def_t = QuantumCircuit(q)
def_t.append(U1Gate(pi / 4), [q[0]], [])
_sel.add_equivalence(TGate(), def_t)

# TdgGate

q = QuantumRegister(1, 'q')
def_tdg = QuantumCircuit(q)
def_tdg.append(U1Gate(-pi / 4), [q[0]], [])
_sel.add_equivalence(TdgGate(), def_tdg)

# U1Gate

q = QuantumRegister(1, 'q')
phi = Parameter('phi')
lam = Parameter('lam')
def_u2 = QuantumCircuit(q)
def_u2.append(U3Gate(pi / 2, phi, lam), [q[0]], [])
_sel.add_equivalence(U2Gate(phi, lam), def_u2)

# CU1Gate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
def_cu1 = QuantumCircuit(q)
for inst, qargs, cargs in [
        (U1Gate(theta / 2), [q[0]], []),
        (CXGate(), [q[0], q[1]], []),
        (U1Gate(-theta / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U1Gate(theta / 2), [q[1]], [])
]:
    def_cu1.append(inst, qargs, cargs)
_sel.add_equivalence(CU1Gate(theta), def_cu1)

# U2Gate

q = QuantumRegister(1, 'q')
theta = Parameter('theta')
def_u1 = QuantumCircuit(q)
def_u1.append(U3Gate(0, 0, theta), [q[0]], [])
_sel.add_equivalence(U1Gate(theta), def_u1)

# U3Gate

# CU3Gate

q = QuantumRegister(2, 'q')
theta = Parameter('theta')
phi = Parameter('phi')
lam = Parameter('lam')
def_cu3 = QuantumCircuit(q)
for inst, qargs, cargs in [
        (U1Gate((lam + phi) / 2), [q[0]], []),
        (U1Gate((lam - phi) / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U3Gate(-theta / 2, 0, -(phi + lam) / 2), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (U3Gate(theta / 2, phi, 0), [q[1]], [])
]:
    def_cu3.append(inst, qargs, cargs)
_sel.add_equivalence(CU3Gate(theta, phi, lam), def_cu3)

# XGate

q = QuantumRegister(1, 'q')
def_x = QuantumCircuit(q)
def_x.append(U3Gate(pi, 0, pi), [q[0]], [])
_sel.add_equivalence(XGate(), def_x)

# CXGate

# CCXGate

q = QuantumRegister(3, 'q')
def_ccx = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[2]], []),
        (CXGate(), [q[1], q[2]], []),
        (TdgGate(), [q[2]], []),
        (CXGate(), [q[0], q[2]], []),
        (TGate(), [q[2]], []),
        (CXGate(), [q[1], q[2]], []),
        (TdgGate(), [q[2]], []),
        (CXGate(), [q[0], q[2]], []),
        (TGate(), [q[1]], []),
        (TGate(), [q[2]], []),
        (HGate(), [q[2]], []),
        (CXGate(), [q[0], q[1]], []),
        (TGate(), [q[0]], []),
        (TdgGate(), [q[1]], []),
        (CXGate(), [q[0], q[1]], [])
]:
    def_ccx.append(inst, qargs, cargs)
_sel.add_equivalence(CCXGate(), def_ccx)

# YGate

q = QuantumRegister(1, 'q')
def_y = QuantumCircuit(q)
def_y.append(U3Gate(pi, pi / 2, pi / 2), [q[0]], [])
_sel.add_equivalence(YGate(), def_y)

# CYGate

q = QuantumRegister(2, 'q')
def_cy = QuantumCircuit(q)
for inst, qargs, cargs in [
        (SdgGate(), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (SGate(), [q[1]], [])
]:
    def_cy.append(inst, qargs, cargs)
_sel.add_equivalence(CYGate(), def_cy)

# ZGate

q = QuantumRegister(1, 'q')
def_z = QuantumCircuit(q)
def_z.append(U1Gate(pi), [q[0]], [])
_sel.add_equivalence(ZGate(), def_z)

# CZGate

q = QuantumRegister(2, 'q')
def_cz = QuantumCircuit(q)
for inst, qargs, cargs in [
        (HGate(), [q[1]], []),
        (CXGate(), [q[0], q[1]], []),
        (HGate(), [q[1]], [])
]:
    def_cz.append(inst, qargs, cargs)
_sel.add_equivalence(CZGate(), def_cz)


class Solution:
    """
    @param n: a decimal number
    @param k: a Integer represent base-k
    @return: a base-k number
    """
    def hexConversion(self, n, k):
        ret = ''
        digits = "0123456789ABCDEF"
        if n < k : return str(n)
        while n != 0 :
            ret += digits[n % k]
            n = n // k
        return ret[::-1]

# 总耗时 628 ms
# 您的提交打败了 97.33% 的提交!


import cv2
import os
import random
import numpy as np
from matplotlib import pyplot as plt
import uuid

from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import Layer, Conv2D, Dense, MaxPooling2D, Input, Flatten
import tensorflow as tf

gpus = tf.config.experimental.list_physical_devices('GPU')
print(gpus)
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)

POS_PATH = os.path.join('data', 'positive')
NEG_PATH = os.path.join('data', 'negative')
ANC_PATH = os.path.join('data', 'anchor')
#
# os.makedirs(POS_PATH)
# os.makedirs(NEG_PATH)
# os.makedirs(ANC_PATH)
#
# cap = cv2.VideoCapture(0)
# while cap.isOpened():
#     ret, frame = cap.read()
#
#     # Promjena veličine framea na 250x250 kako bi se uslikalo samo lice
#     frame = frame[10:10 + 250, 180:180 + 250, :]
#
#     # Prikupljanje anchor fotografija
#     if cv2.waitKey(1) & 0XFF == ord('a'):
#         # Stvaranje jedinstvenog imena slike
#         imgname = os.path.join(ANC_PATH, '{}.jpg'.format(uuid.uuid1()))
#         # Spremanje slike u mapu
#         cv2.imwrite(imgname, frame)
#
#     # Prikupljanje pozitivnih fotografija
#     if cv2.waitKey(1) & 0XFF == ord('p'):
#         # Stvaranje jedinstvenog imena slike
#         imgname = os.path.join(POS_PATH, '{}.jpg'.format(uuid.uuid1()))
#         # Spremanje slike u mapu
#         cv2.imwrite(imgname, frame)
#
#     # Prikaz slike
#     cv2.imshow('Fotografija', frame)
#
#     # Izlazak iz petlje
#     if cv2.waitKey(1) & 0XFF == ord('q'):
#         break
#
# # Gašenje kamere
# cap.release()
# # Zatvaranje svih novootvorenih prozora
# cv2.destroyAllWindows()

#Dohvacanje 300 fotografija iz svake mape
anchor = tf.data.Dataset.list_files(ANC_PATH+'\*.jpg').take(300)
positive = tf.data.Dataset.list_files(POS_PATH+'\*.jpg').take(300)
negative = tf.data.Dataset.list_files(NEG_PATH+'\*.jpg').take(300)

#Oznacavanje pozitivnih fotografija s 1, i negativnih s 0
positives = tf.data.Dataset.zip((anchor, positive, tf.data.Dataset.from_tensor_slices(tf.ones(len(anchor)))))
negatives = tf.data.Dataset.zip((anchor, negative, tf.data.Dataset.from_tensor_slices(tf.zeros(len(anchor)))))
data = positives.concatenate(negatives)

def preprocess(file_path):
    # Čitanje slike iz putanje
    byte_img = tf.io.read_file(file_path)
    # Učitavanje slike
    img = tf.io.decode_jpeg(byte_img)

    # Smanjenje slike na 100x100 piksela
    img = tf.image.resize(img, (100, 100))
    # Smanjenje slike da bude izmedu 0 i 1
    img = img / 255.0

    return img

def preprocess_twin(input_img, validation_img, label):
    return(preprocess(input_img), preprocess(validation_img),label)

data = data.map(preprocess_twin)
data = data.cache()
data = data.shuffle(buffer_size=10000)

# samples = data.as_numpy_iterator()
# samp = samples.next()
#
# img = plt.imshow(samp[0])
# plt.show()
# img2 = plt.imshow(samp[1])
# print(samp[2])
# plt.show()

#Training
train_data = data.take(round(len(data)*.7))
train_data = train_data.batch(16)
train_data = train_data.prefetch(8)

# Testing
test_data = data.skip(round(len(data)*.7))
test_data = test_data.take(round(len(data)*.3))
test_data = test_data.batch(16)
test_data = test_data.prefetch(8)

test_input, test_val, y_true = test_data.as_numpy_iterator().next()

img3 = cv2.subtract(test_input[0],test_val[0])

plt.subplot(1, 4, 1)
plt.imshow(test_input[0])

plt.subplot(1, 4, 2)
plt.imshow(test_val[0])

plt.subplot(1, 4, 3)
plt.imshow(test_input[0][2])

plt.subplot(1, 4, 4)
plt.imshow(test_val[0][2])

plt.show()

def make_embedding():
    inp = Input(shape=(100, 100, 3), name='input_image')

    # First block
    c1 = Conv2D(64, (10, 10), activation='relu')(inp)
    m1 = MaxPooling2D(64, (2, 2), padding='same')(c1)

    # Second block
    c2 = Conv2D(128, (7, 7), activation='relu')(m1)
    m2 = MaxPooling2D(64, (2, 2), padding='same')(c2)

    # Third block
    c3 = Conv2D(128, (4, 4), activation='relu')(m2)
    m3 = MaxPooling2D(64, (2, 2), padding='same')(c3)

    # Final embedding block
    c4 = Conv2D(256, (4, 4), activation='relu')(m3)
    f1 = Flatten()(c4)
    d1 = Dense(4096, activation='sigmoid')(f1)

    return Model(inputs=[inp], outputs=[d1], name='embedding')

embedding = make_embedding()

#embedding.summary()

# Siamese L1 Distance class
class L1Dist(Layer):

    # Init method - inheritance
    def __init__(self, **kwargs):
        super().__init__()

    # Magic happens here - similarity calculation
    def call(self, input_embedding, validation_embedding):
        return tf.math.abs(input_embedding - validation_embedding)

#siamese_network.summary()

def make_siamese_model():
    # Anchor image input in the network
    input_image = Input(name='input_img', shape=(100, 100, 3))

    # Validation image in the network
    validation_image = Input(name='validation_img', shape=(100, 100, 3))

    # Combine siamese distance components
    siamese_layer = L1Dist()
    siamese_layer._name = 'distance'
    distances = siamese_layer(embedding(input_image), embedding(validation_image))

    # Classification layer
    classifier = Dense(1, activation='sigmoid')(distances)

    return Model(inputs=[input_image, validation_image], outputs=classifier, name='SiameseNetwork')

siamese_model = make_siamese_model()
siamese_model.summary()

binary_cross_loss = tf.losses.BinaryCrossentropy()
opt = tf.keras.optimizers.Adam(1e-4) # 0.0001

@tf.function
def train_step(batch):
    # Record all of our operations
    with tf.GradientTape() as tape:
        # Get anchor and positive/negative image
        X = batch[:2]
        # Get label
        y = batch[2]

        # Forward pass
        yhat = siamese_model(X, training=True)
        # Calculate loss
        loss = binary_cross_loss(y, yhat)
    print(loss)

    # Calculate gradients
    grad = tape.gradient(loss, siamese_model.trainable_variables)

    # Calculate updated weights and apply to siamese model
    opt.apply_gradients(zip(grad, siamese_model.trainable_variables))

    # Return loss
    return loss

from tensorflow.python.keras.metrics import Precision, Recall

def train(data, EPOCHS):
    # Loop through epochs
    for epoch in range(1, EPOCHS + 1):
        print('\n Epoch {}/{}'.format(epoch, EPOCHS))
        progbar = tf.keras.utils.Progbar(len(data))

        # Creating a metric object
        r = Recall()
        p = Precision()

        # Loop through each batch
        for idx, batch in enumerate(data):
            # Run train step here
            loss = train_step(batch)
            yhat = siamese_model.predict(batch[:2])
            r.update_state(batch[2], yhat)
            p.update_state(batch[2], yhat)
            progbar.update(idx + 1)
        print(loss.numpy(), r.result().numpy(), p.result().numpy())

EPOCHS = 50

train(train_data, EPOCHS)
#
#Get a batch of test data

#
#
# Set plot size
#plt.figure(figsize=(10,8))

# i = 0
# for x in range(16):
#     # Set first subplot
#     plt.subplot(1, 4, 1)
#     plt.imshow(test_input[x][0])
#
#     plt.subplot(1, 4, 2)
#     plt.imshow(test_input[x])
#
#     # Set second subplot
#     plt.subplot(1, 4, 3)
#     plt.imshow(test_val[x][0])
#
#     plt.subplot(1, 4, 4)
#     plt.imshow(test_val[x])
#
#
#     print(y_true[x])
#     # Renders cleanly
#     plt.show()

# siamese_model.save('siamesemodelv2.h5')
# siamese_model.compile()
# # Reload model
# siamese_model2 = tf.keras.models.load_model('siamesemodelv2.h5',custom_objects={'L1Dist':L1Dist, 'BinaryCrossentropy':tf.losses.BinaryCrossentropy},compile=True)
#
# #siamese_model2 = tf.saved_model.load('siamesemodelv2.h5')
# # Make predictions with reloaded model
#
# test_input, test_val, y_true = test_data.as_numpy_iterator().next()
#
# y_hat = siamese_model2.predict([test_input, test_val])
# # Post processing the results
# res = []
# print(y_hat)
# for prediction in y_hat:
#     if prediction > 0.5:
#         res.append(1)
#     else:
#         res.append(0)
#
#
# #print(res[0])
# print(res)
# #print(y_true)
#
#
# from tensorflow.python.keras.metrics import Precision, Recall
# r = Recall()
# p = Precision()
#
# for test_input, test_val, y_true in test_data.as_numpy_iterator():
#     yhat = siamese_model2.predict([test_input, test_val])
#     r.update_state(y_true, yhat)
#     p.update_state(y_true,yhat)
#
# print("Recall ", r.result().numpy())
# print("Precision ", p.result().numpy())
#
# siamese_model2.predict([test_input, test_val])
#
# siamese_model2.summary()

os.listdir(os.path.join('application_data', 'verification_images'))
os.path.join('application_data', 'input_image', 'input_image.jpg')

for image in os.listdir(os.path.join('application_data', 'verification_images')):
    validation_img = os.path.join('application_data', 'verification_images', image)
    print(validation_img)

def verify(model, detection_threshold, verification_threshold):
    # Build results array
    results = []
    for image in os.listdir(os.path.join('application_data', 'verification_images')):
        input_img = preprocess(os.path.join('application_data', 'input_image', 'input_image.jpg'))
        validation_img = preprocess(os.path.join('application_data', 'verification_images', image))

        # Make Predictions
        result = model.predict(list(np.expand_dims([input_img, validation_img], axis=1)))
        results.append(result)

    # Detection Threshold: Metric above which a prediciton is considered positive
    detection = np.sum(np.array(results) > detection_threshold)

    # Verification Threshold: Proportion of positive predictions / total positive samples
    verification = detection / len(os.listdir(os.path.join('application_data', 'verification_images')))
    verified = verification > verification_threshold

    return results, verified

cap = cv2.VideoCapture(0)
while cap.isOpened():
    ret, frame = cap.read()
    frame = frame[10:10 + 250, 180:180 + 250, :]

    cv2.imshow('Verification', frame)

    # Verification trigger
    if cv2.waitKey(10) & 0xFF == ord('v'):
        # Save input image to application_data/input_image folder
        #         hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        #         h, s, v = cv2.split(hsv)

        #         lim = 255 - 10
        #         v[v > lim] = 255
        #         v[v <= lim] -= 10

        #         final_hsv = cv2.merge((h, s, v))
        #         img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)

        cv2.imwrite(os.path.join('application_data', 'input_image', 'input_image.jpg'), frame)
        # Run verification
        results, verified = verify(siamese_model, 0.5, 0.5)
        print(verified)
        print(results)

    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


#!/usr/bin/env python3
# coding: utf8
import typing
import argparse
import functools
import os
import re
import shutil
import sys
import subprocess as P
import os.path as path

# The background image is of size 1024x1024, the transparent margin on each
# edge is 100px.
BG_IMG = path.join(path.dirname(__file__), "white_bg_1024x1024.png")
BG_WIDTH = 1024
BG_MARGIN = 100
BG_MARGIN_RATIO = 2 * BG_MARGIN / BG_WIDTH

# Original icon png file name
ORIG_PNG_NAME = "icon_512x512.png"

def gm_cmd(cmd: str, debug: bool = False) -> str:
    """
    GraphicsMagick CLI wrapper
    """
    full_cmd = "gm {}".format(cmd)
    if debug:
        print(full_cmd)
    with os.popen(full_cmd) as f:
        return f.read()

def get_width(filename: str) -> int:
    return parse_width(gm_cmd("identify {}".format(filename)))

def parse_width(s: str) -> int:
    m = re.search(r"(\d+)x(\d+)", s)
    if m is None:
        raise Exception("Unknown dimension string")
    return int(m.group(1))

def overlay(size: int, fg_img: str, output_dir: str, scale: int = 1, delta_x: int = 0, delta_y: int = 0, bg_img: str = BG_IMG) -> str:
    inner_size = int(size * (1 - BG_MARGIN_RATIO) * scale)
    offset = int((size - inner_size) / 2)
    gm_cmd("composite -resize {inner_size}x{inner_size} -geometry +{offset_x}+{offset_y} '{icon}' \
                      -resize {outer_size}x{outer_size} '{background}' '{output}'".format(
        inner_size=inner_size,
        outer_size=size,
        offset_x=offset+delta_x,
        offset_y=offset+delta_y,
        icon=fg_img,
        background=bg_img,
        output=path.join(output_dir, "icon_{0}x{0}.png".format(size))
    ))
    return path.join(output_dir, "icon_{0}x{0}.png".format(size))

def resize(size: int, img: str, output_dir: str) -> None:
    new_name = path.join(output_dir, "icon_{0}x{0}.png".format(size))
    gm_cmd("convert -resize {size}x{size} '{img}' '{new_name}'".format(
        size=size, img=img, new_name=new_name))

def convert_icns_to_iconset(icns_file: str) -> str:
    """
    the `.iconset` file is a folder with PNG images of different size
    """
    output_path = path.abspath(path.basename(icns_file).replace(".icns", ".iconset"))
    __ensure_path_not_exist(output_path)
    c = P.call("iconutil -c iconset -o '{}' '{}'".format(output_path, icns_file), shell=True)
    if c != 0:
        raise Exception("Failed to convert icns")
    return output_path

def convert_iconset_to_icns(iconset_file: str) -> str:
    output_path = path.abspath(iconset_file.replace(".iconset", ".icns"))
    __ensure_path_not_exist(output_path)
    c = P.call("iconutil -c icns -o '{}' '{}'".format(output_path, iconset_file), shell=True)
    if c != 0:
        raise Exception("Failed to convert iconset")
    return output_path

def __ensure_path_not_exist(p: str) -> None:
    if path.exists(p):
        raise Exception("Path {} will be overriden".format(p))

def process(iconset_dir: str, output_dir: str) -> None:
    guess_best_size = None
    for s in [512, 256, 128]:
        if path.exists(path.join(iconset_dir, "icon_{0}x{0}.png".format(s))):
            guess_best_size = s
            break
    if guess_best_size is None:
        raise Exception("The icns doesn't contain icon image with good resolution")
    orig_img = path.join(iconset_dir, "icon_{0}x{0}.png".format(guess_best_size))
    img = overlay(guess_best_size, orig_img, output_dir, scale=0.8)
    for s in [16, 32, 128, 256]:
        if s < guess_best_size:
            resize(s, img, output_dir)

def parse_args():
    p = argparse.ArgumentParser("BigSur icon converter")
    p.add_argument("file", metavar="FILE", type=str)
    p.add_argument("-x", help="x offset", type=int, default=0)
    p.add_argument("-y", help="y offset", type=int, default=0)
    return p.parse_args()

if __name__ == "__main__":
    args = parse_args()
    iconset_dir = convert_icns_to_iconset(args.file)
    output_dir = os.path.abspath("new-" + path.basename(iconset_dir))
    os.mkdir(output_dir)
    try:
        process(iconset_dir, output_dir)
        convert_iconset_to_icns(output_dir)
    except Exception as e:
        print(e)
    finally:
        shutil.rmtree(output_dir)
        shutil.rmtree(iconset_dir)


from PyQt5.Qt import *
import sys

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(1400, 600, 600, 600)
        self.setWindowTitle('')
        self.setup_ui()

    def setup_ui(self):
        line_edit = QLineEdit(self)
        line_edit.resize(200, 200)
        line_edit.setTextMargins(30, 30, 30, 30)
        line_edit.setAlignment(Qt.AlignTop)
        print(line_edit.getTextMargins())
        print(line_edit.alignment())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())

文本输入/输入边距.py