from __future__ import print_function, division, absolute_import, unicode_literals

import functools
from ..base import BaseEstimator, BaseModel
from ..utils.params import (param_def, check_int, check_string, check_boolean,
                            check_float, check_variable, check_variable_list,
                            extract_params)

class DecisionTree(BaseEstimator):
    '''
    Decision Tree

    Parameters
    ----------
    alpha : float, optional
        Specifies the value to use for minimal cost-complexity pruning
        for regression trees
    cf_level : float, optional
        Specifies the aggressiveness of tree pruning according to the C4.5
        algorithm.
    criterion : string, optional
        Split criterion. Valid values are 'variance', 'gain', 'gain_ratio',
        and 'gini'.
    leaf_size : int, optional
        Minimum leaf size
    max_braches : int, optional
        Maximum number of branches
    max_depth : int, optional
        Maximum depth of trees
    n_bins : int, optional
        Number of bins to use for numeric variables in the calculation
        of the decision tree
    prune : boolean, optional
        Specify True to use a C4.5 pruning method for classification
        trees or minimal cost-complexity pruning for regression trees
    var_importannce : bool, optional
        Specifies whether the variable importance information is
        generated
    target : string, optional
        The target variable
    nominals : string or list of strings, optional
        The nominal variables
    inputs : string or list of strings, optional
        The input variables

    Examples
    --------
    >>> dtree = DecisionTree(target='Origin',
    ...                      inputs=['MPG_City', 'MPG_Highway', 'Length',
    ...                              'Weight', 'Type', 'Cylinders'],
    ...                      nominals = ['Type', 'Cylinders', 'Origin'])

    Returns
    -------
    :class:`DecisionTree`

    '''

    param_defs = dict(
        alpha=param_def(0, functools.partial(check_float, minimum=0)),
        cf_level=param_def(0.25, functools.partial(check_float, minimum=0, maximum=1)),
        criterion=param_def(None, functools.partial(check_string, allow_none=True,
                                      valid_values=['variance', 'gain',
                                                    'gain_ratio', 'gini'])),
        leaf_size=param_def(5, functools.partial(check_int, minimum=1)),
        max_branches=param_def(2, functools.partial(check_int, minimum=1)),
        max_depth=param_def(6, functools.partial(check_int, minimum=1)),
        n_bins=param_def(20, functools.partial(check_int, minimum=1)),
        prune=param_def(False, check_boolean),
        var_importance=param_def(False, check_boolean),
        target=param_def(None, check_variable),
        nominals=param_def(None, check_variable_list),
        inputs=param_def(None, check_variable_list),
    )

    static_params = dict(
        bin_order=True,
        greedy=True,
        merge_bin=True,
        include_missing=True,
        missing='use_in_search',
        stat=False,
    )

    def __init__(self, alpha=0, cf_level=0.25, criterion=None, leaf_size=5,
                       max_branches=2, max_depth=6, n_bins=20, prune=False,
                       var_importance=False, target=None, nominals=None, inputs=None):
        BaseEstimator.__init__(self, **extract_params(locals()))

    def fit(self, table, *args, **kwargs):
        '''
        Fit function for decision tree

        Parameters
        ----------
        *args : dicts or two-element tuples or consecutive key/value pairs, optional
            The following types are allowed:
                * Dictionaries contain key/value pairs of parameters.
                * Two-element tuples must contain the name of the parameter in the
                  first element and the value in the second element.
                * Consecutive key/value pairs are also allowed.
        **kwargs : keyword arguments, optional
            These keyword arguments are the same as on the constructor.

        Examples
        --------
        >>> dtree = DecisionTree(target='Origin',
        ...                      inputs=['MPG_City', 'MPG_Highway', 'Length',
        ...                              'Weight', 'Type', 'Cylinders'],
        ...                      nominals = ['Type', 'Cylinders', 'Origin'])
        >>> model = dtree.fit(training_data)

        Returns
        -------
        :class:`DecisionTreeModel`

        '''
        params = self.get_combined_params(*args, **kwargs)
        return self._get_super(table).fit(table, **params)

class DecisionTreeModel(BaseModel):
    ''' DecisionTree trained model '''

    param_defs = DecisionTree.param_defs
    static_params = DecisionTree.static_params


import pandas as pd

class Data_Getter:
    """
    This class shall  be used for obtaining the data from the source for training.
    """
    def __init__(self, file_object, logger_object, training_file_path):
        self.training_file = 'Training_FileFromDB/data.csv'
        self.file_object = file_object
        self.logger_object = logger_object
        self.training_file = training_file_path

    def get_data(self):
        """
            Method Name: get_data
            Description: This method reads the csv data from source.
            Parameters : No parameters
            Output: A pandas DataFrame.
            On Failure: Raise Exception

        """

        self.logger_object.log(self.file_object, 'Entered the function get_data of class Data_Getter.')
        try:
            df = pd.read_csv(self.training_file)
            self.logger_object.log(self.file_object, 'Function get_data of class Data_Getter Completed Successfully. Exited this function')
            return df
        except Exception as e:
            self.logger_object.log(self.file_object, 'Error occured in function get_data. Error Message : ' + str(e))


import sys

_SCAN_NR_INDEX = 2

def main():
    if len(sys.argv[1:]) != 2:
        error_msg = "python {} <in> <out>".format(
            sys.argv[0]
        )
        sys.exit(error_msg)

    in_file, out_file = sys.argv[1:]

    with open(in_file) as f, open(out_file, "w") as o:
        line_number = 0
        for line in f:
            new_line = line

            if not line.startswith("SpecId"):
                line_number += 1
                split = line.split()
                split[_SCAN_NR_INDEX] = str(line_number)
                new_line = "\t".join(split) + "\n"

            o.write(new_line)

if __name__ == '__main__':
    main()


import os
import re

SUE_NAME_REGEX = re.compile('(\w+ \d+):')
KEY_VALUE_REGEX = re.compile('(\w+: \d+)')

def get_sue_map(line):
    sue = SUE_NAME_REGEX.findall(line)[0]
    acc = {}
    for thing in KEY_VALUE_REGEX.findall(line):
        key, value = thing.split(': ')
        acc[key] = int(value)
    return sue, acc

def get_sue_maps(in_file):
    acc = {}
    with open(in_file, 'r') as open_file:
        for line in open_file:
            key, value = get_sue_map(line)
            acc[key] = value
    return acc

def get_result_maps(in_file):
    acc = {}
    with open(in_file, 'r') as open_file:
        for line in open_file:
            key, value = line.split(': ')
            acc[key] = int(value)
    return acc

def discern_sue(complete_sue, partial_sues):
    def merge_two_dicts(dict_1, dict_2):
        dict_3 = dict_1.copy()
        dict_3.update(dict_2)
        return dict_3
    return [sue for sue in partial_sues if complete_sue == merge_two_dicts(complete_sue, partial_sues[sue])][0]

def discern_sue_2(complete_sue, partial_sues):
    def evaluate_sue(partial_sue):
        for key in partial_sue:
            guess_val = partial_sue[key]
            complete_val = complete_sue[key]
            if key in ['cats', 'trees']:
                if guess_val <= complete_val:
                    return False
            elif key in ['pomeranians', 'goldfish']:
                if guess_val >= complete_val:
                    return False
            elif guess_val != complete_val:
                return False
        return True
    return [sue for sue in partial_sues if evaluate_sue(partial_sues[sue])][0]

if __name__ == '__main__':
    result_map = get_result_maps(os.path.dirname(__file__) + '/input/day_16.2.input')
    sue_maps = get_sue_maps(os.path.dirname(__file__) + '/input/day_16.1.input')
    print(discern_sue(result_map, sue_maps))
    print(discern_sue_2(result_map, sue_maps))


from __future__ import annotations

import asyncio
from collections.abc import AsyncIterator
from collections.abc import Awaitable
import contextlib
import logging
import pathlib
from typing import Any
from typing import Callable

import libtorrent as lt

from tvaf import caches

from .. import config as config_lib
from .. import plugins
from .. import services

_LOG = logging.getLogger(__name__)
DEFAULT_DOWNLOAD_PATH = pathlib.Path("download")

Default = Callable[[lt.add_torrent_params], Awaitable]
_DEFAULT_FUNCS: plugins.Funcs[Default] = plugins.Funcs("tvaf.services.atp.default")
default_plugin = _DEFAULT_FUNCS.decorator

async def get_default() -> lt.add_torrent_params:
    atp = lt.add_torrent_params()
    for _, func in sorted(_DEFAULT_FUNCS.get().items()):
        await func(atp)
    return atp

Configure = Callable[[lt.add_torrent_params], Awaitable]
_CONFIGURE_FUNCS: plugins.Funcs[Configure] = plugins.Funcs(
    "tvaf.services.atp.configure"
)
configure_plugin = _CONFIGURE_FUNCS.decorator

async def configure(atp: lt.add_torrent_params) -> None:
    for _, func in sorted(_CONFIGURE_FUNCS.get().items()):
        await func(atp)

async def _get_defaults_from_config(
    config: config_lib.Config,
) -> dict[str, Any]:
    config.setdefault("torrent_default_save_path", str(DEFAULT_DOWNLOAD_PATH))

    defaults: dict[str, Any] = {}

    save_path = pathlib.Path(config.require_str("torrent_default_save_path"))
    try:
        # Raises RuntimeError on symlink loops
        save_path = await asyncio.to_thread(save_path.resolve)
    except RuntimeError as exc:
        raise config_lib.InvalidConfigError(str(exc)) from exc

    config["torrent_default_save_path"] = str(save_path)
    defaults["save_path"] = str(save_path)

    name_to_flag = {
        "apply_ip_filter": lt.torrent_flags.apply_ip_filter,
    }

    for name, flag in name_to_flag.items():
        key = f"torrent_default_flags_{name}"
        value = config.get_bool(key)
        if value is None:
            continue
        defaults.setdefault("flags", lt.torrent_flags.default_flags)
        if value:
            defaults["flags"] |= flag
        else:
            defaults["flags"] &= ~flag

    maybe_name = config.get_str("torrent_default_storage_mode")
    if maybe_name is not None:
        full_name = f"storage_mode_{maybe_name}"
        mode = lt.storage_mode_t.names.get(full_name)
        if mode is None:
            raise config_lib.InvalidConfigError(f"invalid storage mode {maybe_name}")
        defaults["storage_mode"] = mode
    return defaults

@caches.asingleton()
async def _get_defaults() -> dict[str, Any]:
    return await _get_defaults_from_config(await services.get_config())

@services.startup_plugin("10_default_atp")
async def _startup_config_default() -> None:
    # Parse existing config
    await _get_defaults()

@services.stage_config_plugin("50_default_atp")
@contextlib.asynccontextmanager
async def _stage_config_default(
    config: config_lib.Config,
) -> AsyncIterator[None]:
    await _get_defaults_from_config(config)
    yield
    _get_defaults.cache_clear()

@default_plugin("50_config")
async def _default_from_config(atp: lt.add_torrent_params) -> None:
    defaults = await _get_defaults()
    for key, value in defaults.items():
        setattr(atp, key, value)


from mars_rover_kata import mars_rover, turn, warp_drive
from pytest import mark

rover_params = [
    ("F", "0:1:N"),
    ("FF", "0:2:N"),
    ("FFF", "0:3:N"),
    ("R", "0:0:E"),
    ("RLL", "0:0:W"),
    ("RF", "1:0:E"),
    ("RFLFLF", "0:1:W"),
    ("LF", "9:0:W"),
    ("RFFFFFFFFFF", "0:0:E"),
    ("FFFFFFFFFF", "0:0:N"),
    ("RRF", "0:9:S"),
]

@mark.parametrize( ("command", "result"), rover_params)
def test_mars_rover_commands(command, result):
    assert mars_rover(command) == result

turn_params = [
    ("N", "R", "E"),
    ("N", "L", "W"),
    ("W", "R", "N"),
]

@mark.parametrize( ("current_heading", "turn_signal", "new_heading"), turn_params)
def test_turn(current_heading, turn_signal, new_heading):
    assert turn(current_heading, turn_signal) == new_heading

