import os
import xml.etree.ElementTree as ET
import tensorflow.keras as keras
import numpy as np
import cv2
import pickle
import copy
# from detection.datasets import transforms, utils
from ..datasets import transforms, utils

class pascal_voc(keras.utils.Sequence):
    def __init__(self, phase):
        # pascal_voc 2007数据的存储路径
        self.data_path = os.path.join(
            'E:\\BaiduNetdiskDownload\\VOCdevkit',
            'VOC2007')
        # batch_size
        self.batch_size = 1
        # 图片的尺寸
        self.target_size = 1216
        # 输入网络中的图像尺寸
        self.scale = (1216, 1216)
        # 类别信息  ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus'....]
        self.classes = ['background', 'person', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
                        'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse',
                        'motorbike', 'pottedplant', 'sheep', 'sofa',
                        'train', 'tvmonitor']

        # 构建目标类别的字典{'background': 0, 'aeroplane': 1, "bicycle": 2....}
        self.class_to_ind = dict(zip(self.classes, range(len(self.classes))))
        # 像素RGB的均值
        self.pixel_means = np.array([[[122.7717, 115.9465, 102.9801]]])
        # 用来指明获取训练集或者是验证集数据
        self.phase = phase
        # 获取图像数量，并加载相应的标签
        self.load_labels()
        # 目标总数量
        self.num_gtlabels = len(self.gt_labels)
        self.img_transform = transforms.ImageTransform(self.scale, self.pixel_means, [1., 1., 1.], 'fixed')
        self.bbox_transform = transforms.BboxTransform()
        self.flip_ratio = 0.5

    def __len__(self):
        # 返回迭代次数
        return np.round(self.num_image / self.batch_size)

    def __getitem__(self, idx):
        # 获取当前batch的起始索引值
        i = idx * self.batch_size
        batch_images = []
        batch_imgmeta = []
        batch_box = []
        bacth_labels = []
        for c in range(self.batch_size):
            # 获取相应的图像
            imname = self.gt_labels[i + c]['imname']
            # 读取图像
            image = self.image_read(imname)
            # 获取原始图像的尺寸
            ori_shape = image.shape
            # 进行尺度调整后的图像及调整的尺度
            image, image_scale, image_shape = self.prep_im_for_blob(image, self.pixel_means, self.target_size)
            # 获取尺度变换后图像的尺寸
            pad_shape = image.shape
            # 将gt_boxlabel与scale相乘获取图像调整后的标注框的大小：boxes.shape=[num_obj,4]
            bboxes = self.gt_labels[i + c]['boxes'] * image_scale
            # 获取对应的类别信息
            labels = self.gt_labels[i + c]['gt_classs']
            # print(labels)
            # 图像的基本信息
            img_meta_dict = dict({
                'ori_shape': ori_shape,
                'img_shape': image_shape,
                'pad_shape': pad_shape,
                'scale_factor': image_scale
            })
            # 将字典转换为列表的形式
            image_meta = self.compose_image_meta(img_meta_dict)
            # print(image_meta)
            batch_images.append(image)
            bacth_labels.append(labels)
            batch_imgmeta.append(image_meta)
            batch_box.append(bboxes)

        # 将图像转换成tensorflow输入的形式:【batch_size,H,W,C】
        batch_images = np.reshape(batch_images, (self.batch_size, image.shape[0], image.shape[1], 3))
        # print(batch_images.shape)
        batch_imgmeta = np.reshape(batch_imgmeta, (self.batch_size, 11))
        # print(batch_imgmeta.shape)
        batch_box = np.reshape(batch_box, (self.batch_size, bboxes.shape[0], 4))
        # print(batch_box.shape)
        bacth_labels = np.reshape(bacth_labels, ((self.batch_size, labels.shape[0])))
        # print(bacth_labels.shape)
        # 返回结果：尺度变换后的图像，图像元信息，目标框位置，目标类别
        return batch_images, batch_imgmeta, batch_box, bacth_labels

    def image_read(self, imname):
        # opencv 中默认图片色彩格式为BGR
        image = cv2.imread(imname)
        # 将图片转成RGB格式
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)
        return image

    def load_labels(self):
        # 根据标签信息加载相应的数据
        if self.phase == 'train':
            txtname = os.path.join(
                self.data_path, 'ImageSets', 'Main', 'trainval.txt')
        else:
            txtname = os.path.join(
                self.data_path, 'ImageSets', 'Main', 'val.txt')
        # 获取图像的索引
        with open(txtname, 'r') as f:
            self.image_index = [x.strip() for x in f.readlines()]
        self.num_image = len(self.image_index)
        # 图像对应的索引放到列表gt_labels中
        gt_labels = []
        # 遍历每一份图像获取标注信息
        for index in self.image_index:
            # 获取标注信息，包括objet box坐标信息 以及类别信息
            gt_label = self.load_pascal_annotation(index)
            # 添加到列表中
            gt_labels.append(gt_label)
        # 将标注信息赋值给属性：self.gt_labels
        self.gt_labels = gt_labels

    def load_pascal_annotation(self, index):
        """
        在PASCAL VOC的XML文件获取边框信息和类别信息
        """
        # 获取XML文件的地址
        filename = os.path.join(self.data_path, 'Annotations', index + '.xml')
        # 将XML中的内容获取出来
        tree = ET.parse(filename)
        # 获取节点图像的size
        image_size = tree.find('size')
        # 将图像的size信息存放到sizeinfo中
        size_info = np.zeros((2,), dtype=np.float32)
        # 宽
        size_info[0] = float(image_size.find('width').text)
        # 高
        size_info[1] = float(image_size.find('height').text)
        # 找到所有的object节点
        objs = tree.findall('object')
        # object的数量
        num_objs = len(objs)
        # boxes 坐标 (num_objs,4)
        boxes = np.zeros((num_objs, 4), dtype=np.float32)
        # class 的数量num_objs个，每个目标一个类别
        gt_classes = np.zeros((num_objs), dtype=np.int32)
        # 遍历所有的目标
        for ix, obj in enumerate(objs):
            # 找到bndbox节点
            bbox = obj.find('bndbox')
            # 获取坐标框的位置信息
            x1 = float(bbox.find('xmin').text) - 1
            y1 = float(bbox.find('ymin').text) - 1
            x2 = float(bbox.find('xmax').text) - 1
            y2 = float(bbox.find('ymax').text) - 1
            # 将位置信息存储在bbox中，注意boxes是一个np类的矩阵 大小为[num_objs,4]
            boxes[ix, :] = [y1, x1, y2, x2]
            # 找到class对应的类别信息
            cls = self.class_to_ind[obj.find('name').text.lower().strip()]
            # 将class信息存入gt_classses中，注意gt_classes也是一个np类的矩阵 大小为[num_objs] 是int值 对应于name
            gt_classes[ix] = cls
            # 获取图像的存储路径
            imname = os.path.join(self.data_path, 'JPEGImages', index + '.jpg')
        # 返回结果
        return {'boxes': boxes, 'gt_classs': gt_classes, 'imname': imname, 'image_size': size_info,
                'image_index': index}

    def prep_im_for_blob(self, im, pixel_means, target_size):
        "对输入的图像进行处理"
        im = im.astype(np.float32, copy=False)
        # 减去均值
        im -= pixel_means
        # 图像的大小
        im_shape = im.shape
        # 最短边
        im_size_min = np.min(im_shape[0:2])
        # 最长边
        im_size_max = np.max(im_shape[0:2])
        # 长边变换到1216的比例
        im_scale = float(target_size) / float(im_size_max)
        # 根据变换比例对图像进行resize
        im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
        shape = (self.target_size, self.target_size, im.shape[-1])
        pad = np.zeros(shape, dtype=im.dtype)
        pad[:im.shape[0], :im.shape[1], ...] = im
        # 返回im 和 im_scale
        return pad, im_scale, im.shape

    def compose_image_meta(self, img_meta_dict):
        '''将图像的原信息转换为列表.
        '''
        # 获取到字典中的信息
        ori_shape = img_meta_dict['ori_shape']
        img_shape = img_meta_dict['img_shape']
        pad_shape = img_meta_dict['pad_shape']
        scale_factor = img_meta_dict['scale_factor']
        flip = 0
        # 转换为一维列表
        img_meta = np.array(
            ori_shape +  # size=3
            img_shape +  # size=3
            pad_shape +  # size=3
            tuple([scale_factor]) +  # size=1
            tuple([flip])  # size=1
        ).astype(np.float32)
        # 返回列表信息
        return img_meta

if __name__ == '__main__':
    import visualize

    pascal = pascal_voc('train')
    # print(pascal.gt_labels)
    image, image_meta, bboxes, labels = pascal[218]
    print(image.shape)
    print(image_meta.shape)
    # print (len(pascal.gt_labels))
    # from detection.datasets.utils import get_original_image
    from ..datasets.utils import get_original_image
    import matplotlib.pyplot as plt
    import cv2

    # img, img_meta, bboxes, labels = data[0].image
    img_mean = [[122.7717, 115.9465, 102.9801]]
    img_std = (1., 1., 1.)
    rgb_img = np.round(image + img_mean).astype('uint8')
    # ori_img = get_original_image(data['image'], img_meta, img_mean)

    visualize.display_instances(rgb_img[0], bboxes[0], labels[0], pascal.classes)
    plt.show()


# -*- coding: utf-8 -*-
"""
Created on Sat Mar 30 08:59:15 2019

@author: MFYDUCK
"""

import numpy as np
import cv2
import math

