"""I/O devices for interacting with the shortest path program
"""

from tkinter import Button, Frame, Label, Tk
from typing import Callable

from mediatorbuilder import NullMediatorBuilder, MediatorBuilder

class InputFrameBuilder:
    """Builder class for inputting the settings for the input frame
    """
    # Private Attributes:
    #   - _data: the data to display to the user to select from
    #   - _geometry: the geometry of the built frame
    #   - _title: the title of the built frame
    #   - _mb: the MediatorBuilder to use to let input fields interact with each other
    #   - _command: the output function to be called when hitting Export Selection

    _data: list[tuple]

    _geometry: str = "300x150"
    _title: str = "Settings Input"

    _mb: MediatorBuilder = NullMediatorBuilder()

    _command: Callable = print

    def set_data(self, data: list[tuple]) -> None:
        """Sets the data to be used for selecting options"""
        self._data = data

    def set_geometry(self, geometry: str) -> None:
        """Sets the size of the frame

        Preconditions:
            - geometry must be a valid input for Tk().geometry()
        """
        self._geometry = geometry

    def set_title(self, title: str) -> None:
        """Sets the title of the frame"""
        self._title = title

    def set_button_command(self, command: Callable) -> None:
        """Sets the command called when clicking the button

        The dict containing the Widget name to its selection is passed into this command
        """
        self._command = command

    def set_mediator_builder(self, mb: MediatorBuilder) -> None:
        """Sets the MediatorBuilder to use when creating the input frame"""
        self._mb = mb

    def get_frame(self) -> Tk:
        """Get the frame using the set settings"""

        world = Tk()
        world.title(self._title)
        world.resizable(height=False, width=True)

        f = Frame(world)
        f.pack()

        mediator = self._mb.get_mediator(parent=f)

        named_widgets = mediator.get_components()
        for row, menu_name in enumerate(named_widgets):
            menu = named_widgets[menu_name]

            Label(f, text=menu_name).grid(row=row, column=0, sticky="nsew")
            menu.grid(row=row, column=1, sticky="nsew")

        def _command_wrapper() -> None:
            self._command(mediator.get_selection())

        Button(f, text="Reset Selection", command=mediator.reset_selection). \
            grid(row=len(named_widgets) + 1, column=0, sticky="sew")

        Button(f, text="Export Selection", command=_command_wrapper). \
            grid(row=len(named_widgets) + 1, column=1, sticky="sew")

        return world


import socket
import sys

TOSENDSERVER = socket.socket()
host = socket.gethostname()
port = 8800

TOSENDSERVER.connect((host, port))

selectedFile = input("Pilih file (contoh : TikTok.mp4) : ")
try:
	tosend_file = open(selectedFile,'rb')
	print ("File opened")
except Exception as fileerror:
	print ("Cannot open this file check this error: %s " % str(fileerror))
Filetosend = tosend_file.read(4069)
while (Filetosend):
    print ("Sending your file...")
    TOSENDSERVER.send(Filetosend)
    Filetosend = tosend_file.read(4096)
tosend_file.close()
print ("File sended sucessfully\n clossing...")
TOSENDSERVER.close()
sys.exit('Closed by system')

import sys
import socket

RECVSERVER = socket.socket()
host = socket.gethostname()
port = 8800
RECVSERVER.bind((host, port))

RECVSERVER.listen(5)
while True:
    c, addr = RECVSERVER.accept()
    print ("File will recv from: ", addr)
    print ("Start recv...")
    FILETORECV = c.recv(4096)
    hasil = input("Masukkan Nama File Hasil Konverter (contoh : Hasil.mp4) : ")
    recv_file = open(hasil,'wb')
    while (FILETORECV):
        print ("Receiving...")
        recv_file.write(FILETORECV)
        FILETORECV = c.recv(4096)
    recv_file.close()
    print ("File recv or converted sucessfully.")
    c.send('Message from client: File received sucessfully. tnx'.encode())
c.close()
sys.exit('closed by system')


# -*- coding: utf-8 -*-
from plone.app.contenttypes.testing import PLONE_APP_CONTENTTYPES_FIXTURE
from plone.app.robotframework.testing import REMOTE_LIBRARY_BUNDLE_FIXTURE
from plone.app.testing import (
    applyProfile,
    FunctionalTesting,
    IntegrationTesting,
    PloneSandboxLayer,
)
from plone.testing import z2

import rer.block.iframembed

class RerBlockIframembedLayer(PloneSandboxLayer):

    defaultBases = (PLONE_APP_CONTENTTYPES_FIXTURE,)

    def setUpZope(self, app, configurationContext):
        # Load any other ZCML that is required for your tests.
        # The z3c.autoinclude feature is disabled in the Plone fixture base
        # layer.
        import plone.restapi
        self.loadZCML(package=plone.restapi)
        self.loadZCML(package=rer.block.iframembed)

    def setUpPloneSite(self, portal):
        applyProfile(portal, 'rer.block.iframembed:default')

RER_BLOCK_IFRAMEMBED_FIXTURE = RerBlockIframembedLayer()

RER_BLOCK_IFRAMEMBED_INTEGRATION_TESTING = IntegrationTesting(
    bases=(RER_BLOCK_IFRAMEMBED_FIXTURE,),
    name='RerBlockIframembedLayer:IntegrationTesting',
)

RER_BLOCK_IFRAMEMBED_FUNCTIONAL_TESTING = FunctionalTesting(
    bases=(RER_BLOCK_IFRAMEMBED_FIXTURE,),
    name='RerBlockIframembedLayer:FunctionalTesting',
)

RER_BLOCK_IFRAMEMBED_ACCEPTANCE_TESTING = FunctionalTesting(
    bases=(
        RER_BLOCK_IFRAMEMBED_FIXTURE,
        REMOTE_LIBRARY_BUNDLE_FIXTURE,
        z2.ZSERVER_FIXTURE,
    ),
    name='RerBlockIframembedLayer:AcceptanceTesting',
)


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from geopy.geocoders import Nominatim
from pprint import pprint
import time

app = Nominatim(user_agent="tutorial")

def getLocation():
    options = Options()
    options.add_argument("--use-fake-ui-for-media-stream")
    timeout = 20
    driver = webdriver.Chrome(
        executable_path='./chromedriver.exe', chrome_options=options)
    driver.get("https://mycurrentlocation.net/")
    wait = WebDriverWait(driver, timeout)
    time.sleep(3)
    longitude = driver.find_elements_by_xpath('//*[@id="longitude"]')
    longitude = [x.text for x in longitude]
    longitude = str(longitude[0])
    latitude = driver.find_elements_by_xpath('//*[@id="latitude"]')
    latitude = [x.text for x in latitude]
    latitude = str(latitude[0])
    driver.quit()
    return (latitude, longitude)

vari = getLocation()
print(type(vari))
(latitude, longitude) = vari
# print(getLocation())

def get_address_by_location(latitude, longitude, language="en"):
    """This function returns an address as raw from a location
    will repeat until success"""
    # build coordinates string to pass to reverse() function
    coordinates = f"{latitude}, {longitude}"
    # sleep for a second to respect Usage Policy
    time.sleep(1)
    try:
        return app.reverse(coordinates, language=language).raw
    except:
        return get_address_by_location(latitude, longitude)

print(get_address_by_location(latitude, longitude))


###############################################################################
#
#  Project:  Embedded Learning Library (ELL)
#  File:     imageConverter.py
#  Authors:  Chris Lovett
#
###############################################################################

import sys
import numpy as np
import cv2
import argparse

def resize_image(image, newSize):
    if (image.shape[0] > image.shape[1]):  # Tall(more rows than cols)
        rowStart = int((image.shape[0] - image.shape[1]) / 2)
        rowEnd = rowStart + image.shape[1]
        colStart = 0
        colEnd = image.shape[1]
    else:  # Wide(more cols than rows)
        rowStart = 0
        rowEnd = image.shape[0]
        colStart = int((image.shape[1] - image.shape[0]) / 2)
        colEnd = colStart + image.shape[0]

        cropped = image[rowStart:rowEnd, colStart:colEnd]
        resized = cv2.resize(cropped, newSize)
        return resized

def prepare_image_for_predictor(image, newSize, scale, bgr2rgb):
    if newSize[0] and newSize[1]:
        resized = resize_image(image, newSize)
    if bgr2rgb != 0:
        resized = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
    resized = resized.astype(np.float).ravel()
    if scale != 0:
        resized *= scale
    return resized

def save_raw(name, data):
    with open(name, 'wb') as f:
        f.write(bytearray(data))
        f.close()

def strtobool(arg):
    if arg.lower() in ['t', 'true', 'yes', '1']:
        return True
    return False

def main(argv):
    """
    This is a plugin for the debugCompiler tool.  It expects a list of string arguments as input and it returns the
    image preprocessed and prepared for input to an ELL test model.  The result has to be a list of floats.
    """
    arg_parser = argparse.ArgumentParser("imageConverter takes an image as input and converts it to an array of \
floating point numbers")
    arg_parser.add_argument("--bgr", default="False",
                            help="specify True if input data should be in BGR format (default False)")
    arg_parser.add_argument("--width", type=int, default=0, help="resize the image to this new width (default None)")
    arg_parser.add_argument("--height", type=int, default=0, help="resize the image to this new height (default None)")
    arg_parser.add_argument("--scale", type=float, default=0,
                            help="scale the floating point numbers by this amount (default None)")
    arg_parser.add_argument("--image", default=None, required=True,
                            help="name of file containing image as png, jpg, etc (default None)")
    arg_parser.add_argument("--outputData", "-od", default=None,
                            help="name of file to write the resulting raw floating point data (default None)")

    args = arg_parser.parse_args(argv)

    image = cv2.imread(args.image)
    if image is None:
        print("Error reading image {}".format(args.image))

    resized = prepare_image_for_predictor(image, (args.height, args.width), args.scale, args.bgr)

    if args.outputData:
        save_raw(args.outputData, resized)

    return list(resized)

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


import sys
import pygame
from pygame import *

import Bird
from Bird import *

# Create a const variables for game
WIDTH = 1000
HEIGHT = 500
FPS = 30
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (100, 200, 255)

# Function which init game and screen for game
def run():
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Pixel Birds")
    clock = pygame.time.Clock()
    screen.fill(BLUE)
    pygame.display.flip()

    bird = Bird(500, 200)
    left = right = False
    up = False

    def render_screen():
        pygame.display.update()
        screen.fill(BLUE)

    def render_bird():
        bird.update(left, right, up)
        bird.draw(screen)

    # Cycle for game event
    game_running = True
    while game_running:
        clock.tick(FPS)
        render_bird()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_running = False
            elif event.type == KEYDOWN and event.key == K_LEFT:
                left = True
            elif event.type == KEYDOWN and event.key == K_RIGHT:
                right = True
            elif event.type == KEYDOWN and event.key == K_UP:
                up = True
            elif event.type == KEYUP and event.key == K_UP:
                up = False
            elif event.type == KEYUP and event.key == K_LEFT:
                left = False
            elif event.type == KEYUP and event.key == K_RIGHT:
                right = False
            elif event.type == QUIT:
                return sys.exit()
        render_screen()

run()


from src.engine.blocks import Block, Convex, Flat
import pytest
import mock

def test_block_class_object_cant_be_created():
    with pytest.raises(TypeError):
        Block()

def test_convex_class_object_cant_be_created():
    with pytest.raises(TypeError):
        Convex()

def test_flat_class_object_cant_be_created():
    with pytest.raises(TypeError):
        Flat()

def test_block_class_has_static_empty_method_texture():
    Block.__abstractmethods__ = set()
    assert Block.texture() is None

def test_block_class_has_empty_method_interact_with_snake():
    Block.__abstractmethods__ = set()
    snake = mock.Mock()
    assert Block().interact_with_snake(snake) is None

def test_block_class_set_field():
    field = mock.Mock()
    Block.__abstractmethods__ = set()
    block = Block()
    block.set_field(field)
    assert block.field == field

def test_flat_class_has_empty_method_interact_with_convex():
    Flat.__abstractmethods__ = set()
    convex = mock.Mock()
    assert Flat().interact_with_convex(convex) is None

def test_convex_class_has_empty_method_move():
    Convex.__abstractmethods__ = set()
    direction = mock.Mock()
    assert Convex().move(direction) is None

def test_convex_class_has_empty_method_check_snake_move():
    Convex.__abstractmethods__ = set()
    assert Convex().check_snake_move() is None

def test_convex_class_has_empty_method_check_move():
    Convex.__abstractmethods__ = set()
    direction = mock.Mock()
    assert Convex().check_move(direction) is None

