import argparse
import os
import sys
# Third-party modules
import ipdb
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import sessionmaker
# Own modules
from industries import run_tests_on_industries
from job_benefits import run_tests_on_job_benefits
from job_locations import run_tests_on_job_locations
from job_salaries import run_tests_on_job_salaries
from roles import run_tests_on_roles
from skills import run_tests_on_skills
from tables import Base
from utilities.genutils import read_yaml_config
from utilities.script_boilerplate import ScriptBoilerplate

logger = None
db_session = None

def get_db_session(main_cfg):
    # SQLAlchemy database setup
    db_url = main_cfg['db_url']
    db_url['database'] = os.path.expanduser(db_url['database'])
    logger.info("Database setup of {}".format(db_url['database']))
    engine = create_engine(URL(**db_url))
    Base.metadata.bind = engine
    # Setup database session
    DBSession = sessionmaker(bind=engine)
    db_session = DBSession()
    return db_session

def main():
    sb = ScriptBoilerplate(
        module_name=__name__,
        module_file=__file__,
        cwd=os.getcwd(),
        parser_desc="Run tests on the `job_data.sqlite` database.",
        parser_formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    sb.parse_args()
    global logger
    logger = sb.get_logger()
    logger.info("Starting the tests")
    # Read YAML configuration file
    try:
        logger.info("Loading the YAML configuration file '{}'".format(
            sb.args.main_cfg))
        main_cfg = read_yaml_config(sb.args.main_cfg)
    except OSError as e:
        logger.exception(e)
        logger.error("Configuration file '{}' couldn't be read. Program will "
                     "exit.".format(sb.args.main_cfg))
        sys.exit(1)
    else:
        logger.info("Successfully loaded the YAML configuration file")
    global db_session
    db_session = get_db_session(main_cfg)
    for test_name, test_value in main_cfg['tests'].items():
        if test_name == 'industries' and test_value:
            logger.info("Running tests on `industries` ...")
            run_tests_on_industries(db_session, sb.logging_cfg_dict)
        elif test_name == 'job_benefits' and test_value:
            logger.info("Running tests on `job_benefits` ...")
            run_tests_on_job_benefits(db_session, sb.logging_cfg_dict)
        elif test_name == 'job_locations' and test_value:
            logger.info("Running tests on `job_locations` ...")
            run_tests_on_job_locations(db_session, sb.logging_cfg_dict)
        elif test_name == 'job_salaries' and test_value:
            logger.info("Running tests on `job_salaries` ...")
            run_tests_on_job_salaries(db_session, sb.logging_cfg_dict)
        elif test_name == 'roles' and test_value:
            logger.info("Running tests on `roles` ...")
            run_tests_on_roles(db_session, sb.logging_cfg_dict)
        elif test_name == 'skills' and test_value:
            logger.info("Running tests on `skills` ...")
            run_tests_on_skills(db_session, sb.logging_cfg_dict)

if __name__ == '__main__':
    try:
        main()
    except (KeyboardInterrupt, KeyError) as e:
        pass


#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from lib.sonardb import sonarDBManager
from contextlib import ExitStack
from more_itertools import consecutive_groups, split_when
from tempfile import mkstemp, mkdtemp
import shutil
import pandas as pd
import numpy as np
import subprocess
from os import getpid, system
from multiprocessing import Pool
import warnings
import math
from tqdm import tqdm
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
import traceback
import gzip
import sys

def create_fix_vcf_header(ref):
    header = "##fileformat=VCFv4.2\n##CreatedBy=covSonarV1.1.4\n##reference="+ref
    format = '\n##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">'
    info = '\n##INFO=<ID=AC,Number=.,Type=Integer,Description="Allele count in genotypes, for each ALT allele, in the same order as listed">'
    info = info+'\n##INFO=<ID=AN,Number=1,Type=Integer,Description="Total number of alleles in called genotypes">'
    info = info+'\n##INFO=<ID=TYPE,Number=.,Type=String,Description="Mutation type e.g., SNP,INS and DEL">\n'
    note =  "##Note_1='Currently we ignore DEL type'\n"
    note =  note+ "##Note_2='This VCF file is genereted by using var2vcf with betaV2, if you find any bugs, then please write a bug report to us'\n"
    # column = "\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t"+sample_id+"\n"
    return header+format+info+note

from multiprocessing import Pool

def bgzip(filename):
    """Call bgzip to compress a file."""
    cmd = ['bgzip', '-f', filename]
    with subprocess.Popen(cmd, encoding='utf8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
        try:
            stdout, stderr = process.communicate(cmd)

        except subprocess.TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise subprocess.TimeoutExpired( output=stdout, stderr=stderr)
        except Exception:
            process.kill()
            raise
    return

def tabix_index(filename):
    """Call tabix to create an index for a bgzip-compressed file."""
    cmd = ['tabix', '-p', 'vcf', filename+'.gz']
    with subprocess.Popen(cmd, encoding='utf8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
        try:
            stdout, stderr = process.communicate(cmd)
        except subprocess.TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise subprocess.TimeoutExpired( output=stdout, stderr=stderr)
        except Exception:
            process.kill()
            raise
    return

def bcftool_index(filename):
    """Call tabix to create an index for a bgzip-compressed file."""
    cmd = ['bcftools', 'index', filename]
    with subprocess.Popen(cmd, encoding='utf8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
        try:
            stdout, stderr = process.communicate(cmd)
        except subprocess.TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise subprocess.TimeoutExpired( output=stdout, stderr=stderr)
        except Exception:
            process.kill()
            raise
    return

def calculate_AC_AN(final_df):
    # calculate AC AN
    # order-preserving index between POS and INFO AC
    # e.g. a.POS;b.POS a.AC,b.AC
    for row in final_df.itertuples():
        unique, counts = np.unique(np.asarray(row[11:]), return_counts=True) # row[11:] means we start from sample ID column
        # for unique, counts in zip(unique, counts):
        AN=0
        AC=''
        for idx, val in enumerate(unique):
            if(val == '.'): # ignore it
                continue
            else:
                _AC = counts[idx]
                AN = AN +_AC
                AC = str(_AC) if not AC else AC+','+str(_AC)
        final_df.at[row.Index, 'INFO'] = 'AN='+str(AN)+';AC='+AC
    return final_df

def _check_variant_type(ref, alt):

    if len(ref) == len(alt) and len(alt)==1: # SNP
        return 'SNP'
    elif len(ref) < len(alt) and len(alt) > 0: # INS
        if ref == alt[0]:
            return 'INS'
        else:
            return 'INDEL'
    elif len(ref) > len(alt) and len(ref) > 0: # DEL
        return 'DEL'
    else:
        print('Unknown:',ref, alt)
        return 'Unknown'

def create_vcf(rows_grouped, tmp_dirname, refdescr):
    refdescr= refdescr.split()[0].replace(">", "")
    process_id =str(getpid())
    # print(process_id+" Start")
    # iterate over each group
    final_snp_df = pd.DataFrame({'#CHROM': pd.Series(dtype='str'),
                   'POS': pd.Series(dtype='int'),
                   'ID': pd.Series(dtype='str'),
                   'REF': pd.Series(dtype='str'),
                    'ALT': pd.Series(dtype='str'),
                    'FILTER': pd.Series(dtype='str'),
                    'QUAL': pd.Series(dtype='str'),
                    'INFO': pd.Series(dtype='str'),
                    'FORMAT': pd.Series(dtype='str'),
                    'TYPE': pd.Series(dtype='str'),}, index = np.arange(1, 29904))
    final_snp_df['POS'] = np.arange(1, 29904)
    final_snp_df['#CHROM'] = refdescr # duplicated line here did a trick for assigning the value
    final_snp_df['ID'] = '.'
    final_snp_df['REF'] = '.'
    final_snp_df['ALT'] = '.'
    final_snp_df['FILTER'] = '.'
    final_snp_df['QUAL'] = '.'
    final_snp_df['INFO'] = '.'
    final_snp_df['FORMAT'] = 'GT'
    final_snp_df['TYPE'] = '.'

    final_indel_df = pd.DataFrame({'#CHROM': pd.Series(dtype='str'),
                'POS': pd.Series(dtype='int'),
                   'ID': pd.Series(dtype='str'),
                   'REF': pd.Series(dtype='str'),
                    'ALT': pd.Series(dtype='str'),
                    'FILTER': pd.Series(dtype='str'),
                    'QUAL': pd.Series(dtype='str'),
                    'INFO': pd.Series(dtype='str'),
                    'FORMAT': pd.Series(dtype='str'),
                    'TYPE': pd.Series(dtype='str'),})
    vcf_filename =process_id+'.vcf'
    full_path = os.path.join(tmp_dirname,vcf_filename)
    with open(full_path, 'w') as f:
        # print("Create VCF file:",full_path)
        f.write(create_fix_vcf_header(refdescr))
        for group_name, df_ in tqdm(rows_grouped, mininterval=0.5):
            try:
                #final_snp_df[group_name] = "." # init value
                #final_indel_df[group_name] = "." # init value
                for row in df_.itertuples():

                    _id = getattr(row, 'ref')+str(getattr(row, 'start'))+getattr(row, 'alt')
                    _type  =_check_variant_type( getattr(row, 'ref'),getattr(row, 'alt'))

                    if(_type == 'SNP' ):
                        # find  ID
                        index_start_postion = getattr(row, 'start')
                        selected_row = final_snp_df.loc[index_start_postion] # return scalar instead DF
                        if(selected_row.ID == '.'): # A

                            final_snp_df.at[index_start_postion, 'ID'] = _id
                            final_snp_df.at[index_start_postion, group_name] = '1'
                            final_snp_df.at[index_start_postion, 'REF'] = getattr(row, 'ref')
                            final_snp_df.at[index_start_postion, 'ALT'] = getattr(row, 'alt')
                            final_snp_df.at[index_start_postion, 'TYPE'] = 'SNP'

                        elif(selected_row.ID != '.'): # B
                            if(selected_row.ID == _id): # only one ID exists and just update GT of a sample
                                final_snp_df.at[index_start_postion, group_name] = '1'
                            else:

                                splited_final_id_list = selected_row.ID.split(";")
                                totel_len = len(splited_final_id_list)
                                for new_GT, splited_final_id in enumerate(splited_final_id_list, start=1):
                                    if(splited_final_id == _id): # Found the exist one
                                        final_snp_df.at[index_start_postion, group_name] = str(new_GT)
                                        break
                                    elif(totel_len == new_GT): # cannot find the same ID ,so we append the new one to the string
                                        final_snp_df.at[index_start_postion, 'ID'] = final_snp_df.at[index_start_postion,'ID']+ ';'+ _id
                                        # with new GT number
                                        final_snp_df.at[index_start_postion, group_name] = str(new_GT + 1)
                                        # appends new alt
                                        final_snp_df.at[index_start_postion, 'ALT'] = final_snp_df.at[index_start_postion,'ALT']+ ','+getattr(row, 'alt')
                        else:
                            # get index
                            print(selected_row)
                            raise ValueError('Something went wrong')

                    #elif(_type == 'DEL'):
                    #    continue
                    elif(_type == 'INS' or _type == 'INDEL'or _type == 'DEL'):   # C      or _type == 'DEL'

                        selected_row = final_indel_df[(final_indel_df['POS'] == getattr(row, 'start')) & (final_indel_df['TYPE'] == _type)]
                        if(len(selected_row) == 0): # D, always insert new records
                            new_row = {'#CHROM': refdescr,'ID': _id, 'POS': int(getattr(row, 'start')), 'REF':getattr(row, 'ref'),
                                        'ALT':getattr(row, 'alt'), 'TYPE':_type,
                                        'FILTER':'.', 'QUAL':'.', 'INFO': '.','FORMAT':'GT', group_name: '1'}
                            final_indel_df = final_indel_df.append(new_row, ignore_index=True)
                        elif(len(selected_row) > 0): # E , found more than 0 which means we can update or insert it
                            for _E_rows  in selected_row.itertuples():
                                index_postion= _E_rows.Index
                                splited_IDs_list = _E_rows.ID.split(";")
                                totel_len = len(splited_IDs_list)
                                for _E_new_GT, splited_ID in enumerate(splited_IDs_list, start=1):
                                    #print('index',index_postion,'test', splited_ID, _E_new_GT)
                                    if(splited_ID == _id): # Found the exist one
                                        #print('Found the exist one', splited_final_id)
                                        final_indel_df.at[index_postion, group_name] = str(_E_new_GT)
                                        break
                                    elif(totel_len == _E_new_GT): # cannot find the same ID ,so we append the new one to the string
                                        final_indel_df.at[index_postion, 'ID'] = final_indel_df.at[index_postion,'ID']+ ';'+ _id
                                        # with new GT number
                                        final_indel_df.at[index_postion, group_name] = str(_E_new_GT + 1)
                                        # appends new alt
                                        final_indel_df.at[index_postion, 'ALT'] = final_indel_df.at[index_postion,'ALT']+ ','+getattr(row, 'alt')

                    else:
                        print('Skip this ', _id) # right now skip for Unknown
                        continue
            except ValueError as err:
                    print(err.args)
                    raise
            except Exception as e:
                    print("An exception occurred at...")
                    print(group_name)
                    print(row)
                    print(selected_row)
                    print(traceback.format_exc())
                    raise e

        final_df = pd.concat( [final_snp_df, final_indel_df ],axis=0,ignore_index=True)
        final_df = final_df.drop(final_df[final_df.ID=='.'].index)
        final_df.replace(np.nan, '.', inplace=True)
        final_df['ALT'].replace('', '.', inplace=True)  # for deletion
        final_df = final_df.sort_values(["POS"], ascending=True)
        final_df = calculate_AC_AN(final_df)
        final_df["INFO"] = final_df["INFO"] +";TYPE="+ final_df["TYPE"]
        final_df= final_df.drop(columns=['TYPE'])
        final_df.to_csv(f, sep='\t', encoding='utf-8', index=False)

    bgzip(full_path)
    tabix_index(full_path)
    return full_path+'.gz'
    # print(process_id+" Finish")

def parallelize_dataframe(df, tmp_dirname, num_cores,refdescr, func):
    _tmp_lis = np.array_split(df, num_cores)
    counter=0
    zip_items = [(_tmp_lis[i],tmp_dirname,refdescr) for i in range(len(_tmp_lis))] # same order
    #with Pool(processes=num_cores) as pool:
    #    res = pool.starmap(func, zip_items)
    pool = Pool(num_cores)
    full_paht_list = pool.starmap(func, zip_items)

	# finish all tasks
    pool.close()
    pool.join()
    #print("Tmp result: ", full_paht_list)
    return full_paht_list

def export2VCF(
    db_path,
    include_acc,
    include_dates,
    output,
    num_cores,
    refdescr="No ref is provided"
    ):
    print('----- You are using sonartoVCF_V2 --------')
    print('WARNING: the function is still experimental/not fully implemented.')
    print('Prepare export2VCF workspace for',num_cores,'cpu')
    with ExitStack() as stack:
        dbm = stack.enter_context(sonarDBManager(db_path))

        where_clause = []
        where_vals = []

        if include_acc:
            where_clause.append(dbm.get_metadata_in_condition('accession'
                                , *include_acc))
            where_vals.extend(include_acc)
        if include_dates:
            where_clause.append(dbm.get_metadata_date_condition('date',
                                *include_dates))

        #print(where_clause)
        fields = 'accession, start, end, alt, ref '
        if where_clause:
            sql =  "SELECT " + fields + " FROM dna_view WHERE " + " AND ".join(where_clause) + ";"
        else:
            sql = "SELECT " + fields + " FROM dna_view;"

        # print("query: " + sql)
        # print("vals: ", where_vals)
        ##############################
        print('Start Bigquery...')
        rows = pd.read_sql(sql,
                   dbm.connection,params=where_vals)
        print('Return:', len(rows), ' records')
        track_vcf = []
        count = 0
        if not rows.empty:
            # rows.to_pickle("dummy.pkl")
            tmp_dirname = mkdtemp( prefix=".sonarCache_")
            # vcf_path=os.path.join(tmp_dirname,)

            # create fasta_id

            #rows['CHROM'] = chrom_id
            #rows['QUAL'] = '.'
            #rows['FILTER'] = '.'
            #rows['INFO'] = '.'
            #rows['FORMAT'] = 'GT'
            # POS or start position: The reference position, with the 1st base is position 1 not 0 , but in covsonar use 0 as the 1st position
            # so we should + 1
            # http://samtools.github.io/hts-specs/VCFv4.2.pdf
            rows['start'] = rows['start'] + 1
            # rows['end'] = rows['end']+1

            rows= rows.loc[ (1 <= rows['start']) & (rows['start'] <= 29903)] # filter out

            rows['alt'] = rows['alt'].replace('', np.nan) # remove Deletion
            # rows['start'] = rows['start'].replace('', np.nan) # remove Insertion
            rows = rows.dropna(axis=0, subset=['alt'])
            rows_grouped = rows.groupby('accession')
            print('With :', len(rows_grouped), ' accessions')
            # split data and write each ACC into individual VCF file.
            print('Start Divide and Conquer ...')
            track_vcf = parallelize_dataframe(rows_grouped, tmp_dirname, num_cores, refdescr, create_vcf)

            # bundle all vcf together
            print('Integrate all VCFs ...')
            divide_merge_vcf(track_vcf, output, num_cores)

            if os.path.isdir(tmp_dirname):
                shutil.rmtree(tmp_dirname)

            print("Finish! compress final result (gz):")

def divide_merge_vcf(list_track_vcf, global_output, num_cores):
    chunk=500
    list_length = math.ceil(len(list_track_vcf)/chunk) # try to merge every
    print('size:', list_length)
    first_create_ = True
    second_create_ = True
    tmp_dirname = mkdtemp(dir='/home/kongkitimanonk/SCRATCH_NOBAK/CovSonar1/workdir_covsonar/test-vcf/',  prefix=".final.sonarCache_")
    # we can tweak performance by using U at Bcftools for piping between bcftools subcommands (future work)
    bar = tqdm(range(list_length), desc="Create Global VCF:")
    merge_type='b'
    for i in bar:
        _vcfs = " ".join(list_track_vcf[chunk*i:chunk*i+chunk])

        if(len(list_track_vcf)==1):
            tmp_output = list_track_vcf[i].replace('.gz', '')
            continue

        if(i == list_length-1):
            merge_type='v'
            #print('final merge')

        if first_create_:
            tmp_output = os.path.join(tmp_dirname,'vcf.2' )
            cmd = "bcftools merge {} -o {} -O{} --threads {}".format(_vcfs,tmp_output, merge_type, num_cores)
            with subprocess.Popen(cmd, encoding='utf8', shell=True) as process:
                stdout, stderr = process.communicate(cmd)
            #bgzip(tmp_output)
            #tabix_index(tmp_output)
            bcftool_index(tmp_output)
            first_create_ = False
            second_create_ = True
        elif second_create_:
            _vcfs = _vcfs +' '+ os.path.join(tmp_dirname,'vcf.2' )
            tmp_output = os.path.join(tmp_dirname,'vcf.3' )

            cmd = "bcftools merge {} -o {} -O{} --threads {}".format(_vcfs,  tmp_output, merge_type, num_cores)
            with subprocess.Popen(cmd, encoding='utf8', shell=True) as process:
                stdout, stderr = process.communicate(cmd)
            #bgzip(tmp_output)
            #tabix_index(tmp_output)
            bcftool_index(tmp_output)
            second_create_ = False
        else:
            _vcfs = _vcfs +' '+ os.path.join(tmp_dirname,'vcf.3' )
            tmp_output = os.path.join(tmp_dirname,'vcf.2' )

            cmd = "bcftools merge {} -o {} -O{} --threads {}".format(_vcfs, tmp_output, merge_type, num_cores)
            with subprocess.Popen(cmd, encoding='utf8', shell=True) as process:
                stdout, stderr = process.communicate(cmd)
            #bgzip( tmp_output)
            #tabix_index(tmp_output)
            bcftool_index(tmp_output)
            second_create_ = True

        if(merge_type =='v'):
            bgzip(tmp_output)
            tabix_index(tmp_output)
    tmp_output = clean_stranger_things(tmp_output+ '.gz', tmp_dirname)
    shutil.copy(tmp_output, global_output+ '.gz')
    # sys.exit(" exist.")
    print('Clean workspace ...')
    if os.path.isdir(tmp_dirname):
        shutil.rmtree(tmp_dirname)

def clean_stranger_things(path_to_vcfgz, tmp_dirname):
    print('Clean strange things in vcf ...')
    output_path_file = os.path.join(tmp_dirname,'vcf.final.gz' )
    with gzip.open(path_to_vcfgz, 'rt') as f:
        with gzip.open(output_path_file, 'wt') as output_file:
            for line in f:
                if line.startswith('#'):
                    if 'bcftools_mergeCommand' in line:
                        continue
                    else:
                        output_file.write(line)
                else:
                    rows = line.split('\t')
                    ### fix duplicate
                    ID = rows[2]
                    rows[2]= ";".join(set(ID.split(';')))

                    output_file.write("\t".join(rows))
    return output_path_file


from flask import Flask, request, jsonify
from surprise.dump import load
import os
import numpy as np

app = Flask(__name__)

Model = load('RecommendationModel.pkl')[1]

@app.route("/", methods = ['GET'])
def Welcome_Message():
    return 'Welcome to my first REST API', 200

@app.route("/predict", methods = ['POST'])
def flask_predict():
    print(request.headers)
    if request.is_json: #Verify data is in json format
        data = request.get_json()
        print(data)
        user_id = str(data['user_id'])
        item_id = str(data['item_id'])

        prediction = Model.predict(user_id, item_id)

        return jsonify(prediction), 201
    return {"error": "Request must be JSON"}, 415

if __name__ == '__main__':
    app.run(host = '127.0.0.1', port = int(os.environ.get("PORT", 5000)))


import re
from typing import List, Tuple

import pytest

from flake8_annotations.checker import FORMATTED_ERROR
from testing.helpers import check_source
from testing.test_cases.variable_formatting_test_cases import (
    variable_formatting_test_cases,
)

SIMPLE_ERROR_CODE = Tuple[str, str]

# Error type specific matching patterns
TEST_ARG_NAMES = {"ANN001": "some_arg", "ANN002": "some_args", "ANN003": "some_kwargs"}
RE_DICT = {"ANN001": r"'(\w+)'", "ANN002": r"\*(\w+)", "ANN003": r"\*\*(\w+)"}

def _simplify_error(error_code: FORMATTED_ERROR) -> SIMPLE_ERROR_CODE:
    """
    Simplify the error yielded by the flake8 checker into an (error type, argument name) tuple.

    Input error codes are assumed to be tuples of the form:
    (line number, column number, error string, checker class)

    Where the error string begins with "ANNxxx" and contains the arg name in the following form:
    ANN001: '{arg name}'
    ANN002: *{arg name}
    ANN003: **{arg name}
    """
    error_type = error_code[2].split()[0]
    arg_name = re.findall(RE_DICT[error_type], error_code[2])[0]
    return error_type, arg_name

class TestArgumentFormatting:
    """Testing class for containerizing parsed error codes & running the fixtured tests."""

    @pytest.fixture(
        params=variable_formatting_test_cases.items(), ids=variable_formatting_test_cases.keys()
    )
    def parsed_errors(self, request) -> Tuple[List[SIMPLE_ERROR_CODE], str]:  # noqa: ANN001
        """
        Create a fixture for the error codes emitted by the test case source code.

        Error codes for the test case source code are simplified into a list of
        (error code, argument name) tuples.
        """
        test_case_name, test_case = request.param
        simplified_errors = [_simplify_error(error) for error in check_source(test_case.src)]

        return simplified_errors, test_case_name

    def test_arg_name(self, parsed_errors: Tuple[List[SIMPLE_ERROR_CODE], str]) -> None:
        """
        Check for correctly formatted argument names.

        Simplified error code information is provided by the fixture as a list of
        (yielded error, test case name) tuples
        """
        assert all(
            TEST_ARG_NAMES[error_type] == arg_name for error_type, arg_name in parsed_errors[0]
        )


import mock
import os

from quantum.openstack.common import jsonutils as json
import quantum.plugins.nicira.nicira_nvp_plugin as nvp_plugin
from quantum.plugins.nicira.nicira_nvp_plugin import nvp_cluster
from quantum.plugins.nicira.nicira_nvp_plugin import NvpApiClient
from quantum.plugins.nicira.nicira_nvp_plugin import nvplib
from quantum.tests import base
from quantum.tests.unit.nicira import fake_nvpapiclient
from quantum.tests.unit import test_api_v2

NICIRA_PKG_PATH = nvp_plugin.__name__
_uuid = test_api_v2._uuid

class NvplibTestCase(base.BaseTestCase):

    def setUp(self):
        # mock nvp api client
        etc_path = os.path.join(os.path.dirname(__file__), 'etc')
        self.fc = fake_nvpapiclient.FakeClient(etc_path)
        self.mock_nvpapi = mock.patch('%s.NvpApiClient.NVPApiHelper'
                                      % NICIRA_PKG_PATH, autospec=True)
        instance = self.mock_nvpapi.start()
        instance.return_value.login.return_value = "the_cookie"

        def _fake_request(*args, **kwargs):
            return self.fc.fake_request(*args, **kwargs)

        instance.return_value.request.side_effect = _fake_request
        self.fake_cluster = nvp_cluster.NVPCluster('fake-cluster')
        self.fake_cluster.add_controller('1.1.1.1', '999', 'foo', 'bar',
                                         9, 9, 9, 9, _uuid())
        self.fake_cluster.api_client = NvpApiClient.NVPApiHelper(
            ('1.1.1.1', '999', True),
            self.fake_cluster.user, self.fake_cluster.password,
            self.fake_cluster.request_timeout, self.fake_cluster.http_timeout,
            self.fake_cluster.retries, self.fake_cluster.redirects)

        super(NvplibTestCase, self).setUp()
        self.addCleanup(self.fc.reset_all)
        self.addCleanup(self.mock_nvpapi.stop)

class TestNvplibNatRules(NvplibTestCase):

    def _test_create_lrouter_dnat_rule(self, func):
        tenant_id = 'pippo'
        lrouter = nvplib.create_lrouter(self.fake_cluster,
                                        tenant_id,
                                        'fake_router',
                                        '192.168.0.1')
        nat_rule = func(self.fake_cluster, lrouter['uuid'], '10.0.0.99',
                        match_criteria={'destination_ip_addresses':
                                        '192.168.0.5'})
        uri = nvplib._build_uri_path(nvplib.LROUTERNAT_RESOURCE,
                                     nat_rule['uuid'],
                                     lrouter['uuid'])
        return json.loads(nvplib.do_single_request("GET", uri,
                                                   cluster=self.fake_cluster))

    def test_create_lrouter_dnat_rule_v2(self):
        resp_obj = self._test_create_lrouter_dnat_rule(
            nvplib.create_lrouter_dnat_rule_v2)
        self.assertEqual('DestinationNatRule', resp_obj['type'])
        self.assertEqual('192.168.0.5',
                         resp_obj['match']['destination_ip_addresses'])

    def test_create_lrouter_dnat_rule_v3(self):
        resp_obj = self._test_create_lrouter_dnat_rule(
            nvplib.create_lrouter_dnat_rule_v2)
        # TODO(salvatore-orlando): Extend FakeNVPApiClient to deal with
        # different versions of NVP API
        self.assertEqual('DestinationNatRule', resp_obj['type'])
        self.assertEqual('192.168.0.5',
                         resp_obj['match']['destination_ip_addresses'])

class NvplibL2GatewayTestCase(NvplibTestCase):

    def _create_gw_service(self, node_uuid, display_name):
        return nvplib.create_l2_gw_service(self.fake_cluster,
                                           'fake-tenant',
                                           display_name,
                                           [{'id': node_uuid,
                                             'interface_name': 'xxx'}])

    def test_create_l2_gw_service(self):
        display_name = 'fake-gateway'
        node_uuid = _uuid()
        response = self._create_gw_service(node_uuid, display_name)
        self.assertEqual(response.get('type'), 'L2GatewayServiceConfig')
        self.assertEqual(response.get('display_name'), display_name)
        gateways = response.get('gateways', [])
        self.assertEqual(len(gateways), 1)
        self.assertEqual(gateways[0]['type'], 'L2Gateway')
        self.assertEqual(gateways[0]['device_id'], 'xxx')
        self.assertEqual(gateways[0]['transport_node_uuid'], node_uuid)

    def test_update_l2_gw_service(self):
        display_name = 'fake-gateway'
        new_display_name = 'still-fake-gateway'
        node_uuid = _uuid()
        res1 = self._create_gw_service(node_uuid, display_name)
        gw_id = res1['uuid']
        res2 = nvplib.update_l2_gw_service(self.fake_cluster, gw_id,
                                           new_display_name)
        self.assertEqual(res2['display_name'], new_display_name)

    def test_get_l2_gw_service(self):
        display_name = 'fake-gateway'
        node_uuid = _uuid()
        gw_id = self._create_gw_service(node_uuid, display_name)['uuid']
        response = nvplib.get_l2_gw_service(self.fake_cluster, gw_id)
        self.assertEqual(response.get('type'), 'L2GatewayServiceConfig')
        self.assertEqual(response.get('display_name'), display_name)
        self.assertEqual(response.get('uuid'), gw_id)

    def test_list_l2_gw_service(self):
        gw_ids = []
        for name in ('fake-1', 'fake-2'):
            gw_ids.append(self._create_gw_service(_uuid(), name)['uuid'])
        results = nvplib.get_l2_gw_services(self.fake_cluster)
        self.assertEqual(len(results), 2)
        self.assertEqual(sorted(gw_ids), sorted([r['uuid'] for r in results]))

    def test_delete_l2_gw_service(self):
        display_name = 'fake-gateway'
        node_uuid = _uuid()
        gw_id = self._create_gw_service(node_uuid, display_name)['uuid']
        nvplib.delete_l2_gw_service(self.fake_cluster, gw_id)
        results = nvplib.get_l2_gw_services(self.fake_cluster)
        self.assertEqual(len(results), 0)

    def test_plug_l2_gw_port_attachment(self):
        tenant_id = 'pippo'
        node_uuid = _uuid()
        lswitch = nvplib.create_lswitch(self.fake_cluster, tenant_id,
                                        'fake-switch')
        gw_id = self._create_gw_service(node_uuid, 'fake-gw')['uuid']
        lport = nvplib.create_lport(self.fake_cluster,
                                    lswitch['uuid'],
                                    tenant_id,
                                    _uuid(),
                                    'fake-gw-port',
                                    gw_id,
                                    True)
        json.loads(nvplib.plug_l2_gw_service(self.fake_cluster,
                                             lswitch['uuid'],
                                             lport['uuid'],
                                             gw_id))
        uri = nvplib._build_uri_path(nvplib.LSWITCHPORT_RESOURCE,
                                     lport['uuid'],
                                     lswitch['uuid'],
                                     is_attachment=True)
        resp_obj = json.loads(
            nvplib.do_single_request("GET", uri,
                                     cluster=self.fake_cluster))
        self.assertIn('LogicalPortAttachment', resp_obj)
        self.assertEqual(resp_obj['LogicalPortAttachment']['type'],
                         'L2GatewayAttachment')

class TestNvpLibLogicalPorts(NvplibTestCase):

    def test_get_port_by_tag(self):
        tenant_id = 'pippo'
        quantum_port_id = 'whatever'
        lswitch = nvplib.create_lswitch(self.fake_cluster, tenant_id,
                                        'fake-switch')
        lport = nvplib.create_lport(self.fake_cluster, lswitch['uuid'],
                                    tenant_id, quantum_port_id,
                                    'name', 'device_id', True)
        lport2 = nvplib.get_port_by_quantum_tag(self.fake_cluster,
                                                lswitch['uuid'],
                                                quantum_port_id)
        self.assertIsNotNone(lport2)
        self.assertEqual(lport['uuid'], lport2['uuid'])

    def test_get_port_by_tag_not_found_returns_None(self):
        tenant_id = 'pippo'
        quantum_port_id = 'whatever'
        lswitch = nvplib.create_lswitch(self.fake_cluster, tenant_id,
                                        'fake-switch')
        lport = nvplib.get_port_by_quantum_tag(self.fake_cluster,
                                               lswitch['uuid'],
                                               quantum_port_id)
        self.assertIsNone(lport)


import streamlit as st
from streamlit_option_menu import option_menu
from globals import logged_user
from _pages import (
    Add_Books,
    Add_Loan,
    Add_Teaching_Materials,
    Add_Users,
    Edit_Books,
    Edit_Teaching_Materials,
    Edit_Users,
    List_Books,
    List_Loans,
    List_Teaching_Materials,
    List_Users,
    Login,
    Home
)

with open('src/globals.py', 'r') as file:
    exec(file.read())

admin_menu=[
    "Home",

    "Add Books",
    "Edit Books",
    "List Books",

    "Add Teaching Materials",
    "Edit Teaching Materials",
    "List Teaching Materials",

    "Add Loan",
    "List Loans",

    "Add Users",
    "Edit Users",
    "List Users"
]

admin_icons=[
    "house",

    "plus-circle",
    "pencil",
    "list-ul",

    "plus-circle",
    "pencil",
    "list-ul",

    "plus-circle",
    "list-ul",

    "plus-circle",
    "pencil",
    "list-ul",
]

member_menu=[
    "Home",
    "Add Loan",
    "List Books",
    "List Loans",
    "List Teaching Materials",
]

member_icons=[
    "house",
    "plus-circle",
    "list-ul",
    "list-ul",
    "list-ul",
]

no_logged_menu=[
    "Login",
    "List Books",
    "List Teaching Materials",
]

no_logged_icons=[
    "dor-open",
    "list-ul",
    "list-ul",
]

def choose_menu():
    if logged_user['role'] is None:
        return no_logged_menu
    elif logged_user["role"] == 'ADMIN':
        return admin_menu
    elif logged_user["role"] == 'MEMBER':
        return member_menu

def choose_icons():
    if logged_user['role'] is None:
        return no_logged_icons
    elif logged_user["role"] == 'ADMIN':
        return admin_icons
    elif logged_user["role"] == 'MEMBER':
        return member_icons

with st.sidebar:
    st.write(f'# LabLibrary')

    selected = option_menu(
        menu_title=None,
        options=choose_menu(),
        icons=choose_icons(),
        menu_icon="cast",
        default_index=0,
        styles={
            "nav-link": {
                "font-size": "1.25rem",
                "text-align": "left",
                "margin":"0.375rem 0",
            },
        }
    )

if selected=="Login":
    Login.create_page()

if selected=="Home":
    Home.create_page()

if selected=="Add Books":
    Add_Books.create_page()

if selected=="Add Loan":
    Add_Loan.create_page()

if selected=="Add Teaching Materials":
    Add_Teaching_Materials.create_page()

if selected=="Add Users":
    Add_Users.create_page()

if selected=="Edit Books":
    Edit_Books.create_page()

if selected=="Edit Teaching Materials":
    Edit_Teaching_Materials.create_page()

if selected=="Edit Users":
    Edit_Users.create_page()

if selected=="List Teaching Materials":
    List_Teaching_Materials.create_page()

if selected=="List Loans":
    List_Loans.create_page()

if selected=="List Users":
    List_Users.create_page()

if selected=="List Books":
    List_Books.create_page()


import requests

# Ask user for the name of a Pokemon
pokemon_name = input("Enter the name of a Pokemon: ")

# Make a GET request to the PokeAPI with the Pokemon name
response = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}")

# Check if the request was successful
if response.status_code == 200:
    # Retrieve the Pokemon's abilities from the API response
    abilities = [ability["ability"]["name"] for ability in response.json()["abilities"]]

    # Display the Pokemon's name and abilities
    print(f"Name: {pokemon_name.capitalize()}")
    print("Abilities:")
    for ability in abilities:
        print(f"- {ability.capitalize()}")
else:
    # If the request was unsuccessful, display an error message
    print(f"Error: Could not retrieve information for {pokemon_name.capitalize()}.")


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

from datetime import datetime

from block_propagation import Block_Propagation_Simulator

def main():
  # run(N, policy, num_arrivals_per_process, arrival_rate, num_processes)
  run(40, 'oldest-first', 30000, 0.5, 5)
  run(40, 'random', 30000, 0.5, 5)
  run(40, 'opportunistic', 30000, 0.5, 5)

  run(40, 'oldest-first', 30000, 0.7, 5)
  run(40, 'random', 30000, 0.7, 5)
  run(40, 'opportunistic', 30000, 0.7, 5)

  run(40, 'oldest-first', 30000, 0.9, 5)
  run(40, 'random', 30000, 0.9, 5)
  run(40, 'opportunistic', 30000, 0.9, 5)

  run(40, 'oldest-first', 30000, 0.95, 5)
  run(40, 'random', 30000, 0.95, 5)
  run(40, 'opportunistic', 30000, 0.95, 5)

  run(40, 'oldest-first', 30000, 0.95, 1)
  run(40, 'random', 30000, 0.95, 1)
  run(40, 'opportunistic', 30000, 0.95, 1)

def run(N, policy, num_blocks, arrival_rate, num_processes):
  output = mp.Queue()
  processes = [mp.Process(target=run_process, \
               args=(output, N, policy, num_blocks, arrival_rate)) \
               for x in range(num_processes)]

  start_time = datetime.now()
  for p in processes:
    p.start()

  for p in processes:
    p.join()

  results = [output.get() for p in processes]

  total_time = np.sum([results[p][0] for p in range(num_processes)])

  num_active_blocks_integral = np.sum([results[p][1] for p in range(num_processes)])
  mean_active_blocks = num_active_blocks_integral/total_time

  num_missing_block_copies_integral = np.sum([results[p][2] for p in range(num_processes)])
  mean_missing_block_copies = num_missing_block_copies_integral/total_time

  mean_cycle_length = np.mean([results[p][3] for p in range(num_processes)])

  mean_blocks_per_cycle = np.mean([results[p][4] for p in range(num_processes)])

  mean_age_of_information = np.mean([results[p][5] for p in range(num_processes)])

  num_active_blocks = []
  num_active_blocks.append([results[p][6] for p in range(num_processes)])
  print('plotting\n')
  plt.figure()
  plt.plot(range(len(num_active_blocks[0][0])), num_active_blocks[0][0])
  plt.show()

  print('N: ' + str(N))
  print('Policy: ' + policy)
  print('Number of Blocks: ' + str(num_processes*num_blocks))
  print('Arrival Rate: ' + str(arrival_rate))

  print('Mean Number of Blocks in System: ' + str(mean_active_blocks))
  print('Mean Number of Missing Block Copies: ' + str(mean_missing_block_copies))
  print('Mean Age of Information: ' + str(mean_age_of_information))
  #print('Mean Cycle Length: ' + str(mean_cycle_length))
  #print('Mean Number of Blocks per Cycle: ' + str(mean_blocks_per_cycle))

  end_time = datetime.now()
  print('Time Elapsed: ' + str(end_time - start_time))

def run_process(output, N, policy, num_blocks, arrival_rate):
  simulator = Block_Propagation_Simulator(N, policy, num_blocks, arrival_rate)
  output.put(simulator.run())

if __name__=='__main__':
  main()


def longestPalindrome(s):
    curr_pal = ""
    long_pal = ""
    for i in range(len(s)):
        sub1 = get_sub(s, i, i)
        sub2 = get_sub(s, i, i + 1)
        curr_pal = sub1 if len(sub1) > len(sub2) else sub2
        long_pal = curr_pal if len(curr_pal) > len(long_pal) else long_pal
    return long_pal

def get_sub(s, l, r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return s[l+1:r]

print(longestPalindrome("babbacc"))


import discord
from discord.ext import commands
import pandas as pd
import os
import matplotlib.pyplot as plt
import io
from discord import File

client = commands.Bot(command_prefix = '.c ')
client.remove_command('help')

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game(name='.c help'))
    print('Bot is online.')

@client.command()
async def help(ctx):

    embed = discord.Embed(
        title='Bot Help',
        colour=discord.Colour.red()
    )
    embed.add_field(name='```.c stat```', value='Returns **Total Confirmed**, **Total Deaths**, and **Total Recovered** \n \n To see stats of all locations use ```.c stat "all"``` \n To see stats of locations other than China use ```.c stat "other"``` \n To see stats of a specific country use ```.c stat "country name"```', inline=False)
    embed.add_field(name = 'Dataset from', value = '[Johns Hopkins CSSE Github](https://github.com/CSSEGISandData/COVID-19)')
    embed.add_field(name='Bot Source Code', value='[Github](https://github.com/picklejason/coronavirus-bot)')

    await ctx.send(embed=embed)

@client.command()
async def clear(ctx, amount : int):
    await ctx.channel.purge(limit=amount+1)

@client.command()
async def stat(ctx, location : str ):

    if len(location) == 2:
        location = location.upper()
    else:
        location = location.title()

    confirmed_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv'
    deaths_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv'
    recovered_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv'

    confirmed_df = pd.read_csv(confirmed_url, error_bad_lines=False)
    deaths_df = pd.read_csv(deaths_url, error_bad_lines=False)
    recovered_df = pd.read_csv(recovered_url, error_bad_lines=False)

    if any(confirmed_df['Country/Region'].str.contains(location)) or location == 'All' or location == 'Other':

        updated = list(confirmed_df)[-1]
        plt.style.use('dark_background')
        fig = plt.figure(dpi=200)

        if location == 'All':
            confirmed = confirmed_df.iloc[:,-1].sum()
            prev_confirmed = confirmed_df.iloc[:,-2].sum()
            deaths = deaths_df.iloc[:,-1].sum()
            prev_deaths = deaths_df.iloc[:,-2].sum()
            recovered = recovered_df.iloc[:,-1].sum()
            prev_recovered = recovered_df.iloc[:,-2].sum()
            ax = confirmed_df.iloc[:,4:].sum().plot(label='Confirmed')
            ax = recovered_df.iloc[:,4:].sum().plot(label='Recovered')
        elif location == 'Other':
            confirmed = confirmed_df[~confirmed_df['Country/Region'].str.contains('China', na=False)].iloc[:,-1].sum()
            prev_confirmed = confirmed_df[~confirmed_df['Country/Region'].str.contains('China', na=False)].iloc[:,-2].sum()
            deaths = deaths_df[~deaths_df['Country/Region'].str.contains('China', na=False)].iloc[:,-1].sum()
            prev_deaths = deaths_df[~deaths_df['Country/Region'].str.contains('China', na=False)].iloc[:,-2].sum()
            recovered = recovered_df[~recovered_df['Country/Region'].str.contains('China', na=False)].iloc[:,-1].sum()
            prev_recovered = recovered_df[~recovered_df['Country/Region'].str.contains('China', na=False)].iloc[:,-2].sum()
            ax = confirmed_df[~confirmed_df['Country/Region'].str.contains('China', na=False)].iloc[:,4:].sum().plot(label='Confirmed')
            ax = recovered_df[~recovered_df['Country/Region'].str.contains('China', na=False)].iloc[:,4:].sum().plot(label='Recovered')
        else:
            confirmed = confirmed_df[confirmed_df['Country/Region'].str.contains(location)].iloc[:,-1].sum()
            prev_confirmed = confirmed_df[confirmed_df['Country/Region'].str.contains(location)].iloc[:,-2].sum()
            deaths = deaths_df[deaths_df['Country/Region'].str.contains(location)].iloc[:,-1].sum()
            prev_deaths = deaths_df[deaths_df['Country/Region'].str.contains(location)].iloc[:,-2].sum()
            recovered = recovered_df[recovered_df['Country/Region'].str.contains(location)].iloc[:,-1].sum()
            prev_recovered = recovered_df[recovered_df['Country/Region'].str.contains(location)].iloc[:,-2].sum()
            ax = confirmed_df[confirmed_df['Country/Region'].str.contains(location)].iloc[:,4:].sum().plot(label='Confirmed')
            ax = recovered_df[recovered_df['Country/Region'].str.contains(location)].iloc[:,4:].sum().plot(label='Recovered')

        change_confirmed = confirmed - prev_confirmed
        if (change_confirmed > 0):
            change_confirmed = f'(+{change_confirmed})'
        else:
            change_confirmed = ''

        change_deaths = deaths - prev_deaths
        if (change_deaths > 0):
            change_deaths = f'(+{change_deaths})'
        else:
            change_deaths = ''

        change_recovered = recovered - prev_recovered
        if (change_recovered > 0):
            change_recovered = f'(+{change_recovered})'
        else:
            change_recovered = ''

        ax.yaxis.grid()
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['left'].set_visible(False)
        ax.legend(loc='upper left', fancybox=True, facecolor='0.2')
        ax.set_ylim(ymin=0)

        locs, _ = plt.yticks()
        ylabels = []
        for l in locs:
            lab = str(int(l)).replace('00000000', '00M').replace('0000000', '0M').replace('000000', 'M').replace('00000', '00K').replace('0000', '0K').replace('000', 'K')
            if not ('K' in lab or 'M' in lab):
                lab = "{:,}".format(int(lab))
            ylabels.append(lab)

        plt.yticks(locs, ylabels)

        filename = 'tmp\\' + location + '_graph.png'
        plt.savefig(filename, transparent=True)
        plt.close(fig)

        with open(filename, 'rb') as f:
            file = io.BytesIO(f.read())

        image = discord.File(file, filename='graph.png')

        embed = discord.Embed(
            title=f'Coronavirus COVID-19 {location} Cases',
            description='Data from [Johns Hopkins CSSE Github](https://github.com/CSSEGISandData/COVID-19)',
            colour=discord.Colour.red()
        )
        embed.set_image(url=f'attachment://graph.png')
        embed.add_field(name='Confirmed', value= f'**{confirmed}** {change_confirmed}')
        embed.add_field(name='Deaths', value=f'**{deaths}** {change_deaths}')
        embed.add_field(name='Recovered', value=f'**{recovered}** {change_recovered}')
        embed.add_field(name='Mortality Rate', value=f'**{round((deaths/confirmed * 100),2)}%**')
        embed.set_footer(text= f'Updated {updated}')

        await ctx.send(file=image, embed=embed)

    else:
        await ctx.send('There is no available data for this location')

if __name__ == '__main__':
    # import config
    # client.run(config.token)
    client.run(os.environ['TOKEN']) #Heroku


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

positions = []
velocities = []
acelerations = []
masses = []

def get_data(text, type):
    request = input(text)
    if type == "string":
        return request
    elif type == "int":
        return int(request)
    elif type == "float":
        return float(request)
    else:
        return "[ERROR] Type not recognized."

def get_random_number(MIN, MAX):
    return random.uniform(MIN, MAX)

def body_generator(bodyQuantity):
    MIN = -100
    MAX = 100

    for iterator in range(bodyQuantity):
        # Creamos los valores aleatorios
        position = np.array([get_random_number(MIN, MAX), get_random_number(MIN, MAX)])
        velocity = np.array([get_random_number(MIN, MAX), get_random_number(MIN, MAX)])
        aceleration = np.array([get_random_number(MIN, MAX), get_random_number(MIN, MAX)])
        # ! In the mass case we don't use `MIN` value because we can't
        # ! have a negative mass.
        mass = get_random_number(0, MAX)

        positions.append(position)
        velocities.append(velocity)
        acelerations.append(aceleration)
        masses.append(mass)

def get_body_position():
    return positions

def core(logger, trayectory):
    bodyQuantity = get_data("How many bodies do you want?\n", "int")
    GRAPHICATION_LIMIT = get_data("Give me a graphication scale, please\n", "float")
    body_generator(bodyQuantity)

    GRAVITATIONAL_CONSTANT = 0.4
    DELTA_T = 0.01
    posi = np.array(get_body_position())
    iterations = 0

    plt.close()
    fig, ax = plt.subplots()

    plt.xlabel("X axis", fontsize=10)
    plt.ylabel("Y axis", fontsize=10)

    inx = max(np.array(posi)[:,0])-min(np.array(posi)[:,0])
    iny = max(np.array(posi)[:,1])-min(np.array(posi)[:,1])

    body, = ax.plot(np.array(posi)[:,0], np.array(posi)[:,1], 'mo')

    ax.set_xlim(min(np.array(posi)[:,0])-inx*GRAPHICATION_LIMIT,max(np.array(posi)[:,0])+inx*GRAPHICATION_LIMIT)
    ax.set_ylim(min(np.array(posi)[:,1])-iny*GRAPHICATION_LIMIT, max(np.array(posi)[:,1])+iny*GRAPHICATION_LIMIT)

    if logger:
        print("Initial positions:\n")
        print(positions)
        print("Initial velocity:\n")
        print(velocities)

    masses[0] = 500
    positions[0] = np.array([0.0, 0.0])
    while iterations < 100:
        for i in range(len(positions)):
            positionsAuxiliary = positions.copy()
            acelerationsAuxiliary = acelerations.copy()
            massesAuxiliary = masses.copy()

            positionsAuxiliary.pop(i)
            acelerationsAuxiliary.pop(i)
            massesAuxiliary.pop(i)

            for anotherBody in range(len(positionsAuxiliary)):
                distance = positionsAuxiliary[anotherBody] - positions[i]
                distanceNorm = np.linalg.norm(distance)

                term = GRAVITATIONAL_CONSTANT * massesAuxiliary[anotherBody] * masses[i] * distance / ((distanceNorm)**3.0)
                acelerations[i] += term
                if logger:
                    print("\nBody force ", anotherBody, ": ")
                    print(term, "\n")

        for body_actual in range(len(positions)):
            positions[body_actual] += velocities[body_actual] * DELTA_T + 0.5 *acelerations[body_actual]*DELTA_T**2
            velocities[body_actual] += (acelerations[body_actual] * DELTA_T)

        posi = np.array(get_body_position())

        if trayectory:
            trayectory, = ax.plot(np.array(posi)[:, 0], np.array(posi)[:, 1], 'co')
            body.set_data(posi[:,0],posi[:,1])
            body, = ax.plot(np.array(posi)[:,0], np.array(posi)[:,1], 'mo')
        else:
            body.set_data(posi[:,0],posi[:,1])

        title = "N-bodies simulator\nTime:" + str(iterations)
        plt.title(title, fontsize=19)
        plt.pause(0.01)
        iterations += 1

    if logger:
        print("\nFinal positions:\n")
        print(positions)
        print("\nFinal velocities:\n")
        print(velocities)

    plt.show()