"""Support for the Wyze lock."""
import logging
from typing import Any, List, Optional, Union

from zigpy.profiles import zha
from zigpy.quirks import CustomCluster, CustomDevice
import zigpy.types as t
from zigpy.zcl import foundation
from zigpy.zcl.clusters.closures import DoorLock
from zigpy.zcl.clusters.general import (
    Basic,
    Identify,
    Ota,
    PollControl,
    PowerConfiguration,
    Time,
)
from zigpy.zcl.clusters.homeautomation import Diagnostic
from zigpy.zcl.clusters.security import IasZone

from . import YUNDING
from zhaquirks import Bus, LocalDataCluster
from zhaquirks.const import (
    CLUSTER_COMMAND,
    DEVICE_TYPE,
    ENDPOINTS,
    INPUT_CLUSTERS,
    MODELS_INFO,
    OFF,
    ON,
    OUTPUT_CLUSTERS,
    PROFILE_ID,
    ZONE_STATE,
)

WYZE_CLUSTER_ID = 0xFC00
ZONE_TYPE = 0x0001

_LOGGER = logging.getLogger(__name__)

class DoorLockCluster(CustomCluster, DoorLock):
    """DoorLockCluster cluster."""

    cluster_id = DoorLock.cluster_id

    def __init__(self, *args, **kwargs):
        """Init."""
        super().__init__(*args, **kwargs)
        self.endpoint.device.lock_bus.add_listener(self)

    def lock_event(self, locked):
        """Motion event."""
        self._update_attribute(0x0000, locked)

class MotionCluster(LocalDataCluster, IasZone):
    """Motion cluster."""

    cluster_id = IasZone.cluster_id

    def __init__(self, *args, **kwargs):
        """Init."""
        super().__init__(*args, **kwargs)
        self.endpoint.device.motion_bus.add_listener(self)
        super()._update_attribute(ZONE_TYPE, IasZone.ZoneType.Contact_Switch)

    def motion_event(self, zone_state):
        """Motion event."""
        super().listener_event(CLUSTER_COMMAND, None, ZONE_STATE, [zone_state])
        _LOGGER.debug("%s - Received motion event message", self.endpoint.device.ieee)

class WyzeCluster(CustomCluster, Basic):
    """Wyze manufacturer specific cluster implementation."""

    cluster_id = WYZE_CLUSTER_ID
    ep_attribute = "wyze_lock_cluster"
    attributes = {}
    server_commands = {}
    client_commands = {}

    def handle_message(
        self,
        hdr: foundation.ZCLHeader,
        args: List[Any],
        *,
        dst_addressing: Optional[
            Union[t.Addressing.Group, t.Addressing.IEEE, t.Addressing.NWK]
        ] = None,
    ):
        """Handle a message on this cluster."""
        self.debug("ZCL request 0x%04x: %s", hdr.command_id, args)
        i = 0
        for arg in args:
            self.info("index: %s value: %s", i, arg)
            i += 1
        self.warning("argument length: %s", len(args))
        self.warning("argument: %s", ",".join(map(str, args)))
        if len(args) < 70 or len(args) > 100:
            self.warning("argument list bad length: %s", len(args))
            return
        self.info(
            "Interesting attributes - 52: %s, 41: %s, 56: %s, 57: %s",
            args[52],
            args[41],
            args[56],
            args[57],
        )

        """
        Manual Lock: 52: 216, 41: 99, 56: 227, 57: 84
        Manual Unlock: 52: 216, 41: 100, 56: 227, 57: 84
        """
        if args[52] == 180 and args[41] == 165:
            self.warning("the lock is unlocked via the app")
            self.endpoint.device.lock_bus.listener_event("lock_event", 2)
        elif args[52] == 180 and args[41] == 162:
            self.warning("the lock is locked via the app")
            self.endpoint.device.lock_bus.listener_event("lock_event", 1)
        elif args[52] == 216 and args[41] == 100:
            self.warning("the lock is unlocked manually")
            self.endpoint.device.lock_bus.listener_event("lock_event", 2)
        elif args[52] == 216 and args[41] == 99:
            self.warning("the lock is locked manually")
            self.endpoint.device.lock_bus.listener_event("lock_event", 1)
        elif args[52] == 189 and args[41] == 162:
            self.warning("the lock is locked via auto lock")
            self.endpoint.device.lock_bus.listener_event("lock_event", 1)
        if args[52] == 74 and args[41] == 177:
            self.warning("the door is open")
            self.endpoint.device.motion_bus.listener_event("motion_event", ON)
        elif args[52] == 74 and args[41] == 178:
            self.warning("the door is closed")
            self.endpoint.device.motion_bus.listener_event("motion_event", OFF)

class WyzeLock(CustomDevice):
    """Wyze lock device."""

    def __init__(self, *args, **kwargs):
        """Init."""
        self.lock_bus = Bus()
        self.motion_bus = Bus()
        super().__init__(*args, **kwargs)

    signature = {
        #  <SimpleDescriptor endpoint=1 profile=260 device_type=10
        # device_version=1
        # input_clusters=[0, 1, 3, 32, 257, 2821, 64512]
        # output_clusters=[10, 25, 64512]>
        MODELS_INFO: [(YUNDING, "Ford")],
        ENDPOINTS: {
            1: {
                PROFILE_ID: zha.PROFILE_ID,
                DEVICE_TYPE: zha.DeviceType.DOOR_LOCK,
                INPUT_CLUSTERS: [
                    Basic.cluster_id,
                    PowerConfiguration.cluster_id,
                    Identify.cluster_id,
                    PollControl.cluster_id,
                    DoorLock.cluster_id,
                    Diagnostic.cluster_id,
                    WYZE_CLUSTER_ID,
                ],
                OUTPUT_CLUSTERS: [Ota.cluster_id, Time.cluster_id, WYZE_CLUSTER_ID],
            }
        },
    }
    replacement = {
        ENDPOINTS: {
            1: {
                PROFILE_ID: zha.PROFILE_ID,
                DEVICE_TYPE: zha.DeviceType.DOOR_LOCK,
                INPUT_CLUSTERS: [
                    Basic.cluster_id,
                    PowerConfiguration.cluster_id,
                    Identify.cluster_id,
                    PollControl.cluster_id,
                    DoorLockCluster,
                    Diagnostic.cluster_id,
                    WyzeCluster,
                    MotionCluster,
                ],
                OUTPUT_CLUSTERS: [Ota.cluster_id, Time.cluster_id, WyzeCluster],
            }
        }
    }


import cv2
import numpy as np
import datetime
import os
import csv
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

from metavision_core.event_io import EventsIterator, LiveReplayEventsIterator, is_live_camera
from metavision_sdk_analytics import TrackingAlgorithm, TrackingConfig, draw_tracking_results
from metavision_sdk_core import OnDemandFrameGenerationAlgorithm
from metavision_sdk_cv import ActivityNoiseFilterAlgorithm, TrailFilterAlgorithm
from metavision_sdk_ui import EventLoop, BaseWindow, MTWindow, UIAction, UIKeyEvent

class Inputs:
    def __init__(self, args):
        self.input_path = args.raw_file_path
        self.process_from = args.process_from * 1e6
        if args.process_to is not None:
            self.process_to = args.process_to * 1e6
        else:
            self.process_to = None
        self.bias_file = args.bias_file_path
        self.update_frequency = float(args.update_frequency)
        if args.accumulation_time > 0:
            self.accumulation_time = int(args.accumulation_time * 1e6)
        else:
            self.accumulation_time = int(1e6/args.update_frequency)
        self.min_size = args.min_size
        self.max_size = args.max_size
        self.activity_time_ths = args.activity_time_ths
        self.activity_ths = args.activity_ths
        self.activity_trail_ths = args.activity_trail_ths
        if args.output_csv_path:
            self.output_csv_path = args.output_csv_path
        else:
            self.output_csv_path = os.getcwd() + '/EVK_'
        self.measurement_time = args.outputs_csv_interval * 1e6
        self.save_flag = args.save_flag
        self.out_video = args.out_video
        self.draw_bb = args.draw_bounding_boxes
        self.replay_factor = args.replay_factor

