#!/usr/bin/python2.7
# -*- coding: latin-1 -*-
import keras.optimizers as optimizers
import numpy as np
import pandas as pd

try:
    reload  # Python 2.7
except NameError:
    try:
        from importlib import reload  # Python 3.4+
    except ImportError:
        from imp import reload  # Python 3.0 - 3.3

import matplotlib as mpl
import matplotlib.pyplot as plt
import sys, warnings, argparse

import os
import sys
import os.path as osp

import time

## Import de la classe CVC ##
cases_folder = osp.abspath(osp.dirname("../cases/"))
sys.path.append(cases_folder)

import tensorflow as tf

from keras.models import Model
from keras.models import Sequential
from keras.layers import Input, Flatten, Dense, MaxPool1D, UpSampling1D, Activation, Conv1D

import Class_Vit_Choc as cvc
cvc = reload(cvc)

from visu_strides import glide1D

try :
    tf.reset_default_graph()
except :
    pass

def model():
    # Unet
    input_shape = (82,1)

    input_data = Input(shape=input_shape)
    x = Conv1D(2, kernel_size=3, padding='same')(input_data)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("in --> Conv1D(32, 2, same) = {}".format(x.get_shape())) # (?, 81, 32)

    x = Conv1D(4, kernel_size=2, padding='same')(input_data)
    x = Activation('relu')(x)
    print ("Conv1D --> Conv1D(32, 2, same). Out_shape = {} \n".format(x.get_shape()))
    #print x.get_shape() # (?, 81, 32)

    in_pool_shape = x.get_shape()

    x = MaxPool1D(pool_size=2, padding='same')(x)
    print ("MaxPool1D pool_size = 2, padding same")
    print ("MaxPool1D(1st enc): in_shape = {}\tOut_shape = {}".format(in_pool_shape, x.get_shape()))
    print (" ")
    #

    x = Conv1D(8, kernel_size=2, padding='same')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Pooled --> Conv1D(64, 2, same). Out_shape = {}".format(x.get_shape()))

    x = Conv1D(64, kernel_size=2, padding='same')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Conv1D --> Conv1D(64, 2, same). Out_shape = {} \n".format(x.get_shape()))

    in_pool_shape = x.get_shape()

    x = MaxPool1D(pool_size=2, padding='same')(x)
    print ("MaxPool1D pool_size = 2, padding same")
    print ("MaxPool1D(2nd enc): in_shape = {}\tOut_shape = {}".format(in_pool_shape, x.get_shape()))
    print (" ")

    x = Conv1D(16, kernel_size=2, padding='same')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Pooled --> Conv1D(128, 2, same). Out_shape = {}".format(x.get_shape()))

    x = Conv1D(16, kernel_size=2, padding='same')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Conv1D --> Conv1D(128, 2, same). Out_shape = {} \n".format(x.get_shape()))

    in_samp_shape = x.get_shape()

    x = UpSampling1D(2)(x)
    print ("Upsampling pool_size = 2")
    print ("UpSampling(1st dec): in_shape= {}\tOut_shape = {}".format(in_samp_shape, x.get_shape()))
    print (" ")

    x = Conv1D(8, kernel_size=2, padding='same')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Upsampled --> Conv1D(64, 2, same). Out_shape = {}".format(x.get_shape()))

    x = Conv1D(4, kernel_size=2, padding='same')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Conv1D --> Conv1D(64, 2, same). Out_shape = {} \n".format(x.get_shape()))

    in_samp_shape = x.get_shape()

    x = UpSampling1D(2)(x)
    print ("Upsampling pool_size = 2")
    print ("UpSampling(2nd dec): in_shape= {}\tOut_shape = {}".format(in_samp_shape, x.get_shape()))
    print (" ")

    x = Conv1D(2, kernel_size=3, padding='valid')(x)
    #Rajouter une couche BN
    x = Activation('relu')(x)
    print ("Upsampled --> Conv1D(32, 2, same). Out_shape = {}".format(x.get_shape()))

    x = Conv1D(1, kernel_size=1, padding='valid')(x)
    #Rajouter une couche BN
    output = Activation('relu')(x)
    print ("Conv1D --> Conv1D(1, 1, same) (Output). Out_shape = {}".format(x.get_shape()))

    unet = Model(input_data, output, name='u_net_out')

    return unet
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# u_it139_0_Nt52_Nx82_CFL0_4_nu0_05_sin.npy

parser = cvc.parser()
cb = cvc.Vitesse_Choc(parser)

def build_dataset(cb) :
    nu52_avail = [0.05, 0.035, 0.025, 0.015]
    Nt = 52
    Nx = 82
    CFL = '0_4'
    str_nu52_avail = [str(i).replace('.', '_') for i in nu52_avail]

#    u_it168_4_Nt52_Nx82_CFL0_4_nu0_05_sin.npy

    true_data =lambda it,neval,s_nu : "u_it%d_%d_Nt52_Nx82_CFL0_4_nu%s_sin.npy" % (it, neval, s_nu)

    warp_name = lambda it, neval, s_nu : osp.join(cb.datapath, true_data(it, neval, s_nu))

    u_means = dict()

    uu = np.zeros((Nx))
    tempu = np.zeros(Nx)

    path_dataset = osp.join(cb.datapath, 'burger_matrices/cas_u')

    std_name = lambda std, it, s_nu : '%s_Nx_82_Nt_52_nu_%s_typei_sin_CFL_0_4_it_%03d.npy' % (std, s_nu, it)

    key_dict = lambda it, s_nu : "u_it%d_Nt52_Nx_82_nu%s" %(it, s_nu)

    ### Calcul de la moyenne
    for s in str_nu52_avail :
        for i in range(cb.itmax) :
            tempu = np.zeros(Nx)
            for ev in range(cb.num_real) :
                uu = np.load(warp_name(i, ev, s))
                for j in range(0, Nx) :
                    tempu[j-1] += uu[j] / cb.num_real

            u_means[key_dict(i, s)] = tempu

    X, y = np.zeros_like(cb.line_x), np.zeros_like(cb.line_x)
    cnt = 0

    X_keys, y_keys = dict(), dict()

    for s in str_nu52_avail :
        for i in range(cb.itmax) :
            betafile = os.path.join(cb.datapath, "burger_matrices/cas_u/betas", std_name("beta", i, s))
#            chol_file = os.path.join(cb.datapath, "burger_matrices/cas_u/cholesky", std_name(chol, i, s))

            vel_file = u_means[key_dict(i, s)]

            X = np.block([ [X], [vel_file] ])
            y = np.block([ [y], [np.load(betafile)] ])

            X_keys[cnt] = key_dict(i, s)
            y_keys[cnt] = betafile

            cnt += 1

    X = np.delete(X, 0, axis=0)
    y = np.delete(y, 0, axis=0)
    return X, y, (cnt, X_keys, y_keys, u_means)

def split_data(X, y):
    permutation = np.random.permutation(len(y))

    X, y = np.copy(X), np.copy(y)

    X_rand = X[permutation]
    y_rand = y[permutation]

    xtr = X_rand[:int(len(y)*0.8)]
    ytr = y_rand[:int(len(y)*0.8)]

    xte = X_rand[int(len(y)*0.8):int(len(y)*0.9)]
    yte = y_rand[int(len(y)*0.8):int(len(y)*0.9)]

    xval = X_rand[int(len(y)*0.9):]
    yval = y_rand[int(len(y)*0.9):]

    return xtr, ytr, xte, yte, xval, yval

def see_pred(cb, unet, u_means, key, indice) :
    u_n = xval[indice]
    beta_pred = unet.predict(u_n.reshape(1, 82, 1)).ravel()

    u_n = u_n.ravel()
    true_beta = yval[indice].ravel()

#    u_beta(self, beta, u_n, verbose=False)
    u_npred = cb.u_beta(beta_pred, u_n)

#    u_nexact =

if __name__ == '__main__':
    #    run brgrs1D_beta.py -nu 5e-2 -itmax 180 -CFL 0.4 -num_real 5 -Nx 82 -Nt 32 -typeJ "u" -dp "./../cases/data/2019_burger_data/"
    parser = cvc.parser()
    cb = cvc.Vitesse_Choc(parser)

    unet = model()
    X, y, utils = build_dataset(cb)

    u_means = utils[-1]

    xtr, ytr, xte, yte, xval, yval = split_data(X, y)

    from keras.callbacks import TensorBoard

    adam = optimizers.Adam(lr=1e-2, decay=1e-5)
    unet.compile(loss='mean_squared_error', optimizer=adam)

    x_train = np.reshape(xtr, (len(xtr), 82, 1))
    y_train = np.reshape(ytr, (len(ytr), 82, 1))

    x_test = np.reshape(xte, (len(xte), 82, 1))
    y_test = np.reshape(yte, (len(yte), 82, 1))

    x_validation = np.reshape(xval, (len(xval), 82, 1))
    y_validation = np.reshape(yval, (len(yval), 82, 1))

    unet.fit(x_train, y_train,
                epochs=10,
#                batch_size=32,
                shuffle=True,
                validation_data=(x_test, y_test))
#                callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])


#!bin/python
import json, logging, email, urllib
import klein
from twisted.web.client import getPage
from twisted.internet.defer import inlineCallbacks
logging.basicConfig(level=logging.WARN)

CHECKVIST = "http://checkvist.com"

config = json.load(open("config.json"))

def tasksUri():
    return CHECKVIST + "/checklists/%s/tasks.json" % str(config['checklist_id'])

@inlineCallbacks
def postTask(taskText):
    result = yield getPage(CHECKVIST + "/auth/login.json", method="POST",
                postdata=urllib.urlencode({
                    'username': config['username'],
                    'remote_key': config['remote_key'],
                    }))
    token = json.loads(result)

    yield getPage(tasksUri(), method="POST",
                postdata=urllib.urlencode({
                    'token': token,
                    'task[content]': taskText,
                    'task[position]': 1,
                }))

@klein.route('/')
def index(request):
    return ('POST an email message to newmail '
            'to add a task. The email subject line becomes the task text.')

@klein.route('/newmail', methods=['POST'])
def newmail(request):
    msg = email.message_from_file(request.content)
    subject = msg['subject']
    if subject is None:
        raise ValueError("no subject found")

    done = postTask(subject)
    done.addCallback(lambda result: "ok")
    return done

klein.run('0.0.0.0', port=9108)


from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__)

@app.route('/')
def welcome():
    return render_template('index.html')

@app.route('/success/<int:number>')
def success(number):

    res=""
    if number>=50:
        res="PASS"
    else:
        res="FAIL"
    exp = {'score':number, 'result':res}

    return render_template('result.html', result=exp)

@app.route('/submit',methods=['POST','GET'])
def result():

    total_score=0.0
    if request.method == 'POST':
        science = float(request.form['science'])
        maths = float(request.form['maths'])
        hindi = float(request.form['hindi'])
        english = float(request.form['english'])

    total_score = (science + maths + hindi + english)/4;
    return redirect(url_for('success',number=total_score))

if __name__=='__main__':
    app.run(debug=True)


import subprocess
from pymongo import MongoClient
import json

client = MongoClient('mongodb://localhost:27017')
db_blocks = client.test001.blocks
db_txes = client.test001.txes
last_db_height = 0

blockcount = int(subprocess.check_output('/root/bin/monkey-cli_p01.sh getblockcount', shell=True, universal_newlines=True))
print(str(blockcount))

for block in db_blocks.find().sort([("_id", -1)]).limit(1):
    last_db_height = int(block['height'])

last_db_height = last_db_height + 1 # start from next block from last inserted
print(str(last_db_height))

if blockcount > last_db_height:
    for index in range(last_db_height,blockcount+1):
        print('index: {}'.format(index))
        # break
        blockhash = subprocess.check_output('/root/bin/monkey-cli_p01.sh getblockhash ' + str(index), shell=True, universal_newlines=True)

        # print(blockhash)

        block = subprocess.check_output('/root/bin/monkey-cli_p01.sh getblock ' + blockhash, shell=True, universal_newlines=True)

        # print(block)

        block_dict = json.loads(block)
        db_blocks.insert_one(block_dict)

        for tx_hash in block_dict['tx']:
            print(tx_hash)
            # raw_tx = subprocess.check_output('/root/bin/monkey-cli_p01.sh getrawtransaction ' + tx_hash, shell=True, universal_newlines=True)
            # print(str(raw_tx))
            # tx = subprocess.check_output('/root/bin/monkey-cli_p01.sh decoderawtransaction ' + raw_tx, shell=True, universal_newlines=True)
            tx = subprocess.check_output('/root/bin/monkey-cli_p01.sh getrawtransaction ' + tx_hash + ' 1', shell=True, universal_newlines=True)
            # print(str(tx))
            db_txes.insert_one(json.loads(tx))


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 11:02:32 2019

