import numpy as np
import tensorflow as tf

def get_losses_old_and_probably_wrong(net_out, cells_coords, within_cells_coords, lambda_coord, lambda_noobj):
    # put net_out to the format of coords:
    n_detectors = net_out.get_shape().as_list()[-1] // 4
    detectors = tf.gather_nd(net_out[0], cells_coords)       # shape = [None, 4 * n_detectors]
    detectors = tf.reshape(detectors, (-1, n_detectors, 4))  # shape = [None, n_detectors, 4]
    predicted_coords = detectors[..., :-1]                   # shape = [None, n_detectors, 3]
    confidence = detectors[..., -1]                          # shape = [None, n_detectors]
    true_coords = within_cells_coords[:, tf.newaxis]         # shape = [None, 1, 3]
    distances = tf.reduce_sum((true_coords - predicted_coords) ** 2, axis=-1)  # [None, n_detectors]
    min_distance = tf.reduce_min(distances, axis=-1)         # [None]
    arg_chosen_detectors = tf.argmin(distances, axis=-1)     # [None]
    index = tf.cast(tf.range(tf.shape(arg_chosen_detectors)[0]), dtype=tf.int64)
    coord_chosen_detectors = tf.stack([index, arg_chosen_detectors], axis=-1)
    trick_coef = tf.stop_gradient(1 + lambda_noobj * confidence / (confidence - 1))   # error when confidence == 1  --> solution = argsort instead of argmin + gather_nd on non minimal indices
    min_distance_loss = min_distance * lambda_coord
    confidence_loss = (tf.gather_nd(confidence, coord_chosen_detectors) - 1) ** 2 * trick_coef
    noobj_loss = net_out[..., 3::4] ** 2 * lambda_noobj
    min_distance_loss_sum = tf.reduce_sum(min_distance_loss)
    confidence_loss_sum = tf.reduce_sum(confidence_loss)
    noobj_loss_sum = tf.reduce_sum(noobj_loss)
    return min_distance_sum, confidence_loss_sum, noobj_loss_sum

def get_losses_old_2(net_out, cells_coords, within_cells_coords, lambda_coord, lambda_noobj):
    # put net_out to the format of coords:
    n_detectors = net_out.get_shape().as_list()[-1] // 4
    detectors = tf.gather_nd(net_out[0], cells_coords)       # shape = [None, 4 * n_detectors]
    detectors = tf.reshape(detectors, (-1, n_detectors, 4))  # shape = [None, n_detectors, 4]
    predicted_coords = detectors[..., :-1]                   # shape = [None, n_detectors, 3]
    confidence = detectors[..., -1]                          # shape = [None, n_detectors]
    true_coords = within_cells_coords[:, tf.newaxis]         # shape = [None, 1, 3]
    distances = tf.reduce_sum((true_coords - predicted_coords) ** 2, axis=-1)  # [None, n_detectors]
    ## distance loss
    min_distance = tf.reduce_min(distances, axis=-1)         # [None]
    min_distance_loss = lambda_coord * min_distance
    ## confidence losses
    # obj loss
    arg_chosen_detectors = tf.argmin(distances, axis=-1)     # [None]
    indices = tf.cast(tf.range(tf.shape(arg_chosen_detectors)[0]), dtype=tf.int64)
    coord_chosen_detectors = tf.stack([indices, arg_chosen_detectors], axis=-1)
    confidence_loss = (tf.gather_nd(confidence, coord_chosen_detectors) - 1) ** 2
    # noobj loss
    length = tf.shape(indices)[0]
    indices = tf.concat([tf.zeros(length, dtype=tf.int64)[:, tf.newaxis], cells_coords, arg_chosen_detectors[:, tf.newaxis]], axis=-1)   # WARNING: how about the batch dim...?
    updates = tf.ones(length)
    shape = tf.cast(tf.shape(net_out[..., 3::4]), tf.int64)
    mask = 1 - tf.scatter_nd(indices, updates, shape)
    noobj_loss = lambda_noobj * mask * net_out[..., 3::4] ** 2
    # sums
    min_distance_loss_sum = tf.reduce_sum(min_distance_loss)
    confidence_loss_sum = tf.reduce_sum(confidence_loss)
    noobj_loss_sum = tf.reduce_sum(noobj_loss)
    return min_distance_loss_sum, confidence_loss_sum, noobj_loss_sum

def get_losses(net_out, cells_coords, within_cells_coords, lambda_coord, lambda_noobj):
    # put net_out to the format of coords:
    NO_BATCH = 0
    n_detectors = net_out.get_shape().as_list()[-1] // 4
    n_spines = tf.shape(cells_coords)[1]
    print("cells_coords", cells_coords.get_shape())             # shape = [None, n_spines, 3]
    print("net_out", net_out.get_shape())                       # shape = [None, x, y, z, 4 * n_detectors]
    detectors = tf.gather_nd(net_out[NO_BATCH], cells_coords[NO_BATCH])       # shape = [None, 4 * n_detectors]
    detectors = tf.reshape(detectors, (-1, n_detectors, 4))     # shape = [n_spines, n_detectors, 4]
    print("detectors", detectors.get_shape())                   # shape = [n_spines, n_detectors, 4]
    predicted_coords = detectors[..., :-1]                      # shape = [n_spines, n_detectors, 3]
    confidence = detectors[..., -1]                             # shape = [n_spines, n_detectors]
    print("within_cells_coords", within_cells_coords.get_shape())                      # shape = [None, n_spines, 3]
    true_coords = tf.transpose(within_cells_coords[NO_BATCH, tf.newaxis], perm=[1, 0, 2])            # shape = [None, 1, 3, n_spines]
    print("true_coords", true_coords.get_shape())                      # shape = [None, 3, None]
    distances = tf.reduce_sum((true_coords - predicted_coords) ** 2, axis=-1)  # [None, n_detectors]
    ## distance loss
    min_distance = tf.reduce_min(distances, axis=-1)            # [None]
    min_distance_loss = lambda_coord * min_distance
    ## confidence losses
    length = tf.shape(cells_coords)[1:2]
    arg_chosen_detectors = tf.argmin(distances, axis=-1)        # [None]
    indices = tf.concat([
        cells_coords[NO_BATCH],
        arg_chosen_detectors[:, tf.newaxis]], axis=-1)
    updates = tf.ones(length)
    shape = tf.cast(tf.shape(net_out[NO_BATCH, ..., 3::4]), tf.int64)
    target_confidence = tf.scatter_nd(indices, updates, shape)
    confidence_loss = (net_out[NO_BATCH, ..., 3::4] - target_confidence) ** 2 * (target_confidence * (1 - lambda_noobj) + lambda_noobj)
    # sums
    min_distance_loss_sum = tf.reduce_sum(min_distance_loss)
    confidence_loss_sum = tf.reduce_sum(confidence_loss)
    min_distance_loss_mean = tf.reduce_mean(min_distance)
    abs_distance = tf.abs(net_out[NO_BATCH, ..., 3::4] - target_confidence)
    confidence_mean_abs_distance = tf.reduce_mean(abs_distance)
    mean_distance_to_1_confidence = tf.reduce_sum(tf.where(tf.equal(target_confidence, 1), x=abs_distance, y=tf.zeros_like(abs_distance))) / tf.reduce_sum(target_confidence)
    ret = {
        "min_distance_loss_sum": min_distance_loss_sum,
        "min_distance_loss_mean": min_distance_loss_mean,
        "confidence_loss_sum": confidence_loss_sum,
        "confidence_mean_abs_distance": confidence_mean_abs_distance,
        "mean_distance_to_1_confidence": mean_distance_to_1_confidence
    }
    return ret

if __name__ == "__main__":
    from network import SimpleLinearModel
    from dataset import naked_dataset
    import argparse
    import pickle
    import os

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "path",
        help="path to the tfrecord file"
    )

    args = parser.parse_args()

    dirpath, name = os.path.split(args.path)
    name = name.replace(".tfrecord", "")
    with open(dirpath + '/' + name + ".args", "rb") as f:
        generation_args = pickle.load(f)

    dataset = naked_dataset(args.path)
    dataset_iterator = dataset.make_initializable_iterator()
    datapoint = dataset_iterator.get_next()

    n_detectors_per_cell = 3
    net = SimpleLinearModel(generation_args, n_detectors_per_cell)
    inp = tf.cast(datapoint["stack"], tf.float32) / 127.5 - 1
    net_out = net(inp)
    cells_coords = tf.stack([
        datapoint["cells_coords_x"],
        datapoint["cells_coords_y"],
        datapoint["cells_coords_z"]], axis=1)
    within_cells_coords = tf.stack([
        datapoint["within_cells_coords_x"],
        datapoint["within_cells_coords_y"],
        datapoint["within_cells_coords_z"]], axis=1)
    lambda_coord = 5
    lambda_noobj = 0.5
    loss = get_losses(net_out, cells_coords, within_cells_coords, lambda_coord, lambda_noobj)

    with tf.Session() as sess:
        sess.run([dataset_iterator.initializer, tf.global_variables_initializer()])
        np_loss = sess.run(loss)

    print(np_loss)


import boto3
import pprint

def main():
    terminate_ec2_instances()

#This function terminates all the running ec2 instances
def terminate_ec2_instances():
    ec2_client = boto3.client("ec2", region_name="us-east-2")
    reservations = ec2_client.describe_instances(Filters=[
        {
            "Name": "instance-state-name",
            "Values": ["running"],
        }
    ]).get("Reservations")

    pp = pprint.PrettyPrinter(indent=4)

    #pp.pprint(reservations)

    for reservation in reservations:
        for instance in reservation["Instances"]:
                instance_id = instance["InstanceId"]
                ec2_client.terminate_instances(InstanceIds=[instance_id])
                instance_type = instance["InstanceType"]
                public_ip = instance["PublicIpAddress"]
                private_ip = instance["PrivateIpAddress"]
            # print(f"{instance_id}, {instance_type}, {public_ip}, {private_ip}")

if __name__ == "__main__":
    main()


from typing import Tuple

import torch
import torch.nn as nn
from torch import Tensor

class Encoder(nn.Module):
    def __init__(self, input_dim: int, emb_dim: int, enc_hid_dim: int, dec_hid_dim: int, dropout: float):
        super().__init__()

        self.input_dim = input_dim
        self.emb_dim = emb_dim
        self.enc_hid_dim = enc_hid_dim
        self.dec_hid_dim = dec_hid_dim
        self.dropout = dropout

        self.embedding = nn.Embedding(input_dim, emb_dim)
        self.rnn = nn.GRU(emb_dim, enc_hid_dim, bidirectional=True)
        self.fc = nn.Linear(enc_hid_dim*2, dec_hid_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, src: Tensor) -> Tuple[Tensor]:
        embedded = self.dropout(self.embedding(src))
        outputs, hidden = self.rnn(embedded)
        hidden = torch.tanh(self.fc(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)))
        return outputs, hidden


import pandas as pd

terrenos_edital = pd.read_csv('df_terracap_df_1.csv')
#terrenos_edital = pd.read_csv('datasets/terracap_vendidos_entre_2019_2021_abr.csv')
terrenos_vendidos = pd.read_csv('datasets/terrenos_vendidos_terracap.csv')

terrenos_edital['end_comp'] = terrenos_edital['end'].str.replace(" ", "")
terrenos_vendidos['endereco_comp'] = terrenos_vendidos['endereco'].str.replace(" ", "")

lista_def = terrenos_edital.drop_duplicates(subset=['id_terracap'])

lista_def = lista_def.rename(columns={'id_terracap': 'ID TERRACAP', 'classficacao': 'Classificação', 'relevo': 'Relevo',
                                      'situacao': 'Situação', 'tipo_de_solo': 'Tipo de Solo', 'forma': 'Forma',
                                      'posicao': 'Posição', 'frente': 'Frente', 'fundo': 'Fundo',
                                      'lado_esquerdo': 'Lado Esquerdo', 'bairro': 'Bairro', 'lado_direito': 'Lado Direito',
                                      'edital_x': 'Edital da Venda', 'valor_caucao_x': 'Valor Caução',
                                      'url_details': 'Link Terracap', 'n_imoveis': 'N. de Imóveis', 'area_y': 'Área',
                                      'coord_name': 'ID das Coordenadas', 'coords': 'Coordenadas'
                                      })

