#!/usr/bin/env python
"""
Unimodal distribution (Aniso Shielding Lineshape Inversion)
===========================================================
"""
# %%
# The following example demonstrates the statistical learning based determination of
# the nuclear shielding tensor parameters from a one-dimensional cross-section of a
# magic-angle flipping (MAF) spectrum. In this example, we use a synthetic MAF
# lineshape from a unimodal tensor distribution.
#
# Before getting started
# ----------------------
#
# Import all relevant packages.
import csdmpy as cp
import matplotlib.pyplot as plt
import numpy as np

from mrinversion.kernel.nmr import ShieldingPALineshape
from mrinversion.linear_model import SmoothLasso, SmoothLassoCV, TSVDCompression
from mrinversion.utils import get_polar_grids

# Setup for the matplotlib figures

# function for 2D x-y plot.
def plot2D(ax, csdm_object, title=""):
    # convert the dimension coordinates of the csdm_object from Hz to pmm.
    _ = [item.to("ppm", "nmr_frequency_ratio") for item in csdm_object.dimensions]

    levels = (np.arange(9) + 1) / 10
    ax.contourf(csdm_object, cmap="gist_ncar", levels=levels)
    ax.grid(None)
    ax.set_title(title)
    get_polar_grids(ax)
    ax.set_aspect("equal")

# %%
# Dataset setup
# -------------
#
# Import the dataset
# ''''''''''''''''''
#
# Load the dataset. Here, we import the dataset as a CSDM data-object.

# the 1D MAF cross-section data in csdm format
domain = "https://sandbox.zenodo.org/record/1065347/files"
filename = f"{domain}/puxfgdh25rru1q3li124anylkgup8rdp.csdf"
data_object = cp.load(filename)

# convert the data dimension from `Hz` to `ppm`.
data_object.dimensions[0].to("ppm", "nmr_frequency_ratio")

# %%
# The variable ``data_object`` holds the 1D MAF cross-section. For comparison, let's
# also import the true tensor parameter distribution from which the synthetic 1D pure
# anisotropic MAF cross-section line-shape is simulated.
datafile = f"{domain}/s5wpm26w4cv3w64qjhouqu458ch4z0nd.csdf"
true_data_object = cp.load(datafile)

# %%
# The plot of the 1D MAF cross-section along with the 2D true tensor parameter
# distribution of the synthetic dataset is shown below.

# the plot of the 1D MAF cross-section dataset.
_, ax = plt.subplots(1, 2, figsize=(9, 3.5), subplot_kw={"projection": "csdm"})
ax[0].plot(data_object)
ax[0].invert_xaxis()

# the plot of the true tensor distribution.
plot2D(ax[1], true_data_object, title="True distribution")
plt.tight_layout()
plt.show()

# %%
# Linear Inversion setup
# ----------------------
#
# Dimension setup
# '''''''''''''''
#
# **Anisotropic-dimension:** The dimension of the dataset that holds the pure
# anisotropic frequency contributions, which in this case, is the only dimension.
anisotropic_dimension = data_object.dimensions[0]

# %%
# **x-y dimensions:** The two inverse dimensions corresponding to the `x` and
# `y`-axis of the `x`-`y` grid.
inverse_dimension = [
    cp.LinearDimension(count=25, increment="370 Hz", label="x"),  # the `x`-dimension.
    cp.LinearDimension(count=25, increment="370 Hz", label="y"),  # the `y`-dimension.
]

# %%
# Generating the kernel
# '''''''''''''''''''''
#
# For MAF datasets, the line-shape kernel corresponds to the pure nuclear shielding
# anisotropy line-shapes. Use the
# :class:`~mrinversion.kernel.nmr.ShieldingPALineshape` class to generate a
# shielding line-shape kernel.
lineshape = ShieldingPALineshape(
    anisotropic_dimension=anisotropic_dimension,
    inverse_dimension=inverse_dimension,
    channel="29Si",
    magnetic_flux_density="9.4 T",
    rotor_angle="90 deg",
    rotor_frequency="14 kHz",
    number_of_sidebands=4,
)

# %%
# Here, ``lineshape`` is an instance of the
# :class:`~mrinversion.kernel.nmr.ShieldingPALineshape` class. The required
# arguments of this class are the `anisotropic_dimension`, `inverse_dimension`, and
# `channel`. We have already defined the first two arguments in the previous
# sub-section. The value of the `channel` argument is the nucleus observed in the MAF
# experiment. In this example, this value is '29Si'.
# The remaining arguments, such as the `magnetic_flux_density`, `rotor_angle`,
# and `rotor_frequency`, are set to match the conditions under which the spectrum
# was acquired. The value of the `number_of_sidebands` argument is the number of
# sidebands calculated for each line-shape within the kernel.
#
# Once the ShieldingPALineshape instance is created, use the
# :meth:`~mrinversion.kernel.nmr.ShieldingPALineshape.kernel` method of the
# instance to generate the MAF line-shape kernel.
K = lineshape.kernel(supersampling=1)

# %%
# Data Compression
# ''''''''''''''''
#
# Data compression is optional but recommended. It may reduce the size of the
# inverse problem and, thus, further computation time.
new_system = TSVDCompression(K, data_object)
compressed_K = new_system.compressed_K
compressed_s = new_system.compressed_s

print(f"truncation_index = {new_system.truncation_index}")

# %%
# Solving the inverse problem
# ---------------------------
#
# Smooth-LASSO problem
# ''''''''''''''''''''
#
# Solve the smooth-lasso problem. You may choose to skip this step and proceed to the
# statistical learning method. Usually, the statistical learning method is a
# time-consuming process that solves the smooth-lasso problem over a range of
# predefined hyperparameters.
# If you are unsure what range of hyperparameters to use, you can use this step for
# a quick look into the possible solution by giving a guess value for the :math:`\alpha`
# and :math:`\lambda` hyperparameters, and then decide on the hyperparameters range
# accordingly.

# guess alpha and lambda values.
s_lasso = SmoothLasso(alpha=5e-5, lambda1=5e-6, inverse_dimension=inverse_dimension)
s_lasso.fit(K=compressed_K, s=compressed_s)
f_sol = s_lasso.f

# %%
# Here, ``f_sol`` is the solution corresponding to hyperparameters
# :math:`\alpha=5\times10^{-5}` and :math:`\lambda=5\times 10^{-6}`. The plot of this
# solution is
_, ax = plt.subplots(1, 2, figsize=(9, 3.5), subplot_kw={"projection": "csdm"})

# the plot of the guess tensor distribution solution.
plot2D(ax[0], f_sol / f_sol.max(), title="Guess distribution")

# the plot of the true tensor distribution.
plot2D(ax[1], true_data_object, title="True distribution")
plt.tight_layout()
plt.show()

# %%
# Predicted spectrum
# ''''''''''''''''''
#
# You may also evaluate the predicted spectrum from the above solution following
residuals = s_lasso.residuals(K, data_object)
predicted_spectrum = data_object - residuals

plt.figure(figsize=(4, 3))
plt.subplot(projection="csdm")
plt.plot(data_object, color="black", label="spectrum")  # the original spectrum
plt.plot(predicted_spectrum, color="red", label="prediction")  # the predicted spectrum
plt.gca().invert_xaxis()
plt.legend()
plt.tight_layout()
plt.show()

# %%
# As you can see from the predicted spectrum, our guess isn't far from the optimum
# hyperparameters. Let's create a search grid about the guess hyperparameters and run
# a cross-validation method for selection.
#
# Statistical learning of the tensors
# -----------------------------------
#
# Smooth LASSO cross-validation
# '''''''''''''''''''''''''''''
#
# Create a guess range of values for the :math:`\alpha` and :math:`\lambda`
# hyperparameters.
# The following code generates a range of :math:`\lambda` and :math:`\alpha` values
# that are uniformly sampled on the log scale.
lambdas = 10 ** (-5.2 - 1 * (np.arange(6) / 5))
alphas = 10 ** (-4 - 2 * (np.arange(6) / 5))

# set up cross validation smooth lasso method
s_lasso_cv = SmoothLassoCV(
    alphas=alphas,
    lambdas=lambdas,
    inverse_dimension=inverse_dimension,
    sigma=0.005,
    folds=10,
)
# run the fit using the compressed kernel and compressed signal.
s_lasso_cv.fit(compressed_K, compressed_s)

# %%
# The optimum hyper-parameters
# ''''''''''''''''''''''''''''
#
# Use the :attr:`~mrinversion.linear_model.SmoothLassoCV.hyperparameters` attribute of
# the instance for the optimum hyper-parameters, :math:`\alpha` and :math:`\lambda`,
# determined from the cross-validation.
print(s_lasso_cv.hyperparameters)

# %%
# The cross-validation surface
# ''''''''''''''''''''''''''''
#
# Optionally, you may want to visualize the cross-validation error curve/surface. Use
# the :attr:`~mrinversion.linear_model.SmoothLassoCV.cross_validation_curve` attribute
# of the instance, as follows. The cross-validation metric is the mean square error
# (MSE).
cv_curve = s_lasso_cv.cross_validation_curve

# plot of the cross-validation curve
plt.figure(figsize=(5, 3.5))
ax = plt.subplot(projection="csdm")
ax.contour(np.log10(s_lasso_cv.cross_validation_curve), levels=25)
ax.scatter(
    -np.log10(s_lasso_cv.hyperparameters["alpha"]),
    -np.log10(s_lasso_cv.hyperparameters["lambda"]),
    marker="x",
    color="k",
)
plt.tight_layout(pad=0.5)
plt.show()

# %%
# The optimum solution
# ''''''''''''''''''''
#
# The :attr:`~mrinversion.linear_model.SmoothLassoCV.f` attribute of the instance holds
# the solution.
f_sol = s_lasso_cv.f

# %%
# The corresponding plot of the solution, along with the true tensor distribution, is
# shown below.
_, ax = plt.subplots(1, 2, figsize=(9, 3.5), subplot_kw={"projection": "csdm"})

# the plot of the tensor distribution solution.
plot2D(ax[0], f_sol / f_sol.max(), title="Optimum distribution")

# the plot of the true tensor distribution.
plot2D(ax[1], true_data_object, title="True distribution")
plt.tight_layout()
plt.show()


#  Copyright 2013 – present by the SalishSeaCast Project contributors
#  and The University of British Columbia
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
"""
"""
import os
from collections import namedtuple

import matplotlib.pyplot as plt
import numpy as np
import pytz
from matplotlib.dates import DateFormatter
from salishsea_tools import data_tools, places, nc_tools, teos_tools

import nowcast.figures.website_theme
from nowcast.figures import shared

def make_figure(
    node_name,
    grid_T_hr,
    dev_grid_T_hr,
    timezone,
    mesh_mask,
    dev_mesh_mask,
    figsize=(8, 10),
    theme=nowcast.figures.website_theme,
):
    """Plot the temperature and salinity time series of observations and model
    results at an ONC VENUS node.

    :arg str node_name: Ocean Networks Canada (ONC) VENUS node name;
                        must be a key in
                        :py:obj:`salishsea_tools.places.PLACES`.

    :arg grid_T_hr: Hourly tracer results dataset from production NEMO run.
    :type grid_T_hr: :class:`netCDF4.Dataset`

    :arg dev_grid_T_hr: Hourly tracer results dataset from development NEMO run.
    :type dev_grid_T_hr: :class:`netCDF4.Dataset`

    :arg str timezone: Timezone to use for display of model results.

    :arg mesh_mask: NEMO mesh mask for production NEMO run.
    :type mesh_mask: :class:`netCDF4.Dataset`

    :arg dev_mesh_mask: NEMO mesh mask for development NEMO run.
    :type dev_mesh_mask: :class:`netCDF4.Dataset`

    :arg 2-tuple figsize: Figure size (width, height) in inches.

    :arg theme: Module-like object that defines the style elements for the
                figure. See :py:mod:`nowcast.figures.website_theme` for an
                example.

    :returns: :py:class:`matplotlib.figure.Figure`
    """
    plot_data = _prep_plot_data(
        node_name, grid_T_hr, dev_grid_T_hr, timezone, mesh_mask, dev_mesh_mask
    )
    fig, (ax_sal, ax_temp) = _prep_fig_axes(figsize, theme)
    _plot_salinity_time_series(ax_sal, node_name, plot_data, theme)
    _plot_temperature_time_series(ax_temp, plot_data, timezone, theme)
    _attribution_text(ax_temp, theme)
    return fig

