from manimlib import *
from manim import *
import numpy as np

class IntegralDivision1(Scene):
    def construct(self):
        # formula = MathTex("\\int {f'(x) \\over f(x)} dx = \\ln |f(x)| + C")
        # titulo = Text("Una fórmula nos dice que").next_to(formula, UP, buff=1)
        # self.play(Write(titulo))
        # self.add(formula)
        # self.play(Write(MathTex("\\text{pero, ¿qué pasa si no se puede conseguir} ~ f'(x) ~ \\text{en el numerador?}").next_to(formula, DOWN, buff=1)))
        #
        # self.wait(3)
        # self.clear()
        # self.play(Write(Text("Cuando esto pase, vamos a distinguir dos casos: ").move_to(UP).set_width(10)))
        # self.play(Write(Tex('$\\bullet$ El grado del numerador es mayor (o igual) que el del denominador \\\\',
        #                         '$\\bullet$ El grado del numerador es menor que el del denominador \\\\').set_width(11)))
        # self.wait(4)
        # self.clear()
        #
        caso1 = Text("Primer caso").to_edge(UL).scale(0.6)
        self.add(caso1)

        texto_aux = Text("En este caso, tenemos que dividir los dos polinomios. Por ejemplo:").scale(0.5)
        texto_aux2 = Text("En este caso, tenemos que dividir los dos polinomios. Por ejemplo:").to_edge(UL).scale(0.3).shift(2*LEFT)
        self.play(Write(texto_aux))
        self.wait()
        self.play(ReplacementTransform(texto_aux, texto_aux2))
        polinomio1_texto = "x^4 + 3x^3 + 6x^2 -2x"
        polinomio2_texto = "x^2 - 4"
        polinomio1 = MathTex(polinomio1_texto)
        polinomio2 = MathTex(polinomio2_texto)
        texto_aux = MathTex("\\int {", polinomio1_texto, "\\over", polinomio2_texto, "} dx")
        texto_aux2 = MathTex("\\int {x^4 + 3x^3 + 6x^2 - 2x \\over x^2 -4} dx").scale(0.4).next_to(caso1, DOWN)
        self.play(Write(texto_aux))
        self.wait()
        self.play(ReplacementTransform(texto_aux, texto_aux2))

        linea_vert = Line(color=WHITE, stroke_width=4).set_length(0.8).rotate(PI/2).next_to(polinomio2, LEFT, buff=0.1)
        linea_hor = Line(color=WHITE, stroke_width=4).set_length(1.6).next_to(polinomio2, DOWN, buff=0.16)
        polinomio1.next_to(polinomio2, LEFT, buff=0.5)
        division = VGroup(polinomio1, polinomio2, linea_vert, linea_hor).shift(UP*1.5)
        self.add(division)
        self.wait()

        circulo1 = Circle(stroke_color=RED, stroke_width=2, radius=0.37).move_to(polinomio2.get_center()).shift(LEFT*0.45)
        circulo2 = Circle(stroke_color=RED, stroke_width=2, radius=0.37).move_to(polinomio1.get_center()).shift(LEFT*2)
        self.add(circulo1)
        self.add(circulo2)
        self.wait()

        multiplicacion = MathTex("x^2 \\cdot ? = x^4").next_to(division, RIGHT, buff=2)
        multiplicacion2 = MathTex("x^2 \\cdot x^2 = x^4").next_to(division, RIGHT, buff=2)
        self.play(ReplacementTransform(VGroup(circulo1.copy(), circulo2.copy()), multiplicacion), run_time=1.5)
        self.wait()
        self.play(ReplacementTransform(multiplicacion, multiplicacion2))
        self.play(FadeOut(circulo2, circulo1))
        primer_mon = MathTex("x^2").next_to(linea_hor, DOWN, buff=0.15).shift(LEFT*0.45)
        self.play(Write(primer_mon))
        self.wait()
        self.play(FadeOut(multiplicacion2))

        multiplicacion = MathTex("x^2 \cdot (x^2 -4) = ").next_to(division, RIGHT, buff=1)
        circulo2 = Circle(radius=0.37, stroke_color=RED, stroke_width=2).move_to(primer_mon.get_center())
        ovalo = Ellipse(width=1.7, height=1, stroke_color=RED, stroke_width=2).move_to(polinomio2.get_center())
        self.add(circulo2)
        self.add(ovalo)
        self.wait()
        self.play(ReplacementTransform(VGroup(circulo2, ovalo).copy(), multiplicacion))
        self.play(FadeOut(circulo2, ovalo))
        resultado = MathTex("x^4 - 4x^2").next_to(multiplicacion, RIGHT)
        self.wait(0.5)
        self.play(Write(resultado))
        resultado_restar = resultado.copy().next_to(polinomio1, DOWN).shift(LEFT*1.3)
        self.play(ReplacementTransform(resultado.copy(), resultado_restar))

        self.play(FadeOut(resultado, multiplicacion))
        linea_resta = Line(color=WHITE, stroke_width=4).set_length(4.7).move_to(resultado_restar.get_center()).shift(DOWN*0.5+RIGHT*1.3)
        self.play(Write(linea_resta))
        resultado_restar_signo = MathTex("-x^4 + 4x^2").next_to(polinomio1, DOWN).shift(LEFT*1.5)
        self.play(ReplacementTransform(resultado_restar, resultado_restar_signo))
        self.wait()

        resultado_resta = MathTex("3x^3 + 10x^2 - 2x").next_to(linea_resta, DOWN).shift(RIGHT*0.58)
        self.play(Write(resultado_resta))

        self.wait()

        circulo2 = Circle(stroke_color=RED, stroke_width=2, radius=0.45).move_to(resultado_resta.get_center()).shift(LEFT*1.35)
        self.add(circulo1)
        self.add(circulo2)
        self.wait()

        multiplicacion = MathTex("x^2 \\cdot ? = 3x^3").next_to(division, RIGHT, buff=2)
        multiplicacion2 = MathTex("x^2 \\cdot 3x = 3x^3").next_to(division, RIGHT, buff=2)
        self.play(ReplacementTransform(VGroup(circulo1.copy(), circulo2.copy()), multiplicacion), run_time=1.5)
        self.wait()
        self.play(ReplacementTransform(multiplicacion, multiplicacion2))
        self.play(FadeOut(circulo2, circulo1))
        segundo_mon = MathTex("x^2+3x").next_to(linea_hor, DOWN, buff=0.15).shift(RIGHT*0.11)
        self.play(ReplacementTransform(primer_mon, segundo_mon))
        self.play(FadeOut(multiplicacion2))

        circulo2 = Circle(radius=0.4, stroke_color=RED, stroke_width=2).move_to(segundo_mon.get_center()).shift(RIGHT*0.52)
        self.add(circulo2)
        self.add(ovalo)
        self.wait()

        multiplicacion = MathTex("3x \\cdot (x^2 -4) = ").scale(0.8).next_to(division, RIGHT, buff=1)

        self.play(ReplacementTransform(VGroup(circulo2, ovalo).copy(), multiplicacion))
        self.play(FadeOut(circulo2, ovalo))
        resultado = MathTex("3x^3 - 12x").scale(0.8).next_to(multiplicacion, RIGHT)
        self.wait(0.5)
        self.play(Write(resultado))

        resultado_resta2 = resultado.copy().scale(1.25).next_to(resultado_resta, DOWN).shift(LEFT*0.7)
        self.play(ReplacementTransform(resultado.copy(), resultado_resta2))

        linea_resta2 = Line(color=WHITE, stroke_width=4).set_length(3.7).move_to(resultado_resta2.get_center()).shift(DOWN*0.5+RIGHT*0.8)
        self.play(Write(linea_resta2))
        resultado_resta2_signo = MathTex("-3x^3 + 12x").move_to(resultado_resta2.get_center()).shift(LEFT*0.2)

        self.play(ReplacementTransform(resultado_resta2, resultado_resta2_signo))

        resultado_resta3 = MathTex("10x^2 + 10x").next_to(linea_resta2.get_center(), DOWN).shift(RIGHT*0.6)
        self.play(FadeOut(multiplicacion, resultado))
        self.play(Write(resultado_resta3))

        circulo2 = Circle(radius=0.53, stroke_color=RED, stroke_width=2).move_to(resultado_resta3.get_center()).shift(LEFT*0.73)
        self.add(circulo2)
        self.add(circulo1)
        self.wait()

        multiplicacion = MathTex("x^2 \\cdot ? = 10x^2").next_to(division, RIGHT, buff=2)
        multiplicacion2 = MathTex("x^2 \\cdot 10 = 10x^2").next_to(division, RIGHT, buff=2)
        self.play(ReplacementTransform(VGroup(circulo1.copy(), circulo2.copy()), multiplicacion), run_time=1.5)
        self.wait()
        self.play(ReplacementTransform(multiplicacion, multiplicacion2))
        self.play(FadeOut(circulo2, circulo1))

        tercer_mon = MathTex("x^2+3x+10").next_to(linea_hor, DOWN, buff=0.15).shift(RIGHT * 0.7)
        self.play(ReplacementTransform(segundo_mon, tercer_mon))
        self.play(FadeOut(multiplicacion2))

        circulo2 = Circle(radius=0.35, stroke_color=RED, stroke_width=2).move_to(tercer_mon.get_center()).shift(
            RIGHT*1.14)
        self.add(circulo2)
        self.add(ovalo)
        self.wait()

        multiplicacion = MathTex("10 \\cdot (x^2 -4) = ").scale(0.8).next_to(division, RIGHT, buff=1)

        self.play(ReplacementTransform(VGroup(circulo2, ovalo).copy(), multiplicacion))
        self.play(FadeOut(circulo2, ovalo))
        resultado = MathTex("10x^2 - 40").scale(0.8).next_to(multiplicacion, RIGHT)
        self.wait(0.5)
        self.play(Write(resultado))

        resultado_resta4 = resultado.copy().scale(1.25).next_to(resultado_resta3, DOWN).shift(LEFT*0.15)
        self.play(ReplacementTransform(resultado.copy(), resultado_resta4))
        self.play(FadeOut(multiplicacion, resultado))
        linea_resta3 = Line(color=WHITE, stroke_width=4).set_length(2.8).next_to(resultado_resta4, DOWN).shift(RIGHT*0.15)
        self.play(Write(linea_resta3))

        resultado_resta4_signo = MathTex("-10x^2 + 40").move_to(resultado_resta4.get_center()).shift(LEFT*0.2)
        self.play(ReplacementTransform(resultado_resta4, resultado_resta4_signo))

        resultado_resta5 = MathTex("10x + 40").next_to(linea_resta3, DOWN).shift(LEFT*0.25)
        self.play(Write(resultado_resta5))

        division_total = VGroup(division, resultado_restar_signo, linea_resta, tercer_mon, resultado_resta,
                                resultado_resta3, resultado_resta2_signo, linea_resta2, resultado_resta5, linea_resta3, resultado_resta4_signo)
        division_chica = division_total.scale(0.8).shift(UP*0.7+LEFT*1)
        # self.play(FadeTransform((division_total, division_chica)))
        self.play(ReplacementTransform(division_total, division_chica))

        dividendo = MathTex("x^4 + 3x^3 + 6x^2 - 2x = ").scale(0.8).next_to(linea_resta2, RIGHT, buff=1.1)
        # igual = Tex("=").next_to(dividendo, DOWN).scale(0.8).shift(LEFT*1.5)
        cociente = MathTex("= (x^2 + 3x + 10)").next_to(dividendo, RIGHT).scale(0.8)
        # por = Tex("\\cdot").next_to(cociente, RIGHT, buff=0.1).scale(0.8)
        divisor = MathTex("\\cdot (x^2 -4)").next_to(cociente, RIGHT).scale(0.8)
        # mas = Tex("+").next_to(divisor, RIGHT, buff=0.1).scale(0.8)
        resto = MathTex("+(10x+40)").next_to(divisor, RIGHT).scale(0.8)

        self.play(Write(dividendo))
        # self.play(Write(igual))
        self.play(Write(cociente))
        # self.play(Write(por))
        self.play(Write(divisor))
        # self.play(Write(mas))
        self.play(Write(resto))

        self.wait(3)


