import numpy as np
from nutils import log, _
import scipy.sparse as sp

from aroma import util

class MetaIntegrand(type):

    def __new__(cls, name, bases, attrs):
        subclass = type.__new__(cls, name, bases, attrs)
        if name != 'Integrand':
            Integrand.subclasses[name] = subclass
        return subclass

class Integrand(metaclass=MetaIntegrand):

    subclasses = {}

    @classmethod
    def accepts(cls, obj):
        return False

    @staticmethod
    def get_subclass(obj):
        for subclass in Integrand.subclasses.values():
            if subclass.accepts(obj):
                return subclass
        return None

    @staticmethod
    def acceptable(obj):
        return isinstance(obj, Integrand) or (Integrand.get_subclass(obj) is not None)

    @staticmethod
    def make(obj):
        if isinstance(obj, Integrand):
            return obj
        if not Integrand.acceptable(obj):
            raise NotImplementedError
        return Integrand.get_subclass(obj)(obj)

    def __init__(self):
        self._properties = {}

    @staticmethod
    def read(group):
        type_ = group.attrs['type']
        subclass = util.find_subclass(Integrand, type_)
        return subclass.read(group)

    def prop(self, *args, **kwargs):
        if args:
            assert all(isinstance(arg, str) for arg in args)
            values = [(self._properties[arg] if arg in self._properties else kwargs[arg]) for arg in args]
            if len(args) == 1:
                return values[0]
            return values
        for key, val in kwargs.items():
            if key not in self._properties:
                self._properties[key] = val
        return self

    def write_props(self, group):
        group = group.require_group('properties')
        for key, value in self._properties.items():
            util.to_dataset(value, group, key)

    def read_props(self, group):
        self._properties = {}
        for key, value in group['properties'].items():
            self._properties[key] = util.from_dataset(value)

    def ensure_shareable(self):
        pass

class ThinWrapperIntegrand(Integrand):

    def __init__(self, obj):
        super().__init__()
        self.obj = obj

    @property
    def ndim(self):
        return len(self.shape)

    @property
    def shape(self):
        return self.obj.shape

    def write(self, group, name):
        sub = group.require_group(name)
        util.to_dataset(self.obj, sub, 'data')
        sub.attrs['type'] = self.__class__.__name__
        self.write_props(sub)
        return sub

    @staticmethod
    def read(group):
        cls = util.find_subclass(ThinWrapperIntegrand, group.attrs['type'])
        retval = cls.__new__(cls)
        retval.obj = util.from_dataset(group['data'])
        retval.read_props(group)
        return retval

class NumpyArrayIntegrand(ThinWrapperIntegrand):

    optimized = True

    @classmethod
    def accepts(cls, obj):
        return isinstance(obj, (np.ndarray,) + util._SCALARS)

    def __init__(self, obj):
        if isinstance(obj, np.ndarray):
            super().__init__(obj)
        else:
            super().__init__(np.array(obj))

    def _contract(self, contraction):
        axes, obj = [], self.obj
        for i, cont in enumerate(contraction):
            if cont is None:
                continue
            assert cont.ndim == 1
            for __ in range(i):
                cont = cont[_,...]
            while cont.ndim < self.ndim:
                cont = cont[...,_]
            obj = obj * cont
            axes.append(i)
        return obj.sum(tuple(axes))

    def get(self, contraction):
        return self._contract(contraction)

    def cache(self, **kwargs):
        return self

    def contract(self, contraction):
        return NumpyArrayIntegrand(self._contract(contraction))

    def project(self, projection):
        obj = self.obj
        s = slice(None)
        for i, p in enumerate(projection):
            if p is None:
                continue
            obj = obj[(s,)*i + (_,s,Ellipsis)]
            obj = obj * p[(_,)*i + (s,s) + (_,) * (self.ndim - i - 1)]
            obj = obj.sum(i+1)
        return NumpyArrayIntegrand(obj)

class ScipyArrayIntegrand(ThinWrapperIntegrand):

    optimized = True

    @classmethod
    def accepts(cls, obj):
        return isinstance(obj, sp.spmatrix)

    def get(self, contraction):
        if all(c is None for c in contraction):
            return self.obj
        ca, cb = contraction
        if ca is None:
            return self.obj.dot(cb)
        elif cb is None:
            return self.obj.T.dot(ca)
        return ca.dot(self.obj.dot(cb.T))

    def cache(self, **kwargs):
        return self

    def contract(self, contraction):
        assert len(contraction) == 2

        ca, cb = contraction
        if ca is None and cb is None:
            return self
        assert ca is None or cb is None

        if ca is None:
            return NumpyArrayIntegrand(self.obj.dot(cb))
        return NumpyArrayIntegrand(self.obj.T.dot(ca))

    def project(self, projection):
        if all(p is None for p in projection):
            return self
        pa, pb = projection
        if pa is None:
            return NumpyArrayIntegrand(self.obj.dot(pb.T))
        elif pb is None:
            return NumpyArrayIntegrand(self.obj.T.dot(pa.T).T)
        return NumpyArrayIntegrand(pa.dot(self.obj.dot(pb.T)))

class COOTensorIntegrand(Integrand):

    optimized = True

    def __init__(self, shape, *args):
        super().__init__()
        assert len(shape) == 3
        assert len(shape) == len(args) - 1
        self.shape = shape
        self.ndim = len(shape)

        nz = np.nonzero(args[-1])
        *indices, self.data = [arg[nz] for arg in args]

        fits = all(np.max(i) <= np.iinfo(np.int32).max for i in indices)
        idx_dtype = np.int32 if fits else np.int64
        indices = tuple(i.astype(idx_dtype, copy=True) for i in indices)
        self.indices = indices

        # TODO: Figure out in advance which assemblers we will need
        self.assemblers = {
            (1,): util.CSRAssembler((shape[0], shape[2]), indices[0], indices[2]),
            (2,): util.CSRAssembler((shape[0], shape[1]), indices[0], indices[1]),
            (1,2): util.VectorAssembler((shape[0],), indices[0])
        }

    def write(self, group, name):
        sub = group.require_group(name)
        datagrp = sub.require_group('data')
        util.to_dataset(self.indices[0], datagrp, 'indices-i')
        util.to_dataset(self.indices[1], datagrp, 'indices-j')
        util.to_dataset(self.indices[2], datagrp, 'indices-k')
        util.to_dataset(self.data, datagrp, 'data')
        datagrp.attrs['shape'] = self.shape
        sub.attrs['type'] = 'COOTensorIntegrand'

        assemblers = datagrp.require_group('assemblers')
        for key, assembler in self.assemblers.items():
            name = ','.join(str(s) for s in key)
            ass_grp = assemblers.require_group(name)
            assembler.write(ass_grp)

        return sub

    @staticmethod
    def read(group):
        datagrp = group['data']
        retval = COOTensorIntegrand.__new__(COOTensorIntegrand)
        retval.indices = datagrp['indices-i'][:], datagrp['indices-j'][:], datagrp['indices-k'][:]
        retval.data = datagrp['data'][:]
        retval.shape = tuple(datagrp.attrs['shape'])

        retval.assemblers = {}
        for key, grp in datagrp['assemblers'].items():
            key = tuple(int(i) for i in key.split(','))
            retval.assemblers[key] = getattr(util, grp.attrs['type']).read(grp)

        return retval

    def ensure_shareable(self):
        self.indices = tuple(util.shared_array(i) for i in self.indices)
        self.data = util.shared_array(self.data)
        for ass in self.assemblers.values():
            ass.ensure_shareable()

    def get(self, contraction):
        retval = self._contract(contraction)
        if not isinstance(retval, COOTensorIntegrand):
            return retval
        return retval.toarray()

    def toarray(self):
        # TODO: This could be more efficient, but this function should never be
        # called in performance-critical code anyway
        # Ravel down to a matrix, convert to scipy, then to numpy, then unravel
        flat_index = np.ravel_multi_index(self.indices[1:], self.shape[1:])
        flat_shape = (self.shape[0], np.product(self.shape[1:]))
        matrix = sp.coo_matrix((self.data, (self.indices[0], flat_index)), shape=flat_shape)
        matrix = matrix.toarray()
        return np.reshape(matrix, self.shape)

    def cache(self, **kwargs):
        return self

    def contract(self, contraction):
        return Integrand.make(self._contract(contraction))

    def _contract(self, contraction):
        if all(c is None for c in contraction):
            return self
        contraction = [(i, c) for i, c in enumerate(contraction) if c is not None]
        axes = tuple(i for i, __ in contraction)
        data = np.copy(self.data)
        for i, c in contraction:
            data *= c[self.indices[i]]
        if axes == (0,1,2):
            return np.sum(data)
        return self.assemblers[axes](data)

    def project(self, projection):
        # TODO: Remove this condition
        assert all(p is not None for p in projection)
        pa, pb, pc = projection
        P, __ = pa.shape
        ass = util.CSRAssembler(self.shape[1:], self.indices[1], self.indices[2])
        ret = np.empty((P, pb.shape[0], pc.shape[0]), self.data.dtype)
        for i in log.iter('index', range(P), length=P):
            data = self.data * pa[i, self.indices[0]]
            mx = ass(data)
            ret[i] = pb.dot(mx.dot(pc.T))
        return NumpyArrayIntegrand(ret)

class LazyIntegral:
    pass

def integrate(*args):
    if all(not isinstance(arg, LazyIntegral) for arg in args):
        return args
    assert all(arg.__class__ == args[0].__class__ for arg in args[1:])
    return args[0].__class__.integrate(*args)


import copy

from bos_consensus.common import Ballot, BallotVotingResult, Message, node_factory
from bos_consensus.blockchain import Blockchain
from bos_consensus.network import Endpoint
from bos_consensus.consensus import get_fba_module
from bos_consensus.consensus.fba.isaac import IsaacState
from bos_consensus.blockchain.util import StubTransport

IsaacConsensus = get_fba_module('isaac').IsaacConsensus

def receive_copy_ballot(self, ballot):
    new_ballot = copy.deepcopy(ballot)
    self.consensus.handle_ballot(new_ballot)

def check_slot_time_stub(ballot):
    pass

def blockchain_factory(name, address, threshold, validator_endpoint_uris, slot_size):
    node = node_factory(name, Endpoint.from_uri(address))
    validators = list()
    for uri in validator_endpoint_uris:
        validators.append(
            node_factory(uri, Endpoint.from_uri(uri)),
        )

    consensus = IsaacConsensus(node, threshold, validators, slot_size)
    consensus._check_slot_time = check_slot_time_stub
    Blockchain.receive_ballot = receive_copy_ballot
    return Blockchain(
        consensus,
        StubTransport()
    )

def generate_ballots(node_names):
    message = Message.new()
    ballots = list()
    n_node = len(node_names)
    assert n_node > 1
    ballot = Ballot.new(node_names[0], message, IsaacState.INIT, BallotVotingResult.agree)
    ballots.append(ballot)
    for i in range(1, n_node):
        ballots.append(Ballot(ballot.ballot_id, node_names[i], message, IsaacState.INIT, BallotVotingResult.agree,
                              ballot.timestamp))

    return ballots

def generate_n_ballots_list(node_names, n):
    ballots_list = list()

    for _ in range(n):
        ballots_list.append(generate_ballots(node_names))

    return ballots_list

def check_all_ballot_state_in_slot(slot, ballots_list, state):
    for ballots in ballots_list:
        assert ballots
        assert slot.get_ballot_state(ballots[0]) == state

    return

def set_all_ballots_state_to(ballots_list, state):
    for ballots in ballots_list:
        for ballot in ballots:
            ballot.state = state

    return

def get_messages_from_ballots_list(ballots_list):
    messages = list()
    for ballots in ballots_list:
        if ballots:
            messages.append(ballots[0].message)

    return messages

def generate_node_names(node_name_prefix, n):
    INIT = 5000
    node_names = list()
    for i in range(1, n + 1):
        node_names.append(f'http://localhost:{INIT+i}')

    return node_names