def _prep_plot_data(
    place, grid_T_hr, dev_grid_T_hr, timezone, mesh_mask, dev_mesh_mask
):
    try:
        j, i = places.PLACES[place]["NEMO grid ji"]
    except KeyError as e:
        raise KeyError(
            "place name or info key not found in salishsea_tools.places.PLACES: {e}"
        )
    node_depth = places.PLACES[place]["depth"]
    station_code = places.PLACES[place]["ONC stationCode"]
    # Production model results
    model_time = nc_tools.timestamp(
        grid_T_hr, range(grid_T_hr.variables["time_counter"].size)
    )
    try:
        # NEMO-3.4 mesh mask
        gdept = mesh_mask.variables["gdept"]
    except KeyError:
        # NEMO-3.6 mesh mask
        gdept = mesh_mask.variables["gdept_0"]
    tracer_depths = gdept[..., j, i][0]
    tracer_mask = mesh_mask.variables["tmask"][..., j, i][0]
    try:
        # NEMO-3.4 mesh mask
        gdepw = mesh_mask.variables["gdepw"]
    except KeyError:
        # NEMO-3.6 mesh mask
        gdepw = mesh_mask.variables["gdepw_0"]
    w_depths = gdepw[..., j, i][0]
    salinity_profiles = grid_T_hr.variables["vosaline"][..., j, i]
    temperature_profiles = grid_T_hr.variables["votemper"][..., j, i]
    model_salinity_ts = _calc_results_time_series(
        salinity_profiles,
        model_time,
        node_depth,
        timezone,
        tracer_depths,
        tracer_mask,
        w_depths,
    )
    model_temperature_ts = _calc_results_time_series(
        temperature_profiles,
        model_time,
        node_depth,
        timezone,
        tracer_depths,
        tracer_mask,
        w_depths,
    )
    # Development model results
    dev_model_time = nc_tools.timestamp(
        dev_grid_T_hr, range(grid_T_hr.variables["time_counter"].size)
    )
    tracer_depths = dev_mesh_mask.variables["gdept_0"][..., j, i][0]
    tracer_mask = dev_mesh_mask.variables["tmask"][..., j, i][0]
    w_depths = dev_mesh_mask.variables["gdepw_0"][..., j, i][0]
    salinity_profiles = dev_grid_T_hr.variables["vosaline"][..., j, i]
    temperature_profiles = dev_grid_T_hr.variables["votemper"][..., j, i]
    dev_model_salinity_ts = _calc_results_time_series(
        salinity_profiles,
        dev_model_time,
        node_depth,
        timezone,
        tracer_depths,
        tracer_mask,
        w_depths,
    )
    dev_model_temperature_ts = _calc_results_time_series(
        temperature_profiles,
        dev_model_time,
        node_depth,
        timezone,
        tracer_depths,
        tracer_mask,
        w_depths,
    )
    # Observations
    onc_data = data_tools.get_onc_data(
        "scalardata",
        "getByStation",
        os.environ["ONC_USER_TOKEN"],
        station=station_code,
        deviceCategory="CTD",
        sensors="salinity,temperature",
        dateFrom=data_tools.onc_datetime(model_time[0], "utc"),
        dateTo=data_tools.onc_datetime(model_time[-1], "utc"),
    )
    plot_data = namedtuple(
        "PlotData",
        "model_salinity_ts, model_temperature_ts, "
        "dev_model_salinity_ts, dev_model_temperature_ts, "
        "ctd_data",
    )
    return plot_data(
        model_salinity_ts=model_salinity_ts,
        model_temperature_ts=model_temperature_ts,
        dev_model_salinity_ts=dev_model_salinity_ts,
        dev_model_temperature_ts=dev_model_temperature_ts,
        ctd_data=data_tools.onc_json_to_dataset(onc_data),
    )

def _calc_results_time_series(
    tracer,
    model_time,
    node_depth,
    timezone,
    tracer_depths,
    tracer_mask,
    w_depths,
    psu_to_teos=False,
):
    time_series = namedtuple("TimeSeries", "var, time")
    if psu_to_teos:
        var = teos_tools.psu_teos(
            [
                shared.interpolate_tracer_to_depths(
                    tracer[i, :], tracer_depths, node_depth, tracer_mask, w_depths
                )
                for i in range(tracer.shape[0])
            ]
        )
    else:
        var = [
            shared.interpolate_tracer_to_depths(
                tracer[i, :], tracer_depths, node_depth, tracer_mask, w_depths
            )
            for i in range(tracer.shape[0])
        ]
    return time_series(var=var, time=[t.to(timezone) for t in model_time])

def _prep_fig_axes(figsize, theme):
    fig, (ax_sal, ax_temp) = plt.subplots(
        2,
        1,
        figsize=figsize,
        sharex=True,
        facecolor=theme.COLOURS["figure"]["facecolor"],
    )
    fig.autofmt_xdate()
    ax_sal.set_facecolor(theme.COLOURS["axes"]["background"])
    ax_temp.set_facecolor(theme.COLOURS["axes"]["background"])
    return fig, (ax_sal, ax_temp)

def _plot_salinity_time_series(ax, place, plot_data, theme):
    ctd_data = plot_data.ctd_data
    qaqc_mask = ctd_data.salinity.attrs["qaqcFlag"] == 1
    ax.plot(
        ctd_data.salinity.sampleTime[qaqc_mask],
        ctd_data.salinity[qaqc_mask],
        linewidth=2,
        label="Observations",
        color=theme.COLOURS["time series"]["VENUS CTD salinity"],
    )
    ax.plot(
        [t.datetime for t in plot_data.model_salinity_ts.time],
        plot_data.model_salinity_ts.var,
        linewidth=2,
        label="Model",
        color=theme.COLOURS["time series"]["VENUS node model salinity"],
        alpha=0.7,
    )
    ax.plot(
        [t.datetime for t in plot_data.dev_model_salinity_ts.time],
        plot_data.dev_model_salinity_ts.var,
        linewidth=2,
        label="Dev Model",
        color=theme.COLOURS["time series"]["VENUS node dev model salinity"],
        alpha=0.5,
    )
    _salinity_axis_labels(ax, place, plot_data, theme)

def _salinity_axis_labels(ax, place, plot_data, theme):
    first_model_day = plot_data.model_salinity_ts.time[0]
    last_model_day = plot_data.model_salinity_ts.time[-1]
    title_dates = first_model_day.format("DD-MMM-YYYY")
    if first_model_day.day != last_model_day.day:
        title_dates = " and ".join((title_dates, last_model_day.format("DD-MMM-YYYY")))
    ax.set_title(
        f'VENUS {place.title()} {places.PLACES[place]["depth"]}m {title_dates}',
        fontproperties=theme.FONTS["axes title"],
        color=theme.COLOURS["text"]["axes title"],
    )
    ax.set_xlim(
        plot_data.model_salinity_ts.time[0].datetime,
        plot_data.model_salinity_ts.time[-1].datetime,
    )
    ax.set_ylabel(
        "Salinity [g/kg]",
        fontproperties=theme.FONTS["axis"],
        color=theme.COLOURS["text"]["axis"],
    )
    ymin, ymax = ax.get_ylim()
    ax.set_ylim(np.floor(ymin) - 1, np.ceil(ymax) + 1)
    ax.legend(loc="best")
    ax.grid(axis="both")
    theme.set_axis_colors(ax)

def _plot_temperature_time_series(ax, plot_data, timezone, theme):
    ctd_data = plot_data.ctd_data
    qaqc_mask = ctd_data.salinity.attrs["qaqcFlag"] == 1
    ax.plot(
        ctd_data.temperature.sampleTime[qaqc_mask],
        ctd_data.temperature[qaqc_mask],
        linewidth=2,
        label="Observations",
        color=theme.COLOURS["time series"]["VENUS CTD temperature"],
    )
    ax.plot(
        [t.datetime for t in plot_data.model_temperature_ts.time],
        plot_data.model_temperature_ts.var,
        linewidth=2,
        label="Model",
        color=theme.COLOURS["time series"]["VENUS node model temperature"],
        alpha=0.7,
    )
    ax.plot(
        [t.datetime for t in plot_data.dev_model_temperature_ts.time],
        plot_data.dev_model_temperature_ts.var,
        linewidth=2,
        label="Dev Model",
        color=theme.COLOURS["time series"]["VENUS node dev model temperature"],
        alpha=0.5,
    )
    tzname = plot_data.model_temperature_ts.time[0].datetime.tzname()
    _temperature_axis_labels(ax, plot_data, timezone, tzname, theme)

def _temperature_axis_labels(ax, plot_data, timezone, tzname, theme):
    ax.set_xlabel(
        f"Date and Time [{tzname}]",
        fontproperties=theme.FONTS["axis"],
        color=theme.COLOURS["text"]["axis"],
    )
    ax.set_xlim(
        plot_data.model_temperature_ts.time[0].datetime,
        plot_data.model_temperature_ts.time[-1].datetime,
    )
    ax.xaxis.set_major_formatter(
        DateFormatter("%d-%b %H:%M", tz=pytz.timezone(timezone))
    )
    ax.set_ylabel(
        "Temperature [°C]",
        fontproperties=theme.FONTS["axis"],
        color=theme.COLOURS["text"]["axis"],
    )
    ymin, ymax = ax.get_ylim()
    ax.set_ylim(np.floor(ymin) - 1, np.ceil(ymax) + 1)
    ax.legend(loc="best")
    ax.grid(axis="both")
    theme.set_axis_colors(ax)

def _attribution_text(ax, theme):
    ax.text(
        1,
        -0.35,
        "Observations from Ocean Networks Canada",
        horizontalalignment="right",
        verticalalignment="top",
        transform=ax.transAxes,
        fontproperties=theme.FONTS["figure annotation small"],
        color=theme.COLOURS["text"]["figure annotation"],
    )


from __future__ import absolute_import

import os
import shutil
import sys
from distutils.dir_util import copy_tree
from zipfile import ZipFile

import requests

WORKER_URL = "https://github.com/ianfab/fishtest/archive/master.zip"

def restart(worker_dir):
    """Restarts the worker, using the same arguments"""
    args = sys.argv[:]
    args.insert(0, sys.executable)
    if sys.platform == "win32":
        args = ['"{}"'.format(arg) for arg in args]

    os.chdir(worker_dir)
    os.execv(sys.executable, args)  # This does not return !

def update():
    worker_dir = os.path.dirname(os.path.realpath(__file__))
    update_dir = os.path.join(worker_dir, "update")
    if not os.path.exists(update_dir):
        os.makedirs(update_dir)

    worker_zip = os.path.join(update_dir, "wk.zip")
    with open(worker_zip, "wb+") as f:
        f.write(requests.get(WORKER_URL).content)

    zip_file = ZipFile(worker_zip)
    zip_file.extractall(update_dir)
    zip_file.close()
    prefix = os.path.commonprefix([n.filename for n in zip_file.infolist()])
    worker_src = os.path.join(update_dir, os.path.join(prefix, "worker"))
    copy_tree(worker_src, worker_dir)
    # the worker runs games from the "testing" folder so change the folder
    os.chdir(worker_dir)
    shutil.rmtree(update_dir)
    testing_dir = os.path.join(worker_dir, "testing")
    if os.path.exists(testing_dir):
        shutil.rmtree(testing_dir)

    restart(worker_dir)


from __future__ import division
import pickle
import io
import os, sys
import csv
import re
import nltk
from string import punctuation

def removePunctuation(text):
    '''
    Removes punctuation, changes to lower case and strips leading and trailing
    spaces.

    Args:
        text (str): Input string.

    Returns:
        (str): The cleaned up string.
    '''
    text.strip()
    return ''.join(c for c in text.encode('ascii', 'ignore') if c not in punctuation or c in ['#','@','.','\n'])

