supported_tags = [
    "INDI",
    "NAME",
    "SEX",
    "BIRT",
    "DEAT",
    "FAMC",
    "FAMS",
    "FAM",
    "MARR",
    "HUSB",
    "WIFE",
    "CHIL",
    "DIV",
    "DATE",
    "HEAD",
    "TRLR",
    "NOTE",
]

class individual(object):

    def __init__(self, uid):
        self.uniqueId = uid
        self.indi_name = None
        self.indi_birth = None
        self.indi_sex = None
        self.indi_death = None
        self.indi_alive = True
        self.fam_id_of_indi_child = []
        self.fam_id_of_indi_parent = []

class family(object):

    def __init__(self, uid):
        self.uniqueId = uid
        self.fam_marr = None
        self.husband = None
        self.husbandName = None
        self.wife = None
        self.wifeName = None
        self.children = []
        self.divorce = None

class tagLine (object):
    def __init__(self, line):
        self.num_level = None
        self.num_tag = None
        self.arguments = None
        self.reference = None

        list_of_line = line.split(' ',)

        self.level = int(list_of_line[0])

        if self.level > 0:
            self.num_tag = list_of_line[1]
            self.arguments = list_of_line[2:]

        if self.level == 0:
            if list_of_line[1] in supported_tags:
                self.num_tag = list_of_line[1]
                self.arguments = None
            else:
                self.num_tag = list_of_line[2]
                self.reference = list_of_line[1]


"""
Custom Vectorizer based on MI
-----------------------------

Using mutual information between metas and words to weight words

Public Methods
~~~~~~~~~~~~~~
    train_model

"""

from __future__ import print_function

import math
from scipy.sparse import coo_matrix, csr_matrix
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

class CustomPreprocessor(object):
    def __call__(self, doc):
        return doc

class CustomTokenizer(object):
    def __call__(self, doc):
        return doc

class MIWeightsVectorizer(object):
    def __init__(self, metas):
        df = (5, 0.90)
        self.tf_vectorizer = CountVectorizer(
            min_df=df[0], max_df=df[1],
            tokenizer=CustomTokenizer(),
            preprocessor=CustomPreprocessor())

        # THIS IS A CHEAT TO CALCULATE meta WEIGHTS
        self.metas = metas
        self.metas = list(set(self.metas))
        self.nbr_of_metas = len(self.metas)
        self.words = None
        self.nbr_of_words = None

    def fit(self, data_samples):
        self.tf_vectorizer.fit(data_samples)
        self.words = self.tf_vectorizer.get_feature_names()
        self.nbr_of_words = len(self.words)

    def transform(self, test_dataset, metas):
        tf_trained = self.tf_vectorizer.transform(test_dataset)
        N = tf_trained.shape[0]

        # THIS IS A CHEAT TO CALCULATE meta WEIGHTS
        metas = list(set(metas))
        nbr_of_metas = len(metas)

        # Here, term occurences is the same as document occurences containing
        # word because a word is present or not in document
        t_counts = [0] * self.nbr_of_words
        count_t_m = [[0] * nbr_of_metas for _ in [0] * self.nbr_of_words]
        coo_tf_trained = coo_matrix(tf_trained)
        for i, j, df in zip(coo_tf_trained.row, coo_tf_trained.col, coo_tf_trained.data):
            # print("document = %d, term = %d, tf = %s" % (i, j, df))
            t_counts[j] += 1  # counting documents for every word
            meta_index = metas.index(metas[i])
            count_t_m[j][meta_index] += 1  # counting metas for every word

        # counts metas
        m_counts = [0] * nbr_of_metas
        for t_m in count_t_m:
            for m_index, m in enumerate(t_m):
                m_counts[m_index] += m

        total_count_m = sum(m_counts)
        m_frequencies = [m_count / total_count_m for m_count in m_counts]
        m_entropy = - sum([m_frequency * math.log(m_frequency) for m_frequency in m_frequencies])

        t_metas_centropy = []
        for t_index, count_m_given_t in enumerate(count_t_m):
            # summing all the metas counts for each words
            total_count_m_given_t = sum(count_m_given_t)
            # Normalizing the ordered metas counts
            # The +1 is to forbid the division by 0 but also penalize the words with to low frequencies
            freq_m_given_t = []
            for occ in count_m_given_t:
                freq_m_given_t.append(occ / total_count_m_given_t)

            info_m_given_t = []
            for freq_m in freq_m_given_t:
                if freq_m == 0:
                    info_m_given_t.append(0)
                else:
                    info_m_given_t.append(- freq_m * math.log(freq_m))
            m_given_t_entropy = sum(info_m_given_t)
            mutual_information = m_entropy - m_given_t_entropy

            if (mutual_information <0):
                # print(self.words[t_index])
                mutual_information = 0

            # Creating a new (word -> meta) normalized counts matrix
            t_metas_centropy.append(mutual_information)

        # helps see the weights of mutual_information
            # # helps see the weights of idf
            # sorted_indexed_idf = np.argsort(t_metas_centropy)[::-1]
            # sorted_word_idf = [[self.words[i], t_metas_centropy[i]] for i in sorted_indexed_idf.tolist()]
            # sorted_word_idf_frame = DataFrame(sorted_word_idf)
            # with open('./output/tfmut_values.txt', 'w') as f:
            #     f.write(sorted_word_idf_frame.to_string())

        row = []
        col = []
        data = []
        for i, j, df in zip(coo_tf_trained.row, coo_tf_trained.col, coo_tf_trained.data):
            # print("row = %d, column = %d, value = %s" % (i, j, df))
            row.append(i)
            col.append(j)
            word_mi = t_metas_centropy[j]
            data.append(word_mi)

        return csr_matrix((np.array(data), (np.array(row), np.array(col))), shape=(N, self.nbr_of_words))

    def get_feature_names(self):
        return self.words

def train_model(data_samples, test_dataset, metas):
    vectorizer = MIWeightsVectorizer()
    vectorizer.fit(data_samples)
    tfidf_trained = vectorizer.transform(test_dataset, metas)

    return {
        'features': vectorizer.get_feature_names(),
        'transformations': tfidf_trained,
        '_model': vectorizer,
        '_name': 'mutual_info'
    }


from googlecloudsdk.api_lib.emulators import datastore_util
from googlecloudsdk.api_lib.emulators import util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base

class Start(base.Command):
  """Start a local datastore emulator.

  This command starts a local datastore emulator.
  """

  detailed_help = {
      'DESCRIPTION': '{description}',
      'EXAMPLES': """\
          To start a local datastore emulator, run:

            $ {command} --data-dir DATA-DIR
          """,
  }

  @staticmethod
  def Args(parser):
    parser.add_argument(
        '--host-port',
        required=False,
        type=arg_parsers.HostPort.Parse,
        help='The host:port to which the emulator should be bound.')
    parser.add_argument(
        '--store-on-disk',
        required=False,
        type=bool,
        default=True,
        help='Whether data should be persisted to disk.')
    parser.add_argument(
        '--consistency',
        required=False,
        type=float,
        default=0.9,
        help='Fraction of job application attempts that should succeed.')

  def Run(self, args):
    if not args.host_port:
      args.host_port = arg_parsers.HostPort.Parse(datastore_util.GetHostPort())
    args.host_port.host = args.host_port.host or 'localhost'

    datastore_util.PrepareGCDDataDir(args.data_dir)
    datastore_process = datastore_util.StartGCDEmulator(args)
    datastore_util.WriteGCDEnvYaml(args)
    util.PrefixOutput(datastore_process, 'datastore')


import datetime
import collections
import threading
import queue

from fast_trader.dtp_quote import settings
from fast_trader.serializer import serializer

def get_client():
    import pyssdb
    host = settings['quote_feed_store']['ssdb_host']
    port = settings['quote_feed_store']['ssdb_port']
    client = pyssdb.Client(host, port)
    return client

class SSDBHashmapStore:

    def __init__(self, name):
        self._client = get_client()
        self._hname = name

    @property
    def client(self):
        return self._client

    def write(self, key, value):
        b = serializer.serialize(value)
        self.client.hset(self._hname, key, b)

    def read(self, key, value):
        b = self.client.hget(self._hname, key)
        if b is None:
            return b
        ret = serializer.deserialize(b)
        return ret

    def list_keys(self):
        return self.client.hkeys(self._hname, '', '')

class SSDBListStore:
    """
    SSDB `list` store

    key naming: 'category;code;date'
    """

    def __init__(self):

        self._client = get_client()

        try:
            self._write_buffer_size = \
                settings['quote_feed_store']['ssdb_write_buffer_size']
        except KeyError:
            self._write_buffer_size = 0

        self._buffer = queue.Queue()
        self._writer = None
        self._buffer_interval = 10
        self._last_write_time = datetime.datetime.now()
        self._writer_running = True
        self._buffer_write()

    @property
    def client(self):
        return self._client

    def _push(self, key, value):
        b = serializer.serialize(value)
        self.client.qpush(key, b)

    def _push_many(self, key, values, client=None):
        many = [serializer.serialize(v) for v in values]
        if client is None:
            cl = self.client
        else:
            cl = client
        cl.qpush(key, *many)

    def _buffer_write(self):
        if self._write_buffer_size <= 0:
            return

        def _flush():
            client = get_client()
            buf = collections.defaultdict(list)
            while self._writer_running:
                now = datetime.datetime.now()
                if (now - self._last_write_time).seconds > self._buffer_interval:
                    slef._last_write_time = now
                    try:
                        for i in range(self._buffer.qsize()):
                            el = self._buffer.get(block=False)
                            buf[el[0]].append(el[1])
                    except queue.Empty:
                        pass
                    for key in buf:
                        v = buf[key]
                        if len(v) > 0:
                            self._push_many(key, v, client)
                            buf[key] = []

        self._writer = threading.Thread(target=_flush)
        self._writer.start()

    def push(self, key, value):
        if self._write_buffer_size == 0:
            self._push(key, value)
        else:
            self._buffer.put((key, value))

    def read_first(self, key):
        ret = self.client.qfront(key)
        if ret is None:
            return
        ret = serializer.deserialize(ret)
        return ret

    def read_last(self, key):
        ret = self.client.qback(key)
        if ret is None:
            return
        ret = serializer.deserialize(ret)
        return ret

    def read(self, key, offset=0, limit=1000000):
        ret = self.client.qrange(key, offset, limit)
        if ret is None:
            return
        ret = [serializer.deserialize(i) for i in ret]
        return ret


class Solution:
    def longestPalindrome(self, s: str) -> str:
        def expands(left, right):
            while left >= 0 and right < len(s) and s[left]==s[right]:
                left -= 1
                right += 1
            return s[left+1 : right]
        result = ''
        if len(s) == 1 or s == s[::-1]:
            return s
        else:
            for i in range(len(s)-1):
                result = max(result, expands(i, i+1), expands(i, i+2), key=len)
            return result
"""
    투 포인터로 확장시키면서 탐색
    DP로도 가능하지만 이는 시간이 오래 걸림

    expands 함수는 좌우 한칸씩 벌리면서 같은 문자열이면 계속 확장시킴
    max의 키값을 설정하여 문자열 길이 len을 기준으로 판별
    result를 반환
"""

q06.가장_긴_팰린드롬_부분_문자열.py


from django.contrib import admin

# Register your models here.
from .models import Pitch, Vote, Room, Slot, Schedule, Flag

def collapse_pitches(model_admin, request, pitch_set):
    base_pitch = pitch_set[0]
    for pitch in pitch_set[1:]:
        base_pitch.merge(pitch)
collapse_pitches.short_description = 'Collapse pitches'

class PitchAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['text', 'author']}),
        ('Details', {'fields': ['created_at', 'uuid']}),
    ]
    actions = [collapse_pitches]

def swap_talks(model_admin, request, talk_set):
    if len(talk_set) != 2:
        # Do nothing; undefined behaviour
        return
    talk_set[0].swap(talk_set[1])
swap_talks.short_description = 'Swap talks'

class ScheduleAdmin(admin.ModelAdmin):
    actions = [swap_talks]

admin.site.site_header = 'Unconf Admin'

admin.site.register(Pitch, PitchAdmin)
admin.site.register(Vote)
admin.site.register(Slot)
admin.site.register(Room)
admin.site.register(Schedule, ScheduleAdmin)
admin.site.register(Flag)


matrix = []
n = int(input())
for row in range(n):
    matrix.append([int(x) for x in input().split()])
command = input()
while command != "END":
    action, row, col, value = command.split()
    row, col, value = int(row), int(col), int(value)
    if len(matrix) > row >= 0 and len(matrix[0]) > col >= 0:
        if action == "Add":
            matrix[row][col] += value
        elif action == "Subtract":
            matrix[row][col] -= value
    else:
        print("Invalid coordinates")
    command = input()
[print(*n) for n in matrix]


import gymnasium as gym
import random
import numpy as np
import pickle

# Ambiente de aprendizagem
ambiente = gym.make("Taxi-v3", render_mode="ansi")

# Tabela de possíveis movimentos zerada
tabela_q = np.zeros([ambiente.observation_space.n, ambiente.action_space.n])

# Movimentos possíveis:
# 0 = sul
# 1 = norte
# 2 = leste
# 3 = oeste
# 4 = pegar o passageiro
# 5 = entregar o passageiro

# Taxa de aprendizagem
alpha = 0.1

# Fator de desconto
gamma = 0.6

# Porcentagem da chance de exploração
epsilon = 0.1

# Quantidade de vezes que o processo será executado
n_loops = 100000

for i in range(n_loops):
    # Estado inicial do agente no loop
    estado = ambiente.reset()[0]

    recompensa = 0
    finalizado = False

    while not finalizado:
        # Exploração
        if random.uniform(0, 1) < epsilon:
            # Ação randômica
            acao = ambiente.action_space.sample()

        #  Exploitation
        else:
            # Ação mais indicada
            acao = np.argmax(tabela_q[estado])

        # Realiza a ação
        proximo_estado, recompensa, finalizado, info, _ = ambiente.step(acao)

        # Armazenando valor atual para aplicar no cálculo
        q_antigo = tabela_q[estado, acao]

        # Encontrando o próximo valor máximo baseado no próximo estado
        proximo_maximo = np.max(tabela_q[proximo_estado])

        # Aplicando Formula do QLearning
        q_novo = (1 - alpha) * q_antigo + alpha * (recompensa + gamma * proximo_maximo)

        # Substituindo o valor na tabela q pelo novo valor encontrado
        tabela_q[estado, acao] = q_novo

        # Mudando o estado do agente
        estado = proximo_estado

# Salvar as instruções obtidas do treinamento em um arquivo .sav
pickle.dump(tabela_q, open("treinamento_taxi.sav", "wb"))

print("Treinamento concluído")


"""Merge & compress dataframe.
"""
import numpy as np
import pandas as pd
import sys
sys.path.append(".")
from scripts.util import timer, reduce_mem_usage

with timer("reading feather data"):
    DATA_FEATHER = "data/processed/"
    train = pd.read_feather(DATA_FEATHER + "train.feather")
    test = pd.read_feather(DATA_FEATHER + "test.feather")
    weather_train = pd.read_feather(DATA_FEATHER + "weather_train.feather")
    weather_test = pd.read_feather(DATA_FEATHER + "weather_test.feather")
    building_metadata = pd.read_feather(DATA_FEATHER + "building_metadata.feather")

# hold original number of samples
n_train = train.shape[0]
n_test = test.shape[0]

print(train.head())

with timer("merging"):
    train = train.merge(building_metadata, on="building_id", how="left")
    train = train.merge(weather_train, on=["site_id", "timestamp"], how="left")
    test = test.merge(building_metadata, on="building_id", how="left")
    test = test.merge(weather_test, on=["site_id", "timestamp"], how="left")

print(train.head())

del building_metadata
del weather_train
del weather_test

with timer("unravel timestmap"):
    train["hour"] = train["timestamp"].dt.hour
    train["day"] = train["timestamp"].dt.day
    train["month"] = train["timestamp"].dt.month
    train["dayofweek"] = train["timestamp"].dt.dayofweek
    test["hour"] = test["timestamp"].dt.hour
    test["day"] = test["timestamp"].dt.day
    test["month"] = test["timestamp"].dt.month
    test["dayofweek"] = test["timestamp"].dt.dayofweek

print(train.head())

with timer("adding meter_label"):
    meter = {0: "electricity", 1: "chilledwater", 2: "steam", 3: "hotwater"}
    train = train.assign(
        meter_label=lambda df: df["meter"].map(meter)
    )
    test = test.assign(
        meter_label=lambda df: df["meter"].map(meter)
    )

print(train.head())

# add log1p y
train["log_meter_reading"] = np.log1p(train["meter_reading"])

with timer("reduce memory"):
    train = reduce_mem_usage(train)
    test = reduce_mem_usage(test)

# check number of samples
assert train.shape[0] == n_train
assert test.shape[0] == n_test

with timer("saving"):
    train.to_feather(DATA_FEATHER + "train.ftr")
    test.to_feather(DATA_FEATHER + "test.ftr")


class Cat:

	def eat(self):
		print("吃")
	def drink(self):
		print("喝")
	def sleep(self):
		print("睡觉")

xiaohuamao = Cat()
xiaohuamao.eat()
xiaohuamao.drink()
xiaohuamao.sleep()

xiaohuamao.color = "花色"
xiaohuamao.weight = "5kg"
a = xiaohuamao.color
print(a)


while True:
    try:
        num = int(input("Introduzca un número natural: "))
        break
    except:
        print("Número inválido.")
i = num-1

def perfecto (num, i):
    divisor = 0
    if i == 0:
        return 0
    if num % i == 0:
        divisor = i
    return divisor + perfecto(num, i-1)

if perfecto (num, i) == num:
    print(f"{num} es un número perfecto.")
else:
    print(f"{num} no es un número perfecto.")


# -*- coding: utf-8 -*-
"""
Created on Th December 1 2022
@author: davidsantiagoquevedo
@author: ntorresd
"""

import warnings
warnings.filterwarnings('ignore')

import sys
import yaml
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

config = yaml.load(open("config.yml", "r"))["default"]

SCRIPTS_PATH = config['PATHS']['PLOT_PATH']
FIG_PATH = config['PATHS']['FIG_PATH'].format(dir = 'plots')
sys.path.append(SCRIPTS_PATH)

import results_severe_outcomes as results_severe_outcomes

fig, ax = plt.subplots(2, 3, figsize=(12, 8), sharex = True)

results_severe_outcomes.plot_ratios(ax=ax[0][1], var='HCR', var_name='HCR')
results_severe_outcomes.plot_ratios(ax=ax[0][2], var='ICU-CR', var_name=' ICU-CR')

results_severe_outcomes.plot_ratios(ax=ax[1][0], var='CFR', var_name='CFR')
results_severe_outcomes.plot_ratios(ax=ax[1][1], var='HFR', var_name='HFR')
results_severe_outcomes.plot_ratios(ax=ax[1][2], var='ICU-FR', var_name='ICU-FR')

handles, labels = ax[1][1].get_legend_handles_labels()
ax[0][0].legend(handles, labels, loc='center')
ax[0][0].axis('off')

ax[0][1].tick_params(axis='x', rotation=90)
ax[0][2].tick_params(axis='x', rotation=90)
ax[1][0].tick_params(axis='x', rotation=90)
ax[1][1].tick_params(axis='x', rotation=90)
ax[1][2].tick_params(axis='x', rotation=90)

ax[0][1].set_title('a.')
ax[0][2].set_title('b.')
ax[1][0].set_title('c.')
ax[1][1].set_title('d.')
ax[1][2].set_title('e.')

ax[0][1].set_xlabel('')
ax[0][2].set_xlabel('')
ax[1][0].set_xlabel('Age group')
ax[1][1].set_xlabel('Age group')
ax[1][2].set_xlabel('Age group')

ax[0][1].set_ylabel('Hospitalisation Case Ratio')
ax[0][2].set_ylabel('ICU Case Ratio')
ax[1][0].set_ylabel('Case Fatality Ratio')
ax[1][1].set_ylabel('Hospitalisation Fatality Ratio')
ax[1][2].set_ylabel('ICU Fatality Ratio')

fig.savefig(FIG_PATH + 'figure_3.png')


import tkinter
from tkinter import ttk

scr=tkinter.Tk()
scr.title("FirstApp")
scr.geometry("500x500")
scr.config(background="lightblue")

"""tkinter.Label(text="Firstname").pack()
tkinter.Label(text="Lastname").pack()"""

"""tkinter.Label(text="Firstname:",bg='lightblue',font='Fixedsys 15 bold',fg='purple').place(x=0,y=0)
tkinter.Label(text="Lastname:",bg='lightblue',font='Fixedsys 15 bold',fg='purple').place(x=0,y=30)"""

tkinter.Label(text="Firstname:",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=0,column=0,sticky='w')
tkinter.Label(text="Lastname:",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=1,column=0,sticky='w')

tkinter.Entry().grid(row=0,column=1,sticky='w')
tkinter.Entry().grid(row=1,column=1,sticky='w')

tkinter.Radiobutton(value=0,text="Male",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=2,column=0,sticky='w')
tkinter.Radiobutton(value=1,text="Female",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=2,column=1,sticky='w')

tkinter.Checkbutton(text="Python",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=3,column=0,sticky='w')
tkinter.Checkbutton(text="PHP",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=4,column=0,sticky='w')
tkinter.Checkbutton(text="Android",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=5,column=0,sticky='w')
tkinter.Checkbutton(text="iOS",bg='lightblue',font='Fixedsys 15 bold',fg='purple').grid(row=6,column=0,sticky='w')

city=['Rajkot','Baroda','Ahmedabad','Surat','Junagadh']
ttk.Combobox(values=city).grid(row=7,column=0)

def btnclick():
    print("This is button!")

tkinter.Button(text="Submit",font='Fixedsys 15 bold',command=btnclick).place(x=200,y=250)
tkinter.mainloop()


# collections.OrderedDict - ещё один похожий на словарь объект, но он помнит порядок, в котором ему были даны ключи.
import collections

d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
o_dict = collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))
print(o_dict)  # OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

# Методы, которых нет у обычного словаря:
# popitem(last=True) - удаляет последний элемент если last=True, и первый, если last=False.
# move_to_end(key, last=True) - добавляет ключ в конец если last=True, и в начало, если last=False.

# Подробнее тут: https://docs.python.org/3/library/collections.html#collections.OrderedDict


#!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# Magic squares and cards problem in Z3
#
# Martin Gardner (July 1971)
# '''
# Allowing duplicates values, what is the largest constant sum for an order-3
# magic square that can be formed with nine cards from the deck.
# '''
#
# This Z3 model was written by Hakan Kjellerstrand (hakank@gmail.com)
# See also my Z3 page: http://hakank.org/z3/
#
from __future__ import print_function
from z3_utils_hakank import *

