import json

notas = list()
medias = list()
auxiliar = list()

def cadastro_aluno(ficha):
    cont = 0
    resp = 'S'
    print('\nCADASTRAR ALUNO\n')
    while cont < 1 and resp in 'Ss' :
        aluno = input('Digite o nome do aluno: ')
        cad = 0
        for alunos in ficha:
            for nome in alunos:
                if nome == aluno:
                    print('Aluno já cadastrado. Deseja cadastrar outro aluno? (S/N)')
                    resp = input()
                    cad += 1

        if cad == 0:
            auxiliar.append(aluno)
            auxiliar.append(notas[:])
            auxiliar.append(medias[:])
            ficha.append(auxiliar[:])
            auxiliar.clear()
            cont += 1

def adicionar_nota(ficha):
    cont = 0
    resp = 'S'
    print('\nADICIONANDO NOTA\n')
    while cont < 1 and resp in 'Ss':
        cad = 0
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            nome_pesquisado = input('Digite o nome do aluno: ')
            for aluno in ficha:
                if aluno[0] == nome_pesquisado:
                    cont2 = True
                    while cont2:
                        try :
                            nota = float(input('Digite a nota do aluno (0.0 - 10.0): '))

                            if (10 >= nota >= 0) and len(aluno[1]) < 3:
                                aluno[1].append(nota)
                                cad += 1
                                cont += 1
                                cont2 = False
                                media = 0
                                for nota in aluno[1]:
                                    media += nota
                                media /= len(aluno[1])
                                aluno[2].clear()
                                aluno[2].append(media)
                            elif len(aluno[1]) >= 3:
                                print('Aluno já possui 3 notas')
                                print('Utilize a opção 6 se deseja editar a nota do aluno')
                                cont2 = False
                            else:
                                print('Nota fora do intervalo. Tente novamente')
                        except Exception as erro:
                            print('Erro ao digitar nota')
                            print(f'O erro foi {erro}')
            if cad >= 1:
                print('Nota adicionada\n')
            else:
                print('Nota não cadastrada. Verifique se o nome do aluno foi digitado corretamente.\n')
                resp = input('Deseja tentar novamente? (S/N): ')

