import struct
import traceback
import logging

from ipaddr import IPv4Network

from yabgp.common import exception as excep
from yabgp.common import constants as bgp_cons
from yabgp.message.attribute import AttributeFlag
from yabgp.message.attribute.origin import Origin
from yabgp.message.attribute.aspath import ASPath
from yabgp.message.attribute.nexthop import NextHop
from yabgp.message.attribute.med import MED
from yabgp.message.attribute.localpref import LocalPreference
from yabgp.message.attribute.atomicaggregate import AtomicAggregate
from yabgp.message.attribute.aggregator import Aggregator
from yabgp.message.attribute.community import Community
from yabgp.message.attribute.originatorid import OriginatorID
from yabgp.message.attribute.clusterlist import ClusterList

LOG = logging.getLogger()

class Update(object):

    """
    An UPDATE message is used to advertise feasible routes that share
    common path attributes to a peer, or to withdraw multiple unfeasible
    routes from service (RFC 4271 page 15)
    """

    def __init__(self):
        """
        +----------------------------------------------------+
        |     Withdrawn Routes Length (2 octets)             |
        +----------------------------------------------------+
        |     Withdrawn Routes (variable)                    |
        +----------------------------------------------------+
        |     Total Path Attribute Length (2 octets)         |
        +----------------------------------------------------+
        |     Path Attributes (variable)                     |
        +----------------------------------------------------+
        |  Network Layer Reachability Information (variable) |
        +----------------------------------------------------+

        @ Withdrawn Routes Length:
            This 2-octets unsigned integer indicates the total length of
        the Withdrawn Routes field in octets. Its value allows the
        length of the Network Layer Reachability Information field to
        be determined, as specified below.
            A value of 0 indicates that no routes are being withdrawn from
        service, and that the WITHDRAWN ROUTES field is not present in
        this UPDATE message.

        @ Withdrawn Routes:
            This is a variable-length field that contains a list of IP
        address prefixes for the routes that are being withdrawn from
        service. Each IP address prefix is encoded as a 2-tuple of the
        form <length, prefix>, whose fields are described below:
                    +---------------------------+
                    |     Length (1 octet)      |
                    +---------------------------+
                    |     Prefix (variable)     |
                    +---------------------------+
            The use and the meaning of these fields are as follows:
            a) Length:
            The Length field indicates the length in bits of the IP
            address prefix. A length of zero indicates a prefix that
            matches all IP addresses (with prefix, itself, of zero
            octets).
            b) Prefix:
            The Prefix field contains an IP address prefix, followed by
            the minimum number of trailing bits needed to make the end
            of the field fall on an octet boundary. Note that the value
            of trailing bits is irrelevant.

        @ Total Path Attribute Length:
            This 2-octet unsigned integer indicates the total length of the
        Path Attributes field in octets. Its value allows the length
        of the Network Layer Reachability field to be determined as
        specified below.
            A value of 0 indicates that neither the Network Layer
        Reachability Information field nor the Path Attribute field is
        present in this UPDATE message.

        @ Path Attributes:
            (path attributes details see RFC 4271 and some other RFCs)

        @ Network Layer Reachability Information:
            This variable length field contains a list of IP address
        prefixes. The length, in octets, of the Network Layer
        Reachability Information is not encoded explicitly, but can be
        calculated as:
        UPDATE message Length - 23 - Total Path Attributes Length
        - Withdrawn Routes Length
        where UPDATE message Length is the value encoded in the fixedsize
        BGP header, Total Path Attribute Length, and Withdrawn
        Routes Length are the values encoded in the variable part of
        the UPDATE message, and 23 is a combined length of the fixedsize
        BGP header, the Total Path Attribute Length field, and the
        Withdrawn Routes Length field.
        Reachability information is encoded as one or more 2-tuples of
        the form <length, prefix>, whose fields are described below:
                    +---------------------------+
                    |      Length (1 octet)     |
                    +---------------------------+
                    |      Prefix (variable)    |
                    +---------------------------+
        The use and the meaning of these fields are as follows:
            a) Length:
                The Length field indicates the length in bits of the IP
            address prefix. A length of zero indicates a prefix that
            matches all IP addresses (with prefix, itself, of zero
            octets).
            b) Prefix:
                The Prefix field contains an IP address prefix, followed by
            enough trailing bits to make the end of the field fall on an
            octet boundary. Note that the value of the trailing bits is
            irrelevant.
        """

    def parse(self, msg):

        """
        Parse BGP Update message

        :param msg: raw BGP update binary PDU data
        :type msg: list
        :return: message after parsing.
        :return type: dict

        """
        t = msg[0]
        asn4 = msg[1]
        msg_hex = msg[2]

        results = {
            "Withdraw": None,
            "Attributes": None,
            "NLRI": None,
            'Time': t,
            'RawData': msg_hex,
            'SubError': None,
            'ErrorData': None}

        # get every part of the update message
        withdraw_len = struct.unpack('!H', msg_hex[:2])[0]
        withdraw_prefix_data = msg_hex[2:withdraw_len + 2]
        attr_len = struct.unpack('!H', msg_hex[withdraw_len + 2:withdraw_len + 4])[0]
        attribute_data = msg_hex[withdraw_len + 4:withdraw_len + 4 + attr_len]
        nlri_data = msg_hex[withdraw_len + 4 + attr_len:]

        try:
            # parse withdraw prefixes
            results['Withdraw'] = self.parse_prefix_list(withdraw_prefix_data)

            # parse nlri
            results['NLRI'] = self.parse_prefix_list(nlri_data)
        except Exception as e:
            LOG.error(e)
            error_str = traceback.format_exc()
            LOG.debug(error_str)
            results['SubError'] = bgp_cons.ERR_MSG_UPDATE_INVALID_NETWORK_FIELD
            results['ErrorData'] = ''
        try:
            # parse attributes
            results['Attributes'] = self.parse_attributes(attribute_data, asn4)
        except excep.UpdateMessageError as e:
            LOG.error(e)
            results['SubError'] = e.sub_error
            results['ErrorData'] = e.data
        except Exception as e:
            LOG.error(e)
            error_str = traceback.format_exc()
            LOG.debug(error_str)
            results['SubError'] = e
            results['ErrorData'] = e

        return results

    @staticmethod
    def parse_prefix_list(data):
        """
        Parses an RFC4271 encoded blob of BGP prefixes into a list

        :param data:
        :return: prefix_list
        """
        prefixes = []
        postfix = data
        while len(postfix) > 0:
            prefix_len = ord(postfix[0])
            if prefix_len > 32:
                LOG.warning('Prefix Length larger than 32')
                raise excep.UpdateMessageError(
                    sub_error=bgp_cons.ERR_MSG_UPDATE_INVALID_NETWORK_FIELD,
                    data=repr(data)
                )
            octet_len, remainder = prefix_len / 8, prefix_len % 8
            if remainder > 0:
                # prefix length doesn't fall on octet boundary
                octet_len += 1
            tmp = postfix[1:octet_len + 1]
            prefix_data = [ord(i) for i in tmp]
            # Zero the remaining bits in the last octet if it didn't fall
            # on an octet boundary
            if remainder > 0:
                prefix_data[-1] &= 255 << (8 - remainder)
            prefix_data = prefix_data + list(str(0)) * 4
            prefix = "%s.%s.%s.%s" % (tuple(prefix_data[0:4])) + '/' + str(prefix_len)
            prefixes.append(prefix)
            # Next prefix
            postfix = postfix[octet_len + 1:]

        return prefixes

    @staticmethod
    def parse_attributes(data, asn4=False):
        """
        Parses an RFC4271 encoded blob of BGP attributes into a list

        :param data:
        :param asn4: support 4 bytes asn or not
        :return:
        """
        attributes = {}
        postfix = data
        while len(postfix) > 0:

            try:
                flags, type_code = struct.unpack('!BB', postfix[:2])

                if flags & AttributeFlag.EXTENDED_LENGTH:
                    attr_len = struct.unpack('!H', postfix[2:4])[0]
                    attr_value = postfix[4:4 + attr_len]
                    postfix = postfix[4 + attr_len:]    # Next attribute
                else:    # standard 1-octet length
                    attr_len = ord(postfix[2])
                    attr_value = postfix[3:3 + attr_len]
                    postfix = postfix[3 + attr_len:]    # Next attribute
            except Exception as e:
                LOG.error(e)
                error_str = traceback.format_exc()
                LOG.debug(error_str)
                raise excep.UpdateMessageError(
                    sub_error=bgp_cons.ERR_MSG_UPDATE_MALFORMED_ATTR_LIST,
                    data='')

            if type_code == bgp_cons.BGPTYPE_ORIGIN:

                decode_value = Origin().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_AS_PATH:

                decode_value = ASPath().parse(value=attr_value, asn4=asn4)

            elif type_code == bgp_cons.BGPTYPE_NEXT_HOP:

                decode_value = NextHop().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_MULTI_EXIT_DISC:

                decode_value = MED().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_LOCAL_PREF:

                decode_value = LocalPreference().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_ATOMIC_AGGREGATE:

                decode_value = AtomicAggregate().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_AGGREGATOR:

                decode_value = Aggregator().parse(value=attr_value, asn4=asn4)

            elif type_code == bgp_cons.BGPTYPE_COMMUNITIES:

                decode_value = Community().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_ORIGINATOR_ID:

                decode_value = OriginatorID().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_CLUSTER_LIST:

                decode_value = ClusterList().parse(value=attr_value)

            elif type_code == bgp_cons.BGPTYPE_NEW_AS_PATH:

                decode_value = ASPath().parse(value=attr_value, asn4=True)

            elif type_code == bgp_cons.BGPTYPE_NEW_AGGREGATOR:

                decode_value = Aggregator().parse(value=attr_value, asn4=True)
            else:
                decode_value = repr(attr_value)
            attributes[type_code] = decode_value

        return attributes

    @staticmethod
    def construct_header(msg):
        """
        Prepends the mandatory header to a constructed BGP message

        :param msg:
        :return:
        """
        #    16-octet     2-octet  1-octet
        # ---------------+--------+---------+------+
        #    Maker      | Length |  Type   |  msg |
        # ---------------+--------+---------+------+
        return struct.pack('!16sHB',
                           chr(255) * 16,
                           len(msg) + 19,
                           2) + msg

    @staticmethod
    def construct_prefix_v4(prefix_list):
        """
        constructs NLRI prefix list

        :param prefix_list: prefix list
        """
        nlri_raw_hex = ''
        for prefix in prefix_list:
            masklen = prefix.split('/')[1]
            ip_hex = IPv4Network(prefix).packed
            masklen = int(masklen)
            if 16 < masklen <= 24:
                ip_hex = ip_hex[0:3]
            elif 8 < masklen <= 16:
                ip_hex = ip_hex[0:2]
            elif masklen <= 8:
                ip_hex = ip_hex[0:1]
            nlri_raw_hex += struct.pack('!B', masklen) + ip_hex
        return nlri_raw_hex

    @staticmethod
    def encode_prefixes(prefixes):
        """Encodes a list of IPPrefix

        :param prefixes: prefix list"""

        prefix_data = ""
        for prefix in prefixes:
            octet_len, remainder = len(prefix) / 8, len(prefix) % 8
            if remainder > 0:
                # prefix length doesn't fall on octet boundary
                octet_len += 1
            prefix_data += struct.pack('!B', len(prefix)) + prefix.packed()[:octet_len]
        return prefix_data


import unittest
import os

path = os.path.dirname(__file__)

class Test(unittest.TestCase):

    def test_parse_perf_file(self):
        import charm.output as charmo

        perffile = os.path.join(path, "testperf.dat")

        perfdata = charmo.CharmPerfData(filename=perffile)

        print(perfdata.rotor_metadata)
        print(perfdata.row_data["CL2D"])