def test_warp_drive():
    assert warp_drive(-1)==9
    assert warp_drive(10)==0
    assert warp_drive(5) == 5


import pytest

from starknet_py.serialization._context import SerializationContext
from starknet_py.serialization.errors import InvalidTypeException, InvalidValueException

@pytest.mark.parametrize(
    "initial_exception, wrapped_class",
    [
        (ValueError("Test"), InvalidValueException),
        (TypeError("Test"), InvalidTypeException),
    ],
)
def test_if_exceptions_are_wrapped(initial_exception, wrapped_class):
    with pytest.raises(wrapped_class, match="Error: Test"):
        with SerializationContext.create():
            raise initial_exception


# -*- coding: utf-8 -*-

# Roger - Facial detection
# Joseph - Canny
# Lyndon - Canny line -> smoothing/thickness modifier along lines
# Sabrina - Textures
# Kelsey - Quantizing RGB/HSV

"""CS4476Prj.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1WGs55cY6plbmUJFE-gipBV8MQNJsHIBL

CS  4476: Fall 2020

Final Project

Sabrina Chua, Kelsey Henson, Joseph Lee, Roger Nhan, Lyndon Puzon

"""

#export
from matplotlib import use
import numpy as np

np.set_printoptions(threshold=np.inf)
from sklearn.cluster import KMeans
from skimage.color import rgb2hsv, hsv2rgb, rgb2gray, rgba2rgb
from skimage import feature, color, draw
from imageio import imread, imsave
from scipy import ndimage
from typing import Tuple, overload
from PIL import Image
from edgeDetection import edgeDetection, edgeDetailDetection
from matplotlib import pyplot as plt
from texture import median_filter, FillColors
from binary_skin import binary_skin_erosion_dilation

#export
def quantize_hsv(img: np.ndarray, k: int):
    """
    Compute the k-means clusters for the input image in the hue dimension of the
    HSV space. Replace the hue values with the nearest cluster's hue value. Finally,
    convert the image back to RGB.

    Inputs:
        img: Input RGB image with shape H x W x 3 and dtype "uint8"
        k: The number of clusters to use

    Output:
        An RGB image with shape H x W x 3 and dtype "uint8"
    """
    quantized_img = np.zeros_like(img)

    ##########################################################################
    # TODO: Convert the image to HSV. Perform k-means clustering in hue      #
    # space. Replace the hue values in the image with the cluster centers.   #
    # Convert the image back to RGB.                                         #
    ##########################################################################

    #Converting image to HSV and retrieving H channels
    image = rgb2hsv(img)
    h,w,_ = image.shape
    hue = image[:,:,0]
    hue = hue.reshape(h*w,1)

    clusters = KMeans(n_clusters=k, random_state=101)
    kmeans = clusters.fit(hue)
    labels = kmeans.predict(hue)

    colors = np.array(kmeans.cluster_centers_)

    for row in range(0,len(hue)):
        hue[row] = colors[labels[row]]

    hue = hue.reshape(image[:,:,0].shape)

    quantized_img = np.copy(image)
    quantized_img[:,:,0] = hue

    quantized_img = hsv2rgb(quantized_img)
    quantized_img = quantized_img * 255
    quantized_img = quantized_img.astype(np.uint8)

    ##########################################################################
    ##########################################################################

    return quantized_img

# Quantize RGB
#export
def quantize_rgb(img: np.ndarray, k: int):
    """
    Compute the k-means clusters for the input image in RGB space, and return
    an image where each pixel is replaced by the nearest cluster's average RGB
    value.

    Inputs:
        img: Input RGB image with shape H x W x 3 and dtype "uint8"
        k: The number of clusters to use

    Output:
        An RGB image with shape H x W x 3 and dtype "uint8"
    """
    quantized_img = np.zeros_like(img)

    ##########################################################################
    # TODO: Perform k-means clustering and return an image where each pixel  #
    # is assigned the value of the nearest clusters RGB values.              #
    ##########################################################################

    x, y, z = img.shape
    listImg = img.reshape(x*y, z)

    kmeans = KMeans(n_clusters=k, random_state=101).fit(listImg)

    # centers = kmeans.cluster_centers_.astype(int)
    print(kmeans.cluster_centers_.shape)
    # kmeans.cluster_centers_ = np.vstack((kmeans.cluster_centers_, np.array([[0, 0, 0]])))
    labels = kmeans.predict(listImg)
    print(kmeans.cluster_centers_.shape)
    return kmeans.cluster_centers_.astype(int)[labels].reshape(x, y, z)

    ##########################################################################
    ##########################################################################

    return quantized_img

original = imread("../res/images/person2.jpg")

if original.shape[2] == 4:
    original = rgba2rgb(original).astype(np.uint8)

# img_quantize = quantize_rgb(original, k=8)
face_mask = binary_skin_erosion_dilation(original)
original_hsv = rgb2hsv(original)
if np.max(face_mask) != 0:
    skin_avgR = np.average(original_hsv[:,:,0], weights=face_mask)
    skin_avgG = np.average(original_hsv[:,:,1], weights=face_mask)
    skin_avgB = np.average(original_hsv[:,:,2], weights=face_mask)
    hsvArr = np.array([skin_avgR, skin_avgG, skin_avgB])
    rgbArr = (hsv2rgb(hsvArr) * 255).astype(np.uint8)
    print(rgbArr)

# face_mask = np.zeros_like(original[:, :, 0])
img_quantize = median_filter(FillColors(np.copy(original), 15, face_mask).get_img())
# img_quantize = original
img_quantize_face = quantize_rgb(original, k=3)

edges = edgeDetection(img_quantize)
edgesDetail = edgeDetailDetection(original)
edges_face = edgeDetection(img_quantize_face, 2)

overlaid_img = np.copy(img_quantize).astype(np.float32)
if np.max(face_mask) != 0:
    overlaid_img[face_mask == 1] = rgbArr
overlaid_img[np.logical_and(edges, np.logical_not(face_mask))] = 0
overlaid_img[np.logical_and(edgesDetail, np.logical_not(face_mask))] *= 0.5
overlaid_img[np.logical_and(edges_face, face_mask)] *= 0.9
overlaid_img = overlaid_img.astype(np.uint8)
# overlaid_img[edges] = 0

# fig, axs = plt.subplots(2, 3, figsize=(15,15))

# axs[0, 0].imshow(original)
# axs[0, 1].imshow(face_mask, cmap="gray")
# axs[0, 2].imshow(edges, cmap="gray")
# axs[1, 0].imshow(edges_face, cmap="gray")
# axs[1, 1].imshow(overlaid_img)

fig, axs = plt.subplots(1, 2)

axs[0].imshow(original)
axs[1].imshow(overlaid_img)

plt.show()
# Smooth/reinforce lines

# Textures
# img_array = imread('hill.jpg')

# fig = plt.figure()
# axes = plt.axes()

# temp = texture.FillColors(img_array, 15)
# image = temp.get_img()
# fitered = texture.median_filter(img_array)

# axes.imshow(fitered)
# plt.show()

#test2

# Blob detection


# -*- coding: utf-8 -*-
'''
模三分析图例
@author: Karwai Kwok
'''

from PyQt4.QtGui import QDialog, QWidget, QLabel, QGridLayout
from PyQt4.QtCore import Qt

class Mod3Legend(QDialog):
    def __init__(self, iface, styleManager, parent=None):
        super(Mod3Legend, self).__init__()
        self.iface = iface
        self.styleManager = styleManager # 小区样式渲染器
        self.parent = parent

        self.initUI()
    # 初始化界面
    def initUI(self):
        self.setWindowTitle(u"模三分析")
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)

        widget_0 = QWidget()
        widget_0.setStyleSheet('QWidget {background-color: red}')
        widget_0.resize(20, 20)
        label_0 = QLabel("0")

        widget_1 = QWidget()
        widget_1.setStyleSheet('QWidget {background-color: yellow}')
        widget_1.resize(20, 20)
        label_1 = QLabel("1")

        widget_2 = QWidget()
        widget_2.setStyleSheet('QWidget {background-color: #47d54c}')
        widget_2.resize(20, 20)
        label_2 = QLabel("2")

        grid = QGridLayout()
        grid.setSpacing(20)
        grid.addWidget(widget_0, 0, 0)
        grid.addWidget(label_0, 0, 1)
        grid.addWidget(widget_1, 1, 0)
        grid.addWidget(label_1, 1, 1)
        grid.addWidget(widget_2, 2, 0)
        grid.addWidget(label_2, 2, 1)

        self.setLayout(grid)
        self.setGeometry(300, 300, 250, 200)

    def closeEvent(self, event):
        self.accept()
        self.styleManager.setCurrentStyle(u"默认")  ##恢复上一级样式，即取消话务量渲染
        self.iface.actionDraw().trigger()


import ast

from packaway.violation import ImportRuleViolation

class ImportAnalyzer(ast.NodeVisitor):
    """ NodeVisitor for analyzing an AST.

    Parameters
    ----------
    module_name : str or None
        The module name (full path) associated with the Python source
        being parsed. None if this is unknown.
    import_rules : list of callable(str, str) -> tuple(bool, str)
        List of callables for validating the import.
        First argument is the current module name.
        Second argument is the (absolute) module name to be imported.
        The callable should return (valid, reason) where the first value
        is whether the import is valid, and the second value is the reason
        if there is a violation (not used if the import is valid.)
    """

    def __init__(self, module_name=None, import_rules=None):
        self.module_name = module_name
        self.import_rules = [] if import_rules is None else import_rules
        self._errors = []

    def visit_Import(self, node):
        """ Reimplemented NodeVisitor.visit_Import """
        for alias in node.names:
            target = alias.name
            for import_rule in self.import_rules:
                is_valid, reason = import_rule(self.module_name, target)
                if not is_valid:
                    self._errors.append(
                        ImportRuleViolation(
                            lineno=node.lineno,
                            col_offset=node.col_offset,
                            message=reason,
                        )
                    )
        self.generic_visit(node)

    def visit_ImportFrom(self, node):
        """ Reimplemented NodeVisitor.visit_ImportFrom """

        for alias in node.names:
            if node.module is None:
                target = alias.name
            else:
                target = ".".join([node.module, alias.name])

            target = _normalize_target_module(
                self.module_name, target, node.level
            )
            for import_rule in self.import_rules:
                is_valid, reason = import_rule(self.module_name, target)
                if not is_valid:
                    self._errors.append(
                        ImportRuleViolation(
                            lineno=node.lineno,
                            col_offset=node.col_offset,
                            message=reason,
                        )
                    )
        self.generic_visit(node)

def _normalize_target_module(source_module, target_module, level):
    """ Normalize relative import, to absolute import if possible.

    Parameters
    ----------
    source_module : str or None
        Name of the module where the import is written.
        If given, this name should be absolute.
    target_module : str
        Name of the module being imported.
        This name can be absolute or relative depending on the value
        of ``level``.
    level : int, optional
        level specifies whether to use absolute or relative
        imports. 0 (the default) means only perform absolute
        imports. Positive values for level indicate the number
        of parent directories to search relative to the directory
        of the module calling import.

    Returns
    -------
    module_name : str
        Normalized import name
    """
    if source_module is None or level == 0:
        return target_module

    source_parts = source_module.split(".")
    if level > len(source_parts):
        raise ValueError("Level is too deep.")
    target_parts = source_parts[:-level] + target_module.split(".")
    return ".".join(target_parts)


from tkinter import *
from tkinter.ttk import *
import time
import serial
import io

#
# Runs with python 3
# works for microlab 500
#
root = Tk()
master = Frame(root, name='master')
master.pack(fill=BOTH)  # fill both sides of the parent
root.title('Syringe Control')  # title for top-level window
root.protocol("WM_DELETE_WINDOW", master.quit)  #quit if the window is deleted

# This is to add a second window
'''
syrStat = Toplevel()
syrStat.title("Syringe Status")
msg = Message(syrStat, text='test    fre          fre')
msg.pack()
button = Button(syrStat, text="Dismiss", command=syrStat.destroy)
button.pack()
'''