lista_def.to_csv('def_terracap_ongoing.csv')

lista_def['Área de Construção Básica'] = None
lista_def['Área de Construção Máxima'] = None
lista_def['Área do Terreno'] = None
lista_def['Participação em Outros Editais'] = None

for i in range(len(lista_def)):
    try:
        lista_def['Área de Construção Básica'].iloc[i] = int(lista_def['area_const_basica'].iloc[i].replace(" m²", ""))
    except:
        pass
    try:
        lista_def['Área de Construção Máxima'].iloc[i] = int(lista_def['area_const_max'].iloc[i].replace(" m²", ""))
    except:
        pass
    try:
        lista_def['Área do Terreno'].iloc[i] = int(lista_def['area_x'].iloc[i].replace(" m²", ""))
    except:
        pass
    part_outros_editais_string = str(lista_def['outros_editais_1'].iloc[i]) + ' ' + str(lista_def['outros_editais_2'].iloc[i]) + \
                                 ' ' + str(lista_def['outros_editais_3'].iloc[i]) + ' ' + str(lista_def['outros_editais_4'].iloc[i]) + \
                                 ' ' + str(lista_def['outros_editais_5'].iloc[i]) + ' ' + str(lista_def['outros_editais_6'].iloc[i]) + \
                                 ' ' + str(lista_def['outros_editais_7'].iloc[i]) + ' ' + str(lista_def['outros_editais_8'].iloc[i]) + \
                                 ' ' + str(lista_def['outros_editais_9'].iloc[i])
    lista_def['Participação em Outros Editais'].iloc[i] = part_outros_editais_string.replace('nan', '')

lista_def.to_csv('def_terracap_ongoing_2.csv')

lista_def = lista_def.rename(columns={'valor_face': 'Valor de Face', 'edital': 'Edital',
                                      'n_imovel_no_edital': 'Nº do Imóvel no Edital',
                                      'area_const_max': 'Area Construção Máxima',
                                      'valor_caucao': 'Valor Caução', 'end': 'Endereço'
                                      }, inplace=False)

lista_def = lista_def.drop(columns=['edital_y', 'endereco', 'index', 'valor_caucao_y', 'area_const_basica',  'Area Construção Máxima'])

lista_def['Número Lances'] = None
lista_def['Valor Lance Vencedor'] = None
lista_def['Valor Lance Segundo Colocado'] = None
lista_def['Valor Lance Terceiro Colocado'] = None
lista_def['R$ Valor / Pot. Max'] = None
lista_def['Entrada'] = None
lista_def['Número Meses'] = None

lista_def = lista_def[lista_def['Área de Construção Máxima'] >= 10]
lista_def['R$ Valor / Pot. Max'] = None
lista_def = lista_def.reset_index()
temp = []

lista_def.to_csv('def_terracap_ongoing_3.csv')

for i in lista_def['end_comp']:
    for j in terrenos_vendidos['endereco_comp']:
        if i == j:
            temp.append(j)
        else:
            pass

for i in range(len(lista_def)):
    end = lista_def['end_comp'][i]
    terrenos_selecionados = terrenos_vendidos[terrenos_vendidos['endereco_comp'].str.contains(end)]
    try:
        lista_def['Número Lances'][i] = len(terrenos_selecionados)
    except:
        lista_def['Número Lances'][i] = 0

    terrenos_selecionados = terrenos_selecionados.reset_index()
    if len(terrenos_selecionados) >= 1:
        if terrenos_selecionados['colocacao'][0] == 'Desclassificado':
            lista_def['Valor Lance Vencedor'][i] = '-'
        else:
            lista_def['Valor Lance Vencedor'][i] = terrenos_selecionados['valor'][0]
    else:
        lista_def['Valor Lance Vencedor'][i] = '-'

    if len(terrenos_selecionados) >= 2:
        if terrenos_selecionados['colocacao'][1] == 'Desclassificado':
            lista_def['Valor Lance Segundo Colocado'][i] = '-'
        else:
            lista_def['Valor Lance Segundo Colocado'][i] = terrenos_selecionados['valor'][1]
    else:
        lista_def['Valor Lance Segundo Colocado'][i] = '-'

    if len(terrenos_selecionados) >= 3:
        if terrenos_selecionados['colocacao'][2] == 'Desclassificado':
            lista_def['Valor Lance Terceiro Colocado'][i] = '-'
        else:
            lista_def['Valor Lance Terceiro Colocado'][i] = terrenos_selecionados['valor'][2]
    else:
        lista_def['Valor Lance Terceiro Colocado'][i] = '-'

    try:
        lista_def['R$ Valor / Pot. Max'][i] = float(lista_def['Valor Lance Vencedor'][i])/float(lista_def['Área de Construção Máxima'][i])
    except:
        lista_def['R$ Valor / Pot. Max'][i] = float(lista_def['Valor de Face'][i]) / float(lista_def['Área de Construção Máxima'][i])
    try:
        lista_def['Número Meses'][i] = int(terrenos_selecionados['meses'][0])
    except:
        lista_def['Número Meses'][i] = '-'
    try:
        lista_def['Entrada'][i] = '{}%'.format(int(terrenos_selecionados['entrada'][0] * 100))
    except:
        lista_def['Entrada'][i] = '-'

lista_def.to_csv('imoveis_cleaned_new.csv')

lista_def.to_excel('imoveis_cleaned.xlsx')

imoveis = pd.read_csv('df_terracap_df_1.csv')
lista_def = imoveis.drop_duplicates(subset=['endereco'])

import pandas as pd
pd.read_csv("pd.read_csv('terracap_estoque_brasilia.csv')")


from torchvision import datasets, transforms

# Specify available data-sets.
AVAILABLE_DATASETS = {
    'mnist': datasets.MNIST,
}

# Specify available transforms.
AVAILABLE_TRANSFORMS = {
    'mnist': [
        transforms.Pad(2),
        transforms.ToTensor(),
    ],
    'mnist28': [
        transforms.ToTensor(),
    ],
}

# Specify configurations of available data-sets.
DATASET_CONFIGS = {
    'mnist': {'size': 32, 'channels': 1, 'classes': 10},
    'mnist28': {'size': 28, 'channels': 1, 'classes': 10},
}


import random

print('Hello, what is your name?')
name = input()

secretNumber = random.randint(1, 20)
print(f'Hello {name}. I am thinking of a number between 1 and 20. Guess the number.')
print(f'Secret number (DEBUG): {secretNumber}')
found = False

for attempt in range(1, 7):
    print('Take a guess')

    guess = int(input())
    if guess == secretNumber:
        print(f"Great! You guessed it correctly in {attempt} attempts")
        found = True
        break;
    elif guess < secretNumber:
        print('Nope. Your guess is too low')
    else:
        print('Nope. Your guess is too high')

if (not found):
    print(f"Sorry. You've run out of attempts. The secret number is {secretNumber}")


import time #pertenece a python
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#from selenium.webdriver.chrome.options import Options
#from selenium.webdriver.support.ui import Select
#from selenium.webdriver.common.by import By
#from selenium.webdriver.support.ui import WebDriverWait
#from selenium.webdriver.support import expected_conditions as EC

chromedriver = '/home/martin/Downloads/python/seleniumTest/drivers/chromedriver'

class alerta(unittest.TestCase):

  def setUp(self):

    self.driver = webdriver.Chrome(executable_path=chromedriver)

  def test_alerta(self):

    driver = self.driver

    driver.get('file:///home/martin/Downloads/python/htlm/alerta.html')

    time.sleep(3)

    alerta = driver.find_element_by_name("alert")

    alerta.click()

    alerta.switch_to_alert()
    time.sleep(3)
    alerta.dismiss()

    driver.close()

if __name__ == "__main__":
 unittest.main()


import pandas as pd
import numpy as np
import math
import sys

def information(data):
	max_val, min_val, count, somme, result = data[0], data[0], 0, 0, []
	for x in data:
		if not np.isnan(x):
			if max_val < x:
				max_val = x
			if min_val > x:
				min_val = x
			count += 1
			somme += x
			result.append(x)
	return max_val, min_val, count, somme, result

def std(data, count, mean):
	s = 0
	for x in data:
		if not np.isnan(x):
			s += (x - mean) **2
	s /= (count - 1)
	return (math.sqrt(s))

def percent(sorted_tab, count):
	length = count - 1
	if (count % 2 == 1):
		q1 = sorted_tab[int(length * 0.25)]
		q2 = sorted_tab[int(length * 0.5)]
		q3 = sorted_tab[int(length * 0.75)]
	else:
		q1 = (sorted_tab[int(length * 0.25)] + sorted_tab[int(length * 0.25) + 1]) / 2
		q2 = sorted_tab[int(length * 0.5)] + sorted_tab[int((length * 0.5) + 1)] / 2
		q3 = (sorted_tab[int(length * 0.75)] + sorted_tab[int(length * 0.75) + 1]) / 2
	return q1, q2, q3

if __name__ == '__main__':
    try:
        data = pd.read_csv(sys.argv[1])
    except:
        print("Usage: python3 describe.py datasets/dataset_train.csv")
        exit (-1)
    features = {}
    features_name = ["Arithmancy","Astronomy","Herbology","Defense Against the Dark Arts","Divination","Muggle Studies","Ancient Runes","History of Magic","Transfiguration","Potions","Care of Magical Creatures","Charms","Flying"]
    for i in range(13):
        feature = {}
        max_val, min_val, count, somme, tab = information(data[features_name[i]])
        feature["Count"] = count
        feature["Mean"] = somme / count
        feature["Std"] = std(data[features_name[i]], count, feature["Mean"])
        feature["Min"] = min_val
        sorted_tab = sorted(tab)
        q1, q2, q3 = percent(sorted_tab, count)
        feature["25%"] = q1
        feature["50%"] = q2
        feature["75%"] = q3
        feature["Max"] = max_val
        features[features_name[i]] = feature
    print(pd.DataFrame.from_dict(features))


import json
import os
from typing import Dict, List

current_dir = os.path.dirname(__file__)
data_path = 'data.json'
abs_path = os.path.join(current_dir, data_path)

def read_data() -> List[Dict]:
    """ Get all data from data.json file.

  Reads all data from the json file and returns a list
  containing all data.
  """
    with open(abs_path, 'r') as file:
        json_text = file.read()
    data = json.loads(json_text)
    return data


def add_time(starTime, addTime, day=0):
    dayCount = 0
    dayStamp = 0
    startTime = starTime.split(" ")
    startHndM = startTime[0]
    dayPeriod = startTime[1]
    addTime = addTime.split(":")
    addHour = int(addTime[0])
    addMInutes = int(addTime[1])
    weekday = {1: "monday", 2: "tuesday", 3: "wednesday",
               4: "thurdsday", 5: "friday", 6: "saturday", 7: "sunday"}
    halfDay = 0
    start = startHndM.split(":")
    hour = int(start[0])
    minutes = int(start[1])
    minutes += addMInutes
    hour += addHour

    if minutes >= 60:
        hour += 1
        minutes -= 60

    while hour >= 24:
        dayStamp += 1
        dayCount += 1
        hour -= 24

    if hour > 12:
        halfDay = 1
        hour -= 12
        if hour == 0:
            hour = 1

    if hour >= 12:
        if dayStamp == 1 and dayPeriod == "PM":
            dayCount += 1
            dayPeriod = "AM"
        if dayPeriod == "AM" and dayStamp == 0:
            dayPeriod = "PM"

    if not day == 0:
        day = day.lower()
        for key, value in weekday.items():
            if day == value:
                day = int(key)
        if dayPeriod == "PM" and halfDay == 1:
            dayCount += 1
            dayPeriod = "AM"
            halfDay -= 1
            if day > 7:
                day -= 7
        elif dayPeriod == "AM" and halfDay == 1:
            dayPeriod = "PM"
        day += (dayCount % 7)
        while day > 7:
            day -= 7
        for key, value in weekday.items():
            if day == key:
                day = value
                day = day.capitalize()
    else:
        if dayPeriod == "PM" and halfDay == 1:
            dayCount += 1
            if dayStamp == "1":
                dayCount += 1
            dayPeriod = "AM"
            halfDay -= 1
        elif dayPeriod == "AM" and halfDay == 1:
            dayPeriod = "PM"

    if len(str(minutes)) < 2:
        minutes = f"0{minutes}"

    if not day == 0:
        if dayCount == 0:
            return f"{hour}:{minutes} {dayPeriod}, {day}"
        elif dayCount == 1:
            return f"{hour}:{minutes} {dayPeriod}, {day} (next day)"
        else:
            return f"{hour}:{minutes} {dayPeriod}, {day} ({dayCount} days later)"
    else:
        if dayCount == 0:
            return f"{hour}:{minutes} {dayPeriod}"
        elif dayCount == 1:
            return f"{hour}:{minutes} {dayPeriod} (next day)"
        else:
            return f"{hour}:{minutes} {dayPeriod} ({dayCount} days later)"