if __name__ == "__main__":
    t = Test()
    t.test_parse_perf_file()


import icmp_cal
import time

class Estimator(object):

    def report_states(self, stats: dict):
        '''
        stats is a dict with the following items
        {
            "send_time_ms": uint,
            "arrival_time_ms": uint,
            "payload_type": int,
            "sequence_number": uint,
            "ssrc": int,
            "padding_length": uint,
            "header_length": uint,
            "payload_size": uint
        }
        '''

    def get_estimated_bandwidth(self) -> int:
        data_file = './data.txt'
        file_name_ref = './estimate_bandwidth.txt'
        with open(data_file) as f1:
            count = f1.readline()
            count = int(count.rstrip())
        if count == 0 or (count % 10) == 0:
            file_name = './result1.txt'
            estimate_bandwidth = int(icmp_cal.calc_bandwidth())
            # 推定帯域幅記録用
            with open(file_name, mode="a", encoding="utf8") as f:
                f.write(str(estimate_bandwidth) + "\n")
            # 10回おきに参照するため推定帯域幅を別ファイルに保存する。
            with open(file_name_ref, mode="w", encoding="utf8") as f3:
                f3.write(str(estimate_bandwidth))
        else:
            # ICMPコードを実行しない時は保存した最新の推定帯域幅を参照する。
            with open(file_name_ref) as f4:
                estimate_bandwidth = f4.readline()
                estimate_bandwidth = int(estimate_bandwidth.rstrip())

        count = count + 1
        with open(data_file, mode="w") as f2:
            f2.write(str(count))
        time.sleep(0.05)
        return int(estimate_bandwidth) # 予想される帯域幅を返す
        # return int(1e6)


import os
import sys
import json
from src.make_dataset import *
from src.build_features import *
from src.relevance_bucket_classifier import *
from src.sentiment_score_regressor import *
import warnings

def main(targets):
    try:
        # check if running using raw data or test data
        if 'test' in targets:
            filepath = os.path.join('data/test', 'data.csv')
            raw = False
        elif 'raw' in targets:
            filepath = os.path.join('data/raw', 'SentimentLabeled_10112022.csv')
            raw = True
        print(filepath)
        # import the tuned parameters
        with open('config/param-A.json') as fh:
                paramA = json.load(fh)
        with open('config/param-B.json') as fh:
                paramB = json.load(fh)

        # run models and get the results
        res_task_1 = RB_classifier(filepath, paramA['svc'], paramA['rf'], raw=raw)
        res_task_2 = SS_regressor(filepath, paramB['gb'], paramB['en'], raw=raw)

        return [res_task_1, res_task_2]

    except Exception as e:
        print(e)

if __name__ == '__main__':
    targets = sys.argv[1]
    warnings.filterwarnings('ignore')
    res = main(targets)
    print(res)


import random
import time
import sys

MAX = 2 ** 32

vi = 0x7380166f4914b2b9172442d7da8a0600a96f30bc163138aae38dee4db0fb0e4e

t = [0x79cc4519, 0x7a879d8a]

rotl = lambda x, n:((x << n) & 0xffffffff) | ((x >> (32 - n)) & 0xffffffff)

def sm3_ff_j(x, y, z, j):
    if 0 <= j and j < 16:
        ret = x ^ y ^ z
    elif 16 <= j and j < 64:
        ret = (x & y) | (x & z) | (y & z)
    return ret

def sm3_gg_j(x, y, z, j):
    if 0 <= j and j < 16:
        ret = x ^ y ^ z
    elif 16 <= j and j < 64:
        ret = (x & y) | ((~ x) & z)
    return ret

def Int2Bin(a, k): # 整数转二进制数同时依据要求进行长度补全
    res = list(bin(a)[2:])
    for i in range(k - len(res)):
        res.insert(0, '0')
    return ''.join(res)

def sm3_p_0(x):
    return x ^ (rotl(x, 9 % 32)) ^ (rotl(x, 17 % 32))

def sm3_p_1(x):
    return x ^ (rotl(x, 15 % 32)) ^ (rotl(x, 23 % 32))

def T(j):
    if j <= 15:
        return t[0]
    else:
        return t[1]

def sm3_cf(v_i, b_i):
    w = []
    w_1 = []
    for i in range(16):
        temp = b_i[i * 32:(i + 1) * 32]
        w.append(int(temp, 2))
    for j in range(16, 68, 1):
        w.append(0)
        w[j] = sm3_p_1(w[j-16] ^ w[j-9] ^ (rotl(w[j-3], 15 % 32))) ^ (rotl(w[j-13], 7 % 32)) ^ w[j-6]
    for j in range(64):
        w_1.append(0)
        w_1[j] = w[j] ^ w[j+4]
    A = [0]*8
    for i in range(8):
        temp = v_i[32 * i:32 * (i + 1)]
        A.append(int(temp, 2))
    for j in range(64):
        SS1 = rotl((rotl(A[0], 12 % 32) + A[4] + rotl(T(j), j % 32)) & 0xffffffff, 7 % 32)
        SS2 = SS1 ^ rotl(A[0], 12 % 32)
        TT1 = (sm3_ff_j(A[0], A[1], A[2], j) + A[3] + SS2 + w_1[j]) % MAX
        TT2 = (sm3_gg_j(A[4], A[5], A[6], j) + A[7] + SS1 + w[j]) % MAX
        A[3] = A[2]
        A[2] = rotl(A[1], 9 % 32)
        A[1] = A[0]
        A[0] = TT1
        A[7] = A[6]
        A[6] = rotl(A[5], 19 % 32)
        A[5] = A[4]
        A[4] = sm3_p_0(TT2)

    temp = Int2Bin(A[0], 32) + Int2Bin(A[1], 32) + Int2Bin(A[2], 32) + \
           Int2Bin(A[3], 32) + Int2Bin(A[4], 32) + Int2Bin(A[5], 32) + \
           Int2Bin(A[6], 32) + Int2Bin(A[7], 32)
    temp = int(temp, 2)
    return temp ^ int(v_i, 2)

def filled(message): #按照SM3要求补全信息符合规范
    message = bin(message)[2:] #除去开头的标识符
    for i in range(4): #防止信息的二进制由于转换缺少位数
        if (len(message) % 4 == 0):
            break
        else:
            message = '0' + message
    length = len(message)
    k = 448 - (length + 1) % 512
    if (k < 0):  # 求取满足等式的最小非负整数k
        k += 512
    message = message + '1' + '0' * k + Int2Bin(length, 64)
    return message

def IterFunction(message): # 按照SM3的实现逻辑进行运算
    n = int(len(message) / 512)
    v = []
    v.append(Int2Bin(vi, 256))
    for i in range(n):
        temp = sm3_cf(v[i], message[512 * i:512 * (i + 1)])
        temp = Int2Bin(temp, 256)
        v.append(temp)
    return v[n]

def SM3(msg):
    msg_1=filled(msg)
    hex(int(msg_1,2))
    res=IterFunction(msg_1)
    result=hex(int(res,2))
    return result[2:]

def Birthday_Attck(n): # 找出两个前nbit相同的hash值
    for i in range(2**(int(n))):
        a1 = random.randint(0,2**n)
        a2 = random.randint(0,2**n)
        if(SM3(a1)[:int(n/4)] == SM3(a2)[:int(n/4)]):
            print('Succeed')
            print("first hash is:\n",SM3(a1))
            print("second hash is:\n",SM3(a2))
            return;
    print('Failed')

print("#--------------------------------------------------------------------#")
print("now, you should input the length of bit you want to match. Require! it must be multiple of 8")
length = int(input())
print("#--------------------------------------------------------------------#\n")
time_start = time.time()
Birthday_Attck(length)
time_end = time.time()
time_c = time_end - time_start
print('the time we use：', time_c, 's')


import aoc_utils
import itertools
import more_itertools
import functools
import operator
import math
from collections import *
from copy import deepcopy
import random
import time
import re
lines = aoc_utils.readlines()
start = lines[0]
connections = {}
laggedamount = {}
for line in lines:
    if line == "" or line==start:
        continue
    else:
        a,b = line.split(" -> ")
        connections[a] = b
density = defaultdict(int)
for x in range(len(start)-1):
    density[start[x]+start[x+1]] += 1
for x in range(40):
    wdensity = deepcopy(density)
    for poly in wdensity:
        sub = connections[poly]
        density[poly[0]+sub] += wdensity[poly]
        density[sub+poly[1]] += wdensity[poly]
        density[poly] -= wdensity[poly]
edensity = defaultdict(int)
for item in density:
    edensity[item[0]] += density[item]
    edensity[item[1]] += density[item]
edensity[start[0]] += 1
edensity[start[-1]] += 1
print(sum(edensity.values()))


#!/usr/bin/python
"""Hyperion Constants."""

KEY_ACCEPT = "accept"
KEY_ACTIVE = "active"
KEY_ADJUSTMENT = "adjustment"
KEY_AUTHORIZE = "authorize"
KEY_AUTHORIZE_LOGIN = "authorize-login"
KEY_AUTHORIZE_LOGOUT = "authorize-logout"
KEY_BRIGHTNESS = "brightness"
KEY_CLEAR = "clear"
KEY_CLIENT = "client"
KEY_COLOR = "color"
KEY_COMMAND = "command"
KEY_COMPONENT = "component"
KEY_COMPONENTSTATE = "componentstate"
KEY_COMPONENTS = "components"
KEY_CONNECTION = "connection"
KEY_CONNECTED = "connected"
KEY_DATA = "data"
KEY_EFFECT = "effect"
KEY_EFFECTS = "effects"
KEY_ENABLED = "enabled"
KEY_FRIENDLY_NAME = "friendly_name"
KEY_HYPERION = "hyperion"
KEY_LED_MAPPING = "imageToLedMapping"
KEY_LED_MAPPING_TYPE = "imageToLedMappingType"
KEY_ID = "id"
KEY_IMAGE = "image"
KEY_IMAGE_STREAM = "imagestream"
KEY_IMAGE_STREAM_START = f"{KEY_IMAGE_STREAM}-start"
KEY_IMAGE_STREAM_STOP = f"{KEY_IMAGE_STREAM}-stop"
KEY_INFO = "info"
KEY_INSTANCE = "instance"
KEY_LEDCOLORS = "ledcolors"
KEY_LED_STREAM_START = "ledstream-start"
KEY_LED_STREAM_STOP = "ledstream-stop"
KEY_LEDS = "leds"
KEY_LED_MAPPING = "imageToLedMapping"
KEY_LOADED_STATE = "loaded-state"
KEY_LOGGED_IN = "logged-in"
KEY_LOGIN = "login"
KEY_LOGOUT = "logout"
KEY_NAME = "name"
KEY_ORIGIN = "origin"
KEY_OWNER = "owner"
KEY_PRIORITY = "priority"
KEY_PRIORITIES = "priorities"
KEY_PRIORITIES_AUTOSELECT = "priorities_autoselect"
KEY_PROCESSING = "processing"
KEY_RGB = "RGB"
KEY_RESULT = "result"
KEY_REQUIRED = "required"
KEY_REQUEST_TOKEN = "requestToken"
KEY_RUNNING = "running"
KEY_SESSIONS = "sessions"
KEY_SET_VIDEOMODE = "videoMode"
KEY_SERVERINFO = "serverinfo"
KEY_SOURCESELECT = "sourceselect"
KEY_START_INSTANCE = "startInstance"
KEY_STATE_LOADED = "startInstance"
KEY_STOP_INSTANCE = "stopInstance"
KEY_SUBCOMMAND = "subcommand"
KEY_SUBSCRIBE = "subscribe"
KEY_SUCCESS = "success"
KEY_SWITCH_TO = "switchTo"
KEY_STATE = "state"
KEY_SYSINFO = "sysinfo"
KEY_TAN = "tan"
KEY_TIMEOUT_SECS = "timeout_secs"
KEY_TOKEN = "token"
KEY_TOKEN_REQUIRED = "tokenRequired"
KEY_UPDATE = "update"
KEY_VERSION = "version"
KEY_VALUE = "value"
KEY_VIDEOMODE = "videomode"
KEY_VISIBLE = "visible"
KEY_VIDEOMODES = ["2D", "3DSBS", "3DTAB"]