def main(n=3):

  sol = SimpleSolver()

  #
  # data
  #

  #
  # declare variables
  #
  x = {}
  for i in range(n):
    for j in range(n):
      x[(i, j)] = makeIntVar(sol, "x(%i,%i)" % (i, j), 1, 13)
  x_flat = [x[(i, j)] for i in range(n) for j in range(n)]

  s = makeIntVar(sol,"s", 1, 13 * 4)
  counts = [makeIntVar(sol, "counts(%i)" % i, 0, 4) for i in range(14)]

  #
  # constraints
  #
  global_cardinality_count(sol, list(range(14)), x_flat, counts)

  # the standard magic square constraints (sans all_different)
  [sol.add(Sum([x[(i, j)] for j in range(n)]) == s) for i in range(n)]
  [sol.add(Sum([x[(i, j)] for i in range(n)]) == s) for j in range(n)]

  sol.add(Sum([x[(i, i)] for i in range(n)]) == s)  # diag 1
  sol.add(Sum([x[(i, n - i - 1)] for i in range(n)]) == s)  # diag 2

  # redundant constraint
  sol.add(Sum(counts) == n * n)

  # objective
  # sol.maximize(s)

  #
  # solution and search
  #
  num_solutions = 0
  while sol.check() == sat:
    num_solutions += 1
    mod = sol.model()
    print("s:", mod.eval(s))
    print("counts:", [mod.eval(counts[i]) for i in range(14)])
    for i in range(n):
      for j in range(n):
        print("%2i" % mod.eval(x[(i, j)]).as_long(), end=' ')
      print()
    print()
    getGreaterSolution(sol,mod,s)

  print()
  print("num_solutions:", num_solutions)

n = 3
if __name__ == "__main__":
  if len(sys.argv) > 1:
    n = int(sys.argv[1])
  main(n)


class OverlayWrapper:
    """Can send commands to the camera overlay."""

    def __init__(self, publisher):
        self.publisher = publisher

    def clear(self):
        """Show no overlay."""
        self.send("clear")

    def rage_overlay(self):
        """Show default rage overlay."""
        self.send("overlays/filter_rage.png", center=True)

    def cloud_overlay(self):
        """Show default cloud overlay."""
        self.send("overlays/filter_clouds.png", center=True)

    def send(self, overlay, x=None, y=None, width=None, height=None,
             fade_in=None, fade_out=None, center=None, stretch=None, animate=None):
        """
        Send command to camera overlay.

        :param str overlay: new overlay source
        :param float x: horizontal offset
        :param float y: vertical offset
        :param float width: image width
        :param float height: image height
        :param float fade_in: fade in duration
        :param float fade_out: fade out duration
        :param bool center: center on screen
        :param bool stretch: stretch to fit bounds
        :param bool animate: animated gif
        """

        if overlay is None:
            raise TypeError("overlay source needs to be set!")

        # Build command but only use set arguments
        args = ""
        if x is not None:
            args += f" -x {x}"
        if y is not None:
            args += f" -y {y}"
        if width is not None:
            args += f" -w {width}"
        if height is not None:
            args += f" -h {height}"
        if fade_in is not None:
            args += f" -i {fade_in}"
        if fade_out is not None:
            args += f" -o {fade_out}"
        if center:
            args += " --center"
        if stretch:
            args += " --stretch"
        if animate:
            args += " --animate"

        command = f"{overlay}{args}"
        print(f"Overlay: {command}")
        self.publisher.send(command)


# Task 1B written by Zeynep Artun

from floodsystem.stationdata import build_station_list
from floodsystem.geo import stations_by_distance
from floodsystem.utils import sorted_by_key

def print_distance(item):
    print("Station Name: {}   Distance: {}".format(item[0], item[1]))

def run():
    """Requirements for Task 1B"""

    # Build list of stations
    stations = build_station_list()

    # Print number of stations
    print("Number of stations: {}".format(len(stations)))

    result = stations_by_distance(stations, (52.2053, 0.1218))
    sorted_result = sorted_by_key(result, 1)
    first_10 = sorted_result[:10]
    last_10 = sorted_result[-10:]
    print("Closest Stations to Camrbidge City Centre\n")
    for i in first_10:
        print_distance(i)
    print("\nFurthest Stations to Cambridge City Centre\n")
    for i in last_10:
        print_distance(i)

    # # Display data from 3 stations:
    # for station in stations:
    #     if station.name in [
    #             'Bourton Dickler', 'Surfleet Sluice', 'Gaw Bridge'
    #     ]:
            # print(station)

if __name__ == "__main__":
    print("*** Task 1B: CUED Part IB Flood Warning System ***")
    run()


import numpy as np
import tables
import os
import sys
import random

path = '/home/taliah/Documents/Course/Project/new_seizure/data/6464/h5'

seed = 8767

folds = []
n = np.array([])
files = []

for filename in os.listdir(path):
	if filename[5] != '4' and filename.endswith('h5'):
		f = tables.open_file('{}/{}'.format(path,filename))
		n = np.append(n, f.root.balance_targets[:].size)
		files += [filename]
		f.close()

N = np.sum(n)

inds = np.arange(len(files))

r = np.random.RandomState(seed)

r.shuffle(inds)

count = 0
fold = []
print(N/10)

for i in range(len(files)):
	count += n[inds[i]]
	fold += [files[inds[i]]]

	if count >= (N/10- 1000):
		folds.append(fold)

		print('{}\t{}'.format(fold,count))
		fold = []
		count = 0


from src.alg.abstract.mtsp_solver import IMtspSolver
from src.common.constants import MAX_TIME_ON_ROAD

class ToursFinderParams(object):
    def __init__(self, distance_matrix=None, min_cnt_tours=None, debug=False):
        self.distance_matrix = distance_matrix
        self.min_cnt_tours   = min_cnt_tours
        self.debug           = debug

class ToursFinder:
    def __init__(self):
        pass

    def compute_tours(self,
                      tours_finder_params : ToursFinderParams,
                      solver              : IMtspSolver,
                      solver_params):

        distance_matrix = tours_finder_params.distance_matrix
        min_cnt_tours   = tours_finder_params.min_cnt_tours

        all_tours = []

        while len(all_tours) < min_cnt_tours:
            sol, cost = solver.run_mtsp(solver_params)

            tours        = sol.get_tours()
            tour_lengths = [sum(distance_matrix[x][y] for x, y in zip(tour[:-1], tour[1:])) for tour in tours]

            tours = self._filter_tours(tours, tour_lengths)

            all_tours += tours

            if tours_finder_params.debug:
                print("Generated MTSP solution, cost = {}".format(cost))

        return all_tours

    def _filter_tours(self, tours, tour_lengths):
        return list(t[0] for t in filter(lambda t: len(t[0]) > 2 and t[1] < MAX_TIME_ON_ROAD, zip(tours, tour_lengths)))


n, k = map(int, input().split())

arr = []
for x in range(n):
    name, size = input().split()
    arr.append((int(size), name))

arr.sort()

good = []

for x in range(n):
    if (x+1 < n and arr[x+1][0] - arr[x][0] <= k) or (x > 0 and arr[x][0] - arr[x-1][0] <= k):
        continue
    good.append(arr[x][1])

print(*sorted(good))


import os

from googletrans import Translator

ROOT_DIR = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop/Pearlcat/text/text_eng')
OUTPUT_DIR = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop/Pearlcat/text')

translator = Translator()

SRC = "en"
DEST = "es"

langMap = {
    "fr": "fre",
    "zh-CN": "chi",
    "es": "spa",
    "ru": "rus",
    "pt": "por",
    "ko": "kor",
    "it": "ita",
    "de": "ger",
    "ja": "jap"
}

def Translate(targetLang):
    print("TRANSLATING: " + targetLang)

    output = os.path.join(OUTPUT_DIR, "text_{dest}".format(dest = langMap[targetLang]))
    os.makedirs(output, exist_ok=True)

    for subdir, dirs, files in os.walk(ROOT_DIR):
        for i in range(len(files)):
            fileName = files[i]
            if not fileName.endswith(".txt"): continue

            print("[" + str(i + 1) + " / " + str(len(files)) + "]" + " (" + fileName + ")")

            try:
                filePath = os.path.join(subdir, fileName)
                f = open(filePath, "r")

                contents = f.readlines()
                f.close()

                firstLine = contents[0]
                contents.pop(0)

                contents = ''.join(contents)
                translated = translator.translate(contents, src=SRC, dest=targetLang).text

                text = firstLine + translated

                f = open(os.path.join(output, fileName), "w", encoding='utf-8-sig')

                f.write(text)
                f.close()

            except:
                print("TRANSLATION ERROR")

Translate("ja")

# for lang in langMap.keys():
#     Translate(lang)


import pytest

from pprint import pprint as pp
from scout.parse.case import (parse_case, parse_ped, parse_individuals,
                              parse_individual, parse_case_data,
                              removeNoneValues)
from scout.exceptions import PedigreeError
from scout.constants import REV_SEX_MAP

