from tkinter import *
import requests
import json

class GUI(object):
    def __init__(self, master=None):
        self.fontePadrao = ("Arial", "10", "bold")

        # CONTAINERS
        self.primeiroContainer = Frame(master)
        self.primeiroContainer["pady"] = 10
        self.primeiroContainer.pack()

        self.segundoContainer = Frame(master)
        self.segundoContainer["padx"] = 20
        self.segundoContainer.pack()

        self.terceiroContainer = Frame(master)
        self.terceiroContainer["padx"] = 20
        self.terceiroContainer.pack()

        self.quartoContainer = Frame(master)
        self.quartoContainer["padx"] = 20
        self.quartoContainer.pack()

        self.quintoContainer = Frame(master)
        self.quintoContainer["padx"] = 20
        self.quintoContainer.pack()

        self.sextoContainer = Frame(master)
        self.sextoContainer["pady"] = 5
        self.sextoContainer["padx"] = 20
        self.sextoContainer.pack()

        # GUI TITLE
        self.titulo = Label(self.primeiroContainer, text="DOJOT -> DEVICE")
        self.titulo["font"] = ("Arial", "10", "bold")
        self.titulo.pack()

        # HOST
        self.hostLabel = Label(self.segundoContainer,text="Host:", font=self.fontePadrao)
        self.hostLabel.pack(side=LEFT)

        self.host = Entry(self.segundoContainer)
        self.host["width"] = 30
        self.host["font"] = self.fontePadrao
        self.host.pack(side=LEFT)

        # PORT
        self.portLabel = Label(self.segundoContainer,text="Port:", font=self.fontePadrao)
        self.portLabel.pack(side=LEFT)

        self.port = Entry(self.segundoContainer)
        self.port["width"] = 30
        self.port["font"] = self.fontePadrao
        self.port.pack(side=LEFT)

        # TOKEN
        self.tokenLabel = Label(self.terceiroContainer,text="Token:", font=self.fontePadrao)
        self.tokenLabel.pack(side=LEFT)

        self.token = Entry(self.terceiroContainer)
        self.token["width"] = 30
        self.token["font"] = self.fontePadrao
        self.token.pack(side=LEFT)

        # DEVICE ID
        self.deviceidLabel = Label(self.quartoContainer,text="Device Id:", font=self.fontePadrao)
        self.deviceidLabel.pack(side=LEFT)

        self.deviceid = Entry(self.quartoContainer)
        self.deviceid["width"] = 30
        self.deviceid["font"] = self.fontePadrao
        self.deviceid.pack(side=LEFT)

        # TOPIC
        self.topicLabel = Label(self.quintoContainer,text="Topic:", font=self.fontePadrao)
        self.topicLabel.pack(side=LEFT)

        self.topic = Entry(self.quintoContainer)
        self.topic["width"] = 30
        self.topic["font"] = self.fontePadrao
        self.topic.pack(side=LEFT)

        #PAYLOAD
        self.payloadLabel = Label(self.quintoContainer, text="Speed:", font=self.fontePadrao)
        self.payloadLabel.pack(side=LEFT)

        self.payload = Entry(self.quintoContainer)
        self.payload["width"] = 30
        self.payload["font"] = self.fontePadrao
        self.payload.pack(side=LEFT)

        # AUTH BUTTON
        self.autenticar = Button(self.sextoContainer)
        print(self.autenticar['command'])
        self.autenticar["text"] = "Send"
        self.autenticar["font"] = ("Arial", "8", "bold")
        self.autenticar["width"] = 12
        self.autenticar["command"] = self.verificaPub
        self.autenticar.pack()

        # HELP BUTTON
        self.helps = Button(self.sextoContainer)
      #  print(self.helps['command'])
        self.helps["text"] = "Help"
        self.helps["font"] = ("Arial", "8", "bold")
        self.helps["width"] = 12
        self.helps["command"] = self.ajuda
        self.helps.pack()

        self.mensagem = Label(self.sextoContainer, text="", font=self.fontePadrao)
        self.mensagem.pack()

        self.ajuda = Label(self.sextoContainer, text="", font=self.fontePadrao)
        self.ajuda.pack()

    # Metodo verificar payload
    def verificaPub(self):
      host = self.host.get()
      port = self.port.get()
      token = self.token.get()
      deviceid = self.deviceid.get()
      payload = self.payload.get()
      topic = self.topic.get()

      url = "http://{}:{}/device/{}/actuate".format(host,port,deviceid)
      Token = "Bearer {}".format(token)

      headers = {
        'Authorization':Token,
        'Content-Type':'application/json'
      }

      data = json.dumps( { "attrs": { topic: float(payload)}})

      response = requests.put(url, headers=headers, data=data)

    def ajuda(self):

      self.ajuda["text"] = """Host: Dojot IP     Port: 8000
                            Token: device-generated token
                            Device Id: device-generated Device ID
                            Topic: pubTimer -> speed publishing on Dojot
                            pubMove -> conveyor speed
                            Speed: time in seconds"""

root = Tk()
GUI(root)
root.mainloop()


# -*- coding: utf-8 -*-
"""Triangular mesh data

This module provides a class for storing triangular meshes. Attributes
of the triangular mesh can be determined. In addition, methodes are available
to derive further information from the triangular grid.

"""

import numpy as np

__author__ = "Uwe Graichen"
__copyright__ = "Copyright 2018-2019, Uwe Graichen"
__credits__ = ["Uwe Graichen"]
__license__ = "BSD-3-Clause"
__version__ = "1.0.12"
__maintainer__ = "Uwe Graichen"
__email__ = "uwe.graichen@tu-ilmenau.de"
__status__ = "Release"

def area_triangle(vertex1, vertex2, vertex3):
    """Estimate the area of a triangle given by three vertices

    The area of the triangle given by three vertices is calculated by the half
    cross product formula.

    Parameters
    ----------
    vertex1 : array, shape (1, 3)
    vertex2 : array, shape (1, 3)
    vertex3 : array, shape (1, 3)

    Returns
    -------
    float
        Area of the triangle given by the three vertices.

    Examples
    --------

    >>> from spharapy import trimesh as tm
    >>> tm.area_triangle([1, 0, 0], [0, 1, 0], [0, 0, 1])
    0.8660254037844386

    """
    vertex1 = np.asarray(vertex1)
    vertex2 = np.asarray(vertex2)
    vertex3 = np.asarray(vertex3)

    trianglearea = (0.5 *
                    np.linalg.norm(np.cross(vertex2 - vertex1,
                                            vertex3 - vertex1)))
    return trianglearea