# ComponentIDs from:
# https://docs.hyperion-project.org/en/json/Control.html#components-ids-explained
KEY_COMPONENTID = "componentId"
KEY_COMPONENTID_ALL = "ALL"
KEY_COMPONENTID_COLOR = "COLOR"
KEY_COMPONENTID_EFFECT = "EFFECT"

KEY_COMPONENTID_SMOOTHING = "SMOOTHING"
KEY_COMPONENTID_BLACKBORDER = "BLACKBORDER"
KEY_COMPONENTID_FORWARDER = "FORWARDER"
KEY_COMPONENTID_BOBLIGHTSERVER = "BOBLIGHTSERVER"
KEY_COMPONENTID_GRABBER = "GRABBER"
KEY_COMPONENTID_LEDDEVICE = "LEDDEVICE"
KEY_COMPONENTID_V4L = "V4L"

KEY_COMPONENTID_EXTERNAL_SOURCES = [
    KEY_COMPONENTID_BOBLIGHTSERVER,
    KEY_COMPONENTID_GRABBER,
    KEY_COMPONENTID_V4L,
]

# Maps between Hyperion API component names to Hyperion UI names.
KEY_COMPONENTID_TO_NAME = {
    KEY_COMPONENTID_ALL: "All",
    KEY_COMPONENTID_SMOOTHING: "Smoothing",
    KEY_COMPONENTID_BLACKBORDER: "Blackbar Detection",
    KEY_COMPONENTID_FORWARDER: "Forwarder",
    KEY_COMPONENTID_BOBLIGHTSERVER: "Boblight Server",
    KEY_COMPONENTID_GRABBER: "Platform Capture",
    KEY_COMPONENTID_LEDDEVICE: "LED Device",
    KEY_COMPONENTID_V4L: "USB Capture",
}
KEY_COMPONENTID_FROM_NAME = {
    name: component for component, name in KEY_COMPONENTID_TO_NAME.items()
}

DEFAULT_INSTANCE = 0
DEFAULT_CONNECTION_RETRY_DELAY_SECS = 30
DEFAULT_TIMEOUT_SECS = 5
DEFAULT_REQUEST_TOKEN_TIMEOUT_SECS = 180
DEFAULT_ORIGIN = "hyperion-py"
DEFAULT_PORT_JSON = 19444
DEFAULT_PORT_UI = 8090


"""""
This script uses a regression based estimation technique to estimate the performance that FinBERT produced on some
target dataset.
"""""

import numpy
import warnings
from finbert import testFinBERT
from functions import calculateDistance
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score

if __name__ == "__main__":

    # Variable Declaration
    distances = []
    ACCDrop = []

    # When the PAD Distance is used, the linear model is expected not to converge
    warnings.filterwarnings("ignore", category=ConvergenceWarning)

    groundTruths, predicted = testFinBERT("phrasebank")
    mainACC = accuracy_score(groundTruths, predicted)

    for targetDataset in ["economynews", "slsamazon", "slsimbd", "slsyelp", "stsgold"]:

        # Calculate distance from source dataset to target dataset
        distances.append(calculateDistance("phrasebank", targetDataset, "pad"))
        print("PAD distance from phrasebank to " + targetDataset + " = " + str(distances[-1]))

        groundTruths, predicted = testFinBERT(targetDataset)
        accuracy = accuracy_score(groundTruths, predicted)
        print(accuracy)
        ACCDrop.append(mainACC - accuracy)
        print(mainACC - accuracy)
        print("ACC drop of " + str(ACCDrop[-1]) + " on the " + targetDataset + " dataset")
        print("-----------------------------------------------------------------------------------------------")

    distanceKDD17 = calculateDistance("phrasebank", "kdd17", "pad")
    print("PAD distance from phrasebank to kdd17 = " + str(distanceKDD17))

    finalRegressionModel = LinearRegression()
    finalRegressionModel.fit(numpy.array(distances).reshape(-1, 1), numpy.array(ACCDrop).reshape(-1, 1))
    resultKDD17 = finalRegressionModel.predict(numpy.array(distanceKDD17).reshape(1, -1))[0][0]
    print("Estimated ACC score on kdd17 = " + str(mainACC - resultKDD17))

    distanceStockNet = calculateDistance("phrasebank", "stocknet", "pad")
    print("PAD distance from phrasebank to stocknet = " + str(distanceStockNet))

    resultStockNet = finalRegressionModel.predict(numpy.array(distanceStockNet).reshape(1, -1))[0][0]
    print("Estimated ACC score on stocknet = " + str(mainACC - resultStockNet))


# -*- coding: utf-8 -*-
"""
@Time ： 2022/2/17 22:16
@Auth ： dhy
@File ：jpg2bin.py
@IDE ：PyCharm
@Motto：ABC(Always Be Coding)

"""
# -*- coding:utf-8 -*-
import os
import pickle as p
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plimg
from PIL import Image
import cv2
def png2bin(gen_dir, bach_dir, label_dir):
    data_batch = {b'batch_label':b'testing batch 1 of 1', b'labels':'', b'data':'', b'filenames':''}
    data=[]
    label=[]
    filename=[]
    for b_dir in bach_dir:
        for l_dir in label_dir:
            im = os.listdir(gen_dir + '/' + b_dir + '/' + l_dir)
            for item in im:
                image_name = gen_dir + '/' + b_dir +'/' + l_dir + '/' + item
                # print(image_name)
                if 'plane' in image_name:
                    label.append(int(0))
                elif 'car' in image_name:
                    label.append(int(1))
                elif 'bird' in image_name:
                    label.append(int(2))
                elif 'cat' in image_name:
                    label.append(int(3))
                elif 'deer' in image_name:
                    label.append(int(4))
                elif 'dog' in image_name:
                    label.append(int(5))
                elif 'frog' in image_name:
                    label.append(int(6))
                elif 'horse' in image_name:
                    label.append(int(7))
                elif 'ship' in image_name:
                    label.append(int(8))
                else:
                    label.append(int(9))
                data_temp = []
                img = cv2.imread(image_name)
                for j in range(2,-1,-1):
                    for i in range(32):
                        for k in range(32):
                            data_temp.append(img[i][k][j])
                # data.append(np.array(data_temp,dtype='uint8'))
                data.append(data_temp)
                filename.append(item.encode())
    data = np.array(data, dtype='uint8')
    data_batch[b'labels'] = label
    data_batch[b'data'] = data
    data_batch[b'filenames'] = filename
    return data_batch

def save_obj(save_dir, data_batch):
    with open(save_dir +'/'+ 'test_batch', 'wb') as f:
        p.dump(data_batch, f, p.HIGHEST_PROTOCOL)

def load_obj(name):
    with open('obj/' + name + '.pkl', 'rb') as f:
        return p.load(f)

if __name__ == "__main__":
    demo = r'F:\AI_work\DP+AI\cifar-10-batches-py\train\batch_1\frog\leptodactylus_pentadactylus_s_000004.png'
    gen_dir = r'F:\AI_work\DP+AI\cifar-10-batches-py\test'
    bach_dir = [r'train\batch_1',]
    label_dir = ['bird', 'car', 'cat', 'deer', 'dog', 'frog', 'horse', 'plane', 'ship', 'truck']
    data_batch = png2bin(gen_dir,bach_dir,label_dir)
    save_dir = r'F:\AI_work\DP+AI\data_1\cifar-10-python'
    save_obj(save_dir, data_batch)


""" Assets Endpoint """
from flask import request
from flask_restx import Namespace, Resource, fields, inputs, reqparse

from service.asset import Asset
from service.asset_likes import AssetLikes
from service.transaction import Transaction
from service.web3 import Web3Alley
from util.jwt_auth import check_apis_are_protected_or_open
from util.utils import load_json_schema

JWT_REQUIRED, JWT_REFRESH_TOKEN_REQUIRED = check_apis_are_protected_or_open()

NS = Namespace(
    'assets',
    description='Operations related to assets')

ASSET_MODEL = NS.schema_model('Asset', load_json_schema('asset-schema.json'))
ASSET_UPDATE_MODEL=NS.schema_model('AssetUpdate',load_json_schema('asset-update-schema.json'))

ASSET_LIKE_MODEL = NS.schema_model('AssetLikes', load_json_schema('asset-like-schema.json'))

ASSET_VIEW_MODEL = NS.model('AssetViews',
            {
                'assetId': fields.String(
                    required=True,
                    descrption="Asset id"
                )
            }
        )

ASSET_FILTER_MODEL = NS.schema_model('AssetFilters', load_json_schema('asset-filter-schema.json'))

BUY_MODEL = NS.model('Buy',
            {
                'assetId': fields.String(
                    required=True,
                    descrption="Asset id"
                ),
                'hash': fields.String(
                    required=True,
                    descrption="Buy Transaction Hash"
                ),
                'buyer': fields.String(
                    required=True,
                    descrption="Buyer Address"
                )
            }
        )

TRANSFER_MODEL = NS.model('Transfer',
            {
                'assetId': fields.String(
                    required=True,
                    descrption="Asset id"
                ),
                'hash': fields.String(
                    required=True,
                    descrption="Transfer Transaction Hash"
                ),
                'to': fields.String(
                    required=True,
                    descrption="Receiver Address"
                )
            }
        )

MINT_MODEL=NS.schema_model('MintAsset', load_json_schema('mint-schema.json'))

BURN_MODEL=NS.model('Burn',{
    'assetId':fields.String(
        required=True,
        descrption="Asset Id"
    ),
    'hash': fields.String(
        required=True,
        descrption="Transfer Transaction Hash"
    ),
    "sign":fields.String(
        required=True,
        descrption="Signature of user"
    )
})

LIST_MODEL=NS.model('List',{
    'listed':fields.Boolean(
        required=True,
        descrption="Listed or not"
    ),
    'assetId':fields.String(
        required=True,
        descrption="Asset Id"
    ),
    'sign':fields.String(
        required=True,
        descrption="Signature of user"
    )
})

PARSER = reqparse.RequestParser()
PARSER.add_argument(
    'creator', type=str, required=False,
    help='Get assets with creator'
)
PARSER.add_argument(
    'owner', type=str, required=False,
    help='Get assets with owner'
)
PARSER.add_argument(
    'status', type=str, required=False,
    help='Get assets with status'
)
PARSER.add_argument(
    'limit', type=str, required=False,
    help='Limit for assets'
)
PARSER.add_argument(
    'offset', type=str, required=False,
    help='Offset for assets'
)
PARSER.add_argument(
    'onSale',type=inputs.boolean, required=False,
    help='Get assets with onSale'
)

SEARCH_PARSER = reqparse.RequestParser()
SEARCH_PARSER.add_argument(
    'search_text', type=str, required=False,
    help='Get assets, profiles with search_text'
)
SEARCH_PARSER.add_argument(
    'limit', type=str, required=False,
    help='Limit for assets'
)

FILTER_PARSER = reqparse.RequestParser()
FILTER_PARSER.add_argument(
    'limit', type=str, required=False,
    default='20',
    help='Limit for assets'
)
FILTER_PARSER.add_argument(
    'offset', type=str, required=False,
    default='0',
    help='Offset for assets'
)

COUNT_PARSER = reqparse.RequestParser()
COUNT_PARSER.add_argument(
    'creator', type=str, required=False,
    help='Get assets with creator'
)
COUNT_PARSER.add_argument(
    'owner', type=str, required=False,
    help='Get assets with owner'
)
COUNT_PARSER.add_argument(
    'status', type=str, required=False,
    help='Get assets with status'
)