from cv2 import cv2

############Capture LiveFeed from Camera and save it##############

cap = cv2.VideoCapture('Megamind.avi')
#1 -- For second camera
#0 -- For default camera
#n -- For nth camera
# file_name -- For video file input

#############Save input from video##########
fourcc=cv2.VideoWriter_fourcc(*'mp4v') #video codec format, more at www.fourcc.org
out=cv2.VideoWriter('ouput.avi',fourcc,20,(720,1280)) #filename,video codec, fps, frame size

open = cap.isOpened() #checks if the videocapture ftn target source is available
while(open):
    ret,frame = cap.read()
    #ret = bool - true if frame available else false
    #frame - the captured frame
    if ret:
        #save captured frame
        out.write(frame)

        #features of frame
        width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
        height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
        print("Height = ",height," Width = ",width)

        #Make frame gray
        frame_gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        cv2.imshow('Capture Frame',frame_gray)
        if cv2.waitKey(50)== ord('q'): #stop video feed if q pressed
            break

cap.release()
out.release()
cv2.destroyAllWindows()

LyndaOpenCv Exercises and Assignments/Chap2/Optional2.py


import sys
import importlib
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from ..base import Task
from .watch_metadata import WatchMetadata

class TaskReloaderTask(Task):
    """
    This task monitors the source code files of all tasks registered to the runner.
    If a file is modified it is reloaded on next execution, all tasks in the file are removed and added again to the runner with the new code.
    Key features:
        - Can reload its own code
        - Can handle multiple tasks in the same file
        - Can handle tasks being added/removed from runner between executions.
    NOTE: Only the file with the task class will be reloaded. If you modify another file and want to reload a task, restart the runner.
    """
    def __clear_removed_task_from_watch_data(self):
        for watch_metadata in self._watch_data.values():
            # set intersection
            watch_metadata.task_names &= set(self.runner.task_data.keys())

    def __add_new_tasks_to_watch_data(self):
        for task_metadata in self.runner.task_data.values():
            task_module = self._get_task_module(task_metadata)
            task_file = task_module.__file__

            if task_file not in self._watch_data:
                watch = self._fs_observer.schedule(self._fs_handler, task_file)
                self._watch_data[task_file] = WatchMetadata(watch, task_module, set())
                self.logger.info(f"Started monitoring file \"{task_file}\"")

            self._watch_data[task_file].task_names.add(task_metadata.name)

    def __clear_stale_watches_from_watch_data(self):
        for path, watch_metadata in self._watch_data.items():
            if len(watch_metadata.task_names) == 0:
                self._fs_observer.unschedule(watch_metadata.watch)
                self._watch_data.pop(path)
                self.logger.info(f"Stopped monitoring file \"{path}\"")

    @staticmethod
    def _get_task_module(task_metadata):
        return sys.modules[task_metadata.task_type.__module__]

    def _on_file_modified(self, event):
        watch_metadata = self._watch_data[event.src_path]
        watch_metadata.should_reload = True
        self.logger.info(f"File \"{event.src_path}\" was modified. Reloading on next execution.")

    def _update_watch_data(self):
        self.__clear_removed_task_from_watch_data()
        self.__add_new_tasks_to_watch_data()
        self.__clear_stale_watches_from_watch_data()

        self.logger.debug(f"Updated watch metadata. Current state:\n{self._watch_data}")

    def _reload_tasks(self, watch_metadata):
        self.logger.info(f"Reloading file \"{watch_metadata.watch.path}\". Tasks in file: {watch_metadata.task_names}")
        tasks_module = importlib.reload(watch_metadata.module)

        for name in watch_metadata.task_names:
            task_metadata = self.runner.task_data[name]
            self.runner.remove_task(name)
            task_metadata.task_type = getattr(tasks_module, task_metadata.task_type.__name__)
            self.runner.add_task(task_metadata)

    def setup(self):
        self._watch_data = {}
        self._fs_handler = FileSystemEventHandler()
        self._fs_handler.on_modified = self._on_file_modified
        self._fs_observer = Observer()
        self._fs_observer.start()

    def teardown(self):
        self._fs_observer.stop()
        self._fs_observer.join()
        self.logger.info("Stopped monitoring all files.")

    def execute(self):
        self._update_watch_data()
        for watch_metadata in self._watch_data.values():
            if watch_metadata.should_reload:
                self._reload_tasks(watch_metadata)
                watch_metadata.should_reload = False


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

import os
import json

from typing import Union
from functools import reduce
from copy import deepcopy

from .file_helper import FileHelper

DEFAULT_CONF_FILE='config.json'

class Configuration:

    __cache = {}

    __instance = None

    def __init__(self,
                 conf_dir='~/.labor',
                 conf_file_name=DEFAULT_CONF_FILE):

        if Configuration.__instance is not None:
            raise Error('this is a singleton, use get_instance function instead!')

        self.file_helper = FileHelper()

        self.conf_dir = conf_dir
        self.conf_file_name = conf_file_name

        self.load()

        Configuration.__instance = self

    @staticmethod
    def get_instance():

        if Configuration.__instance is None:
            Configuration()

        return Configuration.__instance

    def get_full_path(self):
        """
        Returns the full path of the conf file

        Returns
        -------
            str
        """

        return os.path.join(self.conf_dir, self.conf_file_name)

    @property
    def conf_file_name(self):

        return self.__conf_file_name

    @conf_file_name.setter
    def conf_file_name(self, conf_file_name):
        self.__conf_file_name = conf_file_name

    def get(self, key: str):
        """
        Returns a cached conf using a path key

        Parameters
        ----------
            key {str}
        """

        data = deepcopy(self.__cache)

        for k in key.split('.'):

            if data.get(k) is None:
                return None

            data = data.get(k)

        return data

    def put(self, key: str, data: Union[dict, str, bool, int]):
        """
        Insert or update a value using a key address

        Parameters
        ----------
            key: {str} | Ex: 'path.to.your.key'
        """

        if key is None:
            return None

        keys = key.split('.')
        keys.reverse()
        final_key = keys.pop(0)

        final_data = reduce(lambda acc, n_key: {n_key: acc}, keys, {final_key: data})

        self.__cache = {**self.__cache, **final_data}

        self.write()

        return self

    def write(self):
        """
        Save the cached data

        Returns
        -------
            self
        """

        self.file_helper.save_json(
                self.__cache,
                self.conf_dir,
                self.conf_file_name
                )

        return self

    def load(self):

        self.__cache = self.file_helper.load_json(self.get_full_path()) or {}

        return self


from random import randint

from django.http import HttpResponseNotFound, HttpResponseServerError
from django.shortcuts import render

import tours.data as data

# Create your views here.

def main_view(request):
    random_tours = tuple(randint(1, 6) for _ in range(len(data.tours)))
    tours = {"tours": {}}
    for id in random_tours:
        tours["tours"][id] = data.tours[id]
    return render(request, 'index.html', tours)

def departure_view(request, departure):
    departure_from = data.departures.get(departure, None)
    if not departure_from:
        return HttpResponseServerError("Данной страны отправления не существует")

    tours = {
        "departure": f'{departure_from[0].lower()}{departure_from[1:]}',
        "tours": dict(filter(lambda elem: elem[1]["departure"] == departure, data.tours.items()))
    }
    if not tours["tours"]:
        return render(request, 'departure.html', tours)

    total = len(tours["tours"])
    prices = tuple(map(lambda _tour: _tour["price"], tours["tours"].values()))
    nights = tuple(map(lambda _tour: _tour["nights"], tours["tours"].values()))
    tours["total"] = " ".join((
        f'Найдено {total} тура,',
        f'от {min(prices)} до {max(prices)}₽',
        f'и от {min(nights)} до {max(nights)} ночей',
    ))
    return render(request, 'departure.html', tours)

def tour_view(request, id):
    tour = data.tours.get(id, None)
    if not tour:
        return HttpResponseNotFound(f"Тур с {id} не найден =(")

    departure = data.departures.get(tour["departure"], None)
    if not departure:
        return HttpResponseServerError("Данной страны отправления не существует")

    nights = tour["nights"]

    view_1 = {
        "title": f'{tour["title"]} {int(tour["stars"])*"★"}',
        "price": tour["price"],
        "description": tour["description"],
        "departure": f'{tour["country"]} {departure} {nights} ночей',
        "picture": tour["picture"]
    }
    return render(request, 'tour.html', view_1)

def custom_handler404(request, exception):
    return HttpResponseNotFound('Не верный запрос к серверу =(')

def custom_handler500(request):
    return HttpResponseNotFound('Ой, что то сломалось... Простите извините!')


print('=' * 30)
print('{:^30}' .format('BANCO LOC'))
print('=' * 30)
valor = int(input('Qual o valor que deseja sacar: R$'))
total = valor
ced = 50
totalCed = 0
while True:
    if total >= ced:
        total -= ced
        totalCed += 1
    else:
        if totalCed > 0:
            print(f'O total de {totalCed}  cédulas é de {ced}')
            if ced == 50:
                ced = 20
            elif ced == 20:
                ced = 10
            elif ced == 10:
                ced = 1
            totalCed = 0
            if total == 0:
                break
print('=' * 30)
print('OBRIGADO, VOLTE SEMPRE')


from utils import *
from fusion import *

import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.cluster import KMeans
import pickle

SHAPE_DIMENSION = 48
SHAPE_KEYPOINTS = 96
COLOR_DIMENSION = 24
PONDERATION = 0.4
RANDOM_SEED = 40
N_NEIGHBORS = 3
N_DEPTH = 8
TRANSFORMATION_PER_IMG = 20
N_ESTIMATORS = 10
CROSS_VALIDATION = 4
MODE = 'moments'
LOAD_SESSION = False

def extract_color_feature_histogram(extractor, imgs):
    masks = [create_mask(img) for img in imgs]
    label_maps = [extractor.predict(img[mask])
                  for (img, mask) in zip(imgs, masks)]
    histograms = np.array([np.bincount(lm, minlength=len(
        extractor.cluster_centers_)) / len(lm) for lm in label_maps], dtype=np.float64)
    return histograms