def test_parse_case(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should have a owner
    assert case_data['owner'] == scout_config['owner']

def test_parse_case(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case a correct case id
    assert case_data['case_id'] == scout_config['family']

def test_parse_case_madeline(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case a correct case id
    assert case_data['madeline_info']

def test_parse_case_collaborators(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should have a list with collaborators
    assert case_data['collaborators'] == [scout_config['owner']]

def test_parse_case_gene_panels(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should have the same panels like the config
    assert case_data['gene_panels'] == scout_config['gene_panels']

def test_parse_case_default_panels(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should have the same panels like the config
    assert case_data['default_panels'] == scout_config['default_gene_panels']

def test_parse_case_rank_threshold(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should have the same panels like the config
    assert case_data['rank_score_threshold'] == scout_config['rank_score_threshold']

def test_parse_case_rank_model_version(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should have the same rank model version like the config
    assert case_data['rank_model_version'] == scout_config['rank_model_version']

def test_parse_case_vcf_files(scout_config):
    # GIVEN you load sample information from a scout config
    # WHEN case is parsed
    case_data = parse_case(scout_config)
    # THEN the case should the same vcf files as specified in the
    assert case_data['vcf_files']['vcf_snv'] == scout_config['vcf_snv']
    assert case_data['vcf_files']['vcf_sv'] == scout_config['vcf_sv']
    assert case_data['vcf_files']['vcf_snv_research'] == scout_config['vcf_snv_research']
    assert case_data['vcf_files']['vcf_sv_research'] == scout_config['vcf_sv_research']

def test_parse_case_delivery_report(scout_config):
    # GIVEN you load sample information from a scout config

    # WHEN case is parsed
    case_data = parse_case(scout_config)

    # then we should find the delivery report in the parsed data
    assert case_data['delivery_report'] == scout_config['delivery_report']

def test_parse_ped_file(ped_file):
    # GIVEN a pedigree with three samples
    with open(ped_file, 'r') as case_lines:
        # WHEN parsing out relevant sample info
        family_id, samples = parse_ped(case_lines)
    # THEN it should return correct family id
    assert family_id == '643594'
    # THEN it should return correct number of individuals
    assert len(samples) == 3
    # THEN assert the sex has been converted
    for sample in samples:
        assert sample['sex'] in REV_SEX_MAP

def test_parse_case_ped_file(ped_file):
    # GIVEN a pedigree with three samples
    with open(ped_file, 'r') as case_lines:
        # WHEN parsing out relevant sample info
        config_data = parse_case_data(ped=case_lines, owner='cust000')
    # THEN it should return correct family id
    assert config_data['family'] == '643594'
    # THEN it should return correct number of individuals
    assert len(config_data['samples']) == 3

def test_parse_case_minimal_config(minimal_config):
    # GIVEN a minimal config
    # WHEN parsing the config
    case_data = parse_case(minimal_config)
    # THEN assert is was parsed correct
    assert case_data

def test_parse_ped():
    # GIVEN a pedigree with three samples
    case_lines = [
        "#Family ID\tIndividual ID\tPaternal ID\tMaternal ID\tSex\tPhenotype",
        "636808\tADM1059A1\t0\t0\t1\t1",
        "636808\tADM1059A2\tADM1059A1\tADM1059A3\t1\t2",
        "636808\tADM1059A3\t0\t0\t2\t1",
    ]

    # WHEN parsing out relevant sample info
    family_id, samples = parse_ped(case_lines)
    # THEN it should return correct family id
    assert family_id == '636808'
    # THEN it should return correct number of individuals
    assert len(samples) == 3

# ## Test how problems are handeled when parsing a case

def test_parse_case_two_cases_ped():
    # GIVEN ped lines from multiple families
    case_lines = [
        "#Family ID\tIndividual ID\tPaternal ID\tMaternal ID\tSex\tPhenotype",
        "636808\tADM1059A1\t0\t0\t1\t1",
        "636808\tADM1059A2\tADM1059A1\tADM1059A3\t1\t2",
        "636808\tADM1059A3\t0\t0\t2\t1",
        "636809\tADM1059A3\t0\t0\t2\t1",
    ]
    # WHEN parsing case info
    with pytest.raises(PedigreeError):
        # THEN it should raise since there are multiple families
        parse_ped(case_lines)

def test_no_individuals():
    # GIVEN a list with no indioviduals
    samples = []
    # WHEN parsing the individuals
    with pytest.raises(PedigreeError):
        # THEN error should be raised since a family has to have individuals
        parse_individuals(samples)

def test_parse_missing_id():
    # GIVEN a individual without sample_id
    sample_info = {
        'sex': 'male',
        'phenotype': 'affected',
    }
    # WHEN a individual is parsed
    with pytest.raises(PedigreeError):
        # THEN a PedigreeError should be raised
        parse_individual(sample_info)

def test_parse_missing_sex():
    # GIVEN a individual without sex
    sample_info = {
        'sample_id': '1',
        'phenotype': 'affected',
    }
    # WHEN a individual is parsed
    with pytest.raises(PedigreeError):
        # THEN a PedigreeError should be raised
        parse_individual(sample_info)

def test_parse_missing_phenotype():
    # GIVEN a individual without phenotype
    sample_info = {
        'sample_id': '1',
        'sex': 'male',
    }
    # WHEN a individual is parsed
    with pytest.raises(PedigreeError):
        # THEN a PedigreeError should be raised
        parse_individual(sample_info)

def test_parse_wrong_phenotype():
    # GIVEN a individual with wrong phenotype format
    sample_info = {
        'sample_id': '1',
        'sex': 'male',
        'phenotype': 'not-affected',
    }
    # WHEN a individual is parsed
    with pytest.raises(PedigreeError):
        # THEN a PedigreeError should be raised
        parse_individual(sample_info)

def test_parse_wrong_sex():
    # GIVEN a individual with wrong sex format
    sample_info = {
        'sample_id': '1',
        'sex': 'flale',
        'phenotype': 'affected',
    }
    # WHEN a individual is parsed
    with pytest.raises(PedigreeError):
        # THEN a PedigreeError should be raised
        parse_individual(sample_info)

def test_wrong_relations():
    """docstring for test_wrong_relations"""
    # GIVEN a individual with correct family info
    sample_info = {
        'sample_id': '1',
        'sex': 'male',
        'phenotype': 'affected',
        'mother': '3',
        'father': '2'
    }
    mother_info = {
        'sample_id': '3',
        'sex': 'female',
        'phenotype': 'unaffected',
        'mother': '0',
        'father': '0'
    }
    father_info = {
        'sample_id': '2',
        'sex': 'male',
        'phenotype': 'unaffected',
        'mother': '0',
        'father': '0'
    }
    samples = [sample_info, mother_info, father_info]
    # Nothong should happend here
    assert parse_individuals(samples)

    # WHEN changing mother id in proband
    sample_info['mother'] = '5'
    # THEN a PedigreeError should be raised
    with pytest.raises(PedigreeError):
        parse_individuals(samples)

def test_removeNoneValues():
    # WHEN a dict *not* containing a value which is None
    d = {"a":"1", "b":2, "c":3}

    # THEN calling removeNoneValues(dict) will not change dict
    assert d == removeNoneValues(d)

def test_removeNoneValues():
    # WHEN a dict containing a value which is None
    d = {"a":"1", "b":2, "c":None}

    # THEN calling removeNoneValues(dict) will remove key-value pair
    # where value=None
    assert {"a":"1", "b":2} == removeNoneValues(d)


import pytest

from os2mint_omada.omada.models import OmadaUser

@pytest.fixture
def omada_user() -> dict:
    """Base Omada user, as returned by the API."""
    return {
        "Id": 12345678,
        "UId": "5fe3ef67-c6e5-4d09-bdee-80b9bf40544d",
        "VALIDFROM": "2016-06-15T00:00:00+02:00",
        "VALIDTO": "2022-04-18T22:05:21+02:00",
        "IDENTITYCATEGORY": {
            "Id": 123,
            "UId": "e61de13e-d6fb-4c9e-90fd-75f9f1e1df5a",
        },
    }

def test_parse_user(omada_user: dict) -> None:
    """Test parsing of a user."""
    assert OmadaUser.parse_obj(omada_user)

def test_empty_string_is_none(omada_user: dict) -> None:
    """Test that Omada's psuedo-None empty strings are converted to true None."""

    class TestOmadaUser(OmadaUser):
        name: str | None

    omada_user["name"] = ""

    user = TestOmadaUser.parse_obj(omada_user)
    assert user.name is None

def test_fix_pseudo_infinity(omada_user: dict) -> None:
    """Test that Omada's pseudo-infinity of 31/12/9999 is converted to None."""
    omada_user["VALIDTO"] = "9999-12-31T01:00:00+01:00"
    user = OmadaUser.parse_obj(omada_user)
    assert user.valid_to is None


class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        ### method 1 (brute force) O(n^2), O(n)
        res = []
        indices = set()
        for i in range(len(intervals)-1):
            for j in range(i+1, len(intervals)):
                if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][0]:
                    res.append([min(intervals[i][0], intervals[j][0]), max(intervals[i][1], intervals[j][1])])
                    indices.add(i)
                    indices.add(j)
                elif intervals[j][0] <= intervals[i][0] and intervals[j][1] >= intervals[i][0]:
                    res.append([min(intervals[i][0], intervals[j][0]), max(intervals[i][1], intervals[j][1])])
                    indices.add(i)
                    indices.add(j)

        for i in range(len(intervals)):
            if i not in indices:
                res.append(intervals[i])
        return res

        ### method 2 (sorting, less memory)
        intervals.sort(key=lambda x:x[0])
        index = 0

        while index < len(intervals)-1:
            interval1, interval2 = intervals.pop(index), intervals.pop(index)
            if interval1[1] >= interval2[0]:
                intervals.insert(index,[interval1[0],max(interval1[1],interval2[1])])
            else:
                intervals.insert(index, interval2)
                intervals.insert(index, interval1)
                index += 1

        return intervals

        ### method 3 (sorting, more memory)
        intervals.sort(key=lambda x:x[0])
        index = 0
        res = []

        while index < len(intervals):
            if res[-1][1] >= interval[index][0]:
                res.append([res[-1][0],max(res[-1][1],interval[index][1])])
            else:
                res.append(interval[index])
                index += 1

        return res


# cook your dish here
for t in range(int(input())):
    n = int(input())
    o = map(int, input().split(' '))
    a = map(int, input().split(' '))
    o_streak = 0
    a_streak = 0
    o_max = 0
    a_max = 0
    for oi in o:
        if oi != 0:
            o_streak += 1
        else:
            o_streak = 0
        o_max = max(o_max,o_streak)
    for ai in a:
        if ai != 0:
            a_streak += 1
        else:
            a_streak = 0
        a_max = max(a_max,a_streak)
    if o_max > a_max:
        print("Om")
    elif o_max < a_max:
        print("Addy")
    else:
        print("Draw")


import pandas as pd
import glob

base_folder = "datasets-experiments-results/"
files = glob.glob(base_folder + "*")

files.sort()
data = pd.DataFrame(columns=["dataset", "model", "loss", "split_method", "n_splits", "validation_size_perc", "exec"])

for file in files:
    split = file.split("/")[-1].split("_")
    df = pd.read_parquet(file)
    df.insert(len(df.columns), "dataset", [split[0]] * len(df.index))
    df.insert(len(df.columns), "model", [split[1]] * len(df.index))
    df.insert(len(df.columns), "loss", [split[2] + "_" + split[3]] * len(df.index))
    df.insert(len(df.columns), "split_method", [split[4]] * len(df.index))
    df.insert(len(df.columns), "n_splits", [split[5]] * len(df.index))
    df.insert(len(df.columns), "validation_size_perc", [eval(split[6])] * len(df.index))
    df.insert(len(df.columns), "exec", [split[7].split(".")[0]] * len(df.index))

    data = pd.concat([data, df])

data.reset_index(inplace=True, drop=True)
data.to_parquet("datasets-benchmark-experiment-results.parquet", index=False)


import csv
import json
import os

import pandas
import pydantic_core
import torch
from py_config import read_app_config, model_dir, print_3pc_banner, data_dir
from tqdm import tqdm
from pathlib import Path

from color.extractor import ColorExtractor
from color.hsv_repository import HSVRepository
from image_handler import ImageHandler
from segmentation.segmentor import ImageSegmentor

def main():
    torch.cuda.empty_cache()
    print_3pc_banner()

    output_directory = Path(os.getenv("OUTPUT_DIRECTORY")) if os.getenv("OUTPUT_DIRECTORY") else data_dir()
    output_directory.mkdir(parents=True, exist_ok=True)

    print("""
    ###########################################################################
    # Image Segmentation (foreground | background) + Color palette extraction #
    ###########################################################################
    """)

    _app_config = read_app_config()

    # Segmentation Model
    filename = _app_config['model']['u2net']['filename']
    model_path = model_dir(filename)

    batch_size = int(_app_config['model']['u2net']['batch_size'])
    image_segmentor = ImageSegmentor(model_path, batch_size=batch_size)

    print(f"Running on device: {'cuda' if torch.cuda.is_available() else 'cpu'} | Batch size: {batch_size}")

    # Services
    image_handler = ImageHandler()
    color_repository = HSVRepository()
    color_extractor = ColorExtractor(color_repository)

    # Data
    csv_file = list(output_directory.rglob("*base64*.csv"))[0]
    print(f"using data from csv: {csv_file}")
    df = pandas.read_csv(csv_file)
    df = df[df['base64'].notnull()]

    total = len(df.index)
    print(f"total: {total}")

    image_dict = dict(zip(df.image, df.base64))
    id_dict = dict(zip(df.image, df.source_id))

    data = image_segmentor.extract_base64_masks(image_dict)

    with open(str(output_directory / Path("xcurator-color-info.csv")), "a") as w:
        writer = csv.writer(w)
        writer.writerow(["source_id", "image", "foreground", "background", "shiny", "mask_base64"])
        with tqdm(total=total) as pbar:
            for index, item in enumerate(data):

                url = item['source']
                source_id = id_dict[url]
                mask = item['mask']
                foreground = item['foreground']
                background = item['background']

                foreground_palette = color_extractor.extract_color(foreground, 7, 3)
                shiny_palette = color_extractor.shiny_colors(foreground_palette)
                background_palette = color_extractor.extract_color(background, 2, 10)
                mask_base64 = image_handler.to_base64(mask)

                ## store
                foreground = json.dumps(foreground_palette, default=pydantic_core.to_jsonable_python)
                background = json.dumps(background_palette, default=pydantic_core.to_jsonable_python)
                shiny = json.dumps(shiny_palette, default=pydantic_core.to_jsonable_python)

                writer.writerow([source_id, url, foreground, background, shiny, mask_base64])

                del item
                del mask, foreground_palette, background_palette, shiny_palette
                del foreground, background, shiny, mask_base64

                if index % 100 == 0:
                    # Flush the output CSV file
                    w.flush()

                pbar.update(1)
        w.flush()
        w.close()

if __name__ == '__main__':
    import torch.multiprocessing as mp

    mp.set_start_method('spawn', force=True)
    main()


"""
Module BaseMap
"""

import random
"""
State enum. Robots are added at run time.
"""
State = {
    "emptyWhite": -3,
    "emptyGray": -4,
    "obstacle": -1,
    "target": -2,
    # "id1": id1,
    # "id2": id2,
    # ...
}

"""
The map of the game.
"""

class BaseMap():
    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.areas = [[State["emptyWhite"]
                       for x in range(self.width)] for y in range(self.height)]
        self.targets = []
        self.obstacles = []
        # agents is dict. In convenience for finding the certain one
        self.agents = {}
        self.cluster = []

    def answerArea(self, area):
        return self.areas[area["y"]][area["x"]]

"""
God's map. God know every thing.
"""

class GodMap(BaseMap):

    def setObstacles(self, obstacles):
        self.obstacles = obstacles
        for obstacle in obstacles:
            self.areas[obstacle["y"]][obstacle["x"]] = State["obstacle"]

    def setTargets(self, targets):
        self.targets = targets
        for target in targets:
            self.areas[target["y"]][target["x"]] = State["target"]

    def setRandomObstables(self, obstacles_number):
        self.obstacles = []
        for i in range(0, obstacles_number):
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)

            while self.areas[y][x] != State['emptyWhite']:
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)

            obstacle = {"x": x, "y": y}
            self.obstacles.append(obstacle)
            self.areas[obstacle["y"]][obstacle["x"]] = State["obstacle"]

    def setRandomTargets(self, targets_number):
        self.targets = []
        for i in range(0, targets_number):
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)

            while self.areas[y][x] != State['emptyWhite']:
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)

            target = {"x": x, "y": y}
            self.targets.append(target)
            self.areas[target["y"]][target["x"]] = State["target"]

"""
The map for console. Collect information from all agents and give information
back to them.
"""

class ConsoleMap(BaseMap):

    def setAgents(self, agents):
        self.agents = agents
        for id in agents:
            agent = agents[id]
            self.areas[agent.y][agent.x] = agent.id
            self.cluster.append([])

    # update all agents position
    def updateAgents(self, agents):
        self.agents = agents
        for id in agents:
            agent = self.agents[id]
            self.areas[agent.y][agent.x] = agent.id
            area = {"x": agent.x, "y": agent.y}
            if area in self.targets:
                print("find")
                self.targets.remove(area)

    # update a agent's position
    def updateAgent(self, agent):
        self.agents[agent.id] = agent
        self.areas[agent.y][agent.x] = agent.id
        area = {"x": agent.x, "y": agent.y}
        if area in self.targets:
            self.targets.remove(area)

    # update targets information got from agent
    def updateTargets(self, targets):
        for target in targets:
            if not target in self.targets:
                self.targets.append(target)
                self.areas[target["y"]][target["x"]] = State["target"]

    # update obstacles information got from agent
    def updateObstacles(self, obstacles):
        for obstable in obstacles:
            if not obstable in self.obstacles:
                self.obstacles.append(obstable)
                self.areas[obstable["y"]][obstable["x"]] = State["obstacle"]

    def updateObserveAreas(self, areas):
        for area in areas:
            self.areas[area["y"]][area["x"]] = State["emptyGray"]


# Task 1

def divide(numerator, denominator):
    try:
        if denominator == 0:
            return 'Oops, {}/{}, division by zero is error!!!'.format(numerator, denominator)
        sum = numerator / denominator
        return 'Result is {}'.format(sum)
    except:
        return 'Value Error! You did not enter a number!'

# Task 2

import cmath

def solve_quadric_equation(a, b, c):
    try:
        if a == 0:
            return 'Zero Division Error'
        a, b, c = float(a), float(b), float(c)
        discriminant = (b**2 - 4*a*c)
        x1 = complex(-b - discriminant ** 0.5) / (2 * a)
        x2 = complex(-b + discriminant ** 0.5) / (2 * a)
        return 'The solution are x1={} and x2={}'.format(str(x1), str(x2))
    except:
        return 'Could not convert string to float'

# Task 3

class ToSmallNumberGroupError(Exception):
    def __init__(self, num):
        self.num = num

    def __str__(self):
        return repr(self.num)

def check_number_group(number):
    try:
        if isinstance(number, str):
            number = int(number)
        if number > 10:
            return 'Number of your group {} is valid'.format(number)
        if -10 < number <= 10:
            raise ToSmallNumberGroupError('Number of your group can\'t be less than 10')
    except ToSmallNumberGroupError as e:
        return 'We obtain error:' + e.num
    except:
        return 'You entered incorrect data. Please try again.'

# Task 4

class MyError(Exception):
    def __init__(self, number):
        self.number = number

    def __str__(self):
        return repr(self.number)

def check_positive(number):
    try:
        if isinstance(number, str):
            number = int(number)
        if number >= 0:
            return 'You input positive number: {}'.format(float(number))
        if number < 0:
            raise MyError('{}. Try again.'.format(float(number)))
    except MyError as e:
        return 'You input negative number: ' + e.number
    except:
        return 'Error type: ValueError!'

# Task 5

def check_odd_even(num):
    try:
        return 'Entered number is even' if (num % 2) == 0 else 'Entered number is odd'
    except:
        return 'You entered not a number.'

# Task 6

import re

def valid_email(txt):
    validator = bool(re.search(r'^([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,})', txt))
    try:
        return 'Email is valid' if validator else 'Email is not valid'
    except:
        return 'Email is not valid'

# Task 7

def day_of_week(day):
    week = {
        1: 'Monday',
        2: 'Tuesday',
        3: 'Wednesday',
        4: 'Thursday',
        5: 'Friday',
        6: 'Saturday',
        7: 'Sunday'
    }
    try:
        for key, value in week.items():
            if int(day) == key:
                return value
        if day not in range(1, 7):
            return 'There is no such day of the week! Please try again.'
    except:
        return 'You did not enter a number! Please try again.'


from commondescentvector.common_descent_vector import CommonDescentVector
import logging
import time

class MultiObjectiveCDV(CommonDescentVector):
    """ MultiObjectiveCDV class. Inherits from the CommonDescentVector
    class.

    MultiObjectiveCDV is used to return the common descent vector for
    a single objective

    Attributes:
        max_empirical_loss: A numpy array of PyTorch Tensor losses representing the max empirical
            loss for each of the objectives
        copsolver: A COPSolver used for solving the Quadratic Constraint Optimization Problem
        losses: A numpy array of PyTorch Tensor losses representing the actual loss of the objective
        gradients: A multidimensional numpy array representing the gradients of the model
        normalized: Boolean, True if the output of get_descent_vector must be normalized.
    """

    def __init__(self, copsolver, max_empirical_losses=None, normalized=False):
        """Inits MultiObjectiveCDV

        Args:
            copsolver: COPSolver object used to solve the QCOP
            max_empirical_losses: A numpy array of PyTorch Tensor losses representing the max empirical
            loss for each of the objectives
            normalized: Boolean, set to True if the output of get_descent_vector
            must be normalized. Default value: False
        """

        if copsolver is None:
            raise TypeError('Argument: copsolver cannot be NoneType')

        if max_empirical_losses is not None:
            if any(loss <= 0 for loss in max_empirical_losses):
                raise ValueError('Argument: each element of max_empirical loss should be greater than 0')

        self.__max_empirical_losses = max_empirical_losses
        self.__copsolver = copsolver
        self.__normalized = normalized

    def get_descent_vector(self, losses, gradients):
        """Compute and return the Common Descent Vector. Normalize it by the max_empirical
            loss if normalized is set to True.

        Args:
            losses: A numpy array of PyTorch Tensor losses representing the loss
            for each of the objectives.
            gradients: A numpy array of floats representing the gradients for
            each of the objectives

        Returns:
            loss: A PyTorch Tensor loss representing the Common Descent Vector
            alphas: a list of float representing the alphas from the COPSolver
        Raises:
            TypeError: An error occured when there is no objective.
        """

        if losses is None:
            raise TypeError('Argument: losses cannot be NoneType')
        if gradients is None:
            raise TypeError('Argument: gradients cannot be NoneType')
        if len(losses) == 0:
            raise ValueError('Argument: losses cannot be empty')
        if len(gradients) == 0:
            raise ValueError('Argument: gradients cannot be empty')
        if len(gradients) != len(losses):
            raise ValueError('Argument: losses and gradients array must have the same length')

        if self.__normalized:
            if self.__max_empirical_losses is None:
                raise TypeError('Argument: max_empirical_loss must be set')
            if len(losses) != len(self.__max_empirical_losses):
                raise ValueError('Argument: losses must have the same length as max_empirical_losses')
            if len(gradients) != len(self.__max_empirical_losses):
                raise ValueError('Argument: gradients must have the same length as max_empirical_losses')

            alphas = self.__solve_qcop(gradients, self.__normalized)

            for i in range(len(losses)):
                if (i == 0):
                    loss = (alphas[i]/self.__max_empirical_losses[i]) * losses[i]
                else:
                    loss += (alphas[i]/self.__max_empirical_losses[i]) * losses[i]
        else:

            alphas = self.__solve_qcop(gradients, self.__normalized)

            for i in range(len(losses)):
                if (i == 0):
                    loss = alphas[i] * losses[i]
                else:
                    loss += alphas[i] * losses[i]

        return loss, alphas

    def set_max_empirical_losses(self, max_empirical_losses):
        """Set the max empirical loss

        Args:
            max_empirical_loss: A numpy array of PyTorch Tensor loss representing the max empirical
            loss for the objective
        """

        if any(loss <= 0 for loss in max_empirical_losses):
            raise ValueError('Argument: each element of max_empirical loss should be greater than 0')

        self.__max_empirical_losses = max_empirical_losses

    def set_normalized(self, normalized):
        """Set if the CommonDescentVector should be normalized

        Args:
            normalized: True if the descent vector should be normalized
        """

        self.__normalized = normalized

    def __solve_qcop(self, gradients, normalized):
        """Solve the QCOP

        Args:
            normalized: True if the descent vector should be normalized
            gradients: A numpy array of floats representing the gradients for
            each of the objectives

        Returns:
            alphas: list of floats represting the alphas correspond to the weights
            assigned by the QCOP
        """
        logging.debug('CDV: Solving QCOP...')
        start = time.process_time()
        try:
            if (normalized):
                for i in range(len(gradients)):
                    gradients[i] /= self.__max_empirical_losses[i]
            alphas = self.__copsolver.solve(gradients)
        except Exception as err:
            logging.exception(err)
        logging.debug('QCOP completed in: %.4f' % (time.process_time() - start))

        return alphas


import pytorch_lightning as pl
import torch
from torch import nn
from torchmetrics import Accuracy
import torch.nn.functional as F

###############################
#    Multilayer Perceptron    #
###############################

IMAGE_SIZE = 28

class ResNet(pl.LightningModule):
    """
    Convolutional Neural Network (CNN) to solve MNIST with PyTorch Lightning.
    """

    def __init__(self,
            in_channels=1,
            out_channels=62,
            metric=Accuracy(num_classes=62, task="multiclass"),
            lr_rate=0.001,
            seed=None,
    ):
        # Set seed for reproducibility iniciialization
        if seed is not None:
            torch.manual_seed(seed)
            torch.cuda.manual_seed_all(seed)

        self.config = {
            'lr': 8.0505e-05,
            'beta1': 0.851436,
            'beta2': 0.999689,
            'amsgrad': True
        }
        super().__init__()
        self.metric = metric
        self.lr_rate = lr_rate

        self.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU()
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        self.layer1 = nn.Sequential(
            nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(64)
        )

        self.layer2 = nn.Sequential(
            nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(),
            nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(128)
        )
        self.log_softmax = nn.LogSoftmax(dim=1)

        # self.layer3 = nn.Sequential(
        #     nn.Conv2d(128, 512, kernel_size=3, stride=2, padding=1),
        #     nn.BatchNorm2d(512),
        #     nn.ReLU(),
        #     nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1),
        #     nn.BatchNorm2d(512)
        # )

        self.res1 = nn.Sequential(nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True)
        ), nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True))
        )

        self.res2 = nn.Sequential(nn.Sequential(
            nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True)
        ), nn.Sequential(
            nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True))
        )

        # self.res3 = nn.Sequential(nn.Sequential(
        #     nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        #     nn.BatchNorm2d(512),
        #     nn.ReLU(inplace=True)
        # ), nn.Sequential(
        #     nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        #     nn.BatchNorm2d(512),
        #     nn.ReLU(inplace=True))
        # )

        self.classifier = nn.Sequential(
            nn.AdaptiveMaxPool2d((1,1)),
            nn.Flatten(),
            nn.Linear(128, out_channels),

        )

        self.loss_fn = nn.CrossEntropyLoss()

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        # res1
        x = self.layer1(x)
        x = self.res1(x) + x

        # res2
        x = self.layer2(x)
        x = self.res2(x) + x

        # # res3
        # x = self.layer3(x)
        # x = self.res3(x) + x

        x = self.classifier(x)
        x = self.log_softmax(x)
        return x

    def configure_optimizers(self):
        """ """
        return torch.optim.Adam(self.parameters(),
                                lr=self.config['lr'],
                                betas=(self.config['beta1'], self.config['beta2']),
                                amsgrad=self.config['amsgrad'])

    def training_step(self, batch, batch_id):
        """ """
        x, y = batch
        loss = self.loss_fn(self(x), y)
        self.log("Train/Loss", loss, prog_bar=True)
        return loss

    def validation_step(self, batch, batch_idx):
        """ """
        x, y = batch
        logits = self(x)
        loss = self.loss_fn(self(x), y)
        out = torch.argmax(logits, dim=1)
        metric = self.metric(out, y)
        self.log("Validation/Loss", loss, prog_bar=True)
        self.log("Validation/Accuracy", metric, prog_bar=True)
        return loss

    def test_step(self, batch, batch_idx):
        """ """
        x, y = batch
        logits = self(x)
        loss = self.loss_fn(self(x), y)
        out = torch.argmax(logits, dim=1)
        metric = self.metric(out, y)
        self.log("Test/Loss", loss, prog_bar=True)
        self.log("Test/Accuracy", metric, prog_bar=True)
        return loss