PARSER_COLLECTION=reqparse.RequestParser()
PARSER_COLLECTION.add_argument(
    'collectionId',type=str,required=True,
    help='Get NFTs which belongs to that collection'
)
PARSER_COLLECTION.add_argument(
    'limit', type=str, required=False,
    default='20',
    help='Limit for assets'
)
PARSER_COLLECTION.add_argument(
    'offset', type=str, required=False,
    default='0',
    help='Offset for assets'
)

@NS.route('/')
class AssetCollection(Resource):
    """ Assets Collection methods """
    @NS.doc(parser=PARSER)
    def get(self):
        """ Return list of assets """
        args = PARSER.parse_args()
        creator= args.get('creator', None)
        owner= args.get('owner', None)
        status = args.get('status', None)
        limit = args.get('limit', None)
        offset = args.get('offset', None)
        onSale= args.get('onSale',None)
        return Asset().get_all(creator=creator, owner=owner, status=status, limit=limit, offset=offset,onSale=onSale)

    @NS.expect(ASSET_MODEL, validate=True)
    @JWT_REQUIRED
    def post(self):
        """ Creates a asset """
        return Asset().create_one(request.json)

@NS.route('/<string:assetId>')
class AssetItem(Resource):
    """ Asset Item methods """
    def get(self, assetId):
        """ Get a asset """
        return Asset().get_one(assetId)

    @NS.expect(ASSET_UPDATE_MODEL, validate=True)
    def put(self,assetId):
        """ Perform update in Asset """
        return Transaction().update_asset(assetId, request.json)

@NS.route('/count')
class AssetCountCollection(Resource):
    """ Assets Count Collection methods """
    @NS.doc(parser=COUNT_PARSER)
    def get(self):
        """ Return count of assets """
        args = COUNT_PARSER.parse_args()
        creator= args.get('creator', None)
        owner= args.get('owner', None)
        status = args.get('status', None)
        return Asset().get_count(creator=creator, owner=owner, status=status)

@NS.route('/search')
class SearchCollection(Resource):
    """ Search methods """
    @NS.doc(parser=SEARCH_PARSER)
    def get(self):
        """ Return list of assets, profiles """
        args = SEARCH_PARSER.parse_args()
        search_text= args.get('search_text', None)
        limit = args.get('limit', None)
        return Asset().search(search_text=search_text, limit=limit)

@NS.route('/likes')
class AssetLikesCollection(Resource):
    """ Post Asset Like methods """
    @NS.expect(ASSET_LIKE_MODEL, validate=True)
    @JWT_REQUIRED
    def post(self):
        """ Creates a like for asset """
        return AssetLikes().update_like(request.json)

@NS.route('/views')
class AssetViewsCollection(Resource):
    """ Post Asset Like methods """
    @NS.expect(ASSET_VIEW_MODEL, validate=True)
    def post(self):
        """ Creates a view for asset """
        return AssetLikes().update_views(request.json)

@NS.route('/likes/<string:assetId>')
class AssetLikesItem(Resource):
    """ Asset likes for Item methods """
    def get(self, assetId):
        """ Get like for asset """
        return AssetLikes().get_one(assetId)

@NS.route('/likedby/<string:address>')
class AssetLikedByItem(Resource):
    """ Get assets for likedby methods """
    def get(self, address):
        """ Get liked assets for user """
        return AssetLikes().get_liked_assets(address)

@NS.route('/filtered')
class AssetFilterCollection(Resource):
    """ Assets Filter Collection methods """
    @NS.doc(parser=FILTER_PARSER, body=ASSET_FILTER_MODEL)
    @NS.expect(ASSET_FILTER_MODEL, validate=True)
    def post(self):
        """ Return list of filtered assets """
        args = FILTER_PARSER.parse_args()
        limit = args.get('limit')
        offset = args.get('offset')
        print(limit)
        return Asset().get_all_sorted_filtered(request.json, limit=limit, offset=offset)

@NS.route('/buy')
class BuyCollection(Resource):
    """ Buy Collection methods """
    @NS.expect(BUY_MODEL, validate=True)
    def post(self):
        """ Perform buy transaction """
        return Transaction().process_buy_transaction(request.json)

@NS.route('/transfer')
class TransferCollection(Resource):
    """ Transfer Collection methods """
    @NS.expect(TRANSFER_MODEL, validate=True)
    def post(self):
        """ Perform tranfer transaction """
        return Transaction().process_transfer_transaction(request.json)

@NS.route('/mint')
class MintCollection(Resource):
    """ Mint Collection methods """
    @NS.expect(MINT_MODEL, validate=True)
    def post(self):
        """ Minted  assets """
        return Transaction().process_mint_transaction(request.json)

@NS.route('/burn')
class BurnCollection(Resource):
    """ Burn Collection methods """
    @NS.expect(BURN_MODEL, validate=True)
    def post(self):
        """ Burn  asset """
        return Transaction().process_burn_transaction(request.json)

@NS.route('/list')
class ListCollection(Resource):
    """ List Collection methods """
    @NS.expect(LIST_MODEL, validate=True)
    def post(self):
        """ List  assets """
        return Transaction().list_asset(request.json)

# @NS.route('/web3/<string:hash>')
# class Web3Collection(Resource):
#     """ Web3 Collection methods """
#     def get(self, hash):
#         """ Web3 get receipt """
#         return Web3Alley().get_transaction_receipt(hash)

# @NS.route("/verifiedartistesasset")
# class VerifyArtistesAssets(Resource):
#     """List of asset which are minted by verifyed artistes """
#     def get(self):
#         """ List of Assets """
#         return Asset().get_all_verify_assets_artistes()
@NS.route('/latestImages')
class LatestImagesCollection(Resource):
    @NS.doc(parser=FILTER_PARSER)
    def get(self):
        """ Return only latest images of assets """
        args = FILTER_PARSER.parse_args()
        limit = args.get('limit', None)
        offset = args.get('offset', None)
        return Asset().latest_image_assets(limit=limit,offset=offset)
@NS.route('/collectionAssets')
class NftBelongsToCollection(Resource):
    @NS.doc(parser=PARSER_COLLECTION)
    def get(self):
        """ Return assets which belongs to a collection"""
        args= PARSER_COLLECTION.parse_args()
        collectionId=args.get('collectionId')
        limit= args.get('limit',None)
        offset = args.get('offset', None)
        return Asset().get_nft_list_from_collection(collectionId=collectionId,limit=limit,offset=offset)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time

__author__ = 'liyz'

from utils.load_config import read_config
import torchvision.transforms as transforms

import csv
import torch.backends.cudnn as cudnn
from dataset.filelist_Dataset import filelist_DataSet
from utils.functions import *
from torchvision.models import densenet121
from torchvision.models import densenet201

logger = logging.getLogger(__name__)

# print the structure and parameters number of the net
def print_network(net):
    num_params = 0
    for param in net.parameters():
        num_params += param.numel()
    logger.info(str(net))
    logger.info('Total number of parameters: %d' % num_params)

def test(config_path, experiment_info):
    logger.info('------------ flower classification Train --------------')
    logger.info('------------ loading config file ------------')
    global_config = read_config(config_path)
    logger.info(open(config_path).read())
    logger.info('------------   config file info above ------------')
    # set random seed
    seed = global_config['global']['random_seed']
    torch.manual_seed(seed)

    enable_cuda = global_config['train']['enable_cuda']
    device = torch.device("cuda" if enable_cuda else "cpu")
    if torch.cuda.is_available() and not enable_cuda:
        logger.warning("CUDA is avaliable, you can enable CUDA in config file")
    elif not torch.cuda.is_available() and enable_cuda:
        raise ValueError("CUDA is not abaliable, please unable CUDA in config file")

    cudnn.benchmark = True
    torch.set_grad_enabled(False)  # make sure all tensors below have require_grad=False,

    logger.info('constructing dataset...')
    test_filelist_path = global_config['data']['dataset']['test_path']
    test_dataset = filelist_DataSet(test_filelist_path,
                                   transform=transforms.Compose([
                                       transforms.Resize([224,224]),
                                       # transforms.CenterCrop(224),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                            std=[0.229, 0.224, 0.225]),
                                   ]))
    assert test_dataset
    test_batch_size = global_config['test']['test_batch_size']
    test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=test_batch_size, shuffle=False, num_workers=4)

    logger.info('constructing model...')
    model_choose = global_config['global']['model']
    logger.info('Using model is: %s ' % model_choose)
    model = globals()[model_choose]()
    gpu_nums = torch.cuda.device_count()
    logger.info('dataParallel using %d GPU.....' % gpu_nums)
    if gpu_nums > 1:
        model = torch.nn.DataParallel(model)
    model = model.to(device)

    model.eval()  # let training = False, make sure right dropout

    # load model weight
    weight_path = global_config['test']['model_path']
    if os.path.exists(weight_path):
        logger.info('loading existing weight............')
        if enable_cuda:
            weight = torch.load(weight_path, map_location=lambda storage, loc: storage.cuda())
        else:
            weight = torch.load(weight_path, map_location=lambda storage, loc: storage)
        model.load_state_dict(weight, strict=False)
    else:
        raise ValueError("invalid weight path !!!")

    # forward
    logger.info('evaluate forwarding...')

    out_path=global_config['test']['output_file_path']+experiment_info+"_result.csv"
    # to just evaluate score or write answer to file
    if out_path is not None:
        predict_on_model(model=model,batch_data=test_loader,device=device,out_path=out_path)

    logging.info('finished.')

def predict_on_model(model, batch_data, device,out_path):

    epoch_acc = AverageMeter()
    batch_cnt = len(batch_data)
    eval_start_time = time.time()
    for i, batch in enumerate(batch_data, 0):
        batch_start_time = time.time()
        images, idx = batch
        images = images.to(device)
        # forward
        pred_labels = model.forward(images)
        save_test_result_to_csv( pred_labels,idx, out_path)
        batch_time=time.time()-batch_start_time
        logger.info("batch=%d time=%.2f"%(i,batch_time))

    test_time = time.time() - eval_start_time
    logger.info('===== test finished test_time=%.2f====' % (test_time))
    return 0

def save_test_result_to_csv(pred_labels,idx,csv_file_path):
    class_map = {"daisy": 0, "dandelion": 1, "rose": 2, "sunflower": 3, "tulip": 4}
    id2class_map={0:"daisy",1:"dandelion",2:"rose",3:"sunflower",4:"tulip"}
    problem_num = len(pred_labels)
    is_first_batch = True
    if os.path.exists(csv_file_path):
        is_first_batch = False
    out = open(csv_file_path, 'a', newline='')
    csv_write = csv.writer(out, dialect='excel')
    if is_first_batch:
        head_info = ['Id', 'Expected']
        csv_write.writerow(head_info)

    pred_labels = torch.argmax(pred_labels, dim=1)  # 得到一个20*1的矩阵
    for case_count in range(problem_num):
        class_name=id2class_map[pred_labels[case_count].item()]
        cur_row_info = [int(idx[case_count].item()),class_name]
        csv_write.writerow(cur_row_info)
    out.flush()
    out.close()


# 700. Search in a Binary Search Tree

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        node: Optional[TreeNode] = None
        def dfs(root: Optional[TreeNode], val: int):
            nonlocal node
            if root:
                if root.val == val:
                    node = root
                    return
                if root.left:
                    dfs(root.left, val)
                if root.right:
                    dfs(root.right, val)

        dfs(root, val)
        return node


MSG_SALDO_INSUFICIENTE = 'Saldo insuficiente!'
MSG_SUCESSO_SAQUE = 'Saque efetuado com sucesso!'
MSG_SUCESSO_TRANSFERENCIA= 'Transferência efetuada com sucesso!'

