import numpy as np
import pandas as pd
from sklearn.metrics import precision_recall_fscore_support

def collect_labels(file_address):
    '''
    Collects predicted/actual labels from file at file address.
    Returns list of labels for each text.
    '''
    with open(file_address) as f:
        content = f.readlines()
    labels = [c.split(' ')[0] for c in content]
    return labels

def score_labels(test_labels, predict_labels, label_set):
    '''
    Prints and returns mean scores of lists of labels.
    IN:
    test_labels - list of actual labels
    predict_labels - list of predicted labels
    label_set - set of labels to be tallied in evaluation
    OUT: scores from evaluation by SkLearn
    '''
    precision, recall, fscore, support = precision_recall_fscore_support(test_labels, predict_labels, average=None, labels=label_set)

    print('precision: {}'.format(precision.mean()))
    print('recall: {}'.format(recall.mean()))
    print('fscore: {}'.format(fscore.mean()))
#     print('support: {}'.format(support))

    return precision, recall, fscore, support

def score_txtfiles(test_address, predict_address):
    '''
    IN:
    test_address - test file
    pred_address - file of predictions
    label_set - set of labels to be tallied in evaluation
    OUT: scores from evaluation by SkLearn
    '''
    test_labels = collect_labels(test_address)
    predict_labels = collect_labels(predict_address)
    label_set = sorted(list(set(test_labels)))

    precision, recall, fscore, support = score_labels(test_labels, predict_labels, label_set)

    return precision, recall, fscore, support

def score_columns(df, test_column, predict_column):
    '''
    IN:
    df - dataframe of labels and predictions
    test_column - column name of actual labels
    predict_column - column name of predicted labels
    label_set - set of labels to be tallied in evaluation
    OUT: scores from evaluation by SkLearn
    '''
    test_labels = df[test_column]
    predict_labels = df[predict_column]
    label_set = sorted(list(set(test_labels)))

    precision, recall, fscore, support = score_labels(test_labels, predict_labels, label_set)

    return precision, recall, fscore, support


from sklearn.svm import LinearSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import train_test_split
from keras.layers import Dense, Dropout
from keras.models import Sequential
from xgboost import XGBClassifier
import pandas as pd
from imblearn.over_sampling import SMOTE
from common_functions import SentimentScores, convert_label_to_value

class SentimentClassifier(object):
    def __init__(self):
        self.X_train_BOW = None
        self.y_train = None
        self.X_test_BOW = None
        self.y_test = None
        self.num_features = 2000  # number of BOW entries
        self.test_pct = .3      # % of records to be used to test vs train
        self.features = None

    def run_classifier(self, clf):
        scores = SentimentScores(str(clf))
        clf.fit(self.X_train_BOW, self.y_train)
        n = self.y_test.shape[0] - 1
        for i in range(0, n):
            val = clf.predict(self.X_test_BOW[i:i + 1])[0]
            gt = self.y_test[i]
            scores.update(val, gt)
        scores.output_results()

        if 'DecisionTree' in str(clf):
            deciding_features = clf.tree_.feature
            scores.write_string_to_outfile('Top Decision Tree Features:\n')
            for i in range(0, 10):
                scores.write_string_to_outfile(self.features[deciding_features[i]] + "\n")

    def keras_classifier(self, epochs):
        nn_model = Sequential()  # The Sequential model is the simpler of the two types of Keras models
        nn_model.add(Dense(self.num_features, input_dim=self.num_features, activation='relu'))  # Add a hidden layer with ReLU activation
        nn_model.add(Dropout(.15))
        nn_model.add(Dense(1))  # Add an output layer
        nn_model.compile(loss="mse", optimizer="adam")  # Compile the model using mean-squared error as the error function and stochastic gradient descent
        nn_model.fit(self.X_train_BOW, self.y_train, verbose=0, epochs=epochs)
        predict = nn_model.predict(self.X_test_BOW)
        scores = SentimentScores('keras')
        n = self.y_test.shape[0] - 1
        for i in range(0, n):
            pred = predict[i][0]
            if pred < -.3333:
                val = -1
            elif pred > .3333:
                val = 1
            else:
                val = 0
            gt = self.y_test[i]
            scores.update(val, gt)
        scores.output_results()

    def classify(self, lassifier_type):
        df_all = pd.read_csv('/home/data/tweets_preprocessed.txt', header=0, names=['sentiment', 'review'])
        sentiment = df_all['sentiment']
        df_all['sentiment'] = sentiment.map(convert_label_to_value)
        X = df_all['review'].values
        y = df_all['sentiment'].values
        X_train, X_test, self.y_train, self.y_test = train_test_split(X, y, test_size=.3, stratify=y)

        cv = CountVectorizer(ngram_range=(1,3), max_features=self.num_features)
        cv.fit(X_train)
        self.X_train_BOW = cv.transform(X_train)
        self.X_test_BOW = cv.transform(X_test)
        self.features = cv.get_feature_names()

        # Upsample for equal class sizes in training data
        sm = SMOTE()
        self.X_train_BOW, self.y_train = sm.fit_resample(self.X_train_BOW, self.y_train)

        if classifier_type == 'naive_bayes':
            self.run_classifier(MultinomialNB())
        elif classifier_type == 'decision_tree':
            clf = DecisionTreeClassifier()
            self.run_classifier(clf)
        elif classifier_type == 'xgboost':
            self.run_classifier(XGBClassifier())
        elif classifier_type == 'svc':
            self.run_classifier(LinearSVC())
        elif classifier_type == 'nearest_neighbor':
            self.run_classifier(KNeighborsClassifier())
        elif classifier_type == 'mlp':
            self.run_classifier(MLPClassifier())
        elif classifier_type == 'neural_network':
            for epochs in (5, 10, 20, 50):
                self.keras_classifier(epochs)
        elif classifier_type == 'all':
            for clf in (MultinomialNB(), DecisionTreeClassifier(random_state=0), XGBClassifier(), LinearSVC(random_state=0), KNeighborsClassifier()):
                self.run_classifier(clf)
            for epochs in (5, 10, 20, 50):
                self.keras_classifier(epochs)

sc = SentimentClassifier()
sc.classify('summary', 'all')
sc.classify('tweets', 'all')
sc.classify('detail', 'all')


import logging
import os
import sys
from collections import Counter
from typing import Iterable

import tensorflow as tf
from tensorflow.keras import backend as K

def learning_rate_scheduler(num_epochs, max_learning_rate, min_learninga_rate=1e-7):
    lr_delta = (max_learning_rate - min_learninga_rate) / num_epochs

    def _scheduler(epoch, lr):
        return max_learning_rate - lr_delta * epoch

    return _scheduler

def get_logger():
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(logging.Formatter("[%(asctime)s] %(message)s"))
    logger.addHandler(handler)
    return logger

def path_join(*paths: Iterable[str]) -> str:
    """ Join paths to string local paths and google storage paths also """
    if paths[0].startswith("gs://"):
        return "/".join([path.strip("/") for path in paths])
    return os.path.join(*paths)

def get_device_strategy(device) -> tf.distribute.Strategy:
    """ Return tensorflow device strategy """
    # Use TPU
    if device.upper() == "TPU":
        resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=os.environ["TPU_NAME"])
        tf.config.experimental_connect_to_cluster(resolver)
        tf.tpu.experimental.initialize_tpu_system(resolver)
        strategy = tf.distribute.TPUStrategy(resolver)

        return strategy

    # Use GPU
    if device.upper() == "GPU":
        devices = tf.config.list_physical_devices("GPU")
        if len(devices) == 0:
            raise RuntimeError("Cannot find GPU!")
        for device in devices:
            tf.config.experimental.set_memory_growth(device, True)
        if len(devices) > 1:
            strategy = tf.distribute.MirroredStrategy()
        else:
            strategy = tf.distribute.OneDeviceStrategy("/gpu:0")

        return strategy

    # Use CPU
    return tf.distribute.OneDeviceStrategy("/cpu:0")

def n_gram_precision(true_tokens, pred_tokens, n):
    true_n_grams = []
    pred_n_grams = []

    for i in range(len(true_tokens) - n + 1):
        true_n_grams.append(tuple(true_tokens[i : i + n]))
    for i in range(len(pred_tokens) - n + 1):
        pred_n_grams.append(tuple(pred_tokens[i : i + n]))

    true_n_gram_counter = Counter(true_n_grams)
    pred_n_gram_counter = Counter(pred_n_grams)

    correct = 0
    for true_n_gram in true_n_gram_counter:
        correct += min(pred_n_gram_counter[true_n_gram], true_n_gram_counter[true_n_gram])
    return correct / len(true_n_grams)

def calculat_bleu_score(true_tokens, pred_tokens):
    n_gram_score = 1.0
    for n in range(1, 5):
        n_gram_score *= n_gram_precision(true_tokens, pred_tokens, n)
    n_gram_score **= 0.25

    brevity_penalty = min(1.0, len(pred_tokens) / len(true_tokens))

    return n_gram_score * brevity_penalty


import re
from collections import defaultdict, namedtuple
from typing import List, Set
from pathlib import Path

INPUT_FILE = Path(__file__).with_suffix(".input")

RE_NUMS = re.compile(r"-?\d+")

Coord = namedtuple("Coord", ["x", "y", "z", "t"])

def parse_input(instructions: str) -> List[Coord]:
    points = []
    for line in instructions.strip().split("\n"):
        points.append(Coord(*list(map(int, RE_NUMS.findall(line)))))
    return points

def calc_distance(loc1: Coord, loc2: Coord) -> int:
    return abs(loc1.x - loc2.x) + abs(loc1.y - loc2.y) + abs(loc1.z - loc2.z) + abs(loc1.t - loc2.t)

def part_1(list_o_stars: List[Coord]) -> List[Set[Coord]]:
    stars_within_range = defaultdict(set)
    for i, star1 in enumerate(list_o_stars):
        for star2 in list_o_stars[i + 1 :]:
            if calc_distance(star1, star2) <= 3:
                stars_within_range[star1].add(star2)

    constellations = []
    for star in list_o_stars:
        star_set = stars_within_range[star]
        star_set.add(star)

        found_constellations = []
        for i, const in enumerate(constellations):
            for neighbor_star in star_set:
                if neighbor_star in const:
                    found_constellations.append(i)
                    break
        if not found_constellations:
            found_const = set()
            constellations.append(found_const)
        else:
            first, *rest = found_constellations
            rest.sort(reverse=True)
            found_const = constellations[first]
            for i in rest:
                found_const |= constellations[i]
                del constellations[i]
        found_const |= star_set

    return constellations

if __name__ == "__main__":
    DATA = INPUT_FILE.read_text().strip()
    print(len(part_1(parse_input(DATA))))