import pytest
import boto3
import os
import requests
import json

from lambda_service.info_images import info_table

from lambda_service.info_images import handle_info_image_created
from lambda_service.info_images import get_site_metadata
from lambda_service.info_images import get_info_channel

from lambda_service.tests.testutils import make_data_files
from lambda_service.tests.testutils import get_upload_url
from lambda_service.tests.testutils import upload_files
from lambda_service.tests.testutils import get_s3_event

TEST_BASE_FILENAME = "test-ptrdata-20200101-01234567"
TEST_SITE = "test"

@pytest.fixture(scope="module", autouse=True)
def setup_teardown_module():
    make_data_files()
    test_files_directory = 'lambda_service/tests/testing_data'
    files_to_upload = [
        (f"{TEST_BASE_FILENAME}-EX01.fits.bz2", f"{test_files_directory}/testdata.fits.bz2"),
        (f"{TEST_BASE_FILENAME}-EX10.fits.bz2", f"{test_files_directory}/testdata.fits.bz2"),
        (f"{TEST_BASE_FILENAME}-EX10.jpg", f"{test_files_directory}/testdata.jpg"),
        (f"{TEST_BASE_FILENAME}-EX11.jpg", f"{test_files_directory}/testdata.jpg"),
        (f"{TEST_BASE_FILENAME}-EX00.txt", f"{test_files_directory}/testdata.txt"),
    ]
    info_channel = 1
    upload_files(files_to_upload, 'info-images', info_channel)
    # make files
    yield
    # remove_data_files()

def add_site_metadata(site, channel, base_filename):
    info_table.put_item(Item={
        'pk': f'{site}#metadata',
        f'channel{channel}': base_filename
    })

def remove_site_metadata(pk):
    info_table.delete_item(Key={'pk': pk})

@pytest.fixture
def sitemetadata():
    """ Setup and teardown of the dynamodb info-images site#metadata entry """
    base_filename = TEST_BASE_FILENAME
    site = TEST_SITE
    channel = 1
    add_site_metadata(site, channel, base_filename)
    # this is where the test function runs
    yield
    # remove site metadata entry
    remove_site_metadata(f'{site}#metadata')

##### Unit Tests #####

def test_get_info_channel_exists():
    base_filename = 'test_base_filename'
    site_metadata = {
        'pk': 'ptr_data_unittest#metadata',
        'badchannel3': 'test_base_filename',
        'channel1': 'not the correct base_filename',
        'channel2': 'test_base_filename',
    }
    channel = get_info_channel(base_filename, site_metadata)
    assert (channel == 2)

def test_get_info_channel_missing():
    base_filename = 'test_base_filename'
    site_metadata = {
        'pk': 'ptr_data_unittest#metadata',
        'badchannel3': 'test_base_filename',
        'channel1': 'not the correct base_filename',
    }
    channel = get_info_channel(base_filename, site_metadata)
    assert (channel is None)

##### Integration Tests #####

def test_new_info_jpg():

    # make sure the site metadata exists for our test object so the image is saved in the right channel
    channel = 1
    site = TEST_SITE
    base_filename = TEST_BASE_FILENAME
    add_site_metadata(site, channel, base_filename)

    small_jpg_filepath = f"info-images/{base_filename}-EX11.jpg"
    event = get_s3_event(small_jpg_filepath)

    # test the function
    handle_info_image_created(event, {})

    # check that the info-images dynamodb entry was created correctly
    response = info_table.get_item(Key={"pk": f"{site}#{channel}"})
    print(response)
    assert response['Item']

def test_new_info_txt():

    # make sure the site metadata exists for our test object so the image is saved in the right channel
    channel = 1
    site = TEST_SITE
    base_filename = TEST_BASE_FILENAME
    add_site_metadata(site, channel, base_filename)

    txt_filepath = f"info-images/{base_filename}-EX00.txt"
    event = get_s3_event(txt_filepath)

    # test the function
    handle_info_image_created(event, {})

    # Check that the header data was saved for our object
    response = info_table.get_item(Key={"pk": f"{site}#{channel}"})
    print(response)
    assert 'header' in response['Item']

def test_get_site_metadata(sitemetadata):
    base_filename = TEST_BASE_FILENAME
    site = TEST_SITE
    site_metadata = get_site_metadata(site)
    assert(site_metadata['channel1'] == base_filename)


def solve(N, M, roads):
    city_roads = [[] for _ in range(N+1)]
    for A, B, C in roads:
        city_roads[A].append((B, C))
        city_roads[B].append((A, C))

    def dfs(current_city, visited):
        if all(visited):
            return 0
        max_length = 0
        for next_city, length in city_roads[current_city]:
            if not visited[next_city]:
                visited[next_city] = True
                max_length = max(max_length, length + dfs(next_city, visited))
                visited[next_city] = False
        return max_length

    max_distance = 0
    for start_city in range(1, N+1):
        visited = [False] * (N+1)
        visited[start_city] = True
        max_distance = max(max_distance, dfs(start_city, visited))

    return max_distance

N, M = map(int, input().split())
roads = []
for _ in range(M):
    A, B, C = map(int, input().split())
    roads.append((A, B, C))

result = solve(N, M, roads)
print(result)

# TLE 6


#IMPORT
import os
import shutil
import time
import platform
from datetime import datetime

#GET IMAGES FROM DIRECTORY

def getImages(folder):

    print("> locating images...")

    #initialize variables, get list of everything in folder
    fileList = []
    removeList = []
    try:
        os.chdir(folder)
        fileList = os.listdir()
    except:
        print("> error x3: unable to locate directory "+folder)
        exit()

    #remove folders from fileList
    for file in fileList:
        folderFlag = True

        for letter in file:

            if letter == ".":
                folderFlag = False
                break

        if folderFlag == True:
            removeList.append(file)

    for file in removeList:
        fileList.remove(file)

    #error checking: empty directory
    if fileList == []:
        print("> error x1: no files detected in this directory")
        time.sleep(2)
        exit()

    #ask for user confirmation to proceed
    if input("> found "+str(len(fileList))+" photos. Proceed (y/n)? ") != "y":
        exit()

    return fileList

#CREATE FOLDERS FOR ORGANIZATION BY YEAR

def createFolders(fileList, MONTHS):

    print("> detected years...")

    #initialize variables
    yearList = []

    #check through file years, add to yearlist
    for file in fileList:
        year, na = getExifData(file)

        if year not in yearList:
            yearList.append(year)
            print("> "+year)

    #conduct error checking, get directories that already exist
    existingYearList = checkFiles(fileList, yearList)

    #make directories that correspond to yearList
    for year in yearList:

        #if directory already exists, skip it
        if year not in existingYearList:

            for month in MONTHS:
                os.makedirs(year+"/"+month)

    print("> folder structure complete")
    time.sleep(2)

#SORT PHOTOS

def sortPhotos(fileList, MONTHS):

    count = 0

    #go through each file and move it
    for file in fileList:

        count += 1

        #get year and month from exif data
        year, monthNum = getExifData(file)
        month = MONTHS[int(monthNum)-1]

        #use shutil.move to move dat file! (and skip if it already exists!)
        try:
            shutil.move(file, year+"/"+month)
            print("> move "+file)
        except shutil.Error:
            print("> error x6: Unable to move "+file+" because file already exists at destination. Skipping!")

    print("> moved "+str(count)+" files")

#CHECK FOR ERRORS AND ABORT IF FOUND

def checkFiles(fileList, yearList):

    #initialize variables
    existingYearList = []
    flag = False
    error = ""

    """
    #ensure that first 6 chars of filename are numbers
    for file in fileList:
        try:
            int(file[0:6])
        except:
            flag = True
            error = "x2: invalid file name: " + file
    """

    #get list of already existing year folders
    for year in yearList:
        files = os.listdir()
        if year in files:
            existingYearList.append(year)
            print("> found directory "+str(year))

    """
    #ensure that chars 4-6 are a valid month
    erroneousfilename = ""
    try:
        for file in fileList:
            erroneousfilename = file
            if int(file[4:6]) > 12:
                flag = True
                error = "x4: "+file[4:6]+" is not a valid month: " + file

    #check if something really weird happens
    except:
        flag = True
        error = "x5: invalid file names" + erroneousfilename
    """

    #if flag was set to true, then there is an error somewhere
    if flag == True:
        print("> error "+error)
        time.sleep(2)
        exit()

    return existingYearList

#GET DATE OF CREATION FOR A GIVEN FILE

def getExifData(filename):

    #Get current operating environment
    SYSTEM = platform.system()

    #If on Windows
    if SYSTEM == "Windows":
        data = os.path.getmtime(filename)

    #If on MacOS or Linux
    else:
        data = os.stat(filename).st_mtime

    #Convert unix time to month and year
    month = datetime.utcfromtimestamp(data).strftime("%m")
    year = datetime.utcfromtimestamp(data).strftime("%Y")

    return year, month


import os

from . import infopanel
from . import resources
from ...vendors import qute

# --------------------------------------------------------------------------------------------------
def show_tooltip(title=None, descriptive=None, graphic=None, pos=None):
    """
    For the sake of optimisation we only ever instance a single tooltip if
    we can. Therefore this function handles the concept of a singleton.

    :param title: Title to show in the tooltip
    :type title: str

    :param descriptive: A descriptive breakdown for the user
    :type descriptive: str

    :param graphic: An absolute path to a gif demonstrating the behaviour
    :type graphic: str

    :return: carapace.ui.widgets.Tooltip instance
    """
    # -- TODO: This should be removed, its here only whilst
    # -- debugging
    title = title or 'Test'
    descriptive = descriptive or 'this is a demonstration of a tooltip'
    graphic = graphic or resources.get('test.gif')

    # -- Ensure we have a parent - we use the maya window
    parent = qute.utilities.windows.mainWindow()

    # -- If we have an active instance, we strive to re-utilise it
    if TooltipWindow.ACTIVE_INSTANCE:
        try:
            TooltipWindow.ACTIVE_INSTANCE.setData(
                title,
                descriptive,
                graphic,
            )

            TooltipWindow.ACTIVE_INSTANCE.setGeometry(
                pos.x(),
                pos.y(),
                TooltipWindow.ACTIVE_INSTANCE.size().width(),
                TooltipWindow.ACTIVE_INSTANCE.size().height(),
            )

            TooltipWindow.ACTIVE_INSTANCE.show()
            return TooltipWindow.ACTIVE_INSTANCE
        except:
            pass

    # -- In this scenario we could not re-use an existing
    # -- instance, so we shall create a new one
    TooltipWindow.ACTIVE_INSTANCE = TooltipWindow(
        title,
        descriptive,
        graphic,
        parent=parent
    )

    TooltipWindow.ACTIVE_INSTANCE.setGeometry(
        pos.x(),
        pos.y(),
        TooltipWindow.ACTIVE_INSTANCE.size().width(),
        TooltipWindow.ACTIVE_INSTANCE.size().height(),
    )

    TooltipWindow.ACTIVE_INSTANCE.show()

    return TooltipWindow.ACTIVE_INSTANCE