MSG_SUCESSO_DEPOSITO = 'Depósito efetuado com sucesso!'
MSG_SUCESSO_EXCLUIR = 'Conta excluída com sucesso!'

MSG_SUCESSO_CADASTRAR = 'Conta cadastrada com sucesso!'
MSG_ERRO_SAQUE = 'Ocorreu um erro ao efetuar o saque!'
MSG_ERRO_TRANSFERENCIA = 'Ocorreu um erro ao efetuar a transferência!'
MSG_ERRO_DEPOSITO = 'Ocorreu um erro ao efetuar o depósito!'

MSG_ERRO_EXCLUIR_CONTA='Ocorreu um erro ao excluir a conta!'
MSG_ERRO_CADASTRAR_CONTA = 'Ocorreu um erro ao cadastrar a conta!'

MSG_VALOR_SAQUE = 'Valor para saque: '
MSG_VALOR_DEPOSITO = 'Valor para depósito: '
MSG_VALOR_TRANSFERENCIA = 'Valor para transferência: '
MSG_CONTA_INEXISTENTE = 'Conta inexistente!'
MSG_SEM_CONTA_CORRENTE = 'Não há contas correntes cadastradas!'
MSG_SEM_CONTA_SALARIO = 'Não há contas salário cadastradas!'
MSG_SEM_CONTA_POUPANCA = 'Não há contas poupança cadastradas!'
MSG_CONTA_EXISTENTE = "Já existe uma conta cadastrada com esse número!"

MSG_CONTA_PARA_EXCLUIR='Número da conta que deseja excluir: '
MSG_CONTA_PARA_CADASTRAR='Número da conta que deseja cadastrar: '
MSG_NUMERO_CONTA = 'Informe o número da conta: '
MSG_OPCAO_INVALIDA = 'Opção inválida!'
MSG_ENCERRA_SISTEMA = 'Obrigado por utilizar o sistema!'
TAM_VALIDO_CONTA = 5

MSG_NUMERO_CONTA_INVALIDO = 'Número inválido! Qtda digitos: ' + str(TAM_VALIDO_CONTA) + '!'

MSG_OPCOES_TIPOS_CONTAS ='1- Conta Corrente\n' '2- Conta Salário\n' '3- Conta Poupança\n''Informe o tipo da conta desejada: \n'
MSG_OPCOES_TIPOS_CONTAS_LISTAGEM ='1- Conta Corrente\n' '2- Conta Salário\n' '3- Conta Poupança\n''Informe o tipo da conta desejada: \n''4- Todas \n'


import subprocess
import time
from plot import *
from datetime import datetime

time_str = datetime.now().strftime("%y-%m-%d--%H:%M")
root_dir = './Expr-%s/' % time_str

for n_connections in {1}:
    for minRTO in range(1000, 1300, 100):

        normalized_throughput_data = []
        period_data = []

        for period in [x * 0.1 for x in range(3, 31)]:

            output_name = str(minRTO) + '-' + str(period)
            output_dir = root_dir + '/rto-min-%f-tcp_n-%d/interval-%f/' % (minRTO, n_connections, period)

            p = subprocess.Popen('''python dos.py \
                                --output %s \
                                --period %f \
                                --minRTO %d \
                                --tcpNum %d'''
                                 % (output_dir,
                                    period,
                                    minRTO,
                                    n_connections
                                    ), shell=True)
            p.communicate()
            time.sleep(5)
            normalized_throughput_data.append(read_throughput(output_dir))
            period_data.append(period)
        output_dir = root_dir + '/rto-min-%f-tcp_n-%d/' % (minRTO, n_connections)
        plot_throughput(xdata=period_data, ydata=normalized_throughput_data, output_path=output_dir + 'res_all.png')


def pago_estacionamiento():
    total = 0

    # Solicitar el total a cobrar hasta que sea un valor válido y esté dentro del rango permitido
    while total <= 0 or total > 75:
        total_input = input("Introduce el total a cobrar por el estacionamiento (hasta 75): ")
        try:
            total = float(total_input)
        except ValueError:
            print("Error: Ingrese un número válido.")
            continue

        if total <= 0:
            print("El total a cobrar debe ser mayor que cero. Por favor, ingrese un valor válido.")
        elif total > 75:
            print("El total a cobrar no puede exceder los 75. Por favor, ingrese un valor válido.")

    pago = 0

    # Solicitar el monto pagado hasta que sea suficiente y esté dentro del rango permitido
    while pago < total or pago > 150:
        pago_input = input("Introduce el monto que paga el cliente (hasta 150): ")
        try:
            pago = float(pago_input)
        except ValueError:
            print("Error: Ingrese un número válido.")
            continue

        if pago < total:
            print("El monto pagado es insuficiente. Por favor, pague el monto total del estacionamiento.")
        elif pago > 150:
            print("El monto pagado no puede exceder los 150. Por favor, ingrese un valor válido.")

    # Calcular el cambio y los billetes/monedas a entregar
    cambio = pago - total

    denominaciones = [
        ("billete de 100 dólares", 100),
        ("billete de 50 dólares", 50),
        ("billete de 20 dólares", 20),
        ("billete de 10 dólares", 10),
        ("billete de 5 dólares", 5),
        ("billete de 2 dólares", 2),
        ("billete de 1 dólar", 1),
        ("moneda de 50 centavos de dólar", 0.5),
        ("moneda de 25 centavos de dólar", 0.25),
        ("moneda de 10 centavos de dólar", 0.1),
        ("moneda de 5 centavos de dólar", 0.05),
        ("moneda de 1 centavo de dólar", 0.01)
    ]
    billetes_entregados = []
    monedas_entregadas = []
    for denominacion, valor in denominaciones:
        cantidad = int(cambio / valor)
        cambio -= cantidad * valor
        if valor >= 1:
            billetes_entregados.append((denominacion, cantidad))
        else:
            monedas_entregadas.append((denominacion, cantidad))

    # Mostrar los resultados
    print("\n=== Resultados ===")
    print("Total a cobrar: {:.2f} dólares".format(total))
    print("Monto pagado: {:.2f} dólares".format(pago))
    print("Cambio: {:.2f} dólares".format(pago - total))
    print("Billetes a entregar:")
    for denominacion, cantidad in billetes_entregados:
        print("- {}: {}".format(denominacion, cantidad))
    print("Monedas a entregar:")
    for denominacion, cantidad in monedas_entregadas:
        print("- {}: {}".format(denominacion, cantidad))
    total_billetes = sum(cantidad for _, cantidad in billetes_entregados)
    total_monedas = sum(cantidad for _, cantidad in monedas_entregadas)
    print("Total de billetes a entregar: {}".format(total_billetes))
    print("Total de monedas a entregar: {}".format(total_monedas))
pago_estacionamiento()


from typing import Any, Dict, List
from pyspark.sql import DataFrame
import functools
import pyspark.sql.functions as func
from pyspark.sql import Window

from cvm.src.targets.ard_targets import get_ard_targets
from cvm.src.targets.churn_targets import filter_usage, get_churn_targets
from cvm.src.utils.prepare_key_columns import prepare_key_columns
from cvm.src.utils.incremental_manipulation import filter_latest_date, filter_users

def create_l5_cvm_one_day_users_table(
    profile: DataFrame, main_packs: DataFrame, date_chosen: str = "today"
) -> DataFrame:
    """Create l5_cvm_one_day_users_table - one day table of users used for
    training and validating.

    Args:
        profile: monthly customer profiles.
        main_packs: pre-paid main packages description.
        date_chosen: date to create list for. If "today" then take the most recent.
    """

    profile = prepare_key_columns(profile)
    if date_chosen == "today":
        date_chosen = None
    users = filter_latest_date(profile, date_chosen)
    users = users.filter(
        "charge_type == 'Pre-paid' \
         AND subscription_status == 'SA' \
         AND subscription_identifier is not null \
         AND subscription_identifier not in ('null', 'NA') \
         AND cust_active_this_month = 'Y'"
    )
    users = users.filter("subscriber_tenure >= 4")

    main_packs = main_packs.filter(
        "promotion_group_tariff not in ('SIM 2 Fly', \
         'Net SIM', 'Traveller SIM')"
    )
    main_packs = main_packs.select("package_id").withColumnRenamed(
        "package_id", "current_package_id"
    )
    users = users.join(main_packs, ["current_package_id"], "inner")
    columns_to_pick = ["key_date", "subscription_identifier"]
    users = users.select(columns_to_pick)

    return users.distinct()

def add_ard_targets(
    users: DataFrame, reve: DataFrame, parameters: Dict[str, Any], chosen_date: str
) -> DataFrame:
    """ Create table with ARPU drop targets.

    Args:
        users: Table with users and dates to create targets for.
        reve: Table with revenue stats.
        parameters: parameters defined in parameters.yml.
        chosen_date: Date for which targets will be created.
    Returns:
        Table with ARD targets.
    """

    local_parameters = parameters["targets"]["ard"]
    users = prepare_key_columns(users)
    ard_target_tables = [
        get_ard_targets(users, reve, local_parameters[targets], chosen_date)
        for targets in local_parameters
    ]

    def join_targets(df1, df2):
        return df1.join(df2, ["key_date", "subscription_identifier"], "full")

    return functools.reduce(join_targets, ard_target_tables)

def add_churn_targets(
    users: DataFrame, usage: DataFrame, parameters: Dict[str, Any]
) -> DataFrame:
    """ Create table with churn targets.

    Args:
        users: Table with users and dates to create targets for.
        usage: Table with usage stats.
        parameters: parameters defined in parameters.yml.

    Returns:
        Table with churn targets.
    """

    local_parameters = parameters["targets"]["churn"]
    chosen_date = parameters["chosen_date"]

    users = prepare_key_columns(users)
    usage = prepare_key_columns(usage)
    usage = filter_usage(users, usage, parameters)
    churn_target_tables = [
        get_churn_targets(users, usage, local_parameters[targets], chosen_date)
        for targets in local_parameters
    ]

    def join_targets(df1, df2):
        return df1.join(df2, ["key_date", "subscription_identifier"], "full")

    return functools.reduce(join_targets, churn_target_tables)

def create_l5_cvm_one_day_train_test(
    targets_features: DataFrame, parameters: Dict[str, Any],
) -> DataFrame:
    """Adds train-test column to features-targets table. Train share defined in
    parameters.

    Args:
        targets_features: Table with features and targets.
        parameters: parameters defined in parameters.yml.

    Returns:
        targets_features table with extra column with train / test flag.
    """

    train_share = parameters["l5_cvm_one_day_train_test"]["train_share"]

    # add train test flag
    train_test = targets_features.withColumn(
        "train_test", func.when(func.rand() <= train_share, "train").otherwise("test")
    )
    train = train_test.filter("train_test == 'train'").drop("train_test")
    test = train_test.filter("train_test == 'test'").drop("train_test")

    return train, test