def test_block_self_draw_when_drawing_same_size_as_remembered():
    Block().__abstractmethods__ = set()
    frame = mock.Mock()
    position = mock.Mock()
    displayed_texture = mock.Mock()
    block = Block()
    block.displayed_side_length = 10
    block.displayed_texture = displayed_texture
    block.self_draw(frame, position, 10)
    assert block.displayed_texture == displayed_texture
    frame.blit.assert_called_once_with(displayed_texture, position)

def test_convex_that_is_not_alive_self_draw_wont_draw_in_frame_and_will_be_removed_from_its_field():
    Convex().__abstractmethods__ = set()
    convex = Convex()
    convex.is_alive = False
    frame = mock.Mock()
    position = mock.Mock()
    field = mock.Mock()
    convex.field = field
    convex.self_draw(frame, position, 77)
    field.remove_convex.assert_called_once()
    assert not frame.blit.called

def test_convex_that_is_alive_self_draw_will_draw_in_frame_when_remembered_size_equals_current_one():
    Convex().__abstractmethods__ = set()
    convex = Convex()
    convex.is_alive = True
    frame = mock.Mock()
    position = mock.Mock()
    field = mock.Mock()
    convex.field = field
    convex.displayed_side_length = 1234
    convex.self_draw(frame, position, 1234)
    frame.blit.assert_called_once()


import cv2

import serial
import time

def write_read(message):
    if arduino_output:
        arduino.write(bytes(str(message), 'utf-8'))
        time.sleep(0.05)
        data = arduino.readline()
        return data
    return ""

def set_pos(x, y):
    out = str(x)+str(y)+"\n"
    value = write_read(out)
    print(f"write :{out}")
    print(f"read :{value}")

# ^ pip install opencv-contrib-python

# Enable camera

arduino_output = False  # constant for arduino communication, false to test with no arduino
debug = True  # print vars? display image?

if arduino_output:
    arduino = serial.Serial(port='COM20', baudrate=115200, timeout=.1)  # change com port depending on the com port

resX = 1000  # constants for camera res (does not need to match real res)
resY = 500

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(3, resX)
cap.set(4, resY)

# import cascade file for facial recognition
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

# if you want to detect any object for example eyes, use one more layer of classifier as below:
eyeCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml")

dxd = 0
dyd = 0

eye_conf_threshold = 3  # const
face_conf_threshold = 3  # const

eye_coords = []
targetX, targetY = 0, 0
dx, dy = 0, 0
loop_counter = 0

while True:
    success, img = cap.read()
    try:
        imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    except:  # Fix pep thing Vojta
        raise Exception("Camera not found!")

    # Getting corners around the face

    # detecting eyes
    eyes = eyeCascade.detectMultiScale3(
        imgGray,
        outputRejectLevels=True)
    faces = faceCascade.detectMultiScale3(
        imgGray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        outputRejectLevels=True)

    eye_coords = []
    face_coords = []
    # print(faces)
    # print(f"confidence = {eyes[2][0][0]}")
    #
    # for (x, y, w, h) in faces[0]:
    #     face_coords.append((x + (w/2), y + (h/2)))
    #     cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    for counter in range(len(eyes[2])):
        if eyes[2][counter][0] > eye_conf_threshold:
            ex, ey, ew, eh = eyes[0][counter]
            eye_coords.append((ex + (ew / 2), ey + (eh / 2)))
            img = cv2.rectangle(img, (ex, ey), (ex + ew, ey + eh), (255, 0, 0), 3)

    eye_in_face_coords = (-1, -1)

    for counter in range(len(faces[2])):
        if faces[2][counter][0] > face_conf_threshold:
            fx, fy, fw, fh = faces[0][counter]
            for eye_coord in eye_coords:
                currentX = eye_coord[0]
                currentY = eye_coord[1]
                if fx < currentX < fx+fw and fy < currentY < fy+fh:
                    eye_in_face_coords = (currentX, currentY)
            eye_coords.append((fx + (fw / 2), fy + (fh / 2)))
            img = cv2.rectangle(img, (fx, fy), (fx + fw, fy + fh), (255, 0, 0), 3)

    eyesX = []
    eyesY = []
    if eye_in_face_coords != (-1, -1):
        targetX = eye_in_face_coords[0]
        targetY = eye_in_face_coords[1]
    elif len(eye_coords) > 0:
        for eye in eye_coords:
            eyesX.append(eye[0])
            eyesY.append(eye[1])
        targetX = int(sum(eyesX) / len(eyesX))
        targetY = int(sum(eyesY) / len(eyesY))
    else:  # if no target currently on screen, do not move camera
        targetX = (resX/2)
        targetY = (resY/2)

    weightedX = int(float((resX/2) - targetX)/(resX/100))  # expected range: [-100,100]
    weightedY = int(float((resY/2) - targetY)/(resY/100))  # expected range: [-100,100]

    if loop_counter < 50:
        loop_counter += 1
    else:
        loop_counter = 0

    if -10 > weightedX:
        dxd = 2  # 2 means -1, but using only one char
    elif weightedX > 10:
        dxd = 1
    else:
        dxd = 0

    if -10 > weightedY:
        dyd = 1
    elif weightedY > 10:
        dyd = 2  # 2 means -1, but using only one char
    else:
        dyd = 0

    if abs(weightedX) > loop_counter:
        dx = dxd
    else:
        dx = 0
    if abs(weightedY) > loop_counter:
        dy = dyd
    else:
        dy = 0
    if debug:
        print(f"weightedX: {weightedX}\nweightedY: {weightedY}")
        print(f"dxd: {dxd}\ndyd: {dyd}")
        print(f"dx: {dx}\ndy: {dy}")
        print(f"targetX: {targetX}\ntargetY: {targetY}")
        set_pos(dx, dy)
        img = cv2.rectangle(img, (int(targetX-5), int(targetY-5)), (int(targetX+5), int(targetY+5)), (255, 255, 0), 3)
        if eye_in_face_coords != (-1, -1):
            eye_in_face_x = eye_in_face_coords[0]
            eye_in_face_y = eye_in_face_coords[1]
            img = cv2.rectangle(img, (int(eye_in_face_x - 5), int(eye_in_face_y - 5)),
                                (int(eye_in_face_x + 5), int(eye_in_face_y + 5)), (255, 255, 255), 3)
        cv2.imshow('face_detect', img)

    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyWindow('face_detect')


# Run from prefect directory (after terraform vars gen) using
# prefect run --name sim-prep --param name=florance --param year=2018

# For logging, use `logger = prefect.context.get("logger")` within tasks
import argparse
import warnings
import pathlib

from prefect import case
from prefect.utilities import graphql
from prefect.client import Client
from prefect.tasks.control_flow import merge

from conf import PREFECT_PROJECT_NAME, INIT_FINI_LOCK
from tasks.params import (
        param_storm_name, param_storm_year,
        param_use_rdhpcs, param_use_rdhpcs_post, param_run_id,
        param_use_parametric_wind, param_subset_mesh, param_ensemble,
        param_mesh_hmax,
        param_mesh_hmin_low, param_mesh_rate_low,
        param_mesh_trans_elev,
        param_mesh_hmin_high, param_mesh_rate_high,
        param_ensemble_n_perturb, param_hr_prelandfall,
        param_ensemble_sample_rule,
        param_past_forecast,
        param_wind_coupling,
        )
from tasks.data import (
        task_copy_s3_data,
        task_init_run,
        task_final_results_to_s3,
        task_cleanup_run,
        task_cache_to_s3,
        task_cleanup_efs)
from tasks.utils import (
        task_check_param_true,
        task_bundle_params,
        task_get_flow_run_id,
        task_get_run_tag,
        FLock)
from flows.jobs.ecs import (
        make_flow_generic_ecs_task,
        make_flow_solve_ecs_task
        )
from flows.jobs.pw import(
        make_flow_mesh_rdhpcs_pw_task,
        make_flow_mesh_rdhpcs,
        make_flow_solve_rdhpcs_pw_task,
        make_flow_solve_rdhpcs)
from flows.utils import LocalAWSFlow, flow_dependency

# TODO: Later add build image and push to ECS logic into Prefect workflow

# TODO: Use subprocess.run to switch backend here
# TODO: Create user config file to be session based? https://docs-v1.prefect.io/core/concepts/configuration.html#environment-variables

def _check_project():
    client = Client()
    print(f"Connecting to {client.api_server}...")

    qry = graphql.parse_graphql({'query': {'project': ['name']}})
    rsp = client.graphql(qry)

    prj_names = [i['name'] for i in rsp['data']['project']]
    if PREFECT_PROJECT_NAME in prj_names:
        print(f"Project {PREFECT_PROJECT_NAME} found on {client.api_server}!")
        return

    print(f"Creating project {PREFECT_PROJECT_NAME} on {client.api_server}...")
    client.create_project(project_name=PREFECT_PROJECT_NAME)
    print("Done!")

def _make_workflow():
    # Create flow objects
    flow_sim_prep_info_aws = make_flow_generic_ecs_task("sim-prep-info-aws")
    flow_sim_prep_mesh_aws = make_flow_generic_ecs_task("sim-prep-mesh-aws")
    flow_sim_prep_setup_aws = make_flow_generic_ecs_task("sim-prep-setup-aws")
    flow_mesh_rdhpcs_pw_task = make_flow_mesh_rdhpcs_pw_task()
    flow_mesh_rdhpcs = make_flow_mesh_rdhpcs(flow_mesh_rdhpcs_pw_task)
    flow_schism_single_run_aws = make_flow_generic_ecs_task("schism-run-aws-single")
    flow_schism_ensemble_run_aws = make_flow_solve_ecs_task(flow_schism_single_run_aws)
    flow_solve_rdhpcs_pw_task = make_flow_solve_rdhpcs_pw_task()
    flow_solve_rdhpcs = make_flow_solve_rdhpcs(flow_solve_rdhpcs_pw_task)
    flow_sta_html_aws = make_flow_generic_ecs_task("viz-sta-html-aws")
    flow_cmb_ensemble_aws = make_flow_generic_ecs_task(
        "viz-cmb-ensemble-aws"
    )
    flow_ana_ensemble_aws = make_flow_generic_ecs_task(
        "viz-ana-ensemble-aws"
    )

    with LocalAWSFlow("end-to-end") as flow_main:

        result_flow_run_id = task_get_flow_run_id()

        result_run_tag = task_get_run_tag(
            param_storm_name, param_storm_year, result_flow_run_id)

        result_is_rdhpcs_on = task_check_param_true(param_use_rdhpcs)
        result_is_ensemble_on = task_check_param_true(param_ensemble)
        result_is_rdhpcspost_on = task_check_param_true(param_use_rdhpcs_post)

        with FLock(INIT_FINI_LOCK, task_args={'name': 'Sync init'}):
            result_copy_task = task_copy_s3_data()
            result_init_run = task_init_run(
                    result_run_tag, upstream_tasks=[result_copy_task])

        result_bundle_params_1 = task_bundle_params(
                name=param_storm_name,
                year=param_storm_year,
                rdhpcs=param_use_rdhpcs,
                rdhpcs_post=param_use_rdhpcs_post,
                run_id=result_flow_run_id,
                parametric_wind=param_use_parametric_wind,
                ensemble=param_ensemble,
                hr_before_landfall=param_hr_prelandfall,
                past_forecast=param_past_forecast,
                couple_wind=param_wind_coupling,
                )

        result_bundle_params_2 = task_bundle_params(
                name=param_storm_name,
                year=param_storm_year,
                rdhpcs=param_use_rdhpcs,
                run_id=result_flow_run_id,
                subset_mesh=param_subset_mesh,
                mesh_hmax=param_mesh_hmax,
                mesh_hmin_low=param_mesh_hmin_low,
                mesh_rate_low=param_mesh_rate_low,
                mesh_cutoff=param_mesh_trans_elev,
                mesh_hmin_high=param_mesh_hmin_high,
                mesh_rate_high=param_mesh_rate_high
                )

        result_bundle_params_3 = task_bundle_params(
                name=param_storm_name,
                year=param_storm_year,
                run_id=result_flow_run_id,
                parametric_wind=param_use_parametric_wind,
                ensemble=param_ensemble,
                ensemble_num_perturbations=param_ensemble_n_perturb,
                hr_before_landfall=param_hr_prelandfall,
                couple_wind=param_wind_coupling,
                ensemble_sample_rule=param_ensemble_sample_rule,
        )

        after_sim_prep_info = flow_dependency(
                flow_name=flow_sim_prep_info_aws.name,
                upstream_tasks=[result_init_run],
                parameters=result_bundle_params_1)

        # TODO: Meshing based-on original track for now
        # TODO: If mesh each track: diff mesh

        with case(result_is_rdhpcs_on, True):
            after_sim_prep_mesh_b1 = flow_dependency(
                    flow_name=flow_mesh_rdhpcs.name,
                    upstream_tasks=[after_sim_prep_info],
                    parameters=result_bundle_params_2)
        with case(result_is_rdhpcs_on, False):
            after_sim_prep_mesh_b2 = flow_dependency(
                    flow_name=flow_sim_prep_mesh_aws.name,
                    upstream_tasks=[after_sim_prep_info],
                    parameters=result_bundle_params_2)
        after_sim_prep_mesh = merge(after_sim_prep_mesh_b1, after_sim_prep_mesh_b2)

        after_sim_prep_setup = flow_dependency(
                flow_name=flow_sim_prep_setup_aws.name,
                upstream_tasks=[after_sim_prep_mesh],
                parameters=result_bundle_params_3)

        with case(result_is_rdhpcs_on, True):
            after_run_schism_b1 = flow_dependency(
                    flow_name=flow_solve_rdhpcs.name,
                    upstream_tasks=[after_sim_prep_setup],
                    parameters=result_bundle_params_1)
        with case(result_is_rdhpcs_on, False):
            after_run_schism_b2 = flow_dependency(
                flow_name=flow_schism_ensemble_run_aws.name,
                upstream_tasks=[after_sim_prep_setup],
                parameters=result_bundle_params_1)
        after_run_schism = merge(after_run_schism_b1, after_run_schism_b2)

        with case(result_is_ensemble_on, True):
            with case(result_is_rdhpcspost_on, False):
                after_cmb_ensemble = flow_dependency(
                    flow_name=flow_cmb_ensemble_aws.name,
                    upstream_tasks=[after_run_schism],
                    parameters=result_bundle_params_1)
                after_ana_ensemble = flow_dependency(
                    flow_name=flow_ana_ensemble_aws.name,
                    upstream_tasks=[after_cmb_ensemble],
                    parameters=result_bundle_params_1)

            with case(result_is_rdhpcspost_on, True):
                # TODO:
                pass

        with case(result_is_ensemble_on, False):
            after_sta_html = flow_dependency(
                flow_name=flow_sta_html_aws.name,
                upstream_tasks=[after_run_schism],
                parameters=result_bundle_params_1)
        after_gen_viz = merge(after_ana_ensemble, after_sta_html)

        # TODO: Make this a separate flow?
        after_results_to_s3 = task_final_results_to_s3(
                param_storm_name, param_storm_year, result_run_tag,
                upstream_tasks=[after_gen_viz])

        after_cleanup_run = task_cleanup_run(
                result_run_tag, upstream_tasks=[after_results_to_s3])

        with FLock(INIT_FINI_LOCK, upstream_tasks=[after_cleanup_run], task_args={'name': 'Sync cleanup'}):
            after_cache_storage = task_cache_to_s3(
                    upstream_tasks=[after_cleanup_run])
            task_cleanup_efs(
                    result_run_tag,
                    upstream_tasks=[after_cache_storage])

    flow_main.set_reference_tasks([after_cleanup_run])

    all_flows = [
        flow_sim_prep_info_aws,
        flow_sim_prep_mesh_aws,
        flow_sim_prep_setup_aws,
        flow_mesh_rdhpcs_pw_task,
        flow_mesh_rdhpcs,
        flow_schism_single_run_aws,
        flow_schism_ensemble_run_aws,
        flow_solve_rdhpcs_pw_task,
        flow_solve_rdhpcs,
        flow_sta_html_aws,
        flow_cmb_ensemble_aws,
        flow_ana_ensemble_aws,
        flow_main
    ]

    return all_flows