def parse_args():
    import argparse
    """
    Parse command line arguments.
    """
    parser = argparse.ArgumentParser(description='Object Tracking', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    # Base options
    base_options = parser.add_argument_group('Base options')
    base_options.add_argument('-i', '--input-raw-file', dest='raw_file_path', default='',
                              help='Path to input RAW file. If not specified, the live stream of the first available camera is used.'
                              "If it's a camera ID, it will try to open that camera instead.")
    base_options.add_argument('-pf','--process-from', dest='process_from', type=int, default=0,
                              help='Time at which the algorithm starts processing events. If not specified, the algorithm starts processing events from the beginning. Unit: seconds. Default value: 0s.')
    base_options.add_argument('-pt','--process-to', dest='process_to', type=int, default=None,
                              help='Time at which the algorithm stops processing events. If not specific, the algorithm will have to be manually stopped. Unit: seconds. Default value: None.')
    base_options.add_argument('-bf', '--bias-file', dest='bias_file_path',default='',
                              help='Path to BIAS file to modify the parameters of the sensor of the event-based camera. Default: \'\'.')
    #add ROI as input?
    # Algorithm options
    algorithm_options = parser.add_argument_group('Algorithm options')
    algorithm_options.add_argument('-uf', '--update-frequency', dest='update_frequency', type=int, default=1000,
                              help='Frequency of the frame generation of the tracking algorithm. Unit: Hertz. Default: 1000Hz.')
    algorithm_options.add_argument('-at', '--accum-time', dest='accumulation_time', type=float, default=0.,
                              help='Time interval that the tracking algorithm uses to accumulate events into a frame. Unit: seconds. Default: inverse of [update_frequency].')
    # Object options
    object_size_options = parser.add_argument_group('Object options')
    object_size_options.add_argument('-mins', '--min-size', dest='min_size', type=int, default=10,
                                    help='Minimal size of an object to track (or the resulting bounding box). Unit: pixels. Default: 10px.')
    object_size_options.add_argument('-maxs', '--max-size', dest='max_size', type=int, default=100,
                                    help='Maximal size of an object to track (or the resulting bounding box). Unit: pixels. Default: 100px.')
    # Filtering options
    filter_options = parser.add_argument_group('Filtering options')
    filter_options.add_argument('--activity-time-ths', dest='activity_time_ths', type=int, default=10000,
                                help='Length of the time window for activity filtering (Disabled if the threshold is equal to 0).')
    filter_options.add_argument('--activity-ths', dest='activity_ths', type=int, default=1,
                                help='Minimum number of events in the neighborhood.')
    filter_options.add_argument('--activity-trail-ths', dest='activity_trail_ths', type=int, default=1000,
                                help='Length of the time window for trail filtering (in us).')
    # Saving Options
    saving_options = parser.add_argument_group('Saving options')
    saving_options.add_argument('-csv', '--save-csv-path', dest='output_csv_path', type=str, default='',
                                help='File path of output CSV files that contain the information of detected objects, excluding the file extension. Default: \'EVK_\{timestamp\}.csv\' at location of script.')
    saving_options.add_argument('-csvt', '--save-csv-interval', dest='outputs_csv_interval', type=int, default=60,
                                help='Time interval of tracked information saved into a single CSV file. For measurement times longer than the input interval time, several CSV files are saved with their corresponding timestamps. Unit: seconds. Default: 60s.')
    saving_options.add_argument('-csvf', '--save-flag', dest='save_flag', type=bool, default=True,
                                help="Flag that determines if measurements are recorded. Default: True.")
    # Outcome Options
    outcome_options = parser.add_argument_group('Outcome options')
    outcome_options.add_argument('-ov', '--out-video', dest='out_video', type=str, default='',
                                help='File path of output AVI where the video feed is saved with [update frequency] frames per second. If not specified, the video feed will not be saved. Default: \'\'.')
    outcome_options.add_argument('-dbb', '--draw-bb', dest='draw_bounding_boxes', type=bool, default=False,
                                help='Defines if bounding boxes of tracked objects need to be shown in video feed. Default: False.')
    # Replay Option
    replay_options = parser.add_argument_group('Replay options')
    replay_options.add_argument('-rf', '--replay_factor', dest='replay_factor', type=float, default=1.,
                                help='Replay factor. If greater than 1.0 we replay with slow-motion, otherwise this is a speed-up over real-time. Default: 1.0')

    args = parser.parse_args()

    if args.process_to and args.process_from > args.process_to:
        print(f'The processing time interval is not valid. [{args.process_from,}, {args.process_to}]')
        exit(1)

    if args.replay_factor < 0:
        print(f'The replay factor is not valid. [{args.replay_factor}]')
        exit(1)

    return args

def get_biases_from_file(path: str):
    """
    Helper function to read bias from a file. Return biases list with elements: 0 = value, 1 = name.
    """
    biases = {}
    try:
        biases_file = open(path, 'r')
    except IOError:
        print('Cannot open bias file: ' + path)
    else:
        for line in biases_file:
            # Skip lines starting with '%': comments
            if line.startswith('%'):
                continue

            split = line.split("%")
            biases[split[1].strip()] = int(split[0])
    return biases

def main():
    """
    Main
    """
    args = parse_args()
    inputs = Inputs(args)

    total_results = []
    measurement_index = 0

    # Events iterator on Camera or RAW file - CD PRODUCER
    mv_iterator = EventsIterator(input_path=inputs.input_path, start_ts=inputs.process_from,
                                 max_duration=inputs.process_to - inputs.process_from if inputs.process_to else None,
                                 delta_t=1e2)

    if is_live_camera(inputs.input_path): #EVK camera connected
        device = mv_iterator.reader.device
        #i_roi = device.get_i_roi()
        if os.path.isfile(inputs.bias_file):
                b = get_biases_from_file(inputs.bias_file)

                i_ll_biases = device.get_i_ll_biases()
                for bias_name, bias_value in b.items():
                    print(f'Applying {bias_name} = {bias_value}')
                    i_ll_biases.set(bias_name, bias_value)
    elif inputs.replay_factor > 0: #Using a RAW file
        mv_iterator = LiveReplayEventsIterator(mv_iterator, replay_factor=inputs.replay_factor)

    sensor_height, sensor_width = mv_iterator.get_size() # Sensor Geometry

    # Noise + Trail filter that will be applied to events
    activity_noise_filter = ActivityNoiseFilterAlgorithm(sensor_width, sensor_height, inputs.activity_time_ths)
    trail_filter = TrailFilterAlgorithm(sensor_width, sensor_height, inputs.activity_trail_ths)
    events_buf = ActivityNoiseFilterAlgorithm.get_empty_output_buffer()

    # Tracking Algorithm
    tracking_config = TrackingConfig()  # Default configuration
    tracking_algo = TrackingAlgorithm(sensor_width=sensor_width, sensor_height=sensor_height, tracking_config=tracking_config)
    tracking_algo.update_frequency = inputs.update_frequency
    tracking_algo.min_size = inputs.min_size
    tracking_algo.max_size = inputs.max_size

    # Event Frame Generator #acc_time = int(2.0e4 / inputs.update_frequency)
    events_frame_gen_algo = OnDemandFrameGenerationAlgorithm(sensor_width, sensor_height, inputs.accumulation_time)
    output_img = np.zeros((sensor_height, sensor_width, 3), np.uint8)

    # First set up the figure, the axis, and the plot element we want to animate
    # fig = plt.figure()
    # ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
    # line, = ax.plot([], [], lw=2)
    # line2, = ax.plot([], [], lw=2)

    # # initialization function: plot the background of each frame
    # def initfunc():
    #     line.set_data([], [])
    #     line2.set_data([], [])
    #     return line, line2

    # # animation function.  This is called sequentially
    # def animate(i,x,y):
    #     line.set_data(x, y)
    #     return line

    def tracking_cb(ts, tracking_results):
        """
        Tracking callback that is triggered whenever an object is detected.
        """
        nonlocal output_img
        nonlocal total_results
        nonlocal measurement_index

        events_frame_gen_algo.generate(ts, output_img)
        callback_results = tracking_results.numpy().tolist()  # Gets results as numpy.void type
        if len(callback_results) > 0: # Only stores results if not empty
            total_results.extend(callback_results)

            current_time = callback_results[0][2]
            start_time = inputs.measurement_time*measurement_index
            print(total_results[-1][3])
        # x = total_results[-1][3]
        # y = total_results[-1][4]
        # anim = animation.FuncAnimation(fig, animate, init_func=initfunc, fargs=(x,y,), frames=200, interval=20, blit=True)
    # plt.show()

    # Setting output callback to tracking algorithm (asynchronous)
    tracking_algo.set_output_callback(tracking_cb)

    # Process events
    for evs in mv_iterator:
        # Dispatch system events to the window
        EventLoop.poll_and_dispatch()

        # Process events
        activity_noise_filter.process_events(evs, events_buf)
        trail_filter.process_events_(events_buf)
        events_frame_gen_algo.process_events(events_buf)
        tracking_algo.process_events(events_buf)

if __name__ == "__main__":
        main()


from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Dropout, Flatten, Concatenate, Embedding, Activation
from tensorflow.keras.optimizers import RMSprop, Adam
from tensorflow.keras import regularizers
from tensorflow.keras.callbacks import EarlyStopping

import numpy as np
import pandas as pd

def prepro_nn(df, categorical_col):
    data = []
    numeric_cols = [col for col in df.columns if col not in categorical_col]
    data.append(df[numeric_cols].values)
    for col in categorical_col:
        data.append(np.array(df[col].values).reshape(-1, 1))
    return data

def make_model(df1, df2, categorical_feature):
    all_df = pd.concat([df1, df2])
    numeric_feature_num = int(df1.columns.shape[0]) - len(categorical_feature)
    #numeric_feature_num = int((df.dtypes == float).sum() + (df.dtypes == int).sum())
    #print(numeric_feature_num)
    num_input = Input(numeric_feature_num, )
    inputs = []
    embs = []
    embedding_dim = 6
    for col in categorical_feature:
        value_size = all_df[col].unique().shape[0]
        input_cat = Input(1,)
        emb = Embedding(input_dim=value_size, output_dim=int(np.log2(value_size))+1)(input_cat)
        emb = Flatten()(emb)

        inputs.append(input_cat)
        embs.append(emb)

    concat = Concatenate()([num_input, *embs])

    outputs = Dense(1024)(concat)
    outputs = Activation('relu')(outputs)
    outputs = Dropout(.4)(outputs)

    outputs = Dense(128)(outputs)
    outputs = Activation('relu')(outputs)
    outputs = Dropout(.4)(outputs)

    outputs = Dense(1)(outputs)
    outputs = Activation('sigmoid')(outputs)

    model = Model(inputs=[num_input, *inputs], outputs=[outputs])
    model.compile(optimizer=Adam(lr=0.0001), loss="binary_crossentropy")

    return model

def make_model2(df1, df2, categorical_feature):
    all_df = pd.concat([df1, df2])
    numeric_feature_num = int(df1.columns.shape[0]) - int(len(categorical_feature))
    print(numeric_feature_num)
    print("sss")

    print(1)
    num_input = Input(numeric_feature_num, )
    inputs = []
    embs = []

    for col in categorical_feature:
        value_size = all_df[col].unique().shape[0]
        input_cat = Input(1, )
        emb = Embedding(input_dim=value_size, output_dim=int(np.log2(value_size)) + 1)(input_cat)
        emb = Flatten()(emb)

        inputs.append(input_cat)
        embs.append(emb)

    outputs = Concatenate()([num_input, *embs])
    outputs = Dropout(0.13)(outputs)

    outputs = Dense(2000)(outputs)
    outputs = Activation('relu')(outputs)
    outputs = Dropout(0.7)(outputs)

    outputs = Dense(1200)(outputs)
    outputs = Activation('relu')(outputs)
    outputs = Dropout(.4)(outputs)

    outputs = Dense(40)(outputs)
    outputs = Activation('relu')(outputs)

    outputs = Dense(1)(outputs)
    outputs = (Activation('sigmoid'))(outputs)

    model = Model(inputs=[num_input, *inputs], outputs=[outputs])
    model.compile(optimizer=Adam(lr=0.0001), loss="binary_crossentropy")

    return model

def make_model3(df1, df2):

    inputs = Input(df1.shape[1],)
    outputs = Dense(128)(inputs)
    outputs = Activation('relu')(outputs)

    outputs = Dense(32)(outputs)
    outputs = Activation('relu')(outputs)

    outputs = Dense(1)(outputs)
    outputs = (Activation('sigmoid'))(outputs)

    model = Model(inputs=[inputs], outputs=[outputs])
    model.compile(optimizer=Adam(lr=0.0001), loss="binary_crossentropy")

    return model

def make_model4(df1, df2):

    inputs = Input((df1.shape[1],))
    outputs = Dense(32)(inputs)
    outputs = Activation('relu')(outputs)

    outputs = Dense(1)(outputs)
    outputs = (Activation('sigmoid'))(outputs)

    model = Model(inputs=[inputs], outputs=[outputs])
    model.compile(optimizer=Adam(lr=0.001), loss="binary_crossentropy")

    return model


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 22:17:14 2020

@author: Reuben

This file provides a set of encoders and decoders for some basic
error-correcting schemes (basically a bunch of horrific type conversions
with some computations thrown in).

For a useful crash course on basic code, see here:
https://www.youtube.com/playlist?list=PLJHszsWbB6hqkOyFCQOAlQtfzC1G9sf2_

"""

import numpy as np

import ecc.error_correction_utils as utils

def repetition_encoder(message, num_repetitions):
    """
    Encode the given input using a basic repetition code.

    Parameters
    ----------
    message : str
        A binary vector of 0s and 1s to be encoded.
    num_repetitions : int
        Number of times to repeat each input bit.

    Returns
    -------
    str
        Input vector with each bit repeated 'num_repetitions' times.

    """
    if num_repetitions > len(message):
        raise ValueError('Error: the number of repetitions cannot be greater'
                         ' than the length of the input.')
    for bit in message:
        if bit not in ['0', '1', 'x']:
            raise ValueError("Bit values must be '0', '1', or 'x'.")

    return "".join([num_repetitions * bit for bit in message])

def repetition_decoder(code, num_repetitions):
    """
    Decode the given input assuming a basic repetition code.

    Parameters
    ----------
    code : str
        A binary vector of 0s and 1s to be decoded. The value 'x' can also be
        included for any bits with unknown value.
    num_repetitions : int
        Number of times each bit is repeated in the encoding scheme.

    Returns
    -------
    message : str
        Decoded output vector. The output consists of 0s and 1s
        (and x's in the case that num_repetitions is even, and the value of a
        bit cannot be determined or if an unknown bit ('x') is passed in).

    """
    if num_repetitions > len(code):
        raise ValueError('The number of repetitions cannot be greater'
                         ' than the length of the input.')
    if len(code) % num_repetitions != 0:
        raise ValueError('The length of the input is not an integer multiple'
                         ' of the number of repetitions.')

    message = ''

    # Loop through each chunk of repeated bits (codeword).
    for i in range(0, len(code), num_repetitions):
        bit_sum = 0

        # Sum the bits in the chunk.
        for j in range(num_repetitions):
            # If a bit has an unknown value (represented by 'x'), set
            # the average to 0.5 to signify an unknown chunk and exit loop.
            if code[i+j] == 'x':
                bit_sum = 0.5 * num_repetitions     # Sets average to 0.5
                break
            # If the input is a 0 or a 1, add the value to the sum.
            elif code[i+j] == '0' or code[i+j] == '1':
                bit_sum += int(code[i+j])
            # If the input value is an invalid character, raise an error.
            else:
                raise ValueError("Bit values must be '0', '1', or 'x'.")

        # Calculate the average bit value in the chunk.
        average = bit_sum / num_repetitions

        # Set the value of the chunk.
        message += \
            '1' if average > 0.5 else ('0' if average < 0.5 else 'x')

    return message

def hamming_encoder(message, n=3):
    """
    Encode the given message using a (2**n - 1, 2**n - n - 1) Hamming code.

    See https://en.wikipedia.org/wiki/Hamming_code for more info.

    Parameters
    ----------
    message : str
        A binary vector of 0s and 1s to be encoded.
    n : int, optional
        The number n corresponding to a (2**n - 1, 2**n - n - 1) Hamming code
        (with 2**n - 1 bits per codeword, n parity bits per codeword, and thus
        2**n - n - 1 data bits per codeword). The default is 3.

    Returns
    -------
    code : str
        A binary vector of 0s and 1s representing the encoded message.

    """
    # Number of bits containing information from the message per codeword
    # (the other bits are parity bits used for error-detection/correction).
    num_data_bits = 2**n - n - 1

    if len(message) % num_data_bits != 0:
        raise ValueError('Input length is not divisible by the number of data'
                         ' bits per codeword.')

    code = ''
    generator_matrix = utils.hamming_generator_matrix(n)

    # Loop through each chunk of data bits by index.
    for i in range(0, len(message), num_data_bits):
        # Compute the next codeword by multiplying the data chunk
        # by the generator matrix.
        codeword = utils.multiply_binary_finite_field_matrices(
             np.array([list(message[i:i+num_data_bits])]).astype(np.intc),
             generator_matrix
        )
        # Convert codeword from a column vector to a string and append.
        code += ''.join([str(bit) for bit in np.nditer(codeword)])

    return code

def hamming_decoder(code, n=3):
    """
    Decode the given message, assuming a (2**n - 1, 2**n - n - 1) Hamming code.

    Note that a Hamming code can only detect a single error in each codeword.
    If two bits are flipped in a given codeword, it will appear as though a
    single error has occured at a different location, and the mistake will be
    repaired incorrectly.

    See https://en.wikipedia.org/wiki/Hamming_code for more info.

    Parameters
    ----------
    code : str
        A binary vector of 0s and 1s to be decoded.
    n : int, optional
        The number n corresponding to a (2**n - 1, 2**n - n - 1) Hamming code
        (with 2**n - 1 bits per codeword, n parity bits per codeword, and thus
        2**n - n - 1 data bits per codeword). The default is 3.

    Returns
    -------
    message : str
        A binary vector of 0s and 1s representing the decoded message.

    """
    # The number of data bits and parity bits in each codeword.
    codeword_bits = 2**n - 1

    # The number of data bits per codeword.
    num_data_bits = codeword_bits - n

    if len(code) % codeword_bits != 0:
        raise ValueError('Input length is not divisible by the number of'
                         ' bits per codeword.')

    message = ''

    # Compute the parity check matrix for the assumed encoding.
    parity_check_matrix = utils.hamming_parity_check_matrix(n)

    # Loop through each codeword by index.
    for i in range(0, len(code), codeword_bits):
        # Convert codeword from a string to a column vector of integer bits.
        # I hope there is a better way to do this, because this is gross.
        codeword = np.array([[int(bit) for bit in code[i:i+codeword_bits]]]).T

        # Compute the product of the parity check matrix and the codeword,
        # called the syndome vector, to determine which error occurred, if any.
        syndrome_vector = utils.multiply_binary_finite_field_matrices(
            parity_check_matrix, codeword
        )

        # The new message bits before correction of any errors. The last n
        # bits in the codeword are parity bits, which are ignored.
        data = code[i:i+num_data_bits]

        # If the syndrome vector is nonzero, there is an error.
        if np.any(syndrome_vector):
            # The error is located at the index of the column of the parity
            # check matrix equal to the syndrome vector.
            error_location = int(np.where(
                np.all(parity_check_matrix == syndrome_vector, axis=0)
            )[0])
            # Convert the data bits of the codeword to a integer to make
            # correcting the error easier.
            data_val = int(sum(
                [bit * 2**j for j, bit in enumerate(reversed(
                    codeword[:num_data_bits]))]
            ))

            # If the error is in one of the data bits, correct it. Otherwise,
            # the output is unaffected.
            if error_location < num_data_bits:
                # Flip the erroneous bit (using xor at the appropriate
                # location).
                corrected = str(bin(data_val ^ int(2**(n-error_location)))[2:])

                # Finally, set the final value of the data by extending
                # corrected to the appropriate length.
                data = '0' * (num_data_bits - len(corrected)) + corrected

        # Add the corrected (if applicable) new message bits to the message.
        message += data

    return message

# Code testing region.
if __name__ == '__main__':
    num_tests = 10000

    # Test Hamming (7,4) encoder/decoder.
    for test in range(num_tests):
        message = ''

        # Generate a random 40-bit message, which will yield 10 codewords for
        # a Hamming (7,4) code.
        for bit in range(40):
            message += np.random.choice(['0', '1'])

        # Encode the message.
        code = hamming_encoder(message)

        code_distorted = ''

        # Create a distorted code by randomly flipping one bit in each word.
        for i in range(0, len(code), 7):
            index = np.random.randint(0, 6)
            code_distorted += (
                code[i:i+index]
                + ('0' if code[i+index] == '1' else '1')
                + code[i+index+1:i+7]
            )

        # Decode the code and the distorted code and check that both yield the
        # original message.
        assert hamming_decoder(code) == message \
            and hamming_decoder(code_distorted) == message, \
            'WRONG. YOUR CODE IS WRONG. SAD.'


from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class department(models.Model):
    D_name = models.CharField(max_length=200,primary_key=True)
    HOD = models.CharField(max_length=200)

    def publish(self):
        self.save()

    def _str_(self):
        return self.D_name

class Post(models.Model):
    EnrollmentID = models.CharField(primary_key=True,null=False,max_length=20)
    Name = models.CharField(max_length=200)
    Gender = models.CharField(max_length=200)
    Address = models.TextField()
    Department_id = models.ForeignKey(department,on_delete=models.CASCADE)
    Enrollment_date = models.DateTimeField(
            default=timezone.now)

    def publish(self):
        self.Enrollment_date = timezone.now()
        self.save()

class marks(models.Model):
    EnrollmentID = models.ForeignKey(Post,on_delete=models.CASCADE)
    tmarks = models.FloatField()
    grade = models.CharField(max_length=20)

    def publish(self):
        self.save()

class faculty(models.Model):
    Name = models.CharField(max_length=200,primary_key=True)
    dname = models.ForeignKey(department,on_delete=models.CASCADE)

    def publish(self):
        self.save()

    def _str_(self):
        return self.Name

class Course(models.Model):
    CourseID = models.CharField(max_length=200,primary_key=True,null=False)
    cname = models.CharField(max_length=200)
    Instructor = models.ForeignKey(faculty,on_delete=models.CASCADE)

    def publish(self):
        self.save()

    def __str__(self):
        return self.CourseID

class Subwise_marks(models.Model):
    EnrollmentID = models.ForeignKey(Post,on_delete=models.CASCADE)
    C_ID = models.ForeignKey(Course,on_delete=models.CASCADE)
    Marks = models.FloatField()
    class Meta:
        unique_together = (("EnrollmentID", "C_ID"),)
    def publish(self):
        self.save()


from django import template
from django.utils.html import format_html

register = template.Library()

@register.simple_tag
def image(file, max_size=300):
    from main import settings
    if file:
        title = ''
        return image_link(file, title)
    else:
        return ''

@register.simple_tag
def image_link(file, title='Просмотр', classes=''):
    from main import settings
    from PIL import Image
    import os

    if file:
        width = 1000
        height = 800
        try:
            f = Image.open(os.path.join(settings.MEDIA_ROOT,str(file)))
            width, height = f.size
            ratio = width / height
            if width > 1000:
                width = 1000
                height = width / ratio
            elif height > 800:
                height = 800
                width = height * ratio
        except IOError:
            pass
        html = ''+title+''
        return format_html(html)
    else:
        return ''

@register.simple_tag
def get_label(instance, field_name):
    if instance:
        #try:
        return instance._meta.get_field(field_name).verbose_name
        #except:
        #    return None
    else:
        return None

@register.simple_tag
def month(month):
    if month != '':
        from main.structures import MONTHS
        return MONTHS[int(month)-1][1]
    else:
        return ''

@register.filter
def num(value, precision=2):
    if value:
        return ("{:,."+str(precision)+"f}").format(value).replace(',', ' ').replace('.',',')
    else:
        return ''

@register.filter
def rub(value):
    if value:
        return "{:,.2f}".format(value).replace(',', ' ').replace('.',',')+' руб.'
    else:
        return ''

@register.filter
def boolean(value):
    if value:
        return 'Да'
    else:
        return 'Нет'

@register.filter
def empty(value):
    if value is not None:
        return value
    else:
        return ''

@register.inclusion_tag('main/paginator.html', takes_context=True)
def paginator(context, paginated_list):
    if 'is_mobile' in context:
        return {'list': paginated_list, 'is_mobile': context['is_mobile']}
    else:
        return {'list': paginated_list}

@register.inclusion_tag('form.html', takes_context=True)
def table_form(context, form_var, rows_only=False):
    if 'is_mobile' in context:
        return {'form': form_var, 'rows_only': rows_only, 'is_mobile': context['is_mobile']}
    else:
        return {'form': form_var, 'rows_only': rows_only}

@register.filter
def expire(value, days):
    from datetime import date, timedelta
    if isinstance(value, date):
        if value < date.today():
            return format_html(''+value.strftime('%d.%m.%Y')+'')
        elif value - timedelta(days=days) < date.today():
            return format_html(''+value.strftime('%d.%m.%Y')+'')
        else:
            return value.strftime('%d.%m.%Y')

@register.filter
def spaces(value):
    value_str = str(value)
    strlen = len(value_str)
    if strlen > 0:
        comma_position = value_str.find(',')
        if comma_position > 3:
            for i in range(3, comma_position, 3):
                value_str = value_str[0:comma_position-i]+' '+value_str[comma_position-i:]
        elif comma_position < 0:
            if strlen > 3:
                for i in range(3, strlen, 3):
                    value_str = value_str[0:strlen - i] + ' ' + value_str[strlen - i:]
        return value_str
    else:
        return ''

@register.filter
def sum_vals(array, field_name):
    return sum([getattr(elem, field_name) for elem in array])

@register.filter
def count_vals(array, field_name):
    return sum([1 for elem in array if getattr(elem, field_name)])

@register.filter
def cut_length(value, length=50):
    if len(value) > length:
        return value[:length]+'...'
    else:
        return value


"""
    This code has very low cohesion and very high coupling.

    1. If we change the VehicleRegistry class, we need to change in register_vehicle of Application.
    2. it is hard to add new brand category....
    3. We are calculating the tax in same class....
"""

import random
import string

class VehicleRegistry:
    def vehicle_id(self, length):
        return "".join(random.choices(string.ascii_uppercase, k=length))

    def vehicle_license_plate(self, id):
        return f"{id[:2]}-{''.join(random.choices(string.digits, k=2))}-{''.join(random.choices(string.ascii_uppercase, k=2))}"

class Application:
    def register_vehicle(self, brand):

        registry = VehicleRegistry()

        vehicle_id = registry.vehicle_id(12)

        license_plate = registry.vehicle_license_plate(vehicle_id)

        # compute the catalogue price
        catalogue_price = 0
        if brand == "Tesla Model 3":
            catalogue_price = 60000
        elif brand == "Volkswagen ID3":
            catalogue_price = 35000
        elif brand == "BMW 5":
            catalogue_price = 45000

        # compute the tax percentage (default 5% of the catalogue price, except for electric cars where it is 2%)
        tax_percentage = 0.05
        if brand == "Tesla Model 3" or brand == "Volkswagen ID3":
            tax_percentage = 0.02

        # compute the payable tax
        payable_tax = tax_percentage * catalogue_price

        # print out the vehicle registration information
        print("Registration complete. Vehicle information:")
        print(f"Brand: {brand}")
        print(f"Id: {vehicle_id}")
        print(f"License plate: {license_plate}")
        print(f"Payable tax: {payable_tax}")

car = Application()
car.register_vehicle("BMW 5")


"""

Welcome to Facebook!

This is just a simple shared plaintext pad, with no execution capabilities.

When you know what language you would like to use for your interview,
simply choose it from the dropdown in the top bar.

Enjoy your interview!

Q:Shuffle characters of  a string so that no same characters are together
aaabc => abaca, / acaba

aaabbbccc = > abcabcabc

input_string = 'abccba'
sorted_string = sorted(input_string)
aaabbbccc
abaabbccc
abababccc

aaaaaa --> ''
None, null, 'invalid'

aabb
abab

aabbb
ababb
wrong: bbaba

goal: babab

aabbb
ababbababb
babab

aaabbbccc
abaabbccc
abababcccabababccc
bababcaccbababccc
ababcacbc

aabbb
ababb

aa

aaab
abaa

aaaabc
abacaa

Input: aabbb
babb

nlogn
n
a(average
number
of
duplicates
per
character), worst
case
O(N)

Later: Here's a discussion on Stack Overflow of how to solve this:
https://stackoverflow.com/questions/39171840/
"""

def get_string_sorted_so_there_are_no_two_same_characters_in_a_row(
        input_string):
    if len(input_string) < 2:
        return input_string
    sorted_string = sorted(input_string)
    index_of_current_character_to_check = 1
    index_of_the_last_character = len(input_string) - 1
    while index_of_current_character_to_check <= index_of_the_last_character:
        index_of_the_previous_character = index_of_current_character_to_check - 1
        current_character = sorted_string[index_of_current_character_to_check]
        previous_character = sorted_string[index_of_the_previous_character]
        current_character_matches_previous_character = current_character == previous_character
        if current_character_matches_previous_character:
            # search forward for a different character and insert it into the position of the current character
            index_of_potential_separator_character = index_of_current_character_to_check + 1
            we_have_wrapped_around = False
            while True:
                if index_of_potential_separator_character > index_of_the_last_character:
                    index_of_potential_separator_character = 0
                    we_have_wrapped_around = True
                potential_separator_character = sorted_string[
                    index_of_potential_separator_character]
                if we_have_wrapped_around and potential_separator_character == current_character:
                    raise ValueError("This string cannot be sorted as desired.")
                if potential_separator_character == current_character:
                    pass
                else:
                    if not we_have_wrapped_around:
                        sorted_string.pop(
                            index_of_potential_separator_character)
                        sorted_string.insert(potential_separator_character,
                                             index_of_current_character_to_check)
                    else:
                        sorted_string.insert(potential_separator_character,
                                             index_of_current_character_to_check)
                        sorted_string.pop(
                            index_of_potential_separator_character)
                    break
                index_of_potential_separator_character += 1
        index_of_current_character_to_check += 1


##basic text input quiz
from ipywidgets import widgets, Layout, Box, GridspecLayout

def create_textinputquiz_widget(description, text_description, correct_answer, a2, hint):  ##grid for option table

    correct_answer = correct_answer  ##float ##str
    alternativ = widgets.Text(value='',
                              placeholder='',
                              description='',
                              disabled=False, layout=(Layout(width='auto'))
                              )
    ##question description
    description_out = widgets.Output(layout=Layout(width='auto'))
    with description_out:
        print(description)
    ##description before text widget
    text_description_out = widgets.Output(layout=Layout(width='auto'))
    with text_description_out:
        print(text_description)
    ##description after text widget e.g. units
    a2_out = widgets.Output(layout=Layout(width='auto'))
    with a2_out:
        print(a2)
    ##
    feedback_out = widgets.Output()

    def check_selection(b):
        a = alternativ.value

        if a == correct_answer:
            s = "Correct!"

        else:
            s = "Wrong answer unfortunately"
        with feedback_out:
            feedback_out.clear_output()
            print(s)

        return

    check = widgets.Button(description="check")
    check.on_click(check_selection)
    ##
    hint_out = widgets.Output()

    def hint_selection(b):
        with hint_out:
            print(hint)
        with feedback_out:
            feedback_out.clear_output()
            print(hint)

    hintbutton = widgets.Button(description="hint")
    hintbutton.on_click(hint_selection)

    return widgets.VBox([description_out,
                         widgets.HBox([text_description_out, alternativ, a2_out]),
                         widgets.HBox([hintbutton, check]), feedback_out],
                        layout=Layout(display='flex',
                                      flex_flow='column',
                                      align_items='stretch',
                                      width='auto'))

def quiz():
    questions1 = create_textinputquiz_widget('What is the value of dt if you have 5 minutes timestep data?', "answer:", '1/12', "hour",
                                            '[hint]: Read part 1.1')
    questions2 = create_textinputquiz_widget('Is the timeunit same for all energy units?', "answer:", 'yes', "!",
                                             '[hint]: Read part 1.6')
    questions3 = create_textinputquiz_widget('How many production units we have in this model with energy flow always out?', "answer:", '2', "unit(s)",
                                             '[hint]: Read part 1.3')
    questions4 = create_textinputquiz_widget('How many consumption units we have in this model with energy flow always in?', "answer:", '3',
                                             "unit(s)", '[hint]: Read part 1.3')
    questions5 = create_textinputquiz_widget('Is energy flow of storage always in?', "answer:",
                                             'no', "!",'[hint]: Read part 1.3.1')
    questions6 = create_textinputquiz_widget('How much electricity was exported?', "answer:",
                                             '0', "kWh", '[hint]: Read part 1.5')
    questions7 = create_textinputquiz_widget('At what hour the storage was discharged?', "answer:",
                                             '20', "hour", '[hint]: Read part 1.8')
    questions8 = create_textinputquiz_widget('How much electricity was imported this time? (one decimal)', "answer:",
                                             '4.7', "kWh", '[hint]: Read part 1.8')
    display(questions1)
    display(questions2)
    display(questions3)
    display(questions4)
    display(questions5)
    display(questions6)
    display(questions7)
    display(questions8)

quiz()


from anomalous_vertices_detection.graphs.graph_factory import GraphFactory
from anomalous_vertices_detection.graphs import NxGraph
import os
import unittest

class SimulationTest(unittest.TestCase):
    def setUp(self):
        tests_path = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
        tests_input = os.path.join(tests_path, "input/test1.txt")
        self._graph = NxGraph(False)
        self._graph.load_graph(tests_input, start_line=0)
        self._digraph = NxGraph(True)
        self._digraph.load_graph(tests_input, start_line=0)
        self._factory = GraphFactory()
        self._count = 0

    def test_added_random_vertex(self):
        self._factory.create_random_vertex(self._graph, 2, self._graph.vertices, "Sim", "Sim")
        self._factory.create_random_vertex(self._digraph, 2, self._digraph.vertices, "Sim", "Sim")
        self.assertEqual(self._graph.number_of_vertices, 7)
        self.assertEqual(self._digraph.number_of_vertices, 7)
        self.assertEqual(len(self._graph.edges), 11)
        self.assertEqual(len(self._digraph.edges), 12)

    def test_added_random_vertices(self):
        graph = self._factory.add_random_vertices(self._graph, 3, "Sim")
        digraph = self._factory.add_random_vertices(self._digraph, 3, "Sim")
        self.assertEqual(graph.number_of_vertices, 9)
        self.assertEqual(digraph.number_of_vertices, 9)

    def test_added_correct_labels(self):
        graph = self._factory.add_random_vertices(self._graph, 2, "Sim")
        sim_label_counter = 0
        real_label_counter = 0
        for v in graph.vertices:
            if graph.get_node_label(v) == "Sim":
                sim_label_counter += 1
            else:
                real_label_counter += 1
        self.assertEqual(sim_label_counter, 2)
        self.assertEqual(real_label_counter, 6)

        sim_label_counter = 0
        real_label_counter = 0
        digraph = self._factory.add_random_vertices(self._digraph, 2, "Sim")
        for v in digraph.vertices:
            if digraph.get_node_label(v) == "Sim":
                sim_label_counter += 1
            else:
                real_label_counter += 1
        self.assertEqual(sim_label_counter, 2)
        self.assertEqual(real_label_counter, 6)

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


users_list = []
questions_list = []
meetups_list = []
rsvp_list = []
votes = []

class BaseModels(object):
    """ contains methods common to other models """

    def __init__(self, db):
        self.db = db

    def check_db(self):
        if self.db == 'user':
            db = users_list
            return db
        elif self.db == 'questions':
            db = questions_list
            return db
        elif self.db == 'meetups':
            db = meetups_list
            return db

        elif self.db == 'rsvp':
            db = rsvp_list
            return db

    def search_db(self, key, item):
        db = self.check_db()
        data = [record for record in db if record[key] == item]
        if data:
            return data[0]
        else:
            return False

    def search_meetup(self, key, item):
        data = [record for record in meetups_list if record[key] == item]
        if data:
            return data[0]
        else:
            return False

    def return_rsvp(self, key, item):
        rsvp = [record for record in rsvp_list if record[key] == item]
        rsvp.append(rsvp)

    def save_data(self, payload):
        db = self.check_db()
        db.append(payload)

        return db

    def meetup_question(self, meetupId):
        if len(questions_list) == 0:
            return False

        for question in questions_list:
            qlist = []
            if question['meetup_id'] == meetupId:
                qlist.append(question)

            return qlist

    def count_rsvp(self, meetupId):
        count = 0
        for data in rsvp_list:
            if data["meetup_id"] == meetupId and data["response"] == 'yes':
                count += 1

        return count


class queue():
    st = []
    st2 = []

    def __init__(self, input):
        for item in input:
            self.st.append(item)
        while self.st:
            self.st2.append(self.st.pop())

    def enqueue(self, num):
        self.st.append(num)
        while self.st2:
            self.st.append(self.st2.pop())
        while self.st:
            self.st2.append(self.st.pop())

    def dequeue(self):
        if self.st2:
            return self.st2.pop()
        else:
            return 'Empty'


# -*- coding: utf-8 -*-
from Nucleo.mainWindowGUI import *
from Nucleo.embeddedimageGUI import *
from Nucleo.RouteTable import *
from Nucleo.Graph import *
from PyQt5 import uic

class EnbeddedImageWindow(QtWidgets.QMainWindow,Ui_ImageWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)
        self.center()

    # Este metodo centra la ventana
    def center(self):
        frame = self.frameGeometry()
        centerPoint = QtWidgets.QDesktopWidget().availableGeometry().center()
        frame.moveCenter(centerPoint)
        self.move(frame.topLeft())

class RouteTable(QtWidgets.QMainWindow,Ui_Form):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)
        self.setWindowTitle("Route Table")
        self.setMaximumSize(16777215,16777215)
        self.setMinimumSize(16777215,16777215)

class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)
        self.center()
        self.makeGraphButton.clicked.connect(self.buildGraph)
        self.openFileButton.clicked.connect(self.openAFile)
        self.windowImage = EnbeddedImageWindow()
        self.makeTableButton.clicked.connect( self.buildTable)
        self.Form = RouteTable()

    # Este metodo centra la ventana

    def center(self):
        frame = self.frameGeometry()
        centerPoint = QtWidgets.QDesktopWidget().availableGeometry().center()
        frame.moveCenter(centerPoint)
        self.move(frame.topLeft())

    def openAFile(self):
        explorer = QtWidgets.QFileDialog()
        currentDir = explorer.directory().canonicalPath()
        name, typefilter = explorer.getOpenFileName(None, "Open File", currentDir, "Text (*.txt)")
        if name:
            file = open(name)
            content = file.read()
            file.close()
            self.editor.setText(content)

    def buildGraph(self):
        graph = Graph()
        graph.buildGraph(self.editor.toPlainText())
        graph.makeGraph()
        self.showGraph()

    def showGraph(self):
        self.windowImage.setStyleSheet("background-image: url(%s)" % "graph.png")
        self.windowImage.show()

    def showTable(self,content):
        self.Form.textEdit.setText(content)
        self.Form.show()

    def getRouteInTerminal(self):
        graph = Graph()
        graph.buildGraph(self.editor.toPlainText())
        x = self.initialServer.text()
        y = self.finalServer.text()
        if(x != "" and y != ""):
            roads = graph.getRoads(x,y)
            if(roads):
                s = graph.getWeigthOfRoads(roads)
                for k,v in s.items():
                    print("Ruta: %s, Peso: %s" % (roads[k],v))
                print("-"*50)

    def buildTable(self):
        content = []
        graph = Graph()
        graph.buildGraph(self.editor.toPlainText())
        x = self.initialServer.text()
        y = self.finalServer.text()
        roads = graph.getRoads(x,y)
        if roads:
            roadWeigth = graph.getWeigthOfRoads(roads)

            invertedRoadWeigth = dict((v, k) for k, v in roadWeigth.items())

            sortedWeigths = list(invertedRoadWeigth.keys())
            sortedWeigths.sort()

            content.append("-"*80)
            content.append("\tTabla de rutas de %s a %s" %(x,y))
            content.append("-"*80)
            content.append("\tPeso\t|\tRuta")
            for i in sortedWeigths:
                content.append("-" * 80)
                content.append("\t%s\t|\t%s" % (i,roads[invertedRoadWeigth[i]]))

            self.showTable("\n".join(content))

if __name__=="__main__":
    apt = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    apt.exec_()


import sys

def get_fasta_records(lines):
    dna_strings = []
    is_first_dna = True
    id, dna = '', ''
    for line in lines:
        line = line.strip();
        if line[0] == '>':
            if is_first_dna:
                is_first_dna = False
            else:
                dna_strings.append([id, dna])
            id, dna = line[1:], ''
        else:
            dna += line
    dna_strings.append([id, dna])
    return dna_strings

def kmp_failure_array(s):
    m, i, j = len(s), 1, 0
    p = [0] * m
    while i < m:
        if s[j] == s[i]:
            p[i] = j + 1
            i, j = i+1, j+1
        elif j != 0:
            j = p[j-1]
        else:
            i += 1
    return p

def main():
    fasta_records = get_fasta_records(sys.stdin.readlines())
    dna = fasta_records[0][1]
    print(' '.join(list(map(str, kmp_failure_array(dna)))))

if __name__ == '__main__':
    sys.exit(main())


from typing import List, Dict
import json

from geonoderest.geonodetypes import GeonodeCmdOutObjectKey, GeonodeCmdOutListKey
from geonoderest.rest import GeonodeRest
from geonoderest.cmdprint import print_list_on_cmd, print_json

class GeonodeObjectHandler(GeonodeRest):
    LIST_CMDOUT_HEADER: List[GeonodeCmdOutObjectKey] = [
        GeonodeCmdOutListKey(type=list, key="pk")
    ]
    GET_CMDOUT_PROPERTIES: List[GeonodeCmdOutObjectKey] = [
        GeonodeCmdOutListKey(type=list, key="pk")
    ]
    DEFAULT_UPLOAD_KEYS: List[str] = ["key", "value"]
    JSON_OBJECT_NAME: str = ""
    ENDPOINT_NAME: str = ""
    SINGULAR_RESOURCE_NAME: str = ""

    def cmd_list(self, **kwargs):
        """show list of geonode obj on the cmdline"""
        obj = self.list(**kwargs)
        if kwargs["json"]:
            print_json(obj)
        else:
            print_list_on_cmd(obj, self.LIST_CMDOUT_HEADER)

    def list(self, **kwargs) -> Dict:
        """returns dict of datasets from geonode

        Returns:
            Dict: request response
        """
        r = self.http_get(
            endpoint=f"{self.ENDPOINT_NAME}/?page_size={kwargs['page_size']}"
        )
        return r[self.JSON_OBJECT_NAME]

    def cmd_delete(self, pk: int, **kwargs):
        self.delete(pk=pk, **kwargs)
        print(f"{self.JSON_OBJECT_NAME}: {pk} deleted ...")

    def delete(self, pk: int, **kwargs):
        """delete geonode resource object"""
        self.http_get(endpoint=f"{self.ENDPOINT_NAME}/{pk}")
        self.http_delete(endpoint=f"resources/{pk}/delete")

    def cmd_patch(self, pk: int, fields: str, **kwargs):
        obj = self.patch(pk, fields, **kwargs)
        print_json(obj)

    def patch(self, pk: int, fields: str, **kwargs) -> Dict:
        """tries to generate  object from incoming json string

        Args:
            pk (int): pk of the object
            fields (str): string of potential json object

        Returns:
            Dict: obj details

        Raises:
             ValueError: catches json.decoder.JSONDecodeError and raises ValueError as decoding is not working
        """
        try:
            json_data = json.loads(fields)
        except ValueError:
            raise (
                ValueError(
                    f"unable to decode argument: | {fields} | to json object ..."
                )
            )

        return self.http_patch(endpoint=f"{self.ENDPOINT_NAME}/{pk}/", params=json_data)

    def cmd_describe(self, pk: int, **kwargs):
        obj = self.get(pk=pk, **kwargs)
        print_json(obj)

    def get(self, pk: int, **kwargs) -> Dict:
        """get details for a given pk

        Args:
            pk (int): pk of the object

        Returns:
            Dict: obj details
        """
        r = self.http_get(
            endpoint=f"{self.ENDPOINT_NAME}/{pk}?page_size={kwargs['page_size']}"
        )
        return r[self.SINGULAR_RESOURCE_NAME]


#!/usr/bin/python

from atilgan.brooker import factory
from atilgan.utils import timeit

import pandas as pd

@timeit.timeit
def run():
    symbol_name = 'ETHUSDT'
    binance_brooker = factory.create_brooker('user_api_keys.json', factory.BINANCE)
    eth_price = binance_brooker.get_historical_price(symbol_name, 60, "2020/01/01")
    eth_price = eth_price.tz_convert('UTC')  # https://github.com/pandas-dev/pandas/issues/25423
    eth_price.to_parquet(f'data/{symbol_name}.parquet', compression='GZIP', engine='fastparquet')

    load_from_pq = pd.read_parquet(f'data/{symbol_name}.parquet', engine='fastparquet')
    print(load_from_pq.head())
    print(load_from_pq.tail())


from programs.graphs import basic_graph, adjacency_matrix, dijkstra, reader_graph
from files.graph import graph

graphReaded = reader_graph.readerGraph(graph.configGraph)
print(len(graphReaded))
#Creacion del grafo
g = basic_graph.Graph()

#Asignacion de verticies
for i in range(len(graphReaded)):
    for j in range(len(graphReaded[i])):
        if graphReaded[i][j] != '0' and graphReaded[i][j] != 0:
            print(graphReaded[i][j])
            if graph.configGraph['nameNodes'] != None:
                g.addEdge(graph.configGraph['nameNodes'][i], graph.configGraph['nameNodes'][j], graphReaded[i][j])
            else:
                g.addEdge('n'+str(i), 'n'+str(j), graphReaded[i][j])

#Vista del grafo

adjacencyGraph = g.getAdjacencyGraph()  #Matriz de adyacencia

print('lista de adyacencia:', adjacencyGraph)

print('Conecciones')
for v in g:
    for w in v.getConnections():
        print("( %s , %s )" % (v.getId(), w.getId()))

g.drawGraph()

# dijkstra
dist, pred = dijkstra.dijkstra(adjacencyGraph, graph.configGraph['dijkstra'][0])
print('distancia: ',dist)
print('Predecesor: ', pred)
p1, p2 = dijkstra.shortest_path(adjacencyGraph, graph.configGraph['dijkstra'][0], graph.configGraph['dijkstra'][1])
print('Nodos dijkstra: ', p1)
print('Camino dijkstra: ', p2)
dijkstra.make_graph(adjacencyGraph, p2)


class tree():
    def __init__(self, kind, age, hight):
        self.default_kind = oak
        self.default_age = 10
        self.default_hight = 2
    def grown(self, age, hight):
        print("Kind: ", self.kind)
        print("Age: ", self.age)
        print("Hight: ", self.hight)
        self.age += 1
        self.hight += 1
class fruit_tree(tree):
    def fruit(self, fruit):
        self.fruit = input("Is it fruit tree? y/n?:")
        if fruit == "y":
            print("This is the fruit tree")
        else:
            print("The tree has no fruit")
    try:
        input("Is it fruit tree? y/n?:")
    except:
        print("ОШИБКА 0000")


import datetime as dt
import time

import matplotlib; matplotlib.use("TKAgg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation

import serial

import threading

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

def openSerial():
    global xs, y1s, y2s
    xs = []
    y1s = []
    y2s = []
    ser = serial.Serial()
    ser.port = 'COM6'
    ser.baudrate = 9600
    time.sleep(2)
    ser.open()
    while True:
        pressure1 = int(ser.readline())
        pressure2 = int(ser.readline())
        # Add x and y to lists
        xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
        y1s.append(pressure1)
        y2s.append(pressure2)
        # Limit x and y lists to 20 items
        xs = xs[-20:]
        y1s = y1s[-20:]
        y2s = y2s[-20:]
        print("Time: " + xs[-1])
        print("Back: " + str(y1s[-1]))
        print("Front: " + str(y2s[-1]))

def animate(i):
    # Draw x and y lists
    ax.clear()
    ax.plot(xs, y1s)
    ax.plot(xs, y2s)

    # Format plot
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.title('Pressure applied (Front vs. Back)')
    plt.ylabel('Pressure (N)')

# Set up plot to call animate() function periodically
t = threading.Thread(target=openSerial, daemon=True)
t.start()
time.sleep(2)
ani = animation.FuncAnimation(fig, animate, interval=10)
plt.show()


import matplotlib.pyplot as plt
import numpy as np
import causet as cs

#the output of causal diamond generating function

d = 2
c, t, x = cs.causDiam(1000, d)

r=np.linalg.norm(x, axis=0) * 1./(1-np.absolute(t))

#counting the number of points along the radial-axis
count = np.zeros((2,1000))
for i in range(1000):
    count[0, i] = i+1

r.sort()
r = r.reshape((1000,))
count[1,:] = r

#the predicted number of points with time (in a causal diamond with spherical diameter)
predNum = 1000*r**(d-1.)

plt.plot(count[1], count[0], 'b-', r, predNum, 'r-')

plt.xlabel('x')
plt.ylabel('t')
plt.title('Number of points, and number of predicted points with time')
#plt.savefig("test.png")
plt.show()


from collections import deque

from tree.Invert_Binary_Tree import TreeNode

"""approach:
1. traverse binary tree until we find the split of two given nodes. t => O(log n)
1.1 when ever the split occur that's our least common ancestor

edge case:
1. what if node node itself one of the given two nodes
    => then node node must be LCA
"""

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        while root:
            if p.val < root.val and q.val < root.val:
                root = root.left
            elif p.val > root.val and q.val > root.val:
                root = root.right
            else:
                return root.val

    def bfs(self, root):
        if not root:
            return []
        node_values = []
        total_sum = 0
        queue = deque()
        queue.append(root)
        while queue:
            node = queue.popleft()
            node_values.append(node.val)
            total_sum += node.val

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return node_values

def create_tree():
    tree = TreeNode(6)
    tree.left = TreeNode(2)
    tree.right = TreeNode(10)
    tree.left.left = TreeNode(0)
    tree.left.right = TreeNode(4)
    tree.left.right.left = TreeNode(3)
    tree.left.right.right = TreeNode(5)
    tree.right.left = TreeNode(7)
    tree.right.right = TreeNode(11)
    tree.right.left.right = TreeNode(8)
    return tree

if __name__ == '__main__':
    # Tree:
    #       6
    #    /     \
    #   2       10
    #  / \     /  \
    # 0   4   7    11
    #    / \   \
    #   3   5    8
    _tree = create_tree()

    solution = Solution()
    print(solution.lowestCommonAncestor(_tree, _tree.right.left, _tree.right.right))


import src.database as db

database_path = ""

# function to connect to the database

def init_db(database):
    global database_path
    database_path = database

# ----- Metodo get de todo los cursos ---
def get_cursos():
    con = db.conexionBBDD()
    print("Conexión establecida")

    cursor = con.cursor()
    print("Cursor creado")

    cursor.execute("SELECT * FROM cursos")
    print("Consulta ejecutada")

    cursos = cursor.fetchall()

    lista_cursos = []

    for curso in cursos:
        curso = {
            "id": curso[0],
            "created_at": curso[1],
            "titulo": curso[2],
            "descripcion": curso[3],
            "contenido": curso[4]
        }
        lista_cursos.append(curso)

    print(cursos)
    con.commit()
    con.close()
    print("Conexión cerrada")
    return lista_cursos

# ---consulta a la BBDD que junte dos tablas y que nos de el titulo de la curso y id y el titulo de  lecciones y el id de lecciones-------------------------

def get_listado(id):
    con = db.conexionBBDD()
    print("Conexión establecida")

    cursor = con.cursor()
    print("Cursor creado")

    cursor.execute(
        "SELECT cursos.titulo as titulo, lecciones.titulo  as listado, cursos.idcursos as idcursos, lecciones.idlecciones as idlecciones FROM cursos INNER JOIN lecciones ON cursos.idcursos = lecciones.idcursos WHERE lecciones.idcursos = %s", (id,))
    print("Consulta ejecutada")

    indices = cursor.fetchall()

    listado = []
    for indice in indices:

        indice = {"titulo": indice[0],
                  "listado": indice[1],
                  "idcursos": indice[2],
                  "idlecciones": indice[3]}
        listado.append(indice)
    con.commit()
    con.close()
    print("Conexión cerrada")
    return listado

# --conseguir cada leccion

def get_leccion(idleccion):
    con = db.conexionBBDD()
    print("Conexión establecida")

    cursor = con.cursor()
    print("Cursor creado")

    cursor.execute(
        "SELECT * FROM lecciones WHERE idlecciones = %s", (idleccion,))
    print("Consulta ejecutada")

    leccion = cursor.fetchone()

    leccion_individual = {
        "idleccion": leccion[0],
        "created_at": leccion[1],
        "idcursos": leccion[2],
        "titulo": leccion[3],
        "contenido": leccion[4]
    }

    con.commit()
    con.close()
    print("Conexión cerrada")
    return leccion_individual


"""
    array simulation

    Time    O(~N^2)
    Space   O(N)
"""

class Solution:
    def circularGameLosers(self, n: int, k: int) -> List[int]:
        received = n * [False]
        cur = 1
        i = 1
        while received[cur-1] == False:
            received[cur-1] = True
            cur = (cur + i*k) % n
            i += 1
        res = []
        for i in range(n):
            if received[i] == False:
                res.append(i+1)
        return res


# External imports
from uuid import uuid4
from sqlalchemy.orm import Session
from sqlalchemy import func
from datetime import timedelta, datetime
# Helper imports
from core_layer.connection_handler import get_db_session
from core_layer import helper
# Model imports
from core_layer.model.submission_model import Submission

def create_submission_db(submission, is_test, session):
    """Inserts a new submission into the database

    Parameters
    ----------
    submission: Submission, required
        The submission to be inserted

    Returns
    ------
    submission: Submission
        The inserted submission
    """
    session = get_db_session(is_test, session)

    submission.id = str(uuid4())
    submission.submission_date = helper.get_date_time_now(is_test)

    session.add(submission)
    session.commit()

    return submission

def get_submissions_by_item_id(item_id, is_test, session):

    session = get_db_session(is_test, session)
    submissions = session.query(Submission).filter(
        Submission.item_id == item_id).all()
    return submissions

def confirm_submission(submission_id, is_test, session):

    session = get_db_session(is_test, session)
    submission = session.query(Submission).filter(
        Submission.id == submission_id).one()
    submission.status = 'confirmed'
    session.merge(submission)
    session.commit()
    return submission

def anonymize_unconfirmed_submissions(is_test, session):

    session = get_db_session(is_test, session)
    two_days_ago = helper.get_date_time(
        datetime.now() - timedelta(days=2), is_test)
    submissions = session.query(Submission).filter(
        Submission.status == 'unconfirmed', Submission.submission_date < two_days_ago).all()
    counter = 0
    for submission in submissions:
        submission.mail = None
        session.merge(submission)
        counter += 1

    session.commit()
    return counter


from nltk.tokenize import word_tokenize
from sacrebleu.metrics import BLEU, CHRF, TER
from bert_score import score
import os
from models import config
import csv
from rouge import Rouge
import numpy as np

def calc_distinct_n(n, candidates, print_score: bool = True):
    dict = {}
    total = 0
    candidates = [word_tokenize(candidate) for candidate in candidates]
    for sentence in candidates:
        for i in range(len(sentence) - n + 1):
            ney = tuple(sentence[i : i + n])
            dict[ney] = 1
            total += 1
    score = len(dict) / (total + 1e-16)

    if print_score:
        print(f"***** Distinct-{n}: {score*100} *****")

    return score

def calc_distinct(candidates, print_score: bool = True):
    scores = []
    for i in range(2):
        score = calc_distinct_n(i + 1, candidates, print_score)
        scores.append(score)

    return scores

def read_file(file_name, dec_type="Greedy"):
    f = open(f"./results/{file_name}.txt", "r", encoding="utf-8")

    refs = []
    cands = []
    dec_str = f"{dec_type}:"

    for i, line in enumerate(f.readlines()):
        if i == 1:
            _, ppl, _, acc = line.strip("EVAL	Loss	PPL	Accuracy").split()
            print(f"PPL: {ppl}\tAccuracy: {float(acc)*100}%")
        if line.startswith(dec_str):
            exp = line.strip(dec_str).strip("\n")
            cands.append(exp)
        if line.startswith("Ref:"):
            ref = line.strip("Ref:").strip("\n")
            refs.append(ref)

    return refs, cands, float(ppl), float(acc)

if __name__ == "__main__":
    if not os.path.exists(config.report_path):
        os.makedirs(config.report_path)
    files = [
        'emotion_flow',
        'more_emotion',
    ]

    with open(config.report_path + "/Report_Greedy1.csv", "w", newline='') as reportFile:
        fp_write = csv.writer(reportFile)
        fp_write.writerow(
            ['Model', 'PPL', 'Distinct-1', 'Distinct-2', 'Accuracy', 'Bleu', 'Rouge-l', 'P-Bert', 'R-Bert', 'F-Bert', 'CHRF'])
        for f in files:
            print(f"Evaluating {f}")
            refs, cands, p, a = read_file(f, dec_type="Greedy")

            dist_1, dist_2 = calc_distinct(cands)

            bleu = BLEU().corpus_score(cands, [refs])
            print(f"***** BLEU: {bleu.score} *****")

            scores = Rouge().get_scores(cands, refs)
            print(f"***** Rouge-f : {np.mean([score['rouge-l']['f'] for score in scores]) * 100} *****")

            P_Bert, R_Bert, F_Bert = score(cands, refs, lang="en", rescale_with_baseline=True)
            print(f"***** Bert_P: {P_Bert.mean() * 100} *****")
            print(f"***** Bert_R: {R_Bert.mean() * 100} *****")
            print(f"***** Bert_F: {F_Bert.mean() * 100} *****")

            chrf = CHRF().corpus_score(cands, [refs])
            print(f"***** CHRF: {chrf.score} *****")

            result = ['#' + str(f),
                      round(p, 4),
                      round(dist_1 * 100, 4) , round(dist_2 * 100, 4),
                      round(a, 4),
                      round(bleu.score, 4),
                      round(np.mean([score['rouge-l']['f'] for score in scores]) * 100, 4),
                      round(float(P_Bert.mean())* 100, 4), round(float(R_Bert.mean()) * 100, 4), round(float(F_Bert.mean()) * 100, 4),
                      round(chrf.score, 4)]
            fp_write.writerow(result)

    # with open(config.report_path + "/Report_Beam.csv", "w", newline='') as reportFile:
    #     fp_write = csv.writer(reportFile)
    #     fp_write.writerow(
    #         ['Model', 'PPL', 'Distinct-1', 'Distinct-2', 'Accuracy', 'Bleu', 'P-Bert', 'R-Bert', 'F-Bert', 'CHRF', 'TER'])
    #     for f in files:
    #         print(f"Evaluating {f}")
    #         refs, cands, p, a = read_file(f, dec_type="Beam")
    #
    #         dist_1, dist_2 = calc_distinct(cands)
    #
    #         bleu = BLEU().corpus_score(cands, [refs])
    #
    #         print(f"***** BLEU: {bleu.score} *****")
    #
    #         P_Bert, R_Bert, F_Bert = score(cands, refs, lang="en", rescale_with_baseline=True)
    #         print(f"***** Bert_P: {P_Bert.mean() * 100} *****")
    #         print(f"***** Bert_R: {R_Bert.mean() * 100} *****")
    #         print(f"***** Bert_F: {F_Bert.mean() * 100} *****")
    #
    #         chrf = CHRF().corpus_score(cands, [refs])
    #         print(f"***** CHRF: {chrf.score} *****")
    #
    #         ter = TER().corpus_score(cands, [refs])
    #         print(f"***** TER: {ter.score} *****")
    #
    #         result = [f,
    #                   round(p, 4),
    #                   round(dist_1 * 100, 4), round(dist_2 * 100, 4),
    #                   round(a, 4),
    #                   round(bleu.score, 4),
    #                   round(float(P_Bert.mean()) * 100, 4), round(float(R_Bert.mean()) * 100, 4),
    #                   round(float(F_Bert.mean()) * 100, 4),
    #                   round(chrf.score, 4),
    #                   round(ter.score, 4)]
    #         fp_write.writerow(result)


from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class StickDeflectionWidget(QWidget):

    def __init__(self, title: str, x_val: int, y_val: int):
        super(StickDeflectionWidget, self).__init__()

        layout = QVBoxLayout(self)

        self.label = QLabel()
        self.x_coordinate = x_val
        self.y_coordinate = y_val

        canvas = QPixmap(150, 150)
        canvas.fill( QColor("white") )
        self.label.setPixmap(canvas)

        self.draw_widget()

        layout.addWidget( QLabel(title) )
        layout.addWidget(self.label)

    def draw_widget(self):
        painter = QPainter(self.label.pixmap())
        pen = QPen()

        pen.setWidth(10)
        pen.setColor(QColor("red"))

        painter.setPen(pen)
        painter.drawPoint(self.x_coordinate, self.y_coordinate)
        painter.end()


'''
-Medium-
*BFS*

You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.

You are given two arrays redEdges and blueEdges where:

redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and
blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.
Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.

Example 1:

Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]
Example 2:

Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
Output: [0,1,-1]

Constraints:

1 <= n <= 100
0 <= redEdges.length, blueEdges.length <= 400
redEdges[i].length == blueEdges[j].length == 2
0 <= ai, bi, uj, vj < n

'''

from typing import List
from collections import defaultdict, deque

class Solution:
    def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
        graph = defaultdict(list)
        for u,v in redEdges:
            graph[u].append((v, 1))
        for u,v in blueEdges:
            graph[u].append((v, -1))
        res = [-1]*n
        que = deque([(0, 0, 0)])
        visited = {(0,-1), (0, 1)}
        while que:
            u, col, d = que.popleft()
            if res[u] == -1:
                res[u] = d
            for v,c in graph[u]:
                if col > -1 and c == -1 and (v, -1) not in visited:
                    visited.add((v, -1))
                    que.append((v, -1, d+1))
                if col < 1 and c == 1 and (v, 1) not in visited:
                    visited.add((v, 1))
                    que.append((v, 1, d+1))
        return res

if __name__ == "__main__":
    n = 5
    red = [[0,1],[1,2],[2,3],[3,4]]
    blue = [[1,2],[2,3],[3,1]]
    print(Solution().shortestAlternatingPaths(n, red, blue))


from flask import  request, jsonify
from flask.views import MethodView
from app.endereco.model import Enderecos
from app.extensions import db
from app.endereco.auxiliar import testar_entradas_endereco

class EnderecoDetails(MethodView):      # /enderecos
    def get(self):
        enderecos = Enderecos.query.all()
        return jsonify([endereco.json() for endereco in enderecos]),200

    def post(self):
        dados = request.json
        cep = dados.get('cep')
        logadouro = dados.get('logadouro')
        numero = dados.get('numero')
        complemento = dados.get('complemento')
        bairro = dados.get('bairro')
        cidade = dados.get('cidade')
        estado = dados.get('estado')
        usuario_id = dados.get("usuario_id")

        error = testar_entradas_endereco(cep,logadouro,numero,complemento,bairro,cidade,estado,usuario_id)
        if (error != False):
            return error

        endereco = Enderecos(cep = cep, logadouro = logadouro, numero = numero, complemento = complemento,
                             bairro = bairro, cidade = cidade, estado = estado, usuario_id = usuario_id)

        db.session.add(endereco)
        db.session.commit()

        return endereco.json() , 200

class PaginaEnderecos(MethodView):      # /enderecos/<int:id>
    def get(self,id):
        endereco = Enderecos.query.get_or_404(id)
        return endereco.json(),200

    def put(self,id):
        endereco = Enderecos.query.get_or_404(id)
        dados = request.json
        cep = dados.get('cep')
        logadouro = dados.get('logadouro')
        numero = dados.get('numero')
        complemento = dados.get('complemento')
        bairro = dados.get('bairro')
        cidade = dados.get('cidade')
        estado = dados.get('estado')
        usuario_id = dados.get("usuario_id")

        error = testar_entradas_endereco(cep,logadouro,numero,complemento,bairro,cidade,estado,usuario_id)
        if (error != False):
            return error

        endereco.cep = cep
        endereco.logadouro = logadouro
        endereco.numero = numero
        endereco.complemento = complemento
        endereco.bairro = bairro
        endereco.cidade = cidade
        endereco.estado = estado
        endereco.usuario_id = usuario_id

        db.session.commit()
        return endereco.json() , 200

    def patch(self,id):
        endereco = Enderecos.query.get_or_404(id)
        dados = request.json
        cep = dados.get('cep', endereco.cep)
        logadouro = dados.get('logadouro', endereco.logadouro)
        numero = dados.get('numero',endereco.numero)
        complemento = dados.get('complemento',endereco.complemento)
        bairro = dados.get('bairro',endereco.bairro)
        cidade = dados.get('cidade',endereco.cidade)
        estado = dados.get('estado',endereco.estado)
        usuario_id = dados.get("usuario_id",endereco.usuario_id)

        error = testar_entradas_endereco(cep,logadouro,numero,complemento,bairro,cidade,estado,usuario_id)
        if (error != False):
            return error

        endereco.cep = cep
        endereco.logadouro = logadouro
        endereco.numero = numero
        endereco.complemento = complemento
        endereco.bairro = bairro
        endereco.cidade = cidade
        endereco.estado = estado
        endereco.usuario_id = usuario_id

        db.session.commit()
        return endereco.json() , 200

    def delete(self,id):
        endereco = Enderecos.query.get_or_404(id)
        db.session.delete(endereco)
        db.session.commit()
        return endereco.json(), 200


from __future__ import absolute_import, print_function

import docopt
import io
import math
import os
import string
import sys

from resultformat import result_file

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

def resultprint(document, limit=None):
    output = StringIO()
    doc = result_file.parse(document)
    output.write("\n")
    output.write("\n".join(map(str, doc[:limit])))
    output.write("\n")
    return output.getvalue()

def round_decimals(n, decimals=0):
    factor = 10 ** decimals
    return math.floor(n*factor + 0.5) / factor

def resultcsv(document, limit=None):
    output = StringIO()
    doc = result_file.parse(document)
    output.write("Elapsed Time (s);Distance (km);Phys. kJoule;Slope (%);NM;RPM;Speed (km/h);Watt;Gear;Device Active;Pulse;Pulse Type;Training Type;Training Value;Pulse Time 1;2;3;4;5;6\n")
    for record in doc[:limit]:
        output.write('{0};'.format(record.elapsed_time))
        output.write('{0:.3f};'.format(round_decimals(record.distance / 1000, 3)))
        output.write('{0:.1f};'.format(round_decimals(record.energy,1)))
        output.write('{0:.1f};'.format(round_decimals(record.slope * 0.1, 1)))
        output.write('{0:.1f};'.format(round_decimals(record.torque * 0.1, 1)))
        output.write('{0:.1f};'.format(round_decimals(record.rpm * 0.1, 1)))
        output.write('{0:.1f};'.format(round_decimals(record.speed * 0.1, 1)))
        output.write('{0};'.format(record.power))
        output.write('{0};'.format(record.gear))
        output.write('{0};'.format(record.device_active))
        output.write('{0};'.format(record.pulse))
        output.write('{0};'.format(record.pulse_type))
        output.write('{0};'.format(record.training_type))
        output.write('{0:.1f};'.format(round_decimals(record.training_value,1)))
        output.write('{0};'.format(record.pulse_time_1))
        output.write('{0};'.format(record.pulse_time_2))
        output.write('{0};'.format(record.pulse_time_3))
        output.write('{0};'.format(record.pulse_time_4))
        output.write('{0};'.format(record.pulse_time_5))
        output.write('{0}'.format(record.pulse_time_6))
        output.write("\n")
    return output.getvalue()

def main(argv=None):
    if (sys.version_info < (3,0)):
        reload(sys)
        sys.setdefaultencoding('utf-8')

    if (argv == None):
        argv = sys.argv[1:]

    try:
        args = docopt.docopt(__doc__, argv=argv, version='resultread ' + '1.0')

        limit = None
        if args['--limit']:
            limit = int(args['--limit'])

        if args['--input']:
            with io.open(args['--input'], 'rb') as f:
                if args['--raw']:
                    text = resultprint(f.read(), limit)
                else:
                    text = resultcsv(f.read(), limit)
        else:
            with sys.stdin as f:
                if args['--raw']:
                    text = resultprint(f.read(), limit)
                else:
                    text = resultcsv(f.read(), limit)

        if args['--output']:
            with io.open(args['--output'], 'wb') as outfile:
                outfile.write(text.encode('utf-8'))
        else:
            sys.stdout.write(text)

        return 0

    except KeyboardInterrupt:
        print(" Interrupted.", file=sys.stderr)

    except IOError as error:
        print("error: IOError {0}".format(error, file=sys.stderr))

    return 1

if __name__ == "__main__":
    sys.exit(main())


PAYMENT_MODE = {
        'cash': 'Cash',
        'bank': 'Bank',
        'cps': 'CPS'
    }

PAYMENT_TYPE = {
        'advance': 'Advance',
        'balance': 'Balance',
        'fuel': 'Fuel',
        'on_delivery':'On Delivery',
        'write_off': 'Write Off'
    }

CHART_OF_ACCOUNT = {
    "bank": 'ICICI -',
    "cash": 'Cash -',
    "creditors": 'Creditors -',
    "debtors": "Debtors -",
    "current_advance":"Current - Advance -",
    "revenue": {
      "sales": 'Sales -',
    },
    "expense": {
      "tds": "TDS -",
      "write_off": "Write Off -",
      "cost_of_goods_sold": "Cost of Goods Sold -",
      "administrative_expense": "Administrative Expenses -"
    }
  }

JE_DEFAULT = {
    "docstatus": '1',
    "doctype": "Journal Entry",
    "voucher_type": "Journal Entry"
  }

PAYMENT_STATUS = {
  'requested': 'Requested',
  'approved': 'Approved',
  'processed': 'Processed',
  'cancelled': 'Cancelled'
}


from functools import partial
import gym
from typing import Dict, List, Type

from asrel.core.utils import get_class_from_module_path
from asrel.environments.base import BaseEnvironment

class GymEnvironment(gym.Wrapper, BaseEnvironment):
  def __init__(
    self,
    id: str,
    wrappers: List[Dict],
    **kwargs
  ):
    env = gym.make(id)
    for wrapper_config in wrappers:
      wrapper = self.get_wrapper_from_config(wrapper_config)
      env = wrapper(env)

    super().__init__(env)

    self.env = env

  def get_wrapper_from_config(self, config: Dict) -> Type[gym.Wrapper]:
    wrapper_path = config["path"]
    wrapper_class_name = config.get("class")
    wrapper_class = get_class_from_module_path(wrapper_path, class_name=wrapper_class_name, class_suffix="GymWrapper")

    return partial(wrapper_class, **config.get("conf", {}))