# ------------------------------------------------------------------------------
# Bibliotecas
# ------------------------------------------------------------------------------

import streamlit as st
import pandas as pd
import numpy as np
from sklearn.preprocessing import OrdinalEncoder
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import CategoricalNB

# ------------------------------------------------------------------------------

import sys
sys.path.append('./')
import marcelo as mp

# ------------------------------------------------------------------------------

st.markdown("# Aprendizado Supervisionado - Algoritmo Naïve Bayes")

# ------------------------------------------------------------------------------
# Dados
# ------------------------------------------------------------------------------

import os
DIR = "./"
entries = [entry for entry in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, entry))]
option = st.selectbox('Qual o conjunto de dados gostaria de analisar?', mp.Filter(entries, ['csv']))
df_csv = pd.read_csv(option)
df_csv.drop_duplicates(inplace=True)

# ------------------------------------------------------------------------------

df = mp.filter_dataframe(df_csv)
st.dataframe(df.head())

# ------------------------------------------------------------------------------

# https://stackoverflow.com/questions/25039626/how-do-i-find-numeric-columns-in-pandas

# ------------------------------------------------------------------------------

target = st.selectbox('Selecione a coluna alvo (target)', df.columns.tolist()[::-1], key = "target")

# ------------------------------------------------------------------------------

st.write(df[target].value_counts())

# ------------------------------------------------------------------------------

labels = df[target].unique().tolist()
pos_label = st.selectbox('Pos label', labels[::-1], key = "pos_label")
labels.remove(pos_label)
neg_label = st.selectbox('Neg label', labels[::1], key = "neg_label")

if df[target].nunique() == 2:
  st.write("Classificação binária")
  average = "binary"
  step=2
else:
  st.write("Classificação não binária")
  average = st.selectbox('Average', ['weighted','micro','macro'], key = "average")
  step=1

st.write(f"Average: {average}")
st.write(f"Step: {step}")

# ------------------------------------------------------------------------------

features_names = df.columns.tolist()
if target in features_names:
  features_names.remove(target)

categorical = df.select_dtypes(include=['object']).columns.tolist()
if target in categorical:
  categorical.remove(target)

numerical = df.select_dtypes(exclude=['object']).columns.tolist()
if target in numerical:
  numerical.remove(target)

# ------------------------------------------------------------------------------

encoder = OrdinalEncoder(dtype=np.int64)
# Codifica variáveis categóricas usando inteiros
df_X = df
encoder.fit(df_X[categorical])
df_X[categorical] = encoder.transform(df_X[categorical])
df_X = df_X.drop(target, axis=1)
df_y = df.loc[:,[target]]

# ------------------------------------------------------------------------------

data_container = st.container()
with data_container:
  coluna_X, coluna_y = st.columns(2)
  with coluna_X:
    st.write("Atributos Preditores (X)")
    st.write(df_X.head())
  with coluna_y:
    st.write("Atributo Alvo (y)")
    st.write(df_y.head())

# ------------------------------------------------------------------------------
# Aprendizado Supervisionado
# ------------------------------------------------------------------------------

X = df_X.values
y = df_y.values

# ------------------------------------------------------------------------------

if numerical:

  if st.checkbox('MODELO NAÏVE BAYES GAUSSIANO'):

    X_train, X_test, y_train, y_test = mp.metodo_holdout_2(df_X[numerical], df_y.values, 0.80, True)

    # Treinando o modelo com GaussianNB
    nbG_clf = GaussianNB()
    nbG_clf.fit(X_train, y_train)

    # Prevendo a classe de saída para as instâncias de teste
    # Por padrão, a classe retornada é aquela que maximiza a probabilidade a posteriori
    y_predG = nbG_clf.predict(X_test)

    # As probabilidades por classe podem ser observadas com o seguinte comando
    y_probaG = nbG_clf.predict_proba(X_test)

    # --------------------------------------------------------------------------

    mp.plota_todos_os_resultados(df[target].nunique(), nbG_clf.classes_, pos_label, neg_label, y_test, y_predG)

# ------------------------------------------------------------------------------

if categorical:

  if st.checkbox('MODELO NAÏVE BAYES COM DADOS CATEGÓRICOS'):

    X_train, X_test, y_train, y_test = mp.metodo_holdout_2(df_X[categorical], df_y.values, 0.80, True)

    # Treinando o modelo com CategoricalNB
    nbC_clf = CategoricalNB()
    nbC_clf.fit(X_train, y_train)

    # Prevendo a classe de saída para as instâncias de teste
    # Por padrão, a classe retornada é aquela que maximiza a probabilidade a posteriori
    y_predC = nbC_clf.predict(X_test)

    # As probabilidades por classe podem ser observadas com o seguinte comando
    y_probaC = nbC_clf.predict_proba(X_test)

    # --------------------------------------------------------------------------

    mp.plota_todos_os_resultados(df[target].nunique(), nbC_clf.classes_, pos_label, neg_label, y_test, y_predC)

  # ----------------------------------------------------------------------------

# ------------------------------------------------------------------------------


# Projeto CountryGuess
from tkinter import *
import customtkinter
import random

#Listas que armazenam as perguntas, respostas e verificação
BancoPerguntas = [
    'O Japão é considerado o\nprincipal rival da Coreia do Sul',
    'O Brasil é considerado o\nprincipal rival da Argentina',
    'A Turquia é considerada a\nprincipal rival da Grécia',
    'O Brasil faz fronteira com\num membro da União Europeia',
    'Porto Rico é um país',
    'República da China é o\nnome oficial de Taiwan',
    'A Índia tem uma população\nmaior que a da Europa',
    'Sidney é a capital\nda Australia',
    'Toronto é a capital\ndo Canadá',
    'Ottawa é a capital\ndo Canadá',
    'Barbados é o nome\nde um país',
    'A Guiné Equatorial é o único país\nafricano que tem como seu\nidioma oficial o espanhol',
    'El Salvador é o único país\nlatino americano que\nfala holandês',
    'O Brasil é o único país\nque nunca deixou de participar\nde uma Copa do Mundo',
    'O México é a maior economia\nda América Latina',
    'O País com a maior população\ndo mundo é Taiwan',
    'A décima maior economia\ndo mundo é a do Qatar',
    'A Rússia é um país com\nterritório na Ásia e na Europa',
    'Ilhas Marshall não é o\nnome de um país independente',
    'A Bolívia é o país\nmais plano do mundo',
    'San Marino é o Estado/País\nmais antigo do mundo',
    'O menor país do mundo\né o Vaticano, que possui\napenas 800 habitantes oficiais',
    'A cidade de Tóquio,\nno Japão, é a mais\npopulosa do mundo',
    'A China é a única economia\nno rank das 10 maiores\nque não foi pro espaço',
    'Timor-Leste é um país\nafricano que fala português',
    'A China não permite\nque grande empresas estrangeiras\natuem em seu território',
    'O país com o maior\nnúmero de startups\nno mundo é a India',
    'Oymyakon, na Rússia,\né o local habitado mais frio do mundo',
    'É possível cruzar Liechtenstein\nem menos de um dia',
    'A Mongólia é o país\nmenos povoado do mundo',
    ]
BancoRespostas = [
    False,
    True,
    True,
    True,
    False,
    True,
    True,
    False,
    False,
    True,
    True,
    False,
    True,
    True,
    False,
    False,
    False,
    True,
    False,
    True,
    True,
    True,
    True,
    False,
    False,
    True,
    False,
    True,
    True,
    True,
    ]
BancoVerificacao = [
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    ]

#classe dos dados
class Dados:
    def __init__(self, ListaPerguntas, ListaRespostas, ListaVerificacao):
        self.ListaPerguntas = ListaPerguntas
        self.ListaRespostas = ListaRespostas
        self.ListaVerificacao = ListaVerificacao

PacoteDados = Dados(ListaPerguntas= BancoPerguntas, ListaRespostas= BancoRespostas, ListaVerificacao= BancoVerificacao)

#Variáveis do projeto
i = 0
Acertos = 0
Erros = 0

#Funções do programa
#Função para definir a frase inicial do programa
def FraseInicial():
    #é sorteada uma pergunta com um range do mesmo tamanho da lista de perguntas
    global i
    global PacoteDados
    TamanhoLista = (len(PacoteDados.ListaPerguntas))
    i = random.randint(0,TamanhoLista-1)
    TextoInicial = PacoteDados.ListaPerguntas[i]
    #a frase sorteada é marcada como já usada
    PacoteDados.ListaVerificacao[i] = 0
    return TextoInicial

#Função para dar o raise no frame
def FrameRaise(frame):
    frame.tkraise()

#Função para quando o botão VERDADEIRO for clicado
def clickVerdadeiro():
    global i
    global PacoteDados
    global Acertos
    global Erros
    #faz a verificação se o usuário acertou ou não e faz a contagem
    if PacoteDados.ListaRespostas[i] == True:
        Acertos = Acertos + 1
        label_Acertos.configure(text= ("Acertos: " + str(Acertos)))
    else:
        Erros = Erros + 1
        label_Erros.configure(text= ("Erros: " + str(Erros)))
    #checagem se ainda existem frases disponíveis
    ListaAcabou = True
    for verificacao in PacoteDados.ListaVerificacao:
        if verificacao == 1:
            ListaAcabou = False
            break
    if ListaAcabou == True:
        Label_TextoPergunta.configure(text= "Acabaram as perguntas!\nObrigado por jogar!")
        Button_Falso.configure(state="disabled")
        Button_Verdadeiro.configure(state="disabled")
    #caso ainda existam, é sorteada uma nova frase
    else:
        TamanhoLista = (len(PacoteDados.ListaPerguntas))
        #o loop while serve para a nova frase sorteada serem apenas as que ainda não foram usadas
        while PacoteDados.ListaVerificacao[i] != 1:
            i = random.randint(0,TamanhoLista-1)
        #após a nova frase ser sorteada, ela é marcada como já utilizada
        PacoteDados.ListaVerificacao[i] = 0
        Label_TextoPergunta.configure(text= (PacoteDados.ListaPerguntas[i]))

#Função para quando o botão FALSO for clicado
def clickFalso():
    global i
    global PacoteDados
    global Acertos
    global Erros
    #faz a verificação se o usuário acertou ou não e faz a contagem
    if PacoteDados.ListaRespostas[i] == False:
        Acertos = Acertos + 1
        label_Acertos.configure(text= ("Acertos: " + str(Acertos)))
    else:
        Erros = Erros + 1
        label_Erros.configure(text= ("Erros: " + str(Erros)))
    #checagem se ainda existem frases disponíveis
    ListaAcabou = True
    for verificacao in PacoteDados.ListaVerificacao:
        if verificacao == 1:
            ListaAcabou = False
            break
    if ListaAcabou == True:
        Label_TextoPergunta.configure(text= "Acabaram as perguntas!\nObrigado por jogar :)")
        Button_Falso.configure(state="disabled")
        Button_Verdadeiro.configure(state="disabled")
    #caso ainda existam, é sorteada uma nova frase
    else:
        TamanhoLista = (len(PacoteDados.ListaPerguntas))
        #o loop while serve para a nova frase sorteada serem apenas as que ainda não foram usadas
        while PacoteDados.ListaVerificacao[i] != 1:
            i = random.randint(0,TamanhoLista-1)
        #após a nova frase ser sorteada, ela é marcada como já utilizada
        PacoteDados.ListaVerificacao[i] = 0
        Label_TextoPergunta.configure(text= (PacoteDados.ListaPerguntas[i]))

#Propriedades da Main Window
window = Tk()
window.title("CountryGuess")
window.geometry("700x400")
window.resizable(width = False ,height = False)
window.configure(bg="#2F0061")

#definição das imagens usadas
#definição da tela de menu usada no Frame_Menu
ImgMenu = PhotoImage(file= "archives/TelaMenu.png")
#definição do background usado no frame_quiz
background = PhotoImage(file="archives/background.png")