import argparse
import sys
import datetime

from pyramid.paster import bootstrap, setup_logging
from sqlalchemy.exc import OperationalError

from .. import models

def setup_models(dbsession):

    # Grupo
    administrador = models.Grupo(nombre='Administrador')
    dbsession.add(administrador)
    cooperativa = models.Grupo(nombre='Cooperativa')
    dbsession.add(cooperativa)
    cliente = models.Grupo(nombre='Cliente')
    dbsession.add(cliente)

    # Menu
    menu1 = models.Menu(nombre='Boletos', url='', grupo=administrador)
    dbsession.add(menu1)
    menu2 = models.Menu(nombre='Pasajes', url='', grupo=administrador)
    dbsession.add(menu2)
    menu3 = models.Menu(nombre='Boletos', url='', grupo=cooperativa)
    dbsession.add(menu3)
    menu4 = models.Menu(nombre='Pasajes', url='', grupo=cooperativa)
    dbsession.add(menu4)
    menu5 = models.Menu(nombre='Boletos', url='', grupo=cliente)
    dbsession.add(menu5)
    menu6 = models.Menu(nombre='Cuentas', url='', grupo=administrador)
    dbsession.add(menu6)
    menu7 = models.Menu(nombre='Cuentas', url='', grupo=cooperativa)
    dbsession.add(menu7)
    menu8 = models.Menu(nombre='Cooperativa', url='', grupo=administrador)
    dbsession.add(menu8)
    menu9 = models.Menu(nombre='Cooperativa', url='', grupo=cooperativa)
    dbsession.add(menu9)

    # Item
    item1 = models.Item(nombre='Comprar boletos', url='#!/inicio', es_menu=False, menu=menu1)
    dbsession.add(item1)
    item2 = models.Item(nombre='Listar boletos comprados', url='#!/mis-boletos', es_menu=False, menu=menu1)
    dbsession.add(item2)
    item_crear = models.Item(nombre='Crear pasaje', url='#!/add-pasaje', es_menu=False, menu=menu2)
    dbsession.add(item_crear)
    item3 = models.Item(nombre='Listar pasajes', url='#!/list-pasajes', es_menu=False, menu=menu2)
    dbsession.add(item3)
    item4 = models.Item(nombre='Comprar boletos', url='#!/inicio', es_menu=False, menu=menu3)
    dbsession.add(item4)
    item5 = models.Item(nombre='Listar boletos comprados', url='#!/mis-boletos', es_menu=False, menu=menu3)
    dbsession.add(item5)
    item_crear = models.Item(nombre='Crear pasaje', url='#!/add-pasaje', es_menu=False, menu=menu4)
    dbsession.add(item_crear)
    item6 = models.Item(nombre='Listar pasajes', url='#!/list-pasajes', es_menu=False, menu=menu4)
    dbsession.add(item6)
    item7 = models.Item(nombre='Comprar boletos', url='#!/inicio', es_menu=False, menu=menu5)
    dbsession.add(item7)
    item8 = models.Item(nombre='Listar boletos comprados', url='#!/mis-boletos', es_menu=False, menu=menu5)
    dbsession.add(item8)
    item9 = models.Item(nombre='Crear cuentas', url='#!/registro', es_menu=False, menu=menu6)
    dbsession.add(item9)
    item10 = models.Item(nombre='Crear cuentas', url='#!/registro', es_menu=False, menu=menu7)
    dbsession.add(item10)
    item11 = models.Item(nombre='Crear cooperativa', url='#!/add-cooperativa', es_menu=False, menu=menu8)
    dbsession.add(item11)
    item12 = models.Item(nombre='Crear cooperativa', url='#!/add-cooperativa', es_menu=False, menu=menu9)
    dbsession.add(item12)
    item13 = models.Item(nombre='Crear unidad', url='#!/add-unidad', es_menu=False, menu=menu8)
    dbsession.add(item13)
    item14 = models.Item(nombre='Crear unidad', url='#!/add-unidad', es_menu=False, menu=menu9)
    dbsession.add(item14)

    # User
    u_administrador = models.User(username='admin',
                                  nombre='Admin',
                                  apellido='Admin',
                                  email='admin@gmail.com',
                                  activo=True,
                                  cod_verificacion=None,
                                  grupo=administrador)
    u_administrador.set_password('admin')
    dbsession.add(u_administrador)
    cooperativa_loja = models.User(username='loja',
                                   nombre='Loja',
                                   apellido='Loja',
                                   email='loja@gmail.com',
                                   activo=True,
                                   cod_verificacion=None,
                                   grupo=cooperativa)
    cooperativa_loja.set_password('loja')
    dbsession.add(cooperativa_loja)
    cooperativa_cariamanga = models.User(username='cariamanga',
                                         nombre='Cariamanga',
                                         apellido='Cariamanga',
                                         email='cariamanga@gmail.com',
                                         activo=True,
                                         cod_verificacion=None,
                                         grupo=cooperativa)
    cooperativa_cariamanga.set_password('cariamanga')
    dbsession.add(cooperativa_cariamanga)
    basic = models.User(username='juan',
                        nombre='Juan',
                        apellido='Perez',
                        email='juanperez@gmail.com',
                        activo=True,
                        cod_verificacion=None,
                        grupo=cliente)
    basic.set_password('juan')
    dbsession.add(basic)

    # Sitio
    loja = models.Sitio(ciudad='Loja', terminal='Av. Isidro Ayora')
    dbsession.add(loja)
    quito = models.Sitio(ciudad='Quito', terminal='Quitumbe')
    dbsession.add(quito)
    cuenca = models.Sitio(ciudad='Cuenca', terminal='Av. España y Sebastian de Benalcazar')
    dbsession.add(cuenca)
    guayaquil = models.Sitio(ciudad='Guayaquil', terminal='Río Daule')
    dbsession.add(guayaquil)

    # Cooperativa
    cooperativa_loja = models.Cooperativa(nombre='Cooperativa Loja', user=cooperativa_loja)
    dbsession.add(cooperativa_loja)
    cooperativa_cariamanga = models.Cooperativa(nombre='Cooperativa Cariamanga', user=cooperativa_cariamanga)
    dbsession.add(cooperativa_cariamanga)

    # Clase
    vip = models.Clase(nombre='VIP', descripcion='Clase VIP')
    dbsession.add(vip)
    normal = models.Clase(nombre='Normal', descripcion='Clase normal')
    dbsession.add(normal)

    # Unidad
    loja_1 = models.Unidad(numero_asientos=45, numero_unidad=1, clase=vip, cooperativa=cooperativa_loja)
    dbsession.add(loja_1)
    cariamanga_1 = models.Unidad(numero_asientos=40, numero_unidad=1, clase=normal, cooperativa=cooperativa_cariamanga)
    dbsession.add(cariamanga_1)
    cariamanga_2 = models.Unidad(numero_asientos=45, numero_unidad=2, clase=vip, cooperativa=cooperativa_cariamanga)
    dbsession.add(cariamanga_2)

    # Pasaje
    loja_quito_1 = models.Pasaje(salida=datetime.datetime.utcnow(),
                               llegada=datetime.datetime.utcnow(),
                               precio=20.5,
                               asientos_disponibles=45,
                               origen=loja,
                               destino=quito,
                               unidad=loja_1)
    dbsession.add(loja_quito_1)
    loja_quito_2 = models.Pasaje(salida=datetime.datetime.utcnow(),
                               llegada=datetime.datetime.utcnow(),
                               precio=20,
                               asientos_disponibles=40,
                               origen=loja,
                               destino=quito,
                               unidad=cariamanga_1)
    dbsession.add(loja_quito_2)
    loja_guayaquil = models.Pasaje(salida=datetime.datetime.utcnow(),
                                   llegada=datetime.datetime.utcnow(),
                                   precio=18,
                                   asientos_disponibles=45,
                                   origen=loja,
                                   destino=guayaquil,
                                   unidad=loja_1)
    dbsession.add(loja_guayaquil)
    loja_cuenca = models.Pasaje(salida=datetime.datetime.utcnow(),
                               llegada=datetime.datetime.utcnow(),
                               precio=8,
                               asientos_disponibles=45,
                               origen=loja,
                               destino=cuenca,
                               unidad=cariamanga_2)
    dbsession.add(loja_cuenca)

    # Boleto
    boleto_1 = models.Boleto(numero_asientos=2, precio_total=10.5, user=basic, pasaje=loja_quito_1)
    dbsession.add(boleto_1)
    boleto_2 = models.Boleto(numero_asientos=3, precio_total=12.5, user=basic, pasaje=loja_guayaquil)
    dbsession.add(boleto_2)
    boleto_3 = models.Boleto(numero_asientos=25, precio_total=15, user=basic, pasaje=loja_cuenca)
    dbsession.add(boleto_3)

def parse_args(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'config_uri',
        help='Configuration file, e.g., development.ini',
    )
    return parser.parse_args(argv[1:])

def main(argv=sys.argv):
    args = parse_args(argv)
    setup_logging(args.config_uri)
    env = bootstrap(args.config_uri)

    try:
        with env['request'].tm:
            dbsession = env['request'].dbsession
            setup_models(dbsession)
    except OperationalError:
        print('''
Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to initialize your database tables with `alembic`.
    Check your README.txt for description and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.
            ''')


'''
Problem Solving Programmers winter_coding_3
Author: Injun Son
Date: October 31, 2020
'''
import math
from collections import deque
from itertools import combinations

def print_board(board):
    for i in range(len(board)):
        for j in range(len(board[0])):
            print(board[i][j], end=" ")
        print()
    print()

def solution(v):
    answer = [0, 0, 0]
    graph = v
    # print_board(graph)
    visited = [[-1]*len(graph[0]) for _ in range(len(graph))]

    dx = [-1, 0, 0, 1]
    dy = [0, 1, -1, 0]

    def bfs(y, x):
        visited[y][x] = graph[y][x]
        queue = deque()
        queue.append([y, x, graph[y][x]])

        while queue:
            y, x, food = queue.popleft()
            for i in range(4):
                ny, nx = y+dy[i], x+dx[i]
                if 0<=ny<len(graph) and 0<=nx<len(graph[0]) and food == graph[ny][nx] and visited[ny][nx]==-1:
                    visited[ny][nx] = food
                    queue.append([ny, nx, food])

    for i in range(len(graph)):
        for j in range(len(graph[0])):
            if visited[i][j]==-1:
                answer[graph[i][j]]+=1
                bfs(i, j)
    return answer

print(solution([[0,0,1,1],[1,1,1,1],[2,2,2,1],[0,0,0,2]]))
print(solution([[0,0,1],[2,2,1],[0,0,0]]))


import cv2 as cv
import numpy as np