# считываю из файла input.txt всё содержимое по строчно, где каждая строка является данными о выстпулении
# одного из выступающих актёров, в переменную InputData
with open("input.txt", "r") as iFile:
    InputData = iFile.readlines()

# создаю переменные в которых будет кол-во микрофонов для левой и правой кулис
countForLeft = 0
countForRight = 0

# создаю пременную со списком удалённых строк из InputData с данными о выступлений тех актёров,
# для которых ещё один микрофон не нужен, так как им могут передать микрофон актёры,
# которые уже выступели и уходят со сцены в то же время и через ту же кулису,
# что и эти выходящие на сцену актёры
deleted = []

del InputData[0]

# создаю функцию которая проверяет является ли содержимое параметров current и index
# элементами одного из списка в списке deleted, путём перебора списков из списка deleted
# и проверки каждого элемента одного из списка на совпадание с содержимым параметров current и index
def deleted_or_not_deleted(current, index,  deleted):
    for list in deleted:
        if list[0] == current and list[1] == index:
            return False
            break
    else:
        return True

# ниже в теле цикла fоr, проверяю есть ли элементы в списке в InputData,
# являющиеся данными о выступлении актёра, такие что,
# у одного из акёров время и кулиса ухода со сцены,
# совпадали со временем и кулисой выхода на сцену у другого,
# если совпадают и один из одновременно и через одну и ту же кулису уходящих актёров актёр предаёт микрофон только одному
# из одновременно выходящих и через эту же и одну и ту же килису актёров актёру, то из списка InputData удаляю данные
# выходящего актёра, так как для него дополнительный микрофон не нужен,
# потому что ему может передать микрофон уходящий актёр