def extract_shape_feature_moments(imgs):
    res = []

    for i, img in enumerate(imgs):
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        height, width = img.shape
        if height > width:
            img = cv2.copyMakeBorder(
                img, 0, 0, (height - width) // 2, (height - width) // 2, cv2.BORDER_CONSTANT, value=255)
        elif width > height:
            img = cv2.copyMakeBorder(
                img, (width - height) // 2, (width - height) // 2, 0, 0,  cv2.BORDER_CONSTANT, value=255)

        img = cv2.resize(img, (100, 100))

        img = cv2.copyMakeBorder(
            img, 8, 8, 8, 8, cv2.BORDER_CONSTANT, value=255)

        img = cv2.GaussianBlur(img, (5, 5), 0)
        _, img = cv2.threshold(
            img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        img = cv2.Canny(img, 100, 200)

        # plt.imsave(f'test/{i}.png', img)

        moments = cv2.moments(img)

        hu_moments = cv2.HuMoments(moments).flatten()

        hu_moments = -np.sign(hu_moments) * np.log10(np.abs(hu_moments))

        res.append(hu_moments)

    res = np.array(res)

    return res

def extract_shape_feature_histogram(extractor, imgs):
    histograms = []
    orb = cv2.ORB_create()

    for img in imgs:
        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        keypoints = orb.detect(gray_img, None)
        if keypoints == ():
            histograms.append(np.zeros(SHAPE_DIMENSION))
            continue
        keypoints, descriptors = orb.compute(gray_img, keypoints)
        bin_assignment = extractor.predict(descriptors)
        img_feats = np.zeros(SHAPE_DIMENSION)
        for id_assign in bin_assignment:
            img_feats[id_assign] += 1
        histograms.append(img_feats)

    vec = np.array(histograms)
    return vec / SHAPE_KEYPOINTS

def feature_extractor(img_train, load_session=False, mode="moments"):

    cwd = os.getcwd()
    # During developpement
    if cwd != "/app":
        cwd += "/app"

    def color_extractor():
        if load_session == False:
            masks = [create_mask(img) for img in img_train]
            super_sample = create_super_sample(img_train, masks)
            kmean_color = KMeans(n_clusters=COLOR_DIMENSION,
                                 random_state=RANDOM_SEED)
            kmean_color.fit(super_sample)
            pickle.dump(kmean_color, open(f"{cwd}/kmean_color.pkl", "wb"))
        else:
            kmean_color = pickle.load(open(f"{cwd}/kmean_color.pkl", "rb"))

        return kmean_color

    def shape_extractor():

        if load_session == False:
            orb = cv2.ORB_create()

            list_descriptors = []

            for img in img_train:
                gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
                keypoints = orb.detect(gray_img, None)
                if keypoints == ():
                    continue
                keypoints, descriptors = orb.compute(gray_img, keypoints)
                indices = np.random.randint(
                    descriptors.shape[0], size=SHAPE_KEYPOINTS)
                desc_samples = descriptors[indices]
                list_descriptors.append(desc_samples)

            super_sample = np.vstack(list_descriptors)
            kmean_shape = KMeans(n_clusters=SHAPE_DIMENSION,
                                 random_state=RANDOM_SEED)
            kmean_shape.fit(super_sample)
            pickle.dump(kmean_shape, open(f"{cwd}/kmean_shape.pkl", "wb"))
        else:
            kmean_shape = pickle.load(open(f"{cwd}/kmean_shape.pkl", "rb"))

        return kmean_shape

    kmean_color = color_extractor()

    if (mode == 'orb'):
        print("Mode ORB ...")
        kmean_shape = shape_extractor()
        return lambda img: extract_color_feature_histogram(kmean_color, img), lambda img: extract_shape_feature_histogram(kmean_shape, img)
    else:
        print("Mode Hu moments ...")
        return lambda img: extract_color_feature_histogram(kmean_color, img), lambda img: extract_shape_feature_moments(img)

import time
if __name__ == "__main__":
    np.random.seed(RANDOM_SEED)

    print('Loading dataset...')
    dataset, labels = load_dataset("./data/train")
    print('Dataset augmentation...')

    img_train, img_test, label_train, label_test = train_test_split(
        dataset, labels, test_size=0.2, random_state=RANDOM_SEED, stratify=labels)

    img_train_aug, label_train_aug = dataset_augmentation(img_train, label_train, TRANSFORMATION_PER_IMG)

    print("Create feature extractor ...\n")
    color_feature_extractor, shape_feature_extractor = feature_extractor(
        img_train_aug, load_session=LOAD_SESSION, mode=MODE)

    early_fusion(img_train_aug, label_train_aug, img_test, label_test,
                 color_feature_extractor, shape_feature_extractor, n_neighbors=N_NEIGHBORS, n_depth=N_DEPTH, ponderation=PONDERATION)

    # late_fusion(img_train_aug, label_train_aug, img_test, label_test,
    #             color_feature_extractor, shape_feature_extractor, n_neighbors=N_NEIGHBORS, n_depth=N_DEPTH)

    # stacking_early_fusion(img_train_aug, label_train_aug, img_test, label_test, color_feature_extractor,
    #                          shape_feature_extractor, random_seed=RANDOM_SEED, n_estimators=N_ESTIMATORS, cv=CROSS_VALIDATION, ponderation=PONDERATION)

    # stacking_late_fusion(img_train_aug, label_train_aug, img_test, label_test, color_feature_extractor,
    #                          shape_feature_extractor, random_seed=RANDOM_SEED, n_estimators=N_ESTIMATORS, cv=CROSS_VALIDATION, ponderation=PONDERATION)


import os
import logging

from fastapi import FastAPI, HTTPException

from src.model.source import Source
from src.config import ONVIFSettings
from src.onvif.onvif_client import OnvifClientSettings
from src.onvif.onvif_client_device import (
    OnvifClientDevice,
    DeviceInformation,
    SystemDateTime,
    SystemUris,
)
from src.onvif.onvif_client_media import OnvifClientMedia, AudioOutputs

logging.basicConfig(
    format="%(asctime)s %(filename)s %(levelname)s: %(message)s",
    level=os.environ.get("LOGGING", "INFO"),
)

app = FastAPI()

@app.post("/api/device/get_device_information")
async def get_device_information(source: Source) -> DeviceInformation:
    try:
        client = OnvifClientDevice(
            settings=OnvifClientSettings(source=source, common=ONVIFSettings())
        )
        return await client.get_device_information()
    except Exception as exc:  # pylint: disable=broad-except
        logging.exception("Error %s, Traceback: %s", exc, exc.__traceback__)
        raise HTTPException(status_code=409, detail=str(exc)) from exc

@app.post("/api/device/get_system_date_and_time")
async def get_system_date_and_time(source: Source) -> SystemDateTime:
    try:
        client = OnvifClientDevice(
            settings=OnvifClientSettings(source=source, common=ONVIFSettings())
        )
        return await client.get_system_date_and_time()
    except Exception as exc:  # pylint: disable=broad-except
        logging.exception("Error %s, Traceback: %s", exc, exc.__traceback__)
        raise HTTPException(status_code=409, detail=str(exc)) from exc

@app.post("/api/device/get_system_uris")
async def get_system_uris(source: Source) -> SystemUris:
    try:
        client = OnvifClientDevice(
            settings=OnvifClientSettings(source=source, common=ONVIFSettings())
        )
        return await client.get_system_uris()
    except Exception as exc:  # pylint: disable=broad-except
        logging.exception("Error %s, Traceback: %s", exc, exc.__traceback__)
        raise HTTPException(status_code=409, detail=str(exc)) from exc

@app.post("/api/media/get_audio_outputs")
async def get_audio_outputs(source: Source) -> AudioOutputs:
    try:
        client = OnvifClientMedia(
            settings=OnvifClientSettings(source=source, common=ONVIFSettings())
        )
        return await client.get_audio_outputs()
    except Exception as exc:  # pylint: disable=broad-except
        logging.exception("Error %s, Traceback: %s", exc, exc.__traceback__)
        raise HTTPException(status_code=409, detail=str(exc)) from exc


"""
reverse a stack using recursion

given input : [1,2,3,4,5]
expected output : [5,4,3,2,1]
"""
from typing import List

def reverseStack(numbers: List[int]) -> List[int]:

    # base case always return value
    if len(numbers) == 1:
        return numbers

    # Hypothesis, smaller the input list
    temp = numbers[-1]
    numbers.pop()

    reverseStack(numbers)

    # induction step where temp value insert into the stack
    insertIntoStack(numbers, temp)

    return numbers

def insertIntoStack(numbers: List[int], number: int) -> List[int]:

    # base case always return value
    if len(numbers) == 0:
        numbers.append(number)
        return numbers

    # Hypothesis, smaller the input
    temp = numbers[-1]
    numbers.pop()

    insertIntoStack(numbers, number)

    numbers.append(temp)

    return numbers

if __name__ == '__main__':
    stack = [1, 2, 3, 4, 5]
    func_call = reverseStack(stack)
    expected_result = [5, 4, 3, 2, 1]
    assert expected_result == func_call, func_call
    print(func_call)

    stack = [6, 4, 9, 3, 8, 1]
    func_call = reverseStack(stack)
    expected_result = [1, 8, 3, 9, 4, 6]
    assert expected_result == func_call, func_call
    print(func_call)


nome = input("Digite seu nome: ")
nome_meio = input("Digite seu nome do meio: ")
nome_ultimo = input("Digite seu sobrenome: ")

nome_completo = (nome + " " + nome_meio + " " + nome_ultimo)

print(f"{nome_completo}")

# Criptografia

nome_cripto = ''

for indice in range(0,len(nome_completo)):
    nome_cripto += chr(ord(nome_completo[indice])+1)

print(f"{nome_cripto}")


#!/usr/bin/env python3

import os,sys,argparse
from Bio import SeqIO

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def fasta_ids(path):
    for seq in SeqIO.parse(path,'fasta'):
        yield seq.id

def main( argv = None ):

    parser = argparse.ArgumentParser()
    parser.add_argument('-i','--bin-dir',  dest='binDir', required=True, help='Directory of bins')
    parser.add_argument('-o','--output',    dest='outFile', required=True, help='Output directory of results')
    parser.add_argument('-x','--extension', dest='binExt',  default='fa',  help='Extension of bins (other files in directory are ignored)')
    opt = parser.parse_args()

    if not os.path.isdir(opt.binDir):
        eprint(f'-i|--bin-dir directory "{opt.binDir}" does not exists')
        return 1

    with os.scandir(opt.binDir) as it, open(opt.outFile,'w') as out:
        for entry in it:
            if entry.name.endswith(f'.{opt.binExt}'):
                binid = os.path.splitext(entry.name)[0]
                for seqid in fasta_ids(os.path.join(opt.binDir,entry.name)):
                    out.write(f'{seqid}\t{binid}\n')

    return 0

# Check if the program is not being imported
if __name__ == "__main__":
    sys.exit(main())


# coding: utf-8

__author__ = 'Yemilice_lau'

"""
给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。

示例 1：
输入：head = [1,2,3,4,5], k = 2
输出：[4,5,1,2,3]

输入：head = [0,1,2], k = 4
输出：[2,0,1]
"""

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head == None:
            return head

        nums = self.calculnum(head)
        k = k % nums
        c = 0

        fast = slow = head
        while c < k:
            fast = fast.next
            c += 1

        while fast.next != None:
            fast = fast.next
            slow = slow.next

        fast.next = head
        head = slow.next
        slow.next = None
        return head

    def calculnum(self, head):
        z = 0
        while head != None:
            head = head.next
            z += 1
        return z


##
# Electromagnetic radiation can be classified into one of 7 categories according to its
# frequency, as shown in the table below:
#
#   Name                Frequency Range (Hz)
#   ----------------------------------------------------------
#   Radio Waves         Less than 3 × 10**9
#   Microwaves          3 × 10**9 to less than 3 × 10**12
#   Infrared Light      3 × 10**12 to less than 4.3 × 10**14
#   Visible Light       4.3 × 10**14 to less than 7.5 × 10**14
#   Ultraviolet Light   7.5 × 10**14 to less than 3 × 10**17
#   X-Rays              3 × 10**17 to less than 3 × 10**19
#   Gamma Rays          3 × 10**19 or more
#
# Write a program that reads the frequency of some radiation from the user and
# displays name of the radiation as part of an appropriate message.
#

# user's input
user_frq = float(input("Inserisci la frequenza in GHz: "))

# convert Ghz to HZ
HZ = 1e9
frq = user_frq * HZ

# check type of radiations
if frq < 3e9:
    name = "onde radio"
elif 3e9 <= frq < 3e12:
    name = "microonde"
elif 3e12 <= frq < 4.3e14:
    name = "microonde"
elif 4.3e12 <= frq < 7.5e14:
    name = "spettro visibile"
elif 7.5e14 <= frq < 3e17:
    name = "raggi ultravioletti"
elif 3e17 <= frq < 3e19:
    name = "raggi X"
elif 3e19 <= frq :
    name = "raggi Gamma"
else:
    name = ""

# print result
if name == "":
    print("La frequenza delle radiazioni non rientra in questo spettro")
else:
    print("La frequenza di", user_frq, "Ghz corrisponde a:", name)


import glob
import config
import torchaudio, torch, tqdm, os
from utils import *

target_sample_rate = 16000

data_dir = "/home/nhandt23/Desktop/DCASE/Evaluation/"

for folder in glob.glob(data_dir + "Evaluation_audio/*"):
     for audio_file in tqdm.tqdm(glob.glob(folder+"/*")):

          # Gen Audio
          waveform, sr = torchaudio.load(audio_file)
          # print(waveform.size())
          waveform_mono = torch.mean(waveform, dim=0).unsqueeze(0)
          # print(waveform_mono.size())
          waveform_mono_16k = torchaudio.transforms.Resample(sr, target_sample_rate)(waveform_mono)
          # print(waveform_mono_16k.size())
          for id in range(int(waveform_mono_16k.size(1)/target_sample_rate)):
               wave = waveform_mono_16k[:,id*target_sample_rate:(id+1)*target_sample_rate]

               ################
               save_audio_file = audio_file.replace("Evaluation_audio", "Evaluation_audio_splited").replace(".wav","_"+str(id)+".wav")
               create_folder(os.path.dirname(save_audio_file))
               torchaudio.save(save_audio_file, wave, target_sample_rate)


import django.forms as forms
from django.core.exceptions import ValidationError
from .models import TicketPurchase, Ticket, TicketType

class TicketPurchaseForm(forms.ModelForm):
    class Meta:
        model = TicketPurchase
        fields = [
                'buyer_first_name', 'buyer_surname', 'buyer_email',
                'additional_information' ]

        widgets = {
          'buyer_first_name': forms.TextInput(attrs={'class':'form-control'}),
          'buyer_surname': forms.TextInput(attrs={'class':'form-control'}),
          'buyer_email': forms.TextInput(attrs={'class':'form-control'}),
          'coupon': forms.TextInput(attrs={'class':'form-control'}),
          'additional_information': forms.Textarea(attrs={'class':'form-control', 'rows': 2}),
          'additional_contribution': forms.TextInput(attrs={'class':'form-control col-lg-3'}),
          }

class TicketForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        """
        We extends the __init__ method to be able to restrict
        ticket types to available types by overwriting the queryset
        """
        super(TicketForm, self).__init__(*args, **kwargs)
        #self.fields['ticket_type'].queryset = TicketType.objects.available()

    class Meta:
        model  = Ticket
        fields = [
                'name',
                'email',
                'gender',
                'returning_visitor',
        ]
        widgets = {
            'name': forms.TextInput( attrs = {
                    'class':'form-control', 'placeholder': 'Name on badge'}),
            'email': forms.TextInput( attrs = {
                    'class':'form-control', 'placeholder': ''}),
            'gender': forms.Select( attrs={'class':'form-control'} ),
        }

class BaseTicketFormSet(forms.formsets.BaseFormSet):
    def __init__(self, *args, **kargs):
        self.instances = kargs['instances']
        del kargs['instances']
        super(BaseTicketFormSet, self).__init__(*args, **kargs)

    def _initial_form_count(self):
        return len(self.instances)

    def _construct_form(self, i, **kargs):
        kargs['instance'] = self.instances[i]
        kargs['empty_permitted'] = False
        return super(BaseTicketFormSet, self)._construct_form(i, **kargs)

TicketFormSet = forms.formsets.formset_factory(
        TicketForm,
        formset=BaseTicketFormSet,
        can_delete=False
)

class TicketsForm(forms.Form):
    """
    This is the first form: it shows all ticket types and allows the user
    to select how many ticket of each type are desired.
    """
    donation = forms.IntegerField(
            min_value=0,
            required=False,
            help_text=TicketPurchase._meta.get_field('additional_contribution').help_text
    )
    coupon   = forms.CharField(max_length=10, required=False)

    def __init__(self, ticket_types, valid_coupon_codes, *args, **kargs):
        """
        We extends the init method with two new parameters:
        - ticket_types is the list of ticket_types to show in the form
        - valid_coupon_codes is a list of valid coupon codes used in validation
        """
        super(TicketsForm, self).__init__(*args, **kargs)
        self.ticket_types = ticket_types
        for type_ in ticket_types:
            if type_.available():
                field = forms.IntegerField(
                        min_value=0,
                        max_value=10
                )
                self.fields['quantity:%s' % type_.id] = field

        def coupon_validator(c):
            if not c in valid_coupon_codes:
                raise ValidationError('Invalid coupon code')
        self.fields['coupon'].validators.append(coupon_validator)


import random
import time

def get_report(raw_data):
    # evaluates the game_data and calculate the competencies for the report
    my_random = random.uniform(0, 1)

    if 0 <= my_random < 0.001:
        time.sleep(random.uniform(0, 30))

        raise Exception('Unexpected error happened')

    elif 0.001 <= my_random < 0.1:
        time.sleep(random.uniform(0, 0.5))
        report = {'error': 'Did not finished the assessment'}

    elif 0.1 <= my_random < 0.4:
        time.sleep(random.uniform(1, 2))
        calculated_competencies = ['monotony', 'speed', 'accuracy']
        report = {'competencies': {competency: random.randint(1,10) for competency in calculated_competencies}}

    else:
        time.sleep(random.uniform(3, 5))
        calculated_competencies = ['monotony', 'speed', 'accuracy', 'learning', 'conformity']
        report = {'competencies': {competency: random.randint(1,10) for competency in calculated_competencies}}

    return report


import copy
import numpy as np
from layers.base_layer import Layer

class Activation(Layer):
    def forward(self, input):
        self.input = input
        return np.maximum(input, 0)

    def backward(self, last_gradient, lrate, momentum_rate):

        input_flat = self.input.flatten()
        last_flat = last_gradient.flatten()

        for x, inputs in enumerate(input_flat):
            input_flat[x] = 0 if last_flat[x] < 0 else last_flat[x]

        return input_flat.reshape(self.input.shape)


import numpy as np
from osgeo import osr

import logging

from hyo2.abc.lib.gdal_aux import GdalAux
from hyo2.qc.survey.designated.base_designated import BaseDesignated, designated_algos
from hyo2.qc.common.s57_aux import S57Aux

logger = logging.getLogger(__name__)

class DesignatedScanV2(BaseDesignated):

    # setting dictionary: X.X resolution : (number of nodes, delta depth threshold)
    settings = {
        0.5: (8, 1.0),
        1.0: (6, 1.0),
        2.0: (4, 1.0),
        4.0: (3, 1.0)
    }

    def __init__(self, s57, grids, survey_scale, neighborhood=False, specs="2017"):

        super().__init__(s57=s57, grids=grids)
        # inputs
        self.neighborhood = neighborhood
        self.survey_scale = survey_scale
        self.specs = specs

        self.type = designated_algos["DESIGNATED_SCAN_v2"]
        self.designated = list()
        self.loc2geo = None
        self.geo2loc = None
        self.all_features = self.s57.rec10s

        self.fff_features = list()
        self.fff_geo = None
        self.fff_utm = None
        self.fff_closest = None

    def run(self, depth_precision=3):
        logger.info("parameters: neighborhood: %s" % self.neighborhood)
        logger.debug("all S57 features: %d" % len(self.all_features))

        if self.specs == "2017":
            depth_precision = 2

        # test distance used to horizontally flag
        test_dist = self.survey_scale * 0.002
        logger.info("test distance at scale 1:%d: %.2f m" % (self.survey_scale, test_dist))

        # neighborhood-based test
        test_radius = 0
        test_threshold = 0.0
        if self.neighborhood:

            test_radius = 4
            test_threshold = 1.0
            for res in self.settings.keys():

                if res == self.grids.bbox().transform[1]:
                    test_radius = self.settings[res][0]
                    test_threshold = self.settings[res][1]

            logger.debug('neighborhood test @ %.1f-m resolution: radius: %d, threshold: %.1f m'
                         % (self.grids.bbox().transform[1], test_radius, test_threshold))

        # the heavy-lifting is done in C++
        success = self.grids.test_designated_soundings(test_dist, test_radius, test_threshold, self.specs)
        if not success:
            if self.grids.designated.empty():
                raise RuntimeError("not designated soundings in the input grid: %s." % self.grids.basename())
            return False

        # store the coordinate transform from CSAR CRS to geo (using GDAL)
        GdalAux.check_gdal_data()

        try:
            osr_bag = osr.SpatialReference()
            osr_bag.ImportFromWkt(self.grids.bbox().hrs)
            osr_geo = osr.SpatialReference()
            osr_geo.ImportFromEPSG(4326)  # geographic WGS84
            osr_geo.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
            self.loc2geo = osr.CoordinateTransformation(osr_bag, osr_geo)
            # geo2loc = osr.CoordinateTransformation(osr_geo, osr_bag)

        except Exception as e:
            raise RuntimeError("unable to create a valid coords transform: %s" % e)

        # select all the features of interest
        self._select_features()
        if len(self.fff_features) == 0:
            logger.warning("no FFF features to check!")
            return

        self._convert_features_to_array_coords(depth_precision=depth_precision)

        for idx, des in enumerate(self.grids.designated):

            if des.valid:
                continue

            match = False
            for sample in self.fff_closest:
                # logger.debug("sample: %s" % (sample, ))
                if (abs(sample[1] - des.r) <= 1) and (abs(sample[0] - des.c) <= 1) and \
                        (abs(sample[2] - des.designated_depth) <= 0.01):
                    match = True
                    break
            if match:
                logger.debug("#%d: removing flag because of FFF feature match" % idx)
                continue

            logger.debug("#%d: designated: %s -> valid: %s" % (idx, des.str(), des.valid))
            self._append_flagged(x=des.x, y=des.y, note=des.note)

    def _select_features(self):
        """ Select the required VALSOUs"""

        # first select all the feature of interest

        # select by feature type
        fff_filter = ['WRECKS', 'UWTROC', 'OBSTRN']
        fff_features = S57Aux.select_by_object(objects=self.all_features, object_filter=fff_filter)

        # select by geometry
        fff_features = S57Aux.select_only_points(objects=fff_features)

        # select only “description=new or update”
        self.fff_features = S57Aux.select_by_attribute_value(objects=fff_features, attribute='descrp',
                                                             value_filter=['1', '2'])

    def _convert_features_to_array_coords(self, depth_precision):
        # prepare some lists with:
        # - the geographic position of the features (self.fff_geo)
        # - the local (projected) position of the features (self.fff_loc)
        # - the array-base coords of the features (self.fff_array)
        # - the closest array nodes for each feature (self.fff_closest)

        logger.debug("converting FFF features to array coords ...")

        # first retrieve [long, lat, depth]
        self.fff_geo = list()
        for feature in self.fff_features:

            # retrieve depth value
            s57_valsou = None
            for attr in feature.attributes:

                if attr.acronym == 'VALSOU':
                    try:
                        # invert sign due to the CSAR/BAG convention (depths are negative)
                        s57_valsou = -float(attr.value)
                        # logger.debug("VALSOU value: %f" % s57_valsou)
                    except Exception as e:
                        logger.warning("issue in converting value: %s (%s %s) -> unknown VALSOU?" %
                                       (attr.value, feature.centroid.x, feature.centroid.y))
                    continue

            if s57_valsou is None:
                continue

            # append [long, lat, depth]
            self.fff_geo.append([feature.centroid.x, feature.centroid.y, s57_valsou])
        # logger.debug("lon, lat, d: %s" % self.fff_geo)

        # store the coordinate transform from CSAR CRS to geo (using GDAL)
        try:
            osr_grid = osr.SpatialReference()
            # logger.debug("cur_grids: %s" % self.grids.cur_grids)
            osr_grid.ImportFromWkt(self.grids.bbox().hrs)
            osr_geo = osr.SpatialReference()
            osr_geo.ImportFromEPSG(4326)  # geographic WGS84
            osr_geo.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
            # self.loc2geo = osr.CoordinateTransformation(osr_bag, osr_geo)
            self.geo2loc = osr.CoordinateTransformation(osr_geo, osr_grid)

        except Exception as e:
            raise RuntimeError("unable to create a valid coords transform: %s" % e)

        # convert s57 features to grid CRS coords
        self.fff_utm = np.array(self.geo2loc.TransformPoints(np.array(self.fff_geo, np.float64)),
                                np.float64)
        # logger.debug("x, y, z: %s" % self.fff_loc)

        # convert feature to array coords
        fff_array = np.copy(self.fff_utm)
        fff_array[:, 0] = (self.fff_utm[:, 0] - self.grids.bbox().transform[0]) \
                          / self.grids.bbox().transform[1] - 0.5
        fff_array[:, 1] = (self.fff_utm[:, 1] - self.grids.bbox().transform[3]) \
                          / self.grids.bbox().transform[5] - 0.5
        # logger.debug("array: %s" % self.fff_array)

        # convert to the closest array coordinates
        self.fff_closest = np.empty_like(fff_array)
        self.fff_closest[:, 0] = np.rint(fff_array[:, 0])
        self.fff_closest[:, 1] = np.rint(fff_array[:, 1])
        self.fff_closest[:, 2] = np.around(fff_array[:, 2], decimals=depth_precision)
        # logger.debug("closest: %s" % self.valsou_closest)

        logger.debug("converting FFF features to array coords ... DONE! (%d)" % len(self.fff_closest))

    def _append_flagged(self, x, y, note):

        # convert flagged nodes to geographic coords
        try:

            long, lat, _ = self.loc2geo.TransformPoint(x, y)

            self.flagged_designated[0].append(long)
            self.flagged_designated[1].append(lat)
            self.flagged_designated[2].append(note)

            logger.debug("geo-flag: (%.6f, %.6f): %s" % (long, lat, note))

        except Exception as e:
            raise RuntimeError("Unable to perform conversion of the flagged designed to geographic: %s" % e)


import matplotlib.pyplot as plt
import numpy as np

from . import implantation_range, reflection_coeff
from . import estimate_inventory_with_gp_regression

DEFAULT_TIME = 1e7

database_inv_sig = {}

def fetch_inventory_and_error(time):
    """Fetch the inventory and error for a given time

    Args:
        time (float): time (s)

    Returns:
        callable, callable: inventory(T, c), standard deviation(T, c)
    """
    if time in database_inv_sig.keys():  # fetch in database
        inv_T_c_local = database_inv_sig[time]["inv"]
        sig_inv_local = database_inv_sig[time]["sig"]
    else:  # if time is not in the database
        GP = estimate_inventory_with_gp_regression(time=time)

        def inv_T_c_local(T, c):
            if c == 0:
                val = 0
            else:
                val = 10**GP((T, np.log10(c)))[0][0]
            return val

        def sig_inv_local(T, c):
            if c == 0:
                val = 0
            else:
                val = GP((T, np.log10(c)))[1][0]
            return val

        # add to database for later use
        database_inv_sig[time] = {
            "inv": inv_T_c_local,
            "sig": sig_inv_local
        }
    return inv_T_c_local, sig_inv_local

def compute_inventory(T, c_max, time):
    """Computes the monoblock inventory as a function of the surface
    temperature, surface concentration and exposure time.

    If the time is not already in database_inv_sig, another gaussian
    regression is performed.

    Args:
        T (list): Surface temperature (K)
        c_max (list): Surface concentration (H m-3)
        time (float): Exposure time (s)

    Returns:
        numpy.array, numpy.array: list of inventories (H/m), list of standard
        deviation
    """
    inv_T_c_local, sig_inv_local = fetch_inventory_and_error(time)
    # compute inventory (H/m) along divertor
    inventories = [
        float(inv_T_c_local(T_, c)) for T_, c in zip(T, c_max)]
    sigmas = [
        float(sig_inv_local(T_, c)) for T_, c in zip(T, c_max)]
    inventories, sigmas = np.array(inventories), np.array(sigmas)
    return inventories, sigmas

def compute_c_max(
        T, E_ion, E_atom, angles_ion, angles_atom,
        ion_flux, atom_flux, full_export=False, isotope="H"):
    """Computes the surface concentration based on exposure conditions.

    Args:
        T (numpy.array): Surface temperature (K)
        E_ion (numpy.array): Ion incident energy (eV)
        E_atom (numpy.array): Atom incident energy (eV)
        angles_ion (numpy.array): Angle of incidence of ions (deg)
        angles_atom (numpy.array): Angle of incidence of atoms (deg)
        ion_flux (numpy.array): Ion flux (m-2 s-1)
        atom_flux (numpy.array): Atom flux (m-2 s-1)
        full_export (bool, optional): If True, the output will contain the
            surface concentration due to ions and atoms. Defaults to False.
        isotope (str, optional): Type of hydrogen isotope amongst "H", "D",
            "T". Defaults to "H".

    Returns:
        numpy.array or (numpy.array, numpy.array, numpy.array): surface
        concentration or (surface concentration, surface conc. ions,
        surface conc. atoms)
    """
    # Diffusion coefficient Fernandez et al Acta Materialia (2015)
    # https://doi.org/10.1016/j.actamat.2015.04.052
    D_0_W = 1.9e-7
    E_D_W = 0.2
    k_B = 8.617e-5
    D = D_0_W*np.exp(-E_D_W/k_B/T)
    if isotope == "D":
        D *= 1/2**0.5
    elif isotope == "T":
        D *= 1/3**0.5
    # implantation ranges
    implantation_range_ions = [
        float(implantation_range(energy, angle))
        for energy, angle in zip(E_ion, angles_ion)]
    implantation_range_atoms = [
        float(implantation_range(energy, angle))
        for energy, angle in zip(E_atom, angles_atom)]

    # reflection coefficients
    reflection_coeff_ions = [
        float(reflection_coeff(energy, angle))
        for energy, angle in zip(E_ion, angles_ion)]
    reflection_coeff_atoms = [
        float(reflection_coeff(energy, angle))
        for energy, angle in zip(E_atom, angles_atom)]

    reflection_coeff_ions = np.array(reflection_coeff_ions)
    reflection_coeff_atoms = np.array(reflection_coeff_atoms)

    implantation_range_ions = np.array(implantation_range_ions)
    implantation_range_atoms = np.array(implantation_range_atoms)

    # compute c_max
    c_max_ions = (1 - reflection_coeff_ions) * \
        ion_flux*implantation_range_ions/D
    c_max_atoms = (1 - reflection_coeff_atoms) * \
        atom_flux*implantation_range_atoms/D
    c_max = c_max_ions + c_max_atoms

    if full_export:
        return c_max, c_max_ions, c_max_atoms
    else:
        return c_max

def compute_surface_temperature(heat_flux):
    """Computes the surface temperature based on the thermal study
    performed in Delaporte-Mathurin et al, SREP 2020
    https://www.nature.com/articles/s41598-020-74844-w
    """

    return 1.1e-4*heat_flux + 323

if __name__ == "__main__":
    pass


import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

class find_attribute_values():
    def findattributevalues(self):
        driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
        driver.get("https://www.yatra.com/")
        atributevalues = driver.find_element(By.XPATH, "//*[@id='BE_flight_flsearch_btn']").get_attribute("id") # we give the HTML attributes
        driver.maximize_window()
        time.sleep(2)
        driver.find_element(By.XPATH, "//span[normalize-space()='Hotels']").click()
        time.sleep(2)
        driver.back()
        time.sleep(2)
        driver.minimize_window()
        print(atributevalues)
        time.sleep(4)

fe=find_attribute_values()
fe.findattributevalues()


# -*- coding: utf-8 -*-
import numpy
from numpy import loadtxt
import scipy
import pylab
import time
import copy
import os
import re
import sys
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy import stats
from itertools import combinations
from ast import literal_eval
from matplotlib.colors import ListedColormap, NoNorm
from pylab import rcParams

# the axes attributes need to be set before the call to subplot
plt.rc('text', usetex=True)
plt.rc('font', family='serif', weight='bold', size=18)
plt.rc('xtick.major', size=5, pad=7)
plt.rc('ytick.major', size=5, pad=7)
rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath']
plt.rc('xtick', labelsize=18)
plt.rc('ytick', labelsize=18)

lines = open( "const_potts.h", "r" ).readlines()

N = int( (lines[0].split())[2] )
S = int( (lines[1].split())[2] )
p = int( (lines[2].split())[2] )
a = float( (lines[3].split())[2] )
apf = 1.0#float( (lines[6].split())[2] )
zeta = 0.000
N_fact=1000

#for low values of f, many children are globally null, so I discard them. The non-null number (pp) fluctuates.
#if f=0.03 pp=990
#if f=0.01 pp=784
#if f=0.05 pp=1000
pp=1000

for Num_fact in [150]:
	for p_fact in [30]:

		print(p_fact, Num_fact)
		fig = plt.figure(figsize=(5, 5))

		Cmn = (loadtxt("Cmn1_file_a%.2f_apf%.2f_pfact%d_p%d_Nfact%d_Numfact%d_zeta%.3f"%(a, apf, p_fact, p, N_fact, Num_fact, zeta)))[numpy.triu_indices(pp, 1)]
		print(numpy.shape(Cmn))
		b = Cmn/a#[numpy.nonzero(Cmn)]/a
		print(numpy.mean(b))
		#plt.hist(b, bins='fd', histtype='step', normed=1, color='green', alpha=1, zorder=1, label = r'$C_{\mu \nu}$')
		hist, bin_edges = numpy.histogram(b, bins='sqrt', density=True)
		bin_centers = numpy.asarray([(bin_edges[i]+bin_edges[i+1])/2 for i in range(numpy.size(bin_edges)-1)])
		indices = numpy.where(hist>0)
		hist_new=hist[indices]
		bins_new=bin_centers[indices]
		plt.fill_between(bins_new,0,hist_new, alpha=0.5,color='green',label = r'$C_{\mu \nu}$')

		Cij = (loadtxt("Cij1_file_a%.2f_apf%.2f_pfact%d_p%d_Nfact%d_Numfact%d_zeta%.3f"%(a, apf, p_fact, p, N_fact, Num_fact, zeta)))[numpy.triu_indices(N, 1)]
		#print(numpy.nonzero(Cij))
		b = Cij/a#[numpy.nonzero(Cij)]/a
		print(numpy.mean(b))
		#plt.hist(b, bins='auto', histtype='step', normed=1, color='red', alpha=1, zorder=2, label = r'$C_{ij}$')
		hist, bin_edges = numpy.histogram(b, bins='sqrt', density=True)
		bin_centers = numpy.asarray([(bin_edges[i]+bin_edges[i+1])/2 for i in range(numpy.size(bin_edges)-1)])
		indices = numpy.where(hist>0)
		hist_new=hist[indices]
		bins_new=bin_centers[indices]
		plt.fill_between(bins_new,0,hist_new, alpha=0.5,color='red', label = r'$C_{ij}$')

		#plt.xticks(fontsize=14)
		#plt.yticks(fontsize=14)
		plt.ylim(0.01,4000)
		plt.xlim(0,0.4)
		plt.axvline(a/S, color='black')
		plt.yscale('log', nonposy='clip')
		#plt.xlabel('correlation', fontsize=18)
		if (zeta == 0.001):
			#plt.legend()
			fig.suptitle('$f=%.2f$'%(float(p_fact)/float(p)))
		if (p_fact == 50):
			plt.annotate("$\zeta=%s$"%zeta, (0.25,1))
		fig.savefig("distribs_a%.1f_apf%.1f_pfact%d_p%d_Nfact%d_Numfact%d_zeta%.3f.pdf"%(a, apf, p_fact, p, N_fact, Num_fact, zeta), bbox_inches='tight')
		fig.savefig("distribs_a%.1f_apf%.1f_pfact%d_p%d_Nfact%d_Numfact%d_zeta%.3f.png"%(a, apf, p_fact, p, N_fact, Num_fact, zeta), bbox_inches='tight')


from csv import DictReader
from datetime import datetime

from django.core.management import BaseCommand

from main_app.models import User, Posting, RidePosting, ItemPosting, Comment

DATETIME_FORMAT = '%m/%d/%Y %H:%M'

class Command(BaseCommand):

    def handle(self, *args, **options):
        if User.objects.exists() or Posting.objects.exists() or RidePosting.objects.exists() \
        or ItemPosting.objects.exists() or Comment.objects.exists():
            print('Data already loaded...exiting.')
            return
        print("Proceeding to add data")

        print("Adding user data")
        for row in DictReader(open('./test_user_data_01.csv')):
            user = User()
            user.name = row['Name']
            user.email = row['Email']
            user.role = row['role']
            user.save()


import boto3
import time

session = boto3.Session(region_name='us-east-1')
client = session.client(
    'kinesis',
    aws_access_key_id='',
    aws_secret_access_key='',
    endpoint_url='http://localhost:4567'
)

stream_details = client.describe_stream(StreamName='test_stream')
shard_id = stream_details['StreamDescription']['Shards'][0]['ShardId']

response = client.get_shard_iterator(
    StreamName='test_stream',
    ShardId=shard_id,
    ShardIteratorType='TRIM_HORIZON'
)

shard_iterator = response['ShardIterator']

while True:
    response = client.get_records(ShardIterator=shard_iterator, Limit=5)
    shard_iterator = response['NextShardIterator']
    for record in response['Records']:
        if 'Data' in record and len(record['Data']) > 0:
            print(record['Data'])
    time.sleep(0.75)


import numpy as np

def randompoints(a, b):
    x = a + np.random.rand(1, len(a))*(b-a)
    return x

def mc(dimen, a, b, f, N): #depends on dimension, ..., a function f, and the number of points N.
    #res = 0
    #err = 0
    V = 1.0
    for i in range(dimen):
        V = V*(b[i] - a[i])

    sum = 0
    sumq = 0

    for i in range(N):
        x = randompoints(a, b)
        fval = f(x)
        sum = sum + fval
        sumq = sumq + fval**2

    avg = sum/N             #average
    var = sumq/N - avg**2   #variance

    res = avg*V
    err = V*(var/N)**0.5

    return res, err


import matplotlib.pyplot as plt
import torch

from core.basis.logger import setup_logger
from core.ml.isn.config import IsnConfig
from core.ml.isn.image_composer import InnImageComposer
from core.ml.isn.isn import ISN
from core.ml.isn.resnet import PrbCubeResNet
from core.ml.isn.trainer import IsnTrainer
from core.ml.scheduler import LinearScheduler
from scripts.config import TRAINING
from scripts.train.config import train_digit_image_handler, train_background_image_handler, train_digit_label_handler, \
    test_background_image_handler, test_digit_image_handler, test_digit_label_handler

if __name__ == '__main__':
    train_image_composer = InnImageComposer(
        background_image_handler=train_background_image_handler,
        digit_image_handler=train_digit_image_handler,
        digit_label_handler=train_digit_label_handler
    )

    test_image_composer = InnImageComposer(
        background_image_handler=test_background_image_handler,
        digit_image_handler=test_digit_image_handler,
        digit_label_handler=test_digit_label_handler
    )
    training = TRAINING()
    config = IsnConfig(
        train_batch_size=32,
        num_train_steps=1_000_000,
        test_batch_size=128,

        log_frequency=50,
        eval_frequency=10_000,
        saving_frequency=100_000,

        grad_clip_value=10,
        lr_scheduler=LinearScheduler(1e-3, 1e-5, 500_000),

        logger=setup_logger(training.LOG_SAVE_FOLDER, 'isn'),
        output_folder=training.OUTPUT_FOLDER,
        model_load_path=r'/Volumes/XiaoSSD/runs/isn/outputs/1622626340/models/dqn-1000000.weights',
        model_save_folder=training.MODEL_SAVE_FOLDER
    )

    isn = ISN(config, PrbCubeResNet)
    trainer = IsnTrainer(train_image_composer=train_image_composer,
                         dev_image_composer=test_image_composer,
                         config=config,
                         isn=isn)
    data_batch, label_batch, pgrid_batch = trainer.dev_ic.compose(1)
    label, pgrid = trainer.isn.predict(data_batch)

    correct = (label == label_batch)
    label_accuracy = correct.sum() / label.numel()

    correct_digits = torch.logical_and(correct, label != 10)
    match = (pgrid == pgrid_batch)[correct_digits]
    if match.numel() > 0:
        pgrid_accuracy = match.sum() / match.numel()
    else:
        pgrid_accuracy = 1

    print(label_accuracy, pgrid_accuracy)

    fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(4, 1.8), sharex=True, sharey=True)
    plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.05, hspace=0)
    ax0.axes.xaxis.set_visible(False)
    ax0.axes.yaxis.set_visible(False)
    ax1.axes.xaxis.set_visible(False)
    ax1.axes.yaxis.set_visible(False)
    ax2.axes.xaxis.set_visible(False)
    ax2.axes.yaxis.set_visible(False)
    ax0.matshow(data_batch[0][0].numpy())
    ax0.set_title(f'Input Region {label_batch[0]}', fontsize=10)
    ax1.matshow(pgrid[0][0].numpy())
    ax1.set_title(f'ISN Prediction {label[0]}', fontsize=10)
    ax2.matshow(pgrid_batch[0][0].numpy())
    ax2.set_title(f'Ground Truth {label_batch[0]}', fontsize=10)
    plt.show()


# Python 3 recursive program to print
# all n-digit numbers whose sum of
# digits equals to given sum

# Recursive function to print all
# n-digit numbers whose sum of
# digits equals to given sum

# n, sum --> value of inputs
# out --> output array
# index --> index of next digit to be
#		 filled in output array
def findNDigitNumsUtil(n, sum, out, index):
    # Base case
    if (index > n or sum < 0):
        return

    f = ""

    # If number becomes N-digit
    if (index == n):

        # if sum of its digits is equal
        # to given sum, print it
        if (sum == 0):
            out[index] = ""

            for i in out:
                f = f + str(i)
            print(f, end=" ")

        return

    # Traverse through every digit. Note
    # that here we're considering leading
    # 0's as digits
    for i in range(10):
        # append current digit to number
        out[index] = i

        # recurse for next digit with reduced sum
        findNDigitNumsUtil(n, sum - i,
                           out, index + 1)

    # This is mainly a wrapper over findNDigitNumsUtil.

# It explicitly handles leading digit
def findNDigitNums(n, sum):
    # output array to store N-digit numbers
    out = [False] * (n + 1)

    # fill 1st position by every digit
    # from 1 to 9 and calls findNDigitNumsUtil()
    # for remaining positions
    for i in range(1, 10):
        out[0] = i
        findNDigitNumsUtil(n, sum - i, out, 1)

    # Driver Code

if __name__ == "__main__":
    n = 2
    sum = 3

    findNDigitNums(n, sum)

# This code is contributed
# by ChitraNayal


import sqlite3

import aux
import cfg
import db
import fio

# functions for the population of deception corpus tables
# note: chunks are listed in csv files per role and their audio contained in
#       individual files per chunk, with start/end timestamps in name

def _load_chunks(ses_dict, role):
    ''' reads chunk meta-data, returns dict per task with dict of chunks '''
    tsk_chu_dict = {}
    fname = 'chunks_%s.csv' % role.lower()
    for row in fio.read_csv(cfg.META_PATH_DC, fname, skip_header=True):
        ses = '%s_%s' % (row[0][1:4], row[0][5:8])
        if ses in ses_dict:
            # sessions are indexed by spk_id pair in csv file, convert to ses_id
            ses_id = ses_dict[ses][0]
            # each session contains two parts, interviews in either direction
            part = row[0][13]
            tsk_id = 2 * ses_id - (1 if part == '1' else 0)
            if tsk_id not in tsk_chu_dict:
                tsk_chu_dict[tsk_id] = {}
            start = float(row[1])
            end = float(row[2])
            transcript = row[3]
            words = aux.preprocess_transcript(row[3])
            tsk_chu_dict[tsk_id]['%f:%f' % (start, end)] = \
                (start, end, transcript, words)
    return tsk_chu_dict

def _merge_chunks(tsk_chu_dict_ee, tsk_chu_dict_er):
    ''' merges chunks from both speakers in each task by start timestamps '''
    tsk_chu_dict = {}
    for key, val in tsk_chu_dict_ee.items():
        inf = float('inf')
        tsk_chus_ee = [v for k, v in val.items()] + [(inf,)]
        tsk_chus_ee.sort()
        tsk_chus_er = [v for k, v in tsk_chu_dict_er[key].items()] + [(inf,)]
        tsk_chus_er.sort()
        tsk_chu_dict[key] = []
        i = 0
        j = 0
        for k in range(len(tsk_chus_ee) + len(tsk_chus_er) - 2):
            if tsk_chus_ee[i][0] <= tsk_chus_er[j][0]:
                tsk_chu_dict[key].append(('EE',) + tsk_chus_ee[i])
                i += 1
            else:
                tsk_chu_dict[key].append(('ER',) + tsk_chus_er[j])
                j += 1
    return tsk_chu_dict

def get_ses_dict():
    ''' reads list of relevant sessions, returns dict '''
    ses_dict = {}
    for line in fio.readlines(cfg.META_PATH_DC, 'sessions'):
        # sessions are indexed by spk_id pair in file, count pairs for ses_id
        ses_id = len(ses_dict) + 1
        spk_id_b = line[1:4]
        spk_id_a = line[5:8]
        # store conversion from spk_id pair to ses_id in dict
        ses_dict['%s_%s' % (spk_id_b, spk_id_a)] = [ses_id, spk_id_b, spk_id_a]
    return ses_dict

def populate_speakers(ses_dict):
    ''' populates speakers table from dict of relevant sessions '''
    # dict to track speakers stored in database
    spk_dict = {}
    # only read interviewee file, all speakers take either role
    fname = 'chunks_ee.csv'
    for row in fio.read_csv(cfg.META_PATH_DC, fname, skip_header=True):
        ses = '%s_%s' % (row[0][1:4], row[0][5:8])
        if ses in ses_dict and row[13] not in spk_dict:
            # session is relevant and speaker not in database yet
            gender = 'f' if row[15] == 'Female' else 'm'
            db.ins_spk_dc(
                row[13], gender, row[16], row[19], row[21], row[22], row[23],
                row[33], row[35], row[32], row[34], row[31])
            spk_dict[row[13]] = 1

def populate_sessions_and_tasks(ses_dict):
    ''' populates sessions/tasks tables from dict of relevant sessions '''
    for ses_id, spk_id_b, spk_id_a in ses_dict.values():
        db.ins_ses_dc(ses_id, spk_id_a, spk_id_b)
        # B is always interviewer first
        db.ins_tsk_dc(2*ses_id-1, ses_id, 1, 'B')
        db.ins_tsk_dc(2*ses_id, ses_id, 2, 'A')

def populate_turns_and_chunks(ses_dict):
    ''' populates turns/chunks tables from meta-data for relevant sessions '''
    # load chunks to dicts from meta-data csv files
    tsk_chu_dict_ee = _load_chunks(ses_dict, 'EE')
    tsk_chu_dict_er = _load_chunks(ses_dict, 'ER')
    # merge chunk dicts by starting timestamps
    tsk_chu_dict = _merge_chunks(tsk_chu_dict_ee, tsk_chu_dict_er)

    chu_id = 0
    tur_id = 0
    # iterate over merged dict to insert chunks; insert turns as needed
    for tsk_id, chunks in tsk_chu_dict.items():
        turn_index = 0
        chunk_index = 0
        role_prev = None
        for chunk in chunks:
            role = 'd' if chunk[0] == 'ER' else 'f'
            if role_prev != role:
                # change in role marks new turn; insert turn first
                tur_id += 1
                turn_index += 1
                chunk_index = 0
                db.ins_tur_dc(tur_id, tsk_id, turn_index, role)
            chu_id += 1
            chunk_index += 1
            db.ins_chu(chu_id, tur_id, chunk_index, *chunk[1:])
            role_prev = role

def extract_features(ses_id):
    ''' runs feature extraction for all chunks in given session, updates db '''
    db.connect(cfg.CORPUS_ID_DC)
    path = cfg.get_corpus_path(cfg.CORPUS_ID_DC)
    path += 'wav_segments/ses' + str(ses_id) + '/'
    for a_or_b, ch in [('A', 1), ('B', 2)]:
        all_features = {}
        for chu_id, words, start, end, task_index, spk_id_a, spk_id_b \
        in db.find_chunks(ses_id, a_or_b):
            if end - start >= 0.04: # min duration for 75Hz min pitch
                fname = 'p%dp%d-part%d_ch%d:%f:%f.wav' % \
                    (spk_id_b, spk_id_a, task_index, ch, start, end)
                all_features[chu_id] = fio.extract_features(
                    path, fname, ses_id, chu_id, words, start, end, False)
        # function is invoked in parallel, database might be locked;
        # keep trying to update until it works
        done = False
        while not done:
            try:
                for chu_id, features in all_features.items():
                    db.set_features(chu_id, features)
                db.commit()
                done = True
            except sqlite3.OperationalError:
                pass
    db.close()


import random  #import the random library to use randint

def gdie():  #define the D6 function as gdie (gamma die)
    dieroll = random.randint(1, 6) #dieroll = a random integer from 1-6 using randint from the random libray
    if dieroll == 1: dieroll = 1
    if dieroll == 2: dieroll = 1
    if dieroll == 3: dieroll = 2
    if dieroll == 4: dieroll = 0
    if dieroll == 5: dieroll = 0
    if dieroll == 6: dieroll = 0
    #return dieroll  # this would return the dieroll value
    print(dieroll) #this tells the function to print the result of the die roll when called
gdie() #invoke the gdie function


from pymongo import MongoClient

import room_data
from user import User

database_client = MongoClient("mongodb://localhost:27017")
database = database_client['users']

user_db = database['users']
users = []

def load_users():
    for res in user_db.find():
        user = User(res['id'])
        user.garant = res['garant']
        user.ban = res['ban']
        if res['room'] != 'None':
            user.room = room_data.get_room_with_name(res['room'])
        users.append(user)
    print('Пользователи загружены')

def save_users():
    for user in users:
        user_db.update_one(
            {
                'id': user.user_id
            },
            {
                '$set':
                    {
                        'id': user.user_id,
                        'room': user.room.name if user.room else 'None',
                        'garant': user.garant,
                        'ban': user.ban
                    }
            }
        )
    print('Пользователи сохранены')

def get_user_with_id(user_id):
    u = None
    for user in users:
        if user_id == user.user_id:
            u = user
    return u

def user_exists_with_id(user_id):
    for user in users:
        if user.user_id == user_id:
            return True
    return False

def get_all():
    return users


# ============================================================
# A simple singly linked list
# ============================================================
from Node import Node

class Simply_linked_list():
    head = None
    tail = None
    length = 0

    def __init__(self) -> None:
        # Initialize a new list
        self.head = None
        self.tail = None
        self.length = 0
        pass

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n < self.length:
            self.element_n = self.head
            for i in range(self.n):
                self.element_n = self.element_n.get_next()
            self.n += 1
            return self.element_n.get_element()
        else:
            raise StopIteration

    def has_next(self):
        return self.n < self.length

    def add_first(self, element):
        """
        Inserts a new element at the start of the linked list,
        returns the old head
        """
        old_head = self.head
        if self.head == None:
            # List is empty
            self.head = Node(element)
            self.tail = self.head
        else:
            # List has more than one element
            new_head = Node(element)
            new_head.set_next(self.head)
            self.head = new_head

        self.length += 1
        return old_head

    # Add to the end of the list
    def add_last(self, element):
        new_tail = Node(element)
        if self.tail == None:
            # List is empty, set head and tail
            self.tail = new_tail
            self.head = self.tail
        else:
            self.tail.set_next(new_tail)
            self.tail = new_tail

        self.length += 1
        return None

    # Remove the first element of the list
    def remove_first(self):
        if self.head == None:
            raise ValueError("Head is None")

        self.old_head_value = self.head.get_element()
        self.head = self.head.get_next()
        self.length -= 1
        return self.old_head_value

    # Remove the last element of the list
    def remove_last(self):
        if self.tail == None:
            # Tail does not exist
            raise ValueError("Tail is None")

        # Save old tail value
        self.old_tail_value = self.tail.get_element()

        # Handle case where length == 1
        if self.head == self.tail:
            self.head = None
            self.tail = None
            self.length -= 1
            return self.old_tail_value

        # Loop through nodes to get the second to last node
        self.loop_element = self.head
        while self.loop_element.get_next().get_next() != None:
            self.loop_element = self.loop_element.get_next()

        # Set new tail
        self.tail = self.loop_element

        # Delete tail
        self.tail.set_next(None)

        self.length -= 1

        return self.old_tail_value

    # Get size of list
    def get_size(self):
        return self.length

    # Check if the list is empty
    def is_empty(self):
        return self.length == 0

    # Get the head of the list
    def get_first(self):
        if self.head == None:
            raise ValueError("Head is None")
        return self.head.get_element()

    # Get the tain of the list
    def get_last(self):
        if self.tail == None:
            raise ValueError("Tail is None")
        return self.tail.get_element()


from datetime import date # importando funcionalidade da biblioteca datetime
atual = date.today().year #comando de data do ano atual
nasc = int(input('Qual o ano do seu nascimento: '))
idade = atual - nasc
print('Quem nasceu em {} tem {} anos em {}.'.format(nasc, idade, atual))
if idade < 18:
    saldo = 18 - idade #18 que é a idade pra alistar - a variavel idade, o que restar é o saldo que falta
    print(' Você tem {} anos e ainda não pode se alistar, podera daqui a {} anos.'.format(idade, saldo))
    ano = atual + saldo
    print('Seu alistamento será em {}'.format(ano))
elif idade == 18:
    print('Voce tem {} anos e JÀ PODE SE ALISTAR !!!'.format(idade))
else:
    saldo = idade - 18 #idade - 18 que é a jhonson, o que sobrar é o saldo.
    print('Você ja tem {} anos, ja deveria ter se alistado a {} anos.'.format(idade, saldo))
    ano = atual - saldo
    print('Seu alistamento foi em {}.'.format(ano))


import math
import numpy
import unittest

# TODO(markdr): Remove this after soundfile is added to setup.py
import sys
import mock
sys.modules['soundfile'] = mock.Mock()

import acts_contrib.test_utils.audio_analysis_lib.audio_quality_measurement as audio_quality_measurement

class NoiseLevelTest(unittest.TestCase):
    def setUp(self):
        """Uses the same seed to generate noise for each test."""
        numpy.random.seed(0)

    def test_noise_level(self):
        # Generates the standard sin wave with standard_noise portion of noise.
        rate = 48000
        length_in_secs = 2
        frequency = 440
        amplitude = 1
        standard_noise = 0.05

        wave = []
        for index in range(0, rate * length_in_secs):
            phase = 2.0 * math.pi * frequency * float(index) / float(rate)
            sine_wave = math.sin(phase)
            noise = standard_noise * numpy.random.standard_normal()
            wave.append(float(amplitude) * (sine_wave + noise))

        # Calculates the average value after applying teager operator.
        teager_value_of_wave, length = 0, len(wave)
        for i in range(1, length - 1):
            ith_teager_value = abs(wave[i] * wave[i] - wave[i - 1] * wave[i +
                                                                          1])
            ith_teager_value *= max(1, abs(wave[i]))
            teager_value_of_wave += ith_teager_value
        teager_value_of_wave /= float(length * (amplitude**2))

        noise = audio_quality_measurement.noise_level(
            amplitude, frequency, rate, teager_value_of_wave)

        self.assertTrue(abs(noise - standard_noise) < 0.01)

class ErrorTest(unittest.TestCase):
    def test_error(self):
        value1 = [0.2, 0.4, 0.1, 0.01, 0.01, 0.01]
        value2 = [0.3, 0.3, 0.08, 0.0095, 0.0098, 0.0099]
        error = [0.5, 0.25, 0.2, 0.05, 0.02, 0.01]
        for i in range(len(value1)):
            ret = audio_quality_measurement.error(value1[i], value2[i])
            self.assertTrue(abs(ret - error[i]) < 0.001)

class QualityMeasurementTest(unittest.TestCase):
    def setUp(self):
        """Creates a test signal of sine wave."""
        numpy.random.seed(0)

        self.rate = 48000
        self.freq = 440
        self.amplitude = 1
        length_in_secs = 2
        self.samples = length_in_secs * self.rate
        self.y = []
        for index in range(self.samples):
            phase = 2.0 * math.pi * self.freq * float(index) / float(self.rate)
            sine_wave = math.sin(phase)
            self.y.append(float(self.amplitude) * sine_wave)

    def add_noise(self):
        """Adds noise to the test signal."""
        noise_amplitude = 0.01 * self.amplitude
        for index in range(self.samples):
            noise = noise_amplitude * numpy.random.standard_normal()
            self.y[index] += noise

    def generate_delay(self):
        """Generates some delays during playing."""
        self.delay_start_time = [0.200, 0.375, 0.513, 0.814, 1.000, 1.300]
        self.delay_end_time = [0.201, 0.377, 0.516, 0.824, 1.100, 1.600]

        for i in range(len(self.delay_start_time)):
            start_index = int(self.delay_start_time[i] * self.rate)
            end_index = int(self.delay_end_time[i] * self.rate)
            for j in range(start_index, end_index):
                self.y[j] = 0

    def generate_artifacts_before_playback(self):
        """Generates artifacts before playing."""
        silence_before_playback_end_time = 0.2
        end_index = int(silence_before_playback_end_time * self.rate)
        for i in range(0, end_index):
            self.y[i] = 0
        noise_start_index = int(0.1 * self.rate)
        noise_end_index = int(0.1005 * self.rate)
        for i in range(noise_start_index, noise_end_index):
            self.y[i] = 3 * self.amplitude

    def generate_artifacts_after_playback(self):
        """Generates artifacts after playing."""
        silence_after_playback_start_time = int(1.9 * self.rate)
        noise_start_index = int(1.95 * self.rate)
        noise_end_index = int((1.95 + 0.02) * self.rate)

        for i in range(silence_after_playback_start_time, self.samples):
            self.y[i] = 0
        for i in range(noise_start_index, noise_end_index):
            self.y[i] = self.amplitude

    def generate_burst_during_playback(self):
        """Generates bursts during playing."""
        self.burst_start_time = [0.300, 0.475, 0.613, 0.814, 1.300]
        self.burst_end_time = [0.301, 0.476, 0.614, 0.815, 1.301]

        for i in range(len(self.burst_start_time)):
            start_index = int(self.burst_start_time[i] * self.rate)
            end_index = int(self.burst_end_time[i] * self.rate)
            for j in range(start_index, end_index):
                self.y[j] = self.amplitude * (3 + numpy.random.uniform(-1, 1))

    def generate_volume_changing(self):
        """Generates volume changing during playing."""
        start_time = [0.300, 1.400]
        end_time = [0.600, 1.700]
        for i in range(len(start_time)):
            start_index = int(start_time[i] * self.rate)
            end_index = int(end_time[i] * self.rate)
            for j in range(start_index, end_index):
                self.y[j] *= 1.4
        self.volume_changing = [+1, -1, +1, -1]
        self.volume_changing_time = [0.3, 0.6, 1.4, 1.7]

    def test_good_signal(self):
        """Sine wave signal with no noise or artifacts."""
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 0)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 0)
        self.assertTrue(len(result['artifacts']['delay_during_playback']) == 0)
        self.assertTrue(len(result['artifacts']['burst_during_playback']) == 0)
        self.assertTrue(len(result['volume_changes']) == 0)
        self.assertTrue(result['equivalent_noise_level'] < 0.005)

    def test_good_signal_with_noise(self):
        """Sine wave signal with noise."""
        self.add_noise()
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 0)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 0)
        self.assertTrue(len(result['artifacts']['delay_during_playback']) == 0)
        self.assertTrue(len(result['artifacts']['burst_during_playback']) == 0)
        self.assertTrue(len(result['volume_changes']) == 0)
        self.assertTrue(0.009 < result['equivalent_noise_level'] < 0.011)

    def test_delay(self):
        """Sine wave with delay during playing."""
        self.generate_delay()
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 0)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 0)
        self.assertTrue(
            len(result['volume_changes']) == 2 * len(self.delay_start_time))
        self.assertTrue(result['equivalent_noise_level'] < 0.005)

        self.assertTrue(
            len(result['artifacts']['delay_during_playback']) ==
            len(self.delay_start_time))
        for i in range(len(result['artifacts']['delay_during_playback'])):
            delta = abs(result['artifacts']['delay_during_playback'][i][0] -
                        self.delay_start_time[i])
            self.assertTrue(delta < 0.001)
            duration = self.delay_end_time[i] - self.delay_start_time[i]
            delta = abs(result['artifacts']['delay_during_playback'][i][1] -
                        duration)
            self.assertTrue(delta < 0.001)

    def test_artifacts_before_playback(self):
        """Sine wave with artifacts before playback."""
        self.generate_artifacts_before_playback()
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 1)
        delta = abs(result['artifacts']['noise_before_playback'][0][0] - 0.1)
        self.assertTrue(delta < 0.01)
        delta = abs(result['artifacts']['noise_before_playback'][0][1] - 0.005)
        self.assertTrue(delta < 0.004)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 0)
        self.assertTrue(len(result['artifacts']['delay_during_playback']) == 0)
        self.assertTrue(len(result['artifacts']['burst_during_playback']) == 0)
        self.assertTrue(len(result['volume_changes']) == 0)
        self.assertTrue(result['equivalent_noise_level'] < 0.005)

    def test_artifacts_after_playback(self):
        """Sine wave with artifacts after playback."""
        self.generate_artifacts_after_playback()
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 0)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 1)
        delta = abs(result['artifacts']['noise_after_playback'][0][0] - 1.95)
        self.assertTrue(delta < 0.01)
        delta = abs(result['artifacts']['noise_after_playback'][0][1] - 0.02)
        self.assertTrue(delta < 0.001)
        self.assertTrue(len(result['artifacts']['delay_during_playback']) == 0)
        self.assertTrue(len(result['artifacts']['burst_during_playback']) == 0)
        self.assertTrue(len(result['volume_changes']) == 0)
        self.assertTrue(result['equivalent_noise_level'] < 0.005)

    def test_burst_during_playback(self):
        """Sine wave with burst during playback."""
        self.generate_burst_during_playback()
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 0)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 0)
        self.assertTrue(len(result['artifacts']['delay_during_playback']) == 0)
        self.assertTrue(len(result['artifacts']['burst_during_playback']) == 5)
        self.assertTrue(len(result['volume_changes']) == 10)
        self.assertTrue(result['equivalent_noise_level'] > 0.02)
        for i in range(len(result['artifacts']['burst_during_playback'])):
            delta = abs(self.burst_start_time[i] - result['artifacts'][
                'burst_during_playback'][i])
            self.assertTrue(delta < 0.002)

    def test_volume_changing(self):
        """Sine wave with volume changing during playback."""
        self.generate_volume_changing()
        result = audio_quality_measurement.quality_measurement(self.y,
                                                               self.rate)
        self.assertTrue(len(result['artifacts']['noise_before_playback']) == 0)
        self.assertTrue(len(result['artifacts']['noise_after_playback']) == 0)
        self.assertTrue(len(result['artifacts']['delay_during_playback']) == 0)
        self.assertTrue(len(result['artifacts']['burst_during_playback']) == 0)
        self.assertTrue(result['equivalent_noise_level'] < 0.005)
        self.assertTrue(
            len(result['volume_changes']) == len(self.volume_changing))
        for i in range(len(self.volume_changing)):
            self.assertTrue(
                abs(self.volume_changing_time[i] - result['volume_changes'][i][
                    0]) < 0.01)
            self.assertTrue(
                self.volume_changing[i] == result['volume_changes'][i][1])

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