def remover_aluno(ficha):
    print('\nREMOVER ALUNO\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = 0
            nome_pesquisado = input('Digite o nome do aluno: ')
            for aluno in ficha:
                if aluno[0] == nome_pesquisado:
                    ficha.remove(aluno)
                    cad += 1
                    cont += 1
            if cad == 1:
                print(f'O(A) aluno(a) {nome_pesquisado} removido(a)')
            elif nome_pesquisado == 'sair':
                cont +=1
            else:
                print(f'O nome {nome_pesquisado} não foi encontrado')
                print('Digite sair para voltar ao menu')

def remover_nota(ficha):
    print('\nREMOVER NOTA\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = 0
            id_nota = True
            nome_pesquisado = input('Digite o nome do aluno: ')
            for aluno in ficha:
                if aluno[0] == nome_pesquisado:
                    try :
                        nota_pesquisada = int(input('Digite número da nota que deseja remover (1ª, 2ª ou 3ª nota): '))
                        if len(aluno[1]) >= nota_pesquisada:
                            aluno[1].pop(nota_pesquisada - 1)
                            cont += 1
                            cad += 1
                            media = 0
                            for nota in aluno[1]:
                                media += nota
                            if len(aluno[1]) > 0:
                                media /= len(aluno[1])
                                aluno[2].clear()
                                aluno[2].append(media)
                            else:
                                aluno[2].clear()
                        else:
                            id_nota = False

                    except Exception as erro:
                        print('Erro ao digitar a nota')
                        print(f'O erro foi {erro}')
                        id_nota = False

            if cad == 1:
                print(f'A nota {nota_pesquisada} foi removida.')
            elif not(id_nota):
                print(f'A nota não foi não encontrada')
            else:
                print(f'{nome_pesquisado} não foi encontrado')

def editar_nome(ficha):
    print('\nEDITAR NOME\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = 0
            nome_pesquisado = input('Digite o nome do aluno: ')
            for aluno in ficha:
                if aluno[0] == nome_pesquisado:
                    nome = input('Digite o novo nome: ')
                    aluno[0] = nome
                    cont += 1
                    cad += 1

        if cad == 1:
            print('Nome editado')
        elif nome_pesquisado == 'sair':
            cont += 1
        else:
            print('Aluno não encontrado\n Digite sair para voltar ao menu')

def editar_nota(ficha):
    print('\nEDITAR NOTA\n')
    if len(ficha) <= 0:
        print('Ficha ainda não possui alunos cadastrados.\n')

    else:
        cont = 0
        while cont < 1:
            cad = 0
            id_nota = True
            nome_pesquisado = input('Digite o nome do aluno: ')
            for aluno in ficha:
                if aluno[0] == nome_pesquisado:
                    try :
                        nota_pesquisada = int(input('Digite número da nota que deseja editar (1ª, 2ª ou 3ª nota): '))

                        if len(aluno[1]) >= nota_pesquisada:
                            nota = float(input('Digite a nova nota: '))
                            aluno[1].pop(nota_pesquisada - 1)
                            aluno[1].insert(nota_pesquisada - 1, nota)
                            cont += 1
                            cad += 1
                            media = 0
                            for nota in aluno[1]:
                                media += nota
                            if len(aluno[1]) > 0:
                                media /= len(aluno[1])
                                aluno[2].clear()
                                aluno[2].append(media)
                            else:
                                aluno[2].clear()
                        else:
                            id_nota = False

                    except Exception as erro:
                        print('Ocorreu erro ao buscar nota')
                        print(f'O erro foi {erro}')
                        id_nota = False

            if cad == 1:
                print(f'A nota {nota_pesquisada} foi alterada com sucesso')
            elif not(id_nota):
                print(f'A nota não foi encontrada')
            else:
                print(f'{nome_pesquisado} não foi encontrado')

    print(ficha)

def buscar_aluno(ficha):
    print('\nBUSCAR ALUNO POR NOME\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = False
            nome_pesquisado = input('Digite o nome do aluno: ')
            for aluno in ficha:
                if nome_pesquisado in aluno[0]:
                    notas = str()
                    media = 0.0
                    for nota in aluno[1]:
                        notas += str(nota) + " "
                    for nota in aluno[2]:
                        media += nota
                    print('Nome: {0}. Notas: {1}. Média: {2:.2f}'.format(str(aluno[0]).lower().capitalize(), notas, media))
                    cont += 1
                    cad = True

            if not(cad) and nome_pesquisado != 'SAIR':
                print('Aluno não encontrado\nTente novamente ou digite SAIR para voltar ao menu inicial')
            elif nome_pesquisado == 'SAIR':
                cont += 1

def media_turma(ficha):
    print('\nMÉDIA DA TURMA\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.')
            cont += 1
        else:
            media_turma = 0
            for aluno in ficha:
                for media in aluno[2]:
                    media_turma += media
            media_turma /= len(ficha)
            cont += 1
            print('A media da turma é {0:.2f}\n'.format(media_turma))

def melhor_aluno(ficha):
    print('\nMELHOR ALUNO\n')
    cont = 0

    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.')
            cont += 1
        else:
            maior = 0
            for aluno in ficha:
                for media in aluno[2]:
                    if maior < media:
                        maior = media
            for aluno in ficha:
                notas = str()
                for nota in aluno[1]:
                    notas += str(nota) + " "
                for media in aluno[2]:
                    if maior == media:
                        print('{0}. Notas: {1}. Media: {2:.2f}'.format(str(aluno[0]).lower().capitalize(), notas, media))
                    cont += 1

            print()

def classificacao_alfabetica(ficha):
    print('\nALUNOS EM ORDEM ALFABÉTICA\n')
    if len(ficha) <= 0:
       print('Ficha ainda não possui alunos cadastrados.\n')
    else:
        pos = 0
        while pos < len(ficha):
            pos2 = pos
            while (ficha[pos2][0] < ficha[pos2 - 1][0]) and pos2 > 0 :
                aux = ficha[pos2]
                ficha[pos2] = ficha[pos2 - 1]
                ficha[pos2 - 1] = aux
                pos2 -= 1
            pos += 1

        for aluno in ficha:
            if len(aluno[1]) > 0:
                notas = str()
                media = 0

                for nota in aluno[1]:
                    notas += str(nota) + ' '
                for nota in aluno[2]:
                    media += nota
            else:
                media = 0
                notas = '- '

            print('Nome: {0} Notas: {1} Média: {2:.2f}'.format(aluno[0], notas, media))

    print()

def classificacao_media(ficha):
    print('\nALUNOS CLASSIFICADOS POR MEDIA\n')
    if len(ficha) <= 0:
        print('Ficha ainda não possui alunos cadastrados.\n')
    else:
        pos = 0
        while pos < len(ficha):
            pos2 = pos
            while (ficha[pos2][2] > ficha[pos2 - 1][2]) and pos2 > 0 :
                aux = ficha[pos2]
                ficha[pos2] = ficha[pos2 - 1]
                ficha[pos2 - 1] = aux
                pos2 -= 1
            pos += 1

        for aluno in ficha:
            if len(aluno[1]) > 0:
                notas = str()
                media = 0

                for nota in aluno[1]:
                    notas += str(nota) + ' '

                for nota in aluno[2]:
                    media += nota
            else:
                notas = '- '
                media = 0
            print('Nome: {0} Notas: {1} Média: {2:.2f}'.format(str(aluno[0]).lower().capitalize(), notas, media))

    print()

def aprovados(ficha):

    print('\nAPROVADOS POR MEDIA\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = False
            for aluno in ficha:
                media = 0
                notas = str()
                for nota in aluno[1]:
                    notas += str(nota) + ' '
                for nota in aluno[2]:
                    media += nota
                if media >= 7:
                    print('{0}. Notas: {1}. Média: {2}'.format(aluno[0], notas, media))
                    cad = True
                    cont += 1
            if not(cad):
                print('Não houve alunos aprovados\n')

        print()

def alunos_final(ficha):
    print('\nALUNOS NA FINAL\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = False
            for aluno in ficha:
                media = 0
                notas = str()
                for nota in aluno[1]:
                    notas += str(nota) + ' '
                for nota in aluno[2]:
                    media += nota
                if 5 <= media < 7:
                    print('{0}. Notas: {1}. Média: {2}'.format(aluno[0], notas, media))
                    cad = True

            if not(cad):
                print('Não houve alunos na final\n')
        cont += 1

def reprovados(ficha):
    print('\nALUNOS REPROVADOS\n')
    cont = 0
    while cont < 1:
        if len(ficha) <= 0:
            print('Ficha ainda não possui alunos cadastrados.\n')
            cont += 1
        else:
            cad = False
            for aluno in ficha:
                if len(aluno[1]) > 0:
                    media = 0
                    notas = str()
                    for nota in aluno[1]:
                        notas += str(nota) + ' '
                    for nota in aluno[2]:
                        media += nota
                    if  media < 5:
                        print('{0}. Notas: {1}. Média: {2}'.format(aluno[0], notas, media))
                        cad = True

            if not(cad):
                print('Não houveram alunos reprovados\n')
        cont += 1

def salvar_json(ficha) :

    lista_salvar = [
        dict(nome = aluno[0], notas = aluno[1], media = aluno[2])
        for aluno in ficha
    ]

    dict_salvar = {"Ficha": lista_salvar}
    dict_salvar = json.dumps(dict_salvar, indent = 4, sort_keys = False)

    try:
        arquivo_json = open("dados.json", "w")
        arquivo_json.write(dict_salvar)
        arquivo_json.close()

    except Exception as erro:
        print('Ocorreu um erro ao carregar o arquivo.')
        print('O erro é: {}'.format(erro))

def importar_json(ficha):
    arquivo_json = open('dados.json', 'r')
    dados_json = json.load(arquivo_json)
    alunos = dados_json['Ficha']

    try :
        for aluno in alunos :
            auxiliar.append(aluno['nome'])
            auxiliar.append(aluno['notas'])
            auxiliar.append(aluno['media'])
            ficha.append(auxiliar[:])
            auxiliar.clear()
    except Exception as erro:
        print('Ocorreu um erro')
        print(f'O erro é {erro}')


# program to find smallest number in a list

print("========= Naive Method ========")
l = [ i for i in input("List: ").split(" ")]

min1 = l[0]
for i in range(len(l)):
    if l[i] < min1:
        min1 = l[i]

print("Smallest Element: ",min1)

print("\n======= Ask for user input =========")

list1 = []

n =  int(input("Number of Element in List: "))
for i in range(n):
    ele = int(input("enter element: "))
    list1.append(ele)

print("Smallest element in List: ",min(list1))

# Note: Finding Largest can be used similar operation


import requests
import threading
import sys
import os
from bs4 import BeautifulSoup
from pandas import DataFrame
from functools import reduce

if len(sys.argv) == 1:
    CSV_FNAME = 'volunteermatch_data.csv'
else:
    CSV_FNAME = sys.argv[1]

URL_PART1 = 'https://www.volunteermatch.org/search/'

locations = ['New+York%2C+NY%2C+USA', 'Chicago%2C+IL%2C+USA',
             'San+Francisco%2C+CA%2C+USA', 'Boston%2C+MA%2C+USA',
             'Houston%2C+TX%2C+USA', 'Los+Angeles%2C+CA%2C+USA',
             'Philadelphia%2C+PA%2C+USA', 'Seattle%2C+WA%2C+USA',
             'Atlanta%2C+GA%2C+USA', 'Dallas%2C+TX%2C+USA',
             'Portland%2C+OR%2C+USA', 'Cleveland%2C+OH%2C+USA',
             'Denver%2C+CO%2C+USA', 'Washington%2C+DC%2C+USA']

categories = {
    'community': 25,
    'arts_culture': 34,
    'advocacy': 23,
    'seniors': 12,
    'homeless_housing': 7,
    'health_med': 11,
    'child_youth': 22,
    'animals': 30,
    'edu_lit': 15,
    'crisis_support': 14,
    'women': 3
}

dfs = []

def url_to_df(urls, cat):
    opps = []
    for url in urls:
        r = requests.get(url)
        soup = BeautifulSoup(r.content, 'html5lib')
        table = soup.find('div', attrs={'class': 'search-page'})
        for row in table.findAll('div', attrs={'class': 'searchitem PUBLIC'}):
            opp = {}
            opp['title'] = row.h3.text.strip()
            opp['org'] = row.find_all('a')[1].text.strip()
            desc_search = row.find_all('p')
            desc_index = 0
            for i in range(len(desc_search)):
                if len(desc_search[i].getText()) > 100:
                    desc_index = i
            opp['desc'] = row.find_all('p')[desc_index].getText().strip()
            opp['desc'] = opp['desc'].split('\n')[0]
            opp[cat] = True
            opps.append(opp)
    df = DataFrame(opps)
    df = df.drop_duplicates(keep=False)
    dfs.append(df)

threads = []
for cat, cat_v in categories.items():
    urls = []
    for loc in locations:
        url = URL_PART1 + f'?categories={cat_v}&' \
                        + f'l={loc}'
        urls += [url + f'&s={s}' for s in [x*10+1 for x in range(100)]]
    t = threading.Thread(target=url_to_df, args=(urls, cat))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

final_df = reduce(lambda df1, df2: df1.merge(df2, left_on=['title', 'org', 'desc'],
                                                  right_on=['title', 'org', 'desc'],
                                                  how='outer'), dfs)
final_df = final_df.fillna(False)
final_df.to_csv(CSV_FNAME)


# -*- coding: utf-8 -*-
# @Time : 2020/11/22 8:50
# @Author : Zhongyi Hua
# @FileName: ssr_utils.py
# @Usage:
# @Note:
# @E-mail: njbxhzy@hotmail.com

from Bio import SeqIO
from os import remove as del_file
import multiprocessing as multi
from tqdm import tqdm

def build_rep_set(repeat_file, unit_cutoff=None, motif_length_cutoff=None):
    """
        Outputs the repeats info dictionary used by the get_ssrs function.
        Takes list of repeat motifs from repeats file(output by generate_repeats function) as input.
        Creates a dictionary with expanded repeat as the key and (class, motif_length, strand) as values.
        Works either by "length_cutoff=" or by "unit_cutoff=" arguments.
    """
    repeats_out = dict()
    cutoffs = set()
    if unit_cutoff is None:
        unit_cutoff = {1: 9, 2: 6, 3: 6, 4: 6, 5: 5, 6: 4}
    for line in repeat_file:
        motif_dict = dict()
        L = line.strip().split('\t')
        motif_length = int(L[2])
        if motif_length < motif_length_cutoff:
            continue
        motif = L[0]
        motif = motif*unit_cutoff[motif_length]
        cutoffs.add(len(motif))
        motif_dict['class'] = L[1]
        motif_dict['motif_length'] = motif_length
        motif_dict['strand'] = L[3]
        repeats_out[motif] = motif_dict
    repeats_out['cutoff'] = sorted(list(cutoffs))

    return repeats_out

def get_ssrs(seq_record, repeats_info, out):
    """Native function that identifies repeats in fasta files."""
    if type(out) == str:
        out_file = open(out, 'w')
    else:
        out_file = out
    length_cutoffs = repeats_info['cutoff']
    input_seq = str(seq_record.seq).upper()
    input_seq_length = len(input_seq)
    for length_cutoff in length_cutoffs:
        fallback = length_cutoff - 1
        sub_start = 0  # substring start
        sub_stop = sub_start + length_cutoff  # substring stop
        while sub_stop <= input_seq_length:
            sub_stop = sub_start + length_cutoff
            sub_seq = input_seq[sub_start:sub_stop]
            if sub_seq in repeats_info:
                match = True
                repeat_data = repeats_info[sub_seq]
                motif_length = repeat_data['motif_length']
                rep_class = repeat_data['class']
                strand = repeat_data['strand']
                offset = length_cutoff % motif_length
                repeat_seq = input_seq[sub_start+offset:sub_start+offset+motif_length]
                i = 0
                while match:
                    j = sub_stop
                    if sub_stop >= input_seq_length:
                        match = False
                        match_length = sub_stop - sub_start
                        num_units = int(match_length/motif_length)
                        print(seq_record.id, sub_start + 1, sub_stop + 1, rep_class, match_length, strand, num_units, sub_seq[:motif_length], seq_record.id + '_' + str(sub_start + 1), sep="\t", file=out_file)
                        sub_start = sub_stop - fallback
                    elif input_seq[j] == repeat_seq[i]:
                        sub_stop += 1
                        i += 1
                        if i >= motif_length:
                            i = 0
                    else:
                        match = False
                        match_length = sub_stop - sub_start
                        num_units = int(match_length/motif_length)
                        print(seq_record.id, sub_start + 1, sub_stop + 1, rep_class, match_length, strand, num_units, sub_seq[:motif_length], seq_record.id + '_' + str(sub_start + 1), sep="\t", file=out_file)
                        sub_start = sub_stop - fallback
            else:
                sub_start += 1
    if type(out) == str:
        out_file.close()

def fasta_ssrs(args, repeats_info):
    """

    :param args:
    :param repeats_info:  return from build_rep_set function
    :return:
    """
    handle = open(args.input, 'r')

    records = [ _ for _ in SeqIO.parse(handle, 'fasta')]
    num_records = len(records)

    file_output = open(args.output, 'w')
    print('\t'.join(['seqid', 'start', 'end', 'class', 'length', 'strand', 'units', 'motif', 'ID']), file=file_output)

    if args.threads > 1:
        i = 0
        pool = multi.Pool(processes=args.threads)
        for record in records:
            out_name = './temp_%s.tsv' % (i)
            i += 1
            pool.apply_async(get_ssrs, (record, repeats_info, out_name,))

        pool.close()
        pool.join()

        # Concat all the output files into one.
        temp_outs = tqdm(range(num_records), total=num_records)

        for o in temp_outs:
            name = './temp_%s.tsv' % (o)
            temp_outs.set_description("Concatenating file: %d " % (o))
            with open(name, 'r') as fh:
                for line in fh:
                    print(line.strip(), file=file_output)
            del_file(name)

    elif args.threads == 1:
        records = tqdm(records, total=num_records)
        for record in records:
            records.set_description("Processing %s" % (record.id))
            get_ssrs(record, repeats_info, file_output)


name = input('Enter file: ')
handle = open(name)
counts =dict()
for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word, 0) + 1
print('Number of words fox: ', counts.get('fox', 0))
print('Number of every word as dictionary: ', counts)
'''bigcount = None
bigword = None
for word, count in counts.items():
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count
print(bigword, bigcount)'''
tmp = list()
for word, count in counts.items():
    tmp.append((count, word))
tmp = sorted(tmp, reverse=True)
print(f"Here is the descending word frequency in a given text: {tmp}")
for count, word in tmp[:5]:
    print(word, count)


import time

start = time.time()

'''
MAXN=1000
dp = [0]*(MAXN)

# base case
dp[0] = 1
for i in range(1,MAXN):
   dp[i] = dp[i-1] * i
print(dp[-1])
'''
'''
list1 = [0]*10
list2=list1
list1.append(2)
list2.extend([3,4])
print(list1)
print(list2)
'''
def area(length: int, width: int):
    print(length * width)

area_func = globals()["area"]
print(type(area_func))
area_func(5, 5)

print(time.time()-start)


# Released under the MIT License. See LICENSE for details.
#
"""Playlist related functionality."""

from __future__ import annotations

import copy
import logging
from typing import Any, TYPE_CHECKING

import babase

if TYPE_CHECKING:
    from typing import Sequence

    from bascenev1._session import Session

PlaylistType = list[dict[str, Any]]

def filter_playlist(
    playlist: PlaylistType,
    sessiontype: type[Session],
    add_resolved_type: bool = False,
    remove_unowned: bool = True,
    mark_unowned: bool = False,
    name: str = '?',
) -> PlaylistType:
    """Return a filtered version of a playlist.

    Strips out or replaces invalid or unowned game types, makes sure all
    settings are present, and adds in a 'resolved_type' which is the actual
    type.
    """
    # pylint: disable=too-many-locals
    # pylint: disable=too-many-branches
    # pylint: disable=too-many-statements
    from bascenev1._map import get_filtered_map_name
    from bascenev1._gameactivity import GameActivity

    assert babase.app.classic is not None

    goodlist: list[dict] = []
    unowned_maps: Sequence[str]
    available_maps: list[str] = list(babase.app.classic.maps.keys())
    if (remove_unowned or mark_unowned) and babase.app.classic is not None:
        unowned_maps = babase.app.classic.store.get_unowned_maps()
        unowned_game_types = babase.app.classic.store.get_unowned_game_types()
    else:
        unowned_maps = []
        unowned_game_types = set()

    for entry in copy.deepcopy(playlist):
        # 'map' used to be called 'level' here.
        if 'level' in entry:
            entry['map'] = entry['level']
            del entry['level']

        # We now stuff map into settings instead of it being its own thing.
        if 'map' in entry:
            entry['settings']['map'] = entry['map']
            del entry['map']

        # Update old map names to new ones.
        entry['settings']['map'] = get_filtered_map_name(
            entry['settings']['map']
        )
        if remove_unowned and entry['settings']['map'] in unowned_maps:
            continue

        # Ok, for each game in our list, try to import the module and grab
        # the actual game class. add successful ones to our initial list
        # to present to the user.
        if not isinstance(entry['type'], str):
            raise TypeError('invalid entry format')
        try:
            # Do some type filters for backwards compat.
            if entry['type'] in (
                'Assault.AssaultGame',
                'Happy_Thoughts.HappyThoughtsGame',
                'bsAssault.AssaultGame',
                'bs_assault.AssaultGame',
                'bastd.game.assault.AssaultGame',
            ):
                entry['type'] = 'bascenev1lib.game.assault.AssaultGame'
            if entry['type'] in (
                'King_of_the_Hill.KingOfTheHillGame',
                'bsKingOfTheHill.KingOfTheHillGame',
                'bs_king_of_the_hill.KingOfTheHillGame',
                'bastd.game.kingofthehill.KingOfTheHillGame',
            ):
                entry[
                    'type'
                ] = 'bascenev1lib.game.kingofthehill.KingOfTheHillGame'
            if entry['type'] in (
                'Capture_the_Flag.CTFGame',
                'bsCaptureTheFlag.CTFGame',
                'bs_capture_the_flag.CTFGame',
                'bastd.game.capturetheflag.CaptureTheFlagGame',
            ):
                entry[
                    'type'
                ] = 'bascenev1lib.game.capturetheflag.CaptureTheFlagGame'
            if entry['type'] in (
                'Death_Match.DeathMatchGame',
                'bsDeathMatch.DeathMatchGame',
                'bs_death_match.DeathMatchGame',
                'bastd.game.deathmatch.DeathMatchGame',
            ):
                entry['type'] = 'bascenev1lib.game.deathmatch.DeathMatchGame'
            if entry['type'] in (
                'ChosenOne.ChosenOneGame',
                'bsChosenOne.ChosenOneGame',
                'bs_chosen_one.ChosenOneGame',
                'bastd.game.chosenone.ChosenOneGame',
            ):
                entry['type'] = 'bascenev1lib.game.chosenone.ChosenOneGame'
            if entry['type'] in (
                'Conquest.Conquest',
                'Conquest.ConquestGame',
                'bsConquest.ConquestGame',
                'bs_conquest.ConquestGame',
                'bastd.game.conquest.ConquestGame',
            ):
                entry['type'] = 'bascenev1lib.game.conquest.ConquestGame'
            if entry['type'] in (
                'Elimination.EliminationGame',
                'bsElimination.EliminationGame',
                'bs_elimination.EliminationGame',
                'bastd.game.elimination.EliminationGame',
            ):
                entry['type'] = 'bascenev1lib.game.elimination.EliminationGame'
            if entry['type'] in (
                'Football.FootballGame',
                'bsFootball.FootballTeamGame',
                'bs_football.FootballTeamGame',
                'bastd.game.football.FootballTeamGame',
            ):
                entry['type'] = 'bascenev1lib.game.football.FootballTeamGame'
            if entry['type'] in (
                'Hockey.HockeyGame',
                'bsHockey.HockeyGame',
                'bs_hockey.HockeyGame',
                'bastd.game.hockey.HockeyGame',
            ):
                entry['type'] = 'bascenev1lib.game.hockey.HockeyGame'
            if entry['type'] in (
                'Keep_Away.KeepAwayGame',
                'bsKeepAway.KeepAwayGame',
                'bs_keep_away.KeepAwayGame',
                'bastd.game.keepaway.KeepAwayGame',
            ):
                entry['type'] = 'bascenev1lib.game.keepaway.KeepAwayGame'
            if entry['type'] in (
                'Race.RaceGame',
                'bsRace.RaceGame',
                'bs_race.RaceGame',
                'bastd.game.race.RaceGame',
            ):
                entry['type'] = 'bascenev1lib.game.race.RaceGame'
            if entry['type'] in (
                'bsEasterEggHunt.EasterEggHuntGame',
                'bs_easter_egg_hunt.EasterEggHuntGame',
                'bastd.game.easteregghunt.EasterEggHuntGame',
            ):
                entry[
                    'type'
                ] = 'bascenev1lib.game.easteregghunt.EasterEggHuntGame'
            if entry['type'] in (
                'bsMeteorShower.MeteorShowerGame',
                'bs_meteor_shower.MeteorShowerGame',
                'bastd.game.meteorshower.MeteorShowerGame',
            ):
                entry[
                    'type'
                ] = 'bascenev1lib.game.meteorshower.MeteorShowerGame'
            if entry['type'] in (
                'bsTargetPractice.TargetPracticeGame',
                'bs_target_practice.TargetPracticeGame',
                'bastd.game.targetpractice.TargetPracticeGame',
            ):
                entry[
                    'type'
                ] = 'bascenev1lib.game.targetpractice.TargetPracticeGame'

            gameclass = babase.getclass(entry['type'], GameActivity)

            if entry['settings']['map'] not in available_maps:
                raise babase.MapNotFoundError()

            if remove_unowned and gameclass in unowned_game_types:
                continue
            if add_resolved_type:
                entry['resolved_type'] = gameclass
            if mark_unowned and entry['settings']['map'] in unowned_maps:
                entry['is_unowned_map'] = True
            if mark_unowned and gameclass in unowned_game_types:
                entry['is_unowned_game'] = True

            # Make sure all settings the game defines are present.
            neededsettings = gameclass.get_available_settings(sessiontype)
            for setting in neededsettings:
                if setting.name not in entry['settings']:
                    entry['settings'][setting.name] = setting.default

            goodlist.append(entry)

        except babase.MapNotFoundError:
            logging.warning(
                'Map \'%s\' not found while scanning playlist \'%s\'.',
                entry['settings']['map'],
                name,
            )
        except ImportError as exc:
            logging.warning(
                'Import failed while scanning playlist \'%s\': %s', name, exc
            )
        except Exception:
            logging.exception('Error in filter_playlist.')

    return goodlist

def get_default_free_for_all_playlist() -> PlaylistType:
    """Return a default playlist for free-for-all mode."""

    # NOTE: these are currently using old type/map names,
    # but filtering translates them properly to the new ones.
    # (is kinda a handy way to ensure filtering is working).
    # Eventually should update these though.
    return [
        {
            'settings': {
                'Epic Mode': False,
                'Kills to Win Per Player': 10,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Doom Shroom',
            },
            'type': 'bs_death_match.DeathMatchGame',
        },
        {
            'settings': {
                'Chosen One Gets Gloves': True,
                'Chosen One Gets Shield': False,
                'Chosen One Time': 30,
                'Epic Mode': 0,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Monkey Face',
            },
            'type': 'bs_chosen_one.ChosenOneGame',
        },
        {
            'settings': {
                'Hold Time': 30,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Zigzag',
            },
            'type': 'bs_king_of_the_hill.KingOfTheHillGame',
        },
        {
            'settings': {'Epic Mode': False, 'map': 'Rampage'},
            'type': 'bs_meteor_shower.MeteorShowerGame',
        },
        {
            'settings': {
                'Epic Mode': 1,
                'Lives Per Player': 1,
                'Respawn Times': 1.0,
                'Time Limit': 120,
                'map': 'Tip Top',
            },
            'type': 'bs_elimination.EliminationGame',
        },
        {
            'settings': {
                'Hold Time': 30,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'The Pad',
            },
            'type': 'bs_keep_away.KeepAwayGame',
        },
        {
            'settings': {
                'Epic Mode': True,
                'Kills to Win Per Player': 10,
                'Respawn Times': 0.25,
                'Time Limit': 120,
                'map': 'Rampage',
            },
            'type': 'bs_death_match.DeathMatchGame',
        },
        {
            'settings': {
                'Bomb Spawning': 1000,
                'Epic Mode': False,
                'Laps': 3,
                'Mine Spawn Interval': 4000,
                'Mine Spawning': 4000,
                'Time Limit': 300,
                'map': 'Big G',
            },
            'type': 'bs_race.RaceGame',
        },
        {
            'settings': {
                'Hold Time': 30,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Happy Thoughts',
            },
            'type': 'bs_king_of_the_hill.KingOfTheHillGame',
        },
        {
            'settings': {
                'Enable Impact Bombs': 1,
                'Enable Triple Bombs': False,
                'Target Count': 2,
                'map': 'Doom Shroom',
            },
            'type': 'bs_target_practice.TargetPracticeGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Lives Per Player': 5,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Step Right Up',
            },
            'type': 'bs_elimination.EliminationGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Kills to Win Per Player': 10,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Crag Castle',
            },
            'type': 'bs_death_match.DeathMatchGame',
        },
        {
            'map': 'Lake Frigid',
            'settings': {
                'Bomb Spawning': 0,
                'Epic Mode': False,
                'Laps': 6,
                'Mine Spawning': 2000,
                'Time Limit': 300,
                'map': 'Lake Frigid',
            },
            'type': 'bs_race.RaceGame',
        },
    ]

def get_default_teams_playlist() -> PlaylistType:
    """Return a default playlist for teams mode."""

    # NOTE: these are currently using old type/map names,
    # but filtering translates them properly to the new ones.
    # (is kinda a handy way to ensure filtering is working).
    # Eventually should update these though.
    return [
        {
            'settings': {
                'Epic Mode': False,
                'Flag Idle Return Time': 30,
                'Flag Touch Return Time': 0,
                'Respawn Times': 1.0,
                'Score to Win': 3,
                'Time Limit': 600,
                'map': 'Bridgit',
            },
            'type': 'bs_capture_the_flag.CTFGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Respawn Times': 1.0,
                'Score to Win': 3,
                'Time Limit': 600,
                'map': 'Step Right Up',
            },
            'type': 'bs_assault.AssaultGame',
        },
        {
            'settings': {
                'Balance Total Lives': False,
                'Epic Mode': False,
                'Lives Per Player': 3,
                'Respawn Times': 1.0,
                'Solo Mode': True,
                'Time Limit': 600,
                'map': 'Rampage',
            },
            'type': 'bs_elimination.EliminationGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Kills to Win Per Player': 5,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Roundabout',
            },
            'type': 'bs_death_match.DeathMatchGame',
        },
        {
            'settings': {
                'Respawn Times': 1.0,
                'Score to Win': 1,
                'Time Limit': 600,
                'map': 'Hockey Stadium',
            },
            'type': 'bs_hockey.HockeyGame',
        },
        {
            'settings': {
                'Hold Time': 30,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Monkey Face',
            },
            'type': 'bs_keep_away.KeepAwayGame',
        },
        {
            'settings': {
                'Balance Total Lives': False,
                'Epic Mode': True,
                'Lives Per Player': 1,
                'Respawn Times': 1.0,
                'Solo Mode': False,
                'Time Limit': 120,
                'map': 'Tip Top',
            },
            'type': 'bs_elimination.EliminationGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Respawn Times': 1.0,
                'Score to Win': 3,
                'Time Limit': 300,
                'map': 'Crag Castle',
            },
            'type': 'bs_assault.AssaultGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Kills to Win Per Player': 5,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Doom Shroom',
            },
            'type': 'bs_death_match.DeathMatchGame',
        },
        {
            'settings': {'Epic Mode': False, 'map': 'Rampage'},
            'type': 'bs_meteor_shower.MeteorShowerGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Flag Idle Return Time': 30,
                'Flag Touch Return Time': 0,
                'Respawn Times': 1.0,
                'Score to Win': 2,
                'Time Limit': 600,
                'map': 'Roundabout',
            },
            'type': 'bs_capture_the_flag.CTFGame',
        },
        {
            'settings': {
                'Respawn Times': 1.0,
                'Score to Win': 21,
                'Time Limit': 600,
                'map': 'Football Stadium',
            },
            'type': 'bs_football.FootballTeamGame',
        },
        {
            'settings': {
                'Epic Mode': True,
                'Respawn Times': 0.25,
                'Score to Win': 3,
                'Time Limit': 120,
                'map': 'Bridgit',
            },
            'type': 'bs_assault.AssaultGame',
        },
        {
            'map': 'Doom Shroom',
            'settings': {
                'Enable Impact Bombs': 1,
                'Enable Triple Bombs': False,
                'Target Count': 2,
                'map': 'Doom Shroom',
            },
            'type': 'bs_target_practice.TargetPracticeGame',
        },
        {
            'settings': {
                'Hold Time': 30,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Tip Top',
            },
            'type': 'bs_king_of_the_hill.KingOfTheHillGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Respawn Times': 1.0,
                'Score to Win': 2,
                'Time Limit': 300,
                'map': 'Zigzag',
            },
            'type': 'bs_assault.AssaultGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Flag Idle Return Time': 30,
                'Flag Touch Return Time': 0,
                'Respawn Times': 1.0,
                'Score to Win': 3,
                'Time Limit': 300,
                'map': 'Happy Thoughts',
            },
            'type': 'bs_capture_the_flag.CTFGame',
        },
        {
            'settings': {
                'Bomb Spawning': 1000,
                'Epic Mode': True,
                'Laps': 1,
                'Mine Spawning': 2000,
                'Time Limit': 300,
                'map': 'Big G',
            },
            'type': 'bs_race.RaceGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Kills to Win Per Player': 5,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Monkey Face',
            },
            'type': 'bs_death_match.DeathMatchGame',
        },
        {
            'settings': {
                'Hold Time': 30,
                'Respawn Times': 1.0,
                'Time Limit': 300,
                'map': 'Lake Frigid',
            },
            'type': 'bs_keep_away.KeepAwayGame',
        },
        {
            'settings': {
                'Epic Mode': False,
                'Flag Idle Return Time': 30,
                'Flag Touch Return Time': 3,
                'Respawn Times': 1.0,
                'Score to Win': 2,
                'Time Limit': 300,
                'map': 'Tip Top',
            },
            'type': 'bs_capture_the_flag.CTFGame',
        },
        {
            'settings': {
                'Balance Total Lives': False,
                'Epic Mode': False,
                'Lives Per Player': 3,
                'Respawn Times': 1.0,
                'Solo Mode': False,
                'Time Limit': 300,
                'map': 'Crag Castle',
            },
            'type': 'bs_elimination.EliminationGame',
        },
        {
            'settings': {
                'Epic Mode': True,
                'Respawn Times': 0.25,
                'Time Limit': 120,
                'map': 'Zigzag',
            },
            'type': 'bs_conquest.ConquestGame',
        },
    ]