def mfy(img):
    """
    @author: MFYDUCK
    Tek seride belli msafe kalınca true döndürür.
    (tabela gölgesinden dolayı hata alır.)
    """

    #RESMİ BELLEĞE ALMAK

    #2.yol
    #cv2
    # Load an color image in grayscale

    #------------------------------------------------------------------------------
    #KENAR ALGILAMA
    # Burada gri tonlamaya dönüştür.
    gray_image = cv2.cvtColor (img, cv2.COLOR_RGB2GRAY)
    # Canny Edge Detection'ı buradan arayın.
    cannyed_image = cv2.Canny (gray_image, 110, 200)

    #------------------------------------------------------------------------------
    #RESMİN İLGİLİ BÖLGESİNİ ALMAK

    height, width, channels = img.shape
    region_of_interest_vertices = [(0, height-int(height*0.041)),
                              (0, height-int(height*0.2)),
                              (int(width/2)-int(width*0.078),height-int(height*0.416)),
                              (int(width/2) + int(width*0.078),height-int(height*0.416)),
                              (width,height-int(height*0.2)),
                              (width,height-int(height*0.041)),]
    #daha sonra bulunan noktaları matris olarak vermeliyim
    #------------------------------------------------------------------------------
    #RESMİN İLGİLİ BÖLGESİNİ KIRPMAK
    def region_of_interest(img, vertices):
        # Define a blank matrix that matches the image height/width.
        mask = np.zeros_like(img)
        # Retrieve the number of color channels of the image.
        channel_count = 4
        # Create a match color with the same color channel counts.
        match_mask_color = (255,) * channel_count

        # Fill inside the polygon
        cv2.fillPoly(mask, vertices, match_mask_color)

        # Returning the image only where mask pixels match
        masked_image = cv2.bitwise_and(img, mask)

        return masked_image

    cropped_image = region_of_interest(cannyed_image,np.array([region_of_interest_vertices], np.int32),)

    #------------------------------------------------------------------------------
    #KENAR piksellerinden serit oluşturmak
    lines = cv2.HoughLinesP(cropped_image,rho=6,theta=np.pi / 60,threshold=160,lines=np.array([]),
        minLineLength=40,maxLineGap=25)

    #------------------------------------------------------------------------------
    def draw_lines(img, lines, color=[0, 0, 255], thickness=3):
        # If there are no lines to draw, exit.
        if lines is None:
            return
        # Make a copy of the original image.
        img = np.copy(img)
        # Create a blank image that matches the original in size.
        line_img = np.zeros((img.shape[0],img.shape[1],channels),dtype=np.uint8,)
        # Loop over all lines and draw them on the blank image.
        for line in lines:
            for x1, y1, x2, y2 in line:
                cv2.line(line_img, (x1, y1), (x2, y2), color, thickness)
                # Merge the image with the lines onto the original.
        img = cv2.addWeighted(img,0.8,line_img,1.0, 0.0)
        # Return the modified image.
        return img
    #---------------------------------------------------------------------------------------
    #SERİTLERİN EĞİMİNİ BULMAK

    min_line_y = 0
    piksel=0
    for line in lines:
        for x1, y1, x2, y2 in line:
            slope = (y2 - y1) / (x2 - x1) # <-- Calculating the slope.
            if math.fabs(slope) > 0.1: # <-- Only consider extreme slope,eğim yatay değilse cık
                continue
            elif int((y1+y2)/2) > min_line_y :  # <-- Otherwise, right group.
                min_line_y=int((y1+y2)/2)

    piksel=height-min_line_y
    if(piksel<int(height*0.41)):
        return True
    else:
       return False


import dataclasses
from copy import deepcopy
from decimal import Decimal
from typing import Any, Dict, List, Optional, Tuple, Type

from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _

from baserow.contrib.database.action.scopes import (
    TABLE_ACTION_CONTEXT,
    TableActionScopeType,
)
from baserow.contrib.database.rows.handler import (
    GeneratedTableModelForUpdate,
    RowHandler,
)
from baserow.contrib.database.table.handler import TableHandler
from baserow.contrib.database.table.models import GeneratedTableModel, Table
from baserow.core.action.models import Action
from baserow.core.action.registries import (
    ActionScopeStr,
    ActionTypeDescription,
    UndoableActionType,
)
from baserow.core.trash.handler import TrashHandler
from baserow.core.utils import Progress

class CreateRowActionType(UndoableActionType):
    type = "create_row"
    description = ActionTypeDescription(
        _("Create row"), _("Row (%(row_id)s) created"), TABLE_ACTION_CONTEXT
    )

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_id: int

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        values: Optional[Dict[str, Any]] = None,
        model: Optional[Type[GeneratedTableModel]] = None,
        before_row: Optional[GeneratedTableModel] = None,
        user_field_names: bool = False,
    ) -> GeneratedTableModel:
        """
        Creates a new row for a given table with the provided values if the user
        belongs to the related workspace. It also calls the rows_created signal.
        See the baserow.contrib.database.rows.handler.RowHandler.create_row
        for more information.
        Undoing this action trashes the row and redoing restores it.

        :param user: The user of whose behalf the row is created.
        :param table: The table for which to create a row for.
        :param values: The values that must be set upon creating the row. The keys must
            be the field ids.
        :param model: If a model is already generated it can be provided here to avoid
            having to generate the model again.
        :param before_row: If provided the new row will be placed right before that row
            instance.
        :param user_field_names: Whether or not the values are keyed by the internal
            Baserow field name (field_1,field_2 etc) or by the user field names.
        :return: The created row instance.
        """

        row = RowHandler().create_row(
            user,
            table,
            values=values,
            model=model,
            before_row=before_row,
            user_field_names=user_field_names,
        )

        workspace = table.database.workspace
        params = cls.Params(
            table.id, table.name, table.database.id, table.database.name, row.id
        )
        cls.register_action(
            user, params, scope=cls.scope(table.id), workspace=workspace
        )

        return row

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        RowHandler().delete_row_by_id(
            user, TableHandler().get_table(params.table_id), params.row_id
        )

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        TrashHandler.restore_item(
            user, "row", params.row_id, parent_trash_item_id=params.table_id
        )

class CreateRowsActionType(UndoableActionType):
    type = "create_rows"
    description = ActionTypeDescription(
        _("Create rows"), _("Rows (%(row_ids)s) created"), TABLE_ACTION_CONTEXT
    )

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_ids: List[int]
        trashed_rows_entry_id: Optional[int] = None

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        rows_values: List[Dict[str, Any]],
        before_row: Optional[GeneratedTableModel] = None,
        model: Optional[Type[GeneratedTableModel]] = None,
    ) -> List[GeneratedTableModel]:
        """
        Creates rows for a given table with the provided values if the user
        belongs to the related workspace. It also calls the rows_created signal.
        See the baserow.contrib.database.rows.handler.RowHandler.create_rows
        for more information.
        Undoing this action trashes the rows and redoing restores them all.

        :param user: The user of whose behalf the rows are created.
        :param table: The table for which the rows should be created.
        :param rows_values: List of rows values for rows that need to be created.
        :param before_row: If provided the new rows will be placed right before
            the row with this id.
        :param model: If the correct model has already been generated it can be
            provided so that it does not have to be generated for a second time.
        :return: The created list of rows instances.
        """

        rows = RowHandler().create_rows(
            user, table, rows_values, before_row=before_row, model=model
        )

        workspace = table.database.workspace
        params = cls.Params(
            table.id,
            table.name,
            table.database.id,
            table.database.name,
            [row.id for row in rows],
        )
        cls.register_action(
            user, params, scope=cls.scope(table.id), workspace=workspace
        )

        return rows

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        trashed_rows_trash_entry = RowHandler().delete_rows(
            user, TableHandler().get_table(params.table_id), params.row_ids
        )
        params.trashed_rows_entry_id = trashed_rows_trash_entry.id
        action_being_undone.params = params

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        TrashHandler.restore_item(
            user,
            "rows",
            params.trashed_rows_entry_id,
            parent_trash_item_id=params.table_id,
        )

class ImportRowsActionType(UndoableActionType):
    type = "import_rows"
    description = ActionTypeDescription(
        _("Import rows"), _("Rows (%(row_ids)s) imported"), TABLE_ACTION_CONTEXT
    )

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_ids: List[int]
        trashed_rows_entry_id: Optional[int] = None

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        data=List[List[Any]],
        progress: Optional[Progress] = None,
    ) -> Tuple[List[GeneratedTableModel], Dict[str, Any]]:
        """
        Creates rows for a given table with the provided values if the user
        belongs to the related workspace. It also calls the table_updated signal.
        This action is supposed to handle bigger row amount than the createRowsAction,
        it generates an import error report and allow to track the progress.
        Undoing this action trashes the rows and redoing restores them all.
        The new rows are appended to the existing rows.
        See the baserow.contrib.database.rows.handler.RowHandler.import_rows
        for more information.

        :param user: The user of whose behalf the rows are created.
        :param table: The table for which the rows should be imported.
        :param data: List of rows values for rows that need to be created.
        :param progress: An optional progress object to track the task progress.
        :return: The created list of rows instances and the error report.
        """

        created_rows, error_report = RowHandler().import_rows(
            user, table, data, progress=progress
        )

        workspace = table.database.workspace
        params = cls.Params(
            table.id,
            table.name,
            table.database.id,
            table.database.name,
            [row.id for row in created_rows],
        )
        cls.register_action(
            user, params, scope=cls.scope(table.id), workspace=workspace
        )

        return created_rows, error_report

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        trashed_rows_trash_entry = RowHandler().delete_rows(
            user, TableHandler().get_table(params.table_id), params.row_ids
        )
        params.trashed_rows_entry_id = trashed_rows_trash_entry.id
        action_being_undone.params = params

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        TrashHandler.restore_item(
            user,
            "rows",
            params.trashed_rows_entry_id,
            parent_trash_item_id=params.table_id,
        )

class DeleteRowActionType(UndoableActionType):
    type = "delete_row"
    description = ActionTypeDescription(
        _("Delete row"), _("Row (%(row_id)s) deleted"), TABLE_ACTION_CONTEXT
    )

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_id: int

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        row_id: int,
        model: Optional[Type[GeneratedTableModel]] = None,
    ):
        """
        Deletes an existing row of the given table and with row_id.
        See the baserow.contrib.database.rows.handler.RowHandler.delete_row_by_id
        for more information.
        Undoing this action restores the row and redoing trashes it.

        :param user: The user of whose behalf the change is made.
        :param table: The table for which the row must be deleted.
        :param row_id: The id of the row that must be deleted.
        :param model: If the correct model has already been generated, it can be
            provided so that it does not have to be generated for a second time.
        :raises RowDoesNotExist: When the row with the provided id does not exist.
        """

        RowHandler().delete_row_by_id(user, table, row_id, model=model)

        database = table.database
        params = cls.Params(table.id, table.name, database.id, database.name, row_id)
        cls.register_action(
            user, params, scope=cls.scope(table.id), workspace=database.workspace
        )

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        TrashHandler.restore_item(
            user, "row", params.row_id, parent_trash_item_id=params.table_id
        )

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        RowHandler().delete_row_by_id(
            user, TableHandler().get_table(params.table_id), params.row_id
        )