import os
import torch
from pathlib import Path
from configs import Config
from train import Train
from tensorboardX import SummaryWriter

# import torch.distributed as dist
# dist.init_process_group(backend="gloo")

# config
root_dir = Path(os.getcwd()).absolute()
print(f"root directory: {root_dir}")

config_path = f'{root_dir}/config.yaml'
config = Config(config_path)

# hp_str
with open(config_path, 'r') as f:
    hp_str = ''.join(f.readlines())

# torch.set_num_interop_threads(8)  # Inter-op parallelism
# torch.set_num_threads(8)  # Intra-op parallelism

# writer
class MyWriter(SummaryWriter):
    def __init__(self, hp, logdir):
        super(MyWriter, self).__init__(logdir)
        self.hp = hp

    def write_train(self, step, loss):
        self.add_scalar('loss', loss, step)

    def write_val(self, step, val_loss, val_rmse_loss):
        self.add_scalar('val_loss', val_loss, step)
        self.add_scalar('val_rmse_loss', val_rmse_loss, step)

log_dir = os.path.join(root_dir, config.log.log_dir)
os.makedirs(log_dir, exist_ok=True)
writer = MyWriter(config, log_dir)

# train
# torch.Size([1, 60, 1]) torch.Size([1, 60, 1]) torch.Size([1, 60, 3]) torch.Size([1, 30, 3])
# torch.Size([256, 60, 1]) torch.Size([256, 60, 1]) torch.Size([256, 60, 3]) torch.Size([256, 60, 3])
train = Train(config, hp_str, writer, root_dir=root_dir)
# train.test(0)
train.train()
# torchrun
#     --standalone
#     --nnodes=1
#     --nproc_per_node=$NUM_TRAINERS
#     YOUR_TRAINING_SCRIPT.py


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

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.size'] = 12
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['figure.dpi'] = 200