def _regiser(flows):
    # Register unregistered flows
    for flow in flows:
        flow.register(project_name=PREFECT_PROJECT_NAME)

def _viz(flows, out_dir, flow_names):
    flow_dict = {f.name: f for f in flows}
    for flow_nm in flow_names:
        flow = flow_dict.get(flow_nm)
        if flow is None:
            warnings.warn(f'Flow with the name {flow_nm} NOT found!')
        flow.visualize(filename=out_dir/flow.name, format='dot')

def _list(flows):
    flow_names = [f.name for f in flows]
    print("\n".join(flow_names))

def _main(args):

    _check_project()
    all_flows = _make_workflow()
    if args.command in ["register", None]:
        _regiser(all_flows)

    elif args.command == "visualize":
        _viz(all_flows, args.out_dir, args.flowname)

    elif args.command == "list":
        _list(all_flows)

    else:
        raise ValueError("Invalid command!")

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest="command")

    reg_parser = subparsers.add_parser('register')
    viz_parser = subparsers.add_parser('visualize')
    list_parser = subparsers.add_parser('list')

    viz_parser.add_argument('flowname', nargs='+')
    viz_parser.add_argument(
        '--out-dir', '-d', type=pathlib.Path, default='.')

    _main(parser.parse_args())


PRICES = {
    "kebab":3_600_00,
    "tacos":4_000_00,
    "sandwich": 1_200_00,
    "burger":2_200_00,
    "juice":1_200_00
}

class PaytechPaymentHandler:
    def handle_payment(self,amount:int):
        print(f"Charging {amount/100:.2f} XOF using PayTech")

def order_food(elts: list[str]) -> None:
    """The think to note here is,
    We create a `PaytechPaymentHandler` object.
    Something that should not be the responsibility of this function
    """
    total = sum([PRICES[elt] for elt in elts])
    print(f"You order amount is {total} XOF.")
    payment_handler = PaytechPaymentHandler()
    payment_handler.handle_payment(total)
    print("Thank you for trusting us.")

def main():
    order_food(["tacos", "sandwich", "juice"])

if __name__=="__main__":
    main()


# iterate through file
with open("day-4/input.txt", "r") as file:
    overlaps = 0

    for line in file:
        assignments = []

        for assignment in line.strip().split(","):
            assignments.append(assignment.split("-"))
        for i in range(len(assignments)):
            for j in range(len(assignments[i])):
                assignments[i][j] = int(assignments[i][j])

        arrays = []
        for assignment in assignments:
            array = []
            for i in range(assignment[0], assignment[1] + 1):
                array.append(i)
            arrays.append(array)

        print(arrays)

        for i in range(len(arrays[0])):
            if arrays[0][i] in arrays[1]:
                overlaps += 1
                break

    print(f'Number of overlaps: {overlaps}')


#!/usr/bin/env python
#
# midiin_poll.py
#
"""Show how to receive MIDI input by polling an input port."""

from __future__ import print_function

import logging
import sys
import time
import os

from rtmidi.midiutil import open_midiinput
import pandas
import datetime

log = logging.getLogger('midiin_poll')
logging.basicConfig(level=logging.DEBUG)

# Prompt user to indicate what hand(s) they will be practicing with
hand = input("Pleast type 'left', 'right', or 'both' to indicate the hand(s) you are practicing: ")

# Prompt user for practice module name
module = input("Please type the name of the practice module: ")

# Prompts user for MIDI input port, unless a valid port number or name
# is given as the first argument on the command line.
# API backend defaults to ALSA on Linux.
port = sys.argv[1] if len(sys.argv) > 1 else None

# Opens a midi input port and assigns a midiin object and captures name of port
midiin, port_name = open_midiinput(port)

# Prompt for performing a hard exit
print("Entering main loop. Press Control-C to exit.")

# Starts time before any keys are pressed e.g.: beginning of practice session
timer = time.time()

# Create a dataframe to store pressed key data in locally
df = pandas.DataFrame(columns = ['Date', 'Module', 'Hand', 'Time', 'Stroke', 'Key', 'Speed'])

# Main loop for capturing pressed key data
while True:
    # Retrieves most recent midi input message
    msg = midiin.get_message()

    if msg: # Following creates variables and adds them to the dataframe
        message, deltatime = msg
        timer += deltatime
        date = datetime.datetime.now().date()
        df = df.append({
            'Date' : date,
            'Module' : module,
            'Hand' : hand,
            'Time' : timer,
            'Stroke' : message[0],
            'Key' : message[1],
            'Speed' : message[2]
            },
                ignore_index = True)

        # Filters dataframe for beginning and end of key stroke AND foot pedal presses
        df = df[(df.Stroke == 144) | (df.Stroke == 128) | (df.Stroke == 177)]

        # Removes the duplicate foot pedal speed data; foot pedal data can now be IDed as Stroke=177 and Soeed=0
        df = df[-((df.Stroke == 177) & (df.Speed == 127))]

        # Create a unique csv name based on module and date
        filename = date.strftime('%Y-%m-%d') + module + '.csv'

        # Write the data to the datastorace csv
        df.to_csv(filename, mode='w', header=True, index=True)

        time.sleep(0.01)


from flask import Flask, request
app = Flask("ccserver")
datadict = dict()

def log(text:str, filename="log.txt"):
    with open(filename, "a") as f:
        f.write("\n" + text)

@app.route("/up", methods=["GET"])
def up():
    source = request.args.get("source")
    target = request.args.get("target")
    data = request.args.get("data")
    log(data, "up.txt")
    if target in list(datadict.keys()):
        datadict[target].append({source:data})
    else:
        datadict[target] = [{source:data}]
    log(str(datadict), "log.txt")
    return ""

@app.route("/down", methods=["GET"])
def down():
    source = request.args.get("source")
    target = request.args.get("target")
    try:
        for i, source_data in enumerate(datadict[target]):
            if list(source_data.keys())[0] == source:
                requested_data = datadict[target].pop(i)
                return source_data[source]
    except Exception as e:
        log(str(e), "down.txt")
        return ""

app.run("0.0.0.0", port=1234, debug=True)


monster = {
    'Nergigante': {
        "status": ["HP: 10000", "Ataque: Sangramento,Dragão", "Fraquesa: Fogo,Paralizia"],
        "habilidades": ["SAMGRAMENTO"],
        "tipo": ["Fenda do ancião", "images/Nergigante.jpg", "#ef5350"],
    },

    'Bazel': {
        "status": ["HP: 5000", "Ataque: Explosão", "Fraqueza: raio,agua"],
        "habilidades": ["SAMGRAMENTO"],
        "tipo": ["Planalto coralino", "images/Bazel.jpg", "#6f9fbd"],
    },

    'Vaal Hazak': {
        "status": ["HP: 10000", "Ataque: Veneno", "Fraqueza: fogo,Paralizia"],
        "habilidades": ["Efluvio"],
        "tipo": ["Vale", "images/Val.jpg", "#BA68C8"],
    },
}


from tkinter import *
import sys
import random, time
import numpy as np
from threading import *
import requests
from bs4 import BeautifulSoup

#colorTheme = ['white', 'black', 'gray38', 'black']
#colorTheme = ['lightgray', 'white', 'black', 'black']
#colorTheme = ['lightgray', 'black', 'gray38', 'white']
#colorTheme = ['tan', 'saddlebrown', 'brown', 'saddlebrown']
#colorTheme = ['#1b1b1b', 'lightgray', 'gray', 'white']
#colorTheme = ['#1b1b1b', 'lightgray', '#Fc2AEC', 'white']
colorTheme = ['#1b1b1b', 'lightgray', 'red', 'white']

bgColor = colorTheme[0]
fgColor = colorTheme[1]
highlightColor = colorTheme[2]
cursorColor = colorTheme[3]

fonts = [('Courier', 6), ('Courier New', 2), ('Consolas', 1), ('Menlo', 2), ('Andale Mono', 2), ('Linux Libertine Mono O', 3)]
font, kerning = fonts[1]

windowWidth = 700
windowHeight = 800
font_size = 18
indent = 60

path = 'The Land That Time Forgot'

root = Tk()
root.title(str(path))
root.geometry(str(windowWidth) + 'x' + str(windowHeight))
canvas = Canvas(root, highlightthickness = 0, background = bgColor)
canvas.pack(fill = BOTH, expand = 1)

full_text = ''
if path != '':
    full_text = open("/Users/korysanchez/Documents/coding/Resources/" + str(path) + '.txt', 'r').read()
else:
    for i in range(12):
        page = requests.get("https://www.lipsum.com/feed/html")
        soup = BeautifulSoup(page.content, "html.parser")
        results = soup.find(id="lipsum").find_all("p")
        full_text = full_text + str(results[0])[4:-5]
        full_text = full_text + " "

spacing = font_size / 2 + kerning

text = [[]]
c = 0
ii = 0
chars_in_row = 0
newLine = False
allocate = False
active_row, active_col = 0, 0
if '`' in full_text:
    allocate = True
