import numpy as np
import pygame
import Fonts

class Window(pygame.sprite.Sprite):
    """Окно, появляющиеся внутри главного окна симуляции"""

    def __init__(self, position: np.array, size: np.array):
        """Инициализация окна"""
        super().__init__()
        self.Size = size;
        self.image = pygame.Surface((size[0], size[1]), pygame.SRCALPHA, 32).convert_alpha()
        self._top_border = pygame.Surface((size[0], 1), pygame.SRCALPHA, 32).convert_alpha()
        self._left_border = pygame.Surface((1, size[1]), pygame.SRCALPHA, 32).convert_alpha()#
        self._right_border = pygame.Surface((1, size[1]), pygame.SRCALPHA, 32).convert_alpha()
        self._bottom_border:pygame.Surface = pygame.Surface((size[0], 1), pygame.SRCALPHA, 32).convert_alpha()
        self.color = (0, 0, 0, 255)
        self._top_border.fill(self.color)
        self._left_border.fill(self.color)
        self._right_border.fill(self.color)
        self._bottom_border.fill(self.color)

        self.rect = self.image.get_rect()
        self.rect.left = position[0]
        self.rect.top = position[1]
        self._show:bool = True

    @property
    def Show(self):
        """Определяет, показывать ли элемент"""
        return self._show
    @Show.setter
    def Show(self, value:bool):
        self._show = bool(value)
        if self._show:
            self.image.set_alpha(255)
        else:
            self.image.set_alpha(0)

    def Border(self):
        """Рисование рамки вокруг окна."""
        monitor_info = pygame.display.Info()
        self.image.blit(self._top_border, (0,0))
        self.image.blit(self._left_border, (0,0))
        self.image.blit(self._right_border, (self.Size[0]-1, 0))
        self.image.blit(self._bottom_border, (0,self.Size[1]-1))

class PauseWindow(Window):
    """Выдаёт окно паузы"""
    def __init__(self):
        monitor_info = pygame.display.Info()
        width = 200
        height = 70
        super().__init__(np.array([(monitor_info.current_w-width) / 2, (monitor_info.current_h-height) / 2]), np.array([width, height]))
        self.image.fill((0, 0, 0, 120))#0x00000078
        Label = Fonts.LargeFont.render('Пауза', True, (255, 255, 255, 255))
        self.image.blit(Label, ((width - Label.get_width()) / 2, (height - Label.get_height()) / 2))
        self.Border()

class AliveCountWindow(Window):
    '''Выдаёт окно, считающее количество животных и растений всего и каждого вида'''
    def __init__(self):
        monitor_info = pygame.display.Info()
        self._plants_count:int = 0
        self._turtles_count:int = 0
        self._wolves_count:int = 0
        self._rabbit_count:int = 0
        self._animals_count:int = 0
        self._NeedRefresh:bool = False
        self._plants =  Fonts.MainFont.render('Растений:' + str(self._plants_count), True, (255, 255, 255, 255))
        self._turtles = Fonts.MainFont.render('Черепах:' + str(self._plants_count), True, (255, 255, 255, 255))
        self._wolves = Fonts.MainFont.render('Волков:'  + str(self._wolves_count), True, (255, 255, 255, 255))
        self._rabbits = Fonts.MainFont.render('Кроликов:'  + str(self._rabbit_count), True, (255, 255, 255, 255)) #из Террарии
        self._animals = Fonts.MainFont.render('Животных:'  + str(self._animals_count), True, (255, 255, 255, 255))
        self.width = max(self._plants.get_width(), self._turtles.get_width(), self._wolves.get_width(), self._rabbits.get_width()) + 20
        self.height = int(self._plants.get_height()) + int(self._turtles.get_height()) + int(self._wolves.get_height()) + int(self._rabbits.get_height()) + 10 + self._animals.get_height()
        super().__init__(np.array([10, monitor_info.current_h - self.height - 10]), np.array([self.width, self.height]))
        self.Refresh()

    @property
    def PlantsCount(self):
        return self._plants_count
    @PlantsCount.setter
    def PlantsCount(self, value:int):
        try:
            value = int(value)
        except:
            print("AliveCountWindow.PlantsCount не является целым числом")
            return
        if self._plants_count != value:
            self._plants_count = value
            self._plants = Fonts.MainFont.render('Растений: ' + str(self._plants_count), True, (255, 255, 255, 255))
            self._NeedRefresh = True

    @property
    def AnimalsCount(self):
        return self._animals_count
    @AnimalsCount.setter
    def AnimalsCount(self, value:int):
        try:
            value = int(value)
        except:
            print("AliveCountWindow.AnimalsCount не является целым числом")
            return

        if self._animals_count != value:
            self._animals_count = value
            self._animals = Fonts.MainFont.render('Животных: ' + str(self._animals_count), True, (255, 255, 255, 255))
            self._NeedRefresh = True

    @property
    def WolvesCount(self):
        return self._wolves_count
    @WolvesCount.setter
    def WolvesCount(self, value:int):
        try:
            value = int(value)
        except:
            print("AliveCountWindow.WolvesCount не является целым числом")
            return

        if self._wolves_count != value:
            self._wolves_count = value
            self._wolves = Fonts.MainFont.render('Волков: ' + str(self._wolves_count), True, (255, 255, 255, 255))
            self._NeedRefresh = True

    @property
    def RabbitsCount(self):
        return self._rabbit_count
    @RabbitsCount.setter
    def RabbitsCount(self, value:int):
        try:
            value = int(value)
        except:
            print("AliveCountWindow.RabbitsCount не является целым числом")
            return

        if self._rabbit_count != value:
            self._rabbit_count = value
            self._rabbits = Fonts.MainFont.render('Кроликов: ' + str(self._rabbit_count), True, (255, 255, 255, 255))
            self._NeedRefresh = True

    @property
    def TurtlesCount(self):
        return self._turtles_count
    @TurtlesCount.setter
    def TurtlesCount(self, value:int):
        try:
            value = int(value)
        except:
            print("AliveCountWindow.TurtlesCount не является целым числом")
            return

        if self._turtles_count != value:
            self._turtles_count = value
            self._turtles = Fonts.MainFont.render('Черепах: ' + str(self._turtles_count), True, (255, 255, 255, 255))
            self._NeedRefresh = True

    def Refresh(self):
        if self._NeedRefresh:
            self.image.fill((0, 0, 0, 120)) #0x00000078
            self.image.blit(self._animals, ((self.width - self._animals.get_width()) / 2, (self.height - self._animals.get_height()) / 10))
            self.image.blit(self._plants, ((self.width - self._plants.get_width()) / 2, (self.height - self._plants.get_height()) / 3.3))
            self.image.blit(self._turtles, ((self.width - self._turtles.get_width()) / 2, (self.height - self._turtles.get_height()) / 2))
            self.image.blit(self._wolves, ((self.width - self._wolves.get_width()) / 2, (self.height - self._wolves.get_height()) / 1.4))
            self.image.blit(self._rabbits, ((self.width - self._rabbits.get_width()) / 2, (self.height - self._rabbits.get_height()) / 1.1))
            self.Border()
        self._NeedRefresh = False

    def SetValue(self, value, count, name):
        Label = None
        if count != value:
            Lable = Fonts.MainFont.render(name + ': ' + str(value), True, (255, 255, 255, 255))
            self._NeedRefresh = True

        return Lable

class StepsWindow(Window):
    """Показывает колличество ходов, прошедших с начала запуска"""

    def __init__(self):
        monitor_info = pygame.display.Info()
        Label = Fonts.MainFont.render('Ходов: 0', True, (255, 255, 255, 255))
        Label2 = Fonts.MainFont.render('Время: 0 д. 00:00', True, (255, 255, 255, 255))
        self.d_h = 4
        self.width = 150
        self.height = Label.get_height() + Label2.get_height() + self.d_h * 3
        self._count:int = 0
        super().__init__(np.array([10, 10]), np.array([self.width, self.height]))
        self.image.fill((0, 0, 0, 120))
        self.image.blit(Label, ((self.width - Label.get_width()) / 2, self.d_h))
        self.image.blit(Label2,  ((self.width - Label2.get_width()) / 2, self.d_h * 2 + Label.get_height()))

    @property
    def Count(self):
        """Количество ходов"""
        return self._count
    @Count.setter
    def Count(self, value:int):
        try:
            value = int(value)
        except:
            print("StepsWindow.Count не является целым числом")
            return

        self._count = value
        self._count1 = value
        self._count2 = int(self._count1 / 60)
        self._count1 = self._count1 - self._count2 * 60
        self._count3 = int(self._count2 / 24)
        self._count2 = self._count2 - self._count3 * 24

        hours = "0" + str(self._count2) if self._count2 < 10 else str(self._count2)
        minutes  = "0" + str(self._count1) if self._count1 < 10 else str(self._count1)

        self.image.fill((0, 0, 0, 120))
        Label = Fonts.MainFont.render('Ходов: '+str(self._count), True, (255, 255, 255, 255))
        Label2 = Fonts.MainFont.render('Время: '+str(self._count3) + "д. " + hours + ":" + minutes, True, (255, 255, 255, 255))

        self.image.blit(Label, ((self.width - Label.get_width()) / 2, self.d_h))
        self.image.blit(Label2,  ((self.width - Label2.get_width()) / 2, self.d_h * 2 + Label.get_height()))

        self.Border()

class BiomassCount(Window):
    def __init__(self):
        self._all_bio_count = 0.
        self._animals_bio_count = 0.
        self._plants_bio_count = 0.
        monitor_info = pygame.display.Info()

        self._total_label = Fonts.MainFont.render('общ кол-во биомассы:', True, (255, 255, 255, 255))
        self._animals_label = Fonts.MainFont.render('общ кол-во биомассы животного:', True, (255, 255, 255, 255))
        self._plants_label = Fonts.MainFont.render('общ кол-во биомассы растения: ' + str(self._plants_bio_count), True, (255, 255, 255, 255))

        self.width = 300
        self.height = 10 * 4 + self._total_label.get_height() + self._animals_label.get_height() + self._plants_label.get_height()
        super().__init__(np.array([monitor_info.current_w - self.width - 10, 10]), np.array([self.width, self.height]))
        self.Refresh()

    def Refresh(self):
        self._total_label = Fonts.MainFont.render('общ кол-во биомассы: ' + str(self._all_bio_count), True, (255, 255, 255, 255))
        self._animals_label = Fonts.MainFont.render('общ кол-во биомассы животного: ' + str(self._animals_bio_count), True, (255, 255, 255, 255))
        self._plants_label = Fonts.MainFont.render('общ кол-во биомассы растения: ' + str(self._plants_bio_count), True, (255, 255, 255, 255))
        self.image.fill((0, 0, 0, 120))
        self.image.blit(self._total_label, ((self.width - self._total_label.get_width()) / 2, 10))
        self.image.blit(self._animals_label, ((self.width - self._animals_label.get_width()) / 2, 10 * 2 + self._total_label.get_height()))
        self.image.blit(self._plants_label, ((self.width - self._plants_label.get_width()) / 2, 10 * 3 + self._total_label.get_height() + self._animals_label.get_height()))
        self.Border()

    @property
    def All_Bio_Count(self):
        return int(self._all_bio_count)

    @All_Bio_Count.setter
    def All_Bio_Count(self, value: float):
        try:
            value = float(value)
        except:
            print("BiomassCount.All_Bio_Count не является float")
            return
        self._all_bio_count = int(value)
        self.image.fill((0, 0, 0, 120))
        Label = Fonts.MainFont.render('общ кол-во биомассы: ' + str(self._all_bio_count), True, (255, 255, 255, 255))
        self.image.blit(Label, ((self.width - Label.get_width()) / 2, (self.height - Label.get_height()) / 2))

    @property
    def Animal_Bio_Count(self):
        return self._animals_bio_count

    @Animal_Bio_Count.setter
    def Animal_Bio_Count(self, value: float):
        try:
            value = float(value)
        except:
            print("BiomassCount.All_Bio_Count не является float")
            return
        self._animals_bio_count = int(value)
        self.image.fill((0, 0, 0, 120))
        Label = Fonts.MainFont.render('общ кол-во биомассы животного: ' + str(self._animals_bio_count), True,
                                      (255, 255, 255, 255))
        self.image.blit(Label, ((self.width - Label.get_width()) / 2, (self.height - Label.get_height()) / 2))

    @property
    def Plants_Bio_Count(self):
        return int(self._plants_bio_count)

    @Plants_Bio_Count.setter
    def Plants_Bio_Count(self, value: float):
        try:
            value = float(value)
        except:
            print("")
            return
        self._plants_bio_count = int(value)
        self.image.fill((0, 0, 0, 120))
        Label = Fonts.MainFont.render('общ кол-во биомассы растения: ' + str(self._plants_bio_count), True,
                                      (255, 255, 255, 255))
        self.image.blit(Label, ((self.width - Label.get_width()) / 2, (self.height - Label.get_height()) / 2))