for currentData in InputData:

    # создаю копию списка InputData без элемента currentData
    WithoutCurrent = InputData.copy()

    del WithoutCurrent[InputData.index(currentData)]

    for compareData in WithoutCurrent:

        # разбиваю строки currentData и compareData на списки из элементов,
        # которые были соедененны в строках пробелом
        currentDataArtist = currentData.split(" ")
        compareDataArtist = compareData.split(" ")

        # получаю индекс элемента, из списка WithoutCurrent,
        # в списке InputData
        index = InputData.index(compareData)

        # проверяю совпадает ли время ухода со сцены и кулиса, через которую должен уходить актёр,
        # строка с данными которого является элементом списка currentData,
        # со временем выхода актёра на сцену и кулиса, через которую должен выходить актёр,
        # строка с данными которого является элементом списка currentData,
        # так как если время совпадает, то тогда уходящий может передать микрофоно выходящиму, а значит,
        # минимальное количество микрофонов должно быть меньше на один микрофон.
        # Также с помощью функции deleted_or_not_deleted проверяю чтобы каждый из одновременно уходящих со сцены актёров
        # и через одну и ту же кулису, мог передать микрофон,
        # только одному из каждых одновременно выходящих на сцену актёров,
        # в то же время и через ту же кулису что и уходящие со сцены
        if ((currentDataArtist[1] == compareDataArtist[0]) and (currentDataArtist[3].strip() == compareDataArtist[2])
                and deleted_or_not_deleted(currentDataArtist, index,  deleted)):

            # добавляю в конец списка удалённых данных о выступлений тех актёров,
            # для которых ещё один микрофон не нужен,
            # так как им могут передать микрофон актёры данные о выступлениях которых остались в списке InputData,
            # список из строки данных о выступлении каждого из актёров, и присвоенный индекс каждому из актёров
            deleted.append([compareDataArtist, index])

            # удаляю элемент из списка InputData под индексом index
            del InputData[index]

# в теле цикла for, смотрю в строках из списка InputData,
# являющиеся данными о выступлении актёров, для каждого из которых
# нужен дополнительный микрофон,
# одна из которых при каждой отдельной итерации цикла for записывается в переменную data,
# до тех пор пока цикл не прошёлся по всем элементам списка InputData,
# из какой кулисы во время выхода на сцену актёр
# должен взять микрофон

for data in InputData:
    if data.split(" ")[2] == "l":
        countForLeft += 1
    elif data.split(" ")[2] == "r":
        countForRight += 1

# записываю количестов микрофонов для левой и правой кулис в файл output.txt
with open("output.txt", "w") as oFile:
    oFile.write(f"{countForLeft} {countForRight}")


"""
A script to select tb samples to use from Farhat et al 2019,
https://www.nature.com/articles/s41467-019-10110-6#Tab1
"""

import logging
import shutil
import urllib.request as request
from os import path
from contextlib import closing
from typing import List, Union

import numpy as np
import pandas as pd

logging.basicConfig()
logging.root.setLevel(logging.INFO)

def load_raw_data(abs_list: List[str]) -> pd.DataFrame:
    df = pd.read_excel("data/tb/41467_2019_10110_MOESM4_ESM.xlsx", engine="openpyxl")
    df = df[df.columns[:32]]  # remove empty cols created during import
    df = df.loc[
        (df["Country of Isolation"] == "Peru") & (df["DST or MIC"] == "MIC")
    ]  # majority of samples from peru
    df = df.loc[~df["Phylogenetic lineage"].isna()]
    samples_missing_tests = df[abs_list].isna().any(axis=1)
    logging.warning(f"{samples_missing_tests.sum()}/{len(df)} samples will be dropped")
    return df.loc[~samples_missing_tests]

def make_MIC_numeric(x: str) -> float:
    try:
        x = sorted([float(i) for i in x.split("-")])  # type: ignore
        return x[0] + (x[1] - x[0]) / 2  # type: ignore
    except ValueError:
        for i in range(1, 3):
            x_ = x[i:]
            try:
                return float(x_)
            except ValueError:
                pass
        raise ValueError

def parse_MIC_data(df: pd.DataFrame, abs_list: List[str]) -> pd.DataFrame:
    df = df.assign(**{i: df[i].apply(make_MIC_numeric) for i in abs_list})
    return df.assign(**{f"log2_{i}_mic": df[i].apply(np.log2) for i in abs_list})

def _assign_clade(family: Union[str, float]) -> int:
    if family == 4.3:
        return 1
    elif family == 4.1:
        return 2
    else:
        return 3

def group_into_clades(df: pd.DataFrame) -> pd.DataFrame:
    return df.assign(Clade=df["Phylogenetic lineage"].apply(_assign_clade))

def download_single_assembly(acc: str) -> bool:
    try:
        if acc.startswith("M"):
            fasta_name = f"{acc[:4]}01.fasta.gz"
            save_name = f"{acc}.fasta.gz"
            ftp_path = f"ftp://ftp.ebi.ac.uk/pub/databases/ena/wgs/public/{acc[:3].lower()}/{fasta_name}"
        elif acc.startswith("C"):
            save_name = f"{acc}.fasta"
            ftp_path = (
                f"https://www.ebi.ac.uk/ena/browser/api/fasta/{acc}.1?download=true"
            )
        else:
            raise ValueError(f"Unknown accession type: {acc}")
        destination_dir = "/home/bj515/OneDrive/work_stuff/WGS_AMR_prediction/graph_learning/data/tb/assemblies"
        destination = path.join(destination_dir, save_name)
        with closing(request.urlopen(ftp_path)) as r:
            with open(destination, "wb") as f:
                shutil.copyfileobj(r, f)
        return True
    except Exception as e:
        logging.warning(e)
        return False

def download_assemblies(df: pd.DataFrame):
    success = df["WGSAccessionNumber OR Run Accession"].apply(download_single_assembly)
    if not success.all():
        logging.error(f"Failed to download {(~success).sum()} samples")
    else:
        logging.info("Successfully downloaded all samples")

if __name__ == "__main__":
    first_line_abs = ["INH", "PZA", "EMB", "RIF"]
    df = load_raw_data(first_line_abs)
    df = df.loc[df.BioProject == "PRJNA343736\xa0"]  # only this proj has assemblies
    df = parse_MIC_data(df, first_line_abs)
    df = group_into_clades(df)
    df = df.assign(id=df["WGSAccessionNumber OR Run Accession"])
    df.to_csv("data/tb/filtered_accessions.tsv", sep="\t", index=False)


def fun(a,tar):
    for i in range(len(a)-1):
        for j in range(i+1,len(a)):
            if a[i]+a[j] == target:
                return True
            #print(i,j,end="\n")
    return False