syrCtrl = Notebook(master, name='syrCtrl')  # create Notebook in "master"
syrCtrl.pack(fill=BOTH, padx=2, pady=3)  # fill "master" but pad sides -> frame appears
syrCtrlMan = Frame(syrCtrl, name='syrCtrlMan') # create foo tab in Notebook
syrCtrlMan.pack(fill=BOTH)

# Create Init
syrCtrlManInit = LabelFrame(syrCtrlMan, text='Init', name='syrCtrlManLeftInit', relief=GROOVE, borderwidth=2, labelanchor=N)
syrCtrlManInit.grid(row = 0, column = 0, columnspan = 2)
InitBut = Button(syrCtrlManInit, text="Init", command=lambda: syrCtrl().sendCmd('aXS30R'))
InitBut.grid(row = 0, column = 0, rowspan = 2, padx=2, pady=3)
Label(syrCtrlManInit, text="Fine Speed").grid(row = 0, column = 1)
ManFineSpeed = Entry(syrCtrlManInit, width=11)
ManFineSpeed.insert(END, 250)
ManFineSpeed.grid(row = 0, column = 2)
Label(syrCtrlManInit, text="Coarse Speed").grid(row = 1, column = 1)
ManCoarseSpeed = Entry(syrCtrlManInit, width=11)
ManCoarseSpeed.insert(END, 50)
ManCoarseSpeed.grid(row = 1, column = 2)

# Create 'Left Syringe' frame
syrCtrlManLeft = LabelFrame(syrCtrlMan, text='Left Syringe', name='syrCtrlManLeft', relief=GROOVE, borderwidth=2)
syrCtrlManLeft.grid(row = 1, column = 0, padx=2, pady=3)

# Create 'Pick Up' frame in 'Left Syringe' frame
syrCtrlManLeftPickUp = LabelFrame(syrCtrlManLeft, text='Pick-Up (Fine Speed)', name='syrCtrlManLeftPickUp', relief=GROOVE, borderwidth=2, labelanchor=N)
syrCtrlManLeftPickUp.grid(row = 0, column = 0)
PickUp1 = Button(syrCtrlManLeftPickUp, text="PickUp\n1 step", command=lambda: syrCtrl().singleSyrMove('B', 'I', 'P', 1, ManFineSpeed.get()))
PickUp1.grid(row = 0, column = 0, rowspan = 2)
PickUp2 = Button(syrCtrlManLeftPickUp, text="PickUp\n5 steps", command=lambda: syrCtrl().singleSyrMove('B', 'I', 'P', 5, ManFineSpeed.get()))
PickUp2.grid(row = 0, column = 1, rowspan = 2)
PickUp3 = Button(syrCtrlManLeftPickUp, text="PickUp\nSpecified", command=lambda: syrCtrl().singleSyrMove('B', 'I', 'P', int(ManPickUpStep.get()), ManFineSpeed.get()))
PickUp3.grid(row = 0, column = 2, rowspan = 2)
Label(syrCtrlManLeftPickUp, text="<-Steps", ).grid(row = 0, column = 4)
ManPickUpStep = Entry(syrCtrlManLeftPickUp, width=11)
ManPickUpStep.insert(END, 50)
ManPickUpStep.grid(row = 1, column = 4)

# Create 'other' frame in 'Left Syringe' frame
syrCtrlManLeftOther = LabelFrame(syrCtrlManLeft, text='Other (Coarse Speed)', name='syrCtrlManLeftOther', relief=GROOVE, borderwidth=2, labelanchor=N)
syrCtrlManLeftOther.grid(row = 1, column = 0)
LeftOther1 = Button(syrCtrlManLeftOther, text="Empty\nto\nwaste", command=lambda: syrCtrl().singleSyrMove('B', 'O', 'M', 0, ManCoarseSpeed.get()))
LeftOther1.grid(row = 0, column = 0)
LeftOther2 = Button(syrCtrlManLeftOther, text="Empty\nto\nmylar", command=lambda: syrCtrl().singleSyrMove('B', 'I', 'M', 0, ManCoarseSpeed.get()))
LeftOther2.grid(row = 0, column = 1)
LeftOther3 = Button(syrCtrlManLeftOther, text="Fill\nfrom\nwaste", command=lambda: syrCtrl().singleSyrMove('B', 'O', 'M', 2000, ManCoarseSpeed.get()))
LeftOther3.grid(row = 0, column = 2)
LeftOther4 = Button(syrCtrlManLeftOther, text="Fill\nfrom\nmylar", command=lambda: syrCtrl().singleSyrMove('B', 'I', 'M', 2000, ManCoarseSpeed.get()))
LeftOther4.grid(row = 0, column = 4)

# Create 'Right Syringe' frame
syrCtrlManRight = LabelFrame(syrCtrlMan, text='Right Syringe', name='syrCtrlManRight', relief=GROOVE, borderwidth=2)
syrCtrlManRight.grid(row = 1, column = 1, padx=2, pady=3)
# Create 'Dispence' frame in 'Right Syringe' frame
syrCtrlManRightDispence = LabelFrame(syrCtrlManRight, text='Dispence (Fine Speed)', name='syrCtrlManRightDispence', relief=GROOVE, borderwidth=2, labelanchor=N)
syrCtrlManRightDispence.grid(row = 0, column = 0)
Dispence1 = Button(syrCtrlManRightDispence, text="Dispence\n1 step", command=lambda: syrCtrl().singleSyrMove('C', 'O', 'D', 1, ManFineSpeed.get()))
Dispence1.grid(row = 0, column = 0, rowspan = 2)
Dispence2 = Button(syrCtrlManRightDispence, text="Dispence\n5 steps", command=lambda: syrCtrl().singleSyrMove('C', 'O', 'D', 5, ManFineSpeed.get()))
Dispence2.grid(row = 0, column = 1, rowspan = 2)
Dispence3 = Button(syrCtrlManRightDispence, text="Dispence\nSpecified", command=lambda: syrCtrl().singleSyrMove('C', 'O', 'D', int(ManDispStep.get()), ManFineSpeed.get()))
Dispence3.grid(row = 0, column = 2, rowspan = 2)
Label(syrCtrlManRightDispence, text="<-Steps", ).grid(row = 0, column = 4)
ManDispStep = Entry(syrCtrlManRightDispence, width=11)
ManDispStep.insert(END, 50)
ManDispStep.grid(row = 1, column = 4)

# Create 'other' frame in 'Right Syringe' frame
syrCtrlManRightOther = LabelFrame(syrCtrlManRight, text='Other (Coarse Speed)', name='syrCtrlManRightOther', relief=GROOVE, borderwidth=2, labelanchor=N)
syrCtrlManRightOther.grid(row = 1, column = 0)
RightOther1 = Button(syrCtrlManRightOther, text="Empty\nto\nsupply", command=lambda: syrCtrl().singleSyrMove('C', 'I', 'M', 0, ManCoarseSpeed.get()))
RightOther1.grid(row = 0, column = 0)
RightOther2 = Button(syrCtrlManRightOther, text="Empty\nto\nmylar", command=lambda: syrCtrl().singleSyrMove('C', 'O', 'M', 0, ManCoarseSpeed.get()))
RightOther2.grid(row = 0, column = 1)
RightOther3 = Button(syrCtrlManRightOther, text="Fill\nfrom\nsupply", command=lambda: syrCtrl().singleSyrMove('C', 'I', 'M', 2000, ManCoarseSpeed.get()))
RightOther3.grid(row = 0, column = 2)
RightOther4 = Button(syrCtrlManRightOther, text="Fill\nfrom\nmylar", command=lambda: syrCtrl().singleSyrMove('C', 'O', 'M', 2000, ManCoarseSpeed.get()))
RightOther4.grid(row = 0, column = 4)

# Create Stop
syrCtrlManStop = LabelFrame(syrCtrlMan, text='Stop', name='syrCtrlManLeftStop', relief=GROOVE, borderwidth=2, labelanchor=N)
syrCtrlManStop.grid(row = 2, column = 0, columnspan = 2, padx=2, pady=3)
Stop = Button(syrCtrlManStop, text="STOP", command=lambda: syrCtrl().sendCmd('aK'))
Stop.grid(row = 0, column = 0, rowspan = 2)

# add 'Manual tab' tab to Notebook
syrCtrl.add(syrCtrlMan, text="Manual Mode")

# repeat for each tab
# line 1
syrCtrlAuto = Frame(master, name='syrCtrlAuto')
Label(syrCtrlAuto, text="Bottle Speed").grid(row = 0, column = 0)
bottleSpeed = Entry(syrCtrlAuto, width=11)
bottleSpeed.insert(END, 50)
bottleSpeed.grid(row = 0, column = 1)
Label(syrCtrlAuto, text="Syr Size (mL)").grid(row = 0, column = 2)
syrSize = Entry(syrCtrlAuto, width=11)
syrSize.insert(END, 25)
syrSize.grid(row = 0, column = 3)
btn6 = Button(syrCtrlAuto,
				text="Check Time",
				command=lambda : syrCtrl().checkTime(int(cycleNumberFlow.get())))
btn6.grid(row = 0, column = 4)

Label(syrCtrlAuto, text="Flow Speed").grid(row = 1, column = 0)
flowSpeed = Entry(syrCtrlAuto, width=11)
flowSpeed.insert(END, 250)
flowSpeed.grid(row = 1, column = 1)
Label(syrCtrlAuto, text="N cycle").grid(row = 1, column = 2)
cycleNumberFlow = Entry(syrCtrlAuto, width=11)
cycleNumberFlow.insert(END, 5)
cycleNumberFlow.grid(row = 1, column = 3)
btn6 = Button(syrCtrlAuto,
				text="Flow !",
				command=lambda : syrCtrl().flowCycle(int(cycleNumberFlow.get())))
btn6.grid(row = 1, column = 4)

btn5 = Button(syrCtrlAuto,
				text="getReady",
				command=lambda : syrCtrl().dualSyrMove('O', 'M', 0, 20, 'I', 'M', 2000, 20))
btn5.grid(row = 2, column = 0)

btn7 = Button(syrCtrlAuto,
				text="Flush",
				command=lambda : syrCtrl().flush(int(cycleNumberFlow.get())))
btn7.grid(row = 3, column = 0)

syrCtrl.add(syrCtrlAuto, text="Auto Mode") #end of the Auto tab

class syrCtrl():

	def setup(self):
		syrCtrl().sendSimpleCmd('1a')
		syrCtrl().sendCmd('aBYSM1R') # set full resolution -> 2000 step per strokes
		syrCtrl().sendCmd('aCYSM1R') # set full resolution -> 2000 step per strokes
		syrCtrl().sendCmd('aCYSN0R') # eliminates backlash
		syrCtrl().sendCmd('aBYSN0R') # eliminates backlash

	def sendSimpleCmd(self, cmd2send):
		# does not check the 'ack'
		sio.write(cmd2send + '\r') #??? removed unicode here
		sio.flush()
		result = sio.readline() #??? dropped '.decode('utf8')'
		response = result[1:-1]
		print('response is :', response[0:1])
		return response

	def sendCmd(self, cmd2send):
		sio.write(cmd2send + '\r') #??? removed unicode here
		sio.flush()
		result = sio.readline() #??? dropped '.decode('utf8')'
		ack = result[:1]
		#print('sould be 6 :',ord(ack[0]))
		if ord(ack[0]) != (6 or 49):
			raise Exception("bad response {}".format(ord(ack)))
	# strip off leading ack and trailin CR
		response = result[1:-1]
		#print('response is :', response[0:1])
		return response

	def moveAndWait(self, cmdMove):
		#global pl
		try:
			print('execute move', cmdMove)
			syrCtrl().sendCmd(cmdMove)
			while True:
				time.sleep(.2)
				response = syrCtrl().sendCmd('aF')
				# posLeft = getSyrPos()[0]
				# pl.config(text=getSyrPos()[0])
				if response[0:1] == 'Y':
					break
		except Exception as e:
			print('it broke')

	def singleSyrMove(self, syr, valve, type, step, speed):
		cmd = 'a'+syr+valve+type+str(step)+'S'+str(speed)+'R'
		syrCtrl().moveAndWait(cmd)

	def dualSyrMove(self, valveL, typeL, stepL, speedL, valveR, typeR, stepR, speedR):
		cmd = ('a'+
			'B'+valveL+typeL+str(stepL)+'S'+str(speedL)+
			'C'+valveR+typeR+str(stepR)+'S'+str(speedR)+'R')
		syrCtrl().moveAndWait(cmd)

	def syrFlush(self, cycleNum):
		for i in range(cycleNum):
			syrCtrl().dualSyrMove('O', 'M', 2000, 20, 'I', 'M', 2000, 20)
			syrCtrl().dualSyrMove('I', 'M', 0, ManCoarseSpeed.get(), 'O', 'M', 0, ManCoarseSpeed.get())

	def flowCycle(self, cycleNumber):
		for i in range(cycleNumber):
			time.sleep(.5)
			syrCtrl().getReady()
			time.sleep(.5)
			syrCtrl().dualSyrMove('I', 'M', 2000, flowSpeed.get(), 'O', 'M', 0, flowSpeed.get())

	def getReady(self):
		syrCtrl().dualSyrMove('O', 'M', 0, bottleSpeed.get(), 'I', 'M', 2000, bottleSpeed.get())

	def checkTime(self, cycleNumber):
		time = cycleNumber * (int(bottleSpeed.get()) + int(flowSpeed.get()))
		volume = cycleNumber * int(syrSize.get())
		print(('Will flow {} mL in {:.1f} minutes or {:.2f} hours').format(volume, time / 60, time / 3600))

	def flush(self, cycleNumber):
		for i in range(cycleNumber):
			time.sleep(.5)
			syrCtrl().dualSyrMove('I', 'M', 2000, bottleSpeed.get(), 'I', 'M', 2000, bottleSpeed.get())
			time.sleep(.5)
			syrCtrl().dualSyrMove('O', 'M', 0, flowSpeed.get(), 'O', 'M', 0, flowSpeed.get())