for i in range(len(full_text)):
    if full_text[i] == '\n':
        newLine = True
    if ii + spacing + 1 > windowWidth:
        text.append([])
        c = c + 1
        chars_in_row = ii / spacing
        ii = 0
    if ii == 0 and full_text[i] == ' ':
        ii = ii - spacing
    else:
        if newLine:
            text[c].append('~')
            ii = 0
            text.append([])
            c = c + 1
            newLine = False
        else:
            if allocate:
                if full_text[i] == '`':
                    allocate = False
                    active_row, active_col = len(text) - 1, len(text[c]) - 1
                else:
                    text[c].append([full_text[i], -1])
            else:
                text[c].append(full_text[i])
    ii = ii + spacing
windowWidth = int(chars_in_row * spacing + spacing / 2 )
root.geometry(str(windowWidth) + 'x' + str(windowHeight))
curr_row = 0
windowWidth = ii
canvas_texts = []
for i in range(len(text)):
    canvas_texts.append([])

def draw_row(height, row):
    global cursor
    x = spacing - 4 + indent
    for i in range(len(text[row])):
        if len(text[row][i]) > 1:
            color = highlightColor
            if text[row][i][0] == '~':
                color = bgColor
            canvas_text = canvas.create_text(x + i * spacing, height, text = text[row][i][0], font = (font, font_size), fill = color)
        else:
            color = fgColor
            if text[row][i] == '~':
                color = bgColor
            canvas_text = canvas.create_text(x + i * spacing, height, text = text[row][i], font = (font, font_size), fill = color)
        if row == active_row and i == active_col:
            root.unbind(canvas.itemcget(canvas_text - 1, 'text'))
            root.bind(canvas.itemcget(canvas_text, 'text'), lambda event, row = active_row, num = canvas_text: type_letter(event, row, num))

        canvas_texts[row].append(canvas_text)

def shift_row_down(row):
    for i in range(len(text[row])):
        c = canvas.coords(canvas_texts[row][i])
        canvas.coords(canvas_texts[row][i], c[0], c[1] + (spacing * 2 - 2))
def shift_row_up(row):
    for i in range(len(text[row])):
        c = canvas.coords(canvas_texts[row][i])
        canvas.coords(canvas_texts[row][i], c[0], c[1] - (spacing * 2 - 2))
def delete_row(row):
    for i in range(len(canvas_texts[row])):
        canvas.delete(canvas_texts[row][i])
    canvas_texts[row] = []

def scroll_down(event):
    global curr_row
    if shifting:
        if event.keysym == 'Down':
            for i in range(screen_row_count):
                delete_row(curr_row - screen_row_count + i)
            for i in range(screen_row_count):
                draw_row(i * (spacing * 2 - 2) + spacing, len(text) - screen_row_count + i)
        curr_row = len(text)
    elif curr_row < len(text):
        if canvas.itemcget(cursor, 'fill') == cursorColor:
            c = canvas.coords(cursor)
            canvas.coords(cursor, c[0], c[1] - (spacing * 2 - 2), c[2], c[3] - (spacing * 2 - 2))
            if canvas.coords(cursor)[3] <= 0:
                canvas.delete(cursor)
        delete_row(curr_row - screen_row_count)
        for i in range(curr_row - screen_row_count + 1, curr_row ):
            t = Thread(target=shift_row_up, args=[i])
            t.run()
        draw_row(int(windowHeight / (2*spacing - 2)) * (2*spacing - 2) - spacing, curr_row)
        curr_row = curr_row + 1
        canvas.update()
def scroll_up(event):
    global curr_row
    if shifting:
        if event.keysym == 'Up':
            for i in range(screen_row_count):
                delete_row(curr_row - screen_row_count + i)
            for i in range(screen_row_count):
                draw_row(i * (spacing * 2 - 2) + spacing, i)
        curr_row = screen_row_count
    elif curr_row > screen_row_count:
        if canvas.itemcget(cursor, 'fill') == cursorColor:
            c = canvas.coords(cursor)
            canvas.coords(cursor, c[0], c[1] + (spacing * 2 - 2), c[2], c[3] + (spacing * 2 - 2))
            if canvas.coords(cursor)[1] >= windowHeight:
                canvas.delete(cursor)
        delete_row(curr_row - 1)
        for i in range(curr_row - screen_row_count, curr_row - 1):
            t = Thread(target=shift_row_down, args=[i])
            t.run()
        draw_row(spacing, curr_row - screen_row_count - 1)
        curr_row = curr_row - 1
        canvas.update()

def page_down(event):
    global curr_row
    if curr_row + screen_row_count < len(text):
        canvas.delete(cursor)
        for i in range(screen_row_count):
            delete_row(curr_row - screen_row_count + i)
        for i in range(screen_row_count):
            draw_row(i * (spacing * 2 - 2) + spacing, curr_row - 1 + i)
        curr_row = int(curr_row + screen_row_count - 1)
def page_up(event):
    global curr_row
    if curr_row - (2 * screen_row_count) + 1 >= 0:
        canvas.delete(cursor)
        for i in range(screen_row_count):
            delete_row(curr_row - screen_row_count + i)
        for i in range(screen_row_count):
            draw_row(i * (spacing * 2 - 2) + spacing, curr_row - (2 * screen_row_count) + 1 + i)
        curr_row = int(curr_row - screen_row_count + 1)

shifting = False
def shift(event, cond):
    global shifting
    shifting = cond

def type_letter(event, row, num):
    global cursor, active_row, active_col
    num0 = canvas_texts[int(active_row)][int(active_col)]
    canvas.delete(cursor)
    if canvas.itemcget(num0, 'text') != '~':
        c = canvas.coords(num0)
        cursor = canvas.create_line(c[0]+spacing / 2, c[1] - spacing + 2, c[0]+spacing / 2, c[1] + spacing - 3 , fill = cursorColor, width = '1')
    else:
        c = canvas.coords(canvas_texts[(active_row + 1)][0])
        cursor = canvas.create_line(c[0]-spacing / 2, c[1] - spacing + 2, c[0]-spacing / 2, c[1] + spacing - 3 , fill = cursorColor, width = '1')
    if canvas.itemcget(num0, 'text') != '~':
        canvas.itemconfig(num0, fill = highlightColor)
        canvas.update()

    root.unbind('<' + str(event.keysym) + '>')

    text[(active_row)][active_col] = [text[(active_row)][active_col], -1]
    if active_col == len(canvas_texts[active_row]) - 1 or canvas.itemcget(num0, 'text') == '~':
        if len(canvas_texts[active_row - screen_row_count + 2]) != 0:
            page_down(None)
            canvas.delete(cursor)
            c = canvas.coords(canvas_texts[(active_row + 1)][0])
            cursor = canvas.create_line(c[0]-spacing / 2, c[1] - spacing + 2, c[0]-spacing / 2, c[1] + spacing - 3 , fill = cursorColor, width = '1')
        active_row = active_row + 1
        active_col = 0
        next = canvas_texts[active_row][active_col]
    else:
        active_col = active_col + 1
        next = canvas_texts[int(active_row)][int(active_col)]
    if canvas.itemcget(next, 'text') == " ":
        bind = 'space'
    elif canvas.itemcget(next, 'text') == '~':
        bind = "Return"
    elif canvas.itemcget(next, 'text') == '-':
        bind = 'minus'
    elif canvas.itemcget(next, 'text') == "’":
        bind = 'apostrophe'
    elif canvas.itemcget(next, 'text') == ',':
        bind = 'comma'
    else:
        bind = canvas.itemcget(next, 'text')
    root.bind('<' + str(bind) + '>', lambda event, row = active_row, num = next: type_letter(event, row, num))
def die(event):
    with open("/Users/korysanchez/Documents/coding/Resources/" + str(path) + '.txt', 'w') as f:
        for i in range(len(full_text)):
            letter = full_text[i]
            if letter == '~':
                letter = '\n'
            if letter == '`':
                letter = ''
            if (active_row + 1) * (active_col + 1) == i:
                print(active_row, active_col)
                f.write('`')
            f.write(letter)
    sys.exit()

y = spacing
screen_row_count = 0
while y + spacing < windowHeight:
    draw_row(y, curr_row)
    curr_row = curr_row + 1
    y = y + (2 * spacing - 2)
    screen_row_count = screen_row_count + 1

windowWidth = int(chars_in_row * spacing + spacing / 2  + 2 * indent)
windowHeight = int(screen_row_count * (2 * spacing - 2) + spacing / 2 - 2)
root.geometry(str(windowWidth) + 'x' + str(windowHeight))

cursor = canvas.create_line(0, 0, 0, 0, width = '1', fill = cursorColor)
quit_button = canvas.create_rectangle(0, 0, 10, 10, fill = highlightColor, outline = '')
canvas.tag_bind(quit_button, '<Button-1>', die)

#root.bind("<Shift-KeyPress>", lambda event, cond = True: shift(event, cond))
#root.bind("<KeyRelease>", lambda event, cond = False: shift(event, cond))
root.bind("<Down>", scroll_down)
root.bind("<Up>", scroll_up)
root.bind("<Left>", page_up)
root.bind("<Right>", page_down)
if '`' not in full_text:
    root.bind(canvas.itemcget(canvas_texts[0][0], 'text'), lambda event, row = active_row, num = canvas_texts[0][0]: type_letter(event, row, num))

root.mainloop()


def theme_toronto():
    """
    Applies a University of Toronto theme to all subsequential altair plot objects so they are displayed with the U of T visual identity.
    See the visual identity at https://tinyurl.com/t3jjr49
    Three palettes based on the U of T visual identity guidelines can be selected: 'cool', 'vibrant' and 'awards'.
    See more details about the package on GitHub: https://github.com/UBC-MDS/hueniversitypy/blob/master/README.md

    Returns
    -------
    altair plot : altair.vegalite.v4.api.Chart
    	an altair plot with the U of T visual identity colour theme applied.

    Example
    ----------
    >>> from hueniversitypy.theme_toronto import *
    >>> data = pandas.DataFrame({'X': numpy.random.randint(100, size=100),
                                'Y': numpy.random.randint(100, size=100),
                                'Cat': [['A', 'B', 'C'][numpy.random.randint(3, size=1)[0]] for i in range(100)]})
    >>> scatterplot = (altair.Chart(data).mark_circle(size=60, opacity=0.5).encode(x='X', y='Y', color='Cat'))
    >>> alt.themes.register('theme_toronto', theme_toronto)
    >>> alt.themes.enable('theme_toronto')
    >>> scatterplot
    """

    # Code attribution: Sergio Sanchez
    # https://towardsdatascience.com/consistently-beautiful-visualizations-with-altair-themes-c7f9f889602

    # note U of T fonts are not open source, so the most comparable font has been used for this package
    font = "Tahoma"
    labelFont = "Tahoma"

    # Specify colour palette for Toronto
    main_palette = ["#002A5C","#FFE498","#E31837","#008BB0","#DAE5CD",]

    return {
        "config": {
            # Title font and size
            "title": {
                "fontSize": 18,
                "font": font,
                "anchor": "start",
                "fontColor": "#000000"
            },
            # Axes font and sizes
            "axisX": {
                "labelFont": labelFont,
                "labelFontSize": 12,
                "titleFont": font,
                "titleFontSize": 12,
                "title": "X Axis Title (units)",
            },
            "axisY": {
                "labelFont": labelFont,
                "labelFontSize": 12,
                "titleFont": font,
                "titleFontSize": 12,
                "title": "Y Axis Title (units)",
            },
            # Add colour palette
            "range": {
                "category": main_palette,
            }
        }
    }


import io
import subprocess
import nltk
import sys
from finnpos.lib.bin import finnpos_ratna_feats as ratna

FINNPOS_FOLDER          = './finnpos/lib'
BIN_FOLDER              = '{0}/bin'.format(FINNPOS_FOLDER)
MODEL_FOLDER            = '{0}/share/finnpos/ftb_omorfi_model'.format(FINNPOS_FOLDER)
FREQ_WORDS              = '{0}/freq_words'.format(MODEL_FOLDER)
OMORFI_MODEL            = '{0}/ftb.omorfi.model'.format(MODEL_FOLDER)

FINNPOS_RATNA_FEATS     = '{0}/finnpos-ratna-feats.py'.format(BIN_FOLDER)
FINNPOS_LABEL           = '{0}/finnpos-label'.format(BIN_FOLDER)

POSTAG                  = '{0}/postag.py'.format(BIN_FOLDER)