class DeleteRowsActionType(UndoableActionType):
    type = "delete_rows"
    description = ActionTypeDescription(
        _("Delete rows"), _("Rows (%(row_ids)s) deleted"), TABLE_ACTION_CONTEXT
    )

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_ids: List[int]
        trashed_rows_entry_id: int

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        row_ids: List[int],
        model: Optional[Type[GeneratedTableModel]] = None,
    ):
        """
        Deletes rows of the given table with the given row_ids.
        See the baserow.contrib.database.rows.handler.RowHandler.delete_rows
        for more information.
        Undoing this action restores the original rows and redoing trashes them again.

        :param user: The user of whose behalf the change is made.
        :param table: The table for which the row must be deleted.
        :param row_ids: The id of the row that must be deleted.
        :param model: If the correct model has already been generated, it can be
            provided so that it does not have to be generated for a second time.
        :raises RowDoesNotExist: When the row with the provided id does not exist.
        """

        trashed_rows_entry = RowHandler().delete_rows(user, table, row_ids, model=model)

        workspace = table.database.workspace
        params = cls.Params(
            table.id,
            table.name,
            table.database.id,
            table.database.name,
            row_ids,
            trashed_rows_entry.id,
        )
        cls.register_action(
            user, params, scope=cls.scope(table.id), workspace=workspace
        )

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        TrashHandler.restore_item(
            user,
            "rows",
            params.trashed_rows_entry_id,
            parent_trash_item_id=params.table_id,
        )

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        trashed_rows_entry = RowHandler().delete_rows(
            user, TableHandler().get_table(params.table_id), params.row_ids
        )
        params.trashed_rows_entry_id = trashed_rows_entry.id
        action_being_redone.params = params

def get_rows_displacement(
    model: Type[GeneratedTableModel],
    original_row_order: Decimal,
    new_row_order: Decimal,
) -> int:
    """
    Returns the rows count between two row orders.

    :param model: The model of the row.
    :param original_row_order: The row order before move operation.
    :param new_row_order: The row order after move operation.
    """

    def get_displacement(
        lower_order: Decimal,
        higher_order: Decimal,
    ) -> int:
        """Return the rows count between two orders value."""

        return model.objects.filter(
            order__gt=lower_order, order__lt=higher_order
        ).count()

    if new_row_order > original_row_order:
        return get_displacement(original_row_order, new_row_order)
    else:
        return -get_displacement(new_row_order, original_row_order)

def get_before_row_from_displacement(
    row: GeneratedTableModel,
    model: Type[GeneratedTableModel],
    displacement: int,
) -> Optional[GeneratedTableModel]:
    """
    Returns the row instance to use as before in RowHandler().move_row,
    given the displacement.

    :param row: The row instance to use as reference.
    :param model: The model of the row to access data in the table.
    :param displacement: The displacement value.
    """

    if displacement >= 0:
        # a positive displacement means that the row is moved down (bigger order value)
        # so take the row with the order value immediately after the desired position
        try:
            return model.objects.filter(order__gt=row.order).order_by("order")[
                displacement
            ]
        except IndexError:  # after the last line
            return None
    else:
        # displacement < 0 means we are moving the row up (lower order value) but we
        # still need the row with the order value immediately after the desired position
        queryset = model.objects.filter(order__lt=row.order).order_by("-order")
        try:
            # We want to find a row N rows above the provided row, but specifically
            # the before row. The before row is always the row after the slot where
            # we want to move the row. So we minus one from the displacement to get
            # the position instead of this before row.
            return queryset[abs(displacement) - 1]
        except IndexError:
            # cannot be before the first row, so take the first available
            # (the one with the lowest order value as before row).
            return queryset.last()

class MoveRowActionType(UndoableActionType):
    type = "move_row"
    description = ActionTypeDescription(
        _("Move row"), _("Row (%(row_id)s) moved"), TABLE_ACTION_CONTEXT
    )

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_id: int
        rows_displacement: int

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        row_id: int,
        before_row: Optional[GeneratedTableModel] = None,
        model: Optional[Type[GeneratedTableModel]] = None,
    ) -> GeneratedTableModelForUpdate:
        """
        Moves the row before another row or to the end if no before row is provided.
        This moving is done by updating the `order` value of the order.
        See the baserow.contrib.database.rows.handler.RowHandler.move_row
        for more information.
        Undoing this action moves the row back however many positions it was moved
        initially.
        Redoing moves the row in the same direction and number of positions it was
        moved initially.

        :param user: The user of whose behalf the row is moved
        :param table: The table that contains the row that needs to be moved.
        :param row_id: The id of the row that needs to be moved.
        :param before_row: If provided the new row will be placed right before that row
            instance. Otherwise the row will be moved to the end.
        :param model: If the correct model has already been generated, it can be
            provided so that it does not have to be generated for a second time.
        """

        if model is None:
            model = table.get_model()

        row_handler = RowHandler()
        row = row_handler.get_row_for_update(user, table, row_id, model=model)

        original_row_order = row.order

        updated_row = row_handler.move_row(
            user, table, row, before_row=before_row, model=model
        )

        rows_displacement = get_rows_displacement(
            model, original_row_order, updated_row.order
        )

        # no need to register the action if the row was not moved
        if rows_displacement == 0:
            return updated_row

        workspace = table.database.workspace
        params = cls.Params(
            table.id,
            table.name,
            table.database.id,
            table.database.name,
            row.id,
            rows_displacement,
        )
        cls.register_action(user, params, cls.scope(table.id), workspace=workspace)
        return updated_row

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        table = TableHandler().get_table(params.table_id)
        model = table.get_model()

        row_handler = RowHandler()
        row = row_handler.get_row_for_update(user, table, params.row_id, model=model)

        before_row = get_before_row_from_displacement(
            row, model, -params.rows_displacement
        )

        row_handler.move_row(user, table, row, before_row=before_row, model=model)

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        table = TableHandler().get_table(params.table_id)
        model = table.get_model()

        row_handler = RowHandler()
        row = row_handler.get_row_for_update(user, table, params.row_id, model=model)

        before_row = get_before_row_from_displacement(
            row, model, params.rows_displacement
        )

        row_handler.move_row(user, table, row, before_row=before_row, model=model)

# Deprecated in favor of UpdateRowsActionType
class UpdateRowActionType(UndoableActionType):
    type = "update_row"
    description = ActionTypeDescription(
        _("Update row"), _("Row (%(row_id)s) updated"), TABLE_ACTION_CONTEXT
    )
    privacy_sensitive_params = ["row_values", "original_row_values"]

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_id: int
        row_values: Dict[str, Any]
        original_row_values: Dict[str, Any]

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        row_id: int,
        values: Dict[str, Any],
        model: Optional[Type[GeneratedTableModel]] = None,
        user_field_names: bool = False,
    ) -> GeneratedTableModelForUpdate:
        """
        Updates one or more values of the provided row_id.
        See the baserow.contrib.database.rows.handler.RowHandler.update_row
        for more information.
        Undoing this action restores the original values.
        Redoing set the new values again.

        :param user: The user of whose behalf the change is made.
        :param table: The table for which the row must be updated.
        :param row_id: The id of the row that must be updated.
        :param values: The values that must be updated. The keys must be the field ids.
        :param model: If the correct model has already been generated it can be
            provided so that it does not have to be generated for a second time.
        :param user_field_names: Whether or not the values are keyed by the internal
            Baserow field names (field_1,field_2 etc) or by the user field names.
        :raises RowDoesNotExist: When the row with the provided id does not exist.
        :return: The updated row instance.
        """

        if model is None:
            model = table.get_model()

        row_handler = RowHandler()

        if user_field_names:
            values = row_handler.map_user_field_name_dict_to_internal(
                model._field_objects, values
            )

        row = row_handler.get_row_for_update(
            user, table, row_id, enhance_by_fields=True, model=model
        )
        field_ids = set(row_handler.extract_field_ids_from_keys(values.keys()))
        original_row_values = row_handler.get_internal_values_for_fields(row, field_ids)

        updated_row = row_handler.update_row(user, table, row, values, model=model)
        row_values = row_handler.get_internal_values_for_fields(row, field_ids)

        workspace = table.database.workspace
        params = cls.Params(
            table.id,
            table.name,
            table.database.id,
            table.database.name,
            row.id,
            row_values,
            original_row_values,
        )
        cls.register_action(
            user, params, scope=cls.scope(table.id), workspace=workspace
        )

        return updated_row

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        table = TableHandler().get_table(params.table_id)
        RowHandler().update_row_by_id(
            user, table, row_id=params.row_id, values=params.original_row_values
        )

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        table = TableHandler().get_table(params.table_id)
        RowHandler().update_row_by_id(
            user, table, row_id=params.row_id, values=params.row_values
        )