def subs_date_join_important_only(
    important_param: List[Any], parameters: Dict[str, Any], *args: DataFrame,
) -> DataFrame:
    """ Left join all tables with important variables by given keys.

    Args:
        important_param: List of important columns.
        parameters: parameters defined in parameters.yml.
        *args: Tables to join.
    Returns:
        Left joined and filtered tables.
    """

    keys = parameters["key_columns"]
    segments = parameters["segment_columns"]
    must_have_features = parameters["must_have_features"]
    tables = [prepare_key_columns(tab) for tab in args]
    important_param = [
        "subscription_status",
        "age",
        "gender",
        "serenade_status",
        "subscriber_tenure",
        "activation_region",
        "current_package_id",
        "norms_net_revenue",
        "min_rev_arpu_total_idd_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_revenue_monthly_last_month",
        "sum_rev_arpu_total_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_gprs_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_gprs_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_sms_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_sms_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_others_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_others_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_voice_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_voice_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_mms_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_mms_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_ir_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_ir_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_idd_net_revenue_monthly_last_month",
        "sum_rev_arpu_total_idd_net_revenue_monthly_last_three_month",
        "sum_rev_arpu_total_voice_net_tariff_rev_mth_monthly_last_month",
        "sum_rev_arpu_total_voice_net_tariff_rev_mth_monthly_last_three_month",
        "sum_rev_arpu_total_gprs_net_tariff_rev_mth_monthly_last_month",
        "sum_rev_arpu_total_gprs_net_tariff_rev_mth_monthly_last_three_month",
        "sum_rev_arpu_total_sms_net_tariff_rev_mth_monthly_last_month",
        "sum_rev_arpu_total_sms_net_tariff_rev_mth_monthly_last_three_month",
        "sum_rev_arpu_total_mms_net_tariff_rev_mth_monthly_last_month",
        "sum_rev_arpu_total_mms_net_tariff_rev_mth_monthly_last_three_month",
        "sum_rev_arpu_total_others_net_tariff_rev_mth_monthly_last_month",
        "sum_rev_arpu_total_others_net_tariff_rev_mth_monthly_last_three_month",
        "sum_rev_arpu_total_voice_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_voice_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_gprs_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_gprs_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_sms_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_sms_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_mms_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_mms_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_others_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_others_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_ir_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_ir_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_idd_net_tariff_rev_ppu_monthly_last_month",
        "sum_rev_arpu_total_idd_net_tariff_rev_ppu_monthly_last_three_month",
        "sum_rev_arpu_total_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_gprs_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_sms_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_others_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_voice_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_mms_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_ir_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_idd_net_revenue_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_voice"
        + "_net_tariff_rev_mth_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_gprs_net_tariff"
        + "_rev_mth_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_sms_net_tariff_rev_mth_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_mms_net_tariff_rev_mth_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_others_net_tariff"
        + "_rev_mth_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_voice_net_tariff_rev"
        + "_ppu_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_gprs_net_tariff"
        + "_rev_ppu_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_sms_net_tariff_rev_ppu_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_mms_net_tariff_rev_ppu_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_others_net_tariff_rev"
        + "_ppu_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_ir_net_tariff_rev_ppu_monthly_last_month_over_three_month",
        "sum_rev_arpu_total_idd_net_tariff_rev_ppu_monthly_last_month_over_three_month",
        "sum_usg_outgoing_total_call_duration_daily_last_seven_day",
        "sum_usg_outgoing_total_call_duration_daily_last_fourteen_day",
        "sum_usg_outgoing_total_call_duration_daily_last_thirty_day",
        "sum_usg_outgoing_total_call_duration_daily_last_ninety_day",
        "sum_usg_outgoing_data_volume_daily_last_seven_day",
        "sum_usg_outgoing_data_volume_daily_last_fourteen_day",
        "sum_usg_outgoing_data_volume_daily_last_thirty_day",
        "sum_usg_outgoing_data_volume_daily_last_ninety_day",
        "sum_usg_outgoing_total_sms_daily_last_seven_day",
        "sum_usg_outgoing_total_sms_daily_last_fourteen_day",
        "sum_usg_outgoing_total_sms_daily_last_thirty_day",
        "sum_usg_outgoing_total_sms_daily_last_ninety_day",
        "sum_payments_top_ups_daily_last_seven_day",
        "sum_payments_top_ups_daily_last_fourteen_day",
        "sum_payments_top_ups_daily_last_thirty_day",
        "sum_payments_top_ups_daily_last_ninety_day",
        "sum_payments_top_up_volume_daily_last_seven_day",
        "sum_payments_top_up_volume_daily_last_fourteen_day",
        "sum_payments_top_up_volume_daily_last_thirty_day",
        "sum_payments_top_up_volume_daily_last_ninety_day",
    ]

    def filter_column(df, filter_list):
        cols_to_drop = [
            col_name for col_name in df.columns if col_name not in filter_list
        ]
        return df.drop(*cols_to_drop)

    tables = [
        filter_column(tab, important_param + keys + segments + must_have_features)
        for tab in tables
    ]

    def join_on(df1, df2):
        cols_to_drop = [col_name for col_name in df1.columns if col_name in df2.columns]
        cols_to_drop = list(set(cols_to_drop) - set(keys))
        df2 = df2.drop(*cols_to_drop)
        return df1.join(df2, keys, "left")

    return functools.reduce(join_on, tables)

def subs_date_join(parameters: Dict[str, Any], *args: DataFrame,) -> DataFrame:
    """ Left join all tables by given keys.

    Args:
        parameters: parameters defined in parameters.yml.
        *args: Tables to join.
    Returns:
        Left joined tables.
    """

    keys = parameters["key_columns"]
    tables = [prepare_key_columns(tab) for tab in args]

    def join_on(df1, df2):
        cols_to_drop = [col_name for col_name in df1.columns if col_name in df2.columns]
        cols_to_drop = list(set(cols_to_drop) - set(keys))
        df2 = df2.drop(*cols_to_drop)
        return df1.join(df2, keys, "left")

    return functools.reduce(join_on, tables)

def create_sample_dataset(
    df: DataFrame,
    sampling_params: Dict[str, Any],
    subscription_id_suffix: str,
    max_date: str,
) -> DataFrame:
    """ Create dev sample of given table. Dev sample is super small sample. Takes only
    users with certain subscription_identifier suffix.

    Args:
        df: given table.
        sampling_params: parameters of sampling procedure.
        subscription_id_suffix: suffix to filter subscription_identifier with.
        max_date: last date to include.
    Returns:
        Dev sample of table.
    """

    sampling_stages = {
        "filter_users": lambda df: filter_users(df, subscription_id_suffix),
        "take_last_date": lambda df: filter_latest_date(df, max_date),
    }

    for sampling_param in sampling_params:
        df = sampling_stages[sampling_param](df)

    return df

def add_macrosegments(df: DataFrame,) -> DataFrame:
    """ Add macrosegments columns.

    Args:
        df: DataFrame with all features.
    Returns:
        Input DataFrame with extra column marking macrosegment.
    """

    df = df.withColumn(
        "ard_macrosegment",
        func.when(
            (func.col("sum_rev_arpu_total_revenue_monthly_last_month") < 50)
            & (func.col("subscriber_tenure") >= 12),
            "low_arpu_high_tenure",
        )
        .when(
            (func.col("sum_rev_arpu_total_revenue_monthly_last_month") >= 50)
            & (func.col("subscriber_tenure") < 12),
            "high_arpu_low_tenure",
        )
        .when(
            (func.col("sum_rev_arpu_total_revenue_monthly_last_month") >= 50)
            & (func.col("subscriber_tenure") >= 12),
            "high_arpu_high_tenure",
        )
        .otherwise("low_arpu_low_tenure"),
    )
    df = df.withColumn(
        "churn_macrosegment",
        func.when(
            func.col("sum_rev_arpu_total_revenue_monthly_last_month") > 0,
            "positive_arpu",
        ).otherwise("zero_arpu"),
    )
    return df

def add_volatility_scores(
    users: DataFrame, reve: DataFrame, parameters: Dict[str, Any]
) -> DataFrame:
    """Create volatility score for given set of users.

    Args:
        users: DataFrame with users, subscription_identifier column will be
        used.
        Rest will be kept.
        reve: Monthly revenue data.
        parameters: parameters defined in parameters.yml.
    """

    vol_length = parameters["volatility_length"]
    reve_col = "norms_net_revenue"

    reve = prepare_key_columns(reve)
    users = prepare_key_columns(users)

    reve_cols_to_pick = parameters["key_columns"] + [reve_col]
    reve = reve.select(reve_cols_to_pick)
    reve_users_window = Window.partitionBy("subscription_identifier")
    reve = (
        reve.withColumn("reve_history", func.count("key_date").over(reve_users_window))
        .filter("reve_history >= {}".format(vol_length))
        .drop("reve_history")
    )
    vol_window = Window.partitionBy("subscription_identifier").orderBy(
        reve["key_date"].desc()
    )
    reve = reve.withColumn("month_id", func.rank().over(vol_window)).filter(
        "month_id <= {}".format(vol_length)
    )
    volatility = reve.groupby("subscription_identifier").agg(
        func.stddev(func.log(1 + func.col(reve_col))).alias("volatility")
    )

    users = users.join(volatility, "subscription_identifier", "left")

    return users


"""needs MVC imports"""
import unittest
import sys
sys.path.append('/Users/faultyquisby/openclassrooms/PythonFormation/livrables1/P4_carrasco_michael/app')
from controllers.controller import Controller
from models.enums import Gender
from models.enums import TimeControl
from models.tournament import Tournament
from models.player import Player
from models.round import Round
from models.carriers import TournamentCarrier
from models.carriers import PlayerCarrier
from views.menu import CYSMenu
from views.logger import Logger

my_matches = [
    {}
]

my_rounds = [
    Round("round1", "21/21/21", "21/21/21", my_matches),
    Round("round2", "21/21/21", "21/21/21", my_matches),
    Round("round3", "21/21/21", "21/21/21", my_matches),
    Round("round4", "21/21/21", "21/21/21", my_matches)
]

my_player = Player("hey", "heythere", "23/12/1992", Gender.FEMALE, 129)

my_updated_player = Player("hey", "heythere", "23/11/1800",
                           Gender.OTHER, 100)

my_players = [
    Player("Carrasco", "Michael", "23/12/1992", Gender.MALE, 299),
    Player("Myers", "Michael", "25/05/1963", Gender.MALE, 23),
    Player("Weaver", "Susan", "08/08/1949", Gender.FEMALE, 53),
    Player("Tobia", "Jacob", "07/06/1991", Gender.OTHER, 156),
    Player("Kasparof", "Garry", "13/04/1963", Gender.MALE, 2),
    Player("Carlsen", "Magnus", "30/11/1990", Gender.MALE, 1),
    Player("Polgar", "Judit", "23/07/1976", Gender.FEMALE, 5),
    Player("Brunson", "Doyle", "10/08/1933", Gender.MALE, 198),
    Player("Vachier-Lagrave", "Maxime", "21/10/1990", Gender.MALE, 10),
    Player("Scharzenegger", "Arnold", "30/07/1947", Gender.MALE, 78)
]

my_tournament = Tournament(
    "Le grand jeu",
    "5 avenue Victor Hugo",
    "23/12/2021",
    my_rounds,
    my_players,
    TimeControl.BLITZ,
    "C'est le plus gros tournoi d'echecs du monde !")

my_updated_tournament = Tournament(
    "Le petit jeu",
    "mise a jour de l'adresse aaaaa",
    "mise a jour de la dateaaaaa ffdf",
    my_rounds,
    my_players,
    TimeControl.RAPID,
    "mise a jour de la descriptionsadfasd  fdf sf")

my_tournaments = [
    Tournament(
        "Tournoi 1",
        "5 avenue Victor Hugo",
        "23/12/2021",
        my_rounds,
        my_players,
        TimeControl.BLITZ,
        "C'est le plus gros tournoi d'echecs du monde !"),
    Tournament(
        "Tournoi 2",
        "5 avenue Victor Hugo",
        "23/12/2021",
        my_rounds,
        my_players,
        TimeControl.BLITZ,
        "C'est le plus gros tournoi d'echecs du monde !"),
    Tournament(
        "Tournoi 3",
        "5 avenue Victor Hugo",
        "23/12/2021",
        my_rounds,
        my_players,
        TimeControl.BLITZ,
        "C'est le plus gros tournoi d'echecs du monde !")
]