def create_command():
    return 'echo "Samoin" | bash -c "python3 {ratna} {words}"'.format(# | "{label} {model}"'.format(#) | bash -c "{label} {model}'.format(
        ratna=FINNPOS_RATNA_FEATS,
        words=FREQ_WORDS
        #label=FINNPOS_LABEL,
        #model=OMORFI_MODEL
    )
    '''return 'bash -c "py {0}/test.py"'.format(
        FINNPOS_FOLDER
    )
    return 'echo Sanoin | py {0} {1} | {2} {3} | py {4}"'.format(
        FINNPOS_RATNA_FEATS,
        FREQ_WORDS,
        FINNPOS_LABEL,
        OMORFI_MODEL,
        POSTAG
    )'''

def bash_command(cmd, stdin=None, stdout=None):
    '''if stdin is not None and stdout is not None:
        return subprocess.Popen(['bash', '-c', cmd], stdin=stdin, stdout=stdout)
    elif stdin is not None:
        return subprocess.Popen(['bash', '-c', cmd], stdin=stdin)
    elif stdout is not None:
        return subprocess.Popen(['bash', '-c', cmd], stdout=stdout)
    else:'''
    return subprocess.Popen(['bash', '-c', 'bash -c "{cmd}"'.format(cmd=cmd)])#"python3 {0} {1}"'.format(FINNPOS_RATNA_FEATS, FREQ_WORDS)], shell=False)

def postag(token):

    print('Create ratnaProc')
    ratnaProc       = subprocess.Popen([
            'bash',
            '-c',
            'py {0} {1}'.format( FINNPOS_RATNA_FEATS, FREQ_WORDS ),
        ],
        stdin=subprocess.PIPE,
        stderr=sys.stderr,
        stdout=subprocess.PIPE
    )

    #ratnaOut        = ratnaProc.communicate()[0].decode('latin1')
    #print('ratnaOut', ratnaOut)

    print('Create labelProc')
    labelProc       = subprocess.check_output([
            'bash',
            '-c',
            'bash -c "{0} {1}"'.format( FINNPOS_LABEL, OMORFI_MODEL ),
        ],
        stdin=ratnaProc.stdout,
        stderr=sys.stderr
    )
    print('Write to the ratna')
    ratnaProc.stdin.write( bytes(token, 'latin1') )
    print('Wait for the ratna')
    ratnaProc.wait()
    print('Wait for the ratna done')
    #labelProc.stdin.write( bytes(ratnaOut, 'latin1'))
    #out = labelProc.communicate()

    print('Closing processes')
    #labelProc.stdin.close()

    #print('out', out)

    #print('ratnaComm', ratnaProc.communicate()[0].decode('latin1'))

    return

def test(tokens):

    with open(FREQ_WORDS, encoding='utf-8') as file:
        freq_words      = file.read().split('\n')

        stdin       = io.StringIO('\n'.join(tokens))

        print('Loading labelProc')
        labelProc   = subprocess.check_output([
            'bash',
            '-c',
            'bash -c "{0} {1}"'.format( FINNPOS_LABEL, OMORFI_MODEL )
        ], shell=True, stderr=sys.stderr)
        print('labelProc', labelProc)

        print('Pass tokens to the ratna')
        ratna.main('finnpos', 'STDIN', stdin, 'STDOUT', labelProc, sys.stderr, freq_words)

        print('Wait for labelProc')
        #labelProc.wait()
        #finnpos.finnpos_ratna_feats.main('finnpos', 'STDIN', sys.stdin, 'STDOUT', sys.stdout, sys.stderr, freq_words)
        #finnpos.finnpos_ratna_feats.main('finnpos-ratna-feats', "STDIN", stdin, "STDOUT", stdout, stderr, freq_words)

    '''

    if len(argv) != 2:
        stderr.write("cat data | %s freq_word_list\n" % argv[0])
        exit(1)

    freq_words = set(open(argv[1]).read().split('\n'))

    exit(main(argv[0], "STDIN", stdin, "STDOUT", stdout, stderr, freq_words))
    def main(pname, iname, ifile, oname, ofile, olog, freq_words):
    '''

def lemmatize(val):

    print('Lemmatizing data')

    #test(val)

    tokens              = nltk.word_tokenize(val)

    test(tokens)

    #print(postag(tokens[0]))
    #cmd                 = create_command()
    #print('Run', cmd)
    #bash_command(cmd)

    #print(postag(tokens[0]))
    #tags                = [postag(token) for token in tokens]

    #print(tags)

    #tokenized_input     = '\n'.join(tokens)

    #cmd                 = create_command('Sanoin')

    #print(cmd)

    #ps1                 = bash_command(cmd, stdin=subprocess.PIPE)
    #ps1.stdin.buffer.write('testaus')
    #print(ps1.communicate()[0])

    #ps1.stdin.write("tokens")

    #[ps1.stdin.writelines(token) for token in tokens]
    #ps1.stdin.write()

    #bash_command('a="Apples and oranges" && echo "${a/oranges/grapes}"')
    #subprocess.Popen('bash -c "ls"')

    #cmd         = 'bash -c "echo Sanoin | python3 ./lib/bin/finn-pos-ratna-feats.py"'
    #cmd          = 'ls ./finnpos/lib/bin/'
    #cmd             = 'bash -c "echo Sanoin | python3 ./lib/bin/finn-pos-ratna-feats.py ./lib/share/finnpos/ftb_omorfi_model/freq_words"'

    #ps = subprocess.Popen(cmd, shell=True)#, '"python3 ./finnpos-ratna-feats.py"'), stdout=subprocess.PIPE)
    #output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
    #ps.wait()

    #subprocess.Popen(['bash', '-c', 'python3', 'finnpos-ratna-feats.py'], stdin=tokenized_input, stdout=subprocess.PIPE)

    #bash -c "cat tokenized_input | python3 finnpos-ratna-feats.py ../share/finnpos/ftb_omorfi_model/freq_words | ./finnpos-label ../share/finnpos/ftb_omorfi_model/ftb.omorfi.model | python3 postag.py > tagged_input"

    #print(tokenized_input)


# C82_ROBOT
# Author: LOGAN NAIDOO (DEC 2021)

import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node

MY_NEO_ROBOT = os.environ['MY_ROBOT'] # Set the environment variable in bashrc
MY_NEO_ENVIRONMENT = os.environ['MY_ROBOT_ENVIRONMENT'] # Set the environment variable in bashrc

def generate_launch_description():
    use_sim_time = LaunchConfiguration('use_sim_time', default='true')
    map_dir = LaunchConfiguration(
        'map',
        default=os.path.join(
            get_package_share_directory('c82_robot'),
            'maps',
            MY_NEO_ENVIRONMENT+'.yaml'))

    param_file_name = 'navigation.yaml'
    param_dir = LaunchConfiguration(
        'params_file',
        default=os.path.join(
            get_package_share_directory('c82_robot'),
            'configs/',
            param_file_name))

    nav2_launch_file_dir = os.path.join(get_package_share_directory('nav2_bringup'), 'launch')

    return LaunchDescription([
        DeclareLaunchArgument(
            'map',
            default_value=map_dir,
            description='Full path to map file to load'),

        DeclareLaunchArgument(
            'params_file',
            default_value=param_dir,
            description='Full path to param file to load'),

        DeclareLaunchArgument(
            'use_sim_time',
            default_value='true',
            description='Use simulation (Gazebo) clock if true'),

        IncludeLaunchDescription(
            PythonLaunchDescriptionSource([nav2_launch_file_dir, '/bringup_launch.py']),
            launch_arguments={
                'map': map_dir,
                'use_sim_time': use_sim_time,
                'params_file': param_dir}.items(),
        )
    ])


