import pymongo
from bson.objectid import ObjectId
import os

class DLExMongoRecorder():

    def __init__(self, db, pid, expid):
        self.db = db
        self.pid = pid
        self.expid = expid

    def get_exp_info(self, setting_name):

        col = self.db.experiments
        query = {"_id":ObjectId(self.expid)}
        # new_vlues = {"$set": {setting_name: setting_value}}
        # col.update_one(query, new_vlues, upsert=True)
        x =col.find(query)
        return x.next()[setting_name]

    def get_hyper_params(self):
        print("started get hyper param")
        col = self.db.hyperparam
        query = {"expid": self.expid}
        x = col.find(query, {"_id": 0, "expid": 0})
        # print("xxx next=", x.next())
        return x.next()

    def get_train_settings(self):
        col = self.db.train_settings
        query = {"expid": self.expid}
        output = col.find_one(query, {"_id": 0, "expid": 0})
        return output

    # Recording training stat values.
    def record_train_stat(self, iteration, stat_name, stat_value ):
        col = self.db.trainstats
        query = {"expid":self.expid, "iteration": iteration }
        new_values = {"$set": {stat_name: stat_value}}
        col.update_one(query, new_values, upsert=True)

    # record information about experiment (to track progress of the experiment)
    def record_exp_info(self, info_name, info_value):
        col = self.db.experiments
        query = {"_id":ObjectId(self.expid) }
        new_value = {"$set": {info_name: info_value}}
        col.update_one(query, new_value, upsert=True)

    def set_exp_state(self, status):
        col = self.db.experiments
        query = {"_id":ObjectId(self.expid)}
        new_value = { "$set": { "status": status } }

        col.update_one(query, new_value, upsert=True)

    # function to record total epochs
    def add_total_epoch(self):
        current_epoch = self.get_exp_info("total_epochs")
        self.record_exp_info("total_epochs", current_epoch +1 )

    # function to read current total epoch number
    def read_total_epoch(self):
        current_epoch = self.get_exp_info("total_epochs")
        return current_epoch

    # function to record iterations
    def record_iters(self, iter_num):
        self.record_exp_info("iters", iter_num)

    # save dataloader size
    def record_dataloader_size(self, len_dataloader):
        self.record_exp_info("dataloader_size", len_dataloader)

    # Handling models

    def generate_checkpoint_path(self, checkpoint_iter, checkpoint_type):

        col = self.db.models
        # checkpoint_type: "BATCH", "EPOCH".. etc.
        query = {"pid": self.pid, "expid": self.expid, "iter": checkpoint_iter,  "type": checkpoint_type }
        x = col.insert_one(query)

        print("x=",str(x.inserted_id))

        col_exp = self.db.experiments
        query_exp = {"_id": ObjectId(self.expid), "pid": self.pid}
        model_dir_path = col_exp.find_one(query_exp)["models_path"]
        print("model dir path:", model_dir_path)

        # new model path
        model_path = os.path.join(model_dir_path, str(x.inserted_id) + ".tar")

        # update models table back
        new_value = {"$set": {"path": model_path}}

        x1 = col.update(query, new_value, upsert=True)

        print(model_path)

        return model_path

    def load_checkpoint_path(self, checkpoint_iter, checkpoint_type):

        col = self.db.models
        query = {"pid": self.pid, "expid": self.expid, "iter": checkpoint_iter,  "type": checkpoint_type }

        out_dict = col.find_one(query)
        print("chekpoint path =", out_dict["path"])
        return out_dict["path"]

    # handlign img paths

    def add_image(self,  datatype, **kw): # type: INPUTDATA, GENDATA, --> return a path to image

        # get new id for new data
        col = self.db.outputdata
        query ={"expid": self.expid, "type": datatype}
        query.update(kw)
        print("add image updated query:", query)
        x = col.insert_one(query) # x.inserted_id

        col_exp = self.db.experiments
        query_exp = {"_id": ObjectId(self.expid)}
        exp_path = col_exp.find(query_exp, {"_id":0,"output_path":1})

        # new image path
        imgpath = exp_path.next()["output_path"] + "/" + str(x.inserted_id) + ".png"

        # update outputdata collection
        new_value = {"$set": {"imgpath": imgpath}}
        x1 = col.update(query, new_value, upsert=True)

        print(x.inserted_id)
        #  print(exp_path.next())
        return imgpath


import os
import argparse
import numpy as np
import torch

from stimulus import StimGenerator
from models import STPNet, OptimizedRNN, STPRNN
from utilities import train

def main():
    # Training settings
    parser = argparse.ArgumentParser(description='Models of change detection')
    parser.add_argument('--image-set', type=str, default='A', metavar='I',
                        help='image set to train on: A, B, C, D (default: A)')
    parser.add_argument('--model', type=str, default='STPNet', metavar='M',
                        help='model to train: STPNet, RNN, or STPRNN (default: STPNet)')
    parser.add_argument('--noise-std', type=float, default=0.0, metavar='N',
                        help='standard deviation of noise (default: 0.0)')
    parser.add_argument('--syn-tau', type=float, default=6.0, metavar='N',
                        help='STPNet recovery time constant (default: 6.0)')
    parser.add_argument('--hidden-dim', type=int, default=16, metavar='N',
                        help='hidden dimension of model (default: 16)')
    parser.add_argument('--l2-penalty', type=float, default=0.0, metavar='L2',
                        help='L2 penalty on hidden activations (default: 0.0)')
    parser.add_argument('--pos-weight', type=float, default=1.0, metavar='W',
                        help='weight on positive examples (default: 1.0)')
    parser.add_argument('--seq-length', type=int, default=50000, metavar='N',
                        help='length of each trial (default: 50000)')
    parser.add_argument('--delay-dur', type=int, default=500, metavar='N',
                        help='delay duration (default: 500 ms)')
    parser.add_argument('--batch-size', type=int, default=128, metavar='N',
                        help='number of train trial batches (default: 128)')
    parser.add_argument('--epochs', type=int, default=5000, metavar='N',
                        help='epoch train criterion (default: 5000)')
    parser.add_argument('--dprime', type=float, default=2.0, metavar='N',
                        help='dprime train criterion (default: 2.0)')
    parser.add_argument('--patience', type=int, default=1, metavar='N',
                        help='number of epochs to wait above baseline (default: 1)')
    parser.add_argument('--log-interval', type=int, default=100, metavar='N',
                        help='how many epochs to wait before logging training status')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    device = torch.device("cuda" if use_cuda else "cpu")

    # Set random seed
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)

    # Create train stimulus generator
    train_generator = StimGenerator(image_set=args.image_set, seed=args.seed,
                                    batch_size=args.batch_size, seq_length=args.seq_length,
                                    delay_dur=args.delay_dur)

    # Get input dimension of feature vector
    input_dim = len(train_generator.feature_dict[0])

    # Create model
    if args.model == 'STPNet':
        model = STPNet(input_dim=input_dim,
                       hidden_dim=args.hidden_dim,
                       syn_tau=args.syn_tau,
                       noise_std=args.noise_std).to(device)
    elif args.model == 'STPRNN':
        model = STPRNN(input_dim=input_dim,
                       hidden_dim=args.hidden_dim,
                       syn_tau=args.syn_tau,
                       noise_std=args.noise_std).to(device)
    elif args.model == 'RNN':
        model = OptimizedRNN(input_dim=input_dim,
                             hidden_dim=args.hidden_dim,
                             noise_std=args.noise_std).to(device)
    else:
        raise ValueError("Model not found")

    # Define loss function
    criterion = torch.nn.BCEWithLogitsLoss(
        reduction='none', pos_weight=torch.tensor([args.pos_weight]).to(device))
    optimizer = torch.optim.Adam(model.parameters())

    # Initialize tracking variables
    loss_list = []
    dprime = 0
    dprime_list = []
    wait = 0

    for epoch in range(1, args.epochs + 1):
        # Train model
        loss, dprime = train(args, device, train_generator,
                             model, criterion, optimizer)

        loss_list.append(loss)
        dprime_list.append(dprime)

        if epoch % args.log_interval == 0:
            # Print current progress
            print("Epoch: {}  loss: {:.4f}  dprime: {:.2f}".format(
                epoch, loss, dprime))

        if dprime < args.dprime:
            # Reset wait count
            wait = 0
        else:
            # Increase wait count
            wait += 1
            # Stop training after wait exceeds patience
            if wait >= args.patience:
                break

    # Save trained model
    save_dir = './PARAM/'+args.model
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    save_path = save_dir+'/model_train_seed_'+str(args.seed)+'.pt'
    torch.save({'epoch': epoch,
                'loss': loss_list,
                'dprime': dprime_list,
                'state_dict': model.state_dict()}, save_path)

if __name__ == '__main__':
    main()


from settings import SIZE
from settings import HELP_INFO
from ast import literal_eval as make_tuple