class BiomassCountAnimal(Window):
    def __init__(self):
        self._animals_bio_count = 0.
        monitor_info = pygame.display.Info()
        Label = Fonts.MainFont.render('общ кол-во биомассы животного:', True, (255, 255, 255, 255))
        self.width = 300
        self.height = 20
        super().__init__(np.array([monitor_info.current_w - self.width - 10, 30]),np.array([self.width, self.height]))
        self.image.fill((0, 0, 0, 120))
        self.image.blit(Label, ((self.width - Label.get_width()) / 2, (self.height - Label.get_height()) / 2))

class BiomassCountPlants(Window):
    def __init__(self):
        self._plants_bio_count = 0.
        monitor_info = pygame.display.Info()
        Label = Fonts.MainFont.render('общ кол-во биомассы растения:', True, (255, 255, 255, 255))
        self.width = 300
        self.height = 20
        super().__init__(np.array([monitor_info.current_w - self.width - 10, 50]), np.array([self.width, self.height]))
        self.image.fill((0, 0, 0, 120))
        self.image.blit(Label, ((self.width - Label.get_width()) / 2, (self.height - Label.get_height()) / 2))

class Region(Window):
    '''базовый класс области'''
    def __init__(self,position: np.array, size: np.array):
        self._specific_increase = 0.
        super().__init__(position,size)
    @property
    def Specific_Increase(self):
        return self._specific_increase
    @Specific_Increase.setter
    def Specific_Increase(self,value: float):
        try:
            self._specific_increase=float(value)
        except:
            print("Region.Specific_Increase не является float")

class Button(Window):
    """Кнопка"""

    def __init__(self, position: np.array, size: np.array):
        """Инициализация кнопки"""

        # Цвета кнопки
        self._main_color = (0, 0, 0, 120)
        self._mouse_on_color = (50, 50, 50, 120)
        self._pressed_color = (0, 0, 0, 200)
        self._color = self._main_color

        # Состояния кнопки
        self._pressed:bool = False;

        self._text:str = ""
        self.width:int = size[0]
        self.height:int = size[1]
        super().__init__(position, size)
        self._TextElement = Fonts.MainFont.render(self._text, True, (255, 255, 255, 255))
        self.Paint()

        self.Click = self.DoNothing

    @property
    def Color(self):
        """Текущий цвет кнопки"""
        return self._color
    @Color.setter
    def Color (self, value):
        if self._color == value:
            return
        self._color = value
        self.Paint()

    @property
    def Text (self):
        """Текст на кнопке"""
        return self._text
    @Text.setter
    def Text (self, value:str):
        try:
            value = str(value)
        except:
            "Button.Text – ошибка преобразования значения в строку"
        self._text = value
        self._TextElement = Fonts.MainFont.render(self._text, True, (255, 255, 255, 255))
        self.Paint()

    def MouseMotion(self, cursor):
        """Изменение при движении мыши"""
        if self.rect.collidepoint(cursor):
            self.Color = self._pressed_color if self._pressed else self._mouse_on_color
        else:
           self.Color = self._main_color

    def MouseDown(self, cursor):
        """Изменения при нажатии на кнопку мыши"""
        if self.rect.collidepoint(cursor):
            self.Color = self._pressed_color
            self._pressed = True

    def MouseUp(self, cursor):
        """Изменения при отпускании кнопки мыши"""
        if self.rect.collidepoint(cursor):
            self.Color = self._mouse_on_color
            if self._pressed:
                self.Click()
        else:
            self.Color = self._main_color
        self._pressed = False

    def Paint(self):
        """Отрисовка кнопки"""
        self.image.fill(self._color)#0x00000078
        self.image.blit(self._TextElement, ((self.width - self._TextElement.get_width()) / 2, (self.height - self._TextElement.get_height()) / 2))
        self.Border()

    def DoNothing(self):
        pass

class Clickable():
    """ Группа кликабельных элементов"""
    def __init__(self):
        self.items = list()

    def add(self, item):
        """Добавление элемента"""
        self.items.append(item)

    def MouseDown(self, point):
        """Обработка нажатия мыши для всех элементов"""
        for element in self.items:
            element.MouseDown(point)

    def MouseUp(self, point):
        """Обработка отпускания мыши для всех элементов"""
        for element in self.items:
            element.MouseUp(point)

    def MouseMove(self, point):
        """Обработка движения мыши для всех элементов"""
        for element in self.items:
            element.MouseMotion(point)


"""Implementation of the validation step for the service limits module."""
from optiframe import ValidationTask

from cloud_resource_matcher.modules.base import BaseData

from .data import ServiceLimitsData

class ValidationServiceLimitsTask(ValidationTask):
    """A task to validate the data for the service limits module."""

    base_data: BaseData
    service_limits_data: ServiceLimitsData

    def __init__(self, base_data: BaseData, service_limits_data: ServiceLimitsData):
        self.base_data = base_data
        self.service_limits_data = service_limits_data

    def validate(self) -> None:
        """Validate the data for consistency.

        :raises AssertionError: When the data is not valid.
        """
        # Validate cs_to_instance_limit
        for (cs, instances) in self.service_limits_data.cs_to_instance_limit.items():
            assert (
                cs in self.base_data.cloud_services
            ), f"{cs} in cs_to_instance_limit is not a valid CS"
            assert instances >= 0, f"Negative max instance count {instances} for CS {cs}"

        # Validate cr_to_max_instance_demand
        for cr, max_instance_demand in self.service_limits_data.cr_to_max_instance_demand.items():
            assert (
                cr in self.base_data.cloud_resources
            ), f"{cr} in cr_to_max_instance_demand is not a valid CR"
            assert (
                max_instance_demand >= 0
            ), f"Negative max instance demand {max_instance_demand} for CR {cr}"

            total_instance_demand = self.base_data.cr_to_instance_demand[cr]

            assert max_instance_demand <= total_instance_demand, (
                f"The maximum instance demand {max_instance_demand} for CR {cr}"
                f" cannot be larger than the total instance demand {total_instance_demand}"
            )

        for cr in self.base_data.cloud_resources:
            assert (
                cr in self.service_limits_data.cr_to_max_instance_demand.keys()
            ), f"CR {cr} does not have a maximum instance demand specified"


# it ain't pretty but it works ¯\_(ツ)_/¯ #

import numpy as np
from numpy.core.fromnumeric import shape
import copy

with open('input.txt') as f:
    input = f.readlines()

input = list(map(lambda line:line.replace("\n",""),input))
input = list(map(lambda line:list(map(int,line)),input))
input = np.array(input)

risk_levels = np.zeros(shape=np.shape(input))
for iRow in range(np.shape(input)[0]):
    for jCol in range(np.shape(input)[1]):
        higher_or_equal_count = 0

        for rowOffset in range(-1,2):
            for colOffset in range(-1,2):

                if (rowOffset == colOffset) or (rowOffset == -colOffset):
                    continue

                rowIndex = iRow+rowOffset
                if rowIndex < 0 or rowIndex > np.shape(input)[0]-1:
                    continue

                colIndex = jCol+colOffset
                if colIndex < 0 or colIndex > np.shape(input)[1]-1:
                    continue

                if input[iRow,jCol] >= input[rowIndex,colIndex]:
                    higher_or_equal_count += 1

        if higher_or_equal_count == 0:
            risk_levels[iRow,jCol] = input[iRow,jCol] + 1

print(np.sum(risk_levels))

risk_levels[risk_levels != 0] = -1
arrays_equal = False
old_risklevels = copy.deepcopy(risk_levels)
new_risklevels = copy.deepcopy(risk_levels)
while not arrays_equal:
    for iRow in range(np.shape(input)[0]):
        for jCol in range(np.shape(input)[1]):
            for rowOffset in range(-1,2):
                for colOffset in range(-1,2):
                    if old_risklevels[iRow,jCol] != -1:
                        # only check the -1 since they need exploring
                        continue

                    if (rowOffset == colOffset) or (rowOffset == -colOffset):
                        continue

                    rowIndex = iRow+rowOffset
                    if rowIndex < 0 or rowIndex > np.shape(input)[0]-1:
                        continue

                    colIndex = jCol+colOffset
                    if colIndex < 0 or colIndex > np.shape(input)[1]-1:
                        continue

                    """
                    if old_risklevels[rowIndex,colIndex] < 0:
                        # don't compare to -1 and -2
                        continue
                    """

                    if input[rowIndex,colIndex] > input[iRow,jCol]:
                        if input[rowIndex,colIndex] != 9:
                            new_risklevels[rowIndex,colIndex] = -1

            #if old_risklevels[iRow,jCol] == -1:
            #    new_risklevels[iRow,jCol] = -2

    arrays_equal = np.array_equal(old_risklevels,new_risklevels)
    old_risklevels = copy.deepcopy(new_risklevels)

basin_id = -3
id_risklevels = copy.deepcopy(new_risklevels)
prev_id_risklevels = copy.deepcopy(id_risklevels)
all_idd = False
while not all_idd:
    for iRow in range(np.shape(input)[0]):
        for jCol in range(np.shape(input)[1]):

            if  id_risklevels[iRow,jCol] >= 0:
                # not part of basin
                continue

            neighbour_vals = []

            for rowOffset in range(-1,2):
                for colOffset in range(-1,2):

                    if (rowOffset == colOffset) or (rowOffset == -colOffset):
                        continue

                    rowIndex = iRow+rowOffset
                    if rowIndex < 0 or rowIndex > np.shape(input)[0]-1:
                        continue

                    colIndex = jCol+colOffset
                    if colIndex < 0 or colIndex > np.shape(input)[1]-1:
                        continue

                    neighbour_vals.append(id_risklevels[rowIndex,colIndex])

            min_val = min(neighbour_vals)
            if min_val >= -2:
                # no ID yet assigned to this basin
                id_risklevels[iRow,jCol] = basin_id
                if basin_id == -19:
                    x = 5
                basin_id -= 1
            else:
                id_risklevels[iRow,jCol] = min_val

    all_idd = np.array_equal(prev_id_risklevels,id_risklevels)
    prev_id_risklevels = copy.deepcopy(id_risklevels)

(unique, counts) = np.unique(id_risklevels, return_counts=True)
frequencies = np.asarray((unique, counts)).T

print(np.prod(np.flip(np.sort(counts))[1:4]))


import os
import yaml

PROJECT_ROOT = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + "/../../")

def check_unit_testing_module_enabled():
    yaml_file = PROJECT_ROOT + "/west.yml"
    with open(yaml_file, "r") as stream:
        yml = yaml.safe_load(stream)
        unity = next(
            (x for x in yml["manifest"]["projects"] if x["name"] == "testing"), None
        )
        if not unity:
            raise BaseException("You need to add unity project to west.yml")

        expected_testing_path = "modules/test/testing"
        if unity["path"] != expected_testing_path:
            raise BaseException(
                "Please place testing repo under %s" % (expected_testing_path)
            )


import PySimpleGUI as sg
from datetime import date
from model.Funcionario import Funcionario
from utils.Validators import Validators
from utils.Formatters import Formatters
from view.AbstractTela import AbstractTela
from messages.Funcionarios import mensagens