#유클리드 호제법
def gcd(a,b):

    while b != 0:

        a,b = b, a%b

    return a

#오일러의 phi

def phi(n):

    #1과는 어차피 서로소이므로 최솟값은 1
    result = 1

    for i in range(2,n):

        if gcd(i,n) == 1: #2부터 n-1까지 n과의 최대공약수가 1이면

            result += 1

    return result


from .base import *

SECRET_KEY = '3@(2#f78$ima@91y04uhqy*r6c98syn+79xff2=6^6f-b9_5=a'
DEBUG = True
ALLOWED_HOSTS = ['*']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

INSTALLED_APPS += [
    'debug_toolbar',
    'django_extensions',
]

MIDDLEWARE += [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

INTERNAL_IPS = ('127.0.0.1')

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Taks for every hour
CRONJOBS = [
    ('* 6 * * *', 'core.cron.my_cron_job')
]

CRONTAB_DJANGO_SETTINGS_MODULE = 'school.settings.dev'


import bpy
import os
from io_scs_tools.utils.printout import lprint
from io_scs_tools.utils import get_scs_globals as _get_scs_globals

def strip_sep(path):
    """Strips double path separators (slashes and backslashes) on the start and the end of the given path
    :param path: path to strip separators from
    :type path: str
    :return: new stripped path
    :rtype: str
    """
    return path.strip("\\\\").strip("//")

def get_filename(path, with_ext=True):
    """Returns file name from given file, with or without extension.
    It finds last "os.sep" inside string and returns tail.
    :param path: path with file name
    :type path: str
    :param with_ext: return file name with extension or not
    :type with_ext: bool
    :return: file name with or without extension
    :rtype: str
    """

    # find last separator; prefer os.sep otherwise search for normal slash
    last_sep = path.rfind(os.sep)
    if last_sep < 0:
        last_sep = path.rfind("/")

    new_path = path[last_sep + 1:]
    if not with_ext and new_path.rfind(".") > 0:
        new_path = new_path[:new_path.rfind(".")]
    return new_path

def repair_path(filepath):
    """Takes a Blender filepath and tries to make it a valid absolute path."""
    if filepath != '':
        # print('0 filepath:\n"%s"' % filepath)
        filepath = bpy.path.abspath(filepath, start=None, library=None)  # make the path absolute
        # print('1 filepath:\n"%s"' % filepath)
        filepath = os.path.normpath(filepath)  # repair things like "...\dir\dir\..\dir\..."
        # print('2 filepath:\n"%s"' % filepath)
    return filepath

def relative_path(base_path, path):
    """Takes a base path and other path and returns the relative version of the second path
    if possible, otherwise it returns the original one (absolute path)."""
    repaired_base_path = repair_path(base_path)
    # print('repaired_base_path:\n\t"%s"' % repaired_base_path)
    repaired_path = repair_path(path)
    # print('repaired_path:\n\t"%s"' % repaired_path)
    if len(repaired_base_path) > 2:
        # presuming that equality of first two chars means we are on same mount point
        if startswith(repaired_path[:2], repaired_base_path[:2]):
            rel_path = os.path.relpath(repaired_path, repaired_base_path).replace("\\", "/")
            # print('rel_path:\n\t"%s"' % rel_path)
            if not rel_path.startswith("//"):
                rel_path = "//" + rel_path
            return rel_path
        else:
            lprint("W Not possible to create a relative path! Returning absolute path (%s)", (repaired_path,))
            return repaired_path
    else:
        lprint("W No base path specified! It's not possible to create a relative path! Returning absolute path (%s)", (repaired_path,))
        return repaired_path

def get_abs_path(path_in, subdir_path='', is_dir=False, skip_mod_check=False):
    """Gets absolute path to the "SCS Project Base Path" if given path is relative (starts with: "//"),
    otherwise original path is returned.
    If relative path is existing and valid, it returns the absolute path, otherwise None.
    Optionally a subdir_path can be provided, which will be added to the 'SCS Project Base Path'.
    If skipping of mod check is not specified then function will also try to look in two
    parent base directories, in the case "SCS Project Base Path" is currently set to mod/dlc package.

    :param path_in: Absolute or relative path to current 'SCS Project Base path'
    :type path_in: str
    :param subdir_path: Additional subdirs can be provided, they will be added to the 'SCS Project Base Path'
    :type subdir_path: str
    :param is_dir: flag specifying if given path should be directory
    :type is_dir: bool
    :param skip_mod_check: flag specifying if check for dlc/mod should be skipped
    :type skip_mod_check: bool
    :return: Absolute path or None
    :rtype: str
    """
    root_path = _get_scs_globals().scs_project_path
    if subdir_path != '':
        root_path = os.path.join(root_path, subdir_path)

    if path_in.startswith("//"):
        if len(root_path) > 2:
            result = os.path.join(root_path, path_in[2:])
        else:
            result = None
    else:
        result = path_in

    existance_check = os.path.isdir if is_dir else os.path.isfile

    if result is not None and not existance_check(result) and not skip_mod_check:
        result = get_abs_path(path_in, subdir_path="../base", is_dir=is_dir, skip_mod_check=True)

    if result is not None and not existance_check(result) and not skip_mod_check:
        result = get_abs_path(path_in, subdir_path="../../base", is_dir=is_dir, skip_mod_check=True)

    # finally if file/dir not found return correct abs path, not the one from parent dirs
    if result is not None and not existance_check(result) and not skip_mod_check:
        result = get_abs_path(path_in, subdir_path=subdir_path, is_dir=is_dir, skip_mod_check=True)

    return result

def is_valid_shader_texture_path(shader_texture):
    """It returns True if there is valid Shader Texture file, otherwise False.

    :param shader_texture: SCS texture path, can be absolute or relative
    :type shader_texture: str
    :return: True if there is valid Shader Texture file, otherwise False
    :rtype: bool
    """
    if shader_texture != "":

        if shader_texture.startswith("//"):  # RELATIVE PATH

            shader_texture_abs_path = get_abs_path(shader_texture)

            if shader_texture_abs_path and os.path.isfile(shader_texture_abs_path):
                return True

        else:  # ABSOLUTE PATH

            if os.path.isfile(shader_texture):
                return True

    return False

def is_valid_shader_presets_library_path():
    """It returns True if there is valid "*.txt" file in
    the Shader Presets Library directory, otherwise False."""
    shader_presets_filepath = _get_scs_globals().shader_presets_filepath
    if shader_presets_filepath != "":
        if shader_presets_filepath.startswith("//"):  # RELATIVE PATH
            shader_presets_abs_path = get_abs_path(shader_presets_filepath)
            if shader_presets_abs_path:
                if os.path.isfile(shader_presets_abs_path):
                    return True
        else:  # ABSOLUTE PATH
            if os.path.isfile(shader_presets_filepath):
                return True
    return False

def is_valid_trigger_actions_rel_path():
    """It returns True if there is valid "*.sii" file in
    the Trigger Actions directory, otherwise False."""
    trig_actions_abs_path = get_abs_path(_get_scs_globals().trigger_actions_rel_path)
    if trig_actions_abs_path:
        if os.path.isfile(trig_actions_abs_path):
            return True
        else:
            return False
    else:
        return False

def is_valid_sign_library_rel_path():
    """It returns True if there is valid "*.sii" file in
    the Sign Library directory, otherwise False."""
    sign_library_abs_path = get_abs_path(_get_scs_globals().sign_library_rel_path)
    if sign_library_abs_path:
        if os.path.isfile(sign_library_abs_path):
            return True
        else:
            return False
    else:
        return False

def is_valid_tsem_library_rel_path():
    """It returns True if there is valid "*.sii" file in
    the Traffic Semaphore Profile Library directory, otherwise False."""
    tsem_library_abs_path = get_abs_path(_get_scs_globals().tsem_library_rel_path)
    if tsem_library_abs_path:
        if os.path.isfile(tsem_library_abs_path):
            return True
        else:
            return False
    else:
        return False

def is_valid_traffic_rules_library_rel_path():
    """It returns True if there is valid "*.sii" file in
    the Traffic Rules Library directory, otherwise False."""
    traffic_rules_library_abs_path = get_abs_path(_get_scs_globals().traffic_rules_library_rel_path)
    if traffic_rules_library_abs_path:
        if os.path.isfile(traffic_rules_library_abs_path):
            return True
        else:
            return False
    else:
        return False

def is_valid_hookup_library_rel_path():
    """It returns True if there is at least one "*.sii" file in
    the resulting CgFX Library directory, otherwise False."""
    hookup_library_abs_path = get_abs_path(_get_scs_globals().hookup_library_rel_path, is_dir=True)
    if hookup_library_abs_path:
        for root, dirs, files in os.walk(hookup_library_abs_path):
            for file in files:
                if file.endswith(".sii"):
                    return True
            return False
    else:
        return False

def is_valid_matsubs_library_rel_path():
    """It returns True if there is valid "*.db" file in
    the Material Substance Library directory, otherwise False."""
    matsubs_library_abs_path = get_abs_path(_get_scs_globals().matsubs_library_rel_path)
    # print(' matsubs_library_abs_path: %r' % str(matsubs_library_abs_path))
    if matsubs_library_abs_path:
        if os.path.isfile(matsubs_library_abs_path):
            return True
        else:
            return False
    else:
        return False

def get_addon_installation_paths():
    """Returns a list of paths to the directories where the addon can be installed."""
    script_paths = bpy.utils.script_paths()
    addon_dirs = ('addons', 'addons_contrib')
    script_locations = []

    for script_path in script_paths:
        for addon_dir in addon_dirs:
            script_locations.append(os.path.join(script_path, addon_dir, 'io_scs_tools'))

    scs_installation_dirs = []
    for location in script_locations:
        if os.path.isdir(location):
            scs_installation_dirs.append(location)

    if len(scs_installation_dirs) == 0:
        lprint('''\n\nE The installation directory of "SCS Blender Tools" couldn't be detected! (Shouldn't happen!)\n''')
    elif len(scs_installation_dirs) > 1:
        lprint('\n\nW More than one installation of "SCS Blender Tools" detected!\n\t  Please remove redundant installations so the only one '
               'remain.\n')

    return scs_installation_dirs

def get_shader_presets_filepath():
    """Returns a valid filepath to "shader_presets.txt" file. If the file doesn't exists,
    the empty string is returned and Shader Presets won't be available."""
    scs_installation_dirs = get_addon_installation_paths()

    shader_presets_file = ''
    for location in scs_installation_dirs:
        test_path = os.path.join(location, 'shader_presets.txt')
        if os.path.isfile(test_path):
            shader_presets_file = test_path
            break

    return shader_presets_file

def get_texture_path_from_tobj(tobj_filepath, raw_value=False):
    """Get absolute path of texture from given tobj filepath.
    If raw value is requested returned path is direct value written in TOBJ.
    NOTE: there is no safety check if file exists.

    :param tobj_filepath: absolute tobj file path
    :type tobj_filepath: str
    :param raw_value: flag for indicating if texture path shall be returned as it's written in TOBJ
    :type raw_value: bool
    :return: absolute texture file path if found or None
    :rtype: str | None
    """

    from io_scs_tools.internals.containers.tobj import TobjContainer

    container = TobjContainer.read_data_from_file(tobj_filepath, skip_validation=raw_value)
    tobj_dir, tobj_filename = os.path.split(tobj_filepath)

    if container is None:
        return None

    if raw_value:
        return container.map_names[0]

    if container.map_names[0][0] == "/":
        return get_abs_path("//" + container.map_names[0][1:])

    return os.path.join(tobj_dir, container.map_names[0])

def get_texture_extens_and_strip_path(texture_path):
    """Gets all supported texture extensions and strips given input path for any of it.

    :param texture_path: shader texture raw path value
    :type texture_path: str
    :return: list of extensions and stripped path as tuple
    :rtype: tuple[list[str], str]
    """

    extensions = [".tobj", ".tga", ".png"]

    # strip of any extensions ( endswith is most secure, because of possible multiple extensions )
    if texture_path.endswith(".tobj"):

        extensions.insert(0, texture_path[-5:])
        texture_path = texture_path[:-5]

    elif texture_path.endswith(".tga") or texture_path.endswith(".png"):

        extensions.insert(0, texture_path[-4:])
        texture_path = texture_path[:-4]

    return extensions, texture_path

def get_scs_texture_str(texture_string):
    """Get texture string as presented in SCS files: "/material/environment/vehicle_reflection"
    without any file extensions. Input path can also have texture object extension or supported images extensions.
    Path will be searched and returned in this order:
    1. relative path on current SCS Project Base Path
    2. relative path on parent base dirs of current SCS Project Base Path in the case of mod/dlc
    3. find absolute file path
    4. return unchanged texture string path

    :param texture_string: texture string for which texture should be found e.g.: "/material/environment/vehicle_reflection"
    :type texture_string: str
    :return: relative path to texture object or absolute path to texture object or uncanged texture string
    :rtype: str
    """

    scs_project_path = _get_scs_globals().scs_project_path
    orig_texture_string = texture_string

    # remove any directory separators left overs from different platform
    texture_string = texture_string.replace("/", os.sep).replace("\\", os.sep)

    extensions, texture_string = get_texture_extens_and_strip_path(texture_string)

    # if texture string starts with scs project path we can directly strip of project path
    if startswith(texture_string, scs_project_path):
        texture_string = texture_string[len(scs_project_path):]
    else:  # check if texture string came from base project while scs project path is in dlc/mod folder

        # first find longest matching path
        i = 1
        while startswith(scs_project_path, texture_string[:i]) and i < len(texture_string):
            i += 1

        # now check if provided texture string is the same as:
        # current scs project path + one or two directories up + non matched path of the part
        for infix in ("..", ".." + os.sep + ".."):

            nonmatched_path_part = texture_string[i - 2:]

            modif_texture_string = os.path.join(scs_project_path, infix + nonmatched_path_part)
            # if one or two directories up is the same path as texture string
            # and non matched path part is starting with /base we got a hit:
            # resulting relative path is non matched path part with stripped "/base" start
            if is_samepath(modif_texture_string, texture_string) and startswith(nonmatched_path_part, os.sep + "base"):
                texture_string = nonmatched_path_part[5:]
                break

    # check for relative TOBJ, TGA, PNG
    for ext in extensions:
        texture_path = get_abs_path("//" + texture_string.strip(os.sep) + ext)
        if texture_path and os.path.isfile(texture_path):
            return "//" + texture_string.replace(os.sep, "/").strip("/") + ext

    # check for absolute TOBJ, TGA, PNG
    for ext in extensions:
        texture_path = get_abs_path(texture_string + ext, skip_mod_check=True)
        if texture_path and os.path.isfile(texture_path):
            return texture_string.replace(os.sep, "/") + ext

    return orig_texture_string

def get_tobj_path_from_shader_texture(shader_texture, check_existance=True):
    """Gets TOBJ path from shader texture value if exists, otherwise returning None.

    :param shader_texture: shader texture raw path value
    :type shader_texture: str
    :param check_existance: flag indicating if tobj path should be also checked for existance
    :type check_existance: bool
    :return: TOBJ absolute path or None if not found
    :rtype: str | None
    """

    # strip of any extensions ( endswith is most secure, because of possible multiple extensions )
    if shader_texture.endswith(".tobj"):
        tobj_filpath = shader_texture
    elif shader_texture.endswith(".tga") or shader_texture.endswith(".png"):
        tobj_filpath = shader_texture[:-4] + ".tobj"
    else:
        tobj_filpath = shader_texture + ".tobj"

    # NOTE: if there is no existence check then we also shouldn't check for mods file system structure
    tobj_filpath = get_abs_path(tobj_filpath, skip_mod_check=not check_existance)
    if not check_existance or (tobj_filpath and os.path.isfile(tobj_filpath)):
        return tobj_filpath

    return None

def get_skeleton_relative_filepath(armature, directory, default_name):
    """Get's skeleton relative path to given directory. This path can be used for linking
    skeletons in PIM and PIA files.

    :param armature: armature object which will be used as scs skeleton
    :type armature: bpy.types.Object
    :param directory: directory from which relative path of skeleton should be gotten
    :type directory: str
    :param default_name: if custom path is empty this name will be used as the name of pis file
    :type default_name: str
    :return: relative path to predicted PIS file of given armature
    :rtype: str
    """

    skeleton_custom_dir = armature.scs_props.scs_skeleton_custom_export_dirpath
    skeleton_custom_name = armature.scs_props.scs_skeleton_custom_name

    skeleton_path = ""
    if skeleton_custom_dir != "":
        if skeleton_custom_dir.startswith("//"):
            skeleton_path = os.path.relpath(os.path.join(_get_scs_globals().scs_project_path, skeleton_custom_dir[2:]), directory)
        else:
            lprint("E Custom skeleton export path is not relative to SCS Project Base Path.\n\t   " +
                   "Custom path will be ignored, which might lead to wrongly linked skeleton file inside PIM and PIA files.")

    skeleton_name = (skeleton_custom_name if skeleton_custom_name != "" else default_name) + ".pis"

    return os.path.join(skeleton_path, skeleton_name)

def get_animations_relative_filepath(scs_root, directory):
    """Get's skeleton relative path to given directory. This path can be used for linking
    skeletons in PIM and PIA files.

    :param scs_root: scs root object of this animation
    :type scs_root: bpy.types.Object
    :param directory: directory from which relative path of animaton should be gotten
    :type directory: str
    :return: relative path to predicted PIS file of given armature
    :rtype: str
    """

    anims_path = ""

    if scs_root.scs_props.scs_root_object_allow_anim_custom_path:
        animations_custom_dir = scs_root.scs_props.scs_root_object_anim_export_filepath

        if animations_custom_dir != "":

            if animations_custom_dir.startswith("//"):
                anims_path = os.path.relpath(os.path.join(_get_scs_globals().scs_project_path, animations_custom_dir[2:]), directory)
            else:
                return None

    return anims_path

def get_global_export_path():
    """Gets global export path.
    If default export path is empty and blend file is saved inside current scs project path  -> return blend file dir;
    Otherwise return scs project path combined with default export path.
    :return: global export path defined by directory of saved blend file and default export path from settings
    :rtype: str
    """

    scs_project_path = _get_scs_globals().scs_project_path
    is_blend_file_within_base = bpy.data.filepath != "" and startswith(bpy.data.filepath, scs_project_path)
    default_export_path = bpy.context.scene.scs_props.default_export_filepath

    # if not set try to use Blender filepath
    if default_export_path == "" and is_blend_file_within_base:
        return os.path.dirname(bpy.data.filepath)
    else:
        return os.path.join(scs_project_path, default_export_path.strip("//"))

def get_custom_scs_root_export_path(root_object):
    """Gets custom export file path for given SCS Root Object.
    If custom export path is empty and blend file is saved inside current scs project path -> return blend file dir;
    Otherwise return scs porject path combined with custom scs root export path.
    :param root_object: scs root object
    :type root_object: bpy.types.Object
    :return: custom export directory path of given SCS Root Object; None if custom export for SCS Root is disabled
    :rtype: str | None
    """
    scs_project_path = _get_scs_globals().scs_project_path
    is_blend_file_within_base = bpy.data.filepath != "" and startswith(bpy.data.filepath, scs_project_path)

    custom_filepath = None
    if root_object.scs_props.scs_root_object_allow_custom_path:
        scs_root_export_path = root_object.scs_props.scs_root_object_export_filepath
        # if not set try to use Blender filepath
        if scs_root_export_path == "" and is_blend_file_within_base:
            custom_filepath = os.path.dirname(bpy.data.filepath)
        else:
            custom_filepath = os.path.join(scs_project_path, scs_root_export_path.strip("//"))

    return custom_filepath

def get_all_infixed_file_paths(filepath, include_given_path=True):
    """Gets files from same directory using any infixed word without,
    however dot can not appear in infix.

    :param filepath: absolute filepath which shall be checked for any infixed files
    :type filepath: str
    :param include_given_path: if True given file path will be included in returning list otherwise no
    :type include_given_path: bool
    :return: list of all infixed files; optionally given filepath can be added to result list too
    :rtype: list[str]
    """

    infixed_filepaths = [filepath] if include_given_path else []

    orig_dir, orig_file = os.path.split(filepath)

    # if original directory doesn't exists skip searching for any infix files
    if not os.path.isdir(orig_dir):
        return infixed_filepaths

    last_ext_i = orig_file.rfind(".")

    orig_file_prefix = orig_file[:last_ext_i]
    orig_file_postfix = orig_file[last_ext_i:]

    for file in os.listdir(orig_dir):

        # if given file path is already prefixed make sure to ignore it
        if file == orig_file:
            continue

        if file.startswith(orig_file_prefix) and file.endswith(orig_file_postfix) and file.count(".") == 2:
            infixed_filepaths.append(os.path.join(orig_dir, file))

    return infixed_filepaths

def startswith(path1, path2):
    """Checks if first given path starts with second given path.
    It also takes into account windows drive letter which can be big or small.

    :param path1: first path
    :type path1: str
    :param path2: second path
    :type path2: str
    :return: True if path1 starts with path2; False otherwise
    :rtype: bool
    """

    norm_path1 = full_norm(path1)
    norm_path2 = full_norm(path2)

    return norm_path1.startswith(norm_path2)

def is_samepath(path1, path2):
    """Checks if paths are the same
    It also takes into account windows drive letter which can be big or small.

    :param path1: first path
    :type path1: str
    :param path2: second path
    :type path2: str
    :return: True if path1 starts with path2; False otherwise
    :rtype: bool
    """

    norm_path1 = full_norm(path1)
    norm_path2 = full_norm(path2)

    return norm_path1 == norm_path2

def full_norm(path1):
    """Normalize path.
    It also takes into account windows drive letter which can be big or small.

    :param path1: path
    :type path1: str
    :return: normalized path
    :rtype: str
    """

    norm_path1 = os.path.normpath(path1)
    norm_path1 = os.path.normcase(norm_path1)

    return norm_path1

def readable_norm(path):
    """Normalize path in nice human readable form.
    On windows it also converts backslashes to forward ones, to have cross platform output.

    :param path: path to normalize
    :type path: str
    :return: normalized path
    :rtype: str
    """
    norm_path = os.path.normpath(path)
    norm_path = norm_path.replace("\\", "/")

    return norm_path


n = int(input(""))
m = int(input(""))

def get_align(matriz, coluna):
    column = []
    for i in range(len(matriz)):
        column.append(matriz[i][coluna])
    column.sort(reverse=True)
    return len(str(column[0]))

matrizes = [[[int(i)**2 for i in input().split()] for i in range(m)] for i in range(n)]

cont = 4

for i in matrizes:
    print("Quadrado da matriz #%d:" % cont)
    for j in range(m):
        for k in range(m):
            print(" " * (get_align(i, k) - len(str(i[j][k]))), i[j][k], end = ' ', sep='')
        print('')
    print('')
    cont += 1

1º Semester/Programming Fundamentals/Lesson 12/ex1.py


"""URL patterns for Directory Services"""
from django.urls import path

# Must be full path import to allow including url patterns in project urls
from os2datascanner.projects.admin.import_services import views

urlpatterns = [
     path('ldap/add/<uuid:org_id>',
          views.LDAPAddView.as_view(),
          name='add-ldap'),
     path('ldap/edit/<uuid:pk>',
          views.LDAPUpdateView.as_view(),
          name='edit-ldap'),
     path('ldap/test/connection',
          views.verify_connection,
          name='test-ldap-connection'),
     path('ldap/test/authentication',
          views.verify_authentication,
          name='test-ldap-authentication'),
     path('ldap/import/<uuid:pk>',
          views.LDAPImportView.as_view(),
          name='import-ldap'),
     path('msgraph-organization/add/<uuid:org_id>',
          views.MSGraphAddView.as_view(),
          name='add-msgraph'),
     path('msgraph-organization/add/<uuid:org_id>/',
          views.MSGraphAddView.as_view(),
          name='add-msgraph'),
     path('msgraph-organization/edit/<uuid:pk>',
          views.MSGraphUpdateView.as_view(),
          name='edit-msgraph'),
     path('msgraph-organization/import/<uuid:pk>',
          views.MSGraphImportView.as_view(),
          name='import-msgraph'),
     path('os2mo-organization/add/<uuid:org_id>',
          views.OS2moAddView.as_view(),
          name='add-os2mo'),
     path('os2mo-organization/import/<uuid:pk>',
          views.OS2moImportView.as_view(),
          name='import-os2mo'),
]


"""
wordcloud.py: A reusable library for word cloud visualizations
"""

"""
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import pandas as pd

def make_wordcloud(results, vid_dict):
    cloud = WordCloud(background_color="white",width=1000,height=1000, max_words=10,relative_scaling=0.5,
                    normalize_plurals=False).generate_from_frequencies(results[vid_dict])

    plt.imshow(cloud)
"""
import matplotlib.pyplot as plt
from wordcloud import WordCloud

word_could_dict = {'Git':100, 'GitHub':100, 'push':50, 'pull':10, 'commit':80, 'add':30, 'diff':10,
                  'mv':5, 'log':8, 'branch':30, 'checkout':25}

print(word_could_dict['Git'])

wordcloud = WordCloud(width = 1000, height = 500).generate_from_frequencies(word_could_dict)

plt.figure(figsize=(15,8))
plt.imshow(wordcloud)
plt.show()


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="outlierpack-NG",
    version="0.1.0",
    author="Nikhil Gupta",
    author_email="ngupta_be17@thapar.edu",
    description="Removing outliers from a pandas dataframe",
	url='https://github.com/CachingNik/OutlierPack',
	long_description=long_description,
	long_description_content_type="text/markdown",
	packages=setuptools.find_packages(),
	entry_points = {
        'console_scripts': ['Outcli=outlib.outcli:main'],
    },
	keywords = ['CLI', 'OUTLIER', 'Data', 'outlier removal'],
	python_requires='>=2.7',
)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import m2m_changed
from django.core.mail import send_mail