class UpdateRowsActionType(UndoableActionType):
    type = "update_rows"
    description = ActionTypeDescription(
        _("Update rows"), _("Rows (%(row_ids)s) updated"), TABLE_ACTION_CONTEXT
    )
    privacy_sensitive_params = [
        "row_values",
        "original_rows_values_by_id",
        "updated_rows_fields_metadata_by_id",
    ]

    @dataclasses.dataclass
    class Params:
        table_id: int
        table_name: str
        database_id: int
        database_name: str
        row_ids: List[int]
        # !!! WARNING !!!
        # Make sure these values are kept in sync with privacy_sensitive_params above
        # !!! WARNING !!!
        row_values: List[Dict[str, Any]]  # TODO: rename to rows_values
        original_rows_values_by_id: Dict[int, Dict[str, Any]]
        updated_rows_fields_metadata_by_id: Dict[int, Dict[str, Any]]

    @classmethod
    def do(
        cls,
        user: AbstractUser,
        table: Table,
        rows_values: List[Dict[str, Any]],
        model: Optional[Type[GeneratedTableModel]] = None,
    ) -> List[GeneratedTableModelForUpdate]:
        """
        Updates field values in batch based on provided rows with the new values.
        See the baserow.contrib.database.rows.handler.RowHandler.update_rows
        for more information.
        Undoing this action restores the original values.
        Redoing set the new values again.

        :param user: The user of whose behalf the change is made.
        :param table: The table for which the rows must be updated.
        :param rows_values: The rows values that must be updated. The keys must be the
            field ids plus the id of the row.
        :param model: If the correct model has already been generated it can be
            provided so that it does not have to be generated for a second time.
        :return: The updated rows.
        """

        row_handler = RowHandler()

        result = row_handler.update_rows(user, table, rows_values, model=model)
        updated_rows = result.updated_rows

        workspace = table.database.workspace
        params = cls.Params(
            table.id,
            table.name,
            table.database.id,
            table.database.name,
            [row.id for row in updated_rows],
            rows_values,
            result.original_rows_values_by_id,
            result.updated_row_fields_metadata_by_row_id,
        )
        cls.register_action(user, params, cls.scope(table.id), workspace=workspace)

        return updated_rows

    @classmethod
    def serialized_to_params(cls, serialized_params: Any) -> Any:
        """
        When storing integers as dictionary keys in a database, they are saved
        as strings. This method is designed to convert these string keys back
        into integers. This ensures that we can accurately use the row.id as a
        key."
        """

        serialized_params["original_rows_values_by_id"] = {
            int(row_id): row_values
            for row_id, row_values in serialized_params[
                "original_rows_values_by_id"
            ].items()
        }

        serialized_params["updated_rows_fields_metadata_by_id"] = {
            int(row_id): row_values
            for row_id, row_values in serialized_params[
                "updated_rows_fields_metadata_by_id"
            ].items()
        }

        return cls.Params(**deepcopy(serialized_params))

    @classmethod
    def scope(cls, table_id) -> ActionScopeStr:
        return TableActionScopeType.value(table_id)

    @classmethod
    def undo(cls, user: AbstractUser, params: Params, action_being_undone: Action):
        table = TableHandler().get_table(params.table_id)
        original_rows_values = list(params.original_rows_values_by_id.values())
        RowHandler().update_rows(user, table, original_rows_values)

    @classmethod
    def redo(cls, user: AbstractUser, params: Params, action_being_redone: Action):
        table = TableHandler().get_table(params.table_id)
        RowHandler().update_rows(user, table, params.row_values)


import dash
from dash import dcc, html, Input, Output, ctx, callback
import plotly.graph_objects as go # or plotly.express as px
import glob,os
from dash_labs.plugins.pages import register_page
import dash_bootstrap_components as dbc

import pandas as pd

# Code from: https://github.com/plotly/dash-labs/tree/main/docs/demos/multi_page_example1
register_page(__name__, path="/ts")

colors = {
    'background': '#dddddd',
    'grid': '#666666',
    'text': '#333333'
}

labels_list = ["Label 1", "Label 2", "Label 3"]

fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)

layout = html.Div(
    id='dropdowns-parent',
    children=[
        html.Div(
            [html.Div("Choose a Dataset", style={'margin-right': '10px'}),
             dcc.Dropdown(
                 id="dataset",
                clearable=False,
                style={'width': '30%', 'color':'#111111'},
            )],
            style={'display':'flex', 'margin': '10px', 'align-items':'center'}
        ),
        html.Div(
            [html.Div("Choose the time feature", style={'margin-right': '10px'}),
             dcc.Dropdown(
                 id="date_feature",
                clearable=False,
                style={'width': '30%', 'color':'#111111'},
            )],
            style={'display':'flex', 'margin': '10px', 'align-items':'center'}
        ),
        html.Div(
            [html.Div("Choose an other feature", style={'margin-right': '10px'}),
             dcc.Dropdown(
                 id="sensor",
                clearable=False,
                style={'width': '30%', 'color':'#111111'},
            )],
            style={'display':'flex', 'margin': '10px', 'align-items':'center'}
        ),
        html.Div(
            dcc.Graph(
                figure=fig,
                id="ts-chart",
            ),
            style={'margin': '10px', 'justify-content':'center', 'align-items':'center'},
        ),
        html.Div(
            [dbc.Button("Regenerate Labels", color="danger", id="regenerate-button", className="me-1", n_clicks=0),
            html.Div("",style={'margin-left': '2.5%','margin-right': '2.5%'}),
            html.Div([dbc.Button(label, color="primary", id=label, className="me-1", n_clicks=0) for label in labels_list]),
            html.Div("",style={'margin-left': '2.5%','margin-right': '2.5%'})],
            style={'display':'flex', 'margin': '20px', 'align-items':'center', 'justify-content':'center'}
        )
    ]
)

@callback(output=dash.dependencies.Output('dataset', 'options'),
              inputs=[dash.dependencies.Input('dropdowns-parent', 'n_clicks')])
def change_my_dropdown_options(n_clicks):
    if n_clicks is None:
        raise dash.exceptions.PreventUpdate
    datasets = glob.glob1("./uploads","*.csv")
    list.sort(datasets)
    return(datasets)

@callback([Output("sensor", "options"),Output("date_feature", "options")],Input("dataset", "value"))
def update_sensor_dropdown(dataset):
    if dataset!=None:
        df = pd.read_csv("./uploads/{}".format(dataset))
        return df.columns,df.columns
    else:
        return [],[]

list_inputs = [Input("date_feature", "value"), Input("sensor", "value") , Input("dataset", "value"), Input("ts-chart", "figure"), Input("regenerate-button", "n_clicks")]
variable_inputs = [Input(label,"n_clicks") for label in labels_list]

from plotly.subplots import make_subplots
@callback(Output("ts-chart", "figure"), list_inputs + variable_inputs)
def update_chart(date_feature,sensor,dataset,figure, *args):
    # create an empty figure  with no data
    fig = go.Figure()
    fig.add_annotation(text="Choose a dataset, the time feature (column), and then the signal you want to display",showarrow=False,font=dict(size=20))
    if dataset != None:
        df = pd.read_csv("./uploads/{}".format(dataset))
        if date_feature!=None :
            # Si jamais le fichier csv "label" n'existe pas on le crée (vide == tout à 0)
            if not os.path.exists("./results/{}_labels.csv".format(dataset[:-4])) :
                df_labels = pd.DataFrame(df[date_feature])
                df_labels[labels_list] = 0
                df_labels.to_csv("./results/{}_labels.csv".format(dataset[:-4]),index=False)
            df_labels = pd.read_csv("./results/{}_labels.csv".format(dataset[:-4]))
            if "regenerate-button" == ctx.triggered_id:
                df_labels[labels_list] = 0
                df_labels.to_csv("./results/{}_labels.csv".format(dataset[:-4]),index=False)
            for label in labels_list:
                if label == ctx.triggered_id:
                    print(label)
                    figure_data = figure["layout"]
                    range_of_slider = figure_data["xaxis"]["range"]
                    boundary_low =  df_labels.iloc[(df_labels['ts']-range_of_slider[0]).abs().argsort()[0]]["ts"]
                    boundary_high = df_labels.iloc[(df_labels['ts']-range_of_slider[1]).abs().argsort()[0]]["ts"]
                    df_labels.loc[df_labels["ts"].between(boundary_low,boundary_high),label]=1
                    df_labels.to_csv("./results/{}_labels.csv".format(dataset[:-4]),index=False)

            if sensor!=None :
                fig = make_subplots(rows = 2, cols = 1,
                                    vertical_spacing=0.2,
                                    shared_xaxes=True,
                                    row_heights=[0.5,0.25],
                                    )
                fig.add_trace(go.Scatter(x=df[date_feature], y=df[sensor], name=sensor, legendgroup=1), row=1, col=1)
                for fault in labels_list:
                    fig.add_trace(go.Scatter(x=df_labels[date_feature], y=df_labels[fault], name=fault, legendgroup=2), row=2, col=1)
                fig.update_layout(
                    plot_bgcolor=colors['background'],
                    paper_bgcolor=colors['background'],
                    font_color=colors['text'],
                    height=550,
                    xaxis=dict(
                        rangeslider=dict(
                            visible=False,
                            autorange=True,
                        )
                    ),
                    # showlegend=False,
                    legend_tracegroupgap = 240,
                    hovermode='x unified'
                )
                fig.update_xaxes(showline=True, linewidth=1, linecolor='black')
                fig.update_yaxes(showline=True, linewidth=1, linecolor='black')
                fig.update_xaxes(showgrid=True, gridwidth=1.5, gridcolor=colors["grid"])
                fig.update_yaxes(showgrid=True, gridwidth=1.5, gridcolor=colors["grid"])
                fig.update_yaxes(row=2,col=1,range=[-0.1,1.1])
    return fig


import asyncio
import json
import logging
import time
from collections import OrderedDict
from datetime import datetime

import requests

from sonofflan.config import DeviceConfig
from sonofflan.crypto import encrypt, generate_iv