@author: FCRA
"""

from DataReader import get_eigentimes
from readmat import *
from data_processing import find_index, seconds_to_utc

#SHORT PERIOD START
def short_period():
    #short_period = get_eigentimes()[1]              #times from post_datasheet
    t_sp_utc =  40334.7 #seconds_to_utc(short_period)         #converting that to UTC time
    i_t_sp = find_index(t_sp_utc)                   #index of the start of each motion
    tend_sp_utc = 40351.                            #end time of motion
    return t_sp_utc, tend_sp_utc, i_t_sp

def phugoid():
    #phugoid = get_eigentimes()[0]
    t_phu_utc =  40430#seconds_to_utc(phugoid)
    i_t_phu = find_index(t_phu_utc)
    tend_phu_utc = 40650
    return t_phu_utc, tend_phu_utc, i_t_phu

def dutch_roll():
    #dutch_roll = get_eigentimes()[2]
    t_dr_utc = 40651.#seconds_to_utc(dutch_roll)
    i_t_dr = find_index(t_dr_utc)
    tend_dr_utc = 40671.
    return t_dr_utc, tend_dr_utc, i_t_dr

def dutch_roll_yd():
    #dutch_roll_yd = get_eigentimes()[3]
    t_dryd_utc = 40704.#seconds_to_utc(dutch_roll_yd)
    i_t_dryd = find_index(t_dryd_utc)
    tend_dryd_utc = 40720
    return t_dryd_utc, tend_dryd_utc, i_t_dryd

def aper_roll():
    #aper_roll = get_eigentimes()[4]+7
    t_apr_utc = 40278. #seconds_to_utc(aper_roll)-5
    i_t_apr = find_index(t_apr_utc)
    tend_apr_utc = t_apr_utc+30
    return t_apr_utc, tend_apr_utc, i_t_apr

def spiral():
    #spiral = get_eigentimes()[5]-5
    t_spir_utc  = 40795.5 #seconds_to_utc(spiral)
    i_t_spir = find_index(t_spir_utc)
    tend_spir_utc =  t_spir_utc + 60
    return t_spir_utc, tend_spir_utc, i_t_spir

plt.figure()
plt.plot(UTC_Seconds, Deflection_of_aileron, label= "Deflection of Aileron")
#plt.plot(UTC_Seconds, Deflection_of_rudder, label = "Deflection of Rudder")
plt.plot(spiral()[0], Deflection_of_aileron[spiral()[-1]], 'o')
#plt.plot(spiral()[0], Deflection_of_rudder[spiral()[-1]], 'o')

plt.legend()
plt.figure()
plt.plot(UTC_Seconds, Roll_Angle, label= "Roll Angle" )
plt.plot(spiral()[0], Roll_Angle[spiral()[-1]], 'o')

plt.legend()
plt.show()


def getSum(n):
    sum = 0
    while (n != 0):
        sum = sum + int(n % 10)
        n = int(n/10)
    return sum

n = int(input("n = "))
m = int(input("m (suma) = "))
multimea = range(0, n+1)

print("Suma m = ", m)
print("Multimea: ", multimea)

k=0
for i in range(0, len(multimea)):
    if getSum(multimea[i]) == m:
        k+=1
print("Cate numere din aceasta multime suma cifrelor fiecarui numar fiind egal cu m: ", k)


from src.state import State

class Automata:
    def __init__(self):
        self.all_states = []
        self.cur_state = None

    def create(self, states, transistions, initial, finals):
        num = len(states)

        name = ''
        cur_transistions = {}
        is_inital = False
        is_final = False

        for i in range(0, num):
            name = states[i]
            cur_transistions = transistions[i]
            is_inital = name == initial
            is_final = name in finals

            state = State(name, cur_transistions, is_inital, is_final)

            self.all_states.append(state)

        self.cur_state = self.return_initial_state()

        # self.mount()

    def mount(self):
        for state in self.all_states:
            print(state.name)
            print(state.transistions)
            print(state.is_initial)
            print(state.is_final)
            print("\n")

    def reset_inital_state(self):
        self.cur_state = self.return_initial_state()

    def return_initial_state(self):
        for state in self.all_states:
            if state.is_initial:
                return state

    def return_state_by_name(self, name):
        for state in self.all_states:
            if state.name == name:
                return state

    def run_step(self, text):
        if text not in self.cur_state.transistions:
            return 3

        next_state_name = self.cur_state.transistions[text]
        self.cur_state = self.return_state_by_name(next_state_name)

        if self.cur_state == None:
            return 2

        if not self.cur_state.is_final:
            return 1

        return 0


"""
@File    ：test_task_comment.py
@Author  ：Zeno
@Email   ：zhangyongjun@ones.ai
@Date    ：2022/3/21
@Desc    ：任务详情-评论测试用例
"""
from falcons.check import CheckerChain
from falcons.com.nick import feature, story, fixture, parametrize

from main.actions.task import TaskAction
from main.api import task as api
from main.params import task as p

@fixture(scope='module')
def task():
    """测试任务"""
    return TaskAction.new_issue()[0]

@fixture(scope='module')
def _message():
    """评论 UUID 缓存"""
    return []

@fixture(scope='module')
def del_task(task):
    """删除测试任务"""
    yield
    TaskAction.del_task(task)

@feature('任务管理-任务详情')
class TestTaskComment(CheckerChain):
    """"""

    @story('T134471 任务详情-评论：添加评论')
    @parametrize('param', p.message_add())
    def test_comment_add(self, param, task, _message):
        """添加评论"""
        message_p = p.task_messages()[0]
        param.uri_args({'task_uuid': task})
        self.call('添加评论', api.TaskSendMessage, param) \
            .assert_response('code', 200) \
            .update_url(message_p, {'task_uuid': task}) \
            .call('查看评论', api.TaskMessages, message_p) \
            .assert_response('messages[0].text', param.json_value('text')) \
            .cache_to(_message, 'messages[0].uuid')

    @story('T134448 任务详情-评论：编辑评论')
    @parametrize('param', p.message_update())
    def test_comment_update(self, param, task, _message):
        """编辑评论"""

        param.json_update('uuid', _message[0])
        param.uri_args({'task_uuid': task, 'message_uuid': _message[0]})
        message_p = p.task_messages()[0]

        self.call('编辑评论', api.TaskMessageUpdate, param) \
            .assert_response('code', 200) \
            .update_url(message_p, {'task_uuid': task}) \
            .call('查看评论', api.TaskMessages, message_p) \
            .assert_response('messages[0].text', param.json_value('text'))

    @story('T134469 任务详情-评论：上传附件（有编辑工作项权限）')
    @story('T134474 任务详情-评论：通过快捷操作上传图片')
    @story('136231 文件：上传文件')
    def test_comment_update_file(self, task):
        """"""
        TaskAction.upload_file(task)

    @story('T134456 任务详情-评论：回复评论（回复自己的评论）')
    @parametrize('param', p.message_reply())
    def test_comment_replay_own(self, param, task, _message):
        param.json_update('replied_message_uuid', _message[0])
        param.uri_args({'task_uuid': task})

        message_p = p.task_messages()[0]

        self.call('回复评论', api.TaskSendMessage, param) \
            .assert_response('code', 200) \
            .update_url(message_p, {'task_uuid': task}) \
            .call('查看评论', api.TaskMessages, message_p) \
            .assert_response('messages[0].text', param.json_value('text')) \
            .cache_to(_message, 'messages[0].uuid')

    @story('T134473 任务详情-评论：通过快捷操作进行换行')
    @parametrize('param', p.message_add(multi=True))
    def test_comment_add_multi_lines(self, param, task, _message):
        """添加多行评论"""
        message_p = p.task_messages()[0]
        param.uri_args({'task_uuid': task})
        self.call('添加可换行评论', api.TaskSendMessage, param) \
            .assert_response('code', 200) \
            .update_url(message_p, {'task_uuid': task}) \
            .call('查看评论', api.TaskMessages, message_p) \
            .assert_response('messages[0].text', param.json_value('text')) \
            .cache_to(_message, 'messages[0].uuid')

    @story('T134464 任务详情-评论：删除评论')
    @parametrize('param', p.message_delete())
    def test_comment_delete(self, param, task, _message):
        """"""

        for m_uid in _message:
            param.uri_args({'task_uuid': task, 'message_uuid': m_uid})

            self.call('删除评论', api.TaskMessageDelete, param)


#!/usr/bin/env python
import parmed as pmd
import numpy as np
# Load the topology file
top = pmd.load_file('UR.prmtop')

# Print bond information
bonds = []
for bond in top.bonds:
    bonds.append([bond.atom1.idx, bond.atom2.idx])

coords = []; symbols = []; res = []
with open('UR.pdb','r') as fp:
    lines = fp.readlines()[1:]
    for line in lines:
        line = line.strip().split()
        if len(line) == 10:
            symbols.append(line[2][0])
            res.append(line[3])
            coords.append([float(line[5]),float(line[6]),float(line[7])])

np.savez('init.npz', coord = coords, symbol = symbols, bond = bonds, res=res)


def main():
    K = int(input())

    stack = []
    for i in range(K):
        inputData = int(input())
        if inputData == 0:
            stack.pop()
        else:
            stack.append(inputData)
    print(sum(stack))

if __name__ == "__main__":
    main()


from database import Database
import dota_parser as dp
import time

db = Database()

def get_hero_stats(hero_id: int) -> str:
    hero_stats = db.get_hero_statistic(hero_id)
    duration = f'{int(hero_stats[15] // 60):02}:{int(hero_stats[15] % 60):02}'
    hero_str = f'Name: {hero_stats[0]}\nTotal games: {hero_stats[1]}\nPick Rate: {hero_stats[2]}%\nWin Rate: {hero_stats[3]}%\nKills: {hero_stats[4]}\nDeaths: {hero_stats[5]}\nAssists: {hero_stats[6]}\nLast hits: {hero_stats[7]}\nDenies: {hero_stats[8]}\nHero damage: {hero_stats[9]}\nHero healing: {hero_stats[10]}\nNet worth: {hero_stats[11]}\nTower damage: {hero_stats[12]}\nGPM: {hero_stats[13]}\nXPM: {hero_stats[14]}\nAverage game duration: {duration}'
    return hero_str

def get_heroes_names(attr: str):
    return db.get_heroes_names_by_attr(attr)

def get_avg_scores() -> str:
    dire_score = db.get_avg_team_score('dire')
    radiant_score = db.get_avg_team_score('radiant')
    return f'Radiant score {radiant_score} VS Dire score {dire_score}'

def get_teams_winrates() -> str:
    dire_wr = db.get_team_winrate('dire')
    radiant_wr = db.get_team_winrate('radiant')
    return f'Radiant {radiant_wr}% VS Dire {dire_wr}%'

def get_avg_duration() -> str:
    avg_dur = db.get_avg_game_duration()
    return f'{int(avg_dur // 60):02}:{int(avg_dur % 60):02}'

def get_avg_first_blood() -> str:
    avg_time = db.get_avg_fb_timing()
    return f'{int(avg_time // 60):02}:{int(avg_time % 60):02}'

def create_tables() -> None:
    db.create_heroes_table()
    db.create_items_table()
    db.create_regions_table()
    db.create_game_modes_table()
    db.create_lobby_types_table()
    db.create_players_table()
    db.create_matches_table()
    db.create_heroes_index()

def insert_static_data() -> None:
    hero_list = dp.get_heroes()
    items_list = dp.get_items()
    region_list = dp.get_regions()
    gm_list = dp.get_game_modes()
    lt_list = dp.get_lobby_types()

    db.insert_heroes(heroes=hero_list)
    db.insert_items(items=items_list)
    db.insert_regions(regions=region_list)
    db.insert_game_modes(game_mods=gm_list)
    db.insert_lobby_types(lobby_types=lt_list)

def parse_matches(times: int=20) -> None:
    for i in range(times):
        try:
            matches_list = dp.get_matches_info(dp.get_matches(dp.get_matches_ids()))
            db.insert_matches(matches=matches_list)
            time.sleep(60)
        except TypeError:
            pass


from argparse import ArgumentParser
import pandas as pd
import numpy as np
from pascal_voc_writer import Writer
import yaml
from xml_utils import parse_xml

classes = yaml.load(open("classes.yaml"))["classes"]

def load_xml(xml_path):
    schema = ["class","x1","y1", "x2", "y2"]
    lst = parse_xml(xml_path)
    df = pd.DataFrame(dict(zip(schema, lst)))
    return df

def load_proposal(proposal_path):
    data = np.genfromtxt(proposal_path, delimiter=",")
    N, _ = data.shape
    data_dict = {
        "x1": data[:, 0],
        "y1": data[:, 1],
        "x2": data[:, 2],
        "y2": data[:, 3]
        }
    for cls in classes:
        data_dict[cls] = np.zeros(N)
    df = pd.DataFrame(data_dict)
    return df

def get_ious(pred_df, box):
    X = 0
    Y = 1
    X2 = 2
    Y2 = 3
    xml_box = pred_df[["x1", "y1", "x2", "y2"]].values
    N, _ = xml_box.shape
    i_boxes = np.zeros((N,4))
    i_boxes[:, X] = np.maximum(xml_box[:, X].reshape(-1), box[X].reshape(-1))
    i_boxes[:, Y] = np.maximum(xml_box[:, Y].reshape(-1), box[ Y].reshape(-1))
    i_boxes[:, X2] = np.minimum(xml_box[:, X2].reshape(-1), box[X2].reshape(-1))
    i_boxes[:, Y2] = np.minimum(xml_box[:, Y2].reshape(-1), box[Y2].reshape(-1))
    i_area = (i_boxes[:, X2] - i_boxes[:, X]) * (i_boxes[:, Y2] - i_boxes[:, Y])
    i_area[i_boxes[:, X2] < i_boxes[:, X]] = 0
    i_area[i_boxes[:, Y2] < i_boxes[:, Y]] = 0
    xml_area = (xml_box[:, X2] - xml_box[:, X]) * (xml_box[:, Y2] - xml_box[:, Y])
    box_area = (box[X2] - box[X]) * (box[Y2] - box[Y])
    iou = i_area/(xml_area+ box_area - i_area)
    iou_df = pd.DataFrame({
        "class": pred_df["class"],
        "iou": iou
        })
    iou_df = iou_df.groupby("class").sum()
    # print(iou_df)
    return iou_df

def get_votes(pred_df, proposal_df):
    N, _ = pred_df.shape
    M, _ = proposal_df.shape
    for i,row in proposal_df.iterrows():
        box = np.array([row.x1, row.y1, row.x2, row.y2])
        iou_df = get_ious(pred_df, box)
        for key in iou_df.index:
            proposal_df.at[i, key] = iou_df.at[key,"iou"]
    return proposal_df

def get_winner(row):
    # select coords we care about
    select = row[4:]
    # print(select)
    winner = select.idxmax()
    if select[winner] == 0:
        return "Body Text"
    return winner

def write_matches(vote_df, out_path):
    vote_df["winner"] = vote_df.apply(get_winner, axis=1)
    # TODO if this matters we need to fill it in
    writer = Writer("n/a", 1920, 1920)
    for row in vote_df.itertuples():
        writer.addObject(row.winner, int(row.x1),
                int(row.y1),
                int(row.x2),
                int(row.y2))
    writer.save(out_path)

def process_doc(prediction_path, proposal_path, out_path):
    data_xml = load_xml(prediction_path)
    data_proposal = load_proposal(proposal_path)
    vote_df = get_votes(data_xml, data_proposal)
    write_matches(vote_df,out_path)

if __name__ == "__main__":
    parser = ArgumentParser("snap Mask RCNN predictions to connected components bounding boxes")
    parser.add_argument("prediction_path", type=str)
    parser.add_argument("proposal_path", type=str)
    parser.add_argument("out_path", type=str)
    args = parser.parse_args()
    process_doc(args.prediction_path, args.proposal_path, args.out_path)


#!/usr/bin/env python3
'''
Author: qiupengfei@rxthinking.com
Date: 2021-04-22 18:19:28

'''

from qcaudit.application.sampleapplication import SampleApplication
from qcaudit.common.const import AUDIT_TYPE_HOSPITAL
from qcaudit.context import Context
from qcaudit.app import Application
from qcaudit.domain.case.req import GetCaseListRequest, GetEmrListRequest
import unittest
import os
from qcaudit.domain.sample.req import GetSampleRecordRequest

from qcaudit.domain.sample.samplerecord import SampleRecord

class TestSampleApplication(unittest.TestCase):

    def setUp(self):
        mysqlUrl = os.environ.get('MYSQL_URL', 'mysql+pymysql://root:rxthinkingmysql@192.168.100.40:31444/qcmanager_v3?charset=utf8mb4')
        mongoUrl = os.environ.get('MONGO_URL', 'mongodb://192.168.101.159')
        self.app = Application(mysqlUrl, mongoUrl)

        self.context = Context(self.app)

    def test_getsample(self):
        req = GetCaseListRequest(
            tags=['hard']
        )
        result, statData = self.context.getSampleApplication(AUDIT_TYPE_HOSPITAL).getSampleCase(
            req, limit=5, sampleNum=5
        )
        for item in result:
            print(item.caseId, item.tags)
        print(statData)
        assert(len(result) > 0)

    def test_submit(self):
        app = self.context.getSampleApplication(AUDIT_TYPE_HOSPITAL)
        record = app.submitSampleResult(
            ['7948886', '7948887', '7948897'],
            '大数ai', '大数ai'
        )
        print(record.id)
        result = app.getSampleRecordHistory(req=GetSampleRecordRequest(
            id=record.id
        ))
        print([item.id for item in result])
        assert(len(result) == 1)

        app.assignExpert(
            record.id, SampleRecord.ASSIGN_TYPE_AVG
        )
        # 获取明细记录, 应该为3
        req = GetCaseListRequest(
            sampleRecordId=record.id
        )
        result = list(self.context.getCaseApplication(AUDIT_TYPE_HOSPITAL).getCaseList(req))
        assert(len(result) == 3)
        # 检查对应的专家已经分配
        for item in result:
            assert(item.sampleRecordItem.expertId is not None)

        # 恢复现场,删除数据
        app.removeSampleRecord(record.id)
        # 再次获取sample_record, 应该获取不到了
        result = app.getSampleRecordHistory(req=GetSampleRecordRequest(
            id=record.id
        ))
        assert(len(result) == 0)
        # 再次获取明细记录, 应该为0
        req = GetCaseListRequest(
            sampleRecordId=record.id
        )
        result = list(self.context.getCaseApplication(AUDIT_TYPE_HOSPITAL).getCaseList(req))
        assert(len(result) == 0)


import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
import pyrebase
TOKEN = os.getenv('TOKEN')

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

    @commands.Cog.listener()
    async def on_ready(self):
        print("ann cog is online.")

    @commands.command()
    async def ann(self,ctx, channelp, title, desc, footer):
        try:
            channel = self.bot.get_channel(int(channelp))
            embed = discord.Embed(title=title, color=16305198, description=desc)
            embed.set_footer(text=footer)
            await channel.send(embed=embed)
            await ctx.reply(f"Embed sent to <#{channelp}>")
        except Exception as e:
            print(e)

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


class Profile:
    def __init__(self,std,im_size):
        self.mid_pixel = int(im_size/2) # 128/2
        self.x, self.y = self.mid_pixel, self.mid_pixel
        self.im_size = im_size
        self.std = std
        self.noise = False
        self.lam = 0.1133929878

        gkern1d = signal.gaussian(self.im_size, std=std).reshape(self.im_size, 1)
        self.im = np.outer(gkern1d, gkern1d)

        self.im_lrud  = None
        self.im_lr = None
        self.im_ud = None

    def __repr__(self):
        """
        print cluster metadata
        """
        return str(self.im)

    def to_pandas(self):
        """
        convert metadata (as recarray) to pandas DataFrame
        """
        self.meta = pd.DataFrame(self.meta)
        return

    def add_noise(self):
        """
        add Poisson noise to cluster im matrix
        """
        self.noise = np.random.poisson(lam=self.lam, size=self.im.shape)
        self.im += self.noise
        return

    def shift(self):
        """
        shift cluster randomly within bounds of im
        """
        """
        shift cluster randomly within bounds of im
        """
        r = self.std
        mid = self.mid_pixel #center pixel index of 384x384 image
        delta = self.im_size - self.mid_pixel - r - 10

        x = np.random.randint(low=-1*delta,high=delta,size=1)[0]
        y = np.random.randint(low=-1*delta,high=delta,size=1)[0]

        self.x += x
        self.y += y
        im_shift = np.roll(self.im,shift=y,axis=0)
        self.im = np.roll(im_shift,shift=x,axis=1)

        return

    def plot(self,spath='../figs/profile/'):
        """
        plot image
        """
        fig = plt.figure()
        ax = fig.add_subplot(111)
        im = ax.imshow(self.im,interpolation='none',cmap='viridis')

        ticks = np.arange(0,self.size,50)
        plt.xticks(ticks),plt.yticks(ticks)

        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.12)

        plt.colorbar(im, cax=cax)
        # plt.show()
        plt.close()

        return None

    def flip_lr(self):
        im_c = np.zeros((self.im_size,self.im_size))
        im_c[self.x,self.y] = 1

        im_lr = np.fliplr(self.im)
        im_c_lr = np.flipud(im_c)

        self.im_lr = im_lr
        self.x_lr, self.y_lr = [val[0] for val in np.nonzero(im_c_lr)]

        self.im = im_lr
        self.x, self.y = self.x_lr, self.y_lr
        return None

    def flip_ud(self):
        im_c = np.zeros((self.im_size,self.im_size))
        im_c[self.x,self.y] = 1

        im_ud = np.flipud(self.im)
        im_c_ud = np.fliplr(im_c)

        self.im_ud = im_ud
        self.x_ud, self.y_ud = [val[0] for val in np.nonzero(im_c_ud)]

        self.im = im_ud
        self.x, self.y = self.x_ud, self.y_ud
        return None

    def flip_lrud(self):
        im_c = np.zeros((self.im_size,self.im_size))
        im_c[self.x,self.y] = 1

        im_lrud = np.fliplr(np.flipud(self.im))
        im_c_lrud = np.flipud(np.fliplr(im_c))

        self.im_lrud = im_lrud
        self.x_lrud, self.y_lrud = [val[0] for val in np.nonzero(im_c_lrud)]

        self.im = im_lrud
        self.x, self.y = self.x_lrud, self.y_lrud
        return None


from asyncio import exceptions
from scripts.helpful_scripts import get_account, encode_data, upgrade
from brownie import (
    Box,
    ProxyAdmin,
    TransparentUpgradeableProxy,
    Contract,
    exceptions,
    BoxV2,
)
import pytest

##this script tests the upgrading of the box contract both locally and on testnets

def test_upgrade():
    ##arrange
    account = get_account()
    box = Box.deploy({"from": account})
    admin = ProxyAdmin.deploy({"from": account})
    initializer = box.initializer, 1
    encoded_box = encode_data(initializer)
    ##act
    proxyy = TransparentUpgradeableProxy.deploy(
        box, admin, encoded_box, {"from": account}
    )
    proxy_box = Contract.from_abi("Box", proxyy.address, box.abi)
    proxy_box.setNumber(456, {"from": account})
    ##assert
    assert proxy_box.retrieve() == 456
    with pytest.raises(AttributeError):
        proxy_box.increment({"from": account})
    ##act2- upgrading to BoxV2
    boxV2 = BoxV2.deploy({"from": account})
    upgrade(account, proxyy, boxV2, admin, encoded_box)
    proxy_boxV2 = Contract.from_abi("Box", proxyy.address, boxV2.abi)
    proxy_boxV2.increment({"from": account})
    ##assert2
    assert proxy_boxV2.retrieve() == 457


import os

import jieba
import jieba.posseg as pseg
from util import sopen, uutf8, rstr

class Jieba(object):
    def __init__(self, default_path, HMM=False):
        self.pseg = pseg
        self.HMM = HMM
        jieba.load_userdict(os.path.join(
            default_path, "segmenter_dicts/default.dict"))

        self.swords = set()
        for line in sopen(os.path.join(default_path, "segmenter_dicts/stopwords")):
            self.swords.add(line.strip())

    def segment(self, text):
        if not text:
            return []
        words = self.pseg.cut(uutf8(text, from_enc='utf8'), HMM=self.HMM)
        return [rstr(w) for w, f in words if rstr(w) not in self.swords]


# %%
with open('input.txt', 'r') as f:
    data = f.read()

data =  data.split('\n')
# %%
data
# %%
draws = data[0].split(',')
# %%
draws
# %%
def clean_board(board_data) -> list:
    board = []
    for row in board_data:
        row = [number for number in row if number != '']
        board.append(row)

    return board
# %%
class BingoBoard:

    def __init__(self, board_data) -> None:
        cleaned_board = clean_board(board_data)
        self.number_board = cleaned_board
        self.reset_board()

    def check_row(self, row_index) -> bool:
        row = self.board[row_index]
        if row.count(True) == len(row):
            return True
        return False

    def check_column(self, column_index) -> bool:
        column = [row[column_index] for row in self.board]
        if column.count(True) == len(column):
            return True
        return False

    def bingo(self) -> bool:
        for row_index in range(len(self.board)):
            if self.check_row(row_index):
                return True
        for col_index in range(len(self.board[0])):
            if self.check_column(col_index):
                return True

        return False

    def mark_number(self, number) -> None:
        for row_index in range(len(self.number_board)):
            row = self.number_board[row_index]
            if number in row:
                self.board[row_index][row.index(number)] = True

    def reset_board(self) -> None:
        self.board = [[False for _ in row] for row in self.number_board]

# %%
bingo_boards = []

board_data = []
for row in data[2:]:
    if row == '':
        bingo_boards.append(BingoBoard(board_data))
        board_data = []
    else:
        board_data.append(row.split(' '))

# %%
bingo_boards[0].number_board
# %%
bingo_boards[0].board
# %%
winner_found = False
winner_board = None

for board in bingo_boards:
    board.reset_board()

for i, draw in enumerate(draws):
    print(i)
    for bingo_board in bingo_boards:
        bingo_board.mark_number(draw)
        if bingo_board.bingo():
            print(bingo_board.number_board)
            print(bingo_board.board)
            print(draw)
            winner_found = True
            winner_board = bingo_board
            break
    if winner_found:
        break
# %%
def calc_unmarked_sum(board):
    unmarked_sum = 0

    for i, row in enumerate(board.board):
        for j, number in enumerate(row):
            if not number:
                unmarked_sum += int(board.number_board[i][j])

    return unmarked_sum

# %%
int(draw) * calc_unmarked_sum(winner_board)
# %%
winner_count = 0
last_winner = None

for board in bingo_boards:
    board.reset_board()

for i, draw in enumerate(draws):
    print(i, draw)
    for bingo_board in bingo_boards:
        if bingo_board.bingo():
            continue
        bingo_board.mark_number(draw)
        if bingo_board.bingo():
            winner_count += 1
            if winner_count == len(bingo_boards):
                last_winner = bingo_board
                break
    if last_winner:
        break
# %%
last_winner.board

# %%
last_winner.number_board

# %%
int(draw) * calc_unmarked_sum(last_winner)
# %%


#!/usr/bin/env python3

import os

def main():
    '''Demonstrate the ability to perform file management operations in Python:'''

    # Open an existing file
    f = open("Python/sample.txt")
    # Read data from a file
    contents = f.read()
    print(contents)
    # Parse data from a file
    f.readlines()
    f.close()
    # Write data to a file
    f = open("Python/sample.txt", "w")
    f.write("new stuff")
    # Modify data in a file
    with open("Python/sample.txt", "a+") as f:
        f.seek(3)
        f.write("aha!")
        cont = f.read()
        print(cont)

    # Close an open file
    f.close()
    # Print file information to the console
    print(os.stat("Python/sample.txt"))
    # Create a new file
    n = open("Python/newfile.txt", "w+")
    n.close()
    # Append data to an existing file
    f = open("Python/sample.txt", "a+")
    f.write("added to end of file")
    contents = f.read()
    print(contents)
    # Delete a file
    os.remove("Python/newfile.txt")
    # Determine the size of a file
    print("size:", os.path.getsize("Python/sample.txt"))
    # Determine location within a file
    print("location:", f.tell())
    f.close()
    # Insert data into an existing file
    with open("Python/sample.txt", "r") as f:
        contents = f.readlines()
        contents.insert(2, "inserted text")

    with open("Python/sample.txt", "w") as f:
        contents = "".join(contents)
        f.write(contents)

    # look at the rest of the code

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals

from snapshottest import Snapshot

snapshots = Snapshot()

snapshots["test_schema_creator 1"] = [
    """ name: string .