if __name__ == "__main__":
	# serial config
	ser = serial.Serial(
	port='\\.\COM3',
	baudrate=9600,
	parity=serial.PARITY_ODD,
	stopbits=serial.STOPBITS_ONE,
	bytesize=serial.SEVENBITS,
	timeout=.02
	)
	sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
	#time.sleep(10)
	syrCtrl().setup()

	master.mainloop()

'''
class syrCtrl():

    def sendCmd(self, cmd2send):
        print cmd2send

    def moveAndWait(self, cmdMove):
        print cmdMove

    def singleSyrMove(self, par):
        print 'single move', par

    def dualSyrMove(self, par):
        print 'dual move', par

#syrCtrl().singleSyrMove('maybe')
'''

"""

class test():
    def printTata(self):
        # type: () -> object
        print 'tata'

    def printToto(self):
        print 'toto'

test2 = test()

test2.printTata()
"""
'''

import Tkinter as tk

class Notepad(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="word")
        self.vsb = tk.Scrollbar(self, orient="vertical", comman=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="left", fill="both", expand=True)

def main():
    root = tk.Tk()
    Notepad(root).pack(fill="both", expand=True)
    for i in range(5):
        top = tk.Toplevel(root)
        Notepad(top).pack(fill="both", expand=True)

    root.mainloop()

if __name__ == "__main__":
    main()

'''

'''
class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = Frame(self.master)
        self.button1 = Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()

    def new_window(self):
        self.newWindow = Toplevel(self.master)
        self.app = Demo2(self.newWindow)

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = Frame(self.master)
        self.quitButton = Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

def main():
    root = Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

'''


import pandas as pd
import numpy as np
from general_network_modules import *

# Provide the network parameters here

capacities = list((10*np.ones(18)).astype(int))
arrival_rates = [1,2,1,3,1,2]
revenue_rates = [8,2,3,2,10,1]
bandwidths = [1,1,1,1,1,1]
A = np.array([[ 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1],\
                     [ 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\
                     [ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0],\
                     [ 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0],\
                     [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],\
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0]])

def create_link_by_link_policy(T, A, state, capacities):
    policy = []
    num_requests = A.shape[0]
    num_resources = A.shape[1]
    current_numbers = np.array(state.split(':')).astype(int)
    for i in range(num_requests):
        temp = []
        link_indices = np.where(A[i]>0)[0]
        for j in link_indices:
            if capacities[j] - np.matmul(current_numbers, A)[j] >=T[i][j]:
                temp = temp + [1]
            else:
                temp = temp + [0]
        if np.prod(temp) == 1:
            policy = policy + [1]
        else:
            policy = policy + [0]
    return policy

def simulate_general_network(A, T, policy_type):
    steps = 2000000
    num_requests = A.shape[0]
    current_state = [':'.join(items) for items in itertools.product([str(0)], repeat=num_requests)][0]
    total_revenue = 0
    total_time = 0
    for i in range(steps):
        if policy_type == 'accept_all':
            policy = create_default_policy(A, current_state, capacities)
        elif policy_type == 'link_by_link':
            policy = create_link_by_link_policy(T, A, current_state, capacities)
        next_states, next_rates = compute_next_states(capacities, bandwidths, policy, arrival_rates, current_state)
        random_times = [np.random.exponential(1/next_rates[j]) for j in range(len(next_rates))]
        total_revenue += compute_revenue_rate(revenue_rates, current_state)*min(random_times)
        total_time += min(random_times)
        current_state = next_states[np.argmin(random_times)]

    average_revenue = total_revenue/total_time

    return average_revenue

results = pd.DataFrame(columns =['capacities', 'A_matrix', 'arrival_rates', 'revenues', 'T_matrix', 'B_matrix', 'link_by_link_revenue', 'accept_all_revenue'])

T = np.copy(A)
accept_all_revenue = simulate_general_network(A, T, 'accept_all')
print('accept all revenue:', accept_all_revenue)
T, B = compute_link_by_link_heuristic(A, capacities, revenue_rates, arrival_rates, bandwidths)
link_by_link_revenue = simulate_general_network(A, T, 'link_by_link')

print('link by link revenue:', link_by_link_revenue)

new_row = {'capacities': capacities,  'A_matrix': A, 'arrival_rates': arrival_rates,  'revenues': revenue_rates, 'T_matrix': T, 'B_matrix': B, 'link_by_link_revenue':link_by_link_revenue, 'accept_all_revenue': accept_all_revenue}
results = results.append(new_row, ignore_index=True)
results.to_csv('results.csv', index=False)


import os
import zipfile
import shutil
import glob
import tqdm
from subprocess import PIPE, Popen, TimeoutExpired

HEADER = '\033[95m'
OK = '\033[94m'
PASS = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

class Unbundler:
    def __init__(self, folderName):
        self.folderName = folderName
        self.numberOfBundles = 0

    def check_Zip_Or_Folder(self):
        if not os.path.exists(f"{self.folderName}-bundles"):
            if os.path.exists(f"{self.folderName}-bundles.zip"):
                with zipfile.ZipFile(f"{self.folderName}-bundles.zip") as zipd:
                    zipd.extractall(self.folderName)

    def check_And_Create_Unbundled_Dirs(self):
        self.check_Zip_Or_Folder()
        self.numberOfBundles = 0
        bundleFolder = f"{self.folderName}/{self.folderName}-bundles"
        for bundle in os.listdir(bundleFolder):
            self.numberOfBundles += 1
            fromBundle = f"./{bundleFolder}/{bundle}"
            destPath = f"./{self.folderName}/unbundled/{bundle[:-3]}"
            if not os.path.exists(destPath):
                os.makedirs(destPath)
                shutil.copy2(fromBundle, destPath)

    def unbundle_All_Bundles(self):
        print("\tChecking zip file or already created folder...")
        self.check_And_Create_Unbundled_Dirs()
        print(f"\tzip file or folder {PASS}ok{ENDC}\n")
        print("\tInit / Unbundling / Updating...")
        pathBundleFolder = f"{self.folderName}/unbundled/"
        for bundle in tqdm.tqdm(glob.iglob(f"{pathBundleFolder}/*"),
                                total=self.numberOfBundles):
            nomFichierHg = bundle.split('/')[-1]
            optionsInit = ['hg', 'init', f"{bundle}"]
            procInit = Popen(optionsInit, stdout=PIPE, stderr=PIPE,
                             encoding='utf-8')
            resultInit, errInit = procInit.communicate()
            if errInit:
                tqdm.tqdm.write(f"{FAIL}Problème avec hg init !{ENDC}")
                tqdm.tqdm.write(f"{bundle}")
                tqdm.tqdm.write(f"Erreur : \n {WARNING}{errInit}{ENDC}")
                continue
            # Pas d'erreur avec le init on continue
            else:
                os.chdir(bundle)
                optionsUnb = ["hg", "unbundle", f'{nomFichierHg}.hg']
                procUnb = Popen(optionsUnb, stdout=PIPE, stderr=PIPE,
                                encoding='utf-8')
                resultUnb, errUnb = procUnb.communicate()
                os.chdir('../../../')
            if errUnb:
                print(f"{FAIL}Problème avec hg unbundle !{ENDC}")
                print(f"{bundle}")
                print(f"Erreur : \n {WARNING}{errUnb}{ENDC}")
                raise EnvironmentError('unbundle')
            # Pas d'erreur avec le unbundle on continue
            else:
                os.chdir(bundle)
                optionsUpdate = ["hg", "update"]
                procUpdate = Popen(optionsUpdate, stdout=PIPE, stderr=PIPE,
                                   encoding='utf-8')
                resultUpdate, errUpdate = procUpdate.communicate()
                os.chdir('../../../')
            if errUpdate:
                print(f"{FAIL}Problème avec hg update !{ENDC}")
                print(f"{bundle}")
                print(f"Erreur : \n {WARNING}{errUpdate}{ENDC}")
                raise EnvironmentError('update')
            #print(f"\t\t{bundle} {PASS}ok{ENDC}")
        print(f"\tInit / Unbundling / Updating {PASS}ok{ENDC}")


import asyncio
import datetime
import os
import subprocess

import discord
import humanize
import psutil
from cogs.consts import *
from cogs.handlers import Handlers
from discord.ext import commands