class TelaFuncionarioCadastro(AbstractTela):
    def __init__(self, controlador):
        sg.ChangeLookAndFeel('Reddit')

        super().__init__(controlador, nome_tela='Funcionários')

    def init_components(self, modo_edicao, data: Funcionario):
        layout = super().layout_tela_cadastro([
            {
                'key': 'nome_funcionario',
                'label': mensagens.get('label_nome'),
                'type': 'text',
                'default_text': '' if modo_edicao == False else data.nome,
                'disabled': modo_edicao
            },
            {
                'key': 'email',
                'label': mensagens.get('label_email'),
                'type': 'text',
                'default_text': '' if modo_edicao == False else data.email
            },
            {
                'key': 'telefone',
                'label': mensagens.get('label_telefone'),
                'type': 'text',
                'default_text': '' if modo_edicao == False else data.telefone
            },
            {
                'key': 'cpf',
                'label': mensagens.get('label_cpf'),
                'type': 'text',
                'default_text': '' if modo_edicao == False else data.cpf,
                'disabled': modo_edicao
            },
            {
                'key': 'salario',
                'label': mensagens.get('label_salario'),
                'type': 'text',
                'default_text': '' if modo_edicao == False else data.salario
            },
        ], modo_edicao)

        super().set_tela_layout(layout, size=(300, 400))

    def abrir_tela(self, modo_edicao, data: Funcionario):
        self.init_components(modo_edicao, data)

        # Armazena para cada um dos inputs se ele está válido ou não.
        valido = [modo_edicao] * 5

        while True:
            event, values = super().abrir_tela()

            # Caso o usuário feche a janela do programa
            if event == sg.WIN_CLOSED:
                return ('exited', None)

            # Valida os inputs de texto
            elif event == 'input_nome_funcionario':
                valido[0] = super().validar_input(
                    event,
                    Validators.validar_nome(values[event]) == False,
                    'Nome inválido, digite um nome e sobrenome válido.'
                )
                continue
            elif event == 'input_email':
                valido[1] = super().validar_input(
                    event,
                    Validators.validar_email(values[event]) == False,
                    'E-mail inválido, digite um e-mail válido.'
                )
                continue
            elif event == 'input_telefone':
                valido[2] = super().validar_input(
                    event,
                    Validators.validar_telefone(values[event]) == False,
                    'Telefone inválido, digite um telefone válido.'
                )
                continue
            elif event == 'input_cpf':
                valido[3] = super().validar_input(
                    event,
                    Validators.validar_cpf(values[event]) == False,
                    'CPF inválido, digite um CPF válido.'
                )
                continue
            elif event == 'input_salario':
                valido[4] = super().validar_input(
                    event,
                    Validators.validar_numero(values[event]) == False,
                    'Salário inválido, digite um salário válido.'
                )
                continue
            elif event == 'btn_salvar':
                # Verifica se todos os campos são válidos, se não forem, exibe mensagem de erro.
                if False in valido:
                    sg.popup_no_buttons(
                        'Existem campos inválidos, corrija-os antes de salvar.',
                        title='Erro'
                    )
                    continue
                else:
                    super().fechar_tela()
                    return (
                        'criar', {
                            'data_atual': date.today().strftime('%d/%m/%Y'),
                            'salario': values['input_salario'],
                            'nome': values['input_nome_funcionario'],
                            'email': values['input_email'],
                            'telefone': Formatters.formatar_telefone(values['input_telefone']),
                            # por questões de validação...
                            'cpf': Formatters.formatar_cpf(values['input_cpf']),
                        }
                    )
            else:
                return (event, values)


"""empty message

Revision ID: b3fe1c74d97b
Revises: d724dedbe3cd
Create Date: 2020-08-20 16:57:43.500637

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'b3fe1c74d97b'
down_revision = 'd724dedbe3cd'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('course',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('course_type', sa.String(length=12), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    with op.batch_alter_table('course', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_course_course_type'), ['course_type'], unique=False)

    with op.batch_alter_table('cohort', schema=None) as batch_op:
        batch_op.add_column(sa.Column('coh_course', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('coh_grads', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('coh_participants', sa.Integer(), nullable=True))
        batch_op.create_foreign_key('FK_cohort_course', 'course', ['coh_course'], ['id'])
        batch_op.drop_column('coh_deliveryDate')

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('cohort', schema=None) as batch_op:
        batch_op.add_column(sa.Column('coh_deliveryDate', sa.DATETIME(), nullable=True))
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_column('coh_participants')
        batch_op.drop_column('coh_grads')
        batch_op.drop_column('coh_course')

    with op.batch_alter_table('course', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_course_course_type'))

    op.drop_table('course')
    # ### end Alembic commands ###


# 1.Добавьте еще один пункт
#
# 2.Замените 2 пункт на новый
#
# 3.Выведите на экран длину списка
#
# 4.Отсортируйте список по алфавиту
#
# 5.Удалите последний пункт списка

pokupki=["хлеб", "масло", "молоко", "сыр", "сметана"]
pokupki.append("консервы")
pokupki[1]="колбаса"
dlina=len(pokupki)
print(dlina)
pokupki.sort()
pokupki.pop()
print(pokupki)

модули 1 и 2 курс/список покупок.py

список покупок.py


#
#! /usr/bin/env python
#
#
import numpy as np
import matplotlib.pyplot as plt
from fipy import Grid2D, CellVariable, DiffusionTerm, FixedFlux
#
#
#
def GetBx(B0, L, dl) :

    N = [np.int(np.round(i)) for i in np.divide(L, dl)]
    Wx = B0*np.linspace(-L[1]/2, L[1]/2, num = N[1]+1)
    Bx = np.tile(Wx, (N[0]+1, 1))

    return Bx
#
#
def GetBy(B0, L, dl) :

    N = [np.int(np.round(i)) for i in np.divide(L, dl)]
    Wy = B0*np.linspace(-L[0]/2, L[0]/2, num = N[0]+1)
    By = np.repeat(Wy, N[1]+1)
    By = np.reshape(By, [N[0]+1, N[1]+1])

    return By
#
#
def GetJz(Bx, By, dl) :

    dBxdy = np.gradient(Bx, dl[0], dl[1])[1]
    dBydx = np.gradient(By, dl[0], dl[1])[0]

    Jz = dBydx-dBxdy

    return Jz
#
#
def GetAz(Bx, By, Jz, Nc, dl) :

    mesh = Grid2D(dx = dl[0], dy = dl[1], nx = Nc[0], ny = Nc[1])

    _Az = CellVariable(mesh=mesh, value=0.0)

    _Bx = CellVariable(mesh=mesh)
    _Bx.value = np.reshape(Bx, Nc[0]*Nc[1], order = 'F')

    _By = CellVariable(mesh=mesh)
    _By.value = np.reshape(By, Nc[0]*Nc[1], order = 'F')

    _Jz = CellVariable(mesh=mesh)
    _Jz.value = np.reshape(Jz, Nc[0]*Nc[1], order = 'F')

    _Az.equation = (DiffusionTerm(coeff = 1.0)+_Jz == 0)

    # beware of the sign of the flux : always consider outward direction
    BCs = [FixedFlux(value= _By.getFaceValue(), faces=mesh.getFacesLeft()),
           FixedFlux(value=-_By.getFaceValue(), faces=mesh.getFacesRight()),
           FixedFlux(value=-_Bx.getFaceValue(), faces=mesh.getFacesBottom()),
           FixedFlux(value= _Bx.getFaceValue(), faces=mesh.getFacesTop())]

    _Az.equation.solve(var=_Az, boundaryConditions=BCs)

    Az = np.reshape(_Az.value, Nc, order = 'F')

    return Az
#
#
#
Lb = [20, 10]
dl = [.1, .1]

Nc = [np.int(np.round(i))+1 for i in np.divide(Lb, dl)]

Bx = GetBx(1.0, Lb, dl)
By = GetBy(0.2, Lb, dl)
Jz = GetJz(Bx, By, dl)
Az = GetAz(Bx, By, Jz, Nc, dl)

image = plt.imshow(np.transpose(Az), origin = 'lower')
plt.colorbar(image)
#plt.show()
plt.savefig('new.pdf')


class Solution:
    def reversePairs(self, nums):
        self.res=0
        self.mergesort(nums)
        return self.res
    def mergesort(self,nums):
        n=len(nums)
        if n<=1:
            return nums
        mid=n//2
        left=self.mergesort(nums[:mid])
        right=self.mergesort(nums[mid:])
        res=[]
        m=len(left)
        n=len(right)
        i,j=0,0
        while i<m and j<n:
            if left[i]>2*right[j]:
                self.res+=m-i
                j+=1
            else:
                i+=1
        i,j=0,0
        while i<m and j<n:
            if left[i]<=right[j]:
                res.append(left[i])
                i+=1
            else:
                res.append(right[j])
                j+=1
        if i<m:
            res+=left[i:]
        if j<n:
            res+=right[j:]
        return res


# -*- coding: utf-8 -*-
'''
Created on Thu Apr  4 14:44:57 2019

@author: villa
'''
import zmq
import sys
import hashlib
import os

context=zmq.Context()
s=context.socket(zmq.REP)
s.bind('tcp://*:5556')

def calcularhash(nombrearchivo):
	BUF_SIZE = 65536  # lets read stuff in 64kb chunks!
	sha1 = hashlib.sha1()
	with open(nombrearchivo, 'rb') as f:
		while True:
			data = f.read(BUF_SIZE)
			if not data:
				break
			sha1.update(data)
	return sha1

def recibir(diccionario,hashf,nombrearchivo,parte,numeroparte):
	file = open('tempserver'+hashf,'ab') #aqui guardo los datos que van llegando
	file.write(parte)	#adjunta al archivo
	file.close()
	s.send_string(numeroparte) #devuelve el numero se partes recibidas
	print('parte recibida del cliente = '+numeroparte) #muestra el numero de partes recibidas
	sizefile=sys.getsizeof(parte)	#determina el tamano para calcular el hash al final
	if sizefile<10485760: #si llega la ultima parte calcula el hash
		hashtemp=str(calcularhash('tempserver'+hashf).hexdigest())
		if hashf == hashtemp:
			print('\n'+'-------Hash Correcto-------')
			os.rename('tempserver'+hashf,hashf)
			print('\n'+'hash para descargar este archivo '+hashtemp+'\n')
			diccionario={hashtemp:nombrearchivo}
			print('agregado a la base de datos'+'\n')
			return diccionario
		else:
			print('hashes incorrectos')

def enviar(diccionario,hashf,numeroparte):
	nombrearchivo=diccionario[hashf]
	f = open(hashf, 'rb') #el archivo a enviar
	f.seek(10485760*numeroparte)   #tamano en bytes 10485760 = 10 mb
	piece = f.read(10485760)   #tamano en bytes 10485760 = 10 mb
	s.send_multipart([nombrearchivo.encode('utf-8'),bytes(piece)])
	sizepiece=sys.getsizeof(piece)
	print('parte enviada al cliente = '+str(numeroparte))
	f.close()

mibase={}

while True:
	m=s.recv_multipart()

	if m[0].decode('utf-8')=='1':	#recibe(codigo,hash,nombrearchivo,parte,numeroparte)
		mibase=recibir(mibase,m[1].decode('utf-8'),m[2].decode('utf-8'),m[3],m[4].decode('utf-8'))

	if m[0].decode('utf-8')=='2':	#recibe(codigo,hash,numeroparte)
		enviar(mibase,m[1].decode('utf-8'),int(m[2].decode('utf-8')))


# -*- coding: utf-8 -*-
"""
Created on 2018/9/20