import uuid
from time import sleep
import geocoder
import urllib3
urllib3.disable_warnings()

GENDER = (
    ('male', 'MALE'),
    ('female', 'FEMALE')
)

class Player(AbstractUser):
    avatar = models.CharField(max_length=100, default="default_avatar.png")
    birthday = models.DateField(null=True, blank=True)
    gender = models.CharField(max_length=20, choices=GENDER, default='male')
    address = models.CharField(max_length=255, blank=True, null=True)
    home_field = models.ForeignKey("Location", blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Player'
        verbose_name_plural = 'Players'

    def __str__(self):
        return self.email

FACILITY_TYPE = (
    ('indoor', 'Indoor'),
    ('outdoor', 'Outdoor')
)

FIELD_TYPE = (
    ('grass', 'Grass'),
    ('turf', 'Turf'),
    ('futsal', 'Futsal')
)

class Location(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=255)
    facility_type = models.CharField(max_length=20, choices=FACILITY_TYPE, default='outdoor')
    field_type = models.CharField(max_length=20, choices=FIELD_TYPE, default='grass')
    url = models.CharField(max_length=120, null=True, blank=True)
    lat = models.FloatField(default=0)
    lng = models.FloatField(default=0)

    created_by = models.ForeignKey(Player, related_name="field_creator")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    def save(self, **kwargs):
        address = self.address.encode('utf-8')
        trial = 3

        while trial > 0:
            sleep(0.05)
            try:
                g = geocoder.google(address)
                latlon = g.geojson['features'][0]['geometry']['coordinates']
                self.lat = latlon[1]
                self.lng = latlon[0]
                break
            except (RuntimeError, ValueError, TypeError, Exception):
                trial = trial - 1

        super(Location, self).save()

class GameEvent(models.Model):
    location = models.ForeignKey(Location, related_name="events")
    datetime = models.DateTimeField()
    description = models.CharField(max_length=255, blank=True, null=True)
    players = models.ManyToManyField(Player)
    created_by = models.ForeignKey(Player, related_name="game_creator")

    def __str__(self):
        return self.location.name

class GameInvitation(models.Model):
    game = models.ForeignKey(GameEvent)
    player = models.ForeignKey(Player)
    code = models.CharField(max_length=50)
    is_accepted = models.BooleanField(default=False)

def notify_players(sender, instance, action, reverse, model, pk_set, **kwargs):
    if action == 'post_add':
        send_mail(
            'Game Event Notification',
            'You are invited to the game ({}) at {} {}'.format(instance.description, instance.location, instance.datetime),
            'info@goodfoot.club',
            [ii.email for ii in Player.objects.filter(id__in=pk_set)],
            fail_silently=False,
        )

# m2m_changed.connect(notify_players, sender=GameEvent.players.through)


import json

from test_tools.example_stubber import ExampleStubber

class OrganizationsStubber(ExampleStubber):
    """
    A class that implements a variety of stub functions that are used by the
    AWS Organizations unit tests.

    The stubbed functions all expect certain parameters to be passed to them as
    part of the tests, and will raise errors when the actual parameters differ from
    the expected.
    """

    def __init__(self, client, use_stubs=True):
        """
        Initializes the object with a specific client and configures it for
        stubbing or AWS passthrough.

        :param client: A Boto3 Organizations client.
        :param use_stubs: When True, use stubs to intercept requests. Otherwise,
                          pass requests through to AWS.
        """
        super().__init__(client, use_stubs)

    @staticmethod
    def _make_policy_summary(policy):
        return {
            "Id": policy["id"],
            "Arn": f'arn:aws:organizations::111111111111:policy/{policy["name"]}',
            "Name": policy["name"],
            "Description": policy["description"],
            "Type": policy["type"],
            "AwsManaged": False,
        }

    def stub_create_policy(self, policy, error_code=None):
        expected_parameters = {
            "Name": policy["name"],
            "Description": policy["description"],
            "Content": json.dumps(policy["content"]),
            "Type": policy["type"],
        }
        response = {
            "Policy": {
                "PolicySummary": self._make_policy_summary(policy),
                "Content": json.dumps(policy["content"]),
            }
        }
        self._stub_bifurcator(
            "create_policy", expected_parameters, response, error_code=error_code
        )

    def stub_list_policies(self, policy_filter, policies, error_code=None):
        expected_parameters = {"Filter": policy_filter}
        response = {"Policies": [self._make_policy_summary(pol) for pol in policies]}
        self._stub_bifurcator(
            "list_policies", expected_parameters, response, error_code=error_code
        )

    def stub_describe_policy(self, policy, error_code=None):
        expected_parameters = {"PolicyId": policy["id"]}
        response = {
            "Policy": {
                "PolicySummary": self._make_policy_summary(policy),
                "Content": json.dumps(policy["content"]),
            }
        }
        self._stub_bifurcator(
            "describe_policy", expected_parameters, response, error_code=error_code
        )

    def stub_attach_policy(self, policy_id, target_id, error_code=None):
        expected_parameters = {"PolicyId": policy_id, "TargetId": target_id}
        self._stub_bifurcator(
            "attach_policy", expected_parameters, error_code=error_code
        )

    def stub_detach_policy(self, policy_id, target_id, error_code=None):
        expected_parameters = {"PolicyId": policy_id, "TargetId": target_id}
        self._stub_bifurcator(
            "detach_policy", expected_parameters, error_code=error_code
        )

    def stub_delete_policy(self, policy_id, error_code=None):
        expected_parameters = {"PolicyId": policy_id}
        self._stub_bifurcator(
            "delete_policy", expected_parameters, error_code=error_code
        )


import json

import pytest
from api.processing import units
from unyt import unyt_quantity

def test_unyt_encoder():
    test_unyt_dict = {
        "test_quantity": unyt_quantity(5, "Mpc"),
    }

    expected = '{"test_quantity": "5 Mpc"}'
    assert expected == json.dumps(test_unyt_dict, cls=units.UnytEncoder)

def test_convert_swift_units_dict_types_success():
    test_units_dict = {
        "filename": "/a/test/file/path",
        "units": {
            "Unit current in cgs (U_I)": unyt_quantity(1.0, "statA"),
            "Unit length in cgs (U_L)": unyt_quantity(1e24, "cm"),
            "Unit mass in cgs (U_M)": unyt_quantity(1.9e43, "g"),
            "Unit temperature in cgs (U_T)": unyt_quantity(1.0, "K"),
            "Unit time in cgs (U_t)": unyt_quantity(1.09e19, "s"),
        },
        "mass": unyt_quantity(1.0e10, "Msun"),
        "length": unyt_quantity(1.0, "Mpc"),
        "time": unyt_quantity(1000.0, "Gyr"),
        "current": unyt_quantity(1.0, "statA"),
        "temperature": unyt_quantity(1.0, "K"),
    }

    retrieved_dict = units.convert_swift_units_dict_types(test_units_dict)

    for key, value in retrieved_dict.items():
        if isinstance(value, dict):
            for _subkey, subvalue in retrieved_dict[key].items():
                assert isinstance(subvalue, str)
        else:
            assert isinstance(value, str)

def test_convert_swift_units_dict_types_failure():
    test_units_dict = {
        "filename": "/a/test/file/path",
        "mass": unyt_quantity(1.0e10, "Msun"),
        "length": unyt_quantity(1.0, "Mpc"),
        "time": unyt_quantity(1000.0, "Gyr"),
        "current": unyt_quantity(1.0, "statA"),
        "temperature": unyt_quantity(1.0, "K"),
    }

    with pytest.raises(units.SWIFTUnytException):
        units.convert_swift_units_dict_types(test_units_dict)

def test_create_unyt_quantities_success():
    test_dict = {
        "filename": "/a/test/file/path",
        "units": {
            "Unit current in cgs (U_I)": "1.0 statA",
            "Unit length in cgs (U_L)": "1e+24 cm",
            "Unit mass in cgs (U_M)": "1.9e+43 g",
            "Unit temperature in cgs (U_T)": "1.0 K",
            "Unit time in cgs (U_t)": "1.09e+19 s",
        },
        "mass": "10000000000.0 Msun",
        "length": "1.0 Mpc",
        "time": "1000.0 Gyr",
        "current": "1.0 statA",
        "temperature": "1.0 K",
    }

    unyt_quantity_dict = units.create_unyt_quantities(test_dict)

    for key, value in unyt_quantity_dict.items():
        if isinstance(value, dict):
            for _subkey, subvalue in unyt_quantity_dict[key].items():
                assert isinstance(subvalue, unyt_quantity)
        elif key != "filename":
            assert isinstance(value, unyt_quantity)

def test_create_unyt_quantities_failure():
    test_dict = {
        "filename": "/a/test/file/path",
        "mass": "10000000000.0 Msun",
        "length": "1.0 Mpc",
        "time": "1000.0 Gyr",
        "current": "1.0 statA",
        "temperature": "1.0 K",
    }

    with pytest.raises(units.SWIFTUnytException):
        units.create_unyt_quantities(test_dict)


import pygame
from pygame.surface import Surface

import sys

from Screens.Content import Content, State
from Options.Options import KEY_REPEAT_DELAY, KEY_REPEAT_INTERVAL, TITLE_H_START, TITLE_W_START, TITLE_H_SIZE, BUTTON_H, BUTTON_W, FONT, BRICK_SIZE, ICON_H, ICON_W
from Options.Colors import Colors, Color_mod

class Settings(Content):
    def __init__(self) -> None:
        self.options_1: list[str] = [
                'Next tetr',
                'Tetr. shadow',
                'Fps',
                'Fall Speed',
                'LockDelay'
                ]
        self.options_2: list[str] = [
                'Key Rep. Interval',
                'Key Rep. Delay',
                'Soft Drop',
                'Return'
                ]
        self.border: int = (TITLE_H_SIZE - (len(self.options_1) * BUTTON_H)) // (2 * len(self.options_1))

    def update(self, display: Surface) -> State:
        # Remover e colocar em opcoes no Title()
        for e in pygame.event.get():
            if e.type == pygame.MOUSEBUTTONDOWN:
                return State.Title
        pygame.key.set_repeat(KEY_REPEAT_DELAY, KEY_REPEAT_INTERVAL)
        return State.Stay

    def draw(self, display: Surface) -> None:
        self.draw_buttons(display)

    def draw_buttons(self, display) -> None:
        for i in range(len(self.options_1)):
            pygame.draw.rect(display,
                             Colors.PURPLE.value,
                             (TITLE_W_START - (3 * BUTTON_W // 4),
                              TITLE_H_START // 2 + (i * (BUTTON_H + self.border)),
                              BUTTON_W,
                              BUTTON_H // 2))
            pygame.draw.rect(display,
                             Color_mod().get_shadow_from_color(Colors.PURPLE),
                             (TITLE_W_START - (3 * BUTTON_W // 4),
                              TITLE_H_START // 2 + (i * (BUTTON_H + self.border)) + (BUTTON_H // 2),
                              BUTTON_W,
                              BUTTON_H // 2))
            pygame.draw.rect(display,
                             Color_mod().get_light_from_color(Colors.PURPLE),
                             (TITLE_W_START - (3 * BUTTON_W // 4),
                              TITLE_H_START // 2 + (i * (BUTTON_H + self.border)),
                              BUTTON_W,
                              BUTTON_H),
                             width=4)
            button_text: Surface = FONT.render(self.options_1[i], True, Colors.WHITE.value)
            display.blit(button_text, (TITLE_W_START - (3 * BUTTON_W // 4) + (BUTTON_H // 2), TITLE_H_START // 2 + (i * (BUTTON_H + self.border))))
        for i in range(len(self.options_2)):
            pygame.draw.rect(display,
                             Colors.PURPLE.value,
                             (TITLE_W_START + (3 * BUTTON_W // 4),
                              TITLE_H_START // 2 + (i * (BUTTON_H + self.border)),
                              BUTTON_W,
                              BUTTON_H // 2))
            pygame.draw.rect(display,
                             Color_mod().get_shadow_from_color(Colors.PURPLE),
                             (TITLE_W_START + (3 * BUTTON_W // 4),
                              TITLE_H_START // 2 + (i * (BUTTON_H + self.border)) + (BUTTON_H // 2),
                              BUTTON_W,
                              BUTTON_H // 2))
            pygame.draw.rect(display,
                             Color_mod().get_light_from_color(Colors.PURPLE),
                             (TITLE_W_START + (3 * BUTTON_W // 4),
                              TITLE_H_START // 2 + (i * (BUTTON_H + self.border)),
                              BUTTON_W,
                              BUTTON_H),
                             width=4)
            button_text: Surface = FONT.render(self.options_2[i], True, Colors.WHITE.value)
            display.blit(button_text, (TITLE_W_START + (3 * BUTTON_W // 4) + (BUTTON_H // 2), TITLE_H_START // 2 + (i * (BUTTON_H + self.border))))


#!/usr/bin/python3

import os
import argparse

BASE_CMD = 'gtimeout 60 stack exec -- hplus \"{query}\" --stop-refine\
            --stop-threshold=10 --cnt=5'

def main():
    parser = argparse.ArgumentParser(description='Run a single hoogle+ query')
    parser.add_argument('query', help='the signature to be searched')
    args = parser.parse_args()
    os.system(BASE_CMD.format(query=args.query))

if __name__ == "__main__":
    main()


atual = 1
anterior = 0
soma = 0
soma_par = 0
soma_impar = 0
soma_quad = 0
indice = 0
print(" %i" %anterior)
while(soma <= 4000):
    c = atual
    print(" %i" %atual)
    atual = atual + anterior
    anterior = c
    soma += atual
    indice += 1
    if(indice % 2 == 0):
        soma_par += atual
    else:
        soma_impar += atual
    soma_quad = (atual**2)
print("Soma = %i; \nSoma indices pares = %i; \nSoma indices impares = %i; \nSoma dos quadrados dos termos = %i." %(soma, soma_par, soma_impar, soma_quad))


import os, math, re, gc
import decimal
import numpy as np
import scipy as sp
import calendar

from attrdict import AttrDict

from eccodes import *

GRID_SIZE = 0.75
RADIUS = 3
GRIB_FOLDER = '/media/isa/VIS1/'

def drange(x, y, jump):
  x_ = decimal.Decimal(x)
  while x_ < y:
    yield float(x_)
    x_ += decimal.Decimal(jump)

# loc='zurich', latitude=47.25, longitude=8.25
# loc='paris', latitude=48.75, longitude=2.25

def save_location(grib_parameter, loc='los_angeles', latitude=33.75, longitude=241.5):
    """
        Loads data from the grib file and saves it for further faster use
    """
    years = list(range(1979, 2017))
    months = list(range(1, 13))
    diameter = 1 + 2 * RADIUS

    scaled_radius = RADIUS * GRID_SIZE

    start_lat = latitude - scaled_radius
    end_lat = latitude + scaled_radius
    start_lon = longitude - scaled_radius
    end_lon = longitude + scaled_radius

    param_folder = GRIB_FOLDER + grib_parameter + '/' + loc
    if not os.path.exists(param_folder):
        os.makedirs(param_folder)

    for year in years:

        year_folder = param_folder + '/' + str(year)
        if not os.path.exists(year_folder):
            os.makedirs(year_folder)

        f = open(GRIB_FOLDER + grib_parameter + '/' + str(year) + '.grib')
        month_it = 0
        month = 1
        day = 1
        hour = 0

        current_month = []
        current_day = np.zeros((4, diameter, diameter))

        while True:
            gc.collect()
            gid = codes_grib_new_from_file(f)
            if gid is None:
                break

            dataDate = codes_get(gid, 'dataDate')

            dataDate_ = str(dataDate).zfill(8)
            month_ = int(dataDate_[4:6])
            day_ = int(dataDate_[6:8])

            if (month_ > month):
                current_month.append(current_day)
                month_array = np.asarray(current_month)
                print('added month ' + str(month))
                print('month shape:')
                print(month_array.shape)
                np.save(year_folder + '/' + str(month) + '.npy', month_array)
                month = month + 1
                day = 1
                hour = 0
                current_day = np.zeros((4, diameter, diameter))
                current_month = []

            elif (day_ > day):
                current_month.append(current_day)
                hour = 0
                day = day + 1
                current_day = np.zeros((4, diameter, diameter))

            bottomLeft = codes_grib_find_nearest(gid, start_lat, start_lon)[0]
            topRight = codes_grib_find_nearest(gid, end_lat, end_lon)[0]

            latIt = 0
            for lat in reversed(list(drange(bottomLeft.lat, topRight.lat + GRID_SIZE, GRID_SIZE))):
                lonIt = 0
                for lon in drange(bottomLeft.lon, topRight.lon + GRID_SIZE, GRID_SIZE):
                    nearest = codes_grib_find_nearest(gid, lat, lon)[0]
                    current_day[hour, latIt, lonIt] = nearest.value
                    lonIt = lonIt + 1
                latIt = latIt + 1

            codes_release(gid)
            hour = hour + 1

        # save the last month
        current_month.append(current_day)
        month_array = np.asarray(current_month)
        print('added month ' + str(month))
        print('month shape:')
        print(month_array.shape)
        np.save(year_folder + '/' + str(month) + '.npy', month_array)

        f.close()

def save_location_uv(grib_parameter='u_ambient', binary_file='uv_ambient', binary_file_2='.bin_ambient20.bin', uv_param='u', loc='los_angeles', latitude=33.75, longitude=241.5):
    """
        Loads data from the binary files and saves it for further faster use
    """
    years = list(range(1979, 2017))
    months = list(range(1, 13))
    diameter = 1 + 2 * RADIUS

    scaled_radius = RADIUS * GRID_SIZE

    start_lat = int((latitude - scaled_radius) / GRID_SIZE)
    end_lat = int((latitude + scaled_radius) / GRID_SIZE)
    start_lon = int((longitude - scaled_radius) / GRID_SIZE)
    end_lon = int((longitude + scaled_radius) / GRID_SIZE)

    print(start_lat)
    print(end_lat)
    print(start_lon)
    print(end_lon)

    if (uv_param == 'u'):
        uv_param_index = 1
    else:
        uv_param_index = 0

    param_folder = GRIB_FOLDER + grib_parameter + '/' + loc
    if not os.path.exists(param_folder):
        os.makedirs(param_folder)

    for year in years:
        gc.collect()
        if (calendar.isleap(year)):
            month_array = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        else:
            month_array = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        year_folder = param_folder + '/' + str(year)
        if not os.path.exists(year_folder):
            os.makedirs(year_folder)

        array = np.fromfile(GRIB_FOLDER + binary_file + '/' + str(year) + binary_file_2, dtype=np.float32)
        print(array.shape)

        array = np.reshape(array, (-1, 480, 2, 241))
        array = array[:, start_lon:end_lon+1, uv_param_index, start_lat:end_lat+1]
        print(array.shape)

        month = 0
        array_it = 0

        for month_a in month_array:
            month = month + 1
            gc.collect()
            current_month = np.zeros((month_a, 4, diameter, diameter))

            for day_it in range(month_a):
                current_month[day_it, :, :, :] = array[array_it:array_it + 4, :, :]
                array_it = array_it + 4

            print(current_month.shape)
            # swap to be in order day, time, lat, lon
            current_month = np.transpose(current_month, (0, 1, 3, 2))
            np.save(year_folder + '/' + str(month) + '.npy', current_month)

def main():
    #save_location('temperature')
    #save_location('wind_u')
    #save_location('wind_v')
    #save_location('surface_pressure')
    #save_location('pressure')
    #save_location('cloud_cover')
    save_location('total_precipitation', loc='zurich', latitude=47.25, longitude=8.25)
    save_location('total_precipitation', loc='paris', latitude=48.75, longitude=2.25)
    save_location('total_precipitation', loc='los_angeles', latitude=33.75, longitude=241.5)
    #save_location_uv('u_ambient', 'uv_ambient', '.bin_ambient20.bin', 'u')
    #save_location_uv('v_ambient', 'uv_ambient', '.bin_ambient20.bin', 'v')
    #save_location_uv('u_features', 'uv_features', '.bin_features20.bin', 'u')
    #save_location_uv('v_features', 'uv_features', '.bin_features20.bin', 'v')

    return 1

if __name__ == "__main__":
    sys.exit(main())


from Project.src.NeuralNetworks.neural_networks import NN
import numpy as np

classFeatures = [("mon_intensity", np.float),
                 ("mon_duration", np.float),
                 ("mon_hr", np.float),
                 ("tue_intensity", np.float),
                 ("tue_duration", np.float),
                 ("tue_hr", np.float),
                 ("wed_intensity", np.float),
                 ("wed_duration", np.float),
                 ("wed_hr", np.float),
                 ("thu_intensity", np.float),
                 ("thu_duration", np.float),
                 ("thu_hr", np.float),
                 ("fri_intensity", np.float),
                 ("fri_duration", np.float),
                 ("fri_hr", np.float),
                 ("sat_intensity", np.float),
                 ("sat_duration", np.float),
                 ("sat_hr", np.float),
                 ("sun_intensity", np.float),
                 ("sun_duration", np.float),
                 ("sun_hr", np.float),
                 ("weekIntensity", np.float),
                 ("weekDuration", np.float),
                 ("weekHearthrate", np.float),
                 ("weekOveral", np.float)
                 ]
classes = {
    "bad": 0,
    "good": 1
}
classificationResult = "bestAtlethes"

trainPath = "../../../Data/week_riders_random_train.csv"
testPath = "../../../Data/week_riders_random_test.csv"

nn = NN(classFeatures, classificationResult, classes, trainPath, testPath, ";")

solvers = ['lbfgs', 'sgd', 'adam']
activations = ['identity', 'logistic', 'tanh', 'relu']

itters = 100
result = {}

for iter in range(0, itters):

    for solver in solvers:
        for activation in activations:
            result.setdefault(solver + '-' + activation, {'score': 0, 'f1_score': 0})
            res_nn = nn.run(solver, activation)
            result[solver + '-' + activation]['score'] += res_nn['score']
            result[solver + '-' + activation]['f1_score'] += res_nn['f1_score']

    print("Hello " + str(iter) + "%")

result2 = {}
for key, value in result.items():
    val = value
    val['score'] = value['score'] / itters
    val['f1_score'] = value['f1_score'] / itters
    result2[key] = val

print(result)