class Device:
    """Base sonoff device

    Attributes
    ----------
    `id` : str
        The device ID
    `name` : str
        The device name (from configuration)
    `encrypt` : bool
        If the device is encrypted (not DIY mode)
    `key` : str
        The device encryption key (from configuration)
    `url` : str
        The device base URL (used to send commands)
    `last_update` : datetime
        The date and time which the device was updated for the last time
    """

    def __init__(self, data: dict, config: DeviceConfig) -> None:
        """
        Parameters
        ----------
        `data` : dict
            Dictionary with data coming from Zeroconf
        `config` : DeviceConfig
            Configuration for the device
        """

        self._id = config.id
        self._name = config.name
        self._encrypt = data['encrypt']
        self._key = config.key
        self._url = None
        self._last_update = None
        self._logger = logging.getLogger(f"sonofflan.devices.{self.__class__.__name__}")

        self._update(data)

    def _update(self, data: dict) -> None:
        """Internal update method

        Parameters
        ----------
        `data` : dict
            Dictionary with data coming from Zeroconf
        """

        self._encrypt = data['encrypt']
        self._url = f"http://{data['address']}:{data['port']}"
        self._last_update = datetime.utcnow()

    def update(self, data: dict) -> None:
        """Update the device with data from Zeroconf

        Parameters
        ----------
        `data` : dict
            Dictionary with data coming from Zeroconf
        """

        self._logger.debug(f'Updating {self} with {json.dumps(data, indent=2)}')
        if self._id != data['id']:
            self._logger.error(f"Unexpected update for {self} with {data}")
            return
        self._update(data)

    def _repr(self) -> str:
        """Internal representation method"""

        return f'"{self._name}" {self._id} url={self._url} encrypt={self._encrypt}'

    def __repr__(self) -> str:
        """Representation method"""

        return f'{self.__class__.__name__}({self._repr()} updated={self._last_update})'

    def _send(self, url: str, data: str | dict) -> None:
        """Internal send command method

        Parameters
        ----------
        `url` : str
            Command URL
        `data` : str|dict
            Data for the command
        """

        asyncio.get_running_loop().create_task(
            self._async_send(url, data)
        )

    async def _async_send(self, url: str, data: str | dict) -> None:
        """Internal asynchronous send command method

        Parameters
        ----------
        `url` : str
            Command URL
        `data` : str|dict
            Data for the command
        """

        if self._url is None:
            self._logger.error(f"Cannot send commands to {self}: url not valid")
            return

        if type(data) == dict:
            data = json.dumps(data, separators=(",", ":"), indent=None)
        self._logger.debug(f'Sending to "{self._url}{url}" data "{data}"')
        payload = {
            "sequence": str(int(time.time() * 1000)),
            "deviceid": self._id,
            "encrypt": self._encrypt,
        }
        if self._encrypt and self._key is not None:
            payload["selfApikey"] = "123"
            iv = generate_iv()
            payload["iv"] = iv
            data = encrypt(data, iv, self._key)  # type: ignore
        payload["data"] = data

        headers = OrderedDict(
            {
                "Content-Type": "application/json;charset=UTF-8",
                # "Connection": "keep-alive",
                "Accept": "application/json",
                "Accept-Language": "en-gb",
                # "Content-Length": "0",
                # "Accept-Encoding": "gzip, deflate",
                # "Cache-Control": "no-store",
            }
        )
        payload = json.dumps(payload, separators=(",", ":"), indent=None)
        # noinspection PyBroadException
        try:
            response = requests.post(f"{self._url}{url}", headers=headers, data=payload)
        except Exception:
            self._logger.error(f"Cannot send request to {self._url}{url}", exc_info=True)
            return
        # noinspection PyBroadException
        try:
            if response.status_code != 200:
                raise RuntimeError(f"Got HTTP status {response.code}")  # type: ignore
            response_json = json.loads(response.content.decode("utf-8"))
            self._logger.debug(f'Got response {response.status_code} {json.dumps(response_json, indent=2)}')
            if "error" in response_json and response_json["error"] != 0:
                raise RuntimeError(f'Get error {response_json["error"]}')
            self._logger.debug(f'Message sent to {self} successfully!')
        except Exception:
            self._logger.error(f"Error processing response {response}: {response.content}", exc_info=True)

    @property
    def id(self) -> str:
        """The device ID"""

        return self._id  # type: ignore

    @property
    def name(self) -> str:
        """The device name"""

        return self._name  # type: ignore

    @property
    def encrypt(self) -> bool:
        """If the device is encrypted (not DIY mode)"""

        return self._encrypt

    @property
    def key(self) -> str | None:
        """The device encryption key"""

        return self._key

    @property
    def url(self) -> str | None:
        """The device base URL (used to send commands)"""

        return self._url

    @property
    def last_update(self) -> datetime | None:
        """The date and time which the device was updated for the last time"""

        return self._last_update


from conans import ConanFile, CMake

class SquirrelConan(ConanFile):
    name = "squirrel"
    version = "3.0.0"
    license = "Apache-2.0"
    url = "http://squirrel-lang.org/"
    description = "Squirrel is a high level imperative, object-oriented programming language."
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False]}
    default_options = {"shared": False}
    generators = "cmake"
    exports_sources = "CMakeLists.txt", "squirrel/*", "sqstdlib/*", "include/*"

    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

        # Explicit way:
        # self.run('cmake "%s/src" %s' % (self.source_folder, cmake.command_line))
        # self.run("cmake --build . %s" % cmake.build_config)

    def package(self):
        self.copy("*.h", dst="include", src="include")
        self.copy("*.lib", dst="lib", keep_path=False)
        self.copy("*.dll", dst="bin", keep_path=False)
        self.copy("*.dylib*", dst="lib", keep_path=False)
        self.copy("*.so", dst="lib", keep_path=False)
        self.copy("*.a", dst="lib", keep_path=False)

    def package_info(self):
        self.cpp_info
        self.cpp_info.components["sqstdlib"].libs = ["sqstdlib"]
        self.cpp_info.components["sqstdlib"].requires = ["Squirrel"]
        self.cpp_info.components["sqstdlib"].defines= ["_SQ64"]
        self.cpp_info.components["Squirrel"].libs = ["squirrel"]
        self.cpp_info.components["Squirrel"].defines= ["_SQ64"]


import pandas_datareader as web
from datetime import date, timedelta
import pandas as pd
import matplotlib.pyplot as plt
import requests
import json

def carteira(n_dias):
    carteira_df = pd.read_excel("carteira.xlsx")
    carteira_df.head()

    today = date.today()
    days_ago = today - timedelta(n_dias)

    total = ''

    for acao in carteira_df['Carteira']:
        df = web.DataReader(
            f'{acao}', data_source='yahoo', start=days_ago, end=today
        )
        acoes = (
            '
'
            + f' {acao} '
            + '
'
            + '\n'
            +'Fechamento ajustado de hoje: '
            + str(round(df.iloc[-1][-1], 2))
            + '
'
            + 'Fechamento ajustado mínimo dos últimos '
            + str(n_dias)
            + ' dias: '
            + str(round(df['Adj Close'].min(), 2))
            + '
'
            + 'Fechamento ajustado médio dos últimos '
            + str(n_dias)
            + ' dias: '
            + str(round(df['Adj Close'].mean(), 2))
            + '
'
            +'Fechamento ajustado máximo dos últimos '
            + str(n_dias)
            +' dias: '
            + str(round(df['Adj Close'].max(), 2))
            + '
'
        )
        total += acoes + '\n'
    return total

def moeda():
    moeda = requests.get(
        "https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL"
    )
    moeda = moeda.json()
    cotacao_dolar = round(pd.to_numeric(moeda['USDBRL']['bid']), 2)
    cotacao_euro = round(pd.to_numeric(moeda['EURBRL']['bid']), 2)
    cotacao_bitcoin = round(pd.to_numeric(moeda['BTCBRL']['bid']), 2)
    moedas = (
        'Cotação do Dólar: '
        + str(cotacao_dolar)
        + '
'
        + '\nCotação do Euro: '
        + str(cotacao_euro)
        + '
'
        +'\nCotação do Bitcoin: '
        + str(cotacao_bitcoin)
        + '
'
    )
    return moedas


#!/usr/bin/env python3

from os import system

seq = open("rosalind_rna.txt", 'r').read().upper()

def transcribe(sequence):
    """Returns a string of a transcribed DNA Sequence aka RNA"""
    return sequence.replace("T", "U")

print(transcribe(seq))

system("python3 transcribing_DNA_into_RNA.py > solution.txt")


import moderngl as mgl
from constants.colors import Colors
from constants.dimensions import SCREEN_DIMENSIONS
from constants.shape import Shape, SHAPE_VERTICES
from puzzles.puzzle_graph import PuzzleGraph
from engine.renderable import Renderable
from engine.camera import Camera
from models.polyhedron import Polyhedron

class TestScene(Renderable):
    def __init__(self, ctx: mgl.Context):
        self.ctx = ctx
        self.center = (
            SCREEN_DIMENSIONS[0] / 2,
            SCREEN_DIMENSIONS[1] / 2,
        )

    def init(self):
        self.camera = Camera(self.ctx)
        self.puzzle = PuzzleGraph.from_file_name("6_0")
        self.subject = Polyhedron(
            self.ctx, self.camera, SHAPE_VERTICES[Shape.tetrahedron], self.puzzle, "generic.png"
        )

    def handle_events(self, delta_time: int):
        self.subject.handle_events(delta_time)

    def render(self, delta_time: int):
        self.ctx.clear(color=Colors.WHITE)
        self.subject.render(delta_time)

    def destroy(self):
        self.subject.destroy()


"""
'main.py' module.
Runs the game loop.
"""
# ------------------------------------------#

# Code for scene architecture taken from:
# https: // nerdparadise.com / programming / pygame / part7

# ------------------------------------------#

import pygame as pg
from src.menu_scene import MenuScene

class Game:
    """Game class implementation."""

    def __init__(self):
        """Virtually private constructor which initializes the Game class instance."""
        self.menu = MenuScene()  # Initialize the Menu scene for our starting scene
        self.run_game(60, self.menu)  # Run the game on 60 fps

    @staticmethod
    def run_game(fps, starting_scene):
        """
        Run the main loop of the program.
        :param fps: frames per second
        :param starting_scene: the starting scene of the game
        """
        # Initialize Pygame objects
        pg.init()
        screen = pg.display
        clock = pg.time.Clock()
        pg.display.set_caption('LAND OR DIE')

        # Set the active scene to the starting scene
        active_scene = starting_scene

        # If there is an active scene start program loop
        while active_scene is not None:
            # Variable to check for keys being pressed or held down
            pressed_keys = pg.key.get_pressed()

            filtered_events = []  # Event filtering
            for event in pg.event.get():
                quit_attempt = False
                if event.type == pg.QUIT:  # If the player presses the 'X' button
                    quit_attempt = True
                # If the player presses the 'Esc' button
                # or tries the 'Alt+F4' key combination
                elif event.type == pg.KEYDOWN:
                    alt_pressed = pressed_keys[pg.K_LALT] or \
                                  pressed_keys[pg.K_RALT]
                    if event.key == pg.K_ESCAPE:
                        quit_attempt = True
                    elif event.key == pg.K_F4 and alt_pressed:
                        quit_attempt = True
                if quit_attempt:  # On player trying to quit
                    active_scene.terminate()  # Terminate the program loop
                else:
                    filtered_events.append(event)  # Add the events into the filtered list

            # Pass the list of events and pressed keys for processing by the current scene
            active_scene.process_input(filtered_events, pressed_keys)

            # Render current scene's objects to the screen
            active_scene.render(screen)

            # Switch the scene after exiting the current scene loop
            prev_scene = active_scene
            active_scene = active_scene.next
            prev_scene.next = prev_scene

            # Update the display
            pg.display.flip()
            clock.tick(fps)