src = cv.imread("/home/gyh/opencv/lena.jpg")
img = cv.Canny(src,100,150)
"""
cv2.Canny(),就可以完成以上几步。
让我们看如何使用这个函数。这个函数的第一个参数是输入图像。第二和第三
个分别是 minVal 和 maxVal。第三个参数设置用来计算图像梯度的 Sobel
卷积核的大小,默认值为 3。最后一个参数是 L2gradient,它可以用来设定
求梯度大小的方程。如果设为 True,就会使用我们上面提到过的方程,否则
使用方程:Edge − Gradient (G) = |G 2 x | + |G 2 y | 代替,默认值为 False。
"""

cv.imshow("src",src)
cv.imshow("img",img)
cv.waitKey(0)
cv.destroyAllWindows()


from django.db import models
from apps.vendor.models import Vendor
from apps.application.models import Application

from .config import RESPONSE_TYPE_CHOICES
from config import settings

class AdminAction():
    pub_date = models.DateTimeField('date published')
    pub_by = models.CharField(max_length=180)
    modified_date = models.DateTimeField('date modified')
    modified_by = models.CharField(max_length=180)

class Question(AdminAction, models.Model):
    application = models.ForeignKey(Application, blank=True, null=True)
    question_text = models.TextField()
    is_first_question = models.BooleanField(
        default=False,
        help_text="Designates if the question is the first question in the decision tree")
    category = models.PositiveIntegerField(
        default=1, choices=RESPONSE_TYPE_CHOICES , help_text=('type of response to be stored'))
    next_default_question = models.ForeignKey("self", blank=True, null=True)
    is_active = models.BooleanField(
        default=False, help_text='Designates whether a question is active or not')

    def __str__(self):
        return self.question_text

    #note this carefully
    @property
    def response_data(self):
        fields_to_fetch = ['response_text','comment','response_image_url','response_url','send_user_info']
        all_further_responses = QuesRespRelation.objects.filter(question_id=self.id)
        d = []
        for response in all_further_responses:
            res = Response.objects.get(id=response.response_id)
            di = {key:getattr(res,key,"") for key in fields_to_fetch}
            di.update({'question_next':response.question_next_id})
            di.update({'response_id':response.response_id})
            d.append(di)
        return d

class Response(AdminAction, models.Model):
    application = models.ForeignKey(Application, blank=True, null=True)
    response_text = models.TextField()
    comment = models.TextField(blank=True, null=True, help_text ='used to show comment per response if available')
    response_image = models.ImageField(upload_to='images/', blank=True, null=True)
    response_url = models.URLField(max_length=300, blank=True, null=True)
    is_active = models.BooleanField(
        default=False, help_text='Designates whether a resposne is active or not')
    send_user_info = models.BooleanField(
        default=False, help_text='Designates whether the response_message sends request to vendor or not')

    @property
    def response_image_url(self):
        if self.response_image.name:
            return self.response_image.url
        return None

    def __str__(self):
        return self.response_text

class QuesRespRelation(AdminAction, models.Model):
    application = models.ForeignKey(Application, blank=True, null=True)
    question = models.ForeignKey(Question, blank=True, null=True)
    response = models.ForeignKey(
        Response, related_name='quesresprelation', blank=True, null=True)
    question_next = models.ForeignKey(
        Question, related_name='questionnextrelation', blank=True, null=True)
    is_active = models.BooleanField(
        default=False, help_text='Designates whether a question resposne relation is active or not')

    def __str__(self):
        return "When '" + self.question.question_text + "' is responded by '" + self.response.response_text + "'"


#Author:immortal luo
# -*-coding:utf-8 -*-
import pika
# Broker:它提供一种传输服务,它的角色就是维护一条从生产者到消费者的路线，保证数据能按照指定的方式进行传输,
# vhost:虚拟主机,一个broker里可以有多个vhost，用作不同用户的权限分离。

conneection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'
))

# Channel:消息通道,在客户端的每个连接里,可建立多个channel.
channel = conneection.channel()

# Exchange：消息交换机,它指定消息按什么规则,路由到哪个队列。
channel.exchange_declare(exchange='logs',
                         exchange_type='fanout')

# Queue:消息的载体,每个消息都会被投到一个或多个队列。
result = channel.queue_declare(exclusive=True)#随机创建一个Queue,程序结束后自动删除
queue_name = result.method.queue#获取刚创建的Queue的名称

# Binding:绑定，它的作用就是把exchange和queue按照路由规则绑定起来.
channel.queue_bind(exchange='logs',
                   queue=queue_name)
print("[*] Waiting for logs.To exit press CTRL+C")

def callback(ch,method,properties,body):
    print("[x] %r"%body)

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()


from typing import Dict, List, Set, Tuple, Optional, Any, Callable, NoReturn, Union, Mapping, Sequence, Iterable
from transformers import AutoTokenizer, AutoModelForCausalLM

# either GPT2 or another Question answering or text generation model
# https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb
# https://towardsdatascience.com/fine-tuning-gpt2-for-text-generation-using-pytorch-2ee61a4f1ba7
# https://towardsdatascience.com/natural-language-generation-part-2-gpt-2-and-huggingface-f3acb35bc86a
# text generation pe engleza(gpt2): gpt2
# question answering squad2 pe engleza (roberta): deepset/roberta-base-squad2
# perceiver multimodal to be tried

import pdb

def main():
    ro_gpt2_models = ["readerbench/RoGPT2-base", "readerbench/RoGPT2-large", "readerbench/RoGPT2-medium"]
    print(ro_gpt2_models)
    tokenizer = AutoTokenizer.from_pretrained('readerbench/RoGPT2-base')
    model = AutoModelForCausalLM.from_pretrained('readerbench/RoGPT2-base')
    inputs = tokenizer.encode("Este o zi de vara", return_tensors='pt')
    text = model.generate(inputs, max_length=1024, no_repeat_ngram_size=2)
    print(tokenizer.decode(text[0]))

    """
    input:
    Este o zi de vara
    output:
    Este o zi de vara, cu soare, în care soarele strălucește în toată splendoarea sa.
    Este ziua în amiaza mare, când soarele răsare la amiază. În această zi, soarele este la fel de strălucitor ca
    și luna.<|endoftext|>
    """

if __name__ == "__main__":
    main()


import pandas as pd
import torch
import time
import numpy as np
from gensim.models.word2vec import Word2Vec
from torch.autograd import Variable
from sklearn import metrics
from sklearn.model_selection import train_test_split

import warnings
warnings.filterwarnings('ignore')

from model import MethodNN
from util import *

def get_result_1():
    train_data = pd.read_pickle('parsed_source.pkl').sample(frac=1)
    word2vec = Word2Vec.load("word2vec_node_64").wv
    train_data, val_data = train_test_split(train_data, test_size=0.20, random_state=42)

    MAX_TOKENS = word2vec.syn0.shape[0]
    EMBEDDING_DIM = word2vec.syn0.shape[1]
    embeddings = np.zeros((MAX_TOKENS + 1, EMBEDDING_DIM), dtype="float32")
    embeddings[:word2vec.syn0.shape[0]] = word2vec.syn0

    ENCODE_DIM = 64
    HIDDEN_DIM = 32
    LABELS = 1
    BATCH_SIZE = 13
    USE_GPU = False

    model = MethodNN(EMBEDDING_DIM,HIDDEN_DIM,MAX_TOKENS+1,ENCODE_DIM,LABELS,BATCH_SIZE,USE_GPU, embeddings)
    parameters = model.parameters()
    optimizer = torch.optim.Adamax(parameters)
    loss_function = torch.nn.BCELoss()

    best_val_loss = float("inf")
    epochs = 20
    best_model = None
    best_epoch = -1

    def train():
        total_loss = 0.
        permutation = torch.randperm(len(train_data))
        for i in range(0, len(train_data), BATCH_SIZE):
            idx = permutation[i:i+BATCH_SIZE]
            batch_x = train_data['method_seq'].to_numpy()[idx]
            batch_y = train_data['b_label'].to_numpy()[idx]
            optimizer.zero_grad()
            model.batch_size = len(batch_y)
            model.hidden = model.init_hidden()
            output = model(batch_x)
            loss = loss_function(output[0], Variable(torch.FloatTensor(batch_y)))
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
            optimizer.step()
            total_loss += loss.item()
        return total_loss

    def evaluate(eval_model, data):
        total_loss = 0.
        start_time = time.time()
        permutation = torch.randperm(len(data))

        y_pred = []
        y_true = []
        with torch.no_grad():
            for i in range(0, len(data), BATCH_SIZE):
                idx = permutation[i:i+BATCH_SIZE]
                batch_x = data['method_seq'].to_numpy()[idx]
                batch_y = data['b_label'].to_numpy()[idx]
                model.batch_size = len(batch_y)
                model.hidden = model.init_hidden()
                output = model(batch_x)
                loss = loss_function(output[0], Variable(torch.FloatTensor(batch_y)))
                total_loss += loss
                y_pred.extend(output[0].reshape(-1,))
                y_true.extend(batch_y.reshape(-1,))
        return total_loss, y_pred, y_true

    for epoch in range(1, epochs + 1):
        epoch_start_time = time.time()
        train_loss = train()
        val_loss,_,_ = evaluate(model, val_data)
        # print('| end of epoch {:3d} | time: {:5.2f}s | train loss {:5.2f}| valid loss {:5.2f}'.format(epoch, (time.time() - epoch_start_time),train_loss, val_loss))

        if val_loss < best_val_loss:
            best_val_loss = val_loss
            best_model = model
            best_epoch = epoch

    #print("best_epoch", best_epoch)

    test_data = pd.read_pickle('parsed_source_test.pkl').sample(frac=1)
    #print("TESTING")
    test_loss, y_pred, y_true = evaluate(best_model, test_data)

    precision, recall, thresholds = metrics.precision_recall_curve(y_true, y_pred)
    fscore = (2 * precision * recall) / (precision + recall+10**-10)
    ix = np.argmax(fscore)
    y_pred_class = [x>thresholds[ix] for x in y_pred]

    precision, recall, AUC = metrics.precision_score(y_true, y_pred_class), \
                             metrics.recall_score(y_true, y_pred_class),\
                             metrics.roc_auc_score(y_true, y_pred)

    return precision, recall, fscore[ix], AUC

def get_result(add1, add2):
    precision_list = []
    recall_list = []
    AUC_list = []
    fscore_list = []

    for i in range(5):
        precision, recall, fscore, AUC = get_result_1()
        #print(precision, recall, fscore, AUC)
        precision_list.append(precision)
        recall_list.append(recall)
        fscore_list.append(fscore)
        AUC_list.append(AUC)

    print("Train:%s, Test:%s" %(add1.split("/")[-1], add2.split("/")[-1]))
    print("Precision=%0.3f, Recall=%0.3f, F-Score=%.3f, AUC=%0.3f\n" % (np.mean(precision_list), \
                                                                        np.mean(recall), \
                                                                        np.mean(fscore_list),\
                                                                        np.mean(AUC_list)))