class CliInterface:

    def __init__(self, cinema_manager):
        self.__cinema = cinema_manager

    def __command_dispatcher(self, command):
        command_list = command.split(" ")
        if len(command_list) == 1:
            if command_list[0] == "show_movies":
                self.show_movies()
            elif command_list[0] == "finalize":
                print("You don't have a reservation to finalize.")
            elif command_list[0] == 'give_up':
                start_over = input("Do you wan to start over? yes/no: ")
                if start_over == 'yes':
                    self.make_reservation()
                else:
                    print("Your reservation wasn't saved!")
            elif command_list[0] == 'make_reservation':
                for_finalize = self.make_reservation()
                command = input("Enter command: ")
                if command == 'finalize':
                    for seat in for_finalize["list_of_seats"]:
                        reserve_row = seat[0]
                        reserve_column = seat[1]
                        self.__cinema.add_new_reservation(for_finalize["res_name"], for_finalize[
                            "projection_id"], reserve_row, reserve_column)
                else:
                    self.__command_dispatcher(command)
            elif command_list[0] == "help":
                self.helper()
        elif len(command_list) == 2:
            if command_list[0] == "show_movie_projections":
                self.get_all_movies_by_id(command_list[1])
            elif command_list[0] == "cancel_reservation":
                self.__cinema.delete_reservation(command_list[1])
        elif len(command_list) == 3:
            if command_list[0] == "show_movie_projections":
                self.get_all_movies_by_id_and_date(
                    command_list[1], command_list[2])
        else:
            print("No such command!")

    def start(self):
        while True:
            command = input("Enter command: ")
            self.__command_dispatcher(command)
            if command == "exit":
                return False

    def show_movies(self):
        all_movies = self.__cinema.get_all_movies()
        print("Current movies:")
        for movie in all_movies:
            print(movie["movie_info"])
        #print("\n".join([movie["name"] for movie in all_movies]))

    def get_all_movies_by_id(self, num):
        by_id = self.__cinema.get_all_movies_by_id(num)
        if len(by_id) > 0:
            for proj_by_id in by_id:
                print(proj_by_id["proj_for_current_movie"])
        else:
            print ("Invalid input!")

    def get_all_movies_by_id_and_date(self, num, date):
        by_id_and_date = self.__cinema.get_all_movies_by_id_and_date(num, date)
        if len(by_id_and_date) > 0:
            for movie_by_id_and_date in by_id_and_date:
                print(movie_by_id_and_date["proj_for_current_movie"])
        else:
            print ("Invalid input!")

    def how_many_free_seats(self, projection_id, number_of_tickets):
        number_of_free_seats = self.__cinema.get_num_of_seats_by_projection_id(
            projection_id)
        if int(number_of_free_seats[0]) < int(number_of_tickets):
            return False
        return True

    def matrix_print(self, seats):
        list_of_lists = []
        for row in range(0, 10):
            new_row = []
            for elem in range(0, 10):
                new_row.append(".")
            list_of_lists.append(new_row)

        for seat in seats:
            i = seat['row'] - 1
            j = seat['column'] - 1
            list_of_lists[i][j] = "X"

        for each in list_of_lists:
            print(each)

        return list_of_lists

    def make_reservation(self):
        reservation_name = input("Choose name: ")
        number_of_tickets = input("Choose number of tickets: ")
        self.show_movies()
        while True:
            reservation_movie_id = input("Choose movie id: ")
            self.__cinema.get_num_of_free_seats_by_movie_id(
                reservation_movie_id)
            wanted_projection_id = input("Choose projection id: ")
            if self.how_many_free_seats(reservation_movie_id, number_of_tickets):
                break
            else:
                print("There are no more available seats! Enter new id: ")
        list_of_not_available_seats = self.__cinema.show_all_available_spots_matrix(
            wanted_projection_id)
        matrix = self.matrix_print(list_of_not_available_seats)
        count = 0
        list_of_reserved_seats = []
        while int(count) < int(number_of_tickets):
            seat_tuple_str = input("Choose a seat: ")
            seat_tuple = make_tuple(seat_tuple_str)
            if int(seat_tuple[0]) > 10 or int(seat_tuple[0]) < 1 or int(seat_tuple[1]) > 10 or int(seat_tuple[1]) < 1:
                print("There is no such seat")
            elif matrix[int(seat_tuple[0]) - 1][int(seat_tuple[1]) - 1] == 'X':
                print("This seat is taken")
            else:
                count += 1
                list_of_reserved_seats.append(seat_tuple)
        res = {}
        res["res_name"] = reservation_name
        res["list_of_seats"] = list_of_reserved_seats
        res["projection_id"] = wanted_projection_id
        print("If you want to save your reservation type finalize")
        return res

    def helper(self):
        print(HELP_INFO)


import tensorflow as tf

from fennlp.datas.checkpoint import LoadCheckpoint
from fennlp.datas.dataloader import TFWriter, TFLoader
from fennlp.metrics import Metric
from fennlp.models import bert
from fennlp.optimizers import optim
from fennlp.tools import bert_init_weights_from_checkpoint

# 载入参数
# LoadCheckpoint(language='zh', model="bert", parameters="base", cased=True, url=None)
# language: the language you used in your input data
# model: the model you choose,could be bert albert and gpt2
# parameters: can be base large xlarge xxlarge for albert, base medium large for gpt2, base large for BERT.
# cased: True or false, only for bert model.
# url: you can give a link of other checkpoint.
load_check = LoadCheckpoint(language='zh')
param, vocab_file, model_path = load_check.load_bert_param()

# 定制参数
param.batch_size = 6
param.maxlen = 128
param.label_size = 46

# 构建模型
class BERT_NER(tf.keras.Model):
    def __init__(self, param, **kwargs):
        super(BERT_NER, self).__init__(**kwargs)
        self.batch_size = param.batch_size
        self.maxlen = param.maxlen
        self.label_size = param.label_size
        self.bert = bert.BERT(param)
        self.dense = tf.keras.layers.Dense(self.label_size, activation="relu")

    def call(self, inputs, is_training=True):
        bert = self.bert(inputs, is_training)
        sequence_output = bert.get_sequence_output()  # batch,sequence,768
        pre = self.dense(sequence_output)
        pre = tf.reshape(pre, [self.batch_size, self.maxlen, -1])
        output = tf.math.softmax(pre, axis=-1)
        return output

    def predict(self, inputs, is_training=False):
        output = self(inputs, is_training=is_training)
        return output

model = BERT_NER(param)

model.build(input_shape=(3, param.batch_size, param.maxlen))

model.summary()

# 构建优化器
optimizer_bert = optim.AdamWarmup(learning_rate=2e-5,  # 重要参数
                                  decay_steps=10000,  # 重要参数
                                  warmup_steps=1000, )

# 构建损失函数
# mask_sparse_categotical_loss = Losess.MaskSparseCategoricalCrossentropy(from_logits=False,use_mask=True)
sparse_categotical_loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
# 初始化参数
bert_init_weights_from_checkpoint(model,
                                  model_path,
                                  param.num_hidden_layers,
                                  pooler=False)

# 写入数据 通过check_exist=True参数控制仅在第一次调用时写入
writer = TFWriter(param.maxlen, vocab_file,
                  modes=["train"], check_exist=False)

ner_load = TFLoader(param.maxlen, param.batch_size, epoch=5)

# 训练模型
# 使用tensorboard
summary_writer = tf.summary.create_file_writer("./tensorboard")

# Metrics
f1score = Metric.SparseF1Score(average="macro")
precsionscore = Metric.SparsePrecisionScore(average="macro")
recallscore = Metric.SparseRecallScore(average="macro")
accuarcyscore = Metric.SparseAccuracy()

# 保存模型
checkpoint = tf.train.Checkpoint(model=model)
manager = tf.train.CheckpointManager(checkpoint, directory="./save",
                                     checkpoint_name="model.ckpt",
                                     max_to_keep=3)
# For train model
Batch = 0
for X, token_type_id, input_mask, Y in ner_load.load_train():
    with tf.GradientTape() as tape:
        predict = model([X, token_type_id, input_mask])
        loss = sparse_categotical_loss(Y, predict)
        f1 = f1score(Y, predict)
        precision = precsionscore(Y, predict)
        recall = recallscore(Y, predict)
        accuracy = accuarcyscore(Y, predict)
        if Batch % 101 == 0:
            print("Batch:{}\tloss:{:.4f}".format(Batch, loss.numpy()))
            print("Batch:{}\tacc:{:.4f}".format(Batch, accuracy))
            print("Batch:{}\tprecision{:.4f}".format(Batch, precision))
            print("Batch:{}\trecall:{:.4f}".format(Batch, recall))
            print("Batch:{}\tf1score:{:.4f}".format(Batch, f1))
            manager.save(checkpoint_number=Batch)

        with summary_writer.as_default():
            tf.summary.scalar("loss", loss, step=Batch)
            tf.summary.scalar("acc", accuracy, step=Batch)
            tf.summary.scalar("f1", f1, step=Batch)
            tf.summary.scalar("precision", precision, step=Batch)
            tf.summary.scalar("recall", recall, step=Batch)

    grads_bert = tape.gradient(loss, model.variables)
    optimizer_bert.apply_gradients(grads_and_vars=zip(grads_bert, model.variables))
    Batch += 1


from rewriter import *
from os.path import basename
import copy
from lan_parser import *
from cgen import *
from transformation import *
from analysis import *
fileprefix = "../test/C/"

SetNoReadBack = False
DoOptimizations = True