# --------------------------------------------------------------------------------------------------
class ToolTip(qute.QWidget):
    """
    This is the central area  of a tool tip, and the area responsible for showing the
    information to the user
    """

    # ----------------------------------------------------------------------------------------------
    def __init__(self, title, descriptive, graphic, parent=None):
        super(ToolTip, self).__init__(parent=parent)

        # -- We store the movie as a variable to allow us to stop it
        # -- whenever the widget is not visible
        self._movie = None

        # --- Set the default layout
        self.setLayout(
            qute.utilities.layouts.slimify(
                qute.QVBoxLayout(),
            ),
        )

        # -- Define the styling based on the css data
        qute.utilities.styling.apply(
            [
                resources.get('tooltip.css')
            ],
            apply_to=self,
        )

        # -- Load in the ui file
        self.ui = qute.utilities.designer.load(
            resources.get('tooltip.ui'),
        )
        self.layout().addWidget(self.ui)

        # -- Finally apply the data to show in the tooltip
        self.setData(
            title,
            descriptive,
            graphic,
        )

    # ----------------------------------------------------------------------------------------------
    def optimize(self):
        if self._movie:
            self._movie.stop()

    # ----------------------------------------------------------------------------------------------
    def hideEvent(self, *args, **kwargs):
        """
        Whenever this widget is hidden we explicitly stop the movie to ensure
        we're being as optimal as possible.

        :return:
        """
        self.optimize()

    # ----------------------------------------------------------------------------------------------
    def leaveEvent(self, event):
        """
        Whenever we leave this widgets area we want to hide the window

        :param event:
        :return:
        """
        self.window().hide()

    # ----------------------------------------------------------------------------------------------
    def setData(self, title, descriptive, graphic):
        """
        Allows the setting of data within the tooltip

        :param title: Title to show in the tooltip
        :type title: str

        :param descriptive: A descriptive breakdown for the user
        :type descriptive: str

        :param graphic: An absolute path to a gif demonstrating the behaviour
        :type graphic: str

        :return:
        """
        # -- Apply the data textural data
        self.ui.title.setText(title)
        self.ui.descriptive.setText(descriptive)

        # -- Now we assign the movie and play it
        self._movie = qute.QMovie(graphic)
        self._movie.setScaledSize(qute.QSize(400, 400))
        self.ui.graphic.setMovie(self._movie)
        self._movie.start()

# --------------------------------------------------------------------------------------------------
class TooltipWindow(infopanel.PanelWindow):
    """
    This is the main window panel which holds the tooltip widget. This window
    is responsible for the transparency and rounding.
    """
    # -- We used this to track the active instance to allow us
    # -- to re-use it where possible
    ACTIVE_INSTANCE = None

    ROUNDING = 8

    # ----------------------------------------------------------------------------------------------
    def __init__(self, title, descriptive, graphic, parent=None):
        super(TooltipWindow, self).__init__(parent=parent)

        # -- Assign the central widget
        self.setCentralWidget(
            ToolTip(
                title,
                descriptive,
                graphic,
                parent=self,
            ),
        )

    # ----------------------------------------------------------------------------------------------
    def setData(self, title, descriptive, graphic):
        """
        Allows the setting of data within the tooltip

        :param title: Title to show in the tooltip
        :type title: str

        :param descriptive: A descriptive breakdown for the user
        :type descriptive: str

        :param graphic: An absolute path to a gif demonstrating the behaviour
        :type graphic: str
        :return:
        """
        self.centralWidget().setData(title, descriptive, graphic)


from dataclasses import dataclass
from typing import TypeVar, List, Generic, Any, Callable

from plugp100.common.functional.tri import Try

T = TypeVar("T")

@dataclass
class TriggerLogResponse(Generic[T]):
    event_start_id: int
    size: int
    events: List[T]

    @staticmethod
    def try_from_json(
        json: [str, Any], parse_log_item: Callable[[Any], T]
    ) -> Try["TriggerLogResponse[T]"]:
        return Try.of(
            lambda: TriggerLogResponse[T](
                event_start_id=json["start_id"],
                size=json["sum"],
                events=list(map(parse_log_item, json["logs"])),
            )
        )


import discord
import asyncio
import logging
import functools
import requests

from discord.ext import commands
from cachetools import TTLCache
from datetime import datetime, timedelta

from bot.models.track import AsyncAudioSource, Track
from bot.models.voice_context import VoiceContext
# from bot.services.track_service import TrackService
from bot.exceptions.exceptions import YTDLException
from bot.util.log import setup_logging_queue
from bot.util.color import ICE_BLUE

LOG = logging.getLogger('simple')

class Music(commands.Cog):

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        # self.track_service = track_service
        self.voice_contexts = {}
        self.metadata_cache = TTLCache(100, timedelta(hours=12), timer=datetime.now)

    def get_voice_context(self, ctx: commands.Context):
        voice_context = self.voice_contexts.get(ctx.guild.id)
        if not voice_context:
            voice_context = VoiceContext(self.bot, ctx)
            self.voice_contexts[ctx.guild.id] = voice_context

        return voice_context

    def cog_unload(self):
        for state in self.voice_contexts.values():
            self.bot.loop.create_task(state.stop())

    def _is_queue_state_invalid(self, ctx: commands.Context):
        return (not ctx.voice_context or
                not ctx.voice_context.is_playing or
                len(ctx.voice_context.tracks) == 0)

    async def cog_before_invoke(self, ctx: commands.Context):
        ctx.voice_context = self.get_voice_context(ctx)

    async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
        await ctx.send(str(error))

    @commands.command(name='join', invoke_without_subcommand=True)
    async def _join(self, ctx: commands.Context):
        dest = ctx.author.voice.channel

        if ctx.voice_context.voice:
            await ctx.voice_context.voice.move_to(dest)
            return

        ctx.voice_context.voice = await dest.connect()

    @commands.command(name='repeat')
    async def _repeat(self, ctx: commands.Context, *, num: int):

        if not ctx.voice_context.current_track:
            await ctx.send("No track is currently playing!")
            return

        for _ in range(num):
            t = Track(ctx.voice_context.current_track.source.webpage_url)
            await ctx.voice_context.tracks.put(t)

        await ctx.send(f"Enqueued {num} plays of {ctx.voice_context.current_track.source.title}")

    @commands.command(name='play')
    async def _play(self, ctx: commands.Context, *, url: str):

        # This might happen if play is invoked from another coroutine
        if not hasattr(ctx, "voice_context"):
            ctx.voice_context = self.get_voice_context(ctx)

        if not ctx.voice_context.voice:
            await ctx.invoke(self._join)

        try:
            source = await AsyncAudioSource.create(ctx, url, self.metadata_cache)
        except YTDLException as e:
            await ctx.send(f"Nothing found for url {url}...")
        except Exception as e:
            LOG.error(f"Error creating audio source: {e}")
        else:
            track = Track(source)

            # If queue contains items, send queued msg
            if ctx.voice_context.is_playing or len(ctx.voice_context.tracks) > 0:
                await ctx.send(f"Queued up {track.source.title} !")

            await ctx.voice_context.tracks.put(track)

    @commands.command(name='leave')
    async def _leave(self, ctx: commands.Context):
        if not ctx.voice_context.voice:
            return await ctx.send("Not connected to any channel")

        await ctx.voice_context.stop()
        del self.voice_contexts[ctx.guild.id]

    @commands.command(name='pause')
    async def _pause(self, ctx: commands.Context):
        if ctx.voice_context.is_playing and ctx.voice_context.voice.is_playing():
            ctx.voice_context.voice.pause()
            return await ctx.send("Paused!")

    @commands.command(name='resume')
    async def _resume(self, ctx: commands.Context):
        if ctx.voice_context.is_playing and ctx.voice_context.voice.is_paused():
            ctx.voice_context.voice.resume()
            return await ctx.send("Resumed!!")

    @commands.command(name='skip')
    async def _skip(self, ctx: commands.Context):

        if not ctx.voice_context.is_playing:
            return await ctx.send("But there's no song playing!")

        ctx.voice_context.skip()

    @commands.command(name='stop', aliases=['clear', 'quit'])
    async def _stop(self, ctx: commands.Context):
        ctx.voice_context.tracks.clear()

        if ctx.voice_context.is_playing:
            ctx.voice_context.voice.stop()

    @commands.command(name='queue')
    async def _queue(self, ctx: commands.Context):
        if not ctx.voice_context:
            return await ctx.send("I'm not currently active, why not change that with !play")
        tracks = ctx.voice_context.tracks
        return await ctx.send(f"{len(tracks)} tracks are queued")

    @commands.command(name='peek', aliases=['next'])
    async def _peek(self, ctx: commands.Context, num: int = None):

        if self._is_queue_state_invalid(ctx):
            return await ctx.send("No songs are queued!")

        if num is None:
            nxt = ctx.voice_context.tracks[0]
            return await ctx.send(embed=nxt.embed(title='Next up ~', color=ICE_BLUE))

        # Pull in the min(len(queue), num) and send each embed
        for idx in range(min(len(ctx.voice_context.tracks), num)):
            track = ctx.voice_context.tracks[idx]
            title = "Next up ~" if idx == 0 else f"Playing after {idx + 1} tracks"
            await ctx.send(embed=track.embed(
                                title=title,
                                color=ICE_BLUE))

    @commands.command(name='shuffle')
    async def _shuffle(self, ctx: commands.Context):
        if self._is_queue_state_invalid(ctx):
            return await ctx.send("No songs are queued to shuffle!")

        ctx.voice_context.tracks.shuffle()
        await ctx.send("Shuffled tracks in queue! Take a look with !peek {number}")

    # @commands.command(name='top')
    # async def _top(self, ctx:commands.Context, n: int = 1):
    #     top_tracks = await self.track_service.get_top_tracks(ctx.guild.id, n)
    #     await ctx.send(embed=Track.topTracksEmbed(top_tracks, ICE_BLUE))

    @commands.command(name='help')
    async def _help(self, ctx: commands.Context):
        embed = (discord.Embed(
            title='Command list',
            color=ICE_BLUE)
        .add_field(
            name='**!play {url}**',
            value='Queues up a track from YouTube. Must be in a voice channel to use',
            inline=False
        )
        .add_field(
            name='**!skip**',
            value='Skips the track currently playing',
            inline=False
        )
        .add_field(
            name='**!join**',
            value='Moves Elsa into the voice channel the user is currently in',
            inline=False
        )
        .add_field(
            name='**!leave**',
            value='Removes Elsa from the voice channel the user is currently in',
            inline=False
        )
        .add_field(
            name='**!pause**',
            value='Pauses the current track that is playing',
            inline=False
        )
        .add_field(
            name='**!resume**',
            value='Resumes a track that has been paused',
            inline=False
        )
        .add_field(
            name='**!stop**',
            value='Quits the current track, and clears the queue',
            inline=False
        )
        .add_field(
            name='**!queue**',
            value='Gives the number of tracks currently queued',
            inline=False
        )
        .add_field(
            name='**!peek {n}**',
            value='Shows the next n tracks that are in the queue',
            inline=False
        )
        .add_field(
            name='**!shuffle**',
            value='Shuffles tracks in the existing queue',
            inline=False
        )
        # .add_field(
        #     name='**!top {n}**',
        #     value='Displays a leaderboard of N most freqently played tracks',
        #     inline=False
        # )
        .add_field(
            name='**!repeat {n}**',
            value='Queues up the currently playing track N times to repeat',
            inline=False
        ))
        await ctx.send(embed=embed)

    @_join.before_invoke
    @_play.before_invoke
    @_repeat.before_invoke
    async def validate_voice_context(self, ctx: commands.Context):
        if not ctx.author.voice or not ctx.author.voice.channel:
            raise commands.CommandError("You aren't connected to a voice channel")

        if ctx.voice_client:
            if ctx.voice_client.channel != ctx.author.voice.channel:
                raise commands.CommandError("I'm already in a voice channel")