def serialize(obj, ser_filename, isSerializingList=True):
    '''
    Saves a python object to disk.

    If the object being dealt with is a list, the contents of thenew list get
    added to the existing serialized list. Otherwise, the new object ovewrites
    the old one.

    Args:
        obj: Object to save.
        ser_filename: Filename to save object with on disk.
        isSerializingList: Boolean denoting whether object to be saved is a list
                            or not.
    '''
    if(isSerializingList):
        # If pre-existing serialization, get its list representation and add new one to it
        if(os.path.isfile(ser_filename)):
            stored_list = unserialize(ser_filename)
            stored_list.extend(obj)
            f = open(ser_filename, 'wb')
            pickle.dump(stored_list, f)
            f.close()
        else:
            f = open(ser_filename, 'wb')
            pickle.dump(obj, f)
            f.close()
    else:
        f = open(ser_filename, 'wb')
        pickle.dump(obj, f)
        f.close()

def unserialize(ser_filename):
    '''
    Loads a python object from disk.

    Returns:
        The python object at the specified path or None if none is found.
    '''
    if(not os.path.isfile(ser_filename)):
        return None
    else:
        f = open(ser_filename, 'rb')
        obj = pickle.load(f)
        f.close()
        return obj

def map_node_to_dataset_id(content_embedding_data):
    '''
    This functions returns a dictionary which maps a graph node id (which is
    just its position in a list) to the contract or supplier id for that node.
    i.e. The dictionary is of the form {0:'<ID_1>', 1:'<ID_1>', ... , <NODE_N>:'<ID_N>'}

    @param adjmat adjacency matrix as produced by the "adjacency_matrix(similarity_matrix, threshold)"
    function and seen in the corresponding output csv.
    @param content_embedding_data content embeddings as produced by either the "get_train_embeddings()"
    or "get_test_embeddings()" and the corresponding csv files.
    @return mapping dict
    '''
    mapping = {}
    for idx in range(len(content_embedding_data)):
        mapping[idx] = content_embedding_data[idx]['id']

    return mapping


__author__ = 'mesh'
import re
import pymorphy2

morph = pymorphy2.MorphAnalyzer()

# text = open('input.txt', encoding='utf8').read()
text = 'Это зависит от обстоятельств. ' \
       'Вася много работает на заводе.'

def tokzr_WORD(txt): return (re.findall(r'(?ms)\W*(\w+)', txt))  # split words
def tokzr_SENT(txt): return (re.findall(r'(?ms)\s*(.*?(?:\.|\?|!))', txt))  # split sentences
s = 0
sentences = tokzr_SENT(text)
for sentence in sentences:
    w = 0
    words = tokzr_WORD(sentence)
    for word in words:
        # print(s, w, word)
        pos = morph.parse(word)
        # print(pos)
        for guess in pos:
            if 'VERB' in guess.tag:
                print(guess)

        w += 1
    s += 1


'''给出 n 代表生成括号的对数，请你写出一个函数，使其能够生成所有可能的并且有效的括号组合。
例如，给出 n = 3，生成结果为：
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
'''
'''采用回溯法，当'('的数量小于n时，向S中添加；当')'小于'('的数量时，S中添加')' '''
class Solution:
    def generateParenthesis(self,n):
        list1 = list()
        self.backtracks(n,list1, S='', l=0, r =0)
        return list1

    def backtracks(self,n,list1,S, l,r):
        if l < n:
            self.backtracks(n,list1,S+'(',l+1,r)
        if r < l :
            self.backtracks(n,list1,S+')',l,r+1)
        if len(S) == 2*n:
            list1.append(S)
            return

if __name__ == '__main__':
    s = Solution()
    print(s.generateParenthesis(3))


import argparse
import sys
import subprocess
import os

parser = argparse.ArgumentParser()
parser.add_argument('inputfile', type=str, help='input file')
parser.add_argument('folder_output', type=str, help='folder output')
parser.add_argument('max_peptide', type=int, help='how much peptides u want to use in the clustring')
args = parser.parse_args()

inputfile = args.inputfile
outputfolder = args.folder_output.rstrip('/') + '/'
max_peptide = args.max_peptide #how much peptides u want to use in the clustring
seqs = "seqs/"
threshhold = 0.5 # identity
n = 2
l = 1

outputfilename = inputfile[:inputfile.find('.')]
while '/' in outputfilename:
  outputfilename = outputfilename[outputfilename.find('/')+1:]
print(outputfilename)
foldername = inputfile[:inputfile.find('/' + outputfilename)]
while '/' in foldername:
  foldername = foldername[foldername.find('/')+1:]

### clustring
outputfile = outputfolder + outputfilename
if not os.path.exists(outputfolder): os.mkdir(outputfolder)
cmd = "cd-hit -c " + str(threshhold) + " -n " + str(n) + " -l " + str(l) + ' -i ' + inputfile + " -o " + outputfile
subprocess.call(cmd, shell=True)

#what seqs in each cluster
if not os.path.exists(outputfolder + seqs): os.mkdir(outputfolder + seqs)

header_prefix_to_seq = {} #short header to seq
header_prefix_to_header = {} #short header to header
with open(inputfile[:-len("TrimmedCysLoop.fas")] + "fs", 'r') as f:
  for line in f:
     if line.startswith('>'):
       header_prefix = line[:line.find("Len")]  # e.g >448_Length_8_Repeats_309.9084062045127_Type_8
       header_prefix_to_header[header_prefix] = line
       header_prefix_to_seq[header_prefix] = ""
     else:
       header_prefix_to_seq[header_prefix] += line