arr = [-2,1,2,4,7,11]
target = 23

print(fun(arr,target))

#complexity of o(n^2)


#
# MazeGame v 1.0.0
# {Server side version}
# Python version
#
# SmartFoxServer PRO example file
#
# (c) 2005 - 2006 gotoAndPlay()
#

# number of players in the room
numPlayers = 0

# associative array of users in the room
users = {}

# flag that handles if the game is started
gameStarted = False

# id of the current room
currentRoomId = -1

# id of Player1
p1id = -1

# id of Player 2
p2id = -1

# Extension initialization
def init():
	pass

# Extension destroy
def destroy():
	pass

# Handle client request
def handleRequest(cmd, params, user, fromRoom, protocol):
	if protocol == "str":
		if cmd == "mv":
			handleMove(params, user)

# Handle server event
def handleInternalEvent(evt):
	global currentRoomId, numPlayers, p1id, p2id, gameStarted

	evtName = evt.getEventName()

	# Handle a user joining the room
	if evtName == "userJoin":
		# get the id of the current room
		if currentRoomId == -1:
			currentRoomId = evt.getObject("room").getId()

		# Get the user object
		u = evt.getObject("user")

		# add this user to our list of local users in this game room
		# We use the userId number as the key
		users[u.getUserId()] = u

		# Increase the number of players
		numPlayers += 1

		if u.getPlayerIndex() == 1:
			p1id = u.getUserId()
		else:
			p2id = u.getUserId()

		# If we have two players and the game was not started yet
		# it's time to start it now!
		if numPlayers == 2 and gameStarted == False:
			startGame()

	# Handle a user leaving the room or a user disconnection
	elif evtName == "userExit" or evtName == "userLost":
		# get the user id
		uId = int(evt.getParam("uid"))

		# get the playerId of the user that left the room
		if evtName == "userExit":
			oldPid = int(evt.getParam("oldPlayerIndex"))

		# get the playerId of the user that disconnected
		elif evtName == "userLost":
			pids = evt.getObject("playerIndexes")
			oldPid = pids[0]

		u = users[uId]

		# let's remove the player from the list
		del users[uId]

		numPlayers -= 1

		# game stops
		gameStarted = False

		# if one player is still in the room let's update him
		if numPlayers > 0:
			res = {}
			res["_cmd"] = "stop"
			res["n"] = u.getName()

			_server.sendResponse(res, currentRoomId, None, users.values())

# Game starts: send a message to both players
def startGame():
	global gameStarted
	gameStarted = True

	res = {}
	res["_cmd"] = "start"
	res["p1"] = {"id":p1id, "name":users[p1id].getName(), "x":1, "y":1}
	res["p2"] = {"id":p2id, "name":users[p2id].getName(), "x":22, "y":10}

	_server.sendResponse(res, currentRoomId, None, users.values())

# Handle the player move and broadcast it to the other player
def handleMove(params, user):
	if gameStarted:
		res = []
		res.append("mv")
		res.append(params[0])
		res.append(params[1])

		uid = user.getUserId()

		if uid == p1id:
			recipient = users[p2id]
		else:
			recipient = users[p1id]

		_server.sendResponse(res, currentRoomId, user, [recipient], _server.PROTOCOL_STR)


print("Welcome User")

name= input("Please enter your name:")
family= input("Please enter your family:")

print("Please enter your scores(0-20)")

l1= float(input())
l2= float(input())
l3= float(input())

if l1<0 or l2<0 or l3<0 or l1>20 or l2>20 or l3>20:

    print("Invalid input")

else:
    average=(l1+l2+l3)/3
    if average>=17:
        print("Great")
    elif average<17 and average>=12:
        print("Normal")
    elif average<12:
        print("Fail")
    print(name, family,", your average is:",average)


import tkinter

def calculate_miles_to_km():
    number = float(miles_input_miles.get())
    result = round(number * 1.60934, 3)
    miles_label_result.config(text=result)

def calculate_km_to_miles():
    number = float(km_input_miles.get())
    result = round(number / 1.60934, 3)
    km_label_result.config(text=result)

def calculate_mils_to_mm():
    number = float(mils_input_miles.get())
    result = round(number / 39.37, 3)
    mils_label_result.config(text=result)

def calculate_mm_to_mils():
    number = float(mm_input_miles.get())
    result = round(number * 39.37, 3)
    mm_label_result.config(text=result)

window = tkinter.Tk()
# window.minsize(width=100, height=100)
window.title("Mile to Km converter")
window.config(padx=20, pady=20)

# Miles to KM
miles_input_miles = tkinter.Entry()
miles_input_miles.insert(tkinter.END, string="0.0")
miles_input_miles.config(width=10, justify="center")
miles_input_miles.grid(row=0, column=1)

miles_label_miles = tkinter.Label()
miles_label_miles.config(text="miles")
miles_label_miles.grid(row=0, column=2)

miles_label_equal = tkinter.Label()
miles_label_equal.config(text="is equal to")
miles_label_equal.grid(row=1, column=0)

miles_label_result = tkinter.Label()
miles_label_result.config(text="0.0")
miles_label_result.grid(row=1, column=1)

miles_label_km = tkinter.Label()
miles_label_km.config(text="km")
miles_label_km.grid(row=1, column=2)

miles_button_calculate = tkinter.Button()
miles_button_calculate.config(text="Calculate", command=calculate_miles_to_km)
miles_button_calculate.grid(row=2, column=1)

label_space_1 = tkinter.Label()
label_space_1.grid(row=3)

# KM to Miles
km_input_miles = tkinter.Entry()
km_input_miles.insert(tkinter.END, string="0.0")
km_input_miles.config(width=10, justify="center")
km_input_miles.grid(row=4, column=1)

km_label_miles = tkinter.Label()
km_label_miles.config(text="km")
km_label_miles.grid(row=4, column=2)

km_label_equal = tkinter.Label()
km_label_equal.config(text="is equal to")
km_label_equal.grid(row=5, column=0)

km_label_result = tkinter.Label()
km_label_result.config(text="0.0")
km_label_result.grid(row=5, column=1)

km_label_km = tkinter.Label()
km_label_km.config(text="miles")
km_label_km.grid(row=5, column=2)

km_button_calculate = tkinter.Button()
km_button_calculate.config(text="Calculate", command=calculate_km_to_miles)
km_button_calculate.grid(row=6, column=1)

label_space_2 = tkinter.Label()
label_space_2.grid(row=7)

# Mils to mm
mils_input_miles = tkinter.Entry()
mils_input_miles.insert(tkinter.END, string="0.0")
mils_input_miles.config(width=10, justify="center")
mils_input_miles.grid(row=8, column=1)

mils_label_miles = tkinter.Label()
mils_label_miles.config(text="mils")
mils_label_miles.grid(row=8, column=2)

mils_label_equal = tkinter.Label()
mils_label_equal.config(text="is equal to")
mils_label_equal.grid(row=9, column=0)

mils_label_result = tkinter.Label()
mils_label_result.config(text="0.0")
mils_label_result.grid(row=9, column=1)

mils_label_km = tkinter.Label()
mils_label_km.config(text="mm")
mils_label_km.grid(row=9, column=2)

mils_button_calculate = tkinter.Button()
mils_button_calculate.config(text="Calculate", command=calculate_mils_to_mm)
mils_button_calculate.grid(row=11, column=1)

label_space_3 = tkinter.Label()
label_space_3.grid(row=12)

# mm to Mils
mm_input_miles = tkinter.Entry()
mm_input_miles.insert(tkinter.END, string="0.0")
mm_input_miles.config(width=10, justify="center")
mm_input_miles.grid(row=13, column=1)

mm_label_miles = tkinter.Label()
mm_label_miles.config(text="mm")
mm_label_miles.grid(row=13, column=2)

mm_label_equal = tkinter.Label()
mm_label_equal.config(text="is equal to")
mm_label_equal.grid(row=14, column=0)

mm_label_result = tkinter.Label()
mm_label_result.config(text="0.0")
mm_label_result.grid(row=14, column=1)

mm_label_km = tkinter.Label()
mm_label_km.config(text="mils")
mm_label_km.grid(row=14, column=2)

mm_button_calculate = tkinter.Button()
mm_button_calculate.config(text="Calculate", command=calculate_mm_to_mils)
mm_button_calculate.grid(row=15, column=1)

window.mainloop()


import gymnasium as gym
import os
from stable_baselines3 import *
import numpy as np
from custom_breakout_only_ball import CustomBreakoutOnlyBall

models_dir = "models/dqn"
log_dir = "logs"

if not os.path.exists(models_dir):
    os.makedirs(models_dir)

if not os.path.exists(log_dir):
    os.makedirs(log_dir)

env = CustomBreakoutOnlyBall()

model = DQN("MlpPolicy", env, verbose=1, tensorboard_log=log_dir)

TIMESTEPS = 10000

for i in range(1, 300):
    model.learn(total_timesteps=TIMESTEPS, reset_num_timesteps=False, tb_log_name="dqn")
    model.save(f"{models_dir}/{TIMESTEPS*i}")


import tkinter as tk
import locale
from datetime import datetime
from datetime import timedelta
import csv
import gettext
from collections import defaultdict

def select_shoes():
    # refresh variables
    my_language = language.get()
    my_choice = choice.get()

    # set the locale
    locale_functions[my_language].install()
    _ = locale_functions[my_language].gettext
    locale.setlocale(locale.LC_ALL, my_language)

    # get the price
    exchange_rate = my_prices["USD"][my_locales[language.get()]]
    USD_price = choice_to_prices[choice.get()]
    final_price = USD_price * exchange_rate
    formatted_price = locale.currency(final_price, grouping=True, international=True)

    # get delivery days
    delivery_days = choice_to_delivery_days[my_choice]

    # set up the messages
    price_message = _("The price of your selection is %(price)s.") % {'price' : formatted_price}
    arriving = _("Your order will arrive in %(days)s days.") % {'days' : delivery_days}
    total_message = " ".join([price_message, arriving])
    message.config(text = total_message)

    # refresh all prices on buttons
    price_1_USD = choice_to_prices[1]
    price_1_final = price_1_USD * exchange_rate
    price_1_formatted = locale.currency(price_1_final, grouping=True, international=True)
    price_1 = tk.Label(photo_1_frame, text=price_1_formatted, compound="top", bd=5)
    price_1.pack(side=tk.BOTTOM)

    price_2_USD = choice_to_prices[2]
    price_2_final = price_2_USD * exchange_rate
    price_2_formatted = locale.currency(price_2_final, grouping=True, international=True)
    price_2 = tk.Label(photo_2_frame, text=price_2_formatted, compound="top", bd=5)
    price_2.pack(side=tk.BOTTOM)

    price_3_USD = choice_to_prices[3]
    price_3_final = price_3_USD * exchange_rate
    price_3_formatted = locale.currency(price_3_final, grouping=True, international=True)
    price_3 = tk.Label(photo_3_frame, text=price_3_formatted, compound="top", bd=5)
    price_3.pack(side=tk.BOTTOM)

def read_forex(path):
    my_prices = defaultdict(dict)
    with open(path, "r", encoding="utf-8") as my_file:
        my_reader = csv.reader(my_file)
        data = [row for row in my_reader]
        for row in data[1:]:
            for col in range(1, len(row)):
                my_prices[row[0]].update({data[0][col] : float(row[col])})
    return my_prices

en = gettext.translation('es_MX',
                         localedir='locale',
                         languages=['es'],
                         fallback=True)
zh = gettext.translation('zh_CN',
                         localedir='locale',
                         languages=['zh'],
                         fallback=True)
ru = gettext.translation('ru_RU',
                         localedir='locale',
                         languages=['ru'],
                         fallback=True)