# Initiate the program loop with the first scene
myGame = Game()


# coding: utf-8

# In[3]:

import pandas as pd
import time
import os
import sys
import random
from IPy import IP,IPSet

# 将forwarding-table.txt读入为df_all
# 将df_all每个条目生成一条IP
# 组成ipset_test
#
# 从中随机抽取size个条目作为df_sub
# 将df_sub的条目组成为ipset_sub
# 输出为sub-table.txt(格式同forwarding-table.txt)
#
# 求ipset_test & ipset_sub ，输入match_i.txt
# 求ipset_test - ipset_sub ，输入notmatch_i.txt
#
# c运行match_i.txt，输出match_o.txt
# c运行notmatch_i.txt，输出notmatch_o.txt
#
# 比较match_o.txt和match_i.txt是否相等
# 看notmatch_o.txt是否为空

# In[48]:

size = 30000
random.seed(time.time())

# In[49]:

df_all = pd.read_csv('./test_file/forwarding-table.txt',sep=' ')
df_sub = df_all.sample(n=size)

# In[50]:

#创建c读取的用来建立路由表的subtable.txt
df_sub.to_csv('./test_file/subtable_%d.csv'%size)
with open('./test_file/subtable_%d.csv'%size,'r')as f_csv,open('./test_file/subtable_%d.txt'%size,'w') as f_txt:
    csv = f_csv.readlines()[1:]
    txt = ''.join([' '.join(line.split(',')[1:]) for line in csv])
    f_txt.write(txt)

# In[51]:

#将读入数据创建为IP对象
print('creating IP object')
ipset_all_list = [IP(df_all.iloc[i]['ip']+'/%d'%df_all.iloc[i]['mask_len']) for i in range(len(df_all))]
ipset_sub_list = [IP(df_sub.iloc[i]['ip']+'/%d'%df_sub.iloc[i]['mask_len']) for i in range(len(df_sub))]

# In[52]:

#创建测试集
print('creating ipset_test_list')
ipset_test_list = [ip[random.randint(0,len(ip)-1)] for ip in ipset_all_list]

print('creating ipset_test')
ipset_test = IPSet(ipset_test_list)
print('creating ipset_sub')
ipset_sub  = IPSet(ipset_sub_list)

print('creating match')
match    = ipset_test & ipset_sub
print('creating notmatch')
notmatch = ipset_test - ipset_sub
print('data set success')

# In[61]:

#输出创建好的测试集
for s,file_name in zip([match,notmatch],['./test_file/match_i_%d.txt'%size,'./test_file/notmatch_i_%d.txt'%size]):
    with open(file_name,'w') as f:
        print(file_name)
        txt = ['%x\n'%ip.int() for ip in list(s)]
        f.write(''.join(txt))

# In[63]:

#运行程序
print('gcc t.c -g -o t')
os.system('gcc t.c -g -o t')

subtable   = './test_file/subtable_%d.txt'%size
match_i    = './test_file/match_i_%d.txt'%size
notmatch_i = './test_file/notmatch_i_%d.txt'%size
match_o    = './test_file/match_o_%d.txt'%size
notmatch_o = './test_file/notmatch_o_%d.txt'%size

os.system('./t -subtable %s -match_i %s -match_o %s -notmatch_i %s -notmatch_o %s'              %(subtable,    match_i,    match_o,    notmatch_i,    notmatch_o))

# In[ ]:

#测试运行结果
with open(match_i,'r') as fmi, open(match_o,'r') as fmo:
    if fmi.read() == fmo.read():
        print('match test: succcess')
    else:
        print('match test: fail')

with open(notmatch_o,'r') as fnmo:
    if fnmo.read() == '':
        print('notmatch test: success')
    else:
        print('notmatch test: fail')


# Run in PyCharm
import random
from math import *

def fitness_score(population_array, city_list):
   # city_list = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio",
   #              "San Diego", "Dallas", "San Jose", "Austin", "Charlotte", "Denver", "Seattle", "Portland",a
   #              "Miami", "Atlanta"]
   # NY to LA, to Chicago.... LA to Chicago, to Houston..
                   # NY     LA    Chi   Hous  Phoe  Phi   SAnt  SDi   Dal   SJos  Aus   Cha  Den   Sea   Por    Mia   Atl
   distance_list = [[    0, 2806,  813, 1662, 2519,   95, 1821, 2838, 1578, 3032, 1773,  619, 1882, 2956, 2905, 1371,  873], # NY1
                    [ 2806,    0, 2126, 1667,  479, 2758, 1492,  127, 1453,  340, 1492, 2462, 1183, 1135,  961, 2746, 2174], # LA2
                    [  813, 2126,    0, 1074, 1763,  783, 1233, 2065,  959, 2380, 1154,  788, 1002, 2071, 2137, 1347,  717], # Chicago3
                    [ 1662, 1667, 1074,    0, 1204, 1582,  222, 1537,  260, 1888,  192, 1152, 1084, 2278, 2205, 1473,  793], # Houston4
                    [ 2519,  479, 1763, 1204,    0, 2327, 1216,  405, 1048,  735, 1006, 2051,  790, 1507, 1298, 2378, 1846], # Phoenix5
                    [   95, 2758,  783, 1582, 2327,    0, 1774, 2773, 1514, 2967, 1709,  523, 1765, 2859, 2874, 1219,  800], # Philadelphia6
                    [ 1821, 1492, 1233,  222, 1216, 1774,    0, 1386,  274, 1750,   88, 1228,  945, 2253, 2180, 1538, 1015], # San Antonio7
                    [ 2838,  127, 2065, 1537,  405, 2773, 1386,    0, 1350,  466, 1299, 2384, 1078, 1259, 1085, 2671, 2139], # San Diego8
                    [ 1578, 1453,  959,  260, 1048, 1514,  274, 1350,    0, 1710,  195, 1026,  795, 2100, 2026, 1345,  782], # Dallas9
                    [ 3032,  340, 2380, 1888,  735, 2967, 1750,  466, 1710,    0, 1716, 2669, 1273,  838,  664, 3003, 2431], # San Jose10
                    [ 1773, 1492, 1154,  192, 1006, 1709,   88, 1299,  195, 1716,    0, 1186,  915, 2139, 2066, 1460,  905], # Austin11
                    [  619, 2462,  788, 1152, 2051,  523, 1228, 2384, 1026, 2669, 1186,    0, 1598, 2796, 2755,  786,  245], # Charlotte12
                    [ 1882, 1183, 1002, 1084,  790, 1765,  945, 1078,  795, 1273,  915, 1598,    0, 1363, 1258, 2091, 1430], # Denver13
                    [ 2956, 1135, 2071, 2278, 1507, 2859, 2253, 1259, 2100,  838, 2139, 2796, 1363,    0,  174, 3297, 2635], # Seattle14
                    [ 2905,  961, 2137, 2205, 1298, 2874, 2180, 1085, 2026,  664, 2066, 2755, 1258,  174,    0, 3256, 2594], # Portland15
                    [ 1371, 2746, 1347, 1473, 2378, 1219, 1538, 2671, 1345, 3003, 1460,  786, 2091, 3297, 3256,    0,  730], # Miami16
                    [  873, 2174,  717,  793, 1846,  800, 1015, 2139,  782, 2431,  905,  245, 1430, 2635, 2594,  730,    0]  #Atlanta17
                    ]

   a = -1
   b = -1
   c = -1
   d = -1
   fitness_array = []

   for i in range(len(population_array)):
       total = 0
       for j in range(len(population_array[i])): #0, 1,2 ,3 ,4
           if j + 1 < len(population_array[i]):

               #This gets coordinates for above array
               for x in range(len(city_list)):
                   if population_array[i][j] == city_list[x]:
                       a = x
                   if population_array[i][j+1] == city_list[x]:
                       b = x
                   #End city
                   if population_array[i][len(population_array[i])-1] == city_list[x]:
                       c = x
                   #Start City
                   if population_array[i][0] == city_list[x]:
                       d = x
               #print("Should Have Four of These: ", distance_list[a][b])
               total = total + distance_list[a][b]
               #print("The Four total is: ", total)
       #print("End to Start: ", distance_list[c][d])
       total = total + distance_list[c][d]
       #print("The final total should be: ", total)
       fitness_array.append(total)
   return fitness_array