def LexAndParse(name, createTemp):
    import ply.yacc as yacc
    cparser = yacc.yacc()
    lex.lex()

    run = 1
    while run:
        filename = fileprefix + name + '/' + name + 'For.cpp'
        funcname = basename(os.path.splitext(filename)[0])
        try:
            f = open(filename, 'r')
            s = f.read()
            f.close()
            ## print s
        except EOFError:
            break

        lex.input(s)
        while 1:
            tok = lex.token()
            if not tok: break
            ## print tok

        ast = cparser.parse(s)
        ## ast.show()
        ## print ast
        ## print slist
        cprint = CGenerator()
        ## printres = cprint.visit(ast)
        ## print printres
        rw = Rewriter()
        rw.initOriginal(ast)
        tempfilename = fileprefix + name + '/'+'temp' +name.lower() + '.cpp'
        if createTemp:
            rw.rewrite(ast, funcname, changeAST = True)
            cprint.createTemp(ast, filename = tempfilename)

        run = 0
        filename = tempfilename
        ## funcname = basename(os.path.splitext(filename)[0])
        try:
            f = open(filename, 'r')
            s = f.read()
            f.close()
        except EOFError:
            break

        ast = cparser.parse(s)
        ## ## ast.show()
        tempast = copy.deepcopy(ast)
        tempast2 = copy.deepcopy(ast)
        return (rw, ast, tempast, tempast2, funcname)

def CGen(name, funcname, an, tempast2, ast, kernelstringname = ''):
        cprint = CGenerator()
        rw = an.rw
        an.generate_kernels(tempast2, name, fileprefix)
        ## rw.InSourceKernel(tempast2, filename = fileprefix + name + '/'+funcname + '.cl', kernelstringname = kernelstringname)
        boilerast = rw.generateBoilerplateCode(ast)
        cprint.createTemp(boilerast, filename = fileprefix + name + '/'+'boilerplate.cpp')

def matmul():
    name = 'MatMul'
    (rw, ast, tempast, tempast2, funcname) = LexAndParse(name, True)
    rw.initNewRepr(tempast)
    tf = Transformation(rw)

    an = Analysis(rw, tf)
    if DoOptimizations:
        an.Transpose()
        an.DefineArguments()
        an.PlaceInReg()
        an.PlaceInLocalMemory()
    if SetNoReadBack:
        tf.SetNoReadBack()

    ## rw.DataStructures()
    CGen(name, funcname, an, tempast2, ast)

def jacobi():
    name = 'Jacobi'
    (rw, ast, tempast, tempast2, funcname) = LexAndParse(name, True)
    rw.initNewRepr(tempast)
    tf = Transformation(rw)

    an = Analysis(rw, tf)

    if DoOptimizations:
        an.Transpose()
        an.DefineArguments()
        an.PlaceInReg()

        tf.localMemory(['X1'], west = 1, north = 1, east = 1, south = 1, middle = 0)
        an.PlaceInLocalMemory()
    if SetNoReadBack:
        tf.SetNoReadBack()

    CGen(name, funcname, an, tempast2, ast)

def knearest():
    name = 'KNearest'
    (rw, ast, tempast, tempast2, funcname) = LexAndParse(name, True)
    tf = Transformation(rw)
    tf.SetParDim(1)
    rw.initNewRepr(tempast)

    an = Analysis(rw, tf)
    if DoOptimizations:
        an.Transpose()
        an.DefineArguments()
        an.PlaceInReg()
        an.PlaceInLocalMemory()
    if SetNoReadBack:
        tf.SetNoReadBack()
    ## rw.DataStructures()
    ## rw.Unroll2({'k' : 0})

    CGen(name, funcname, an, tempast2, ast)

def nbody():
    name = 'NBody'
    (rw, ast, tempast, tempast2, funcname) = LexAndParse(name, True)

    rw.initNewRepr(tempast)
    tf = Transformation(rw)
    an = Analysis(rw, tf)
    if DoOptimizations:
        an.Transpose()
        an.DefineArguments()
        an.PlaceInReg()
        an.PlaceInLocalMemory()

    if SetNoReadBack:
        tf.SetNoReadBack()
    ## rw.Unroll2({'j': 32})
    CGen(name, funcname, an, tempast2, ast)

def laplace():
    name = 'Laplace'
    (rw, ast, tempast, tempast2, funcname) = LexAndParse(name, True)
    tf = Transformation(rw)
    tf.SetParDim(1)
    rw.initNewRepr(tempast)
    an = Analysis(rw, tf)
    if DoOptimizations:
        an.Transpose()
        an.DefineArguments()
        an.PlaceInReg()
        an.PlaceInLocalMemory()

    if SetNoReadBack:
        tf.SetNoReadBack()

    ## rw.DataStructures()

    ## tf.Unroll2({'d' : 0, 'd_outer' : 0, 'd_inner' : 0})
    CGen(name, funcname, an, tempast2, ast)

def gaussian():
    name = 'GaussianDerivates'
    (rw, ast, tempast, tempast2, funcname) = LexAndParse(name, True)
    ## rw.SetParDim(1)
    rw.initNewRepr(tempast, dev = 'CPU')
    tf = Transformation(rw)

    an = Analysis(rw, tf)
    if DoOptimizations:
        an.Transpose()
        an.DefineArguments()
        an.PlaceInReg()
        an.PlaceInLocalMemory()

        ## tf.Unroll2({'k' : 0, 'd' : 0, 'g' : 0, 'b' : 0})
    ## rw.DataStructures()
    if SetNoReadBack:
        tf.SetNoReadBack()
    CGen(name, funcname, an, tempast2, ast)

if __name__ == "__main__":
    matmul()
    jacobi()
    knearest()
    nbody()
    laplace()
    gaussian()