class TriMesh(object):
    """Triangular mesh class

    This class can be used to store data to define a triangular mesh and it
    provides atributes and methodes to derive further information about the
    triangular mesh.

    Parameters
    ----------
    trilist: array, shape (n_triangles, 3)
        List of triangles, each row of the array contains the edges of
        a triangle. The edges of the triangles are defined by the
        indices to the list of vertices. The index of the first vertex
        is 0. The number of triangles is n_triangles.
    vertlist: array, shape (n_points, 3)
        List of coordinates x, y, z which describes the positions of the
        vertices.

    Attributes
    ----------
    trilist: array, shape (n_triangles, 3)
        List of triangles of the mesh.
    vertlist: array, shape (n_points, 3)
        List of coordinates of the vertices
    """

    def __init__(self, trilist, vertlist):
        self.trilist = np.asarray(trilist)
        self.vertlist = np.asarray(vertlist)

    @property
    def trilist(self):
        """Get or set the list of triangles.

        Setting the list of triangles will simultaneously check if the
        triangle list is in the correct format.
        """

        return self._trilist

    @trilist.setter
    def trilist(self, trilist):
        if trilist.ndim != 2:
            raise ValueError('Triangle list has to be 2D!')
        elif trilist.shape[1] != 3:
            raise ValueError('Each entry of the triangle list has to consist '
                             'of three elements!')
        # pylint: disable=W0201
        self._trilist = np.asarray(trilist)

    @property
    def vertlist(self):
        """Get or set the list of vertices.

        Setting the list of triangles will simultaneously check if the
        vertice list is in the correct format.
        """

        return self._vertlist

    @vertlist.setter
    def vertlist(self, vertlist):
        if vertlist.ndim != 2:
            raise ValueError('Vertex list has to be 2D!')
        elif vertlist.shape[1] != 3:
            raise ValueError('Each entry of the vertex list has to consist '
                             'of three elements!')
        # pylint: disable=W0201
        self._vertlist = np.asarray(vertlist)

    def weightmatrix(self, mode='inv_euclidean'):
        """Compute a weight matrix for a triangular mesh

        The method creates a weighting matrix for the edges of a triangular
        mesh using different weighting function.

        Parameters
        ----------
        mode : {'unit', 'inv_euclidean', 'half_cotangent'}, optional
            The parameter `mode` specifies the method for determining
            the edge weights. Using the option 'unit' all edges of the
            mesh are weighted by unit weighting function, the result
            is an adjacency matrix. The option 'inv_euclidean' results
            in edge weights corresponding to the inverse Euclidean
            distance of the edge lengths. The option 'half_cotangent'
            uses the half of the cotangent of the two angles opposed
            to an edge as weighting function. the default weighting
            function is 'inv_euclidean'.

        Returns
        -------
        weightmatrix : array, shape (n_points, n_points)
            Symmetric matrix, which contains the weight of the edges
            between adjacent vertices. The number of vertices of the
            triangular mesh is n_points.

        Examples
        --------

        >>> from spharapy import trimesh as tm
        >>> testtrimesh = tm.TriMesh([[0, 1, 2]], [[1., 0., 0.], [0., 2., 0.],
        ...                                        [0., 0., 3.]])
        >>> testtrimesh.weightmatrix(mode='inv_euclidean')
        array([[ 0.        ,  0.4472136 ,  0.31622777],
               [ 0.4472136 ,  0.        ,  0.2773501 ],
               [ 0.31622777,  0.2773501 ,  0.        ]])

        """

        # plausibility test of option 'mode'
        if mode not in ('unit', 'inv_euclidean', 'half_cotangent'):
            raise ValueError("Unrecognized mode '%s'" % mode)

        # get the largest index from from triangle list
        maxindex = self.trilist.max()

        # fill the weight matrix with zeros, the size is (maxindex + 1)^2
        weightmatrix = np.zeros((maxindex + 1, maxindex + 1), dtype=float)

        if mode == 'unit':
            # iterate over triangle list an build weight matrix
            for x in self.trilist:

                weightmatrix[x[0], x[1]] = 1
                weightmatrix[x[1], x[0]] = 1

                weightmatrix[x[0], x[2]] = 1
                weightmatrix[x[2], x[0]] = 1

                weightmatrix[x[1], x[2]] = 1
                weightmatrix[x[2], x[1]] = 1

        elif mode == 'inv_euclidean':
            # iterate over triangle list an build weight matrix
            for x in self.trilist:
                # compute the three vectors of the triangle
                vec10 = self.vertlist[x[1]] - self.vertlist[x[0]]
                vec20 = self.vertlist[x[2]] - self.vertlist[x[0]]
                vec21 = self.vertlist[x[2]] - self.vertlist[x[1]]

                # fill in the weights in the weight matrix
                weightmatrix[x[0], x[1]] = (1 / np.linalg.norm(vec10))
                weightmatrix[x[1], x[0]] = (1 / np.linalg.norm(vec10))
                weightmatrix[x[0], x[2]] = (1 / np.linalg.norm(vec20))
                weightmatrix[x[2], x[0]] = (1 / np.linalg.norm(vec20))
                weightmatrix[x[2], x[1]] = (1 / np.linalg.norm(vec21))
                weightmatrix[x[1], x[2]] = (1 / np.linalg.norm(vec21))

        else:
            # iterate over triangle list an build weight matrix
            for x in self.trilist:
                # compute the directional vectors at the 1st vertex
                vec1 = self.vertlist[x[1]] - self.vertlist[x[0]]
                vec2 = self.vertlist[x[2]] - self.vertlist[x[0]]

                # compute the weight of the edge 0.5 * cot
                tempweight = 0.5 * (1.0 /
                                    np.tan(np.arccos(np.dot(vec1, vec2) /
                                                     (np.linalg.norm(vec1) *
                                                      np.linalg.norm(vec2)))))

                weightmatrix[x[1], x[2]] += tempweight
                weightmatrix[x[2], x[1]] += tempweight

                # compute the directional vectors at the 2nd vertex
                vec1 = self.vertlist[x[0]] - self.vertlist[x[1]]
                vec2 = self.vertlist[x[2]] - self.vertlist[x[1]]

                # compute the weight of the edge 0.5 * cot
                tempweight = 0.5 * (1.0 /
                                    np.tan(np.arccos(np.dot(vec1, vec2) /
                                                     (np.linalg.norm(vec1) *
                                                      np.linalg.norm(vec2)))))

                weightmatrix[x[0], x[2]] += tempweight
                weightmatrix[x[2], x[0]] += tempweight

                # compute the directional vectors at the 3rd vertex
                vec1 = self.vertlist[x[0]] - self.vertlist[x[2]]
                vec2 = self.vertlist[x[1]] - self.vertlist[x[2]]

                # compute the weight of the edge 0.5 * cot
                tempweight = 0.5 * (1.0 /
                                    np.tan(np.arccos(np.dot(vec1, vec2) /
                                                     (np.linalg.norm(vec1) *
                                                      np.linalg.norm(vec2)))))

                weightmatrix[x[0], x[1]] += tempweight
                weightmatrix[x[1], x[0]] += tempweight

        # return the weight matrix
        return weightmatrix

    def laplacianmatrix(self, mode='inv_euclidean'):
        """Compute a laplacian matrix for a triangular mesh

        The method creates a laplacian matrix for a triangular
        mesh using different weighting function.

        Parameters
        ----------
        mode : {'unit', 'inv_euclidean', 'half_cotangent'}, optional
            The methods for determining the edge weights. Using the option
            'unit' all edges of the mesh are weighted by unit weighting
            function, the result is an adjacency matrix. The option
            'inv_euclidean' results in edge weights corresponding to the
            inverse Euclidean distance of the edge lengths. The option
            'half_cotangent' uses the half of the cotangent of the two angles
            opposed to an edge as weighting function. the default weighting
            function is 'inv_euclidean'.

        Returns
        -------
        laplacianmatrix : array, shape (n_points, n_points)
            Matrix, which contains the discrete laplace operator for data
            defined at the vertices of a triangular mesh. The number of
            vertices of the triangular mesh is n_points.

        Examples
        --------

        >>> from spharapy import trimesh as tm
        >>> testtrimesh = tm.TriMesh([[0, 1, 2]], [[1., 0., 0.], [0., 2., 0.],
        ...                                        [0., 0., 3.]])
        >>> testtrimesh.laplacianmatrix(mode='inv_euclidean')
        array([[ 0.76344136, -0.4472136 , -0.31622777],
               [-0.4472136 ,  0.72456369, -0.2773501 ],
               [-0.31622777, -0.2773501 ,  0.59357786]])

        """

        # plausibility test of option 'mode'
        if mode not in ('unit', 'inv_euclidean', 'half_cotangent'):
            raise ValueError("Unrecognized mode '%s'" % mode)

        # determine the weight matrix with
        weightmatrix = self.weightmatrix(mode=mode)

        # compute the laplacian matrix
        laplacianmatrix = np.diag(weightmatrix.sum(axis=0)) - weightmatrix

        # return the laplacian matrix
        return laplacianmatrix

    def massmatrix(self, mode='normal'):
        """Mass matrix of a triangular mesh

        The method determines a mass matrix of a triangular mesh.

        Parameters
        ----------

        mode : {'normal', 'lumped'}, optional
            The `mode` parameter can be used to select whether a normal mass
            matrix or a lumped mass matrix is to be determined.

        Returns
        -------
        massmatrix : array, shape (n_points, n_points)
            Symmetric matrix, which contains the mass values for each edge and
            vertex for the FEM approch. The number of vertices of the
            triangular mesh is n_points.

        Examples
        --------

        >>> from spharapy import trimesh as tm
        >>> testtrimesh = tm.TriMesh([[0, 1, 2]], [[1., 0., 0.], [0., 2., 0.],
        ...                                        [0., 0., 3.]])
        >>> testtrimesh.massmatrix()
        array([[ 0.58333333,  0.29166667,  0.29166667],
               [ 0.29166667,  0.58333333,  0.29166667],
               [ 0.29166667,  0.29166667,  0.58333333]])

        References
        ----------
        :cite:`vallet07,dyer07,zhang07`

        """

        # plausibility test of option 'mode'
        if mode not in ('normal', 'lumped'):
            raise ValueError("Unrecognized mode '%s'" % mode)

        # get the largest index from from triangle list
        maxindex = self.trilist.max()

        # fill the weight matrix with zeros, the size is (maxindex + 1)^2
        massmatrix = np.zeros((maxindex + 1, maxindex + 1), dtype=float)

        if mode == 'lumped':
            # iterate over triangle list an build mass matrix
            for x in self.trilist:
                # compute the area of the triangle
                temparea = area_triangle(self.vertlist[x[0]],
                                         self.vertlist[x[1]],
                                         self.vertlist[x[2]])

                # add to every matrix element belonging to the vertex v(i) of
                # the triangle a 3rd of the triangle area
                massmatrix[x[0], x[0]] += temparea / 3
                massmatrix[x[1], x[1]] += temparea / 3
                massmatrix[x[2], x[2]] += temparea / 3
        else:
            # iterate over triangle list an build mass matrix
            for x in self.trilist:
                # compute the area of the triangle
                temparea = area_triangle(self.vertlist[x[0]],
                                         self.vertlist[x[1]],
                                         self.vertlist[x[2]])

                # add to every matrix element belonging to the edge e(i,j) of
                # the triangle a twelfth of the triangle area
                massmatrix[x[0], x[1]] += temparea / 12
                massmatrix[x[1], x[0]] = massmatrix[x[0], x[1]]
                massmatrix[x[0], x[2]] += temparea / 12
                massmatrix[x[2], x[0]] = massmatrix[x[0], x[2]]
                massmatrix[x[1], x[2]] += temparea / 12
                massmatrix[x[2], x[1]] = massmatrix[x[1], x[2]]

                # add to every matrix element belonging to the vertex v(i) of
                # the triangle a sixth of the triangle area
                massmatrix[x[0], x[0]] += temparea / 6
                massmatrix[x[1], x[1]] += temparea / 6
                massmatrix[x[2], x[2]] += temparea / 6

        # return the mass matrix
        return massmatrix

    def stiffnessmatrix(self):
        """Stiffness matrix of a triangular mesh

        The method determines a stiffness matrix of a triangular mesh.

        Returns
        -------
        stiffmatrix : array, shape (n_points, n_points)
            Symmetric matrix, which contains the stiffness values for each edge
            and vertex for the FEM approch. The number of vertices of the
            triangular mesh is n_points.

        Examples
        --------

        >>> from spharapy import trimesh as tm
        >>> testtrimesh = tm.TriMesh([[0, 1, 2]], [[1., 0., 0.], [0., 2., 0.],
        ...                                        [0., 0., 3.]])
        >>> testtrimesh.stiffnessmatrix()
        array([[-0.92857143,  0.64285714,  0.28571429],
               [ 0.64285714, -0.71428571,  0.07142857],
               [ 0.28571429,  0.07142857, -0.35714286]])

        References
        ----------
        :cite:`vallet07`

        """

        # get the largest index from from triangle list
        maxindex = self.trilist.max()

        # fill the weight matrix with zeros, the size is (maxindex + 1)^2
        stiffmatrix = np.zeros((maxindex + 1, maxindex + 1), dtype=float)

        # compute the cot weight matrix
        weightmatrix = self.weightmatrix(mode='half_cotangent')

        # compute and return the stiffness matrix
        stiffmatrix = -np.diag(weightmatrix.sum(axis=0)) + weightmatrix

        return stiffmatrix


import sys
import xml.etree.ElementTree as ET

class ScannerError(Exception):
    pass

class UnknownTypeError(Exception):
    def __init__(self, t):
        super().__init__(f"Unknown type: {t}")

def validate_type(t):
    if (
        t == "uint"
        or t == "int"
        or t == "fixed"
        or t == "string"
        or t == "object"
        or t == "new_id"
        or t == "array"
        or t == "fd"
    ):
        return t
    else:
        raise UnknownTypeError(t)

def option_map(value, f):
    if value != None:
        return f(value)
    else:
        return value

class Name:
    def __init__(self, name):
        assert name
        self.name = name

    def snake(self):
        return self.name

    def screaming(self):
        return self.name.upper()

    def pascal(self):
        return "".join([word.capitalize() for word in self.name.split("_")])

    def camel(self):
        return self._uncapitalise(self.pascal())

    def text(self):
        return self.name.replace("_", " ")

    def _uncapitalize(self, string):
        return s[:1].lower() + s[1:]

    def __add__(self, other_name):
        if type(other_name) == str:
            return Name(self.name + "_" + other_name.lower())
        elif type(other_name) == Name:
            return Name(self.name + "_" + other_name.name)
        else:
            raise TypeError(f"Can't add Name to {type(other_name)}")

class Description:
    def __init__(self, root):
        self.text = (
            "\n".join([line.strip() for line in root.text.splitlines()])
            if root.text
            else ""
        )
        self.summary = option_map(root.attrib.get("summary"), lambda s: s.strip())

    def __repr__(self):
        return self.summary

class EnumEntry:
    def __init__(self, root):
        self.name = Name(root.attrib["name"])
        self.value = root.attrib["value"]
        self.summary = root.attrib.get("summary")

    def __repr__(self):
        return f"\t\t\t{self.name} ({self.value})"

class Enum:
    def __init__(self, root):
        self.name = Name(root.attrib["name"])
        self.description = None
        self.entries = []

        for child in root:
            if child.tag == "description":
                self.description = Description(child)
            elif child.tag == "entry":
                self.entries.append(EnumEntry(child))
            else:
                raise ScannerError(f'Unknown item in enum: "{child.tag}"')

    def __repr__(self):
        return f"\t\tEnum '{self.name}':\n" + "\n".join(
            map(lambda e: e.__repr__(), self.entries)
        )

class Arg:
    def __init__(self, root):
        self.name = Name(root.attrib["name"])
        self.type = validate_type(root.attrib["type"])
        self.interface = option_map(root.attrib.get("interface"), Name)
        self.nullable = root.attrib.get("allow-null") == "true"
        self.summary = root.attrib.get("summary")

    def is_interface(self):
        return self.type == "new_id"

    def __repr__(self):
        return f"{self.name}: {self.type}"

class ArgList:
    def __init__(self):
        self.args = []

    def add_arg(self, arg):
        self.args.append(arg)

    def return_arg(self):
        for arg in self.args:
            if arg.is_interface():
                return arg

    def parameters(self):
        for arg in self.args:
            if arg.is_interface() and arg.interface != None:
                continue
            yield arg

    def marshal_arguments(self):
        for arg in self.args:
            yield arg

    def __repr__(self):
        return "(" + ",".join(map(lambda a: a.__repr__(), self.args)) + ")"

class Event:
    def __init__(self, root):
        self.name = Name(root.attrib["name"])
        self.description = None
        self.args = []

        for child in root:
            if child.tag == "description":
                self.description = Description(child)
            elif child.tag == "arg":
                self.args.append(Arg(child))
            else:
                raise ScannerError(f'Unknown item in event: "{child.tag}"')

    def __repr__(self):
        return f"\t\tEvent '{self.name}' " + self.args.__repr__()