es = gettext.translation('es_MX',
                         localedir='locale',
                         languages=['es'],
                         fallback=True)
fr = gettext.translation('fr_FR',
                         localedir='locale',
                         languages=['fr'],
                         fallback=True)
ko = gettext.translation('ko_KR',
                         localedir='locale',
                         languages=['ko'],
                         fallback=True)
ja = gettext.translation('ja_JP',
                         localedir='locale',
                         languages=['ja'],
                         fallback=True)

locale_functions = {
    "en_US" : en,
    "zh_CN" : zh,
    "ru_RU" : ru,
    "es_MX" : es,
    "fr_FR" : fr,
    "ko_KR" : ko,
    "ja_JP" : ja}

my_locales = {
    "en_US" : "USD",
    "zh_CN" : "RMB",
    "ru_RU" : "RUB",
    "es_MX" : "MXN",
    "fr_FR" : "EUR",
    "ko_KR" : "KRW",
    "ja_JP" : "JPY",}

choice_to_prices = {
    1 : 19.99,
    2 : 29.99,
    3 : 14.99,}

choice_to_delivery_days = {
    1 : 2,
    2 : 4,
    3 : 6,}

root = tk.Tk()
root.withdraw()

root.title('Shoe Shop')
root.deiconify()

top_bar = tk.Frame(root, bd=5)
top_bar.pack(side=tk.TOP)

top = tk.Frame(root, bd=5)
top.pack(side=tk.TOP)

choice = tk.IntVar()

my_prices = read_forex('forex.csv')

photo_1_frame = tk.Frame(top)
photo_1_frame.pack(side=tk.LEFT)
photo_1 = tk.PhotoImage(file="shoes/shoes_1.png")
photo_1_label = tk.Label(photo_1_frame, image=photo_1, text="Rainbow Stars", compound="top", bd=5)
photo_1_label.pack(side=tk.TOP)
R1 = tk.Radiobutton(photo_1_frame, text="Option 1", variable=choice, value=1, command=select_shoes)
R1.pack(side=tk.BOTTOM)
price_1 = tk.Label(photo_1_frame, text="$19.99", compound="top", bd=5)
price_1.pack(side=tk.BOTTOM)
# Delivery Days: 1

photo_2_frame = tk.Frame(top)
photo_2_frame.pack(side=tk.LEFT)
photo_2 = tk.PhotoImage(file="shoes/shoes_2.png")
photo_2_label = tk.Label(photo_2_frame, image=photo_2, text="Converse", compound="top", bd=5)
photo_2_label.pack(side=tk.TOP)
R2 = tk.Radiobutton(photo_2_frame, text="Option 2", variable=choice, value=2, command=select_shoes)
R2.pack(side=tk.BOTTOM)
price_2 = tk.Label(photo_2_frame, text="$29.99", compound="top", bd=5)
price_2.pack(side=tk.BOTTOM)
# Delivery Days: 2

photo_3_frame = tk.Frame(top)
photo_3_frame.pack(side=tk.LEFT)
photo_3 = tk.PhotoImage(file="shoes/shoes_3.png")
photo_3_label = tk.Label(photo_3_frame, image=photo_3, text="Slip Ons", compound="top", bd=5)
photo_3_label.pack(side=tk.TOP)
R3 = tk.Radiobutton(photo_3_frame, text="Option 3", variable=choice, value=3, command=select_shoes)
R3.pack(side=tk.BOTTOM)
price_3 = tk.Label(photo_3_frame, text="$14.99", compound="top", bd=5)
price_3.pack(side=tk.BOTTOM)
# Delivery Days: 3

my_loc = "es"
locale.setlocale(locale.LC_ALL, my_loc)
# create a timestamp
delivery_days = 3
delivery_date = datetime.now() + timedelta(days=delivery_days)
format = "%A, %d %b %Y %H:%M:%S %Z"
delivery_date = delivery_date.strftime(format)

bottom = tk.Frame(root, borderwidth=5)
bottom.pack(side=tk.BOTTOM)

language = tk.StringVar()
language.set("en_US")
language_menu = tk.OptionMenu(top_bar, language, *locale_functions.keys())
language_menu.pack(side=tk.LEFT)

message = tk.Label(bottom)
message.pack()

tk.mainloop()


from time import time
import six
import json
from chameleon import PageTemplate
import numpy as np
import argparse

from time_limit import set_time_limit

parser = argparse.ArgumentParser()
parser.add_argument('-num_of_rows', type=int, default=400)
parser.add_argument('-num_of_cols', type=int, default=400)
args = parser.parse_args()

BIGTABLE_ZPT = """\
<table xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<tr tal:repeat="row python: options['table']">
<td tal:repeat="c python: row.values()">
<span tal:define="d python: c + 1"
tal:attributes="class python: 'column-' + %s(d)"
tal:content="python: d" />
</td>
</tr>
</table>""" % six.text_type.__name__

@set_time_limit()
def lambda_handler(event, context):
    num_of_rows = event['num_of_rows']
    num_of_cols = event['num_of_cols']

    start = time()
    tmpl = PageTemplate(BIGTABLE_ZPT)

    # 创建一个row * col的矩阵
    data = {}
    for i in range(num_of_cols):
        data[str(i)] = i

    table = [data for x in range(num_of_rows)]
    options = {'table': table}

    data = tmpl.render(options=options)
    latency = time() - start
    # print(latency)

    # result = json.dumps({'latency': latency, 'data': data})
    return latency

if __name__ == "__main__":
    event = dict()
    event['num_of_rows'] = args.num_of_rows
    event['num_of_cols'] = args.num_of_cols

    # print()
    # print("#### test: chameleon ####")
    total = list()
    for i in range(1):
        total.append(lambda_handler(event=event, context=None))
    # print("mean: " + str(np.mean(total)))
    # print("std:  " + str(np.std(total)))


from leetcode_projects.tree import TreeNode, construct_tree

class Solution:
    def sumOfLeftLeaves2(self, root: TreeNode) -> int:
        if not root:
            return 0
        return self.sum_left(root.left, True) + self.sum_left(root.right, False)

    def sum_left(self, node, left=True):
        if not node:
            return 0
        if not (node.left or node.right):
            if left:
                return node.val
            else:
                return 0
        return self.sum_left(node.left, True) + self.sum_left(node.right, False)

    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        isNodeLeaf = lambda node: not node.left and not node.right

        def dfs(node) -> int:
            ans = 0
            if node.left:
                ans += node.left.val if isNodeLeaf(node.left) else dfs(node.left)
            if node.right:
                ans += dfs(node.right) if not isNodeLeaf(node.right) else 0
            return ans

        return dfs(root) if root else 0

if __name__ == '__main__':
    s = Solution()
    l = [3, 9, 20, None, None, 15, 7]
    root = construct_tree(l)
    print(s.sumOfLeftLeaves(root))


import torch

import torchvision

from models import basicblock as B

def show_kv(net):
    for k, v in net.items():
        print(k)

# should run train debug mode first to get an initial model
#crt_net = torch.load('../../experiments/debug_SRResNet_bicx4_in3nf64nb16/models/8_G.pth')
#
#for k, v in crt_net.items():
#    print(k)
#for k, v in crt_net.items():
#    if k in pretrained_net:
#        crt_net[k] = pretrained_net[k]
#        print('replace ... ', k)

# x2 -> x4
#crt_net['model.5.weight'] = pretrained_net['model.2.weight']
#crt_net['model.5.bias'] = pretrained_net['model.2.bias']
#crt_net['model.8.weight'] = pretrained_net['model.5.weight']
#crt_net['model.8.bias'] = pretrained_net['model.5.bias']
#crt_net['model.10.weight'] = pretrained_net['model.7.weight']
#crt_net['model.10.bias'] = pretrained_net['model.7.bias']
#torch.save(crt_net, '../pretrained_tmp.pth')

# x2 -> x3
'''
in_filter = pretrained_net['model.2.weight'] # 256, 64, 3, 3
new_filter = torch.Tensor(576, 64, 3, 3)
new_filter[0:256, :, :, :] = in_filter
new_filter[256:512, :, :, :] = in_filter
new_filter[512:, :, :, :] = in_filter[0:576-512, :, :, :]
crt_net['model.2.weight'] = new_filter

in_bias = pretrained_net['model.2.bias']  # 256, 64, 3, 3
new_bias = torch.Tensor(576)
new_bias[0:256] = in_bias
new_bias[256:512] = in_bias
new_bias[512:] = in_bias[0:576 - 512]
crt_net['model.2.bias'] = new_bias

torch.save(crt_net, '../pretrained_tmp.pth')
'''

# x2 -> x8
'''
crt_net['model.5.weight'] = pretrained_net['model.2.weight']
crt_net['model.5.bias'] = pretrained_net['model.2.bias']
crt_net['model.8.weight'] = pretrained_net['model.2.weight']
crt_net['model.8.bias'] = pretrained_net['model.2.bias']
crt_net['model.11.weight'] = pretrained_net['model.5.weight']
crt_net['model.11.bias'] = pretrained_net['model.5.bias']
crt_net['model.13.weight'] = pretrained_net['model.7.weight']
crt_net['model.13.bias'] = pretrained_net['model.7.bias']
torch.save(crt_net, '../pretrained_tmp.pth')
'''

# x3/4/8 RGB -> Y

def rgb2gray_net(net, only_input=True):

    if only_input:
        in_filter = net['0.weight']
        in_new_filter = in_filter[:,0,:,:]*0.2989 + in_filter[:,1,:,:]*0.587 + in_filter[:,2,:,:]*0.114
        in_new_filter.unsqueeze_(1)
        net['0.weight'] = in_new_filter

#    out_filter = pretrained_net['model.13.weight']
#    out_new_filter = out_filter[0, :, :, :] * 0.2989 + out_filter[1, :, :, :] * 0.587 + \
#        out_filter[2, :, :, :] * 0.114
#    out_new_filter.unsqueeze_(0)
#    crt_net['model.13.weight'] = out_new_filter
#    out_bias = pretrained_net['model.13.bias']
#    out_new_bias = out_bias[0] * 0.2989 + out_bias[1] * 0.587 + out_bias[2] * 0.114
#    out_new_bias = torch.Tensor(1).fill_(out_new_bias)
#    crt_net['model.13.bias'] = out_new_bias

#    torch.save(crt_net, '../pretrained_tmp.pth')

    return net

if __name__ == '__main__':

    net = torchvision.models.vgg19(pretrained=True)
    for k,v in net.features.named_parameters():
        if k=='0.weight':
            in_new_filter = v[:,0,:,:]*0.2989 + v[:,1,:,:]*0.587 + v[:,2,:,:]*0.114
            in_new_filter.unsqueeze_(1)
            v = in_new_filter
            print(v.shape)
            print(v[0,0,0,0])
        if k=='0.bias':
            in_new_bias = v
            print(v[0])

    print(net.features[0])

    net.features[0] = B.conv(1, 64, mode='C')

    print(net.features[0])
    net.features[0].weight.data=in_new_filter
    net.features[0].bias.data=in_new_bias

    for k,v in net.features.named_parameters():
        if k=='0.weight':
            print(v[0,0,0,0])
        if k=='0.bias':
            print(v[0])

    # transfer parameters of old model to new one
    model_old = torch.load(model_path)
    state_dict = model.state_dict()
    for ((key, param),(key2, param2)) in zip(model_old.items(), state_dict.items()):
        state_dict[key2] = param
        print([key, key2])
       # print([param.size(), param2.size()])
    torch.save(state_dict, 'model_new.pth')

   # rgb2gray_net(net)