"""AdaNet input utility functions.

Copyright 2018 The AdaNet Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

def _make_any_batch_size_placeholder(name, shape, dtype, is_sparse):
  """Makes a placeholder that can accept any batch size."""

  modifiable_shape = [None]
  if shape:
    modifiable_shape += shape[1:]
  if is_sparse:
    return tf.sparse_placeholder(shape=modifiable_shape, dtype=dtype, name=name)
  return tf.placeholder(shape=modifiable_shape, dtype=dtype, name=name)

def make_placeholder_input_fn(input_fn):
  """Makes a placeholder input_fn which mimics the given input_fn.

  Requires an input function `input_fn` that returns a tuple of:

  * features: Dictionary of string feature name to `Tensor`.
  * labels: `Tensor` of labels or Dictionary of string label name to `Tensor`
  (for multi-task learning problems).

  The returned input_fn, when called, returns feature and label `Tensor`
  placeholders which have the same shape, name, and type as those returned
  by `input_fn`, but which can accept any batch size. This prevents an
  exported graph from setting a fixed batch size, so that any batch size
  can be used once imported.

  Args:
    input_fn: The input function.

  Returns:
    An input_fn that mimics `input_fn` with placeholder features and labels.
  """

  # Create temporary graph to collect `Tensor` information.
  with tf.Graph().as_default():
    features, labels = input_fn()
    feature_info = {}
    for name, feature in features.items():
      feature_info[name] = (feature.op.name, feature.get_shape().as_list(),
                            feature.dtype, isinstance(feature, tf.SparseTensor))
    if isinstance(labels, dict):
      label_info = {
          name: (tensor.op.name, tensor.get_shape().as_list(), tensor.dtype)
          for name, tensor in labels.items()
      }
    else:
      label_info = (labels.op.name, labels.get_shape().as_list(), labels.dtype)

  def _placeholder_input_fn():
    """Returns (features, labels) without fixed batch_size dimensions."""

    features = {}
    for name, info in feature_info.items():
      feature_op_name, feature_shape, feature_dtype, is_sparse = info
      features[name] = _make_any_batch_size_placeholder(
          feature_op_name, feature_shape, feature_dtype, is_sparse)
    if isinstance(label_info, dict):
      labels = {}
      for name, single_label_info in label_info.items():
        label_op_name, label_shape, label_dtype = single_label_info
        labels[name] = _make_any_batch_size_placeholder(
            label_op_name, label_shape, label_dtype, is_sparse=False)
    else:
      label_op_name, label_shape, label_dtype = label_info
      labels = _make_any_batch_size_placeholder(
          label_op_name, label_shape, label_dtype, is_sparse=False)
    return features, labels

  return _placeholder_input_fn


import numpy as np
from scipy.stats import kendalltau
from sklearn.metrics import recall_score

def scorePerformance(
        prMean_pred, prMean_true,
        rtMean_pred, rtMean_true,
        rrStd_pred, rrStd_true,
        ecgId_pred, ecgId_true):
    """
    Computes the combined multitask performance score.
    The 3 regression tasks are individually scored using Kendalls
    correlation coeffficient.
    The user classification task is scored according to macro averaged
    recall, with an adjustment for chance level. All performances are
    clipped at 0.0, so that zero indicates chance or worse performance,
    and 1.0 indicates perfect performance.
    The individual performances are then combined by taking
    the geometric mean.
    :param prMean_pred: 1D float32 numpy array.
        The predicted average P-R interval duration over the window.
    :param prMean_true: 1D float32 numpy array.
        The true average P-R interval duration over the window.
    :param rtMean_pred: 1D float32 numpy array.
        The predicted average R-T interval duration over the window.
    :param rtMean_true: 1D float32 numpy array.
        The true average R-T interval duration over the window.
    :param rrStd_pred: 1D float32 numpy array.
        The predicted R-R interval duration standard deviation over the window.
    :param rrStd_true: 1D float32 numpy array.
        The true R-R interval duration standard deviation over the window.
    :param ecgId_pred: 1D int32 numpy array.
        The predicted user ID label for each window.
    :param ecgId_true: 1D int32 numpy array.
        The true user ID label for each window.
    :return:
        - The combined performance score on all tasks;
                0.0 means at least one task has chance level performance
                or worse while 1.0 means all tasks are solved perfectly.
        - The individual task performance scores are also returned
    """

    # Input checking
    assert isinstance(ecgId_pred, np.ndarray)
    assert len(ecgId_pred.shape) == 1
    assert ecgId_pred.dtype == np.int32

    assert isinstance(ecgId_true, np.ndarray)
    assert len(ecgId_true.shape) == 1
    assert ecgId_true.dtype == np.int32

    assert isinstance(rrStd_pred, np.ndarray)
    assert len(rrStd_pred.shape) == 1
    assert rrStd_pred.dtype == np.float32

    assert isinstance(rrStd_true, np.ndarray)
    assert len(rrStd_true.shape) == 1
    assert rrStd_true.dtype == np.float32

    assert isinstance(prMean_pred, np.ndarray)
    assert len(prMean_pred.shape) == 1
    assert prMean_pred.dtype == np.float32

    assert isinstance(prMean_true, np.ndarray)
    assert len(prMean_true.shape) == 1
    assert prMean_true.dtype == np.float32

    assert isinstance(rtMean_pred, np.ndarray)
    assert len(rtMean_pred.shape) == 1
    assert rtMean_pred.dtype == np.float32

    assert isinstance(rtMean_true, np.ndarray)
    assert len(rtMean_true.shape) == 1
    assert rtMean_true.dtype == np.float32

    assert (len(ecgId_pred) == len(ecgId_true)) \
        and (len(ecgId_pred) == len(prMean_pred)) \
        and (len(ecgId_pred) == len(prMean_true)) \
        and (len(ecgId_pred) == len(rtMean_pred)) \
        and (len(ecgId_pred) == len(rtMean_true)) \
        and (len(ecgId_pred) == len(rrStd_pred)) \
        and (len(ecgId_pred) == len(rrStd_true))

    # Accuracy is computed with macro averaged recall so that accuracy
    # is computed as though the classes were balanced, even if they are not.
    # Note that provided training, validation and testing sets are balanced.
    # Unbalanced classes would only be and issue if a new train/validation
    # split is created.
    # Any accuracy value worse than random chance will be clipped at zero.

    ecgIdAccuracy = recall_score(ecgId_true, ecgId_pred, average='macro')
    adjustementTerm = 1.0 / len(np.unique(ecgId_true))
    ecgIdAccuracy = (ecgIdAccuracy - adjustementTerm) / (1 - adjustementTerm)
    if ecgIdAccuracy < 0:
        ecgIdAccuracy = 0.0

    # Compute Kendall correlation coefficients for regression tasks.
    # Any coefficients worse than chance will be clipped to zero.
    rrStdTau, _ = kendalltau(rrStd_pred, rrStd_true)
    if rrStdTau < 0:
        rrStdTau = 0.0

    prMeanTau, _ = kendalltau(prMean_pred, prMean_true)
    if prMeanTau < 0:
        prMeanTau = 0.0

    rtMeanTau, _ = kendalltau(rtMean_pred, rtMean_true)
    if rtMeanTau < 0:
        rtMeanTau = 0.0

    # Compute the final performance score as the geometric mean of the
    # individual task performances. A high geometric mean ensures that
    # there are no tasks with very poor performance that are masked by good
    # performance on the other tasks. If any task has chance performance
    # or worse, the overall performance will be zero. If all tasks are
    # perfectly solved, the overall performance will be 1.

    combinedPerformanceScore = np.power(
        rrStdTau * prMeanTau * rtMeanTau * ecgIdAccuracy, 0.25)

    return (
        combinedPerformanceScore,
        prMeanTau, rtMeanTau, rrStdTau, ecgIdAccuracy
    )

def example():
    prMean_pred = np.random.randn(480).astype(np.float32)
    prMean_true = (np.random.randn(480).astype(
        np.float32) / 10.0) + prMean_pred

    rtMean_pred = np.random.randn(480).astype(np.float32)
    rtMean_true = (np.random.randn(480).astype(
        np.float32) / 10.0) + rtMean_pred

    rrStd_pred = np.random.randn(480).astype(np.float32)
    rrStd_true = (np.random.randn(480).astype(np.float32) / 10.0) + rrStd_pred

    ecgId_pred = np.random.randint(low=0, high=32, size=(480,), dtype=np.int32)
    ecgId_true = np.random.randint(low=0, high=32, size=(480,), dtype=np.int32)

    print(
        scorePerformance(
            prMean_true, prMean_pred,
            rtMean_true, rtMean_pred,
            rrStd_true, rrStd_pred,
            ecgId_true, ecgId_pred
        )
    )

if __name__ == '__main__':

    example()


__author__ = 'oun1982'
from socket import *
from time import ctime

HOST = 'localhost'
PORT = 5000
BUFFER_SIZE = 1024
ADDRESS = (HOST,PORT)

server = socket(AF_INET,SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)

while True:
    print('waiting for connection...')
    client, address = server.accept()
    print('Connection from : ',address)
    data_byte = str.encode(ctime())
    client.send(data_byte)
    client.close()


#calss header
class _CASSETTE():
	def __init__(self,):
		self.name = "CASSETTE"
		self.definitions = [u'a flat rectangular device containing a very long strip of magnetic material that is used to record sound and/or pictures, or a machine that uses such devices: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'nouns'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


import pygame
### Screen Constants
TILE_SIZE = 64
SCREEN_WIDTH = TILE_SIZE * 16
SCREEN_HEIGHT = TILE_SIZE * 10

### Color Constants
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
GREY = (20, 20, 20)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)
BROWN = (160, 100, 60)

### IMAGE FILE NAMES ocated in /images
WALL_IMG_FILENAME = 'tile_11.png'
ZOMBIE_IMG_FILENAME = 'zombie1_hold.png'
PLAYER_IMG_FILENAME = 'manBlue_gun.png'
BULLET_IMG_FILENAME = 'circle_bullet.png'
FLASH_IMGS = ['flash00.png', 'flash01.png', 'flash02.png', 'flash03.png', 'flash04.png', 'flash05.png', 'flash06.png', 'flash07.png']
ITEM_IMGS = {'health' : 'health_pack.png'}

### PLAYER SETTINGS
PLAYER_SPEED = 250 # pixels per second
PLAYER_ROTATION_SPEED = 200 # degrees per second
GUN_BARREL_OFFSET = pygame.math.Vector2(28, 10)  # a vector to offset the bullets from center of player
PLAYER_HEALTH = 100

### BULLET SETTINGS
BULLET_SPEED = 500
BULLET_LIFE = 1000
FIRE_RATE = 200 # delay in fire
BULLET_SIZE = 6
BULLET_KICKBACK = 50
BULLET_SPREAD = 5
BULLET_DAMAGE = 10
BULLET_KNOCKBACK = 50

### ZOMBIE SETTINGS
ZOMBIE_ACCELERATION = [80, 90, 100, 110, 120] # pixels per second per second
ZOMBIE_HIT_BOX_SIZE = 30 # pixels by pixels
ZOMBIE_FRICTION = 0.4
ZOMBIE_HEALTH = 100
ZOMBIE_DAMAGE = 10
ZOMBIE_KNOCKBACK = 30
AVOID_RADIUS = 50

### SPECIAL EFFECTS
FLASH_TIME = 100
FLASH_SIZE = 20

### LAYERS
WALL_LAYER = 1
ITEMS_LAYER = 2
PLAYER_LAYER = 3
ZOMBIE_LAYER = 4
BULLET_LAYER = 5
EFFECTS_LAYER = 6

### ITEMS
HEALTH_PACK_AMT = 20
ITEM_BOB_RANGE = 15
ITEM_BOB_RATE = .4


import urllib.request
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
	def __init__(self):
		HTMLParser.__init__(self)
		self.to_show = 0
		self.tag_name = ''
		self.last_was_br = 0

		self.artist_name = ''
		self.song_name = ''
		self.file_name = ''

		self.lyrics = ''

		self.data = []
	def handle_starttag(self, tag, attrs):
		if tag == 'br':
			if not self.last_was_br:
				self.last_was_br = 1
			else:
				self.lyrics += '\n'
				self.last_was_br = 0;
		else:
			self.last_was_br = 0;
			for name, value in attrs:
				if name == 'class' and value == 'lyricbox':
					self.to_show = 1
					self.tag_name = tag
	def handle_data(self, data):
		self.last_was_br = 0;
		if self.to_show:
			self.lyrics += data
			self.lyrics += '\n'
	def handle_endtag(self, tag):
		if self.to_show and tag == self.tag_name:
			self.to_show = 0
			self.tag_name = ''

	def write_to_file(self):
		f = open(self.file_name, 'w')
		f.write('Artist: ' + self.artist_name + '\n')
		f.write('Song  : ' + self.song_name + '\n\n\n')
		f.write(self.lyrics)

print('- Inform artist name: ')
artist_name = input()
print('--- Inform song name: ')
song_name   = input()

artist_name_api = artist_name.replace(' ', '_')
song_name_api   =   song_name.replace(' ', '_')

with urllib.request.urlopen('http://lyrics.wikia.com/wiki/' + artist_name_api + ':' + song_name_api) as response:
	html = response.read().decode("utf-8")

	parser = MyHTMLParser()
	parser.artist_name = artist_name
	parser.song_name = song_name
	parser.file_name = artist_name_api + ':' + song_name_api
	parser.feed(html)
	parser.write_to_file()


from modules.base_module import Module

icon = "https://raw.githubusercontent.com/AvaCity/avacity-2.0/master/" \
       "readme/star.png"
class_name = "Support"

class Support(Module):
    prefix = "spt"

    def __init__(self, server):
        self.server = server
        self.commands = {"init": self.init, "gscnl": self.get_social_channels}

    def init(self, msg, client):
        client.send(["spt.init", {"a": False}])

    def get_social_channels(self, msg, client):
        channels = []
        channels.append({"act": True, "prt": 1, "id": 1, "stid": "github",
                         "dsctn": "Поставьте звёздочку ;(", "ttl": "GitHub",
                         "icnurl": icon,
                         "lnk": "https://github.com/AvaCity/avacity-2.0"})
        client.send(["spt.gscnl", {"scls": channels}])


from app.models import User, Rating
import plotly
import numpy as np
import pandas as pd
import plotly.graph_objs as go

def datetime(x):
    return np.array(x, dtype=np.datetime64)

def get_ratings(shortname, rating_type='elo'):
    user = User.query.filter_by(shortname=shortname).first()
    ratings = Rating.query \
        .filter_by(rating_type=rating_type) \
        .filter_by(user_id=user.id) \
        .order_by(Rating.timestamp).all()
    values = [r.rating_value for r in ratings]
    dates = datetime([r.timestamp for r in ratings])
    match_ids = [r.match_id for r in ratings]
    source = pd.DataFrame(dict(
        date=dates,
        rating=values,
        match_id=match_ids
    ))

    return source

def plot_ratings(shortname, rating_type):
    source = get_ratings(shortname, rating_type=rating_type)
    hover_text = []
    for index, row in source.iterrows():
        match_id = row['match_id']
        if pd.isnull(match_id):
            # To allow formatting of ids laters
            match_id = 0
        hover_text.append((
            "Match ID: {match_id}
"+
            "Time: {date}
"+
            "Rating: {rating}
").format(
                match_id = format(match_id, "1.0f") ,
                date = row["date"].ctime(),
                rating = format(row["rating"], "1.0f")
            ))

    data = go.Scatter(
            x = source.loc[:,"date"],
            y = source.loc[:,"rating"],
            text = hover_text,
            hoverinfo = 'text',
            marker = dict(
                color = 'green'
            ),
            showlegend = False
        )
    data_comp = [data]

    layout_comp = go.Layout(
        title='Performance over time',
        hovermode='closest',
        xaxis=dict(
            title='Time',
        ),
        yaxis=dict(
            title='Rating',
    ))

    fig_comp = go.Figure(data=data_comp, layout=layout_comp)
    div = plotly.offline.plot(fig_comp, show_link=False, output_type="div", include_plotlyjs=False)

    return div


import threading, traceback, sys

import g2o
import geometry as g
import numpy as np

class ControlableLock(object):
    def __init__(self, is_locking=True, verbose=False):
        self._lock = threading.Lock()
        self.is_locking = is_locking
        self.verbose = verbose

    def acquire(self):
        if(self.is_locking):
            if(self.verbose):
                print >>sys.stderr, "acquired", self
                #traceback.print_tb
            self._lock.acquire()

    def release(self):
        if(self.is_locking):
            if(self.verbose):
                print >>sys.stderr, "released", self
                #traceback.print_tb
            self._lock.release()

    def __enter__(self):
        self.acquire()

    def __exit__(self, type, value, traceback):
        self.release()

class g2oGraphBuilder():

    def __init__(self):
        self.optimizer = g2o.SparseOptimizer()
        # self.solver = g2o.BlockSolverX(g2o.LinearSolverDenseX())
        # self.solver = g2o.BlockSolverSE3(g2o.LinearSolverEigenSE3())
        self.solver = g2o.BlockSolverSE3(g2o.LinearSolverCholmodSE3())

        self.algorithm = g2o.OptimizationAlgorithmLevenberg(self.solver)
        self.optimizer.set_algorithm(self.algorithm)
        self.already_initialized = False
        self.last_lost = 0
        self.lock = ControlableLock(True)
        self.set_of_new_edges = set()
        self.set_of_new_vertex = set()
        self.has_removed = False

    def add_vertex(self, vertex_id, vertexPose, fixed=False):
        # print("add_vertex")
        # vertexPose has to be Isometry3D
        with self.lock:
            vc = g2o.VertexSE3()
            vc.set_id(vertex_id)
            vc.set_estimate(vertexPose)
            vc.set_fixed(fixed)

            self.optimizer.add_vertex(vc)
            self.set_of_new_vertex.add(vc)

    def add_edge(self, vertex0_id, vertex1_id, measure, measure_information=None, robust_kernel_value=None):
        '''
        Helper function to add an edge
        vertex 0 and 1 are valid IDs of vertex inside optimizer.
        measure is a Isometry3d that map the transform from vertex0 to vertex1
        '''

        ## TODO
        # robust kernels? They are made to reduce the impact of outliers.
        # They have to be specified separatly for each edge, with a value
        # example : robust_kernel = g2o.RobustKernelHuber(np.sqrt(5.991))
        #           edge.set_robust_kernel(robust_kernel)
        ##

        # print("add_edge")
        # print(optimizer.vertices())
        if vertex0_id in self.optimizer.vertices():

            with self.lock:

                if vertex1_id not in self.optimizer.vertices():
                    vc1 = g2o.VertexSE3()
                    vc1.set_id(vertex1_id)
                    vc1.set_estimate(
                        self.optimizer.vertex(vertex0_id).estimate() * measure)
                    vc1.set_fixed(False)
                    self.optimizer.add_vertex(vc1)
                    self.set_of_new_vertex.add(vc1)

                edge = g2o.EdgeSE3()
                edge.set_vertex(0, self.optimizer.vertex(vertex0_id))
                edge.set_vertex(1, self.optimizer.vertex(vertex1_id))
                edge.set_measurement(measure)

                if measure_information is not None:
                    edge.set_information(measure_information)

                if robust_kernel_value is not None:
                    robust_kernel = g2o.RobustKernelHuber(robust_kernel_value)
                    edge.set_robust_kernel(robust_kernel)

                self.optimizer.add_edge(edge)

                # Adding edge to set of new edge to update initialization
                self.set_of_new_edges.add(edge)

        else:
            if vertex1_id in self.optimizer.vertices():
                with self.lock:
                    vc0 = g2o.VertexSE3()
                    vc0.set_id(vertex0_id)
                    vc0.set_estimate(
                        self.optimizer.vertex(vertex1_id).estimate() *
                        measure.inverse())
                    vc0.set_fixed(False)
                    self.optimizer.add_vertex(vc0)

                    self.set_of_new_vertex.add(vc0)
                    edge = g2o.EdgeSE3()
                    edge.set_vertex(0, self.optimizer.vertex(vertex0_id))
                    edge.set_vertex(1, self.optimizer.vertex(vertex1_id))
                    edge.set_measurement(measure)
                    if (measure_information):
                        edge.set_information(measure_information)
                    # edge.set_information(np.eye(6) * 2)
                    finished = self.optimizer.add_edge(edge)
                    self.set_of_new_edges.add(edge)

            else:
                with self.lock:
                    vc0 = g2o.VertexSE3()
                    vc0.set_id(vertex0_id)
                    vc0.set_fixed(False)
                    self.optimizer.add_vertex(vc0)
                    self.set_of_new_vertex.add(vc0)

                self.add_edge(vertex0_id, vertex1_id, measure, robust_kernel_value=robust_kernel_value)

    def vertices_and_edges(self):
        return (self.optimizer.vertices(), self.optimizer.edges())

    def vertex_pose(self, vertexId):
        # print("vertex_pose")
        with self.lock:
            if (vertexId not in self.optimizer.vertices()):
                print("Vertex %i is not in the g2o graph" % vertexId)
                if (self.last_lost != 0 and
                        self.last_lost in self.optimizer.vertices()):
                    print(
                        "Vertex %i wasn't but is now in g2o graph" % self.last_lost)
                elif (self.last_lost != 0):
                    print("Vertex %i wasn't and still isn't in g2o graph" %
                        self.last_lost)
                self.last_lost = vertexId
        return (self.optimizer.vertex(vertexId).estimate())

    def set_fixed(self, vertexId):
        with self.lock:
            if (vertexId in self.optimizer.vertices()):
                self.optimizer.vertex(vertexId).set_fixed(True)
            else:
                print("Vertex %i is not in the g2o graph" % vertexId)

    def get_transform(self, vertex1, vertex2):
        # print("get_transform")
        with self.lock:
            if (vertex1 not in self.optimizer.vertices() or
                    vertex2 not in self.optimizer.vertices()):
                print("Requesting transform between non existant vertices")
                return 0
            vc1 = self.optimizer.vertex(vertex1).estimate()
            vc2 = self.optimizer.vertex(vertex2).estimate()
            transfom = vc1.inverse() * vc2
        return transfom

    def remove_vertex(self, vertex_id):
        # print("remove_vertex")

        with self.lock:
            self.has_removed = True
            # print("trying to remove %i" % vertex_id)
            if(vertex_id in self.optimizer.vertices()):
                vc = self.optimizer.vertex(vertex_id)
                # print("it is here, let's remove it")
                if(vc in self.set_of_new_vertex):
                    # print("removing %i or the set of new vertex" % vertex_id)
                    self.set_of_new_vertex.remove(vc)
                edge_to_remove = []
                for edge in self.set_of_new_edges:
                    # print(edge.vertices())
                    if vc in edge.vertices():
                        # print("edges to remove added edge")
                        if edge not in edge_to_remove:
                            edge_to_remove.append(edge)
                for edge in edge_to_remove:
                    self.set_of_new_edges.remove(edge)
                self.optimizer.remove_vertex(vc, detach=True)

                # print("success")
            else:
                print("was not in optimizer")

    def optimize(self,
                 number_of_steps,
                 verbose=True,
                 save_result=True,
                 output_name="output.g2o",
                 online=False):
        # print("optimize")
        with self.lock:
            self.optimizer.set_verbose(verbose)
            if (not self.already_initialized):

                self.optimizer.initialize_optimization()
                self.set_of_new_edges = set()
                self.set_of_new_vertex = set()
                self.already_initialized = True
                self.optimizer.compute_initial_guess()
            else:
                if(not self.has_removed):
                    self.optimizer.update_initialization(self.set_of_new_vertex,
                                                    self.set_of_new_edges)
                else:
                    self.optimizer.initialize_optimization()
                    self.has_removed = False
                self.set_of_new_edges = set()
                self.set_of_new_vertex = set()
                # self.optimizer.compute_initial_guess()
            self.optimizer.compute_active_errors()
            if (verbose):
                print('Optimization:')
                print('Initial chi2 = %f' % self.optimizer.chi2())
            self.optimizer.optimize(number_of_steps, online=online)

            if (save_result):
                self.optimizer.save(output_name)

        return self.optimizer.chi2()
        # batch_stat = self.optimizer.batch_statistics
        # print(batch_stat)


import Parser, CodeWriter, sys, glob
from Util import *

class VMTranslator:
    """ VM translater module """

    def __init__(self, file_list, file_out):
        '''
        Constructor
        Input: file_list (list of strings), file_out (string)
        '''
        self.files_in = file_list
        self.file_out = file_out

    def translate_all(self):
        '''
        Translates all the .vm files in file_list to assembly language
        and save the output to file_out.
        '''
        code_writer = CodeWriter.CodeWriter(self.file_out)
        for file_in in self.files_in:
            self.translate(file_in, code_writer)
        code_writer.close()

    def translate(self, file_in, code_writer):
        '''
        Translate a single .vm file. Called in self.translate_all().
        Input: file_in (string), code_writer (CodeWriter object)
        '''
        parser = Parser.Parser(file_in)
        code_writer.set_file_name(file_in)
        while parser.has_more_commands():
            parser.advance()
            arg1 = parser.arg1()
            # For project 07, only consider C_ARITHMETIC, C_PUSH and C_POP.
            if parser.command_type() == C_ARITHMETIC:
                code_writer.write_arithmetic(arg1)
            elif parser.command_type() in [C_PUSH, C_POP]:
                arg2 = parser.arg2()
                code_writer.write_push_pop(parser.command_type(), arg1, arg2)

if __name__ == "__main__":

    if len(sys.argv) != 2:
        print("Usage: python VMTranslator.py <file.vm|directory>")
    arg = sys.argv[1]

    # If the argument ends with ".vm", use it as the single input file.
    if arg.endswith(".vm"):
        file_list = [arg]
        file_out = arg.replace('.vm', '.asm')
    # Otherwise, consider the argument as a directory.
    else:
        if arg.endswith("/"):
            arg = arg[:-1]
        # Get a list of files ending with ".vm" from the directory.
        file_list = glob.glob(arg + "/*.vm")
        if len(file_list) == 0:
            print("""Error: No proper input file names found. Please use a file name ending with '.vm' or a directory containing '.vm' files.""")
            sys.exit()
        file_out = arg + ".asm"

    vm_translator = VMTranslator(file_list, file_out)
    vm_translator.translate_all()


# Copyright 2018,2019,2020,2021 Sony Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest
import nnabla as nn
import nnabla.parametric_functions as PF
import numpy as np
from nnabla.testing import assert_allclose

def ref_bcast(x_data_list, src):
    results = []
    for x_data in x_data_list:
        results.append(x_data * (src + 1))
    return results

@pytest.mark.parametrize("seed", [313])
@pytest.mark.parametrize("src", [0, 1])
@pytest.mark.parametrize("inplace", [True, False])
def test_bcast(seed, src, inplace, comm_nccl_opts):
    if comm_nccl_opts is None:
        pytest.skip(
            "Communicator test is disabled. You can turn it on by an option `--test-communicator`.")
    if len(comm_nccl_opts.devices) < 2:
        pytest.skip(
            "Communicator test is disabled. Use more than 1 gpus.")

    comm = comm_nccl_opts.comm
    device_id = int(comm_nccl_opts.device_id)
    n_devices = len(comm_nccl_opts.devices)

    # Variables
    x_list = []
    x_data_list = []
    num_layers = 20
    rng = np.random.RandomState(seed)
    for l in range(num_layers):
        x_data = rng.rand(3, 4)
        x_data_list.append(x_data)
        x = nn.Variable(x_data.shape)
        x.d = x_data * (device_id + 1)
        x_list.append(x)

    # Bcast
    comm.bcast([x.data for x in x_list], src, inplace=inplace)

    # Ref
    refs = ref_bcast(x_data_list, src)

    # Check
    for x, ref in zip(x_list, refs):
        assert_allclose(x.d, ref, rtol=1e-3, atol=1e-6)


from pizza import Pizza

def read_data(filename):
    """Read data from the specified file"""
    with open(filename, 'r') as f:
        content = f.read().splitlines()
    n_pizzas, teams_of2, teams_of3, teams_of4 = map(int, content[0].split(' '))

    menu = []

    for i in range(n_pizzas):
        menu.append(Pizza(i, content[i + 1].split(' ')[1:]))

    return menu, teams_of2, teams_of3, teams_of4

def calculate_score(order, pizza):
    """Calculate the score for the chosen pizzas"""
    unique_ingredients = set(pizza.ingredients)
    for p in order:
        unique_ingredients = unique_ingredients.union(p.ingredients)
    return len(unique_ingredients)

def process_order(team_of, teams_number, menu):
    """Process the order for the specified number of teams """
    orders = []
    while menu != [] and len(orders) < teams_number:
        score_max = 0
        team_order = []
        for _ in range(team_of):
            selected = None
            for pizza in menu:
                score = calculate_score(team_order, pizza)
                if score > score_max:
                    score_max = score
                    selected = pizza
            if selected is not None:
                team_order.append(selected)
                menu.remove(selected)
        if len(team_order) == team_of:
            orders.append((team_of, team_order))
    return orders

def write_data(outfile, orders):
    """Write results to the output file"""
    with open(outfile, 'w') as out:
        out.write(str(len(orders)) + '\n')
        for order in orders:
            indexes = ' '.join(str(pizza.index) for pizza in order[1])
            out.write(str(order[0]) + ' ' + indexes + '\n')

def deliver(filename, outfile):
    """Complete delivery for all teams"""
    menu, teams_of2, teams_of3, teams_of4 = read_data(filename)
    orders = []
    orders.extend(process_order(2, teams_of2, menu))
    orders.extend(process_order(3, teams_of3, menu))
    orders.extend(process_order(4, teams_of4, menu))
    write_data(outfile, orders)

if __name__ == '__main__':

    INPUT_PATH = './input'
    OUTPUT_PATH = './output'

    INPUT_SUFFIX = '.in'
    OUTPUT_SUFFIX = '.out'

    files = [
        'a_example',
        'b_little_bit_of_everything',
        'c_many_ingredients',
        'd_many_pizzas',
        'e_many_teams'
    ]

    for file in files:
        deliver(f'{INPUT_PATH}/{file + INPUT_SUFFIX}',
                f'{OUTPUT_PATH}/{file + OUTPUT_SUFFIX}')


# C - Guess The Number
# https://atcoder.jp/contests/abc157/tasks/abc157_c

N,M = list(map(int,input().split()))

digit_num_list = [list(map(int, input().split())) for i in range(0,M)]

# 最小数、最大数を作る。
min = ["1"]
for n in range(1,N):
    min.append("0")
min = int("".join(min))

max = []
for n in range(0,N):
    max.append("9")
max = int("".join(max))

# print(min)
# print(max)

# 求める整数
ans = ["0"]*N
# print(len(ans))

# M桁目まで検証すればよい。
for i in range(min,max):
    cnt = 0
    for digit_num in digit_num_list:

        # # print("=========")
        # # print(digit_num)
        # # print(str(i))
        # # print(digit_num[0])
        # # print(str(i)[digit_num[0]]-1)
        # # print("=========")

        # print("=========")
        # print(int(str(i)[digit_num[0]-1]))
        # print(digit_num[1])
        # print(i)
        # print("=========")

        if int(str(i)[digit_num[0]-1]) == digit_num[1]:
            ans[digit_num[0]-1] = str(digit_num[1])
            print(ans)
            cnt += 1
        else:
            break

        print("".join(ans))
        exit()

    if cnt == N:
        print("".join(ans))
        exit()

print(-1)


# Runtime: 984ms
# Your runtime beats 53.26% of python submissions.

class Solution(object):
  def isMatch(self, s, p):
    """
    :type s: str
    :type p: str
    :rtype: bool
    """
    if len(s) != 0 and len(p) != 0 and s[0] != p[0] and p[0] != '*' and p[0] != '?': return False
    p_ = ''
    for letter in p:
      if letter != '*' or not len(p_) or p_[-1] != '*': p_ += letter
    p = p_
    table = []
    for i in range(len(s)):
      table.append([])
      for j in range(len(p)): table[i].append(-1)
    def match(i, j):
      if i == -1 and j == -1: return True
      elif i == -1 and j != -1:
        if set(p[:j + 1]) == set(['*']): return True
        return False
      elif i != -1 and j == -1: return False
      if table[i][j] != -1: return table[i][j]
      if s[i] == p[j] or p[j] == '?': table[i][j] = match(i - 1, j - 1)
      elif p[j] == '*':
        table[i][j] = False
        for k in range(-1, i + 1):
          if match(k, j - 1):
            table[i][j] = True
            break
      else:
        table[i][j] = False
      return table[i][j]
    return match(len(s) - 1, len(p) - 1)


import warnings
import pprint
from contextlib import suppress

from bonobo.config import Option, Service, Configurable, use

from cromulent import model, vocab

from pipeline.linkedart import add_crom_data, get_crom_object, \
			MakeLinkedArtLinguisticObject

#mark - Physical Catalogs

class AddAuctionCatalog(Configurable):
	helper = Option(required=True)
	non_auctions = Service('non_auctions')

	def __call__(self, data:dict, non_auctions):
		'''Add modeling for auction catalogs as linguistic objects'''
		cno = data['catalog_number']
		rec_num = data['star_record_no']

		# this information may either come from `data` (for the auction events branch of the pipeline)
		# or from `non_auctions` (for the catalogs branch, which lacks this information,
		# but will have access to the `non_auctions` service which was shared from the events branch)
		sale_type = non_auctions.get(cno, data.get('non_auction_flag'))
		if sale_type:
			non_auctions[cno] = sale_type
		sale_type = sale_type or 'Auction'
		catalog = self.helper.catalog_text(cno, sale_type)

		content = data['star_csv_data']
		row = vocab.Transcription(ident='', content=content)
		row.part_of = self.helper.static_instances.get_instance('LinguisticObject', 'db-sales_events')
		creation = vocab.TranscriptionProcess(ident='')
		creation.carried_out_by = self.helper.static_instances.get_instance('Group', 'gpi')
		row.created_by = creation
		row.identified_by = self.helper.gpi_number_id(rec_num, vocab.StarNumber)

		catalog._validate_profile = False
		catalog.features_are_also_found_on = row

		cdata = {'uri': catalog.id}
		puid = data.get('persistent_puid')
		if puid:
			puid_id = self.helper.gpi_number_id(puid)
			catalog.identified_by = puid_id
			cdata['identifiers'] = [puid_id]

		data['_catalog'] = add_crom_data(data=cdata, what=catalog)
		yield data

class AddPhysicalCatalogObjects(Configurable):
	helper = Option(required=True)
	non_auctions = Service('non_auctions')

	def __call__(self, data:dict, non_auctions):
		'''Add modeling for physical copies of an auction catalog'''
		catalog = get_crom_object(data['_catalog'])
		record = get_crom_object(data['_catalog_record'])
		cno = data['catalog_number']
		owner = data['owner_code']
		copy = data['copy_number']
		sale_type = non_auctions.get(cno, 'Auction')
		catalogObject = self.helper.physical_catalog(cno, sale_type, owner, copy, add_name=True)
		catalogObject.referred_to_by = record
		data['uri'] = catalogObject.id
		info = data.get('annotation_info')
		if info:
			catalogObject.referred_to_by = vocab.Note(ident='', content=info)
		catalogObject.carries = catalog

		add_crom_data(data=data, what=catalogObject)
		return data

class AddPhysicalCatalogOwners(Configurable):
	helper = Option(required=True)
	location_codes = Service('location_codes')
	unique_catalogs = Service('unique_catalogs')

	def __call__(self, data:dict, location_codes, unique_catalogs):
		'''Add information about the ownership of a physical copy of an auction catalog'''
		# Add the URI of this physical catalog to `unique_catalogs`. This data will be used
		# later to figure out which catalogs can be uniquely identified by a catalog number
		# and owner code (e.g. for owners who do not have multiple copies of a catalog).
		cno = data['catalog_number']
		owner_code = data['owner_code']
		copy_number = data.get('copy_number', '')
		owner_name = None
		entry_record = get_crom_object(data.get('_catalog'))
		with suppress(KeyError):
			owner_name = location_codes[owner_code]
			owner_uri = self.helper.make_proj_uri('ORGANIZATION', 'LOCATION-CODE', owner_code)
			data['_owner'] = {
				'label': owner_name,
				'uri': owner_uri,
				'referred_to_by': [entry_record],
				'identifiers': [
					model.Name(ident='', content=owner_name),
					model.Identifier(ident='', content=str(owner_code))
				],
			}
			owner = model.Group(ident=owner_uri)
			owner.referred_to_by = entry_record
			add_crom_data(data['_owner'], owner)
			if not owner_code:
				warnings.warn(f'Setting empty identifier on {owner.id}')
			add_crom_data(data=data['_owner'], what=owner)
			catalog = get_crom_object(data)
			catalog.current_owner = owner

		owner_uri = self.helper.physical_catalog_uri(cno, owner_code, None) # None here because we want a key that will stand in for all the copies belonging to a single owner
		copy_uri = self.helper.physical_catalog_uri(cno, owner_code, copy_number)
		unique_catalogs[owner_uri].add(copy_uri)
		return data

#mark - Physical Catalogs - Informational Catalogs

class PopulateAuctionCatalog(Configurable):
	'''Add modeling data for an auction catalog'''
	helper = Option(required=True)
	static_instances = Option(default="static_instances")

	def lugt_number_id(self, content):
		lugt_number = str(content)
		lugt_id = vocab.LocalNumber(ident='', label=f'Lugt Number: {lugt_number}', content=lugt_number)
		assignment = model.AttributeAssignment(ident='')
		assignment.carried_out_by = self.static_instances.get_instance('Person', 'lugt')
		lugt_id.assigned_by = assignment
		return lugt_id

	def __call__(self, data):
		d = {k: v for k, v in data.items()}
		parent = data['parent_data']
		cno = str(parent['catalog_number'])
		sno = parent['star_record_no']
		entry_record = get_crom_object(data.get('_catalog'))
		catalog = get_crom_object(d)
		for lugt_no in parent.get('lugt', {}).values():
			if not lugt_no:
				warnings.warn(f'Setting empty identifier on {catalog.id}')
			catalog.identified_by = self.lugt_number_id(lugt_no)

		for seller_verbatim in parent.get('title_pg_sell', {}).values():
			catalog.referred_to_by = vocab.TitlePageText(ident='', content=seller_verbatim)

		if not cno:
			warnings.warn(f'Setting empty identifier on {catalog.id}')

		catalog.identified_by = self.helper.gpi_number_id(cno, vocab.LocalNumber)

		if not sno:
			warnings.warn(f'Setting empty identifier on {catalog.id}')
		catalog.identified_by = self.helper.gpi_number_id(sno, vocab.StarNumber)
		notes = data.get('notes')
		if notes:
			note = vocab.Note(ident='', content=parent['notes'])
			catalog.referred_to_by = note
		return d

class AddAuctionCatalogEntry(Configurable):
	helper = Option(required=True)
	non_auctions = Service('non_auctions')

	def __call__(self, data:dict, non_auctions):
		'''Add modeling for auction catalogs as linguistic objects'''
		cno = data['auction_of_lot']['catalog_number']
		rec_num = data['pi_record_no']
		record_uri = self.helper.make_proj_uri('CATALOG', cno, 'RECORD', rec_num)
		record = vocab.ParagraphText(ident=record_uri, label=f'Sale recorded in catalog (record number {rec_num})')
		data['_sale_record'] = add_crom_data({'uri': record_uri}, record)

		page_id = data.get('pg')
		pdf_page_id = data.get('ppg')
		if not page_id:
			yield data
			return

		sale_type = non_auctions.get(cno, data.get('non_auction_flag'))
		if sale_type:
			non_auctions[cno] = sale_type
		sale_type = sale_type or 'Auction'
		catalog = self.helper.catalog_text(cno, sale_type)

		cdata = add_crom_data(data={'uri': catalog.id}, what=catalog)
		idents = [
			vocab.PageNumber(ident='', content=page_id),
		]
		if pdf_page_id:
			idents.append(vocab.make_multitype_obj(vocab.PageNumber, vocab.OrderNumber, ident='', content=pdf_page_id, label=f'Page Order'))
		data['_text_page'] = {
			'uri': self.helper.make_proj_uri('CATALOG', cno, 'Page', page_id),
			'object_type': [vocab.PageTextForm,self.helper.catalog_type(cno,sale_type)],
			'label': f'Sale Catalog {cno}, Page {page_id}',
			'identifiers': idents,
			'referred_to_by': [],
			'part_of': [cdata],
			'part': [],
		}

		mlo = MakeLinkedArtLinguisticObject()
		mlo(data['_text_page'])

		yield data

class AddPhysicalCatalogEntry(Configurable):
	helper = Option(required=True)
	non_auctions = Service('non_auctions')

	def __call__(self, data:dict, non_auctions):
		'''Add modeling for the entry describing a physical auction catalog in the PSCP dataset.'''
		cno = data['catalog_number']
		owner = data['owner_code']
		copy = data['copy_number']
		rec_num = data['star_record_no']
		sale_type = non_auctions.get(cno, data.get('non_auction_flag', 'Auction'))
		keys = [v for v in [cno, owner, copy] if v]
		record_uri = self.helper.make_proj_uri('ENTRY', 'PHYS-CAT', *keys)
		content = data['star_csv_data']

		catalog_label = self.helper.physical_catalog_label(cno, sale_type, owner, copy)
		row_name = f'STAR Entry for Physical {catalog_label}'
		row = vocab.EntryTextForm(ident=record_uri, content=content, label=row_name)
		row.part_of = self.helper.static_instances.get_instance('LinguisticObject', 'db-sales_catalogs')
		creation = model.Creation(ident='')
		creation.carried_out_by = self.helper.static_instances.get_instance('Group', 'gpi')
		row.created_by = creation
		row.identified_by = self.helper.gpi_number_id(rec_num, vocab.StarNumber)
		row.identified_by = vocab.PrimaryName(ident='', content=row_name)
		er_classification = model.Type(ident='http://vocab.getty.edu/aat/300379790', label='Electronic Records')
		er_classification.classified_as = vocab.instances["object type"]
		row.classified_as = er_classification
		data['_catalog_record'] = add_crom_data({'uri': record_uri}, row)

		yield data


# Data Engineering Trial Task
# Created by: Kovács Balázs

import datetime
import json
from google.cloud import pubsub_v1
import os.path
from os import path

# We are saving the aggregates to an internal text file.
# If it already exists, just delete it.

if path.exists('hourly.txt'):
    os.remove('hourly.txt')

# Creating an infinite loop, so the program runs continuously
while True:

    # Variables where we store the number of rides
    total = 0
    pickups = 0
    dropoffs = 0

    # We put every ID in this variable
    msgt = []

    try:

        # Creating subscription
        subscriber = pubsub_v1.SubscriberClient()
        subscription_path = subscriber.subscription_path('ems-dp-candidates', 'taxirides-kb-321783763627')

        # Callback method
        def callback(message):
            global pickups, dropoffs, total, msgt

            if message.attributes:

                msg = bytes.decode(message.data)
                jsonmsg = json.loads(msg)

                # if the ID exists in 'msgt', that means we already have this data, so we go the next iteration
                # and we won't have duplicates of the rows.
                if jsonmsg['ride_id'] in msgt:
                    message.nack()
                    return

                msgt.append(jsonmsg['ride_id'])

                # Counting total rides, pickups and dropoffs
                total += 1

                if jsonmsg['ride_status'] == 'pickup':
                    pickups += 1
                if jsonmsg['ride_status'] == 'dropoff':
                    dropoffs += 1

            message.ack()

        streaming_pull_future = subscriber.subscribe(
            subscription_path, callback=callback
        )

        # Pulling data for an hour
        streaming_pull_future.result(timeout=3600)

    except:
        # Saving aggregates to file
        f = open('hourly.txt', "a")
        f.write('Total: ' + str(total))
        f.write(' Dropoffs: ' + str(dropoffs))
        f.write(' Pickups: ' + str(pickups) + '\n')
        f.close()


y = True
z = True
a = 0
c = 1
print("Let's play a game! Think of a number in your head.")
print("")
print("Make sure to answer in 'y' (yes) or 'n' (no) format")
print("")

while z == True:
	print("Is the number greater than {0}?".format(c))
	answer1 = input()
	if answer1 == "y":
		c = c*2
	if answer1 == "n":
		z = False

b = (a + c)/2

print("")
print("Now make sure to answer in 'g' (greater than), 'e'(equal to), 'l' (less than) format")

while y == True:
	print("")
	print("Is the number greater than, equal or less than {0}?".format(b))
	answer2 = input()
	if answer2 == "g":
		a = b
		b = int((b + c)/2)
	if answer2 == "l":
		c = b
		b = int((b + a)/2)
	if answer2 == "e":
		print("")
		print("I found your number!")
		y = False


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

import argparse
import params
import random
from utils import *
from sklearn.svm import SVC
from models import trainer, predictor

def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def main():

	params.print_params()
	parser = argparse.ArgumentParser()
	parser.add_argument('--local_test', type=str2bool, default=False, help='local test verbose')
	parser.add_argument('--src_id', type=int, default=0, help='source domain id')
	parser.add_argument('--tar_id', type=int, default=2, help='target domain id')
	args = parser.parse_args()

	print ('source domain:', params.domains[args.src_id])
	print ('target domain:', params.domains[args.tar_id])
	print ('===> ' + 'Start Running')

	avg_acc_svm = 0.0
	avg_acc_tr = 0.0

	train_doc, train_labels = Doc(params.domains[args.src_id], args)
	test_doc, test_labels = Doc(params.domains[args.tar_id], args)
	# print ('train data:', len(train_doc), len(train_labels)) # _, _,
	# print ('test data:', len(test_doc), len(test_labels)) # _, _,

	total_train_num = params.train_num * 2
	data_mat = Format(train_doc[:total_train_num] + test_doc[total_train_num:total_train_num+params.unlabel[args.tar_id]])

	data_train = data_mat[:total_train_num]
	label_train = train_labels[:total_train_num]

	data_test = data_mat[total_train_num:total_train_num+params.unlabel[args.tar_id]]
	label_test = test_labels[total_train_num:total_train_num+params.unlabel[args.tar_id]]

	print ('===> ' + 'Data Loaded')

	for k in range(params.rep):

		### pick small set of labeled data in target domain
		# random_list = random.sample(range(params.unlabel[args.tar_id]), params.num_data_target)

		# load pre-selected samples for books -> electronics
		# np.save('./data/b2e.npy',random_list)
		random_list = np.load('./data/b2e.npy')

		Ts = []
		l = []
		zero_cnt = 0
		one_cnt = 0
		for i in random_list:
			Ts.append(data_test[i])
			l.append(label_test[i])
			# print (label_test[i])
			if label_test[i] == -1:
				zero_cnt += 1
			else:
				one_cnt += 1

		print ()
		print (zero_cnt, one_cnt)

		Ts = np.array(Ts)
		l = np.array(l)
		data_train = np.concatenate((data_train, Ts))
		label_train = np.concatenate((label_train, l))
		data_test = np.array(data_test)
		label_test = np.array(label_test)

		if args.local_test:
			print ('train data:', data_train.shape, label_train.shape)
			print ('test data:', data_test.shape, label_test.shape)

		print ('repetition {:}:'.format(k+1))
		### our methods ###
		weakClassArr = trainer(data_train, label_train, args, params.numIt)
		acc = predictor(data_test, label_test, weakClassArr)
		print ('ours: ', acc)
		avg_acc_tr += acc

		### svm classifier (baseline) ###
		clf = SVC(gamma='auto', kernel='rbf')
		clf.fit(data_train, label_train)
		pred = clf.predict(data_test)
		acc = evaluate(pred, label_test)
		print ('svm: ', acc)
		avg_acc_svm += acc

	print ('\naverage results:')
	print ('avg acc ours:', avg_acc_tr / params.rep)
	print ('avg acc svm:', avg_acc_svm / params.rep)
	print ()

if __name__ == '__main__':
    main()


aceleracao = float(input("Digite o valor de aceleracao: "))
v0 = float(input("Digite a velocidade inicial: "))
T = float(input("Digite o valor de tempo do percurso: "))
V = v0 + (aceleracao *T)

if (V <= 40):
            print("Veículo muito lento.")

elif(V <= 60):
    print("Velocidade permitida.")

elif(V <= 80):
    print("Velocidade de cruzeiro.")

elif(V <= 120):
    print("Veículo rápido.")

elif(V > 120):
    print("Veículo muito rápido.")

else:
    print("Digite um valor válido. ")