#criação dos elementos da GUI
#FRAME MENU
Frame_Menu = Frame(window, width= 702, height= 400)
Label_ImgMenu = Label(Frame_Menu, image= ImgMenu)
Button_Jogar = customtkinter.CTkButton(
    master= Frame_Menu,
    command= lambda:FrameRaise(Frame_Quiz),
    text= "JOGAR",
    text_font="none 17 bold",
    text_color= "black",
    hover= True,
    hover_color= "#ff6123",
    height=50,
    width= 200,
    border_width=2,
    corner_radius=8,
    border_color= "black",
    bg_color="#994900",
    fg_color= "#ff4800")
#FRAME QUIZ
Frame_Quiz = Frame(window, width= 702, height= 400)
Label_background = Label(Frame_Quiz, image= background)
Label_TextoPergunta = Label(Frame_Quiz, text=FraseInicial(), bg="#f68500", fg="black", font="none 25 bold")
label_Acertos = customtkinter.CTkLabel(Frame_Quiz, text="Acertos: 0", text_font="none 20 bold", text_color="#78ff00", bg_color="black")
label_Erros = customtkinter.CTkLabel(Frame_Quiz, text="Erros: 0", text_font="none 15 bold", text_color="#ff0000", bg_color="black")
Button_Verdadeiro = customtkinter.CTkButton(
    master= Frame_Quiz,
    command= clickVerdadeiro,
    text= "VERDADEIRO",
    text_font="none 17 bold",
    text_color= "black",
    hover= True,
    hover_color= "#ff6123",
    height=50,
    width= 250,
    border_width=2,
    corner_radius=8,
    border_color= "black",
    bg_color="#da7700",
    fg_color= "#ff4800",)
Button_Falso = customtkinter.CTkButton(
    master= Frame_Quiz,
    command=clickFalso,
    text= "FALSO",
    text_font="none 17 bold",
    text_color= "black",
    hover= True,
    hover_color= "#ff6123",
    height=50,
    width= 250,
    border_width=2,
    corner_radius=8,
    border_color= "black",
    bg_color="#da7700",
    fg_color= "#ff4800")

#Organização do programa (uso do .place)
#organização no Frame_Menu
Frame_Menu.place(x= -2, y= 0)
Label_ImgMenu.place(x= 0, y= 0)
Button_Jogar.place(x= 350, y= 340, anchor=CENTER)
#organização no Frame_Quiz
Frame_Quiz.place(x= -2, y= 0)
Label_background.place(x= 0, y= 0)
Label_TextoPergunta.place(x= 350, y= 100, anchor=CENTER)
Button_Verdadeiro.place(x= 78,y= 254)
Button_Falso.place(x= 370,y= 254)
label_Acertos.place(x= 350,y= 348, anchor=CENTER)
label_Erros.place(x= 350,y= 375, anchor=CENTER)

#execução do programa
#definindo que o Frame_Menu será o que aparecerá primeiro
FrameRaise(Frame_Menu)
#definindo a frase inicial

#roda o loop principal
window.mainloop()


import numpy as np
import sys
import itertools

# open the prod.E file from James calcEnergies and skip every stride
with open('./prod.E') as Efile:
   E = np.genfromtxt(itertools.islice(Efile, 0, None, 1))
print (len(E))
#print (E)

# create a dictionary to search for the Energy of a given frame
frame_num = np.arange(1, len(E)+1, 1)
search_dict = dict(zip(frame_num, E))
#print (search_dict)

# number of dihedrals used to do the clustering
num_dih=5
# total lines in the dihedral output file
tot_lines = sum(1 for line in open('./prod.dihCpptraj'))
# nume of lines, excluding the first ndihedrals plus 2 lines
num_lines = tot_lines - (num_dih+2)
frame_line = np.arange(1, num_lines,2)
'''
#Cluster          1         12 [   0  35  35   0   9  ]
#60753 72966 167026 176440 244210 247479 293530 312993 405705 408614 432235 457397
#Cluster          2         12 [   0  24  35  34  27  ]
#78842 175310 191609 229174 271836 300427 301868 330822 358703 395121 406582 498142
#Cluster          3         11 [  35  24   1  24   1  ]
#2204 43163 136212 169578 191693 315533 325892 395535 436611 454616 458803
'''

st = open('select_struct.dat', 'w')
st.write('CLuster Frame#   Energy \n')
# open the output file from clusterdihedral command in cpptraj
with open('prod.dihCpptraj', "r") as f:
    # skip the first line, the next ndihedral line and then one more line
    for _ in range(num_dih+2):
        next(f)
    # for every line after this
    for line in f:
        # split the lines
        l1 = line.strip().split()
        # if the line has the word Cluster get the total frame in that cluster
        if l1[0] == 'Cluster':
            tot_frame = l1[2]
            #print (tot_frame)
        # the next line is the frame numbers for that cluster
        else:
            # create a list that has all the frame and Energies for that cluster
            low_frame = []; low_E = []
            # for every frame in that cluster
            for i in range(int(tot_frame)):
                # get the frame number
                target = l1[i]
                target = int(target)
                #print (target)
                # get the Energy for that frame number
                E = search_dict[target]
                #print (E)
                # append E and frame to list
                low_frame.append(target); low_E.append(E)
            # now get the lowest Energy structure in that cluster
            minE = min(low_E)
            # get the index of the lowerst Energy
            index_min = min(range(len(low_E)), key=low_E.__getitem__)
            # now get the frame of the lowest Energy
            minFrame = low_frame[index_min]
            #print ("minE = %s, minFrame = %s" %(minE, minFrame))
            st.write("%s     %s\n" %(minFrame, minE))
            # clear the list for the next cluster
            low_frame.clear(); low_E.clear()


import pytest

from opentaxii.server import create_server
from opentaxii.utils import get_config_for_tests

INBOX = dict(
    id = 'inbox-A',
    type = 'inbox',
    description = 'inboxA description',
    destination_collection_required = 'yes',
    address = '/relative/path',
    accept_all_content = 'yes',
    protocol_bindings = ['urn:taxii.mitre.org:protocol:http:1.0', 'urn:taxii.mitre.org:protocol:https:1.0']
)

DISCOVERY = dict(
    id = 'discovery-A',
    type = 'discovery',
    description = 'discoveryA description',
    address = '/relative/discovery',
    advertised_services = ['inboxA', 'discoveryA'],
    protocol_bindings = ['urn:taxii.mitre.org:protocol:http:1.0']
)

DISCOVERY_EXTERNAL = dict(
    id = 'discovery-B',
    type = 'discovery',
    description = 'discoveryB description',
    address = 'http://example.com/a/b/c',
    protocol_bindings = ['urn:taxii.mitre.org:protocol:http:1.0']
)

INTERNAL_SERVICES = [INBOX, DISCOVERY]
SERVICES = INTERNAL_SERVICES + [DISCOVERY_EXTERNAL]

DOMAIN = 'example.com'

@pytest.fixture(scope='module')
def server():
    config = get_config_for_tests(DOMAIN)
    server = create_server(config)

    server.persistence.create_services_from_object(SERVICES)
    server.reload_services()

    return server

def test_services_configured(server):
    assert len(server.services) == len(SERVICES)
    assert len(server.path_to_service) == len(INTERNAL_SERVICES)

    assert server.path_to_service[DISCOVERY['address']].id == DISCOVERY['id']

    assert all(map(lambda x: x.address.startswith(DOMAIN), server.path_to_service.values()))


""" A command line menu-driven python application providing users with the
    ability to search and display U.S. State Capital, population and Flowers.
"""

import sys
import matplotlib.pyplot as plt
from usa_data_generator import UsaDataGenerator as generator

def display_data(us):
    """ Displays all the U.S states in Alphabetical order.

        Includes Capital, State Population, and Flower.
    """
    us.print_data()

def search_data(us):
    """ Displays the Capital, Population, and Flower given input.
    """
    data = us.get_data()
    state = get_state_input(data)

    us.print_state(state)
    us.show_state_flowers(state)
    print()

def display_bar(us):
    """ Displays the top five populations in the US via bar graph!
    """
    data = us.get_data()

    populations = []

    for key, value in data.items():
        populations.append((key, value["population"])) # create tuples

    populations.sort(key = lambda pop_value: pop_value[1]) # sort tuples by 2nd value

    top_five = populations[-5:] # get last 5 values

    top_five_states = []
    top_five_populations = []

    for item in top_five:
        state, population = item

        top_five_states.append(state)
        top_five_populations.append(population)

    fig = plt.figure()
    ax_obj = fig.add_axes([0,0,1,1])
    ax_obj.bar(top_five_states, top_five_populations)

    ax_obj.legend(labels=['Population'])

    plt.show()

def check_int(response):
    """ checks if response is a valid int greater than 0

    Args:
        response (string): input from the user

    Raises:
        ValueError: in case int value is less than 0, raise
        value error - checked.

    Returns:
        int: response to int type
    """
    try:
        if int(response) >= 0:
            return int(response)

        raise ValueError()
    except ValueError:
        response = input('Please enter a valid int: ').strip()

    return check_int(response=response)

def update_population(us):
    """ Updates the population of a state via user input
    """
    data = us.get_data()
    state = get_state_input(data)
    new_population = check_int(input("Enter a new population (whole numbers only >= 0): "))

    us.update_state(state, "population", new_population)
    us.print_state(state)

def exit_program(us):
    """ Exits the Program
    """
    print("Thank you for participating! Goodbye.")
    sys.exit()

def get_state_input(data):
    """ Prompts the user for a valid US state.

    Args:
        data (dict): [A dictionary of the U.S states and appropriate info]

    Returns:
        string: A valid U.S state given by the user.
    """
    state = input("Please enter a valid US state to search/update: ").strip()

    state_names = state.split(" ")

    if len(state_names) > 1:
        for state_concat in state_names:
            state_concat.strip().capitalize()

        state = state_names[0] + " " + state_names[1]
    else:
        state = state.capitalize()

    if state in data.keys():
        return state

    return get_state_input(data)

def check_input(response):
    """Checks if the user wants to return to the menu

    Args:
        response (string): the user's input

    Returns:
        string: the user's input
    """

    if response == "<":
        run()

    return response

def run():
    """ Displays menu options and prompts the user for a menu option.
    """
    options = {
        "1": display_data,
        "2": search_data,
        "3": display_bar,
        "4": update_population,
        "5": exit_program
    }

    while 1:
        print("\nWelcome to the Python State Capital and Flower List Application\n" +
            "\n1: Display all U.S. States in Alphabetical order",
            "along with the Capital, State Population, and Flower" +
            "\n2: Search for a specific state and display the appropriate" +
            "Capital name, State Population, and an image of the associated State Flower." +
            "\n3: Provide a Bar graph of the top 5 populated States",
            "showing their overall population." +
            "\n4. Update the overall state population for a specific state." +
            "\n5. Exit the program")
        print("\nEnter '<' to return to the menu at any time.\n")

        option = input("Enter an option: ").strip()

        if option in options.keys():
            us = generator()
            options[option](us)
        else:
            print("Please enter a valid menu option.")


#!flask/bin/python
from app import create_app, db
from flask.ext.script import Manager, Shell, Command, Option
from flask.ext.migrate import Migrate, MigrateCommand
from app.models import User, Role, Album, Directory, Photo, ExifData
import os

if os.path.exists('.env'):
	print('Importing environment from .env...')
	for line in open('.env'):
		var = line.strip().split('=')
		if len(var) == 2:
			os.environ[var[0]] = var[1]
			os.putenv(var[0], var[1])

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)

def make_shell_context():
	return dict(app=app, db=db, User=User, Role=Role,
			Album=Album, Directory=Directory,
			Photo=Photo, ExifData=ExifData)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