def tolist(x):
    if not isinstance(x, list):
        return [x]
    elif x is None:
        return [None]
    else:
        return x

def plot_train_curve(train_record_path, label, fig_path=None,
                     var_name='loss_record', dpi=100, interactive=False,
                     linewidth=2):

    train_record_paths = tolist(train_record_path)
    labels = tolist(label)

    fig, ax = plt.subplots(1, 1, tight_layout=True)
    for train_record_path, label in zip(train_record_paths, labels):
        record_info = np.load(train_record_path)
        loss_record = record_info[var_name]
        n_epoch = np.max(np.nonzero(loss_record)[0])
        loss_record = loss_record[:n_epoch+1]
        ax.plot(loss_record, label=label, linewidth=linewidth)

    ax.set_xlabel('epoch')
    ax.set_ylabel('loss')
    ax.legend()

    if fig_path is not None:
        fig.savefig(fig_path, dpi=dpi)
        print(f'fig is saved to {fig_path}')

    if interactive is True:
        plt.show()

def parse_args():
    parser = argparse.ArgumentParser(description='plot learning curve')
    parser.add_argument('--train-record', dest='train_record_path', type=str,
                        required=True, nargs='+',
                        help='train record path')
    parser.add_argument('--label', dest='label', type=str, default=None,
                        nargs='+', help='label for each train record')
    parser.add_argument('--var-name', dest='var_name', type=str,
                        default='loss_record', help='')
    parser.add_argument('--linewidth', dest='linewidth', type=int,
                        default=2, help='')
    parser.add_argument('--fig-path', dest='fig_path', type=str, default=None,
                        help='')
    parser.add_argument('--interactive', dest='interactive', type=str,
                        default='false', choices=['true', 'false'], help='')
    parser.add_argument('--dpi', dest='dpi', type=int, default=100,
                        help='dpi if figure')
    args = parser.parse_args()
    return args