def generate_blockchains(node_names, threshold, slot_size=5):
    blockchains = list()
    for i in range(len(node_names)):
        validators = copy.deepcopy(node_names)
        node_name = node_names[i]
        validators.remove(node_name)
        blockchain = blockchain_factory(
            node_name,
            node_name,
            threshold,
            validators,
            slot_size,
        )
        blockchains.append(blockchain)

    return blockchains

def get_validator_nodes(blockchains, blockchain):
    nodes = [blockchain.node for blockchain in blockchains]
    nodes.remove(blockchain.node)
    return nodes

def set_validator_all_each_other(blockchains):
    for blockchain in blockchains:
        validator_nodes = get_validator_nodes(blockchains, blockchain)
        for node in validator_nodes:
            blockchain.consensus.add_to_validator_connected(node)
        blockchain.consensus.init()

def run_blockchain_scalability(n_nodes, threshold, n_ballots_in_slot, n_sending_ballots):
    assert n_nodes > 1

    node_names = generate_node_names('http://localhost:', n_nodes)
    blockchains = generate_blockchains(node_names, threshold, n_ballots_in_slot)
    set_validator_all_each_other(blockchains)
    ballots_list = generate_n_ballots_list(node_names, n_sending_ballots)
    assert ballots_list

    ballot_size = len(ballots_list[0])

    # receive multiple ballots simultaniously
    for i in range(ballot_size):
        for ballots in ballots_list:
            for blockchain in blockchains:
                blockchain.receive_ballot(ballots[i])

    for blockchain in blockchains:
        check_all_ballot_state_in_slot(blockchain.consensus.slot, ballots_list, IsaacState.SIGN)

    set_all_ballots_state_to(ballots_list, IsaacState.SIGN)

    # receive multiple ballots simultaniously
    for i in range(ballot_size):
        for ballots in ballots_list:
            for blockchain in blockchains:
                blockchain.receive_ballot(ballots[i])

    for blockchain in blockchains:
        check_all_ballot_state_in_slot(blockchain.consensus.slot, ballots_list, IsaacState.ACCEPT)

    set_all_ballots_state_to(ballots_list, IsaacState.ACCEPT)

    # receive multiple ballots simultaniously
    for i in range(ballot_size):
        for ballots in ballots_list:
            for blockchain in blockchains:
                blockchain.receive_ballot(ballots[i])

    messages = get_messages_from_ballots_list(ballots_list)

    # check all confirm by save message
    for message in messages:
        for blockchain in blockchains:
            assert message in blockchain.consensus.messages

def test_blockchain_scalability():
    run_blockchain_scalability(3, 100, 2, 2)
    run_blockchain_scalability(5, 100, 10, 10)

    return


from app import db
from sqlalchemy.sql import func
import datetime

class Lego(db.Model):
    __tablename__='lego'
    id = db.Column(db.Integer, primary_key=True)
    model = db.Column(db.String(255))
    name = db.Column(db.String(255))
    price = db.Column(db.String(255))
    description = db.Column(db.Text())
    rating = db.Column(db.String(255))
    available = db.Column(db.String(255))
    updated = db.Column(db.DateTime())

    def __init__(
            self, model=None, name=None, price=None,
            description=None, rating=None, available=None
        ):
        self.model = model
        self.name = name
        self.price = price
        self.description = description
        self.rating = rating
        self.available = available

    def json(self):
        output = {}
        output['id'] = self.id
        output['model'] = self.model
        output['name'] = self.name
        output['price'] = self.price
        output['description'] = self.description
        output['rating'] = self.rating
        output['available'] = self.available
        if self.updated:
            output['updated'] = self.updated.strftime("%m/%d/%Y, %H:%M:%S")
        return output


#!/usr/bin/env python
from pstudio import AE, set_output
import numpy as np
import matplotlib.pyplot as plt
from math import pi

set_output('-')
#ae = AE('H', xcname='LDA', relativity='NR', config='1s1')
#ae = AE('Li', xcname='LDA', relativity='NR')
#ae = AE('Cl', xcname='LDA', relativity='SR')
#ae = AE('Ti', xcname='LDA', relativity='NR', config='[Ar] 3d2 4s1', rmin=1e-4)
ae = AE('Ti', xcname='LDA-py', relativity='SR')

try:
    ae.run(verbose=True)
except RuntimeError as err:
    print(err)

r = ae.rgd.r

# plot density
plt.figure()
plt.plot(r, ae.n*r*r, label='density')
plt.xlim(0,20)
plt.legend()
plt.show(block=False)

# plot the potential
plt.figure()
plt.plot(r, ae.vtot, label='Vtot')
plt.plot(r, ae.vion, label='Vion', linestyle='dashed')
plt.xlim(0,20)
plt.ylim(-10,0)
plt.legend()
plt.show(block=False)

plt.figure()
plt.plot(r, ae.vxc*r, label='Vxc*r')
plt.xlim(0,20)
plt.legend()
plt.show(block=False)

# plot orbitals
plt.figure()
for orb in ae.orbitals:
    plt.plot(r, orb.ur, label='n={0},l={1}'.format(orb.n,orb.l))
plt.xlim(0,10)
plt.legend()
plt.show()

quit()


from bottle import route, run, HTTPError, request, HTTPResponse
import album

"""
Requirements:
    1. Веб-сервер принимает GET-запросы по адресу /albums/<artist> и выводит на экран
    сообщение с количеством альбомов исполнителя artist и списком названий этих альбомов.

    2. Веб-сервер принимает POST-запросы по адресу /albums/ и сохраняет переданные пользователем
    данные об альбоме. Данные передаются в формате веб-формы. Если пользователь пытается передать
    данные об альбоме, который уже есть в базе данных, обработчик запроса отвечает
    HTTP-ошибкой 409 и выводит соответствующее сообщение.

    3. Набор полей в передаваемых данных полностью соответствует схеме таблицы album базы данных.

    [id:INTEGER, year:INTEGER, artist:TEXT, genre:TEXT, album:TEXT]

    4. В качестве исходной базы данных использовать файл albums.sqlite3.

    5. До попытки сохранить переданные пользователем данные, нужно провалидировать их.
    Проверить, например, что в поле "год выпуска" передан действительно год.
"""

def valid_data(album_data):
    """
    Description:
        Получает словарь album, который проверяет на наличие всех полей из списка required_items, а также на соответствие некоторым проверкам на валидность вводимой информации. Подведёт словарь к некоторому стандарту и возвратит его в случае успешных проверок. Иначе - вернёт текст ошибки.

    Returns:
        Возвратит раскрытый список: результат в виде булевого значения; значение ошибки / валидный словарь.
    """
    for item in album.required_items:
        if not album_data.get(item):
            return False, 'Missing attribute "%s".' % item
    try:
        album_data["year"] = int(album_data["year"])
    except ValueError:
        return False, 'Incorrect "year" attribute (not a number).'
    else:
        if album_data["year"] < 1860 or album_data["year"] > 2020:
            return False, 'Incorrect "year" attribute (it can\'t be real).'

    for item in album_data:
        # some editing here...
        pass
        # if item != "year":
        #     album_data[item] = str(album_data[item])
    return True, album_data

@route('/albums/<artist>')
def get_albums(artist):
    """
    Description:
        Возвратит строку с заголовком, а также нумерованый список альбомов (при наличии).
        Если альбомов исполнителя нет в базе - веведет 404 с соответствующим сообщением.
    """
    album_list = album.find(artist)
    if not album_list:
        return HTTPError(404, "There are no %s albums in the database." % artist)

    header = "