class Request:
    def __init__(self, root):
        self.name = Name(root.attrib["name"])
        self.description = None
        self.is_destructor = root.attrib.get("type") == "destructor"
        self.args = ArgList()

        for child in root:
            if child.tag == "description":
                self.description = Description(child)
            elif child.tag == "arg":
                self.args.add_arg(Arg(child))
            else:
                raise ScannerError(f'Unknown item in request: "{child.tag}"')

    def __repr__(self):
        return f"\t\tRequest '{self.name}' " + self.args.__repr__()

class Interface:
    def __init__(self, root):
        self.name = Name(root.attrib["name"])
        self.description = None

        self.enums = []
        self.events = []
        self.requests = []

        for child in root:
            if child.tag == "description":
                self.description = Description(child)
            elif child.tag == "enum":
                self.enums.append(Enum(child))
            elif child.tag == "event":
                self.events.append(Event(child))
            elif child.tag == "request":
                self.requests.append(Request(child))
            else:
                raise ScannerError(f'Unknown item in interface: "{child.tag}"')

    def __repr__(self):
        return (
            f"\tInterface '{self.name}':\n"
            + "\n".join(map(lambda e: e.__repr__(), self.enums))
            + "\n"
            + "\n".join(map(lambda e: e.__repr__(), self.events))
            + "\n"
            + "\n".join(map(lambda r: r.__repr__(), self.requests))
        )

class Specification:
    def __init__(self, root):
        assert root.tag == "protocol"
        self.name = Name(root.attrib["name"])
        self.copyright = None
        self.interfaces = []

        for child in root:
            if child.tag == "copyright":
                self.copyright = child.text
            elif child.tag == "interface":
                self.interfaces.append(Interface(child))
            else:
                raise ScannerError(f'Unknown item in specification: "{child.tag}"')

    def __repr__(self):
        return f"Protocol '{self.name}':\n" + "\n\n".join(
            map(lambda ch: ch.__repr__(), self.interfaces)
        )

def print_help():
    print("Usage: python scanner.py < [protocol-description.xml]")

def parse_string(string):
    root = ET.fromstring(string)
    return Specification(root)

def parse_stdin():
    return parse_string(sys.stdin.read())

def run():
    if len(sys.argv) > 1:
        print_help()
    else:
        print(parse_stdin())

if __name__ == "__main__":
    run()


import pandas as pd

champPath = '../files/leagueChampions.csv'
gamesPath = '../files/leagueDataset.csv'
# Making CSVS from Excel Datasheets

read_league_xlsx = pd.read_excel('../files/GamesListPatch108.xlsx',)
read_league_champions_xlsx = pd.read_excel('../files/GamesListPatch108.xlsx', sheet_name='ChampionsList')

read_league_xlsx.to_csv('gamesPath', index=None, header=True)
read_league_champions_xlsx.to_csv('champPath', index=None, header=True)

champsDF = pd.read_csv(champPath)
gamesDF = pd.read_csv(gamesPath)
print(gamesDF.head(20))


import tensorflow as tf
import numpy as np
from tensorflow.python.keras.optimizer_v2 import adam as adam_v2
from sklearn.metrics import accuracy_score
from pathlib import Path
import os
import time

import utils
from utils.options import config
import networks

class SeekerTrainer:

    def __init__(self, model, weight_dir='weights', log_dir='logs', optimizer=None, loss_function=None, debug=False):

        self.model = model
        self.debug = debug

        if not debug:
            self.weight_dir = weight_dir
            if not Path(weight_dir).is_dir():
                os.makedirs(weight_dir)

            self.log_dir = log_dir
            if not Path(log_dir).is_dir():
                os.makedirs(log_dir)
            self.train_summary_writer = tf.summary.create_file_writer(log_dir + '/batch')
            self.epoch_summary_writer = tf.summary.create_file_writer(log_dir + '/epoch')

        if optimizer:
            self.optimizer = optimizer
        else:
            self.optimizer = adam_v2.Adam()

        if loss_function:
            self.loss_function = loss_function
        else:
            self.loss_function = tf.keras.losses.CategoricalCrossentropy()

        self.iteration = 0
        self.epoch_loss = []
        self.total_train_loss = []
        self.validation_acc = []
        self.current_classification_loss = 0.

    def loss(self, x, y):

        y_ = self.model(x)

        classification_loss = self.loss_function(y_true=y, y_pred=y_)

        if not self.debug:
            with self.train_summary_writer.as_default():
                tf.summary.scalar('training loss', classification_loss, step=self.iteration)

        return classification_loss

    def train_batch(self, x, y):

        with tf.GradientTape() as tape:
            loss_value = self.loss(x, y)

        grads = tape.gradient(loss_value, self.model.trainable_variables)

        total_grad = np.abs(np.concatenate([g.numpy().flatten() for g in grads], axis=0)).sum()

        if not debug:
            with self.train_summary_writer.as_default():
                tf.summary.scalar('gradients', total_grad, step=self.iteration)

        self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))

        return loss_value

    def train(self, train_data, training_steps, max_epochs=10, test_data=None, validation_steps=None, update_every=6):

        last_update = start_time = time.time()

        for epoch in range(max_epochs):

            epoch_loss_avg = tf.keras.metrics.Mean()

            for i, (x, y) in enumerate(train_data):

                self.iteration += 1

                batch_loss = self.train_batch(x, y)

                epoch_loss_avg(batch_loss)
                self.total_train_loss.append(batch_loss)

                if i == training_steps:
                    break

                if (time.time() - last_update) >= update_every * 3600:
                    last_update = time.time()
                    print('\n  [Model has been successfully training for {:.1f} hours.'
                          'Currently at step {} of {}, in epoch {}]\n'.format((last_update - start_time) / 3600,
                                                                              i+1, training_steps, epoch+1))

            avg = epoch_loss_avg.result()

            if not debug:
                with self.epoch_summary_writer.as_default():
                    tf.summary.scalar('Average loss per epoch', avg, step=epoch+1)
            self.epoch_loss.append(avg)

            print('End of epoch {}. Average training Loss: {:.3f}'.format(epoch+1, avg))

            if test_data:
                acc = self.evaluate(test_data, validation_steps)
                if not debug:
                    with self.epoch_summary_writer.as_default():
                        tf.summary.scalar('Validation accuracy', acc, step=epoch+1)
                self.validation_acc.append(acc)
                print('Validation accuracy: {:.2f}%'.format(acc*100))

        time_elapsed = (time.time() - start_time)
        if time_elapsed < 3600:
            print('Training finished after {} mimutes.\n'.format(int(time_elapsed / 60)))
        else:
            print('Training finished after {:.1f} hours.\n'.format(time_elapsed / 3600))

    def evaluate(self, data, steps):

        accuracy = tf.keras.metrics.Mean()

        for i, (x, y) in enumerate(data):

            preds = self.model(x)

            y_pred = [np.argmax(pr) for pr in preds]
            y_true = [np.argmax(pr) for pr in y]
            accuracy(accuracy_score(y_true, y_pred))

            if i == steps:
                break

        return accuracy.result().numpy()