# CAMEL
address1 = "../../Dataset/AST/camel/camel-1.2.csv"
address2 = "../../Dataset/AST/camel/camel-1.4.csv"
address3 = "../../Dataset/AST/camel/camel-1.6.csv"
get_data(address1, address2)
get_result(address1, address2)
get_data(address2, address3)
get_result(address2, address3)

# # Jedit
# address1 = "../../Dataset/AST/jedit/jedit-3.2.csv"
# address2 = "../../Dataset/AST/jedit/jedit-4.0.csv"
# address3 = "../../Dataset/AST/jedit/jedit-4.1.csv"
# # get_data(address1, address2)
# # get_result(address1, address2)
# # get_data(address2, address3)
# get_result(address2, address3)

# # Log4j
# address1 = "../../Dataset/AST/log4j/log4j-1.0.csv"
# address2 = "../../Dataset/AST/log4j/log4j-1.1.csv"
# get_data(address1, address2)
# get_result(address1, address2)

# # lucene
# address1 = "../../Dataset/AST/lucene/lucene-2.0.csv"
# address2 = "../../Dataset/AST/lucene/lucene-2.2.csv"
# address3 = "../../Dataset/AST/lucene/lucene-2.4.csv"
# get_data(address1, address2)
# get_result(address1, address2)
# get_data(address2, address3)
# get_result(address2, address3)

# # xalan
# address1 = "../../Dataset/AST/xalan/xalan-2.4.csv"
# address2 = "../../Dataset/AST/xalan/xalan-2.5.csv"
# address3 = "../../Dataset/AST/xalan/xalan-2.6.csv"
# get_data(address1, address2)
# get_result(address1, address2)
# get_data(address2, address3)
# get_result(address2, address3)

# # synapse
# address1 = "../../Dataset/AST/synapse/synapse-1.0.csv"
# address2 = "../../Dataset/AST/synapse/synapse-1.1.csv"
# address3 = "../../Dataset/AST/synapse/synapse-1.2.csv"
# get_data(address1, address2)
# get_result(address1, address2)
# get_data(address2, address3)
# get_result(address2, address3)

# # xerces
# address1 = "../../Dataset/AST/xerces/xerces-1.2.csv"
# address2 = "../../Dataset/AST/xerces/xerces-1.3.csv"
# address3 = "../../Dataset/AST/xerces/xerces-1.4.csv"
# # get_data(address1, address2)
# get_result(address1, address2)
# get_data(address2, address3)
# get_result(address2, address3)


"""A Raibert style controller for Minitaur."""

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

import math
import attr
import gin
import numpy as np

from pybullet_envs.minitaur.agents.baseline_controller import minitaur_raibert_controller_utils
from pybullet_envs.minitaur.envs.utilities import minitaur_pose_utils

LEFT_FRONT_LEG_ID = 0
LEFT_HIND_LEG_ID = 1
RIGHT_FRONT_LEG_ID = 2
RIGHT_HIND_LEG_ID = 3

DIAGONAL_LEG_PAIR_1 = (LEFT_FRONT_LEG_ID, RIGHT_HIND_LEG_ID)
DIAGONAL_LEG_PAIR_2 = (LEFT_HIND_LEG_ID, RIGHT_FRONT_LEG_ID)

LEFT_LEG_IDS = (LEFT_FRONT_LEG_ID, LEFT_HIND_LEG_ID)
RIGHT_LEG_IDS = (RIGHT_FRONT_LEG_ID, RIGHT_HIND_LEG_ID)

# The max horizontal foot offset (in meters) for turning.
_FOOT_HORIZONTAL_OFFSET_FOR_TURNING = 0.1

_STANCE_TG_PHASE_COMPRESSION = 1.5
_STANCE_TG_DELTA_EXTENSION = 0.2
_STANCE_HORIZONTAL_SCALING_FACTOR = 1.2

_DEFAULT_SWING_SPEED_GAIN = 0.015

_DEFAULT_SWING_FOOT_CLEARANCE = 0.005

_PITCH_SWING_FEEDBACK_SCALING_FACTOR = 1.2

# A POD container to describe the controller's high level behavior.
@attr.s
class BehaviorParameters(object):
  """Highlevel parameters for Raibert style controller."""
  stance_duration = attr.ib(type=float, default=0.25)
  desired_forward_speed = attr.ib(type=float, default=0.)
  desired_turning_speed = attr.ib(type=float, default=0.)
  standing_height = attr.ib(type=float, default=0.2)
  desired_incline_angle = attr.ib(type=float, default=0.)

def generate_default_swing_trajectory(phase, init_pose, end_pose):
  """A swing trajectory generator.

  Args:
    phase: Float. Between [0, 1].
    init_pose: A tuple. The leg pose (swing, extension) at phase == 0 the
      beginning of swing.
    end_pose: A tuple. The leg pose at phase == 1 the end of swing.

  Returns:
    The desired leg pose for the current phase.
  """
  # Try phase compression
  normalized_phase = math.sqrt(min(phase * 1.5, 1))

  # For swing, we use a linear interpolation:
  swing = (end_pose[0] - init_pose[0]) * normalized_phase + init_pose[0]

  # For extension, we can fit a second order polynomial:
  min_ext = (init_pose[1] + end_pose[1]) / 2 - 0.8
  min_ext = max(min_ext, 0.5)

  # The phase value at which the extension reaches the minimal value min_ext.
  # phi is small, the swing leg will try to lift higher in the first half of
  # swing.
  phi = 0.1

  # We convert the extension back into the cartesion space. In this way we can
  # guarantee a lift-up trajectory. The ankle to hip distance is easier to
  # compute than a full forward-kinematics.
  min_ankle_dist = minitaur_raibert_controller_utils.extension_to_ankle_dist(
      min_ext)
  init_ankle_dist = minitaur_raibert_controller_utils.extension_to_ankle_dist(
      init_pose[1])
  end_ankle_dist = minitaur_raibert_controller_utils.extension_to_ankle_dist(
      end_pose[1])

  # The polynomial is: a * phi^2 + b * phi + c
  delta_1 = min_ankle_dist - init_ankle_dist
  delta_2 = end_ankle_dist - init_ankle_dist
  delta_p = phi * phi - phi

  a = (delta_1 - phi * delta_2) / delta_p

  b = (phi * phi * delta_2 - delta_1) / delta_p

  ankle_dist = (
      a * normalized_phase * normalized_phase + b * normalized_phase +
      init_ankle_dist)

  l1 = minitaur_raibert_controller_utils.UPPER_LEG_LEN
  l2 = minitaur_raibert_controller_utils.LOWER_SHORT_LEG_LEN

  ankle_dist = min(max(ankle_dist, l2 - l1 + 0.01), l2 + l1 - 0.01)

  extension = minitaur_raibert_controller_utils.ankle_dist_to_extension(
      ankle_dist)

  return (swing, extension)

@gin.configurable
def generate_default_stance_trajectory(phase,
                                       init_pose,
                                       end_pose,
                                       use_constant_extension=False):
  """A stance strajectory generator.

  Args:
    phase: Float. Between [0, 1].
    init_pose: A tuple. The leg pose (swing, extension) at phase == 0, i.e. the
      beginning of stance.
    end_pose: A tuple. The leg pose at phase == 1, i.e. the end of stance.
    use_constant_extension: Boolean. Whether or not to fix the extension during
      stance.

  Returns:
    The desired leg pose for the current phase.
  """
  normalized_phase = min(_STANCE_TG_PHASE_COMPRESSION * math.sqrt(phase), 1)
  swing = (end_pose[0] - init_pose[0]) * normalized_phase + init_pose[0]

  # The extension evolves nonlinearly according to the parabola equation.
  if use_constant_extension:
    extension = end_pose[1]
  else:
    extension = end_pose[1] - 4 * _STANCE_TG_DELTA_EXTENSION * (
        normalized_phase**2 - normalized_phase)
  return (swing, extension)

def get_stance_foot_offset_for_turning(leg_id, steering_signal):
  """Modify the stance foot position to achieve turning.

  The strategy works for trotting gaits.

  Args:
    leg_id: Integer. The leg index.
    steering_signal: Float. The desired turning signal in [-1, 1]. Because we
      don't have an accurate mapping from angular velocity to the foot offset,
      the steering signal should be treated as a reference and only its relative
      magnitude matters.

  Returns:
    The stance foot's horizontal offset.

  """
  clipped_steering_signal = np.clip(steering_signal, -1, 1)

  if leg_id in LEFT_LEG_IDS:
    return _FOOT_HORIZONTAL_OFFSET_FOR_TURNING * clipped_steering_signal
  else:
    return -(_FOOT_HORIZONTAL_OFFSET_FOR_TURNING * clipped_steering_signal)

def get_leg_swing_offset_for_pitching(body_pitch, desired_incline_angle):
  """Get the leg swing zero point when the body is tilted.

  For example, when climbing up or down stairs/slopes, the robot body will tilt
  up or down. By compensating the body pitch, the leg's trajectory will be
  centered around the vertical direction (not perpendicular to the surface).
  This helps the robot to generate thrust when going upwards, and braking when
  going downwards.

  Args:
    body_pitch: Float. Current body pitch angle.
    desired_incline_angle: Float. The desired body pitch angle.

  Returns:
    The stance and swing leg swing offset.

  """
  kp = 0.2
  return -((1 - kp) * body_pitch + kp * desired_incline_angle)