with open(outputfile + ".clstr", 'r') as clstrf:
  cluster_size = 0
  for line in clstrf:
    if line.startswith('>') or line == '':
      if cluster_size:
        filename = foldername + "_Members_" + str(pepcount) + "_ClusterSize_" + str(cluster_size) + filename
        with open(outputfolder + seqs + filename, 'w') as f:
          f.write(data)
      filename = '_' + line.lstrip('>').rstrip().replace(' ','_') + ".fas" # e.g ">Cluster 0" -> "_Cluster_0.fs" # +
      data = ""
      cluster_size = 0
      pepcount = 0
    else:
      if pepcount == max_peptide:
        continue
      header_prefix = line[line.find('>'):line.find("Len")] # e.g 0	14aa, >1423_Length_14_Repe... *
      pepcount += 1
      header = header_prefix_to_header[header_prefix]
      data +=  header + header_prefix_to_seq[header_prefix]
      cluster_size += float(header.split('_')[4])  # ">6365_Length_12_Repeats_9.15083876588128_Type_12" -> 9.15083876588128


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 4, kernel_size=5)  # Conv2d(in_channels, out_channels, kernel_size, ...)
        self.pool = nn.MaxPool2d(2, 2)  # MaxPool2d(kernel_size, stride=None, padding=0, ...)
        self.conv2 = nn.Conv2d(4, 4, kernel_size=5)
        self.fc = nn.Linear(4 * 4 * 4, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        # 28 * 28 -> 4 * 24 * 24 -> 4 * 12 * 12
        x = self.pool(F.relu(self.conv2(x)))
        # 4 * 12 * 12 -> 8 * 8 * 8 -> 8 * 4 * 4
        x = x.view(-1, 4 * 4 * 4)
        x = self.fc(x)
        return x

if __name__ == '__main__':
    net = Net()
    input_ = torch.randn(10, 1, 28, 28)
    # print(input_)
    out = net(input_)
    print(out)


# Your code here
import os

def finder(files, queries):
    """
    YOUR CODE HERE
    """
    mapping = {}

    for filename in files:
        basename = os.path.basename(os.path.normpath(filename))
        if basename in mapping:
            mapping[basename].append(filename)
        else:
            mapping[basename] = [filename]

    result = []

    for query in queries:
        if query in mapping:
            result += mapping[query]

    return result

if __name__ == "__main__":
    files = [
        '/bin/foo',
        '/bin/bar',
        '/usr/bin/baz'
    ]
    queries = [
        "foo",
        "qux",
        "baz"
    ]
    print(finder(files, queries))


def main():
	"""main method asks for user input and calls the
	grammar checker method with user input"""
	init_sentence = input("Please insert a sentence: ")
	sentence = init_sentence.split(" ")

	follow = isGrammarlyCorrect(sentence)
	print(follow)
	return follow

def isGrammarlyCorrect(s):
	"""This method recieves a list and compares it with the
	possible combinations to form a sentence. if no possible rule is
	followed or the list has less than 3 words, the method returns False.
	else, returns true."""
	person_word = ['Nao', 'Shila']
	position_word = ['above', 'below', 'left', 'right']
	object_words = ['car', 'person', 'dog', 'diamond']
	behaviour_words = ['recognise', 'detect', 'avoid', 'replace']
	pronoun_words = ['I', 'you', 'they']
	texture_words = ['smooth', 'dimpled', 'rough']

	if (len(s) < 3):
		return False

	if(s[0] in person_word):

		if(s[1] in behaviour_words):

			if(s[2] in object_words):
				return True

			elif(s[2] in texture_words and s[3] in object_words):
				return True

			elif(s[2] in position_word):
				return True

			else:
				return False

		else:
			return False

	elif(s[0] in pronoun_words):

		if(s[1] in behaviour_words):

			if(s[2] in position_word or s[2] in object_words):
				return True

			else:
				return False

		else:
			return False

	else:
		return False

if __name__ == '__main__':
	main()


import gym
import os
import custom_ant
from PlotCallBack import PlotCallBack
import numpy as np
import matplotlib.pyplot as plt

from stable_baselines3 import A2C
from stable_baselines3.common.evaluation import evaluate_policy

from stable_baselines.bench import Monitor
from stable_baselines3.common import results_plotter
from stable_baselines3.common.results_plotter import load_results, ts2xy
from stable_baselines3.common.callbacks import BaseCallback

## User Parameters ##
ENV_ID='Block-v2'
TOTAL_TIMESTEPS = 5e5
TRAIN_MODE='DEFAULT'   # Choose from OPTUNA, DEFAULT, or BOTH
EVALUATE = True     # False will skip the evaluation step
#####################

bag_dir = 'bag/'
os.makedirs(bag_dir, exist_ok=True)
scores = []
results = []

def train_model(optuna, env, bag_dir):

  if optuna:
    print("Training with Optuna-optimized hyperparameters")
    prefix = "optuna/"
    log_dir = bag_dir + prefix
    env, callback = setup_callback(log_dir, env)
    model = A2C('MlpPolicy', env,
          gamma = 0.9949651748245363,
          n_steps = 2,
          ent_coef = 1.4874340288559667e-06,
          max_grad_norm = 0.7428181598534858,
          learning_rate = 4.7667230267782784e-05,
          gae_lambda = 0.9868067509887242,
          verbose=0,

          )
  else:
    print("Training with stable-baselines3 default hyperparameters")
    prefix = "default/"
    log_dir = bag_dir + prefix
    env, callback = setup_callback(log_dir, env)
    model = A2C('MlpPolicy', env,
          gamma = 0.99,
          n_steps = 5,
          ent_coef = 0.0,
          max_grad_norm = 0.5,
          learning_rate = 0.0007,
          gae_lambda = 1.0,
          verbose=0
    )

  # Train the agent
  model.learn(total_timesteps=int(TOTAL_TIMESTEPS), callback=callback)
  best_model = A2C.load(os.getcwd() + "/" + log_dir + "/best_model", verbose=1)

  if EVALUATE: eval(best_model, prefix)
  env.close()
  return

# Evaluate the trained agent
def eval(model, prefix):
  print("Evaluating the best " + prefix + " model")
  mean_reward, std_reward = evaluate_policy(model, env, n_eval_episodes=10)
  scores.append(prefix + ": mean_reward = " + str(mean_reward) + " +/- " + str(std_reward))

def setup_callback(log_dir, env):
  if os.path.isfile(log_dir + 'monitor.csv'):
    print("A monitor.csv already exists. Deleting it.")
    os.remove(log_dir + 'monitor.csv')
    if not os.path.isfile(log_dir + 'monitor.csv'):
      print("Old monitor.csv successfully deleted")
  os.makedirs(log_dir, exist_ok=True)
  env = Monitor(env, log_dir)
  callback = PlotCallBack(check_freq=1000, log_dir=log_dir)
  return env, callback

legend_names = []

if TRAIN_MODE != 'OPTUNA':
  results.append(bag_dir + "default/")
  env = gym.make(ENV_ID)
  train_model(False, env, bag_dir)
  legend_names.append('Default')
if TRAIN_MODE != 'DEFAULT':
  results.append(bag_dir + "optuna/")
  env = gym.make(ENV_ID)
  train_model(True, env, bag_dir)
  legend_names.append('Optuna')

for score in scores:
  print(score)

results_plotter.plot_results(results, TOTAL_TIMESTEPS, results_plotter.X_TIMESTEPS, ENV_ID)
plt.legend(legend_names)
plt.show()


from datetime import datetime, timedelta
from dateutil import tz
import re
import time
import yaml

DATE_PATTERN = r'(^\d{4}-\d{2}-\d{2}).(\d{2}:\d{2}:\d{2}).*'
DATETIME_PATTERN = r'(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}).*'
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'

def get_quarter_daterange(year, quarter):
    # Q1 starts in April, start of tax year
    num_firebreak = quarter - 1
    start_week_num = quarter * 13 + num_firebreak

    if start_week_num > 52:
        start_week_num -= 53
        year += 1

    start_week = "{}-W{}".format(year, start_week_num)
    start_date = datetime.strptime(start_week + '-1', "%Y-W%W-%w")

    end_week_num = start_week_num + 12
    if end_week_num > 52:
        end_week_num -= 53
        year += 1

    end_week = "{}-W{}".format(year, end_week_num)

    end_date = datetime.strptime(end_week + '-5', "%Y-W%W-%w")

    return start_date, end_date

def get_bi_weekly_sprint_dates(q_start, q_end):
    sprints = []
    sprint_start = q_start
    while sprint_start < q_end:
        sprint_end = sprint_start + timedelta(weeks=2) - timedelta(seconds=1)
        sprint = {
            'started_on': str(sprint_start),
            'ended_on': str(sprint_end)
        }
        sprints.append(sprint)
        sprint_start += timedelta(weeks=2)

    last_sprint = sprints[-1]
    if last_sprint['ended_on'] > str(q_end):
        last_sprint['ended_on'] = str(q_end - timedelta(seconds=1))

    return sprints

def get_datetime(datetime_str):
    matched_datetime = re.search(DATETIME_PATTERN, datetime_str)
    if matched_datetime:
        return datetime.strptime(matched_datetime.group(1), DATETIME_FORMAT)

def get_date_string(date_and_time):
    matched_date = re.search(DATE_PATTERN, str(date_and_time))

    if matched_date:
        date_str = matched_date.group(1)
        if matched_date.group(2) == "23:00:00":
            utc_time = datetime.strptime(f"{date_str}T{matched_date.group(2)}", DATETIME_FORMAT)

            from_zone = tz.gettz('UTC')
            to_zone = tz.gettz('Europe/London')

            # Tell the datetime object that it's in UTC time zone since
            # datetime objects are 'naive' by default
            utc = utc_time.replace(tzinfo=from_zone)

            # Convert time zone
            london = utc.astimezone(to_zone)

            matched_date = re.search(DATE_PATTERN, str(london))
            date_str = matched_date.group(1)

        return date_str

def get_time_diff(started_at, ended_at=None):
    def count_days_on_weekends(start, end):
        weekend_count = 0
        while start <= end:
            if start.weekday() in {5, 6}:
                weekend_count += 1
            start += timedelta(days=1)
        return weekend_count

    if ended_at:
        # if start or end is on a weekend should the day be pushed to Friday / Monday?
        # As otherwise that day will be lost as it lands on the weekend
        start = get_datetime(started_at) if type(started_at) is str else started_at
        end = get_datetime(ended_at) if type(ended_at) is str else ended_at
        weekend_days = count_days_on_weekends(start, end)
        return end - start - timedelta(days=weekend_days)

def get_process_cycle_efficiency(cycle_time, blocked_time=None):
    if blocked_time:
        return (cycle_time - blocked_time) / cycle_time

    return 1  # no blocked time so 100% efficient

class Base:
    def get_metrics(self, last_num_weeks=None):
        pass


#task21 = TaskClass.Task(20,4,[40, 45, 32, 14],[5, 9, 8, 7])
#taskL.append(task21)

def argmax(T,Solution,C):
    max_t=0
    max_sum=0
    for t in T:
        S=0
        for i in Solution[t]:
            S=S+C[i]
        if S>max_sum:
            max_sum=S
            max_t=t

    return max_t

def knapsack_dylp(A,B,C):
   T={0:0} #Hash: biggest value of set for weight - {weight:value}
   Solution={0:[]}
   #Cicle for all targes $\frac{c_i}{a_i}$
   for i in range(0,A.shape[0]):
   #    print C[i],"/",A[i],":",
       T_old=dict(T)  #copy $T_{k-1}$ into $T_{old}$
  #     print T
       #Cicle for all partial summ
       for x in T_old:
           if (x+A[i])<=B:
               if (not i in Solution[x]):
                if ( (x+A[i] not in T)  or (T[x+A[i]]<T_old[x]+C[i])):
                   T[x+A[i]]=T_old[x]+C[i]
                   Solution[x+A[i]]=Solution[x]+[i]
 #      print "    -->",T
   ResultCost = max(T.values())
   Result = Solution[argmax(T,Solution,C)]
   return (Result, ResultCost)


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

def _i(prefix, output_string, postfix="\n"):
  """ 行先頭に "ok" 等の文字が出力されないようにフォーマットする
  """
  return "\n".join([prefix + line for line in output_string.split("\n")]) + "\n"

class Tap(object):
  def __init__(self, writer):
    self.writer = writer
    self.test_count = 0
    self.succeeded = 0
    self.failed = 0
    self.errored = 0
    self.not_ok_list = []
    self.current = None

  def total_elapsed(self):
    return self.succeeded + self.failed + self.errored

  def debug(self, debug_str):
    writer = self.writer
    writer.write(_i("  # ", unicode(debug_str)))

  def start(self, scenario):
    self.current = scenario

  def succeed(self):
    writer = self.writer

    self.succeeded += 1
    writer.write("ok {0} - {1}\n".format(
      self.total_elapsed(), self.current.doc))

  def fail(self, exception):
    """
    @param exception AssertionFailed
    """
    writer = self.writer

    self.failed += 1
    self.not_ok_list.append(self.total_elapsed())
    writer.write("not ok {0} - {1}\n".format(
      self.total_elapsed(), self.current.doc))
    writer.write("  ------------------------------------------------------------\n")
    writer.write(_i("  ", "filename: {0}".format(self.current.setting.filename)))
    writer.write(_i("  ", "action_index: {0}".format(exception.action_index)))
    writer.write(_i("  ", "assert_index: {0}".format(exception.assert_index)))
    writer.write(_i("  ", "assertion: {0}".format(exception.assertion)))
    writer.write(_i("  ", "compared: "))
    for i, items in enumerate(exception.compared):
      for j, item in enumerate(items):
        writer.write(_i(u"    ", "{0}-{1}: {2}".format(i, j, item)))
    writer.write("  ------------------------------------------------------------\n")

  def error(self, exception):
    """
    @param exception ActionException
    """
    writer = self.writer

    self.errored += 1
    self.not_ok_list.append(self.total_elapsed())
    writer.write("not ok {0} - {1}\n".format(
      self.total_elapsed(), self.current.doc))
    writer.write("  ------------------------------------------------------------\n")
    writer.write(_i("  ", "filename: {0}".format(self.current.setting.filename)))
    writer.write(_i("  ", "action_index: {0}".format(exception.action_index)))
    writer.write(_i("  ", exception.stack_trace))
    writer.write("  ------------------------------------------------------------\n")

  def start_test(self, test_count):
    writer = self.writer

    self.test_count = test_count
    writer.write("1..{0}\n".format(test_count))

  def end_test(self, elapsed_time):
    writer = self.writer

    writer.write("\n")
    if self.not_ok_list:
      writer.write("FAILED tests {0}\n".format(
        ", ".join([str(e) for e in self.not_ok_list])))
      writer.write("Failed {0}/{1} tests, {2:.2f}% ok ({3:.3f} sec elapsed)\n".format(
        len(self.not_ok_list), self.test_count,
        float(self.succeeded) / self.test_count * 100,
        elapsed_time))
    else:
      if self.test_count == 1:
        writer.write("1 test succeeded ({0:.3f} sec elapsed)\n".format(
          elapsed_time))
      else:
        writer.write("{0} tests all succeeded ({1:.3f} sec elapsed)\n".format(
          self.test_count, elapsed_time))


#!/bin/python
print("Mary had a little lamb.")
print("Its fleece was white as %s." % 'snow')
print("And everywhere that Mary went.")
print("." * 10)  # what'd that do?

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

# if we use comma at the end of 'end6', then it will not go to new line.
print(end1 + end2 + end3 + end4 + end5 + end6, end='$', sep='-')
print(end7 + end8 + end9 + end10 + end11 + end12)
print("\n \n")

# Look for python inbuilt new line character.
""" \n  is used for new line in python"""


import pandas as pd
import xml.etree.ElementTree as ET
import requests
import re
from requests.exceptions import ConnectionError, HTTPError

def get_ndec(strfloat):
    tmplist = strfloat.strip().split('.')
    return 0 if len(tmplist) == 1 else len(tmplist[1])

class Config:

    XML_URI = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml"
    CUBE_NS = "{http://www.ecb.int/vocabulary/2002-08-01/eurofxref}"
    DB_EXCH_CURRENCY = pd.DataFrame()
    CURRENCY_NDEC = {'EUR': 2}
    STARTUP_STATUS = "NOK"
    HTTP_ERROR = ""
    DATE_REGEX = re.compile('\d\d\d\d\-\d\d\-\d\d')

    @classmethod
    def init_app(cls, app):
        try:
            response = requests.get(cls.XML_URI)
            response.raise_for_status()
        except HTTPError as he:
            cls.HTTP_ERROR = f'Error on startup: requests will not be fulfilled: {he}'
        except ConnectionError as ce:
            cls.HTTP_ERROR = f'Error on startup: requests will not be fulfilled: {ce}'
        else:
            xml_eurofxref = response.content
            root = ET.XML(xml_eurofxref)
            root_cube = root.find(f'{cls.CUBE_NS}Cube')

            if root_cube is None:
                app.config['HTTP_ERROR'] = f'Error on startup: unknown namespace {cls.CUBE_NS}'
                return

            for cube_time in root_cube:
                time_val = cube_time.attrib['time']
                cls.DB_EXCH_CURRENCY.loc[time_val, 'EUR'] = 1.00
                for cube in cube_time:
                    curr = cube.attrib['currency']
                    rate = cube.attrib['rate']
                    cls.DB_EXCH_CURRENCY.loc[time_val, curr] = float(cube.attrib['rate'])
                    ndec = get_ndec(cube.attrib['rate'])
                    if curr not in cls.CURRENCY_NDEC or cls.CURRENCY_NDEC[curr] < ndec:
                        cls.CURRENCY_NDEC[curr] = ndec

            cls.STARTUP_STATUS = "OK"

        app.config['HTTP_ERROR'] = cls.HTTP_ERROR
        app.config['STARTUP_STATUS'] = cls.STARTUP_STATUS

class DevelopmentConfig(Config):
    DEBUG = True

class TestingConfig(Config):
    TESTING = True

class ProductionConfig(Config):

    @classmethod
    def init_app(cls, app):
        Config.init_app(app)

        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.ERROR)
        app.logger.addHandler(file_handler)

config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}


#!/usr/bin/env python

'''
Online example from :
http://www.vtk.org/Wiki/VTK/Examples/Python/Graphs/EdgeWeights

Going to heavly comment out the steps to understand how to edit
this into what we need to make other graphs
'''

import vtk  							# Manditory on all python VTK
import random

g = vtk.vtkMutableUndirectedGraph() 	 	# Sets up empty data structure

# Create a list of 1000 Vertexs
vertex_list = []
for i in range(1000):
	vertex_list.append(g.AddVertex())