""",
    """ is_person: bool .
""",
    """ estate: string .
""",
    """ is_lawsuit: bool .
""",
    """ is_lawyer: bool .
""",
    """ is_judge: bool .
""",
    """ number: string .
""",
    """ is_disctrict: bool .
""",
    """ last_name: string .
""",
    """ is_courtsection: bool .
""",
    """ is_kind: bool .
""",
]


"""
Write a function converting a Roman numeral from a given string N into an Arabic numeral.
Values may range from 1 to 100 and may contain invalid symbols.
Invalid symbols and numerals out of range should raise ValueError.

Numeral / Value:
I: 1
V: 5
X: 10
L: 50
C: 100

Example:
N = 'I'; result = 1
N = 'XIV'; result = 14
N = 'LXIV'; result = 64

Example of how the task should be called:
python3 task_3_ex_2.py LXIV

Note: use `argparse` module to parse passed CLI arguments
"""
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('n')
args = 0

def from_roman_numerals(args):
    d = {'IV': '4 ', 'IX': '9 ', 'XL': '40 ', 'XC': '90 '}
    d2 = {'I': '1 ', 'V': '5 ', 'X': '10 ', 'L': '50 ', 'C': '100 '}
    for i in args:
        if i not in d2:
            raise ValueError
    for i in d.keys():
        if i in args:
            args = args.replace(i, d[i])
    for i in d2.keys():
        if i in args:
            args = args.replace(i, d2[i])
    result = sum(map(int, args.split()))
    return result if result <= 100 else ValueError

def main():
    global args
    args = parser.parse_args()
    print(from_roman_numerals(args.n))

if __name__ == "__main__":
    main()


import csv
import sys

import numpy

reader = csv.reader(sys.stdin)

alders = numpy.array(next(reader)[3:])

votes = numpy.array(list(reader))
votes = votes[:, 3:]

no_votes = -((votes == 'no').astype(int))
yes_votes = (votes == 'yes').astype(int)

votes = no_votes + yes_votes

u, s, vh = numpy.linalg.svd(votes.T)

dim_1 = numpy.argsort(u[:, 0])
dim_2 = numpy.argsort(-u[:, 1])

oppose_together = numpy.dot(no_votes.T, no_votes)

oppose_together = oppose_together[dim_2, :][:, dim_2]

writer = csv.writer(sys.stdout)

writer.writerow([''] + list(alders[dim_2]))
for alder, row in zip(alders[dim_2], oppose_together):
     writer.writerow([alder] + list(row.astype(str)))


import logging

from rq import Worker, Connection

from conn import r

listen = ["default"]

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d  - %(message)s')
    with Connection(r):
        logging.debug(listen)
        worker = Worker(listen)
        worker.work()


import argparse
import dataloader
from model import IEMSAModel
import torch
import torch.nn as nn
import torch.optim as optim
import datetime
from tensorboardX import SummaryWriter
from recorder import Recorder

def epoch(epoch_idx, is_train):
    model.train() if is_train else model.eval()
    loader = train_loader if is_train else val_loader
    recorder.epoch_start(epoch_idx, is_train, loader)
    for batch_idx, batch in enumerate(loader):
        batch_size = batch['response'].size()[0]
        batch = {key: val.to(device) for key, val in batch.items()}
        optimizer.zero_grad()
        output = model(batch)
        loss = criterion(output[1], batch['response'][:, 1:])
        for logit, batch_key in zip(output[0], ['post_2', 'post_3', 'post_4']):
            loss += criterion(logit, batch[batch_key][:, 1:])
        if is_train:
            loss.backward()
            optimizer.step()
        recorder.batch_end(batch_idx, batch_size, loss.item())
    recorder.log_text(output, batch)
    recorder.epoch_end()

def train():
    for epoch_idx in range(1, args.epochs + 1):
        epoch(epoch_idx, is_train=True)
        epoch(epoch_idx, is_train=False)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='parser')
    parser.add_argument('--project', type=str, default='iemsa')
    parser.add_argument('--timestamp', type=str, default=datetime.datetime.now().strftime("%y%m%d%H%M%S"))
    parser.add_argument('--data_dir', type=str, default='data')
    parser.add_argument('--log_dir', type=str, default='log')
    parser.add_argument('--batch_size', type=int, default=128)
    parser.add_argument('--epochs', type=int, default=100)
    parser.add_argument('--lr', type=float, default=1e-4)
    parser.add_argument('--log_interval', type=int, default=100)
    parser.add_argument('--glove_path', type=str, default='data/glove.6B.200d.txt')
    parser.add_argument('--d_embed', type=int, default=200)
    parser.add_argument('--d_hidden', type=int, default=256)
    parser.add_argument('--d_context', type=int, default=256) # msa context vector
    parser.add_argument('--n_word_vocab', type=int, default=10000)
    parser.add_argument('--n_rel_vocab', type=int, default=45)
    parser.add_argument('--n_layer', type=int, default=2)
    parser.add_argument('--max_decode_len', type=int, default=10)
    parser.add_argument('--seed', type=int, default=42)
    parser.add_argument('--num_workers', type=int, default=4)
    parser.add_argument('--no_cuda', action='store_true')
    args = parser.parse_args()

    device = torch.device("cuda:0" if not args.no_cuda and torch.cuda.is_available() else "cpu")
    torch.manual_seed(args.seed)
    train_loader = dataloader.get_dataloader(args.data_dir, 'train', args.batch_size, args.num_workers)
    val_loader = dataloader.get_dataloader(args.data_dir, 'val', args.batch_size, args.num_workers)
    model = IEMSAModel(args, train_loader.dataset.idx2word)
    model = model.to(device)
    optimizer = optim.Adam(model.parameters(), args.lr)
    criterion = nn.CrossEntropyLoss(ignore_index=0)
    writer = SummaryWriter(f'{args.log_dir}/{args.project}_{args.timestamp}')
    recorder = Recorder(args, writer, train_loader.dataset.idx2word)

    train()


## 计数排序
## 空间换时间
## 稳定排序，外排序，时间复杂度O(n + k)，但是对于数据范围很大的数组，需要大量时间和内存。

def counting_sort(nums):
    if not nums:
        return nums
    n = len(nums)
    _min, _max = min(nums), max(nums)
    tmp_nums = [0]*(_max - _min + 1)
    # fill the extra space with frequency of elements
    for num in nums:
        tmp_nums[num - _min] += 1

    j = 0
    for i in range(n):
        while tmp_nums[j] == 0:
            j += 1
        nums[i] = j + _min
        tmp_nums[j] -= 1
    return nums


import json

def read(file):
    with open(file) as file:
        data = json.load(file)
        city = data["city"]
        bots = data["bots"]
        population = data["population"]

        print(f"\nCity Name: {city}")
        print(f"\nPopulation Size: {population}")
        for bot in bots:
            bot_name = bot["name"]
            bots_stats = bot["stats"]
            bots_stats_speed = bots_stats["speed"]
            bots_stats_strength = bots_stats["strength"]
            print(f"\nBot Name: {bot_name}\nSpeed: {bots_stats_speed}\nStrength: {bots_stats_strength}")

def run():
    read("robocity.json")

if __name__ == "__main__":
    run()


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

import numpy as np
import tensorflow as tf
from tensorflow.python.ops import array_ops
from tensorflow.contrib.rnn.python.ops import core_rnn_cell
from tensorflow.python.util import nest
from tensorflow.python.ops import variable_scope as vs
from sklearn.base import BaseEstimator, ClassifierMixin
import time
from type import DiversityQuery

def select_by_index(value, index, zero_base=True):
    select_dim = tf.shape(value)[1]
    mask = tf.equal(tf.range(select_dim), tf.expand_dims(index, axis=-1) - (0 if zero_base else 1))
    return tf.boolean_mask(value, mask)

def tensormul(tensor, arrs):
    dims = [d.value for d in tensor.get_shape()]
    batch = tf.shape(arrs[0])[0]
    ultimate = [batch] + dims
    tensor = tf.reshape(tf.tile(tensor, [batch] + [1] * (len(dims) - 1)), ultimate)
    arrs = [tf.reshape(tf.tile(tf.reshape(arrs[i], [batch, dims[i], 1]),
                               [1, int(np.product(dims[:i])), int(np.product(dims[i+1:]))]),
                       ultimate) for i in range(len(arrs))]
    for arr in arrs:
        tensor *= arr
    return tf.reduce_sum(tensor, list(range(1, len(ultimate))))

def interaction_op(emb1, emb2, var_name, op='general', attn=False):
    s1 = emb1.get_shape()[1].value
    s2 = emb2.get_shape()[1].value
    if op == 'general':
        variable = vs.get_variable(var_name, [s1, s2])
        return tensormul(variable, [emb1, emb2])
    elif op == 'dot':
        return tf.reduce_sum(emb1 * emb2, reduction_indices=1) * (-1 if attn else 1)

class RNNCellBase(core_rnn_cell.RNNCell):
    def zero_state_np(self, batch_size, dtype):
        states = np.zeros((batch_size, self.state_size), dtype=dtype)
        return states

class DSSACell(RNNCellBase):
    '''
    DSSA cell: combination of traditional RNN and pooling
    '''
    VALID_OP = {'general', 'dot'}
    VALID_POOL = {'max', 'min'}

    def __init__(self, cell, n_doc_emb, n_rel_feat, n_query_emb, most_n_subquery,
                 lambdaa=0.5, op='general', pool='max', state_is_tuple=False):
        if not isinstance(cell, core_rnn_cell.RNNCell):
            raise TypeError('cell should be instance of RNNCell')
        if op not in DSSACell.VALID_OP:
            raise ValueError('op not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSACell.VALID_OP))))
        if pool not in DSSACell.VALID_POOL:
            raise ValueError('pool not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSACell.VALID_POOL))))
        if nest.is_sequence(cell.state_size) != state_is_tuple:
            raise ValueError('base cell state_is_tuple is not consistent with the current. '
                             'base state size is: {}'.format(cell.state_size))
        self.cell = cell
        self.n_doc_emb = n_doc_emb
        self.n_rel_feat = n_rel_feat
        self.n_query_emb = n_query_emb
        self.most_n_subquery = most_n_subquery
        self.lambdaa = lambdaa
        self.op = op
        self.pool = pool
        self.state_is_tuple = state_is_tuple

    @property
    def state_size(self):
        ss = (self.cell.state_size, self.most_n_subquery, self.most_n_subquery)
        if self.state_is_tuple:
            return ss
        return sum(ss)

    @property
    def output_size(self):
        return 1

    def __call__(self, inputs, state, scope=None):
        with vs.variable_scope(scope or type(self).__name__):
            with vs.variable_scope('Transformation'):
                batch_size = tf.shape(inputs)[0]
                input_dim = tf.shape(inputs)[1]
                # the samples in the same batch must have same number of subtopics
                to_attn_len = tf.to_int32(tf.reduce_max(array_ops.slice(inputs, [0, input_dim - 1], [-1, -1]))) - 1
                to_attn_len = tf.maximum(to_attn_len, 0) # avoid bug for paddings
                query_rel = array_ops.slice(inputs, [0, 0], [-1, self.n_rel_feat])
                subquery_rel = tf.reshape(array_ops.slice(inputs, [0, self.n_rel_feat],
                                                          [-1, self.n_rel_feat * to_attn_len]),
                                          [batch_size, to_attn_len, self.n_rel_feat])
                doc_emb = array_ops.slice(inputs, [0, self.n_rel_feat * self.most_n_subquery], [-1, self.n_doc_emb])
                query_emb = array_ops.slice(inputs,
                                            [0, self.n_rel_feat * self.most_n_subquery + self.n_doc_emb],
                                            [-1, self.n_query_emb])
                to_attn = tf.reshape(array_ops.slice(
                    inputs,
                    [0, self.n_rel_feat * self.most_n_subquery + self.n_doc_emb + self.n_query_emb + 1],
                    [-1, (self.n_query_emb + 1) * to_attn_len]), [batch_size, to_attn_len, self.n_query_emb + 1])
                initial_weight = to_attn[:, :, self.n_query_emb]
                subquery_emb = to_attn[:, :, :self.n_query_emb]
                last_state = state[:, :self.cell.state_size]
                last_attn_rnn = array_ops.slice(state, [0, self.cell.state_size], [-1, to_attn_len])
                last_attn_pool = array_ops.slice(state,
                                                 [0, self.cell.state_size + self.most_n_subquery],
                                                 [-1, to_attn_len])
                last_attn = last_attn_rnn + last_attn_pool
                last_attn = tf.nn.softmax(last_attn + tf.log(initial_weight))
            with vs.variable_scope('DocumentSequenceRepresentation'):
                cur_output, cur_state = self.cell(doc_emb, last_state)
            with vs.variable_scope('Scoring'):
                lambda_factor = vs.get_variable('Lambda', [1],
                                                initializer=tf.constant_initializer(self.lambdaa, dtype=tf.float32),
                                                trainable=False)
                # diversity score
                div_score = tf.zeros([batch_size])
                relw = vs.get_variable('RelW', [self.n_rel_feat, 1])
                sub_rel = tf.reduce_sum(subquery_rel * tf.reshape(relw, [self.n_rel_feat]), reduction_indices=2)
                div_score += tf.reduce_sum(sub_rel * last_attn, reduction_indices=1)
                div_score += interaction_op(doc_emb,
                                            tf.reduce_sum(tf.expand_dims(last_attn, -1) * subquery_emb,
                                                          reduction_indices=1),
                                            'OutW', op=self.op)
                # relevance score
                rel_score = tf.zeros([batch_size])
                rel_score += tf.reshape(tf.matmul(query_rel, relw), [batch_size])
                vs.get_variable_scope().reuse_variables()
                rel_score += interaction_op(doc_emb, query_emb, 'OutW', op=self.op)
                score = lambda_factor * div_score + (1.0 - lambda_factor) * rel_score
            with vs.variable_scope('SubtopicAttention'):
                # rnn attention part
                attn_rnn = tf.reshape(interaction_op(
                    tf.reshape(tf.tile(cur_output, [1, to_attn_len]), [-1, self.cell.output_size]),
                    tf.reshape(subquery_emb, [-1, self.n_query_emb]), 'AttnW', op=self.op, attn=True),
                    [batch_size, to_attn_len])
                # pooling attention part
                attn_relw = vs.get_variable('AttnRelW', [self.n_rel_feat, 1])
                attn_sub_rel = tf.reduce_sum(subquery_rel * tf.reshape(attn_relw, [self.n_rel_feat]),
                                             reduction_indices=2)
                if self.pool == 'max':
                    attn_pool = tf.reduce_max(tf.stack([attn_sub_rel, last_attn_pool], axis=2),
                                              reduction_indices=2)
                elif self.pool == 'min':
                    attn_pool = tf.reduce_min(tf.stack([attn_sub_rel, last_attn_pool], axis=2),
                                              reduction_indices=2)
            score = tf.reshape(score, [batch_size, 1])
            next_state = (cur_state,
                          tf.concat([attn_rnn,
                                     tf.zeros((batch_size, self.most_n_subquery - to_attn_len))], axis=1),
                          tf.concat([attn_pool,
                                     tf.zeros((batch_size, self.most_n_subquery - to_attn_len))], axis=1))
            if self.state_is_tuple:
                return score, next_state
            return score, tf.concat(list(next_state), axis=1)

    def zero_state_np(self, batch_size, dtype):
        if self.pool == 'max':
            v = np.finfo(np.float32).min
        elif self.pool == 'min':
            v = np.finfo(np.float32).max
        if self.state_is_tuple:
            state_base = tuple(np.zeros([batch_size, d]) for d in self.cell.state_size)
        else:
            state_base = np.zeros([batch_size, self.cell.state_size])
        state_rnn = np.zeros((batch_size, self.most_n_subquery), dtype=dtype)
        state_pool = np.ones((batch_size, self.most_n_subquery), dtype=dtype) * v
        if self.state_is_tuple:
            return (state_base, state_rnn, state_pool)
        return np.concatenate([state_base, state_rnn, state_pool], axis=1)

    def zero_state(self, batch_size, dtype):
        if self.pool == 'max':
            v = tf.float32.min
        elif self.pool == 'min':
            v = tf.float32.max
        state_base = self.cell.zero_state(batch_size, dtype)
        state_rnn = array_ops.zeros([batch_size, self.most_n_subquery], dtype=dtype)
        state_pool = tf.fill([batch_size, self.most_n_subquery], v)
        if self.state_is_tuple:
            return (state_base, state_rnn, state_pool)
        return tf.concat([state_base, state_rnn, state_pool], axis=1)

class DSSA(BaseEstimator, ClassifierMixin):
    '''
    DSSA model
    '''
    VALID_INTERACTION = {'general', 'dot'}
    VALID_CELL_TYPE = {'vanilla', 'LSTM', 'GRU'}
    VALID_OPTIMIZATION = {'listpair'}

    def __init__(self,
                 n_rel_feat=10,
                 n_doc_emb=10,
                 n_query_emb=10,
                 hidden_size=10,
                 interaction='general',
                 cell_type='vanilla',
                 lambdaa=0.5,
                 most_n_subquery=10,
                 most_n_pair=10,
                 most_n_doc=10,
                 doc_emb=np.ones((10, 110)),
                 query_emb=np.ones((10, 11)),
                 learning_rate=.1,
                 n_epochs=10,
                 batch_size=10,
                 optimization='listpair',
                 save_epochs=None,
                 verbose=True,
                 random_seed=0,
                 reuse_model=None,
                 save_model=None):
        self.n_rel_feat = n_rel_feat
        self.n_doc_emb = n_doc_emb
        self.n_query_emb = n_query_emb
        self.hidden_size = hidden_size
        self.interaction = interaction
        self.cell_type = cell_type
        self.lambdaa = lambdaa
        self.most_n_subquery = most_n_subquery
        self.most_n_pair = most_n_pair
        self.most_n_doc = most_n_doc
        self.doc_emb = doc_emb
        self.query_emb = query_emb
        self.learning_rate = learning_rate
        self.n_epochs = n_epochs
        self.batch_size = batch_size
        self.optimization = optimization
        self.save_epochs = save_epochs
        self.verbose = verbose
        self.random_seed = random_seed
        self.reuse_model = reuse_model
        self.save_model = save_model

    def check_params(self):
        if self.interaction not in DSSA.VALID_INTERACTION:
            raise ValueError('interaction not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSA.VALID_INTERACTION))))
        if self.cell_type not in DSSA.VALID_CELL_TYPE:
            raise ValueError('cell_type not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSA.VALID_CELL_TYPE))))
        if not isinstance(self.doc_emb, np.ndarray) or not isinstance(self.query_emb, np.ndarray):
            raise ValueError('both doc_emb and query_emb should by instance of numpy.ndarray')
        self.doc_emb_actual_size = self.n_rel_feat * self.most_n_subquery + self.n_doc_emb
        if self.doc_emb.shape[1] != self.doc_emb_actual_size:
            raise ValueError('doc_emb shape[1] is unexpected. {} is desired while we got {}'
                             .format(self.doc_emb_actual_size, self.doc_emb.shape[1]))
        self.query_emb_actual_size = self.n_query_emb + 1
        if self.query_emb.shape[1] != self.query_emb_actual_size:
            raise ValueError('query_emb shape[1] is unexpected. {} is desired while we got {}'
                             .format(self.query_emb_actual_size, self.query_emb.shape[1]))
        if self.optimization not in DSSA.VALID_OPTIMIZATION:
            raise ValueError('optimization not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSA.VALID_OPTIMIZATION))))
        self.input_dim = 1 + self.most_n_subquery
        self.expand_input_dim = \
            self.n_rel_feat * self.most_n_subquery + self.n_doc_emb + (self.n_query_emb + 1) * self.most_n_subquery
        if self.reuse_model and not hasattr(self, 'session_'): # read model from file
            self.graph_ = tf.Graph()
            with self.graph_.as_default():
                tf.set_random_seed(self.random_seed)
                with vs.variable_scope('DSSA', initializer=
                tf.uniform_unit_scaling_initializer(seed=self.random_seed)) as scope:
                    self.build_graph()
                    scope.reuse_variables()
                    self.build_graph_test()
            self.session_ = tf.Session(graph=self.graph_)
            print('load model from "{}"'.format(self.reuse_model))
            self.saver.restore(self.session_, self.reuse_model)

    @staticmethod
    def get_cell(cell_type, hidden_size):
        if cell_type == 'vanilla':
            return core_rnn_cell.BasicRNNCell(num_units=hidden_size)
        elif cell_type == 'GRU':
            return core_rnn_cell.GRUCell(num_units=hidden_size)
        elif cell_type == 'LSTM':
            return core_rnn_cell.LSTMCell(num_units=hidden_size, state_is_tuple=False)

    @property
    def weights(self):
        if not hasattr(self, 'session_'):
            raise AttributeError('need fit or fit_iterable to be called before getting weights')
        return [(v.name, v.eval(self.session_))
                for v in self.graph_.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='DSSA')]

    def batcher(self, X, y=None):
        for q in X:
            n_sample = q['train_x'].shape[0]
            if n_sample <= 0:
                continue
            for i in range(0, n_sample, self.batch_size):
                yield q['train_x'][i:i + self.batch_size], None

    def batch_to_feeddict(self, X, y):
        if self.optimization == 'listpair':
            return self.batch_to_feeddict_listpair(X, y)

    def batch_to_feeddict_listpair(self, X, y):
        batch_num = X.shape[0]
        actual_dim = self.most_n_doc * (self.input_dim + 1) + \
                     self.most_n_pair * (2 * (self.input_dim + 1) + 1 + 1) + \
                     1 + 1
        if X.shape[1] != actual_dim:
            raise ValueError('input X\'s dimension is unexpected. '
                             '{} is desired while we got {}'.format(actual_dim, X.shape[1]))
        # assemble feed_dict
        feed_dict = {}
        feed_dict[self.context_input] = \
            X[:, :self.most_n_doc * (self.input_dim + 1)].reshape(batch_num, self.most_n_doc, self.input_dim + 1)
        feed_dict[self.context_input_len] = X[:, -2]
        feed_dict[self.pair_input_len] = X[:, -1]
        pair = X[:, self.most_n_doc * (self.input_dim + 1):-2].reshape(batch_num, self.most_n_pair, -1)
        feed_dict[self.pair_input] = pair[:, :, :-2].reshape(batch_num, self.most_n_pair, 2, self.input_dim + 1)
        feed_dict[self.pair_target] = pair[:, :, -2].astype(np.int32)
        feed_dict[self.pair_weight] = pair[:, :, -1]
        return feed_dict

    def build_graph_test(self):
        if not hasattr(self, 'cell'):
            raise AttributeError('need build train graph before build test graph')
        with vs.variable_scope('TestInput'):
            self.test_input = tf.placeholder(tf.float32, shape=[None, None, self.input_dim + 1], name='test_input')
            self.test_input_len = tf.placeholder(tf.int32, shape=[None], name='test_input_len')
            self.test_initial_state = tf.placeholder(tf.float32,
                                                     shape=[None, self.cell.state_size],
                                                     name='test_initial_state')
            dim = tf.shape(self.test_input)
            batch_num = dim[0]
            doc_num = dim[1]
        with vs.variable_scope('EmbeddingLookup'):
            tid = tf.nn.embedding_lookup(self.doc_emb_W,
                                         tf.to_int32(self.test_input[:, :, :1]))
            tiq = tf.nn.embedding_lookup(self.query_emb_W,
                                         tf.to_int32(self.test_input[:, :, 1:1 + self.most_n_subquery]))
            test_input_expand = tf.concat([tf.reshape(tid, [batch_num, doc_num, -1]),
                                           tf.reshape(tiq, [batch_num, doc_num, -1]),
                                           self.test_input[:, :, self.input_dim:]], axis=2)
            test_input_expand.set_shape([None, None, self.expand_input_dim + 1])
        with vs.variable_scope('DSSA-RNNMP'):
            outputs, self.states = tf.nn.dynamic_rnn(
                initial_state=self.test_initial_state,
                cell=self.cell,
                dtype=tf.float32,
                sequence_length=self.test_input_len,
                inputs=test_input_expand)
            self.outputs_test = tf.reshape(select_by_index(outputs, self.test_input_len, zero_base=False),
                                           [batch_num])

    def build_graph(self):
        if self.optimization == 'listpair':
            self.build_graph_listpair()

    def build_graph_listpair(self):
        with vs.variable_scope('TrainInput'):
            self.context_input = tf.placeholder(tf.float32, shape=[None, self.most_n_doc, self.input_dim + 1],
                                                name='context_input')
            self.context_input_len = tf.placeholder(tf.int32, shape=[None], name='context_input_len')
            self.pair_input = tf.placeholder(tf.float32, shape=[None, self.most_n_pair, 2, self.input_dim + 1],
                                             name='pair_input_raw')
            self.pair_weight = tf.placeholder(tf.float32, shape=[None, self.most_n_pair], name='pair_weight_raw')
            self.pair_target = tf.placeholder(tf.int32, shape=[None, self.most_n_pair], name='pair_target_raw')
            self.pair_input_len = tf.placeholder(tf.int32, shape=[None], name='pair_input_len')
        with vs.variable_scope('TrainInputShape'):
            batch_num = tf.shape(self.context_input)[0]
        with vs.variable_scope('EmbeddingLookup'):
            self.doc_emb_W = tf.get_variable('doc_emb_W',self.doc_emb.shape,
                                             initializer=tf.constant_initializer(self.doc_emb),
                                             trainable=False)
            #self.doc_emb_W = tf.constant(self.doc_emb, dtype=tf.float32, name='doc_emb_W')
            self.query_emb_W = tf.get_variable('query_emb_W',self.query_emb.shape,
                                               initializer=tf.constant_initializer(self.query_emb),
                                               trainable=False)
            #self.query_emb_W = tf.constant(self.query_emb, dtype=tf.float32, name='query_emb_W')
            # look up context_input doc & query embedding
            cid = tf.nn.embedding_lookup(self.doc_emb_W,
                                         tf.to_int32(self.context_input[:, :, :1]))
            ciq = tf.nn.embedding_lookup(self.query_emb_W,
                                         tf.to_int32(self.context_input[:, :, 1:1 + self.most_n_subquery]))
            context_input_expand = tf.concat([tf.reshape(cid, [batch_num, self.most_n_doc, -1]),
                                              tf.reshape(ciq, [batch_num, self.most_n_doc, -1]),
                                              self.context_input[:, :, self.input_dim:]], axis=2)
            context_input_expand.set_shape([None, self.most_n_doc, self.expand_input_dim + 1])
            # look up pair_input doc & query embedding
            pid = tf.nn.embedding_lookup(self.doc_emb_W,
                                         tf.to_int32(self.pair_input[:, :, :, :1]))
            piq = tf.nn.embedding_lookup(self.query_emb_W,
                                         tf.to_int32(self.pair_input[:, :, :, 1:1 + self.most_n_subquery]))
            pair_input_expand = tf.concat([tf.reshape(pid, [batch_num, self.most_n_pair, 2, -1]),
                                           tf.reshape(piq, [batch_num, self.most_n_pair, 2, -1]),
                                           self.pair_input[:, :, :, self.input_dim:]], axis=3)
            pair_input_expand.set_shape([None, self.most_n_pair, 2, self.expand_input_dim + 1])
        with vs.variable_scope('DSSA-RNNMP'):
            cell = DSSA.get_cell(self.cell_type, self.hidden_size)
            self.cell = DSSACell(cell=cell, n_doc_emb=self.n_doc_emb, n_rel_feat=self.n_rel_feat,
                                 n_query_emb=self.n_query_emb, most_n_subquery=self.most_n_subquery,
                                 lambdaa=self.lambdaa, op=self.interaction, pool='max', state_is_tuple=False)
            outputs, context_states = tf.nn.dynamic_rnn(
                cell=self.cell,
                dtype=tf.float32,
                sequence_length=self.context_input_len,
                inputs=context_input_expand
            )
            with vs.variable_scope('ContextPairTransformation'):
                context_states = tf.reshape(tf.tile(context_states, [1, self.most_n_pair * 2]),
                                            [batch_num, self.most_n_pair, 2, self.cell.state_size])
                pair_mask = tf.range(self.most_n_pair) < tf.expand_dims(self.pair_input_len, -1)
                pair_weight_selected = tf.boolean_mask(self.pair_weight, pair_mask, name='pair_weight_select')
                pair_target_selected = tf.boolean_mask(self.pair_target, pair_mask, name='pair_target_select')
                pair_input_selected = tf.boolean_mask(pair_input_expand, pair_mask, name='pair_input_select')
                self.pair_input_selected = tf.reshape(pair_input_selected, [-1, 1, self.expand_input_dim + 1])
                context_states_selected = tf.boolean_mask(context_states, pair_mask, name='pair_states_select')
                self.context_states_selected = tf.reshape(context_states_selected, [-1, self.cell.state_size])
                actual_batch_num = tf.shape(pair_weight_selected)[0]
            vs.get_variable_scope().reuse_variables()
            outputs, second_states = tf.nn.dynamic_rnn(
                initial_state=self.context_states_selected,
                cell=self.cell,
                dtype=tf.float32,
                sequence_length=tf.fill([actual_batch_num * 2], 1),
                inputs=self.pair_input_selected
            )
        with vs.variable_scope('Loss'):
            self.outputs = tf.reshape(outputs, [actual_batch_num, 2])
            self.prob = tf.nn.softmax(self.outputs, name='pair_prob')
            target = tf.reshape(select_by_index(self.prob, pair_target_selected, zero_base=True),
                                [actual_batch_num])
            self.accuracy = tf.reduce_sum(tf.cast(target > 0.5, tf.float32)) /\
                            tf.cast(tf.reduce_prod(tf.shape(target)), tf.float32)
            self.log_loss = -tf.reduce_sum(pair_weight_selected * tf.log(target), name='log_loss')
            self.trainer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.log_loss)
        self.init_all_vars = tf.global_variables_initializer()
        self.saver = tf.train.Saver()

    def fit_iterable(self, X, y=None):
        # check params
        self.check_params()
        # init graph and session
        if not hasattr(self, 'session_'):
            self.graph_ = tf.Graph()
            with self.graph_.as_default():
                tf.set_random_seed(self.random_seed)
                with vs.variable_scope('DSSA', initializer=
                tf.uniform_unit_scaling_initializer(seed=self.random_seed)) as scope:
                    self.build_graph()
                    scope.reuse_variables()
                    self.build_graph_test()
            self.session_ = tf.Session(graph=self.graph_)
            self.session_.run(self.init_all_vars)
        # iteration
        for epoch in range(self.n_epochs):
            epoch += 1
            start = time.time()
            perm = np.random.permutation(len(X))
            loss_list, accuracy_list = [], []
            for i, (bX, by) in enumerate(self.batcher(X[perm], y[perm] if isinstance(y, np.ndarray) else None)):
                fd = self.batch_to_feeddict(bX, by)
                if self.optimization == 'listpair':
                    log_loss, accuracy, _ = \
                        self.session_.run([self.log_loss, self.accuracy, self.trainer], feed_dict=fd)
                    accuracy_list.append(accuracy)
                    loss_list.append(log_loss)
            if self.verbose: # output epoch stat
                print('{:<10}\t{:>7}:{:>5.3f}:{:>7.3f}'
                      .format('EPO[{}_{:>3.1f}]'.format(epoch, (time.time() - start)/60),
                              'train', np.mean(accuracy_list), np.mean(loss_list)), end='')
            if self.save_epochs and epoch % self.save_epochs == 0: # save the model
                if self.save_model:
                    self.saver.save(self.session_, self.save_model)
                yield
            # save the final model
            elif epoch == self.n_epochs and self.save_epochs and self.n_epochs % self.save_epochs != 0:
                if self.save_model:
                    self.saver.save(self.session_, self.save_model)
                yield
            if self.verbose:
                print('')

    def fit(self, X, y=None):
        list(self.fit_iterable(X, y))
        return self

    def decision_function(self, X):
        self.check_params()
        if not hasattr(self, 'session_'):
            raise AttributeError('need fit or fit_iterable to be called before prediction')
        ranks = []
        for q in X:
            select = []
            raw_data = q['test_x']
            n_doc = raw_data.shape[0]
            for r in range(n_doc):
                remain_ind = [i for i in range(n_doc) if i not in select]
                batch_input = np.array([[raw_data[i]] for i in remain_ind])
                out, states = self.session_.run([self.outputs_test, self.states], feed_dict={
                    self.test_input: batch_input,
                    self.test_input_len: np.ones((len(remain_ind))),
                    self.test_initial_state:
                        np.tile(last_states, [len(remain_ind)]).reshape(len(remain_ind), self.cell.state_size)
                        if r > 0 else self.cell.zero_state_np(len(remain_ind), np.float32)
                })
                next = np.argmax(out)
                select.append(remain_ind[next])
                last_states = states[next]
            ranks.append(select)
        return ranks

    def predict(self, X):
        return self.decision_function(X)

    def score(self, X, y, sample_weight=None):
        ranks = self.predict(X)
        metrics = []
        for i in range(len(X)):
            dq = y[i]
            ndq = DiversityQuery(dq.query, dq.qid, dq.subtopics, dq.docs[ranks[i]])
            metrics.append(ndq.get_metric('alpha_nDCG'))
        return np.mean(metrics)

    def __del__(self):
        if hasattr(self, 'session_'):
            self.session_.close()


# The currencies prices may be outdated

# Prices for exchange
exchange_rates = {
    "euros": {"libras": 0.84, "dolares": 1.18},
    "libras": {"euros": 1.18, "dolares": 1.40},
    "dolares": {"euros": 0.85, "libras": 0.71}
}

# Currencies to work with
currencies = ["euros", "libras", "dolares"]
# Function to trade
def exchange(currency_from, currency_to, amount):
    price = exchange_rates[currency_from.lower()][currency_to.lower()]
    result = price * amount
    return result

# Additional info
print("!Bienvenido¡\n")
print("Los precios pueden estar desactualizados.\n")
print("En cualquier momento, puede escribir 'salir' para detener el programa.\n")

print("[!]" + "-"*100 + "[!]")

while True:
    currency_from = input("Trabajamos con Euros, Libras y Dolares.\n¿Con qué divisa quiere trabajar hoy? ")
    if currency_from.lower() == "salir":
        print("[*] Finalizando... !Hasta luego¡")
        break
    elif currency_from.lower() not in currencies:
        print("Divisa no válida. Inténtalo de nuevo.")
        continue
    print(f"Ha escogido trabajar con {currency_from.capitalize()}")

    amount = None
    while amount is None:
        try:
            amount = float(input(f"Cantidad de {currency_from.lower()}: "))
        except ValueError:
            print("[!] Error... Por favor, introduzca un número.")
            continue

    currency_to = input(f"¿A qué divisa quiere convertir {amount} {currency_from.lower()}? ")
    if currency_to.lower() not in currencies:
        print("Divisa no válida. Inténtalo de nuevo.")
        continue

    result = exchange(currency_from, currency_to, amount)
    print(f"-> {amount} {currency_from} equivale a {result} {currency_to}")


from typing import Optional

import discord
from discord import app_commands

from ns_bot.controllers.base_nationstate_controller import BaseNationstateController
from ns_bot.data.shards import (
    SPECIAL_WORLD_ASSEMBLY_SHARDS,
    VALID_WORLD_ASSEMBLY_SHARDS,
)
from ns_bot.formatting.world_assembly_info import FormatWAInfo

class WorldAssemblyController(BaseNationstateController):
    @classmethod
    async def wa_shards_autocomplete(
        cls, _: discord.Interaction, current: str
    ) -> list[app_commands.Choice[str]]:
        return cls.shard_autocomplete(current, VALID_WORLD_ASSEMBLY_SHARDS)

    async def info(
        self,
        interaction: discord.Interaction,
        council: app_commands.Choice[int],
        shard: Optional[str] = None,
    ):
        shards = [shard] if shard else None
        if shard.lower() in SPECIAL_WORLD_ASSEMBLY_SHARDS:
            shards.append("resolution")
        data = await self.bot.nationstates_api.get_wa_data(council.value, shards=shards)
        await FormatWAInfo.format(council.name, shard, data, interaction)


import numpy as np
import tensorflow as tf

def idcnn_layer(layer_inputs, block_cnt=2, layer_per_block=5, name="idcnn_layer"):
    '''
    @param layer_inputs: [batch_size, seq_length, emb_size]
    @param block_cnt: 有几个block堆叠而成.
    @param layer_per_block: 每个block里面有几个layer.
    @return: [batch_size, seq_length, emb_size]
    '''
    _inputs = tf.expand_dims(layer_inputs, 1)
    channels = _inputs.shape[-1]
    with tf.variable_scope(name):
        for block_id in range(block_cnt):
            for layer_id in range(layer_per_block):
                with tf.variable_scope("conv_layer-{}".format(layer_id),
                                       reuse=True if block_id > 0 else False):
                    filter_weights = tf.get_variable("w_{}".format(layer_id),
                                                     shape=[1, 3, channels, channels],
                                                     initializer=tf.contrib.layers.xavier_initializer())
                    filter_bias = tf.get_variable("b_{}".format(layer_id), shape=[channels])
                    conv = tf.nn.atrous_conv2d(_inputs,
                                               filters=filter_weights,
                                               rate=np.power(2, layer_id),
                                               padding="SAME",
                                               name="conv_layer-{}".format(layer_id))
                    conv = tf.nn.bias_add(conv, filter_bias)
                    _inputs = tf.nn.relu(conv)
        return tf.squeeze(_inputs, axis=1, name="output")

def lstm_layer(inputs, in_lengths, lstm_layers, lstm_units, rnn_dropout_ratio=1.0, name="lstm_layer"):
    '''
    @param inputs: [batch_size, seq_length, emb_size]
    @param in_lengths: [batch_size]
    @param lstm_layers: lstm 层数
    @param lstm_units: lstm units 个数
    @param rnn_dropout_ratio: dropout
    @return: [batch_size, seq_length, emb_size]
    '''
    with tf.variable_scope(name):
        def gen_lstm_cell():
            return tf.nn.rnn_cell.DropoutWrapper(tf.contrib.rnn.BasicLSTMCell(num_units=lstm_units),
                                                 output_keep_prob=rnn_dropout_ratio)

        # 多层 lstm
        outputs, output_state_fw, output_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(
            [gen_lstm_cell() for _ in range(lstm_layers)],
            [gen_lstm_cell() for _ in range(lstm_layers)],
            inputs=inputs,
            sequence_length=in_lengths,
            dtype=tf.float32)
        return outputs


#!/usr/bin/env python3

import sys
import csv
import json
from termcolor import colored

# First clean csv, we can then re-use the csvToJSON script for all datasets.
source_url = "https://www.oscr.org.uk/about-charities/search-the-register/charity-register-download"
source_date = "2019"

# some of these are aliasses of other names also in the list
# Names from: https://www.geni.com/projects/Counties-of-Scotland-United-Kingdom/14402
counties = [
        "Aberdeenshire",
        "Angus",
        "Argyllshire",
        "Ayrshire",
        "Banffshire",
        "Moray council",
        "Aberdeenshire council",
        "Berwickshire",
        "Buteshire",
        "Caithness",
        "Clackmannanshire",
        "Dumfriesshire",
        "Dumfries",
        "Galloway)",
        "Dunbartonshire",
        "Lothian-Main-Page",
        "East Lothian",
        "Haddingtonshire",
        "Midlothian",
        "Fife/Fifeshire",
        "Inverness-shire",
        "Kincardineshire",
        "Kinross-shire",
        "Perth",
        "Kinross",
        "Kirkcudbrightshire",
        "Lanarkshire",
        "Linlithgowshire",
        "West Lothian",
        "Midlothian",
        "Edinburghshire",
        "Moray",
        "Morayshire",
        "Elginshire",
        "Nairnshire-Main-Page",
        "Nairn",
        "Nairnshire",
        "Highland",
        "Orkney",
        "Peebles-shire",
        "Borders",
        "Perthshire",
        "Perth",
        "Kinross",
        "Stirling",
        "Renfrewshire",
        "Ross and Cromarty",
        "Roxburghshire",
        "Selkirkshire",
        "Shetland",
        "Stirlingshire",
        "Sutherland",
        "West Lothian",
        "Linlithgowshire",
        "Wigtownshire"
    ]

# Categories from the 'purpose' field that have these values
# will be placed in the generic category 'human'.
nature_category_list = [
        "The advancement of environmental protection or improvement",
        ]

animal_category_list = [
        "The advancement of animal welfare"
        ]

education_category_list = [
        "The advancement of education",
        ]

health_category_list = [
        "The advancement of health",
        ]

community_category_list = [
        "The advancement of citizenship or community development",
        "The prevention or relief of poverty",
        "The saving of lives",
        "The provision of recreational facilities, or the organisation of recreational activities, with the object of improving the conditions of life for the persons for whom the facilities or activities are primarily intended",
        "The advancement of human rights, conflict resolution or reconciliation",
        "The promotion of religious or racial harmony",
        "The promotion of equality and diversity",
        "The relief of those in need by reason of age, ill health, disability, financial hardship or other disadvantage",
        ]

religion_category_list = [
        "The advancement of religion",
        ]

culture_category_list = [
        "The advancement of the arts, heritage, culture or science",
        ]

sports_category_list = [
        "The advancement of public participation in sport",
        ]

def in_list(purpose, category_list):
    for cat in category_list:
        if cat in purpose:
            return 1
    return 0

def get_category_values(purposes):
    # Using 0 as false, 1 as true
    # Because more compact in search engine (would otherwise write "True")

    # clean purpose from quotes
    pur = purposes.strip().replace("'", "")

    nature = in_list(pur, nature_category_list)
    animal = in_list(pur, animal_category_list)
    education = in_list(pur, education_category_list)
    health = in_list(pur, health_category_list)
    community = in_list(pur, community_category_list)
    religion = in_list(pur, religion_category_list)
    culture = in_list(pur, culture_category_list)
    sports = in_list(pur, sports_category_list)

    return nature, animal, education, health, community, religion, culture, sports

def get_values_from_address(address):
    '''
    "Sports Pavilion, Pentcaitland, East Lothian"
    "The Old Garage, Mill Hills Farm, Crieff, Perthshire"
    "29A Westburn Drive, Aberdeen"
    "60 Brookfield Place, Alva, Clackmannanshire"
    "21 Church Street, Brechin, Angus"
    "Keppochan Farmhouse, Cladich, Dalmally"
    "Meeks Road Surgery, 10 Meeks Road, Falkirk"
    "24 Lanark Road, Edinburgh"
    "6 annerley court, cuparhead, coatbridge, lanarkshire"
    '''
    city = ""
    state = ""  # County / Shire
    parts = address.split(",")
    found_state = False
    # we 'reverse' parts, because we expect our values
    # to be within last 3 items.
    for part in reversed(parts):
        if not found_state:
            for county in counties:
                if part.strip() in county:
                    state = county.strip()
                    found_state = True
        else:
            city = part.strip()
            return city, state

    # couldn't find county, lets assume city is last
    city = address.split(",")[-1].strip()
    return city, state

def fix_nulls(s):
    for line in s:
        yield line.replace('\0', ' ')

def parse(input_file_path, output_file_path):

    # we assume it data has heading like this:
    """
    Charity Number,
    Charity Name,
    Registered Date,
    Known As,
    Charity Status,
    Notes,
    Postcode,
    Constitutional Form,
    Previous Constitutional Form 1,
    Geographical Spread,
    Main Operating Location,
    Purposes,
    Beneficiaries,
    Activities,
    Objectives,
    Principal Office/Trustees Address,
    Website,
    Most recent year income,
    Most recent year expenditure,
    Mailing cycle,
    Year End,
    Donations and legacies income,
    Charitable activities income,
    Other trading activities income,
    Investments income,
    Other income,
    Raising funds spending,
    Charitable activities spending,
    Other spending,
    Parent charity name,
    Parent charity number,
    Parent charity country of registration,
    Designated religious body,
    Regulatory Type
    """
    # For new file we are going to first rewrite the heading
    # We keep: Legal Name, City, State, Country, Website
    # We add: Source URL, Source date
    end_part = source_url + "," + source_date + "\n"

    print("Opening output file..")
    with open(output_file_path, 'w+', encoding="utf-8") as output_file:

        print("Write header..")
        fieldnames = [
                "OfficialID",
                "Name",
                "City",
                "State",
                "Country",
                "Website",
                "NAT",
                "ANI",
                "EDU",
                "HEA",
                "COM",
                "REL",
                "CUL",
                "SPO",
                "SourceURL",
                "SourceDate"
                ]
        output_writer = csv.DictWriter(output_file,
                                        fieldnames=fieldnames,
                                        delimiter=',',
                                        quotechar='"',
                                        quoting=csv.QUOTE_MINIMAL)
        output_writer.writeheader();

        # open to read source
        print("Opening source file..")

        with open(input_file_path, 'r') as input_file:

            input_reader = csv.DictReader(fix_nulls(input_file))

            for line in input_reader:
                city, state = get_values_from_address(line["Principal Office/Trustees Address"])
                nature, animal, education, health, community, religion, culture, sports = get_category_values(line["Purposes"])

                output_writer.writerow({"OfficialID": line["Charity Number"],
                                        "Name": line["Charity Name"],
                                        "City": city,
                                        "State": state,
                                        "Country": "SC",
                                        "Website": line["Website"],
                                        "NAT": nature,
                                        "ANI": animal,
                                        "EDU": education,
                                        "HEA": health,
                                        "COM": community,
                                        "REL": religion,
                                        "CUL": culture,
                                        "SPO": sports,
                                        "SourceURL": source_url,
                                        "SourceDate": source_date})

    # print first couple of lines as check
    with open(output_file_path) as lines:
        print(colored("First two lines of created file:", 'green') )
        print(lines.readline(), end='')
        print(lines.readline(), end='')

    print(colored("Ended cleaning CSV file", "green"))


from search import *

class Problem:
    def __init__(self, initial, goal=None):
        self.initial = initial
        self.goal = goal

    def actions(self, state):
        raise NotImplementedError

    def result(self, state, action):
        raise NotImplementedError

    def goal_test(self, state):
        if isinstance(self.goal, list):
            return is_in(state, self.goal)
        else:
            return state == self.goal

    def path_cost(self, c, state1, action, state2):
        return c + 1

    def value(self, state):
        raise NotImplementedError

# ________________
class VacuumCleaner(Problem):

    def __init__(self, initial, goal):
        self.initial =initial
        self.goal =   goal
        super().__init__(initial, goal)

    def find_agent_square(self, state):
        for agentpos in state:
            if agentpos == (1,1):
                return state.index((1,1))
            elif agentpos == (0,1):
                return state.index((0,1))

    def actions(self, state):
        possible_actions = ["UP", "DOWN", "LEFT", "RIGHT", "SUCK",]
        index_agent_square = self.find_agent_square(state)

        if index_agent_square % 3 == 0:
            possible_actions.remove("LEFT")
        if index_agent_square < 3:
            possible_actions.remove("UP")
        if index_agent_square % 3 == 2:
            possible_actions.remove("RIGHT")
        if index_agent_square > 5:
            possible_actions.remove("DOWN")

        return possible_actions

    def result(self, state, action):
        agent = self.find_agent_square(state)

        new_state = list(state)

        if(action == "UP" or action == "DOWN" or action == "RIGHT" or action == "LEFT"):
            delta = {'UP': -3, 'DOWN': 3, 'LEFT': -1, 'RIGHT': 1}
            frontier = agent + delta[action]
            if (new_state[frontier][0] == 0):
                new_state[frontier] = (0,1)
            else:
                new_state[frontier] = (1,1)
            if(new_state[agent][0]==0):
                new_state[agent] = (0,0)
            else:
                new_state[agent] = (1,0)
        else:
            new_state[agent] = (0,1)

        return tuple(new_state)

    def goal_test(self, state):
        return state == self.goal

initial =   ((1,0), (1,0), (1,0),
             (0,0), (0,1), (0,0),
             (0,0), (0,0), (0,0))

goal =      ((0,0), (0,0), (0,0),
             (0,0), (0,1), (0,0),
             (0,0), (0,0), (0,0))
problem = VacuumCleaner(initial, goal)
print(breadth_first_graph_search(problem).solution())

Trabalho 1/Atividade02 VacuumCleaner- LIA/vacumm_cleaner.py


#!/usr/bin/python
#	vim:fileencoding=utf-8
# (C) 2010 Michał Górny, distributed under the terms of 3-clause BSD license

import codecs, os.path
from diffmask.util import DiffmaskList

class MaskMerge(DiffmaskList):
	""" A class representing the contents of a set of merged
		package.mask files as a string list (with newlines preserved).
		"""
	def ProcessMaskFile(self, file, header):
		""" Read a single package.mask file (being given as an open file
			instance) and append it with the name `header'. """
		mf = file.readlines()

		# try to drop copyright, examples etc.
		ccb = None # current comment block
		gotwhite = True # whitespace status

		for i in range(len(mf)):
			if mf[i].startswith('#'):
				if gotwhite:
					ccb = i
					gotwhite = False
			elif not mf[i].strip():
				gotwhite = True
			else: # package atom
				if ccb is not None:
					del mf[:ccb]
				break

		# Ensure the trailing newline.
		try:
			if mf[-1].strip():
				mf.append('\n')
		except IndexError: # An empty repo? Just omit it.
			return

		self.extend(['## *%s*\n' % header, '\n'])
		self.extend(mf)

	def ProcessRepos(self):
		for o in self.portdb.getRepositories():
			path = self.portdb.getRepositoryPath(o)
			try:
				maskf = codecs.open(os.path.join(path, 'profiles', 'package.mask'), 'r', 'utf8')
			except IOError:
				pass
			else:
				self.ProcessMaskFile(maskf, o)

	def ProcessProfiles(self):
		for p in self.portdb.settings.profiles:
			try:
				maskf = codecs.open(os.path.join(p, 'package.mask'), 'r', 'utf8')
			except IOError:
				pass
			else:
				profname = 'profile: %s' % os.path.relpath(p, os.path.join(self.portdb.porttree_root, 'profiles'))
				self.ProcessMaskFile(maskf, profname)

	def __init__(self, dbapi):
		""" Instantiate the MaskMerge class. Grab the list of active
			package.mask files from Portage and read them. """
		self.portdb = dbapi
		self.ProcessRepos()
		self.ProcessProfiles()
		# Drop the trailing blank line.
		if not self[-1].strip():
			del self[-1]


from CGComponents import *

SCREEN_WIDTH = 300
SCREEN_HEIGHT = 300

def clip_test(p, q, u1, u2):
    result = True
    if p < 0.0:
        r = q / p
        if r > u2:
            result = False
        elif r > u1:
            u1 = r
    elif p > 0.0:
        r = q / p
        if r < u1:
            result = False
        elif r < u2:
            u2 = r
    elif q < 0.0:
        result = False

    return u1, u2, result

def liang_barsky(point_bottom_left, point_top_right, line):
    u1 = 0.0
    u2 = 1.0

    x_min = point_bottom_left.x
    x_max = point_top_right.x
    y_min = point_bottom_left.y
    y_max = point_top_right.y

    dx = line.p2.x - line.p1.x
    dy = line.p2.y - line.p1.y

    u1, u2, result = clip_test(-dx, line.p1.x - x_min, u1, u2)
    if result:
        u1, u2, result = clip_test(dx, x_max - line.p1.x, u1, u2)
        if result:
            u1, u2, result = clip_test(-dy, line.p1.y - y_min, u1, u2)
            if result:
                u1, u2, result = clip_test(dy, y_max - line.p1.y, u1, u2)
                if result:
                    if u2 < 1.0:
                        line.p2.x = line.p1.x + (u2 * dx)
                        line.p2.y = line.p1.y + (u2 * dy)
                    if u1 > 0.0:
                        line.p1.x = line.p1.x + (u1 * dx)
                        line.p1.y = line.p1.y + (u1 * dy)
                    print('x1:{0}   y1:{1}  x2:{2}  y2:{3}'.format(line.p1.x, line.p1.y, line.p2.x, line.p2.y))

def main():
    rect_bottom_left = Point2D(0, 0)
    rect_top_right = Point2D(10, 10)

    line_1 = Line2D(Point2D(-5, 3), Point2D(15, 9))
    liang_barsky(rect_bottom_left, rect_top_right, line_1)

    input('Press <enter> to close')

if __name__ == "__main__":
    main()


from PIL import Image, ImageDraw

imagen = Image.open('gatito.jpg')

rojos = [0 for _ in range(256)]
verdes = [0 for _ in range(256)]
azules = [0 for _ in range(256)]

for r, g, b in imagen.getdata():
    rojos[r] += 1
    verdes[g] += 1
    azules[b] += 1

def generar_histograma(conteos, nombre_archivo):
    lienzo = Image.new('RGB', (256, 256))
    lapicero = ImageDraw.Draw(lienzo)

    maximo_conteo = max(conteos)
    for color, conteo in enumerate(conteos):
        factor = conteo / maximo_conteo
        lapicero.line([(color, 256), (color, 256 - (factor * 256))])

    lienzo.save(nombre_archivo)

generar_histograma(rojos, 'rojos.jpg')
generar_histograma(verdes, 'verdes.jpg')
generar_histograma(azules, 'azules  .jpg')


import streamlit as st
from helpers import set_bg_hack_url

def set_background_widget(background_url):
    set_bg_hack_url(background_url)

def sidebar_widget():
    st.sidebar.title("Options")

    input_media = st.sidebar.radio(label="Search with...", options=["text", "image"])

    st.sidebar.markdown(
        """This example lets you use a *textual* description to search through *images* of tattoos using [Jina](https://github.com/jina-ai/jina/).
        """
    )

    st.sidebar.markdown(
        "[Repo link](https://github.com/k-zehnder/jina-clip-streamlit)"
    )

    st.sidebar.markdown(
        "[Credits](https://github.com/jina-ai/example-multimodal-fashion-search)"
    )
    return input_media


from flask import Flask, render_template, request
import chatbot as mymodule

app = Flask(__name__)

# app.static_folder='static'

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/get')
def get_bot_response():
    userAnswer = request.args.get('msg')
    chat = mymodule.ChatBot(userAnswer)
    return str(chat.check_answer())

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


scores = [3,1,4,7,1,5,9,2,4,2,0,5,6]

i = 1

maximum = scores[0]
minimum = scores[0]

while i < len(scores):
    element = scores[i]

    if element > maximum:
        maximum = element

    if element < minimum:
        minimum = element

    i+=1

print(maximum)
print(minimum)


import numpy as np

def import_data(filePath):
    data = np.loadtxt(filePath, delimiter=";", skiprows=1)
    data = data.astype(int)
    return data

def convert(file_path):
    data = import_data(file_path)

    output = []

    for record in data:
        n_record = []
        for i in record:
            n_record.append(i)

        output.append(n_record)

    return output


class SYSINFO:

    DATA_STRING = ""

    def __init__(self):
        self.sysinfo = self.get_sys_info()
        self.boot_time = self.get_cpu_info()
        self.cpu_info = self.get_cpu_info()
        self.mem_usage = self.get_mem_usage()
        self.disk_info = self.get_disk_info()
        self.net_info = self.get_net_info()

        def get_size(self, bolter, suffix="B"):
            factor = 1024
            for unit in ["", "K", "M", "G", "T", "P"]:
                if bolter < factor:
                    return f"{bolter:.2f}{unit}{suifiX}"

                bolter /= factor