def caeserCifer():
    # get the encryption key
    key = int(input("Enter the key for encryption:"))
    messageToEncrypt = input("Enter the message to encrypt:")
    messageToEncrypt = messageToEncrypt.upper()
    encryptedMessage = ''
    for i in messageToEncrypt:
        echar = ord(i) + key
        if echar <= 90:
            encryptedMessage += chr(echar)
        if echar > 90:
            echar = echar - 26
            encryptedMessage += chr(echar)
    print(encryptedMessage)
    return encryptedMessage
def decryptCifer():
    key = int(input("Enter the key for decryption:"))
    messageToDecrypt = input("Enter the message to decrypt:")
    messageToDecrypt = messageToDecrypt.upper()
    decryptedMessage = ''
    for i in messageToDecrypt:
        dchar = ord(i) - key
        if dchar >= 65:
            decryptedMessage += chr(dchar)
        if dchar < 65:
            dchar = dchar + 26
            decryptedMessage += chr(dchar)
    print(decryptedMessage.replace(':',' '))
def bruteForceForDecryption(key,messageToDecrypt):
    if key <= 25:
        decryptedMessage = ''
        for i in messageToDecrypt:
            dchar = ord(i) - key
            if dchar >= 65:
                decryptedMessage += chr(dchar)
            if dchar < 65:
                dchar = dchar + 26
                decryptedMessage += chr(dchar)
        print(decryptedMessage.replace(':',' '))
        opt = input("Does the decrypted message has some meaning(y or n):")
        if opt.lower() == 'y':
            pass
        if opt.lower() == 'n':
            bruteForceForDecryption(key+1,a)
    else:
        print("Sorry no valid message found")
a = caeserCifer()
decryptCifer()
bruteForceForDecryption(1,a)


#!/usr/bin/env python3
# Name: Daniel Schmelter (dschmelt)
# Group Members: None

"""
This program should take in input of a codon or amino acid 1 letter or 3 letter code
and then output the corresponding codon or amino acid matching it via dictionaries
"""
import sys

class Converter:

    #long amino acid code keys, short values
    short_AA = {
                'CYS': 'C', 'ASP': 'D', 'SER': 'S', 'GLN': 'Q', 'LYS': 'K',
                'ILE': 'I', 'PRO': 'P', 'THR': 'T', 'PHE': 'F', 'ASN': 'N',
                'GLY': 'G', 'HIS': 'H', 'LEU': 'L', 'ARG': 'R', 'TRP': 'W',
                'ALA': 'A', 'VAL': 'V', 'GLU': 'E', 'TYR': 'Y', 'MET': 'M'
                }
    #switches keys and values so short key has long AA value
    long_AA = {value:key for key,value in short_AA.items()}

    rnaCodonTable = {
    # Second Base
    # U             C             A             G
    #U
    'UUU': 'Phe', 'UCU': 'Ser', 'UAU': 'Tyr', 'UGU': 'Cys',
    'UUC': 'Phe', 'UCC': 'Ser', 'UAC': 'Tyr', 'UGC': 'Cys',
    'UUA': 'Leu', 'UCA': 'Ser', 'UAA': '---', 'UGA': '---',
    'UUG': 'Leu', 'UCG': 'Ser', 'UAG': '---', 'UGG': 'Trp',
    #C
    'CUU': 'Leu', 'CCU': 'Pro', 'CAU': 'His', 'CGU': 'Arg',
    'CUC': 'Leu', 'CCC': 'Pro', 'CAC': 'His', 'CGC': 'Arg',
    'CUA': 'Leu', 'CCA': 'Pro', 'CAA': 'Gln', 'CGA': 'Arg',
    'CUG': 'Leu', 'CCG': 'Pro', 'CAG': 'Gln', 'CGG': 'Arg',
    #A
    'AUU': 'Ile', 'ACU': 'Thr', 'AAU': 'Asn', 'AGU': 'Ser',
    'AUC': 'Ile', 'ACC': 'Thr', 'AAC': 'Asn', 'AGC': 'Ser',
    'AUA': 'Ile', 'ACA': 'Thr', 'AAA': 'Lys', 'AGA': 'Arg',
    'AUG': 'Met', 'ACG': 'Thr', 'AAG': 'Lys', 'AGG': 'Arg',
    #G
    'GUU': 'Val', 'GCU': 'Ala', 'GAU': 'Asp', 'GGU': 'Gly',
    'GUC': 'Val', 'GCC': 'Ala', 'GAC': 'Asp', 'GGC': 'Gly',
    'GUA': 'Val', 'GCA': 'Ala', 'GAA': 'Glu', 'GGA': 'Gly',
    'GUG': 'Val', 'GCG': 'Ala', 'GAG': 'Glu', 'GGG': 'Gly'
    }
    dnaCodonTable = {key.replace('U','T'):value for key, value in rnaCodonTable.items()}

def main():

    t = Converter()
        #take input and convert it to upper case
    code = (input("Please enter a codon or Amino Acid 1 or 3 letter code: ")).upper()

        #check if the input is in any of the dictionaries
    if code in t.short_AA:        #searches one letter dic
        print ('{} = {}'.format(code, t.short_AA[code].upper()))
    elif code in t.long_AA:         #searches three letter dic
        print ('{} = {}'.format(code, t.long_AA[code].upper()))
    elif code in t.rnaCodonTable:  #searches RNA codons)
        print ('{} = {}'.format(code, t.rnaCodonTable[code].upper()))
    elif code in t.dnaCodonTable:     #searches DNA codon table
        print ('{} = {}'.format(code, t.dnaCodonTable[code].upper()))
    else:
        print('unknown')        #if code is not in the dictionaries, print unknown
main()


from PIL import Image
import numpy as np
import math

def openImage(image, loc = None):
    '''
    reads an image with the given and returns a numpy array
    :param image:
    :return:
    '''
    img = Image.open(image)
    arr = np.asarray(img, dtype=np.int32)
    return arr

def saveImage(image_array, name, loc = None):
    '''
    saves the image array 'image_array' as image at the given location 'loc' with the given name
    :param image_array:
    :param name:
    :return:
    '''
    im = Image.fromarray(image_array.astype('uint8'), mode="RGB")
    im.save(name)

def showImage(image_array):
    '''

    :param image_array: a numpy array
    :return:
    '''
    im = Image.fromarray(image_array.astype('uint8'), mode="RGB")
    im.show()

def affineTransform(img_arr, M, size_new_img):
    '''
    used for scaling and transformation
    :param img_arr: numpy array of input image
    :param M: transformation matrix
    :param size_new_img: a tuple which contains the width and height of new image
    :return: resulting array when input image array is transformed with the supplied transformation matrix M
    '''

    # get height and width of old and new image
    h_old, w_old, num_channel = img_arr.shape
    w_new, h_new = size_new_img
    new_img = np.zeros((h_new, w_new, num_channel), dtype=np.uint8)
    for i in range(w_new):
        for j in range(h_new):
            # calculate pixel pos of destination pixel from pixel pos of source pixels
            pos_in_old_img = M.reshape((2,3))*(np.matrix([i,j,1]).reshape(3,1))
            pos_in_old_img = pos_in_old_img.reshape((1,2)).astype(int)
            pos_x, pos_y = pos_in_old_img.item(0), (pos_in_old_img.item(1))

            if 0<pos_x<w_old and 0<pos_y<h_old:
                new_img[j,i] = img_arr[pos_y, pos_x]

    return new_img

def affineTransformForRotation(img_arr, M, size_new_img):
    '''
    used for rotation
    :param img_arr: numpy array of input image
    :param M: transformation matrix
    :param size_new_img: a tuple which contains the width and height of new image
    :return: resulting array when input image array is transformed with the supplied transformation matrix M
    '''
    h_old, w_old, num_channel = img_arr.shape
    w_new, h_new = size_new_img
    new_img = np.zeros((h_new, w_new, num_channel), dtype=np.uint8)
    for i in range(w_new):
        for j in range(h_new):
            # calculate pixel pos of destination pixel from pixel pos of source pixels
            pos_in_old_img = ( M *
                               (
                                       np.matrix([i,j]).reshape((2,1)) \
                                       - np.matrix([w_new/2, h_new/2]).reshape((2,1)) \
                              ) \
                             )\
                             + np.matrix([w_old/2, h_old/2]).reshape((2,1))
            pos_in_old_img = pos_in_old_img.reshape((1,2)).astype(int)
            pos_x, pos_y = pos_in_old_img.item(0), (pos_in_old_img.item(1))

            if 0<pos_x<w_old and 0<pos_y<h_old:
                new_img[j,i] = img_arr[pos_y, pos_x]

    return new_img

def rotation(img_arr, theta):
    '''
    rotates the image by the given angle 'theta'
    :param img_arr: numpy array of imput image
    :param theta: angle of rotation
    :return: numpy array of rotated image
    '''
    # determine shape of img
    height, width = img_arr.shape[:2]

    cos = math.cos(math.radians(theta))
    sin = math.sin(math.radians(theta))

    # make rotation matrix
    rot_mat = np.matrix([[cos, sin], [-sin, cos]])

    # calculate new height and width to account for rotation
    newWidth = int((height * abs(sin)) + (width * abs(cos)))
    newHeight = int((height * abs(cos)) + (width * abs(sin)))

    new_img = affineTransformForRotation(img_arr, rot_mat, (newWidth, newHeight))
    return new_img

def scaling(img_arr, scale):
    '''
    scales the images by the given scale factor 'scale'
    :param img_arr: numpy array of imput image
    :param scale: scale-factor
    :return: numpy array of rotated image
    '''
    # shape of img
    height, width = img_arr.shape[:2]

    # make scaling matrix
    transformMat = np.matrix([[(1/scale), 0.0, 0.0],[0.0, (1/scale), 0.0]])

    # calculate new height and width
    newWidth = int(width*scale)
    newHeight = int(height*scale)

    new_img = affineTransform(img_arr, transformMat, (newWidth, newHeight))
    return new_img

def shift(img_arr, tx, ty):
    '''
    translated the image by the given shifting distance tx,ty
    :param img_arr: numpy array of imput image
    :param tx: shifting distance in x-direction
    :param ty: shifting distance in y-direction
    :return: numpy array of rotated image
    '''
    # shape of img
    height, width = img_arr.shape[:2]
    #print(height, width)
    transformMat = np.matrix([[1, 0, -tx],[0, 1, -ty]])

    # calculate new height and width
    #newWidth = width +abs(tx)
    #newHeight = height +abs(ty)
    newWidth = width
    newHeight = height

    new_img = affineTransform(img_arr, transformMat, (newWidth, newHeight))
    return new_img

def main():
    img_arr = openImage("image.png")
    #**************************************************

    #**************************************************
    #For rotation of Image
    theta = -45
    print("Rotating image by theta: {}".format(theta))
    rot_img = rotation(img_arr, theta)
    saveImage(rot_img, "output1.png")
    print("Done!!!")
    showImage(rot_img)
    #**************************************************

    #**************************************************
    # For Scaling of Image
    scale = 2
    print("Scaling image by factor: {}".format(scale))
    scaled_img = scaling(img_arr, scale)
    saveImage(scaled_img, "output2.png")
    print("Done!!!")
    showImage(scaled_img)
    #**************************************************

    #**************************************************
    #For Shifting of Image
    tx=10
    ty=10
    print("Shifting Image by tx={0}, ty={1}".format(tx, ty))
    shifted_img = shift(img_arr, tx, ty)
    saveImage(shifted_img, "output3.png")
    print("Done!!!")
    showImage(shifted_img)
    #**************************************************

if __name__ == '__main__':
    main()


from datetime import date, timedelta
import factory
import factory.fuzzy

from user_extensions.factories import UserFactory

from . import models

TEST_SYSTEM_CHOICES = [s[0] for s in models.SYSTEM_CHOICES]
TEST_COUNTRY_CHOICES = [c[0] for c in models.COUNTRY_CHOICES]

class TrashProfileFactory(factory.django.DjangoModelFactory):
    """Dummy TrashProfile"""
    class Meta:
        model = models.TrashProfile

    user = factory.SubFactory(UserFactory)
    system = factory.fuzzy.FuzzyChoice(TEST_SYSTEM_CHOICES)

    current_household = factory.SubFactory(
        "trashinator.factories.HouseHoldFactory",
        user=factory.SelfAttribute("..user"))