def crossover (population_array, crossover_chance):
   #pop array sorted so shortest paths are in start of array
   crossover_array = []
   child_array = []
   weighted_array = []
   x = random.randint(0, 100)
   if crossover_chance == 0:
       return population_array
   if x > crossover_chance: #No crossover
       return population_array
   else:
       while len(crossover_array) < len(population_array):
           #CREATE WEIGHTED LIST TO DRAW FROM
           weighted_array.clear()
           i = len(population_array) #number of cities
           x = 0
           #from 0 up to i-1
           while x < len(population_array) : # X goes from 0 to 4
               temporary = [population_array[x]] * i
               weighted_array = weighted_array + temporary
               x += 1
               i -=1
           random.shuffle(weighted_array)

           #Trouble
           draw1 = random.randint(0, len(weighted_array)-1) #Integer
           draw2 = random.randint(0, len(weighted_array)-1) #Integer
           while draw1 == draw2:
               draw2 = random.randint(0, len(weighted_array) - 1)
           parent1 = weighted_array[draw2]
           parent2 = weighted_array[draw1]

           #Random length from random position in parent 1 put in same spot in new array
           #Start with Parent1------------------------------------
           child_array = [None] * len(population_array[0])
           length_segment = random.randint(1, (len(child_array) - 1)) #if len is 5, 5-1=4//Ex segment is 3
           #L4 in 5 cities: goes 0 or 1 //L3 in a 5: goes 0,1,or 2//L2 in a 5 goes 0,1,2,3//L1 goes 01234
           up_to = len(child_array) - length_segment #5 - 3 = 2
           starting_positon = random.randint(0, up_to) #rand from 0 to 2
           #from parent 1, grab starting positon and next length segment
           for y in range(length_segment):
               child_array[starting_positon+y] = parent1[starting_positon+y]

           #PUT PARENT 2 INTO CHILD---------------------------------------------------------------------
           short_parent2 = [x for x in parent2 if x not in child_array]
           #print("New parent2 is:", short_parent2)
           none_positions = []
           for i in range(len(child_array)):
               if child_array[i] == None:
                   none_positions.append(i)
           random.shuffle(none_positions)

           for i in range(len(none_positions)):
               child_array[none_positions[i]] = short_parent2[i]
           #print("This is the Final Child", child_array)
           crossover_array.append(child_array)
       return crossover_array

def mutation (population_array, mutation_rate):
   if mutation_rate == 0:
       return population_array
   #   Each city has a X% chance of being swapped with another random city that's not itself
   for i in range(len(population_array)):
       x = random.randint(0,100)
       if x < mutation_rate:
           y = random.randint(0, len(population_array[i]) - 1)
           j = random.randint(0, len(population_array[i]) - 1)
           while y == j:
               j = random.randint(0, len(population_array[i]) - 1)
           population_array[i][j], population_array[i][y] = population_array[i][y], population_array[i][j]
   return population_array

# MAIN STARTS HERE---------------------------------------------------------------------------------------
city_list = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio",
           "San Diego", "Dallas", "San Jose", "Austin", "Charlotte", "Denver", "Seattle", "Portland",
           "Miami", "Atlanta"]

#Input number of cities
x = 0
while x == 0:
   try:
       num_cities = input("Enter Number of Cities: ")
       num_cities = int(num_cities)
       if num_cities >17 or num_cities < 4:
           print("Number of cities has to be between 4 and 17.")
       else:
           x = 1
   except ValueError:
       print("This is not an interger.")

# Input Populaton Size
x = 0
while x == 0:
   try:
       chosen_population = input("Enter Population Size: ")
       chosen_population = int(chosen_population)
       if chosen_population < 5 or chosen_population >100:
           print("Population needs to be between 5 and 100.")
       else:
           x = 1
   except:
       print("This is not an interger.")

# Input Crossover Chance
x = 0
while x == 0:
   try:
       crossover_chance = input("Enter Crossover Chance: ")
       crossover_chance = float(crossover_chance)
       if crossover_chance < 0 or crossover_chance >100:
           print("Crossover chance needs to be between 0 and 100.")
       else:
           x = 1
   except:
       print("This is not a number.")

# Input Mutation Chance
x = 0
while x == 0:
   try:
       mutation_rate = input("Enter Mutation Chance: ")
       mutation_rate = float(mutation_rate)
       if mutation_rate < 0 or mutation_rate >100:
           print("Mutation Rate needs to be between 0 and 100.")
       else:
           x = 1
   except:
       print("This is not a number.")

#Target Goal
x = 0
while x == 0:
   try:
       target_goal = input("Same best score for how many generations: ")
       target_goal = int(target_goal)
       if target_goal < 0 or target_goal >100000:
           print("Best score needs to be between 0 and 100,000.")
       else:
           x = 1
   except:
       print("This is not a number.")

#----------------------------------------------------------------------------------------------------
#GENERATION ZERO
#Random city has to be assigned a random spot in the array
#2D array with inner array lenght of num_cities and total arrays equal to population
population_array = []
chromosome = [None] * num_cities #Length of chromosome is now 5 of "None"
temp_city_list = city_list[0:num_cities]
pop_length = 0

while pop_length < chosen_population:
   # Random positon in array (0,5) is from 0 to 5, thus num_cities - 1
   rand_pos = random.randint(0,num_cities - 1)
   # Random city from City1 to CityX
   rand_city = temp_city_list[random.randint(0,len(temp_city_list)-1)]
   #Check that space is open and city is not repeated
   #Using temp list will remove cities that are already used
   if chromosome[rand_pos] == None:
       chromosome[rand_pos] = rand_city
       temp_city_list.remove(rand_city)
   if len(temp_city_list) == 0:
       population_array.insert(pop_length, chromosome)
       pop_length += 1
       #Reset chromosome and temp city list
       chromosome = [None] * num_cities
       temp_city_list = city_list[0:num_cities]
pop_length = 0

#------------------------------------------------------------------------------------------
shortest_distance = 9999999
best_route = []
generation_number = 0
best_generation_number=0
best_score_counter = 0
#while loop// one counter for total number of generations//one to say when algorythm is done
   #ie shortest distance doesn't change for 1k generations, 2k generations, 50k generations
while best_score_counter < target_goal:
   if generation_number % 1000 == 0:
       print("Generation: ", generation_number)
   #------------------------------------------------------------------------------------------------------
   #DETERMINE FITNESS - each separate path in total miles
   score = fitness_score(population_array, city_list)
   #print("This is the score: ", score)
   #--------------------------------------------------------------------------
   #SORT FITNESS ARRAY
   sort_score = score.copy()
   sort_score.sort() #Represents shortest to longest path
   placement = []
   #put pop array in same order as sorted score
   for i in range(len(sort_score)):
       for j in range(len(sort_score)):
           if score[i] == sort_score[j]  and j not in placement:
               placement.append(j)

   sorted_population_array = [None] * len(population_array)
   for i in range(len(population_array)):
       sorted_population_array[placement[i]] = population_array[i]

   if sort_score[0] < shortest_distance:
       best_score_counter = 0
       shortest_distance = sort_score[0]
       best_generation_number = generation_number
       print("New Shortest Distance in generation:", generation_number," is: ", shortest_distance, "miles.")
       best_route = sorted_population_array[0]
       print("New Best Route is: ", best_route)

   #--------------------------------------------------------------------------------
   #CROSSOVER
   population_array = crossover(sorted_population_array, crossover_chance)
   #-----------------------------------------------------------------------------

   #MUTATION STEP - For TSP problem, swap two cities
   population_array = mutation(population_array, mutation_rate)
   best_score_counter += 1
   generation_number += 1
print("Shortest Distance Found:", shortest_distance, "miles.")
print("Generation Number: ", best_generation_number)
print("Best Route Found: ", best_route)


from torch import nn
from .cnn_models import CNNcell
from .get_motion import FixRGBchannel
from .fusion import Conv2Linear

class OnlyCNN(nn.Module):
    def __init__(self,
                 num_class,
                 motion_type='RGB',
                 cnn_model='resnet',
                 pool_type='maxpool'):
        super(OnlyCNN, self).__init__()
        self.num_class = num_class
        self.motion_type = motion_type
        self.cnn_model = cnn_model
        self.pool_type = pool_type

        print('-' * 60)
        print("""
                Initializing FAST with base model:
                OnlyCNN Configurations:
                        cnn_model:          {}
                        motion_type:        {}
                        output_num_class:   {}
        """.format(self.cnn_model,
                   self.motion_type,
                   self.num_class))
        print('-' * 60)

        self._prepare_base_model()

    def _prepare_base_model(self):
        # initialize cnn model
        if 'resnet' in self.cnn_model:
            self.cnn_layer1 = CNNcell(16, 16, 32, 2)
            self.cnn_layer2 = CNNcell(32, 32, 64, 2)
            self.cnn_layer3 = CNNcell(64, 64, 256, 2)
            self.cnn_layer4 = CNNcell(256, 256, 512, 2)
        else:
            raise RuntimeError("Not support this type cnn model '{}' yet!"
                               .format(self.cnn_model))
        # initialize motion features model
        if self.motion_type != 'RGB':
            raise RuntimeError("OnlyRNN model just support RGB motion type!")
        self.fix_rgb_channel = FixRGBchannel(3, 8, 16)
        # initialize head layers
        self.conv2linear = Conv2Linear(512, self.num_class, self.pool_type)

    def forward(self, last_cell_info, past_x, next_x):
        # get motion features
        fix_rgb = self.fix_rgb_channel(next_x)
        motion_feature = fix_rgb

        # cnn and rnn layer1 forward
        cnn_layer1_x = self.cnn_layer1(motion_feature)

        # cnn and rnn layer2 forward
        cnn_layer2_x = self.cnn_layer2(cnn_layer1_x)

        # cnn and rnn layer3 forward
        cnn_layer3_x = self.cnn_layer3(cnn_layer2_x)

        # cnn and rnn layer4 forward
        cnn_layer4_x = self.cnn_layer4(cnn_layer3_x)

        # conv to linear layer
        out = self.conv2linear(cnn_layer4_x)

        # collect rnn_cell_info
        rnn_cell_info = last_cell_info
        return out, rnn_cell_info


lst = ["It's over 9000 !", "All", ""]

# print(lst)
# print(memes)

print((filter(None, lst)))
# print(list(filter(lambda x: len(x) > 10, lst)))

def ft_filter(function_to_apply, list_of_inputs):
	if not function_to_apply:
		return (x for x in list_of_inputs if x)
	return (x for x in list_of_inputs if function_to_apply(x))

print((ft_filter(None, lst)))
# print(list(ft_filter(lambda x: len(x) > 10, lst)))


import itertools
from io import BytesIO
from typing import Union

from PIL import Image

from ralgo.exceptions import InvalidArgument, InvalidImage