# Create a fully connected graph 		# Adding in the edges between them
for i in range(1000):
	while(True):
		v1 = random.choice(vertex_list)
		v2 = random.choice(vertex_list)
		if(v1 != v2):
			g.AddGraphEdge(v1,v2)
			break

# Making the layout view
# Which is an awsome class that handles a lot of the backend
# stuff for interaction with the graph we are about to make
graphLayoutView = vtk.vtkGraphLayoutView()

# Toss in your graph into this view
graphLayoutView.AddRepresentationFromInput(g)

# General Set Up Stuff
graphLayoutView.SetLayoutStrategy("Simple 2D")

# Recenters the camera around our points
graphLayoutView.ResetCamera()

# Opens and renders the window
graphLayoutView.Render()

# I have no idea what the hell this does
graphLayoutView.GetLayoutStrategy().SetRandomSeed(0)

# Sets up the interaction widets/event_listeners
graphLayoutView.GetInteractor().Start()


import time
import asyncio
from aiohttp import ClientSession

from utils import (
    sec_to_mcs,
    url, params, headers
)
from test_cases import SecondTestCase, FirstTestCase

async def fetch(session):
    start_time = time.time()

    async with session.get(
        url=url, params=params, headers=headers
    ) as response:
        status_code = response.status
        response = await  response.read()

        end_time = time.time()
        elapsed = end_time-start_time

        test = FirstTestCase(
            response={
                'content': response,
                'microseconds': sec_to_mcs(elapsed),
                'status_code': status_code,
                'end_time': end_time,
                'start_time': start_time,
            },
            methods=[
                'test_content_size',
                'test_response_time',
                'test_response_code',
                'test_information_volume'
            ]
        )
        test.run()
        return test

async def run(count_test):
    tasks = []

    async with ClientSession() as session:
        for i in range(count_test):
            task = asyncio.ensure_future(fetch(session))
            tasks.append(task)

        tests = await asyncio.gather(*tasks)
        SecondTestCase(
            methods=[
                'test_all_subtest_passed',
                'test_rps',
                'test_latency',
            ],
            tests=tests

        ).run()

if __name__ == '__main__':
    count_test = 8
    glob_time = time.time()

    loop = asyncio.get_event_loop()
    future = asyncio.ensure_future(run(count_test))
    loop.run_until_complete(future)

    print('Glob end %s' % (time.time() - glob_time))


#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2017/12/16 10:44
# @Author  : Shiyu Li
# @Software: PyCharm
# https://github.com/ritchieng/wideresnet-tensorlayer

import tensorlayer as tl
from tensorlayer.layers import *
import numpy as np
import time
import os

## Download data, and convert to TFRecord format, see ```tutorial_tfrecord.py```
X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(
    shape=(-1, 32, 32, 3), plotable=False)

# X_train = np.asarray(X_train, dtype=np.float32)
# y_train = np.asarray(y_train, dtype=np.int64)
# X_test = np.asarray(X_test, dtype=np.float32)
# y_test = np.asarray(y_test, dtype=np.int64)

print('X_train.shape', X_train.shape)  # (50000, 32, 32, 3)
print('y_train.shape', y_train.shape)  # (50000,)
print('X_test.shape', X_test.shape)  # (10000, 32, 32, 3)
print('y_test.shape', y_test.shape)  # (10000,)
print('X %s   y %s' % (X_test.dtype, y_test.dtype))

def data_to_tfrecord(images, labels, filename):
    """ Save data into TFRecord """
    if os.path.isfile(filename):
        print("%s exists" % filename)
        return
    print("Converting data into %s ..." % filename)
    cwd = os.getcwd()
    writer = tf.python_io.TFRecordWriter(filename)
    for index, img in enumerate(images):
        img_raw = img.tobytes()
        ## Visualize a image
        # tl.visualize.frame(np.asarray(img, dtype=np.uint8), second=1, saveable=False, name='frame', fig_idx=1236)
        label = int(labels[index])
        # print(label)
        ## Convert the bytes back to image as follow:
        # image = Image.frombytes('RGB', (32, 32), img_raw)
        # image = np.fromstring(img_raw, np.float32)
        # image = image.reshape([32, 32, 3])
        # tl.visualize.frame(np.asarray(image, dtype=np.uint8), second=1, saveable=False, name='frame', fig_idx=1236)
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
            'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),
        }))
        writer.write(example.SerializeToString())  # Serialize To String
    writer.close()

def read_and_decode(filename, is_train=None):
    """ Return tensor to read from TFRecord """
    filename_queue = tf.train.string_input_producer([filename])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.int64),
                                           'img_raw': tf.FixedLenFeature([], tf.string),
                                       })
    # You can do more image distortion here for training data
    img = tf.decode_raw(features['img_raw'], tf.float32)
    img = tf.reshape(img, [32, 32, 3])
    img = tf.cast(img, tf.float32)  # * (1. / 255) - 0.5
    # if is_train == True:
    #     # 1. Randomly crop a [height, width] section of the image.
    #     img = tf.random_crop(img, [24, 24, 3])
    #     # 2. Randomly flip the image horizontally.
    #     img = tf.image.random_flip_left_right(img)
    #     # 3. Randomly change brightness.
    #     img = tf.image.random_brightness(img, max_delta=63)
    #     # 4. Randomly change contrast.
    #     img = tf.image.random_contrast(img, lower=0.2, upper=1.8)
    #     # 5. Subtract off the mean and divide by the variance of the pixels.
    #     try: # TF 0.12+
    #         img = tf.image.per_image_standardization(img)
    #     except: # earlier TF versions
    #         img = tf.image.per_image_whitening(img)
    #
    # elif is_train == False:
    #     # 1. Crop the central [height, width] of the image.
    #     img = tf.image.resize_image_with_crop_or_pad(img, 24, 24)
    #     # 2. Subtract off the mean and divide by the variance of the pixels.
    #     try: # TF 0.12+
    #         img = tf.image.per_image_standardization(img)
    #     except: # earlier TF versions
    #         img = tf.image.per_image_whitening(img)
    # elif is_train == None:
    #     img = img

    label = tf.cast(features['label'], tf.int32)
    return img, label

# ## Save data into TFRecord files
# data_to_tfrecord(images=X_train, labels=y_train, filename="train.cifar10")
# data_to_tfrecord(images=X_test, labels=y_test, filename="test.cifar10")

batch_size = 64
# For generator
num_examples = X_train.shape[0]
index_in_epoch = 0
epochs_completed = 0

# For wide resnets
blocks_per_group = 4
widening_factor = 4

# Basic info
batch_num = 64
img_row = 32
img_col = 32
img_channels = 3
nb_classes = 10