class TestOne(unittest.TestCase):
    def test_db(self):
        # CREATE
        c = Controller(TournamentCarrier(), PlayerCarrier(), CYSMenu("Test"))

        # insert one tournament details version
        c.insert_tournament("Le petit jeu",
                "9 rue de la 1ere D.F.L",
                "24/12/2021",
                my_rounds,
                my_players,
                TimeControl.RAPID,
                "C'est le plus petit tournoi d'echecs du monde !")
        # insert one tournament Obj version
        c.insert_tournament_obj(my_tournament)
        # insert multiple tournaments
        c.insert_tournament_objs(my_tournaments)

        # insert one player details version
        c.insert_player("test", "bob", "23/12/1992", Gender.MALE, 500)
        # insert one player Obj version
        c.insert_player_obj(my_player)
        # insert multiple players
        c.insert_player_objs(my_players)

        # READ
        c.log_all_items()
        #c.log_all_players(bullet_points=True)
        #c.log_all_tournaments(bullet_points=True)
        #c.log_all_items(bullet_points=True)
        #c.log_item('Le grand jeu', 'tournament')
        #c.log_item('Michael Carrasco', 'player')

        # UPDATE
        # update tournament details version
        #c.update_tournament("Le petit jeu",
        #        "mise a jour de l'adresse",
        #        "mise a jour de la date",
        #        my_rounds,
        #        my_players,
        #        TimeControl.RAPID,
        #        "mise a jour de la description")
        # update tournament obj version
        #c.update_tournament_obj(my_updated_tournament)
        # update player details version
        #c.update_player("test", "bob", "23/11/1900", Gender.FEMALE, 39)
        # update player obj version
        #c.update_player_obj(my_updated_player)
        #c.log_item('Le petit jeu', 'tournament')

        #c.log_items()

        # we close the current sqlite database connection explicitly
        #if isinstance(c.models[0], TournamentCarrier):
            #tinydb_backend.disconnect_from_db(c.models[0].connection)
            # the sqlite backend understands that it needs to open a new connection
            #c.log_items()
            #tinydb_backend.disconnect_from_db(c.models[0].connection)
        # we close the current sqlite database connection explicitly
        #if isinstance(c.models[1], PlayerCarrier):
            #tinydb_backend.disconnect_from_db(c.models[1].connection)
            # the sqlite backend understands that it needs to open a new connection
            #c.log_items()
            #tinydb_backend.disconnect_from_db(c.models[1].connection)


from item import Item, item
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
    def __init__(self, name=None, current_room=None, inventory=[]):
        self.name = name
        self.current_room = current_room
        self.inventory = inventory

    def __str__(self):
        return f'Player info: Player Name: "{self.name}" Current Location: "{self.current_room}" Inventory Bag: "{self.inventory}"'

    def add_item(self):
        # self.inventory.append()
        #adding an item to my list in Player object. so.
        #need a data type {item}
        return self.item

    # def drop_item(self):
    #     return self.inventory.remove()
        # return f'drop_item {self.inventory}'

player = Player('carlitos', 'room', ['something cool'])
print(player)
print(player.name)
print(player.current_room)
print(player.inventory)
# print(item)
player.inventory.append('caprisun')
player.inventory.append('pop-tarts')
# player.inventory.remove('something cool')
print(player.inventory)
player.drop_item()

print(player)


import logging
from logging.handlers import TimedRotatingFileHandler

from src.settings import get_log_file_path

def _logger() -> logging.Logger:
    lg = logging.getLogger('AccessCounter')
    lg.setLevel(logging.INFO)
    handler = TimedRotatingFileHandler(get_log_file_path(), when="m", interval=1)
    lg.addHandler(handler)
    return lg

logger = _logger()


from pylab import *

a = float(input())
c = float(input())
x = linspace(-10, 10, 1001)

for i in range(5):
    y = a * x**i + i*x + c
    plot(x, y)

title("Funksjon")
xlabel("x")
ylabel("f(x)")
xlim(-5, 5)
ylim(-5, 20)
axhline(y=0, color="k")
axvline(x=0, color="k")
grid()
show()


#!/usr/bin/env python

from distutils import log
from distutils.core import setup
from distutils.command.build_scripts import build_scripts
from distutils.command.install_data import install_data

from docutils.core import publish_file
from docutils.writers import manpage

class install_data_man_one(install_data):
    def run(self):
        # Go through each "directory" entry.
        new_data_files = []
        for data in self.data_files:
            # Skip over files not destined for man1 directories.
            if not isinstance(data, tuple) or data[0] != 'share/man/man1':
                new_data.append(data)
                continue

            # Go through the files, and look for *.rst pages.
            new_list = []
            for entry in data[1]:
                # Only process *.rst files.
                if not entry.endswith('.rst'):
                    new_list.append(entry)
                    continue

                # Use docutils to convert the RST document to manpage 1 format.
                man = entry[:-4] + '.1'
                log.info("converting %s -> %s" % (entry, man))
                publish_file(source_path=entry, destination_path=man,
                             writer=manpage.Writer())
                new_list.append(man)

            new_data_files.append((data[0], new_list))
        # Pass the processed list to the original install_data.run()
        self.data_files = new_data_files
        install_data.run(self)

class build_scripts_strip_py(build_scripts):
    def run(self):
        # Process the files list, stripping '.py' from script names.
        new_list = []
        for script in self.scripts:
            if script.endswith('.py'):
                self.copy_file(script, script[:-3])
                script = script[:-3]
            new_list.append(script)
        # Pass the processed list to the original build_scripts.run()
        self.scripts = new_list
        build_scripts.run(self)

setup(name='wavlooper',
      version='1.0',
      license='GPL-3',
      description="Loop a WAV file with optional fadeout.",
      author="Ryan \"ZDBioHazard\" Turner",
      author_email='zdbiohazard2@gmail.com',
      url='https://github.com/ZDBioHazard/wavlooper/',
      scripts=['wavlooper.py'],
      data_files=[('share/man/man1', ['wavlooper.rst'])],
      cmdclass={"build_scripts": build_scripts_strip_py,
                "install_data": install_data_man_one})


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 13:46:45 2020

This module contains several classes to be used for constructing models using GPytorch.
Any custom kernel or custom GPytorch regression model can be defined as a class here.

To Do: Allow user to set the kernels, not just RBF. The mean can stay constant for now.
To Do: Consider making one model that can be either exact or sparse, and arbitrary kernel. This would simplify all this down to one class.