%s albums [%d]:
" % (album_list[0].artist, len(album_list)) # album_list[0].artist -- берём оригинальное имя из базы, с учётом заглавных букв
    album_names = ["{} ({})".format(album.album, album.year) for album in album_list]
    list_elements = ["
%s

" % name for name in album_names]
    albums_html = "

\n" + '\n'.join(list_elements) + "
"
    return header + albums_html

@route('/albums/', method = "POST")
def add_album():
    """
    Description:
        Обрабатывает POST-запросы на добавление альбома по адресу HOSTPORT/albums/.
        Параметры запроса считываются из полей передаваемой формы. Если введённые параметры
        не пройдут валидацию - вернёт ошибку 404 с указанием причины. Если данный альбом
        уже находится в базе (совпатают поля исполнителя, года и названия) - ответит
        ошибкой 409 с указанием причины.
    """
    album_data = {}
    for item in album.required_items:
        album_data[item] = request.forms.get(item)
    valid, data = valid_data(album_data)
    if not valid:
        return HTTPResponse(data, 400)
    if album.album_exists(data):
        return HTTPResponse("This album is already in the database.", 409)
    else:
        album.add(data)
        return "Database updated."

if __name__ == "__main__":
    run(host = "localhost", port = 8080, debug = True)


def xyz(l):
    a = 7
    retcode = "no"
    for i in range(len(l)):
        if l[i] == a:
            retcode = "Bingo"
    return retcode

listing = [ 1,2,3,4,5,6,8 ]
print(xyz(listing))


'''
# Sample code to perform I/O:

name = input()                  # Reading input from STDIN
print('Hi, %s.' % name)         # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''

# Write your code here

def main():
    N = int(input())
    d = dict()
    for x in 'abcdefghijklmnopqrstuvwxyz':
        d[x] = 0

    for case in range(0,N):
        sdict = dict(d)
        tdict = dict(d)

        S = input()
        T= input()

        for x in S:
            sdict[x] += 1
        for x in T:
            tdict[x] +=1
        count = 0
        for x in 'abcdefghijklmnopqrstuvwxyz':
            if sdict[x] < tdict[x]:
                count+= tdict[x] - sdict[x]
            if sdict[x] > tdict[x]:
                count += sdict[x] - tdict[x]
        print(count)
main()


import pandas as pd
import numpy as np
from bo.design_space.design_space import DesignSpace
from bo.optimizers.hebo import HEBO
from sim_With_bullet import *
import csv
def obj(params, table, bagdata) -> np.ndarray:
    out = np.zeros((params.shape[0], 1))
    for i in range(params.shape[0]):
        X = [
             params.iloc[i].get('res'),
             params.iloc[i].get('f')

        ]
        #,params.iloc[i].get('latf'),
        model = Model(X, init_pos.copy(), init_vel.copy())
        t_sim, sim_pos, _ = model.sim_bullet(table, 'DIRECT')
        simdata = np.hstack((t_sim, sim_pos))
        # loss = Lossfun(bagdata.copy(), simdata, 'DIRECT')
        loss_ang = Lossfun2(bagdata.copy(), simdata.copy(), table, 'DIRECT')
        # loss_dis = get_Err(bagdata, simdata)
        if loss_ang == 180.3334:
            loss = loss_ang
            print("180.3334 fehler:", filename)

        else:
            loss = loss_ang
        # plt.plot(simdata[:,1], simdata[:,2], label='sim')
        # plt.plot(bagdata[:,1], bagdata[:,2], label='bag')
        # plt.legend()
        # plt.show()

        out[i] = loss_ang
    return out

if __name__ == "__main__":

    bag_dir = "/home/hszlyw/Documents/airhockey/20210224/all_short/"
    dir_list = os.listdir(bag_dir)
    dir_list.sort()

#  [t_lateral_f, left_right_rim_res, left_rim_f, four_side_rim_res, four_side_rim_latf, angvel]  [5,]
    param_list = [
        {'name': 'res', 'type': 'num', 'lb': .5, 'ub': .95},
        {'name': 'f', 'type': 'num', 'lb': 0., 'ub': .8}

    ]
    np.random.seed(99)
    space = DesignSpace().parse(param_list)
    opt = HEBO(space)

    # init value
    rec = pd.DataFrame({

                        'res': [.9, .7, .95, .59, .67, .75, .62, .8],
                        'f': [.1, .3, .45, .6, .01, .4, .6, .7]

    }
                        )

    data = []

    objs = []
    params = []
    n_sugg = 15
    fileHeader = ["iters", "res", "f",  "objs" ]
    with open("/home/hszlyw/PycharmProjects/ahky/iiwa_envs/results_v1/zum Ausarbeitung2/seg_ang/short/" + "test", 'w') as csvfile:
        cw = csv.writer(csvfile)
        cw.writerow(fileHeader)

        for iter in range(70):
            rec = opt.suggest(n_suggestions=n_sugg)
            # obj_value = np.zeros((n_sugg, 1)) # nrows = n_suggestions
            obj_value = []
            mean_obj = []

            for filename in dir_list:
                # filename = dir_list[1]
                # filename = "2021-02-24-15-09-02.bag"

                # print(filename)
                data = []
                with open(bag_dir + filename, 'r') as f:
                    # with open(bag_dir+'8.txt', 'r') as f:

                    for line in f:
                        data.append(np.array(np.float64(
                            line.replace("[", " ").replace("]", " ").replace(",", " ").replace("\n", "").split())))
                    data = np.array(data)
                    table = data[0, :]
                    bagdata = np.array(data[1:, :])
                    # table = bagdata[0, :]
                    table[2] = 0.11945
                    # bagdata = bagdata[1:, :]
                    bagdata[:, 3] = 0.11945 * np.ones(bagdata.shape[0])
                    lin_ang_vel = get_vel(bagdata.copy())
                    # init_pos = np.hstack((bagdata.copy()[0, 1:3], 0.11945))  # [3,]
                    for i, vel in enumerate(lin_ang_vel):
                        if (np.abs(vel[0:2]) > 0.1).any() and (np.abs(lin_ang_vel[i + 2, 0:2]) > 0.1).any():
                            begin_idx = i + 10
                            break
                        else:
                            continue
                    init_pos = np.hstack((bagdata.copy()[0, 1:3], 0.11945))  # [3,]
                    init_vel = vel2initvel(lin_ang_vel, bagdata.copy(), begin_idx)  # In [n,7]

                    # lin_ang_vel = get_vel(bagdata.copy())  # In [n,7], Out[n,6]
                    # begin_idx = np.argmax(np.abs(lin_ang_vel[:, 2]))      ######### see vel_y [:,1] if hit shortrim
                    # init_vel = lin_ang_vel[begin_idx, :]

                    # bagdata = bagdata[:back_process(lin_ang_vel), :]

                    tempobj = obj(rec, table, bagdata.copy())
                    # while (tempobj == 180.3334).any():  # 180.3334 wrong loss, should remove
                    #     tempobj = np.delete(tempobj, np.where(tempobj == 180.3334))

                    # tempobj = np.mean(tempobj)

                    # obj_value = tempobj + obj_value       # float64
                    obj_value.append(tempobj)

            obj_value = np.array(obj_value).squeeze().T
            for i, objs in enumerate(obj_value):
                mean_obj.append(np.mean([obj for obj in objs if obj != 180.3334 ] )  )

            mean_obj = np.array(mean_obj).reshape(n_sugg,1)
            for j in range(n_sugg):

                cw.writerow([
                    str(iter),
                    str(rec.res.values[j]),
                    str(rec.f.values[j]),
                    str(np.float(mean_obj[j]))])

            # print(obj_value)
            opt.observe(rec, mean_obj)
            # objs.append(obj_value)

            print('iter', iter)
            print('file', 99)
            #
            print("Current: ", "objective: {} ".format(mean_obj[0, 0]),
                  "parameter: [res: {}, "
                  "f: {},"
                  .format(rec.res.values[0],
                           rec.f.values[0],
                                         print("Best: ", "objective: {} ".format(opt.y.min()),
                  "parameter: [res: {}, "
                  "f: {}, "
                                               .format(
                                                 opt.X.iloc[opt.y.argmin()]['res'],
                                                 opt.X.iloc[opt.y.argmin()]['f']
            ) ))
                  )


from rest_framework import serializers

from resume_cv.models import (
    Award,
    Certificate,
    Contact,
    Education,
    Experience,
    ResumeCV,
    Skill,
)

class SkillSerializer(serializers.ModelSerializer):
    class Meta:
        model = Skill
        fields = ['id', 'name', 'description']
        read_only_fields = fields

class ExperienceSerializer(serializers.ModelSerializer):
    skill = SkillSerializer(read_only=True, many=True)

    class Meta:
        model = Experience
        fields = '__all__'
        read_only_fields = [f.name for f in model._meta.get_fields()]

class EducationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Education
        fields = '__all__'
        read_only_fields = [f.name for f in model._meta.get_fields()]

class CertificateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Certificate
        fields = '__all__'
        read_only_fields = [f.name for f in model._meta.get_fields()]

class AwardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Award
        fields = '__all__'
        read_only_fields = [f.name for f in model._meta.get_fields()]

class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact
        fields = '__all__'
        read_only_fields = [f.name for f in model._meta.get_fields()]

class ResumeCVSerializer(serializers.ModelSerializer):
    contact = ContactSerializer(read_only=True)
    experiences = ExperienceSerializer(read_only=True, many=True)
    educations = EducationSerializer(read_only=True, many=True)
    certificates = CertificateSerializer(read_only=True, many=True)
    awards = AwardSerializer(read_only=True, many=True)

    class Meta:
        model = ResumeCV
        fields = [
            'id',
            'title',
            'summary',
            'contact',
            'experiences',
            'educations',
            'certificates',
            'awards',
            'first_name',
            'last_name',
            'full_name',
        ]
        read_only_fields = [f.name for f in model._meta.get_fields()]


"""
（ボールに書かれた整数、ボールの連続する個数）の形でリストに入れる
スタックで管理する
番兵を入れておくと楽
"""

N = int(input())
a = list(map(int, input().split()))
L = [[-1, 0]]
ans = 0
for cx in a:
    tx, cnt = L[-1]
    ans += 1
    if cx == tx:
        L[-1][1] += 1
    else:
        L.append([cx, 1])
    if L[-1][0] == L[-1][1]:
        L.pop()
        ans -= cx
    print(ans)


#Recall in Worked Example 5.2.5 that we showed you the code
#for two versions of binary_search: one using recursion, one
#using loops. For this problem, use the recursive one.
#
#In this problem, we want to implement a new version of
#binary_search, called binary_search_year. binary_search_year
#will take in two parameters: a list of instances of Date,
#and a year as an integer. It will return True if any date
#in the list occurred within that year, False if not.
#
#For example, imagine if listOfDates had three instances of
#date: one for January 1st 2016, one for January 1st 2017,
#and one for January 1st 2018. Then:
#
#  binary_search_year(listOfDates, 2016) -> True
#  binary_search_year(listOfDates, 2015) -> False
#
#You should not assume that the list is pre-sorted, but you
#should know that the sort() method works on lists of dates.
#
#Instances of the Date class have three attributes: year,
#month, and day. You can access them directly, you don't
#have to use getters (e.g. myDate.month will access the
#month of myDate).
#
#You may copy the code from Worked Example 5.2.5 and modify
#it instead of starting from scratch. You must implement
#binary_search_year recursively.
#
#Don't move this line:
from datetime import date

#Write your code here!

def binary_search_year(dates, year):
    dates.sort()
    #print("First entry")
    #print (f"My sorted array is {dates} \n")

    midDate = dates[len(dates)//2]
    #print (f"My midDate is {midDate}\n")

    if year == midDate.year:
        #print(f"Match found return True\n")
        return True
    elif year > midDate.year:
        start_index = dates.index(midDate)
        end_index = len(dates)
        if end_index == 0:
            #print(f"I am returning False from greater check\n")
            return False
        greater_arr = dates[start_index:end_index]
        #print(f"greater function {start_index} {end_index}\n")
        #print(f"My greater array is {greater_arr}\n")
        #print("Calling again from greater")
        return binary_search_year(greater_arr, year)
    else:
        start_index = 0
        end_index = dates.index(midDate)
        if end_index == 1:
            #print(f"I am returning False from lesser check\n")
            return False
        lesser_arr = dates[start_index:end_index+1]
        #print(f"lesser function {start_index} {end_index}\n")
        #print(f"My lesser array is {lesser_arr}\n")
        #print("Calling again from lesser")
        return binary_search_year(lesser_arr, year)

#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: True, then False
listOfDates = [date(2016, 11, 26), date(2014, 11, 29),
               date(2008, 11, 29), date(2000, 11, 25),
               date(1999, 11, 27), date(1998, 11, 28),
               date(1990, 12, 1), date(1989, 12, 2),
               date(1985, 11, 30)]

print(binary_search_year(listOfDates, 2016))
print(binary_search_year(listOfDates, 2007))


import argparse

from timezonefinder import TimezoneFinder, TimezoneFinderL

tf = TimezoneFinder()
tfL = TimezoneFinderL()
functions = [
    tf.timezone_at,
    tf.certain_timezone_at,
    None,
    tfL.timezone_at,
    tfL.timezone_at_land,
    tf.timezone_at_land,
]

def main():
    parser = argparse.ArgumentParser(description="parse TimezoneFinder parameters")
    parser.add_argument("lng", type=float, help="longitude to be queried")
    parser.add_argument("lat", type=float, help="latitude to be queried")
    parser.add_argument("-v", action="store_true", help="verbosity flag")
    parser.add_argument(
        "-f",
        "--function",
        type=int,
        choices=[0, 1, 3, 4, 5],
        default=0,
        help="function to be called:"
        "0: TimezoneFinder.timezone_at(), "
        "1: TimezoneFinder.certain_timezone_at(), "
        "2: removed, "
        "3: TimezoneFinderL.timezone_at(), "
        "4: TimezoneFinderL.timezone_at_land(), "
        "5: TimezoneFinder.timezone_at_land(), ",
    )
    parsed_args = parser.parse_args()  # takes input from sys.argv
    tz = functions[parsed_args.function](lng=parsed_args.lng, lat=parsed_args.lat)
    if parsed_args.v:
        print("Looking for TZ at lat=", parsed_args.lat, " lng=", parsed_args.lng)
        print(
            "Function:",
            ["timezone_at()", "certain_timezone_at()"][parsed_args.function],
        )
        print("Timezone=", tz)
    else:
        print(tz)


import logging
from abc import ABCMeta, abstractmethod
from typing import List, Tuple, Optional, Union, Iterable

from messageflux.iodevices.base import InputDevice, OutputDeviceManager, ReadResult, InputDeviceManager
from messageflux.iodevices.base.common import MessageBundle, Message
from messageflux.message_handling_service import MessageHandlingServiceBase

_logger = logging.getLogger(__name__)

class PipelineResult:
    """
    a result from pipeline handler
    """

    def __init__(self,
                 output_device_name: str,
                 message_bundle: Union[MessageBundle, Message]):
        self.output_device_name = output_device_name
        if isinstance(message_bundle, Message):
            message_bundle = MessageBundle(message=message_bundle)

        self.message_bundle = message_bundle

class PipelineHandlerBase(metaclass=ABCMeta):
    """
    a pipeline handler base class. used to handle a single message that passes through the pipeline
    """

    def prepare(self):
        """
        called when the service starts.
        can be overrided by child class to perform some initialization logic
        """
        pass

    def shutdown(self):
        """
        called when the service stops.
        can be overrided by child class to perform some cleanup logic
        """
        pass

    @abstractmethod
    def handle_message(self,
                       input_device: InputDevice,
                       message_bundle: MessageBundle) -> Optional[Union[PipelineResult, Iterable[PipelineResult]]]:
        """
        Handles a message from an input device. and returns a tuple of the output device name, message and headers to
        send to.

        :param input_device: The input device that sent the message.
        :param message_bundle: The message that was received.

        :return: None if the message should not be sent to any output device.
        PipelineResult (or iterable of) if messages should be sent to the output device with the given name.
        """
        pass

class FixedRouterPipelineHandler(PipelineHandlerBase):
    """
    A pipeline handler that routes all messages to a single output device. without any processing.
    """

    def __init__(self, output_device_name: str):
        self._output_device_name = output_device_name

    def handle_message(self,
                       input_device: InputDevice,
                       message_bundle: MessageBundle) -> Optional[PipelineResult]:
        """
        routes the message to the fixed output

        :param input_device: The input device that sent the message.
        :param message_bundle: The message that was received.

        :return: a pipeline result that has the input message bundle, and the fixed output device name
        """
        output_message_bundle = MessageBundle(message=message_bundle.message.copy(), device_headers={})
        return PipelineResult(output_device_name=self._output_device_name,
                              message_bundle=output_message_bundle)

class PipelineService(MessageHandlingServiceBase):
    """
    a service that uses a PipelineHandler object to process messages from input, and send to output
    """

    def __init__(self, *,
                 input_device_manager: InputDeviceManager,
                 input_device_names: Union[List[str], str],
                 pipeline_handler: PipelineHandlerBase,
                 output_device_manager: Optional[OutputDeviceManager] = None,
                 **kwargs):
        """

        :param pipeline_handler: the pipeline handler to use for handling the messages
        :param output_device_manager: Optional. the output device manager to send messages to
        :param **kwargs: passed to parent as is
        """
        super().__init__(input_device_manager=input_device_manager,
                         input_device_names=input_device_names,
                         **kwargs)
        self._output_device_manager = output_device_manager
        self._pipeline_handler = pipeline_handler

    def _prepare_service(self):
        super()._prepare_service()
        if self._output_device_manager is not None:
            self._output_device_manager.connect()
        self._pipeline_handler.prepare()

    def _handle_message_batch(self, batch: List[Tuple[InputDevice, ReadResult]]):
        for input_device, read_result in batch:
            pipeline_handler_result = self._pipeline_handler.handle_message(input_device, read_result)
            if pipeline_handler_result is not None:
                if isinstance(pipeline_handler_result, PipelineResult):
                    pipeline_handler_result = [pipeline_handler_result]
                for pipeline_result in pipeline_handler_result:
                    if self._output_device_manager is None:
                        _logger.warning("pipeline handler returned a result to output to device: "
                                        f"'{pipeline_result.output_device_name}', "
                                        f"but no output_device_manager was given")
                        continue

                    output_device = self._output_device_manager.get_output_device(pipeline_result.output_device_name)
                    output_device.send_message(message=pipeline_result.message_bundle.message,
                                               device_headers=pipeline_result.message_bundle.device_headers)

    def _finalize_service(self, exception: Optional[Exception] = None):
        try:
            super()._finalize_service(exception)
        finally:
            if self._output_device_manager is not None:
                self._output_device_manager.disconnect()
            self._pipeline_handler.shutdown()


"""add x and y

Revision ID: 3555f61aaa79
Revises: 79972ec5f79d
Create Date: 2023-06-22 15:03:27.338959

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "3555f61aaa79"
down_revision = "79972ec5f79d"
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("hero", sa.Column("x", sa.Integer(), nullable=False))
    op.add_column("hero", sa.Column("y", sa.Integer(), nullable=False))
    # ### end Alembic commands ###
    # generate_er_diagram(f'migrations/versions/{revision}_er_diagram.png')
    # generate_er_markdown(f'migrations/versions/{revision}_er_diagram.md', f'migrations/versions/er_diagram_{revision}.png')

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("hero", "y")
    op.drop_column("hero", "x")
    # ### end Alembic commands ###


# https://leetcode.com/problems/add-binary/

# Input: a = "11", b = "1"
# Output: "100"
#
# Input: a = "1010", b = "1011"
# Output: "10101"

a = '1010'
b = '1011'

class Solution(object):
    def addBinary(self, a, b):
        carry = 0
        ans = ''
        i = 0

        a = a[::-1]
        b = b[::-1]

        while i < len(a) or i < len(b) or carry !=0:
            x = 0
            if i < len(a) and a[i] == '1':
                x = 1
            y = 0
            if i < len(b) and b[i] == '1':
                y = 1
            ans = str((x+y+carry)%2) + ans
            carry = (x+y+carry)//2
            i += 1
        return ans

c = Solution()
c.addBinary(a, b)


"""Q1. A farmer is asking you to tell him how many legs can be counted among all his animals. The farmer breeds three
species:

chickens = 2 legs cows = 4 legs pigs = 4 legs The farmer has counted his animals and he gives you a subtotal for each
species. You have to implement a function that returns the total number of legs of all the animals.
"""

"""
Create a function that finds the highest integer in the list using recursion.
"""

"""
Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz".

If the number is a multiple of 3 the output should be "Fizz".
If the number given is a multiple of 5, the output should be "Buzz".
If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz".
If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below.
The output should always be a string even if it is not a multiple of 3 or 5.
"""
"""
write python code for hollow diamond star pattern
"""

def total_leg(chickens, cows, pigs):
    legs = 2 * chickens + 4 * cows + 4 * pigs
    return legs

def find_max(arr):
    if len(arr) <= 1:
        return arr[0]
    else:
        m = max(arr[1:])
        return m if m > arr[0] else arr[0]

def fizzbuzz(n):
    if n % 3 == 0 and n % 5 == 0:
        return "FizzBuzz"
    elif n % 3 == 0:
        return "Fizz"
    elif n % 5 == 0:
        return "Buzz"
    else:
        return str(n)

def hollow_diamond(num):
    for i in range(1, num + 1):
        for j in range(1, num - i + 1):
            print(" ", end=" ")
        for j in range(1, 2 * i):
            if j == 1 or j == 2 * i - 1:
                print("*", end=" ")
            else:
                print(" ", end=" ")
        print()
    for i in range(num - 1, 0, -1):
        for j in range(1, num - i + 1):
            print(" ", end=" ")
        for j in range(1, 2 * i):
            if j == 1 or j == 2 * i - 1:
                print("*", end=" ")
            else:
                print(" ", end=" ")
        print()

if __name__ == '__main__':
    # print(total_leg(3, 5, 7))
    # arr = [3, 100, 4, 56, 67, 89, 23]
    # print(find_max(arr))
    # print(fizzbuzz(45))
    num = int(input("Enter number of rows N : "))
    hollow_diamond(num)


"""
This module provides top interface of external module features.
"""

# Standard libraries

# Azad libraries
from .. import constants as Const
from ..errors import AzadError
from .abstract import (
    AbstractExternalModule, AbstractProgrammingLanguage,
    AbstractExternalGenerator, AbstractExternalValidator,
    AbstractExternalSolution
)
from .python3 import (
    AbstractPython3, Python3Generator, Python3Validator, Python3Solution
)
from .cpp import (
    AbstractCpp, CppGenerator, CppSolution, CppValidator,
    AbstractC, CSolution
)
from .java import JavaSolution, AbstractJava

from .js import (
    JsSolution
)

_classes = {
    Const.SourceFileLanguage.Python3: {
        Const.SourceFileType.Generator: Python3Generator,
        Const.SourceFileType.Validator: Python3Validator,
        Const.SourceFileType.Solution: Python3Solution
    },
    Const.SourceFileLanguage.Cpp: {
        Const.SourceFileType.Generator: CppGenerator,
        Const.SourceFileType.Validator: CppValidator,
        Const.SourceFileType.Solution: CppSolution,
    },
    Const.SourceFileLanguage.C: {
        Const.SourceFileType.Solution: CSolution,
    },
    Const.SourceFileLanguage.Java: {
        Const.SourceFileType.Solution: JavaSolution,
    },
    Const.SourceFileLanguage.Javascript: {
        Const.SourceFileType.Solution: JsSolution,
    }
}

def getExternalModuleClass(
        lang: Const.SourceFileLanguage,
        sourceType: Const.SourceFileType) -> type:
    try:
        return _classes[lang][sourceType]
    except (KeyError, IndexError) as err:
        raise AzadError(
            "Unsupported (Lang %s, Type %s) pair." %
            (lang.name, sourceType.name)).with_traceback(err.__traceback__)


from flask_restful import Resource, reqparse
from utils.param_check import check_params
from database.db_ops_get_meas import DB_Ops_Get_Measurements

class GetMeasurements(Resource):
    def __init__(self):
        self.reqparser = reqparse.RequestParser()
        self.reqparser.add_argument('db_name', type=str, help='Name of the database')
        self.get_meas = DB_Ops_Get_Measurements()
        super(GetMeasurements, self).__init__()

    def get(self):
        args = self.reqparser.parse_args()
        params_check_result = check_params(['db_name'], args)
        if params_check_result[0] is False:
            return params_check_result[1]

        db_name = args['db_name']
        result = self.get_meas.get_measurements(db_name)

        return result


from random import expovariate as ernd
from module.entity import *
from core.timer import *
from core.simapi import *

class CAlohaApp(CEntity):
    def __init__(self, appName, parent=None):
        super().__init__(parent)
        self.sCount = 0
        self.rCount = 0
        self.name = appName
        self.timer=CTimer()
        self.T = 0.001
        self.my_t=self.T

    def tx(self,rate=1.0):
        self.msg = "this is the aloha frame"
        self.cnt = 10000
        self.delay = 1.0/rate
        self.d=ernd(1.0/self.delay)
        if self.d <= self.my_t:
            self.timer.start(self.T,self.OnTimer)
        else:
            self.timer.start(self.T,self.retx)
    def OnTimer(self):
        # smprint("[%s sent]%s" % (self.name,self.msg))
        apdu = copy.deepcopy(self.msg)
        self.send(0, apdu)
        self.sCount += 1
        self.cnt -= 1
        self.my_t += self.T
        if self.cnt > 0:
            self.d += ernd(1.0/self.delay)
            if self.d <= self.my_t:
                self.timer.start(self.T, self.OnTimer)
            else:
                self.timer.start(self.T, self.retx)
    def retx(self):
        self.my_t += self.T
        if self.d <= self.my_t:
            self.timer.start(self.T, self.OnTimer)
        else:
            self.timer.start(self.T, self.retx)
    def handle_rx(self, intf_no, apdu, dst=None, src=None):
        self.rCount += 1
        # smprint("[%s rcvd]%s" % (self.name,apdu))
        del apdu

    def stat(self):
        print("%s 统计：发送%d 接收%d" % (self.name,self.sCount,self.rCount))


import lycee
from lycee import *

def exo1():
    figure()
    nb_eoliennes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    nb_parc = [40, 40, 30, 115, 150, 135, 23, 38, 18, 19]
    affiche_tableau([["nb éoliennes"]+nb_eoliennes,["nb parcs"]+nb_parc],markdown=True)
    set_y_min_max(0,160)
    baton(nb_eoliennes, nb_parc, couleur="red",
          titre="constitution des parc éoliens",
          abscisse="nombre d'éoliennes par parc",
          ordonnee="nombre de parcs")
    affiche_graphique()

def exo2():
    """1 créer un programme qui demande et affiche l'âge d'une personne.
       2 après avoir créer une variable mon_age dont la valeur est votre âge,
       modifier le programme pour qu'il retourne la phase suivante si l'utilisateur
       a rentré 35 et que votre ans est 16:
        Vous avez 35 ans, j'ai 15 ans nous avons donc 20 ans de différence.
       3 Si l'utilisateur entre 15 et que vous avez 35 ans : le résultat obtenu sera :
       Vous avez 35 ans, j'ai 15 ans nous avons donc -20 ans de différence.
       Modifier votre programme pour que la différence d'âge soit toujours positive."""

    # question 1
    age = demande("Entrer votre âge")
    # print(f"Vous avez {age} ans")
    # question 2
    mon_age = 57
    difference = mon_age - age
    # question 3
    difference = abs(mon_age - age)
    if mon_age < age:
        difference = age - mon_age
    else:
        difference = mon_age - age
    print(f"Vous avez {age} ans, j'ai {mon_age} ans nous avons donc {difference} ans de différence.")

def exo3():
    # diagramme secteur
    # Source d'énergie et coût de MW électrique
    figure()
    prix_moyen = [90, 50, 80, 140]
    source_energie = ["Gaz", "Nucléaire", "Eolien", "Photovoltaïque"]
    secteur(prix_moyen, source_energie,
            titre="Source d'énergie et coût de MW électrique",
            autopct= lambda prix_moyen: f"{prix_moyen:.2f} €" )
    affiche_graphique()

def exo4():
    # diagramme barre ou colonne
    figure()
    colonne([7, 2, 0, 4], 500, 1000, eff=True, color='orange',
            titre="Puissance parc éolien",
            abscisse="Puissance totale MW",
            ordonnee="nombre de régions")
    affiche_graphique()

def exo5():
    figure(figsize=(6, 6))
    annee = [2012, 2013, 2014, 2015, 2016, 2017, 2018]
    capacite = [7613, 8558, 9285, 10505, 12065, 13757, 15307]
    trace_courbe(annee, capacite, stroke='red', abscisse="Années", ordonnee="Capacité de production (en MW)")
    affiche_graphique()

def exo6():
    figure(1,2)
    colonne([7, 2, 0, 4], 500, 1000, eff=True, color='orange',
            titre="Puissance parc éolien",
            abscisse="Puissance totale MW",
            ordonnee="nombre de régions")
    annee = [2012, 2013, 2014, 2015, 2016, 2017, 2018]
    capacite = [7613, 8558, 9285, 10505, 12065, 13757, 15307]
    trace_courbe(annee, capacite, stroke='red', abscisse="Années", ordonnee="Capacité de production (en MW)")
    affiche_graphique()

def exo7():
    affiche_tableau([["Prénom","âge"],["Paul",15],["Pierre",14],["Jacques",16]]+[["total",45]],mini=10,aligner="gc",markdown=True)

def exo8():
    liste2CSV([[1,2,3,4,5],[11,22,33,44,55]],"essai.txt",affiche=True)
def exo9():
    print(affiche_poly([1, 2, 3], format="python"))
    print(affiche_poly([1, 2, 3]))

def exo10():
    lycee.x=10
    print(demande("entrer votre formule"))

def exo11():
    figure(figsize=(6, 5))
    jour = ["D", "L", "M", "M", "J", "V", "S"]
    stroke("blue")
    jours = [1, 2, 3, 4, 5, 6, 7]
    montreal = [-10, -14, -8, 0, 1, 5, 2]
    toronto = [-7, -10, -2, 3, 5, 4, 0]
    set_y_min_max(-15,10)
    ligne_brisee(jour, montreal, toronto, abscisse="Jour", ordonnee="Température en °C",
                 labels=["Montréal", "Toronto"],
                 marker="v")
    affiche_graphique()

if __name__ == '__main__':
    exo1()


#!/usr/bin/env python3
import random
import math
import time
import sys
import re

import networkx as nx
from primergen.common.check import *
from primergen.common.util import random_primer_with_balanced_gc
from primergen.common.graph_utils import *

from .base import BasePrimerExtractor

PRINT_EVERY_NTH_ITERATION_N = 20000

class GreedyPrimerExtractor(BasePrimerExtractor):
    def __init__(self, initial_primers=None, target=TARGET_PRIMERS, strategy="greedy"):
        super().__init__(initial_primers, target, strategy)

    def generate(self):
        """
        Just run through the list of initial primers and grab ones that don't clash with the current list
        """
        start_compute_time = time.process_time()
        for init_primer in self.initial_primers:
            self.iterations += 1
            # Don't let printing slow us down
            if self.iterations % PRINT_EVERY_NTH_ITERATION_N == 0:
                elapsed = time.process_time() - start_compute_time
                progress_fraction = self.iterations / len(self.initial_primers)
                eta_min = int(
                    (elapsed / progress_fraction) * (1 - progress_fraction) / 60
                )
                eta_sec = int(
                    (elapsed / progress_fraction) * (1 - progress_fraction) % 60
                )
                progress_percent = round(progress_fraction * 100, 2)
                print(
                    f"Iter {self.iterations}\t({progress_percent}%)\tETA: {eta_min} m {eta_sec} s"
                )

            for other_primer in self.primers:
                if not is_primer_pair_valid(
                    init_primer, other_primer, limit=MIN_EDIT_DISTANCE
                ):
                    super().new_edit_error()
                    break
            else:
                super().found_new_primer(init_primer)

if __name__ == "__main__":
    GreedyPrimerExtractor().execute()


opc = 0
import numpy as np
import matplotlib.pyplot as plt
import cv2
import base64
from PIL import Image
from io import BytesIO
import argparse
import sys

def letter2ASCII(msg):
     for i in msg:
        yield ord(i)

def encoder(imagen , mensaje, pattern, img=False):

    imagen = cv2.imread(imagen, 1)
    imagen = cv2.cvtColor(imagen, cv2.COLOR_BGR2RGB)

    if img ==False:
        mensaje = open("{}".format(mensaje), "r")
        mensaje = mensaje.read()

    generador = letter2ASCII(mensaje)
    pattern = pattern
    cont = 0
    length = len(mensaje)
    space = (imagen.shape[0] * imagen.shape[1] * 3) - pattern

    if space < length*pattern:
        print('Text too large')
        return 0

    for chn in range(4):
        for row in range(imagen.shape[0]):
            for col in range(imagen.shape[1]):
                cont += 1
                if cont == pattern :
                    cont = 0
                    try:
                        imagen[row][col][chn] = next(generador)
                    except StopIteration:
                        imagen[row][col][chn] = 0
                        name = input('    Name to save new image: ')
                        cv2.imwrite('{}'.format(name),cv2.cvtColor(imagen, cv2.COLOR_BGR2RGB))
                        print('\n')
                        print('------- Image Encoded :) --------')
                        print('\n')
                        print('\n')
                        return imagen

def decoder(imagen, pattern, img=False):
    imagen = cv2.imread(imagen, 1)
    imagen = cv2.cvtColor(imagen, cv2.COLOR_BGR2RGB)

    pattern = pattern
    message = ''
    cont = 0

    for chn in range(4):
        for row in range(imagen.shape[0]):
            for col in range(imagen.shape[1]):
                cont += 1
                if cont == pattern:
                    cont = 0
                    letra = imagen[row][col][chn]
                    if letra != 0:
                        message = message + chr(letra)
                    else:
                        if img == False:
                            print('\n')
                            print('Msg: ', message)
                            print('\n')
                            print('\n')
                            return message
                        else:
                            return message

if __name__ == '__main__':

    while opc != 5:

        print('\n ------- Menu -------')
        print('1.) Text -> Image')
        print('2.) Image -> Text')
        print('3.) Image into Image')
        print('4.) Image from Image')
        print('5.) Exit')
        print('\n')
        opc = int( input("  Option: ") )

        if opc == 1:
            path = input("\n    Path for image: ")
            msg = input("    .txt file: ")
            patt = int(input("    Pattern: "))
            encoder(path, msg, patt)
        elif opc == 2:
            path = input("\n    Path for image: ")
            patt = int(input("    Pattern: "))
            decoder(path, patt)

        elif opc == 3:

            path = input("\n    Path for base image: ")
            path2 = input("    Path for image to hide: ")
            patt = int(input("    Pattern: "))
            msg = None

            with open("{}".format(path2), "rb") as img_file:
                msg = base64.b64encode(img_file.read())

            msg = msg.decode('utf-8')

            encoder(path, msg, patt, True)

        elif opc == 4:

            path = input("\n    Path for image: ")
            patt = int(input("    Pattern: "))
            data = decoder(path, patt, True)

            im = Image.open(BytesIO(base64.b64decode(data)))
            im.save('imageFromDecoder.png', 'PNG')

            print('\n')
            print('------- Image Decoded :) --------')
            print('\n')
            print('\n')

        elif opc == 5:
            print('\n Bye :(')
            sys.exit()


import json
import lib
import os

def RFIHandRangeDecision(hand, position):
    if position == lib.Position.BigBlind.name:
        return True

    f = open("hand-range-charts.json")
    data = json.load(f);
    handRange = data[lib.Action.RFI.name][position];
    hand.sort(key=cardToNumber, reverse=True)

    print(hand)
    for subsetRange in handRange:
        if checkCardInSubsetRange(hand, subsetRange) == True:
            return True
    return False

def aggressorHandRangeDecision(hand, position, action, aggressor):
    f = open("hand-range-charts.json")
    data = json.load(f);
    print(action)
    print(position)
    print(aggressor)
    handRangeChartURL = data[action][position][aggressor];
    os.system("gopen ./preflop-charts/" + handRangeChartURL)

def checkCardInSubsetRange(hand, subsetRange):
    # Example of a subset of range in shortform: A9s+
    if cardToNumber(hand[0]) < rankToNumber(subsetRange[0]):
        return False
    if cardToNumber(hand[1]) < rankToNumber(subsetRange[1]):
        return False

    if subsetRange[2] == 's': #'s' means cards are suited. 'o' is offsuit
        if hand[0]["suit"] == hand[1]["suit"]:
            return True

    if subsetRange[2] == 'o': # 'o' is offsuit
        return True

    if subsetRange[0] == subsetRange[1]: # Dealing with pairs
        if hand[0]["rank"] == hand[1]["rank"]:
            if cardToNumber(hand[0]) >= rankToNumber(subsetRange[0]):
                return True

    return False

def cardToNumber(card):
    return rankToNumber(card["rank"])

def rankToNumber(card):
    if card == 'A':
        return 14
    elif card == 'K':
        return 13
    elif card == 'Q':
        return 12
    elif card == 'J':
        return 11
    elif card == 'T':
        return 10
    else:
        return int(card)


from rest_framework.views import status
from app.api.helpers.constants import (VEHICLE_REGISTRATION_SUCCESS_MESSAGE)
from .base_test import TestBaseCase

class RegisterVehicleTest(TestBaseCase):

    def test_register_vehicle_successeds(self):
        """
        Test schedule route
        """
        response = self.register_vehicle_succeeds()
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIsInstance(response.data, dict)
        self.assertIn('message', response.data)
        self.assertEqual(response.data['message'],
                        VEHICLE_REGISTRATION_SUCCESS_MESSAGE)


def canConstruct(target, wordBank, memo={}):

    if target in memo:
        return memo[target]

    if target == '':
        return 1

    total = 0

    for word in wordBank:
        if target[: len(word)] == word:
            numWays = canConstruct(target[len(word):], wordBank, memo)
            total += numWays
    memo[target] = total
    return total

print(canConstruct('abcdef',['ab','abc','cd','def','abcd']))
print(canConstruct('eeeeeeeeeeeeeeeeeeeeeeeeeeeef',
['e','eee','eeee','ee','eeeee']))


#再议服务器
from socket import *

tcp=socket(AF_INET,SOCK_STREAM)
tcp.bind(("",6666))
tcp.listen(5)
while True:
	newsocket,clientaddr=tcp.accept()
	print(clientaddr)
	while True:
		content=newsocket.recv(1024)
		if len(content) > 0:
			print(content.decode("gb2312"))
		else:
			break
		senddate=input("输入要发送的内容")
		newsocket.send(senddate.encode("gb2312"))

	newsocket.close()
tcp.close()


from params import Params
import params
import tensorflow as tf
import math
import time
from MCTreeSearch import MCTS
from hex_game import Board as Game
import copy

#TODO remove imports after testing
from nim import NimGame
import numpy as np
import random as r

# timer class template from https://realpython.com/python-timer/#creating-a-python-timer-class
class TimerError(Exception):
    """A custom exception used to report errors in use of Timer class"""

class Timer:
    def __init__(self, name):
        self.name = name
        self._start_time = None
        self.total_time = 0.0

    def start(self):
        """Start a new timer"""
        if self._start_time is not None:
            raise TimerError(f"Timer is running. Use .stop() to stop it")

        self._start_time = time.perf_counter()

    def stop(self):
        """Stop the timer, and report the elapsed time"""
        if self._start_time is None:
            raise TimerError(f"Timer is not running. Use .start() to start it")

        elapsed_time = time.perf_counter() - self._start_time
        self.total_time += elapsed_time
        self._start_time = None
        #print(f"Elapsed time: {elapsed_time:0.4f} seconds")

    def __repr__(self):
        return "name: {}, used {} seconds during run".format(self.name, self.total_time)

class RLSystem():
    def __init__(self):
        self.tournament_wins = 0
        self.game = Game
        self.board = self.game()
        self.actor = ActorNN("default")
        self.replay_buffer = self.actor.RBUF
        self.mcts = MCTS(self)
        self.next_starting_player = 1

    def reset_game_and_change_start_player(self):
        self.board = self.game()
        self.board.current_player = self.next_starting_player
        self.next_starting_player *= -1

    def get_battle_move(self, board):
        """Used when in tournament"""
        #Need to have a method with same name in both actor and RL_agent
        return self.get_move_from_mcts(board)

    def get_move_from_mcts(self, board):
        self.board = copy.deepcopy(board)
        self.mcts = MCTS(self, start_board=self.board)
        action_index, move_index = self.mcts.mc_search(timed=True)
        return move_index

    def play_game_with_mcts_and_train(self):
        self.reset_game_and_change_start_player()
        counter = 0
        self.mcts.re_init(self.board) #Sets state to start
        while not self.board.is_game_ended():
            counter += 1
            print("real moves done:{}".format(counter))
            action_index, move_index = self.mcts.mc_search()
            self.add_case_to_RBUF()
            self.board.do_move(move_index)
            self.mcts.update_root_node(action_index)

            if Params.display_actual_game == True:
                self.board.display()
        self.actor.train()

    def default_policy(self, board_state:np.array, legal_moves_full_vec:np.array):
        #predict_timer.start()
        move = self.actor.default_policy(board_state, legal_moves_full_vec)       #TODO more of the logic should happen here
        #predict_timer.stop()
        return move
    def add_case_to_RBUF(self ):
        distribution = self.mcts.get_root_distribution()

        assert math.isclose(distribution.sum(), 1, abs_tol=0.001), "distribution should sum to 1 but was: {}".format(distribution.sum())  # TODO remove later

        self.replay_buffer.add_case(self.mcts.root_node.board_state, distribution)

    def save(self, file_name):
        tf.keras.models.save_model(self.actor.model, "neural_nets/"+file_name)
    def __repr__(self):
        self.actor.tournament_wins = self.tournament_wins
        return self.actor.__repr__()

class StupidActor():
    def get_move_distribution(self, board_state):
        return [1] + [0 for _ in range(Params.nn_output_size-1)]

    def default_policy(self, board_state):
        """return index for move, may be illegal"""
        distribution = self.get_move_distribution(board_state)
        max_val = max(distribution)
        return distribution.index(max_val)

class IndexIterator():
    def __init__(self,  to_i, from_i=0):
        """

        :param to_i: non inclusive, must be higher than from_i
        :param from_i: inclusive, must be less than to_i (default 0)
        """
        self.from_i = from_i
        self.to_i = to_i
        self.current_i = from_i

    def next(self):
        ret = self.current_i
        if self.current_i +1 == self.to_i:
            self.current_i = self.from_i
        else:
            self.current_i += 1

        return ret

class RBUF():

    def __init__(self, size):
        self.targets = []
        self.inputs = []
        self.is_filled = False
        self.size = size
        self.index_iterator = IndexIterator(size)

    def add_case(self, board_state, target_dist):
        if not self.is_filled:
            self.targets.append(target_dist)
            self.inputs.append(board_state)
            if self.targets.__len__() == self.size:
                self.is_filled = True
        else:
            index = self.index_iterator.next()
            self.targets[index] = target_dist
            self.inputs[index] = board_state
    def get_n_random_training_cases(self, size):
        """

        :param size: number of cases, if size is larger than amount of cases all are returned
        :return: tuple of type (inputs:np.array, targets:np.array)
        """
        if size >= self.inputs.__len__():
            return (np.array(self.inputs), np.array(self.targets))

        index_list = np.arange(self.targets.__len__())
        index_list = np.random.choice(index_list, size=size, replace=False)
        return (np.array(self.inputs)[index_list], np.array(self.targets)[index_list])

    def get_n_last_targets(self, n):
        if self.targets.__len__() >=n:
            return np.array(self.targets[-n:])
        else:
            return np.array(self.targets)

    def get_n_last_inputs(self, n):
        if self.inputs.__len__() >=n:
            return np.array(self.inputs[-n:])
        else:
            return np.array(self.inputs)

class ActorNN():
    def __init__(self, name):
        self.tournament_wins = 0
        self.name = name
        self.get_dist_timer = Timer("PREDICT_DISTRIBUTION_TIMER")
        self.RBUF = RBUF(Params.RBUF_size)
        self.model = tf.keras.Sequential()
        self.model.add(tf.keras.Input(shape=(Params.nn_input_size,), dtype=tf.int64))
        for layer_size in Params.nn_inner_layer_dims:
            self.model.add(tf.keras.layers.Dense(layer_size, activation=Params.nn_inner_activation_function))
        self.model.add(tf.keras.layers.Dense(Params.nn_output_size, activation="softmax"))
        optimizer = Params.nn_optimizer(learning_rate=Params.nn_learning_rate)
        self.model.compile(optimizer=optimizer, loss=Params.nn_loss_function)

    def get_move_distribution(self, board_state):
        #if Params.time_code == True:
        #    self.get_dist_timer.start()
        dist = self.model(board_state )
        #if Params.time_code == True:
        #    self.get_dist_timer.stop()
        return dist
    def get_battle_move(self, board):
        return self.default_policy(board_state=board.get_state(), legal_moves_full_vec=board.get_available_moves_full_vector())
    def default_policy(self, board_state:np.array, legal_moves_full_vec:np.array):
        """returns action index to use for move, same as argument for do_move in game"""

        distribution = self.get_move_distribution(board_state.reshape(1, board_state.shape[0]))
        distribution = distribution*legal_moves_full_vec #removes illegal moves from dist
        assert np.sum(distribution) != 0, "All legal moves have 0 probability" #TODO remove when it works
        return np.argmax(distribution)

    def train(self):
        inputs, targets = self.RBUF.get_n_random_training_cases(Params.RBUF_cases_per_train)
        self.model.fit(inputs, targets, batch_size=5, epochs=Params.nn_training_epochs)
    def __repr__(self):
        return "name: {}, wins: {}".format(self.name, self.tournament_wins)

#Separarate, only in this file to avoid circular import
class TOPP():
    def __init__(self, names_of_nns=[], use_only_nn=True):
        """:use_only_nn, true (default) means only nn selects move, False uses mcts search"""
        self.agents = []
        for nn_name in names_of_nns:
            a = ActorNN(nn_name)
            a.model = tf.keras.models.load_model("neural_nets/"+nn_name, custom_objects={'deepnet_cross_entropy':params.deepnet_cross_entropy})
            if not use_only_nn:
                rl_agent = RLSystem()
                rl_agent.actor = a
                a = rl_agent
            self.agents.append(a)
        self.board = Game()

    def tournament(self):
        for index, actor1 in enumerate(self.agents):
            for actor2 in self.agents[index + 1:]:
                self.battle_actors(actor1, actor2)
    def battle_actors(self, actor_1:ActorNN, actor_2:ActorNN):
        game_count = Params.G
        #TODO might be some asymmetry bug here
        turn = 1 #"actor 1 is 1 and actor 2 is -1
        last_game_start = 1
        #TODO set exploration to 0
        for _ in range(game_count):
            if Params.display_battle_nn:
                self.board.display()
                time.sleep(Params.battle_nn_display_delay)
            while not self.board.is_game_ended():
                current_player = actor_1 if turn == 1 else actor_2
                if Params.display_battle_nn:
                    print(current_player, "will do next move")
                move_index = current_player.get_battle_move(self.board)
                self.board.do_move(move_index)
                if Params.display_battle_nn:
                    self.board.display()
                    time.sleep(Params.battle_nn_display_delay)
                turn *= -1
            if self.board.winner*last_game_start == 1:
                actor_1.tournament_wins += 1
            else:
                actor_2.tournament_wins += 1
            last_game_start *= -1
            turn = last_game_start
            self.board = Game()
        #print("{} won: {} while {} won: {} games".format(actor_1, actor_1.tournament_wins, actor_2, actor_2.tournament_wins))

# actor_1 = ActorNN("ACTOR_10_episodes")
# actor_1.model = tf.keras.models.load_model("neural_nets/hex_first_try_10_episodes")
#
# actor_2 = ActorNN("ACTOR_50_episodes")
# actor_2.model = tf.keras.models.load_model("neural_nets/hex_first_try_50_episodes")
#
# actor_3 = ActorNN("ACTOR_120_episodes")
# actor_3.model = tf.keras.models.load_model("neural_nets/hex_first_try_120_episodes")
#
# actor_4 = ActorNN("ACTOR_350_episodes")
# actor_4.model = tf.keras.models.load_model("neural_nets/hex_first_try_350_episodes")
#
# topp = TOPP(None, None)
# topp.battle_nn(actor_1=actor_1, actor_2=actor_3)

all_timer = Timer("ALL_TIMER")
all_timer.start()

def reload_run(c_val, epsilon_val, list_of_names, last_saved_gen):
    Params.c_factor = c_val
    Params.epsilon = epsilon_val
    for i in range(0, last_saved_gen+1, Params.save_interval):
        list_of_names.append(Params.name_of_run+"_"+str(i))

#Full run
def full_algorithm():
    rl_sys = RLSystem()
    name = Params.name_of_run
    names = ["size_6_big_run_125","size_6_big_run_two_100", "size_6_big_run_three_40"] #Of saved nns
    last_saved_gen = 200 #should be 0 if starting a new run
    if True: #change true to false if starting new run
        reload_run(0.42, 0.015, names, last_saved_gen=last_saved_gen)
    elif Params.save_nns:
        rl_sys.save(name+"_0")
        names.append(name+"_0")
    tournament = TOPP(names_of_nns=names, use_only_nn=Params.use_nn_for_battle)
    tournament.tournament()
    print(*tournament.agents, sep="\n")
    print(names)
    print("epsilon: {}, c_factor: {}\n".format(Params.epsilon, Params.c_factor))
    tournament = None
    for i in range(last_saved_gen+1, Params.episodes+1):
        print("EPISODE_NUMBER: {}".format(i))
        rl_sys.play_game_with_mcts_and_train()
        Params.c_factor = Params.c_factor*Params.c_factor_decay
        Params.epsilon = Params.epsilon*Params.epsilon_decay
        Params.epsilon = max(Params.epsilon, Params.epsilon_min)
        if Params.save_nns:
            if i%Params.save_interval == 0:
                rl_sys.save(name+"_{}".format(i))
                names.append(name+"_{}".format(i))
                tournament = TOPP(names_of_nns=names, use_only_nn=Params.use_nn_for_battle)
                tournament.tournament()
                print(*tournament.agents, sep="\n")
                print(names)
                print("epsilon: {}, c_factor: {}\n".format(Params.epsilon, Params.c_factor))
                tournament = None
    if Params.save_nns:
        tournament = TOPP(names_of_nns=names, use_only_nn=Params.use_nn_for_battle)
        tournament.tournament()
        print(*tournament.agents, sep="\n")

def load_nn_and_tournament():
     name = "size_4_big_nn_episodes"
     names = [name + "_{}".format(runs) for runs in range(0, 101, 20)]
     #names.reverse()
     t = TOPP(names, use_only_nn=Params.use_nn_for_battle)
     t.tournament()
     print(*t.agents, sep="\n")

def battle_0_vs_100():
    names = ["size_4_big_nn_episodes_100", "size_4_big_nn_episodes_0"]
    t = TOPP(names, use_only_nn=Params.use_nn_for_battle)
    #Params.display_battle_nn = True
    t.tournament()
    print(*t.agents, sep="\n")
def load_agent(nn_file_path:str, use_mcts=True):
    actor = ActorNN(nn_file_path)
    actor.model = tf.keras.models.load_model(nn_file_path, custom_objects={'deepnet_cross_entropy':params.deepnet_cross_entropy})
    if use_mcts:
        rl_agent = RLSystem()
        rl_agent.actor = actor
        return rl_agent
    return actor

if __name__ == "__main__":
    #battle_0_vs_100()
    full_algorithm()
    #load_nn_and_tournament()
all_timer.stop()
print(all_timer)
print(MCTS.rollout_timer)
print(MCTS.select_move_timer)
print(MCTS.tree_policy_timer)


# Напишите программу,
# которая принимает на вход вещественное число и показывает сумму его цифр

#для целых чисел
#num = int(input("Введите целое: "))
#sum = 0
#while (num != 0):
#  sum = sum + num % 10
#  num = num // 10
#print("Сумма цифр числа равна: ", sum)

#для вещественных чисел
num = input("Введите вещественное число: ")
# разделим введённое (тип данных строка) на две части
x = num.split(".")
a = int(x[0]) # целая часть
b = int(x[1]) # дробная часть
с = 0
while (a != 0): # складываем числа целой части
    с = с + (a % 10)
    a = a // 10

while (b != 0): # складываем числа дробной части
    с = с + (b % 10)
    b = b // 10
print("Сумма цифр равна:", с)


"""
Course:         CS 7641 Assignment 1, Spring 2020
Date:           January 19th, 2020
Author:         Maziar Mardan
GT Username:    mmardan3
"""

import dataloader
import KNN
import ANN
import DT
import SVM
import Boosting
import experiments

if __name__ == '__main__':
    # import datasets
    dataset = []
    dataset1 = dataloader.incomeDS()
    dataset1.processDataset()
    dataset.append(dataset1)
    dataset2 = dataloader.wineDS()
    dataset2.processDataset()
    dataset.append(dataset2)

    steps = 2
    file = open('Best Hyperparameters at Step '+str(1)+'.txt', 'w')
    file.write("Best Hyperparameters at Step " + str(1) + '\n')
    file.write("Figures are from step "+str(steps)+'\n')

    # create the experiment class
    exp = experiments.experiments()

    for set in dataset:
        file.write("Dataset "+str(set.datasetNo)+" Information:\n")
        file.flush()

        # start the first learner KNN
        knn = KNN.KNNLearner(datasetNo=set.datasetNo)
        _, bestParams = exp.getBestGridSearchedModel(knn, set)
        print("Best Grid-Searched Params for KNN", bestParams)
        file.write("Best Grid-Searched Params for KNN: "+str(bestParams)+'\n')
        file.flush()
        knnBestGridSearched = KNN.KNNLearner(**bestParams, datasetNo=set.datasetNo)
        exp.getLearningCurve(knnBestGridSearched, set)
        exp.getComplexityCurve(knnBestGridSearched, set)

        # repeat the learning process
        for i in range(steps):
            knnBestGridSearched = exp.repeatTheLearningProcess(knnBestGridSearched, set)

        score = exp.scoreTestingSet(knnBestGridSearched, set)

        print("Testing Score for KNN: ", score)
        file.write("Testing Score for KNN: " + str(score) + '\n')
        file.flush()

        # start the second learner Decision Tree
        dt = DT.DTLearner(datasetNo=set.datasetNo)
        _, bestParams = exp.getBestGridSearchedModel(dt, set)
        print("Best Grid-Searched Params for Decision Tree", bestParams)
        file.write("Best Grid-Searched Params for Decision Tree: " + str(bestParams)+'\n')
        file.flush()
        dtBestGridSearched = DT.DTLearner(**bestParams, datasetNo=set.datasetNo)
        exp.getLearningCurve(dtBestGridSearched, set)
        exp.getComplexityCurve(dtBestGridSearched, set)

        # repeat the learning process
        for i in range(steps):
            dtBestGridSearched = exp.repeatTheLearningProcess(dtBestGridSearched, set)

        score = exp.scoreTestingSet(dtBestGridSearched, set)

        print("Testing Score for Decision Tree: ", score)
        file.write("Testing Score for Decision Tree: " + str(score) + '\n')
        file.flush()

        # start the fourth learner SVM
        svm = SVM.SVMLearner(datasetNo=set.datasetNo)
        _, bestParams = exp.getBestGridSearchedModel(svm, set)
        print("Best Grid-Searched Params for SVM", bestParams)
        file.write("Best Grid-Searched Params for SVM: " + str(bestParams)+'\n')
        file.flush()
        svmBestGridSearched = SVM.SVMLearner(**bestParams, datasetNo=set.datasetNo)
        exp.getLearningCurve(svmBestGridSearched, set)
        exp.getComplexityCurve(svmBestGridSearched, set)

        # repeat the learning process
        for i in range(steps):
            svmBestGridSearched = exp.repeatTheLearningProcess(svmBestGridSearched, set)

        score = exp.scoreTestingSet(svmBestGridSearched, set)

        print("Testing Score for SVM: ", score)
        file.write("Testing Score for SVM: " + str(score) + '\n')
        file.flush()

        # start the fifth learner Boosting
        boosting = Boosting.BoostingLearner(datasetNo=set.datasetNo)
        _, bestParams = exp.getBestGridSearchedModel(boosting, set)
        print("Best Grid-Searched Params for Boosting", bestParams)
        file.write("Best Grid-Searched Params for Boosting: " + str(bestParams)+'\n')
        file.flush()
        boostingBestGridSearched = Boosting.BoostingLearner(**bestParams, datasetNo=set.datasetNo)
        exp.getLearningCurve(boostingBestGridSearched, set)
        exp.getComplexityCurve(boostingBestGridSearched, set)

        # repeat the learning process
        for i in range(steps):
            boostingBestGridSearched = exp.repeatTheLearningProcess(boostingBestGridSearched, set)

        score = exp.scoreTestingSet(boostingBestGridSearched, set)

        print("Testing Score for Boosting: ", score)
        file.write("Testing Score for Boosting: " + str(score) + '\n')
        file.flush()

        # start the third learner ANN
        ann = ANN.ANNLearner(datasetNo=set.datasetNo)
        _, bestParams = exp.getBestGridSearchedModel(ann, set)
        print("Best Grid-Searched Params for Neural Networks", bestParams)
        file.write("Best Grid-Searched Params for Neural Networks: " + str(bestParams)+'\n')
        file.flush()
        annBestGridSearched = ANN.ANNLearner(**bestParams, datasetNo=set.datasetNo)
        exp.getLearningCurve(annBestGridSearched, set)
        exp.getComplexityCurve(annBestGridSearched, set)
        exp.getTrainingTimeCurve(annBestGridSearched, set)

        # repeat the learning process
        for i in range(steps):
            annBestGridSearched = exp.repeatTheLearningProcess(annBestGridSearched, set)

        score = exp.scoreTestingSet(annBestGridSearched, set)

        print("Testing Score for Neural Network: ", score)
        file.write("Testing Score for Neural Network: " + str(score) + '\n')
        file.flush()

    file.close()


#! /usr/bin/env python3
# Ping Client
# Name: Edel Barcenas
# UCID: eeb24,  31446886
# CS 356-008
import sys
import socket
import time
import struct

# Get the server hostname, port and data length as command line arguments
host = sys.argv[1]  # ip address
port = int(sys.argv[2])

# Creates UDP client socket. AF_INET: Address from Internet, SOCK_DGRAM: UDP
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# throws TimeoutError after one second
clientsocket.settimeout(1)

sequenceNum = 1
# Packets sent, received, lost
ps, pr, pl = 0, 0, 0
totalTime, minPing, maxPing = 0.0, 10.0, 0.0

while sequenceNum < 11:
    # increment packets sent
    ps += 1
    # encode/pack message
    # h: short int signed, 1: outgoing message
    outgoing = struct.pack('>HH', 1, sequenceNum)

    print("IP " + host + " Port " + str(port), end='')

    # start round trip timer
    timer = time.time()

    # Send data to server
    clientsocket.sendto(outgoing, (host, port))

    try:
        # Receive the server response
        dataEcho, address = clientsocket.recvfrom(1024)
        dataUnpacked = struct.unpack('>HH', dataEcho)

        # end round trip timer
        timer = time.time() - timer
        # update timing records & packets received
        totalTime += timer
        pr += 1
        if timer < minPing:
            minPing = timer
        if timer > maxPing:
            maxPing = timer

        print(" Ping " + str(timer), " Sequence Num: " + str(dataUnpacked[1]))

    except:
        # increment packets lost
        pl += 1
        print(" TIMED OUT   Sequence Num: " + str(sequenceNum))

    sequenceNum += 1

# final print statement
print("\nPackets Sent: "+str(ps)+
      "\nPackets Recieved: "+str(pr)+
      "\nPackets Lost: "+str(pl)+
      "\nLoss Rate: "+str(float(pl)/ps*100)+"%"
      "\nMin Ping: "+str(minPing)+
      "\nMax Ping: "+str(maxPing)+
      "\nAvg Ping: "+str(totalTime/(pr)))

# Close the client socket
clientsocket.close()


from flask import Blueprint, jsonify, session, request
# from app.models import db, User, Catch, Subpost, Condition
# from app.utils import upload, format_errors
# from sqlalchemy.orm import joinedload
import os

map_routes = Blueprint('map', __name__)
@map_routes.route("/key", methods=["GET"])
def load_map_api_key():
    key = os.environ.get('MAPS_API_KEY')
    return {'googleMapsAPIKey': key}

# @map_routes.route("/key", methods=["GET"])


import sys

from main.kuhn import kuhn

class VengAlg():
    def __init__(self, matrix):
        self.matrix = matrix

    def execute(self):
        self.reduce_matrix(min)
        matchings = self.get_max_matchings(self.build_adjacency_matrix())
        while not self.is_perfect_matchings(matchings):
            free_vertex = self.get_free_vertex(matchings)
            alpha_sets = self.get_sets_for_alpha(matchings, free_vertex)
            self.make_alpha_and_reduce_matrix(alpha_sets)
            matchings = self.get_max_matchings(self.build_adjacency_matrix())
        return matchings

    def reduce_matrix(self, minimize_func):
        for i, row in enumerate(self.matrix):
            reduce_value = minimize_func(row)
            for j, item in enumerate(row):
                self.matrix[i][j] = self.matrix[i][j] - reduce_value
        if self.is_not_covered_cols_present():
            for j in self.get_not_covered_col_indexes():
                reduce_value = self.apply_for_col(j, minimize_func)
                for i in range(len(self.matrix)):
                    self.matrix[i][j] = self.matrix[i][j] - reduce_value

    def build_adjacency_matrix(self):
        return [[item == 0 for item in row] for row in self.matrix]

    def apply_for_col(self, col_index, apply_func):
        reverted_matrix = [[None for item in row] for row in self.matrix]
        for j in range(len(self.matrix)):
            for i in range(len(self.matrix)):
                reverted_matrix[j][i] = self.matrix[i][j]
        return apply_func(reverted_matrix[col_index])

    def is_not_covered_cols_present(self):
        covered_cols = []
        for j in range(len(self.matrix)):
            trigger = False
            for i in range(len(self.matrix)):
                if self.matrix[i][j] == 0:
                    trigger = True
                    break
            covered_cols.append(trigger)
        for item in covered_cols:
            if not item:
                return True
        return False

    def get_not_covered_col_indexes(self):
        col_indexes = []
        for j in range(len(self.matrix)):
            trigger = False
            for i in range(len(self.matrix)):
                if self.matrix[i][j] == 0:
                    trigger = True
                    break
            if not trigger:
                col_indexes.append(j)
        return col_indexes

    def get_max_matchings(self, adjacency_matrix):
        matrix = [[1 if x else 0 for x in row] for row in adjacency_matrix]
        result = kuhn(matrix)
        max_matchings = []
        for col, row in enumerate(result):
            if row != -1:
                max_matchings.append((row, col))
        return max_matchings

    def is_perfect_matchings(self, matchings):
        return len(matchings) == len(self.matrix)

    def get_free_vertex(self, max_matchings):
        rows = [0 for i in range(len(self.matrix))]
        cols = [0 for j in rows]
        result = {'rows': [],
                  'cols': []}

        for item in max_matchings:
            i, j = item
            rows[i] = 1
            cols[j] = 1

        for i in range(len(rows)):
            if rows[i] == 0:
                result['rows'].append(i)
            if cols[i] == 0:
                result['cols'].append(i)
        return result

    def get_sets_for_alpha(self, max_matchings, free_vertexes):
        vertexes = []
        chain = set()
        for i in free_vertexes['rows']:
            for j in range(len(self.matrix)):
                if self.matrix[i][j] == 0:
                    vertexes.append((i, j))
        for vertex in vertexes:
            i, j = vertex
            for item in max_matchings:
                ii, jj = item
                if j == jj:
                    chain.add((ii, jj))
        x = set()
        y = set()
        yy = set()
        for item in chain:
            i, j = item
            x.add(i)
            y.add(j)
        for item in free_vertexes['rows']:
            x.add(item)
        for i in range(len(self.matrix)):
            yy.add(i)

        return {'rows': x, 'cols': yy - y}

    def make_alpha_and_reduce_matrix(self, sets):
        xlist = list(sets['rows'])
        ylist = list(sets['cols'])
        res = [[-1 for item in row] for row in self.matrix]
        for i in xlist:
            for j in ylist:
                res[i][j] = self.matrix[i][j]
        minimum = sys.maxsize

        for i, row in enumerate(res):
            for j in range(len(res)):
                if minimum > res[i][j] and res[i][j] != -1 and res[i][j] != 0:
                    minimum = res[i][j]
        cols = set([i for i in range(len(self.matrix))]) - sets['cols']
        for i in xlist:
            for j in range(len(self.matrix)):
                self.matrix[i][j] -= minimum
        for i in range(len(self.matrix)):
            for j in list(cols):
                self.matrix[i][j] += minimum


import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

matplotlib.use('TkAgg')

def takeLine():
    x1 = np.random.uniform(-1, 1)
    x2 = np.random.uniform(-1, 1)
    y1 = np.random.uniform(-1, 1)
    y2 = np.random.uniform(-1, 1)

    ydiff = y2 - y1
    xdiff = x2 - x1

    slope = ydiff / xdiff
    inter = (xdiff * y2 - ydiff * x2) / xdiff

    return slope, inter

def getY(slope, inter, x1, x2):
    est_x2 = slope * x1 + inter
    y = np.sign(x2 - est_x2)
    return y

def takeSample(numPoint):
    x1 = np.random.uniform(-1, 1, numPoint * 2)
    x = x1.reshape(numPoint, 2)
    temp = np.zeros((numPoint, 1)) + 1
    x = np.hstack((temp, x))
    return x

N = 10
def test1(m, c):
    x1 = np.random.uniform(-10, 10, N)
    x2 = np.random.uniform(-10, 10, N)
    y = np.sign(x2 - (m * x1 + c))
    return np.hstack((np.zeros((N, 1))+1, x1.reshape((N, 1)), x2.reshape((N, 1)))), y

def pred_y(w, x):
    pred = np.sign(np.transpose(x @ w))
    return pred

def perceptron(X, Y):
    w = np.zeros(len(X[0]))
    eta = 1
    epochs = 2

    for t in range(epochs):
        for i, x in enumerate(X):
            if (np.dot(X[i], w)*Y[i]) <= 0:
                w = w + eta * X[i] * Y[i]

    return w

corrupt = 0.1
corruptNum = int(corrupt * N)

def noiseY(Y):
    choice = np.random.randint(0, N, corruptNum)
    for i in range(corruptNum):
        Y[i] = Y[i] * -1
    return Y

def hw(noise):
    m, c = takeLine()
    trainx, trainy = test1(m, c)
    if noise:
        trainy = noiseY(trainy)
    w = perceptron(trainx, trainy)
    estY = pred_y(w, trainx)
    err = 1 - sum(estY == trainy) / N
    Ein = err

    testx, testy = test1(m, c)
    estY = pred_y(w, testx)
    err = 1 - sum(estY == testy) / N
    Eout = err

    return Ein, Eout

def Q1():
    for j in range(5):
        numIter = 1000
        totalEin, totalEout = 0, 0
        for i in range(numIter):
            ein, eout = hw(True)
            totalEin = totalEin + ein
            totalEout = totalEout + eout
        print('avgEin = ', str(totalEin/numIter), ', avgEout = ', str(totalEout/numIter))

def Q2():
    for j in range(10):
        numIter = 2
        totalEin, totalEout = 0, 0
        for i in range(numIter):
            ein, eout = hw(False)
            totalEin = totalEin + ein
            totalEout = totalEout + eout
        print('avgEin = ', str(totalEin/numIter), ', avgEout = ', str(totalEout/numIter))

Q2()


import nltk
from nltk.stem import WordNetLemmatizer
from nltk.stem import SnowballStemmer
nltk.download('wordnet')
nltk.download('omw-1.4')

class LemmatizerAndStemmer:
    @staticmethod
    def lemmatize_tweet(tweet: str) -> str:
        """
        Lemmatizes a tweet. worst, worse, bad -> bad.
        :param tweet: The tweet to lemmatize.
        :return: The lemmatized tweet.
        """
        lemmatizer = WordNetLemmatizer()
        new_tweet = ""
        for word in tweet.split(' '):
            new_tweet += lemmatizer.lemmatize(word) + ' '
        return new_tweet

    @staticmethod
    def stem_tweet(tweet: str) -> str:
        """
        Stems a tweet. plays, playing -> play.
        :param tweet: The tweet to stem.
        :return: The stemmed tweet.
        """
        ps = SnowballStemmer("english")
        new_tweet = ""
        for word in tweet.split(' '):
            new_tweet += ps.stem(word) + ' '
        return new_tweet

    @staticmethod
    def stem_and_lemmatize_tweet(tweet: str) -> str:
        """
        Stems and lemmatizes a tweet.
        :param tweet: The tweet to stem and lemmatize.
        :return: The stemmed and lemmatized tweet.
        """
        return LemmatizerAndStemmer.lemmatize_tweet(LemmatizerAndStemmer.stem_tweet(tweet))


import tensorflow as tf
class S_Layer:
	def __init__(self):
		print("Creating a New Siamese Class")

	def siamese_f(self,state,target):
		print("I am inside the siamese_f")
		self.siamese_s=self.construct_Siamese(state)
		self.siamese_t=self.construct_Siamese(target)
		self.obs=tf.concat(values=[self.siamese_s, self.siamese_t], axis=1,name='obs')
		return self.obs
		print("shaa")

	'''
	def __init__(self,state,target):

		self.siamese_s=self.construct_Siamese(state)
		self.siamese_t=self.construct_Siamese(target)
		self.obs = tf.concat(values=[self.siamese_s, self.siamese_t], axis=1,name='obs')
	'''

	def construct_Siamese(self, input):
		print("Building the Siamese with shared variables")
		with tf.variable_scope("Siamese", reuse=tf.AUTO_REUSE):
			layer_1 = tf.layers.dense(inputs=input, units=512, activation=tf.nn.leaky_relu, name='layer1')
			layer_2 = tf.layers.dense(inputs=layer_1, units=512, activation=tf.nn.leaky_relu, name='layer2')
			#v = tf.get_variable("v", [1])
			#print(v)
		return layer_2


from email import message
import torch
import pandas as pd
import matplotlib.pyplot as plt
from torch import ne, nn
from torch.autograd import Variable
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import time
import numpy as np
import util

# --------------------------------（常量定义）------------------------------
time_steps = 24 # ~ 2小时
epoch = 40
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
batch_size = 64
log_every = 20
patience = 200
min_val_loss = float('inf')
# ------------------------------- （LSTM 模型）---------------------------------------

# 加载数据集
def load_data(path, np_type=True):
    data_csv = pd.read_csv(path, usecols=[2])
    data_csv = data_csv.dropna()
    dataset = data_csv.values
    dataset = dataset.astype('float32')
    x, y = split_data(dataset,np_type)
    return x, y

def split_data(dataset,np_type=True):
    dataX, dataY = [], []
    lens = len(dataset)
    for i in range(lens - time_steps):
        dataX.append(dataset[i: i + time_steps])
        dataY.append(dataset[i + time_steps])
    dataX = np.array(dataX).reshape(-1, time_steps)
    dataY = np.array(dataY)
    return dataX, dataY

class TrafficDataset(Dataset):
    def __init__(self,filepath):
        train_x, train_y = load_data(filepath)
        var_x = torch.tensor(train_x, dtype=torch.float32, device=device)
        var_y = torch.tensor(train_y, dtype=torch.float32, device=device)
        self.x = var_x
        self.y = var_y
        self.len = train_y.shape[0]
        print(self.len)

    def __getitem__(self,index):
        return self.x[index], self.y[index]

    def __len__(self):
        return self.len

# 模型定义
class lstm_reg(nn.Module):
    def __init__(self, input_size, hidden_size, output_size=1, num_layers=2):
        super(lstm_reg, self).__init__()
        self.rnn = nn.LSTM(input_size, hidden_size, num_layers) # rnn
        self.reg = nn.Linear(hidden_size * time_steps, 1024) # 回归
        self.reg2 = nn.Linear(1024, output_size) # 回归
        self.activate = nn.ReLU()

    def forward(self, x):
        x, _ = self.rnn(x) # (seq, batch, hidden)
        s, b, h = x.shape
        x = x.view(b, s*h) # 转换成线性层的输入格式
        x = self.reg(x)
        x = self.activate(x)
        x = self.reg2(x)
        return x

# ------------------------------- （LSTM训练）---------------------------------------

def test_net(net):
    net.eval()
    test_x, test_y = load_data('~/16-5m.csv')
    test_x = test_x[0,:]
    print(test_x)
    result_y = []

    for i in range(0, test_y.shape[0]):
        var_x = torch.tensor(test_x, dtype=torch.float32, device=device)
        var_x = util.get_batchs_for_lstm(var_x, time_steps)
        pred_y = net(var_x).cpu()
        pred_y_num = pred_y.view(-1).data.numpy().tolist()[0]
        test_x = test_x.tolist()
        test_x.append(pred_y_num)
        result_y.append(pred_y_num)
        test_x = test_x[1:] #后移一格，24步预测后一步
        test_x = np.array(test_x)
    print('begin draw...')
    plt.plot(result_y, 'r', label='prediction')
    plt.plot(test_y, 'b', label='real')
    plt.legend(loc='best')
    plt.show()

def train_lstm():
    train_dataset = TrafficDataset('~/15-5m.csv')
    val_dataset = TrafficDataset('~/16-5m.csv')

    print(torch.cuda.is_available())
    net = lstm_reg(1, 64).to(device)
    criterion = nn.MSELoss()
    optimizer = torch.optim.Adam(net.parameters(), lr=1e-2)

    train_loader = DataLoader(dataset=train_dataset,
                          batch_size=batch_size,
                          shuffle=False,
                          num_workers=0)

    val_loader = DataLoader(dataset=val_dataset,
                          batch_size=batch_size,
                          shuffle=False,
                          num_workers=0)

    for epoch_num in range(epoch):
        losses = []
        for i, data in enumerate(train_loader, 0):
            # 前向传播
            var_x, var_y = data
            var_x = util.get_batchs_for_lstm(var_x, time_steps)
            out = net(var_x)
            loss = criterion(out, var_y)
            # 反向传播
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            loss_num = loss.data.item()
            losses.append(loss_num)

        print('Epoch: {}'.format(epoch_num))
        if (epoch_num % log_every) == log_every - 1:
            val_loss = util.compute_val_loss(net, val_loader, criterion, epoch_num, device, time_steps)
            message = 'Epoch: {}, train_mae: {:.5f}, val_mae: {:.6f} '.format(epoch_num, np.mean(losses), val_loss)
            print(message)
    return net

result_net = train_lstm()
test_net(result_net)