import os
import unittest
from gcn.classification.baseline_trainer import BaselineTrainer
from gcn.classification.baseline import LSTMClassifier

class TestBaselineTrainer(unittest.TestCase):

    def test_build(self):
        root = os.path.join(os.path.dirname(__file__), "../../")
        trainer = BaselineTrainer(root, preprocessor_name="test_cbt_preprocessor")

        trainer.build()
        self.assertTrue(len(trainer.preprocessor.vocabulary.get()) > 1000)
        print(trainer.preprocessor.vocabulary.get()[:100])
        print(trainer.preprocessor_path)
        os.remove(trainer.preprocessor_path)

    def test_train(self):
        root = os.path.join(os.path.dirname(__file__), "../../")
        trainer = BaselineTrainer(root, preprocessor_name="test_cbt_preprocessor")
        trainer.build()

        vocab_size = len(trainer.preprocessor.vocabulary.get())
        model = LSTMClassifier(vocab_size)
        model.build(trainer.num_classes)

        metrics = trainer.train(model.model, epochs=2)
        self.assertTrue(metrics.history["acc"][-1] - metrics.history["acc"][0] > 0)


import numpy as np
import re

def obtener_states(archivo):
    with open(archivo, 'r') as f:
        contenido = f.read()

    inicio_bloque = 'states'
    fin_bloque = 'endstates'

    inicio = contenido.find(inicio_bloque)
    fin = contenido.find(fin_bloque)

    if inicio == -1 or fin == -1:
        return []  # Si no se encuentra uno de los bloques, retorna un arreglo vacío

    inicio += len(inicio_bloque)
    contenido_bloque = contenido[inicio:fin].strip()
    arreglo_contenido = contenido_bloque.split(',')

    states = [s.strip() for s in arreglo_contenido]

    grid_bloque = 'Grid:'
    grid_inicio = contenido.find(grid_bloque)
    grid_inicio += len(grid_bloque)
    grid_fin = contenido.find('\n', grid_inicio + 1)
    first_row_grid = contenido[grid_inicio:grid_fin].strip().split()
    size = len(first_row_grid)

    return states, (size, size)

def obtener_initial_state(archivo):
    with open(archivo, 'r') as f:
        contenido = f.read()

    inicio_bloque = 'initialstate'
    fin_bloque = 'endinitialstate'

    inicio = contenido.find(inicio_bloque)
    fin = contenido.find(fin_bloque)

    if inicio == -1 or fin == -1:
        return []  # Si no se encuentra uno de los bloques, retorna un arreglo vacío

    inicio += len(inicio_bloque)
    contenido_bloque = contenido[inicio:fin].strip()
    arreglo_contenido = contenido_bloque.split(',')

    return [s.strip() for s in arreglo_contenido][0]

def obtener_goal_state(archivo):
    with open(archivo, 'r') as f:
        contenido = f.read()

    inicio_bloque = 'goalstate'
    fin_bloque = 'endgoalstate'

    inicio = contenido.find(inicio_bloque)
    fin = contenido.find(fin_bloque)

    if inicio == -1 or fin == -1:
        return []  # Si no se encuentra uno de los bloques, retorna un arreglo vacío

    inicio += len(inicio_bloque)
    contenido_bloque = contenido[inicio:fin].strip()
    arreglo_contenido = contenido_bloque.split(',')

    return [s.strip() for s in arreglo_contenido][0]

def obtener_actions(archivo, move, actions_moves):
    with open(archivo, 'r') as f:
        contenido = f.read()

    inicio_bloque = 'action ' + move
    fin_bloque = 'endaction'

    inicio = contenido.find(inicio_bloque)
    fin = contenido.find(fin_bloque, inicio)

    if inicio == -1 or fin == -1:
        return []  # Si no se encuentra uno de los bloques, retorna un arreglo vacío

    inicio += len(inicio_bloque)
    contenido_bloque = contenido[inicio:fin].strip()
    lineas = contenido_bloque.split('\n')

    for linea in lineas:
        elementos = linea.split()
        state_dicc = actions_moves.get(elementos[0])
        if state_dicc == None:
            actions_moves[elementos[0]] = {}

        move_dicc = actions_moves[elementos[0]].get(move)
        if move_dicc == None:
            actions_moves[elementos[0]][move] = {
                'acciones': []
            }

        action = {
            'estado_sucesor': elementos[1],
            'probabilidad_de_accion': float(elementos[2]),
            'descartar': float(elementos[3])
        }
        actions_moves[elementos[0]][move]['acciones'].append(action)

    return actions_moves

def obtener_cost(archivo, actions_moves):
    with open(archivo, 'r') as f:
        contenido = f.read()

    inicio_bloque = 'cost'
    fin_bloque = 'endcost'

    inicio = contenido.find(inicio_bloque)
    fin = contenido.find(fin_bloque)

    if inicio == -1 or fin == -1:
        return []  # Si no se encuentra uno de los bloques, retorna un arreglo vacío

    inicio += len(inicio_bloque)
    contenido_bloque = contenido[inicio:fin].strip()
    lineas = contenido_bloque.split('\n')

    for linea in lineas:
        elementos = linea.split()
        state_dicc = actions_moves.get(elementos[0])
        if state_dicc == None:
            actions_moves[elementos[0]] = {}

        move_dicc = actions_moves[elementos[0]].get(elementos[1])
        if move_dicc == None:
            actions_moves[elementos[0]][elementos[1]] = {}

        actions_moves[elementos[0]][elementos[1]
                                    ]['costo'] = float(elementos[2])

    return actions_moves

def filtrar_por_state(matrix, state):
    filas_coincidentes = []

    for fila in matrix:
        if fila[0] == state:
            filas_coincidentes.append(fila)

    return filas_coincidentes

def savePolicy(initial_state, goal_state, policy, iteration, execution_time, grid_shape, archivo):
    archivo_split = archivo.split('/')[-2:]
    x, y = grid_shape

    initial_state_x_y = re.findall(r'\d+', initial_state)
    goal_state_x_y = re.findall(r'\d+', goal_state)

    array = np.empty(x * y, dtype=object)

    counter = 0
    for i in range(x):
        for j in range(y):
            array[counter] = '■'
            counter += 1

    matriz = array.reshape(x, y)

    for (state, move) in policy:
        if state == goal_state:
            matriz[int(goal_state_x_y[0]) - 1,
                   int(goal_state_x_y[1]) - 1] = '\U0001F7E2'
            continue

        if state == initial_state:
            if move == 'move-north':
                matriz[int(initial_state_x_y[0]) - 1,
                       int(initial_state_x_y[1]) - 1] = '\U0001F446'
            if move == 'move-south':
                matriz[int(initial_state_x_y[0]) - 1,
                       int(initial_state_x_y[1]) - 1] = '\U0001F447'
            if move == 'move-west':
                matriz[int(initial_state_x_y[0]) - 1,
                       int(initial_state_x_y[1]) - 1] = '\U0001F448'
            if move == 'move-east':
                matriz[int(initial_state_x_y[0]) - 1,
                       int(initial_state_x_y[1]) - 1] = '\U0001F449'
            continue

        if state == None:
            continue

        x_y = re.findall(r'\d+', state)

        if move == 'move-north':
            matriz[int(x_y[0])-1, int(x_y[1])-1] = '↑'
            continue

        if move == 'move-south':
            matriz[int(x_y[0])-1, int(x_y[1])-1] = '↓'
            continue

        if move == 'move-west':
            matriz[int(x_y[0])-1, int(x_y[1])-1] = '←'
            continue

        if move == 'move-east':
            matriz[int(x_y[0])-1, int(x_y[1])-1] = '→'

    filename = 'Experimentos/' + archivo_split[0] + '_' + \
        archivo_split[1].replace('.net', '.policy')

    policy_str = matriz.transpose()[::-1]

    with open(filename, 'w') as fout:
        fout.writelines([
            'Número de iteraciones hasta la convergencia: ' + str(iteration),
            '\nEl tiempo en milisegundos utilizado por el algoritmo: ' +
            str(execution_time),
            '\nPolicy:\n'
        ])
        np.savetxt(fout, policy_str, fmt='%s')
        fout.close()

    return filename


from src.swen344_db_utils import *

def build_tables():
    exec_sql_file('Baseball-AL-East-2015.sql')

def find_team():
    team_sql = """
        SELECT name, title, team FROM Coach
            WHERE title= 'Manager'
    """
    team = exec_get_all(team_sql)
    print("Managers")
    print("---------------------------------")
    for row in team:
        print(row[0] + "   " + row[1] + "   " + row[2])

def find_player_name():
    play_name_sql = """
        SELECT Player.name, Coach.name, Coach.team
        FROM Player
        INNER JOIN Coach ON Player.team = Coach.team
        WHERE player.position = 1
        AND Coach.title = 'Pitching Coach'
        AND player.age > 30
    """
    print("\nPitchers over age of 30 and their coach")
    print("---------------------------------")
    player = exec_get_all(play_name_sql)
    for row in player:
        print(row[0], row[1], row[2])

def find_infielders():
    find_sql = """
    SELECT Player.name, Player.number, Player.age, Team.ballpark
        FROM Player
        INNER JOIN Team ON Player.team = Team.name
        WHERE player.position BETWEEN 3 AND 6
        AND Team.ballpark = 'Camden Yards'
    """
    print("\nInfielders")
    print("---------------------------------")
    infield = exec_get_all(find_sql)
    for row in infield:
        print(row[0], row[1], row[2])

def find_rays():
    rays_sql = """
        SELECT name, number FROM Player
            WHERE team = 'Rays'
            ORDER BY name
    """
    rays = exec_get_all(rays_sql)
    print("\nRays Players")
    print("---------------------------------")
    for row in rays:
        print(row[0], row[1])

def find_num_infielders():
    num_sql = """
        SELECT COUNT(position) FROM Player
            WHERE position BETWEEN 3 AND 6
    """

    print("\nnum of infielders")
    print("---------------------------------")
    num = exec_get_all(num_sql)
    print(num[0])

def find_avg_pitcher_age():
    find_sql = """
        SELECT ROUND(AVG(age),2) FROM Player
            WHERE position = 1

    """
    print("\nAverage pitcher age")
    print("---------------------------------")
    age = exec_get_all(find_sql)
    print(age[0])

def find_num():
    find_sql = """
        SELECT COUNT(position), team from Player
            WHERE position BETWEEN 3 AND 6
            GROUP BY team
    """
    print("\ninfielders grouped by team")
    print("---------------------------------")
    infield = exec_get_all(find_sql)
    for row in infield:
        print(row[0])

def main():
    build_tables()
    find_team()
    find_player_name()
    find_infielders()
    find_rays()
    find_num_infielders()
    find_avg_pitcher_age()
    find_num()

main()


import django_filters
from graphql_relay import from_global_id
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from graphql import GraphQLError

from creator.analyses.models import Analysis
from creator.analyses.mutations import Mutation

class AnalysisNode(DjangoObjectType):
    class Meta:
        model = Analysis
        interfaces = (relay.Node,)

    @classmethod
    def get_node(cls, info, id):
        """
        Only return if the user is allowed to view analyses
        """
        user = info.context.user

        if not (
            user.has_perm("analyses.view_analysis")
            or user.has_perm("analyses.view_my_study_analysis")
        ):
            raise GraphQLError("Not allowed")

        try:
            analysis = cls._meta.model.objects.get(id=id)
        except cls._meta.model.DoesNotExist:
            raise GraphQLError("Analysis does not exist")

        # If user only has view_my_study_analysis, make sure the analysis
        # belongs to one of their studies
        if user.has_perm("analyses.view_analysis") or (
            user.has_perm("analyses.view_my_study_analysis")
            and user.studies.filter(
                kf_id=analysis.version.root_file.study.kf_id
            ).exists()
        ):
            return analysis

        raise GraphQLError("Not allowed")