@author: gaoan
"""
from tigeropen.common.response import TigerResponse
from tigeropen.trade.domain.account import PortfolioAccount
from tigeropen.common.util.string_utils import camel_to_underline

ACCOUNT_FIELD_MAPPINGS = {'sMA': 'sma', 'updateTime': 'timestamp', 'realizedPnL': 'realized_pnl',
                          'unrealizedPnL': 'unrealized_pnl', 'regTMargin': 'regt_margin', 'regTEquity': 'regt_equity',
                          'cashValue': 'cash', 'initMarginReq': 'initial_margin_requirement',
                          'maintMarginReq': 'maintenance_margin_requirement', 'futuresPnl': 'futures_pnl'}

MARKET_VALUE_FIELD_MAPPINGS = {'updateTime': 'timestamp'}

class AssetsResponse(TigerResponse):
    def __init__(self):
        super(AssetsResponse, self).__init__()
        self.assets = []
        self._is_success = None

    def parse_response_content(self, response_content):
        response = super(AssetsResponse, self).parse_response_content(response_content)
        if 'is_success' in response:
            self._is_success = response['is_success']

        if self.data:
            if 'items' in self.data:
                for item in self.data['items']:
                    account = item['account']
                    asset = PortfolioAccount(account)
                    summary = asset.summary

                    for key, value in item.items():
                        if value is None:
                            continue
                        tag = ACCOUNT_FIELD_MAPPINGS[key] if key in ACCOUNT_FIELD_MAPPINGS else camel_to_underline(key)
                        if hasattr(summary, tag):
                            setattr(summary, tag, value)
                        elif 'market_values' == tag:
                            if isinstance(value, dict):
                                for sub_key, sub_value in value.items():
                                    currency = sub_key
                                    market_value = asset.market_value(currency=currency)
                                    self._parse_market_value(market_value, sub_value)
                            elif isinstance(value, list):
                                for sub_value in value:
                                    currency = sub_value.get('currency')
                                    if not currency:
                                        continue
                                    market_value = asset.market_value(currency=currency)
                                    self._parse_market_value(market_value, sub_value)
                        elif 'segments' == tag and value:
                            if isinstance(value, dict):
                                for sub_key, sub_value in value.items():
                                    segment_name = sub_key
                                    segment = asset.segment(segment_name=segment_name)
                                    self._parse_segment(segment, sub_value)
                            elif isinstance(value, list):
                                for sub_value in value:
                                    segment_name = sub_value.get('category')
                                    if not segment_name:
                                        continue
                                    segment = asset.segment(segment_name=segment_name)
                                    self._parse_segment(segment, sub_value)

                    self.assets.append(asset)

    @staticmethod
    def _parse_segment(segment, sub_value):
        for segment_key, segment_value in sub_value.items():
            if segment_value is None:
                continue
            if segment_key in ACCOUNT_FIELD_MAPPINGS:
                sub_tag = ACCOUNT_FIELD_MAPPINGS[segment_key]
            else:
                sub_tag = camel_to_underline(segment_key)
            setattr(segment, sub_tag, segment_value)

    @staticmethod
    def _parse_market_value(market_value, sub_value):
        for mv_key, mv_value in sub_value.items():
            if mv_value is None:
                continue
            if mv_key in ACCOUNT_FIELD_MAPPINGS:
                sub_tag = ACCOUNT_FIELD_MAPPINGS[mv_key]
            else:
                sub_tag = camel_to_underline(mv_key)
            if hasattr(market_value, sub_tag):
                setattr(market_value, sub_tag, mv_value)


from subprocess import check_output

class Utilities(object):
    """ Contains common functionality used by all other applications in this project. """

    @staticmethod
    def get_output(dump_location, plugin, profile=None, suggested_profile=None, args=None):

        """
        Performs the specified command (plugin) on the specified dump.

        :param dump_location: Location of the dump to be analyzed.
        :param plugin: Command to be fired upon the dump file.
        :param profile: Profile of the dump.
        :param args: Additional command-line arguments.

        :return: Output of the command.

        """

        try:

            # Checking if no profile is specified.
            if profile is None:

                # Executing the command without any profile specified.
                command = ('python ./volatility/vol.py %s -f "%s"' % (plugin, dump_location))

            # Checking if a profile is specified...
            else:
                command = None
                # iterate throw all the suggested proflie
                if suggested_profile:

                    profile_list = []
                    for i_profile in suggested_profile.split(","):
                        if "(" in i_profile:
                            test = i_profile.split("(")
                            if test:
                                profile_list.append(test[0].strip())
                        else:
                            profile_list.append(i_profile.strip())

                    if profile_list:
                        print (profile_list)
                        for prof in profile_list:
                            # Exboomer-win2003-2006-03-17.imge cuting the command with any profile specified.
                            command = ('python ./volatility/vol.py %s -f "%s" --profile="%s" --output=greptext'
                                       % (plugin, dump_location, prof))

                            if args:
                                # Appending them to the command string.
                                command += " %s" % args

                            output = check_output(command, shell=True).split("\n")
                            # print(output)
                            if output[0] == "No suitable address space mapping found":
                                continue
                            else:
                                break

                    else:
                        command = ('python ./volatility/vol.py %s -f "%s" --profile="%s"'
                                   % (plugin, dump_location, profile))

            # Checking if additional arguments are specified...
            if args:
                # Appending them to the command string.
                command += " %s" % args

            # Firing the command and splitting by newlines.
            output = check_output(command, shell=True).split("\n")
            # print (output)
            # Checking if the first line is "No suitable address space mapping found".

            if output[0] == "No suitable address space mapping found":
                raise Exception("Could not analyze the dump. Either the profile, the dump or both are invalid.")

            # Returning the output.
            return output

        # In case of errors...
        except Exception as e:
            raise Exception("An error occurred while firing '%s' command on '%s' under '%s' profile : %s"
                            % (plugin, dump_location.split("/")[-1], profile, str(e)))

    @staticmethod
    def separate_raw_data(output_list):

        """
        Separates the output list into collection of lists.

        :param output_list: List of output to be separated.

        :return: Output separated into a list.

        """

        try:

            # Initialing an empty list.
            separated = []

            # Iterating each items of the output list.
            for lst in output_list:

                # Initialing an empty temp list.
                temp = []

                # Iterating each element in "lst" from the first index.
                for line in lst[1:]:

                    # Separating the data using pipe sign and stripping away any > signs.
                    # > usually means starting of a row.
                    parts = [None if part.strip() == "" else part.strip() for part in line.strip(">").split("|")]

                    # If "parts" is not empty.
                    if parts:
                        # Appending the parts in the temp list except the first element which is always None.
                        temp.append(parts[1:])

                # Append the temp list elements in separated list.
                separated.append(temp)

            # Returning the separated list.
            return separated

        # In case of any exceptions...
        except Exception as e:
            raise Exception("An error occurred while separating data: " + str(e))


# pylint: disable=C0111,W0212,R0903,W0201,C0301,E0401
import unittest
import calendar
from losantmqtt import Device

class MqttMock(object):

    def __init__(self):
        self.publish_calls = []

    def publish(self, topic, payload):
        self.publish_calls.append([topic, payload])
        return 0

class MsgMock(object):
    def __init__(self, msg):
        self.payload = msg

class TestDevice(unittest.TestCase):

    def setUp(self):
        self.device = Device("device_id", "device_key", "device_secret")

    def test_correct_props(self):
        self.assertEqual(self.device._device_id, "device_id")
        self.assertEqual(self.device._key, "device_key")
        self.assertEqual(self.device._secret, "device_secret")
        self.assertEqual(self.device._secure, True)
        self.assertEqual(self.device._command_topic(), "losant/device_id/command")
        self.assertEqual(self.device._state_topic(), "losant/device_id/state")

    def test_add_remove_observer(self):
        self.event_fired = 0
        def on_event(device):
            self.assertEqual(device, self.device)
            self.event_fired += 1
        self.device.add_event_observer("test", on_event)
        self.device._fire_event("test")
        self.assertEqual(self.event_fired, 1)
        self.device.remove_event_observer("test", on_event)
        self.device._fire_event("test")
        self.assertEqual(self.event_fired, 1)

    def test_send_state(self):
        self.device._mqtt_client = MqttMock()
        calls = self.device._mqtt_client.publish_calls
        self.assertEqual(len(calls), 0)
        result = self.device.send_state({"one": "two"}, 1234)
        self.assertEqual(result, True)
        calls = self.device._mqtt_client.publish_calls
        self.assertEqual(len(calls), 1)
        self.assertEqual(calls[0][0], "losant/device_id/state")
        expected_payload = '{"data": {"one": "two"}, "time": 1234}'
        self.assertEqual(calls[0][1], expected_payload)

    def test_receive_command(self):
        self.cmd_msg = None
        def on_command(device, msg):
            self.assertEqual(device, self.device)
            self.cmd_msg = msg
        self.device.add_event_observer("command", on_command)
        mock = MsgMock('{"name":"start","payload":{"one":[2,3]},"time":{"$date":"2016-06-01T01:09:51.145Z"}}')
        self.device._cb_client_command(None, None, mock)
        self.assertEqual(self.cmd_msg["name"], "start")
        self.assertEqual(self.cmd_msg["payload"], {"one": [2, 3]})
        self.assertEqual(self.cmd_msg["time"].microsecond, 145000)
        self.assertEqual(calendar.timegm(self.cmd_msg["time"].utctimetuple()), 1464743391.0)


import logging
import json

import connexion
from flask_testing import TestCase
from flask import current_app

from papahana.controllers import authorization_utils as auth_utils
from papahana.controllers import controller_helper as helpers
from papahana.encoder import JSONEncoder
from papahana import util

MODE = 'dev'

class BaseTestCase(TestCase):

    def create_app(self):
        logging.getLogger('connexion.operation').setLevel('ERROR')
        app = connexion.App(__name__, specification_dir='../swagger/')
        app.app.json_encoder = JSONEncoder
        app.add_api('papahana.yaml')

        # mode = 'dev'
        # mode = util.read_mode()
        mode = MODE
        print(f'working with mode: {mode}')
        urls = util.read_urls()
        config_params = util.read_config(mode)

        with app.app.app_context():
            current_app.config_params = config_params
            current_app.urls = urls
            current_app.mode = mode

        return app.app

    def set_api_cookie(self):
        config_params = util.read_config('dev')
        keck_id = config_params['admin'][0]
        query = {'keck_id': keck_id}
        results = helpers.get_by_query(query, 'observerCollect', db_name='obs_db')
        raw_api_key = results[0]['api_key']
        api_key = auth_utils._encrypt_str(raw_api_key)
        uid = auth_utils._encrypt_str(str(keck_id))

        self.client.set_cookie('.keck.hawaii.edu', 'ODB-API-UID', uid)
        self.client.set_cookie('.keck.hawaii.edu', 'ODB-API-KEY', api_key)

    def insert_ob(self, ob_body):

        response = self.client.open(
            '/obsBlocks',
            method='POST',
            data=json.dumps(ob_body),
            content_type='application/json')

        self.assert200(response,
                       'Failed __init__ insert_ob -- did not insert OB.')

        ob_id = response.data.decode('utf-8').replace("\n", "").replace('"', '')

        return ob_id

    def delete_ob(self, ob_id):
        query_string = [('ob_id', ob_id)]
        response = self.client.open(
            '/obsBlocks',
            method='DELETE',
            query_string=query_string)

        self.assert_status(response, 200,
                           'Failed __init__ delete_ob,  did not delete OB')


from functools import reduce
from operator import add

from math import cos, pi
from scipy import signal
import matplotlib.pyplot as plt

from migen import *
from migen.fhdl import verilog
import numpy

sample = 5000       #Number of Samples
Fs = 5000           #Sample Frequency
fc = 800           #Cutoff frequ
w_c = 2*fc/Fs       #Digital Frequ
n = 3               #Order of the filter

# A synthesizable FIR filter.
class FIR(Module):
    def __init__(self, coefb,coefa, wsize=32):
        self.coefa = coefa
        self.coefb = coefb
        self.wsize = wsize
        self.i = Signal((self.wsize, True))
        self.o = Signal((self.wsize, True))

        ###

        mulsb = [0]
        mulsa = [0]
        srcb = self.i
        for c in self.coefb:
            sregb = Signal((self.wsize, True))      #Neues Signal sregb erstellen
            self.sync += sregb.eq(srcb)             #Neues Signal mit dem Namen sregb wird mit jedem sync mit dem Wert aus Sourceb geladen
            srcb = sregb                            #Source B entspricht nun sregb -> ist also ein Signal
            c_fpb = int(c*2**(self.wsize - 1))      #Koeffizient c wird mit 2^15 multipliziert
            mulsb.append(c_fpb*sregb)               #Der Ergebnisliste wird der Skallierte Koeffizient multipliziert mit sregb angehängt

        sum_fulla = Signal((2*self.wsize-1, True))
        sum_fullb = Signal((2*self.wsize-1, True))
        sum_full = Signal((2*self.wsize-1, True))

        self.sync += sum_fullb.eq(reduce(add, mulsb))                       #Register
        self.sync += sum_full.eq((sum_fullb+sum_fulla)>> self.wsize)        #Hier passiert ein Fehler

        srca = sum_full
        for c in self.coefa:
            srega = Signal((self.wsize, True))
            self.sync += srega.eq(srca)
            srca = srega
            c_fpa = int(c*2**(self.wsize - 1))
            mulsa.append(c_fpa*srega)
        self.sync += sum_fulla.eq(reduce(add, mulsa))
        self.comb += self.o.eq(sum_full)

# A test bench for our FIR filter.
# Generates a sine wave at the input and records the output.
def fir_tb(dut, frequency, inputs, outputs):
    f = 2**(dut.wsize - 1)                                      #Skallierung
    x = numpy.arange(sample)                                    #Array von 1 - 5000 anlegen
    for x in x:
        y = 0.1*numpy.sin(2 * numpy.pi * frequency * x / Fs)    #Sinus erzeugen mit Frequenz frequency und der Auflösung Fs
        yield dut.i.eq(int(f*y))                                #Neuer erzeugter Wert y nach input i wird hier geschrieben
        inputs.append(y*0.1)                                    #Input Array wird gefüllt
        outputs.append((yield dut.o)/f*0.1*info)                     #Output Array wird mit dem Output des Filters gefüllt
        yield

if __name__ == "__main__":
    # Compute filter coefficients with SciPy.
    #coef = signal.remez(30, [0, 0.1, 0.2, 0.4, 0.45, 0.5], [0, 1, 0])
    #coefb = signal.firwin(100, cutoff = 0.1, window = "hanning", pass_zero=True)
    #coefb, coefa = signal.iirfilter(n,w_c, btype="lowpass", analog=False, ftype="butter")
    coefb, coefa = signal.butter(n, w_c, btype='lowpass', analog=False, output='ba', fs=None)
    print(coefb,coefa)

    #Rescale-----------------------------------------------------------------
    ValueArray = []
    ValueArray.append(abs(numpy.amin(coefb)))
    ValueArray.append(abs(numpy.amax(coefb)))
    ValueArray.append(abs(numpy.amin(coefa)))
    ValueArray.append(abs(numpy.amax(coefa)))
    info = numpy.amax(ValueArray)
    print(info)
    coefb = coefb/info
    coefa = coefa/info
    #-------------------------------------------------------------------------

    # Simulate for different frequencies and concatenate
    # the results.
    in_signals = []
    out_signals = []
    for frequency in [1,10,100,1000]:
        dut = FIR(coefb,coefa)
        tb = fir_tb(dut, frequency, in_signals, out_signals)
        run_simulation(dut, tb)

    # Plot data from the input and output waveforms.
    plt.plot(in_signals)
    plt.plot(out_signals)
    plt.show()
    print(coefb,coefa)

    # Print the Verilog source for the filter.
    fir = FIR(coefb,coefa)
    print(verilog.convert(fir, ios={fir.i, fir.o}))


from product import Product
class Grower:
    def read_file(self):
        fp = open('products.txt', 'r', encoding="utf-8")
        lines = fp.readlines()
        fp.close()

        self.products = []

        for line in lines[1::]:
            (id, name, price, quantity) = line.split(';')
            product = Product(id, name, price, quantity)
            self.products.append(product)

    # legdrágább zöldség
    def larger(self):
        max_product = self.products[0]
        for product in self.products:
            if product.price > max_product.price:
                max_product = product
        print("Legdrágább zöldség: ", max_product.name, max_product.price)

    # Az összes paprika ára
    def calcPepperPrice(self):
        ossz_ar = 0
        for product in self.products:
            if product.name == "paprika":
                ossz_ar = product.price * product.weight
        print("Paprika készleten ár alapján: ", ossz_ar)

    # Mennyi a vöröshagyma és a karalábé tömege együtt?
    def sumOnionKohlrabiWeight(self):
        ossz_tomeg = 0
        for product in self.products:
            if product.name == "vöröshagyma" or product.name == "karalábé":
                ossz_tomeg += product.weight
        print("Hagyma és karalábé össz tömege: ", ossz_tomeg)

    # Mi a neve legnagyobb tömegű zöldségnek?
    def showLargerWeight(self):
        max_product = self.products[0]
        for product in self.products:
            if product.weight > max_product.weight:
                max_product = product
        print("Legnagyobb tömegű zöldség: ", max_product.name, max_product.weight)

    # Van karalábé?
    def isHaveKohlrabi(self):
        n = len(self.products)
        zoldi = "karalábé"
        i = 0
        while i < n and self.products[i].name.find(zoldi) == -1:
            i += 1
        if i < n:
            print("Van ilyen")
        else:
            print("Nincs ilyen")

    # Hány zöldség drágább mint 700 Ft.
    def moreThenSevenhundred(self):
        darab = 0
        for product in self.products:
            if product.price > 700:
                darab += 1
        print("Hány darab zöldség drágább mint 700?:", darab)

grower = Grower()
grower.read_file()
grower.larger()
grower.calcPepperPrice()
grower.sumOnionKohlrabiWeight()
grower.showLargerWeight()
grower.isHaveKohlrabi()
grower.moreThenSevenhundred()


"""Launches online integration