def main():
    args = parse_args()
    plot_train_curve(train_record_path=args.train_record_path,
                     label=args.label,
                     var_name=args.var_name,
                     linewidth=args.linewidth,
                     fig_path=args.fig_path,
                     dpi=args.dpi,
                     interactive=args.interactive == 'true')

if __name__ == '__main__':
    main()


from gtts import gTTS
from io import BytesIO

import speech_recognition as sr

print('<< Show Sound Device List >>\n', sr.Microphone.list_microphone_names())

cur_weather = '맑음'
next_weather = '더 맑음'
text = '현재 날씨는 {}이며 내일 날씨는 {} 입니다.'.format(cur_weather, next_weather)

tts = gTTS(text=text, lang='ko')

out_file_name = 'test.mp3'
tts.save(out_file_name)

import pygame

freq = 24000    # sampling rate, 44100(CD), 16000(Naver TTS), 24000(google TTS)
bitsize = -16   # signed 16 bit. support 8,-8,16,-16
channels = 1    # 1 is mono, 2 is stereo
buffer = 2048   # number of samples (experiment to get right sound)

# default : pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
pygame.mixer.init(freq, bitsize, channels, buffer)
pygame.mixer.music.load(out_file_name)
pygame.mixer.music.play()

clock = pygame.time.Clock()
while pygame.mixer.music.get_busy():
    clock.tick(30)