class AnalysisFilter(django_filters.FilterSet):
    file_kf_id = django_filters.CharFilter(
        field_name="version__root_file__kf_id", lookup_expr="exact"
    )

    class Meta:
        model = Analysis
        fields = ["creator", "known_format"]

    order_by = django_filters.OrderingFilter(fields=("created_at",))

class Query(object):
    analysis = relay.Node.Field(
        AnalysisNode, description="Get a single analysis"
    )
    all_analyses = DjangoFilterConnectionField(
        AnalysisNode,
        filterset_class=AnalysisFilter,
        description="Get all analyses",
    )

    def resolve_all_analyses(self, info, **kwargs):
        """
        Return all analyses if user has view_analysis
        Return only analyses in user's studies if user has the
            view_my_study_analysis permission
        Return not allowed otherwise
        """
        user = info.context.user

        if not (
            user.has_perm("analyses.list_all_analysis")
            or user.has_perm("analyses.view_my_study_analysis")
        ):
            raise GraphQLError("Not allowed")

        if user.has_perm("analyses.list_all_analysis"):
            return Analysis.objects.all()

        if user.has_perm("analyses.view_my_study_analysis"):
            return Analysis.objects.filter(
                version__root_file__study__in=user.studies.all()
            ).all()

        raise GraphQLError("Not allowed")


import unittest
from unittest import TestCase

from spiralPrint import spiralPrint

class TestSpiralPrint(unittest.TestCase):
    def test_matrix(self):
        self.assertEquals(spiralPrint('https://raw.githubusercontent.com/avito-tech/python-trainee-assignment/main/matrix.txt'),[
    10, 50, 90, 130,
    140, 150, 160, 120,
    80, 40, 30, 20,
    60, 100, 110, 70,
])


import os

import boto3

s3 = boto3.client('s3', region_name=os.environ['AWS_REGION'])
dynamodb = boto3.resource('dynamodb', region_name=os.environ['AWS_REGION'])

def s3_put_object(bucket_name, upload_data, object_key):
    result = s3.put_object(
        Bucket=bucket_name,
        Key=object_key,
        Body=upload_data
    )

    return result

def s3_get_object(bucket_name, object_key):
    result = s3.get_object(
        Bucket=bucket_name,
        Key=object_key
    )

    return result

def s3_generate_presigned_url(bucket_name, object_key):
    presigned_url = s3.generate_presigned_url(
        ClientMethod='get_object',
        Params={'Bucket': bucket_name, 'Key': object_key},
        ExpiresIn=3600
    )

    return presigned_url

def dynamodb_scan(table_name):
    Table = dynamodb.Table(table_name)

    result = Table.scan()

    return result

def dynamodb_get_item(table_name, key):
    Table = dynamodb.Table(table_name)

    result = Table.get_item(Key=key)

    return result

def dynamodb_put_item(table_name, item):
    Table = dynamodb.Table(table_name)

    result = Table.put_item(Item=item)

    return result


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import listdir
import re

class DataUnifier():
    files = []
    output_file = ""
    temp_storage = []

    def __init__(self):
        pass

    def unify_full(self, directory, output):
        self.output_file = output
        self.files = [directory+file for file in listdir(directory)]
        self._clear_outputfile
        self._merge_sentences()

    def unify_file(self, file):
        self.files = [file]
        self._merge_sentences(individual=True)
        return self.temp_storage

    def _clear_outputfile(self):
        with open(self.output_file, "w+") as file:
            return

    def _merge_sentences(self, individual=False):
        for filename in self.files:
            with open(filename, "r", encoding="utf8") as file:
                sentence = ""
                for line in file:
                    line = self._clean_line(line)
                    if line in ["", " "]:
                        self._write_output(sentence, individual)
                        sentence = ""
                    else:
                        sentence += " "
                        for character in line:
                            if character in ",.?!:;":
                                output = self._clean_line(sentence)
                                self._write_output(output, individual)
                                sentence = ""
                            else:
                                sentence += character

    def _clean_line(self, line):
        line = line.strip()
        line = line.lower()
        line = re.sub("[^A-Za-z ,.?!:;]", " ", line)
        #line = re.sub(" +", " ", line)
        line = line.split()
        line = " ".join(line)
        return line

    def _write_output(self, sentence, individual):
        validation = sentence.split()
        if len(validation)>0 and validation[0]!= " ":
            if individual:
                self.temp_storage.append(sentence)
                return
            with open(self.output_file, "a+") as output:
                output.write(sentence+"\n")

#unifier = DataUnifier()

#unifier.unify_full("../data/trimmed/","../data/unified/sentences.txt")


import numpy as np
import gzip
import torch
from torch_geometric.data import Data

def load_mnist_graph(data_size=60000):
    data_list = []
    labels = 0
    with gzip.open('./dataset/train-labels-idx1-ubyte.gz', 'rb') as f:
        labels = np.frombuffer(f.read(), np.uint8, offset=8)

    for i in range(data_size):
        edge = torch.tensor(np.load('./dataset/graphs/'+str(i)+'.npy').T,dtype=torch.long)
        x = torch.tensor(np.load('./dataset/node_features/'+str(i)+'.npy')/28,dtype=torch.float)

        d = Data(x=x, edge_index=edge.contiguous(),t=int(labels[i]))
        data_list.append(d)
        if i%1000 == 999:
            print("\rData loaded "+ str(i+1), end="  ")

    print("Complete!")
    return data_list


"""Celery tasks module"""

from celery import Celery
from core.config import settings
from celery.schedules import crontab

app = Celery(__name__, include=["services.vk.bots_creation.tasks", "services.vk.stat_boost.tasks"])
app.conf.broker_url = settings.CELERY_BROKER_URL
app.conf.result_backend = settings.CELERY_RESULT_BACKEND
app.autodiscover_tasks()

app.conf.beat_schedule = {
    'inspect_bots_at_midnight': {
        'task': 'services.vk.stat_boost.tasks.inspect_bots',
        'schedule': crontab(minute=0, hour=0),
    },
}


import glob
import os
import json
import random
import pickle
import tqdm
import numpy as np

dict_dedede = {'的': 0, '地': 1, '得': 2}

files = []
for file in glob.glob("data/wiki_zh/**", recursive=True):
    if os.path.isdir(file):
        continue
    files.append(file)

np.random.shuffle(files)

# read json files
samples = []
for file in tqdm.tqdm(files[:500]):
    with open(file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            json_data = json.loads(line)
            text = json_data['text']
            for i in range(len(text)):
                if text[i] == '的' or text[i] == '地' or text[i] == '得':
                    if text[i] == '的':
                        l_ = random.randint(1, 15)
                        r_ = random.randint(1, 15)
                        sample = (text[i-l_:i], text[i+1:i+r_],
                                dict_dedede[text[i]])
                        samples.append(sample)
                    elif text[i] == '地':
                        for j in range(random.randint(1, 5)):
                            l_ = random.randint(1, 15)
                            r_ = random.randint(1, 15)
                            sample = (text[i-l_:i], text[i+1:i+r_],
                                    dict_dedede[text[i]])
                            samples.append(sample)
                        for j in range(random.randint(1, 6)):
                            l_ = random.randint(3, 5)
                            r_ = random.randint(3, 5)
                            sample = (text[i-l_:i], text[i+1:i+r_],
                                    dict_dedede[text[i]])
                            samples.append(sample)
                    else:
                        for j in range(random.randint(1, 10)):
                            l_ = random.randint(1, 15)
                            r_ = random.randint(1, 15)
                            sample = (text[i-l_:i], text[i+1:i+r_],
                                    dict_dedede[text[i]])
                            samples.append(sample)
                        for j in range(random.randint(1, 6)):
                            l_ = random.randint(3, 5)
                            r_ = random.randint(3, 5)
                            sample = (text[i-l_:i], text[i+1:i+r_],
                                    dict_dedede[text[i]])
                            samples.append(sample)

print("Total samples: ", len(samples))

的 = 0
地 = 0
得 = 0
for sample in samples:
    if sample[2] == 0:
        的 += 1
    elif sample[2] == 1:
        地 += 1
    else:
        得 += 1

print("的：{}，地：{}，得：{}".format(的, 地, 得))

with open('data/samples/wiki_zh_mini.pkl', 'wb+') as f:
    pickle.dump(samples, f)


def gcd(n1, n2):
	if   n1 == 0:
		return n2
	elif n2 == 0:
		return n1
	x = max(n1, n2)
	y = min(n1, n2)

	return gcd(y, x % y)

if __name__ == '__main__':
	numbers = list(map(int, input().split(' ')[:2]))
	print(gcd(numbers[0], numbers[1]))


'''
A custom logistic regression model for classifying cat and dog images
'''

import numpy as np
import pandas as pd
import matplotlib.pyplot as pyplot
import cv2
import os
from random import shuffle
from PIL import Image
from sklearn.model_selection import train_test_split
from LogisticRegssionImplement import LogisticRegression

train_cat = "catdog/training_set/cats"
test_cat = "catdog/test_set/cats"
train_dog = "catdog/training_set/dogs"
test_dog = "catdog/test_set/dogs"

def prepare_dataset():
    test_data_cat = []
    train_data_cat = []
    test_data_dog = []
    train_data_dog = []
    for img in os.listdir(train_cat):
        path = os.path.join(train_cat, img)
        img1 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img1 = cv2.resize(img1, (128,128))
        train_data_cat.append(img1)
    for img in os.listdir(train_dog):
        path = os.path.join(train_dog, img)
        img1 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img1 = cv2.resize(img1, (128,128))
        train_data_dog.append(img1)
    for img in os.listdir(test_cat):
        path = os.path.join(test_cat, img)
        img1 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img1 = cv2.resize(img1, (128,128))
        test_data_cat.append(img1)
    for img in os.listdir(test_dog):
        path = os.path.join(test_dog, img)
        img1 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img1 = cv2.resize(img1, (128,128))
        test_data_dog.append(img1)
    print(len(train_data_cat),len(test_data_cat),len(train_data_dog),len(test_data_dog))
    train_data = np.concatenate((np.asarray(train_data_cat), np.asarray(train_data_dog)),axis=0)
    test_data = np.concatenate((np.asarray(test_data_cat), np.asarray(test_data_dog)),axis=0)
    x_data = np.concatenate((train_data, test_data), axis=0)
    z1 = np.zeros(4000)
    o1 = np.ones(4005)
    z2 = np.zeros(1011)
    o2 = np.zeros(1012)
    y_data = np.concatenate((z1,o1,z2,o2), axis=0).reshape(x_data.shape[0],1)
    return x_data,y_data

x_data, y_data = prepare_dataset()
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.15, random_state=42)
number_of_train = x_train.shape[0]
number_of_test = x_test.shape[0]
x_train_flatten = x_train.reshape(number_of_train,x_train.shape[1]*x_train.shape[2])
x_test_flatten = x_test .reshape(number_of_test,x_test.shape[1]*x_test.shape[2])
x_train = x_train_flatten.T
x_test = x_test_flatten.T
y_test = y_test.T
y_train = y_train.T