class SquareDecoder:
    file: Union[str, bytes]

    image: Image
    output: str

    def __load_file(self) -> tuple:
        if isinstance(self.file, str):
            self.image = Image.open(self.file)

            if self.image.size[0] == self.image.size[1]:
                return self.image.size

            raise InvalidImage(message="The given image has an invalid size")

        if isinstance(self.file, bytes):
            self.image = Image.open(BytesIO(self.file))

            return self.image.size

        raise InvalidArgument(
            message="The file must be given by path (str) or bytes (bytes)"
        )

    @staticmethod
    def __color2char(color):
        if sum(color) > 128:
            return ","

        return "."

    def decode(self, file: Union[str, bytes]) -> str:
        self.file = file

        height, weight = self.__load_file()

        self.output = ""

        for x, y in itertools.product(range(height), range(weight)):
            if sum(self.image.getpixel((y, x))) == 0:
                break

            self.output += self.__color2char(self.image.getpixel((y, x)))

        return self.output


import networking_oneview.conf

_opts = [
    ('DEFAULT', networking_oneview.conf.default.opts),
    ('oneview', networking_oneview.conf.oneview.opts)
]

def list_opts():
    """Return a list of oslo.config options available in Networking OneView.

    The returned list includes all oslo.config options. Each element of
    the list is a tuple. The first element is the name of the group, the
    second element is the options.

    The function is discoverable via the 'networking-oneview' entry point under
    the 'oslo.config.opts' namespace.

    The function is used by Oslo sample config file generator to discover the
    options.

    :returns: a list of (group, options) tuples.
    """
    return _opts


import gymnasium
import numpy as np

import mevo

# define a fitness function to get fitness for every individual
def fitness_fn(ind: mevo.individuals.Individual, conf: dict) -> float:
    ep_r = 0
    env = gymnasium.make('CartPole-v1')
    for _ in range(2):
        s, _ = env.reset()
        for _ in range(500):  # in one episode
            logits = ind.predict(s)
            a = np.argmax(logits)
            s, r, done, _, _ = env.step(a)
            ep_r += r
            if done:
                break
    return ep_r

if __name__ == "__main__":
    # training
    with mevo.GeneticAlgoNet(max_size=20, layer_size=[4, 8, 2], drop_rate=0.7, mutate_rate=0.5, n_worker=-1) as pop:
        for generation in range(40):
            pop.evolve(fitness_fn=fitness_fn)
            print(f"generation={generation}, top_fitness={pop.top.fitness:.2f}")

    # deploy the best individual
    env = gymnasium.make('CartPole-v1', render_mode="human")
    while True:
        s, _ = env.reset()
        while True:  # in one episode
            logits = pop.top.predict(s)
            a = np.argmax(logits)
            s, _, done = env.step(a)[:3]
            if done:
                break


import re

def flatten_re(iterable):
    x = re.findall(r'-?\d+', str(iterable))
    return [int(i) for i in x]

def flatten(iterable):
    resp = []
    for item in iterable:
        if isinstance(item, (list, tuple)):
            resp.extend(flatten(item))
        elif item is not None:
            resp.append(item)
    return resp

x = flatten([12,[[[[3,None,8]]]],-14])
print(x)


import pytest

from basilisk import thermal

def test_NetworkMass2():
    """
    that the network mass works correctly
    """
    m = thermal.NetworkMass2()
    m.initialTemperature = 300
    m.c_p = 0.75
    m.mass = 23
    heatMsg = thermal.HeatRateMsgClass()
    m.addIndependentHeatRate(heatMsg.get_reader())

    expected=1
    assert 1 == pytest.approx(expected)

if __name__ == "__main__":
    test_NetworkMass2()


#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import pygame
from typing import List

from .render_context import RenderContext
from .base.inputs import InputEvent, InputManager
from .base.context import Context
from .base.floor import Floor
from .base.room import Room
from .base.sprite import Sprite
from .base.game_constants import SpriteType
from .level_loader import LevelLoader
from .sprites.sidebar import SideBar
from .base.music_manager import MusicManager
from .main_menu import MainMenu

class Game(object):
    def __init__(self, render_context: RenderContext):
        self.running = True
        self.render_context = render_context
        self.input_manager = InputManager()
        self.clock = pygame.time.Clock()
        self.current_floor: Floor = None
        self.current_room: Room = None
        self.floors: List[Floor] = []
        self.context = Context()
        self.context.render_context = self.render_context
        self.sidebar: SideBar = SideBar()

        # print("Scale acceleration: " + pygame.transform.get_smoothscale_backend())

    def load(self):
        Sprite._update_render_context(self.render_context)
        menu = MainMenu.create_menu()
        self.floors = LevelLoader().load_levels()
        self.floors.append(menu)
        self.current_floor = menu
        self.current_room = self.current_floor.initial_room
        self.sidebar = SideBar()
        MusicManager.playmusic(self.current_room.music)
        if not self.current_floor.menu:
            self.current_room.sprites.append(self.sidebar)

    def set_floor(self, floor_name):
        was_menu = self.current_floor.menu
        for floor in self.floors:
            if floor.name == floor_name:
                self.current_floor = floor
        if not was_menu and not self.current_floor.menu:
            for player in self.current_room.sprites.find_by_type(SpriteType.PLAYER):
                self.current_floor.take_player_properties(player)

        self.set_room(self.current_floor.initial_room.name)

    def set_room(self, room_name):
        self.current_room = self.current_floor.get_room(room_name)
        MusicManager.playmusic(self.current_room.music)
        self.context.block_doors = True
        if not self.current_floor.menu:
            self.current_room.sprites.append(self.sidebar)

    def update(self):
        events = pygame.event.get()
        event_set = self.input_manager.get_events(events)

        for event in event_set:
            if event == InputEvent.QUIT:
                self.running = False

        for event in events:
            if event.type == pygame.VIDEORESIZE:
                self.render_context.resize(event.dict['size'])
                Sprite._update_render_context(self.render_context)

        if self.context.change_room is not None:
            player = self.current_room.remove_player()
            self.set_room(self.context.change_room)
            self.current_room.add_player(player)
            self.context.change_room = None

        if self.context.change_level is not None:
            if self.context.change_level == "exit":
                self.running = False
                return
            self.set_floor(self.context.change_level)
            self.context.change_level = None

        self.context.input_events = event_set
        self.context.sprites = self.current_room.sprites

        for sprite in self.context.sprites:
            sprite.update(self.context)
            if self.context.lost:
                self.context.lost = False
                self.load()
                self.set_floor("main_menu")
                return

    def render(self):
        self.render_context.screen.fill((200, 200, 100))
        for sprite in self.context.sprites.by_z_index:
            img = sprite.image
            rect = sprite.rect
            if img is None or rect is None:
                continue
            self.render_context.screen.blit(img, rect)

    def game(self):
        self.load()

        while self.running:
            self.update()
            self.render()

            self.context.delta_t = self.clock.tick(60)
            pygame.display.update()


# Problem 69
# Answer: 510510

def gcd(a,b):
    if a == 0:
        return b
    return gcd(b % a, a)

def phi(n):
    count = n
    p = 2
    while(p*p <= n):
        if n % p == 0:
            while n % p == 0:
                n = n//p
            count *= 1.0 - (1.0/float(p))
        p += 1

    if n > 1:
        count *= 1.0 - (1.0/float(n))

    return int(count)

def main():
    maxResult = 0
    maxNum = 0
    for i in range(1, 1000000):
        p = i/phi(i)
        if p > maxResult:
            maxResult = p
            maxNum = i
    return maxNum

print(main())


# https://www.codewars.com/kata/5efae11e2d12df00331f91a6
import hashlib

def crack(hash):
    hash = bytes.fromhex(hash)
    print(hash)

    for i in range(0, 99999):
        res = hashlib.md5(("%05d" % i).encode())
        if res.digest() == hash:
            return "%05d" % i


#!/usr/bin/env python3
import sys
import os
sys.path.insert(0, os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "lib"
))
from lottie.utils import script
from lottie import objects
from lottie import Point, Color

last_frame = 180
an = objects.Animation(last_frame)

layer = objects.ShapeLayer()
an.add_layer(layer)

group = layer.add_shape(objects.Group())

star = group.add_shape(objects.Star())
star.inner_radius.value = 40
star.outer_radius.value = 100
star.position.value = Point(256, 256)

star = group.add_shape(objects.Star())
star.inner_radius.value = 20
star.outer_radius.value = 50
star.position.value = Point(256, 256)

round = layer.add_shape(objects.RoundedCorners())
round.radius.add_keyframe(0, 0)
round.radius.add_keyframe(last_frame/2, 30)
round.radius.add_keyframe(last_frame, 0)

stroke = group.add_shape(objects.Stroke(Color(1, 1, 0), 10))

script.script_main(an)


from string import lower
from xml.sax.saxutils import escape
from django.utils.translation import ugettext as _

from datawinners.utils import is_empty_string
from mangrove.datastore.documents import GroupDocument
from mangrove.datastore.group import Group
from mangrove.errors.MangroveException import DataObjectNotFound
from mangrove.utils.types import is_empty

def get_group_details(dbm):
    group_details = []
    rows = dbm.load_all_rows_in_view('group_by_name')
    for row in rows:
        group_details.append({'name': escape(row['value']['name'])})
    return group_details

def check_uniqueness_of_group(dbm, group_name):
    rows = dbm.load_all_rows_in_view('group_by_name', key=lower(group_name))
    if len(rows) > 0:
        return False
    return True

def get_group_by_name(dbm, group_name):
    rows = dbm.load_all_rows_in_view('group_by_name', key=lower(group_name))
    if is_empty(rows):
        raise DataObjectNotFound('group', "Group not found")
    doc = GroupDocument.wrap(rows[0]['value'])
    return Group.new_from_doc(dbm, doc)

def create_new_group(dbm, group_name):
    if group_name.lower() in ["all contacts", "tous les contacts"]:
        return False, _("Group with same name already exists.")

    is_unique = check_uniqueness_of_group(dbm, group_name)
    if is_empty_string(group_name):
        return False, _('Group name is empty')
    if is_unique and not is_empty_string(group_name):
        new_group = Group(dbm, group_name)
        new_group.save()
        return True, _("Group <b>%s</b> successfully added.") % escape(group_name)
    return False, _("Group with same name already exists.")