"""Add host_switched field to game

Revision ID: 394a2bf76d9a
Revises: 29d69456e7ef
Create Date: 2021-01-09 12:11:21.868366

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '394a2bf76d9a'
down_revision = '29d69456e7ef'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('game', sa.Column('host_switched', sa.Boolean(), default=False, nullable=False))
    op.create_unique_constraint(None, 'gamelog', ['id'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'gamelog', type_='unique')
    op.drop_column('game', 'host_switched')
    # ### end Alembic commands ###


import random

# define a list of greetings
greetings = ["Hello", "Hi", "Hey", "Greetings", "Welcome"]

# define a list of questions the bot can answer
questions = ["What services do you offer?", "What is your address?", "Do you have any available appointments?", "What is the phone number for the hospital?"]

# define a list of possible responses to each question
services_responses = ["We offer a range of medical services including general consultations, surgery, radiology, and emergency care.", "Our hospital provides comprehensive medical services including diagnostic, treatment and surgical services."]
address_responses = ["Our hospital is located at shivaji Nagar Pune.", "Our address is Shivaji Nagar Pune.", "We are located at Shivaji Nagar Pune."]
appointment_responses = ["Yes, we have several available appointments over the next few days.", "I'm sorry, all of our appointments are currently booked.", "We have limited availability for appointments this week."]
doctor_responses = ["Dr. Piyush Rao", "Dr. Samidha Rao"]
phone_responses = ["You can reach our hospital at 555-1234.", "Our phone number is 555-5678.", "Please call us at 555-9012."]

# define a list of goodbye messages
goodbyes = ["Goodbye", "Thanks for chatting", "Take care", "Bye", "Have a nice day"]

# define a function to generate a response to a user's input
def generate_response(user_input):
    # check if the user input is a greeting
    for word in user_input.split():
        if word.lower() in greetings:
            return random.choice(greetings) + ", how can I assist you today?"

    # check if the user input is a question about services
    for word in user_input.split():
        if word.lower() in ["services", "service", "medical"]:
            return random.choice(services_responses)

    # check if the user input is a question about the hospital's address
    for word in user_input.split():
        if word.lower() in ["address", "location"]:
            return random.choice(address_responses)

    # check if the user input is a question about appointment availability
    for word in user_input.split():
        if word.lower() in ["appointments"]:
            return random.choice(appointment_responses)

    for word in user_input.split():
        if word.lower() in ["doctors", "available doctor"]:
            return random.choice(doctor_responses)

    # check if the user input is a question about the hospital's phone number
    for word in user_input.split():
        if word.lower() in ["phone", "number"]:
            return random.choice(phone_responses)

    # if the user input is none of the above, provide a default response
    return "I'm sorry, I don't understand. Can you please rephrase your question?"

# start the chatbot
print("Welcome to the hospital chatbot. How can I assist you today?")
while True:
    user_input = input("> ")
    if user_input.lower() in ["exit", "quit", "goodbye"]:
        print(random.choice(goodbyes))
        break
    else:
        response = generate_response(user_input)
        print(response)


from __future__ import annotations

import time
from typing import Optional

import jose
from fastapi import HTTPException, Request, Response, status
from fastapi.security import APIKeyCookie

from skyline_apiserver import schemas
from skyline_apiserver.config import CONF
from skyline_apiserver.core.security import generate_profile_by_token, parse_access_token
from skyline_apiserver.db import api as db_api
from skyline_apiserver.types import constants

class TokenCookie(APIKeyCookie):
    async def __call__(self, request: Request) -> str:
        api_key = request.cookies.get(self.model.name)
        if not api_key:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=constants.ERR_MSG_TOKEN_NOTFOUND,
            )
        return api_key

async def getJWTPayload(request: Request) -> Optional[str]:
    token = request.cookies.get(CONF.default.session_name)
    return token

async def get_profile(request: Request) -> schemas.Profile:
    payload = await TokenCookie(name=CONF.default.session_name)(request)
    try:
        await db_api.purge_revoked_token()
        token = parse_access_token(payload)
        is_revoked = await db_api.check_token(token.uuid)
        if is_revoked:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=constants.ERR_MSG_TOKEN_REVOKED,
            )
        profile = await generate_profile_by_token(token)
    except HTTPException as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=e.detail,
        )
    except jose.exceptions.ExpiredSignatureError as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=constants.ERR_MSG_TOKEN_EXPIRED + " : " + str(e),
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=str(e),
        )
    return profile

async def get_profile_update_jwt(request: Request, response: Response) -> schemas.Profile:
    profile = await get_profile(request)

    if 0 < profile.exp - time.time() < CONF.default.access_token_renew:
        profile.exp = int(time.time()) + CONF.default.access_token_expire
        response.set_cookie(CONF.default.session_name, profile.toJWTPayload())
        response.set_cookie(constants.TIME_EXPIRED_KEY, str(profile.exp))
    return profile


'''
Chord module
July 6, 2020
By Robin Nash

This module contains a Chord class, Instrument class, note functions, and musical and chord data.

The Chord class holds a name of a chord and has functions to return the notes that make up the chord,
how to play the chord on different instruments, and more.
The Instrument class holds data on an instrument.
This module contains information on musical instruments.

Definitions
Simplified form: can be sharp or flat; each section is of the proper dictionary form
Sharp form: simplified form and tonic is always expressed as a sharp
Flat form: simplified form and tonic is always expressed as a flat
'''

class Chord:
    '''
    Holds the data for a chord.
    Finds the notes and qualities that make up a chord based on its name.
    Can transpose the chord by any number of half steps.
    Can map the fingering for a chord on ukulele, guitar, or banjo.
    Currently supports chords of type major, minor, sus, sus2, aug, dim, and
    a maj7, dom7, or maj6 can be added to any to add an extra interval.
    '''

    def __init__(self,chordName):
        self.originalName = chordName
        self.name = chordName
        self.qualities = []
        self.tonic = ""
        # Simplifys chord name and sets chord qualities
        self.setNameAndQual()

    def __repr__(self):
        return self.name

    def setNameAndQual(self, flat = True):
        '''Helper function to set chord name in simplified form and set chord qualities'''
        name = self.name

        # Get valid tonic
        parts = [name[0].upper()]
        name = name[1:]
        last = None

        # Checks for extra (fourth) intervals (ex. Maj7)
        for extra in extraInts:
            for crappy in [q for q in extraInts[extra] if len(q)<=len(name)]:
                # Replaces the end of the name if it ends with the extraInt
                if name[-len(crappy):] == crappy:
                    name = name[:-len(crappy)]
                    last = extra
                    break

        # Checks for flat or sharp
        for crappy in [q for q in accidentals['b'] if len(q)<=len(name)]:
            if crappy == name[:len(crappy)]:
                name = name[len(crappy):]
                parts[0]+='b'
                break
        for crappy in [q for q in accidentals['#'] if len(q)<=len(name)]:
            if crappy == name[:len(crappy)]:
                name = name[len(crappy):]
                parts[0]+='#'
                break

        # Fixes potentially strange enharmonic equivalents of tonic (ex Cb -> B)
        parts[0] = validify(parts[0])

        # Checks for the main chord quality
        for qual in qualities:
            for crappy in qualities[qual]:
                if crappy == name:
                    parts.append(qual)
                    name = ''
                    break
            # in case of 'aug' or something, it will be an empty string then it will think there's also a Major
            if len(parts) == 2:
                break

        # add fourth to list
        if last:
            parts.append(last)

        # make sure name string is empty
        if name!= "" or parts[0][0] not in "ABCDEFG":
            raise ValueError ('Invalid Chord Name:', self.name)

        # Set the variables
        self.name = "".join(parts)
        self.tonic = parts.pop(0)
        self.qualities = parts

    def getName(self, flat = True):
        '''Returns the name of the chord'''
        name = self.name
        if self.tonic.endswith("#") and flat:
            name = flatten(self.tonic) + name[2:]

        if self.tonic.endswith("b") and not flat:
            name = sharpen(self.tonic) + name[2:]

        return name

    def getIntervals(self):
        '''Converts the qualities into intervals. Intergers represent # of half steps from tonic'''
        intervals = ()
        for qual in self.qualities:
            intervals += qualityIntervals[qual]
        return intervals

    def getNotes(self, flat = True):
        '''Returns the notes the chord is made of'''

        # Picks flats or sharps list depending on tonic and flat argument
        tonic = flatten(self.tonic) if flat else sharpen(self.tonic)
        if len(self.tonic) == 1:
            notes = flats if flat else sharps
        else:
            notes = flats if isFlat(tonic) else sharps

        chordNotes = [tonic]
        start = notes.index(tonic)
        for interval in self.getIntervals():
            chordNotes.append(notes[(start+interval)%len(notes)])
        return chordNotes

    def getTabs(self, instrument, tab = [], tabs = []):
        '''Returns many fingerings for the chord on a given instrument'''
        notes = self.getNotes(flat = False)

        # List of lists that each hold where the first occurance of all notes in the chord is played on each string
        stringTabs = [sorted([instrument.notes[note][string] for note in notes]) for string in range(instrument.strings)]

        # Makes every combo of tabs for chord (does not ensure all notes are being played)
        if len(tab) < instrument.strings:
            for i in range(len(notes)):
                self.getTabs(instrument, tab[:]+[stringTabs[len(tab)][i]], tabs)

        # Adds the tab if it contains all notes and fingering is close enough together
        else:
            # accomodate banjo
            if instrument.name == 'banjo':
                if [] not in [[tab[i] for i in range(len(tab)) if tab[i]==instrument.notes[note][i]] for note in notes if note!="G"] and greatestDistance(tab) <= instrument.fingerDistance:
                    tab.append(0 if 'G' in notes else 'x')
                    tabs.append(tab[:])
            else:
                if [] not in [[tab[i] for i in range(len(tab)) if tab[i]==instrument.notes[note][i]] for note in notes] and greatestDistance(tab) <= instrument.fingerDistance:
                    tabs.append(tab[:])

        return tabs

    def getTransposed(self, halfSteps):
        '''Returns a transposed chord object transposed by halfSteps half steps'''
        notes = flats if isFlat(self.tonic) else sharps
        tonic = notes[(notes.index(self.tonic) + halfSteps)%len(notes)]
        return Chord("".join([tonic] +self.qualities))

    def isSharp(self):
        '''Returns if the tonic is not flat'''
        return isSharp(self.tonic)

    def isFlat(self):
        '''Returns if the tonic is not sharp'''
        return isFlat(self.tonic)

#### Instrument Class #######################################################################
class Instrument:
    def __init__(self, name, tuning, fingerDistance = 4):
        self.name = name
        self.fingerDistance = fingerDistance
        #Tuning should be first string up (ex for guitar: ["E","B","G","D","A","E"])
        self.tuning = tuning
        self.strings = len(tuning)
        # Tuple of first occurance of each note on each string as sharps
        self.notes = {note : tuple(getDistance(sharps, sharpen(n), note) for n in tuning) for note in sharps}
        if name == 'banjo':
            for note in self.notes:
                self.notes[note] = self.notes[note][:-1] + ((0,) if note == "G" else (self.notes[note][-1]+5,))

# modified for 5th string
class Banjo(Instrument):
    def __init__(self, fingerDistance = 4):
        super().__init__("banjo", ["D","B","G","D","G"], fingerDistance = 4)
        self.strings = 4 # not true, but we want to mostly ignore the last string
        self.notes_full = {}
        for note in self.notes:
            self.notes_full[note] = self.notes[note][:-1] + ((0,) if note == "G" else (self.notes[note][-1]+5,))
            self.notes[note] = self.notes[note][:-1]

#### Note functions #####################################################################################

def validify(note):
    '''Fixes strange enharmonic equivalents. For example turns a note like Cb into B.
    However if note is invalid like "H#", it will return the original note "H#"'''
    bad = ['B#','E#','Cb','Fb']
    good = ['C','F','B','E']
    if note in bad:
        note = good[bad.index(note)]
    return note

def isSharp(note):
    '''Returns Boolean variable for if a given note name is sharp'''
    return True if (note+" ")[1] == "#" else False

def isFlat(note):
    '''Returns Boolean variable for if a given note name is flat'''
    return True if (note+" ")[1] == "b" else False

def sharpen(note):
    '''Returns sharp equivilent of a note, note must be inputted in simplified form'''
    if note in flats:
        note = sharps[flats.index(note)]
    return note

def flatten(note):
    '''Returns flat equivilent of a note, note must be inputted in simplified form'''
    if note in sharps:
        note = flats[sharps.index(note)]
    return note

def getDistance(s, a, b):
    '''Returns the round-about distance between 2 items in a list'''
    A = s.index(a)
    B = s.index(b)
    if A<=B:
        return B-A
    else:
        return len(s)-(A-B)

def greatestDistance(tab):
    '''Returns the greatest distance between 2 intergers in a list of intergers (expect 0 because open string)'''
    return max([i for i in tab if i != 0]) - min([i for i in tab if i != 0])

def getIntName(halfSteps):
    '''Returns the name of an interval given the number of half steps from the tonic'''
    return intervalNames[halfSteps%len(intervalNames)]

def isValid(chordName):
    '''Returns if a given chord name is valid to create a chord object'''
    try:
        chord = Chord(chordName)
        return True
    except ValueError:
        return False

#### Music and Chord Data ####################################################################

# dictionaries for crappy parts
accidentals = {'#':['#','sharp'],'b':['flat','f','b','♭']}#,'s'
qualities = {'dim':['dim','-','diminished'],'aug':['aug','augmented','+'],'sus2':['Sus2','sus2'],'sus':['Sus4','sus4','sus','Sus'],'':['M','Maj','maj','major',''],'m':['minor','min','m']}
extraInts = {'Maj7':['Maj7','maj7','major7'],'7':['7','dom7','7th'],'6':['6','maj6','Maj6']}
parts = [extraInts, qualities]

# List of intervals from tonic in semitones that are associated with each chord quality
qualityIntervals = {'m': (3, 7), 'dim': (3, 6), 'aug': (4, 8), 'sus': (5, 7), 'sus2': (2, 7), '': (4, 7),   'Maj7': (11,), '7': (10,), '6': (9,)}

intervalNames = ['P1','m2','M2','m3','M3','P4','Tri','P5','m6','M6','m7','M7','P8']

sharps= ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flats = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']

############## Instrument Data ##############################################

# Ukulele
ukuleleNotes = {'C':(3,8,0,5), 'C#':(4,9,1,6), 'D':(5,10,2,7), 'D#':(6,11,3,8), 'E':(7,0,4,9), 'F':(8,1,5,10), 'F#':(9,2,6,11), 'G':(10,3,7,0), 'G#':(11,4,8,1), 'A':(0,5,9,2), 'A#':(1,6,10,3), 'B':(2,7,11,4)}
ukuStrings = [[sharps[i%12] for i in range(i,19+i)] for i in [9,4,0,7]]
ukulele_ = {'name':'ukulele','notes':ukuleleNotes,'fingerDistance':4 ,'strings':4}
ukulele = Instrument("ukulele", ["A","E","C","G"], 4)

# Banjo
banjoNotes = {'C':(10,10,5,1,10), 'C#':(11,11,6,2,11), 'D':(12,0,7,3,0), 'D#':(13,1,8,4,1), 'E':(14,2,9,5,2), 'F':(15,3,10,6,3), 'F#':(16,4,11,7,4), 'G':(0,5,0,8,5), 'G#':(6,6,1,9,6), 'A':(7,7,2,10,7), 'A#':(8,8,3,11,8), 'B':(9,9,4,0,9)}
banjoStrings = [['G' for i in range(6)]+[sharps[i%12] for i in range(8,25)]]+[[sharps[i%12] for i in range(i,23+i)] for i in [sharps.index(note) for note in ('D','G','B','D')]]
banjo_ = {'name':'banjo','notes':banjoNotes,'fingerDistance':3 ,'strings':5}
##banjo = Instrument("banjo", ["D","B","G","D","G"])# last string is G but the string starts up 5 semitones
banjo = Banjo()

# Guitar
guitarStrings = [[sharps[i%12] for i in range(ii,19+ii)] for ii in [sharps.index(note) for note in 'EBGDAE']]
guitarNotes = {note:tuple([guitarStrings[x].index(note) for x in range(6)]) for note in sharps}
guitar_ = {'name':'guitar','notes':guitarNotes, 'fingerDistance':2 ,'strings':6}
guitar = Instrument("guitar", ["E","B","G","D","A","E"], 2)

instruments = {'ukulele':ukulele, 'banjo':banjo, 'guitar':guitar}

# Tests #
if __name__ == "__main__":
    print(banjo.notes)
    for c in ["C","A","A7","Am7"]:
        c= Chord(c)
        print(c)
        print(c.getTabs(banjo,[],[]))

    # mini test app
    flat = False
    while True:
        c = input("Enter chord name: ")
        if c in ['f','s']:
            flat = c == 'f'
            continue
        c = Chord(c)
        print(c.getNotes(flat))#
        print(c.getName(flat))
##        print(c.getNotes(True))


import re

target = 'hello'

reg = re.compile(r'hel(%s)o' % '.')
result = reg.search(target)

print(result)
# => <re.Match object; span=(0, 5), match='hello'>

print(result.groups()[0])
# => l


import numpy as np
import matplotlib.pyplot as plt
import time
from ancillary import FP_NR
from plotting import set_styles
import timeit

def equilibrium1(T, Z, Tc, psi, k):
    """Simple equilibrium temperature equation, copied from lecture files"""
    return psi*Tc - (0.684 - 0.0416 * np.log(T/(1e4 * Z*Z)))*T

def equilibrium2(T, Z, Tc, psi, nH, A, xi, k, aB):
    """More realistic equilibrium temperature equation, copied from lecture files"""
    return (psi*Tc - (0.684 - 0.0416 * np.log(T/(1e4 * Z*Z)))*T - .54 * ( T/1e4 )**.37 * T)*k*nH*aB + A*xi + 8.9e-26 * (T/1e4)

def full_run():
    ## Variables
    aB = 2e-13 # cm^3 s^-1
    k= 1.38e-16 # erg/K
    psi = 0.929 #
    Tc = 1e4 # K
    Z = 0.015 #
    A = 5e-10 # erg
    xi = 1e-15 # s^-1

    # Bracketing Params.
    Tmin = 1
    Tmax1 = 1e7
    Tmax2 = 1e15
    rootfinder = FP_NR
    ####
    set_styles()

    # 2a
    equilibrium1_func = lambda x: equilibrium1(x, Z, Tc, psi, k)
    t0 = time.time()
    root, num_iter = rootfinder(equilibrium1_func, [Tmin, Tmax1], target_x_acc=0.1, target_y_acc=1e-15)
    t1 = time.time()
    y_root = equilibrium1_func(root)
    print(f'Root found for equation 1 using FP_NR:\nT={root:.2E}K (f(T)={y_root:.8E}\nNum Iter: {num_iter}, time:{t1-t0:.2E}s\n')

    # Plot the function
    x = np.linspace(Tmin, Tmax1, 1000)
    y = equilibrium1_func(x)
    plt.plot(x, y, label='Equilibrium Function')
    plt.axhline(y=0, c='black', ls='--', alpha=0.8)

    plt.scatter([Tmin, Tmax1], [equilibrium1_func(Tmin), equilibrium1_func(Tmax1)], c='red', label='Starting Points', marker='X')
    plt.scatter(root, y_root, c='green', label=f'Root T={root:.2E}K (f(T)={y_root:.2E})', marker='X')

    plt.xlabel(r'$^{10}\log~T$')
    plt.ylabel(r'$\propto\,\Gamma_{pe}~-~\Lambda_{rr}$')
    plt.title('Simple HII Region Equilibrium')

    plt.xlim(Tmin, Tmax1)
    plt.xscale('log')
    plt.legend()
    plt.savefig('results/simple_hiiregion_roots.png', bbox_inches='tight')
    plt.clf()

    #2b
    table_txt = ""
    for i, n_power in enumerate([-4, 0, 4]):
        n = 10**(n_power)
        equilibrium2_func = lambda x: equilibrium2(x, Z, Tc, psi, n, A, xi, k, aB)
        t0 = time.time()
        root, num_iter = rootfinder(equilibrium2_func, [Tmin, Tmax2], target_y_acc=1e-10, target_x_acc=1e-10)
        t1 = time.time()
        y_root = equilibrium2_func(root)

        x = np.logspace(np.log10(Tmin), np.log10(Tmax2), 5000)
        y = equilibrium2_func(x)

        plt.plot(x, np.abs(y), c=f'C{i}',   label=rf'$n$ = {n:.0E} cm$^{-3}$')
        plt.scatter(root, np.abs(y_root), label=f'T={root:.2E}', c=f'C{i}', marker='X', zorder=0)
        table_txt += rf"$10^{{{n_power}}}$ & {root:.2E} & {y_root:.2E} & {num_iter} & {t1-t0:.2}\\" +'\n'
        print(f'Root found for equation 2, n=10^{n_power} using FP_NR:\nT={root:.2E}K (f(T)={y_root:.8E}\nNum Iter: {num_iter}, time:{t1-t0:.2E}s\n')
    plt.xlabel(r'$^{10}\log~T$')
    plt.ylabel(r'$\propto\,^{10}\log|\Gamma~-~\Lambda$|')
    plt.title('Complex HII Region Equilibrium')

    plt.xlim(Tmin, Tmax2)
    plt.xscale('log')
    plt.yscale('log')
    plt.legend()
    plt.savefig('results/complex_hiiregion_roots.png', bbox_inches='tight')

    table_txt = table_txt[:-4] # remove the last \\\n
    with open('results/complex_hiiregion_table.txt', 'w') as file:
        file.write(table_txt)

def main():
    full_run()

if __name__ == '__main__':
    main()


import os
import pickle
import random

from faker import Faker
from sqlalchemy.sql.expression import func

from app import app
from models.guest import GuestModel
from models.participant import ParticipantModel

app.app_context().push()

from models.event import EventModel

fake = Faker()
client = app.test_client()

def generate_events(num=1000):
    for _ in range(num):
        end_datetime = fake.date_time_between('-1M', '+1M')
        event = EventModel(
            name=fake.sentence(),
            start=fake.date_time_between('-1M', end_datetime),
            end=end_datetime,
            description=fake.text(512)
        )

        for participant in ParticipantModel.query.order_by(func.random()) \
                .limit(random.randint(1, 3)):
            event.participants.append(participant)

        for guest in GuestModel.query.order_by(func.random()) \
                .limit(random.randint(1, 20)):
            event.guests.append(guest)

        event.save_to_db()

def load_participants(path=os.path.join('data', 'authors.pickle')):
    with open(path, 'rb') as file:
        participants = pickle.load(file)

    for name in participants:
        participant = ParticipantModel(name=name)
        participant.save_to_db()

def generate_guests(num=100):
    for _ in range(num):
        guest = GuestModel(name=fake.name())
        guest.save_to_db()

if __name__ == '__main__':
    load_participants()
    generate_guests()
    generate_events()


import random

bag = ['S', 'L', 'Z', 'O', 'T', 'I', 'J']
first=True

def get_next_shape(seed):
    random.seed(seed)
    global bag, first
    if first:
        random.shuffle(bag)
        first = False
    while True:
        if bag == []:
            bag = ['S', 'L', 'Z', 'O', 'T', 'I', 'J']
            random.shuffle(bag)
            yield bag.pop()
        else:
            yield bag.pop()


def SortedListInsrt(l,x):
    newList=[]
    inserted = False
    for z in l:
        if not inserted:
            if x<z:
                newList+=[x]
                inserted=True
        newList+=[z]

    if not inserted:
        newList+=[x]
    return(newList)

s=[15, 21, 22, 25, 29, 31, 34, 35, 41, 44, 45, 46, 47, 48, 53, 54, 57, 59, 64, 67, 68, 69, 71, 72, 81]

w=SortedListInsrt(s,39)

print(w)


# Import libraries
import os
import sys
import time
import math
import random
import numpy as np
from PIL import Image
import tensorflow as tf
#from libtiff import TIFF
import skimage.morphology
from osgeo import ogr, gdal
from scipy import ndimage
#import tifffile
import matplotlib.pyplot as plt
from skimage.filters import rank
from sklearn.utils import shuffle
from skimage.morphology import disk
from skimage.transform import resize
import tensorflow.keras.backend as K
from tensorflow.keras.layers import *
from contextlib import redirect_stdout
from sklearn.metrics import confusion_matrix
from skimage.util.shape import view_as_windows
from sklearn.metrics import average_precision_score
from tensorflow.keras.optimizers import Adam, SGD, RMSprop
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from tensorflow.keras.models import Model, load_model, Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#from tensorflow.keras.applications.vgg16 import preprocess_input
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau

#import os
#os.environ["CUDA_VISIBLE_DEVICES"]=""

#physical_devices = tf.config.experimental.list_physical_devices('GPU')
#tf.config.experimental.set_memory_growth(physical_devices[0], True)
gpu_devices = tf.config.experimental.list_physical_devices('GPU')
for device in gpu_devices: tf.config.experimental.set_memory_growth(device, True)

# Functions
def load_optical_image(patch):
    # Read tiff Image
    print (patch)
    gdal_header = gdal.Open(patch)
    img = gdal_header.ReadAsArray()
    #img_tif = TIFF.open(patch)
    #img = img_tif.read_image()
    img = np.transpose(img.copy(), (1, 2, 0))
    print('Image shape :', img.shape)
    return img

def load_SAR_image(patch):
    #Function to read SAR images
    print (patch)
    gdal_header = gdal.Open(patch)
    db_img = gdal_header.ReadAsArray()
    #img_tif = TIFF.open(patch)
    #db_img = img_tif.read_image()
    #db_img = np.transpose(db_img, (1, 2, 0))
    temp_db_img = 10**(db_img/10)
    temp_db_img[temp_db_img>1] = 1
    return temp_db_img

def load_tiff_image(patch):
    # Read tiff Image
    print (patch)
    gdal_header = gdal.Open(patch)
    img = gdal_header.ReadAsArray()
    return img

def filter_outliers(img, bins=1000000, bth=0.001, uth=0.999, mask=[0]):
    img[np.isnan(img)]=0 # Filter NaN values.
    if len(mask)==1:
        mask = np.zeros((img.shape[:2]), dtype='int64')
    for band in range(img.shape[-1]):
        hist = np.histogram(img[:mask.shape[0], :mask.shape[1]][mask!=2, band].ravel(),bins=bins) # select not testing pixels
        cum_hist = np.cumsum(hist[0])/hist[0].sum()
        max_value = np.ceil(100*hist[1][len(cum_hist[cum_hist<uth])])/100
        min_value = np.ceil(100*hist[1][len(cum_hist[cum_hist<bth])])/100
        img[:,:, band][img[:,:, band]>max_value] = max_value
        img[:,:, band][img[:,:, band]<min_value] = min_value
    return img

def create_mask(size_rows, size_cols, grid_size=(6,3)):
    num_tiles_rows = size_rows//grid_size[0]
    num_tiles_cols = size_cols//grid_size[1]
    print('Tiles size: ', num_tiles_rows, num_tiles_cols)
    patch = np.ones((num_tiles_rows, num_tiles_cols))
    mask = np.zeros((num_tiles_rows*grid_size[0], num_tiles_cols*grid_size[1]),
        dtype=np.uint8)
    count = 0
    for i in range(grid_size[0]):
        for j in range(grid_size[1]):
            count = count+1
            mask[num_tiles_rows*i:(num_tiles_rows*i+num_tiles_rows), num_tiles_cols*j:(num_tiles_cols*j+num_tiles_cols)] = patch*count
    #plt.imshow(mask)
    print('Mask size: ', mask.shape)
    return mask

def create_idx_image(ref_mask):
    im_idx = np.arange(ref_mask.shape[0] * ref_mask.shape[1]).reshape(ref_mask.shape[0] , ref_mask.shape[1])
    return im_idx

def extract_patches(im_idx, patch_size, overlap):
    '''overlap range: 0 - 1 '''
    row_steps, cols_steps = int((1-overlap) * patch_size[0]), int((1-overlap) * patch_size[1])
    patches = skimage.util.view_as_windows(im_idx, patch_size, step=(row_steps, cols_steps))
    return patches

def retrieve_idx_percentage(reference, patches_idx_set, patch_size, pertentage = 5):
    count = 0
    new_idx_patches = []
    reference_vec = reference.reshape(reference.shape[0]*reference.shape[1])
    for patchs_idx in patches_idx_set:
        patch_ref = reference_vec[patchs_idx]
        class1 = patch_ref[patch_ref==1]
        if len(class1) >= int((patch_size**2)*(pertentage/100)):
            count = count + 1
            new_idx_patches.append(patchs_idx)
    return np.asarray(new_idx_patches)

def extract_patches_mask_indices(input_image, patch_size, stride):
    h, w = input_image.shape
    image_indices = np.arange(h*w).reshape(h,w)
    window_shape = patch_size
    window_shape_array = (window_shape, window_shape)
    patches_array = np.array(view_as_windows(image_indices, window_shape_array, step = stride))
    num_row,num_col,row,col = patches_array.shape
    patches_array = patches_array.reshape(num_row*num_col,row,col)
    return patches_array

def normalization(image, norm_type = 1):
    image_reshaped = image.reshape((image.shape[0]*image.shape[1]),image.shape[2])
    if (norm_type == 1):
        scaler = StandardScaler()
    if (norm_type == 2):
        scaler = MinMaxScaler(feature_range=(0,1))
    if (norm_type == 3):
        scaler = MinMaxScaler(feature_range=(-1,1))
    scaler = scaler.fit(image_reshaped)
    image_normalized = scaler.fit_transform(image_reshaped)
    image_normalized1 = image_normalized.reshape(image.shape[0],image.shape[1],image.shape[2])
    return image_normalized1

def get_patches_batch(image, rows, cols, radio, batch):
    temp = []
    for i in range(0, batch):
        batch_patches = image[rows[i]-radio:rows[i]+radio+1, cols[i]-radio:cols[i]+radio+1, :]
        temp.append(batch_patches)
    patches = np.asarray(temp)
    return patches

def pred_recostruction(patch_size, pred_labels, image_ref):
    # Reconstruction
    stride = patch_size
    h, w = image_ref.shape
    num_patches_h = int(h/stride)
    num_patches_w = int(w/stride)
    count = 0
    img_reconstructed = np.zeros((num_patches_h*stride,num_patches_w*stride))
    for i in range(0,num_patches_w):
        for j in range(0,num_patches_h):
            img_reconstructed[stride*j:stride*(j+1),stride*i:stride*(i+1)]=pred_labels[count]
            #img_reconstructed[32*i:32*(i+1),32*j:32*(j+1)]=p_labels[count]
            count+=1
    return img_reconstructed

def mask_no_considered(image_ref, past_ref, buffer):
    # Creation of buffer for pixel no considered
    image_ref_ = image_ref.copy()
    im_dilate = skimage.morphology.dilation(image_ref_, disk(buffer))
    im_erosion = skimage.morphology.erosion(image_ref_, disk(buffer))
    inner_buffer = image_ref_ - im_erosion
    inner_buffer[inner_buffer == 1] = 2
    outer_buffer = im_dilate-image_ref_
    outer_buffer[outer_buffer == 1] = 2

    # 1 deforestation, 2 unknown
    image_ref_[outer_buffer + inner_buffer == 2 ] = 2
    #image_ref_[outer_buffer == 2 ] = 2
    image_ref_[past_ref == 1] = 2
    return image_ref_

def matrics_AA_recall(thresholds_, prob_map, ref_reconstructed, mask_amazon_ts_, px_area):
    thresholds = thresholds_
    metrics_all = []

    for thr in thresholds:
        print(thr)

        img_reconstructed = np.zeros_like(prob_map).astype(np.int8)
        img_reconstructed[prob_map >= thr] = 1

        mask_areas_pred = np.ones_like(ref_reconstructed)
        area = skimage.morphology.area_opening(img_reconstructed, area_threshold = px_area, connectivity=1)
        area_no_consider = img_reconstructed-area
        mask_areas_pred[area_no_consider==1] = 0

        # Mask areas no considered reference
        mask_borders = np.ones_like(img_reconstructed)
        #ref_no_consid = np.zeros((ref_reconstructed.shape))
        mask_borders[ref_reconstructed==2] = 0
        #mask_borders[ref_reconstructed==-1] = 0

        mask_no_consider = mask_areas_pred * mask_borders
        ref_consider = mask_no_consider * ref_reconstructed
        pred_consider = mask_no_consider*img_reconstructed

        ref_final = ref_consider[mask_amazon_ts_==1]
        pre_final = pred_consider[mask_amazon_ts_==1]

        # Metrics
        cm = confusion_matrix(ref_final, pre_final)
        #TN = cm[0,0]
        FN = cm[1,0]
        TP = cm[1,1]
        FP = cm[0,1]
        precision_ = TP/(TP+FP)
        recall_ = TP/(TP+FN)
        mm = np.hstack((recall_, precision_))
        metrics_all.append(mm)
    metrics_ = np.asarray(metrics_all)
    return metrics_

def resnet_block(x, n_filter, ind):
    x_init = x

    ## Conv 1
    x = Conv2D(n_filter, (3, 3), activation='relu', padding="same", name = 'res1_net'+str(ind))(x)
    x = Dropout(0.5, name = 'drop_net'+str(ind))(x)
    ## Conv 2
    x = Conv2D(n_filter, (3, 3), activation='relu', padding="same", name = 'res2_net'+str(ind))(x)

    ## Shortcut
    s  = Conv2D(n_filter, (1, 1), activation='relu', padding="same", name = 'res3_net'+str(ind))(x_init)

    ## Add
    x = Add()([x, s])
    return x

def resnet_block_dropout(x, n_filter, ind):
    x_init = x

    ## Conv 1
    x = Conv2D(n_filter, (3, 3), activation='relu', padding="same", name = 'res1_net'+str(ind))(x)
    x = Dropout(0.5, name = 'drop_net'+str(ind))(x, training=True)
    ## Conv 2
    x = Conv2D(n_filter, (3, 3), activation='relu', padding="same", name = 'res2_net'+str(ind))(x)

    ## Shortcut
    s  = Conv2D(n_filter, (1, 1), activation='relu', padding="same", name = 'res3_net'+str(ind))(x_init)

    ## Add
    x = Add()([x, s])
    return x

def resnet_block_spatial_dropout(x, n_filter, dropout_seed, ind, training=True):
    x_init = x

    ## Conv 1
    x = Conv2D(n_filter, (3, 3), activation='relu', padding="same", name = 'res1_net'+str(ind))(x)
    # x = Dropout(0.5, name = 'drop_net'+str(ind))(x, training = True)
    x = SpatialDropout2D(0.25, name = 'drop_net'+str(ind), seed = dropout_seed)(x, training = training)

    ## Conv 2
    x = Conv2D(n_filter, (3, 3), activation='relu', padding="same", name = 'res2_net'+str(ind))(x)

    ## Shortcut
    s  = Conv2D(n_filter, (1, 1), activation='relu', padding="same", name = 'res3_net'+str(ind))(x_init)

    ## Add
    x = Add()([x, s])
    return x
# Residual U-Net model
def build_resunet(input_shape, nb_filters, n_classes, last_activation='softmax'):
    '''Base network to be shared (eq. to feature extraction)'''
    input_layer= Input(shape = input_shape, name="input_enc_net")

    res_block1 = resnet_block(input_layer, nb_filters[0], 1)
    pool1 = MaxPool2D((2 , 2), name='pool_net1')(res_block1)

    res_block2 = resnet_block(pool1, nb_filters[1], 2)
    pool2 = MaxPool2D((2 , 2), name='pool_net2')(res_block2)

    res_block3 = resnet_block(pool2, nb_filters[2], 3)
    pool3 = MaxPool2D((2 , 2), name='pool_net3')(res_block3)

    res_block4 = resnet_block(pool3, nb_filters[2], 4)

    res_block5 = resnet_block(res_block4, nb_filters[2], 5)

    res_block6 = resnet_block(res_block5, nb_filters[2], 6)

    upsample3 = Conv2D(nb_filters[2], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net3')(UpSampling2D(size = (2,2))(res_block6))

    merged3 = concatenate([res_block3, upsample3], name='concatenate3')

    upsample2 = Conv2D(nb_filters[1], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net2')(UpSampling2D(size = (2,2))(merged3))

    merged2 = concatenate([res_block2, upsample2], name='concatenate2')

    upsample1 = Conv2D(nb_filters[0], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net1')(UpSampling2D(size = (2,2))(merged2))
    merged1 = concatenate([res_block1, upsample1], name='concatenate1')

    output = Conv2D(n_classes,(1,1), activation = last_activation, padding = 'same', name = 'output')(merged1)

    return Model(input_layer, output)

def build_resunet_dropout(input_shape, nb_filters, n_classes):
    '''Base network to be shared (eq. to feature extraction)'''
    input_layer= Input(shape = input_shape, name="input_enc_net")

    res_block1 = resnet_block_dropout(input_layer, nb_filters[0], 1)
    pool1 = MaxPool2D((2 , 2), name='pool_net1')(res_block1)

    res_block2 = resnet_block_dropout(pool1, nb_filters[1], 2)
    pool2 = MaxPool2D((2 , 2), name='pool_net2')(res_block2)

    res_block3 = resnet_block_dropout(pool2, nb_filters[2], 3)
    pool3 = MaxPool2D((2 , 2), name='pool_net3')(res_block3)

    res_block4 = resnet_block_dropout(pool3, nb_filters[2], 4)

    res_block5 = resnet_block_dropout(res_block4, nb_filters[2], 5)

    res_block6 = resnet_block_dropout(res_block5, nb_filters[2], 6)

    upsample3 = Conv2D(nb_filters[2], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net3')(UpSampling2D(size = (2,2))(res_block6))

    upsample3 = Dropout(0.5)(upsample3, training=True)

    merged3 = concatenate([res_block3, upsample3], name='concatenate3')

    upsample2 = Conv2D(nb_filters[1], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net2')(UpSampling2D(size = (2,2))(merged3))

    upsample2 = Dropout(0.5)(upsample2, training=True)

    merged2 = concatenate([res_block2, upsample2], name='concatenate2')

    upsample1 = Conv2D(nb_filters[0], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net1')(UpSampling2D(size = (2,2))(merged2))
    upsample1 = Dropout(0.5)(upsample1, training=True)

    merged1 = concatenate([res_block1, upsample1], name='concatenate1')

    output = Conv2D(n_classes,(1,1), activation = 'softmax', padding = 'same', name = 'output')(merged1)

    return Model(input_layer, output)

# Residual U-Net model
def build_resunet_dropout_spatial(input_shape, nb_filters, n_classes, dropout_seed = None, last_activation='softmax', training=True):
    '''Base network to be shared (eq. to feature extraction)'''

    dropout = 0.25

    input_layer= Input(shape = input_shape, name="input_enc_net")

    res_block1 = resnet_block_spatial_dropout(input_layer, nb_filters[0], dropout_seed, 1, training=training)
    pool1 = MaxPool2D((2 , 2), name='pool_net1')(res_block1)

    res_block2 = resnet_block_spatial_dropout(pool1, nb_filters[1], dropout_seed, 2, training=training)
    pool2 = MaxPool2D((2 , 2), name='pool_net2')(res_block2)

    res_block3 = resnet_block_spatial_dropout(pool2, nb_filters[2], dropout_seed, 3, training=training)
    pool3 = MaxPool2D((2 , 2), name='pool_net3')(res_block3)

    res_block4 = resnet_block_spatial_dropout(pool3, nb_filters[2], dropout_seed, 4, training=training)

    res_block5 = resnet_block_spatial_dropout(res_block4, nb_filters[2], dropout_seed, 5, training=training)

    res_block6 = resnet_block_spatial_dropout(res_block5, nb_filters[2], dropout_seed, 6, training=training)

    upsample3 = Conv2D(nb_filters[2], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net3')(UpSampling2D(size = (2,2))(res_block6))

    upsample3 = SpatialDropout2D(dropout, seed = dropout_seed)(upsample3, training=training)

    merged3 = concatenate([res_block3, upsample3], name='concatenate3')

    upsample2 = Conv2D(nb_filters[1], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net2')(UpSampling2D(size = (2,2))(merged3))

    upsample2 = SpatialDropout2D(dropout, seed = dropout_seed)(upsample2, training=training)

    merged2 = concatenate([res_block2, upsample2], name='concatenate2')

    upsample1 = Conv2D(nb_filters[0], (3 , 3), activation = 'relu', padding = 'same',
                       name = 'upsampling_net1')(UpSampling2D(size = (2,2))(merged2))

    upsample1 = SpatialDropout2D(dropout, seed = dropout_seed)(upsample1, training=training)

    merged1 = concatenate([res_block1, upsample1], name='concatenate1')

    output = Conv2D(n_classes,(1,1), activation = last_activation, padding = 'same', name = 'output')(merged1)

    return Model(input_layer, output)

def excludeBackgroundAreasFromTest(vector_test, label_mask_test):
    return vector_test[label_mask_test != 2]

def getTestVectorFromIm(im, mask, mask_return_value = 1):
    return im[mask == mask_return_value]

def unpadIm(im, npad):
    return im[:-npad[0][1], :-npad[1][1]]


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2, 10)
y = x**2

#plt.plot(x,y)
#plt.show()
#Attention au dimention !!

#Param c coleur c='red'
#Param lw line wight epaisseur du trait lw=5
#Param ls line style ls='--'

#=====================================

plt.figure()#feuille de travaille
#param figsize (en inch) pour demensionner le taille de la figure

plt.plot(x, y, label="quadratique")#on dessine sur le figure
plt.plot(x, x**3, label="cubique")
plt.title("TestMathPlot")
plt.xlabel("axe x")
plt.ylabel("axe y")
plt.legend()
plt.show()

plt.savefig('TestMathPlot.png')

#====================================

plt.subplot(2, 1, 1)
plt.plot(x, y, c='red')

plt.subplot(2, 1, 2)
plt.plot(x, y, c='blue')

#===================================
dataset = {f"experience{i}": np.random.randn(100) for i in range (4)}
#On se cree un dico de data avec 4 entre

# print(dataset)

def graphique(dataset):

    lkey = list(dataset.keys())
    plt.figure()

    for i in range(len(lkey)):
        plt.subplot(len(lkey), 1, i+1)
        plt.plot(dataset.get(lkey[i]))

    plt.show()

graphique(dataset)