class Git(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.assignees = "PineaFan"
        self.emojis = Emojis
        self.colours = Cols()
        self.handlers = Handlers(self.bot)

        self.head = str(subprocess.check_output(["git", "rev-parse", "HEAD"]))[2:-3]
        self.branch = str(subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]))[2:-3]
        self.commit = str(subprocess.check_output(["git", "show-branch", self.branch]))[(5+(len(self.branch))):-3]
        self.url = str(subprocess.check_output(["git", "config", "--get", "remote.origin.url"]))[2:-3]

    @commands.command(aliases=["v"])
    async def version(self, ctx):
        total_size = 0
        for path, _, files in os.walk("./data/guilds"):
            for f in files:
                fp = os.path.join(path, f)
                total_size += os.path.getsize(fp)

        await ctx.send(embed=discord.Embed(
            title=f"{self.bot.user.name}",
            description=f"**Repository:** {self.url.split('/')[-2]}/{self.url.split('/')[-1]}\n"
                        f"**Branch:** `{self.branch}`\n"
                        f"**HEAD:** `{self.head}`\n"
                        f"**Commit:** `{self.commit}`\n"
                        f"**Server size:** `{humanize.naturalsize(os.path.getsize(f'./data/guilds/{ctx.guild.id}.json')) if ctx.guild else 0}`"
                        f" • `{humanize.naturalsize(total_size)}`\n"
                        f"**Uptime:** `{str(datetime.datetime.now()-self.bot.uptime).split('.')[0]}`",
            colour=self.colours.red,
            url="https://discord.gg/bPaNnxe"
        ).set_footer(
            text=f"You probably don't know what most of this means - "
                 f"If you do know what this means, you can become a programmer of {self.bot.user.name} and other bots at https://discord.gg/bPaNnxe",
            icon_url=self.bot.user.avatar.url
        ))

    @commands.command()
    @commands.is_owner()
    async def git(self, ctx):
        m = await ctx.send(embed=loading_embed)
        for r in [834127343206400021, 834148997324472391, 834127343533555713, 834127343525822474, 834127343244673055, 834139266921267211]:  # 834127343576023130
            await m.add_reaction(self.bot.get_emoji(r))

        gc = {
            "commit": 834127343525822474,
            "pull": 834148997324472391,
            "merge": 834127343533555713,
            "push": 834127343244673055,
            "fetch": 834127343206400021,
            "fork": 834127343576023130,
            "reload": 834139266921267211
        }

        self.head = str(subprocess.check_output(["git", "rev-parse", "HEAD"]))[2:-3]
        self.branch = str(subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]))[2:-3]
        self.commit = str(subprocess.check_output(["git", "show-branch", self.branch]))[(5+(len(self.branch))):-3]
        self.url = str(subprocess.check_output(["git", "config", "--get", "remote.origin.url"]))[2:-3]
        while True:
            await m.edit(embed=discord.Embed(
                title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                description=f"Current version for `{self.url.split('/')[-2]}/{self.url.split('/')[-1]}`\n"
                            f"**Branch:** `{self.branch}`\n"
                            f"**HEAD:** `{self.head}`\n"
                            f"**Commit:** `{self.commit}`\n\n"
                            f"{self.bot.get_emoji(gc['fetch'])} **Fetch** latest commit\n"
                            f"{self.bot.get_emoji(gc['pull'])} **Pull** fetched version\n"
                            f"{self.bot.get_emoji(gc['merge'])} **Merge** with current version\n"
                            f"{self.bot.get_emoji(gc['commit'])} **Commit** current code\n"
                            f"{self.bot.get_emoji(gc['push'])} **Push** current commit\n\n"
                            f"{self.bot.get_emoji(gc['reload'])} **PM2 reload**",
                colour=self.colours.green
            ))
            try:
                reaction = await ctx.bot.wait_for("reaction_add", timeout=60, check=lambda _, user: user == ctx.author)
            except asyncio.TimeoutError:
                break

            try:
                await m.remove_reaction(reaction[0].emoji, ctx.author)
            except Exception as e:
                print(e)

            if reaction is None:
                break
            elif reaction[0].emoji.name == "Fetch":
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['fetch'])} Fetch\n\n>>> Fetching",
                    colour=self.colours.green
                ))
                out = subprocess.run(["git", "fetch"], stdout=subprocess.PIPE)
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['fetch'])} Fetch\n\n>>> "
                                f"{'Fetched successfully' if out.returncode == 0 else 'Exited with code `' + str(out.returncode) +'`'}",
                    colour=self.colours.green
                ))
                await asyncio.sleep(3)
            elif reaction[0].emoji.name == "Pull":
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['pull'])} Pull\n\n>>> Pulling",
                    colour=self.colours.green
                ))
                out = subprocess.run(["git", "pull"], stdout=subprocess.PIPE)
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['pull'])} Pull\n\n>>> {'Pulled successfully' if out.returncode == 0 else 'Exited with code `' + str(out.returncode) +'`'}",
                    colour=self.colours.green
                ))
                await asyncio.sleep(3)
            elif reaction[0].emoji.name == "Merge":
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['merge'])} Merge\n\n>>> Merging",
                    colour=self.colours.green
                ))
                out = subprocess.run(["git", "merge"], stdout=subprocess.PIPE)
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['merge'])} Merge\n\n>>> "
                                f"{'Merged successfully' if out.returncode == 0 else 'Exited with code `' + str(out.returncode) +'`'}",
                    colour=self.colours.green
                ))
                await asyncio.sleep(3)
            elif reaction[0].emoji.name == "Commit":
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['commit'])} Commit\n\n>>> Enter a commit message",
                    colour=self.colours.green
                ))
                try:
                    message = await ctx.bot.wait_for("message", timeout=60, check=lambda message: message.author.id == ctx.author.id)
                except asyncio.TimeoutError:
                    break

                try:
                    await message.delete()
                except discord.HTTPException:
                    pass
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['commit'])} Commit\n\n>>> Committing",
                    colour=self.colours.green
                ))
                out = subprocess.run(["git", "commit", "-am", f'"{message.content}"'], stdout=subprocess.PIPE)
                backn = "\n"
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['commit'])} Commit\n\n>>> "
                                f"{f'Committed successfully with message:{backn} {message.content}' if out.returncode == 0 else 'Exited with code `' + str(out.returncode) +'`'}",
                    colour=self.colours.green
                ))
                await asyncio.sleep(3)
            elif reaction[0].emoji.name == "Push":
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['push'])} Push\n\n>>> Pushing",
                    colour=self.colours.green
                ))
                out = subprocess.run(["git", "push"], stdout=subprocess.PIPE)
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['push'])} Push\n\n>>> "
                                f"{'Pushed successfully' if out.returncode == 0 else 'Exited with code `' + str(out.returncode) +'`'}",
                    colour=self.colours.green
                ))
                await asyncio.sleep(3)
            elif reaction[0].emoji.name == "reload":
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['reload'])} PM2 Reload\n\n>>> Reloading",
                    colour=self.colours.green
                ))
                try:
                    out = subprocess.run(["pm2", "reload", "0"], stdout=subprocess.PIPE).returncode
                except FileNotFoundError:
                    out = 1
                await m.edit(embed=discord.Embed(
                    title=f"{self.bot.get_emoji(gc['fork'])} Git Controls",
                    description=f"{self.bot.get_emoji(gc['reload'])} PM2 Reload\n\n>>> "
                                f"{'Reloaded successfully' if out == -2 else 'Exited with code `' + str(out) +'`'}",
                    colour=self.colours.green
                ))
                return

    @commands.command()
    async def usage(self, ctx):
        m = await ctx.send(embed=loading_embed)
        cpu = psutil.getloadavg()
        cpu = round(sum(cpu) / len(cpu) / psutil.cpu_count(), 2)
        mem = round((psutil.virtual_memory().used/psutil.virtual_memory().total)*100, 2)
        temp, count = 0, 0
        try:
            sensors = psutil.sensors_temperatures()
        except AttributeError:
            sensors = []
        for sensor in sensors:
            for each in sensors[sensor]:
                temp += each.current
                count += 1
        tempav = round(temp/count, 2)
        swap = round(psutil.swap_memory().percent, 2)
        disk = psutil.disk_usage('/').percent

        await m.edit(embed=discord.Embed(
            title="Usage statistics",
            description=f"**Server time:** {self.handlers.strf(datetime.datetime.now())}\n"
                        f"**CPU:** {cpu}%\n"
                        f"**Memory:** {mem}%\n"
                        f"**Swap:** {swap}%\n"
                        f"**Disk:** {disk}%\n"
                        f"**Temperature:** {tempav}°c",
            color=self.colours.green
        ))

def setup(bot):
    bot.add_cog(Git(bot))


__author__ = "Jake Nunemaker"
__copyright__ = "Copyright 2020, National Renewable Energy Laboratory"
__maintainer__ = "Jake Nunemaker"
__email__ = "Jake.Nunemaker@nrel.gov"

from copy import deepcopy
from itertools import product

import pytest

from wisdem.orbit.phases.design import OffshoreSubstationDesign

base = {
    "site": {"depth": 30},
    "plant": {"num_turbines": 50},
    "turbine": {"turbine_rating": 6},
    "substation_design": {},
}

@pytest.mark.parametrize(
    "depth,num_turbines,turbine_rating",
    product(range(10, 51, 10), range(3, 13, 1), range(20, 80, 10)),
)
def test_parameter_sweep(depth, num_turbines, turbine_rating):
    config = {
        "site": {"depth": depth},
        "plant": {"num_turbines": num_turbines},
        "turbine": {"turbine_rating": turbine_rating},
        "substation_design": {},
    }

    o = OffshoreSubstationDesign(config)
    o.run()

    # Check valid substructure length
    assert 10 <= o._outputs["offshore_substation_substructure"]["length"] <= 80

    # Check valid substructure mass
    assert 200 <= o._outputs["offshore_substation_substructure"]["mass"] <= 2500

    # Check valid topside mass
    assert 200 <= o._outputs["offshore_substation_topside"]["mass"] <= 5000

    # Check valid substation cost
    assert 1e6 <= o.total_cost <= 300e6

def test_oss_kwargs():
    test_kwargs = {
        "mpt_cost_rate": 13500,
        "topside_fab_cost_rate": 15500,
        "topside_design_cost": 5e6,
        "shunt_cost_rate": 40000,
        "switchgear_cost": 15e5,
        "backup_gen_cost": 2e6,
        "workspace_cost": 3e6,
        "other_ancillary_cost": 4e6,
        "topside_assembly_factor": 0.08,
        "oss_substructure_cost_rate": 7250,
        "oss_pile_cost_rate": 2500,
        "num_substations": 2,
    }

    o = OffshoreSubstationDesign(base)
    o.run()
    base_cost = o.total_cost

    for k, v in test_kwargs.items():
        config = deepcopy(base)
        config["substation_design"] = {}
        config["substation_design"][k] = v

        o = OffshoreSubstationDesign(config)
        o.run()
        cost = o.total_cost

        assert cost != base_cost


from net import AlphaZeroResNet
import torch
import chess
from input_representation import board_to_planes
from output_representation import legal_moves_to_flat_planes
from MCTS_search import MCTS
import numpy as np
import time
import pandas as pd

def get_priors(visits, legal_moves, color):
    '''
    Helper function for getting the priors which are used for training the neural network.

    Arguments:
        visits (np.array): Contains the visit counts for the children correspondig to the legal moves.
        legal_moves (list(chess.MOVE)): A list of all possible legal moves.
        color (Optional[chess.COLOR]): Either chess.WHITE or chess.BLACK.

    Return:
        (np.array): A vetor of with 4096 entries containing the probabilities according to the visit count for all legal moves.
                    See alphazero.output_representation for further explanation on this representation.
    '''
    probs = visits / np.sum(visits)
    return legal_moves_to_flat_planes(legal_moves, probs, color)

def self_play(model, expansions_per_move, device):
    '''
    This plays a game in selfplay move, using the given model and device.

    Arguments:
        model (AlphaZeroResNet): The model with which the neural network evaluation should be peformed.
        expansions_per_move (int): The number of nodes that should be expanded before the MCTS decides on a move to play.
        device (torch.device()): The device on which the neural network evaluation should be performed.

    Returns:
        states (list()): All states that were chosen by the search.
        values (np.array): The values correspondig to the states.
                            Obtained by making a list of the outcome of the game containing the values from the perspective from the player at time step t.
        priors (np.array): The priors correspondig to the states. Entries are obtained by the function get_priors().
        outcome (chess.Outcome): The outcome of the self play game.
        move_count (int): The full move count after which the game ended.
    '''
    priors = list()
    states = list()

    board = chess.Board()
    mcts = MCTS(model, expansions_per_move, device)

    # Initialization run
    chosen_child = mcts.search(board)
    state = board_to_planes(chosen_child.parent.board, chosen_child.parent.last_moves)
    states.append(state)
    priors.append(get_priors(chosen_child.parent.child_visits, chosen_child.parent.legal_moves, chosen_child.parent.color))

    for i in range(239):
        if chosen_child.board.is_game_over():
            break
        chosen_child = mcts.search(use_exisitng_node=chosen_child)
        state = board_to_planes(chosen_child.parent.board, chosen_child.parent.last_moves)
        states.append(state)
        priors.append(get_priors(chosen_child.parent.child_visits, chosen_child.parent.legal_moves, chosen_child.parent.color))

    outcome = chosen_child.board.outcome()
    print(outcome)
    if outcome is not None:
        value = 0 if outcome.winner is None else (1 if outcome.winner else -1)
    else:
        value = 0

    print(chosen_child.board)
    print(chosen_child.board.fullmove_number)

    values = np.empty((len(states),), dtype=np.float32)
    values[::2] = value
    values[1::2] = -value

    return states, np.array(values, dtype=np.float32), np.array(priors, dtype=np.float32), outcome, chosen_child.board.fullmove_number

