import sqlite3
import os.path
from functools import wraps
from interfaces import Book, Preference

datab = None
db_init = {
    "create_books":
        "CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY ASC,name TEXT,path TEXT,'time' TIMESTAMP DEFAULT CURRENT_TIMESTAMP);",
    "create_history":
        "CREATE TABLE IF NOT EXISTS history (id INTEGER PRIMARY KEY ASC,book_id INTEGER,page TEXT,'time' TIMESTAMP DEFAULT CURRENT_TIMESTAMP);",
    "create_relation":
        "CREATE TABLE IF NOT EXISTS current (book_id INTEGER NOT NULL , history_id);",
    "create_prefs":"CREATE TABLE IF NOT EXISTS preferences (id INTEGER PRIMARY KEY ASC, name TEXT, style TEXT,zoom INTEGER);",
    "create_history_trigger":
        """CREATE TRIGGER on_read
            AFTER INSERT ON history
            BEGIN
                UPDATE current SET history_id = new.id WHERE book_id = new.book_id;
            END;""",
    "create_onbookadd_trigger":
        """CREATE TRIGGER on_book_add AFTER INSERT ON books BEGIN INSERT INTO current(book_id) VALUES(new.id); END;"""
    }

class db(object):
    db_name = "knowledge.db"

    def __init__(self):
        if not os.path.exists(self.db_name):
            db = sqlite3.connect(self.db_name)
            db.execute(db_init["create_books"])
            db.execute(db_init["create_history"])
            db.execute(db_init["create_relation"])
            db.execute(db_init["create_prefs"])
            db.execute(db_init["create_onbookadd_trigger"])
            db.execute(db_init["create_history_trigger"])
            # add default preferences
            db.execute("INSERT INTO preferences (name, style, zoom) VALUES('Normal','spreadNone','0');")
            db.execute("INSERT INTO preferences (name, style, zoom) VALUES('Novel','spreadOdd','0');")
            db.commit()
            db.close()

    def connect(self):
        return sqlite3.connect(self.db_name)

datab = db()