Usage:
  main.py [-h | --help]  [options]

Options:
  -h --help                         Show this screen.
  --host HOST                       Set host address [default: 127.0.0.1].
  --port PORT                       Set host port [default: 5000]
  --debug                           Set debug mode
"""
import docopt
import flask

from flask import render_template, request
from datetime import datetime

import parser_shotgun
import models
from config import app, db

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/update_event")
def update_event():
    url = request.args.get("url")
    parser = parser_shotgun.ParserShotgun()
    try:
        infos = parser.get_infos(url)
        infos["error"] = False
    except parser_shotgun.BadUrlError:
        infos = {"error": True}
    return infos

@app.route("/save_form", methods=["POST"])
def save_form():
    url = request.form["url"]
    mail = request.form["mail"]
    prices = request.form["prices"][:-1]
    event_date = request.form["event_date_input"]

    import send_notification

    s = send_notification.SendNotification()
    s.send(url, mail, prices, event_date)

    flask.flash(
        f"WIP (non-fonctionnel) : Enregistrement des notifications pour l'évènement {url} pour les prix {prices} à l'adresse mail {mail}. Date : {event_date}."
    )

    return flask.redirect(flask.url_for("index"))

if __name__ == "__main__":
    arguments = docopt.docopt(__doc__)

    app.run(host=arguments["--host"], port=int(arguments["--port"]), debug=arguments["--debug"])


from __future__ import print_function, division, absolute_import

import numpy as np
import quaternion
from quaternion.numba_wrapper import njit

def slerp(R1, R2, t1, t2, t_out):
    """Spherical linear interpolation of rotors

    This function uses a simpler interface than the more fundamental
    `slerp_evaluate` and `slerp_vectorized` functions.  The latter
    are fast, being implemented at the C level, but take input `tau`
    instead of time.  This function adjusts the time accordingly.

    Parameters
    ----------
    R1: quaternion
        Quaternion at beginning of interpolation
    R2: quaternion
        Quaternion at end of interpolation
    t1: float
        Time corresponding to R1
    t2: float
        Time corresponding to R2
    t_out: float or array of floats
        Times to which the rotors should be interpolated

    """
    tau = (t_out-t1)/(t2-t1)
    return np.slerp_vectorized(R1, R2, tau)

def squad(R_in, t_in, t_out):
    """Spherical "quadrangular" interpolation of rotors with a cubic spline

    This is the best way to interpolate rotations.  It uses the analog
    of a cubic spline, except that the interpolant is confined to the
    rotor manifold in a natural way.  Alternative methods involving
    interpolation of other coordinates on the rotation group or
    normalization of interpolated values give bad results.  The
    results from this method are as natural as any, and are continuous
    in first and second derivatives.

    The input `R_in` rotors are assumed to be reasonably continuous
    (no sign flips), and the input `t` arrays are assumed to be
    sorted.  No checking is done for either case, and you may get
    silently bad results if these conditions are violated.

    This function simplifies the calling, compared to `squad_evaluate`
    (which takes a set of four quaternions forming the edges of the
    "quadrangle", and the normalized time `tau`) and `squad_vectorized`
    (which takes the same arguments, but in array form, and efficiently
    loops over them).

    Parameters
    ----------
    R_in: array of quaternions
        A time-series of rotors (unit quaternions) to be interpolated
    t_in: array of float
        The times corresponding to R_in
    t_out: array of float
        The times to which R_in should be interpolated

    """
    if R_in.size == 0 or t_out.size == 0:
        return np.array((), dtype=np.quaternion)

    # This list contains an index for each `t_out` such that
    # t_in[i-1] <= t_out < t_in[i]
    # Note that `side='right'` is much faster in my tests
    i_in_for_out = t_in.searchsorted(t_out, side='left')
    np.clip(i_in_for_out, 0, len(t_in) - 1, out=i_in_for_out)
    i_in = np.unique(i_in_for_out)

    # Now, for each index `i` in `i_in`, we need to compute the
    # interpolation "coefficients" (`A_i`, `B_ip1`).
    #
    # I previously tested an explicit version of the loops below,
    # comparing `stride_tricks.as_strided` with explicit
    # implementation via `roll` (as seen here).  I found that the
    # `roll` was significantly more efficient for simple calculations,
    # though the difference is probably totally washed out here.  In
    # any case, it might be useful to test again.
    #
    A = R_in * np.exp((- np.log((~R_in) * np.roll(R_in, -1))
                       + np.log((~np.roll(R_in, 1)) * R_in) * ((np.roll(t_in, -1) - t_in) / (t_in - np.roll(t_in, 1)))
                       ) * 0.25)
    B = np.roll(R_in, -1) * np.exp((np.log((~np.roll(R_in, -1)) * np.roll(R_in, -2))
                                    * ((np.roll(t_in, -1) - t_in) / (np.roll(t_in, -2) - np.roll(t_in, -1)))
                                    - np.log((~R_in) * np.roll(R_in, -1))) * -0.25)

    # Correct the first and last A time steps, and last two B time steps
    A[0] = R_in[0] * np.exp((np.log((~R_in[0])*R_in[1])
                             + np.log((~(R_in[0]*(~R_in[1])*R_in[0]))*R_in[0])
                             - 2 * np.log((~R_in[0]) * R_in[1])
                             ) * 0.25)
    A[-1] = R_in[-1]
    B[-2] = R_in[-1]
    #B[-1] = quaternion.one

    # Use the coefficients at the corresponding t_out indices to
    # compute the squad interpolant
    R_ip1 = np.array(np.roll(R_in, -1)[i_in_for_out])
    R_ip1[-1] = R_ip1[-2]*(~R_ip1[-3])*R_ip1[-2]
    tau = (t_out - t_in[i_in_for_out]) / ((np.roll(t_in, -1) - t_in)[i_in_for_out])
    R_out = np.squad_vectorized(tau, R_in[i_in_for_out], A[i_in_for_out], B[i_in_for_out], R_ip1)

    return R_out

@njit
def frame_from_angular_velocity_integrand(rfrak, Omega):
    import math
    from numpy import dot, cross
    from .numpy_quaternion import _eps
    rfrakMag = math.sqrt(rfrak[0] * rfrak[0] + rfrak[1] * rfrak[1] + rfrak[2] * rfrak[2])
    OmegaMag = math.sqrt(Omega[0] * Omega[0] + Omega[1] * Omega[1] + Omega[2] * Omega[2])
    # If the matrix is really close to the identity, return
    if rfrakMag < _eps * OmegaMag:
        return Omega[0] / 2.0, Omega[1] / 2.0, Omega[2] / 2.0
    # If the matrix is really close to singular, it's equivalent to the identity, so return
    if abs(math.sin(rfrakMag)) < _eps:
        return Omega[0] / 2.0, Omega[1] / 2.0, Omega[2] / 2.0

    OmegaOver2 = Omega[0] / 2.0, Omega[1] / 2.0, Omega[2] / 2.0
    rfrakHat = rfrak[0] / rfrakMag, rfrak[1] / rfrakMag, rfrak[2] / rfrakMag

    return ((OmegaOver2 - rfrakHat * dot(rfrakHat, OmegaOver2)) * (rfrakMag / math.tan(rfrakMag))
            + rfrakHat * dot(rfrakHat, OmegaOver2) + cross(OmegaOver2, rfrak))

class appending_array(object):
    def __init__(self, shape, dtype=np.float, initial_array=None):
        self._a = np.empty(shape, dtype=dtype)
        self.n = 0
        if initial_array is not None:
            assert initial_array.dtype == dtype
            assert initial_array.shape[1:] == shape[1:]
            assert initial_array.shape[0] <= shape[0]
            self.n = initial_array.shape[0]
            self._a[:self.n, ...] = initial_array[:]

    def append(self, row):
        self.n += 1
        if self.n > self._a.shape[0]:
            self._a = np.resize(self._a, (2*self._a.shape[0],)+self._a.shape[1:])
        self._a[self.n-1, ...] = row

    @property
    def a(self):
        return self._a[:self.n, ...]

def integrate_angular_velocity(Omega, t0, t1, R0=None, tolerance=1e-12):
    """Compute frame with given angular velocity

    Parameters
    ==========
    Omega: tuple or callable
        Angular velocity from which to compute frame.  Can be
          1) a 2-tuple of float arrays (t, v) giving the angular velocity vector at a series of times,
          2) a function of time that returns the 3-vector angular velocity, or
          3) a function of time and orientation (t, R) that returns the 3-vector angular velocity
        In case 1, the angular velocity will be interpolated to the required times.  Note that accuracy
        is poor in case 1.
    t0: float
        Initial time
    t1: float
        Final time
    R0: quaternion, optional
        Initial frame orientation.  Defaults to 1 (the identity orientation).
    tolerance: float, optional
        Absolute tolerance used in integration.  Defaults to 1e-12.

    Returns
    =======
    t: float array
    R: quaternion array

    """
    import warnings
    from scipy.integrate import ode

    if R0 is None:
        R0 = quaternion.one

    try:
        t_Omega, v = Omega
        from scipy.interpolate import InterpolatedUnivariateSpline
        Omega_x = InterpolatedUnivariateSpline(t_Omega, v[:, 0])
        Omega_y = InterpolatedUnivariateSpline(t_Omega, v[:, 1])
        Omega_z = InterpolatedUnivariateSpline(t_Omega, v[:, 2])
        def Omega_func(t, R):
            return [Omega_x(t), Omega_y(t), Omega_z(t)]
        Omega_func(t0, R0)
    except (TypeError, ValueError):
        def Omega_func(t, R):
            return Omega(t, R)
        try:
            Omega_func(t0, R0)
        except TypeError:
            def Omega_func(t, R):
                return Omega(t)
            Omega_func(t0, R0)

    def RHS(t, y):
        R = quaternion.quaternion(*y)
        return (0.5 * quaternion.quaternion(0.0, *Omega_func(t, R)) * R).components

    y0 = R0.components

    solver = ode(RHS)
    solver.set_integrator('dop853', nsteps=1, atol=tolerance, rtol=0.0)
    solver.set_initial_value(y0, t0)
    solver._integrator.iwork[2] = -1  # suppress Fortran-printed warning

    t = appending_array((int(t1-t0),))
    t.append(solver.t)
    R = appending_array((int(t1-t0), 4))
    R.append(solver.y)

    warnings.filterwarnings("ignore", category=UserWarning)
    while solver.t < t1:
        solver.integrate(t1, step=True)
        t.append(solver.t)
        R.append(solver.y)
    warnings.resetwarnings()

    t = t.a
    R = quaternion.as_quat_array(R.a)

    return t, R


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

"""UDP
"""

import asyncio
import logging

class EchoClientProtocol(asyncio.DatagramProtocol):
    """EchoClientProtocol"""
    def __init__(self, msg):
        logging.info("{} ".format(msg))
        super().__init__()
        self._transport = None
        self._msg = b'hello' if msg is None else msg

    def connection_made(self, transport):
        logging.info("on socket ready")
        self._transport = transport
        self._transport.sendto(self._msg)

    def datagram_received(self, data, addr):
        logging.info("{} {}".format(data, addr))
        self._transport.close()

    def connection_lost(self, exc):
        logging.info("only call on self close")

async def coro(address, port, msg):
    logging.info("{} {} {}".format(address, port, msg))
    loop = asyncio.get_event_loop()
    await loop.create_datagram_endpoint(
        lambda: EchoClientProtocol(msg), remote_addr=(address, port))

def start(address="127.0.0.1", port=8888, msg=None):
    logging.info("{} {} {}".format(address, port, msg))
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(coro(address, port, msg), loop=loop)


from datetime import date
from api import borrow_data
from api.userUtils import isUserAvailable, userIdExist
from api.booksUtils import isBookAvailable, updateCopies, bookIdExist, searchBookById

borrowIdCorrelative = 1

def returnBook(borrow_id):
    errors = []

    borrow_id = int(borrow_id)

    print('ID recibida ', borrow_id)

    if borrowIdExist(borrow_id):
        if not isBorrowReturned(borrow_id):

            borrowToModify = searchBorrowById(borrow_id)
            bookBorrow = borrowToModify['borrow_book']
            bookIdBorrow = bookBorrow['id_book']

            updateCopies(bookIdBorrow, True)

            for borrow in borrow_data:
                if borrow['id_borrow'] == borrow_id:

                    updateData = {"returned": True}
                    borrow.update(updateData)
                    return [True, errors]

        else:
            errors.append('El prestamo ya ha sido devuelto')
    else:
        errors.append('No existe la ID del prestamo')

    return [False, errors]

def createNewBorrow(borrowInfo):
    errors = []
    data = {}

    try:
        userId = borrowInfo["id_user"]

        if userIdExist(userId):
            try:
                bookId = borrowInfo["id_book"]
                if bookIdExist(bookId):
                    if isUserAvailable(userId):

                        if isBookAvailable(bookId):
                            updateCopies(bookId, False)

                            book = searchBookById(bookId)
                            global borrowIdCorrelative
                            correlativo = borrowIdCorrelative

                            dateStr = date.today().strftime("%d/%m/%Y")

                            data = {"id_borrow": correlativo, "borrow_date": dateStr,
                                    "returned": False, "id_user": userId, "borrow_book": book}
                            borrowIdCorrelative += 1

                            return [data, None]
                        else:
                            errors.append('No existe disponibilidad')
                    else:
                        errors.append('Usuario no apto para prestamos')
                else:
                    errors.append('Id de libro no registrada')

            except KeyError:
                errors.append('El atributo id_book es requerido')
        else:
            errors.append('Id de usuario no registrada')
    except KeyError:
        errors.append('El atributo id_user es requerido')

    return [None, errors]

def searchBorrow(idB):
    errors = []

    if borrowIdExist(idB):
        borrow = searchBorrowById(idB)
        return [borrow, None]
    else:
        errors.append('Id del prestamo no encontrada')

    return [None, errors]

def borrowIdExist(idB):
    posiblesIds = []

    print(borrow_data)

    for borrow in borrow_data:
        try:
            posiblesIds.append(borrow['id_borrow'])
        except:
            pass

    print('comparando ', idB, ' con ', posiblesIds, (idB in posiblesIds))

    return (idB in posiblesIds)

def getReportByUserId(idU, returned):

    errors = []
    data = []

    if idU is not None:
        if(userIdExist(idU)):

            for borrow in borrow_data:

                clause = True
                if returned == True:
                    clause = (borrow['id_user'] ==
                              idU and borrow['returned'] == True)
                elif returned == False:
                    clause = (borrow['id_user'] ==
                              idU and borrow['returned'] == False)
                else:
                    clause = (borrow['id_user'] == idU)

                if clause:
                    data.append(borrow)

            return [data, False]

        else:
            errors.append('No existe usuario con dicha ID')
    else:
        errors.append('El id de usuario es requerida')

    return [False, errors]

def isBorrowReturned(idB):
    for borrow in borrow_data:
        if borrow['id_borrow'] == idB:
            return borrow['returned']

def searchBorrowById(idB):
    for borrow in borrow_data:
        if borrow['id_borrow'] == idB:
            return borrow


def notas(* notas, sit=False):
    """
    -> Função para analisar notas e situações de vários alunos.
    :param notas: uma ou mais notas de um estudante.
    :param sit: (opcional) indica a situção do aluno: Exelente, bom ou insuficiente.
    :return: retorna um dicionário com as informações do aluno.
    """
    menor = maior = soma = 0
    for k, i in enumerate(notas):
        if k == 0:
            menor = maior = i
        else:
            if i > maior:
                maior = i
            if i < menor:
                menor = i
    for g in notas:
        soma += g
    media = soma/len(notas)
    alunos = dict()
    alunos['quant'] = len(notas)
    alunos['maior'] = maior
    alunos['menor'] = menor
    alunos['media'] = media

    if sit == True:
        if media > 9.0:
            alunos['situação'] = 'Exelente'
        elif 7.0 < media < 9.0:
            alunos['situação'] = 'Bom'
        elif 5.0 < media < 7.0:
            alunos['situação'] = 'Regurla'
        else:
            alunos['situação'] = 'Insuficiente'
    return alunos

a = notas(10.0, 8.45, 9.0, 7.89, sit=True)
print(f'{a}')


import numpy as np
import glob
#code from cameracongig.xml
import copy
import xml.etree.ElementTree as ET

DEFAULT_CONFIGFILE="""<?xml version="1.0" ?>
<file>
    <CameraConfig version="2">
        <system  />
        <skeleton />
        <postprocessing height_min="0" height_max="0" radius_filter="0" greenscreenremoval="0">
            <depthfilterparameters  />
        </postprocessing>
        <camera serial="0" type="">
            <trafo>
                <values v00="1" v01="0" v02="0" v03="0" v10="0" v11="1" v12="0" v13="0" v20="0" v21="0" v22="1" v23="0" v30="0" v31="0" v32="0" v33="1"  />
            </trafo>
        </camera>
    </CameraConfig>