pygame.mixer.quit()


import sys
from datetime import datetime

MIN = -((2 ** 15) - 1)

def cut_rod(p, n):
	if n == 0:
		return 0
	q = MIN

	# loop runs from 0 to n-1
	for i in range (0,n):
		# n-(i+1) because loop run from 0 instead of 1
		q = max([q, p[i]+cut_rod(p,n-(i+1))])

	return q

def memoized_cut_rod(p, n):
	r = dict()
	#  n+1 because we need a dict from [0....n]
	for i in range(0,n+1):
		r[i] = MIN
	return memoized_cut_rod_aux(p, n, r)

def memoized_cut_rod_aux(p, n, r):
	q = MIN
	if r[n] >= 0:
		return r[n]
	if n == 0:
		q = 0
	elif q == MIN:
		for i in range(0, n):
			# n-(i+1) because loop run from 0 instead of 1
			q = max([q, p[i]+memoized_cut_rod_aux(p, n-(i+1), r)])
	r[n] = q
	# print(r)
	return q

def bottom_up_cut_rod(p, n):
	r = dict()
	r[0] = 0

	# for subproblem size n=1 to n
	for j in range(1, n+1):
		q = MIN

		# find solution using solutions of subproblems below choosen subproblem
		for i in range(0, j):
			q = max([q, p[i]+r[j-(i+1)]])
		r[j] = q
	return r[n]