class HouseHoldFactory(factory.django.DjangoModelFactory):
    """Dummy HouseHold"""
    class Meta:
        model = models.HouseHold

    user = factory.SubFactory(UserFactory)
    population = factory.fuzzy.FuzzyInteger(1, 8)
    country = factory.fuzzy.FuzzyChoice(TEST_COUNTRY_CHOICES)

class TrashFactory(factory.django.DjangoModelFactory):
    """Dummy Trash"""
    class Meta:
        model = models.Trash

    @factory.sequence
    def date(x):
        return date.today() - timedelta(x)

    household = factory.SubFactory("trashinator.factories.HouseHoldFactory")
    gallons = factory.fuzzy.FuzzyFloat(0, 13)

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        trash = model_class.create(*args, **kwargs)
        trash.save()
        return trash

class TrackingPeriodFactory(factory.django.DjangoModelFactory):
    """TrackingPeriod"""
    class Meta:
        model = models.TrackingPeriod

    status = "PROGRESS"

    @staticmethod
    def from_trash(first, count, *args, **kwargs):

        for i in range(count):
            day = first.date - timedelta(days=(i + 1))
            TrashFactory(date=day, household=first.household,
                         tracking_period=first.tracking_period)

        first.tracking_period.save()
        return first.tracking_period


calcstrats = {
    'subtraction': lambda x, y: x - y,
    'addition': lambda x, y: x + y,
    'multiplication': lambda x, y: x * y,
    'division': lambda x, y: x / y
    }

def printStrats(lst):
    for c in lst.keys():
        print(c)

def operateOnInput(task):
    """Operate on user-defined input"""
    values = input('Enter two integers separated by a comma and whitespace: ')
    str_list = list(values.split(', '))
    int_list = list(map(int, str_list))

    result = calcstrats[task](
        int_list[0],
        int_list[1]
        )
    print(f'The result is {result}')

def main():

    print('Welcome to the Small Calculator! What do you want to do? Available operations are')
    printStrats(calcstrats)
    task = input()
    operateOnInput(task)

    while True:
        continuation = input('Keep calculating? Enter Y for yes, or N for no: ')
        if continuation == 'Y':
            print('Choose your operation. Available operations are')
            printStrats(calcstrats)
            task = input()
            operateOnInput(task)
        elif continuation == 'N':
            print('Goodbye!')
            break

if __name__ == '__main__':
    main()


from matplotlib.pylab import plt
from mpl_toolkits.mplot3d import Axes3D
from .common import *

def function_2_show(x):
    fig = plt.figure()
    ax = Axes3D(fig)
    _x, _y = np.meshgrid(x[0], x[1])
    _z = function_2(np.array([_x, _y]))
    ax.plot_surface(_x, _y, _z,
                    rstride=1,
                    cstride=1,
                    cmap='rainbow'
                    )
    plt.show()

def numerical_gradient_show(x, f):
    x, y = np.meshgrid(*x)

    x = x.flatten()
    y = y.flatten()

    grad = numerical_gradient(f, np.array([x, y]))

    plt.figure()
    plt.quiver(x, y, -grad[0], -grad[1], angles='xy', color='#666666')
    plt.xlabel('x0')
    plt.ylabel('x1')
    plt.grid()
    plt.legend()
    plt.draw()
    plt.show()


import torch
import torch.nn as nn
from torch.autograd import Variable

def weights_init(m):
    if isinstance(m, nn.Conv1d) or isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv3d):
        m.weight.data.normal_(0, 0.02)
        m.bias.data.zero_()
    elif isinstance(m, nn.BatchNorm1d) or isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm3d):
        m.weight.data.normal_(1, 0.02)
        m.bias.data.zero_()
    elif isinstance(m, nn.Linear):
        m.bias.data.zero_()

class ConvEncoder2D(nn.Module):
    def __init__(self, num_layers, in_channels = 3, out_channels = 8, batch_norm = True):
        super(ConvEncoder2D, self).__init__()

        # set up number of layers
        if isinstance(num_layers, int):
            num_layers = [num_layers, 0]

        network = []

        # several 3x3 convolutional layers and max-pooling layers
        for k in range(num_layers[0]):
            # 2d convolution
            network.append(nn.Conv2d(in_channels, out_channels, 3, padding = 1))

            # batch normalization
            if batch_norm:
                network.append(nn.BatchNorm2d(out_channels))

            # non-linearity and max-pooling
            network.append(nn.LeakyReLU(0.2, True))
            network.append(nn.MaxPool2d(2))

            # double channel size
            in_channels = out_channels
            out_channels *= 2

        # several 1x1 convolutional layers
        for k in range(num_layers[1]):
            # 2d convolution
            network.append(nn.Conv2d(in_channels, in_channels, 1))

            # batch normalization
            if batch_norm:
                network.append(nn.BatchNorm2d(in_channels))

            # non-linearity
            network.append(nn.LeakyReLU(0.2, True))

        # set up modules for network
        self.network = nn.Sequential(*network)
        self.network.apply(weights_init)

    def forward(self, inputs):
        return self.network.forward(inputs)

class ConvEncoder3D(nn.Module):
    def __init__(self, num_layers, in_channels = 3, out_channels = 8, batch_norm = True):
        super(ConvEncoder3D, self).__init__()

        # set up number of layers
        if isinstance(num_layers, int):
            num_layers = [num_layers, 0]

        network = []

        # several 3x3 convolutional layers and max-pooling layers
        for k in range(num_layers[0]):
            # 3d convolution
            network.append(nn.Conv3d(in_channels, out_channels, 3, padding = 1))

            # batch normalization
            if batch_norm:
                network.append(nn.BatchNorm3d(out_channels))

            # non-linearity and max-pooling
            network.append(nn.LeakyReLU(0.2, True))
            network.append(nn.MaxPool3d(2))

            # double channel size
            in_channels = out_channels
            out_channels *= 2

        # several 1x1 convolutional layers
        for k in range(num_layers[1]):
            # 3d convolution
            network.append(nn.Conv3d(in_channels, in_channels, 1))

            # batch normalization
            if batch_norm:
                network.append(nn.BatchNorm3d(in_channels))

            # non-linearity
            network.append(nn.LeakyReLU(0.2, True))

        # set up modules for network
        self.network = nn.Sequential(*network)
        self.network.apply(weights_init)

    def forward(self, inputs):
        return self.network.forward(inputs)

class SeqEncoder(nn.Module):
    def __init__(self, input_size, feature_size = 128, num_layers = 1, hidden_size = 256, dropout = 0.9):
        super(SeqEncoder, self).__init__()
        self.num_layers = num_layers
        self.hidden_size = hidden_size

        # set up modules for recurrent neural networks
        self.rnn = nn.LSTM(input_size = input_size,
                           hidden_size = hidden_size,
                           num_layers = num_layers,
                           batch_first = True,
                           dropout = dropout,
                           bidirectional = True)
        self.rnn.apply(weights_init)

        # set up modules to compute features
        self.feature = nn.Linear(hidden_size * 2, feature_size)
        self.feature.apply(weights_init)

    def forward(self, inputs):
        # set up batch size
        batch_size = inputs.size(0)

        # compute hidden and cell
        hidden = Variable(torch.zeros(self.num_layers * 2, batch_size, self.hidden_size).cuda())
        cell = Variable(torch.zeros(self.num_layers * 2, batch_size, self.hidden_size).cuda())
        hidden_cell = (hidden, cell)

        # recurrent neural networks
        _, (hidden, cell) = self.rnn.forward(inputs, hidden_cell)

        # concatenate hidden states from both directions (fixme: do not support multiple layers)
        hidden_forward, hidden_backward = torch.split(hidden, 1, 0)
        hidden = torch.cat([hidden_forward.squeeze(0), hidden_backward.squeeze(0)], 1)

        # compute features by hidden states
        features = self.feature.forward(hidden)
        return features


from django.conf.urls import patterns, url
from django.contrib import admin

from referral import views

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(
        r'^$',
        views.ViewReferral.as_view(),
        name='get'
    ),
    url(
        r'^add/$',
        views.AddReferral.as_view(),
        name='add'
    ),
    url(
        r'^status/$',
        views.ReferralStatus.as_view(),
        name='status'
    )
)


from django.conf.urls import patterns, url
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView

from blog.feeds import RecentPostsFeed, AllPostsFeed, PostCommentsFeed
from blog.models import Post

# Post URLs.
urlpatterns = patterns('',
    # (Mostly) Restful URLs.
    url(r'^(?:posts/)*$',
        ListView.as_view(model=Post, template_name='posts/index.html',
                         paginate_by=10),
        name='posts'),

    url(r'^posts/new/$',
        staff_member_required(CreateView.as_view(
                model=Post,
                template_name='posts/new.html')),
        name='new_post'),

    url(r'^post/(?P<pk>\d+)/$',
        DetailView.as_view(model=Post, template_name='posts/show.html'),
        name='post'),

    url(r'^post/(?P<pk>\d+)/edit/$',
        staff_member_required(UpdateView.as_view(
                model=Post,
                template_name='posts/edit.html')),
        name='edit_post'),

    # URLs as specified by the project instructions.
    url(r'^(?P<slug>[^/]+)/$',
        DetailView.as_view(model=Post, template_name='posts/show.html'),
        name='post_by_slug'),
)

# Feed URLs.
urlpatterns += patterns('',
    url(r'^posts/recent/rss/$', RecentPostsFeed(), name='recent_posts_feed'),
    url(r'^posts/rss/$', AllPostsFeed(), name='all_posts_feed'),
    url(r'^post/(?P<pk>\d+)/rss/$', PostCommentsFeed(),
        name='post_comments_feed'),
    url(r'^(?P<slug>[^/]+)/rss/$', PostCommentsFeed(),
        name='post_comments_feed_by_slug'),
)


from torch import nn

class LabelSmoothedCrossEntropyCriterion(nn.Module):
    """Implement label smoothing."""

    def __init__(self, eps=0.1, reduction=True):
        super(LabelSmoothedCrossEntropyCriterion, self).__init__()
        self.eps = eps
        self.reduction = reduction

    def forward(self, lprobs, target, pad_mask):
        lprobs = lprobs.view(-1, lprobs.size(-1))
        target = target.view(-1, 1)
        pad_mask = pad_mask.view(-1, 1)
        if self.reduction:
            nll_loss = -lprobs.gather(dim=-1, index=target).masked_fill_(pad_mask == 0, 0.0)
            nll_loss = nll_loss.sum()
            smooth_loss = -lprobs.sum(dim=-1, keepdim=True).masked_fill_(pad_mask == 0, 0.0)
            smooth_loss = smooth_loss.sum()
        else:
            nll_loss = -lprobs.gather(dim=-1, index=target)[pad_mask]
            smooth_loss = -lprobs.sum(dim=-1, keepdim=True)[pad_mask]
        eps_i = self.eps / lprobs.size(-1)
        loss = (1. - self.eps) * nll_loss + eps_i * smooth_loss
        return loss, pad_mask.sum()


import sys
M = int(sys.stdin.readline())
S = [0]*21
for i in range(M):
    a = list(sys.stdin.readline().split())
    if len(a) > 1 : a[1] = int(a[1])
    if a[0] == 'add': S[a[1]] = 1
    elif a[0] == 'remove': S[a[1]] = 0
    elif a[0] == 'check':
        if S[a[1]] == 1: print(1)
        else: print(0)
    elif a[0] == 'toggle':
        if S[a[1]] == 1: S[a[1]] = 0
        else: S[a[1]] = 1
    elif a[0] == 'all':
        S = [1] * 21
    elif a[0] == 'empty':
        S = [0] * 21


# -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 11:22:32 2022