if __name__ == '__main__':

    # Experiment identifier
    identifier = config['identifier']

    # Model configurations
    model_id = config['model']
    pretrained_seeker_weights = None

    if config['seeker_weights']:
        p = Path(config['seeker_weights']).absolute()
        if p.exists():
            pretrained_seeker_weights = config['seeker_weights']
        else:
            print('No valid seeker weights found at:', config['seeker_weights'])
            print('Will train seeker from skratch.')

    # training configurations
    max_epochs = config['max_epochs']
    batch_size = config['batch_size']
    debug = config['debug']

    # Data configurations
    image_shape = (config['image_size'], ) * 2
    train_images = config['train_images']
    test_images = config['test_images']
    channels = config['channels']
    input_shape = image_shape + (channels,)
    num_classes = config['num_classes']

    if config['config'] == 'mnist':
        train_set = utils.datagen.mnist(batch_size=batch_size, split='train')
        test_set = utils.datagen.mnist(batch_size=batch_size, split='test')
    elif config['config'] == 'fashion':
        train_set = utils.datagen.fashion(batch_size=batch_size, split='train')
        test_set = utils.datagen.fashion(batch_size=batch_size, split='test')
    elif config['config'] == 'cifar10':
        train_set = utils.datagen.cifar10(batch_size=batch_size, split='train', channels=channels)
        test_set = utils.datagen.cifar10(batch_size=batch_size, split='test', channels=channels)
    elif config['config'] == 'cifar100':
        train_set = utils.datagen.cifar100(batch_size=batch_size, split='train', channels=channels)
        test_set = utils.datagen.cifar100(batch_size=batch_size, split='test', channels=channels)
    else:
        data_dir = Path(config['data_dir'])
        train_set = utils.datagen.image_generator(data_dir / 'train', batch_size=batch_size, image_shape=image_shape,
                                                  channels=channels)
        test_set = utils.datagen.image_generator(data_dir / 'test', batch_size=batch_size, image_shape=image_shape,
                                                 channels=channels)

    log_dir = str(Path('logs') / config['config'] / 'seeker' / identifier)
    weight_dir = str(Path('weights') / config['config'] / 'seeker' / identifier)

    print('Initializing seeker model')
    seeker = networks.seek.available_models[model_id](input_shape, num_classes)

    if pretrained_seeker_weights:
        print('Loading pre-trained seeker weights')
        seeker.load_weights(pretrained_seeker_weights)

    seeker_trainer = SeekerTrainer(model=seeker, weight_dir=weight_dir, log_dir=log_dir, debug=debug)

    with utils.training.WeightFailsafe(weight_dir, seeker, debug=debug):
        seeker_trainer.train(train_set, training_steps=train_images//batch_size,  max_epochs=max_epochs,
                             test_data=test_set, validation_steps=test_images//batch_size, update_every=6)

    print('Test set accuracy: {:.2f}%'.format(seeker_trainer.evaluate(test_set, test_images//batch_size) * 100))

    if not debug:
        final_weights = str(Path(weight_dir) / 'final_weights.h5')
        print('Saving model to:', final_weights)
        seeker.save_weights(final_weights)


def get_people_count(activity):
    counter = 0

    result = []

    for name in activity:
        if name not in result:
            result += [name]
            counter += 1

    print("All people on the concert are " + str(counter))
    return result


flag = 0
while flag != 99 :
    var = int(input("정수를 입력하세요 "))
    if var > 0:
        if var % 2 == 0:
            print("{}는 양짝수입니다.".format(var))
        else:
            print("{}는 양홀수 입니다.".format(var))

    elif var == 0:
        print("{}는 0입니다.".format(var))
    else:
        if var % 2 == 0:
            print("{}는 음짝수입니다.".format(var))
        else:
            print("{}는 음홀수 입니다.".format(var))
    flag = var


#! /usr/bin/env python2.6
# -*- coding: utf-8 -*-

__author__ = 'Justin S Bayer, <bayer.justin@googlemail.com>'

import cStringIO as StringIO
import json
import unittest

import drecks

class DrecksTest(unittest.TestCase):

  def setUp(self):
    self.stream = StringIO.StringIO()

  def test_json_reporter(self):
    self.logger = drecks.Logger()
    self.logger.register_reporter(drecks.JsonReporter(stream=self.stream))
    self.logger.log(('error', 'critical'), message='blablabla')
    self.logger.log(('error', 'network'), message='blablabla2')
    data = self.stream.getvalue()
    lines = data.split('\n')
    recovered1 = json.loads(lines[0][5:])
    self.assertEqual(recovered1['labels'], ['error', 'critical'])
    self.assertEqual(recovered1['message'], 'blablabla')

    recovered2 = json.loads(lines[1][5:])
    self.assertEqual(recovered2['labels'], ['error', 'network'])
    self.assertEqual(recovered2['message'], 'blablabla2')

  def test_filter(self):
    logger = drecks.Logger()
    r = drecks.ListReporter()
    r.filters.append(lambda l, i, t: 'error' in l)
    logger.register_reporter(r)
    logger.log(('error',), message="foo")
    logger.log(('no-error',), message="foo")
    self.assertEqual(r.items[0][0], ('error',))

  def test_getlogger(self):
    logger1 = drecks.get_logger('one')
    logger2 = drecks.get_logger('one')
    self.assertEqual(id(logger1), id(logger2))
    self.assertEqual(id(drecks._loggers.values()[0]), id(logger1))

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


import unittest

from linked_list.AddTwoNumbers import add_two_numbers
from linked_list.test.utils import transform_array_to_list_node, transform_list_node_to_array

class MyTestCase(unittest.TestCase):
    def test_add_two_numbers(self):
        list1 = transform_array_to_list_node(self, [2, 4, 3])
        list2 = transform_array_to_list_node(self, [5, 6, 4])
        res = add_two_numbers(self, list1, list2)
        actual = transform_list_node_to_array(self, res)

        self.assertEqual([7, 0, 8], actual)

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


"""
解答例:https://atcoder.jp/contests/abc202/submissions/26853748
"""

import sys
import math,itertools,bisect,heapq
from collections import defaultdict,deque,Counter
sys.setrecursionlimit(10**8)

#入力
input = sys.stdin.readline
inp = lambda : int(input())
inpl = lambda : list(map(int,input().split()))
inpl_1 = lambda : list(map(lambda x:int(x)-1, input().split()))
inpl_s = lambda : list(input().split())
inpl_grid = lambda H: [input() for i in range(H)]
inpl_2d = lambda H: [list(map(int,input().split())) for i in range(H)]

#各種定数
INF = float("INF")
MOD = 10**9+7 #問題によって変える

#各種関数
def stoi(ch,zero = "a"):
    return ord(ch)-ord(zero)

def itos(num,zero = "a"):
    return chr(num+ord(zero))

def yes_no(cond, Yes = "Yes", No = "No"):
    if cond:
        print(Yes)
    else:
        print(No)
N = inp()
A = inpl()
cnt = [0]*(N+1)
for i in A:
    cnt[i] += 1
B = inpl()
C = inpl_1()
ans = 0
for i in range(N):
    ans +=cnt[B[C[i]]]
print(ans)


"""

Facundo Montenegro 90329 -1k3

Turno 03 – Enunciado 02 [T3E2]:

Desarrolle un programa completo en Python, controlado por menú de opciones, que incluya las siguientes opciones:

1.)    Ingrese las tres notas obtenidas por un alumno en sus trabajos prácticos. Calcular y mostrar el promedio.
Además, mostrar su calificación final, teniendo en cuenta que si el promedio es menor a 4 su calificación es
"Insuficiente"; si el promedio es un valor mayor o igual a 4 pero menor a 7 su calificación es "Aprobado",
y si el promedio es mayor o igual a 7 entonces su calificación es “Sobresaliente”.

2.)    Ingresar una secuencia de números, a razón de un número por vuelta de ciclo. La carga de dicha secuencia
finaliza cuando se ingresa un cero. Se deberá determinar y mostrar la cantidad de números comprendidos entre 10 y 30
inclusive, y además el valor promedio de los números comprendidos en el intervalo ya mencionado.

3.)    Terminar el programa.

"""

print('Menu de opciones')
print('1- Notas Trabajo practico')
print('2- Secuencia de numeros ')
print('3- Salir')

opc = int(input('Ingrese una opcion: '))

while opc != 3:
    if opc == 1:

        calificacion = None

        nota_1 = int(input('Ingrese la nota #1: '))
        nota_2 = int(input('Ingrese la nota #2: '))
        nota_3 = int(input('Ingrese la nota #3: '))

        promedio = (nota_1 + nota_2 + nota_3) / 3

        if promedio < 4:
            calificacion = 'Insuficiente'
        elif promedio >= 4 and promedio < 7:
            calificacion = 'Aprobado'
        elif promedio >= 7:
            calificacion = 'Sobresaliente'

        print(f'El promedio es {round(promedio,2)}')
        print(f'Su calificacion es {calificacion}')

    elif opc == 2:

        numero = int(input('Ingrese un numero :  '))

        cont_numeros_intervalo = 0
        cont_numeros_cargados = 0
        sumatoria_numeros_intervalo = 0

        while numero != 0:

            cont_numeros_cargados += 1

            if numero <= 30 and numero >= 10:
                sumatoria_numeros_intervalo += numero
                cont_numeros_intervalo += 1

            numero = int(input('Ingrese un numero (con 0 corta) :  '))

        promedio_intervalo = sumatoria_numeros_intervalo / cont_numeros_intervalo

        print(f'Cantidad de numeros cargados: {cont_numeros_cargados}')
        print(f'Cantidad de numeros entre 10 y 30 inclusive: {cont_numeros_intervalo}')
        print(f'El valor promedio de los numeros en el intervalo es {promedio_intervalo}')

    else:
        print('Por favor, ingrese una opcion valida')

    print('Menu de opciones')
    print('1- Notas Trabajo practico')
    print('2- Secuencia de numeros ')
    print('3- Salir  ')

    opc = int(input('Ingrese una opcion: '))

print('Fin del programa')


#Stone Paper Scissor
import random

options = ["stone", "paper", "scissor"]
cpuScore = 0
userScore = 0
while True:
    user = input("Enter your choice : stone / paper / scissor : ")
    cpu = random.choice(options)
    print("User : {}, CPU : {}".format(user, cpu))
    if user == cpu:
        print("Tie...")
    elif user == "stone" and cpu == "paper":
        print("CPU Win...")
        cpuScore += 1
    elif user == "paper" and cpu == "scissor":
        print("CPU Win...")
        cpuScore += 1
    elif user == "scissor" and cpu == "stone":
        print("CPU Win...")
        cpuScore += 1
    elif user == "stone" and cpu == "scissor":
        print("User Win...")
        userScore += 1
    elif user == "paper" and cpu == "stone":
        print("User Win...")
        userScore += 1
    elif user == "scissor" and cpu == "paper":
        print("User Win...")
        userScore += 1
    print("CPU Score : {}, User Score : {}".format(cpuScore, userScore))


import logging
import argparse
import numpy as np
import pandas as pd
import os, sys
import matplotlib.pyplot as plt

from utils import plot_utils as pu
from utils import data_utils as du
from utils import conf_utils as cu
from utils import metric_utils as mu
from utils import science_utils as su
from utils import logging_utils as lu
from utils import utils_emcee_poisson as mc

plt.switch_backend("agg")

"""
TO REPRODUCE
- data: pippin/AM_DATA5YR.yml
- models: trained 1g. 26XB
- predictions: reproduce/1h.SNN_26XDESBOSSTED_DATA.sh

"""

def setup_logging():
    logger = None

    # Create logger using python logging module
    logging_handler_out = logging.StreamHandler(sys.stdout)
    logging_handler_out.setLevel(logging.DEBUG)

    logging_handler_err = logging.StreamHandler(sys.stderr)
    logging_handler_err.setLevel(logging.WARNING)

    logger = logging.getLogger("localLogger")
    logger.setLevel(logging.INFO)
    logger.addHandler(logging_handler_out)
    logger.addHandler(logging_handler_err)

    # create file handler which logs even debug messages
    fh = logging.FileHandler("logpaper.log", mode="w")
    fh.setLevel(logging.DEBUG)
    logger.addHandler(fh)

    return logger

if __name__ == "__main__":

    DES5yr = os.getenv("DES5yr")
    DES = os.getenv("DES")

    parser = argparse.ArgumentParser(description="Code to reproduce results paper")

    parser.add_argument(
        "--path_data_fits",
        type=str,
        default=f"{DES}/data/DESALL_forcePhoto_real_snana_fits/D_JLA_DATA5YR_DENSE_SNR/output/DESALL_forcePhoto_real_snana_fits/FITOPT000.FITRES.gz",
        help="Path to data SALT2 fits",
    )
    parser.add_argument(
        "--path_data_class",
        type=str,
        default=f"{DES}/DES5YR/data_preds/snndump_26XBOOSTEDDES/models/",
        help="Path to data predictions",
    )
    parser.add_argument(
        "--path_sim_fits",
        type=str,
        default=f"{DES}/DES5YR/snndump_5X/2_LCFIT/JLA_5XDES/output/PIP_AM_DES5YR_SIMS_TEST_5XDES/FITOPT000.FITRES.gz",
        help="Path to simualtion SALT2 fits (for selection efficiency)",
    )
    parser.add_argument(
        "--path_sim_class",
        type=str,
        default=f"{DES}/DES5YR/snndump_5X/models/",
        help="Path to sim predictions",
    )
    parser.add_argument(
        "--path_dump",
        default=f"./dump_DES5YR",
        type=str,
        help="Path to output & sample",
    )
    parser.add_argument(
        "--nofit", action="store_true", help="if no fit to selection function",
    )

    # Init
    args = parser.parse_args()
    path_data_fits = args.path_data_fits
    path_data_class = args.path_data_class
    path_sim_fits = args.path_sim_fits
    path_dump = args.path_dump
    path_sim_class = args.path_sim_class

    path_plots = f"{path_dump}/plots_sample_wz/"
    os.makedirs(path_plots, exist_ok=True)
    path_samples = f"{path_dump}/samples"

    # logger
    logger = setup_logging()

    # save configuration
    logger.info("_______________")
    logger.info("CONFIGURATION")
    logger.info(f"{args}")  # --path_sims {path_sims}"

    # Load sample
    path_sample = f"{path_samples}/photoIa_cosmo_quantile_average_probability_set_0.csv"
    lu.print_blue("Loading sample & fits", path_sample)
    sample = pd.read_csv(path_sample)
    data_fits = du.load_salt_fits(path_data_fits)
    # select only events that are in the selected photometric sample
    sample_fits = data_fits[data_fits.SNID.isin(sample.SNID)]
    lu.print_green(f"Photo Ia sample {len(sample)} fits: {len(sample_fits)}")

    lu.print_blue("Loading data preds cosmo_quantile", path_sim_fits)
    data_preds = du.load_merge_all_preds(
        path_class=path_data_class,
        model_name="vanilla_S_*_zspe*_cosmo_quantile_lstm_64x4_0.05_1024_True_mean",
        norm="cosmo_quantile",
    )

    # Load 5X simulation fits
    lu.print_blue("Loading sim fits", path_sim_fits)
    sim_fits = du.load_salt_fits(path_sim_fits)

    # same redshift cut than data
    sim_fits = sim_fits[(sim_fits["zHD"] > 0.05) & (sim_fits["zHD"] < 1.3)]
    # now options
    sim_JLA_fits = su.apply_JLA_cut(sim_fits)
    # select true SNe Ia and apply same JLA cuts than sample
    sim_Ia_fits = sim_fits[sim_fits.SNTYPE.isin(cu.spec_tags["Ia"])]
    sim_Ia_fits_JLA = su.apply_JLA_cut(sim_Ia_fits)

    lu.print_blue("Loading sim preds cosmo_quantile", path_sim_class)
    sim_preds = du.load_merge_all_preds(path_class=path_sim_class)

    # evaluate performance of our classification model in independent sims
    sim_wfits = pd.merge(sim_fits, sim_preds["cosmo_quantile"])
    sim_wfits_JLA = pd.merge(sim_JLA_fits, sim_preds["cosmo_quantile"])
    df_txt_stats_sel = pd.DataFrame(
        columns=["norm", "dataset", "method", "accuracy", "efficiency", "purity"]
    )
    df_txt_stats_JLA = pd.DataFrame(
        columns=["norm", "dataset", "method", "accuracy", "efficiency", "purity"]
    )
    for method, desc in cu.dic_sel_methods.items():
        list_seeds_sets = (
            cu.list_seeds_set[0] if method == "predicted_target_S_" else cu.list_sets
        )
        # sel cuts only
        df_txt_stats_sel = mu.get_multiseed_performance_metrics(
            sim_wfits,
            key_pred_targ_prefix=method,
            list_seeds=list_seeds_sets,
            df_txt=df_txt_stats_sel,
            dic_prefilled_keywords={
                "norm": "cosmo_quantile",
                "dataset": "selection cuts",
                "method": desc,
            },
        )
        # JLA only
        df_txt_stats_JLA = mu.get_multiseed_performance_metrics(
            sim_wfits_JLA,
            key_pred_targ_prefix=method,
            list_seeds=list_seeds_sets,
            df_txt=df_txt_stats_JLA,
            dic_prefilled_keywords={
                "norm": "cosmo_quantile",
                "dataset": "JLA",
                "method": desc,
            },
        )
    lu.print_green("Performance on 5XDES with cuts")
    print("Selection cuts")
    print(
        df_txt_stats_sel[["method", "accuracy", "efficiency", "purity"]].to_latex(
            index=False
        )
    )
    print("JLA cuts")
    print(
        df_txt_stats_JLA[["method", "accuracy", "efficiency", "purity"]].to_latex(
            index=False
        )
    )

    sim_cut_photoIa = sim_preds["cosmo_quantile"]["average_probability_set_0"] > 0.5
    sim_photoIa_fits = sim_JLA_fits[
        sim_JLA_fits.SNID.isin(sim_preds["cosmo_quantile"][sim_cut_photoIa].SNID.values)
    ]
    lu.print_yellow(
        "Assuming that redshift quality + multiseason cuts are not necessary in sims"
    )

    logger.info("")
    logger.info("Check selection function")
    lu.print_yellow("Using simulated SNe Ia")
    print("- with converging SALT2 fit")
    print("- using HOST efficiency from M. Vincenzi")

    # Selection function
    variable = "m0obs_i"
    quant = 0.01
    min_var = sample_fits[variable].quantile(quant)
    lu.print_yellow(
        f"Not using photo Ias with {variable}<{min_var} (equivalent to quantile {quant}, possible if low-z)"
    )
    df, minv, maxv = du.data_sim_ratio(
        sample_fits,
        sim_Ia_fits_JLA,
        var=variable,
        path_plots=path_plots,
        min_var=min_var,
        norm=1 / 150,  # the scale of the simulations vs. DES
    )
    if args.nofit:
        lu.print_red("Not doing sel function emcee_fitting!!!!")
    else:
        # Emcee fit of dat/sim
        theta_mcmc, min_theta_mcmc, max_theta_mcmc = mc.emcee_fitting(
            df, path_plots, min_var=min_var
        )

    # sanity ratio z
    variable = "zHD"
    quant = 0.01
    min_var = sample_fits[variable].quantile(quant)
    tmo, tmominv, mtmoaxv = du.data_sim_ratio(
        sample_fits,
        sim_Ia_fits_JLA,
        var=variable,
        path_plots=path_plots,
        min_var=min_var,
    )

    logger.info("")
    logger.info("General properties of sample & sim")
    # histo c,x1,z and c,x1 evolution by redshift
    pu.overplot_salt_distributions_lists(
        [sim_Ia_fits_JLA, sample_fits],
        list_labels=["sim Ia JLA", "Baseline DES JLA",],
        path_plots=path_plots,
    )
    # add info wether is deep fields or not
    sim_Ia_fits_JLA["deep"] = sim_Ia_fits_JLA["FIELD"].apply(
        lambda row: any(f in row for f in ["X3", "C3"])
    )
    sample_fits["deep"] = sample_fits["FIELD"].apply(
        lambda row: any(f in row for f in ["X3", "C3"])
    )
    sim_Ia_fits_JLA["shallow"] = sim_Ia_fits_JLA["FIELD"].apply(
        lambda row: any(
            f in row for f in ["X1", "X2", "C1", "C2", "E1", "E2", "S1", "S2"]
        )
    )
    sample_fits["shallow"] = sample_fits["FIELD"].apply(
        lambda row: any(
            f in row for f in ["X1", "X2", "C1", "C2", "E1", "E2", "S1", "S2"]
        )
    )
    # deep
    sim_Ia_fits_JLA_deep = sim_Ia_fits_JLA[sim_Ia_fits_JLA["deep"] == True]
    sample_fits_deep = sample_fits[sample_fits["deep"] == True]
    # shallow fields
    sim_Ia_fits_JLA_shallow = sim_Ia_fits_JLA[sim_Ia_fits_JLA["shallow"] == True]
    sample_fits_shallow = sample_fits[sample_fits["shallow"] == True]

    pu.overplot_salt_distributions_lists_deep_shallow(
        [sim_Ia_fits_JLA, sample_fits,],
        list_labels=["sim Ia JLA", "Baseline DES JLA",],
        path_plots=path_plots,
        suffix="deep_and_shallow_fields",
    )
    print("n events in each zbin")
    sample_fits.groupby("zHD_bin").count()["SNID"]

    logger.info("")
    logger.info("Effect of selection cuts")
    lu.print_blue("Loading data with only selection cuts")
    path_sample_selcuts = f"{path_samples}/only_selection_cuts.csv"
    tmp_sample_selcuts_only = pd.read_csv(path_sample_selcuts)
    selcuts_fits = data_fits[data_fits.SNID.isin(tmp_sample_selcuts_only.SNID.values)]

    logger.info("")
    logger.info("Effect of SNN models")
    path_plots_allmodels = f"{path_dump}/plots_sample/all_models/"
    os.makedirs(path_plots_allmodels, exist_ok=True)
    # on simulated SNe
    # contamination against all sims that go into photoIa
    pu.plot_contamination_list([(sim_preds, sim_JLA_fits)], path_plots=path_plots)
    # sim: check if there variations with different classification models
    pu.overplot_salt_distributions_allmodels(
        sim_fits,
        sim_preds["cosmo_quantile"],
        path_plots=path_plots_allmodels,
        namestr="sim",
    )

    # on data
    # after selection cuts!!!!!
    pu.overplot_salt_distributions_allmodels(
        selcuts_fits,
        data_preds["cosmo_quantile"],
        path_plots=path_plots_allmodels,
        namestr="selcuts",
    )

    # HD
    merged_sample_fits_with_preds = pd.merge(
        sample_fits, data_preds["cosmo_quantile"], on="SNID"
    )

    pu.plot_HD_residuals(
        merged_sample_fits_with_preds,
        f"{path_plots}/HDres.png",
        prob_key="average_probability_set_0",
    )


# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

import ast
from math import *

import bpy
from bpy.props import BoolProperty, StringProperty, EnumProperty, FloatVectorProperty, IntProperty
from mathutils import Vector
import json
import io

from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import fullList, updateNode, dataCorrect, match_long_repeat

"""
JSON format:
    {
        "vertices": [[1, 2, 3], [2, 3, 4], [4,5,6]],
        "edges": [[0,1]],
        "faces": [[0,1,2]]
    }
    In vertices list, any of numbers can be replaced by string (variable name).
"""

# To be extended?
safe_names = dict(sin=sin, cos=cos, pi=pi, sqrt=sqrt)

def get_variables(string):
    root = ast.parse(string, mode='eval')
    result = {node.id for node in ast.walk(root) if isinstance(node, ast.Name)}
    return result.difference(safe_names.keys())

# It could be safer...
def safe_eval(string, variables):
    env = dict()
    env.update(safe_names)
    env.update(variables)
    env["__builtins__"] = {}
    root = ast.parse(string, mode='eval')
    return eval(compile(root, "<expression>", 'eval'), env)

def evaluate(json, variables):
    result = {}
    result['edges'] = json['edges']
    result['faces'] = json['faces']
    result['vertices'] = []

    groups = {}

    for idx, vertex in enumerate(json['vertices']):
        v = []
        if isinstance(vertex, (list, tuple)) and len(vertex) == 3:
            coords = vertex
        elif isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance(vertex[-1], (str, list, tuple)):
            coords = vertex[:-1]
            g = vertex[-1]
            if isinstance(g, str):
                groupnames = [g]
            else:
                groupnames = g
            for groupname in groupnames:
                if groupname in groups:
                    groups[groupname].append(idx)
                else:
                    groups[groupname] = [idx]

        for c in coords:
            if isinstance(c, str):
                try:
                    val = safe_eval(c, variables)
                    #self.debug("EVAL: {} with {} => {}".format(c, variables, val))
                except NameError as e:
                    self.exception(e)
                    val = 0.0
            else:
                val = c
            v.append(val)
        result['vertices'].append(v)
    return result, groups

def selected_masks_adding(node):
    """ adding new list masks nodes if none """
    if node.outputs[0].is_linked: return
    loc = node.location

    tree = bpy.context.space_data.edit_tree
    links = tree.links

    mo = tree.nodes.new('MaskListNode')
    mv = tree.nodes.new('SvMoveNodeMK2')
    rf = tree.nodes.new('SvGenNumberRange')
    vi = tree.nodes.new('GenVectorsNode')
    mi = tree.nodes.new('SvMaskJoinNode')
    vd = tree.nodes.new('ViewerNode2')
    mo.location = loc+Vector((300,0))
    mv.location = loc+Vector((550,0))
    vi.location = loc+Vector((350,-225))
    rf.location = loc+Vector((0,-225))
    mi.location = loc+Vector((800,0))
    vd.location = loc+Vector((1000,0))

    links.new(node.outputs[0], mo.inputs[0])   #verts
    links.new(node.outputs[3], mo.inputs[1])   #mask
    links.new(mo.outputs[0], mi.inputs[0])   #mask
    links.new(mo.outputs[3], mv.inputs[0])   #True out
    links.new(vi.outputs[0], mv.inputs[1])   #vector
    links.new(rf.outputs[0], vi.inputs[2])   #range
    links.new(mv.outputs[0], mi.inputs[1])   #True in
    links.new(mo.outputs[4], mi.inputs[2])   #False
    links.new(mi.outputs[0], vd.inputs[0])   #Verts
    links.new(node.outputs[2], vd.inputs[1])   #Faces
    mi.Level = 2
    mo.level = 2
    rf.mode='FRANGE_COUNT'
    rf.stop_=4
    rf.count_=4

class SvJsonFromMesh(bpy.types.Operator):
    "JSON from selected mesh"
    bl_idname = "node.sverchok_json_from_mesh"
    bl_label = "JSON from mesh"
    bl_options = {'REGISTER'}

    nodename: StringProperty(name='nodename')
    treename: StringProperty(name='treename')

    def execute(self, context):
        node = bpy.data.node_groups[self.treename].nodes[self.nodename]
        if not bpy.context.selected_objects[0].type == 'MESH':
            node.info("JSON from mesh: selected object is not mesh")
            self.report({'INFO'}, 'It is not a mesh selected')
            return

        object = bpy.context.selected_objects[0]
        mesh = object.data
        result = {}
        verts = []
        isselected = False
        for v in mesh.vertices:
            names = set()
            for grp in v.groups:
                name = object.vertex_groups[grp.group].name
                names.add(name)
            if v.select:
                names.add('Selected')
                isselected = True
            if names:
                vertex = self.round(v) + [list(sorted(names))]
            else:
                vertex = self.round(v)
            verts.append(vertex)

        if isselected:
            if not 'Selected' in node.inputs.keys() and not node.outputs[0].is_linked:
                node.outputs.new('SvStringsSocket', 'Selected')
                if node.sample_tree:
                    selected_masks_adding(node)
        result['vertices'] = verts
        result['edges'] = mesh.edge_keys
        result['faces'] = [list(p.vertices) for p in mesh.polygons]

        self.write_values(self.nodename, json.dumps(result, indent=2))
        bpy.data.node_groups[self.treename].nodes[self.nodename].filename = self.nodename
        return{'FINISHED'}

    def round(self, vector):
        precision = bpy.data.node_groups[self.treename].nodes[self.nodename].precision
        vector = [round(x, precision) for x in vector.co[:]]
        return vector

    def write_values(self,text,values):
        texts = bpy.data.texts.items()
        exists = False
        for t in texts:
            if bpy.data.texts[t[0]].name == text:
                exists = True
                break

        if not exists:
            bpy.data.texts.new(text)
        bpy.data.texts[text].clear()
        bpy.data.texts[text].write(values)

class SvMeshEvalNode(bpy.types.Node, SverchCustomTreeNode):
    '''Parametric mesh JSON'''
    bl_idname = 'SvMeshEvalNode'
    bl_label = 'Mesh Expression'
    bl_icon = 'OUTLINER_OB_EMPTY'
    sv_icon = 'SV_MESH_EXPRESSION'

    def on_update(self, context):
        self.adjust_sockets()
        updateNode(self, context)

    filename: StringProperty(default="", update=on_update)
    precision: IntProperty(name = "Precision",
                    description = "Number of decimal places used for coordinates when generating JSON from selection",
                    min=0, max=10, default=8,
                    update=updateNode)

    sample_tree: BoolProperty(name = "Example tree",
                    description = "Create example nodes when generating JSON from selection",
                    default = False,
                    update=updateNode)

    def draw_buttons(self, context, layout):
        row = layout.row()
        row.prop_search(self, 'filename', bpy.data, 'texts', text='', icon='TEXT')
        row = layout.row()

        do_text = row.operator('node.sverchok_json_from_mesh', text='from selection')
        do_text.nodename = self.name
        do_text.treename = self.id_data.name

    def draw_buttons_ext(self, context, layout):
        self.draw_buttons(context, layout)
        layout.prop(self, "precision")
        layout.prop(self, "sample_tree")

    def sv_init(self, context):
        self.inputs.new('SvStringsSocket', "a")

        self.outputs.new('SvVerticesSocket', "Vertices")
        self.outputs.new('SvStringsSocket', "Edges")
        self.outputs.new('SvStringsSocket', "Faces")

    def load_json(self):
        internal_file = bpy.data.texts[self.filename]
        f = io.StringIO(internal_file.as_string())
        json_data = json.load(f)
        self.validate_json(json_data)
        return json_data

    def validate_json(self, json):
        if not "vertices" in json:
            raise Exception("JSON does not have `vertices' key")
        if not "edges" in json:
            raise Exception("JSON does not have `edges' key")
        if not "faces" in json:
            raise Exception("JSON does not have `faces' key")

    def get_variables(self):
        variables = set()
        json = self.load_json()
        if not json:
            return variables

        for vertex in json["vertices"]:
            if isinstance(vertex, (list, tuple)) and len(vertex) == 3:
                coords = vertex
            elif isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance(vertex[-1], (str, list, tuple)):
                coords = vertex[:-1]

            for c in coords:
                if isinstance(c, str):
                    vs = get_variables(c)
                    variables.update(vs)

        return list(sorted(list(variables)))

    def get_group_names(self):
        groups = set()
        json = self.load_json()
        if not json:
            return groups

        for vertex in json["vertices"]:
            if isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance(vertex[-1], (str, list, tuple)):
                g = vertex[-1]
                if isinstance(g, str):
                    names = [g]
                else:
                    names = g
                for name in names:
                    if name in ['Vertices', 'Edges', 'Faces']:
                        raise Exception("Invalid name for vertex group. It should not be Vertices, Edges or Faces.")
                    groups.add(name)

        return list(sorted(list(groups)))

    def get_defaults(self):
        result = {}
        json = self.load_json()
        if not json or 'defaults' not in json:
            return result
        if not isinstance(json['defaults'], dict):
            return result
        return json['defaults']

    def adjust_sockets(self):
        variables = self.get_variables()
        #self.debug("adjust_sockets:" + str(variables))
        #self.debug("inputs:" + str(self.inputs.keys()))
        for key in self.inputs.keys():
            if key not in variables:
                self.debug("Input {} not in variables {}, remove it".format(key, str(variables)))
                self.inputs.remove(self.inputs[key])
        for v in variables:
            if v not in self.inputs:
                self.debug("Variable {} not in inputs {}, add it".format(v, str(self.inputs.keys())))
                self.inputs.new('SvStringsSocket', v)

        groups = self.get_group_names()
        for key in self.outputs.keys():
            if key in ['Vertices', 'Edges', 'Faces']:
                continue
            if key not in groups:
                self.debug("Output {} not in groups {}, remove it".format(key, str(groups)))
                self.outputs.remove(self.outputs[key])
        for name in sorted(groups):
            if name not in self.outputs:
                self.debug("Group {} not in outputs {}, add it".format(name, str(self.outputs.keys())))
                self.outputs.new('SvStringsSocket', name)

    def update(self):
        '''
        update analyzes the state of the node and returns if the criteria to start processing
        are not met.
        '''

        # keeping the file internal for now.
        if not (self.filename in bpy.data.texts):
            return

        self.adjust_sockets()

    def get_input(self):
        variables = self.get_variables()
        defaults = self.get_defaults()
        result = {}
        default_results = {}

        for var in defaults.keys():
            d = defaults[var]
            if isinstance(d, (int, float)):
                default_results[var] = d

        for var in variables:
            if var in self.inputs and self.inputs[var].is_linked:
                result[var] = self.inputs[var].sv_get()[0]
                default_results[var] = result[var][0]
            else:
                value = defaults.get(var, 1.0)
                if isinstance(value, str):
                    #self.debug("Eval: {} = {}, {}".format(var, value, default_results))
                    value = safe_eval(value, default_results)
                    default_results[var] = value
                result[var] = [value]
            #self.debug("get_input: {} => {}".format(var, result[var]))
        return result

    def groups_to_masks(self, groups, size):
        result = {}
        for name in groups:
            result[name] = [idx in groups[name] for idx in range(size)]
        return result

    def process(self):

        if not self.outputs[0].is_linked:
            return

        var_names = self.get_variables()
        inputs = self.get_input()

        result_vertices = []
        result_edges = []
        result_faces = []
        result_masks_dict = {}

        template = self.load_json()

        if var_names:
            input_values = [inputs[name] for name in var_names]
            parameters = match_long_repeat(input_values)
        else:
            parameters = [[[]]]
        for values in zip(*parameters):
            variables = dict(zip(var_names, values))

            json, groups = evaluate(template, variables)
            verts = json['vertices']
            result_vertices.append(verts)
            result_edges.append(json['edges'])
            result_faces.append(json['faces'])

            masks = self.groups_to_masks(groups, len(verts))
            for name in masks.keys():
                if name in result_masks_dict:
                    result_masks_dict[name].add(masks[name])
                else:
                    result_masks_dict[name] = [masks[name]]

        self.outputs['Vertices'].sv_set(result_vertices)
        self.outputs['Edges'].sv_set(result_edges)
        self.outputs['Faces'].sv_set(result_faces)

        for name in result_masks_dict.keys():
            self.outputs[name].sv_set(result_masks_dict[name])

    def storage_set_data(self, storage):
        geom = storage['geom']
        filename = storage['params']['filename']

        bpy.data.texts.new(filename)
        bpy.data.texts[filename].clear()
        bpy.data.texts[filename].write(geom)

    def storage_get_data(self, storage):
        if self.filename and self.filename in bpy.data.texts:
            text = bpy.data.texts[self.filename].as_string()
            storage['geom'] = text
        else:
            self.warning("Unknown filename: {}".format(self.filename))

def register():
    bpy.utils.register_class(SvJsonFromMesh)
    bpy.utils.register_class(SvMeshEvalNode)

def unregister():
    bpy.utils.unregister_class(SvJsonFromMesh)
    bpy.utils.unregister_class(SvMeshEvalNode)


# compact directory tree, moving all files into current directory

import os
import sys

if len(sys.argv) < 2:
    print("usage: {0} <directory>".format(sys.argv[0]))
    sys.exit()

root_dir = sys.argv[1]

def scan_tree(path, cur_name):
    with os.scandir(path) as it:
        for entry in it:
            full_name = os.path.join(path, entry.name)
            if entry.is_dir():
                scan_tree(full_name, cur_name+entry.name+'_')
            elif cur_name:
                new_name = cur_name+entry.name
                print(new_name)
                os.rename(full_name, os.path.join(root_dir, new_name))

scan_tree(root_dir, '')


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

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

def main():

    myset = set()
    n = int(input())

    for _ in range(1, n + 1):
        myset.add(input())

    print(len(myset))

if __name__ == '__main__':
    main()


from django.db import models
from django.db.models import BooleanField, Exists, OuterRef, Q, Value
from users.models import User

class RecipeQuerySet(models.QuerySet):
    """
    Кастомный queryset для модели Recipe.
    Добавлены поля 'is_favorited' и 'is_in_shopping_cart'.
    """

    def annotated(self, user):
        """Ожидает на вход экземпляр модели 'user'."""

        # Проверяем все возможные ситуации с параметром 'user'.
        if (not isinstance(user, User)
                or user is None
                or not user.is_authenticated):
            return self.annotate(
                is_favorited=Value(False, output_field=BooleanField()),
                is_in_shopping_cart=Value(False, output_field=BooleanField())
            )
        return self.annotate(
            is_favorited=Exists(
                self.filter(
                    # Существует ли связка рецепт-любимый рецепт-юзер.
                    Q(recipe_favorite__recipe=OuterRef('pk'))
                    & Q(recipe_favorite__user=user)
                )),
            is_in_shopping_cart=Exists(
                self.filter(
                    # Существует ли связка рецепт-корзина-юзер.
                    Q(in_shopping_cart__recipe=OuterRef('pk'))
                    & Q(in_shopping_cart__user=user)
                ))
        )

class RecipeManager(models.Manager):
    """
    Кастомный менеджер для queryset'а Recipe.
    Метод annotated() принимает в качестве аргумента экземпляр юзера,
    либо None по умолчанию.
    Дальнейшая проверка юзера реализована в RecipeQueryset.
    """

    def get_queryset(self):
        return RecipeQuerySet(self.model, using=self._db)

    def annotated(self, user=None):
        return self.get_queryset().annotated(user)


"""
Library of matrix transformation functions adapted from vispy.
"""

from __future__ import division

# Note: we use functions (e.g. sin) from math module because they're faster

import math
import numpy as np
import numpy.linalg

def translate(offset, dtype=None):
    """Return an N-dimensional translation matrix (of shape N+1,N+1)

    Parameters
    ----------
    offset : array-like
        Amount to translate each axis
    dtype : dtype | None
        Output type (if None, then same as *offset*).

    Returns
    -------
    M : ndarray
        Transformation matrix describing the translation.
    """
    if dtype is None:
        dtype = offset.dtype
    M = np.eye(len(offset) + 1, dtype=dtype)
    M[-1, :len(offset)] = offset
    return M

def scale(s, dtype=None):
    """Return an N-dimensional scaling matrix (of shape N+1,N+1)

    Parameters
    ----------
    scale : array-like, shape (3,)
        Scale factors for each axis
    dtype : dtype | None
        Output type (if None, then same as *scale*).

    Returns
    -------
    M : ndarray
        Transformation matrix describing the scaling.
    """
    if dtype is None:
        dtype = scale.dtype
    return np.array(np.diag(np.concatenate([s, (1.,)])), dtype)

def rotate2d(angle, dtype=None):
    """Return a 2D rotation matrix (shape 2,2)

    Parameters
    ----------
    angle : float
        The angle of rotation, in degrees.
    dtype : dtype | None
        Output dtype
    """
    rad = np.radians(angle)
    c, s = math.cos(rad), math.sin(rad)
    M = np.array([
        [c,  s],
        [-s, c],
    ], dtype=dtype)
    return M

def rotate3d(angle, axis, dtype=None):
    """Return a 3D rotation matrix (shape 3,3) for rotation about a vector.

    Parameters
    ----------
    angle : float
        The angle of rotation, in degrees.
    axis : ndarray
        The x, y, z coordinates of the axis direction vector.
    dtype : dtype | None
        Output dtype
    """
    angle = np.radians(angle)
    assert len(axis) == 3
    x, y, z = axis / np.linalg.norm(axis)
    c, s = math.cos(angle), math.sin(angle)
    cx, cy, cz = (1 - c) * x, (1 - c) * y, (1 - c) * z
    M = np.array([
        [cx * x + c, cy * x - z * s, cz * x + y * s],
        [cx * y + z * s, cy * y + c, cz * y - x * s],
        [cx * z - y * s, cy * z + x * s, cz * z + c],
    ], dtype).T
    return M

def affine_map(points1, points2):
    """ Find an N-D affine transformation that maps points1 onto points2.

    Arguments are specified as arrays of coordinates, shape (N+1, N).
    """
    N = points1.shape[1]
    N1 = N + 1
    if points2.shape != (N1, N) or points1.shape != (N1, N):
        raise TypeError("Points must have shape (N+1, N)")
    A = np.ones((N1, N1))
    A[:, :N] = points1
    B = np.ones((N1, N1))
    B[:, :N] = points2

    # solve N sets of linear equations to determine
    # transformation matrix elements
    matrix = np.eye(N1)
    for i in range(N):
        # solve Ax = B; x is one row of the desired transformation matrix
        matrix[i] = np.linalg.solve(A, B[:, i])

    return matrix[:N]

def bilinear_map2d(points1, points2):
    """
    Find a bilinear transformation matrix (shape 2x4) that maps 2D points1 onto 2D points2.

    Parameters
    ----------
    points1 :  array-like (N, 2)
        Array of N+1 2D points
    points2 :  array-like (N, 2)
        Array of N+1 2D points

    To use this matrix to map a point [x,y]::

        mapped = np.dot(matrix, [x*y, x, y, 1])
    """
    ## A is 4 rows (points) x 4 columns (xy, x, y, 1)
    ## B is 4 rows (points) x 2 columns (x, y)
    A = np.array([[points1[i,0]*points1[i,1], points1[i,0], points1[i,1], 1] for i in range(4)])
    B = np.array([[points2[i,0], points2[i,1]] for i in range(4)])

    ## solve 2 sets of linear equations to determine transformation matrix elements
    matrix = np.zeros((2,4))
    for i in range(2):
        matrix[i] = numpy.linalg.solve(A, B[:,i])  ## solve Ax = B; x is one row of the desired transformation matrix

    return matrix

def frustum(left, right, bottom, top, znear, zfar):
    """Create view frustum

    Parameters
    ----------
    left : float
        Left coordinate of the field of view.
    right : float
        Right coordinate of the field of view.
    bottom : float
        Bottom coordinate of the field of view.
    top : float
        Top coordinate of the field of view.
    znear : float
        Near coordinate of the field of view.
    zfar : float
        Far coordinate of the field of view.

    Returns
    -------
    M : ndarray
        View frustum matrix (4x4).
    """
    assert(right != left)
    assert(bottom != top)
    assert(znear != zfar)

    M = np.zeros((4, 4))
    M[0, 0] = +2.0 * znear / float(right - left)
    M[2, 0] = (right + left) / float(right - left)
    M[1, 1] = +2.0 * znear / float(top - bottom)
    M[2, 1] = (top + bottom) / float(top - bottom)
    M[2, 2] = -(zfar + znear) / float(zfar - znear)
    M[3, 2] = -2.0 * znear * zfar / float(zfar - znear)
    M[2, 3] = -1.0
    return M


#!/usr/bin/python
# coding=utf-8

import urllib3
import datetime
import time
import urllib

# 创建连接特定主机的连接池
http_pool = urllib3.HTTPConnectionPool('ent.qq.com')
# 获取开始时间
now = time.localtime(time.time())
strStart = time.strftime("%Y/%m/%d %H:%M:%S", now)

for i in range(0, 100, 1):
    print(i)
    # 组合URL字符串
    url = 'http://ent.qq.com/a/20111216/%06d.htm' % i
    print(url)

    # 开始同步获取内容
    r = http_pool.urlopen('GET', url, redirect=False)
    print(r.status, r.headers, len(r.data))

# 打印时间
print('start time : ', strStart)

now = time.localtime(time.time())
strEnd = time.strftime("%Y/%m/%d %H:%M:%S", now)
print('end time : ', strEnd)


testCases = int(input())

for _ in range(testCases):
    num = int(input())
    inp = list(set(map(int, input().split())))
    inp = sorted(inp)
    flag = True

    if len(inp) == 1:
        print('YES')
        continue
    for i in range(len(inp) - 1):
        # print(i)
        if inp[i+1] - inp[i] <= 1:
            continue
        else:
            flag = False
            break
        #     del inp[i]
        #     # c +=1

    if flag:
        print("YES")
    else:
        print("NO")


#####создаем класс game
class game:
    #создаем атрибуты класса
    name="cs 1.6"
    model="шутер"
    founded="1996"
    #создаем методы класса
    def start(self):
        print ("запуск игры cs1.6")
    def maps (self):
        print("запуск карты dust 2")

    def stop(self):
        print("выход из игры cs1.6")

game_a=game()
game_b=game()
game_a.start()
game_a.maps()
game_b.stop()


import os
import numpy as np
import pickle

from data_collection import load_collections
from define import define
from resources import resources_dirname

area = define.details_areas['graphtarget']['label']

filepath = os.path.join(resources_dirname, 'graphtarget.res')
if os.path.exists(filepath):
    with open(filepath, 'rb') as f:
        table = pickle.load(f)
else:
    table = {}

def get_graphtarget(image_details):
    if image_details.height != define.details_trimsize[1]:
        return None

    np_value = np.array(image_details.crop(area))
    flattend = np_value.flatten()

    unique, counts = np.unique(flattend, return_counts=True)
    dark_count = np.count_nonzero(unique < 100)
    mode = unique[np.argmax(counts[dark_count:])+dark_count]

    if not mode in table.keys():
        return None

    count = np.count_nonzero(flattend==mode)
    if not count in table[mode].keys():
        return None

    return table[mode][count]

def larning_graphtarget(targets):
    global table

    print('larning graphtarget')
    print(f'count: {len(targets)}')

    table = {}
    keys = {}
    values = []
    for key, target in targets.items():
        value = target['value']
        np_value = target['np']
        flattend = np_value.flatten()

        unique, counts = np.unique(flattend, return_counts=True)
        dark_count = np.count_nonzero(unique < 100)
        mode = unique[np.argmax(counts[dark_count:])+dark_count]
        if not mode in table.keys():
            table[mode] = {}
            keys[mode] = {}

        count = np.count_nonzero(flattend==mode)
        if count in table[mode].keys():
            if table[mode][count] != value:
                print(f'mode: {mode}')
                print(f'count: {count}')
                print(f'value: {value}')
                print(f'key: {key}')
                print(f'duplicate: {table[mode][count]}, {keys[mode][count]}')
                print("NG")
                return
        else:
            table[mode][count] = value
            keys[mode][count] = key
            values.append(value)

    uniques, counts = np.unique(np.array(values), return_counts=True)
    multicount_values = [value for value in np.where(counts>=2,uniques,None) if value is not None]
    if len(multicount_values) != 0:
        print(multicount_values)
        print('NG')
        return

    with open(filepath, 'wb') as f:
        pickle.dump(table, f)

    return table

if __name__ == '__main__':
    collections = load_collections()

    targets = {}
    for collection in collections:
        label = collection.label
        if collection.details is not None:
            image = collection.details

            if 'graphtarget' in label['details'].keys() and label['details']['graphtarget'] != '':
                targets[collection.key] = {
                    'value': label['details']['graphtarget'],
                    'np': np.array(image.crop(area))
                }

    larning_graphtarget(targets)

    print(table)


"""
You can to create 2 instances of a `Price` class and to do operations between them:
        - add prices;
        - do a subtraction of prices.
"""

from dataclasses import dataclass
from decimal import Decimal

# Indices for conversion to dollars
convert_currencies: dict = {"USD": Decimal("1.00"), "EUR": Decimal("0.97"), "UAH": Decimal("0.027")}

# list of currencies available for calculation
currencies: list = [val for val in convert_currencies]

class PriceError(Exception):
    pass

@dataclass()
class Price:
    amount: Decimal
    currency: str  # currencies

    def __post_init__(self):
        if self.currency not in currencies:
            raise PriceError("❌ Price rejected. Currency is not supported.")

    def __str__(self) -> str:
        return f"The prise is {self.amount} {self.currency}"

    def __add__(self, other: "Price") -> "Price":
        self.comparison(other)
        print("⏳ Counting the total price...")
        return Price(amount=(self.amount + other.amount).quantize(Decimal("1.00")), currency=self.currency)

    def __sub__(self, other: "Price") -> "Price":
        self.comparison(other)
        if self.amount >= other.amount:
            print("⏳ Counting the difference...")
            return Price(amount=(self.amount - other.amount).quantize(Decimal("1.00")), currency=self.currency)
        else:
            raise PriceError("The negative price is not possible 😕")

    def comparison(self, other):
        """Currency comparison."""
        if self.currency != other.currency:
            self.convert()
            other.convert()

    def convert(self):
        """Performs currency conversion against the dollar"""
        for index in convert_currencies:
            if index == self.currency:
                self.amount *= convert_currencies[index]
                self.currency = "USD"

def create_price():
    """Creates an instances of a `Price` class"""
    user_input = input(f"Available currencies: {currencies}.   Enter the price in format:\nPRICE CURRENCY\n").split(" ")
    return Price(amount=Decimal(user_input[0]), currency=user_input[1].upper())

def handle_base_errors(func):
    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except PriceError as error:
            print(f"Error: {error}")
        except Exception as error:
            print(f"A certain error occurred: {error}")

    return inner

@handle_base_errors
def main():
    # Ask about prices
    price_a = create_price()
    price_b = create_price()

    price_c = price_a + price_b
    price_d = price_a - price_b

    print(price_c)
    print(price_d)

if __name__ == "__main__":
    main()


import pygame
from pygame.sprite import Sprite

class Ship(Sprite):

    def __init__(self, ai_seetings, screen):
        # 初始化飞船并设置其初始位置
        super(Ship, self).__init__()
        self.screen = screen
        self.ai_seetings = ai_seetings

        # 加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # 将每搜新飞船放在屏幕底部中央
        # 将飞船中心的x坐标设置为屏幕矩形的中心x坐标
        # 将飞船下边缘坐标设置为屏幕矩形的下边缘
        self.rect.centerx = self.screen_rect.centerx
        # 这里能看出来,self.rect=self.image.get_rect()是将类给赋值到这个属性上去了。
        # 所以这里是又在给self.rect这个类设置属性
        self.rect.bottom = self.screen_rect.bottom
        # 在飞船的属性center中存储小数值
        self.center = float(self.rect.centerx)
        self.moving_right = False
        self.moving_left = False

    def blitme(self):
        """在指定的位置绘制飞船"""
        self.screen.blit(self.image, self.rect)

    def update(self):
        """根据移动标志调整飞船的位置"""
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_seetings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_seetings.ship_speed_factor

        self.rect.centerx = self.center

    def center_ship(self):
        """让飞船在屏幕上居中"""
        self.center = self.screen_rect.centerx


import datetime

import requests

# response = requests.get(url="http://api.open-notify.org/iss-now.json")
# response.raise_for_status()
# response = response.json()
# long = response["iss_position"]["longitude"]
# print(f"The ISS is at Longitude:{long}")

# r = requests.get(url="https://api.kanye.rest")
# r = r.json()
# print(r)

MY_LAT = 52.375893
MY_LONG = 9.732010

parameters = {
    "lat": MY_LAT,
    "lng": MY_LONG,
    "formatted": 0,

}

r = requests.get(url="https://api.sunrise-sunset.org/json", params=parameters)
r.raise_for_status()
r = r.json()["results"]["sunrise"]
print(r)
print(datetime.datetime.now())


import unittest

import numpy as np

from ml4trade.domain.constants import SIMULATION_ENV_ACTION_SPACE
from ml4trade.domain.production import ProductionSystem
from ml4trade.domain.prosumer import Prosumer
from ml4trade.domain.units import MWh, Currency
from utils import setup_default_consumption_system, setup_default_clock, setup_default_battery, setup_default_market

class TestSetNewActions(unittest.TestCase):
    def setUp(self) -> None:
        clock = setup_default_clock()
        self.prosumer = Prosumer(
            battery=setup_default_battery(),
            clock_view=clock.view(),
            production_system=ProductionSystem(None, None),
            consumption_system=setup_default_consumption_system(clock),
            initial_balance=Currency(50),
            energy_market=setup_default_market()
        )
        self.action = SIMULATION_ENV_ACTION_SPACE.sample()
        self.prosumer.schedule(self.action)

    def test_set_new_buy_amounts(self):
        self.assertIsNone(self.prosumer.scheduled_buy_amounts)

        self.prosumer.set_new_actions()

        self.assertTrue(np.array_equal(
            self.prosumer.scheduled_buy_amounts,
            [MWh(a) for a in self.action[0:24]]
        ))

    def test_set_new_sell_amounts(self):
        self.assertIsNone(self.prosumer.scheduled_sell_amounts)

        self.prosumer.set_new_actions()

        self.assertTrue(np.array_equal(
            self.prosumer.scheduled_sell_amounts,
            [MWh(a) for a in self.action[24:48]]
        ))

    def test_set_new_buy_thresholds(self):
        self.assertIsNone(self.prosumer.scheduled_buy_thresholds)

        self.prosumer.set_new_actions()

        self.assertTrue(np.array_equal(
            self.prosumer.scheduled_buy_thresholds,
            [Currency(a) for a in self.action[48:72]]
        ))

    def test_set_new_sell_thresholds(self):
        self.assertIsNone(self.prosumer.scheduled_sell_thresholds)

        self.prosumer.set_new_actions()

        self.assertTrue(np.array_equal(
            self.prosumer.scheduled_sell_thresholds,
            [Currency(a) for a in self.action[72:96]]
        ))

    def test_next_day_actions(self):
        self.assertIsNotNone(self.prosumer.next_day_actions)

        self.prosumer.set_new_actions()

        self.assertIsNone(self.prosumer.next_day_actions)


import matplotlib.pyplot as plt

import re

numbers = re.compile('-?\d+.?\d+')

DDPG_LLC = 'ddpg_llc'
DDPG_MCC = 'ddpg_mcc'
PPO_LLC = 'ppo_llc'
PPO_MMC = 'ppo_mmc'

path = PPO_LLC

with open(path + '/episode_reward1.txt') as f:
    lines = f.readlines()
f.close()

means1 = []
deviations1 = []

for line in lines:
    result = list(map(float, numbers.findall(line)))
    means1.append(result[1])
    deviations1.append(result[2])

with open(path +'/episode_reward2.txt') as f:
    lines = f.readlines()
f.close()

means2 = []
deviations2 = []

for line in lines:
    result = list(map(float, numbers.findall(line)))
    means2.append(result[1])
    deviations2.append(result[2])

with open(path +'/episode_reward3.txt') as f:
    lines = f.readlines()
f.close()

means3 = []
deviations3 = []

for line in lines:
    result = list(map(float, numbers.findall(line)))
    means3.append(result[1])
    deviations3.append(result[2])

print(f'm1: {len(means1)}')
print(f'm2: {len(means2)}')
print(f'm3: {len(means3)}')

xs = [x for x in range(len(means1))]
mean_mean = [(x1+x2+x3)/3 for (x1,x2,x3) in zip(means1,means2,means3) ]

#plt.plot(xs, means, label="run 1")
#plt.plot(xs, means2, label="run 2")
#plt.plot(xs, means3, label="run 3")
plt.plot(xs, mean_mean, label="avg mean reward", color='r')
plt.xlabel("Episode")
plt.ylabel("Reward")
plt.legend(loc="lower right")

plt.show()


import discord
from discord import app_commands
from discord.ext import commands

import global_functions
from datas.datas import Datas

import random, asyncio

tirage_en_cours = False

class Tirage(commands.Cog):
    def __init__(self,bot):
        self.bot = bot

    #modo
    @app_commands.command(name="change_channel",description="permet de changer ou d'initialiser le channel d'un joueur")
    async def change_channel(self,interaction:discord.Interaction,user:discord.Member):
        await interaction.response.defer()
        player = global_functions.Player(user.name,user.id)
        player.is_player()
        if global_functions.bon_role(interaction.user):
            player.salon=interaction.channel_id
            player.update_stats_player_fichier()
            await interaction.edit_original_response(content=f"{Datas.emogi_cristal}** Le Salon perso de __{user}__ est désormais __{interaction.channel.name}__. ** {Datas.emogi_cristal}")
        else:
            await interaction.edit_original_response(content="vous n'avez pas le bon role")

    @app_commands.command(name="see_pity_of_a_player",description="permet de voir la pity d'un joueur")
    async def see_pity_of_a_player(self,interaction:discord.Interaction,user:discord.Member):
        await interaction.response.defer()
        if global_functions.bon_role(interaction.user):
            player=global_functions.Player(user.name,user.id)
            player.is_player()
            await interaction.edit_original_response(content=f"pour l'obtention d'une 4 étoiles: {player.pity[0]}/{player.pity[2]} \n pour l'obtention d'une 5 étoiles: {player.pity[1]}/{player.pity[3]}\n pour l'obtention d'une 6 étoiles: {player.pity[4]}/{player.pity[5]}")
        else:
            await interaction.edit_original_response(content="vous n'avez pas le bon role")

    @app_commands.command(name="edit_pity_of_a_player",description="permet de modifier la pity d'un joueur")
    async def edit_pity_of_a_player(self,interaction:discord.Interaction,user:discord.Member,dénominateur_4:int=False,dénominateur_5:int=False,numérateur_4:int=False,numérateur_5:int=False,dénominateur_6:int=False,numérateur_6:int=False):
        if global_functions.bon_role(interaction.user):
            await interaction.response.defer()
            player = global_functions.Player(user.name,user.id)
            player.is_player()
            if not numérateur_5:
                numérateur_5=player.pity[1]
            if not numérateur_4:
                numérateur_4=player.pity[0]
            if not dénominateur_4:
                dénominateur_4=player.pity[2]
            if not dénominateur_5:
                dénominateur_5=player.pity[3]
            if not numérateur_6:
                numérateur_6=player.pity[4]
            if not dénominateur_6:
                dénominateur_6=player.pity[5]
            player.pity = [numérateur_4,numérateur_5,dénominateur_4,dénominateur_5,numérateur_6,dénominateur_6]
            player.update_stats_player_fichier()
            await interaction.edit_original_response(content=f"le joueur {user.name} a désormais comme pity: \npour 4 étoiles: {player.pity[0]}/{player .pity[2]} \npour 5 étoiles {player.pity[1]}/{player .pity[3]} \net pour 6 étoiles: {player.pity[4]}/{player .pity[5]} ")
        else:
             await interaction.edit_original_response(content="vous n'avez pas le bon role")

    #players
    @app_commands.command(name="tirage",description="permet de faire des tirages")
    async def tirages(self,interaction:discord.Interaction,nombre_de_tirage:int):
        global tirage_en_cours
        await interaction.response.defer()
        player = global_functions.Player(interaction.user.id,interaction.user.id)
        player.is_player()
        channel_perso=self.bot.get_channel(player.salon)
        if player.nb_gemmes>=nombre_de_tirage and nombre_de_tirage<=10 and interaction.channel_id==Datas.channel_tirage_gacha and not tirage_en_cours:
            tirage_en_cours = True
            await interaction.edit_original_response(content=f"vous avez obtenus...")

            #yato
            """if player.yato_tirages>0:
                if nombre_de_tirage>player.yato_tirages:
                    nombre_de_tentative_gemmes=player.yato_tirages
                else:
                    nombre_de_tentative_gemmes=nombre_de_tirage
                compteur_de_gemmes=0
                for i in range(nombre_de_tentative_gemmes):
                    if random.randint(1,5)==4:
                        compteur_de_gemmes+=1
                        nombre_de_tirage-=1
                        player.nb_gemmes+=1
                        player.gemmes_spend+=1
                    player.yato_tirages-=1
                player.update_stats_player_fichier()
                for i in range(compteur_de_gemmes):
                    await channel_perso.send("vous avez gagné 2 gemmes")
                    if not interaction.channel==channel_perso:
                        await interaction.channel.send("vous avez gagné 2 gemmes")
                    await asyncio.sleep(2)
            player.update_stats_player_fichier()"""

            for i in player.tirages(nombre_de_tirage):
                if not type(i)==str:
                    i.is_item()
                    await asyncio.sleep(i.stars)
                    if player.salon!=1040228357981343764:
                        await channel_perso.send(f"{i.name} : {i.stars} étoiles :")
                    if not interaction.channel==channel_perso:
                        await interaction.channel.send(f"{i.name} : {i.stars} étoiles :")
                    if i.url_img:
                        if player.salon!=1040228357981343764:
                            await channel_perso.send(f"{i.url_img}")
                        if not interaction.channel==channel_perso:
                            await interaction.channel.send(f"{i.url_img}")
                else:
                    await asyncio.sleep(5)
                    await interaction.channel.send("vous avez gagné 2 cristaux d'expedition")
            tirage_en_cours = False
        elif not interaction.channel_id==Datas.channel_tirage_gacha:
            await interaction.edit_original_response(content=f"vous êtes dans le mauvais channel aller dans tirage gacha pour effectuer cette commande")
        elif nombre_de_tirage>10:
            await interaction.edit_original_response(content="vous ne pouvez éffectuer qu'un maximum de 10 tirages à la fois")
        elif tirage_en_cours:
            await interaction.edit_original_response(content=f"un tirage est déja en cours veuillez patienter et retenter plus tard")
        else:
            await interaction.edit_original_response(content=f"il vous manque {nombre_de_tirage-player.nb_gemmes} gemmes")

    @app_commands.command(name="see_pity",description="permet de voir sa pity")
    async def voir_sa_pity(self,interaction:discord.Interaction):
        await interaction.response.defer(ephemeral=True)
        player=global_functions.Player(interaction.user.name,interaction.user.id)
        player.is_player()
        await interaction.edit_original_response(content=f"**Votre pity :star::star::star::star: : {player.pity[0]}/{player.pity[2]} **\n**Votre pity :star::star::star::star::star: : {player.pity[1]}/{player.pity[3]} **\n**Votre pity :star::star::star::star::star::star: : {player.pity[4]}/{player.pity[5]} **")

async def setup(bot):
    await bot.add_cog(Tirage(bot))