with tf.device('/cpu:0'):
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
    # prepare data in cpu
    x_train_, y_train_ = read_and_decode("train.cifar10", True)
    x_test_, y_test_ = read_and_decode("test.cifar10", False)

    x_train_batch, y_train_batch = tf.train.shuffle_batch([x_train_, y_train_],
                                                          batch_size=batch_size, capacity=2000, min_after_dequeue=1000,
                                                          num_threads=32)  # set the number of threads here
    # for testing, uses batch instead of shuffle_batch
    x_test_batch, y_test_batch = tf.train.batch([x_test_, y_test_],
                                                batch_size=batch_size, capacity=50000, num_threads=32)

    def zero_pad_channels(x, pad=0):
        """
        Function for Lambda layer
        """
        pattern = [[0, 0], [0, 0], [0, 0], [pad - pad // 2, pad // 2]]
        return tf.pad(x, pattern)

    def residual_block(x, count, nb_filters=16, subsample_factor=1):
        prev_nb_channels = x.outputs.get_shape().as_list()[3]

        if subsample_factor > 1:
            subsample = [1, subsample_factor, subsample_factor, 1]
            # shortcut: subsample + zero-pad channel dim
            name_pool = 'pool_layer' + str(count)
            shortcut = tl.layers.PoolLayer(x,
                                           ksize=subsample,
                                           strides=subsample,
                                           padding='VALID',
                                           pool=tf.nn.avg_pool,
                                           name=name_pool)

        else:
            subsample = [1, 1, 1, 1]
            # shortcut: identity
            shortcut = x

        if nb_filters > prev_nb_channels:
            name_lambda = 'lambda_layer' + str(count)
            shortcut = tl.layers.LambdaLayer(
                shortcut,
                zero_pad_channels,
                fn_args={'pad': nb_filters - prev_nb_channels},
                name=name_lambda)

        name_norm = 'norm' + str(count)
        y = tl.layers.BatchNormLayer(x,
                                     decay=0.999,
                                     epsilon=1e-05,
                                     is_train=True,
                                     name=name_norm)

        name_conv = 'conv_layer' + str(count)
        y = tl.layers.Conv2dLayer(y,
                                  act=tf.nn.relu,
                                  shape=[3, 3, prev_nb_channels, nb_filters],
                                  strides=subsample,
                                  padding='SAME',
                                  name=name_conv)

        name_norm_2 = 'norm_second' + str(count)
        y = tl.layers.BatchNormLayer(y,
                                     decay=0.999,
                                     epsilon=1e-05,
                                     is_train=True,
                                     name=name_norm_2)

        prev_input_channels = y.outputs.get_shape().as_list()[3]
        name_conv_2 = 'conv_layer_second' + str(count)
        y = tl.layers.Conv2dLayer(y,
                                  act=tf.nn.relu,
                                  shape=[3, 3, prev_input_channels, nb_filters],
                                  strides=[1, 1, 1, 1],
                                  padding='SAME',
                                  name=name_conv_2)

        name_merge = 'merge' + str(count)
        out = tl.layers.ElementwiseLayer([y, shortcut],
                                         combine_fn=tf.add,
                                         name=name_merge)
        return out

    def model_batch_norm(x_crop, y_, reuse):
        """ Batch normalization should be placed before rectifier. """
        with tf.variable_scope("model", reuse=reuse):
            tl.layers.set_name_reuse(reuse)
            net = InputLayer(x_crop, name='input')
            net = Conv2dLayer(net,
                              act=tf.nn.relu,
                              shape=[3, 3, 3, 16],
                              strides=[1, 1, 1, 1],
                              padding='SAME',
                              name='cnn_layer_first')
            for i in range(0, blocks_per_group):
                nb_filters = 16 * widening_factor
                count = i
                net = residual_block(net, count, nb_filters=nb_filters, subsample_factor=1)

            for i in range(0, blocks_per_group):
                nb_filters = 32 * widening_factor
                if i == 0:
                    subsample_factor = 2
                else:
                    subsample_factor = 1
                count = i + blocks_per_group
                net = residual_block(net, count, nb_filters=nb_filters, subsample_factor=subsample_factor)

            for i in range(0, blocks_per_group):
                nb_filters = 64 * widening_factor
                if i == 0:
                    subsample_factor = 2
                else:
                    subsample_factor = 1
                count = i + 2 * blocks_per_group
                net = residual_block(net, count, nb_filters=nb_filters, subsample_factor=subsample_factor)

            net = tl.layers.BatchNormLayer(net,
                                           decay=0.999,
                                           epsilon=1e-05,
                                           is_train=True,
                                           name='norm_last')

            net = tl.layers.PoolLayer(net,
                                      ksize=[1, 8, 8, 1],
                                      strides=[1, 8, 8, 1],
                                      padding='VALID',
                                      pool=tf.nn.avg_pool,
                                      name='pool_last')

            net = tl.layers.FlattenLayer(net, name='flatten')

            net = tl.layers.DenseLayer(net,
                                       n_units=nb_classes,
                                       act=tf.identity,
                                       name='fc')

            y = net.outputs

            ce = tl.cost.cross_entropy(y, y_, name='cost')
            # L2 for the MLP, without this, the accuracy will be reduced by 15%.
            # L2 = 0
            # for p in tl.layers.get_variables_with_name('relu/W', True, True):
            #     L2 += tf.contrib.layers.l2_regularizer(0.004)(p)
            cost = ce #+ L2

            correct_prediction = tf.equal(tf.cast(tf.argmax(y, 1), tf.int32), y_)
            acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

            return net, cost, acc

    with tf.device('/gpu:0'):
        network, cost, acc, = model_batch_norm(x_train_batch, y_train_batch, None)
        _, cost_test, acc_test = model_batch_norm(x_test_batch, y_test_batch, True)

    ## train
    n_epoch = 5000
    learning_rate = 0.01
    print_freq = 1
    n_step_epoch = int(len(y_train) / batch_size)
    n_step = n_epoch * n_step_epoch

    with tf.device('/gpu:0'):
        # train_op = tf.train.AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999,
        #     epsilon=1e-08, use_locking=False).minimize(cost)
        train_op = tf.train.GradientDescentOptimizer(
            learning_rate, use_locking=False).minimize(cost, var_list=network.all_params)

    tl.layers.initialize_global_variables(sess)

    network.print_params(False)
    network.print_layers()

    print('   learning_rate: %f' % learning_rate)
    print('   batch_size: %d' % batch_size)
    print('   n_epoch: %d, step in an epoch: %d, total n_step: %d' % (n_epoch, n_step_epoch, n_step))

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    step = 0
    for epoch in range(n_epoch):
        start_time = time.time()
        train_loss, train_acc, n_batch = 0, 0, 0
        for s in range(n_step_epoch):
            ## You can also use placeholder to feed_dict in data after using
            # val, l = sess.run([x_train_batch, y_train_batch])
            # tl.visualize.images2d(val, second=3, saveable=False, name='batch', dtype=np.uint8, fig_idx=2020121)
            # err, ac, _ = sess.run([cost, acc, train_op], feed_dict={x_crop: val, y_: l})
            err, ac, _ = sess.run([cost, acc, train_op])
            step += 1
            train_loss += err
            train_acc += ac
            n_batch += 1

        if epoch + 1 == 1 or (epoch + 1) % print_freq == 0:
            print("Epoch %d : Step %d-%d of %d took %fs" % (
            epoch, step, step + n_step_epoch, n_step, time.time() - start_time))
            print("   train loss: %f" % (train_loss / n_batch))
            print("   train acc: %f" % (train_acc / n_batch))

            test_loss, test_acc, n_batch = 0, 0, 0
            for _ in range(int(len(y_test) / batch_size)):
                err, ac = sess.run([cost_test, acc_test])
                test_loss += err
                test_acc += ac
                n_batch += 1
            print("   test loss: %f" % (test_loss / n_batch))
            print("   test acc: %f" % (test_acc / n_batch))

    coord.request_stop()
    coord.join(threads)
    sess.close()


height = 500
width = 500
nx = 6
ny = 6
l = 60
slide = 0

def setup():
    size(width, height)
    stroke(0, 102, 0) #цвет рамки
    fill(0, 102, 0)   #цвет закраски
    frameRate(5) #скорость прокрутки

def draw():
    global slide
    background(0)
    for i in range(ny):
        for k in range(nx):
            x = ((k+1)*width/nx)-((width/nx)/2)
            y = ((i+1)*height/ny)-((height/ny)/2)
            if slide == 0:
                line(x, y-(l/2), x, y+(l/2))
            if slide == 1:
                rect(x-l/2, y-l/2, l, l)
            if slide == 2:
                ellipse(x, y, l, l)
                #triangle(x-2, y-2, 100+x, 20+y, 40+x, 90+y)
    slide = (slide + 1)%3


class Doraemon:
    def __init__(self,w,h,c):
        self.weight = w
        self.height = h
        self.color = c
        self.pocket_num = 3
        print("__Creating Now__\n" +
              "僕、ドラえもんです.")

    def pocket(self,nobi):
        self.nobi_ask = nobi
        self.pocket_num *= nobi ** 2

Dora1 = Doraemon(129.3, 129.3, "blue")
print(Dora1.pocket_num)
help = int(input("のび太くんのドラえもーんの掛け声は何回ですか?"))
Dora1.pocket(help)
print("以上より" + str(Dora1.pocket_num) + "個です")

"""print("僕の体重は" + str(Dora1.weight) + "kgだよ。意外に重いねテクノロジーだね")
print("なので、ダイエットします。")

momentum = int(input("何キロぐらい減らしたい?"))
Dora1.weight -= momentum
print("えい！\n" + str(round(Dora1.weight,1)) + "kgになったよ")"""


import random
import time

from card import Card
from nemesisCard import NemesisCard
from nemesis import Nemesis
from player import Player

class Game:

    characterArray = {
        "Mist": {
                "power": 1, "maxCharge": 4, "starterBreach": [0,0,3,4], "deck": [],"hand" : []
        }
    }

    def __init__(self, nbPlayers):
        self.nbPlayers = nbPlayers
        self.nemesisName = "empty"
        self.nemesis = None
        self.mainMenu = True
        self.characterSelect = False
        self.characterList = ["Mist", "Jian","a","b","c","d","e","f","g","h","i","j","k","l","m","n"]
        self.characterSelected = []
        self.playerList = []
        self.deckOrder = []
        self.discardDeckOder = []
        self.gemDeck = []
        self.relicDeck = []
        self.spellDeck = []
        self.reserveDeck = []
        self.reserveDeckCount = [7, 7, 7, 5, 5, 5, 5, 5, 5]
        self.isPlaying = True
        self.win = None
        self.chooseEffect = []
        self.isPossibleChooseEffect = []
        self.waitingForPlayerChoice = False

    def setNbPlayers(self,stringPlayers):
        self.nbPlayers = stringPlayers.split("-")[1]

    def setNemesisName(self,nemesis):
        self.nemesisName = nemesis.split("-")[1]

    def setupNemesis(self):
        self.nemesis = Nemesis(self.nemesisName)
        self.nemesis.setupNemesis(self.nbPlayers)
        self.mainMenu = False

    def setPlayer(self,index,name):
        self.characterSelected[index] = name

    def launchGame(self):
        #self.createDeckOrder()
        self.createTestDeckOrder()
        self.createAllCards()
        self.createReserve()
        self.createPlayerSetup()
        self.nemesis.additionnalSetup()

    def gameIsOver(self, boolean):
        self.win = boolean
        self.isPlaying = False

    def doNemesisTurn(self):
        self.doNemesisBoard()
        self.nemesisDrawCard()

    def nemesisDrawCard(self):
        if not self.nemesis.nemesisDeck:
            if not self.nemesis.nemesisBoard:
                self.gameIsOver(True)
        else:
            card = self.nemesis.drawNemesisCard()
            self.doNemesisCard(False, card)

    def doNemesisBoard(self):
        if not self.nemesis.nemesisBoard:
            for card in self.nemesis.nemesisBoard:
                self.doNemesisCard(True, card)

    def doNemesisCard(self, boolean, nemesisCard):
        if nemesisCard.cardType == "Serviteur":
            self.doServiteurEffect(boolean,nemesisCard)
        elif nemesisCard.cardType == "Pouvoir":
            self.doCardPowerEffect(boolean,nemesisCard)
        elif nemesisCard.cardType == "Attaque":
            self.doAttaqueEffect(nemesisCard)

    def checkEffet(self, effect):
        self.isPossibleChooseEffect = [False, False]
        isPossible = False
        if effect =="065":
            for player in self.playerList:
                if player.charge > 0:
                    isPossible = True
                    self.isPossibleChooseEffect[1] = True
                if player.spellBoard:
                    self.isPossibleChooseEffect[0] = True
                    isPossible = True
        return isPossible

    def doServiteurEffect(self,alreadyOnBoard,nemesisCard):
        if alreadyOnBoard:
            effectNumber = nemesisCard.cardEffect
            #Souffle Du Labyrinthe
            if effectNumber == "065":
                if self.checkEffect("065"):
                    self.chooseNemesisEffect(1, 2)

    def doChoosenEffect(self,codeEffect,player):
        #1 - Discard Prepared Spell
        #2 - Loose 1 charge
        if codeEffect == 1:
            player.discardSpell(1)
        elif codeEffect == 2:
            player.looseCharge(1)

        self.waitingForPlayerChoice = False

    def chooseNemesisEffect(self,codeFirstEffect,codeSecondEffect):
        self.chooseEffect = [codeFirstEffect, codeSecondEffect]
        self.waitingForPlayerChoice = True
        while self.waitingForPlayerChoice:
            time.sleep(1)

    def createPlayerSetup(self):
        i = 1
        for char in self.characterSelected:
            player = Player(char, i, Game.characterArray[char]["power"], Game.characterArray[char]["maxCharge"], Game.characterArray[char]["starterBreach"], Game.characterArray[char]["deck"], Game.characterArray[char]["hand"])
            self.playerList.extend(player)
            i += 1

    def createReserve(self):
        random.shuffle(self.gemDeck)
        random.shuffle(self.relicDeck)
        random.shuffle(self.spellDeck)
        firstGem = self.getReserveCard("Gemme",0,3)
        secondGem = self.getReserveCard("Gemme",3,4)
        thirdGem = self.getReserveCard("Gemme",5,6)
        firstRelic = self.getReserveCard("Relic",1,4)
        secondRelic = self.getReserveCard("Relic",4,8)
        firstSpell = self.getReserveCard("Spell",1,3)
        secondSpell = self.getReserveCard("Spell",3,4)
        thirdSpell = self.getReserveCard("Spell",4,5)
        fourthSpell = self.getReserveCard("Spell",6,9)
        self.reserveDeck.extend([firstGem,secondGem,thirdGem,firstRelic,secondRelic,firstSpell,secondSpell,thirdSpell,fourthSpell])
        for card in self.reserveDeck:
            print(card.cardName)

    def getReserveCard(self,type,min,max):
        keepLooping = True
        print("GetReserveCard " + type + " Min " + str(min) + " Max " +  str(max))
        while keepLooping:
            if type == "Gemme":
                card = self.gemDeck[random.randint(0, len(self.gemDeck) - 1)]
                print("Checking " + card.cardName)
                if card.cardCost >= min and card.cardCost <= max:
                    print("Accepted " + card.cardName)
                    self.gemDeck.remove(card)
                    keepLooping = False
            elif type == "Relic":
                card = self.relicDeck[random.randint(0,len(self.relicDeck) - 1)]
                if card.cardCost >= min and card.cardCost <= max:
                    self.relicDeck.remove(card)
                    keepLooping = False
            elif type == "Spell":
                card = self.spellDeck[random.randint(0,len(self.spellDeck) - 1)]
                if card.cardCost >= min and card.cardCost <= max:
                    self.spellDeck.remove(card)
                    keepLooping = False

        return card

    def createDeckOrder(self):
        if int(self.nbPlayers) == 1:
            self.deckOrder = [1,1,1,0,0]
        elif int(self.nbPlayers) == 2:
            self.deckOrder = [1, 1, 2, 2, 0, 0]
        elif int(self.nbPlayers) == 3:
            self.deckOrder = [1, 2, 3, 5, 0, 0]
        elif int(self.nbPlayers) == 4:
            self.deckOrder = [1, 2, 3, 4, 0, 0]

        random.shuffle(self.deckOrder)

    def createTestDeckOrder(self):
        self.deckOrder = [0, 0, 1, 2]

    def createAllCards(self):
        self.createGemCards()
        self.createRelicCards()
        self.createSpellCards()

    def createGemCards(self):
        elementExtraterrestre = Card("Gemme", "Élément Extraterrestre", "004", 4)
        beryliteHantee = Card("Gemme", "Beylite Hantée", "011",3)
        pierreDeDouleur = Card("Gemme", "Pierre De Douleur", "018", 6)
        opaleBrulante = Card("Gemme", "Opale Brûlante", "56", 5)
        saphirNuageux = Card("Gemme", "Saphir Nuageux", "62", 6)
        agregatDeDiamants = Card("Gemme", "Agrégat De Diamants", "69", 4)
        jade = Card("Gemme","Jade","76",2)
        rubisFulgurant = Card("Gemme", "Rubis Fulgurant", "83", 4)
        perleFiltrante = Card("Gemme", "PerleFiltrante", "90", 3)
        ambreDeBRisbois = Card("Gemme", "Ambre De V'Risbois", "9788",3)
        agateSangsue = Card("Gemme", "Agate Sangsue", "N02",3)
        scarabeeFossilise = Card("Gemme", "Scarabée Fossilisé", "V03",3)
        pierreDeSang = Card("Gemme", "Pierre De Sang", "W56", 6)
        mineraiDeLaBreche = Card("Gemme", "Minerai De La Brèche", "W63", 4)
        diamantInquietant = Card("Gemme", "Diamant Inquiétant", "W70",3)
        magnetiteCongelee = Card("Gemme", "Mangétite Congelée", "W84",3)
        bouquetDeScories = Card("Gemme", "Bouquet De Scories", "W91", 4)
        verrePyroclastique = Card("Gemme", "Verre Pyroclastique", "W98",3)
        self.gemDeck.extend([elementExtraterrestre,beryliteHantee,pierreDeDouleur,opaleBrulante,saphirNuageux,agregatDeDiamants,jade,
                             rubisFulgurant,perleFiltrante,ambreDeBRisbois,agateSangsue,scarabeeFossilise,pierreDeSang,mineraiDeLaBreche,
                             diamantInquietant,magnetiteCongelee,bouquetDeScories,verrePyroclastique])

    def createRelicCards(self):
        sphereDesSecrets = Card("Relic", "Sphère Des Secrets", "030", 3)
        batonDexplosion = Card("Relic", "Bâton D'explosion", "104", 3)
        vortexEnBouteille = Card("Relic", "Vortex En Bouteille", "109", 3)
        dagueFlechissante = Card("Relic", "Dague Fléchissante", "114", 2)
        orbeDeStabilisation = Card("Relic", "Orbe De Stabilisation", "119", 4)
        talismanDeMage = Card("Relic", "Talisman De Mage", "124", 5)
        cubeAstral = Card("Relic", "Cube Astral", "025", 5)
        prismeInstable = Card("Relic", "Prisme Instable", "129", 3)
        marteauEnFusion = Card("Relic", "Marteau En Fusion", "N09", 5)
        spiraleTemporelle = Card("Relic", "Spirale Temporelle", "N14", 7)
        cleDimensionnelle = Card("Relic", "Clé Dimensionnelle", "V10", 8)
        cachetDeLeternite = Card("Relic", "Cachet De L'éternité", "V15", 3)
        lingotErratique = Card("Relic", "Lingot Erratique", "W77", 5)
        boussoleDeCairn = Card("Relic", "Boussole De Cairn", "W105", 4)
        parcheminDuConclave = Card("Relic", "Parchemin Du Conclave", "W110", 3)
        attrapeurDeDemons = Card("Relic", "Attrapeur De Démons", "W115", 3)
        totemDeMage = Card("Relic", "Totem De Mage", "W120", 2)
        fetichePrimordial = Card("Relic", "Fétiche Primordial", "W125", 4)
        ganteletDeVorticite = Card("Relic", "Gantelet De Vorticité", "W130", 6)

        self.relicDeck.extend([sphereDesSecrets, dagueFlechissante, batonDexplosion, vortexEnBouteille, orbeDeStabilisation, talismanDeMage, cubeAstral, prismeInstable, marteauEnFusion, spiraleTemporelle, cleDimensionnelle,
                               cachetDeLeternite, lingotErratique, boussoleDeCairn, parcheminDuConclave, attrapeurDeDemons, totemDeMage, fetichePrimordial, ganteletDeVorticite])

    def createSpellCards(self):

        carboniser = Card("Spell", "Carboniser", "035", 8)
        catalyseur = Card("Spell", "Catalyseur", "040", 6)
        auraDeReaction = Card("Spell", "Aura De Réaction", "045", 5)
        conduitDuNeant = Card("Spell", "Conduit Du Néant", "050", 7)
        pyromancie = Card("Spell", "Pyromancie", "055", 7)
        calciner = Card("Spell", "Calciner", "060", 5)
        visionAplifiée = Card("Spell", "Vision Amplifiée", "134", 4)
        nexusDesArcanes = Card("Spell", "Nexus Des Arcanes", "139", 7)
        arcChaotique = Card("Spell", "Arc Chaotique", "144", 6)
        videDévorant = Card("Spell", "Vide Dévorant", "149", 7)
        feuObscur = Card("Spell", "Feu Obscur", "154", 5)
        volDessence = Card("Spell", "Vol D'Essence", "159", 5)
        eclairEnrage = Card("Spell", "Éclair Enragé", "164", 5)
        miseAFeu = Card("Spell", "Mise à Feu", "169", 4)
        tentaculeDeLave = Card("Spell", "Tentacule De Lave", "174", 4)
        vagueDoubli = Card("Spell", "Vague D'Oubli", "179", 5)
        flammeDuPhenix = Card("Spell", "Flamme Du Phénix", "184", 3)
        apercuPlanaire = Card("Spell", "Aperçu Planaire", "189", 6)
        echoSpectral = Card("Spell", "Écho Spectral", "194", 3)
        fouetArdent = Card("Spell", "Fouet Ardent", "199", 6)
        flamber = Card("Spell", "Flamber", "N19", 4)
        radiance = Card("Spell", "Radiance", "N24", 8)
        laMarqueDuSage = Card("Spell", "La Marque Du Sage", "N29", 7)
        eclairDeProphetie = Card("Spell", "Éclair De Prophétie", "N34", 6)
        resonance = Card("Spell", "Résonance", "V20", 6)
        embrassement = Card("Spell", "Embrassement", "V25", 2)
        fulminer = Card("Spell", "Fulminer", "V30", 5)
        feuInterieur = Card("Spell", "Feu Intérieur", "V36", 2)
        flechetteThermique = Card("Spell", "Fléchette Thermique", "V40", 4)
        aurore = Card("Spell", "Aurore", "W135", 5)
        carbonisation = Card("Spell", "Carbonisation", "W140", 4)
        conjurationDesOublies = Card("Spell", "Conjuration Des Oubliés", "W145", 6)
        flecheCeleste = Card("Spell", "Flèche Céleste", "W150", 5)
        champDeConvection = Card("Spell", "Champ De Convection", "W155", 5)
        cristallisation = Card("Spell", "Cristallisation", "W160", 8)
        equilibre = Card("Spell", "Équilibre", "W165", 7)
        torrentArdent = Card("Spell", "Torrent Ardent", "W170", 5)
        eclairDechirant = Card("Spell", "Éclair Déchirant", "W175", 4)
        meche = Card("Spell", "Mèche", "W180", 4)
        forgeNova = Card("Spell", "Forge Nova", "W185", 6)
        affluxPyrotechnique = Card("Spell", "Afflux Pyrotechnique", "W190", 4)
        retourALaPoussiere = Card("Spell", "Retour À La Poussière", "W195", 7)
        familierImaginaire = Card("Spell", "Familier Imaginaire", "W200", 3)

        self.spellDeck.extend([carboniser, catalyseur, auraDeReaction, conduitDuNeant, pyromancie, calciner, visionAplifiée, nexusDesArcanes, arcChaotique, videDévorant, feuObscur, volDessence,
                               eclairEnrage, miseAFeu, tentaculeDeLave, vagueDoubli, flammeDuPhenix, apercuPlanaire, echoSpectral, fouetArdent, flamber, radiance, laMarqueDuSage, eclairDeProphetie,
                               resonance, embrassement, fulminer, feuInterieur, flechetteThermique, aurore, carbonisation, conjurationDesOublies, flecheCeleste, champDeConvection, cristallisation,
                               equilibre, torrentArdent, eclairDechirant, meche, forgeNova, affluxPyrotechnique, retourALaPoussiere, familierImaginaire])


import numpy as np
import scipy as sp
from scipy.integrate import odeint
from scipy import linalg as la
from math import *
import cmath

class Lorenz:

    def __init__(self, coordinaten, sigma = 10.0, rho = 28, beta = 8/3):
        self.s = float(sigma)
        self.r = float(rho)
        self.b = float(beta)
        self.xs = coordinaten[0]
        self.ys = coordinaten[1]
        self.zs = coordinaten[2]

    def solve(self, T, dt):
        T = int(T)
        dt = float(dt)
        looptijd = [0]*ceil(T/dt)
        for i in range(len(looptijd)):
            looptijd[i] = i*dt

        return odeint(self.lorenz, [self.xs, self.ys, self.zs], looptijd)

    def lorenz(self, lijst, t):
        x = lijst[0]
        y = lijst[1]
        z = lijst[2]
        x_dot = self.s*(y - x)
        y_dot = x*(self.r - z) - y
        z_dot = x*y - self.b*z
        return [x_dot, y_dot, z_dot]

    def df(self, u):

        jacobi = np.array([[0,0,0],[0,0,0],[0,0,0]])
        jacobi[0][0] = -1*self.s
        jacobi[0][1] = self.s
        jacobi[1][0] = self.r - float(u[2])
        jacobi[1][1] = -1
        jacobi[1][2] = - float(u[0])
        jacobi[2][0] = float(u[1])
        jacobi[2][1] = float(u[0])
        jacobi[2][2] = -1*self.b
        print(jacobi)

        return jacobi

    def isStable(self, u):
        res = self.df(u)
        w = la.eigvals(res)

        if (w[0].real<0 and w[1].real<0 and w[2].real<0):
            return True
        else:
            return False


import tensorflow as tf
import time

from bot_code.trainer.base_classes.default_model_trainer import DefaultModelTrainer
from bot_code.trainer.utils import random_packet_creator
from bot_code.trainer.utils import controller_statistics
from bot_code.utils.dynamic_import import get_class
from tqdm import tqdm

class RandomPacketTrainer(DefaultModelTrainer):
    total_batches = None
    save_step = None
    teacher_package = None
    teacher_class_name = None
    teacher = None
    controller_stats = None
    start_time = None
    model_save_time = None
    frame_per_file = 20000

    def __init__(self):
        super().__init__()

    def get_random_data(self, packet_generator, input_formatter):
        state_object = packet_generator.get_random_array()
        output_array = input_formatter.create_input_array(state_object, state_object.time_diff)
        return output_array, state_object

    def get_config_name(self):
        return 'randomised_trainer.cfg'

    def get_event_filename(self):
        return 'random_packet'

    def load_config(self):
        super().load_config()
        # Obtaining necessary data for training from the config
        config = self.create_config()
        self.total_batches = config.getint('Randomised Trainer Configuration', 'total_batches')
        self.save_step = config.getint('Randomised Trainer Configuration', 'save_step')
        # Over here the model data is obtained
        self.teacher_package = config.get('Randomised Trainer Configuration', 'teacher_package')
        self.teacher_class_name = config.get('Randomised Trainer Configuration', 'teacher_class_name')

    def setup_trainer(self):
        super().setup_trainer()
        self.teacher = self.teacher_package.split('.')[-1]

    def instantiate_model(self, model_class):
        return model_class(self.sess, self.action_handler.get_logit_size(),
                           action_handler=self.action_handler, is_training=True,
                           optimizer=self.optimizer,
                           config_file=self.create_model_config(), teacher=self.teacher)

    def setup_model(self):
        super().setup_model()
        teacher_class = get_class(self.teacher_package, self.teacher_class_name)
        teacher = teacher_class(self.batch_size)
        packet_generator = random_packet_creator.TensorflowPacketGenerator(self.batch_size)
        input_state, state_object = self.get_random_data(packet_generator, self.input_formatter)

        real_output = teacher.get_output_vector_model(state_object)
        real_indexes = self.action_handler.create_action_indexes_graph(tf.stack(real_output, axis=1))
        self.model.create_model(input_state)
        self.model.create_copy_training_model(model_input=input_state, taken_actions=real_indexes)
        self.model.create_savers()
        self.model.initialize_model()

        # Print out what the model uses
        self.model.printParameters()

        # Initialising statistics and printing them before training
        self.controller_stats = controller_statistics.OutputChecks(self.sess, self.action_handler,
                                                                   self.batch_size, self.model.smart_max,
                                                                   state_object=state_object,
                                                                   bot=teacher)
        self.controller_stats.create_model()

    def _run_trainer(self):
        self.start_time = time.time()
        self.controller_stats.get_amounts()

        total_batches = self.total_batches
        batch_size = self.batch_size
        save_step = 100.0 / self.save_step
        sess = self.sess
        model = self.model

        # Percentage to print statistics (and also save the model)
        save_step = int((total_batches * batch_size) / save_step)
        print('training on the equivalent of', self.total_batches * self.batch_size / self.frame_per_file, 'games')
        print('Prints at this percentage:', 100.0 / ((total_batches * batch_size) / save_step))
        model_counter = 0
        self.model_save_time = 0

        # Running the model
        for i in tqdm(range(total_batches)):
            model.run_train_step(True, None, i)

            if ((i + 1) * batch_size) % save_step == 0:
                print('\nStats at', (i + 1) * batch_size, 'frames (', i + 1, 'batches): ')
                self.controller_stats.get_amounts()
                print('Saving model', model_counter)
                start_saving = time.time()
                model.save_model(model.get_model_path(model.get_default_file_name() + str(model_counter)),
                                 global_step=i, quick_save=True)
                # print('saved model in', time.time() - start_saving, 'seconds')
                self.model_save_time += time.time() - start_saving
                model_counter += 1

    def finish_trainer(self):
        print('trained on the equivalent of', self.total_batches * self.batch_size / self.frame_per_file, 'games')
        start_saving = time.time()
        self.model.save_model()
        print('saved model in', time.time() - start_saving, 'seconds')
        self.model_save_time += time.time() - start_saving

        total_time = time.time() - self.start_time
        print('Total time:', total_time)
        print('Time per batch:', (total_time - self.model_save_time) / (float(self.total_batches)))
        print('Time spent saving', self.model_save_time)

        print('Final stats:')
        self.controller_stats.get_amounts()
        self.controller_stats.get_final_stats()
        super().finish_trainer()

if __name__ == '__main__':
    RandomPacketTrainer().run()


# Sprite classes
import pygame
from pkg.level1.settings import *
from pkg.foundation.display import *
from .interactionmark import *
from .jaildoor import *
from .mob import *
from .speechballoon import *
from .spritesheet import *
from .toilet import *
from .text import *

class Walls(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((width, height))
        #self.image.fill(RED)
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

class Exits(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((width, height))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

class Bed(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((width, height))
        #self.image.fill(GREEN)
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

class Bars(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((width, height))
        #self.image.fill(GREEN)
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

class Player(pygame.sprite.Sprite):
    def __init__(self, visible_speech_balloon):
        self.visible_speech_balloon = visible_speech_balloon
        self.spritesheet = Spritesheet('pkg/level1/images/spritesheet.png')
        pygame.sprite.Sprite.__init__(self)
        self.walking = False
        self.can_walk = True
        self.current_frame = 0
        self.last_update = 0
        self.load_images()
        self.image = self.walk_down_frames[0]
        self.rect = self.image.get_rect()
        self.rect.x = (width / 2)
        self.rect.y = (height / 2)
        self.speedx = 0
        self.speedy = 0

    def load_images(self):
        # Player walk sprites
        self.walk_up_frames = [self.spritesheet.get_image(771, 324, 57, 82),
                               self.spritesheet.get_image(771, 407, 57, 82),
                               self.spritesheet.get_image(771, 324, 57, 82),
                               self.spritesheet.get_image(877, 83, 57, 82)]
        for frame in self.walk_up_frames:
            frame.set_colorkey(BLACK)

        self.walk_down_frames = [   self.spritesheet.get_image(889, 263, 57, 82),
                                    self.spritesheet.get_image(780, 174, 57, 82),
                                    self.spritesheet.get_image(889, 263, 57, 82),
                                    self.spritesheet.get_image(759, 84, 57, 82)]
        for frame in self.walk_down_frames:
            frame.set_colorkey(BLACK)

        self.walk_left_frames = [   self.spritesheet.get_image(664, 0, 57, 82),
                                    self.spritesheet.get_image(659, 246, 57, 82),
                                    self.spritesheet.get_image(664, 0, 57, 82),
                                    self.spritesheet.get_image(697, 164, 57, 82)]
        for frame in self.walk_left_frames:
            frame.set_colorkey(BLACK)

        self.walk_right_frames = [  self.spritesheet.get_image(635, 164, 57, 82),
                                    self.spritesheet.get_image(602, 82, 57, 82),
                                    self.spritesheet.get_image(635, 164, 57, 82),
                                    self.spritesheet.get_image(602, 0, 57, 82)]
        for frame in self.walk_right_frames:
            frame.set_colorkey(BLACK)

    def update(self):
        self.animate()
        self.speedx = 0
        self.speedy = 0
        self.keys = pygame.key.get_pressed()
        if (self.keys[pygame.K_UP] or self.keys[pygame.K_w]) and self.can_walk:
            if not self.visible_speech_balloon:
                self.speedy = -6
                self.speedx = 0
        if (self.keys[pygame.K_DOWN] or self.keys[pygame.K_s])  and self.can_walk:
            if not self.visible_speech_balloon:
                self.speedy = 6
                self.speedx = 0
        if (self.keys[pygame.K_LEFT] or self.keys[pygame.K_a])  and self.can_walk:
            if not self.visible_speech_balloon:
                self.speedx = -6
                self.speedy = 0
        if (self.keys[pygame.K_RIGHT] or self.keys[pygame.K_d])  and self.can_walk:
            if not self.visible_speech_balloon:
                self.speedx = 6
                self.speedy = 0

        self.rect.x += self.speedx
        self.rect.y += self.speedy

    def animate(self):
        now = pygame.time.get_ticks()
        if self.speedx | self.speedy != 0:
            self.walking = True
        else:
            self.walking = False
        # walk animation
        if self.walking:
            if now - self.last_update > 200:
                self.last_update = now
                self.current_frame = (self.current_frame + 1) % len(self.walk_left_frames)
                if self.speedx > 0:
                    self.image = self.walk_right_frames[self.current_frame]
                if self.speedx < 0:
                    self.image = self.walk_left_frames[self.current_frame]
                if self.speedy < 0:
                    self.image = self.walk_up_frames[self.current_frame]
                if self.speedy > 0:
                    self.image = self.walk_down_frames[self.current_frame]


from tkinter import Label, Frame, Button, Checkbutton, Radiobutton, Listbox,\
	Tk, StringVar, IntVar, Entry, END, X, BOTH

#create a window
window = Tk()

# create a label (text line)
text_label = Label(window, text="hello tkinter !")
# display the label in the windows
text_label.pack()

# create a text zone
var_text = StringVar()
line_text = Entry(window, textvariable=var_text, width=30)
line_text.pack()

# create a check zone
var_case = IntVar()
case = Checkbutton(window, text="don't ask this question",
	variable=var_case)
case.pack()

# create a radio button
var_choice = StringVar()

red_choice = Radiobutton(window, text="red", variable=var_choice,
	value="red")
blue_choice = Radiobutton(window, text="blue", variable=var_choice,
	value="blue")
green_choice = Radiobutton(window, text="green", variable=var_choice,
	value="green")

red_choice.pack()
blue_choice.pack()
green_choice.pack()

# create a listbox
liste = Listbox(window)

liste.insert(END, "hy")
liste.insert(END, "i'm")
liste.insert(END, "rock")
liste.insert(END, "baby")

liste.pack()

# create a frame
frame = Frame(window, width=768, height=576, borderwidth=1)
frame.pack(fill=BOTH)

msg = Label(frame, text="our window")
msg.pack(side="top", fill=X)

# create a button to quit the window
exit_button = Button(window, text="exit", command=window.quit)
exit_button.pack()

# begin the loop Tkinter
window.mainloop()


from plone.app.layout.viewlets.common import ViewletBase
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.component import getMultiAdapter

class ViewOptions(ViewletBase):
    render = ViewPageTemplateFile('viewoptions.pt')

    def _isType(self, type):
        return self.context.portal_type == type

    def _endsWith(self, path):
        return self.context.request.URL.endswith(path)

    def getTabs(self):

        project = self.context.restrictedTraverse('@@unep_utils').projectParentURL()
        if project:
            tabs = [
                (project, "Overview",
                    self._isType('Project') and self._endsWith('/base_view')),
                ("%s/project_general_info" % project,"General",
                    self._isType('ProjectGeneralInformation')),
                ("%s/fmi_folder" % project, "Financial",
                    self._isType('FMIFolder')),
                ("%s/milestones" % project, "Milestones",
                    self._isType('Milestone')),
                ("%s/mne_folder" % project, "Monitoring & Evaluation",
                    self._isType('MandEfolder')),
                ("%s/@@reports" % project, "Reports",
                    self._isType('Project') and self._endsWith('/@@reports')),
                ("%s/documents" % project, "Documents",
                    self._isType('Folder')),
            ]
        elif self._isType('ProjectDatabase'):
            tabs = [
                (self.context.absolute_url(), "Projects A-Z",
                    self._endsWith('/base_view')),
                ("%s/@@reports" % self.context.absolute_url(), "Reports",
                    self._endsWith('/@@reports')),
            ]
        else:
            return []

        return [dict(url=i, title=j, selected=k) for i,j,k in tabs]


'''
Created on Jul 24, 2013

@package: ally core
@copyright: 2012 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Gabriel Nistor

Provides the indexing for content definitions.
'''

from ally.api.type import Type
from ally.container.ioc import injected
from ally.design.processor.attribute import requires, defines
from ally.support.util import firstOf
from ally.support.util_context import listing, iterate
from ally.design.processor.context import Context
from ally.design.processor.handler import HandlerProcessor

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

class Decoding(Context):
    '''
    The decoding context.
    '''
    # ---------------------------------------------------------------- Defined
    contentDefinitions = defines(dict, doc='''
    @rtype: dictionary{string: Context}
    The definition context for the content decoding indexed by category.
    ''')
    # ---------------------------------------------------------------- Required
    parent = requires(Context)
    name = requires(str)
    children = requires(dict)

class Definition(Context):
    '''
    The definition context.
    '''
    # ---------------------------------------------------------------- Defined
    name = defines(str, doc='''
    @rtype: string
    The definition name.
    ''')
    types = defines(list, doc='''
    @rtype: list[Type]
    The definition types in the normal order of the appearance.
    ''')
    references = defines(list, doc='''
    @rtype: list[Context]
    The definition references that directly linked with this definition.
    ''')
    # ---------------------------------------------------------------- Required
    category = requires(str)

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

@injected
class DefinitionContentHandler(HandlerProcessor):
    '''
    Implementation for a handler that provides the indexing for content definitions.
    '''

    separator = None
    # The separator to use for content names, if not provided the names will be placed as simple names.

    def __init__(self):
        assert self.separator is None or isinstance(self.separator, str), 'Invalid separator %s' % self.separator
        super().__init__(Definition=Definition)

    def process(self, chain, decoding:Decoding, definition:Context=None, **keyargs):
        '''
        @see: HandlerProcessor.process

        Index the definition for content.
        '''
        assert isinstance(decoding, Decoding), 'Invalid decoding %s' % decoding

        if not definition: return
        assert isinstance(definition, Definition), 'Invalid definition %s' % definition

        if decoding.contentDefinitions is None: decoding.contentDefinitions = {}
        assert isinstance(definition.category, str), 'Invalid definition category %s' % definition.category
        assert definition.category not in decoding.contentDefinitions, 'Already a definition for \'%s\'' % definition.category

        decoding.contentDefinitions[definition.category] = definition
        if self.separator: definition.name = self.separator.join(reversed(listing(decoding, Decoding.parent, Decoding.name)))
        else: definition.name = decoding.name

        if decoding.children:
            for child in decoding.children.values():
                assert isinstance(child, Decoding), 'Invalid decoding %s' % child
                if child.contentDefinitions and definition.category in child.contentDefinitions:
                    if definition.references is None: definition.references = []
                    definition.references.append(child.contentDefinitions[definition.category])

        if not definition.types:
            for child in iterate(decoding, lambda decoding: firstOf(decoding.children.values())
                                 if decoding.children and len(decoding.children) == 1 else None):
                assert isinstance(child, Decoding), 'Invalid decoding %s' % child

                if child.type and child.type.isPrimitive:
                    assert isinstance(child.type, Type), 'Invalid decoding type %s' % child.type
                    if definition.types is None: definition.types = []
                    definition.types.append(child.type)
                    break

        return definition