@gin.configurable
class RaibertSwingLegController(object):
  """The swing leg controller."""

  def __init__(self,
               speed_gain=_DEFAULT_SWING_SPEED_GAIN,
               foot_clearance=_DEFAULT_SWING_FOOT_CLEARANCE,
               leg_trajectory_generator=generate_default_swing_trajectory):
    """Initializes the controller.

    Args:
      speed_gain: Float. The speed feedback gain to modulate the target foot
        position.
      foot_clearance: Float. The foot clearance (at the end of the swing phase)
        in meters.
      leg_trajectory_generator: A trajectory generator function.
    """
    self._speed_gain = speed_gain
    self._foot_clearance = foot_clearance
    self._leg_trajectory_generator = leg_trajectory_generator

  def get_action(self, raibert_controller):
    """Get the swing legs' desired pose."""
    current_speed = raibert_controller.estimate_base_velocity()
    phase = raibert_controller.get_phase()
    rpy = raibert_controller.robot.base_roll_pitch_yaw

    leg_pose_set = {}
    for i in raibert_controller.swing_set:
      # Target foot horizontal position is calculated according to Raibert's
      # original formula in "Legged robots that balance".
      target_foot_horizontal_position = (
          raibert_controller.behavior_parameters.stance_duration / 2 *
          current_speed + self._speed_gain *
          (current_speed -
           raibert_controller.behavior_parameters.desired_forward_speed))

      # 1) Convert the target foot position to leg pose space.
      # Lift the foot a little bit.
      target_foot_vertical_position = -(
          raibert_controller.behavior_parameters.standing_height -
          self._foot_clearance)
      target_foot_position = (target_foot_horizontal_position,
                              target_foot_vertical_position)
      target_leg_pose = minitaur_raibert_controller_utils.foot_position_to_leg_pose(
          target_foot_position)

      # 2) Generates the curve from the swing start leg pose to the target leg
      # pose and find the next leg pose on the curve based on current swing
      # phase.

      desired_leg_pose = self._leg_trajectory_generator(
          phase, raibert_controller.swing_start_leg_pose, target_leg_pose)

      swing_offset = get_leg_swing_offset_for_pitching(
          rpy[1], raibert_controller.behavior_parameters.desired_incline_angle)

      leg_pose_set[i] = (desired_leg_pose[0] + swing_offset,
                         desired_leg_pose[1])

    return leg_pose_set

@gin.configurable
class RaibertStanceLegController(object):
  """The controller that modulates the behavior of the stance legs."""

  def __init__(self,
               speed_gain=0.1,
               leg_trajectory_generator=generate_default_stance_trajectory):
    """Initializes the controller.

    Args:
      speed_gain: Float. The speed feedback gain to modulate the target stance
        foot position.
      leg_trajectory_generator: A trajectory generator function. Generates the
        desired leg pose during the stance phase.
    """
    self._speed_gain = speed_gain
    self._leg_trajectory_generator = leg_trajectory_generator

  def get_action(self, raibert_controller):
    """Get the desired leg pose for the stance legs."""

    phase = raibert_controller.get_phase()
    current_speed = raibert_controller.estimate_base_velocity()
    rpy = raibert_controller.robot.base_roll_pitch_yaw

    leg_pose_set = {}
    for i in raibert_controller.stance_set:
      desired_forward_speed = (
          raibert_controller.behavior_parameters.desired_forward_speed)

      target_foot_horizontal_position = -_STANCE_HORIZONTAL_SCALING_FACTOR * (
          raibert_controller.behavior_parameters.stance_duration / 2 *
          current_speed - self._speed_gain *
          (current_speed - desired_forward_speed))

      target_foot_horizontal_position += get_stance_foot_offset_for_turning(
          i, raibert_controller.behavior_parameters.desired_turning_speed)

      target_foot_position = (
          target_foot_horizontal_position,
          -raibert_controller.behavior_parameters.standing_height)
      target_leg_pose = minitaur_raibert_controller_utils.foot_position_to_leg_pose(
          target_foot_position)

      desired_leg_pose = (
          self._leg_trajectory_generator(
              phase, raibert_controller.stance_start_leg_pose, target_leg_pose))

      swing_offset = _PITCH_SWING_FEEDBACK_SCALING_FACTOR * get_leg_swing_offset_for_pitching(
          rpy[1], raibert_controller.behavior_parameters.desired_incline_angle)

      leg_pose_set[i] = (desired_leg_pose[0] + swing_offset,
                         desired_leg_pose[1])

    return leg_pose_set

@gin.configurable
class MinitaurRaibertController(object):
  """A Raibert style controller for trotting gait."""

  def __init__(self,
               robot,
               behavior_parameters=BehaviorParameters(),
               swing_leg_controller=RaibertSwingLegController(),
               stance_leg_controller=RaibertStanceLegController(),
               pose_feedback_controller=None):
    self._time = 0
    self._robot = robot
    self.behavior_parameters = behavior_parameters

    self._last_recorded_speed = 0

    self._swing_leg_controller = swing_leg_controller
    self._stance_leg_controller = stance_leg_controller
    self._pose_feeback_controller = pose_feedback_controller

    # The leg order is FL, RL, FR, RR -> [0, 1, 2, 3]
    self._swing_set = DIAGONAL_LEG_PAIR_1
    self._stance_set = DIAGONAL_LEG_PAIR_2

    # Compute the initial leg pose.
    self._swing_start_leg_pose = self.get_swing_leg_pose()
    self._stance_start_leg_pose = self.get_stance_leg_pose()

  @property
  def robot(self):
    return self._robot

  @property
  def swing_set(self):
    return self._swing_set

  @property
  def stance_set(self):
    return self._stance_set

  @property
  def swing_start_leg_pose(self):
    return self._swing_start_leg_pose

  @property
  def stance_start_leg_pose(self):
    return self._stance_start_leg_pose

  def _get_average_leg_pose(self, leg_indices):
    """Get the average leg pose."""
    current_leg_pose = minitaur_pose_utils.motor_angles_to_leg_pose(
        self._robot.motor_angles)

    # extract the swing leg pose from the current_leg_pose
    leg_pose = []
    for index in leg_indices:
      leg_pose.append([
          current_leg_pose[index],
          current_leg_pose[index + minitaur_pose_utils.NUM_LEGS]
      ])

    leg_pose = np.array(leg_pose)
    return np.mean(leg_pose, axis=0)

  def get_swing_leg_pose(self):
    """Get the current swing legs' average pose."""
    return self._get_average_leg_pose(self._swing_set)

  def get_stance_leg_pose(self):
    """Get the current stance legs' average pose."""
    return self._get_average_leg_pose(self._stance_set)

  def get_phase(self):
    """Compute the current stance/swing phase."""
    return math.fmod(self._time, self.behavior_parameters.stance_duration
                    ) / self.behavior_parameters.stance_duration

  def _get_new_swing_stance_set(self):
    """Switch the set of swing/stance legs based on timing."""
    swing_stance_phase = math.fmod(self._time,
                                   2 * self.behavior_parameters.stance_duration)
    if swing_stance_phase < self.behavior_parameters.stance_duration:
      return (DIAGONAL_LEG_PAIR_1, DIAGONAL_LEG_PAIR_2)
    return (DIAGONAL_LEG_PAIR_2, DIAGONAL_LEG_PAIR_1)

  def update(self, t):
    """Update the internal status of the controller.

    Args:
      t: Float. The current time after reset in seconds.
    """
    self._time = t
    new_swing_set, new_stance_set = self._get_new_swing_stance_set()

    # If there is a stance/swing switch.
    if new_swing_set[0] is not self._swing_set[0]:
      self._swing_set = new_swing_set
      self._stance_set = new_stance_set

      # Also records the starting pose.
      self._swing_start_leg_pose = self.get_swing_leg_pose()
      self._stance_start_leg_pose = self.get_stance_leg_pose()

  def estimate_base_velocity(self):
    """Estimate the current CoM speed."""
    # It is best to use a sensor fusion approach.
    stance_leg_pose = self.get_stance_leg_pose()

    delta_sw = stance_leg_pose[0] - self._stance_start_leg_pose[0]

    x, y = minitaur_raibert_controller_utils.leg_pose_to_foot_position(
        stance_leg_pose)
    toe_hip_len = math.sqrt(x**2 + y**2)
    horizontal_dist = toe_hip_len * delta_sw
    phase = self.get_phase()
    speed = self._last_recorded_speed
    if phase > 0.1:
      speed = horizontal_dist / (
          self.behavior_parameters.stance_duration * phase)
      self._last_recorded_speed = speed
    return speed

  def get_swing_leg_action(self):
    return self._swing_leg_controller.get_action(self)

  def get_stance_leg_action(self):
    return self._stance_leg_controller.get_action(self)

  def get_action(self):
    """Gets the desired motor angles."""
    leg_pose = [0] * minitaur_pose_utils.NUM_MOTORS
    swing_leg_pose = self.get_swing_leg_action()
    for i in self._swing_set:
      leg_pose[i] = swing_leg_pose[i][0]
      leg_pose[i + minitaur_pose_utils.NUM_LEGS] = swing_leg_pose[i][1]

    stance_leg_pose = self.get_stance_leg_action()
    for i in self._stance_set:
      leg_pose[i] = stance_leg_pose[i][0]
      leg_pose[i + minitaur_pose_utils.NUM_LEGS] = stance_leg_pose[i][1]

    return minitaur_pose_utils.leg_pose_to_motor_angles(leg_pose)


import os
import openpyxl
import pandas as pd
import numpy as np

def load_exam(file_path) -> pd.DataFrame:
    wb = openpyxl.load_workbook(file_path)
    ws = wb.active
    for i in range(12,52):
        ws.cell(row=2,column=i).value = f"{ws.cell(row=2,column=i).value} [{ws.cell(row=1,column=(i-(i-2)%5)).value}]"
    data = np.array(list(ws.values))
    cols = data[1]
    data = data[data[:,2]=="Kutno"]

    return pd.DataFrame(data,columns=cols)

def process_files_in_directory(dirname: str) -> pd.DataFrame:
    reports = None
    for filename in os.listdir(dirname):
        if filename.startswith("Wyniki_"):
            with open("../Kutno_HackSQL/" + filename, "r") as f:
                result = load_exam("../Kutno_HackSQL/" + filename)
                result['Year'] = int(filename[-9:-5])
                if reports is None:
                    reports = result
                else:
                    reports = pd.concat([reports,result])

    return reports


import sqlite3 as sql

habilidades_de_armas = { "perforar": {
                "nombre":"perforar",
                "efecto":'',
                "dano_en_area":False,
                "multiplicador_de_dano":1.1,
                'rolls':3
            },
            "desgarrar": {
                "nombre":"desgarrar",
                "efecto":'sangrado',
                "dano_en_area":False,
                "multiplicador_de_dano":1,
                'rolls':3
            },
            "sinfonia": {
                "nombre":"sinfonia",
                "efecto":'',
                "dano_en_area":True,
                "multiplicador_de_dano":0.9,
                'rolls':4
            },
            "ritardando": {
                "nombre":"ritardando",
                "efecto":'reducir_velocidad',
                "dano_en_area":False,
                "multiplicador_de_dano":0.8,
                'rolls':4
            },
            "tiro": {
                "nombre":"tiro",
                "efecto":'',
                "dano_en_area":False,
                "multiplicador_de_dano":0.9,
                'rolls':2
            },
            "tiro_de_francotirador": {
                "nombre":"tiro_de_francotirador",
                "efecto":'ignorar_armadura',
                "dano_en_area":False,
                "multiplicador_de_dano":0.9,
                'rolls':3
            },
            "maldecir": {
                "nombre":"maldecir",
                "efecto":'',
                "dano_en_area":False,
                "multiplicador_de_dano":1,
                'rolls':3
            },
            "explosion": {
                "nombre":"explosion",
                "efecto":'',
                "dano_en_area":True,
                "multiplicador_de_dano":0.9,
                'rolls':4
            },
            "morder": {
                "nombre":"morder",
                "efecto":'sangrado',
                "dano_en_area":False,
                "multiplicador_de_dano":0.9,
                'rolls':2
            },
            "rebanar": {
                "nombre":"rebanar",
                "efecto":'',
                "dano_en_area":False,
                "multiplicador_de_dano":1,
                'rolls':3
            },
            "estocada": {
                "nombre":"estocada",
                "efecto":'',
                "dano_en_area":False,
                "multiplicador_de_dano":1.2,
                'rolls':4
            }
}