def extended_bottom_up_cut_rod(p, n):
	r = dict()
	s = dict()
	r[0] = 0
	s[0] = 0
	# for subproblem size n=1 to n
	for j in range(1,n+1):
		q = MIN

		# find solution using solutions of subproblems below, choosen subproblem
		for i in range(0, j):
			if q < p[i] + r[j-(i+1)]:
				q = p[i]+r[j-(i+1)]
				s[j] = i+1
		r[j] = q
	return r,s

def print_cut_rod_solution(p, n):
	r, s = extended_bottom_up_cut_rod(p,n)
	print('extended_bottom_up_cut_rod outputs: ')
	print('r: ',r)
	print('s: ',s)
	while n > 0:
		print(s[n])
		n -= s[n]

def timeit_wrapper(f, p, n, name):
	start_time = datetime.now()
	print(f'Maximum revenue found using {name}: {f(p, n)}')
	print(f'Excution time of {name}: {(datetime.now() - start_time)}\n')

if __name__ == '__main__':

	# price list, list is extended from the one in text book to see the time difference when problem size increases
	p = ([1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 32, 35, 45, 46, 50])

	# problem size or rod size
	n = 14

	timeit_wrapper(f=cut_rod, p=p, n=n, name='cut_rod')
	timeit_wrapper(f=memoized_cut_rod, p=p, n=n, name='memoized_cut_rod')
	timeit_wrapper(bottom_up_cut_rod, p, n, 'bottom_up_cut_rod')

	print_cut_rod_solution(p, n)