@manager.command
def test():
	"""Run the unit tests."""
	import coverage
	cov = coverage.coverage(branch=True, include='app/*')
	cov.start()
	import unittest
	tests = unittest.TestLoader().discover('tests')
	unittest.TextTestRunner(verbosity=2).run(tests)
	cov.stop()
	cov.save()
	print('Coverage Summary:')
	cov.report()
	cov.erase()

def _get_pybabel():
	import sys
	if sys.platform == 'win32':
		pybabel = 'flask\\Scripts\\pybabel'
	else:
		pybabel = 'flask/bin/pybabel'
	return pybabel

BabelCommand = Manager(usage='Perform pybabel related tasks')

@BabelCommand.command
def update(babel_cfg = 'app/babel.cfg', translations_dir = 'app/translations', pot_file='app/translations/messages.pot'):
	"""Update catalogs with new texts."""
	pybabel = _get_pybabel()
	os.system(pybabel + ' extract -F ' + babel_cfg + ' -k lazy_gettext -o ' + pot_file + ' app')
	os.system(pybabel + ' update -i ' + pot_file + ' -d ' + translations_dir)

@BabelCommand.command
def compile(translations_dir = 'app/translations'):
	"""Compile the catalogs."""
	pybabel = _get_pybabel()
	os.system(pybabel + ' compile -d ' + translations_dir)

@BabelCommand.command
def init(language, translations_dir = 'app/translations', pot_file='app/translations/messages.pot'):
	"""Init new language catalogs."""
	pybabel = _get_pybabel()
	os.system(pybabel + ' init -i ' + pot_file + ' -d ' + translations_dir + ' -l ' + language)

manager.add_command('babel', BabelCommand)

if __name__ == "__main__":
	manager.run()


# -*- coding:utf-8 -*-
# Author: ssdcxy
# Date: 2020-03-10 09:36:36
# LastEditTime: 2020-03-10 09:59:39
# LastEditors: ssdcxy
# Description: 剪绳子 II
# FilePath: /arithmetic_oj/JianzhiOffer/14-2.py