@author: nnetznik
"""

import pandas as pd
import os

path = "C:/Users/nnetznik/Documents/Capstone/data/"
files = os.listdir(path)

df_list = [pd.read_csv(path+file) for file in files]
df = pd.concat(df_list, axis=0).sample(100000, axis=0, random_state=100)

df.to_csv(path+'sample.csv')


import json

filename = "testfolder/config.json"

def gifTerms(argv):
    # prints list of term keys
    if len(argv) == 2:
        try:
            file = open(filename, 'r')
        except FileNotFoundError:
            print("No query terms found.")
        else:
            try:
                contents = json.load(file)
            except json.decoder.JSONDecodeError:
                file.close()
                print("No query terms found.")
            else:
                file.close()
                keys = list(contents)
                if len(keys):
                    print(list(contents))
                else:
                    print("No query terms found.")

    # removes term key from config.json
    elif len(argv) > 3 and argv[2] == '-D':
        term = argv[3]
        try:
            file = open(filename, 'r')
        except FileNotFoundError:
            print("Query term doesn't exist to remove.")
        else:
            try:
                contents = json.load(file)
            except json.decoder.JSONDecodeError:
                print("Query term doesn't exist to remove.")
                file.close()
            else:
                try:
                    contents[term]
                except KeyError:
                    print("Query term doesn't exist to remove.")
                # if the term exists in config.json then remove it
                else:
                    newContents = {}
                    keys = list(contents)
                    for key in keys:
                        if key != term:
                            newContents[key] = contents[key]
                    file = open(filename, 'w')
                    file.write(json.dumps(newContents, indent=4))
                    print(f"Successfully removed {term} from config.json.")
                    file.close()

    elif len(argv) == 3 and argv[2] == '-D':
        print("Str value expected. Ex: py . -c -D {term}")

    elif len(argv) > 2 and argv[2] != '-D':
        print(f"Unknown flag: {argv[2]}")

if __name__ ==  '__main__':
    gifTerms(['.','-c'])


import sys
sys.stdin = open('t.txt','r')

def printlist(lst,cur,idx):
    for i in range(idx):
        cur = cur.next
    return cur.data

def InsertAt(mylist,idx,val):
    new = Node(val)
    #빈 리스트일 때, 맨 앞에 삽입
    if mylist.head == None:
        if idx == 0 :
            mylist.head = mylist.tail = new
        else : return

    #맨 뒤에 삽입
    elif mylist.size <= idx:
        new.next = mylist.tail
        mylist.tail = new

    #중간에 삽입
    else :
        cur = mylist.head
        for _ in range(idx - 1):
            cur = cur.next
        new.next = cur.next
        cur.next = new

    mylist.size += 1

T = int(input())
for tc in range(1,T+1):
    N,M,L = map(int,input().split())
    arr = [int(x) for x in input().split()]

    class Node():
        def __init__(self,d=0,n=None):
            self.data = d
            self.next = n

    class LinkedList():
        def __init__(self):
            self.head = None
            self.tail = None
            self.size = 0

    mylist = LinkedList()

    pre, cur = None,None
    for i in range(-1,-N-1,-1):
        cur = Node(arr[i], pre)
        pre = cur
        if i == -1 :
            mylist.tail = cur
        elif i == -N:
            mylist.head = cur

    mylist.size = N

    #Insert
    for i in range(M):
        idx, val = map(int,input().split())
        InsertAt(mylist, idx, val)

    print("#{} {}".format(tc,printlist(mylist,mylist.head,L)))


from tkinter import *
from PIL import Image, ImageTk
from editFunctions import sharpenImage, blurImage, rotateCounter
from editFunctions import rotateClockwise, cropImage, sketchImage, oilImage, pencilImage, foilImage, negativeImage

def changeImage(counter):
	img = ImageTk.PhotoImage(Image.open('image' + str(counter) +'.jpg'))
	panel.configure(image = img)
	panel.image = img

def sharpenImageFunction():
	global rotateCounter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	sharpenImage(curImg, counter)
	changeImage(counter)

def blurImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	blurImage(curImg, counter)
	changeImage(counter)

def rotateCounterFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	rotateCounter(curImg, counter)
	changeImage(counter)

def rotareClockwiseFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	rotateClockwise(curImg, counter)
	changeImage(counter)

def cropImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	cropImage(curImg, counter)
	changeImage(counter)

def undoFunction():
	global counter
	if counter > 0:
		counter = counter - 1
	changeImage(counter)

def sketchImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	sketchImage(curImg, counter)
	changeImage(counter)

def oilImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	oilImage(curImg, counter)
	changeImage(counter)

def paintImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	pencilImage(curImg, counter)
	changeImage(counter)

def foilImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	foilImage(curImg, counter)
	changeImage(counter)

def negativeImageFunction():
	global counter
	curImg = 'image' + str(counter) + '.jpg'
	counter = counter + 1
	negativeImage(curImg, counter)
	changeImage(counter)

main = Tk()
counter = 0
main.title("Photo Editor")
main.geometry("1000x505")
var = IntVar()
editingBox = Frame(main)

undoButton = Button(main, text="Undo", command=undoFunction, font=20)
undoButton.pack(side=BOTTOM, pady=10)

formatLabel = Label(editingBox, text = "Format", font=16)
formatLabel.pack(side = TOP, pady=10)

sharpenButton = Button(editingBox, text = "Sharpen Image", command=sharpenImageFunction, width=20)
sharpenButton.pack(side = TOP)

blurButton = Button(editingBox, text="Blur Image", command=blurImageFunction, width=20)
blurButton.pack(side = TOP)

cropButton = Button(editingBox, text="Crop", command=cropImageFunction, width=20)
cropButton.pack(side = TOP)

rotateCounterButton = Button(editingBox, text="Rotate Counter Clockwise", command = rotateCounterFunction, width=20)
rotateCounterButton.pack(side = TOP)

rotateClockwiseButton = Button(editingBox, text="Rotate Clockwise", command = rotateCounterFunction, width=20)
rotateClockwiseButton.pack(side = TOP)

img = ImageTk.PhotoImage(Image.open('image' + str(counter) + '.jpg'))
panel = Label(main, image=img)
panel.pack(side= LEFT, padx=20)

negativeButton = Button(editingBox, text="Negative Photo", command=negativeImageFunction, width=20)
negativeButton.pack(side = BOTTOM)

foilButton = Button(editingBox, text="Foil art", command=foilImageFunction, width=20)
foilButton.pack(side = BOTTOM)

pencilButton = Button(editingBox, text="Sharp Paint", command = paintImageFunction, width=20)
pencilButton.pack(side = BOTTOM)

oilButton = Button(editingBox, text="Oil Paint", command=oilImageFunction, width=20)
oilButton.pack(side = BOTTOM)

sketchButton = Button(editingBox, text="Sketch Light", command=sketchImageFunction, width=20)
sketchButton.pack(side = BOTTOM)

filterLabel = Label(editingBox, text = "Filters", font=16)
filterLabel.pack(side = BOTTOM, pady=10)

editingBox.pack()
main.mainloop()


def calc(S, p):
    if S == 1 and p == 2:
        return True
    elif (S == 1 and p == 1) or (S > 1 and p >= 2) or S < 1:
        return False
    if S % 2 == 0 and S % 3 == 0:
        return calc(S // 2, p + 1) or calc(S // 3, p + 1)
    elif S % 2 == 0 and S % 3 != 0:
        return calc(S // 2, p + 1) or calc(S - 3, p + 1)
    elif S % 2 != 0 and S % 3 == 0:
        return calc(S - 2, p + 1) or calc(S // 3, p + 1)
    elif S % 2 != 0 and S % 3 != 0:
        return calc(S - 2, p + 1) or calc(S - 3, p + 1)

max_cur_S = 0
for i in range(1, 38):
    if calc(i, 0):
        print(i)
        max_cur_S = max(max_cur_S, i)
print(max_cur_S)


# -*- coding: utf-8 -*-
# @File    : VerticalOrderTraversalOfABinaryTree.py
# @Date    : 2022-08-14
# @Author  : tc
"""
987. 二叉树的垂序遍历
给你二叉树的根结点 root ，请你设计算法计算二叉树的 垂序遍历 序列。
对位于 (row, col) 的每个结点而言，其左右子结点分别位于 (row + 1, col - 1) 和 (row + 1, col + 1) 。树的根结点位于 (0, 0) 。
二叉树的 垂序遍历 从最左边的列开始直到最右边的列结束，按列索引每一列上的所有结点，形成一个按出现位置从上到下排序的有序列表。如果同行同列上有多个结点，则按结点的值从小到大进行排序。
返回二叉树的 垂序遍历 序列。
示例 1：
输入：root = [3,9,20,null,null,15,7]
输出：[[9],[3,15],[20],[7]]
解释：
列 -1 ：只有结点 9 在此列中。
列  0 ：只有结点 3 和 15 在此列中，按从上到下顺序。
列  1 ：只有结点 20 在此列中。
列  2 ：只有结点 7 在此列中。
示例 2：

输入：root = [1,2,3,4,5,6,7]
输出：[[4],[2],[1,5,6],[3],[7]]
解释：
列 -2 ：只有结点 4 在此列中。
列 -1 ：只有结点 2 在此列中。
列  0 ：结点 1 、5 和 6 都在此列中。
          1 在上面，所以它出现在前面。
          5 和 6 位置都是 (2, 0) ，所以按值从小到大排序，5 在 6 的前面。
列  1 ：只有结点 3 在此列中。
列  2 ：只有结点 7 在此列中。
示例 3：

输入：root = [1,2,3,4,6,5,7]
输出：[[4],[2],[1,5,6],[3],[7]]
解释：
这个示例实际上与示例 2 完全相同，只是结点 5 和 6 在树中的位置发生了交换。
因为 5 和 6 的位置仍然相同，所以答案保持不变，仍然按值从小到大排序。

提示：
树中结点数目总数在范围 [1, 1000] 内
0 <= Node.val <= 1000

自定义排序

我们可以从根节点开始，对整棵树进行一次遍历，在遍历的过程中使用数组 nodes 记录下每个节点的行号row，列号col 以及值value。
在遍历完成后，我们按照col 为第一关键字升序，row 为第二关键字升序，value 为第三关键字升序，对所有的节点进行排序即可。
在排序完成后，我们还需要按照题目要求，将同一列的所有节点放入同一个数组中。
因此，我们可以对nodes 进行一次遍历，并在遍历的过程中记录上一个节点的列号lastcol。
如果当前遍历到的节点的列号col与 lastcol 相等，则将该节点放入与上一个节点相同的数组中，
否则放入不同的数组中。