armas = {
            "lanza": {
                "nombre":"lanza",
                "habilidades": "perforar desgarrar",
                "calidad":1,
                "stats":{
                    'dano_base':9,
                    'tipo_de_dano':'fisico',
                    'afinidad':'fuerza',
                    'bonus_armadura':0,
                    'bonus_resistencia':0,
                    'bonus_evasion':1,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "arco_de_caza": {
                "nombre":"arco_de_caza",
                "habilidades": "tiro tiro_de_francotirador",
                "calidad":1,
                "stats":{
                    'dano_base':6,
                    'tipo_de_dano':'fisico',
                    'afinidad':'observacion',
                    'bonus_armadura':0,
                    'bonus_resistencia':0,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "laud_roto": {
                "nombre":"laud_roto",
                "habilidades": "sinfonia ritardando",
                "calidad":1,
                "stats":{
                    'dano_base':6,
                    'tipo_de_dano':'magico',
                    'afinidad':'talento',
                    'bonus_armadura':0,
                    'bonus_resistencia':0,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "tomo_de_aprendiz": {
                "nombre":"tomo_de_aprendiz",
                "habilidades": "maldecir explosion",
                "calidad":1,
                "stats":{
                    'dano_base':7,
                    'tipo_de_dano':'magico',
                    'afinidad':'inteligencia',
                    'bonus_armadura':0,
                    'bonus_resistencia':0,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "espada_corta": {
                "nombre":"espada_corta",
                "habilidades": "rebanar estocada",
                "calidad":1,
                "stats":{
                    'dano_base':7,
                    'tipo_de_dano':'fisico',
                    'afinidad':'fuerza',
                    'bonus_armadura':0,
                    'bonus_resistencia':0,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "colmillos": {
                "nombre":"colmillos",
                "habilidades": "morder",
                "calidad":1,
                "stats":{
                    'dano_base':7,
                    'tipo_de_dano':'fisico',
                    'afinidad':'fuerza',
                    'bonus_armadura':0,
                    'bonus_resistencia':0,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    }
}
armaduras = {
            "botas_viejas": {
                "nombre":"botas_viejas",
                "habilidad_pasiva":'',
                "calidad":1,
                "stats":{
                    'bonus_armadura':1,
                    'bonus_resistencia':0,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "casco_roto": {
                "nombre":"casco_roto",
                "habilidad_pasiva":'',
                "calidad":1,
                "stats":{
                    'bonus_armadura':1,
                    'bonus_resistencia':1,
                    'bonus_evasion':0,
                    'bonus_vitalidad':1,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "chaleco_de_cuero": {
                "nombre":"chaleco_de_cuero",
                "habilidad_pasiva":'',
                "calidad":1,
                "stats":{
                    'bonus_armadura':2,
                    'bonus_resistencia':1,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "tunica": {
                "nombre":"tunica",
                "habilidad_pasiva":'',
                "calidad":2,
                "stats":{
                    'bonus_armadura':1,
                    'bonus_resistencia':2,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':3,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':1,
                    'bonus_suerte':0}
                    },
            "cota_de_mallas": {
                "nombre":"cota_de_mallas",
                "habilidad_pasiva":'',
                "calidad":2,
                "stats":{
                    'bonus_armadura':7,
                    'bonus_resistencia':3,
                    'bonus_evasion':0,
                    'bonus_vitalidad':2,
                    'bonus_fuerza':2,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':0,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "traje_lujoso": {
                "nombre":"traje_lujoso",
                "habilidad_pasiva":'',
                "calidad":2,
                "stats":{
                    'bonus_armadura':4,
                    'bonus_resistencia':4,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':0,
                    'bonus_talento':6,
                    'bonus_observacion': 0,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    },
            "chaleco_de_asesino": {
                "nombre":"chaleco_de_asesino",
                "habilidad_pasiva":'',
                "calidad":2,
                "stats":{
                    'bonus_armadura':4,
                    'bonus_resistencia':4,
                    'bonus_evasion':0,
                    'bonus_vitalidad':0,
                    'bonus_fuerza':0,
                    'bonus_inteligencia':0,
                    'bonus_velocidad':2,
                    'bonus_talento':6,
                    'bonus_observacion': 7,
                    'bonus_enfoque':0,
                    'bonus_suerte':0}
                    }
}
consumibles = {
            "barba_de_dios": {
                "nombre":"barba_de_dios",
                "stats":{
                    'dano_base':'',
                    'efecto_en_tablero':'curacion',
                    'efecto_en_combate':'curacion',
                    'curacion_base': 18}
                    },
            "raiz_dorada": {
                "nombre":"raiz_dorada",
                "stats":{
                    'dano_base':'',
                    'efecto_en_tablero':'concentrarse',
                    'efecto_en_combate':'concentrarse',
                    'curacion_base': 0,}
                    },
            "hiedra_bailarina": {
                "nombre":"hiedra_bailiarina",
                "stats":{
                    'dano_base':'',
                    'efecto_en_tablero':'movilidad',
                    'efecto_en_combate':'aumentar_velocidad',
                    'curacion_base': 0}
                    },
            "panax": {
                "nombre":"panax",
                "stats":{
                    'dano_base':'',
                    'efecto_en_tablero':'curar_veneno',
                    'efecto_en_combate':'curar_veneno',
                    'curacion_base': 0}
                    },
            "hierba_del_erudito": {
                "nombre":"hierba_del_erudito",
                "stats":{
                    'dano_base':'',
                    'efecto_en_tablero':'ganar_xp',
                    'efecto_en_combate':'ganar_xp',
                    'curacion_base': 0}
                    }
}

clases = {  "herrero": {
                "nombre":"herrero",
                "arma_inicial":'lanza',
                "habilidad_pasiva":'firmeza',
                "sprite_path":r'C:\Users\54115\Desktop\python\For The Queen\assets\dc-mon\holy\paladin.png',
                "atributos":{
                    'vitalidad':85,
                    'fuerza':81,
                    'inteligencia':50,
                    'velocidad':61,
                    'talento':77,
                    'observacion': 57,
                    'suerte':55},
                "stats":{
                    'armadura':1,
                    'resistencia':0,
                    'evasion':9,
                    'puntos_de_enfoque':4}
            },
            "erudito": {
                "nombre":"erudito",
                "arma_inicial":'tomo_de_aprendiz',
                "habilidad_pasiva": 'reenfocar',
                "sprite_path":r'C:\Users\54115\Desktop\python\For The Queen\assets\dc-mon\wizard.png',
                "atributos":{
                    'vitalidad':65,
                    'fuerza':47,
                    'inteligencia':83,
                    'velocidad':75,
                    'talento':75,
                    'observacion': 71,
                    'suerte':55},
                "stats":{
                    'armadura':0,
                    'resistencia':1,
                    'evasion':15,
                    'puntos_de_enfoque':5}
            },
            "bardo": {
                "nombre":"bardo",
                "arma_inicial":'laud_roto',
                "habilidad_pasiva":'entretener',
                "sprite_path":r'C:\Users\54115\Desktop\python\For The Queen\assets\dc-mon\unique\mnoleg.png',
                "atributos":{
                    'vitalidad':73,
                    'fuerza':77,
                    'inteligencia':53,
                    'velocidad':63,
                    'talento':81,
                    'observacion': 59,
                    'suerte':55},
                "stats":{
                    'armadura':0,
                    'resistencia':1,
                    'evasion':13,
                    'puntos_de_enfoque':4}
            },
            "cazador": {
                "nombre":"cazador",
                "arma_inicial":'arco_de_caza',
                "habilidad_pasiva":'tiro_cargado',
                "sprite_path":r'C:\Users\54115\Desktop\python\For The Queen\assets\dc-mon\deep_elf_master_archer.png',
                "atributos":{
                    'vitalidad':71,
                    'fuerza':57,
                    'inteligencia':51,
                    'velocidad':83,
                    'talento':69,
                    'observacion': 83,
                    'suerte':55},
                "stats":{
                    'armadura':1,
                    'resistencia':1,
                    'evasion':20,
                    'puntos_de_enfoque':4}
            },
    }

criaturas = { "esqueleto":{
                    'nombre':'esqueleto',
                    'arma':'espada_corta',
                    'nivel':0,
                    'puntos_de_vida':17,
                    'dano_de_ataque':4,
                    'armadura':1,
                    'resistencia':0,
                    'evasion':0,
                    'sprite_path':r'C:\Users\54115\Desktop\python\For The Queen\assets\UNUSED\monsters\skeleton_small.png'
            },
            "lobo":{
                    'nombre':'lobo',
                    'arma':'colmillos',
                    'nivel':1,
                    'puntos_de_vida':16,
                    'dano_de_ataque':6,
                    'armadura':0,
                    'resistencia':0,
                    'velocidad':85,
                    'evasion':5,
                    'sprite_path':r'C:\Users\54115\Desktop\python\For The Queen\assets\dc-mon\animals\wolf.png'
            },
            "murcielago":{
                    'nombre':'murcielago',
                    'arma':'colmillos',
                    'nivel':1,
                    'puntos_de_vida':15,
                    'dano_de_ataque':5,
                    'armadura':0,
                    'resistencia':1,
                    'velocidad':90,
                    'evasion':10,
                    'sprite_path':r'C:\Users\54115\Desktop\python\For The Queen\assets\UNUSED\monsters\quasit.png'
            },
            "serpiente":{
                    'nombre':'serpiente',
                    'arma':'colmillos',
                    'nivel':1,
                    'puntos_de_vida':30,
                    'dano_de_ataque':1,
                    'armadura':0,
                    'resistencia':1,
                    'velocidad':90,
                    'evasion':10,
                    'sprite_path':r'C:\Users\54115\Desktop\python\For The Queen\assets\UNUSED\monsters\yellow_snake.png'
            }
}

class AdministradorDeBaseDeDatos:
    def __init__(self, nombre):
        self.conexion = sql.connect(nombre + ".db")
        #tablas a llenar en ejecucion
        self.crear_tabla_jugadores()
        self.crear_tabla_aventureros()

        #tablas que se llenan al iniciar el programa
        self.crear_tabla_clases()
        self.crear_tabla_criaturas()
        self.crear_tabla_armas()
        self.crear_tabla_armaduras()
        self.crear_tabla_consumibles()
        self.crear_tabla_habilidades_de_armas()

        #inserts iniciales
        self.insertar_clases()
        self.insertar_criaturas()
        self.insertar_armas()
        self.insertar_armaduras()
        self.insertar_consumibles()
        self.insertar_habilidades_de_armas()

        '''
        inserts en ejecucion, no van a ir en este constructor sino en el de Jugador y Aventurero respectivamente
        self.insertar_jugador()
        self.insertar_aventurero()
        '''

    def realizar_consulta(self, query):
        cursor  = self.conexion.cursor()
        consulta = f"{query}"
        cursor.execute(consulta)
        resultado = cursor.fetchall()[0]
        self.efectuar_cambios()
        return resultado #type list

    def realizar_consulta_de_cambio(self, query):
        cursor  = self.conexion.cursor()
        consulta = f"{query}"
        cursor.execute(consulta)
        self.efectuar_cambios()

    def efectuar_cambios(self):
        self.conexion.commit()

    def crear_tabla_jugadores(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS jugadores (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_clases(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS clases (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT,
                    arma_inicial TEXT,
                    habilidad_pasiva TEXT,
                    vitalidad INT,
                    fuerza INT,
                    inteligencia INT,
                    velocidad INT,
                    talento INT,
                    observacion INT,
                    suerte INT,
                    armadura INT,
                    resistencia INT,
                    evasion INT,
                    puntos_de_enfoque INT,
                    sprite_path TEXT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_aventureros(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS aventureros (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                nombre TEXT,
                arma INT,
                clase TEXT,
                habilidad_pasiva TEXT,
                nivel INT,
                vitalidad INT,
                fuerza INT,
                inteligencia INT,
                velocidad INT,
                talento INT,
                observacion INT,
                suerte INT,
                armadura INT,
                resistencia INT,
                evasion INT,
                vida_base INT,
                puntos_de_enfoque INT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_criaturas(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS criaturas (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT,
                    arma TEXT,
                    nivel INT,
                    puntos_de_vida INT,
                    dano_de_ataque INT,
                    armadura INT,
                    resistencia INT,
                    evasion INT,
                    sprite_path TEXT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_armas(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS armas (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT,
                    habilidades TEXT,
                    calidad INT,
                    dano_base INT,
                    tipo_de_dano TEXT,
                    afinidad TEXT,
                    bonus_vitalidad INT,
                    bonus_fuerza INT,
                    bonus_inteligencia INT,
                    bonus_velocidad INT,
                    bonus_talento INT,
                    bonus_observacion INT,
                    bonus_suerte INT,
                    bonus_armadura INT,
                    bonus_resistencia INT,
                    bonus_evasion INT,
                    bonus_enfoque INT
                    )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_armaduras(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS armaduras (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT,
                    habilidad_pasiva TEXT,
                    calidad INT,
                    bonus_vitalidad INT,
                    bonus_fuerza INT,
                    bonus_inteligencia INT,
                    bonus_velocidad INT,
                    bonus_talento INT,
                    bonus_observacion INT,
                    bonus_suerte INT,
                    bonus_armadura INT,
                    bonus_resistencia INT,
                    bonus_evasion INT,
                    bonus_enfoque INT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_consumibles(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS consumibles (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT,
                    dano_base TEXT,
                    curacion_base INT,
                    efecto_en_tablero TEXT,
                    efecto_en_combate TEXT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def crear_tabla_habilidades_de_armas(self):
        cursor = self.conexion.cursor()
        consulta = f'''CREATE TABLE IF NOT EXISTS habilidades_de_armas (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    nombre TEXT,
                    efecto TEXT,
                    dano_en_area TINYINT,
                    multiplicador_de_dano REAL,
                    rolls INT )'''
        cursor.execute(consulta)
        self.efectuar_cambios()

    def insertar_jugador(self, jugador):#en ejecucion
        query = f"INSERT INTO jugadores VALUES (NULL, '{jugador.nombre}')"
        self.realizar_consulta_de_cambio(query)

    def insertar_clase(self, clase):
        cursor  = self.conexion.cursor()
        insert = f'''INSERT INTO clases VALUES (
                    NULL,
                    '{clases[clase]['nombre']}',
                    '{clases[clase]['arma_inicial']}',
                    '{clases[clase]['habilidad_pasiva']}',
                    '{clases[clase]['atributos']['vitalidad']}',
                    '{clases[clase]['atributos']['fuerza']}',
                    '{clases[clase]['atributos']['inteligencia']}',
                    '{clases[clase]['atributos']['velocidad']}',
                    '{clases[clase]['atributos']['talento']}',
                    '{clases[clase]['atributos']['observacion']}',
                    '{clases[clase]['atributos']['suerte']}',
                    '{clases[clase]['stats']['armadura']}',
                    '{clases[clase]['stats']['resistencia']}',
                    '{clases[clase]['stats']['evasion']}',
                    '{clases[clase]['stats']['puntos_de_enfoque']}',
                    '{clases[clase]['sprite_path']}' )'''
        cursor.execute(insert)
        self.efectuar_cambios()

    def insertar_clases(self):
        for clase in clases:
            self.insertar_clase(clase)

    def insertar_criatura(self, criatura):
        cursor  = self.conexion.cursor()
        insert = f'''INSERT INTO criaturas VALUES (
                    NULL,
                    '{criaturas[criatura]['nombre']}',
                    '{criaturas[criatura]['arma']}',
                    '{criaturas[criatura]['nivel']}',
                    '{criaturas[criatura]['puntos_de_vida']}',
                    '{criaturas[criatura]['dano_de_ataque']}',
                    '{criaturas[criatura]['armadura']}',
                    '{criaturas[criatura]['resistencia']}',
                    '{criaturas[criatura]['evasion']}',
                    '{criaturas[criatura]['sprite_path']}' )'''
        cursor.execute(insert)
        self.efectuar_cambios()

    def insertar_criaturas(self):
        for criatura in criaturas:
            self.insertar_criatura(criatura)

    def insertar_arma(self, arma):
        cursor  = self.conexion.cursor()
        insert = f'''INSERT INTO armas VALUES (
                    NULL,
                    '{armas[arma]['nombre']}',
                    '{armas[arma]['habilidades']}',
                    '{armas[arma]['calidad']}',
                    '{armas[arma]['stats']['dano_base']}',
                    '{armas[arma]['stats']['tipo_de_dano']}',
                    '{armas[arma]['stats']['afinidad']}',
                    '{armas[arma]['stats']['bonus_vitalidad']}',
                    '{armas[arma]['stats']['bonus_fuerza']}',
                    '{armas[arma]['stats']['bonus_inteligencia']}',
                    '{armas[arma]['stats']['bonus_velocidad']}',
                    '{armas[arma]['stats']['bonus_talento']}',
                    '{armas[arma]['stats']['bonus_observacion']}',
                    '{armas[arma]['stats']['bonus_suerte']}',
                    '{armas[arma]['stats']['bonus_armadura']}',
                    '{armas[arma]['stats']['bonus_resistencia']}',
                    '{armas[arma]['stats']['bonus_evasion']}',
                    '{armas[arma]['stats']['bonus_enfoque']}' )'''
        cursor.execute(insert)
        self.efectuar_cambios()

    def insertar_armas(self):
        for arma in armas:
            self.insertar_arma(arma)

    def insertar_armadura(self, armadura):
        cursor  = self.conexion.cursor()
        insert = f'''INSERT INTO armaduras VALUES (
                    NULL,
                    '{armaduras[armadura]['nombre']}',
                    '{armaduras[armadura]['habilidad_pasiva']}',
                    '{armaduras[armadura]['calidad']}',
                    '{armaduras[armadura]['stats']['bonus_vitalidad']}',
                    '{armaduras[armadura]['stats']['bonus_fuerza']}',
                    '{armaduras[armadura]['stats']['bonus_inteligencia']}',
                    '{armaduras[armadura]['stats']['bonus_velocidad']}',
                    '{armaduras[armadura]['stats']['bonus_talento']}',
                    '{armaduras[armadura]['stats']['bonus_observacion']}',
                    '{armaduras[armadura]['stats']['bonus_suerte']}',
                    '{armaduras[armadura]['stats']['bonus_armadura']}',
                    '{armaduras[armadura]['stats']['bonus_resistencia']}',
                    '{armaduras[armadura]['stats']['bonus_evasion']}',
                    '{armaduras[armadura]['stats']['bonus_enfoque']}' )'''
        cursor.execute(insert)
        self.efectuar_cambios()

    def insertar_armaduras(self):
        for armadura in armaduras:
            self.insertar_armadura(armadura)

    def insertar_consumible(self, consumible):
        cursor  = self.conexion.cursor()
        insert = f'''INSERT INTO consumibles VALUES (
                    NULL,
                    '{consumibles[consumible]['nombre']}',
                    '{consumibles[consumible]['stats']['dano_base']}',
                    '{consumibles[consumible]['stats']['curacion_base']}',
                    '{consumibles[consumible]['stats']['efecto_en_tablero']}',
                    '{consumibles[consumible]['stats']['efecto_en_combate']}' )'''
        cursor.execute(insert)
        self.efectuar_cambios()

    def insertar_consumibles(self):
        for consumible in consumibles:
            self.insertar_consumible(consumible)

    def insertar_habilidad_de_arma(self, arma):
        cursor  = self.conexion.cursor()
        insert = f'''INSERT INTO habilidades_de_armas VALUES (
                    NULL,
                    '{habilidades_de_armas[arma]['nombre']}',
                    '{habilidades_de_armas[arma]['efecto']}',
                    '{habilidades_de_armas[arma]['dano_en_area']}',
                    '{habilidades_de_armas[arma]['multiplicador_de_dano']}',
                    '{habilidades_de_armas[arma]['rolls']}' )'''
        cursor.execute(insert)
        self.efectuar_cambios()

    def insertar_habilidades_de_armas(self):
        for habilidad in habilidades_de_armas:
            self.insertar_habilidad_de_arma(habilidad)

administradorDeBaseDeDatos = AdministradorDeBaseDeDatos("For_The_Queen")


import gym

from envs.common_wrappers import NoopResetEnv, ClipRewardEnv, MaxAndSkipEnv, ProcessFrame84
from envs.common_wrappers import FrameStack, ExtraTimeLimit, ImageToPyTorch, NormalizedEnv, RescaleImageEnv
from envs.dm_lab_env import Dmlab_env

def make_atari(args):
    env = gym.make(args.env_name)
    env = NoopResetEnv(env, noop_max=args.noop_max)
    if args.clip_rewards:
        env = ClipRewardEnv(env)
    if 'NoFrameskip' in env.spec.id and args.skip_frames > 0:
        env = MaxAndSkipEnv(env, skip=args.skip_frames)
    env = ProcessFrame84(env, crop=False)
    if args.stack_frames > 1:
        env = FrameStack(env, args.stack_frames)
    env = ExtraTimeLimit(env, args.max_episode_steps)
    env = ImageToPyTorch(env)
    if args.normalize_env:
        env = NormalizedEnv(env)
    return env

def make_dm_lab(args, recording):
    env = Dmlab_env(args)
    if recording:
        env = RescaleImageEnv(env, size=(args.prev_frame_h, args.prev_frame_w))
    if args.clip_rewards:
        env = ClipRewardEnv(env)
    if args.skip_frames > 0:
        env = MaxAndSkipEnv(env, skip=args.skip_frames)
    if args.stack_frames > 1:
        env = FrameStack(env, args.stack_frames)
    env = ImageToPyTorch(env)
    if args.normalize_env:
        env = NormalizedEnv(env)
    return env

def make_env(env_args, recording=False):
    if env_args.env_type == "atari":
        return make_atari(env_args)
    elif env_args.env_type == "dmlab":
        return make_dm_lab(env_args, recording)
    else:
        raise NotImplemented


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = 500
y = 500
direction = 0
matr = np.matrix(np.zeros((x, y)))
arr = np.array([int(x/2), int(y/2), 0])
# polozenie (x,y) i kierunek ruchu 0 - E, 1 - N, 2 - W, 3 - S

def nextstep(matr, arr):
    if arr[2] == 0:
        arr[0] += 1
    if arr[2] == 1:
        arr[1] += 1
    if arr[2] == 2:
        arr[0] -= 1
    if arr[2] == 3:
        arr[1] -= 1
    if matr[arr[0], arr[1]] == 0:
        arr[2] = (arr[2] + 1) % 4
        matr[arr[0], arr[1]] = 1
    else:
        arr[2] = (arr[2] + 3) % 4
        matr[arr[0], arr[1]] = 0

fig = plt.figure()
im = plt.imshow(matr, vmax=1)

def animate(i):
    nextstep(matr, arr)
    im.set_data(matr)
    return im,

anim = FuncAnimation(fig, animate, frames=2000000, interval=0, blit=True)
plt.show()


import torch.nn as nn
import torchvision.models as models

from attention_model import Attn_Net_Gated

def get_final_model(model_name, attention_module, hidden_dim, hidden_dim2, use_b, dropout):

    if attention_module != None:
        if attention_module == 'faisal':

            if model_name == 'RESNET18':
                dim = 512
            elif model_name == 'RESNET50':
                dim = 1024
            else:
                print('wrong model name')
                exit()

            model = Attn_Net_Gated(dim,hidden_dim,hidden_dim2,dropout,use_b,1)
        else:
            exit() # not running the other anymore

    else:
        if model_name == 'RESNET18':
            model = get_model(model_name)

        else:
            print('Wrong model name')
            exit()

    model = model.cuda()
    return model

def get_model(model_name):

    if model_name == 'RESNET18':

        model = models.resnet18(pretrained=True)
        for param in model.parameters():
            param.requires_grad = False

        fc = nn.Linear(in_features=512, out_features=1, bias=True)
        model.fc = fc

        for param in model.fc.parameters():
            param.requires_grad = True

    elif model_name == 'RESNET50':
        model = models.resnet50(pretrained=True)
        for param in model.parameters():
            param.requires_grad = False

        fc = nn.Linear(in_features=2048, out_features=1, bias=True)
        model.fc = fc

        for param in model.fc.parameters():
            param.requires_grad = True

    return model


from __future__ import unicode_literals
"""
A simplified client to notarising documents on the Bitcoin blockchain.

Uses the Ascribe.io SPOOL library to
 - manage generating addresses,
 - selecting tx inputs/outputs and
 - building txs

"""
from spool import Spool
from spool import Wallet

from bitcoin import bin_hash160, bin_to_b58check

import hashlib
from builtins import object, str, super
import sys
import os

_magicbyte = 111
spool = Spool()
min_confirmations = 0

# Federation wallet is responsible for maintaining a list of addresses that contain just enough Bitcoin for sending custom OP_RETURN transactions.

def fund_federation_wallet(fed_wallet, fund_wallet, fund_wallet_secret):
	from_address = fund_wallet.root_address[1]
	to_address = fed_wallet.root_address[1]
	nfees = int(os.environ.get('NFEES'))
	ntokens = int(os.environ.get('NTOKENS'))

	unsigned_tx = spool._t.simple_transaction(from_address,
											 [(to_address, spool.FEE)] * nfees + [(to_address, spool.TOKEN)] * ntokens,
											 min_confirmations=min_confirmations)
	signed_tx = spool._t.sign_transaction(unsigned_tx, fund_wallet_secret)
	return signed_tx

# Generate tx to notarise data on blockchain
def generate_notarise_tx(fed_address, fed_pass, data_to_notarise):
	unsigned_tx = spool.simple_spool_transaction(fed_address,
                                                [fed_address],
                                                op_return=str(data_to_notarise),
                                                min_confirmations=min_confirmations)

	signed_tx = spool._t.sign_transaction(unsigned_tx, fed_pass)

	return signed_tx

# def generate_unqiue_addr_for_path(wallet, path):
# 	gendPath, addr = wallet.address_from_path(path)
# 	print("Generated address %s from %s" % addr, gendPath)

def gen_address_for_data(data):
	print("Hashing data: "+str(data))

	# https://gist.github.com/patricklodder/b27fb3e91c0566272976#file-gistfile1-py-L390
	# RIPEMD160(SHA256(data))
	fingerprint = bin_hash160(data.encode())
	print("Data fingerprint: "+str(fingerprint.encode('hex')))

	address = str(bin_to_b58check(fingerprint), magicbyte=_magicbyte)
	print("Final address: "+str(address))

	return address

def push_tx(tx):
	tx_id = spool._t.push(tx)
	print("Pushed tx %s" % tx_id)
	return tx_id

if __name__ == "__main__":
	cmd = sys.argv[1]

	FUND_WALLET_SECRET = os.environ.get('FUND_WALLET_SECRET')
	FEDERATION_WALLET_SECRET = os.environ.get('FED_WALLET_SECRET')

	fund_wallet = Wallet(FUND_WALLET_SECRET)
	fed_wallet = Wallet(FEDERATION_WALLET_SECRET)

	if cmd == 'fund':
		print("Funding federation wallet %s..." % fed_wallet.root_address[1])
		tx = fund_federation_wallet(fed_wallet, fund_wallet, FUND_WALLET_SECRET)
		txid = push_tx(tx)
		print("https://www.blocktrail.com/BTC/tx/%s" % txid)

	elif cmd == 'notarise':

		data = sys.argv[2]
		if(len(data) < 16):
			print("Data needs to be 16+ bytes")
			raise Exception

		data_prefixed = "TEST"+str(data)
		if(len(data_prefixed) > 80):
			print("Data needs to be 80 bytes or less")
			raise Exception

		print('Notarising data...')

		tx_hex = generate_notarise_tx(fed_wallet.root_address[1], FEDERATION_WALLET_SECRET, data_prefixed)

		print("Pushing %s" % tx_hex)
		push_tx(tx_hex)

	else:
		print("Syntax: registerWorkSimple.py (fund | notarise) <data>")

	exit(0)


'''
Author: Mayank Prakash Pandey
'''

import pickle
import streamlit as st
import numpy as np

# Adding header and author information
st.header('Book Recommender')
st.markdown("A **Machine Learning** Powered App by :red[**Mayank Prakash Pandey**] :computer:")

# Loading the necessary pickle files
model = pickle.load(open('models/similarity_scores.pkl', 'rb'))
final_rating = pickle.load(open('models/books.pkl', 'rb'))
book_pivot = pickle.load(open('models/pt.pkl', 'rb'))
top_books = pickle.load(open('models/popular.pkl','rb'))

# Creating a sidebar panel with a list of books
df=top_books
st.sidebar.title("Top 50 Books")
book_list = st.sidebar.selectbox("Select a book", df['Title'])

# Show the selected book's title and rating on the main page
if book_list:
    selected_book = df[df['Title'] == book_list]
    st.sidebar.title("Selected Book")
    st.sidebar.image(selected_book['URL'].values[0])
    st.sidebar.write("Title :red[:] ", selected_book['Title'].values[0])
    st.sidebar.write("Author :red[:] ", selected_book['Author'].values[0])
    st.sidebar.write("Rating :red[:] ", np.round(selected_book['Avg_Rating'].values[0],2),"(",str(selected_book['Num_Ratings'].values[0]),"votes)")
    st.sidebar.write("Publisher :red[:] ", selected_book['Publisher'].values[0])
    st.sidebar.write("Year :red[:] ", str(selected_book['Publication_Year'].values[0]))

# Defining the recommendation function
def recommend_book(book_name):
    # Fetch the index of the selected book
    index = np.where(book_pivot.index == book_name)[0][0]
    # Top 3 similar books
    similar_items = sorted(list(enumerate(model[index])), key=lambda x: x[1], reverse=True)[1:5]

    data = []
    for i in similar_items:
        item = []
        temp_df = final_rating[final_rating['Title'] == book_pivot.index[i[0]]]
        item.extend(list(temp_df.drop_duplicates('Title')['Title'].values))
        item.extend(list(temp_df.drop_duplicates('Title')['Author'].values))
        item.extend(list(temp_df.drop_duplicates('Title')['URL'].values))
        data.append(item)
    return data

# Create a dropdown to select a book
selected_books = st.selectbox(
    "**Type or select a book from the dropdown**",
    book_pivot.index.values
)

if st.button('Show Recommendation'):
    recommended_books  = recommend_book(selected_books)
    col1, col2, col3 = st.columns(3,gap="large")
    with col1:
        st.image(recommended_books[1][2])
        st.text(recommended_books[1][0])
        st.text(recommended_books[1][1])
    with col2:
        st.image(recommended_books[2][2])
        st.text(recommended_books[2][0])
        st.text(recommended_books[2][1])
    with col3:
        st.image(recommended_books[3][2])
        st.text(recommended_books[3][0])
        st.text(recommended_books[3][1])

hide_menu_style="""
            <style>
 #           #MainMenu {visibility: hidden;}
            footer {visibility:hidden;}
            </style>
            """
st.markdown(hide_menu_style, unsafe_allow_html=True)