class Solution:
    def cuttingRope(self, n: int) -> int:
        def helper(x, a, b):
            rem = 1
            while a > 0:
                if a % 2: rem = (rem * x) % 1000000007
                x = x ** 2 % 1000000007
                a //= 2
            return rem
        if n <= 3: return n - 1
        a, b= n // 3 - 1, n % 3
        rem = helper(3, a, b)
        if b == 0: return (rem * 3) % 1000000007
        if b == 1: return (rem * 4) % 1000000007
        return (rem * 6) % 1000000007

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            n = int(line);

            ret = Solution().cuttingRope(n)

            out = str(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()


import os
import logging

from homescraper.config import parse_config
from homescraper.providers import get_apartments
from homescraper.exceptions import UnknownSearchProvider
from homescraper.db import ApartmentDb
from homescraper.notification import notify_new_apartment

_logger = logging.getLogger(__name__)

def scrape_apartments(config_path):
    queries, db_path, twilio = parse_config(config_path)
    _logger.info(f'Loaded {len(queries)} queries..')

    new_db = False
    if not os.path.exists(db_path):
        new_db = True

    db = ApartmentDb(db_path)

    new_apartments = []
    for q in queries:
        _logger.info('Searching new apartments for query "%s".. ' % q['name'])
        try:
            apartments = get_apartments(q['url'], q.get('count', 50))
            _logger.info(f'Returned {len(apartments)} apartments.. ')

            count = 0
            for apartment in apartments:
                if db.add_apartment(apartment):
                    new_apartments.append(apartment)
                    count += 1

            _logger.info(f'found {count} new apartments')
        except UnknownSearchProvider:
            _logger.info('skipping: unknown provider')

    if not new_db and len(new_apartments) < 3:
        for new_apt in new_apartments:
            notify_new_apartment(twilio['sid'], twilio['token'], twilio['from'], twilio['to'], new_apt)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2016/6/15 22:52

@project: spbgcapital homepage
@version: 0.99
@file: spbgcapital.py
@author: SPBG Co.,Ltd. ing / 北京正民惠浩投资管理有限公司 ing
@contact: ing@spbgcapital.com
@site: http://www.spbgcapital.com
"""
import logging

from flask import Flask
from jinja2 import Environment, PackageLoader

from db.mysqldb.backup.sqlalchemydb import SqlalchemyDB

logging.basicConfig(level=logging.INFO)

# 获取网站渲染所有参数的类
class Website(object):
    page = ['home.html']

    def __init__(self, sqlsession):
        self.page = Website.page
        self.func = dict()
        self.cls = dict()
        for file in self.page:
            self.func[file] = file.split('.')[0]
            self.cls[file] = file.split('.')[0].capitalize()
            myobj = eval(self.cls[file]+'()')
            renderkw = myobj.get_render_kw(sqlsession)
            setattr(self, self.func[file], renderkw)

app = Flask(__name__)  # 初始化Flask
env = Environment(loader=PackageLoader('template', '/'))  # 初始化jinja2环境

# 初始化jinja2渲染参数对象
session = SqlalchemyDB('website.cfg').getsession()  # 获取sqlalchemy的session
web = Website(session)  # 初始化网页对象

@app.route('/', methods=['GET', 'POST'])
def home():
    template = env.get_template('home.html')
    view = template.render(**web.home)
    logging.info(view)
    return view

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


import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import ml_project
import Densities
import SCAN
import SCANL

atom = Densities.Atom("xe")

r, h = np.linspace(0.001, 10, 2000, retstep=True)

d0, d1, g0, g1, t0, t1, l0, l1 = atom.get_densities(r)

""" making sure that the values of these parameters are not very very less"""
idxs = (d0+d1) > 1e-10
r = r[idxs]
d0 = d0[idxs]
d1 = d1[idxs]
g0 = g0[idxs]
g1 = g1[idxs]
t0 = t0[idxs]
t1 = t1[idxs]
l0 = l0[idxs]
l1 = l1[idxs]

radius=ml_project.Wigner_Seitz_radius(d0+d1)
zeta = ml_project.spin_polarization(d0,d1)
reduced_density = ml_project.reduced_density_gradient(g0+g1, d0+d1)
reduced_laplacian = ml_project.reduced_density_laplacian(l0+l1, d0+d1)
uniform = ml_project.uniform(radius)
Ec_0 = SCAN.corgga_0(SCAN.DEFAULT_C_PARAMS, radius, reduced_density, zeta)
Ec_1 = SCAN.corgga_1(SCAN.DEFAULT_C_PARAMS, radius,reduced_density , zeta)
gx =   SCAN.get_gx(SCAN.DEFAULT_X_PARAMS,reduced_density**2)
g_constant = np.full_like(gx, 1.174)

def h1(s):
    d1 = ((10*s**2)/81)/0.064
    d2 = 1+d1
    v1 = 0.064/d2
    v2 = 1.064-v1
    return v2
h1 = h1(reduced_density)

radius = 1/(1+radius)
reduced_density = 1/(1+reduced_density)
reduced_laplacian = np.tanh(reduced_laplacian)
dx_zeta = 0.5*((1+zeta)**(4/3)+(1-zeta)**(4/3))

""" obtaining test data and e_x_uniform electron gas from the above import python file"""
X_test_processed= np.vstack([radius, reduced_density, reduced_laplacian,dx_zeta, Ec_0, Ec_1, gx, g_constant, h1]).T

""" running tensor flow and obtaining F_xc for the trained model using a test set"""
""" loading a saved model too here"""
fig = plt.figure()

ax1 = fig.add_subplot(111)

with tf.Session() as sess:
    new_saver1 = tf.train.import_meta_graph('/Users/kanun/Desktop/ML_project/python_code/new/new.meta')
    graph1=new_saver1.restore(sess, tf.train.latest_checkpoint('./new'))

    graph1 = tf.get_default_graph()

    X1 = graph1.get_tensor_by_name('X:0')
    feed_dict = {X1:X_test_processed}

    predict1 = graph1.get_tensor_by_name('predict:0')
    Fxc_out1= sess.run(predict1, feed_dict)
"""
f= open("/Users/kanun/Desktop/Fxc.txt","w")
data = Fxc_out1
np.savetxt(f, data,fmt='%.8f' )
f.close()
"""
Exc_ML1 = 4*math.pi*h*Fxc_out1.squeeze()*uniform*r**2*(d0+d1)
E_xc1 = np.sum(Exc_ML1)
"""
with tf.Session() as sess:
    new_saver2 = tf.train.import_meta_graph('/Users/kanun/Desktop/ML_project/python_code/relu_tanh/rt.meta')
    graph2=new_saver2.restore(sess, tf.train.latest_checkpoint('./relu_tanh'))

    graph2 = tf.get_default_graph()

    X1 = graph2.get_tensor_by_name('X:0')
    feed_dict = {X1:X_test_processed}

    predict2 = graph2.get_tensor_by_name('predict:0')
    Fxc_out2= sess.run(predict2, feed_dict)
Exc_ML2 = 4*math.pi*h*Fxc_out2.squeeze()*uniform*r**2*(d0+d1)
E_xc2 = np.sum(Exc_ML2)
"""
""" SCAN Fxc"""
ex = SCAN.getscan_x(SCAN.DEFAULT_X_PARAMS, d0, d1, g0, g1, t0, t1)
ec = SCAN.getscan_c(SCAN.DEFAULT_C_PARAMS, d0, d1, g0, g1, t0, t1, zeta)
e_xc = ex+ec
Fxc_SCAN = e_xc/(uniform*(d0+d1))

epp_xc_SCAN = 4*math.pi*h*e_xc*r**2
Exc_SCAN = np.sum(epp_xc_SCAN)

""" spin 0"""

radius_0=ml_project.Wigner_Seitz_radius(d0)
#zeta = ml_project.spin_polarization(d0)
reduced_density_0 = ml_project.reduced_density_gradient(g0, d0)
reduced_laplacian_0 = ml_project.reduced_density_laplacian(l0, d0)

Ft0 = 1

def Ft2(s, q):
    Ft2 = ((5/27)*(s**2))+((20/9)*q)
    return Ft2
Ft2_spin0 = Ft2(reduced_density_0,reduced_laplacian_0)

def Ft4(s,q):
    Ft4 = ((8/81)*(q**2))-((1/9)*(s**2)*q)+((8/243)*(s**4))
    return Ft4
Ft4_spin0 = Ft4(reduced_density_0,reduced_laplacian_0)

def Ftw(s):
    Ftw = (5/3)*(s**2)
    return Ftw
Ftw_spin0 = Ftw(reduced_density_0)

def FtMGE4(ft0,ft2,ft4,ftw):
    numerator = ft0+ft2+ft4
    den1 = ft4/(1+ftw)
    den2 = den1**2
    den3 = 1+den2
    den4 = np.sqrt(den3)
    FtMGE4 = numerator/den4
    return FtMGE4
FtMGE4_spin0 = FtMGE4(Ft0, Ft2_spin0, Ft4_spin0, Ftw_spin0)

def z_pc(ftmge4,ftw):
    z_pc = ftmge4-ftw
    return z_pc
z_pc_spin0 = z_pc(FtMGE4_spin0,Ftw_spin0)
z_pc_spin0 = np.around(z_pc_spin0,2)

def theta_pc(z_pc):
    a = 1.784720
    b = 0.258304
    theta_pc = np.zeros(z_pc.shape)
    idxs = (z_pc > 0)*(z_pc < a)
    theta_pc[idxs] = ((1+ np.exp(a/(a-z_pc[idxs])))/(np.exp(a/z_pc[idxs])+np.exp(a/(a-z_pc[idxs]))))**b
    theta_pc[z_pc >= a] = 1.0
    return theta_pc
theta_pc_spin0 = theta_pc(z_pc_spin0)

Ft_PC_spin0 = Ftw_spin0+z_pc_spin0*theta_pc_spin0
tau_UEG_spin0 = (3*(3*math.pi**2)**(2/3)*(d0)**(5/3))/10
tau_d_spin0 = Ft_PC_spin0*tau_UEG_spin0

"""for spin 1"""

radius1=ml_project.Wigner_Seitz_radius(d1)
#zeta = ml_project.spin_polarization(d1)
reduced_density_1 = ml_project.reduced_density_gradient(g1, d1)
reduced_laplacian_1 = ml_project.reduced_density_laplacian(l1, d1)

Ft0 = 1

def Ft2(s, q):
    Ft2 = ((5/27)*(s**2))+((20/9)*q)
    return Ft2
Ft2_spin1 = Ft2(reduced_density_1,reduced_laplacian_1)

def Ft4(s,q):
    Ft4 = ((8/81)*(q**2))-((1/9)*(s**2)*q)+((8/243)*(s**4))
    return Ft4
Ft4_spin1 = Ft4(reduced_density_1,reduced_laplacian_1)

def Ftw(s):
    Ftw = (5/3)*(s**2)
    return Ftw
Ftw_spin1 = Ftw(reduced_density_1)

def FtMGE4(ft0,ft2,ft4,ftw):
    numerator = ft0+ft2+ft4
    den1 = ft4/(1+ftw)
    den2 = den1**2
    den3 = 1+den2
    den4 = np.sqrt(den3)
    FtMGE4 = numerator/den4
    return FtMGE4
FtMGE4_spin1 = FtMGE4(Ft0, Ft2_spin1, Ft4_spin1, Ftw_spin1)

def z_pc(ftmge4,ftw):
    z_pc = ftmge4-ftw
    return z_pc
z_pc_spin1 = z_pc(FtMGE4_spin1,Ftw_spin1)
z_pc_spin1 = np.around(z_pc_spin1,2)
def theta_pc(z_pc):
    a = 1.784720
    b = 0.258304
    theta_pc = np.zeros(z_pc_spin1.shape)
    idxs = (z_pc > 0)*(z_pc < a)
    theta_pc[idxs] = ((1+ np.exp(a/(a-z_pc[idxs])))/(np.exp(a/z_pc[idxs])+np.exp(a/(a-z_pc[idxs]))))**b
    theta_pc[z_pc >= a] = 1.0
    return theta_pc
theta_pc_spin1 = theta_pc(z_pc_spin1)

Ft_PC_spin1 = Ftw_spin1+z_pc_spin1*theta_pc_spin1
tau_UEG_spin1 = (3*(3*math.pi**2)**(2/3)*(d1)**(5/3))/10
tau_d_spin1 = Ft_PC_spin1*tau_UEG_spin1

""" total density"""

radius=ml_project.Wigner_Seitz_radius(d0+d1)
zeta = ml_project.spin_polarization(d0,d1)
reduced_density = ml_project.reduced_density_gradient(g0+g1, d0+d1)
reduced_laplacian = ml_project.reduced_density_laplacian(l0+l1, d0+d1)

Ft0 = 1

def Ft2(s, q):
    Ft2 = ((5/27)*(s**2))+((20/9)*q)
    return Ft2
Ft2 = Ft2(reduced_density,reduced_laplacian)

def Ft4(s,q):
    Ft4 = ((8/81)*(q**2))-((1/9)*(s**2)*q)+((8/243)*(s**4))
    return Ft4
Ft4 = Ft4(reduced_density,reduced_laplacian)

def Ftw(s):
    Ftw = (5/3)*(s**2)
    return Ftw
Ftw = Ftw(reduced_density)

def FtMGE4(ft0,ft2,ft4,ftw):
    numerator = ft0+ft4+ftw
    den1 = ft4/(1+ftw)
    den2 = den1**2
    den3 = 1+den2
    den4 = np.sqrt(den3)
    FtMGE4 = numerator/den4
    return FtMGE4
FtMGE4 = FtMGE4(Ft0, Ft2, Ft4, Ftw)

def z_pc(ftmge4,ftw):
    z_pc = ftmge4-ftw
    return z_pc
z_pc = z_pc(FtMGE4,Ftw)
z_pc = np.around(z_pc,2)
def theta_pc(z_pc):
    a = 1.784720
    b = 0.258304
    theta_pc = np.zeros(z_pc.shape)
    idxs = (z_pc > 0)*(z_pc < a)
    theta_pc[idxs] = ((1+ np.exp(a/(a-z_pc[idxs])))/(np.exp(a/z_pc[idxs])+np.exp(a/(a-z_pc[idxs]))))**b
    theta_pc[z_pc >= a] = 1.0
    return theta_pc
theta_pc = theta_pc(z_pc)

Ft_PC = Ftw+z_pc*theta_pc
ds_zeta = (np.power(1.0 + zeta, 5.0/3.0) + np.power(1.0 - zeta, 5.0/3.0))/2.0
tau_UEG = (3*(3*math.pi**2)**(2/3)*(d0+d1)**(5/3))/10
tau_UEG = tau_UEG*ds_zeta
tau_d_total = Ft_PC*tau_UEG

ex = SCANL.getscan_x(SCANL.DEFAULT_X_PARAMS, d0, d1, g0, g1, tau_d_spin0, tau_d_spin1)
ec = SCANL.getscan_c(SCANL.DEFAULT_C_PARAMS, d0+d1, g0+g1, tau_d_total, zeta)
e_xc = ex+ec
Fxc_scanl = e_xc/(uniform*(d0+d1))

epp_xc_scanl = 4*math.pi*h*e_xc*r**2
Exc_scan_l = np.sum(epp_xc_scanl)

size = 0.4
ax1.plot(r,Fxc_SCAN, color = 'black', label = '$F_{xc}[SCAN]$')
ax1.plot(r, Fxc_out1.squeeze(),'--' ,color = 'red', label = '$F_{xc}[ML]$')
ax1.plot(r, Fxc_scanl,'--' ,color = 'blue', label = '$F_{xc}[SCANL]$')
#ax1.plot(r, Fxc_scanl,':' ,color = 'blue', label = '$F_{xc}[SCAN-L]$')
ax1.set_ylim([0,1.8])
ax1.set_xlim(0,9)
ax1.legend()
ax1.set_ylabel('$F_{xc}$',fontsize=12)
ax1.set_xlabel('r ($a_{0}$)',fontsize=12)
ax1.tick_params(direction= 'in')
plt.xticks(fontsize = 10)
plt.yticks(fontsize = 10)
plt.legend(loc = 0, fontsize = 'small')
plt.text(0.8,0.7, "Silicon:",color = 'black', fontsize = 12)
plt.text(0.5, 0.6, "E${}_{xc}$[ML]:    "+"{:.6f} $E_h$" .format(E_xc1), color = 'black',fontsize = 12)
plt.text(0.5, 0.5, "E${}_{xc}$[SCAN]: "+"{:.6f} $E_h$ " .format(Exc_SCAN),color = 'black', fontsize = 12)
#plt.text(0.5, 0.3, "E${}_{xc}$[ML-relu_tanh]:    "+"{:.6f} $E_h$" .format(E_xc2), color = 'black',fontsize = 12)
plt.text(0.5, 0.3, "E${}_{xc}$[SCAN-L]: "+"{:.6f} $E_h$ " .format(Exc_scan_l),color = 'black', fontsize = 12)
plt.tight_layout()
plt.show()


#coding:UTF-8
import socket
import datetime
import threading

def socket_udp_server():
	s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#SOCK_DGRAM指类型是UDP
	host='192.168.0.2'#监听指定的ip,host=''即监听所有的ip
	port=8080
    #绑定端口
	s.bind((host,port))
	while True:
		data,addr=s.recvfrom(1024)
		if data:
			print(data)
			print("卡号："+data[16:26].decode('ascii')+"时间："+data[26:33].decode('ascii'))
			if data[-4:-2].decode('ascii')=="0C":
				now=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
				sdt="JTP"+data[3:8].decode('ascii')+"00100C"+now+"73"
				print(sdt)
				s.sendto(sdt.encode('utf-8'),addr)
			else:
				sdt="JTP"+data[3:8].decode('ascii')+"00040BOKBD"
				print(sdt)
				s.sendto(sdt.encode('utf-8'),addr)
		else:
			continue

def main():
	p = threading.Thread(target=socket_udp_server, )
	p.start()

main()


"""empty message

Revision ID: d4fa3c88f984
Revises:
Create Date: 2023-07-05 14:30:16.151008

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'd4fa3c88f984'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('characters',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('head_img', sa.String(), nullable=True),
    sa.Column('main_img', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_characters'))
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('characters')
    # ### end Alembic commands ###


"""
Author:		Chris Wailes <chris.wailes@gmail.com>
Project:		Ouroboros
Date:		2010/09/01
Description:	A transformation that flattens the provided AST.
"""

from assembler.tagging import OBJ

from lib.ast import *
from lib import util

from lib.symbol_table import SymbolTable

analysis	= []
args		= []

def init():
	from transforms.pass_manager import register
	register('flatten', flatten, analysis, args)

def flatten(node, st = None, inPlace = False):
	newChildren	= []
	newInPlace	= None
	preStmts		= []

	# Setup flattening for this node's children.
	if util.classGuard(node, Assign, BasicBlock, Module):
		newInPlace = node.__class__

	elif isinstance(node, Function):
		st = node.st

	# Flatten our children.
	if isinstance(node, While):
		if not isinstance(node.cond, Symbol):
			condBody, node.cond = flatten(node.cond, st)
			node.condBody = BasicBlock(condBody)

		bodyPreStmts, node.body = flatten(node.body, st)
		preStmts.append(bodyPreStmts)

	elif isinstance(node, If):
		for child in node:
			childPreStmts, newChild = flatten(child, st, newInPlace)

			preStmts.append(childPreStmts)
			newChildren.append(newChild)

		# Set our new child nodes.
		newChildren = util.flatten(newChildren)
		node.setChildren(newChildren)

	else:
		for child in node:
			childPreStmts, newChild = flatten(child, st, newInPlace)

			if isinstance(node, BasicBlock):
				newChildren.append(childPreStmts)
				newChildren.append(newChild)

			else:
				preStmts.append(childPreStmts)
				newChildren.append(newChild)

		# Set our new child nodes.
		newChildren = util.flatten(newChildren)
		node.setChildren(newChildren)

	# Flatten the current node.
	if classGuard(node, BinOp, FunctionCall, IfExp, UnaryOp) and not inPlace:
		sym = st.getTemp()
		preStmts.append(Assign(sym, node))

		node = sym

	# Flatten our list of pre-statements.
	preStmts = util.flatten(preStmts)

	return node if isinstance(node, Module) else (preStmts, node)


import fbchat
from datetime import datetime, timedelta
from pontozobiztos import chatmongo, chatscheduler
import pytz
import re
import random

group_thread: fbchat.GroupData

def init(thread, *args, **kwargs):
    global group_thread
    group_thread = thread

    sched = chatscheduler.get_scheduler()
    # sched.add_job(callback, 'cron', hour='7,20', minute=30)
    sched.add_job(callback, 'cron', hour='8,20', minute=8)

def on_message(message, author):
    """
        Args:
            message (fbchat.MessageData)
            author(models.User.User)
    """
    pass

def top_n_most_reactions(year: int, n=3):
    from_date = datetime.today().replace(year=year, hour=0, minute=0, second=0,
                                         microsecond=0, tzinfo=pytz.UTC)
    to_date = from_date + timedelta(days=1)
    res = chatmongo.get_message_collection().aggregate([
        {'$match': {'created_at': {'$gte': from_date, '$lt': to_date}}},
        {"$project": {
            "_id": 1,
            "author": 1,
            "reactions": {"$objectToArray": "$reactions"}}},
        {"$unwind": "$reactions"},
        {"$sort": {"_id": 1}},
        {"$group": {
            "_id": "$_id",
            "react_count": {"$sum": 1}}},
        {"$sort": {"react_count": -1}},
        {"$limit": n},
    ])
    return list(res)

def top_n_legacy_emojis(year, n=3):
    from_date = datetime.today().replace(year=year, hour=0, minute=0, second=0,
                                         microsecond=0, tzinfo=pytz.UTC)
    to_date = from_date + timedelta(days=1)
    res = chatmongo.get_message_collection().aggregate([
        {'$match': {'created_at': {'$gte': from_date, '$lt': to_date}}},
    ])
    res = list(res)

    smile_patterns = [r':d+', r'xd+', r'^lol.*']
    pat = re.compile(r'(?:' + '|'.join(smile_patterns) + ')')

    for i in range(len(res)):
        smile_count = 0
        for msg_later in res[i+1:]:
            if pat.search(msg_later['text'].lower()):
                smile_count += 1
            else:
                res[i]['smile_count'] = smile_count
                i += smile_count
                break

    res = [x for x in res if x.get('smile_count', 0) != 0]
    res.sort(key=lambda x: x.get('smile_count', 0), reverse=True)
    return res[:n]

def callback():
    top3 = []
    year = 0
    year_today = datetime.today().year
    while not top3:
        year = random.randint(2014, year_today - 1)
        top3 = top_n_most_reactions(year) or top_n_legacy_emojis(year)
    selected_msg = random.choice(top3)

    reply_text = f'Ezen a napon, {year_today - year} évvel ezelőtt'
    group_thread.send_text(text=reply_text, reply_to_id=selected_msg['_id'])


# coding=gbk
from locust import HttpUser, task, HttpLocust, between
import os
import json
import random
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from utils.ReadFileUtils import ReadFileUtils
import configparser
config = configparser.ConfigParser()
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

class TaskLocust(HttpUser):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.userIds = ReadFileUtils().readCsvFile(r'C:\Users\dyd9981\PycharmProjects\pythonProject8\sources\userIdsList')
    @task(1)
    def CFG(self):
            # req = self.client.get("请求地址", headers=,data, verify=False)   返回的req为接口返回的相关信息
            req = self.client.get("/boss/system/check/mongoUserMatch?1=1", headers={}, verify=False)
            if req.status_code == 200:
                print("success")
            else:
                print("fails")
            print("接口返回" + json.dumps(req.json(), indent=2));

            req = self.client.get("/boss/system/check/userInfoByIdForMysql?userId=109856", headers={}, verify=False)
            if req.status_code == 200:
                print("success")
            else:
                print("fails")
            print("接口返回" + json.dumps(req.json(), indent=2));
            # post 请求
            # req = self.client.post("/api/api/",data={"MY_APP_VERSION": "1.1.0", },verify=False)# 避免ssl认证
            # if req.status_code == 200:
            #     print("success")
            # else:
            #     print("fails")
    # @task(1)
    # def MYsql(self):
    #         req = self.client.get("/boss/system/check/userInfoByIdForMysql?userId=109856", headers={}, verify=False)
    #         if req.status_code == 200:
    #             print("success")
    #         else:
    #             print("fails")
    #         print("接口返回" + json.dumps(req.json(), indent=2));

    # @task(1)
    # def Redis(self):
    #         req = self.client.get("/boss/system/check/userInfoByIdForRedis?userId=109856", headers={}, verify=False)
    #         if req.status_code == 200:
    #             print("success")
    #         else:
    #             print("fails")
    #         print("接口返回" + json.dumps(req.json(), indent=2));
    #
    # @task(5)
    # def RedisToMap(self):
    #         req = self.client.get("/boss/system/check/userInfoByIdForRedisToMap?userId=109856", headers={}, verify=False)
    #         if req.status_code == 200:
    #             print("success")
    #         else:
    #             print("fails")
    #         print("接口返回" + json.dumps(req.json(), indent=2));

if __name__ == "__main__":
    # locust -f 执行文件名称  --host= 压测域名  --web-host=可视化界面的指定路由
    min_wait = 2000
    max_wait = 3000
    os.system("locust -f 0704.py --host=https://test-middle.51k1k.com:443  --web-host=192.168.40.195")   # 测试


from random import randint
import matplotlib.pyplot as plt

tot = 0
antant = 1000
sim = []
for i in range(1, antant+1):
    person1 = 0
    ant = 100_000
    for rulett in range(ant):
        gønner = [0 for x in range(6)]
        gønner[randint(0, 5)] = 1

        if gønner.index(1)%2 == 0:
            person1 += 1

    sim.append(tot/i)

    print(i, person1/ant, tot/i)
    if person1/ant > 0.5:
        tot+=1

print(tot/antant)

plt.plot(sim)
plt.show()


#!/usr/bin/python3
"""This script takes in a URL, sends a request to the URL and displays
    the body of the response"""

if __name__ == "__main__":
    import requests
    import sys
    i = requests.get(sys.argv[1])
    if i.status_code == requests.codes.ok:
        print(i.text)
    else:
        print("Error code: {}".format(i.status_code))


# -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 11:22:44 2019

@author: ZohrehRaziei
"""

"""
Porgrammer Zohreh Raziei: zohrehraziei@gmail.com
vehicle Routing Problem with using Heuristic with Valid Inequality

"""
import math
import random
import networkx
from gurobipy import *

def vrp(V,c,m,q,Q,veh_set,hobj):
    def vrp_callback(model,where):

        # remember to set     model.params.DualReductions = 0     before using!
        # remember to set     model.params.LazyConstraints = 1     before using!
        if where != GRB.callback.MIPSOL:
            return
        edges = []
        for (i,j) in x:
            if model.cbGetSolution(x[i,j]) > .5:
                if i != V[0] and j != V[0]:
                    edges.append( (i,j) )
        G = networkx.Graph()
        G.add_edges_from(edges)
        Components = networkx.connected_components(G)
        for S in Components:
            S_card = len(S)
            q_sum = sum(q[i] for i in S)
            NS = int(math.ceil(float(q_sum)/Q))
            S_edges = [(i,j) for i in S for j in S if i<j and (i,j) in edges]
            if S_card >= 3 and (len(S_edges) >= S_card or NS > 1):
                model.cbLazy(quicksum(x[i,j] for i in S for j in S if j > i) <= S_card-NS)
                print ("adding cut for",S_edges)
        return

    model = Model("vrp")
    model.setParam('LogToConsole',0)
    x = {}
    for i in V:
        for j in V:
            if j > i and i == V[0]:       # depot
                x[i,j] = model.addVar(ub=2, vtype="I", name="x(%s,%s)"%(i,j))
            elif j > i:
                x[i,j] = model.addVar(ub=1, vtype="I", name="x(%s,%s)"%(i,j))
    model.update()

    model.addConstr(quicksum(x[V[0],j] for j in V[1:]) == 2*m, "DegreeDepot")
    model.addConstr(quicksum(c[i,j]*x[i,j] for i in V for j in V if j>i) <= hobj, "UpperBound")
    for veh in veh_set:
        idx = veh_set.index(veh)
        if idx < len(veh_set)-1:
            min_idx = min(veh[-1],veh_set[idx+1][0])
            max_idx = max(veh[-1],veh_set[idx+1][0])
            rhs = len(veh)+2
            model.addConstr(x[1,veh[1]] + x[1,veh[-1]] + quicksum(x[min(veh[j],veh[j+1]),max(veh[j],veh[j+1])]  for j in range(len(veh)-1) ) + x[min_idx,max_idx] <= rhs, "Valid(%s)"%idx)
            for nd in V:
                if nd != V[0]:
                    model.addConstr(x[1,veh[1]] + x[1,veh[-1]] + quicksum(x[min(veh[j],veh[j+1]),max(veh[j],veh[j+1])] for j in range(len(veh)-1) ) + x[1,nd] <= rhs, "Valid2(%s)"%idx)

    for i in V[1:]:
        model.addConstr(quicksum(x[j,i] for j in V if j < i) +
                        quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i)

    model.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j>i), GRB.MINIMIZE)

    model.update()
    model.__data = x
    return model,vrp_callback

def distance(x1,y1,x2,y2):
    """distance: euclidean distance between (x1,y1) and (x2,y2)"""
    return math.sqrt((x2-x1)**2 + (y2-y1)**2)

def make_data(n):
    """make_data: compute matrix distance based on euclidean distance"""
    V = range(1,n+1)
    #x = dict([(i,random.random()) for i in V])
    #y = dict([(i,random.random()) for i in V])
    c,q,x,y = {},{},{},{}
    Q = 100
    for i in V:
     #   q[i] = random.randint(10,20)
       # Valuee[i] = random.randint(20,30)
        for j in V:
            if j > i:
                c[i,j] = distance(x[i],y[i],x[j],y[j])

    return V,c,q,Q,vlu

def read_data():
    import xlrd
    file_loc=".\\dist.xlsx"
    wkb=xlrd.open_workbook(file_loc)
    dat_mat = []
    nrow = 0
    for sht in range(2): #Three sheets: 0:c[i,j] 1:q[j], 2:vlu[j]
        sheet=wkb.sheet_by_index(sht)
        _matrix=[]
        nrow = 0
        for row in range (sheet.nrows):
            _row = []
            nrow += 1
            for col in range (sheet.ncols):
                _row.append(sheet.cell_value(row,col))
            _matrix.append(_row)
        dat_mat.append(_matrix)

    V = range(1,nrow+1)
    c,q,x,y = {},{},{},{}
    Q = 100
   # q = {}
    for i in V:
        q[i] = dat_mat[1][i-1][0]
        x[i] = dat_mat[0][i-1][0]
        y[i] = dat_mat[0][i-1][1]
    for i in V:
        for j in V:
            if j > i:
                c[i,j] = distance(x[i],y[i],x[j],y[j])

#        for j in V:
#            if j > i:
#                c[i,j] = dat_mat[0][i-1][j-1]

    return V,c,q,Q

def represent(x):
    edges = []
    tour = ''
    for i in V:
        if i > V[0] and x[V[0],i].X > .5:
            cond = True
            for t in edges:
                if str(i) in t:
                    cond = False
                    break
            if cond == True:
                tour = str(V[0]) + ' - ' + str(i)
                nextn = i
                prevnext = nextn
                point = [str(V[0]) + ',' + str(i)]
                for v in V:
                    if nextn == V[0]:
                        break
                    for (ii,jj) in x:
                        e = str(ii) + ',' + str(jj)
                        if e not in point and x[ii,jj].X > .5:
                            if str(nextn) == str(ii):
                                point.append(str(ii) + ',' + str(jj))
                                tour += ' - ' + str(jj)
                                nextn = jj
                            elif str(nextn) == str(jj):
                                point.append(str(ii) + ',' + str(jj))
                                tour += ' - ' + str(ii)
                                nextn = ii
                            if nextn == V[0]:
                                edges.append(tour)
                                break
                if nextn == prevnext:
                    tour += ' - ' + str(V[0])
                    edges.append(tour)

    return edges

def heuristic_greedy(V,c,m,q,Q):
    demands = list(q.values())
    nodes = list(q.keys())
    measure = [demands[i-1]*(0.1/(c[(1,int(i))] if i != 1 and c[(1,int(i))] != 0 else 10000)) for i in nodes]
    veh_set = []
    obj = 0

    while len(demands) > 0:
        n1 = measure.index(max(measure))
        if len(nodes) > 1:
            veh = [nodes[n1]]
            obj += c[(1,nodes[n1])]
            C = Q - q[nodes[n1] - 1]
            measure.remove(measure[n1])
            nodes.remove(nodes[n1])
            while C > 0:
                ls = [c[(min(veh[-1],int(i)),max(veh[-1],int(i)))] for i in nodes if int(i) != 1]
                ls2 = [int(i) for i in nodes if int(i) != 1]
                if len(ls)>0:
                    n1 = int(ls2[ls.index(min(ls))])
                    C = C - q[n1 - 1]
                    obj += c[(min(veh[-1],int(n1)),max(veh[-1],int(n1)))]
                    veh.append(n1)
                    measure.remove(measure[nodes.index(n1)])
                    nodes.remove(n1)
                else:
                    break
            obj += c[(1,veh[-1])]
            veh_set.append(veh)
        else:
            break

    return veh_set, obj

def heuristic(V,c,m,q,Q):
    nodes = list(q.values())
    nodes2 = list(q.keys())
    veh_set = []
    obj = 0

    while len(nodes) > 0:
        n1 = nodes.index(max(nodes))
        if n1 > 1:
            veh = [n1]
            obj += c[(1,n1)]
            nodes.remove(q[n1])
            nodes2.remove(n1)
            C = Q - q[n1]
            while C > 0:
                ls = [c[(veh[-1],int(i))] for i in nodes2 if int(i) != 1 and i > veh[-1]]
                ls2 = [int(i) for i in nodes2 if int(i) != 1 and i > veh[-1]]
                if len(ls)>0:
                    n1 = int(ls2[ls.index(min(ls))])
                    C = C - q[n1]
                    obj += c[(veh[-1],n1)]
                    veh.append(n1)
                    nodes.remove(q[n1])
                    nodes2.remove(n1)
                else:
                    break
            obj += c[(1,veh[-1])]
            veh_set.append(veh)
        else:
            break

    print(veh_set)
    print ("objective: ", obj)

def var_print(x):
    for var in x:
        if x[var].X > 0.5:
            print (x[var])

if __name__ == "__main__":
    import sys
    import time

    #n = 20
    m = 10
    seed = 1
    random.seed(seed)
    #V,c,q,Q = make_data(n)
    V,c,q,Q = read_data()
    veh_set, obj = heuristic_greedy(V,c,m,q,Q)
    print ("heuristic objective: ", obj)
    print (veh_set)
    start_time2 = time.time()
    print("--- Running time: %s seconds ---" % (time.time() - start_time2))

    model,vrp_callback = vrp(V,c,m,q,Q,veh_set,obj)

    # model.Params.OutputFlag = 0 # silent mode
    # 0 : min value
    model.params.DualReductions = 0
    model.params.LazyConstraints = 1
    #1: Implies Gurobi algorithms to avoid certain reductions and transformations
    #that are incompatible with lazy constraints.
    start_time3 = time.time()
    model.optimize(vrp_callback)
    x = model.__data

    edges = represent(x)

    print ("Optimal objective:",model.ObjVal)
    print ("Edges in the solution:")
    print (sorted(edges))
    print ("Positive Vars: ")
    var_print(x)

    print("--- Running time valid inequalities: %s seconds ---" % (time.time() - start_time3))


# -*- coding: utf-8 -*-
"""
Created on Wed Mar  8 13:06:55 2023

@author: rayver
"""

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

# Import dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values

# Split dataset into train/test datasets
'''
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=0)
'''

# Fit linear regression with dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X,y)

# Fit polynomial regression with dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

# Visualization of the results of the Linear Model
plt.scatter(X, y, c = "red")
plt.plot(X, lin_reg.predict(X), c = "blue")
plt.title("Linear Regression Model")
plt.xlabel("Position of the employee")
plt.ylabel("Salary ($)")
plt.show()

# Visualization of the results of the Polynomial Model
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape(len(X_grid), 1) # Smooth
plt.scatter(X, y, c = "red")
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), c = "blue")
plt.title("Polynomial Regression Model")
plt.xlabel("Position of the employee")
plt.ylabel("Salary ($)")
plt.show()

# Predict of models
lin_reg.predict([[6.5]])
lin_reg_2.predict(poly_reg.fit_transform([[6.5]]))

2 - Regression/Section 6 - Polynomial Regression/polynomial_regression.py


"""
This is a utility script for the download and installation of chi-tech
dependencies.
"""
import os
import sys
import argparse
import textwrap
import subprocess
import shutil
from typing import Optional, TextIO

if sys.version_info.major < 3:
    raise Exception("Python version detected to be " +
                    str(sys.version_info.major) + "." +
                    str(sys.version_info.minor) +
                    " but is required to >= 3")

class TextColors:
    RED = "\033[31m"
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

error_beg = TextColors.RED
error_end = TextColors.ENDC

# ========================================== Process commandline arguments
arguments_help = textwrap.dedent('''\
Run the dependency builder.
''')

parser = argparse.ArgumentParser(
    description="This is a utility script for the download and installation" +
                "of chi-tech dependencies.",
    epilog=arguments_help
)

parser.add_argument(
    "-d", "--directory", default=None, type=str, required=True,
    help="Directory into which the dependencies will be installed"
)

parser.add_argument(
    "-j", "--jobs", default=4, type=int, required=False,
    help="Allow N compile jobs at once"
)

parser.add_argument(
    "-v", "--verbose", default=False, type=bool, required=False,
    help="Controls verbose failure"
)

parser.add_argument(
    "-dl", "--download_only", default=False, type=bool, required=False,
    help="Controls verbose failure"
)

argv = parser.parse_args()  # argv = argument values

# =========================================== Check stuff
# Check the test directory exists
if not os.path.isdir(argv.directory):
    raise NotADirectoryError(argv.directory)

install_dir = os.path.abspath(argv.directory)
print(f"Installation directory identified: {install_dir}")
print()
log_file = open(f"{install_dir}/log.txt", 'w')
log_file.write("***** ChiTech dependency configurator script *****\n\n")

# ========================================== Define versions and download paths
VERSION = 0
URL = 1
package_info = {
    "readline": ["8.0",
                 "ftp://ftp.gnu.org/gnu/readline/readline-8.0.tar.gz"],
    "ncurses": ["6.1",
                "https://invisible-mirror.net/archives/ncurses/ncurses-6.1.tar.gz"],
    "lua": ["5.4.6",
            "https://www.lua.org/ftp/lua-5.4.6.tar.gz"],
    "petsc": ["3.17.0",
              "https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-3.17.0.tar.gz"],
    "vtk": ["9.3.0.rc1",
            "https://www.vtk.org/files/release/9.3/VTK-9.3.0.rc1.tar.gz"]
}

log_file.write("Packages in the dependency list:\n")
for pkg in package_info:
    log_file.write(f"{pkg:9s}= {package_info[pkg][VERSION]}\n")
log_file.write("\n")

log_file.write("Download paths:\n")
for pkg in package_info:
    log_file.write(f"{pkg:9s}= {package_info[pkg][URL]}\n")
log_file.write("\n")

# ========================================== Define utilities
# ######################################
# Runs a subprocess
def ExecSub(command: str,
            out_log: Optional[TextIO] = subprocess.PIPE,
            err_log: Optional[TextIO] = subprocess.PIPE,
            env_vars=None):
    success = True

    if argv.verbose:
        print(f"command: {command}")

    result = subprocess.Popen(command,
                              stdout=out_log,
                              stderr=err_log,
                              shell=True,
                              env=env_vars)
    output, error = result.communicate()

    if result.returncode != 0:
        success = False

    outputstr = ""
    if output is not None:
        outputstr = output.decode('ascii')

    return success, error.decode("utf8"), outputstr

# ######################################
# Redefine make command for gnu
make_command = "make"
s, e, outstr = ExecSub(make_command + " --version")
if outstr.find("GNU Make") >= 0:
    make_command = "make OMAKE_PRINTDIR=gmake"

# ######################################
# Checks whether an executable exists
def CheckExecutableExists(thingname: str, thing: str):
    log_file.write(f"Checking for {thingname}:\n")
    log_file.flush()
    success, errorc, outstr = ExecSub(f"{thing} --version", out_log=log_file)
    if not success:
        log_file.write(errorc)
        print(error_beg + f"Valid {thingname} not found" + error_end)
        exit(1)
    else:
        log_file.write(f"{thingname} found\n\n")

# ###################################### Get package
# Downloads a package using either wget or curl
def DownloadPackage(downloader, url, pkg, ver):
    pkgdir = f"{install_dir}/downloads"
    log_file.write(f"Downloading {pkg.upper()} {ver} to \"{pkgdir}\" " +
                   f"with command: {downloader} {url}")
    download_cmd = f"{downloader}" if downloader == "wget" else f"{downloader}"
    output_cmd = "" if downloader == "wget" else f"--output {pkg}-{ver}.tar.gz"

    pkgdir_relative = os.path.relpath(pkgdir)

    print(f"Downloading {pkg.upper()} {ver} to \"{pkgdir_relative}\" " +
          f"with command:\n{download_cmd} {url} {output_cmd}", end="",
          flush=True)

    already_there = False
    if not os.path.exists(f"{install_dir}/downloads/{pkg}-{ver}.tar.gz"):
        ExecSub(f"{download_cmd} {url} {output_cmd}", out_log=log_file)

        if os.path.exists(f"{install_dir}/downloads/{pkg.upper()}-{ver}.tar.gz"):
            item = f"{pkg.upper()}-{ver}.tar.gz"
            shutil.move(f"{item}", f"{item.lower()}")
    else:
        already_there = True

    if os.path.exists(f"{install_dir}/downloads/{pkg}-{ver}.tar.gz"):
        there = f"Already downloaded" if already_there else ""
        print(f" {TextColors.OKGREEN}Success{TextColors.ENDC} {TextColors.OKCYAN}{there}{TextColors.ENDC}")
        log_file.write(f" Success {there}\n")
        return True
    else:
        print(error_beg + " Failure" + error_end)
        log_file.write(" Failure\n")
        return False

# Makes a directory if it does not exist yet
def MakeDirectory(dirpath: str):
    if not os.path.isdir(dirpath):
        os.mkdir(dirpath)

# Makes the necessary system calls to extract a tar.gz file
def ExtractPackage(pkg, ver):
    print(f"Extracting package with command tar -zxf {pkg}-{ver}.tar.gz")

    success, err, outstr = ExecSub(f"tar -zxf {pkg}-{ver}.tar.gz", log_file)

    if not success:
        print(err)
        exit(1)

    # Check if folder defaulted to upper
    if os.path.exists(f"{pkg.upper()}-{ver}") and not os.path.exists(f"{pkg}-{ver}"):
        success, err, outstr = ExecSub(f"mv {pkg.upper()}-{ver}/ {pkg}-{ver}/", log_file)

        if not success:
            print(err)
            exit(1)

    os.chdir(f"{pkg}-{ver}")

# ========================================== Check system environment
# Check for download utils
log_file.write("Checking for wget/curl: ")
downloader = ""
if shutil.which("wget") is None:
    log_file.write("wget not found. ")
    if shutil.which("curl") is None:
        log_file.write("curl not found. ")
        raise Exception("Neither wget nor curl found on this system. " +
                        "The script then has no means to download the " +
                        "dependencies.")
    else:
        log_file.write("curl found\n")
        downloader = "curl"
else:
    log_file.write("wget found\n")
    downloader = "wget"
# downloader = "curl"

# Check mpicc, mpicxx, mpifort
mpicc = os.getenv("CC") if len(os.getenv("CC")) > 0 else "mpicc"
mpicxx = os.getenv("CXX") if len(os.getenv("CXX")) > 0 else "mpicxx"
mpifort = os.getenv("FC") if len(os.getenv("FC")) > 0 else "mpifort"
CheckExecutableExists("mpicc", mpicc)
CheckExecutableExists("mpicxx", mpicxx)
CheckExecutableExists("mpifort", mpifort)

# Check cmake exists
CheckExecutableExists("cmake", "cmake")

# ========================================== Creating directories
MakeDirectory(f"{install_dir}/downloads")

# ========================================== Download packages
os.chdir(f"{install_dir}/downloads")
dl_errors = []
for pkg in package_info:
    if not DownloadPackage(downloader, package_info[pkg][URL], pkg,
                           package_info[pkg][VERSION]):
        dl_errors.append(pkg)
os.chdir(f"{install_dir}")

if len(dl_errors) > 0:
    log_file.write(
        "\nFailed to download the following packages:\n")
    for pkg in dl_errors:
        log_file.write(pkg + " ")
    log_file.write("\n")
    print(error_beg +
          f"Failed to download {len(dl_errors)} package(s)\n" +
          "Check that the url exists or that the platform you are on actually " +
          "actually allows it. You could also try to manually download these " +
          "packages from the url's below:\n")
    for pkg in dl_errors:
        print(f"{pkg:9s}= {package_info[pkg][URL]}")
    print(error_end)
    exit(1)

if argv.download_only:
    exit(0)

print()

# ========================================== Install command for ncurses and
# readline
def InstallPackage(pkg: str, ver: str, gold_file: str):
    package_log_filename = f"{install_dir}/{pkg.upper()}/{pkg}_log.txt"
    MakeDirectory(f"{install_dir}/{pkg.upper()}")
    pkg_install_dir = f"{install_dir}/{pkg.upper()}/{pkg}-{ver}/chi_build"

    shutil.copy(f"{install_dir}/downloads/{pkg}-{ver}.tar.gz",
                f"{install_dir}/{pkg.upper()}/{pkg}-{ver}.tar.gz")

    os.chdir(f"{install_dir}/{pkg.upper()}/")

    # Check if it is installed already
    if not os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        ExtractPackage(pkg, ver)

        package_log_file = open(package_log_filename, "w")

        print(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"", flush=True)
        log_file.write(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"")
        log_file.write(f" See {package_log_filename}\n")
        log_file.flush()

        env_vars = os.environ.copy()
        if len(os.getenv("CC")) == 0:
            env_vars["CC"] = shutil.which("mpicc")
        if len(os.getenv("CXX")) == 0:
            env_vars["CXX"] = shutil.which("mpicxx")
        if len(os.getenv("FC")) == 0:
            env_vars["FC"] = shutil.which("mpifort")

        command = f"./configure --prefix={pkg_install_dir}"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = f"make -j{argv.jobs}"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = "make install"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        package_log_file.close()
    else:
        print(f"{pkg.capitalize()} already installed")

    os.chdir(install_dir)

    if os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        return True
    else:
        return False

# ========================================== Install command for lua
def InstallLuaPackage(pkg: str, ver: str, gold_file: str,
                      readline_install: str,
                      ncurses_install: str):
    package_log_filename = f"{install_dir}/{pkg.upper()}/{pkg}_log.txt"
    MakeDirectory(f"{install_dir}/{pkg.upper()}")
    pkg_install_dir = f"{install_dir}/{pkg.upper()}/{pkg}-{ver}/install"

    shutil.copy(f"{install_dir}/downloads/{pkg}-{ver}.tar.gz",
                f"{install_dir}/{pkg.upper()}/{pkg}-{ver}.tar.gz")

    os.chdir(f"{install_dir}/{pkg.upper()}/")

    # Check if it is installed already
    if not os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        ExtractPackage(pkg, ver)

        package_log_file = open(package_log_filename, "w")

        print(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"", flush=True)
        log_file.write(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"")
        log_file.write(f" See {package_log_filename}\n")
        log_file.flush()

        env_vars = os.environ.copy()
        if len(os.getenv("CC")) == 0:
            env_vars["CC"] = shutil.which("mpicc")
        if len(os.getenv("CXX")) == 0:
            env_vars["CXX"] = shutil.which("mpicxx")
        if len(os.getenv("FC")) == 0:
            env_vars["FC"] = shutil.which("mpifort")

        lib_path = env_vars.get("LIBRARY_PATH", "")
        lib_path = f"{lib_path}:{readline_install}/lib:" \
                   f"{ncurses_install}/lib"
        env_vars["LIBRARY_PATH"] = lib_path

        c_path = env_vars.get('CPATH', "")
        c_path = f"{c_path}:{readline_install}/include"
        env_vars["CPATH"] = c_path

        os_tag = "linux"
        if "Darwin" in os.uname():
            os_tag = "macosx"

        command = f"make {os_tag} MYCFLAGS=-fPIC MYLIBS=-lncurses -j{argv.jobs}"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = "make local"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        package_log_file.close()
    else:
        print(f"{pkg.capitalize()} already installed")

    os.chdir(install_dir)

    if os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        return True
    else:
        return False

# ========================================== Install command for PETSc
def InstallPETSC(pkg: str, ver: str, gold_file: str):
    package_log_filename = f"{install_dir}/{pkg.upper()}/{pkg}_log.txt"
    MakeDirectory(f"{install_dir}/{pkg.upper()}")
    pkg_install_dir = f"{install_dir}/{pkg.upper()}/{pkg}-{ver}-install"

    shutil.copy(f"{install_dir}/downloads/{pkg}-{ver}.tar.gz",
                f"{install_dir}/{pkg.upper()}/{pkg}-{ver}.tar.gz")

    os.chdir(f"{install_dir}/{pkg.upper()}/")

    # Check if it is installed already
    if not os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        ExtractPackage(pkg, ver)

        package_log_file = open(package_log_filename, "w")

        print(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"", flush=True)
        log_file.write(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"")
        log_file.write(f" See {package_log_filename}\n")
        log_file.flush()

        env_vars = os.environ.copy()
        if len(os.getenv("CC")) == 0:
            env_vars["CC"] = shutil.which("mpicc")
        if len(os.getenv("CXX")) == 0:
            env_vars["CXX"] = shutil.which("mpicxx")
        if len(os.getenv("FC")) == 0:
            env_vars["FC"] = shutil.which("mpifort")

        command = f"./configure --prefix={pkg_install_dir}"
        command += """ \\
--download-hypre=1  \\
--with-ssl=0  \\
--with-debugging=0  \\
--with-pic=1  \\
--with-shared-libraries=1  \\
--download-fblaslapack=1  \\
--download-metis=1  \\
--download-parmetis=1  \\
--download-superlu_dist=1  \\
--with-cxx-dialect=C++11  \\
--with-64-bit-indices  \\
CC=$CC CXX=$CXX FC=$FC  \\
CFLAGS='-fPIC -fopenmp'  \\
CXXFLAGS='-fPIC -fopenmp'  \\
FFLAGS='-fPIC -fopenmp'  \\
FCFLAGS='-fPIC -fopenmp'  \\
F90FLAGS='-fPIC -fopenmp'  \\
F77FLAGS='-fPIC -fopenmp'  \\
COPTFLAGS='-O3 -march=native -mtune=native'  \\
CXXOPTFLAGS='-O3 -march=native -mtune=native'  \\
FOPTFLAGS='-O3 -march=native -mtune=native'  \\"""
        command += f"PETSC_DIR={install_dir}/{pkg.upper()}/{pkg}-{ver}"

        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = f"{make_command} all -j{argv.jobs}"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = f"{make_command} install"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        package_log_file.close()
    else:
        print(f"{pkg.capitalize()} already installed")

    os.chdir(install_dir)

    if os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        return True
    else:
        return False

# ========================================== Install vtk
def InstallVTK(pkg: str, ver: str, gold_file: str):
    package_log_filename = f"{install_dir}/{pkg.upper()}/{pkg}_log.txt"
    MakeDirectory(f"{install_dir}/{pkg.upper()}")
    pkg_install_dir = f"{install_dir}/{pkg.upper()}/{pkg}-{ver}-install"

    shutil.copy(f"{install_dir}/downloads/{pkg}-{ver}.tar.gz",
                f"{install_dir}/{pkg.upper()}/{pkg}-{ver}.tar.gz")

    os.chdir(f"{install_dir}/{pkg.upper()}/")

    # Check if it is installed already
    if not os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        ExtractPackage(pkg, ver)

        package_log_file = open(package_log_filename, "w")
        MakeDirectory(f"{install_dir}/{pkg.upper()}/{pkg}-{ver}/chi_build")

        print(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"", flush=True)
        log_file.write(f"Configuring {pkg.upper()} {ver} to \"{os.getcwd()}\"")
        log_file.write(f" See {package_log_filename}\n")
        log_file.flush()

        env_vars = os.environ.copy()
        if len(os.getenv("CC")) == 0:
            env_vars["CC"] = shutil.which("mpicc")
        if len(os.getenv("CXX")) == 0:
            env_vars["CXX"] = shutil.which("mpicxx")
        if len(os.getenv("FC")) == 0:
            env_vars["FC"] = shutil.which("mpifort")

        os.chdir("chi_build")

        command = f"cmake -DCMAKE_INSTALL_PREFIX={pkg_install_dir} "
        command += """ \\
-DBUILD_SHARED_LIBS:BOOL=ON \\
-DVTK_Group_MPI:BOOL=ON \\
-DVTK_GROUP_ENABLE_Qt=NO \\
-DVTK_GROUP_ENABLE_Rendering=NO \\
-DVTK_GROUP_ENABLE_Imaging=NO \\
-DVTK_GROUP_ENABLE_StandAlone=WANT \\
-DVTK_GROUP_ENABLE_Web=NO \\
-DVTK_BUILD_TESTING:BOOL=OFF \\
-DCMAKE_BUILD_TYPE=Release \\
-DCMAKE_CXX_FLAGS=-std=c++11 \\
../
"""
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = f"{make_command} -j{argv.jobs}"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        command = f"{make_command} install"
        success, err, outstr = ExecSub(command, out_log=package_log_file, env_vars=env_vars)
        if not success:
            print(command, err)
            log_file.write(f"{command}\n{err}\n")
            package_log_file.write(f"{command}\n{err}\n")

        package_log_file.close()
    else:
        print(f"{pkg} already installed")

    os.chdir(install_dir)

    if os.path.exists(f"{pkg_install_dir}/{gold_file}"):
        return True
    else:
        return False

# ========================================== Collective install point
log_file.write("\nInstalling packages:\n")
log_file.flush()
install_errors = []
for pkg in package_info:
    log_file.write(f"{pkg}\n")
    log_file.flush()
    ver = package_info[pkg][VERSION]
    success = False
    if pkg == 'readline':
        success = InstallPackage(pkg, ver, gold_file="lib/libreadline.a")
    elif pkg == 'ncurses':
        success = InstallPackage(pkg, ver, gold_file="lib/libncurses.a")
    elif pkg == 'lua':
        readline_install = f"{install_dir}/{'readline'.upper()}/readline-" + \
                           f"{package_info['readline'][VERSION]}/chi_build"
        ncurses_install = f"{install_dir}/{'ncurses'.upper()}/ncurses-" + \
                          f"{package_info['ncurses'][VERSION]}/chi_build"
        success = InstallLuaPackage(pkg, ver, gold_file="lib/liblua.a",
                                    readline_install=readline_install,
                                    ncurses_install=ncurses_install)
    elif pkg == 'petsc':
        success = InstallPETSC(pkg, ver, gold_file="include/petsc")
    elif pkg == 'vtk':
        success = InstallVTK(pkg, ver, gold_file="include")
    else:
        print(f"No build rules for {pkg}")

    if not success:
        install_errors.append(pkg)

if len(install_errors) > 0:
    log_file.write(
        "\nFailed to install the following packages:\n")
    for pkg in install_errors:
        log_file.write(pkg + " ")
    log_file.write("\n")
    print(error_beg +
          f"Failed to install {len(install_errors)} package(s)\n" +
          "Check the package's associated log file, i.e., PACKAGE/package_log.txt" +
          "for information as to why the install failed. You could also try to " +
          "manually install these packages")
    print(error_end)
    exit(1)

# ========================================== Create envvars file
module_file = open(f"{install_dir}/configure_deproots.sh", "w")

lua_version = package_info["lua"][VERSION]
petsc_version = package_info["petsc"][VERSION]
vtk_version = package_info["vtk"][VERSION]

lua_root = f"{install_dir}/LUA/lua-{lua_version}/install"
petsc_root = f"{install_dir}/PETSC/petsc-{petsc_version}-install"
vtk_dir = f"{install_dir}/VTK/vtk-{vtk_version}-install"

module_file.write(f'export LUA_ROOT={lua_root}\n')
module_file.write(f'export PETSC_ROOT={petsc_root}\n')
module_file.write(f'export VTK_DIR={vtk_dir}\n')

if os.path.exists(f"{vtk_dir}/lib64"):
    module_file.write(f'export LD_LIBRARY_PATH="{vtk_dir}/lib64":$LD_LIBRARY_PATH\n')
else:
    module_file.write(f'export LD_LIBRARY_PATH="{vtk_dir}/lib":$LD_LIBRARY_PATH\n')
module_file.write('echo "Enviroment set for compiling. ' +
                  'If recompiling changed sources execute"\n')
module_file.write('echo "     ./configure clean"\n')
module_file.write('echo " "\n')
module_file.write('echo "Otherwise just execute:"\n')
module_file.write('echo "     ./configure"\n')

module_file.close()

ExecSub("chmod u+x configure_deproots.sh", log_file)
log_file.close()

print("\n########## Chi-Tech Dependency install complete ##########")
print("\nWhen opening ChiTech in an IDE, the following environment variables" +
      " need to be set:\n")

print(f'LUA_ROOT = {lua_root}')
print(f'PETSC_ROOT = {petsc_root}')
print(f'VTK_DIR = {vtk_dir}')
print()
print(TextColors.WARNING +
      "When compiling ChiTech, in a terminal, the following environment variables" +
      " need to be set:\n" +
      TextColors.ENDC)

print(f'export LUA_ROOT="{lua_root}"')
print(f'export PETSC_ROOT="{petsc_root}"')
print(f'export VTK_DIR="{vtk_dir}"')
if os.path.exists(f"{vtk_dir}/lib64"):
    print(f'export LD_LIBRARY_PATH="{vtk_dir}/lib":$LD_LIBRARY_PATH')
else:
    print(f'export LD_LIBRARY_PATH="{vtk_dir}/lib64":$LD_LIBRARY_PATH')

print()
print(f"To set these terminal environment variables automatically, execute:")
print(f"    $. {install_dir}/configure_deproots.sh\n")


from pydub import AudioSegment
import glob, os
import util.hashmap as hashMap
import numpy as np
from librosa.feature import chroma_stft
import librosa.display as display
import librosa
import scipy.io.wavfile as wav
from scipy import signal
import matplotlib.pyplot as plt
import time

#https://gist.github.com/gchavez2/53148cdf7490ad62699385791816b1ea
#https://ieeexplore.ieee.org/document/4564924   (artigo interessante)
#https://kevinsprojects.wordpress.com/2014/12/13/short-time-fourier-transform-using-python-and-numpy/    (site legal sobre stft)
#https://musicinformationretrieval.com/stft.html
#https://www.mathworks.com/matlabcentral/fileexchange/45197-short-time-fourier-transform-stft-with-matlab   em matlab

def fileAccount(directory, format):
    """Contabiliza a quantiade de musicas no formato mp3 dentro de um diretorio.
    """
    os.chdir(directory)           #muda o diretorio para directory
    number = 0
    for file in glob.glob("*"+format):
        number = number + 1

    return number

def fileNames(directory):
    """
    Retorna lista com os nomes dos arquivos no diretorio
    """
    os.chdir(directory)           #muda o diretorio para directory
    names = []
    names = os.listdir()
    return names

def readfile(row):
    """
    Retorna a duracao da nota e a nota para esta linha.
    """
    line = row.split()
    start = line[0]
    end = line[1]
    chord = line[2]
    return start, end, chord

def timeToMiliSeconds(start, end):
    """
    Retorna o tempo de inicio e fim em milissegundos.
    """
    startTime = start*1000
    endTime = end*1000
    return int(startTime), int(endTime)

def mapChords(countChordsFile):
    """
    Recebe um arquivo onde contem a contagem de acordes e a quantidade e retorna um map com esses dois valores
    Entrada:
    -countChordsFile: diretorio com o arquivo txt

    Saída:
    -hm: um map de acorde com um inteiro
    """

    arq = open(countChordsFile, 'r')
    hm = hashMap.HashMap()

    for row in arq:
        count = int(row.split(' ')[0])
        chord = row.split(' ')[1].split('\n')[0].replace('/', '|')

        hm.put(chord, count)

    return hm

def normalizeChordNames(name):
    """
    converte as notas em Bemois notas em sustenidos ou naturais
    """

    newName = ""

    if(name.find('Cb') >= 0):
        newName = 'B' + name.split('b')[1]
    elif(name.find('Db') >= 0):
        newName = 'C#' + name.split('b')[1]
    elif(name.find('Eb') >= 0):
        newName = 'D#' + name.split('b')[1]
    elif(name.find('Fb') >= 0):
        newName = 'E' + name.split('b')[1]
    elif(name.find('Gb') >= 0):
        newName = 'F#' + name.split('b')[1]
    elif(name.find('Ab') >= 0):
        newName = 'G#' + name.split('b')[1]
    elif(name.find('Bb') >= 0):
        newName = 'A#' + name.split('b')[1]
    else:
        newName = name

    return newName

def wavGenerete(mp3Files, segmented_audio, chordsFiles, mapChords, limit = 0):
    """
    Faz a segmentacao dos arquivos de audio com base nos arquivos de acordes.\n
    \t-mp3Files: diretorio com os arquivos no formato .mp3;\n
    \t-segmented_audio: destivo onde ira ser salvo os arquivos segmentados no formato .wav;\n
    \t-chordsFiles: Arquivo onde esta os mapeamento dos acordes.
    """
    segmented_audio2 = "dataset/segmented_audio2/"

    actualDirectory = os.getcwd()        #Salva a posicao do diretorio atual
    names = fileNames(mp3Files)      #pega todas as musicas do diretorio
    os.chdir(actualDirectory)       #retorna para o diretorio inicial

    t = 1/44100                     #tempo de amostragem de um cd

    hm = hashMap.HashMap()

    i = 0
    while(i < len(names)):
        name = names[i].split('.mp')[0]

        name = normalizeChordNames(name)            #converte notas

        sound = AudioSegment.from_mp3(mp3Files+name+'.mp3')

        chords = open(chordsFiles + name+ '.lab')

        for row in chords:

            start, end, chord = readfile(row)

            if(not hm.get(chord)):          #Verifica se ja existe o acorde chord
                hm.put(chord, 1)            #Cria uma nova chave
            else:
                k = hm.get(chord)
                k = k + 1
                hm.put(chord, k)            #atualiza a hash

            startTime, endTime = timeToMiliSeconds(float(start), float(end))

            if(t < (endTime - startTime)):      #necessario para nao gerar segmentos menor do que o tempo de amostragem

                #abre a musica e corta um trecho e salva em wav com o nome da nota
                fragment = sound[startTime:endTime]
                # fragment.export(segmented_audio + chord +  "_in" + str(hm.get(chord)) +".wav", format="wav")

                chord = chord.replace('/', '|')

                if(mapChords.get(chord) and mapChords.get(chord) >= limit ):
                    # salva em segmento 1
                    fragment.export(segmented_audio + chord +  "_in" + str(hm.get(chord)) +".wav", format="wav")
                else:
                    # salva em sagmento 2
                    fragment.export(segmented_audio2 + chord +  "_in" + str(hm.get(chord)) +".wav", format="wav")

        chords.close
        i = i + 1

def printChroma(chroma):
    """
    Imprime o grafico do groma
    """
    plt.figure(figsize=(10, 4))
    display.specshow(chroma, y_axis='chroma', x_axis='time')
    plt.colorbar()
    plt.title('Chromagram')
    plt.tight_layout()
    plt.show()

def chromaGeneration(segmented_audio, arq, windows='hann', lengthWindows=2048, hopWindows=512, lengthWindowsFeature=44):
    """
    Converte para o dominio da frequencia com STFT e gera a base de dabaBase
    \t-segmented_audio: caminho dos arquivos de audio wav;
    \t-arq: Caminho onde sera gerado o banco de dados;
    \t-windows: tipo de janela Ex: 'blackman', 'hamming', por padao sera hann;
    \t-lengthWindows: tamanho da janela Inteiro. Padrao eh 2048 pontos
    \t-hopWindows: tamanho do salto das janelas. Padrao eh 512 pontos
    \t-lengthWindowsFeature: tamanho da janela para extrair o vetor do chroma. Padrao eh 44 pontos
    """

    actualDirectory = os.getcwd()        #Salva a posicao do diretorio atual
    names = fileNames(segmented_audio)      #pega todos as musicas do diretorio
    os.chdir(actualDirectory)       #retorna para o diretorio inicial

    hm = hashMap.HashMap()

    # arq.write('C, C#, D, D#, E, F, F#, G, G#, A, A#, B, chords\n')    #cabecario do banco de dados

    i = 0
    while(i < len(names)):
        name = names[i].split('.')[0]

        # samplerate, samples = wav.read(segmented_audio + names[i] )     #samplerate tempo de amostragem para 1 seg
        audio, samplerate = librosa.load(segmented_audio + names[i], 44100)

        # if(i==0):
        #print(name)
        chroma = chroma_stft(audio, samplerate, None, np.inf, lengthWindows, hopWindows, None, windows)
        # chroma = chroma_stft(audio, samplerate)
        #print(chroma)
        #printChroma(chroma)
        winStart = 0
        winEnd = lengthWindowsFeature        #janela de deslocamento no chroma
        while(winEnd < len(chroma[0])):

            k = 0
            while(k < len(chroma)):
                    mean = np.mean(chroma[k][winStart:winEnd])     #calcula a media do trecho da porcao da lista
                    arq.write(str(round(mean,3)))
                    k = k + 1

                    arq.write(str(', '))

            arq.write(str(name.split('_')[0]))
            arq.write('\n')

            winStart = winEnd
            winEnd = winEnd + lengthWindowsFeature           #atualiza o deslocamento do chroma

        #print(chroma)
        #print(len(chroma[1]))
        # printChroma(chroma)

        i = i + 1

def main():
    """Funcao para gerar trechos de mp3 e espectros stft"""

    #variaveis referente ao diretorio
    mp3Files = "dataset/mp3/"
    chordsFiles = "dataset/chords/"
    segmented_audio = "dataset/segmented_audio/"
    dataBase = "dataset/bd/bd.csv"
    countChords = "dataset/count_chords.txt"

    #variaveis de entrada da STFT
    windows = 'blackman'
    lengthWindows = 500        #tamanho da janela em seg
    hopWindows = 100         #salto da janela em seg

    #variaveis de configuracao do chroma
    lengthWindowsFeature = 11

    #variavel para dividir o banco de dados em dois, ou seja, esta variavel e reponsavel para
    #limitar o valor minimo de ocorrencia de um acorde
    limit = 400

    inicio = time.time()

    #carrega a lista de todos acordes
    hm = mapChords(countChords)
    fim = time.time()
    duracao = fim - inicio
    print("Carregamento do Map concluido..., Duracao:  " + str(duracao))

    #fase de segmentacao
    # wavGenerete(mp3Files, segmented_audio, chordsFiles, hm, limit)
    # fim = time.time()
    # duracao = fim - inicio
    # print("Fase de segmentacao concluida..., Duracao: " + str(duracao))

    arq = open(dataBase, 'w')
    #converter para o dominio da frequencia e  generacao dos chromas
    chromaGeneration(segmented_audio, arq, windows, lengthWindows, hopWindows, lengthWindowsFeature)
    fim = time.time()
    duracao = fim - inicio
    print("Geracao do banco de dados finalizado..., Duracao: " + str(duracao))

    arq.close()

if __name__ == "__main__":
    main()