代码参考:https://leetcode.cn/problems/vertical-order-traversal-of-a-binary-tree/solution/er-cha-shu-de-chui-xu-bian-li-by-leetcod-clsh/
"""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

from typing import List
class Solution:
    def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
        nodes = list()

        def dfs(node, row, col):
            if not node:
                return
            nodes.append((col, row, node.val))
            dfs(node.left, row + 1, col - 1)
            dfs(node.right, row + 1, col + 1)

        dfs(root, 0, 0)
        nodes.sort()
        ans = list()
        lastcol = float("-inf")

        for col, row, value in nodes:
            if col != lastcol:
                lastcol = col
                ans.append(list())
            ans[-1].append(value)
        return ans


import time
import board
import busio
import array
import math
import adafruit_adxl34x

i2c = busio.I2C(board.SCL, board.SDA)
accelerometer = adafruit_adxl34x.ADXL345(i2c)

accel = []
upperthreshold = 5.0
lowerthreshold = -5.0
steps = 0
count = 0
height = 72
stride = 0
distance = 0
speed = 0
start = time.time()

#height = height * 0.0254

while True:
    StrideT = time.time() - start
    StrideTime = (int(StrideT))
    #print(StrideTime)
    x, y, z = accelerometer.acceleration
    mag = math.sqrt((x**2)+(y**2)+(z**2))
    accel.append(mag)
    mean = sum(accel) / len(accel)
    magzero = mag - mean
    print(magzero)
    #print(accelerometer.acceleration)
    time.sleep(0.25)

    if ( magzero > upperthreshold ):
        steps = steps + 1
        print(steps)
        count = count + 1
        #print(count)
        #distance = distance + (stride * steps)
        #print(distance)
    if ( magzero < lowerthreshold ):
        steps = steps + 1
        print(steps)
        count = count + 1
        #print(count)
        #distance = distance + (stride * steps)
        #print(distance)
    #else:
        #print( "No step detected" )

        if(StrideTime % 2 == 0):
            if (count == 1):
                stride = height / 5
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
            if (count == 2):
                stride = height / 4
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
            if (count == 3):
                stride = height / 3
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
            if (count == 4):
                stride = height / 2
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
            if (count == 5):
                stride = height / 1.2
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
            if (6 <= count < 8):
                stride = height
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
            if (count >= 8):
                stride = height * 1.2
                #print(stride)
                distance = distance + (steps * stride)
                #print(distance)
                speed = count * (stride / 2)
                print(speed)
        else:
            count = 0


import setuptools

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

setuptools.setup(
    name="recipes-scrapper", # Replace with your own username
    version="1.0.0",
    author="Hector Santos",
    description="A recipes scrapper",
    packages=setuptools.find_packages('src', include=['nooddle_scrapper*']),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    install_requires=[
        'beautifulsoup4==4.9.1',
        'selenium==3.141.0'
    ],
    setup_requires=['pytest-runner'],
    tests_require=[
         'pytest',
    ],
    test_suite='pytest',
    python_requires='>=3.6',
)


import sys
input = sys.stdin.readline

def print_all():
    for i in range(9):
        print(*arr[i])

    exit(0)

def check(x, y, cur):
    # 같은 행, 열에 같은 숫자가 있으면 불가능
    for i in range(9):
        if arr[x][i] == cur: return False
        if arr[i][y] == cur: return False

    # 3 x 3 정사각형 범위를 위한 변수 선언
    start_x = (x // 3) * 3
    end_x = (x // 3) * 3 + 3
    start_y = (y // 3) * 3
    end_y = (y // 3) * 3 + 3

    # 3 x 3 정사각형 안에 같은 값이 있으면 불가능
    for i in range(start_x, end_x):
        for j in range(start_y, end_y):
            if arr[i][j] == cur:
                return False

    return True

def dfs(x, y, cur):
    if cur == cnt: # 해결이 완료되었으면 최종 출력
        print_all()
    elif y == 9: # 다음 줄로 넘어감
        dfs(x + 1, 0, cur)

    elif arr[x][y] == 0:
        for i in range(1, 10):
            if check(x, y, i):
                arr[x][y] = i
                dfs(x, y + 1, cur + 1)
                arr[x][y] = 0 # 혹여라도 이후에 잘못되었으면 복구해야 함

    else:
        dfs(x, y + 1, cur)

if __name__ == "__main__":
    cnt = 0

    arr = [0 for _ in range(9)]
    for i in range(9):
        arr[i] = list(map(int, input().split()))
        cnt = cnt + arr[i].count(0)

    dfs(0, 0, 0)

[BOJ] 백준 풀이/단계별로 풀어보기 (step by step)/#15 백트래킹/2580_스도쿠 (22.08.07 성공).py


#code
import sys
def form_paren(table,a,b,c):
    print(a,b,c)
    first=''
    if a==b or a+1==b:
        if a==b:
            first = chr(ord('A')+a)
        else:
            first = chr(ord('A')+a)+chr(ord('A')+b)
    else:
        ind = table[a][b][1]
        if len(ind)!=0:
            first = form_paren(table,*ind)

    second = ''
    if b==c:
         if b==c:
            first = chr(ord('A')+b)
         else:
            first = chr(ord('A')+b)+chr(ord('A')+c)
    else:
        ind= table[b+1][c][1]
        if len(ind) != 0:
            second =form_paren(table,*ind)
    return '('+first+second+')'

def solve(arr):

    table = [[[0,[]] for _ in range(0,len(arr))] for _ in range(0,len(arr))]

    for sub in range(2,len(arr)):
        for i in range(0,len(arr)-sub):
            j = i+sub-1
            paren = []
            min_op = sys.maxsize
            for k in range(i,j):
                op = (arr[i]*arr[k+1]*arr[j+1])+table[i][k][0]+table[k+1][j][0]
                if op < min_op:
                    min_op = op
                    paren = [i,k,j]
            table[i][j][0] = min_op
            table[i][j][1] = paren
    a,b,c = table[0][len(arr)-2][1]
    print(form_paren(table,a,b,c))

def read_input():
    test = int(input())
    for x in range(0,test):
        n = int(input())
        arr = [int(y) for y in input().strip().split()]
        solve(arr)
read_input()


#from LiterateAstroids.game.constants import CENTER_X, CENTER_Y
import arcade

from game.constants import (
    SCREEN_WIDTH,
    SCREEN_HEIGHT,
    WORKING_DIRECTORY,
)
from game.astroid import Astroid
from game.db_connect import DB_Connect
from game.laser import Laser
from game.ship import Ship
from game.data import Data
from game.inputs import Inputs
from game.tracker import Tracker
from game.gameover import GameOver
from game.db_connect import DB_Connect
from game.boom import Boom

class Director(arcade.View):

    def __init__(self):
        super().__init__()
        self.spritelist = None
        self.explosionlist = None
        self.asteroidlist = None
        self.laserlist = None
        self.ship = None
        self.astroid = None
        self.data = Data()
        self.inputs = Inputs()
        self.tracker = Tracker()
        self.gameover = GameOver()
        self.db = DB_Connect()
        self.text = None
        self.sig_gameover = False
        self.spawning = False   # DO NOT CHANGE
        self.spawn_counter = 1  # DO NOT CHANGE

        # sounds

        # like this better for laser
        self.laser_sound = None
        #sound for end of game explosion
        self.explosion_sound = None
        # for asteroid hitting ship sound
        self.explosion_asteroid_sound = None

        # ASTEROID SPAWN PARAMETERS
        self.spawn_amount = 3
        self.spawn_interval = 100
        self.asteroid_speed = 20

        # WAIT PARAMETERS
        self.count = 0
        self.target = -1
        self.waiting = False
        # Background music
        self.sound_song = None

    def setup(self):
        self.background = arcade.load_texture(
            WORKING_DIRECTORY+"/game/images/stars.png")

        # Inintialize sound effects
        self.laser_sound = arcade.load_sound("game\sounds\laser_gun.wav")
        self.explosion_sound = arcade.load_sound("game\sounds\ship_explode.wav")
        self.explosion_asteroid_sound = arcade.load_sound("game\sounds\explosion1.wav")

        # Initialize backgound music
        #self.sound_song = arcade.load_sound(":resources:music/1918.mp3")
        self.sound_song = arcade.load_sound("game\sounds\BGM-1.mp3")
        arcade.play_sound(self.sound_song)

        # creates a sprite list under name spritelist
        self.spritelist = arcade.SpriteList()
        self.explosionlist = arcade.SpriteList()
        self.asteroidlist = arcade.SpriteList()
        self.laserlist = arcade.SpriteList()

        self.ship = Ship()
        self.inputs = Inputs()
        # adds ship to sprite list /// THIS NEEDS TO BE THE FIRST ITEM ///
        self.spritelist.append(self.ship)

    # WAIT FUNCTION
    def wait_dur(self, duration):
        if self.waiting:
            if self.count <= 0:
                self.target = duration
                self.count += 1
            elif self.count >= self.target:
                self.waiting = False
                self.count = 0
                self.target = -1
            else:
                self.count += 1
        else:
            self.waiting = True

    def on_draw(self):
        arcade.start_render()
        # Draw background
        arcade.draw_lrwh_rectangle_textured(
            0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, self.background)

        # Updates graphics for all sprites
        self.laserlist.draw()
        self.spritelist.draw()
        self.explosionlist.draw()
        self.asteroidlist.draw()
        # Makes the first text in the list red, and the rest green
        for i in range(len(self.asteroidlist)):
            if i == 0:
                self.asteroidlist[i].draw_letter(arcade.color.RED)
            else:
                self.asteroidlist[i].draw_letter(arcade.color.GREEN)

        # Draw foreground
        if self.tracker.gethp() == 6:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH6.png")
        elif self.tracker.gethp() == 5:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH5.png")
        elif self.tracker.gethp() == 4:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH4.png")
        elif self.tracker.gethp() == 3:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH3.png")
        elif self.tracker.gethp() == 2:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH2.png")
        elif self.tracker.gethp() == 1:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH1.png")
        elif self.tracker.gethp() < 1:
            self.foreground = arcade.load_texture(
                WORKING_DIRECTORY+"/game/images/shipshellH0.png")

        arcade.draw_lrwh_rectangle_textured(
            0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, self.foreground)

        # Update text on screen
        self.inputs.draw(str(self.tracker.getscore()))

    # Check for key press and for is_match signal
    # Spawns new asteroid with new word if there is a match
    # Spawns a new laser pointed at the first asteroid in the list
    def on_key_press(self, symbol, modifer):
        # Waches for the "word matched" signal from the inputs object
        if len(self.asteroidlist) > 0:
            word = self.asteroidlist[0].get_word()
        else:
            word = ""
        if self.inputs.pressed(symbol, modifer, word) and len(self.asteroidlist) > 0:
            self.spritelist[0].point_to(
                self.asteroidlist[0].get_pos(), self.asteroidlist[0].get_id())

    # Check for key release

    def on_key_release(self, symbol, modifier): self.inputs.released(
        symbol, modifier)

    def on_update(self, delta_time):
        for sprite in self.spritelist:

            if len(self.asteroidlist) > 0 and sprite.update(self.asteroidlist[0].get_id()) == True:
                arcade.play_sound(self.laser_sound)
                self.laserlist.append(
                    Laser(40, self.spritelist[0].get_target_angle()))

        self.asteroidlist.update()
        self.laserlist.update()
        self.explosionlist.update()

        # Update keyboard inputs
        self.inputs.update()

        # Check for collisions with the laser and the asteroids
        # Delete both if there is contact
        if (len(self.laserlist) > 0 and len(self.asteroidlist) > 0):
            if arcade.check_for_collision(self.asteroidlist[0], self.laserlist[0]):
                self.explosionlist.append(
                    Boom(self.asteroidlist[0].center_x, self.asteroidlist[0].center_y, 7))
                # expolode when hits asteroid with laser
                arcade.play_sound(self.explosion_sound)
                self.laserlist.pop(0)
                self.asteroidlist.pop(0)
                self.tracker.addscore()

        # spawn_counter is used to spawn multiple asteroids with a 30 tick gap
        if len(self.asteroidlist) <= 0 and self.spawning == False:
            self.spawning = True
            self.spawn_counter = self.spawn_interval * self.spawn_amount
        if self.spawn_counter % self.spawn_interval == 0:
            self.asteroidlist.append(
                Astroid(2, self.data.random_word(self.tracker.getscore())))
        if self.spawn_counter >= 2:
            self.spawn_counter -= 1
        if self.spawn_counter < 2:
            self.spawning = False

        if len(self.asteroidlist) > 0 and len(self.spritelist) > 0:
            if arcade.check_for_collision(self.asteroidlist[0], self.spritelist[0]):
                self.explosionlist.append(
                    Boom(self.asteroidlist[0].center_x, self.asteroidlist[0].center_y, 7))

                self.asteroidlist.pop(0)
                if self.tracker.gethp() > 1:
                    self.tracker.minushp()
                    arcade.play_sound(self.explosion_asteroid_sound)
                else:
                    self.tracker.minushp()
                    self.explosionlist.append(
                        Boom(self.ship.center_x, self.ship.center_y, 30))
                    self.spritelist[0].alpha = 0
                    self.spritelist.pop()
                    self.sig_gameover = True

                    arcade.play_sound(self.explosion_sound)
                    # Wait 1 seconds
                    # self.spritelist.pop(-1)

                    # wait 1 second
                    self.wait_dur(100)

        if self.waiting == True:
            self.wait_dur(100)  # continue waiting
        else:
            if self.sig_gameover == True:
                self.gameover.gather(
                    str(self.tracker.getscore()), self.inputs, self.db,)
                self.window.show_view(self.gameover)

        for laser in self.laserlist:
            if laser.get_pos()[0] > SCREEN_WIDTH or laser.get_pos()[0] < 0:
                laser.remove_from_sprite_lists()
            if laser.get_pos()[1] > SCREEN_HEIGHT or laser.get_pos()[1] < 0:
                laser.remove_from_sprite_lists()