def update_model(states, values, priors, model, optimizer, device):
    '''
    This function updates the given model, using the given optimizer and device.
    Updates are performed using the training data obtained from one self play game.

    Arguments:
        states (list()): The list of states chosen in self play.
        values (np.array): The correspondig values.
        priors (np.array): The correspondig priors.
        model (AlphaZeroResNet): The model that should be trained.
        device (torch.device()): The device the model should be trained on.
    '''
    for state, value, prior in zip(states, values, priors):
        value_prediction, prior_prediction = model(state.to(device))
        value = torch.FloatTensor([value]).to(device)
        prior = torch.FloatTensor(prior).to(device)

        value_loss = torch.pow(value_prediction - value, 2)
        policy_loss = torch.dot(prior, torch.log(prior_prediction[0]))
        loss = 0.2 * value_loss - 0.8 * policy_loss

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

for i in range(50):
    MODEL_NAME = '44f_256c_18b_trained'
    EXPANSIONS_PER_MOVE = 800
    device = torch.device('cuda:0')

    model = AlphaZeroResNet(44, 256, num_res_blocks=18)
    model.load_state_dict(torch.load('./trained_models/' + MODEL_NAME))
    model.to(device)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.02, weight_decay=0.0001, momentum=0.9)

    outcomes = list()
    times = list()
    move_counts = list()

    t0 = time.time()
    states, values, priors, outcome, move_count = self_play(model, EXPANSIONS_PER_MOVE, device)
    t1 = time.time()

    outcomes.append(outcome)
    times.append(t1-t0)
    move_counts.append(move_count)

    print(f'Time: {t1-t0}')

    update_model(states, values, priors, model, optimizer, device)

    df_old = pd.read_csv('./trained_models/training_statistics.csv')
    df_new = pd.DataFrame.from_dict({'outcome': outcomes, 'time': times, 'move_count': move_counts})
    df = pd.concat([df_old, df_new])
    df.to_csv('./trained_models/training_statistics.csv', header=True, index=False)

    torch.save(model.state_dict(), './trained_models/' + MODEL_NAME)

    print(f'No. Games played: {i + 1}')


from django.urls import path

from advertisement.views import AdvertisementCreateView, AdvertisementDetailView, AdvertisementListView, \
    AdvertisementUpdateView

urlpatterns = [
    path('list/', AdvertisementListView.as_view(), name='adv-list'),
    path('detail/<str:upc>', AdvertisementDetailView.as_view(), name='adv-detail'),
    path('update/<str:upc>/', AdvertisementUpdateView.as_view(), name='adv-update'),
    path('create/', AdvertisementCreateView.as_view(), name='adv-create'),
]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utils function to initialize all the image path before training the networks

Usage:
    from src.utils import initialize_file_path

Author:
    Aurelien Callens - 27/04/2022