lr = LogisticRegression()
lr.logistic_regression(x_train, y_train, x_test, y_test,learning_rate = 0.01, no_iteration = 100)


class Trie(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.tree = {}

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: None
        """
        cur = 0
        c = self.tree
        while cur < len(word) and word[cur] in c:
            c = c[word[cur]]
            cur += 1

        for i in range(cur, len(word)):
            c[word[i]] = {}
            c = c[word[i]]
        c[0] = 0

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        c = self.tree
        for i in word:
            if i not in c:
                return False
            c = c[i]
        if 0 in c:
            return True
        else:
            return False

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        c = self.tree
        for i in prefix:
            if i not in c:
                return False
            c = c[i]
        return True

t = Trie()
word = 'adasd'
t.insert(word)
print(t.search(word))
print(t.startsWith('ad'))


# --------------------------------------------------------
# Author: James Griffiths
# Date Created: Wednesday, 3rd July 2019
# Version: 1.0
# --------------------------------------------------------
#
# You are going to be given a word. Your job is to return the middle character of the
# word. If the word's length is odd, return the middle character. If the word's length
# is even, return the middle 2 characters.

def get_middle(s):
    # your code here
    wordlen = len(s)
    if wordlen % 2 == 0:
        # is even, so find middle two characters
        middlechar = s[len(s) // 2 - 1] + s[len(s) // 2]

    else:
        # is odd, so find the middle letter
        middlechar = s[len(s) // 2]

    return middlechar

midchar = get_middle(input("Please type in a word: "))
print(midchar)


import shutil
import tempfile

from tasks.forms import TaskCreateForm
from tasks.models import Task
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, override_settings
from django.urls import reverse

# Create a temporary folder for media files
# We'll override the media folder for the test
TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

# We'll use the temporary folder TEMP_MEDIA_ROOT
# for saving media files during the test, and then we'll delete it
@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class TaskCreateFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        # Create a database record to validate the existing slug
        Task.objects.create(
            title='Test title',
            text='Test body',
            slug='first'
        )
        # Create a form if you need to validate the attributes
        cls.form = TaskCreateForm()

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        # shutil is a Python library with useful tools
        # for managing files and directories, including
        # creating, deleting, copying, moving, and editing
        # The shutil.rmtree method deletes the directory and all its content
        shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)

    def setUp(self):
        # Create an unauthorized client
        self.guest_client = Client()

    def test_create_task(self):
        """Valid form creates a record in Task."""
        # Count the number of records in Task
        tasks_count = Task.objects.count()
        # To test image upload,
        small_gif = (
            b'\x47\x49\x46\x38\x39\x61\x01\x00'
            b'\x01\x00\x00\x00\x00\x21\xf9\x04'
            b'\x01\x0a\x00\x01\x00\x2c\x00\x00'
            b'\x00\x00\x01\x00\x01\x00\x00\x02'
            b'\x02\x4c\x01\x00\x3b'
        )
        uploaded = SimpleUploadedFile(
            name='small.gif',
            content=small_gif,
            content_type='image/gif'
        )
        form_data = {
            'title': 'Test title',
            'text': 'Test body',
            'image': uploaded,
        }
        response = self.guest_client.post(
            reverse('tasks:home'),
            data=form_data,
            follow=True
        )
        # Test if the redirect works
        self.assertRedirects(response, reverse('tasks:task_added'))
        # Check if the number of posts increased
        self.assertEqual(Task.objects.count(), tasks_count+1)
        # Check that the record with the specified slug has been created
        self.assertTrue(
            Task.objects.filter(
                slug='testovyij-zagolovok',
                text='Test body',
                image='tasks/small.gif'
                ).exists()
        )

    def test_cant_create_existing_slug(self):
        # Count the number of records in Task
        tasks_count = Task.objects.count()
        form_data = {
            'title': 'Title from the form',
            'text': 'Body from the form',
            'slug': 'first',  # Try to submit a slug already existing in the database
        }
        # Send a POST request
        response = self.guest_client.post(
            reverse('tasks:home'),
            data=form_data,
            follow=True
        )
        # Make sure that the database record was not created
        # Compare the number of records in Task before and after submitting the form
        self.assertEqual(Task.objects.count(), tasks_count)
        # Check that the form returned an appropriate error:
        # take the 'form' dictionary from the response object
        # and specify the expected error for the 'slug' field of this dictionary
        self.assertFormError(
            response,
            'form',
            'slug',
            'Slug "first" already exists, enter a unique slug'
        )
        # Check that the site didn't crash and that the page returns a 200 status code
        self.assertEqual(response.status_code, 200)

    # If you haven't tested the contents of labels in models
    # or redefined them when creating the form - we test like this:
    def test_title_label(self):
        title_label = TaskCreateFormTests.form.fields['title'].label
        self.assertEqual(title_label, 'Title')

    def test_title_help_text(self):
        title_help_text = TaskCreateFormTests.form.fields['title'].help_text
        self.assertEqual(title_help_text, 'Enter task name')


import json

import py_html.core as html
import py_latex.core as latex
from flask import (
    Blueprint,
    Response,
    redirect,
    render_template,
    request,
    session,
    url_for,
)
from pdflatex import PDFLaTeX

blueprint = Blueprint("blueprint", __name__)
from . import models

docuemntclass = models.DocumentClass()
config = models.Config()
personal_settings = models.PersonalSettings()
cvtitle = models.CvTitle()
# documentclass = core.latexCommand(
#    command="documentclass",
#    args={"docclass": "moderncv"},
#    opt_args={"args": "10pt,a4paper,sans"},
# )
packages = models.Packages(
    packages=[
        latex.usepackage(package="multicol"),
        latex.usepackage(package="geometry", scale="scale=0.75"),
        latex.usepackage(package="xcolor"),
        latex.usepackage(package="draftwatermark", opt=""),
        latex.latexCommand(
            command="SetWatermarkText", args={"Text": "Design Andreas Rabenstein"}
        ),
        latex.latexCommand(command="SetWatermarkScale", args={"Scale": 0.4}),
        latex.latexCommand(command="SetWatermarkColor", args={"color": "red!30"}),
    ]
)
# document = core.latexEnv(command="document", children=["asdf"])
document = models.Document()
document.add_content(models.section(title="First title"))

page = models.LatexDocument(
    documentclass=docuemntclass,
    config=config,
    packages=packages,
    personalsettings=personal_settings,
    document=document,
    cvtitle=cvtitle,
)

@blueprint.route("/update/<part>", methods=["POST", "GET"])
def updateSetting(part):
    if request.form:
        print("UPDATING ", part)
        getattr(page, part).from_dict(dict(request.form))
        return redirect(request.referrer)

@blueprint.route("/add_multicolumn/<document_element>")
def add_multi_elem(document_element):
    document.content[int(document_element)].add_field()
    return redirect(request.referrer)

@blueprint.route("/add_element/<type>/<position>")
def add_element(type, position):
    document.add_content(type, position=int(position))

    return redirect(request.referrer)

@blueprint.route("/mv_element/<orig_pos>/<new_pos>")
def mv_element(orig_pos, new_pos):
    document.swap_content(int(orig_pos), int(new_pos))
    return redirect(request.referrer)

@blueprint.route("/", methods=["POST", "GET"])
def index():
    if request.form:
        print("AM I EVER HERE?")
        raise ValueError("IM AM HERE")
        document.from_dict(dict(request.form))
    body = page.to_html()

    body += html.div(
        className=" d-flex flex-row-reverse",
        style="justify-content-right; margin-top:10px;",
        children=[
            html.div(
                className="dropdown show",
                children=[
                    html.a(
                        className="btn btn-secondary dropdown-toggle",
                        href="#",
                        children="Download",
                        data_toggle="dropdown",
                        aria_haspopup="true",
                        aria_expanded="false",
                    ),
                    html.div(
                        className="dropdown-menu",
                        children=[
                            html.a(
                                className="dropdown-item",
                                href=url_for("blueprint.download", type="pdf"),
                                children="pdf",
                            ),
                            html.a(
                                className="dropdown-item",
                                href=url_for("blueprint.download", type="json"),
                                children="json",
                            ),
                            html.a(
                                className="dropdown-item",
                                href=url_for("blueprint.download", type="tex"),
                                children="tex",
                            ),
                        ],
                    ),
                ],
            ),
            html.a(
                className="btn btn-secondary",
                style="margin-right:10px;",
                children="Upload",
                href=url_for("blueprint.upload"),
            ),
        ],
    ).__str__()

    lat = (
        page.to_latex().replace("\n", "
").replace("\t", "    ")
    )
    return render_template("main.html", body=body, latex=lat)

@blueprint.route("/download/<type>")
def download(type):
    if type == "pdf":
        main = page.to_latex()
        pdfl = PDFLaTeX.from_binarystring(main.encode("utf-8"), jobname="test")
        ret_file, _, _ = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)
    elif type == "json":
        ret_file = json.dumps(page.to_dict(), indent=4)
    elif type == "tex":
        ret_file = page.to_latex()
    return Response(
        ret_file,
        mimetype=f"text/{type}",
        headers={"Content-disposition": f"attachment; filename=mcv.{type}"},
    )

def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ["json"]

@blueprint.route("/upload", methods=["GET", "POST"])
def upload():
    if request.method == "POST":
        # check if the post request has the file part
        if "file" not in request.files:
            return redirect(request.referrer)
        file = request.files["file"]
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == "":
            return redirect(request.referrer)
        if file and allowed_file(file.filename):
            dictionary = json.loads(file.read())
            page.from_dict(dictionary)
            return redirect(url_for("blueprint.index"))
    return """
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    """


import pygame

pygame.init()
pygame.display.set_caption("GAME")
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
#Height and width of the window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

player = pygame.Rect((300, 250, 50, 50))
#Assign a rectangle to the variable x=300 y=250 width = 50 height=50

import pygame
import random
pygame.init()
pygame.display.set_caption("GAME")
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
#Height and width of the window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

spaceship = pygame.image.load("spaceship_yellow.png").convert_alpha()

player = pygame.Rect((300, 250, 50, 50))
obstacle_rect = pygame.Rect(random.randint(0,500), random.randint(0, 300), 25, 25)

rect_1 = pygame.Rect(0,0, 150,100)
#rect_1.width = 400
#rect_1.height = 200
rect_2 = spaceship
rect_2 = spaceship.get_rect()
rect_2.topleft = (200,200)

#Assign a rectangle to the variable x=300 y=250 width = 50 height=50

clock = pygame.time.Clock()

run = True
while run:

    clock.tick(60)
    screen.fill((255, 255, 255))

    #draws the rectangle
    pygame.draw.rect(screen, (122,34,56),obstacle_rect)

    screen.blit(spaceship, rect_2)

    key = pygame.key.get_pressed()
    if key[pygame.K_a] == True:
        rect_2.x -=5
    elif key[pygame.K_d] == True:
        rect_2.x +=5
    elif key[pygame.K_s] == True:
        rect_2.y +=5
    elif key[pygame.K_w] == True:
        rect_2.y -=5

    #when a certain key is pressed the player moves

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pygame.display.update()

pygame.quit()


"""
Functions used to run multiple SingleCellFusion steps at once

Below code was written/developed by Fangming Xie, Ethan Armand, and Wayne Doyle

(C) 2019 Mukamel Lab GPLv2
"""

import logging
from . import features
from . import imputation
from . import integration
from . import utils

# Start log
wrap_log = logging.getLogger(__name__)

def fuse_data(loom_source,
              loom_target,
              correlation,
              loom_output='integrated.loom',
              layer_source='',
              layer_target='',
              layer_impute='imputed',
              feat_source='Accession',
              feat_target='Accession',
              cell_source='CellID',
              cell_target='CellID',
              cluster_source='ClusterID',
              cluster_target='ClusterID',
              pca_target=None,
              valid_ra_source=None,
              valid_ra_target=None,
              valid_ca_source=None,
              valid_ca_target=None,
              label_source=None,
              label_target=None,
              var_method='kruskal',
              common_attr='CommonVariable',
              variable_attr='VariableFeatures',
              kruskal_n=8000,
              var_percentile=30,
              neighbor_method='knn',
              n_neighbors=20,
              relaxation=10,
              speed_factor=10,
              n_trees=10,
              remove_version=False,
              low_mem=False,
              batch_size=5000,
              tmp_dir=None,
              seed=23,
              verbose=True):
    """
    Wrapper for running all steps of SingleCellFusion. Finds common variable features, imputes data, and integrates.

    Args:
        loom_source (str): Path to loom file that will provide counts to others
        loom_target (str/list): Path(s) to loom files that will receive imputed counts
        correlation (str/list): Expected correlation between loom_source and loom_target
            positive/+ for RNA-seq and ATAC-seq
            negative/- for RNA-seq or ATAC-seq and snmC-seq
        loom_output (str): Path to output loom file that contains observed/imputed counts for a given modality
        layer_source (str): Layer in loom_source containing observed counts
        layer_target (str/list): Layer(s) in loom_target containing imputed counts
        layer_impute (str/list): Output layer in loom_target
            A row attribute with the format Valid_{layer_out} will be added
            A col attribute with the format Valid_{layer_out} will be added
        feat_source (str): Row attribute specifying unique feature names in loom_source
        feat_target (str/list): Row attribute(s) specifying unique feature names in loom_target
        cell_source (str): Column attribute containing unique cell IDs in loom_source
            IDs will be included in loom_output under the column attribute CellID
        cell_target (str/list): Column attribute(s) containing unique cell IDs in loom_target
        cluster_source (str/list/None): Column attribute(s) specifying cluster assignments for each cell in loom_source
            Necessary if the kruskal method is used
        cluster_target (str/list/None): Column attribute(s) specifying cluster assignments for each cell in loom_target
            Necessary if the kruskal method is used
        pca_target (str/list/None): Column attribute containing PCs in loom_target
            Used if neighbor_method is mnn_rescue
        valid_ra_source (str): Row attribute specifying valid features in loom_source
            Should point to a boolean array
        valid_ra_target (str/list): Row attribute(s) specifying valid features in loom_target
            Should point to a boolean array
        valid_ca_source (str): Column attribute specifying valid cells in loom_source
            Should point to a boolean array
        valid_ca_target (str/list): Column attribute(s) specifying valid cells in loom_target
            Should point to a boolean array
        label_source (str/None): Optional, labels to be added to cells from loom_source
            Will be saved in the column attribute Modality
            If provided, label_target must also be provided
        label_target (str/list/None): Optional, labels to be added to cells from loom_target
        var_method (str): Method for finding variable genes
            vmr: variance mean ratio (found in deciles)
            sd: standard deviation (found in deciles)
            kruskal: Kruskal-Wallis test (recommended)
        common_attr (str): Output row attribute which will specify valid common features
        variable_attr (str/None): Output row attribute which will specify valid, variable features
            Only used if method is sd or vmr
            If method is kruskal the following row attributes will automatically be added
                 kruskal_H: H statistic from Kruskal-Wallis test
                 kruskal_pval: p-value from Kruskal-Wallis test
                 kruskal_max_cluster_pct: Percentage of cells with non-zero counts in clusters
                    Percent is from the cluster that has the largest number of non-zero counts
                 kruskal_cluster_attr: Cluster attribute used for performing Kruskal-Wallis test
        kruskal_n (int/None): Use the top kruskal_n number of genes from each loom file to find common features
            Only used if method is kruskal
        var_percentile (int): Whole number (0-100) percent of variable genes to select per decile of expression
            Only used if method is sd or vmr
        neighbor_method (str): Method for performing imputation
                knn: constrained knn
                mnn_direct: mutual nearest neighbors with rescue of cells (can only be done if low_mem = False)
                mnn_rescue: mutual nearest neighbors with cells that made direct neighbors (only if low_mem = False)
        n_neighbors (int/list): Minimum amount of neighbors that can be made
        relaxation (int/list): Relax search for constrained kNN by this factor
            Increases the number of neighbors that a source cell can make before saturation
            Only used if method is knn
        speed_factor (int/list): Speed up search of constrained kNN by this factor
            Will increase memory but decrease running time
            Only used if method is knn
        n_trees (int): Number of trees for approximate kNN search
            See Annoy documentation
        remove_version (bool/list): If true remove version number
            Anything after the first period is dropped (useful for GENCODE IDs)
            If a list, will behave differently for each loom file
            If a boolean, will behave the same for each loom_file
        low_mem (bool): If true, performs imputation in a slow but less memory-intensive manner
        batch_size (int): Chunk size for batches, used if low_mem
            Higher values mean faster code, but more memory
        tmp_dir (str): Path to directory for temporary files
            If None, uses system defaults
        seed (int): Seed for randomization
        verbose (bool): Print logging messages
    """
    # Check low_mem flags for unsupported options so user does not run code that they do not need to
    if not low_mem:
        if neighbor_method == 'mnn_rescue':
            raise ValueError('mnn_rescue can only be performed if low_mem is true')
        elif neighbor_method == 'mnn_direct':
            raise ValueError('mnn_direct can only be performed if low_mem is true')
    # Check inputs
    is_a_list = False
    if isinstance(loom_target, list):
        utils.all_same_type_size(parameters=[loom_target,
                                             layer_target,
                                             correlation],
                                 expected_type='list',
                                 confirm_size=True)
        check_parameters = [feat_target,
                            cell_target,
                            valid_ra_target,
                            valid_ca_target,
                            remove_version,
                            label_target,
                            layer_impute,
                            pca_target]
        checked = utils.mimic_list(parameters=check_parameters,
                                   list_len=len(loom_target))
        feat_target = checked[0]
        cell_target = checked[1]
        valid_ra_target = checked[2]
        valid_ca_target = checked[3]
        remove_version = checked[4]
        label_target = checked[5]
        layer_impute = checked[6]
        pca_target = checked[7]
        is_a_list = True
    elif isinstance(loom_target, str):
        utils.all_same_type_size(parameters=[loom_target,
                                             layer_target,
                                             correlation,
                                             feat_target,
                                             cell_target],
                                 expected_type='str',
                                 confirm_size=False)

    # Prep for finding common features
    if is_a_list:
        loom_files = loom_target.copy()
        layers = layer_target.copy()
        cell_attrs = cell_target.copy()
        feat_attrs = feat_target.copy()
        cluster_attrs = cluster_target.copy()
        valid_ras = valid_ra_target.copy()
        valid_cas = valid_ca_target.copy()
    else:
        loom_files = [loom_target]
        layers = [layer_target]
        cell_attrs = [cell_target]
        feat_attrs = [feat_target]
        cluster_attrs = [cluster_target]
        valid_ras = [valid_ra_target]
        valid_cas = [valid_ca_target]
    loom_files.append(loom_source)
    layers.append(layer_source)
    cell_attrs.append(cell_source)
    feat_attrs.append(feat_source)
    cluster_attrs.append(cluster_source)
    valid_ras.append(valid_ra_source)
    valid_cas.append(valid_ca_source)
    # Find common features
    features.find_common_variable(loom_files=loom_files,
                                  layers=layers,
                                  method=var_method,
                                  cell_attrs=cell_attrs,
                                  feat_attrs=feat_attrs,
                                  cluster_attrs=cluster_attrs,
                                  common_attr=common_attr,
                                  variable_attr=variable_attr,
                                  valid_ras=valid_ras,
                                  valid_cas=valid_cas,
                                  kruskal_n=kruskal_n,
                                  percentile=var_percentile,
                                  low_mem=low_mem,
                                  batch_size=batch_size,
                                  remove_version=remove_version,
                                  verbose=verbose)

    # Impute data
    imputation.perform_imputation(loom_source=loom_source,
                                  loom_target=loom_target,
                                  method=neighbor_method,
                                  layer_source=layer_source,
                                  layer_target=layer_target,
                                  layer_impute=layer_impute,
                                  correlation=correlation,
                                  feat_source=feat_source,
                                  feat_target=feat_target,
                                  cell_source=cell_source,
                                  cell_target=cell_target,
                                  pca_target=pca_target,
                                  valid_ra_source=common_attr,
                                  valid_ra_target=common_attr,
                                  valid_ca_source=valid_ca_source,
                                  valid_ca_target=valid_ca_target,
                                  n_neighbors=n_neighbors,
                                  relaxation=relaxation,
                                  speed_factor=speed_factor,
                                  n_trees=n_trees,
                                  remove_version=remove_version,
                                  low_mem=low_mem,
                                  batch_size=batch_size,
                                  tmp_dir=tmp_dir,
                                  seed=seed,
                                  verbose=verbose)
    # Integrate data
    integration.integrate_data(loom_source=loom_source,
                               loom_target=loom_target,
                               loom_output=loom_output,
                               layer_source=layer_source,
                               layer_target=layer_impute,
                               feat_source=feat_source,
                               feat_target=feat_target,
                               cell_source=cell_source,
                               cell_target=cell_target,
                               label_source=label_source,
                               label_target=label_target,
                               valid_ra_source=common_attr,
                               valid_ra_target=common_attr,
                               valid_ca_source=valid_ca_source,
                               valid_ca_target=valid_ca_target,
                               remove_version=remove_version,
                               low_mem=low_mem,
                               batch_size=batch_size,
                               verbose=verbose)


import digitalio
import busio
import board
from adafruit_epd.ssd1675 import Adafruit_SSD1675
from adafruit_epd.ssd1680 import Adafruit_SSD1680
from adafruit_epd.epd import Adafruit_EPD
from PIL import Image, ImageDraw, ImageFont

def load_screen():
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    ecs = digitalio.DigitalInOut(board.CE0)
    dc = digitalio.DigitalInOut(board.D22)
    rst = digitalio.DigitalInOut(board.D27)
    busy = digitalio.DigitalInOut(board.D17)

    display = Adafruit_SSD1680(  # Newer eInk Bonnet
        # display = Adafruit_SSD1675(   # Older eInk Bonnet
        122, 250, spi, cs_pin=ecs, dc_pin=dc, sramcs_pin=None, rst_pin=rst, busy_pin=busy)

    display.rotation = 1

    return display

def load_fonts():
    small_font = ImageFont.truetype(
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16
    )
    medium_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20)
    large_font = ImageFont.truetype(
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 24
    )
    icon_font = ImageFont.truetype("./meteocons.ttf", 48)

    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    return small_font, medium_font, large_font, icon_font, WHITE, BLACK

def draw_text(draw, width, height, font, text, fill):
    font_width, font_height = font.getsize(text)
    print(font_width, font_height)
    draw.text((
        width // 2 - font_width // 2,
        height // 2 - font_height // 2
    ), text, font=font, fill=fill)

def run_display(display, value):
    pass

def refresh_screen(display):
    display.fill(Adafruit_EPD.WHITE)
    display.display()

def main():
    display = load_screen()
    width = display.width
    height = display.height
    small_font, medium_font, large_font, icon_font, WHITE, BLACK = load_fonts()
    refresh_screen(display)
    image = Image.new("RGB", (width, height), color=BLACK)
    draw = ImageDraw.Draw(image)
    im_1 = draw_text(draw, width, height, small_font, "HELLO", BLACK)

    #display.image(im_1)
    display.display()

if __name__ == '__main__':
    main()


"""
    📌 Напишите декоратор, который сохраняет в json файл
    параметры декорируемой функции и результат, который она
    возвращает. При повторном вызове файл должен
    расширяться, а не перезаписываться.
    📌 Каждый ключевой параметр сохраните как отдельный ключ
    json словаря.
    📌 Для декорирования напишите функцию, которая может
    принимать как позиционные, так и ключевые аргументы.
    📌 Имя файла должно совпадать с именем декорируемой
    функции.
"""
import json
import os
from typing import Callable

def add_params_to_json( func:Callable )-> Callable[[], None ]:
    def wrapper(*args,**kwargs):
        file_path = f'{func.__name__}.json'
        data = []
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as json_file:
                data = json.load(json_file)
        curr_data = {
            'args': args,
            **kwargs
        }
        result = func(*args,**kwargs)
        curr_data['result'] = result
        data.append(curr_data)
        with open(file_path, 'w', encoding='utf-8') as json_file:
            json.dump(data, json_file, indent=2, ensure_ascii = False)
        return result
    return wrapper

@add_params_to_json
def sum_nums(*args, **kwargs)->int:
    return sum(args)

@add_params_to_json
def concat_str(*args, **kwargs)->str:
    return ''.join(args)

if __name__ == '__main__':
    sum_nums(1,2,3, x=5,y=6,z=7)
    concat_str('aa','b','cccc', word='test')


import sys
sys.stdin = open("11718in.txt")

# 초기화와 반복문의 위치를 조건에 따라 잘 설정해줘야한다..!

def catch(r, c):
    cnt = 0 # 토끼의 개수를 누적할 변수
    for k in range(8): # 8방향 탐색
        nr = r  # 방향 전환되면 원래 위치로 돌아와서 탐색해야한다
        nc = c
        for u in range(N-1): # 최대 탐색 범위가 N-1까지의 범위라고 생각해서 이렇게 증가시켰는데... 그냥 계속 증가하는 수로 설정하고 인덱스 벗어나면 빠져나오게도 설정할 수 있는듯..?
            nr += dr[k] # 설정 방법에 따라 기준위치에서 곱셈 이동하게도 가능..?
            nc += dc[k]
        # 델타로 이동한 위치의 범위 체크
            if 0 <= nr < N and 0 <= nc < N and ARR[nr][nc] != 0: # 범위 안벗어나면
                if ARR[nr][nc] == "2": # 토끼면  # 테스트케이스 상 사냥꾼이 같은 토끼를 잡는 경우는 없으므로 그대로 둬도 무방
                    cnt += 1 # 카운트를 증가시켜라
                elif ARR[nr][nc] == "3": # 바위면
                    break # 해당방향 이동 중지
                # elif ARR[nr][nc] == "1": # 사냥꾼이면 # 테스트케이스상 사냥꾼이 사냥꾼을 사격할 수 있는 케이스는 없는듯..?
                #     break # 해당 방향 이동 중지
            else: # 범위 벗어나면 반복문 종료 # 벗어나도 위에 조건문에 의해 탐색은 안하긴 함..
                break
    return cnt

def hunt():
    totalCnt = 0
    for i in range(N):
        for j in range(N):
            if ARR[i][j] == '1': # 사냥꾼이면
                totalCnt += catch(i, j)
    return totalCnt # 반복문 다 돌면 함수 종료

# 8방향 델타
dr = [0, 0, 1, -1, 1, 1, -1, -1]
dc = [1, -1, 0, 0, 1, -1, 1, -1]

T = int(input())

for tc in range(1, T+1):
    # N X N 배열
    N = int(input())

    ARR = [list(input().split()) for _ in range(N)]

    result = hunt()

    print(f'#{tc} {result}')


from collections import deque
import sys
input = sys.stdin.readline

N = int(input())

deq = deque()

def solve(command):
    if command == 'pop_front':
        if deq:
            return deq.popleft()
        else:
            return -1
    elif command == 'pop_back':
        if deq:
            return deq.pop()
        else:
            return -1
    elif command == 'size':
        return len(deq)
    elif command == 'empty':
        if deq:
            return 0
        else:
            return 1
    elif command == 'front':
        if deq:
            return deq[0]
        else:
            return -1
    elif command == 'back':
        if deq:
            return deq[-1]
        else:
            return -1
    elif command.split()[0] == 'push_front':
        deq.appendleft(command.split()[1])
        return
    elif command.split()[0] == 'push_back':
        deq.append(command.split()[1])
        return

for _ in range(N):
    result = solve(input().rstrip())
    if result != None:
        print(result)


import matlab.engine
eng = matlab.engine.start_matlab()

src = 'Z:\sstcre_imaging'
mouse = "e201"
day = "1"
imgfl = [os.path.join(src, mouse, day, xx) for xx in os.listdir(os.path.join(src, mouse, day)) if "000" in xx]
pth = 'Z:\sstcre_analysis\Fall.mat'
eng.format_conversion_Suite2p_CNMF_e(pth,nargout=0)

fmatfl='Z:/sstcre_analysis/fmats/e200_week1/e200_day001_Fall.mat'
vrfl='Z:/sstcre_imaging\e200/3/behavior/vr\E200_16_Feb_2023_time(07_26_44).mat'
savepth = eng.VRalign(fmatfl,vrfl,nargout=1)


import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
from wordcloud import WordCloud, STOPWORDS
import numpy as np

#title
st.title('Tweet Sentiment Analysis')
#markdown
#st.markdown('This application is all about tweet sentiment analysis of airlines. We can analyse reviews of the passengers using this streamlit app.')
#sidebar
st.sidebar.title('AnÃ¡lise de Sentimedos das companhias aÃ©reas')
# sidebar markdown
st.sidebar.markdown("ðŸ›«Nesta apresentaÃ§Ã£o serÃ¡ feita uma anÃ¡lise das reviews dos passageiros de companhias aÃ©reas americanas.ðŸ›«")
#loading the data (the csv file is in the same folder)
#if the file is stored the copy the path and paste in read_csv method.
data=pd.read_csv('tweet.csv')
#checkbox to show data
if st.checkbox("Mostrar tabela"):
    st.write(data.head(50))
#subheader
st.sidebar.subheader('Analisador de Tweets')
#radio buttons
tweets=st.sidebar.radio('tipo de sentimento',('positive','negative','neutral'))
st.write(data.query('airline_sentiment==@tweets')[['text']].sample(1).iat[0,0])
st.write(data.query('airline_sentiment==@tweets')[['text']].sample(1).iat[0,0])
st.write(data.query('airline_sentiment==@tweets')[['text']].sample(1).iat[0,0])
#selectbox + visualisation
# An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content.
## Multiple widgets of the same type may not share the same key.
select=st.sidebar.selectbox('VisualizaÃ§Ã£o dos tweets',['Histogram','Pie Chart'],key=1)
sentiment=data['airline_sentiment'].value_counts()
sentiment=pd.DataFrame({'Sentiment':sentiment.index,'Tweets':sentiment.values})
st.markdown("###  Sentimentos em relaÃ§Ã£o Ã s empresas")
if select == "Histogram":
        fig = px.bar(sentiment, x='Sentiment', y='Tweets', color = 'Tweets', height= 500)
        st.plotly_chart(fig)
else:
        fig = px.pie(sentiment, values='Tweets', names='Sentiment')
        st.plotly_chart(fig)

#slider
st.sidebar.markdown('Hora e local dos tweets')
hr = st.sidebar.slider("Hora do Dia", 0, 23)
data['Date'] = pd.to_datetime(data['tweet_created'])
hr_data = data[data['Date'].dt.hour == hr]
if not st.sidebar.checkbox("Hide", True, key='2'):
    st.markdown("### Location of the tweets based on the hour of the day")
    st.markdown("%i tweets during  %i:00 and %i:00" % (len(hr_data), hr, (hr+1)%24))
    st.map(hr_data)

#multiselect
st.sidebar.subheader("Sentimento dos tweets em relaÃ§Ã£o a cada companhia")
choice = st.sidebar.multiselect("Airlines", ('US Airways', 'United', 'American', 'Southwest', 'Delta', 'Virgin America'), key = '0')
if len(choice)>0:
    air_data=data[data.airline.isin(choice)]
    # facet_col = 'airline_sentiment'
    fig1 = px.histogram(air_data, x='airline', y='airline_sentiment', histfunc='count', color='airline_sentiment',labels={'airline_sentiment':'tweets'}, height=600, width=800)
    st.plotly_chart(fig1)


# Tuple is a collection which is ordered and unchanegable. Allows duplicate members

#Create tuple

fruits = ('Apples', 'Oranges', 'Grapes')
# fruits2 = tuple(('Apples', 'Oranges', 'Grapes'))

#Single value need a trailing comma
fruits2 = ('Apples',)

#Delte tuple
del fruits2

# print(len(fruits2))

# fruits[0] = 'Pears'

# A set is a collection which is unordered and unindexed. No duplicate members

# Create set

fruits_set = {'Apples', 'Oranges', 'Mango'}

# Check if in a set
print('Apples' in fruits_set)

#Add to set
fruits_set.add('Grape')

#Remove from set
# fruits_set.remove("Grape")

# #Clear set
# fruits_set.clear()

#Add duplicate
fruits_set.add('Apples')

print(fruits_set)


import L1_ina as VR
import L1_log as Log
import time

def getVoltagetoLog():
    Voltage_Reader = VR.readVolts()
    Vol_to_Log = Log.tmpFile(Voltage_Reader, "SV")
    return
if __name__ == "__main__":
    while True:
        getVoltagetoLog()
        time.sleep(1)


"""

"""

## source.python imports

from menus import PagedMenu, PagedOption, Text

## warcraft.package imports

from .main import main_menu
from ..players import player_dict
from ..translations import spendskills_menu_strings

## __all__ declaration

__all__ = ("spend_skills_menu", )

## callback declarations

def _on_spend_skills_build(menu, index):
    player = player_dict[index]
    menu.clear()
    menu.description = spendskills_menu_strings['description'].get_string(
        amount=player.race.unused_points)
    for skill in player.race.skills:
        selectable = (skill.level < skill.max_level) and skill.is_available(player)
        menu.append(
            PagedOption(
                spendskills_menu_strings['skill'].get_string(name=skill.name,
                    level=skill.level, max_level=skill.max_level),
                skill,
                highlight=selectable,
                selectable=selectable
            )
        )
    menu.append(Text(' '))
    menu.append(
        PagedOption(
            spendskills_menu_strings['reset'].get_string(),
            None,
            selectable=True
        )
    )

def _on_spend_skills_select(menu, index, choice):
    player = player_dict[index]
    skill = choice.value
    if not skill:
        ## Reset Skills
        for race_skill in player.race.skills:
            race_skill.level = race_skill.min_level
    elif player.race.unused_points and skill.level < skill.max_level:
        ## Increment Skill by 1
        skill.level_up(1)
    if player.race.unused_points > 0:
        ## Repeat menu...
        return menu

## menu declarations

spend_skills_menu = PagedMenu(
    title=spendskills_menu_strings['header'],
    build_callback=_on_spend_skills_build,
    select_callback=_on_spend_skills_select,
    parent_menu=main_menu,
)


from entities.entity import Entity
from entities.gui import buttons
from displays.levels.level import LevelComponent
import constants as C
import pygame
from entities.gui import overlays
class EndRoundMenu(LevelComponent):
    fadeSpeed = 5
    def __init__(self):
        screen = C.GAME.SCREEN.get_rect()

        # Buttons
        playAgain = buttons.PlayAgainButton()
        super().__init__((screen.width*.4,screen.height*.4),entities=[])

        self.rect.centerx = screen.centerx
        self.rect.centery = screen.centery

        playAgain.rect.centerx = self.rect.width *.5
        playAgain.rect.centery = self.rect.height *.5
        playAgain.abs_pos = (self.rect.x+playAgain.rect.x,
                             self.rect.y+playAgain.rect.y)
        self.entities.append(playAgain)

        # Main Menu Button
        menu = buttons.MainMenuButton()
        menu.rect.centerx = self.rect.width *.5
        menu.rect.centery = self.rect.height *.7
        menu.abs_pos = (self.rect.x+menu.rect.x,
                             self.rect.y+menu.rect.y)
        self.entities.append(menu)


import json

pre_result = []
with open("ingredients.json", "r", encoding='utf-8') as read_file:
    data = json.load(read_file)
    i = 1
    for item in data:
        pre_item = dict()
        pre_item['model'] = 'api.ingredient'
        pre_item['pk'] = i
        pre_item['field'] = {
            'name': item['name'],
            'measurement_unit': item['measurement_unit']
        }
        pre_result.append(pre_item)
        i += 1

with open("../backend/ingredients_data.json", "w",
          encoding='utf-8') as write_file:
    json.dump(pre_result, write_file, indent=4, ensure_ascii=False)


#!/usr/bin/env python3
import time
import os
import importlib
import re
import datetime
from multiprocessing import Process, Queue
from classes.arguments import *
from classes.fix_go import Go_Fixer
from classes.gaf_parser import gaf_parse
from classes.Evaluator import Evaluator
from classes.plotter import Plotter
from classes.Dict2Array import Dict2Array
from classes.filter_gaf import filter_gaf
from classes.splitter import split
from classes.lsdr import PLST as PLST_class
from classes.call_PLST import call_PLST
from classes.train_matrix import train_matrix

class thread_print:
    def __init__(self):
        self.q = Queue()

    def print(self, toprint):
        self.q.put(toprint)

    def display(self):
        if self.q.qsize() > 0:
            print(self.q.get())

class tprint:
    def print(self, toprint):
        print(toprint)

def step(requests, results, predictor, testdata, traindata, testclass_array,
         trainclass, arraymaker, gofixer, gofix, evaluators, t, plst):
    while requests.qsize() > 0:
        #t.print("START")
        fraction = requests.get()
        sample = split(trainclass, fraction)
        train = train_matrix()
        matrix, go_index_reverse, rat_index = train.convert(gaf_parse(sample))
        #t.print("AFTER TRAIN CONVERT")
        if plst > 0:
            #t.print("STARTING a.train")
            a = call_PLST()
            matrix = a.train(matrix, plst, PLST_class)
            #t.print("RAN a.train")
        #t.print("STARTING PREDICTION")
        matrix, rat_index = predictor.get_predictions(testdata, matrix, rat_index)
        if plst > 0:
            #t.print("STARTING a.inverse")
            matrix = a.inverse(matrix)
            del a
            #t.print("RAN a.inverse")
        #t.print("STARTING backconvert")
        predictions = train.back_convert(matrix, rat_index, go_index_reverse, predictor.get_train())
        del matrix, rat_index, go_index_reverse, train
        #t.print("STARTING GOFIX")
        if gofix:
            pred_array = arraymaker.make_array(predictions, gofixer.fix_go, predictor.get_dtype(), t)
        else:
            pred_array = arraymaker.make_array(predictions,
                                               gofixer.replace_obsolete_terms, predictor.get_dtype(), t)
        #t.print("STARTING EVAL")
        evaluator = Evaluator(testclass_array, pred_array, evaluators)

        evaluation = evaluator.get_evaluation()
        results.put((fraction, evaluation))

def main():
    title, multargs = get_args()
    plotter = Plotter()
    methodlist = []
    plotconfig = []
    number = 0
    extrastring = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    file = open(title + extrastring,"w")
    file.write("title: " + title + "\n")
    for legend in multargs:
        if len(multargs) > 1:
            print("\nRUN:", legend)

        methodlist.append(legend)
        args = multargs[legend]
        plotconfig.append((args["color"], args["linetype"]))
        #print(plotconfig)
        argname = re.split('/|\.', args["predictor"])[-2]
        modname = args["predictor"].split(".")[0].replace("/", ".")
        print("Using predictor:", modname)
        Predictor = importlib.import_module(modname).Predictor
        gofix = not "nogofix" in args
        threads = args["threads"]
        if threads == "*":
            threads = os.sysconf("SC_NPROCESSORS_ONLN")
        print("Using %s threads"%threads)

        print("Loading input files")
        testclass_file = open(args["testgaf"], "r")
        trainclass_file = open(args["traingaf"], "r")
        traindata_file = open(args["traindata"], "r")
        testdata_file = open(args["testdata"], "r")
        testclass = testclass_file.readlines()
        trainclass = trainclass_file.readlines()
        traindata = traindata_file.readlines()
        testdata = testdata_file.readlines()
        testclass_file.close()
        trainclass_file.close()
        traindata_file.close()
        testdata_file.close()

        t = tprint()

        print("Parsing annotation")
        testclass = gaf_parse(filter_gaf(testclass, args["evidence"],
                                         args["domain"]))
        trainclass = filter_gaf(trainclass, args["evidence"], args["domain"])

        print("Reading GO-tree")
        gofixer = Go_Fixer("files/go-basic.obo")

        print("Indexing all GO-terms")
        allterms = []
        for terms in list(gaf_parse(trainclass).values()) + \
            list(testclass.values()):
            if gofix:
                terms = gofixer.fix_go(terms, t)
            allterms.extend(terms)
        if "predargs" in args:
            predictor = Predictor(traindata, args["predargs"])
        else:
            predictor = Predictor(traindata, None)
        arraymaker = Dict2Array(allterms, testclass)

        if gofix:
            testclass_array = arraymaker.make_array(testclass, gofixer.fix_go, bool, t)
        else:
            testclass_array = arraymaker.make_array(testclass,
                                                gofixer.replace_obsolete_terms, bool, t)

        print("\nSTARTING")
        requests = Queue()
        for fraction in range(100, 0, -args["stepsize"]):
            for r in range(0, args["repeats"]):
                requests.put(fraction)

        total = requests.qsize()
        processes = []
        results = Queue()
        t = thread_print()
        done = 0

        print("Progress: 0%")
        for x in range(threads):
            p = Process(target = step, args = (requests, results, predictor,
                                               testdata, traindata,
                                               testclass_array, trainclass,
                                               arraymaker, gofixer, gofix,
                                               args["evaluator"], t, args["plst"]))
            p.start()
            processes.append(p)
        file.write("legend: " + legend + "\nlinetype: " +
                   args["linetype"] + "\ncolor: " + args["color"] + "\n" )
        file.write("fraction\tmetric\tresult\n")
        reslist = []
        while total - done > 0:
            t.display()
            if results.qsize() > 0:
                r = results.get()
                done += 1
                print("Progress:", str(round(100 - (total - done)
                                             / total * 100)) + "%")
                reslist.append(r)
            time.sleep(0.1)
        for r in sorted(reslist, key=lambda x: x[0]):
            for metric, evaluation in r[1].items():
                print("Fraction:", r[0], "Metric:", metric, "Evaluation:",
                      evaluation)
                file.write(str(r[0]) + "\t" + str(metric) + "\t" + str(evaluation) + ";\t")
            plotter.add_score(r[0], r[1])
            file.write("\n")
    file.close()

    plotter.plot_performance(title, methodlist, plotconfig, extrastring)

main()


# -*- coding: utf-8 -*-
from flask import *
from heapq import heappush, heappop
import heapq
import querysearch

app = Flask(__name__)

temp_query = ""

@app.route("/")
def search():
    return render_template('page_query.html')

@app.route("/results", defaults={'page': 1}, methods=['GET','POST'])
@app.route("/results/<page>", methods=['GET','POST'])
def results(page):
    global temp_query
    if type(page) is not int:
        page = int(page.encode('utf-8'))
    try:
        if temp_query == "":
            query = ""
            query = request.form['query'].encode('utf-8')
            query = query + " " + request.form['director'].encode('utf-8')
            query = query + " " + request.form['starring'].encode('utf-8')
            query = query + " " + request.form['location'].encode('utf-8')
            temp_query = query
        elif request.method == 'POST':
            query = ""
            query = request.form['query'].encode('utf-8')
            query = query + " " + request.form['director'].encode('utf-8')
            query = query + " " + request.form['starring'].encode('utf-8')
            query = query + " " + request.form['location'].encode('utf-8')
            temp_query = query
        else:
            query = temp_query

        search_results = querysearch.query_search(query)

        # get the number of results
        result_num = search_results[1]

        # if we find the results, extract title and text information from doc_data, else do nothing
        if result_num > 0:
            dicList = search_results[0]
            heap = []
            # extract the top 30 records with highest similarity scores
            for dic in dicList:
                if len(heap) < 30:
                    heapq.heappush(heap, (dicList[dic], dic))
                else :
                    minScore = heap[0]
                    if dicList[dic] < minScore[0]:
                        heapq.heapreplace(heap, (dicList[dic], dic))
            # pop the records from heap into list
            rList = []
            while heap:
                rList.append(heapq.heappop(heap))

            # the final record number
            finalResult_num = len(rList)

            # generate output contents
            resList = querysearch.completeWeight(rList)

            # generate output contents for current page
            start = 0 + (page-1)*10
            end = 10 + (page-1)*10
            resultsList = resList[start:end]
        else:
            resultsList = search_results[0]

        # get stop words list
        stop_list = search_results[2]

        return render_template('page_SERP.html', text=query, results=resultsList, res_num=finalResult_num, stop_len=len(stop_list), stops=stop_list, page_num=page)
    except KeyError:
        return "Problem"

@app.route("/documents/<res>", methods=['GET'])
def documents(res):
    query = res
    contents = querysearch.doc_search(str(query))
    contents = querysearch.pretty(contents)
    return render_template('page_targetArticle.html',film=contents)

@app.route("/morelikethis/<res>", methods=['GET','POST'])
def morelike(res):
    res = str(res.encode('utf-8'))
    res_list = querysearch.moreDocSearch(res)
    search_results = querysearch.completeWeight(res_list)
    return render_template('page_moreLike.html', results=search_results)

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


from typing import *
import collections
import heapq

class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        graph = collections.defaultdict(list)
        for time in times:
            graph[time[0]].append((time[1], time[2]))

        dist = collections.defaultdict(int)
        heap = [(0, k)]

        while heap:
            time, node = heapq.heappop(heap)
            # Make dist to contain only shortest path
            # -> avoid updating dist values, priority values in the heap
            # (the first time node gets included in the heap, it is the shortest path)
            if node not in dist:
                dist[node] = time
                for next_node, edge in graph[node]:
                    heapq.heappush(heap, (time+edge, next_node))

        if len(dist) == n:
            return max(dist.values())
        return -1

s = Solution()
print(s.networkDelayTime([[2,1,1],[2,3,1],[3,4,1]], 4, 2))


from typing import List, Union

from django.conf import settings
from django.contrib import admin
from django.urls import URLPattern, URLResolver, include, path
from django.views import defaults as default_views

urlpatterns: List[Union[URLPattern, URLResolver]] = [
    # Django Admin, use {% url 'admin:index' %}
    path(settings.ADMIN_URL, admin.site.urls),
    # User management
    path("users/", include("star_wars_explorer.users.urls", namespace="users")),
    path("accounts/", include("allauth.urls")),
    # Your stuff: custom urls includes go here
    path("", include("star_wars_explorer.etl.urls", namespace="etl")),
]

if settings.DEBUG:
    # This allows the error pages to be debugged during development, just visit
    # these url in browser to see how these error pages look like.
    urlpatterns += [
        path(
            "400/",
            default_views.bad_request,
            kwargs={"exception": Exception("Bad Request!")},
        ),
        path(
            "403/",
            default_views.permission_denied,
            kwargs={"exception": Exception("Permission Denied")},
        ),
        path(
            "404/",
            default_views.page_not_found,
            kwargs={"exception": Exception("Page not Found")},
        ),
        path("500/", default_views.server_error),
    ]
    if "debug_toolbar" in settings.INSTALLED_APPS:
        import debug_toolbar

        urlpatterns = [path("__debug__/", include(debug_toolbar.urls)), *urlpatterns]


"""
### Resample rasters. ###

Module to resample rasters to a target resolution.
Can uses references from vector or other raster datasets.
"""

# Standard library
import sys; sys.path.append("../../")
from typing import Union, Optional, List

# External
from osgeo import gdal
import numpy as np

# Internal
from buteo.utils import (
    utils_io,
    utils_base,
    utils_gdal,
    utils_path,
    utils_translate,
)
from buteo.raster import core_raster, core_raster_io

def _raster_resample(
    raster: Union[str, gdal.Dataset],
    target_size: Union[List[Union[int, float]], int, float, gdal.Dataset, str],
    out_path: Optional[str] = None,
    *,
    target_in_pixels: bool = False,
    resample_alg: str = "nearest",
    overwrite: bool = True,
    creation_options: Optional[List[str]] = None,
    dtype: Optional[str] = None,
    dst_nodata: Union[float, int, str] = "infer",
    verbose: int = 0,
    ram: float = 0.8,
    ram_max: Optional[int] = None,
    ram_min: Optional[int] = 100,
) -> Union[str, gdal.Dataset]:
    """ Internal. """
    assert isinstance(raster, (gdal.Dataset, str)), f"The input raster must be in the form of a str or a gdal.Dataset: {raster}"

    if out_path is None:
        out_path = utils_path._get_temp_filepath(name="resampled_raster.tif")
    else:
        if not utils_path._check_is_valid_output_filepath(out_path):
            raise ValueError(f"Invalid output path: {out_path}")

    ref = core_raster._raster_open(raster)
    metadata = core_raster._get_basic_metadata_raster(ref)

    if isinstance(target_size, (gdal.Dataset, str)):
        x_res, y_res = utils_gdal._get_raster_size(target_size)
        x_pixels = None
        y_pixels = None
    elif target_in_pixels:
        x_res = None
        y_res = None

        if isinstance(target_size, (list, tuple)):
            assert len(target_size) == 2, f"Invalid target_size. {target_size}"
            x_pixels = target_size[0]
            y_pixels = target_size[1]
        elif isinstance(target_size, (int, float)):
            x_pixels = target_size
            y_pixels = target_size
        else:
            raise RuntimeError(f"Invalid target_size. {target_size}")
    else:
        x_pixels = None
        y_pixels = None

        if isinstance(target_size, (list, tuple)):
            assert len(target_size) == 2, f"Invalid target_size. {target_size}"
            x_res = target_size[0]
            y_res = target_size[1]
        elif isinstance(target_size, (int, float)):
            x_res = target_size
            y_res = target_size
        else:
            raise RuntimeError(f"Invalid target_size. {target_size}")

    out_format = utils_gdal._get_raster_driver_name_from_path(out_path)

    src_nodata = metadata["nodata_value"]
    out_nodata = None
    if dst_nodata == "infer":
        dst_nodata = src_nodata
    else:
        assert isinstance(dst_nodata, (int, float, type(None))), "dst_nodata must be an int, float, 'infer', or 'None'"
        out_nodata = dst_nodata

    if dtype is None:
        dtype = metadata["dtype"]

    if out_nodata is not None and not utils_translate._check_is_value_within_dtype_range(out_nodata, dtype):
        raise ValueError(f"Invalid nodata value for datatype. value: {out_nodata}, dtype: {dtype}")

    utils_path._delete_if_required(out_path, overwrite)

    if verbose == 0:
        gdal.PushErrorHandler("CPLQuietErrorHandler")

    options = gdal.WarpOptions(
        format=out_format,
        width=x_pixels,
        height=y_pixels,
        xRes=x_res,
        yRes=y_res,
        outputType=utils_translate._translate_dtype_numpy_to_gdal(dtype),
        resampleAlg=utils_translate._translate_resample_method(resample_alg),
        creationOptions=utils_gdal._get_default_creation_options(creation_options),
        srcNodata=metadata["nodata_value"],
        dstNodata=out_nodata,
        multithread=True,
        warpMemoryLimit=utils_gdal._get_dynamic_memory_limit(ram, min_mb=ram_min, max_mb=ram_max),
    )

    resampled = gdal.Warp(out_path, ref, options=options)

    if verbose == 0:
        gdal.PopErrorHandler()

    if resampled is None:
        raise RuntimeError(f"Error while resampling raster: {out_path}")

    return out_path

def raster_resample(
    raster,
    target_size,
    out_path=None,
    *,
    target_in_pixels=False,
    resample_alg="nearest",
    creation_options=None,
    dtype=None,
    dst_nodata="infer",
    prefix="",
    suffix="",
    overwrite=True,
    add_uuid=False,
    add_timestamp: bool = False,
    verbose: int = 0,
    ram: float = 0.8,
    ram_max: Optional[int] = None,
    ram_min: Optional[int] = 100,
):
    """
    Resampled raster(s) given a target size.
    Beware, if your input is in latitude and longitude, you'll need to specify the target_size in degrees as well.

    Parameters
    ----------
    raster : str/gdal.Dataset/list
        The input raster(s) to resample.

    target_size : str/int/ogr.DataSource/gdal.Dataset
        The desired resolution for the resampled raster(s), in the same unit as the raster projection.
        x_res, y_res - or x_pixels, y_pixels if target_in_pixels is True.

    target_in_pixels : bool, optional
        If True, interprets target_size as the number of pixels, default: False

    out_path : str, optional
        The output path for the resampled raster(s). If not provided, the output path is inferred from the input raster(s), default: None

    resample_alg : str, optional
        The resampling algorithm to use, default: "nearest"

    creation_options : list, optional
        A list of creation options for the output raster(s), default: None

    dtype : str, optional
        The output data type, default: None

    dst_nodata : str/int/float, optional
        The nodata value for the output raster(s), default: "infer"

    prefix : str, optional
        A prefix to add to the output path, default: ""

    suffix : str, optional
        A suffix to add to the output path, default: ""

    add_uuid : bool, optional
        If True, adds a uuid to the output path, default: False

    add_timestamp : bool, optional
        If True, adds a timestamp to the output path, default: False

    verbose : int, optional
        The verbosity level, default: 0

    ram : float, optional
        The amount of RAM to use for the resampling, default: 0.8 (80% of the total RAM)

    ram_max : int, optional
        The maximum amount of RAM to use for the resampling, default: None

    ram_min : int, optional
        The minimum amount of RAM to use for the resampling, default: 100

    overwrite : bool, optional
        If True, overwrites the output raster(s) if it/they already exist, default: True

    Returns
    -------
    str/list[str]
        The output path(s) of the resampled raster(s).
    """
    utils_base._type_check(raster, [str, gdal.Dataset, [str, gdal.Dataset]], "raster")
    utils_base._type_check(target_size, [tuple, [int, float], int, float, str, gdal.Dataset], "target_size")
    utils_base._type_check(target_in_pixels, [bool], "target_in_pixels")
    utils_base._type_check(out_path, [str, [str], None], "out_path")
    utils_base._type_check(resample_alg, [str], "resample_alg")
    utils_base._type_check(overwrite, [bool], "overwrite")
    utils_base._type_check(creation_options, [[str], None], "creation_options")
    utils_base._type_check(dst_nodata, [str, int, float, None], "dst_nodata")
    utils_base._type_check(dtype, [str, None, np.dtype, type(np.int8)], "dtype")
    utils_base._type_check(prefix, [str], "prefix")
    utils_base._type_check(suffix, [str], "postfix")
    utils_base._type_check(add_uuid, [bool], "add_uuid")
    utils_base._type_check(add_timestamp, [bool], "add_timestamp")
    utils_base._type_check(verbose, [int], "verbose")
    utils_base._type_check(ram, [int, float], "ram")
    utils_base._type_check(ram_max, [int, float, None], "ram_max")
    utils_base._type_check(ram_min, [int, float, None], "ram_min")

    input_is_list = isinstance(raster, list)

    input_rasters = utils_io._get_input_paths(raster, "raster")
    output_rasters = utils_io._get_output_paths(
        input_rasters,
        out_path,
        add_uuid=add_uuid,
        add_timestamp=add_timestamp,
        prefix=prefix,
        suffix=suffix,
        overwrite=overwrite,
    )

    utils_path._delete_if_required_list(output_rasters, overwrite)

    resampled_rasters = []
    for idx, in_raster in enumerate(input_rasters):
        resampled_rasters.append(
            _raster_resample(
                in_raster,
                target_size,
                target_in_pixels=target_in_pixels,
                out_path=output_rasters[idx],
                resample_alg=resample_alg,
                overwrite=overwrite,
                creation_options=creation_options,
                dtype=dtype,
                dst_nodata=dst_nodata,
                ram=ram,
                ram_max=ram_max,
                ram_min=ram_min,
            )
        )

    if input_is_list:
        return resampled_rasters

    return resampled_rasters[0]

def resample_array(
    arr,
    target_shape_pixels,
    resample_alg="bilinear",
    channel_last=True,
):
    """ Resample a numpy array using the GDAL algorithms. """
    utils_base._type_check(arr, [np.ndarray, np.ma.MaskedArray], "arr")
    utils_base._type_check(target_shape_pixels, [tuple, [int, float]], "target_shape_pixels")
    utils_base._type_check(resample_alg, [str], "resample_alg")
    utils_base._type_check(channel_last, [bool], "channel_last")

    assert len(arr.shape) in [2, 3], f"Invalid array shape: {arr.shape}"
    assert len(target_shape_pixels) in [2, 3], f"Invalid target_shape_pixels: {target_shape_pixels}"

    if len(target_shape_pixels) == 3:
        if channel_last:
            target_shape_pixels = (target_shape_pixels[0], target_shape_pixels[1])
        else:
            target_shape_pixels = (target_shape_pixels[1], target_shape_pixels[2])
    else:
        raise ValueError(f"Invalid target_shape_pixels: {target_shape_pixels}")

    arr_as_raster = core_raster_io.raster_create_from_array(arr, channel_last=channel_last)
    resampled = _raster_resample(
        arr_as_raster,
        target_shape_pixels,
        target_in_pixels=True,
        resample_alg=resample_alg,
    )
    out_arr = core_raster_io.raster_to_array(resampled)

    utils_gdal.delete_dataset_if_in_memory(arr_as_raster)
    utils_gdal.delete_dataset_if_in_memory(resampled)

    return out_arr


import flet as ft
from calculadora import calcular_imc, mens_sit

def main(page: ft.Page):
    page.title = 'IMC'

    # resultado
    res_imc = 0
    res = 'Não Informado'

    # controle
    peso = ft.TextField(label='Exemplo 70', bgcolor=ft.colors.WHITE, border=None)
    altura = ft.TextField(label='Exemplo 1.80', bgcolor=ft.colors.WHITE, border=None)
    resultado_imc = ft.TextField(value=str(res_imc), read_only=True, text_align=ft.alignment.center, text_size=25, color=ft.colors.WHITE, border_color=ft.colors.BLUE)
    resultado = ft.TextField(value=str(res), read_only=True, text_align=ft.alignment.center, text_size=25, color=ft.colors.WHITE, border_color=ft.colors.BLUE)

    def click(e):
        res_imc = calcular_imc(peso.value, altura.value)
        res = mens_sit(res_imc)

        resultado_imc.value = str(f'{res_imc:.2f}')
        resultado.value = str(res)
        page.update()

    botao = ft.ElevatedButton(text='Calcular', bgcolor=ft.colors.RED_400, color=ft.colors.WHITE, width=400, on_click=click)

    #container
    c1 = ft.Container(
        ft.Column(
            [
                peso,
                altura,
                botao
            ]
        ),
        bgcolor=ft.colors.BLUE,
        padding=10,
        width=400,
        border_radius=10,
    )
    c2 = ft.Container(
        ft.Column(
            [
                ft.Text('O seu IMC esta abaixo', color=ft.colors.WHITE, text_align=ft.alignment.center, size=20),
                resultado_imc,
                resultado
            ],
        ),
        bgcolor=ft.colors.BLUE,
        padding=10,
        width=400,
        border_radius=10,
        alignment=ft.alignment.center
    )

    page.add(c1, c2)

ft.app(target=main)


from django.db import models
import django.utils.timezone as timezone

# 预案编制
class PlanyType(models.Model):
    class Meta:
        verbose_name = "预案编制"
        verbose_name_plural = "预案编制"

    type_name = models.CharField(verbose_name="编制名称", max_length=30, unique=True)
    type_desc = models.TextField(verbose_name="编制描述")
    type_status = models.BooleanField(verbose_name="编制状态", default=1)
    add_time = models.DateTimeField(verbose_name="创建时间", default=timezone.now)
    modify_time = models.DateTimeField(verbose_name="修改时间", auto_now=True)

    def __str__(self):
        return self.type_name

# 预案模板
class PlanyTemplate(models.Model):
    class Meta:
        verbose_name = "预案模板"
        verbose_name_plural = "预案模板"

    template_name = models.CharField(verbose_name="模板名称", max_length=30, unique=True)
    ersion_num = models.CharField(verbose_name="版本号", max_length=30)
    file = models.FileField(upload_to='upload/user', verbose_name="详细文件", blank=True, null=True)
    company_name = models.CharField(verbose_name="编制单位", max_length=30)
    create_user = models.CharField(verbose_name="编制人", max_length=30)
    create_time = models.DateTimeField(verbose_name="编制时间", auto_now=timezone.now)
    use_info = models.TextField(verbose_name="使用说明", null=True, blank=True)
    description = models.TextField(verbose_name="模板描述", null=True, blank=True)
    add_time = models.DateTimeField(verbose_name="描述时间", default=timezone.now)
    modify_time = models.DateTimeField(verbose_name="修改时间", auto_now=True)

    def __str__(self):
        return self.template_name

# 预案管理
class Plans(models.Model):
    class Meta:
        verbose_name = "预案生成"
        verbose_name_plural = "预案生成"

    plan_name = models.CharField(verbose_name="预案名称", max_length=100)
    template = models.ForeignKey("PlanyTemplate", on_delete=models.DO_NOTHING, verbose_name="处理模板", null=True)
    plantype = models.ForeignKey("PlanyType", on_delete=models.DO_NOTHING, verbose_name="预案编制", null=True)
    implementation_objectives = models.CharField(verbose_name="实施目标", null=True, max_length=100, blank=True)
    plan_implementer = models.CharField(verbose_name="预案实施人", null=True, blank=True, max_length=100)
    plan_des = models.TextField(verbose_name="方案描述", null=True, blank=True)
    plan_detail = models.TextField(verbose_name="方案细节", null=True)
    add_time = models.DateTimeField(verbose_name="创建时间", default=timezone.now)
    modify_time = models.DateTimeField(verbose_name="修改时间", auto_now=True)

    def __str__(self):
        return self.plan_name

# 城市分类
class City(models.Model):
    class Meta:
        verbose_name = "城市录入"
        verbose_name_plural = "城市录入"

    city_name = models.CharField(verbose_name="城市名称", max_length=30, unique=True)
    # type_status = models.BooleanField(verbose_name="类型状态", default=1)
    add_time = models.DateTimeField(verbose_name="创建时间", default=timezone.now)
    modify_time = models.DateTimeField(verbose_name="修改时间", auto_now=True)

    def __str__(self):
        return self.city_name

# 方案评估
class Assessment(models.Model):
    class Meta:
        verbose_name = "方案评估"
        verbose_name_plural = "方案评估"

    assessment_name = models.CharField(verbose_name="评估名称", max_length=30, unique=True)
    assessment_description = models.TextField(verbose_name="评估描述")
    file = models.FileField(verbose_name="评估文件", upload_to='upload/user')
    plan = models.ForeignKey("Plans", verbose_name="方案名称", on_delete=models.DO_NOTHING)
    city = models.ForeignKey("City", verbose_name="评估城市", on_delete=models.DO_NOTHING)
    assessment_user = models.CharField(verbose_name="评估人", max_length=100)
    add_time = models.DateTimeField(verbose_name="评估时间", default=timezone.now)
    modify_time = models.DateTimeField(verbose_name="修改时间", auto_now=True)

    def __str__(self):
        return self.assessment_name


import sys
sys.stdin = open("5174in.txt")

def inorder(v):
    global cnt
    if v != 0: # 노드번호 v가 0이 아닐때까지만 실행 # 0이면 종료
        inorder(tree[v][0]) # 왼쪽 자식 보기
        cnt += 1
        inorder(tree[v][1]) # 오른쪽 자식 보기

T = int(input())

for tc in range(1, T+1):
    E, N = map(int, input().split())
    tree = [[0, 0] for _ in range(E+2)]
    tmp = list(map(int, input().split()))
    for i in range(0, len(tmp), 2):
        if tree[tmp[i]][0]:
            tree[tmp[i]][1] = tmp[i+1]
        else:
            tree[tmp[i]][0] = tmp[i+1]
    # print(tree)
    cnt = 0
    inorder(N)
    print(f'#{tc} {cnt}')


maxsus_soz = "ABCDEFGHIJKLMNOPQRTUSTVWXYZ"

numbers = [12, 4, 13, 8, 13, 6, 8, 20, 12, 8, 12, 19, 18, 10, 8, 17, 1, 4, 10]

result = ''

for x in numbers:
    result+=str(maxsus_soz[x])

print(result)


""" Converts a binary file into a DNA string according to a given bytewise codebook.

Author: Azat Akhmetov <azat@utexas.edu>
"""
import math
import pickle
import time

# Inputs and parameters
input_file = 'Input/tars/Hamming 10 kb.tar'

encoded_dna_filename = 'Output/Encoded DNA/Hamming 10 kb encoded dna.txt'
encoded_blocks_filename = 'Output/Encoded DNA/Hamming 10 kb encoded blocks.txt'

codebook_path = 'Input/codebook.pickle'  # A pickle file generated by construct_codebooks.py which maps each codeword to a number. Do not lose this! It is necessary for decoding.

compress_data = True  # Whether the compress data before encoding. Setting this to false is not recommended, the option is here for debugging.
encoded_bytes_path = 'Intermediate data/encoded bytes.txt'  # A dump of the input as a bytestream, for debug

# Load the codebook DNA-number conversion table
codebook = pickle.load(open(codebook_path, 'rb'))

# Read file as list of bytes and convert into a base-n number (for n codewords)
def bytes_to_base_n(byte_array, to_base):
    """ Converts a byte array to a base n number.

    :param byte_array: Array of bytes, with most significant byte (highest digit) first.
    :param to_base: What base the result should be in.
    :return: The number in the new base, given as array of digits, most significant first.
    """

    x = int.from_bytes(byte_array, byteorder='big')

    result = []
    carry_over = x
    now = time.time()
    print('Beginning conversion of {0} bytes to numbers...'.format(len(byte_array)))
    while carry_over > 0:
        remainder = int(carry_over % to_base)
        result.insert(0, remainder)

        new_carry_over = (carry_over - remainder) // to_base
        carry_over = new_carry_over

        new_now = time.time()
        if new_now-now > 1:
            print('{0:.1%} complete...'.format(1 - math.log(carry_over)/math.log(x)))
            now = new_now

    if len(result) < 1:
        result = [0]

    print('Finished converting.')
    return result

n = len(codebook)

raw_file = open(input_file, 'rb').read()

if compress_data:
    import lzma

    print("Compressing file with LZMA...")
    bytes_to_encode = lzma.compress(data=raw_file, format=lzma.FORMAT_XZ)
else:
    bytes_to_encode = raw_file

open(encoded_bytes_path, 'w').write('\n'.join([str(b) for b in bytes_to_encode]))

converted_to_new_base = bytes_to_base_n(bytes_to_encode, n)

# Encode each digit into DNA
encoded = []
for d in converted_to_new_base:
    w = codebook[d]
    encoded += [w]

# Write DNA sequence to files
encoded_blocks = '\n'.join(encoded)
open(encoded_blocks_filename, 'w').write(encoded_blocks)

encoded_dna = ''.join(encoded)
open(encoded_dna_filename, 'w').write(encoded_dna)

print('Done!')


import numpy as np

# This method could be inproved by specifying the order of trying
# different k values. For example, start with average, then continue
# trying average of average and max, recursively loop through these
# averages.

# n th triangle number
def triangular_distance(num) -> int:
    # Optimize efficiency by adding memoization to this function
    # Did not implement because numpy.ndarray is unhashable
    # https://github.com/numpy/numpy/issues/14294
    return np.absolute(num * (num + 1) // 2)

# Naive distance of array value to k
def naive_distance(array, k):
    return np.absolute(array - k)

def solution_1(data)->tuple:
    sum = float('inf')
    pos = -1

    for k in range(data.max() + 1):
        array = naive_distance(data, k)
        temp_sum = np.sum(array)

        if temp_sum < sum:
            sum = temp_sum
            pos = k

    return sum, pos

def solution_2(data)->tuple:
    sum = float('inf')
    pos = -1

    for k in range(data.max() + 1):
        array = naive_distance(data, k)
        array = triangular_distance(array)

        temp_sum = np.sum(array)

        if temp_sum < sum:
            sum = temp_sum
            pos = k

    return sum, pos

def main():
    data = np.loadtxt('day_7_data.txt', dtype=np.int64, delimiter=',')

    # Solution: (fuel, position)
    print(solution_1(data))
    print(solution_2(data))

if __name__ == '__main__':
    main()