"""
Wraps database query aroud database connections , returns cached result
1->st arg of decorated function should be db connection
"""
def db_decorator(dbinstance):
    def f_dec(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            conn = dbinstance.connect()
            params = (conn,) + args;
            cache = func(*params, **kwargs)
            conn.commit()
            conn.close()
            return cache
        return wrapper
    return f_dec

@db_decorator(datab)
def save_data(conn, data):
    for change in data:
        res = conn.execute(
            f"INSERT INTO history (book_id,page) VALUES((SELECT id FROM books WHERE path = '{change}'),{data[change]});")

@db_decorator(datab)
def insert_book_db(conn, books):
    for book in books:
        res = conn.execute(
            f"INSERT INTO books(name,path) VALUES ('{book.name}','{book.path}');")
        conn.execute(
            f"INSERT INTO history (book_id,page) VALUES((SELECT id FROM books WHERE name = '{book.name}'),0);")

@db_decorator(datab)
def load_books(conn):
    res = conn.execute(
        'SELECT name,path,page FROM current INNER JOIN books ON books.id = current.book_id INNER JOIN history ON history.id = current.history_id;').fetchall()
    data = []
    for book in res:
        data.append(Book(name=book[0], path=book[1], page=book[2]))
    return data

@db_decorator(datab)
def load_prefs(conn):
    res = conn.execute(
        'SELECT name, style, zoom FROM preferences').fetchall()
    data = []
    for ref in res:
        data.append(Preference(name = ref[0], style = ref[1], zoom = ref[2]))
    return data

@db_decorator(datab)
def insert_pref_db(conn,pref):
    conn.execute(
            f"INSERT INTO preferences (name, style, zoom) VALUES('{pref.name}','{pref.style}','{pref.zoom}');")

@db_decorator(datab)
def mark_finished(conn,book_name):
    conn.execute(
            f"DELETE FROM current WHERE book_id = (SELECT id FROM books WHERE name = '{book_name}');")

if __name__ == "__main__":
    datab = db()


# 255. Verify Preorder Sequence in Binary Search Tree

'''
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.

Example 1:
Input: preorder = [5,2,1,3,6]
Output: true

Example 2:

Input: preorder = [5,2,6,1,3]
Output: false
'''
class Solution:
    def verifyPreorder(self, preorder: List[int]) -> bool:
        return self.constantSolution(preorder)

    # O(n) time | O(n) space
    def naiveTLE(self, preorder: List[int]) -> bool:
        def isSorted(arr: List[int]):
            if len(arr) <= 1:
                return True

            mid = 0

            while mid < len(arr) and arr[mid] <= arr[0]:
                mid += 1

            for i in range(mid + 1, len(arr)):
                if arr[i] <= arr[0]:
                    return False

            return isSorted(arr[1:mid]) and isSorted(arr[mid:])

        return isSorted(preorder)

    # O(n) time | O(n) space
    def stackSolution(self, preorder: List[int]) -> bool:
        stack = []
        low = float('-inf')

        for p in preorder:
            if p < low:
                return False

            while stack and p > stack[-1]:
                low = stack.pop()

            stack.append(p)

        return True

    # O(n) time | O(1) space, mutating input array
    def constantSolution(self, preorder: List[int]) -> bool:
        low = float('-inf')
        i = 0

        for p in preorder:
            if p < low:
                return False

            while i > 0 and p > preorder[i - 1]:
                low = preorder[i - 1]
                i -= 1

            preorder[i] = p
            i += 1

        return True

1. Problems/f. Trees/b. BST - Traversal - Verify Preorder Sequence in Binary Search Tree.py


import numpy as np
from navec import Navec

NAVEC_UNK = '<unk>'
NAVEC_PAD = '<pad>'
navec = Navec.load('saved/embedding/navec_hudlit_v1_12B_500K_300d_100q.tar')
DIMENSION_EMBEDDING = navec.get('<unk>').shape[0]

def vectorize_sentence(sentence: str, vectorizer=navec, unc_token=NAVEC_UNK, pad_token=NAVEC_PAD,
                       max_sequence_length=18) -> np.array:
    tokens = sentence.split()
    embedd_tokens = [vectorizer.get(t, vectorizer[unc_token]) for t in tokens[:max_sequence_length]]
    if len(embedd_tokens) < max_sequence_length:
        embedd_tokens += [vectorizer[pad_token]] * (max_sequence_length - len(embedd_tokens))
    return np.array(embedd_tokens)


import tkinter as Tk
from const import (WIDTH, HEIGHT)

BACKGROUND_COLOR = 'white'

class Frame(Tk.Frame):
    def __init__(self, master=None):
        Tk.Frame.__init__(self, master)
        self.master.title("FPS Simulater")
        self.master.geometry("+20+20")
        self.cvs = Tk.Canvas(self, width=WIDTH, height=HEIGHT, relief=Tk.SUNKEN, borderwidth=2, bg=BACKGROUND_COLOR)
        self.cvs.pack(fill=Tk.BOTH, expand=1)


from setuptools import setup, find_packages

with open("README.md") as readmeFile:
    readmeStr = readmeFile.read()

setup(
    name="parsegrammar",
    version="0.1.0",
    metadata_version="1.0",
    description="A library with Symbol Graph and Grammar classes",
    author="Laurkan Rodriguez",
    author_email="laurkan@engineer.com",
    long_description=readmeStr,
    long_description_content_type="text/markdown",
    url="https://github.com/lorkaan/parsegrammar.git",
    download_url="https://github.com/lorkaan/parsegrammar/archive/v0.1.0.tar.gz",
    install_requires =[],
    packages=['parsegrammar'],
    classifiers=[
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3.8",
        "Operating System :: OS Independent"
    ]
)


"""
Module to define Out of beam position.
"""
from typing import Optional, List, Tuple
from ReflectometryServer.geometry import Position

class OutOfBeamPosition:
    """
    The definition of a geometry component's out of beam position.
    """
    def __init__(self, position, tolerance: float = 1, threshold: Optional[float] = None, is_offset: bool = False):
        """
        Params:
            position: The out-of-beam position along the movement axis.
            tolerance: The tolerance around the position in which to consider the component as "out of beam"
            threshold: The threshold for the beam above which to consider this position to be "out of beam"
            is_offset: Turns the position into an offset so that the parked position follows the beam with the offset
                set added to it.
        """
        self._final_position = float(position)
        self.tolerance = float(tolerance)
        if threshold is not None:
            threshold = float(threshold)
        self.threshold = threshold
        self.is_offset = is_offset
        self._sequence = [position]

    def get_final_position(self) -> float:
        """

        Returns: final position out of beam position after any parking sequence has been executed

        """
        return self._final_position

    def get_sequence_position(self, parking_index):
        """
        Get the position at the current parking sequence. If past the end of the sequence return the final position
        Args:

            parking_index: parking sequence number; None for finally parking position

        Returns:
            parking position for index; None there is no sequence position for this index
        """
        if parking_index is None or len(self._sequence) <= parking_index:
            return None
        return self._sequence[parking_index]

    def get_parking_sequence_length(self):
        """
        Returns: length of the parking sequence
        """
        return len(self._sequence)

class OutOfBeamLookup:
    """
    Facilitates lookup of out-of-beam positions / status for a single axis out of a list of possible positions depending
    on where the beam intersects with that movement axis.
    """
    def __init__(self, positions: List[OutOfBeamPosition]):
        self._validate(positions)
        self._sorted_out_of_beam_positions = sorted(positions, key=lambda position:
                                                    (position.threshold is None, position.threshold), reverse=True)

    @staticmethod
    def _validate(positions):
        """
        Validate the given list of positions for this lookup.

        Args:
            positions (list[OutOfBeamPositions]: The positions
        """
        if positions:
            filter_default = [x for x in positions if x.threshold is None]
            if len(filter_default) == 0:
                raise ValueError("ERROR: No default Out Of Beam Position defined for lookup.")
            if len(filter_default) > 1:
                raise ValueError("ERROR: Multiple default Out Of Beam Position defined for lookup.")
            thresholds = [entry.threshold for entry in positions]
            if len(set(thresholds)) != len(thresholds):
                raise ValueError("ERROR: Duplicate values for threshold in different Out Of Beam positions.")
        else:
            raise ValueError("ERROR: No positions defined.")

    def get_position_for_intercept(self, beam_intercept: Position):
        """
        Returns the appropriate out-of-beam position along the movement axis for the given beam interception.

        Args:
            beam_intercept: The beam interception for the movement axis
                with out-of-beam positions

        Returns: The out-of-beam position
        """
        default_pos = self._sorted_out_of_beam_positions[0]
        pos_with_threshold_below_intercept = [x for x in self._sorted_out_of_beam_positions[1:] if
                                              x.threshold <= beam_intercept.y]
        if len(pos_with_threshold_below_intercept) > 0:
            position_to_use = pos_with_threshold_below_intercept[0]
        else:
            position_to_use = default_pos
        return position_to_use

    def out_of_beam_status(self, beam_intercept: Position, displacement: float, distance_from_beam: float,
                           parking_index: Optional[int]) -> Tuple[bool, bool]:
        """
        Checks whether a given value for displacement represents an out of beam position or at the end of the current
            sequence for a given beam interception and parking sequence number.

        Args:
            beam_intercept: The current beam interception
            displacement: The value to search in out of beam positions.
            distance_from_beam: Distance from the beam to the current position
            parking_index: current parking sequence index

        Returns:
            False if the given displacement represents an out of beam position, True otherwise
            True if the given displacement is at the end of the current sequence number, False otherwise;
                if parking sequence is None then return True we are at the end of the sequence because we are not
                waiting to finish movement; If we are after the last parking sequence also return True because we must
                have reached the last position
        """
        out_of_beam_position = self.get_position_for_intercept(beam_intercept)
        if out_of_beam_position.is_offset:
            axis_position = distance_from_beam
        else:
            axis_position = displacement
        in_beam = abs(axis_position - out_of_beam_position.get_final_position()) > out_of_beam_position.tolerance
        is_at_sequence_position = out_of_beam_position.get_sequence_position(parking_index)
        if is_at_sequence_position is None:
            at_sequence_index = True
        else:
            at_sequence_index = abs(axis_position - is_at_sequence_position) < out_of_beam_position.tolerance

        return in_beam, at_sequence_index

    def get_max_sequence_count(self):
        """

        Returns: maximum sequence length for any parking sequence

        """
        return max([position.get_parking_sequence_length() for position in self._sorted_out_of_beam_positions])

class OutOfBeamSequence(OutOfBeamPosition):
    """
    Out of Beam position which gives a sequence instead of just a fixed position.
    """

    def __init__(self, sequence, tolerance: float = 1, threshold: Optional[float] = None, is_offset: bool = False):
        """
        Initialise.
        Args:
            sequence: sequence of park positions that the component will go through when parking the axis. None is don't
                move it; if the sequence is too short last value is repeated
            tolerance: tolerance to within which the axis must get before the sequence number is increased or for final
                point that the axis is assumed to be out of beam
            threshold: The threshold for the beam above which to consider this position to be "out of beam"
            is_offset: Turns the position into an offset so that the parked position follows the beam with the offset
                set added to it.
        """
        self._validate(sequence)
        super(OutOfBeamSequence, self).__init__(sequence[-1], tolerance, threshold, is_offset)
        self._sequence = sequence

    def _validate(self, sequence):
        if sequence[-1] is None:
            raise ValueError("ERROR: Out of beam sequence ends in None this is not allowed")

        found_non_none = False
        for val in sequence:
            if val is None and found_non_none:
                raise ValueError("ERROR: Out of beam sequence has a None between values this is not allowed")
            elif val is not None:
                found_non_none = True


from ContaCorrente import ContaCorrente
from ContaPoupanca import ContaPoupanca

opcao_escolhida = 0

conta_poupanca = ContaPoupanca(123, 300)
conta_corrente = ContaCorrente(321, 500, 200)

#testando deposito e verificando rendimento sem determinar medida de tempo
conta_poupanca.depositar(100)
conta_poupanca.verificar_rendimento_ao_ano(5)
print(conta_poupanca.taxa_de_rendimento)
print(conta_poupanca.get_saldo())

#testando saque acima do valor
conta_poupanca.sacar(600)

#testando saque dentro do valor
conta_poupanca.sacar(10.0)
print(conta_poupanca.get_saldo())

#teste deposito conta corrente
conta_corrente.depositar(200)
print(conta_corrente.get_saldo())

#teste saque que da erro
conta_corrente.sacar(1000)

#teste saque que funciona
conta_corrente.sacar(200)
print(conta_corrente.get_saldo())


# The Four materials problem is a benchmark heat conduction problem in transient regime proposed by the CTTC (2016)
# https://pdfs.semanticscholar.org/7a2e/0e56e20f165507f24cb611ee0e2827b85118.pdf (Section 2.2)

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm

# Define the domain
x_len = 1.1
y_len = 0.8
x_points = 21
y_points = 17
del_x = x_len/float(x_points-1)
del_y = y_len/float(y_points-1)
x_gr = np.linspace(0, x_len, x_points)
y_gr = np.linspace(0, y_len, y_points)

# Define the parameters
t_steps = 100
del_t = 1

rho = np.zeros((x_points, y_points))
Cp = np.zeros((x_points, y_points))
lam = np.zeros((x_points, y_points))

for i in range(x_points):
    for j in range(y_points):
        if x_gr[i] < 0.5 and y_gr[j] < 0.4:
            rho[i,j] = 1500
            Cp[i,j] = 750
            lam[i,j] = 170
        elif x_gr[i] >= 0.5 and y_gr[j] < 0.7:
            rho[i, j] = 1600
            Cp[i, j] = 770
            lam[i, j] = 140
        elif x_gr[i] < 0.5 and y_gr[j] >= 0.4:
            rho[i, j] = 1900
            Cp[i, j] = 810
            lam[i, j] = 200
        else:
            rho[i, j] = 2500
            Cp[i, j] = 930
            lam[i, j] = 140

Temp = np.zeros((x_points, y_points))
Temp_new = np.zeros((x_points, y_points))
T_bott = 23
Q_top = 60
T_f = 33
alp = 9
Temp[:,0] = T_bott
Temp[-1, :] = 8

# Iterations
coeff_mat = np.zeros((y_points, y_points))
sol_mat = np.zeros(y_points)
for it in range(t_steps):
    for i in range(1, x_points-1):
        for j in range(1, y_points-1):
            aW = lam[i, j] * del_y / float(0.5 * del_x)
            aE = lam[i, j] * del_y / float(0.5 * del_x)
            aN = lam[i, j] * del_x / float(0.5 * del_y)
            aS = lam[i, j] * del_x / float(0.5 * del_y)
            Sp = - rho[i, j] * Cp[i, j] * del_x * del_y / float(del_t)
            Su = rho[i, j] * Cp[i, j] * del_x * del_y * Temp[i,j] / float(del_t)
            aP = aW + aE + aN + aS - Sp

            coeff_mat[j, j] = aP
            coeff_mat[j, j + 1] = -1.0 * aE
            coeff_mat[j, j - 1] = -1.0 * aW
            sol_mat[j] = Su

        # Bottom point
        aW = 0
        aE = 0
        aN = 0
        aS = 0
        aP = 1
        coeff_mat[0,0] = aP
        sol_mat[0] = T_bott

        # Top point
        aW = lam[i, -1] * del_y / float(0.5 * del_x)
        aE = 0
        aN = 0
        aS = lam[i, -1] * del_x / float(0.5 * del_y)
        Sp = - rho[i, -1] * Cp[i, -1] * del_x * del_y / float(del_t) - alp * del_y
        Su = rho[i, -1] * Cp[i, -1] * del_x * del_y * Temp[i,-1] / float(del_t) + Q_top*del_x
        aP = aW + aE + aN + aS - Sp
        coeff_mat[-1, -1] = aP
        coeff_mat[-1, -2] = -1.0* aW
        sol_mat[-1] = Su

        Temp[i,:] = np.linalg.solve(coeff_mat, sol_mat)

    # Left boundary
    for j in range(1, y_points-1):
        aW = 0
        aE = lam[0, j] * del_y / float(0.5 * del_x)
        aN = lam[0, j] * del_y / float(0.5 * del_y)
        aS = lam[0, j] * del_x / float(0.5 * del_y)
        Sp = - rho[0, j] * Cp[0, j] * del_x * del_y / float(del_t) - alp * del_y
        Su = rho[0, j] * Cp[0, j] * del_x * del_y * Temp[0, j] / float(del_t) + alp * del_y * T_f
        aP = aW + aE + aN + aS - Sp

        coeff_mat[j, j] = aP
        coeff_mat[j, j + 1] = -1.0 * aE
        coeff_mat[j, j - 1] = -1.0 * aW
        sol_mat[j] = Su

    # Bottom point
    aW = 0
    aE = 0
    aN = 0
    aS = 0
    aP = 1
    coeff_mat[0, 0] = aP
    sol_mat[0] = T_bott

    # Top point
    aW = lam[0, -1] * del_y / float(0.5 * del_x)
    aE = 0
    aN = 0
    aS = lam[0, -1] * del_x / float(0.5 * del_y)
    Sp = - rho[0, -1] * Cp[0, -1] * del_x * del_y / float(del_t) - alp * del_y
    Su = rho[0, -1] * Cp[0, -1] * del_x * del_y * Temp[0, -1] / float(del_t) + Q_top * del_x
    aP = aW + aE + aN + aS - Sp
    coeff_mat[-1, -1] = aP
    coeff_mat[-1, -2] = -1.0* aW
    sol_mat[-1] = Su

    Temp[0, :] = np.linalg.solve(coeff_mat, sol_mat)

    # Right boundary
    Temp[-1, :] = 8 + 0.005*it

print ("\n Temperature distribution is : \n" + str(Temp))
plt.contourf(y_gr, x_gr, Temp, cmap = cm.jet)
plt.colorbar()
plt.title("Temperature distribution for timestep: " + str(t_steps))
plt.savefig("Temp_dist.png")
plt.show()


import requests
from parsel import Selector
from lxml.html import fromstring
import csv
proxies = {
 'http': 'http://172.16.244.221:20001',
  'https': 'https://172.16.244.221:20001',
 }
Final_Data = []

#def Parse_Page(url):
resp = requests.get('https://www.gsmarena.com/',proxies=proxies)
parser = fromstring(resp.text)
Brand_List = parser.xpath("//div[@class='brandmenu-v2 light l-box clearfix']//li//a//@href")[:5]
print(Brand_List)
for brand in Brand_List:
    #Parse_Product(brand)
    resp = requests.get(brand)
    parser = fromstring(resp.text)
    Product_List = parser.xpath("///div[@class='makers']//li//a//@href").extract()

    for prod in Product_List:
            #Product_Data(prod)
        resp = requests.get(prod)
        parser = fromstring(resp.text)
        Product_Name = parser.xpath("//h1[@class='specs-phone-name-title']/text()")
        Product_Price = parser.xpath("//td[@data-spec='price']//a/text()")
        Product_Storage = parser.xpath("//td[@data-spec='internalmemory']/text()")
        Product_Network = parser.xpath("//td[@class='nfo']//a[@class='link-network-detail collapse']/text()")
        Product_Url = parser.xpath("//div[@class='specs-photo-main']//a/@href")
        for Item in zip(Product_Name, Product_Price, Product_Storage, Product_Network, Product_Url):
            Data = {
                'Name': Item[0],
                'Price': Item[1],
                'Storage': Item[2],
                'Network': Item[3],
                'URL': Item[4],
                    }
            Final_Data.append(Data)

#Parse_Page('https://www.gsmarena.com')
# toCSV = Final_Data
# keys = toCSV[0].keys()
# with open('Output.csv', 'w', newline='')  as output_file:
#     dict_writer = csv.DictWriter(output_file, keys)
#     dict_writer.writeheader()
#     dict_writer.writerows(toCSV)


import pytest
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction

from promocodes.models import Promocode

@pytest.mark.django_db
def test_cant_edit_promocode_name():

    promocode = Promocode.objects.create(name='PROMOCODE', type='additional_discount', discount=10)

    with pytest.raises(ValidationError) as e:
        promocode.name = 'PROMOCODE EDITED NAME'
        promocode.save()

    promocode.refresh_from_db()
    assert promocode.name == 'PROMOCODE'
    assert e.value.message == "Запрещено изменять название промокода. Создайте новый промокод, если хотите другое название."

@pytest.mark.django_db
def test_saving_in_uppercase():

    promocode = Promocode.objects.create(name='promocode', type='additional_discount', discount=10)
    promocode.refresh_from_db()

    assert promocode.name == 'PROMOCODE'

@pytest.mark.django_db
def test_cant_save_two_promocodes_with_equal_name_in_uppercase():
    with transaction.atomic():
        promocode = Promocode.objects.create(name='PROMOCODE', type='additional_discount', discount=10)
    with transaction.atomic():
        with pytest.raises(ValidationError) as e:
            promocode2 = Promocode.objects.create(name='promocode', type='additional_discount', discount=10)

    assert Promocode.objects.count() == 1

@pytest.mark.django_db
@pytest.mark.parametrize(
    "discount_type, discount",
    (
        ("additional_discount", -50),
        ("additional_discount", 0),
        ("additional_discount", 101),
        ("additional_discount", None),
        ("fix_discount", -50),
        ("fix_discount", 0),
        ("fix_discount", 101),
        ("fix_discount", None),
        ("additional_price", -1),
        ("additional_price", 0),
        ("additional_price", 8888888),
    )
)
def test_promocode_discount_validation(discount_type, discount):
    with pytest.raises(ValidationError) as e:
        Promocode.objects.create(name='PROMOCODE', type=discount_type, discount=discount)

    assert Promocode.objects.count() == 0


import numpy as np
from scipy import linalg

class PCA:
    def __init__(self, n, whiten):
        self.n = n
        self.n_components = n
        self.mean = None
        self.whiten = whiten

    def fit(self, X):

        n_samples, n_features = X.shape
        n_components = self.n_components

        self.mean = np.mean(X, axis=0)
        X -= self.mean

        U, S, Vt = linalg.svd(X, full_matrices=False)

        # flip eigenvectors' sign
        U, Vt = self.svd_flip(U, Vt)

        components_ = Vt

        explained_variance_ = (S ** 2) / (n_samples - 1)
        total_var = explained_variance_.sum()
        explained_variance_ratio_ = explained_variance_ / total_var
        singular_values_ = S.copy()  # Store the singular values.

        self.n_samples_, self.n_features_ = n_samples, n_features
        self.components_ = components_[:n_components]
        self.n_components_ = n_components
        self.explained_variance_ = explained_variance_[:n_components]
        self.explained_variance_ratio_ = \
            explained_variance_ratio_[:n_components]
        self.singular_values_ = singular_values_[:n_components]
        self.explained_variance = [i/np.sum(self.singular_values_) for i in self.singular_values_]

    def svd_flip(self,u, v):

        max_abs_cols = np.argmax(np.abs(u), axis=0)
        signs = np.sign(u[max_abs_cols, range(u.shape[1])])
        u *= signs
        v *= signs[:, np.newaxis]
        return u, v

    def transform(self, X):
        #X = X - self.mean
        if self.mean is not None:
            X = X - self.mean
        X_transformed = np.dot(X, self.components_.T)
        if self.whiten:
            X_transformed /= np.sqrt(self.explained_variance_)
        return X_transformed


import tensorflow as tf
import os
import sys
from models.utils.ConvFeatureDescriptor import ConvFeatureDescriptor

class RandomForest(object):

    def __init__(self, x_dim, y_dim, n_channels, n_classes, model_dir, n_trees=10, max_nodes=1000):
        self.x_dim = x_dim  # get dims from dataset json
        self.y_dim = y_dim
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.n_features = self.x_dim * self.y_dim
        self.model_dir = model_dir
        self.n_trees = n_trees
        self.max_nodes = max_nodes
        self.model = None

    def InitialiseModel(self, model_dir="model_dir"):
        params = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams(
            num_classes=self.n_classes,
            num_features=self.n_features,
            regression=False,  # We are strictly doing classification problems.
            num_trees=self.n_trees,
            max_nodes=self.max_nodes
        )

        self.model = tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator(params)
        self.descriptor = ConvFeatureDescriptor(batch_size=128, x_dim=self.x_dim, y_dim=self.y_dim)

    def TrainModel(self, x_train, y_train, batch_size, num_steps):

        descriptor = ConvFeatureDescriptor(batch_size=batch_size, x_dim=self.x_dim, y_dim=self.y_dim)
        x_train = descriptor.get_feature_vectors(x_train)  # Apply VGG16 feature detection to input data

        self.model.fit(x=x_train, y=y_train)

    def EvaluateModel(self, x_eval, y_eval, batch_size):

        descriptor = ConvFeatureDescriptor(batch_size=batch_size, x_dim=self.x_dim, y_dim=self.y_dim)
        x_eval = descriptor.get_feature_vectors(x_eval)  # Apply VGG16 feature detection to input data

        return self.model.evaluate(x=x_eval, y=y_eval)

    def Predict(self, x_predict):

        return self.model.predict(x=x_predict)

#
# if __name__ == "__main__":
#
#     base_path = os.getcwd().split("/")
#     while base_path[-1] != str("p5_afm_2018_demo"):
#         base_path = base_path[:-1]
#     sys.path.append(os.path.join("/".join(base_path) + "/models"))


#!/usr/bin/python
# -*- coding: UTF-8 -*-

def power(x):
    if x ** 2 >= 50:
        print('{}的平方为:{},不小于50，继续'.format(x, x ** 2))
    else:
        print('{}的平方为:{},小于50，退出'.format(x, x ** 2))
        quit()
while True:
    x = int(input('输入数字:'))
    power(x)


from sys import stdin

n1, n2 = map(int, stdin.readline().strip().split())
gcf = 1
i = 2
while i <= n1 and i <= n2:
    if n1 % i != 0 or n2 % i != 0:
        i += 1
    else:
        gcf *= i
        n1 //= i
        n2 //= i

print(gcf)
print(gcf * n1 * n2)

# Solution
def gcd(x, y):
    if y != 0:
        return gcd(y, x%y)
    else :
        return x
def lcm(x, y):
    return (x*y)//gcd(x,y)
N, M = map(int, input().split())

print(gcd(N, M))
print(lcm(N, M))


# import required packages
import os
import numpy as np

# set working directory appropriately by method
os.chdir("~/GaPP_27/Application/1_dgp_new/files/")      # for GPR
os.chdir("~/GaPP_27/Application/3_mcmcdgp_new/files/")  # for MCMC GPR
os.chdir("~/GaPP_27/Application/4_tpr_new/files/")      # for TPR

# returns (x, y, sigma) where x = 0, y = H_0, sigma = std. error
def geth0f(dataname, covname, pname):
    xysigma = open("H_" + dataname + "_" + covname + "_" + pname + ".txt").readline().strip().split()
    xysigma = [float(x) for x in xysigma]
    return xysigma

# sigma distance between two values of H0: see eq. (28) of Briffa et al. (2020)
def calcsigmadistance(h01, h02, sigmanp, sigmap):
    return round((h01 - h02) / np.sqrt(sigmanp ** 2 + sigmap ** 2), 4)

# list of covariance functions and priors
datas = ["CC", "CC+SN", "CC+SN+BAO"]
covfns = ["SquEx", "DoubleSquEx", "Matern32", "Matern52", "Matern72", "Matern92", "Cauchy", "RatQuadratic"]
priors = ["NoPrior", "Riess", "TRGB", "H0LiCOW", "CM", "Planck", "DES"]
priorvals = [None, 74.22, 69.8, 73.3, 75.35, 67.4, 67.4]
priorsdevs = [None, 1.82, 1.9, 1.7, 1.68, 0.5, 1.1]

# get and save H0 and sigma distance values in dictionaries
fxd = {}
fyd = {}
fydr = {}      # rounded values
fsigmad = {}
fsigmadr = {}  # rounded values
sigmadist = {}

# for each covfunction and prior and dataset:
for k in range(len(covfns)):
    for j in range(len(priors)):
        for i in range(len(datas)):

            ctr = tuple([datas[i], priors[j], covfns[k]])

            # get H0 value
            (fxd[ctr], fyd[ctr], fsigmad[ctr]) = geth0f(datas[i], covfns[k], priors[j])
            fydr[ctr] = round(float(fyd[ctr]), 3)
            fsigmadr[ctr] = round(float(fsigmad[ctr]), 4)
            print(covfns[k] + " " + datas[i] + " " + priors[j] + " f: " + str(fydr[ctr]) + " +/- " + str(fsigmadr[ctr]))

            # calculate sigma distance to each prior
            for p in range(len(priors)):
                if p != 0:  # exclude non-prior case
                    ctr2 = tuple([datas[i], priors[j], covfns[k], priors[p]])
                    sigmadist[ctr2] = calcsigmadistance(fyd[ctr], priorvals[p], fsigmad[ctr], priorsdevs[p])
                    print("Sigma Distance to " + priors[p] + ": " + str(sigmadist[ctr2]))

            print

# functions used in table generation
def gety(i1, j1, covfn):
    return "{:.3f}".format(round(fyd[datas[i1], priors[j1], covfn], 3))

def getsigma(i1, j1, covfn):
    return "{:.3f}".format(round(fsigmad[datas[i1], priors[j1], covfn], 3))

def getdist(i1, j1, covfn, p1):
    return "{:.4f}".format(sigmadist[datas[i1], priors[j1], covfn, priors[p1]])

def gettablerow(i1, j1, covfn):
    return str(gety(i1, j1, covfn)) + " \\pm " + \
           str(getsigma(i1, j1, covfn)) + "$ & $" + \
           str(getdist(i1, j1, covfn, 1)) + "$ & $" + \
           str(getdist(i1, j1, covfn, 2)) + "$ & $" + \
           str(getdist(i1, j1, covfn, 3)) + "$ & $" + \
           str(getdist(i1, j1, covfn, 4)) + "$ & $" + \
           str(getdist(i1, j1, covfn, 5)) + "$ & $" + \
           str(getdist(i1, j1, covfn, 6)) + "$ \\\\\n"

def printlatextable(covfn, alert=False):
    if alert:
        print("Printing table for " + covfn)
        print("---------------------------------------------------------")

    print("\\begin{landscape}\\thispagestyle{mylandscape}\n"
          "\\begin{table}[ht]\\centering\\small\n"
          "\\begin{tabular}{cccccccc}\n"
          "\\hline\n"
          "\\textbf{Dataset} &\n"
          "\\textbf{$\\hat{H}_0$} &\n"
          "\\textbf{$d(\\hat{H}_0, \\hat{H}_0^R)$} &\n"
          "\\textbf{$d(\\hat{H}_0, \\hat{H}_0^{TRGB})$} &\n"
          "\\textbf{$d(\\hat{H}_0, \\hat{H}_0^{HW})$} &\n"
          "\\textbf{$d(\\hat{H}_0, \\hat{H}_0^{CM})$} &\n"
          "\\textbf{$d(\\hat{H}_0, \\hat{H}_0^P)$} &\n"
          "\\textbf{$d(\\hat{H}_0, \\hat{H}_0^{DES})$} \\\\ \\hline\n"
          "CC                            & $" + gettablerow(0, 0, covfn) +
          "CC+SN                         & $" + gettablerow(1, 0, covfn) +
          "CC+SN+BAO                     & $" + gettablerow(2, 0, covfn) +
          "CC+$\\hat{H}_0^R$             & $" + gettablerow(0, 1, covfn) +
          "CC+SN+$\\hat{H}_0^R$          & $" + gettablerow(1, 1, covfn) +
          "CC+SN+BAO+$\\hat{H}_0^R$      & $" + gettablerow(2, 1, covfn) +
          "CC+$\\hat{H}_0^{TRGB}$        & $" + gettablerow(0, 2, covfn) +
          "CC+SN+$\\hat{H}_0^{TRGB}$     & $" + gettablerow(1, 2, covfn) +
          "CC+SN+BAO+$\\hat{H}_0^{TRGB}$ & $" + gettablerow(2, 2, covfn) +
          "CC+$\\hat{H}_0^{HW}$          & $" + gettablerow(0, 3, covfn) +
          "CC+SN+$\\hat{H}_0^{HW}$       & $" + gettablerow(1, 3, covfn) +
          "CC+SN+BAO+$\\hat{H}_0^{HW}$   & $" + gettablerow(2, 3, covfn) +
          "CC+$\\hat{H}_0^{CM}$          & $" + gettablerow(0, 4, covfn) +
          "CC+SN+$\\hat{H}_0^{CM}$       & $" + gettablerow(1, 4, covfn) +
          "CC+SN+BAO+$\\hat{H}_0^{CM}$   & $" + gettablerow(2, 4, covfn) +
          "CC+$\\hat{H}_0^P$             & $" + gettablerow(0, 5, covfn) +
          "CC+SN+$\\hat{H}_0^P$          & $" + gettablerow(1, 5, covfn) +
          "CC+SN+BAO+$\\hat{H}_0^P$      & $" + gettablerow(2, 5, covfn) +
          "CC+$\\hat{H}_0^{DES}$         & $" + gettablerow(0, 6, covfn) +
          "CC+SN+$\\hat{H}_0^{DES}$      & $" + gettablerow(1, 6, covfn) +
          "CC+SN+BAO+$\\hat{H}_0^{DES}$  & $" + gettablerow(2, 6, covfn) +
          "\\end{tabular}\n"
          "\\caption{MCMC GPR Results with " + str(covfn) + " covariance function}\n"
          "\\label{tab:MCMCdgp" + str(covfn) + "}\n"
          "\\end{table}"
          "\\end{landscape}")

    print

for k in range(len(covfns)):
    printlatextable(covfns[k])


from re import T
import ply.lex as lex
import ply.yacc as yacc
import math
import sys

#Constants
WAIT_UNTIL_END = "WAIT_UNTIL_END"
FUNCTION_CALL = "FUNCTION_CALL"
#Memory

lnNum = 0
blockLevel = 0
env = {}

#stacks
goto = []
prev = []
state = []
envStack = []
func_calls = []
func_return = []
func_blockLevel = []
passed_args = []

#Key Value pairs
funcGoto = {}           #Key -> Func Name, Value -> starting line number

#-- Lexical Analysis --

DEBUG = False
prompt = "Enter < 1 > for terminal\nEnter < 2 > for running file\n"

def peek_stack(stack):
    if stack:
        return stack[-1]
    else:
        return -1

#Convert inputs into tokens, run logic and compare valid syntax
reserved = {
    #'else' : 'ELSE',
}
tokens = [
    'INT',
    'FLOAT',
    'NAME',
    'PLUS',
    'MINUS',
    'DIVIDE',
    'MULTIPLY',
    'ASSIGN',
    'LESSTHAN',
    'GREATERTHAN',
    'EQUALS',
    'NOTEQUALS',
    'LPAREN',
    'RPAREN',
    'IF',
    'WHILE',
    'THEN',
    'END',
    'RETURN',
    'FUNC',
    'COMMA',
    'STRING',
    'PRINT',
    'FLOOR',
    'CEILING',
]+ list(reserved.values())
#PLY looks for the the syntax 't_' to register what a token will look like

# 'r' is for raw strings

t_PLUS = r'\+'
t_MINUS = r'\-'
t_MULTIPLY = r'\*'
t_DIVIDE = r'\/'
t_ASSIGN = r'\='
t_LESSTHAN = r'\<'
t_GREATERTHAN = r'\>'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_COMMA = r'\,'

t_WHILE = r'\🔁'
t_IF = r'\🤔'
t_THEN = r'\👶'
t_END = r'\💀'
t_FUNC = r'\#⃣'
t_RETURN = r'\↩'
t_PRINT = r'\🖨'
t_FLOOR = r'\📥'
t_CEILING = r'\📤'

t_ignore = r' '

#Function order matters! Lexer compares the functions from top to bottom.

# def t_char(t):
#    r'\'([^\\\n]|(\\.))*?\''

def t_STRING(t):
    r'\"([^\\\n]|(\\.))*?\"'
    t.value = str(t.value).replace('"', '')
    return t

def t_FLOAT(t):
    #Regular expression with a length greater than one in front and behind a point
    r'\d+\.\d+'
    t.value = float(t.value)
    return t

def t_INT(t):
    #Regular expression for any value of length greater than 1
    r'\d+'
    t.value = int(t.value)
    return t

def t_NAME(t):
    #Regular expression, variable name has to start with a character that is not a number
    r'[a-zA-Z_][a-zA-Z_0-9]*'
    t.type = reserved.get(t.value,'NAME')    # Check for reserved words
    return t

def t_EQUALS(t):
    #Only passes ==
    r'(?<!=)==(?!=)'
    return t

def t_NOTEQUALS(t):
    #This regex passes both == and !=
    r'(?<![!=])[!=]=(?!=)'
    return t

def t_COMMENT(t):
     r'\💬.*'
     pass
     # No return value. Token discarded

# Define a rule so we can track line numbers
def t_NEWLINE(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

def t_error(t):
    print("Illegal character on line "+ str(t.lexer.lineno) + " '%s'" % t.value[0])
    t.lexer.skip(1)

lexer = lex.lex()

#'precedence' removes ambiguity
precedence = (
    ('left', 'PLUS', 'MINUS'),
    ('left', 'MULTIPLY', 'DIVIDE')
)
#-- Parsing --

#Start of parser Tree
def p_emoticode(p):
    '''
    emoti : code
          | conditional
          | while
          | function
          | end
    '''
    p[0] = p[1]

def p_code(p):
    #Exists to execute other blocks without running emoticode
    '''
     code : expression
          | var_assign
          | return
          | print
          | empty
    '''
    global state
    #Do not run until parser finds END
    if peek_stack(state) == WAIT_UNTIL_END:
        p[0] = None
    else:
        p[0] = p[1]

def p_var_assign(p):
    '''
    var_assign : NAME ASSIGN expression
    '''
    p[0] = ('=', p[1], p[3])

def p_expression(p):
    #recursive expression, allows expressions such as 1+2+3+4...+n
    '''
    expression : expression PLUS expression
               | expression DIVIDE expression
               | expression MULTIPLY expression
               | expression MINUS expression
               | expression LESSTHAN expression
               | expression GREATERTHAN expression
               | expression EQUALS expression
               | expression NOTEQUALS expression
    '''
    # line  = p.lineno(2)        # line number of the PLUS token
    # index = p.lexpos(2)        # Position of the PLUS token

    #expression tree
    p[0] = (p[2], p[1], p[3])

def p_function(p):
    '''
    function : FUNC NAME LPAREN args RPAREN THEN
    '''
    #Check if there is a request to run the function
    p[0] = ('function', p[2], p[4])

def p_conditional(p):
    '''
    conditional : IF expression THEN
    '''

    p[0] = ('cond', p[2])

def p_while(p):
    '''
    while : WHILE expression THEN
    '''
    global state
    global goto
    #If false, skip the loop
    p[0] = ('while', p[2])

def p_end(p):
    '''
    end : END
    '''

    p[0] = ('end', p[1])

def p_return(p):
    '''
    return : RETURN expression
           | RETURN empty

    '''
    p[0] = ('return', p[2])

def p_args(p):
    '''
    args : args COMMA args
    '''
    #needs existing variables names to be passed as args
    # if not create new vars with the pass values
    p[0] = ('args', p[1], p[3])

def p_args_single(p):
    '''
    args : NAME
         | empty
    '''
    p[0] = ('args', p[1], None)

def p_callfunc(p):
    '''
    callfunc : NAME LPAREN param RPAREN
    '''
    #If the result for the function was resolved, return the result
    if peek_stack(func_return) != -1 and peek_stack(func_return) is not None:
        #Remove and return from funcEnv
        p[0] = func_return.pop()
    else:
        p[0] = ('callfunc', p[1], p[3])

def p_param(p):
    '''
    param : param COMMA param
    '''
    p[0] = ('param', p[1], p[3])

def p_params_single(p):
    '''
    param : expression
          | empty
    '''
    p[0] = ('param', p[1], None)

def p_expression_var(p):
    '''
    expression : NAME
    '''
    #Expression will be evaluated to whatever the value is
    p[0] = ('var', p[1])

def p_expression_data(p):
    '''
    expression : INT
               | FLOAT
               | STRING
               | callfunc
               | floor
               | ceiling
    '''
    #Expression will be evaluated to whatever the value is
    p[0] = p[1]

def p_expression_parenthesis(p):
    '''
    expression : LPAREN expression RPAREN
    '''
    #remove parentheses, evaluate anything inside parenthesis as seperate expression
    p[0] = p[2]

def p_print(p):
    '''
    print : PRINT LPAREN expression RPAREN
    '''
    p[0] = ('print', p[3])

def p_floor(p):
    '''
    floor : FLOOR LPAREN expression RPAREN
    '''
    p[0]= ('floor', p[3])

def p_ceiling(p):
    '''
    ceiling : CEILING LPAREN expression RPAREN
    '''
    p[0]= ('ceiling', p[3])

def p_error(p):
    print("Syntax Error Found!")

def p_empty(p):
    '''
    empty :
    '''
    p[0] = None

parser = yacc.yacc()

def run(p):
    global env
    global blockLevel
    global func_calls
    global func_return
    global goto
    global lnNum

    #runs parse
    if type(p) == tuple:
        if p[0] == '+':
            return run(p[1]) + run(p[2])
        elif p[0] == '-':
            return run(p[1]) - run(p[2])
        elif p[0] == '*':
            return run(p[1]) * run(p[2])
        elif p[0] == '/':
            return run(p[1]) / run(p[2])
        elif p[0] == '<':
            return run(p[1]) < run(p[2])
        elif p[0] == '>':
            return run(p[1]) > run(p[2])
        elif p[0] == '==':
            return run(p[1]) == run(p[2])
        elif p[0] == '!=':
            return run(p[1]) != run(p[2])
        elif p[0] == 'print':
            output = str(run(p[1]))
            if output != "None":
                return print(">> " + output)

        elif p[0]=='floor':
            return math.floor(run(p[1]))

        elif p[0]=='ceiling':
            return math.ceil(run(p[1]))

        elif p[0] == 'while':
            blockLevel +=1
            if not run(p[1]) or peek_stack(state) == WAIT_UNTIL_END:
                #If true, run the block and run the check again
                state.append(WAIT_UNTIL_END)
            else:
                #Add while line# to goto stack for later reference
                goto.append(lnNum)

        elif p[0] == 'function':
            blockLevel += 1
            if peek_stack(func_calls) == str(p[1]):
                #Function starts
                func_blockLevel.append(blockLevel)
                func_calls.pop()
                #Run args
                run(p[2])
            else:
                #register the function in the dictionary
                funcGoto[str(p[1])] = lnNum
                state.append(WAIT_UNTIL_END)

        elif p[0] == 'cond':
            #If WAIT_UNTIL_END before conditional, then add to the stack and ignore this step
            blockLevel += 1
            if not run(p[1]) or peek_stack(state) == WAIT_UNTIL_END:
                state.append(WAIT_UNTIL_END)

        elif p[0] == 'callfunc':
            #append a goto back to the line where the function was called
            prev.append(lnNum)
            #append the function's goto line number to the goto stack
            goto.append(funcGoto[p[1]])
            #append a new function call, immediately activates goto. Pass function name
            func_calls.append(p[1])
            #Run the params
            return run(p[2])

        elif p[0] == "param":
            #last param inserted first, pops last
            param2 = run(p[2])
            param1 = run(p[1])

            #Pass none empty parameters
            if param2 is not None:
                passed_args.append(param2)
            if param1 is not None:
                passed_args.append(param1)

        elif p[0] == "args":
            #create vars in a scope
            argName1 = run(p[1])
            if argName1 is not None:
                envStack.append({argName1 : passed_args.pop()})

            argName2 = run(p[2])
            if argName2 is not None:
                envStack.append({argName2 : passed_args.pop()})

        elif p[0] == 'return':
            #exit function
            blockLevel = peek_stack(func_blockLevel)-1
            #Append the expression result to the return stack
            func_return.append(run(p[1]))

        elif p[0] == 'end':
            blockLevel -= 1
            if peek_stack(state) != -1:
                state.pop()
            run(p[1])

        elif p[0] == '=':
            env[p[1]] = run(p[2])
            if DEBUG:
                print(env)

        elif p[0] == 'var':
            envScope = peek_stack(envStack)

            #Prioritize global vars
            if p[1] in env:
                return env[p[1]]

            elif envScope != -1:
                if p[1] in envScope:
                    #print(envScope[p[1]])
                    #only look at variables within the top of the stack (scope)
                    return envScope[p[1]]
            else:
                return 0
    else:
        return p

filename = input("Input the file name (Ex: test.ec , loop.ec, func.ec, countdown.ec):\n")
if DEBUG:
    print("\nDEBUG IS ON.\n")
with open(filename,"r") as f:
    # readlines() returns a list of items, each item is a line in your file
    data = f.readlines()

    while lnNum < len(data):

        result = parser.parse(data[lnNum])
        run(result)
        lnNum += 1

        # print(goto)

        prevLn = peek_stack(prev)
        peekBlock = peek_stack(func_blockLevel)
        gotoLn = peek_stack(goto)

        if peek_stack(func_calls) != -1: #if a function was called, jump to it
            lnNum = goto.pop()
        #Start of GOTO logic -> handles jumps between lines

        #Handle loops
        elif result and gotoLn > 0:
            #Goto's trigger on END when inside a loop
            if result[0] == 'end':
                #Resolve any WAIT states before goto's
                if peek_stack(state) != -1:
                    state.pop()
                else:
                    #modify lnNum, start from the goto line
                    lnNum = goto.pop()

        #Handle functions

        elif result and prevLn > 0:
            #If exited block level, that means function was exited
            if blockLevel < peekBlock:
                lnNum = prev.pop()
                func_blockLevel.pop()
                #release variables in function scope
                envStack.pop()


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

class Custom_Conv1d(nn.Module):
    def __init__(self, filter_size, patch_dim, linear=True, small_init=True):
        super(Custom_Conv1d, self).__init__()
        self.conv = nn.Conv1d(in_channels=1, out_channels=filter_size, kernel_size=int(patch_dim), stride=int(patch_dim))
        self.filter_size = filter_size
        self.linear = linear
        if small_init:
            self.conv.weight = torch.nn.Parameter(self.conv.weight*0.001)
            self.conv.bias = torch.nn.Parameter(self.conv.bias*0.001)

    def cubic_act(self, x):
        return x**3

    def forward(self, x):
        # x: [num_data, 1, num_patches * patch_dim]
        x = self.conv(x)
        # x: [num_data, filter_size, num_patches]
        if self.linear == False:
            x = self.cubic_act(x)
        x = torch.sum(x, dim=-1)
        output = torch.stack([torch.sum(x[:,:self.filter_size//2],1), torch.sum(x[:,self.filter_size//2:],1)]).transpose(1,0)

        return output

class MoE(nn.Module):
    def __init__(self, num_patches, num_expert, patch_dim, filter_size, device, linear=True, strategy='top-1'):
        super(MoE, self).__init__()
        self.gating_param = nn.Conv1d(in_channels=1, out_channels=num_expert, kernel_size=int(patch_dim*num_patches/num_patches), stride=int(patch_dim*num_patches/num_patches))
        self.softmax = nn.Softmax(dim=-1)
        self.num_expert = num_expert
        self.strategy = strategy # Gating strategy

        self.expert = nn.ModuleList()
        self.device = device
        for i in range(num_expert):
            self.expert.append(Custom_Conv1d(filter_size, patch_dim, linear))

        # Zero init
        self.gating_param.weight = torch.nn.Parameter(self.gating_param.weight * 0)

    def forward(self, x, training=True):
        # x [num_data, 1, num_patches * patch_dim]

        # h: [num_data, num_expert, num_patches]
        h = self.gating_param(x)

        # h: [num_data, num_expert]
        h = torch.sum(h, dim=-1)

        # Calculate π : [num_data, num_expert]
        if self.strategy == 'top-1':
            if training:
                h = h + torch.rand((h.shape[0], h.shape[1])).to(self.device)
            # this will be argmax top 1 routing
            pi_val, pi_idx = h.topk(k=1, dim=-1)
            mask = F.one_hot(pi_idx, self.num_expert).type(torch.float)
            density = mask.mean(dim=0)
            density_h = h.mean(dim=0)
            loss = (density_h * density).mean() * float(self.num_expert ** 2)

            # We did not implement mask_flat that controls exceeded expert_capacity
            # Original paper not used it
            combine_tensor = (pi_val[..., None] * mask)

            dispatch_tensor = torch.einsum('bne->ben', mask)

            # x: [num_data, 1, num_patches * patch_dim]
            # dispatch_tensor: [num_data, num_expert, 1]
            # expert_inputs: [num_expert, num_data, 1, num_patches * patch_dim]
            expert_inputs = torch.einsum('bnd,ben->ebd', x, dispatch_tensor).unsqueeze(dim=2)
            output = []
            for i in range(self.num_expert):
                output.append(self.expert[i](expert_inputs[i]))
            output = torch.stack(output, dim=0)
            # output: [num_expert, num_data, 2]
            # dispatch_tensor [num_data, num_expert, 1]
            combine_tensor = torch.transpose(combine_tensor, dim0=-2, dim1=-1)
            output = torch.einsum("dei,edj->dj", combine_tensor, output)
        else:
            # [to-do] soft-routing model
            pi_val = self.softmax(h)

            # pi_val, pi_idx: [num_data, num_expert]
            # pi_idx returns order of idx from lowest to highest value
            # [lowest_value_idx, ..., highest_value_idx]
            pi_idx = torch.argsort(pi_val, dim=-1)

        return output, dispatch_tensor.squeeze(dim=-1), loss


import itertools
integers = (i for i in range(1, 11))
squared = (x * x for x in integers)
negated = (-y for y in squared)
for num in negated:
    print(num)

with open("capitals.txt") as file:
    single_line_gen = (line for line in file)
    capitals_and_cities = (l.replace("\n", ("")).split(",") for l in single_line_gen)
    capitals_dict = dict(capitals_and_cities)
    print(capitals_dict)

def parse_ranges(ranges_string):
    ranges_string = ranges_string.replace(' ', '')
    first_generator = (x.split('-') for x in ranges_string.split(','))
    second_generator = ([k for k in range(int(x), int(y) + 1)] for x, y in first_generator)
    third_generator = itertools.chain.from_iterable(second_generator)
    return third_generator

print(list(parse_ranges("1-2,4-4,8-10")))
print(list(parse_ranges("0-0,4-8,20-21,43-45")))


# 动物父类
import yaml

class Animal:

    def __init__(self, name, color, age, sex):
        self.name = name
        self.color = color
        self.age = age
        self.sex = sex

    def call(self):
        print(f"{self.name} can be call")

    def run(self):
        print(f"{self.name} can be run")

# 猫的子类
class Cat(Animal):

    def __init__(self, name, color, age, sex, hair="短发"):
        self.name = name
        self.color = color
        self.age = age
        self.sex = sex
        self.hair = hair

    def CatchMouse(self):
        print(f"{self.name}会捉老鼠")

    def call(self):
        print("喵喵叫")

# 狗的子类
class Dog(Animal):

    def __init__(self, name, color, age, sex, hair="长毛"):
        self.name = name
        self.color = color
        self.age = age
        self.sex = sex
        self.hair = hair

    def CareHome(self):
        print(f"{self.name}会看家")

    def call(self):
        print("汪汪叫")

if __name__ == '__main__':
    with open("animal_data.yml", 'rb') as f:
        datas = yaml.safe_load(f)
    # 从配置文件读取猫的属性
    cat = datas["cat"]
    cat_name = cat["name"]
    cat_color = cat["color"]
    cat_age = cat["age"]
    cat_sex = cat["sex"]
    # 猫的实例
    cat1 = Cat(cat_name, cat_color, cat_age, cat_sex)
    # 调用猫桌老鼠的方法
    cat1.CatchMouse()
    # 打印猫的属性
    print(f"猫的名字叫{cat1.name}，颜色为{cat1.color}，年龄{cat1.age}岁，性别{cat1.sex}，毛发为{cat1.hair}，捉到了老鼠。")

    # 从配置文件读取狗的属性
    dog = datas["dog"]
    dog_name = dog["name"]
    dog_color = dog["color"]
    dog_age = dog["age"]
    dog_sex = dog["sex"]
    # 狗的实例
    dog1 = Dog(dog_name, dog_color, dog_age, dog_sex)
    # 狗看家
    dog1.CareHome()
    # 打印狗的属性
    print(f"狗的名字叫{dog1.name}，颜色为{dog1.color}，年龄{dog1.age}岁，性别{dog1.sex}，毛发为{dog1.hair}")


"""
This script is the `main` script, which is the entry point to the :mod:
`einstein`. The user can input a variety of arguments to run the models
for analyzing and experimenting with solar data. Evaluation metrics such
as 'r-Squared', 'Mean Absolute Error' and 'Root Mean Squared Error' are
returned for analysis, on running the regression models, and plots of
'GHI', 'DHI' and 'DNI' versus the timestamps are returned for analysis,
on running the `PVLibModel`.

Author:
-----------
Aashish Yadavally
"""
import argparse
import subprocess
import pandas as pd
import findspark
findspark.init()

from einstein.dataset import Loader
from einstein.models.isotonic import IsotonicRegressor
from einstein.models.linear import (LinearRegressor, RidgeRegressor,
                                    LassoRegressor)
from einstein.models.trees import DTRegressor, RFRegressor, GBTreeRegressor
from einstein.utils.summary_table import draw

def get_parser():
    """Creates a new argument parser

    Returns:
        parser (argparse.ArgumentParser)
            Parser contains user-defined arguments
    """
    parser = argparse.ArgumentParser(description='Solar Irradiance Prediction')
    parser.add_argument('--model', dest='model', default='mlr', type=str,
                        choices=['mlr', 'rr', 'lr', 'dt', 'rf', 'gbt', 'pvlib',
                                 'ir'], help='PVLib Forecast Model, or Models\
                                 for prediction: Linear Regression, Ridge\
                                 Regression, Lasso Regression, Decision Trees,\
                                 Random Forests, Gradient Boost Trees,\
                                 Isotonic Regression')
    parser.add_argument('--grid', dest='grid', default='3', type=str,
                        choices=['1', '3', '5'], help='1 -> (1, 1) ;\
                        3 -> (3, 3); 5 -> (5, 5)\nGrid Size - Grid sizes\
                        around ATHENS location')
    parser.add_argument('--encrypt_bucket', dest='encrypt_bucket', type=str,
                        required=True, help='Google Storage\
                        Bucket address containing the encrypted files')
    parser.add_argument('--decrypt_bucket', dest='decrypt_bucket', type=str,
                        required=True, help='Google Storage\
                        Bucket address containing the key text file and\
                        where the decrypt files are saved')
    parser.add_argument('--year', dest='year', default='2017', type=str,
                        choices=['2017', '2018', '2017_2018'],
                        help='NAM-NMM data year range')
    parser.add_argument('--target_hr', dest='target_hr', default=1, type=int,
                        choices=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
                        help='Prediction for hour offset in the reftime\
                        dimension')
    parser.add_argument('--maxDepth', dest='maxDepth', type=int, help='Maximum\
                        number of levels in each decision tree - parameter for\
                        Decision Trees, Random Forests, Gradient Boost Trees')
    parser.add_argument('--maxBins', dest='maxBins', type=int,
                        help='Number of bins used for discretizing continuous\
                        features - parameter for Decision Trees, Random\
                        Forests, Gradient Boost Trees')
    parser.add_argument('--numTrees', dest='numTrees', type=int, help='Number\
                        of trees in the ensemble - parameter for Random\
                        Forests.')
    parser.add_argument('--maxIter', dest='maxIter', type=int, help='Maximum\
                        number of iterations - parameter for Linear\
                        Regresion, Ridge Regression, Lasso Regression,\
                        Gradient Boost Trees')
    parser.add_argument('--tol', dest='tol', type=float, help='Convergence\
                        tolerance for iterative algorithms - parameter for\
                        Linear Regression, Ridge Regression, Lasso Regression')
    parser.add_argument('--regParam', dest='regParam', type=float,
                        help='Regularization parameter - parameter for Linear\
                        Regression, Ridge Regression, Lasso Regression')
    parser.add_argument('--loss', dest='loss', type=str, help='Loss function \
                        to be optimized - parameter for Linear Regression,\
                        Ridge Regression, Lasso Regression.')
    parser.add_argument('--epsilon', dest='epsilon', type=float, help='The \
                        shape parameter to control the amount of robustness\
                        (must be > 1.0) - parameter for Linear Regression,\
                        Ridge Regression, Lasso Regression')
    parser.add_argument('--isotonic', dest='isotonic', default='True',
                        type=bool, choices=[True, False],
                        help='Isotonicity of model')
    parser.add_argument('--fm', dest='forecast_model', type=str, help='PVLib\
                        Forecast Model', default='NAM',
                        choices=['NAM', 'RAP', 'GFS', 'NDFD', 'HRRR'])
    parser.add_argument('--start', dest='start', type=pd.Timestamp,
                        help='Start of PVLib Forecast')
    parser.add_argument('--stop', dest='stop', type=pd.Timestamp, help='End\
                        of PVLib Forecast')
    parser.add_argument('--lat', dest='lat', type=float, help='Latitude')
    parser.add_argument('--lon', dest='lon', type=float, help='Longitude')
    parser.add_argument('--test', dest='test', type=bool, default=False,
                        choices=[True, False], help='To run the test suite')
    return parser

def run(args=None):
    '''Main entry point for :mod: `einstein` project

    Arguments:
        args (list):
            A list of arguments as input in the command line at the time of
            execution of the project. `None` lets it use sys.argv
    '''
    parser = get_parser()
    args = parser.parse_args()

    if args.test:
        print('Running Test Suite...')
        subprocess.call("python -m pytest", shell=True)
    elif args.model == "pvlib":
        from einstein.models.pvlib import PVLibModel

        pvlib_model = PVLibModel(model_name=args.forecast_model, lat=args.lat,
                                 lon=args.lon, start=args.start,
                                 stop=args.stop)
        pvlib_model.plot()
    else:
        filename = f'{args.year}_{args.grid}.csv'

        loader = Loader(target_hour=args.target_hr,
                        encrypt_path=args.encrypt_bucket,
                        decrypt_path=args.decrypt_bucket,
                        filename=filename)
        df = loader.load_data().repartition(48)
        input_cols = loader.input_cols
        if args.model == "mlr":
            model_name = 'Linear Regression'
            regressor = LinearRegressor(input_cols, maxIter=args.maxIter,
                                        regParam=args.regParam, tol=args.tol,
                                        loss=args.loss, epsilon=args.epsilon)
        elif args.model == "rr":
            model_name = 'Ridge Regression'
            regressor = RidgeRegressor(input_cols, maxIter=args.maxIter,
                                       regParam=args.regParam, tol=args.tol,
                                       loss=args.loss, epsilon=args.epsilon)
        elif args.model == "lr":
            model_name = 'Lasso Regression'
            regressor = LassoRegressor(input_cols, maxIter=args.maxIter,
                                       regParam=args.regParam, tol=args.tol,
                                       loss=args.loss, epsilon=args.epsilon)
        elif args.model == "dt":
            model_name = 'Decision Tree'
            regressor = DTRegressor(input_cols, maxDepth=args.maxDepth,
                                    maxBins=args.maxBins)
        elif args.model == "rf":
            model_name = 'Random Forest'
            regressor = RFRegressor(input_cols, numTrees=args.numTrees,
                                    maxDepth=args.maxDepth,
                                    maxBins=args.maxBins)
        elif args.model == "gbt":
            model_name = 'Gradient Boost Tree'
            regressor = GBTreeRegressor(input_cols, maxDepth=args.maxDepth,
                                        maxIter=args.maxIter,
                                        maxBins=args.maxBins)
        elif args.model == 'ir':
            model_name = 'Isotonic Regression'
            regressor = IsotonicRegressor(input_cols, isotonic=args.isotonic)
        train_df, test_df = df.randomSplit([0.9, 0.1], seed=100)
        # Repartitioning the data
        train_df.repartition(48)
        test_df.repartition(48)
        r2, mae, rmse = regressor.fit_transform(train_df, test_df)

        metrics = {'r-Squared': r2, 'Mean Absolute Error': mae,
                   'Root Mean Squared Error': rmse}
        # Deleting the data from the bucket
        subprocess.run(f'gsutil rm {args.decrypt_bucket}{filename}',
                       shell=True)
        # Print the Regression Statistics Summary
        draw(args.year, args.target_hr, args.grid, model_name, metrics)

if __name__ == '__main__':
    run()


from django.shortcuts import render
from tethys_sdk.permissions import login_required
from tethys_sdk.gizmos import Button
from tethys_sdk.gizmos import DataTableView

@login_required()
def home(request):
    """
    Controller for the app home page.
    """

    datatable_default = DataTableView(
        column_names=('Name', 'Age', 'Job'),
        rows=[('Bill', 30, 'contractor'),
            ('Fred', 18, 'programmer'),
            ('Bob', 26, 'boss')],
        searching=False,
        orderClasses=False,
        lengthMenu=[ [10, 25, 50, -1], [10, 25, 50, "All"] ],
        )

    save_button = Button(
        display_text='',
        name='save-button',
        icon='glyphicon glyphicon-floppy-disk',
        style='success',
        attributes={
            'data-toggle':'tooltip',
            'data-placement':'top',
            'title':'Save'
        }
    )

    edit_button = Button(
        display_text='',
        name='edit-button',
        icon='glyphicon glyphicon-edit',
        style='warning',
        attributes={
            'data-toggle':'tooltip',
            'data-placement':'top',
            'title':'Edit'
        }
    )

    remove_button = Button(
        display_text='',
        name='remove-button',
        icon='glyphicon glyphicon-remove',
        style='danger',
        attributes={
            'data-toggle':'tooltip',
            'data-placement':'top',
            'title':'Remove'
        }
    )

    previous_button = Button(
        display_text='Previous',
        name='previous-button',
        attributes={
            'data-toggle':'tooltip',
            'data-placement':'top',
            'title':'Previous'
        }
    )

    next_button = Button(
        display_text='Next',
        name='next-button',
        attributes={
            'data-toggle':'tooltip',
            'data-placement':'top',
            'title':'Next'
        }
    )

    context = {
        'save_button': save_button,
        'edit_button': edit_button,
        'remove_button': remove_button,
        'previous_button': previous_button,
        'next_button': next_button,
        'datatable_view': datatable_default
    }

    return render(request, 'catalogo_de_sequia_rd/home.html', context)


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 24 08:35:24 2017

@author: Ayushi
"""
import pandas as pd
import readDataset as rd
from scipy.spatial import distance
import numpy as np
from scipy.sparse.csgraph import minimum_spanning_tree

def getDistances(allData,centroid):
    row,col=allData.shape
    allData['distance']=-1
    for i in range(row):
        dist=distance.euclidean(allData.iloc[i,0:col-1],centroid)
        allData.iloc[i,-1]=dist
    allData=allData.sort_values(['distance'],ascending=['False'])
    return allData

#approach2 : connected distance between points
def closest_node(allData, node):
    row,col=allData.shape
    dist = np.sqrt(np.sum((allData.iloc[:,0:col-3] - node)**2, axis=1))
    index=np.argmin(dist[~allData.loc[:,'done']])
    return index

def getConnectedDistances(trainingSet,point):
    row,col=trainingSet.shape
    trainingSet['done']=False
    trainingSet['pos']=-1
    count=int(0)
    while(not all(trainingSet.loc[:,'done'])):
        rownum=closest_node(trainingSet.copy(),point)
        trainingSet.loc[rownum,'done']=True
        trainingSet.loc[rownum,'pos']=count
        count+=1
        point=trainingSet.loc[rownum,:].copy()
        point=point.iloc[0:col-1]

    trainingSet=trainingSet.sort_values(['pos'],ascending=['False'])
    #print (trainingSet)
    return trainingSet.iloc[:,0:col]

#apporach3 : minimum spanning tree
def minSpanningTree(trainingSet,testInstance):
    row,col=trainingSet.shape
    dists = distance.cdist(trainingSet.iloc[:,0:col-1],trainingSet.iloc[:,0:col-1], 'euclidean')
    mst=minimum_spanning_tree(dists)
    trainingSet['done']=False
    trainingSet['pos']=-1
    count=0
    mst=mst.toarray().astype(float)
    rownum=closest_node(trainingSet,testInstance)
    point=trainingSet.loc[rownum,:].copy()
    point=point.iloc[0:col-1]
    trainingSet.loc[rownum,'done']=True
    trainingSet.loc[rownum,'pos']=count#    distances=[]
    stack = [trainingSet.index.get_loc(rownum)] #(point,index,distance) # serial number saved
    count+=1
    while len(stack)>0:
        rownum=stack.pop()
        rownum_orig=trainingSet.index.get_values()[rownum] #index value saved in orig
        point=trainingSet.loc[rownum_orig,:].copy()
        point=point.iloc[0:col-1]

        temp=list(np.nonzero(mst[rownum]))[0]
        temp1=list(np.nonzero(mst[:,rownum]))[0]
        temp=list(temp)+list(temp1)
        for i in temp:
            k=trainingSet.index.get_values()[i]
            if trainingSet.loc[k,'done']==False:
                stack.extend([i])
                trainingSet.loc[k,'done']=True
                trainingSet.loc[k,'pos']=count#    distances=[]
                count+=1

    trainingSet=trainingSet.sort_values(['pos'],ascending=['False'])
    return trainingSet.iloc[:,0:col]

def sortbasedOnclassLabel(feature_vector,ordermeasure):
    centroids=pd.DataFrame()
    for k in set(feature_vector.classLabel):
        x=feature_vector[feature_vector.classLabel==k].mean()
        centroids=centroids.append(x.to_frame().T,ignore_index=True)

    sorted_data=pd.DataFrame()
    for i in set(feature_vector.classLabel):
        if(ordermeasure=='centroid_distance'):
            temp=getDistances(feature_vector[feature_vector.classLabel==i].copy(),centroids[centroids.classLabel==i].iloc[:,0:-1])
            sorted_data=pd.concat([sorted_data,temp])

        elif(ordermeasure=='connected_distance'):
            temp=getConnectedDistances(feature_vector[feature_vector.classLabel==i].copy(),centroids[i])
            sorted_data=pd.concat([sorted_data,temp])

        elif(ordermeasure=='mst_distance'):
            temp=minSpanningTree(feature_vector[feature_vector.classLabel==i].copy(),centroids[i])
            sorted_data=pd.concat([sorted_data,temp])

    return sorted_data.iloc[:,0:-1]

if __name__=="__main__":
    feature_vector, classLabel_given,class_label_dict, row, col=rd.readIrisDataset()

    feature_vector.loc[:,'classLabel']=classLabel_given
    sorted_data=sortbasedOnclassLabel(feature_vector,'centroid_distance')


from app import database as db
from app import settings
import random

def listCaughtPokemon(tID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select pokemonID from wild_pokemon_caught_by_trainers where trainers_tID like "+str(tID)
    cursor.execute(query)
    result = cursor.fetchall()
    if len(result) < 1:
        print("You have not caught any pokemon!")
    else:
        print("here is all your pokemans: ")
        i = 1
        for poke in result:
            print("\t"+str(i)+") "+trainerPokeID2Name(poke[0]))
            i=i+1

    cursor.close()
    con.close()
    return

def listLocation(tID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select towns_townID from trainers where tID like "+str(tID)
    cursor.execute(query)
    result = cursor.fetchone()
    print ("Current location: ", tID2Name(result[0]))
    cursor.close()
    con.close()
    return result[0]

def tID2Name(tID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select townName from towns where townID like "+str(tID)
    cursor.execute(query)
    result = cursor.fetchone()
    cursor.close()
    con.close()
    return result[0]

def listLocalPokemon(tID):
    location = listLocation(tID)
    query = "SELECT wild_pokemon_pID from wild_pokemon_found_in_towns where towns_townID like "+str(location)
    con = db.mySqlCon()
    cursor = con.cursor()
    cursor.execute(query)
    result = cursor.fetchall()
    cursor.close()
    con.close()
    print("Pokemon that can be found here: ")
    for poke in result:
        print("\t"+wildPokeID2Name(poke[0]))
    return result

def wildPokeID2Name(pID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select pName from wild_pokemon where pID like "+str(pID)
    cursor.execute(query)
    result = cursor.fetchone()
    return result[0]

def trainerPokeID2Name(pID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select personalName from wild_pokemon_caught_by_trainers where trainers_tID like "+str(settings.trainerID)+" and pokemonID like "+str(pID)
    cursor.execute(query)
    result = cursor.fetchone()
    return result[0]

def catchPokemon(tID):
    pokeList = listLocalPokemon(tID)

    choice = pokeList[random.randrange(len(pokeList)-1)]
    print("A wild "+wildPokeID2Name(choice[0])+" has appeared!")
    ans = input("Press 1 to battle or 2 to run away: ")
    if ans == "1":
        print("//TODO implement: battle")
        wildPokemon(choice[0])
    if ans == "2":
        print("run away")

    return

def listInventory():
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select items_itemID from trainers_has_items where tID like "+str(settings.trainerID)
    cursor.execute(query)
    results = cursor.fetchall()
    if len(results) < 1:
        print("Your inventory is empty!")
    else:
        print("Inventory: ")
        i = 1
        for item in results:
            print("\t"+str(i)+") "+ itemID2Name(item[0]))
            i=i+1

    return 0

def addItem2Inventory(itemID):
    inventorySize = db.returnItemCount(settings.trainerID)
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "INSERT INTO `pokemon`.`trainers_has_items` (`itemNum`, `tID`, `items_itemID`) VALUES ('"+str(inventorySize+1)+"',"+str(settings.trainerID)+", '"+str(itemID)+"');"
    cursor.execute(query)
    con.commit()
    cursor.close()
    con.close()
    return

def itemID2Name(iID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select itemName from items where itemID like "+str(iID)
    cursor.execute(query)
    result = cursor.fetchone()
    return result[0]

def trainerItemID2Name(iID):
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select items_itemID from trainers_has_items where itemNum like "+str(iID)
    cursor.execute(query)
    result = cursor.fetchone()
    return itemID2Name(result[0])

def giveItemToPoke():
    selection = pokeDetails()
    listInventory()
    item = input("Please select an item you'd like to give to "+trainerPokeID2Name(selection)+": ")
    print(trainerItemID2Name(item))
    query = "UPDATE wild_pokemon_caught_by_trainers SET `trainers_itemNum`='"+str(item)+"' WHERE `pokemonID`='"+str(selection)+"' and`trainers_tID`='"+str(settings.trainerID)+"';"
    con = db.mySqlCon()
    cursor = con.cursor()
    cursor.execute(query)
    con.commit()
    cursor.close()
    con.close()

    return

def returnPokesItem(pID):
    query = "select trainers_itemNum from wild_pokemon_caught_by_trainers where trainers_tID like "+str(settings.trainerID)+" and pokemonID like "+str(pID)
    con = db.mySqlCon()
    cursor = con.cursor()
    cursor.execute(query)
    results = cursor.fetchone()
    cursor.close()
    con.close()
    if results[0] == "None":
        return "No item"
    item = trainerItemID2Name(results[0])
    return item

def pokeUseItem(pID):
    print (returnPokesItem(str(pID)))
    return

def pokeDetails():
    listCaughtPokemon(settings.trainerID)
    selection = input("Select a pokemon to display its detailed information: ")
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "select * from wild_pokemon_caught_by_trainers where pokemonID like "+str(selection)+" and trainers_tID like "+str(settings.trainerID)
    cursor.execute(query)
    results = cursor.fetchone()
    cursor.close()
    con.close()
    print("Pokemon, NickName, Level, current HP, MAX HP, item")
    if str(results[8]) == "None":
        print(str(wildPokeID2Name(results[1]))+", "+str(results[5])+", "+str(results[4])+", "+str(results[6])+", "+str(results[7]) + ", "+"none")
    else:
        print(str(wildPokeID2Name(results[1]))+", "+str(results[5])+", "+str(results[4])+", "+str(results[6])+", "+str(results[7]) + ", "+str(trainerItemID2Name(results[8])))
    return selection

def chooseStartingPokemon(tID):
    choice = input("Please select one of the following starting pokemon:\n\t1) Bulbasaur\n\t2) Charmander\n\t3) Squirtle\n\tchoice: ")
    name = input("Please enter a name for your Pokemon: ")
    if choice == "1":
        trainerCatchesPokemon(1,name)
        print("Bulbasaur! Great choice")
        return
    if choice == "2":
        trainerCatchesPokemon(4, name)
        print("Charmander! Fire up!")
        return
    if choice == "3":
        trainerCatchesPokemon(7,name)
        print("Squirtle squirt!")
        return
    return 0

def wildPokemon(pID):
    wildPokemon = wildPokeID2Name(pID)
    inBattle = True
    wildHP = 100
    listCaughtPokemon(settings.trainerID)
    ans = input("Select a Pokemon to send out: ")
    print(""+trainerPokeID2Name(ans)+"! I choose you!")

    while inBattle:
        ans = input("Press 1 to attempt to catch "+wildPokemon+", or 2 to attack: ")
        if ans == "1":
            print(wildPokemon+"'s health is "+str(wildHP))
            if wildHP > 50:
                rng = random.randrange(100)
            elif wildHP > 25:
                rng = random.randrange(50)
            else:
                rng = random.randrange(30)
            print("Your rng is: ", rng)
            if rng < 25:
                print(wildPokemon+" was captured!")
                if str(input("Press 1 to give your "+wildPokemon+" a nickname: ")) == "1":
                        name = input("Please enter a nickname for your "+wildPokemon+": ")
                else:
                    name = wildPokemon
                trainerCatchesPokemon(pID, name)
                inBattle = False
                return
        if ans == "2":
            print(wildPokemon+"'s health is "+str(wildHP))
            dmg = random.randrange(20)
            print("You do "+str(dmg)+" damage to "+wildPokemon)
            wildHP = wildHP - dmg
            if wildHP < 1:
                print(wildPokemon+" fainted!")
                inBattle = False
                return
    return 0

def trainerCatchesPokemon(pID, name):
    con = db.mySqlCon()
    cursor = con.cursor()
    if random.randrange(10) < 5:
        gender = "M"
    else:
        gender = "F"
    count = db.returnTrainerCatchCount(settings.trainerID)
    print("current count: "+str(count))
    query = "INSERT INTO `wild_pokemon_caught_by_trainers` (`pokemonID`, `wild_pokemon_pID`, `trainers_tID`, `pGender`, `pLevel`, `personalName`, `pokeHP`, `pokeHPMAX`) VALUES ("+str(count)+","+str(pID)+","+str(settings.trainerID)+", '"+gender+"', 1, '"+name+"',100,100)"
    cursor.execute(query)
    con.commit()
    cursor.close()
    con.close()
    db.incrementTrainerCatchCount(settings.trainerID)
    return

def listTowns():
    con = db.mySqlCon()
    cursor = con.cursor()
    cursor.execute("SELECT townName from towns")
    result = cursor.fetchall()
    print("Towns you can travel to: ")
    i=0
    for city in result:
        print("\t"+str(i)+": "+city[0])
        i=i+1
    return result

def travel(tID):
    listTowns()
    ans = input("Please enter the number for the location you'd like to travel to: ")
    print(ans)
    con = db.mySqlCon()
    cursor = con.cursor()
    query = "UPDATE `pokemon`.`trainers` SET `towns_townID`='"+str(ans)+"' WHERE `tID`='"+str(tID)+"';"
    cursor.execute(query)
    con.commit()
    return


from tkinter import *
import math
import random
import functools

#Longitud de Cromosoma (Cantidad de Objetos)
#l_Cromosoma = 8
#Tamanio de Poblacion
t_Poblacion = 8
#Peso Maximo
goal = 4

#Conteo de Generaciones
generacion = 1

#Punto de Cruce
#puntoCruce=l_Cromosoma//2

def crearIndividuo():
    limite_superior = random.randint(0,20)
    individuo = [random.randint(0,5) for i in range(0, limite_superior)]
    return individuo

def crearPoblacion():
	global poblacion, valoresFitness
	for i in range(0,t_Poblacion):
		poblacion.append(crearIndividuo())
		valoresFitness.append(0)

#Regresa un tupla con el peso total y el beneficio total de cada individuo
def decodificarCromosoma(individuo):
    tanque5 = 0
    tanque3 = 0
    valor = []
    tam = len(individuo)
    for i in range (tam):
        if individuo[i] == 0:
            tanque5 += 5
        elif individuo[i] == 1:
            tanque3 += 3
        elif individuo[i] == 2:
            tanque5 -= 5
        elif individuo[i] == 3:
            tanque3 -= 5
        elif individuo[i] == 4:
            tanque5 = tanque5 + (5-tanque3)
        elif individuo[i] == 5:
            tanque3 = tanque3 + (3-tanque5)
    valor.append(tanque5)
    valor.append(tanque3)
    return valor

#Devuelve el beneficio del individuo, si el peso pasa el peso maximo se penaliza
def fitness (Pt_Vt):
    global gamma
    tanque5 = Pt_Vt[0]
    #tanque3 = Pt_Vt[1]
    if (tanque5 > goal):
        return tanque5 - gamma*(tanque5 - goal)
    else:
        return tanque5

def evaluarCromosomas():
    global valoresFitness, poblacion
    for i in range (len(poblacion)):
        W_V = decodificarCromosoma(poblacion[i])
        valoresFitness[i]=fitness(W_V)

def compararCromosomas(cromosoma1,cromosoma2):
    W_V1=decodificarCromosoma(cromosoma1)
    W_V2=decodificarCromosoma(cromosoma2)
    fitness_Value1=fitness(W_V1)
    fitness_Value2=fitness(W_V2)
    if fitness_Value1 < fitness_Value2:
        return 1
    elif fitness_Value1 == fitness_Value2:
        return 0
    else: #fitness_Value1 > fitness_Value2
        return -1

def crearRueda ():
	global valoresFitness

	maxv=max(valoresFitness)
	acc=0
	for p in range(t_Poblacion):
		acc+=maxv-valoresFitness[p]
	fraction=[]
	for p in range(t_Poblacion):
		fraction.append( float(maxv-valoresFitness[p])/acc)
		if fraction[-1]<=1.0/Lrueda:
			fraction[-1]=1.0/Lrueda
	fraction[0]-=(sum(fraction)-1.0)/2
	fraction[1]-=(sum(fraction)-1.0)/2

	wheel=[]
	pc=0

	for f in fraction:
		Np=int(f*Lrueda)
		for i in range(Np):
			wheel.append(pc)
		pc+=1

	return wheel

def nuevaGeneracion():
    global generacion
    generacion += 1
    print("Generacion: "+str(generacion))
    poblacion.sort(key=functools.cmp_to_key(compararCromosomas))
    puntoCruce = len(poblacion[0])//2
    print("Poblacion Antigua Ordenada: \n"+str(poblacion))
    aux = decodificarCromosoma(poblacion[0])
    #print("Auxiliar = "+str(aux[1]))
    if(aux[1] <= goal):
        print("\nMejor solucion hasta el momento:")
        print("f("+str(decodificarCromosoma(poblacion[0]))+")= "+str(fitness(decodificarCromosoma(poblacion[0]))))
    else:
        print("No hay solucion")
    #Aplicamos Elitismo, los mejores dos individuos iran directamente a la siguiente generacion
    # print("Mejor individuo 1: "+str(poblacion[0]))
    # print("Mejor individuo 2: "+str(poblacion[1]))
    nuevaPoblacion[0]=poblacion[0]
    nuevaPoblacion[1]=poblacion[1]
    for i in range(0,(t_Poblacion-2)//2):
        ruleta=crearRueda()
        #Se seleccionan dos progenitores al azar
        p1=random.choice(ruleta)
        # print("Progenitor 1: "+str(p1))
        p2=random.choice(ruleta)
        # print("Progenitor 2: "+str(p2))
        #Se crean dos Descendientes haciendo uso del punto de Cruce
        o1=poblacion[p1][0:puntoCruce]
        o1.extend(poblacion[p2][puntoCruce:len(poblacion[0])])
        # print("Descendiente 1 antes de mutar: "+str(o1))
        o2=poblacion[p2][0:puntoCruce]
        o2.extend(poblacion[p1][puntoCruce:len(poblacion[0])])
        # print("Descendiente 2 antes de mutar: "+str(o2))
        #Cada descendiente es mutado con una probabilibad "mutacion"
        if random.random() < mutacion:
            o1[int(round(random.random()*(len(poblacion[0])-1)))]^=1
        if random.random() < mutacion:
            o2[int(round(random.random()*(len(poblacion[0])-1)))]^=1
        #Los descendientes son agregados a la nueva poblacion
        # print("Descendiente 1 despues de mutar: "+str(o1))
        # print("Descendiente 2 despues de mutar: "+str(o2))
        nuevaPoblacion[2+2*i]=o1
        nuevaPoblacion[3+2*i]=o2
    #La nueva generacion remplaza a la vieja
    poblacion[:]=nuevaPoblacion[:]
    print("Poblacion: \n"+str(poblacion))
    print("\n------------------------\n")

def play():
    for i in range(10000):
        nuevaGeneracion()

# Boton para siguiente generacion:
master = Tk()
button1 = Button(master, text="Next 10000 Generations", command=play)
button1.pack()

button2 = Button(master, text="Next Generation", command=nuevaGeneracion)
button2.pack()

#Probabilidad de Mutacion
mutacion=0.5

gamma = 3

Lrueda=t_Poblacion*10

poblacion = []
valoresFitness = []
crearPoblacion()

print("------------------------\n\nGeneracion: " +str(generacion))
print("Poblacion: \n"+str(poblacion))

poblacion.sort(key=functools.cmp_to_key(compararCromosomas))
evaluarCromosomas()

print("\n------------------------\n")

nuevaPoblacion = poblacion[:]

mainloop()


import pprint
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects, HTTPError
import json
import keys
import traceback

pp = pprint.PrettyPrinter(indent=4)

# ID:
# BTC: 1
# ETH: 1027
# SOL: 5426
# MOB: 7878
# FTT: 4195
# BEAN: 12503
# GOLD: 3575

class Crypto(object):
    def __init__(self, *args, **kwargs):
        self.url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
        self.parameters = {
          'convert':'USD',
          # 'symbol':'BTC,ETH,SOL,FTT,GOLD'
          'id':'1,1027,5426,4195,3575'
        }
        self.headers = {
          'Accepts': 'application/json',
          'X-CMC_PRO_API_KEY': keys.coinmarketcap_key,
        }

    def get_crypto_quotes(self):
        session = Session()
        session.headers.update(self.headers)

        response = session.get(self.url, params=self.parameters)
        response.raise_for_status()

        data = json.loads(response.text)

        watched_tickers = {"BTC":"1", "ETH":"1027", "SOL":"5426", "FTT":"4195","GOLD":"3575"}
        reported_tickers = {}
        crypto_list = data["data"]

        for symbol,id in watched_tickers.items():
            crypto = crypto_list[id]
            current_price = crypto["quote"]["USD"]["price"]
            daily_volume = crypto["quote"]["USD"]["volume_24h"]
            daily_percent_change = crypto["quote"]["USD"]["percent_change_24h"]

            reported_tickers[symbol] = {}
            reported_tickers[symbol]["price"] = current_price
            reported_tickers[symbol]["volume"] = daily_volume
            reported_tickers[symbol]["change"] = daily_percent_change

        status_string = ""
        status_tuples = []
        for reported_ticker, values in reported_tickers.items():
            trend = "↓"
            trend_status = "down"
            if values["change"]>=0:
                trend = "↑"
                trend_status = "up"

            status_string = reported_ticker + ": " + "$" + "{:.2f}".format(values["price"]) + " "  + trend + " {:.2f}".format(values["change"]) + "%  "
            status_tuples.append((status_string, trend_status))
           #  print(status_string)
        return(status_tuples)

    def getMap(self):
        url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
        parameters = {
          # 'convert':'USD'z,
          # 'symbol':'BTC,ETH,SOL,MOB'
          # 'id':'1,1027,5426'
        }
        session = Session()
        session.headers.update(self.headers)

        response = session.get("https://pro-api.coinmarketcap.com/v1/cryptocurrency/map", params=parameters)
        response.raise_for_status()

        data = json.loads(response.text)
        return data

if __name__ == "__main__":
    ticker = Crypto()
    pp.pprint(ticker.getMap())
    # pp.pprint(ticker.get_crypto_quotes())


import tensorflow as tf

def build_lstm_by_device(units):
    if tf.test.is_built_with_cuda():
        lstm = tf.keras.layers.LSTM(
            units=units, return_sequence=True, return_state=True)
    else:
        lstm = tf.keras.layers.RNN(
            tf.keras.layers.LSTMCell(units),
            return_sequences=True, return_state=True)
    return lstm

class Encoder(tf.keras.Model):
    def __init__(self, vocab_size, embedding_size, rnn_size):
        super(Encoder, self).__init__()
        self.rnn_size = rnn_size
        self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_size)
        self.lstm = build_lstm_by_device(rnn_size)

    def call(self, sequence, states):
        embed = self.embedding(sequence)
        output, state_h, state_c = self.lstm(embed, initial_state=states)
        return output, state_h, state_c

    def init_states(self, batch_size):
        return (tf.zeros([batch_size, self.rnn_size]),
                tf.zeros([batch_size, self.rnn_size]))

class LuongAttention(tf.keras.Model):
    def __init__(self, rnn_size):
        super(LuongAttention, self).__init__()
        self.wa = tf.keras.layers.Dense(rnn_size)

    def call(self, encoder_output, decoder_output):
        score = tf.matmul(encoder_output, tf.expand_dims(self.wa(decoder_output), 2))
        alignment = tf.nn.softmax(score, axis=1)
        context = tf.matmul(alignment, encoder_output, transpose_a=True)
        return context, tf.squeeze(alignment, 2)

class Decoder(tf.keras.Model):
    def __init__(self, vocab_size, embedding_size, rnn_size, attention_func):
        super(Decoder, self).__init__()
        self.attention = LuongAttention(rnn_size, attention_func)
        self.rnn_size = rnn_size
        self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_size)
        self.lstm = build_lstm_by_device(rnn_size)
        self.wc = tf.keras.layers.Dense(rnn_size, activation='tanh')
        self.ws = tf.keras.layers.Dense(vocab_size)

    def call(self, sequence, state, encoder_output):
        # Remember that the input to the decoder
        # is now a batch of one-word sequences,
        # which means that its shape is (batch_size, 1)
        embed = self.embedding(sequence)

        # Therefore, the lstm_out has shape (batch_size, 1, rnn_size)
        lstm_out, state_h, state_c = self.lstm(embed, initial_state=state)

        # Use self.attention to compute the context and alignment vectors
        # context vector's shape: (batch_size, 1, rnn_size)
        # alignment vector's shape: (batch_size, 1, source_length)
        context, alignment = self.attention(lstm_out, encoder_output)

        # Combine the context vector and the LSTM output
        # Before combined, both have shape of (batch_size, 1, rnn_size),
        # so let's squeeze the axis 1 first
        # After combined, it will have shape of (batch_size, 2 * rnn_size)
        lstm_out = tf.concat(
            [tf.squeeze(context, 1), tf.squeeze(lstm_out, 1)], 1)

        # lstm_out now has shape (batch_size, rnn_size)
        lstm_out = self.wc(lstm_out)

        # Finally, it is converted back to vocabulary space: (batch_size, vocab_size)
        logits = self.ws(lstm_out)

        return logits, state_h, state_c, alignment


import pika
from skyamqp.rpc import RPC_Server_Thread, RPC_Client_Thread
from skyamqp.queue import Queue_Server_Thread, Queue_Client_Thread
import threading
import uuid
import time
import logging
logger = logging.getLogger('skyamqp')
logger.setLevel(logging.WARNING)

class AMQP_Client:
  __queueCmd__ = []
  def __init__(self, host, username, password, virtual_host: str = '/', port: int = 5672, heartbeat: int = 0):
    self.__connectionId__ = str(uuid.uuid4())
    threading.Thread(target=self.__create_thread, args=(host, username, password, virtual_host, port, heartbeat)).start()

  def create_RPC_Server(self, queue: str, on_message: None, prefetch_count: int):
    rpcServerId = str(uuid.uuid4())
    self.__queueCmd__.append({
      "method": "create_RPC_Server",
      "args": {
        "queue": queue,
        "on_message": on_message,
        "prefetch_count": prefetch_count,
        "id": rpcServerId
      }
    })
    return RPC_Server(rpcServerId, queue, self.__queueCmd__)

  def create_RPC_Client(self, queue: str, timeout: int = 0):
    rpcClientId = str(uuid.uuid4())
    self.__queueCmd__.append({
      "method": "create_RPC_Client",
      "args": {
        "queue": queue,
        "timeout": timeout,
        "id": rpcClientId
      }
    })
    return RPC_Client(rpcClientId, queue, self.__queueCmd__, timeout)

  def create_Queue_Server(self, queue: str, group: str, on_message: None, prefetch_count: int):
    queueServerId = str(uuid.uuid4())
    self.__queueCmd__.append({
      "method": "create_Queue_Server",
      "args": {
        "queue": queue,
        "group": group,
        "on_message": on_message,
        "prefetch_count": prefetch_count,
        "id": queueServerId
      }
    })
    return Queue_Server(queueServerId, queue, self.__queueCmd__)

  def create_Queue_Client(self, queue: str):
    queueClientId = str(uuid.uuid4())
    self.__queueCmd__.append({
      "method": "create_Queue_Client",
      "args": {
        "queue": queue,
        "id": queueClientId
      }
    })
    return Queue_Client(queueClientId, queue, self.__queueCmd__)

  def __create_thread(self, host, username, password, virtual_host, port, heartbeat):
    connection = AMQP_Client_Thread(host, username, password, virtual_host, port, heartbeat)
    rpcServerList = {}
    rpcClientList = {}
    queueServerList = {}
    queueClientList = {}
    listCmd = {}
    while True:
      if len(self.__queueCmd__):
        cmd = self.__queueCmd__[0]
        # RPC
        if cmd['method'] == 'create_RPC_Server':
          rpcServer = connection.create_RPC_Server(cmd['args']['queue'], cmd['args']['on_message'], cmd['args']['prefetch_count'])
          rpcServerList[cmd['args']['id']] = rpcServer
          listCmd[cmd['args']['id']] = cmd
        if cmd['method'] == 'RPC_Server.stop':
          rpcServerList[cmd['args']['id']].stop()
          listCmd[cmd['args']['id']] = None

        if cmd['method'] == 'create_RPC_Client':
          rpcClient = connection.create_RPC_Client(cmd['args']['queue'], cmd['args']['timeout'])
          rpcClientList[cmd['args']['id']] = rpcClient
          listCmd[cmd['args']['id']] = cmd
        if cmd['method'] == 'RPC_Client.send':
          rpcClientList[cmd['args']['id']].send(cmd['args'])

        # Queue
        if cmd['method'] == 'create_Queue_Server':
          queueServer = connection.create_Queue_Server(cmd['args']['queue'], cmd['args']['group'], cmd['args']['on_message'], cmd['args']['prefetch_count'])
          queueServerList[cmd['args']['id']] = queueServer
          listCmd[cmd['args']['id']] = cmd
        if cmd['method'] == 'Queue_Server.stop':
          queueServerList[cmd['args']['id']].stop()
          listCmd[cmd['args']['id']] = None

        if cmd['method'] == 'create_Queue_Client':
          queueClient = connection.create_Queue_Client(cmd['args']['queue'])
          queueClientList[cmd['args']['id']] = queueClient
          listCmd[cmd['args']['id']] = cmd
        if cmd['method'] == 'Queue_Client.send':
          queueClientList[cmd['args']['id']].send(cmd['args'])

        self.__queueCmd__.remove(cmd)
      else:
        try:
          connection.__connection__.process_data_events(0.2)
        except Exception as e:
          logger.warning(e)
          if isinstance(e, pika.exceptions.AMQPError):
            # re-connect
            if connection.__connection__.is_open:
              connection.__connection__.close()
            time.sleep(0.2)
            connection = AMQP_Client_Thread(host, username, password, virtual_host, port, heartbeat)
            for key in listCmd:
              if listCmd[key] is None:
                pass
              else:
                self.__queueCmd__.append(listCmd[key])
          else:
            raise e

class AMQP_Client_Thread:
  __connection__: pika.BlockingConnection
  __clientChannel__: pika.adapters.blocking_connection.BlockingChannel
  def __init__(self, host, username, password, virtual_host: str = '/', port: int = 5672, heartbeat: int = 0):
    try:
      self.__connection__ = pika.BlockingConnection(
        pika.ConnectionParameters(
          host=host,
          port=port,
          virtual_host=virtual_host,
          heartbeat=heartbeat,
          credentials=pika.PlainCredentials(username, password)
        )
      )
    except pika.exceptions.AMQPConnectionError as e:
      raise e

  def create_RPC_Server(self, queue: str, on_message: None, prefetch_count: int):
    return RPC_Server_Thread(self.__connection__, queue, on_message, prefetch_count)
  def create_RPC_Client(self, queue: str, timeout: int = 0):
    if not hasattr(self, "__clientChannel__"):
      self.__clientChannel__ = self.__connection__.channel()
      self.__clientChannel__.confirm_delivery()
    return RPC_Client_Thread(self.__connection__, self.__clientChannel__, queue, timeout)

  def create_Queue_Server(self, queue: str, group: str, on_message: None, prefetch_count: int):
    return Queue_Server_Thread(self.__connection__, queue, group, on_message, prefetch_count)
  def create_Queue_Client(self, queue: str):
    if not hasattr(self, "__clientChannel__"):
      self.__clientChannel__ = self.__connection__.channel()
      self.__clientChannel__.confirm_delivery()
    return Queue_Client_Thread(self.__connection__, self.__clientChannel__, queue)

class RPC_Server:
  def __init__(self, id, queue, q: list):
    self.queue = queue
    self.id = id
    self.queueCmd = q
  def stop(self):
    self.queueCmd.append({
      "method": 'RPC_Server.stop',
      "args": {
        "id": self.id,
      }
    })

class RPC_Client:
  def __init__(self, id, queue, q: list, timeout: int):
    self.id = id
    self.queue = queue
    self.queueCmd = q
    self.timeout = timeout
  def send(self, routing_key: str, dataInput: dict):
    cmd = {
      "method": "RPC_Client.send",
      "args": {
        "routing_key": routing_key,
        "dataInput": dataInput,
        "id": self.id,
        "corr_id": str(uuid.uuid4()),
        "response": None,
        "exception": None
      }
    }
    self.queueCmd.append(cmd)
    period = 0.1
    t = 0
    while cmd['args']['response'] is None and cmd['args']['exception'] is None and (self.timeout == 0 or t < self.timeout):
      t += period
      time.sleep(period)
    if not (cmd['args']['exception'] is None):
      raise Exception(cmd['args']['exception'])
    if cmd['args']['response'] is None:
      raise Exception('REQUEST_WAS_TIMED_OUT')
    response: dict = cmd['args']['response']
    return response

class Queue_Server:
  def __init__(self, id, queue, q: list):
    self.queue = queue
    self.id = id
    self.queueCmd = q
  def stop(self):
    self.queueCmd.append({
      "method": 'Queue_Server.stop',
      "args": {
        "id": self.id,
      }
    })

class Queue_Client:
  def __init__(self, id, queue, q: list):
    self.id = id
    self.queue = queue
    self.queueCmd = q
  def send(self, routing_key: str, dataInput: dict):
    cmd = {
      "method": "Queue_Client.send",
      "args": {
        "routing_key": routing_key,
        "dataInput": dataInput,
        "id": self.id,
        "corr_id": str(uuid.uuid4()),
        "response": None,
        "exception": None
      }
    }
    self.queueCmd.append(cmd)
    period = 0.05
    while cmd['args']['response'] is None and cmd['args']['exception'] is None:
      time.sleep(period)
    if not (cmd['args']['exception'] is None):
      raise Exception(cmd['args']['exception'])
    if cmd['args']['response'] is None:
      raise Exception('REQUEST_WAS_TIMED_OUT')
    response: dict = cmd['args']['response']
    return response