</file>
"""
FILTER_PARAMS_REALSENSE=dict(
    do_threshold="1",
    threshold_near="0.2",
    threshold_far="4",

    depth_x_erosion="2",
    depth_y_erosion="2",

    do_decimation="1",
    decimation_value="2",

    do_spatial="1",
    spatial_iterations="1",
    spatial_alpha="0.5",
    spatial_delta="20",
    spatial_filling="1",

    do_temporal="1",
    temporal_alpha="0.4",
    temporal_delta="20",
    temporal_percistency="3",
)

SYSTEM_PARAMS_REALSENSE=dict(
    usb2width="640",
    usb2height="480",
    usb2fps="15",
    usb3width="1280",
    usb3height="720",
    usb3fps="30",
    usb2allowed="0",
    exposure="-1",
    whitebalance="-1",
    backlight_compensation="0",
    laser_power="360",
    density_preferred="1"
)

SKELETON_PARAMS_REALSENSE=dict()

FILTER_PARAMS_KINECT=dict(
    do_threshold="1",
    threshold_near="0.2",
    threshold_far="4",

    depth_x_erosion="1",
    depth_y_erosion="1",
)

SYSTEM_PARAMS_KINECT=dict(
    color_height="720",
    depth_height="576",
    fps="15",
    sync_master_serial="",
    colormaster="1",
    color_exposure_time="-1",
    color_whitebalance="-1",
    color_backlight_compensation="-1",
    color_brightness="-1",
    color_contrast="-1",
    color_saturation="-1",
    color_sharpness="-1",
    color_gain="-1",
    color_powerline_frequency="-1"
)

SKELETON_PARAMS_KINECT=dict(
    sensor_orientation="-1",
    processing_mode="-1",
    model_path=""
)

DEFAULT_FILENAME="cameraconfig.xml"
DEFAULT_TYPE="realsense"
DEFAULT_FILTER_PARAMS=FILTER_PARAMS_REALSENSE
DEFAULT_SYSTEM_PARAMS=SYSTEM_PARAMS_REALSENSE
DEFAULT_SKELETON_PARAMS=SKELETON_PARAMS_REALSENSE

def selectCameraType(cameraType):
    global DEFAULT_TYPE, DEFAULT_FILTER_PARAMS, DEFAULT_SYSTEM_PARAMS, DEFAULT_SKELETON_PARAMS
    DEFAULT_TYPE = cameraType
    DEFAULT_FILTER_PARAMS = globals()[f'FILTER_PARAMS_{cameraType.upper()}']
    DEFAULT_SYSTEM_PARAMS = globals()[f'SYSTEM_PARAMS_{cameraType.upper()}']
    DEFAULT_SKELETON_PARAMS = globals()[f'SKELETON_PARAMS_{cameraType.upper()}']

class CameraConfig:

    def __init__(self, confFilename, read=True):
        self.confFilename = confFilename
        self.serials = []
        self.matrices = []
        self.tree = None
        if read:
            self._readConf(self.confFilename)
            self._parseConf()

    def _readConf(self, confFilename):
        self.tree = ET.parse(confFilename)

    def copyFrom(self, other):
        self.tree = copy.deepcopy(other.tree)
        self._parseConf()

    def fillDefault(self):
        root = ET.fromstring(DEFAULT_CONFIGFILE)
        paramElt = root.find('CameraConfig/postprocessing/depthfilterparameters')
        for k, v in DEFAULT_FILTER_PARAMS.items():
            paramElt.set(k, v)
        paramElt = root.find('CameraConfig/system')
        for k, v in DEFAULT_SYSTEM_PARAMS.items():
            paramElt.set(k, v)
        paramElt = root.find('CameraConfig/skeleton')
        for k, v in DEFAULT_SKELETON_PARAMS.items():
            paramElt.set(k, v)
        self.tree = ET.ElementTree(root)

        self._parseConf()

    def _parseConf(self):
        root = self.tree.getroot()
        for camElt in root.findall('CameraConfig/camera'):
            serial = camElt.attrib['serial']
            assert serial
            trafoElt = camElt.find('trafo')
            valuesElt = trafoElt.find('values')
            va = valuesElt.attrib
            trafo = [
                [float(va['v00']), float(va['v01']), float(va['v02']), float(va['v03'])],
                [float(va['v10']), float(va['v11']), float(va['v12']), float(va['v13'])],
                [float(va['v20']), float(va['v21']), float(va['v22']), float(va['v23'])],
                [float(va['v30']), float(va['v31']), float(va['v32']), float(va['v33'])],
            ]
            self.serials.append(serial)
            self.matrices.append(trafo)

    def save(self):
        self.tree.write(self.confFilename)

    def savef(self, filename):
        self.tree.write(filename)

    def getcount(self):
        return len(self.serials)

    def getserials(self):
        return self.serials

    def getmatrix(self, tilenum):
        return self.matrices[tilenum]

    def addcamera(self, serial):
        root = self.tree.getroot()
        firstCamElt = root.find('CameraConfig/camera')
        newCamElt = copy.deepcopy(firstCamElt)
        newCamElt.set('serial', serial)
        newCamElt.set('type', DEFAULT_TYPE)
        ccElt = root.find('CameraConfig')
        ccElt.append(newCamElt)

        self.serials.append(serial)
        matrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
        self.matrices.append(matrix)

        self.setmatrix(len(self.serials)-1, matrix)

    def setmatrix(self, tilenum, matrix):
        self.matrices[tilenum] = copy.deepcopy(matrix)
        serial = self.serials[tilenum]
        root = self.tree.getroot()
        camElt = root.find(f"CameraConfig/camera[@serial='{serial}']")
        trafoElt = camElt.find('trafo')
        valuesElt = trafoElt.find('values')
        valuesElt.set('v00', str(matrix[0][0]))
        valuesElt.set('v01', str(matrix[0][1]))
        valuesElt.set('v02', str(matrix[0][2]))
        valuesElt.set('v03', str(matrix[0][3]))
        valuesElt.set('v10', str(matrix[1][0]))
        valuesElt.set('v11', str(matrix[1][1]))
        valuesElt.set('v12', str(matrix[1][2]))
        valuesElt.set('v13', str(matrix[1][3]))
        valuesElt.set('v20', str(matrix[2][0]))
        valuesElt.set('v21', str(matrix[2][1]))
        valuesElt.set('v22', str(matrix[2][2]))
        valuesElt.set('v23', str(matrix[2][3]))
        valuesElt.set('v30', str(matrix[3][0]))
        valuesElt.set('v31', str(matrix[3][1]))
        valuesElt.set('v32', str(matrix[3][2]))
        valuesElt.set('v33', str(matrix[3][3]))

    def setserial(self, tilenum, serial):
        oldSerial = self.serials[tilenum]
        self.serials[tilenum] = serial
        root = self.tree.getroot()
        camElt = root.find(f"CameraConfig/camera[@serial='{oldSerial}']")
        camElt.set('serial', serial)
        camElt.set('type', DEFAULT_TYPE)

    def setdistance(self, threshold_near, threshold_far):
        root = self.tree.getroot()
        dfElt = root.find('CameraConfig/postprocessing/depthfilterparameters')
        dfElt.set('do_threshold', "1")
        dfElt.set('threshold_near', str(threshold_near))
        dfElt.set('threshold_far', str(threshold_far))

    def setheight(self, height_min, height_max):
        root = self.tree.getroot()
        ppElt = root.find('CameraConfig/postprocessing')
        ppElt.set('height_min', str(height_min))
        ppElt.set('height_max', str(height_max))

    def setsystemparam(self, name, value):
        root = self.tree.getroot()
        sysElt = root.find('CameraConfig/system')
        value = str(value)
        sysElt.set(name, value)

    def setfilterparam(self, name, value):
        root = self.tree.getroot()
        dfElt = root.find('CameraConfig/postprocessing/depthfilterparameters')
        value = str(value)
        dfElt.set(name, value)
#endcode cameraconfig.xml

filenames = glob.glob('cwipc-sxr-dataset/**/*.xml', recursive=True)
for filename in filenames:
    cameraconfig = CameraConfig(filename, read=True)

    #create copy
    cameraconfig.savef(filename+'_old')

    #we rotate 180degrees on y axis
    r_angle = np.radians(180)
    ry_matrix = [[np.cos(r_angle), 0, np.sin(r_angle), 0],
                [0, 1, 0, 0],
                [-np.sin(r_angle), 0, np.cos(r_angle), 0],
                [0, 0, 0, 1]]
    m = 0
    for matrix in cameraconfig.matrices:
        nmatrix = np.asarray(ry_matrix) @ np.asarray(matrix) #nice discovery: if we invert the multiplication order, the result is the point of view of each of the cameras
        cameraconfig.setmatrix(m, nmatrix)
        m+=1

    #save modified cameraconfig
    cameraconfig.save()


import sys
import time

import yaml
from actions.command import CommandAction

from actions.gui import (
    ClickAction,
    FindTextAction,
    KeySequenceAction,
    MATCH_STRATEGY,
    ScreenShot,
    ScrollForAppear,
    TypeWriteAction,
    WaitForAppear,
    WaitUntilVisible,
)

actions = [
    ClickAction,
    CommandAction,
    FindTextAction,
    KeySequenceAction,
    ScreenShot,
    ScrollForAppear,
    TypeWriteAction,
    WaitForAppear,
    WaitUntilVisible,
]

name_to_action = {action.instruction_type: action for action in actions}

def parse_step(step, defaults_provider=None):
    action = name_to_action[step["type"]]

    required = {arg: step[arg] for arg in action.required}
    optional = {arg: step[arg] for arg in action.optional if arg in step}

    if defaults_provider is not None:
        optional = {
            **{
                key: value
                for key, value in defaults_provider.items()
                if key in action.optional
            },
            **optional,
        }

    return action(**required, **optional)

def run_yaml(path):
    with open(path) as fp:
        instruction = yaml.safe_load(fp)

    defaults_provider = {}
    default_match_strategy = MATCH_STRATEGY.DEFAULT
    default_sleep = 1
    if instruction[0]["type"] == "config":
        default_sleep = instruction[0].get("between_sleep", 1)
        default_match_strategy = instruction[0].get(
            "default_match_strategy", default_match_strategy
        )
        instruction[:] = instruction[1:]

    defaults_provider["strategy"] = default_match_strategy

    actions = [parse_step(step, defaults_provider) for step in instruction]
    all_actions_len = len(actions)

    for i, (action, step) in enumerate(zip(actions, instruction), start=1):
        print(f"RUNNING ({i}/{all_actions_len}) {step['type']}:", action.name)
        time.sleep(step.get("before_sleep", 0))
        action.run()
        time.sleep(step.get("after_sleep", default_sleep))

if __name__ == "__main__":
    run_yaml(sys.argv[1])


from collections import namedtuple
import torch
import torch.nn as nn
from torchvision import models

class VGG16(nn.Module):
    """
    modified version of VGG16 model to access activations from

    middle layers for neural style transfer.
    """

    def __init__(self, requires_grad=True):
        super().__init__()

        self.slice1 = nn.Sequential()
        self.slice2 = nn.Sequential()
        self.slice3 = nn.Sequential()
        self.slice4 = nn.Sequential()

        # NOTE: change False to TRUE before actual training on colab
        vgg_pretrained_features = models.vgg16(pretrained=True).features

        for x in range(4):
            self.slice1.add_module(str(x), vgg_pretrained_features[x])

        for x in range(4, 9):
            self.slice2.add_module(str(x), vgg_pretrained_features[x])

        for x in range(9, 16):
            self.slice3.add_module(str(x), vgg_pretrained_features[x])

        for x in range(16, 23):
            self.slice4.add_module(str(x), vgg_pretrained_features[x])

        for param in self.parameters():
            param.requires_grad = requires_grad

    def forward(self, x):
        h = self.slice1(x)
        h_relu1_2 = h
        h = self.slice2(h)
        h_relu2_2 = h
        h = self.slice3(h)
        h_relu3_3 = h
        h = self.slice4(h)
        h_relu4_3 = h
        vgg_outputs = namedtuple('VggOutputs', ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3'])
        out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3)
        return out


import numpy as np
import time
from scipy.optimize import fmin
from computeX import computeX
from draw import draw
from movePoints import movePoints
import matplotlib.pyplot as plt

def folding_opt(fig, points, edges, creases, faces, rhoT, maxIter, outfile):
    size_crease = len(creases)
    w0 = 0.8
    w1 = 0.2
    w2 = 0.01
    w = w0
    D = 0.015

    rho_series = np.zeros((maxIter, size_crease))
    rho_delta = np.zeros((1, size_crease))
    rho_delta = np.reshape(rho_delta, size_crease)
    points0 = points
    crease_vect = points[creases[:, 1]]-points[creases[:, 0]]
    print(crease_vect)
    count = [1]
    draw(fig, points, edges, creases, outfile, count)
    for i in range(500):
        if np.linalg.norm(rho_delta - rhoT, 1) < 1e-2:
            print("convergence reached: err = 1e-2")
            break
        rho_rand = np.random.uniform(-np.pi, np.pi, (1, size_crease))
        rho_rand = np.reshape(rho_rand, size_crease)
        mapd = map(lambda x: -1 if x < 0 else 1, rhoT)
        rho_rand = np.array([val*rho_rand[j] for j, val in enumerate(mapd)])
        direc = (1-w)*rho_rand + w*rhoT
        rho_tau = rho_delta + D * direc
        rho = findFoldable(rho_tau, points0, creases)
        condi1 = isValid(rho)
        condi2 = (np.linalg.norm((rhoT-rho), 1) <
                  np.linalg.norm((rhoT-rho_delta), 1))
        if condi1 and condi2:
            rho_delta = rho
            w = w + w1
            rho_series[i] = rho
            points = movePoints(points0, crease_vect, faces, rho)
            draw(fig, points, edges, creases, outfile, count)
        else:
            w = w - w2
        w = max(min(w, 1), 0)
    points = movePoints(points0, crease_vect, faces, rho)
    print(rho)
    draw(fig, points, edges, creases, outfile, count)
    return rho_series

def isValid(rho):
    if True in (np.absolute(rho) > np.pi):
        return False
    else:
        return True

def findFoldable(rho_tau, points, creases):
    rho_opt = fmin(targetFunc, rho_tau, args=(points, creases), ftol=1.0e-3)
    return rho_opt

def targetFunc(rho, points, creases):
    vertices = np.unique(creases[:, 0])
    F = 0
    for i in range(vertices.size):
        X = np.identity(4)
        for j in range(len(creases)):
            if creases[j][0] == vertices[i]:
                creases_vect = points[creases[j][1]] - points[creases[j][0]]
                X = np.dot(X, computeX(creases_vect, rho[j],
                           points[vertices[i]]))
        F += np.linalg.norm((X-np.identity(4)), 1)
    return F


import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import numpy as np
from scipy.special import gammaln
from scipy.stats import kendalltau

# The date to process
dt = "2012-04-01"

# Create a set of graphs in one pdf file.
pdf = PdfPages("internet_%s.pdf" % dt)

# Load the traffic statistics (one record per minute
# within a day).
df = pd.read_csv("traffic_stats_%s.csv" % dt)

# Rename the columns
cname = {"Traffic": "Total traffic", "UDP": "UDP", "TCP": "TCP",
         "Sources": "Unique sources"}

# Plot each column of data (total traffic, distinct sources,
# UDP traffic, TCP traffic).
for i in range(4):
    plt.clf()
    plt.axes([0.17, 0.1, 0.75, 0.8])
    plt.plot(df.iloc[:, 2+i])
    plt.grid(True)
    plt.xlabel("Minutes", size=15)
    plt.ylabel(cname[df.columns[2+i]], size=15)
    pdf.savefig()

# Plot the quantile functions for each traffic statistic.
for i in range(4):
    plt.clf()
    plt.axes([0.17, 0.1, 0.75, 0.8])
    pp = np.linspace(0, 1, df.shape[0])
    plt.plot(pp, np.sort(df.iloc[:, 2+i]))
    plt.grid(True)
    plt.xlabel("Probability point", size=15)
    plt.ylabel(cname[df.columns[2+i]] + " quantile", size=15)
    pdf.savefig()

# Plot the entropy data
ent = pd.read_csv("entropy_minute_%s.csv" % dt, header=None)
plt.clf()
plt.plot(ent)
plt.grid(True)
plt.xlabel("Minutes", size=15)
plt.ylabel("Destination port entropy", size=15)
pdf.savefig()

# Return ICC for blocks of length m minutes.
def anova(x, m):
    y = np.reshape(x, (-1, m)) # hours by minutes
    w = y.var(1).mean()
    b = y.mean(1).var()
    t = y.var()
    return b/t

print("            ICC")
print("       60m       240m")
for x in df.Traffic, df.Sources, df.TCP, df.UDP:
    x = np.asarray(x)
    print("%10.3f %10.3f" % (anova(x, 60), anova(x, 240)))

# Calculate the Kendall's tau autocorrelation for z at lag k.
def kt(z, k):
    n = len(z)
    x = z[0:n-k]
    y = z[k:n]
    return kendalltau(x, y).correlation

# Calculate all the Kendall's tau autocorrelation values (for
# each data series, at different lags).
# f[j, k, t] is the tau-autocorrelations for series j (e.g.
# total traffic) differenced to order k at lag t.
f = []
for j in range(4):
    v = []
    # Difference the series at various orders
    for diffo in 0, 1, 2:
        z = df.iloc[:, 2+j]
        if diffo > 0:
            z = np.diff(z, diffo)
        u = []
        for k in range(1, 241):
            u.append(kt(z, k))
        u = np.asarray(u)
        v.append(u)
    f.append(v)
f = np.asarray(f)

# Plot the tau autocorrelations as time series
# k = order of differencing
for k in range(3):
    plt.clf()
    plt.grid(True)
    for j in range(4):
        x = np.arange(k, 240)
        plt.plot(x, f[j, k, k:], label=cname[df.columns[2+j]])
    plt.xlabel("Lag minutes", size=15)
    plt.ylabel("Tau-autocorrelation", size=15)
    plt.title("Order %d differences" % k)
    ha,lb = plt.gca().get_legend_handles_labels()
    leg = plt.figlegend(ha, lb, "upper center", ncol=4)
    leg.draw_frame(False)
    pdf.savefig()

# Get null quantiles for Kendall's tau
def kt0():
    z = []
    for j in range(100):
        y = np.random.normal(size=24*60)
        v = [kt(y, k) for k in range(1, 241)]
        v = np.asarray(v)
        z.append(v)
    z = np.asarray(z)
    z.sort(1)
    z.sort(0)
    return z

z0 = kt0()

# Plot the tau autocorrelations as quantile functions relative to null
# k = order of differencing
for k in range(3):

    for j in range(4):
        y = f[j, k, k:]
        plt.clf()
        plt.grid(True)
        mn = y.min()
        mx = y.max()
        plt.plot([mn, mx], [mn, mx], '-', color='orange')
        plt.plot(z0[5, k:], np.sort(y), color='grey')
        plt.plot(z0[50, k:], np.sort(y), color='blue')
        plt.plot(z0[95, k:], np.sort(y), color='grey')
        plt.ylabel("Observed tau autocorrelation", size=15)
        plt.xlabel("Null tau autocorrelation", size=15)
        plt.title(cname[df.columns[2+j]] + " order %d differences" % k)
        pdf.savefig()

# Calculate the binomial coefficient "n choose m".
def bincoeff(n, m):
    return np.exp(gammaln(n + 1) - gammaln(n - m + 1) - gammaln(m + 1))

# Calculate the l-moment of order k, for the data vector x.
# The order (k) must be equal to 1, 2, 3, or 4.
def lmoment(x, k):

    n = len(x)
    x = np.sort(x)
    ii = np.arange(1, n + 1, dtype=np.float64)

    if k == 1:
        return np.mean(x)
    elif k == 2:
        c = 2*ii - n - 1
        c /= bincoeff(n, 2)
        c /= 2
        return np.dot(x, c)
    elif k == 3:
        c = bincoeff(ii-1, 2) - 2*(ii-1)*(n-ii) + bincoeff(n-i, 2)
        c /= bincoeff(n, 3)
        c /= 3
        return np.dot(x, c)
    elif k == 4:
        c = bincoeff(ii-1, 3) - 3*bincoeff(ii-1, 2)*(n-ii) + 3*(ii-1)*bincoeff(n-ii, 2) - bincoeff(n-ii, 3)
        c /= bincoeff(n, 4)
        c /= 4
        return np.dot(x, c)

# Calculate the first four L-moments of all outcomes,
# for each hour within a day.
lmom = np.zeros((24, 16))
ii = 0
for hour in range(24):
    x = df.iloc[ii:ii+60, 2:].values
    ii += 60
    u = []
    for k in range(4):
        for j in range(1, 5):
            u.append(lmoment(x[:, k], j))
    u = np.asarray(u)
    lmom[hour, :] = u

# Plot each L moment (calculated by hour) as a function of time.
jj = 0
for k in range(4):
    for j in range(4):
        plt.clf()
        plt.axes([0.2, 0.1, 0.75, 0.8])
        plt.grid(True)
        plt.plot(lmom[:, jj])
        plt.xlabel("Hour", size=15)
        plt.ylabel("L-moment of order %d" % (j + 1), size=15)
        plt.title(cname[df.columns[2 + k]])
        pdf.savefig()
        jj += 1

# Calculate the Hurst index using means and variances.
def hurst(x):
    z = []
    # m is the block size
    for m in 15, 30, 60:
        y = np.reshape(x, (-1, m))
        v = y.mean(1).var()
        z.append([m, v])
    z = np.log(np.asarray(z))
    c = np.cov(z.T)
    b = c[0, 1] / c[0, 0]
    return b/2 + 1

# Calculate the Hurst index using absolute values.
def hurstabs(x):
    z = []
    # m is the block size
    for m in 15, 30, 60:
        y = np.reshape(x, (-1, m))
        v = np.mean(np.abs(y.mean(1)))
        z.append([m, v])
    z = np.log(np.asarray(z))
    c = np.cov(z.T)
    b = c[0, 1] / c[0, 0]
    return b + 1

# Calculate the Hurst index two ways, for all four data series.
print("Hurst parameters:")
for j, x in enumerate([df.Traffic, df.Sources, df.UDP, df.TCP]):
    print(df.columns[2+j])
    for diffo in range(3):
        x = np.asarray(x, dtype=np.float64)
        z = np.diff(x, diffo)
        z = z[0:60*(len(z)//60)]
        z -= z.mean()
        print("    %4d %7.3f %7.3f" % (diffo, hurst(z), hurstabs(z)))

# Use regularized regression to study the autoregressive structure of the
# traffic and unique sources series.

from numpy.lib.stride_tricks import as_strided
import statsmodels.api as sm

labs = ["Traffic", "Sources", "UDP", "TCP"]
for j,x in enumerate([df.Traffic, df.Sources, df.UDP, df.TCP]):

    x = np.asarray(x)
    x = np.log(x)
    x -= x.mean()

    # This is a trick to lag the data without copying
    z = as_strided(x, shape=(len(x)-30, 30), strides=(8, 8))

    y = z[:, 0]
    x = z[:, 1:30]

    # Use four approaches to regression
    for jj in 0, 1, 2, 3:

        params = []

        if jj == 0:
            title = "OLS"
            result = sm.OLS(y, x).fit()
            params.append(result.params)
        elif jj == 1:
            title = "Ridge"
            for alpha in 0.001, 0.01, 0.1:
                result = sm.OLS(y, x).fit_regularized(alpha=alpha, L1_wt=0)
                params.append(result.params)
        elif jj == 2:
            title = "Lasso"
            for alpha in 0.001, 0.01, 0.1:
                result = sm.OLS(y, x).fit_regularized(alpha=alpha, L1_wt=1)
                params.append(result.params)
        elif jj == 3:
            title = "Elastic net"
            for alpha in 0.00001, 0.001, 0.1:
                result = sm.OLS(y, x).fit_regularized(alpha=alpha, L1_wt=0.1)
                params.append(result.params)

        plt.clf()
        plt.title(labs[j] + " " + title)
        for p in params:
            plt.plot(np.arange(1, len(p)+1), p)
        plt.xlabel("Lag", size=15)
        plt.ylabel("Coefficient", size=15)
        plt.grid(True)
        plt.ylim(-1, 1)
        pdf.savefig()

pdf.close()


"""
this scripts fixes the encoding of some non-UTF characters that are saved with the
Numeric character reference (for example: ç was saved as ç)
Thankfully, the html library can unescape these characters for so we can write the
text back as UTF
"""
import numpy as np

def format_data(df):
    # remove last column, its empty
    df.drop(df.columns[len(df.columns) - 1], axis=1, inplace=True)

    # some authors and editors names have a : at the end, remove that
    def RemoveColon(string):
        return string.replace(':', '')

    df['authors'] = df['authors'].astype(str).apply(RemoveColon)
    df['editors'] = df['editors'].astype(str).apply(RemoveColon)

    # replace all \N with NaN (pandas like it this way)
    df.replace("\\N", np.NaN, inplace=True)
    df.replace('nan', np.NaN, inplace=True)
    print('fixed again nan')

    """
    as per Email from PIK:
    Das was unter "keywords" steht sind die
    alten Abteilungsnamen, die bis vor der Evaluation des Instituts in den 2000ern Bestand
    hatten. Danach wurden neue Domainnamen gebildet - die ab diesem Zeitpunkt im Feld x9
    hinterlegt sind. Tats?chliche Keywords liegen also, wenn vorhanden, in Feld "x1".

    however, the field x9 does not exist in the data we received
    """
    df.rename(columns={
        'keywords': 'oldDepartmentNames',
        'x1 ( =Feld "Keyword";  u.a. belegt mit Info zu peer-review, wenn kein ISI-Journal)': 'keywordsAndPeerReview',
        'x4 ( = DOI / Identifier)': 'DOI',
        'relation (= Serie)': 'series'
    }, inplace=True)

    return df