@author: soper3
"""

import gpytorch
import numpy as np

class CellDrugKernel(gpytorch.kernels.Kernel):
    """
    kernel to combine cell drug kernels respectively to make composite kernel with product or adding
    """

    def __init__(self, kernel_cell, kernel_drug, cell_drug_split, operation='add'):
        """
        inputs
        --------------------------------------------------------------------------
        kernel_cell: Gpy kernel object corresponding to rbf kernel on cell features
        kernel_drug: Gpy kernel object corresponding to rbf kernel on drug features
        cell drug split: index in which the two sets of features are split in training data
        operation: string 'add to add or multiply kernels
        """
        super(CellDrugKernel, self).__init__()
        self.kernel_cell = kernel_cell
        self.kernel_drug = kernel_drug
        self.cell_drug_split = cell_drug_split
        self.operation = operation

    def forward(self, x1, x2, last_dim_is_batch,diag=True):
        """
        inputs
        --------------------------------------------------------------------------
        x1, x2: feature data arrays
        """
        cell_forward = self.kernel_cell.forward(x1[:,:self.cell_drug_split], x2[:,:self.cell_drug_split])
        drug_forward = self.kernel_drug.forward(x1[:,self.cell_drug_split:], x2[:,self.cell_drug_split:])

        if self.operation=='product':
            out = cell_forward * drug_forward
        else:
            out = cell_forward + drug_forward

        return out

class ExactGPModel(gpytorch.models.ExactGP):
    """
    Nonsamping version of GP, uses every training point in kernel
    """
    def __init__(self, train_x, train_y, likelihood):
        """
        inputs
        --------------------------------------------------------------------------
        train_x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        train_y : training data vector of cell-drug response vector
        likelihood: likelihood to use in MLE for this GP model, should be marginal log likelihood
        """
        super(ExactGPModel, self).__init__(train_x, train_y, likelihood)
        self.mean_module = gpytorch.means.ConstantMean()
        self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())

    def forward(self, x):
        """
        inputs
        --------------------------------------------------------------------------
        x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        """
        mean_x = self.mean_module(x)
        covar_x = self.covar_module(x)
        return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)

class SparseGPModel(gpytorch.models.ExactGP):
    """
    Sampling GP model, only defines process at n inducing points
    """
    def __init__(self, train_x, train_y, likelihood, n_inducing_points):
        """
        inputs
        --------------------------------------------------------------------------
        train_x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        train_y : training data vector of cell-drug response vector
        likelihood: likelihood to use in MLE for this GP model, should be marginal log likelihood
        n_inducing_points: number of samples to take from data
        """
        super(SparseGPModel, self).__init__(train_x, train_y, likelihood)
        self.n_inducing_points = n_inducing_points
        self.mean_module = gpytorch.means.ConstantMean()
        self.base_covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel(lengthscale_constraint=gpytorch.constraints.GreaterThan(0.1))) #lengthscale_constraint=gpytorch.constraints.GreaterThan(0.1)
        n,m=train_x.shape
        inducing_points = np.random.choice(n, size=n_inducing_points, replace=False)
        self.covar_module = gpytorch.kernels.InducingPointKernel(self.base_covar_module, inducing_points=train_x[inducing_points,:],likelihood=likelihood)
        self.train_x = train_x
        self.train_y = train_y
        self.recording = True

    def forward(self, x):
        """
        inputs
        --------------------------------------------------------------------------
        x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        """
        mean_x = self.mean_module(x)
        covar_x = self.covar_module(x)
        if self.recording:
            self.covar_x = covar_x
        return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
    # getters
    def getTrainY(self):
        return self.train_y

    def getTrainX(self):
        return self.train_x # second dimension is just task numbers

    def getCovar(self):
        return self.covar_x

class ExactGPCompositeKernelModel(gpytorch.models.ExactGP):
    """
    Nonsamping version of GP, uses every training point and splits features into two kernels, one for drug and one for cell line
    """
    def __init__(self, train_x, train_y, likelihood, cell_drug_split):
        """
        inputs
        --------------------------------------------------------------------------
        train_x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        train_y : training data vector of cell-drug response vector
        likelihood: likelihood to use in MLE for this GP model, should be marginal log likelihood
        cell_drug_split: index at which we should split our features to go into different kernels
        """
        super(ExactGPCompositeKernelModel, self).__init__(train_x, train_y, likelihood)
        self.cell_drug_split = cell_drug_split
        n,m=train_x.shape
        self.mean_module = gpytorch.means.ConstantMean()
        self.cell_covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
        self.drug_covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
        self.covar_module = CellDrugKernel(self.cell_covar_module, self.drug_covar_module, cell_drug_split)#, n-cell_drug_split)

    def forward(self, x):
        """
        inputs
        --------------------------------------------------------------------------
        x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        """
        mean_x = self.mean_module(x)
        covar_x = self.covar_module(x)
        return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)

class SparseGPCompositeKernelModel(gpytorch.models.ExactGP):
    """
    Sampling GP model, only defines process at n inducing points. Uses two seperate kernels for drug and cell features
    """
    def __init__(self, train_x, train_y, likelihood, cell_drug_split, n_inducing_points):
        """
        inputs
        --------------------------------------------------------------------------
        train_x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        train_y : training data vector of cell-drug response vector
        likelihood: likelihood to use in MLE for this GP model, should be marginal log likelihood
        cell_drug_split: index at which we should split our features to go into different kernels
        n_inducing: points where GP is defined (samples from training set)
        """
        super(SparseGPCompositeKernelModel, self).__init__(train_x, train_y, likelihood)
        self.cell_drug_split = cell_drug_split
        self.n_inducing_points = n_inducing_points
        n,m=train_x.shape
        inducing_points = np.random.choice(n, size=n_inducing_points, replace=False)
        self.mean_module = gpytorch.means.ConstantMean()
        self.cell_covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
        self.drug_covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
        self.base_covar_module = CellDrugKernel(self.cell_covar_module, self.drug_covar_module, cell_drug_split, n-cell_drug_split)
        self.covar_module = gpytorch.kernels.InducingPointKernel(self.base_covar_module, inducing_points=train_x[inducing_points,:],likelihood=likelihood)

    def forward(self, x):
        """
        inputs
        --------------------------------------------------------------------------
        x: training data for x, should be 2d array with shape (nsamples,nfeatures)
        """
        mean_x = self.mean_module(x)
        covar_x = self.covar_module(x)
        return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)


import numpy as np
import matplotlib.pyplot as plt
import csv

time = np.arange(1000)
LEN = 1000
DELTA_LEN = 50

def CPI_value():
    delta = np.random.random(DELTA_LEN)*0.00010 - 0.000025
    new_delta = []
    for i in range(len(delta)):
        for _ in range(int(LEN / DELTA_LEN)):
            new_delta.append(delta[i])
    init = 2
    out = np.zeros(1000)
    out[0] = init + new_delta[0]
    for i in range(1, 1000):
        out[i] = out[i-1] * (1+new_delta[i])
    return out

if __name__ == "__main__":
    cpi_value = CPI_value()
    with open('../../dataset/cpi_value.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(cpi_value)
    plt.figure()
    plt.plot(time, cpi_value)
    plt.title("CPI value per timestamp")
    plt.xlabel("time")
    plt.ylabel("Value of CPI")
    plt.savefig("../../images/cpi_value.png")


# Do not modify these lines
__winc_id__ = '7b9401ad7f544be2a23321292dd61cb6'
__human_name__ = 'arguments'

# Add your code after this line
# Part 1 Greet Template
def greet(name, greeting_template="Hello, <name>!"):
    return greeting_template.replace("<name>", name)

# Part 2 Force
def force(mass, body='earth'):
    # Round the gravity factor to 1 decimal
    bodies = {
        'mercury': 3.7,
        'venus': 8.87,
        'earth': 9.8,
        'mars': 3.71,
        'jupiter': 24.79,
        'saturn': 10.44,
        'uranus': 8.69,
        'neptune': 11.15,
        'pluto': 0.62,
        'moon': 1.62,
        'sun': 274.0
    }
    gravity = round(bodies[body], 1)
    return mass * gravity

# Part 3 Gravity
def pull(m1, m2, d):
    G = 6.674 * 10 ** -11
    pull = G * ((m1 * m2) / d ** 2)
    return pull


from base_etl import BaseETL

class PatientStep01(BaseETL):

    def run(
        self,
    ):
        sql= '''
            SELECT 환자번호, 원무접수ID, 성별,
            replace (수진당시나이, 'yrs', '') as age,
                입원일,
                퇴원일,
                `주소(시,도)`,
                `주소(시,군,구)`,
                `신장(cm)` as height1,
                `체중(kg)` as weight1
            FROM patient
            ORDER BY 환자번호
        '''
        df = self.df_from_sql(db_name="gc_raw", sql=sql)
        self.insert(df, db_name="gc_protocol", tb_name="patient_step_01")

if __name__ == "__main__":
    obj = PatientStep01()
    obj.run()


# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# <codecell>

#%pylab inline
import numpy as np
import urllib2
import urllib
import Image
from mpl_toolkits.basemap import Basemap
import csv
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

# <codecell>

url = 'http://www.cgd.ucar.edu/cas/catalog/surface/dai-runoff/coastal-stns-byVol-updated-oct2007.txt' #libreria para descargar archivos de url
urllib.urlretrieve(url, "catalogo.txt")
f = urllib.urlopen(url)
data = f.read()
with open("catalogo.txt", "wb") as code: #reconstruye el archivo linea por linea
    code.write(data)

# <codecell>

lst = map(str, open('catalogo.txt').readlines()) #convierte las lineas en una lista
todo = np.asarray(lst) #convierte a arreglo

# <codecell>

##solo queremos operar con la segunda columna, se crea un arreglo de dos dimensiones con el indice y el numero buscado
A = np.zeros((len(todo),2))
B = np.zeros(len(todo))
C = np.zeros(len(todo))
for i in range(1, len(todo)):
    a = todo[i].split(' ') #separa las lineas del arreglo por espacios
    a[:] = [x for x in a if x != ''] #escoge todo lo que no sea espacio
    A[i,0] = i
    A[i,1] = a[1]
    B[i] = a[2]
    C[i] = a[3]
A = A[1:,:] #define el nuuevo arreglo

# <codecell>

A_sorted = A[A[:, 1].argsort()] #ordena de menor a mayor el arreglo
A_i = A_sorted[925-300:925,:] #selecciona los ultimos 300 que ya sabemos que son los mayores
index = A_i[:,0]
ratio = A_i[:,1]
lon = []
lat = []
for el in index:
    lon.append(B[int(el)])
    lat.append(C[int(el)])

# <codecell>

EL_QUE_VA_PA_CSV = np.column_stack((index,ratio,lon,lat))

# <codecell>

fileout = open("hfile.csv", "w")
fileout.write('No,m2s_ratio,lonm,latm\n')
for i in range(300):
    fileout.write('%f,%f,%f,%f\n'%(index[i],ratio[i],lon[i],lat[i]))
fileout.close()

# <codecell>

#for el in lat: #la lista para basemap
    #print el
#type(flux)
#values = ','.join(str(v) for v in flux)
#values.split()
#values[::-1]

# <codecell>

#for el in top_300:
    #print el

# <codecell>

a = lat
b = lon
c=np.column_stack((a,b))
d = c.tolist()

# <codecell>

son_todos=[] #vuelve a llenar en el arreglo inicial que tiene todos los datos
for j in range(len(todo)):
    b = todo[j].split(' ')
    b[:] = [x for x in b if x != '']
    son_todos.append(b)

# <codecell>

#for j in son_todos:
    #print j

# <codecell>

with open("top_basemap.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(d)

# <codecell>

csvfile = "top_300.csv" #guarda como archivo csv
with open(csvfile, "w") as output:
    writer = csv.writer(output, delimiter=' ', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    for val in son_todos:
        writer.writerow([val])
with open("top_basemap.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(d)

# <codecell>

#!ls

# <codecell>

#!head hfile.csv

# <codecell>

# <codecell>


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import albums_plugin.models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Photo',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('image', models.ImageField(upload_to=albums_plugin.models.generate_folder_path)),
                ('caption', models.TextField(null=True, blank=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='PhotoAlbum',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=250)),
                ('description', models.TextField(null=True, blank=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='photo',
            name='album',
            field=models.ForeignKey(related_name='photos', to='albums_plugin.PhotoAlbum'),
            preserve_default=True,
        ),
    ]


import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the dataset
df = pd.read_csv(r"D:\security\tmdb_movies_data.csv")

# Dropping irrelevant column
df = df.drop(['id','imdb_id','homepage','tagline','overview','release_date','original_title'],axis=1)

# Handling missing values
df = df.dropna()

# Categorical to numerical conversion
df['genres'] = df['genres'].apply(lambda x: x.split(',')[0])
df['production_companies'] = df['production_companies'].apply(lambda x: x.split(',')[0])

# Splitting the data into features and target variable
X = df.drop(['revenue'],axis=1)
y = df['revenue']

# One-hot encoding
X = pd.get_dummies(X)

# Convert revenue into binary labels
y = np.where(y > y.median(), 1, 0)

# Splitting the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Initializing the model
model = LogisticRegression()

# Training the model
model.fit(X_train, y_train)

# Evaluating the model
y_pred = model.predict(X_test)

print('Accuracy:', accuracy_score(y_test, y_pred))


# #tuples are immutable, may be nested,
# and can contain mutable objects. IE:
# t = 12345, 54321, 'hello!'
# print(t[0])
# u = t, (1, 2, 3, 4, 5)
# empty = ()
# print(type(empty))

zoo = ("monkey", "pig", "chicken", "dog", "bigger dog")
(first_animal, second_animal, third_animal, fourth_animal, _fifth_animal) = zoo
# print(zoo.index("monkey"))
animal_to_find = "pig"
# search the tuple to see if it contains a particular value
if animal_to_find in zoo:
    print(f"{animal_to_find} is in the zoo")
else:
  print("nope not in this zoo!")

# convert the tuple into a list, add items to the list
# then convert back to a tuple
zoo_list = list(zoo)
zoo_list.extend(["puppy", "horse", "penguin"])
zoo = tuple(zoo_list)
for animal in zoo:
  print(f"{animal} loves the zoo!")


import numpy as np
import cv2 as cv
import open3d as o3d

from point_cloud_calibration.tools.algorithm import affine

def image_registration(points, frame, lastFrame):
    """
    :param points: [n, 2]
    """
    H, _ = _img_reg(frame, lastFrame)
    u, v = points[:, 0], points[:, 1]
    points = affine(u, v, H)
    return points, H

def point_cloud_registration(source, target):
    """
    :param source: [n, 2]
    :param target: [n, 2]
    :return:
    """
    source = np.concatenate((source, np.zeros(source.shape[0])), axis=1).T
    target = np.concatenate((target, np.zeros(target.shape[0])), axis=1).T
    points = _point_reg(source, target)
    return points

def _img_reg(img1, img2, id=None):
    # 初始化 AKAZE 探测器
    akaze = cv.AKAZE_create()
    # 使用 SIFT 查找关键点和描述
    kp1, des1 = akaze.detectAndCompute(img1, None)
    kp2, des2 = akaze.detectAndCompute(img2, None)

    # BFMatcher 默认参数
    bf = cv.BFMatcher()
    matches = bf.knnMatch(des1, des2, k=2)

    # 旋转测试
    good_matches = []
    for m, n in matches:
        if m._distance < 0.75 * n._distance:
            good_matches.append([m])

    # 选择匹配关键点
    ref_matched_kpts = np.float32([kp1[m[0].queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
    sensed_matched_kpts = np.float32([kp2[m[0].trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
    # 计算 homography
    H, status = cv.findHomography(ref_matched_kpts, sensed_matched_kpts, cv.RANSAC, 5.0)
    # 变换
    warped_image = cv.warpPerspective(img1, H, (img1.shape[1], img1.shape[0]))
    if id is None:
        return H, warped_image
    else:
        cv.imwrite('./data/new_3/warped%d.jpg' % id, warped_image)

def _point_reg(source, target):
    trans_init = np.asarray([[1, 0, 0, 0],
                             [0, 1, 0, 0],
                             [0, 0, 1, 0],
                             [0, 0, 0, 1]])

    reg_p2p = o3d.pipelines.registration.registration_icp(
        source, target, 0.02, trans_init,
        o3d.pipelines.registration.TransformationEstimationPointToPoint(),
        o3d.pipelines.registration.ICPConvergenceCriteria(max_iteration=200)
    )

    source.transform(reg_p2p.transformation)
    return np.asarray(source.points)[:, :2].astype(int)


from flask import Flask, jsonify, abort, make_response, request
from flask.views import MethodView
from flasgger import Swagger, swag_from
import os
from settings import PATH_TO_OPENAPI

app = Flask(__name__)
app.config['SWAGGER'] = {
    'title': 'Test API',
}
app.config['SWAGGER']['openapi'] = '3.0.0'
swagger = Swagger(app=app, template_file=PATH_TO_OPENAPI, parse=True)

class GetUser(MethodView):
    def get(self):
        return jsonify({'id': request.args.get('userId'), 'type': 'NORMAL'})

class GetGroup(MethodView):
    def get(self):
        return jsonify({'name': request.args.get('groupName'), 'type': 'NORMAL'})

app.add_url_rule(
    '/users/', view_func=GetUser.as_view(name='users'),
    methods=['GET'])

app.add_url_rule(
    '/groups/', view_func=GetGroup.as_view(name='groups'),
    methods=['GET'])

app.run(debug=True)