"""
import os

def sorted_list_path(dirname, file_ext=".npy"):
    """Create a sorted list of all the files in the indicated repository.

    Parameters
    ----------
    dirname : str
    Filepath of the repository containing the data.
    file_ext : str, optional
    Extension of the files we want to list. The default is ".npy".

    """
    res_list = sorted(
       [
        os.path.join(dirname, fname)
        for fname in os.listdir(dirname)
        if fname.endswith(file_ext)
        ]
    )
    return(res_list)

def initialize_file_path(dir_name, split):
    """
    Create the list of image depending on the indicated split

    Parameters
    ----------
    dir_name : str
        Filepath of the repository containing the data.
    split : str
        Split

    Returns
    -------
    List with two elements: X paths and Y paths
    """
    input_dir = "./data_CNN/" + dir_name + "/" + split + "/Input/"
    target_dir = "./data_CNN/" + dir_name + "/" + split + "/Target/"

    input_img_paths = sorted_list_path(input_dir)
    target_img_paths = sorted_list_path(target_dir)
    return(input_img_paths, target_img_paths)


import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import KFold
import sqlite3
from sqlite3 import Error
import sys
def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by the db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)

    return conn

def makeDataset(conn):
    """
    Query all odds for every match from Match table an the attributes of the
    teams of the match
    :param conn: the Connection object
    :return:
    """
    cur = conn.cursor()
    cur.execute("SELECT t.home_team_goal ,t.away_team_goal,t1.buildUpPlaySpeed, t1.buildUpPlayPassing, t1.chanceCreationPassing,  t1.chanceCreationCrossing,  t1.chanceCreationShooting,  t1.defencePressure,"+
    "t1.defenceAggression,  t1.defenceTeamWidth, t2.buildUpPlaySpeed, t2.buildUpPlayPassing, t2.chanceCreationPassing,  t2.chanceCreationCrossing,  t2.chanceCreationShooting,  t2.defencePressure,  t2.defenceAggression,"+
    "t2.defenceTeamWidth,t.B365H, t.B365D, t.B365A, t.BWH, t.BWD,  t.BWA, t.IWH, t.IWD,  t.IWA,  t.LBH, t.LBD,  t.LBA  FROM [Match] t INNER JOIN "+
"(SELECT *FROM Team_Attributes ta INNER JOIN (SELECT team_api_id , MAX(date) AS MaxDateTime FROM Team_Attributes GROUP BY team_api_id) groupedtt ON ta.team_api_id = groupedtt.team_api_id AND ta.date = groupedtt.MaxDateTime ) t1 "+
 " ON t1.team_api_id=t.home_team_api_id  INNER JOIN  (SELECT *FROM Team_Attributes ta INNER JOIN (SELECT team_api_id , MAX(date) AS MaxDateTime FROM Team_Attributes GROUP BY team_api_id) groupedtt "+
"ON ta.team_api_id = groupedtt.team_api_id AND ta.date = groupedtt.MaxDateTime ) t2  ON t2.team_api_id=t.away_team_api_id "
"WHERE home_team_goal IS NOT NULL AND away_team_goal IS NOT NULL AND B365H IS NOT NULL AND B365D IS NOT NULL AND B365A IS NOT NULL AND IWH IS NOT NULL AND IWD IS NOT NULL AND IWA "+
"IS NOT NULL AND BWH IS NOT NULL AND BWD IS NOT NULL AND BWA IS NOT NULL AND LBH IS NOT NULL AND LBD IS NOT NULL AND LBA IS NOT NULL  group by t.id ")
    data = cur.fetchall()

    data=np.array(data)
    x=data[:,2:len(data[0])]
    y=data[:,0:2]
    return x,y

def multilayer_perceptron(x,goals):
    x=np.array(x)
    goals=np.array(goals)
    mean_taining_score=0
    mean_success_rate=0
    kfold = KFold(10)
    i=1
    #10-fold cross validation
    for train_index, test_index in kfold.split(x):
        x_train, x_test=x[train_index],x[test_index]
        goals_train, goals_test=goals[train_index],goals[test_index]
        d_train=[]
        #calculate the result from the score for training and testing data
        for goal in goals_train:
            if goal[0]>goal[1]:
                d_train.append('H')
            elif goal[0]<goal[1]:
                d_train.append('A')
            else :
                  d_train.append('D')

        d_test=[]
        for goal in goals_test:
            if goal[0]>goal[1]:
                d_test.append('H')
            elif goal[0]<goal[1]:
                d_test.append('A')
            else :
                d_test.append('D')

        #trasform the desired output to binary vector
        y_dense = LabelBinarizer().fit_transform(d_train)
        y_dense_test = LabelBinarizer().fit_transform(d_test)
        #train mlp
        clf = MLPClassifier(solver='sgd', alpha=1e-5,max_iter=1000,hidden_layer_sizes=(80, 40, 20), random_state=1)
        clf.fit(x_train, y_dense)
        #add the result of training score
        mean_taining_score+=clf.score(x_train, y_dense)
        #test the mlp
        y_predict=clf.predict(x_test)
        #print(y_predict)
        #print(len(x_test)," ",len(y_dense_test))
        print(i,")Successfull predictions rate",clf.score(x_test, y_dense_test))
        mean_success_rate+=clf.score(x_test, y_dense_test)
        i+=1
    mean_taining_score/=10
    mean_success_rate/=10
    mean_success_rate *=100
    print("Mean training score:", mean_taining_score)
    print("Successfull predictions mean rate", mean_success_rate,"% \n")

def main():
    np.set_printoptions(threshold=sys.maxsize)
    database = "database.sqlite"

    # create a database connection
    conn = create_connection(database)
    if conn:
        print(" making Dataset...")
        x,goals=makeDataset(conn)
        print(" training and testing multilayer perceptron...")
        multilayer_perceptron(x,goals)

if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import imageio
import os
import random as rnd
import time
import matplotlib.colors as colors
import matplotlib.lines as lines
from matplotlib import cm
from matplotlib.ticker import LinearLocator
from mpl_toolkits.mplot3d import Axes3D

def der(f, x_i):
    derf = np.zeros_like(f)
    if x_i == 'r':
        for k in range(len(f)):
            for i in range(len(f[0])):
                if i>1 and i<len(f[0])-2:
                    derf[k][i] = (f[k][i-2]-8*f[k][i-1]+8*f[k][i+1]-f[k][i+2])/(12*delta_r)
                elif i==1 or i==len(f[0])-2:
                    if i==1:
                        a = 1
                    else:
                        a = -1
                    derf[k][i] = a*(-3*f[k][i-1*a]-10*f[k][i]+18*f[k][i+1*a]-6*f[k][i+2*a]+f[k][i+3*a])/(12*delta_r)
                else:
                    if i==0:
                        a = 1
                    else:
                        a = -1
                    derf[k][i] = a*(-25*f[k][i]+48*f[k][i+1*a]-36*f[k][i+2*a]+16*f[k][i+3*a]-3*f[k][i+4*a])/(12*delta_r)
    elif x_i == 'z':
        for k in range(len(f)):
            for i in range(len(f[0])):
                if k>1 and k<len(f)-2:
                    derf[k][i] = (f[k-2][i]-8*f[k-1][i]+8*f[k+1][i]-f[k+2][i])/(12*delta_z)
                elif k==1 or k==len(f)-2:
                    if k==1:
                        a = 1
                    else:
                        a = -1
                    derf[k][i] = a*(-3*f[k-1*a][i]-10*f[k][i]+18*f[k+1*a][i]-6*f[k+2*a][i]+f[k+3*a][i])/(12*delta_z)
                else:
                    if k==0:
                        a = 1
                    else:
                        a = -1
                    derf[k][i] = a*(-25*f[k][i]+48*f[k+1*a][i]-36*f[k+2*a][i]+16*f[k+3*a][i]-3*f[k+4*a][i])/(12*delta_z)
    else:
        print('ERROR')
        print('Por favor introduzca una direccion valida')
        input()
        exit()

    return derf

x,y = np.meshgrid(np.arange(-3,3, step=0.1),np.arange(-3,3, step=0.1))
f = np.zeros_like(x)
df = np.zeros_like(x)
delta_r=0.1
delta_z=0.1
for i in range(len(f)):
    for k in range(len(f[0])):
        f[k][i] = 2*np.exp(-x[k][i]**2-y[k][i]**2)+0.6*np.sqrt(x[k][i]**2+y[k][i]**2)

#df = der(f,'z')
df = der(f,'r')
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x,y,f)
plt.show()

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x,y,df)
plt.show()

plt.plot(x[len(f[0])//2], f[len(f[0])//2],x[len(f[0])//2],df[len(f[0])//2],'--g')
plt.show()


#"Tree" "DFS"
#Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#My recursive version, DFS, O(n).
#Your runtime beats 89.53% of python submissions.
class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root: return False
        if root.left==None and root.right==None: return sum==root.val #Leaf node
        if root.left==None: return self.hasPathSum(root.right,sum-root.val) #Only right child
        if root.right==None: return self.hasPathSum(root.left,sum-root.val) #Only left child
        return self.hasPathSum(root.left,sum-root.val)  or self.hasPathSum(root.right,sum-root.val) #Two children


import math
import numpy as np
from numpy import matlib

def k__(c, sections):
    matrix = np.matlib.zeros(shape=((sections + 1), (sections + 1)))
    matrix[0, 0] = matrix[-1, -1] = 3
    matrix[1, 1] = matrix[-2, -2] = 7 + c
    matrix[1, 0] = matrix[1, 2] = matrix[-2, -1] = matrix[-2, -3] = -4
    matrix[1, 3] = matrix[-2, -4] = 1
    for _i in range(2, sections - 1):
        matrix[_i, _i] = 6 + c
        matrix[_i, _i - 2] = matrix[_i, _i + 2] = 1
        matrix[_i, _i - 1] = matrix[_i, _i + 1] = -4
    return matrix

def imext__(v, *args):
    """Descripción: *Pendiente*"""
    n1_ = v[1]
    n2_ = -v[2] + (8 * v[1])
    p1_ = v[-2]
    p2_ = (8 * v[-2]) - v[-3]
    v1 = np.append(np.insert(v, 0, (n2_, n1_)), (p1_, p2_))
    for tupl_ in args:
        if len(tupl_) == 3:
            v1[tupl_[0]] += tupl_[1] * v1[tupl_[2]]
        else:
            v1[tupl_[0]] += tupl_[1]
    return v1

def tmv__(vector_, m__, sections, v=False):
    """Descripción: *Pendiente*"""
    x = np.zeros(sections + 1)
    y = 2
    if not v:
        sums = ((1, 1), (-2, 0), (1, -1))
    else:
        sums = ((1, 2), (-2, 1), (2, -1), (-1, -2))
    for i in range(sections + 1):
        for tupl_ in sums:
            x[i] += tupl_[0] * vector_[i + y + tupl_[1]]
    z = np.dot(x, m__)
    return z

def v_maker2(dl, m__, sections):
    """Descripción: *Pendiente*"""
    vector = np.zeros(sections + 1)
    vector[0] = (dl[1] - (2 * dl[0]) + dl[1]) * m__
    vector[-1] = (dl[-2] - (2 * dl[-1]) + dl[-2]) * m__
    for i in range(1, sections):
        vector[i] = (dl[i + 1] - (2 * dl[i]) + dl[i - 1]) * m__
    return vector

def local_matrix(element):
    """Descripción: Esta función calcula y asigna los valores individuales por elemento, que después serán usados para
    crear la matrix y vector generales de la estructura."""
    # vector = element.vector

    if element.type is not None:
        area = element.type.area
    else:
        print("No type assigned")
        return False

    long = element.vector.long
    sections = element.sections
    poisson = element.poisson
    elasticity = element.type.e
    izz = element.type.izz
    iyy = element.type.iyy
    delta_x = long / sections
    mzz = (elasticity * izz) / delta_x ** 2
    myy = (elasticity * iyy) / delta_x ** 2
    vzz = (elasticity * izz) / (2 * delta_x ** 3)
    vyy = (elasticity * iyy) / (2 * delta_x ** 3)
    axial = (elasticity * area) / long
    torsion = ((elasticity / (2 * (1 + poisson))) * element.type.j) / long

    f_a = (element.loads.kv * element.type.a1 * delta_x ** 4) / \
          (1000 * elasticity * izz)
    f_b = (element.loads.kh * element.type.a2 * delta_x ** 4) / \
          (1000 * elasticity * iyy)
    element.data.f_a = f_a

    if element.data.new_kzz is None:
        element.data.kzz = k__(f_a, sections)
    else:
        element.data.kzz = element.data.new_kzz

    element.data.kyy = k__(f_b, sections)
    element.data.mzz = mzz
    element.data.myy = myy
    element.data.vzz = vzz
    element.data.vyy = vyy

    d1zz = imext__(np.dot(element.data.kzz.I,
                          -(np.insert(np.zeros(sections), 0, 3))).A1, (0, -6, 2))
    d2zz = imext__(np.dot(element.data.kzz.I,
                          -(np.append(np.zeros(sections), 3))).A1, (-1, -6, -3))
    te1zz = imext__(np.dot(element.data.kzz.I,
                           -(np.insert(np.zeros(sections), 1, 2 * delta_x))).A1,
                    (0, 8 * delta_x), (1, 2 * delta_x))
    te2zz = imext__(np.dot(element.data.kzz.I,
                           -(np.insert(np.zeros(sections), -1, 2 * delta_x))).A1,
                    (-1, 8 * delta_x), (-2, 2 * delta_x))
    d1yy = imext__(np.dot(element.data.kyy.I,
                          -(np.insert(np.zeros(sections), 0, 3))).A1, (0, -6, 2))
    d2yy = imext__(np.dot(element.data.kyy.I,
                          -(np.append(np.zeros(sections), 3))).A1, (-1, -6, -3))
    te1yy = imext__(np.dot(element.data.kyy.I,
                           -(np.insert(np.zeros(sections), 1, 2 * delta_x))).A1,
                    (0, 8 * delta_x), (1, 2 * delta_x))
    te2yy = imext__(np.dot(element.data.kyy.I,
                           -(np.insert(np.zeros(sections), -1, 2 * delta_x))).A1,
                    (-1, 8 * delta_x), (-2, 2 * delta_x))

    m1zz = tmv__(d1zz, mzz, sections)
    m2zz = tmv__(d2zz, mzz, sections)
    tm1zz = tmv__(te1zz, mzz, sections)
    tm2zz = tmv__(te2zz, mzz, sections)

    m1yy = tmv__(d1yy, myy, sections)
    m2yy = tmv__(d2yy, myy, sections)
    tm1yy = tmv__(te1yy, myy, sections)
    tm2yy = tmv__(te2yy, myy, sections)

    v1zz = tmv__(d1zz, vzz, sections, v=True)
    v2zz = tmv__(d2zz, vzz, sections, v=True)
    tv1zz = tmv__(te1zz, vzz, sections, v=True)
    tv2zz = tmv__(te2zz, vzz, sections, v=True)

    v1yy = tmv__(d1yy, vyy, sections, v=True)
    v2yy = tmv__(d2yy, vyy, sections, v=True)
    tv1yy = tmv__(te1yy, vyy, sections, v=True)
    tv2yy = tmv__(te2yy, vyy, sections, v=True)

    keb = np.matlib.zeros(shape=(12, 12))
    # region one
    keb[0, 0] = axial
    keb[1, 1] = - v1zz[0]
    keb[1, 5] = - tv1zz[0]
    keb[2, 2] = - v1yy[0]
    keb[2, 4] = tv1yy[0]
    keb[3, 3] = torsion
    keb[4, 2] = - m1yy[0]
    keb[4, 4] = tm1yy[0]
    keb[5, 1] = m1zz[0]
    keb[5, 5] = tm1zz[0]
    # region two
    keb[6, 0] = - axial
    keb[7, 1] = v1zz[sections]
    keb[7, 5] = tv1zz[sections]
    keb[8, 2] = v1yy[sections]
    keb[8, 4] = - tv1yy[sections]
    keb[9, 3] = - torsion
    keb[10, 2] = m1yy[sections]
    keb[10, 4] = - tm1yy[sections]
    keb[11, 1] = - m1zz[sections]
    keb[11, 5] = - tm1zz[sections]
    # region three
    keb[0, 6] = - axial
    keb[1, 7] = - v2zz[0]
    keb[1, 11] = tv2zz[0]
    keb[2, 8] = - v2yy[0]
    keb[2, 10] = - tv2yy[0]
    keb[3, 9] = - torsion
    keb[4, 8] = - m2yy[0]
    keb[4, 10] = - tm2yy[0]
    keb[5, 7] = m2zz[0]
    keb[5, 11] = - tm2zz[0]
    # region four
    keb[6, 6] = axial
    keb[7, 7] = v2zz[sections]
    keb[7, 11] = - tv2zz[sections]
    keb[8, 8] = v2yy[sections]
    keb[8, 10] = tv2yy[sections]
    keb[9, 9] = torsion
    keb[10, 8] = m2yy[sections]
    keb[10, 10] = tm2yy[sections]
    keb[11, 7] = - m2zz[sections]
    keb[11, 11] = tm2zz[sections]
    # rotational matrix
    cos_nu = math.cos(math.radians(element.vector.nu))
    sin_nu = math.sin(math.radians(element.vector.nu))
    cos_lm = math.cos(math.radians(element.vector.lm))
    sin_lm = math.sin(math.radians(element.vector.lm))

    def __tr_filler(_tr):
        """Tr matrix filler function"""
        for __j in [0, 3, 6, 9]:
            _tr[__j + 1, __j] = sin_lm
            _tr[__j + 1, __j + 1] = cos_lm
            _tr[__j, __j] = cos_nu * cos_lm
            _tr[__j, __j + 1] = -cos_nu * sin_lm
            _tr[__j, __j + 2] = -sin_nu
            _tr[__j + 2, __j] = sin_nu * cos_lm
            _tr[__j + 2, __j + 1] = -sin_nu * sin_lm
            _tr[__j + 2, __j + 2] = cos_nu
        return _tr

    tr = __tr_filler(np.matlib.zeros(shape=(12, 12)))
    kebg = np.dot(np.dot(tr, keb), tr.T)
    element.data.tr = tr
    element.data.keb = keb
    element.data.kebg = kebg
    pp = area * (element.type.p_mat / 10000)
    element.data.pp_scc = ((pp * (long / 100)) / sections) * sin_lm
    p_axial = ((- sin_lm *
                pp * (long / 100)) / 2) + \
              ((- math.sin(math.radians(element.loads.aw)) * element.loads.wy *
                (long / 100)) / 2)
    p_scc_y = ((pp * (long / 100) * cos_lm) / sections) * \
              ((delta_x ** 3) / (elasticity * izz))
    p_scc_z = 0
    w_scc_y = ((((element.loads.wy * long) / 100) *
                math.cos(math.radians(element.loads.aw))) / sections) * \
              ((delta_x ** 3) / (elasticity * izz))
    w_scc_z = ((element.loads.wz * (long / 100)) /
               sections) * ((delta_x ** 3) / (elasticity * iyy))
    try:
        if element.type.armour is True:
            p_elem = pp * (long / 100)
            vplocal_y = np.zeros(sections + 1)
            vplocal_z = np.zeros(sections + 1)
            p_vertical = -(cos_lm * p_elem) / 2
    except AttributeError:
        setattr(element.type, 'armour', False)
    finally:
        if element.type.armour is False:
            vplocal_y = np.insert(np.append(np.full((sections - 1,), (p_scc_y + w_scc_y)), 0), 0, 0)
            vplocal_z = np.insert(np.append(np.full((sections - 1,), (p_scc_z + w_scc_z)), 0), 0, 0)

    dlzz = np.dot(element.data.kyy.I, -vplocal_z).A1
    dlyy = np.dot(element.data.kzz.I, -vplocal_y).A1
    element.data.dlzz = dlzz
    element.data.dlyy = dlyy
    mdlyy = v_maker2(dlyy, mzz, sections)
    mdlzz = v_maker2(dlzz, myy, sections)
    element.data.mdlyy = mdlyy
    element.data.mdlzz = mdlzz

    def v_maker3(dl, v__, vplocal, i__):
        """Descripción: *Pendiente*"""
        vector = np.empty(sections + 1)
        vector[0] = ((dl[2] - (2 * dl[1]) + (2 * dl[1]) - ((8 * dl[1]) - dl[2])) * v__) + \
                    ((vplocal[1] / 2) * (elasticity * i__ / (delta_x ** 3)))
        vector[1] = (dl[3] - (2 * dl[2]) + (2 * dl[0]) - dl[1]) * v__
        vector[-2] = (dl[-2] - (2 * dl[-1]) + (2 * dl[-3]) - dl[-4]) * v__
        vector[-1] = ((((8 * dl[-2]) - dl[-3]) - (2 * dl[-2]) + (2 * dl[-2]) - dl[-3]) * v__) - \
                     ((vplocal[1] / 2) * (elasticity * i__ / (delta_x ** 3)))
        for i in range(2, sections - 1):
            vector[i] = (dl[i + 2] - (2 * dl[i + 1]) + (2 * dl[i - 1]) - dl[i - 2]) * v__
        return vector

    vdlyy = v_maker3(dlyy, vzz, vplocal_y, izz)
    vdlzz = v_maker3(dlzz, vyy, vplocal_z, iyy)

    pcu_local = [0] * 12
    if element.type.armour is True:
        pcu_local[0] = p_axial
        pcu_local[1] = p_vertical
        pcu_local[6] = p_axial
        pcu_local[7] = p_vertical
    else:
        pcu_local[0] = p_axial
        pcu_local[1] = - vdlyy[0]
        pcu_local[2] = - vdlzz[0]
        pcu_local[4] = - mdlzz[0]
        pcu_local[5] = mdlyy[0]
        pcu_local[6] = p_axial
        pcu_local[7] = vdlyy[sections]
        pcu_local[8] = vdlzz[sections]
        pcu_local[10] = mdlzz[sections]
        pcu_local[11] = - mdlyy[sections]

    element.data.pculocal = pcu_local
    element.data.pc_ = np.dot(tr, np.asarray(pcu_local)).A1

    __dict = locals()
    for value in __dict:
        setattr(element.data, str(value), __dict[value])

    return element


def english_cypher(s: str, n:int) -> int:
    eng_alpha = [chr(i) for i in range(ord('a'), ord('z')+1)]
    eng_alpha_upper = [chr(i) for i in range(ord('A'), ord('Z')+1)]
    cyphered = []
    for i in s:
        if i in eng_alpha:
            cyphered.append((eng_alpha.index(i) + n) % 26)
        else:
            cyphered.append(i)

    cyphered1 = []
    for i in cyphered:
        if str(i).isdigit():
            cyphered1.append(eng_alpha[i])
        else:
            cyphered1.append(i)
    for i in cyphered1:
        if i.isupper():
            cyphered1[cyphered1.index(i)] = (eng_alpha_upper.index(i) + n) % 26

    for i in cyphered1:
        if str(i).isdigit():
            cyphered1[cyphered1.index(i)] = eng_alpha_upper[i]

    return ''.join(cyphered1)

s = input()

a = [(len(i.strip(',!.?"'))) for i in s.split()]
lst = []
for i in a:
    lst.append((english_cypher(s, i)))
for i in range(len(lst)):
    print(lst[i].split()[i], end=' ')


import pandas as pd

class XlsxValidator:
    """
    XlsxValidator is for comparing the results of a previous model run
    to the results of a current model run.
    """

    def compare_expected_to_actual(self, expected_xlsx, actual_module_type_operation_list, validation_output_xlsx):
        """
        This compares the expected costs as calculated by a prior model run
        with the actual results from a current model run.

        It compares the results row by row and prints any differences.

        Parameters
        ----------
        expected_xlsx : str
            The absolute filename of the expected output .xlsx file.

        actual_module_type_operation_list : str
            The module_type_operation_list as returned by a subclass of
            XlsxManagerRunner.

        validation_output_xlsx : str
            The absolute pathname to the output file with the comparison
            results.

        Returns
        -------
        bool
            True if the expected and actual results are equal. It returns
            False otherwise.
        """
        # First, make the list of dictionaries into a dataframe, and drop
        # the raw_cost and raw_cost_total_or_per_turbine columns.
        actual_df = pd.DataFrame(actual_module_type_operation_list)
        actual_df.drop(['raw_cost', 'raw_cost_total_or_per_turbine'], axis=1, inplace=True)
        expected_df = pd.read_excel(expected_xlsx, 'costs_by_module_type_operation', engine='openpyxl')
        #expected_df = expected_df.dropna(inplace=True, how='all')
        expected_df.rename(columns={
            'Project ID with serial': 'project_id_with_serial',
            'Number of turbines': 'num_turbines',
            'Turbine rating MW': 'turbine_rating_MW',
            'Module': 'module',
            'Operation ID': 'operation_id',
            'Type of cost': 'type_of_cost',
            'Cost per turbine': 'cost_per_turbine',
            'Cost per project': 'cost_per_project',
            'USD/kW per project': 'usd_per_kw_per_project'
        }, inplace=True)

        cost_per_project_actual = actual_df[
            ['cost_per_project', 'project_id_with_serial', 'module', 'operation_id', 'type_of_cost']]
        cost_per_project_expected = expected_df[
            ['cost_per_project', 'project_id_with_serial', 'module', 'operation_id', 'type_of_cost']]

        comparison = cost_per_project_actual.merge(
            cost_per_project_expected,
            on=['project_id_with_serial', 'module', 'operation_id', 'type_of_cost'])

        comparison.rename(columns={'cost_per_project_x': 'cost_per_project_actual',
                                    'cost_per_project_y': 'cost_per_project_expected'}, inplace=True)

        comparison['difference_validation'] = comparison['cost_per_project_actual'] - comparison['cost_per_project_expected']

        # Regardless of the outcome, write the end result of the comparison
        # to the validation output file.
        columns_for_comparison_output = [
            'project_id_with_serial',
            'module',
            'operation_id',
            'type_of_cost',
            'cost_per_project_actual',
            'cost_per_project_expected',
            'difference_validation'
        ]
        comparison.to_excel(validation_output_xlsx, index=False, columns=columns_for_comparison_output)

        # If the comparison dataframe is empty, that means there are no common
        # projects in the expected data that match the actual data.
        if len(comparison) < 1:
            print('=' * 80)
            print('Validation error: There are no common projects between actual and expected data.')
            print('=' * 80)
            return False

        # Find all rows where the difference is unequal to 0. These are rows
        # that failed validation. Note that, after the join, the rows may be
        # in a different order than the originals.
        #
        # Round the difference to a given number of decimal places.
        failed_rows = comparison[comparison['difference_validation'].round(decimals=4) != 0]

        if len(failed_rows) > 0:
            print('=' * 80)
            print('The following rows failed validation:')
            print(failed_rows)
            print('=' * 80)
            return False
        else:
            return True


from unittest import mock

import pytest
from confluent_kafka import Consumer
from streaming_data_types.fbschemas.forwarder_config_update_rf5k.UpdateType import (
    UpdateType,
)
from streaming_data_types.forwarder_config_update_rf5k import (
    Protocol,
    StreamInfo,
    serialise_rf5k,
)

from forwarder.common import Channel, EpicsProtocol, config_change_to_command_type
from forwarder.configuration_store import ConfigurationStore
from forwarder.parse_config_update import parse_config_update
from tests.kafka.fake_producer import FakeProducer

DUMMY_UPDATE_HANDLER = None

CHANNELS_TO_STORE = {
    Channel("channel1", EpicsProtocol.PVA, "topic1", "f142"): DUMMY_UPDATE_HANDLER,
    Channel("channel2", EpicsProtocol.CA, "topic2", "tdct"): DUMMY_UPDATE_HANDLER,
}

STREAMS_TO_RETRIEVE = [
    StreamInfo(
        channel.name,
        channel.schema,
        channel.output_topic,
        Protocol.Protocol.PVA
        if channel.protocol == EpicsProtocol.PVA
        else Protocol.Protocol.CA,
    )
    for channel in CHANNELS_TO_STORE.keys()
]

class FakeKafkaMessage:
    def __init__(self, message):
        self._message = message

    def value(self):
        return self._message

def assert_stored_channel_correct(outputted_channel):
    # Will only be found if key exists and as the key is the channel
    # it will only match if the values are exactly the same.
    assert outputted_channel in CHANNELS_TO_STORE

def test_when_multiple_pvs_dumped_config_contains_all_pv_details():
    producer = FakeProducer()
    store = ConfigurationStore(producer, consumer=None, topic="store_topic")

    store.save_configuration(CHANNELS_TO_STORE)

    stored_message = parse_config_update(producer.published_payloads[-1])  # type: ignore
    stored_channels = stored_message.channels

    assert_stored_channel_correct(stored_channels[0])  # type: ignore
    assert_stored_channel_correct(stored_channels[1])  # type: ignore

def test_when_no_pvs_stored_message_type_is_remove_all():
    producer = FakeProducer()
    store = ConfigurationStore(producer, consumer=None, topic="store_topic")

    store.save_configuration({})

    stored_message = parse_config_update(producer.published_payloads[-1])  # type: ignore

    assert stored_message.channels is None
    assert (
        stored_message.command_type
        == config_change_to_command_type[UpdateType.REMOVEALL]
    )

def test_retrieving_stored_info_with_no_pvs_gets_message_without_streams():
    mock_consumer = mock.create_autospec(Consumer)
    mock_consumer.get_watermark_offsets.return_value = (0, 100)
    message = serialise_rf5k(UpdateType.REMOVEALL, [])
    mock_consumer.consume.return_value = [FakeKafkaMessage(message)]
    store = ConfigurationStore(
        producer=None, consumer=mock_consumer, topic="store_topic"
    )

    config = parse_config_update(store.retrieve_configuration())
    assert config.channels is None

def test_retrieving_stored_info_with_multiple_pvs_gets_streams():
    mock_consumer = mock.create_autospec(Consumer)
    mock_consumer.get_watermark_offsets.return_value = (0, 100)
    message = serialise_rf5k(UpdateType.ADD, STREAMS_TO_RETRIEVE)
    mock_consumer.consume.return_value = [FakeKafkaMessage(message)]
    store = ConfigurationStore(
        producer=None, consumer=mock_consumer, topic="store_topic"
    )

    config = parse_config_update(store.retrieve_configuration())
    channels = config.channels

    assert_stored_channel_correct(channels[0])  # type: ignore
    assert_stored_channel_correct(channels[1])  # type: ignore

def test_retrieve_config_find_valid_message_amongst_junk():
    message = serialise_rf5k(UpdateType.ADD, STREAMS_TO_RETRIEVE)
    messages_in_storage_topic = [
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 1 ::")],
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 2 ::")],
        [FakeKafkaMessage(message)],
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 3 ::")],
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 4 ::")],
    ]  # type: ignore

    mock_consumer = mock.create_autospec(Consumer)
    mock_consumer.get_watermark_offsets.return_value = (
        0,
        len(messages_in_storage_topic),
    )

    mock_consumer.consume.side_effect = messages_in_storage_topic

    store = ConfigurationStore(
        producer=None, consumer=mock_consumer, topic="store_topic"
    )
    config = parse_config_update(store.retrieve_configuration())
    channels = config.channels
    assert_stored_channel_correct(channels[0])  # type: ignore
    assert_stored_channel_correct(channels[1])  # type: ignore

def test_retrieve_config_with_only_junk_as_message_in_storage_topic():
    messages_in_storage_topic = [
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 1 ::")],
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 2 ::")],
        [FakeKafkaMessage(":: SOME JUNK MESSAGE 3 ::")],
    ]  # type: ignore
    mock_consumer = mock.create_autospec(Consumer)
    mock_consumer.get_watermark_offsets.return_value = (
        0,
        len(messages_in_storage_topic),
    )
    mock_consumer.consume.side_effect = messages_in_storage_topic

    store = ConfigurationStore(
        producer=None, consumer=mock_consumer, topic="store_topic"
    )
    with pytest.raises(RuntimeError):
        store.retrieve_configuration()

def test_retrieve_config_with_empty_storage_topic():
    messages_in_storage_topic = []  # type: ignore
    mock_consumer = mock.create_autospec(Consumer)
    mock_consumer.get_watermark_offsets.return_value = (
        0,
        len(messages_in_storage_topic),
    )
    mock_consumer.consume.side_effect = messages_in_storage_topic

    store = ConfigurationStore(
        producer=None, consumer=mock_consumer, topic="store_topic"
    )
    with pytest.raises(RuntimeError):
        store.retrieve_configuration()


#%%
import os

#%%
os.mkdir("Map uit python")
# %%
os.getcwd()
# %%
files_folders = os.listdir()
# %%
os.makedirs("map_1/map_2/map_3")
# %%
os.remove("export_autos.csv")
# %%
os.removedirs("map_1/map_2/map_3",)
# %%


import numpy

def apply(a1, a2, output=None):
    return numpy.subtract(a1, a2, out=output)

def baseline(a):
    n = a.shape[0]
    s = a.shape[1:]

    baseline = numpy.zeros(shape=a.shape)
    for i in range(n):
        apply(a[i],a[n-1], output=baseline[i])

    return baseline

def pairwise(a, invert=False):
    n = a.shape[0]

    pairwise = numpy.zeros(shape=a.shape)
    if not invert:
        for i in range(1,n):
            apply(a[i],a[i-1], output=pairwise[i])
    else:
        for i in range(1,n):
            apply(a[i-1],a[i], output=pairwise[i])

    return pairwise