# Write a program that keeps the information about products and their prices.
# Each product has a name, a price, and a quantity:
# •	If the product doesn't exist yet, add it with its starting quantity.
# •	If you receive a product, which already exists, increases its quantity by the input quantity and if its price is
# different, replace the price as well.
# You will receive products' names, prices, and quantities on new lines. Until you receive the command "buy", keep
# adding items. Finally, print all items with their names and the total price of each product.
# Input
# •	Until you receive "buy", the products will be coming in the format: "{name} {price} {quantity}".
# •	The product data is always delimited by a single space.
# Output
# •	Print information about each product in the following format:
# "{product_name} -> {total_price}"
# •	Format the total price to the 2nd digit after the decimal separator.

def calc_price(input_name: str, input_price: float, input_quantity: int, input_products: dict):
    if input_name not in input_products:
        input_products[input_name] = [input_quantity, input_price]
    else:
        input_products[input_name][0] += input_quantity
        input_products[input_name][1] = input_price

    return input_products

products = {}
command = input()

while command != "buy":
    name, price, quantity = command.split()
    products = calc_price(name, float(price), int(quantity), products)

    command = input()

for product, total_price in products.items():
    print(f"{product} -> {(total_price[0] * total_price[1]):.2f}")


import os

# Obtener la ruta del escritorio
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")

# Crear la ruta completa del archivo
file_path = os.path.join(desktop_path, "instalacion.txt")

# Pregunta el número de OT y si es NEBA
numero_ot = input("Introduce el número de OT: ")
es_neba = input("¿La instalación es NEBA? (s/n): ")

# Variable global retirar CM
retirar_cm = ""

#defines funcion para escribir
def global_cm():
    global retirar_cm

# Variable global retirar Deco HD
retirar_deco_hd = ""

# Definir una función global de retirar deco para llamar a la variable fuera del If
def global_deco_hd():
    # Acceder a la variable global
    global retirar_deco_hd

# Abrir el archivo en modo de escritura (si no existe, se crea)
with open(file_path, "w") as file:
    # Registrar número de OT y si es NEBA
    file.write(f"Número de OT: {numero_ot}\n")

    # Preguntar sobre la instalación precableada
    instalacion_precableada = input("¿La instalación es precableada? (s/n): ")

    sn_retro=input("¿Es retrofit? (s/n): ")

    if instalacion_precableada.lower() == "s":
        cableada_por = input("¿Quien precableo? ")
        file.write(f"Instalación precableada por {cableada_por}\n")

    # Preguntar sobre la reasignación del CTO
    reasignar_cto = input("¿Se reasigna la CTO? (s/n): ")

    if reasignar_cto.lower() == "s":
        cto_habia = input("¿Qué CTO había anteriormente? ")
        cto_nueva = input("¿Qué CTO se instala ahora? ")
        puerto = input("¿En qué puerto se reasigna? ")
        file.write(f"Se reasigna CTO de {cto_habia} a {cto_nueva} en el puerto {puerto}\n")

        # Preguntar sobre la acometida exterior
    if instalacion_precableada.lower() == "n":
        acometida_exterior = input("¿Se instala acometida exterior? (s/n): ")

        if acometida_exterior.lower() == "s":
            acometida_uso = input("¿Qué tipo de acometida se utilizó? (huawei/corning/zte): ")
            acometida_total = input("¿Cuántos metros era la acometida? ")
            acometida_utilizada = input("¿Cuántos metros de acometida se utilizaron? ")
            file.write(f"Se instala acometida exterior {acometida_uso} de {acometida_total} metros y se utilizan {acometida_utilizada} metros\n")

        if instalacion_precableada.lower() == "n" and acometida_exterior.lower() == "n":
            # Preguntar sobre la acometida interior
            acometida_total_interior = input("¿De cuantos metros era la acometida de interior? ")
            acometida_utilizada = input("¿Cuantos metros de acometidad de interior se utilizaron? ")
            file.write(f"Se instala acometida interior de {acometida_total_interior} metros y se utilizan {acometida_utilizada} metros\n")

    file.write("Se instalan equipos en ubicaciones indicadas por el cliente.\n")

    if es_neba.lower() == "s":
        # Preguntar sobre la ONT y el Router
        modelo_ont = input("Introduce el modelo de ONT: ")
        mac_ont = input("Introduce la MAC de la ONT: ")
        modelo_router = input("Introduce el modelo de Router: ")
        mac_router = input("Introduce la MAC del Router: ")
        serial_router = input("Introduce el serial del Router: ")
        file.write(f"Se instala ONT {modelo_ont} con MAC {mac_ont}.\n ")
        file.write(f"Se instala Router {modelo_router} con MAC {mac_router} y serial {serial_router}.\n")
    else:
        # Preguntar sobre la MAC y el serial del Router
        router_noneba =input("Dime el modelo del Router: ")
        mac_router = input("Introduce la MAC del Router: ")
        serial_router = input("Introduce el serial del Router: ")
        file.write(f"Se instala Router {router_noneba} con MAC {mac_router} y serial {serial_router}.\n")

    # Preguntar sobre la retirada de CM o Deco HD
    if sn_retro.lower()=="s":
        retirar_cm = input("¿Se retira un CM? (s/n): ")

        if retirar_cm.lower() == "s":
            modelo_cm = input("Introduce el modelo del CM: ")
            mac_cm = input("Introduce la MAC del CM: ")
            file.write(f"Se retira CM {modelo_cm} con MAC {mac_cm}.\n")

        retirar_deco_hd = input("¿Se retira un Deco HD? (s/n): ")

        if retirar_deco_hd.lower() == "s":
            modelo_deco_hd = input("Introduce el modelo del Deco HD: ")
            caid_deco_hd = input("Introduce el CAID del Deco HD: ")
            file.write(f"Se retira Deco HD {modelo_deco_hd} con CAID {caid_deco_hd}.\n")

    instalar_decodificador = input("¿Se ha instalado decodificador? (s/n): ")

    if instalar_decodificador.lower() == "s":
        modelo_decodificador = input("Introduce el modelo del decodificador: ")
        caid_decodificador = input("Introduce el CAID del decodificador: ")
        file.write(f"Se instala decodificador 4K {modelo_decodificador} con CAID {caid_decodificador}.\n")

    instalar_wifimesh = input("¿Se ha instalado WiFiMesh? (s/n): ")

    if instalar_wifimesh.lower() == "s":
        serial1_wifimesh = input("Serial WIFIMESH 1: ")
        serial2_wifimesh = input("Serial WIFIMESH 2: ")
        file.write(f"Se instala pareja WiFi Mesh con serial {serial1_wifimesh} y {serial2_wifimesh}.\n")

    conectar_tomas_telefono = input("¿Se dejan conectadas las tomas de teléfono? (s/n): ")

    if conectar_tomas_telefono.lower() == "no":
        file.write("No se dejan conectadas las tomas de teléfono a la ONT a petición del cliente.\n")
    else:
        file.write("Se dejan conectadas las tomas de teléfono a la ONT a petición del cliente.\n")

    instalar_cable_telefono = input("¿Se ha instalado cable de telefono? (s/n): ")

    if instalar_cable_telefono.lower() == "s":
        metros_cable = input("Introduce metros de cable de telefono: ")
        file.write(f"Se instala cable de telefono de {metros_cable} m.\n")

    instalar_cable_datos = input("¿Se ha instalado cable de datos? (s/n): ")

    if instalar_cable_datos.lower() == "s":
        metros_cable_datos = input("Introduce metros de cable de datos: ")
        file.write(f"Se instala cable de datos de {metros_cable_datos} m.\n")

    link_speedtest = input("Introduce el enlace del Speedtest: ")
    link_kiron_ftth = input("Introduce el enlace de Kiron FTTH: ")
    link_voip = input("Introduce el enlace de VoIP: ")
    file.write(f"Link Speedtest: {link_speedtest}\n")
    file.write(f"Link Kiron FTTH: {link_kiron_ftth}\n")
    file.write(f"Link VoIP: {link_voip}\n")

    if instalar_decodificador.lower() == "s":
        link_kirontv4k = input("Introduce el enlace de KironTV4K: ")
        file.write(f"Link KironTV4K: {link_kirontv4k}\n")

    file.write(f" \n")

    file.write(f"--------------------Aqui van los enlaces de ulises--------------------\n")

    file.write(f" \n")

    if es_neba.lower() == "s":
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?instalado={mac_router}&returnwa=instalado&nordenBC={numero_ot}\n")
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?instalado={mac_ont}&returnwa=instalado&nordenBC={numero_ot}\n")

    if instalar_decodificador.lower() == "s":
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?instalado={caid_decodificador}&returnwa=instalado&nordenBC={numero_ot}\n")

    if instalar_wifimesh.lower() == "s":
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?instalado={serial1_wifimesh}&returnwa=instalado&nordenBC={numero_ot}\n")
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?instalado={serial2_wifimesh}&returnwa=instalado&nordenBC={numero_ot}\n")

    if retirar_deco_hd.lower() == "s":
        global_deco_hd()
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?retirado={caid_deco_hd}&returnwa=masmovil&nordenBC={numero_ot}&TipoEquipoRetirado=1595&TipoRecogida=1\n")

    if retirar_cm.lower() == "s":
        global_cm()
        file.write(f"https://ulises2.obremo.es/obremowa/movil/mEquiposMundoRReportados.aspx?retirado={mac_cm}&returnwa=masmovil&nordenBC={numero_ot}&TipoEquipoRetirado=1595&TipoRecogida=1\n")

    # Mostrar un mensaje de confirmación
    print(f"El archivo '{file_path}' se ha generado exitosamente.")


import json
from datetime import datetime
import uuid
import os
import boto3

# set env variables
DATETIME = os.environ['GET_DATETIME']
UUID = os.environ['GET_UUID']
QUEUE_URL = os.environ['QUEUE_URL']

def lambda_handler(event, context):
    apiEvent = event['rawPath']
    sqs = boto3.resource('sqs')
    queue = sqs.Queue(QUEUE_URL)

    try:
        if apiEvent == DATETIME:
            message = datetime.strftime(
                datetime.now(), "%m-%d-%Y, %I:%M:%S %p (UTC)")

        elif apiEvent == UUID:
            message = str(uuid.uuid4())

        else:
            print(f"Error: '{apiEvent}' does not exist.")

        print(message)

        response = queue.send_message(MessageBody=message)

        print(f"MessageID: '{response['MessageId']}' sent to queue.")

        return json.dumps(message)

    except Exception as e:
        print(e)


#EXERCISE 3:
#Write a program that opens the dna.txt file and calculates the total number of bases,
# and the number of the different bases
#You must use a loop for counting the bases, Suppose that the DNA files always contains correct sequences

filename = open('dna.txt', 'r')
text = filename.read()
filename.close()

count_A = 0
count_C = 0
count_T = 0
count_G = 0

print("Total length: ", len(text))

for i in text:
    if i == 'A':
        count_A = count_A + 1
    elif i == 'C':
        count_C = count_C + 1
    elif i == 'G':
        count_G = count_G + 1
    elif i == 'T':
        count_T = count_T + 1

print("A: ", count_A)
print("C: ", count_C)
print("G: ", count_G)
print("T: ", count_T)


import matplotlib.pyplot as plt
from keras.datasets import mnist
import numpy as np
import glob

images = []
labels = []
for path in glob.glob("/Users/vineet/Desktop/cnn/English/img/GoodImg/Bmp/Sample*"):
#     print(path)
#     for img in glob.glob("/Users/vineet/Desktop/cnn/English/img/GoodImg/Bmp/Sample001/*.png"):
    for img in glob.glob(path+"/*.png"):
#         print(img)
        n= plt.imread(img)
        images.append(np.resize(n,(32,32,3)))
        prefix = img.split("/Sample")
        prefix = prefix[1].split("/")
        labels.append(prefix[0])

image2 = np.array(images)
image2.shape

labels = np.array(labels)
labels.shape

from keras.utils import to_categorical
labels = to_categorical(labels)

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten,MaxPooling2D
#create model
model = Sequential()
#add model layers
model.add(Conv2D(filters = 32, kernel_size=(4,4), activation="relu",input_shape = (32,32,3)))
model.add(Conv2D(64, kernel_size=(4,4), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(4,4), activation="relu"))
model.add(Conv2D(10, kernel_size=(4,4), activation="relu"))
model.add(MaxPooling2D(pool_size=(4, 4)))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(80, activation='relu'))
model.add(Dense(63, activation="softmax"))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.fit(image2, labels, epochs=5)


import tensorflow as tf
import tensorflow_datasets as tfds

# Get Data
imdb,info = tfds.load('imdb_reviews/subwords8k',as_supervised=True,with_info=True)
train_dataset,test_dataset = imdb['train'],imdb['test']

# Encode and Decode string
encoder = info.features['text'].encoder
print(f'Vocabulary size: {encoder.vocab_size}')

sample_string = 'Hello Tensorflow'
encoded_string = encoder.encode(sample_string)
original_string = encoder.decode(encoded_string)
print(f'Encoded String: {encoded_string}')
print(f'Orginal String: {original_string}')
for index in encoded_string:
  print('{} ----> {}'.format(index, encoder.decode([index])))

# Create Dataset
BUFFER_SIZE = 10000
BATCH_SIZE = 64

train_dataset = train_dataset.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.padded_batch(BATCH_SIZE)

test_dataset = test_dataset.padded_batch(BATCH_SIZE)

# Model
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(encoder.vocab_size,16),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(8)),
    tf.keras.layers.Dense(8,activation='relu'),
    tf.keras.layers.Dense(1)
])

def compile_fit(model):

    model.compile(
        optimizer='adam',
        loss='binary_crossentropy',
        metrics=['acc']
    )

    history = model.fit(train_dataset,
        validation_data = test_dataset,
        epochs=5
    )

history = compile_fit(model)

test_loss, test_acc = model.evaluate(test_dataset)
print('Test Loss: {}'.format(test_loss))
print('Test Accuracy: {}'.format(test_acc))


# coding:utf-8

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense
import matplotlib.pyplot as plt
np.random.seed(9)

class RnnRegressor(object):
    def __init__(self, *, input_path, look_back, batch_size, epochs):
        # data prepare
        self.__file = pd.read_csv(input_path, usecols=[1]).values
        self.__look_back = look_back
        self.__X, self.__y = [None for _ in range(2)]
        self.__train_scaler, self.__test_scaler = [None for _ in range(2)]
        self.__train, self.__train_label, self.__test, self.__test_label = [None for _ in range(4)]

        # function set
        self.__net = None

        # goodness of function
        self.__batch_size = batch_size

        # pick the best function
        self.__epochs = epochs

    def data_prepare(self):
        def create_X_y(file=self.__file, look_back=self.__look_back):
            X = []
            y = []
            for i in range(len(file) - look_back - 1):
                X.append(file[i:(i+look_back), 0])
                y.append(file[i+look_back, 0])
            return np.array(X).reshape((-1, look_back)), np.array(y).reshape((-1, 1))
        self.__X, self.__y = create_X_y()

        self.__train, self.__test, self.__train_label, self.__test_label = train_test_split(
            self.__X,
            self.__y,
            test_size=0.2,
            shuffle=False
        )

        self.__train_scaler = StandardScaler().fit(self.__train)
        self.__train = self.__train_scaler.transform(self.__train)
        self.__test = self.__train_scaler.transform(self.__test)
        self.__train = self.__train.reshape((-1, self.__look_back, 1))
        self.__test = self.__test.reshape((-1, self.__look_back, 1))

        self.__test_scaler = StandardScaler().fit(self.__train_label)
        self.__train_label = self.__test_scaler.transform(self.__train_label)

    def function_set(self):
        self.__net = Sequential([
            LSTM(units=4, input_length=self.__look_back, input_dim=1),
            Dense(1)
        ])

    def goodness_of_function(self):
        self.__net.compile(loss="mse",optimizer="adam")

    def pick_the_best_function(self):
        self.__net.fit(self.__train, self.__train_label, batch_size=self.__batch_size, epochs=self.__epochs, verbose=2)
        plt.plot(self.__test_scaler.inverse_transform(self.__net.predict(self.__test)))
        plt.plot(self.__test_label)
        plt.show()

if __name__ == "__main__":
    rr = RnnRegressor(
        input_path="international-airline-passengers.csv",
        look_back=3,
        batch_size=1,
        epochs=200
    )
    rr.data_prepare()
    rr.function_set()
    rr.goodness_of_function()
    rr.pick_the_best_function()


import asyncio
import logging
from typing import Optional

import discord
from redbot.core import commands
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.utils.predicates import ReactionPredicate

from .abc import MixinMeta
from .converters import RealEmojiConverter

log = logging.getLogger("red.maxcogs.onconnect")

class Commands(MixinMeta):
    """Commands for managing the cog's settings are found here."""

    @commands.is_owner()
    @commands.guild_only()
    @commands.group(name="connectset")
    async def _connectset(self, ctx: commands.Context) -> None:
        """Settings for shard event logging."""

    @_connectset.command(name="channel", usage="[channel]")
    @commands.bot_has_permissions(add_reactions=True)
    async def _channel(
        self, ctx, *, channel: Optional[discord.TextChannel] = None
    ) -> None:
        """Set the channel to log shard events to.

        **Example:**
        - `[p]connectset channel #general`
        This will set the event channel to general.

        **Arguments:**
        - `[channel]` - Is where you set the event channel. Leave it blank to disable.
        """
        embed_requested = await ctx.embed_requested()
        if channel:
            if channel.permissions_for(ctx.guild.me).embed_links is False:
                return await ctx.send(
                    f"I do not have the `embed_links` permission in {channel.mention}."
                )

            await self.config.statuschannel.set(channel.id)
            log.info(f"Status Channel set to {channel} ({channel.id})")
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description=f"Events will now be sent to {channel.mention}.",
                    colour=await ctx.embed_colour(),
                )
                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(
                    ctx=ctx, message=f"Events will now be sent to {channel.mention}."
                )

        elif await self.config.statuschannel() is not None:
            if embed_requested:
                embed = discord.Embed(
                    title="Are you sure you want to disable events?",
                    colour=await ctx.embed_colour(),
                )
                msg = await ctx.send(embed=embed)
            else:
                msg = await ctx.send("Are you sure you want to disable events?")

            start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)
            pred = ReactionPredicate.yes_or_no(msg, ctx.author)
            try:
                await self.bot.wait_for("reaction_add", check=pred, timeout=60)
            except asyncio.TimeoutError:
                await self.maybe_reply(
                    ctx=ctx,
                    message="You took too long to respond, cancelling.",
                    mention_author=True,
                )
                await msg.clear_reactions()
            else:
                if pred.result is True:
                    await self.config.statuschannel.set(None)
                    log.info("Status Channel has been disabled.")
                    if embed_requested:
                        embed = discord.Embed(
                            title="Setting Changed",
                            description="Events have been disabled.",
                            colour=await ctx.embed_colour(),
                        )
                        await self.maybe_reply(ctx=ctx, embed=embed)
                    else:
                        await self.maybe_reply(
                            ctx=ctx, message="Events have been disabled."
                        )
                else:
                    await self.maybe_reply(ctx=ctx, message="Cancelled.")
        else:
            await self.maybe_reply(
                ctx=ctx,
                message=(
                    f"Events are already disabled. Use `{ctx.clean_prefix}connectset "
                    "channel #channel` to enable."
                ),
                mention_author=True,
            )

    @_connectset.group(name="emoji", aliases=["emojis"])
    async def _emoji(self, ctx: commands.Context):
        """Settings to change default emoji.

        NOTE: If you want to set custom emojis, your bot needs to share the same server
        as the custom emoji.
        """

    @_emoji.command(name="green", usage="[emoji]")
    async def _emoji_green(
        self, ctx: commands.Context, *, emoji: Optional[RealEmojiConverter] = None
    ) -> None:
        """Change the green emoji to your own.

        **Example:**
        - `[p]connectset emoji green :green_heart:`
        This will change the green emoji to :green_heart:.

        **Arguments:**
        - `[emoji]` - Is where you set the emoji. Leave it blank to reset.
        """
        embed_requested = await ctx.embed_requested()
        if not emoji:
            await self.config.green.clear()
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description="The green emoji has been reset.",
                    color=await ctx.embed_color(),
                )

                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(
                    ctx=ctx, message="The green emoji has been reset."
                )
        else:
            await self.config.green.set(str(emoji))
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description=f"The green emoji has been set to {emoji}.",
                    color=await ctx.embed_color(),
                )
                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(
                    ctx=ctx, message=f"The green emoji has been set to {emoji}."
                )

    @_emoji.command(name="orange", usage="[emoji]")
    async def _emoji_orange(
        self, ctx: commands.Context, *, emoji: Optional[RealEmojiConverter] = None
    ) -> None:
        """Change the orange emoji to your own.

        **Example:**
        - `[p]connectset emoji orange :orange_heart:`
        This will change the orange emoji to :orange_heart:.

        **Arguments:**
        - `[emoji]` - Is where you set the emoji. Leave it blank to reset.
        """
        embed_requested = await ctx.embed_requested()
        if not emoji:
            await self.config.orange.clear()
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description="The orange emoji has been reset.",
                    color=await ctx.embed_color(),
                )

                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(
                    ctx=ctx, message="The orange emoji has been reset."
                )
        else:
            await self.config.orange.set(str(emoji))
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description=f"The orange emoji has been set to {emoji}.",
                    color=await ctx.embed_color(),
                )
                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(
                    ctx=ctx, message=f"The orange emoji has been set to {emoji}."
                )

    @_emoji.command(name="red", usage="[emoji]")
    async def _emoji_red(
        self, ctx: commands.Context, *, emoji: Optional[RealEmojiConverter] = None
    ) -> None:
        """Change the red emoji to your own.

        **Example:**
        - `[p]connectset emoji red :heart:`
        This will change the red emoji to :heart:.

        **Arguments:**
        - `[emoji]` - Is where you set the emoji. Leave it blank to reset.
        """
        embed_requested = await ctx.embed_requested()
        if not emoji:
            await self.config.red.clear()
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description="The red emoji has been reset.",
                    color=await ctx.embed_color(),
                )

                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(ctx=ctx, message="The red emoji has been reset.")
        else:
            await self.config.red.set(str(emoji))
            if embed_requested:
                embed = discord.Embed(
                    title="Setting Changed",
                    description=f"The red emoji has been set to {emoji}.",
                    color=await ctx.embed_color(),
                )
                await self.maybe_reply(ctx=ctx, embed=embed)
            else:
                await self.maybe_reply(
                    ctx=ctx, message=f"The red emoji has been set to {emoji}."
                )

    @_connectset.command(name="showsettings", aliases=["settings"])
    async def _show_settings(self, ctx: commands.Context) -> None:
        """Shows the current settings for OnConnect."""
        config = await self.config.all()
        chan_config = config["statuschannel"]
        status_channel = f"<#{chan_config}>" if chan_config else "Not set."
        green_emoji = config["green"]
        orange_emoji = config["orange"]
        red_emoji = config["red"]
        if await ctx.embed_requested():
            embed = discord.Embed(
                title="OnConnect Settings",
                description=f"**Status Channel:** {status_channel}",
                colour=await ctx.embed_colour(),
            )
            embed.add_field(name="Green Emoji:", value=green_emoji)
            embed.add_field(name="Orange Emoji:", value=orange_emoji)
            embed.add_field(name="Red Emoji:", value=red_emoji)
            await self.maybe_reply(ctx=ctx, embed=embed)
        else:
            message = (
                "**OnConnect Settings**\n"
                f"Status Channel: {status_channel}\n"
                f"Green Emoji: {green_emoji}\n"
                f"Orange Emoji: {orange_emoji}\n"
                f"Red Emoji: {red_emoji}"
            )
            await self.maybe_reply(ctx=ctx, message=message)

    @_connectset.command(name="version")
    async def _version(self, ctx: commands.Context) -> None:
        """Shows the cog version."""
        message = f"Author: {self.__author__}\nVersion: {self.__version__}"
        if await ctx.embed_requested():
            embed = discord.Embed(
                title="Cog Version:",
                description=message,
                colour=await ctx.embed_colour(),
            )
            await self.maybe_reply(ctx=ctx, embed=embed)
        else:
            await self.maybe_reply(ctx=ctx, message=f"**Cog Version:**\n{message}")


"""
https://leetcode.com/problems/add-two-numbers/
"""
from itertools import zip_longest

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 리스트노드를 array 자료구조로 변환
def trans_to_arr(head):
    nums = []
    while head:
        nums.append(head.val)
        head = head.next
    return nums

# array를 리스트노드로 변환
def trans_to_list(nums):
    dummy = cur = ListNode(0)
    for n in nums:
        cur.next = ListNode(n)
        cur = cur.next
    return dummy.next

class Solution:
    def sol1(self, l1, l2):
        nums1 = trans_to_arr(l1)
        nums2 = trans_to_arr(l2)

        # 두 수 더하기 연산
        res = []
        carry = 0
        for n1, n2 in zip_longest(nums1, nums2, fillvalue=0):
            carry, remainder = divmod(n1 + n2 + carry, 10)
            res.append(remainder)
        if carry == 1:
            res.append(1)

        return trans_to_list(res)

    def sol2(self, l1, l2):
        dummy = cur = ListNode(0)
        carry = 0
        while l1 or l2 or carry:
            cur.next = ListNode()
            cur = cur.next
            n1, n2 = 0, 0
            if l1:
                n1 = l1.val
                l1 = l1.next
            if l2:
                n2 = l2.val
                l2 = l2.next

            carry, remainder = divmod(n1 + n2 + carry, 10)
            cur.val = remainder

        return dummy.next

    def addTwoNumbers(self, l1, l2):
        #return self.sol1(l1, l2)
        return self.sol2(l1, l2)

l1 = trans_to_list([2, 4, 3])
l2 = trans_to_list([5, 6, 4])

sol = Solution()
head = sol.addTwoNumbers(l1, l2)
assert trans_to_arr(head) == [7, 0, 8]

leetcode/01_medium/2. Add Two Numbers.py


from __future__ import unicode_literals
import pytest  # noqa
from textx import metamodel_from_str

grammar = """
Shape:
    'shape'
    points+=Point
    'end'
;
Point:
    'point' x=INT y=INT
;
"""

def test_user_class_with_slots():
    """
    User supplied meta class.
    """
    class Point(object):
        "User class."
        __slots__ = ['parent', 'x', 'y']

        def __init__(self, parent, x, y):
            self.parent = parent
            self.x = x
            self.y = y

    modelstr = """
    shape
    point 34 45
    point 12 23
    end
    """

    mm = metamodel_from_str(grammar, classes=[Point],
                            auto_init_attributes=False)
    model = mm.model_from_str(modelstr)
    # Test that user class is instantiated
    point = model.points[0]

    assert type(point).__name__ == "Point"
    assert type(point) is Point

    assert len(model.points) == 2
    assert point.x == 34
    assert point.y == 45


'''
풀이

처음부터 brute force로 풀면 되는 거를 괜히 꼼수부리려다가 6번이나 틀렸다.
'''

def findButton(order, channel, length, n, availableBtn):
    if order == length:
        return channel

    minNum = 5000001
    minChannel = 0
    for i in availableBtn:
        currChannel = findButton(order + 1, channel * 10 + i, length, n, availableBtn)
        if minNum > abs(n - currChannel):
            minNum = abs(n - currChannel)
            minChannel = currChannel
    return minChannel

n = int(input())
m = int(input())
if m == 0:
    brokenBtn = []
else:
    brokenBtn = list(map(int, input().split()))

if m == 10:
    print(abs(n - 100))
else:
    availableBtn = [i for i in range(10) if i not in brokenBtn]

    availableCase = [abs(n - 100)]
    for i in range(1, 7):
        btnCount = findButton(0, 0, i, n, availableBtn)
        availableCase.append(abs(n - btnCount) + i)
    print(min(availableCase))


#! /usr/bin/python3
# -------------------------------------------------------------------------
from serial     import *
from time       import time, sleep
from os         import system
from WiiProxy   import MultiWii
#from UDP        import UDP
# -------------------------------------------------------------------------
class Init(object):
    # ---------------------------------------------------------------------
    c = None
    s = None
    TAKEOFF_TIME = 5   # in seconds
    LAND_TIME = 10   # in seconds
    HOVER_THROTTLE = 1200
    RATIO = (HOVER_THROTTLE-1000)/TAKEOFF_TIME

    ARM_DELAY    = 0.5
    WRITE_DELAY    = 0.05
    WRITE_INTERVAL = 0.2
    #[roll,pitch,yaw,throttle] [arming, angle_mode, aux3,aux4]
    default_motors   = [1000, 1000, 1000, 1000]
    default_channels = [1500, 1500, 1500, 1000]
    channels_arm     = [1500, 1500, 2000, 1000, 1500, 1500, 1500, 1500]
    channels_disarm  = [1500, 1500, 1000, 1000, 1000, 1500, 1500, 1500]
    msg = None
    HEADERS = ['accy','accz', 'gyrx','gyry','gyrz', 'magx','magy','magz', 'angx','angy','heading','alt', 'm1','m2','m3','m4', 'roll','pitch','yaw','throttle','aux1','aux2','aux3','aux4']  #'accx'
    # ---------------------------------------------------------------------

    def __init__(self):
        self.init()

    def init(self):
        #self.net = UDP()
        self.s = Serial()
        #self.s.port             = "/dev/ttyACM0"
        self.s.port             = "/dev/UART_CF"
        self.s.baudrate         = 115200
        self.s.bytesize         = EIGHTBITS
        self.s.parity           = PARITY_NONE
        self.s.stopbits         = STOPBITS_ONE
        self.s.write_timeout    = 3
        self.s.xonxoff          = False
        self.s.rtscts           = False
        self.s.dsrdtr           = False

        try:
            self.s.open()
        except SerialException:
            print("init serial port error: "+self.s.port)
            self.msg = "init serial port error"
            #exit()
        #finally:
        #    self.msg = "init serial port error"
        self.c= MultiWii(self.s)
        #if not self.c: exit()
        #sleep(MultiWii.INIT_TIMEOUT)

    # ---------------------------------------------------------------------
    def arm(self):
        print("init port")
        self.init()
        print("arm")
        start = time()
        elapsed = 0
        while elapsed < self.ARM_DELAY:
            self.set_channels(self.channels_arm)
            sleep(self.WRITE_DELAY)
            elapsed = time() - start
        #sleep(1)

    def disarm(self):
        print("disarm")
        start = time()
        elapsed = 0
        while elapsed < self.ARM_DELAY:
            self.set_channels(self.channels_disarm)
            sleep(self.WRITE_DELAY)
            elapsed = time() - start
        #sleep(1)

    def close(self):
        self.disarm()
        self.s.close()
        self.s = None

    '''
    #betaflight only (auto_disarm_delay, disarm_kill_switch, small_angle)
    def get_arming(self):
        return self.c.get_arming()
    '''
    ##############################################################################
    def get_altitude(self):
        return self.c.get_altitude()

    def get_attitude(self):
        return self.c.get_attitude()

    def get_motors(self):
        return self.c.get_motors()

    def get_channels(self):
        #return self.c.get_channels(raw=True)  #default raw=False
        return self.c.get_channels()  #default raw=False
        #cleanflight:raw=True / betaflight:raw=False

    def get_imu(self):
        return self.c.get_imu()

    def get_all_data(self):
        imu = self.get_imu()
        att = self.get_attitude()
        alt_raw = self.get_altitude()
        alt = { 'alt': alt_raw[0] }
        #print('alt='+str(alt_raw))
        coord = {**att, **alt}
        motors_list = self.get_motors()
        #print(motors_list)
        motors={ 'm1':motors_list[0],'m2':motors_list[1],'m3':motors_list[2],'m4':motors_list[3] }
        channels=self.get_channels()
        #print(motors_list)
        return {**imu, **coord, **motors, **channels}

    def get_all_data_str(self):
        data = self.get_all_data()
        #print("accx,accy,accz, gyrx,gyry,gyrz, magx,magy,magz, angx,angy,heading,alt, m1,m2,m3,m4, roll,pitch,yaw,throttle,aux1,aux2,aux3,aux4")
        #HEADERS = ['accy','accz', 'gyrx','gyry','gyrz', 'magx','magy','magz', 'angx','angy','heading','alt', 'm1','m2','m3','m4', 'roll','pitch','yaw','throttle','aux1','aux2','aux3','aux4']  #'accx'
        str0 = str(data["accx"])
        for i in self.HEADERS:
            str0+=','+str(data[i])
        return str0
    ##############################################################################
    def set_motors(self,motors):
        return self.c.set_motors(motors)

    def set_channels(self,channels):
        self.c.set_channels(channels)

    ##############################################################################
    def reset_channels(self):
        self.set_channels(self.default_channels)

    def reset_motors(self):
        self.set_motors(self.default_motors)
    ##############################################################################
    def takeoff_channels(self):
        throttle = 1000+round(self.RATIO*self.TAKEOFF_TIME)
        #channels = [1500, 1500, 1500, throttle]    #old format
        channels = [1500, 1500, 1500, throttle, 1501,1502,1503,1504]    #arming, angle_mode, x, x
        self.set_channels(channels)
        #self.logger(self.get_all_data_str())

    def land_channels(self):
        throttle = self.HOVER_THROTTLE-round(self.RATIO*self.LAND_TIME)
        channels = [1500, 1500, 1500, throttle, 1501,1502,1503,1504]    #arming, angle_mode, x, x
        self.set_channels(channels)

    # ---------------------------------------------------------------------
    def takeoff(self):
        init_time = time()
        time_last = 0
        print("accx,accy,accz, gyrx,gyry,gyrz, magx,magy,magz, angx,angy,heading,alt, m1,m2,m3,m4, roll,pitch,yaw,throttle,aux1,aux2,aux3,aux4")
        while time_last < self.TAKEOFF_TIME:
            #print("in takeoff loop, ts=" + str(time_last) +" round="+str(round(time_last)))
            self.takeoff_channels()
            #self.takeof_motors(time_last)
            sleep(self.WRITE_INTERVAL)    #send rc > 5hz
            time_last = time()-init_time
            #self.net.broadcast(self.get_all_data_str())

    def land(self):
        init_time = time()
        time_last = 0
        while time_last < self.TAKEOFF_TIME:
            #print("in takeoff loop, ts=" + str(time_last) +" round="+str(round(time_last)))
            self.land_channels()
            #self.land_motors(time_last)
            sleep(self.WRITE_INTERVAL)    #send rc > 5hz
            time_last = time()-init_time


import json
import pyaudio
import numpy as np

delay_time = 0
with open('config.json') as f:
    data = json.load(f)
    delay_time = data['delay']

mod_freq = 0.2
mod_depth = 0.005
mix = 0.5

p = pyaudio.PyAudio()

input_stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)

output_stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, output=True)

delay_samples = int(delay_time * 44100)
delay_buffer = np.zeros(delay_samples, dtype=np.float32)
buffer_pos = 0

lfo = np.sin(2*np.pi*mod_freq*np.arange(44100)/44100).astype(np.float32)

while True:
    input_block = input_stream.read(1024)

    input_data = np.frombuffer(input_block, dtype=np.int16).astype(np.float32) / 32768.0

    # Apply the chorus effect to the input block
    output_data = np.zeros_like(input_data)
    for n in range(len(input_data)):
        # Add the input sample to the delay line buffer
        delay_buffer[buffer_pos] = input_data[n]

        # Compute the modulated delay line index
        mod_idx = buffer_pos + int(mod_depth * delay_samples * lfo[n])

        # Read the delayed sample from the buffer
        delayed_sample = delay_buffer[mod_idx % delay_samples]

        # Mix the original and delayed sample
        output_data[n] = (1-mix) * input_data[n] + mix * delayed_sample

        # Update the delay line buffer position
        buffer_pos += 1
        buffer_pos %= delay_samples

    output_block = (output_data * 32768.0).astype(np.int16).tobytes()

    output_stream.write(output_block)


# Any year is input through the keyboard. Write a program to determine whether the year is a leap
# year or not.

# Get the year from the user
year = int(input("Enter a year: "))

# Check if it's a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 14:50:49 2016

@author: PRANAV
"""
import matplotlib.pyplot as plt
a=input('enter a sequence')
pi=[]
a=a.split(',')
for elem in a:
    pi.append(int(elem))

pie=pi
final=[]
somthing=[]
number=0
loop=0
loopy=0
loopyy=0
lenpie=0
lensomthing=0
def iteration(pi,final,somthing,number,loop,lenpie):
    final.append(pi[0])
    lenpie=len(pi)
    while loop<lenpie:
        loop=loop+1
        try:
            number=abs(pi[1]-pi[0])
            somthing.append(number)
            pi.pop(0)
        except IndexError:
            loop=1+lenpie
    loop=0
    pi.pop()

#funtion to do xxx
def oppi(pi,final,somthing,number,lensomthing,loop):
    final.append(somthing[0])
    lensomthing=len(somthing)
    while loop<lensomthing:
        loop=loop+1
        try:
            number=abs(somthing[1]-somthing[0])
            pi.append(number)
            somthing.pop(0)
        except IndexError:
            loop=1+lensomthing
    loop=0
    somthing.pop()
# end function

while len(a)>loopy:
    loopy=loopy+1
    if loopy%2!=0:
        iteration(pi,final,somthing,number,loop,lenpie)
    else:
        oppi(pi,final,somthing,number,lensomthing,loop)
print(final)
plt.plot(range(len(final)),final)
plt.show()


# -*- coding: utf-8 -*-
"""
Holds all key chembl queries
"""
import logging
import sqlalchemy as sql
import pandas as pd
from mmp_kg import config
from mmp_kg.connectors.base_con import ChemDb

class ChemSqlDb(ChemDb):
    def __init__(self):
        self.db_path = config.chembl_sqlite_db
        self.name = self.source_name()

    @staticmethod
    def source_name():
        return 'chembl'

    def get_connection(self):
        path_to_db = self.db_path
        connection = sql.create_engine(f'sqlite:///{path_to_db}')
        return connection

    def make_query(self, template: str, **kwargs):
        sql = query_template_dict[template](**kwargs)

        conn = self.get_connection()
        df = pd.read_sql_query(sql, conn)

        # Add details of query to the dataframe
        query_params = kwargs
        query_params['template'] = template
        df['query'] = str(query_params)
        df['source'] = self.name

        # Log
        logging.info(f'Found {len(df)} records for {template}')

        return df

    @staticmethod
    def get_available_query_templates():
        return list(query_template_dict.keys())

def return_identity(x):
    return x

def get_adme_assays_for_docid(doc_id):
    """ get all assays for a single chembl document id"""
    query = f'''SELECT *
               FROM ASSAYS a
               WHERE a.doc_id = {doc_id}
               AND a.assay_type = 'A'
            '''
    return query

def get_assay_compounds(assay_id_list):
    assay_ids = tuple(assay_id_list)
    ''' get all compounds for a list of assay ids'''
    query = f'''SELECT cs.molregno, cs.canonical_smiles, act.standard_relation,
               act.standard_value, act.standard_units, act.standard_type,
               a.assay_id, a.description, a.assay_organism, a.assay_strain,
               a.assay_cell_type, a.tid, a.assay_type, a.tissue_id, a.variant_id,
               a.assay_id || ' ' || act.standard_type ||' ' || act.standard_units || ' ' || a.assay_organism as assay_concat
               FROM activities act
               JOIN compound_structures cs ON act.molregno = cs.molregno
               JOIN assays a ON a.assay_id = act.assay_id
               WHERE act.assay_id IN {assay_ids}
               '''
    return query

query_template_dict = {
    'adme_assays_for_docid': lambda doc_id: get_adme_assays_for_docid(doc_id),
    'get_assay_compounds_from_assay_ids': lambda assay_id_list: get_assay_compounds(assay_id_list),
    'custom_query': lambda sql: return_identity(sql),
}


def do_dfs(arr,flag,index):
    if index==len(arr)-1:
        return set([index])

    even_jump_index=None
    odd_jump_index=None

    total_indexes=set()

    for i in range(index+1,len(arr)):
        if arr[i]>= arr[index]:
            if odd_jump_index==None: odd_jump_index=i
            elif arr[i]<arr[odd_jump_index]:
                odd_jump_index=i

        if not flag and arr[i]<= arr[index]:
            if even_jump_index==None: even_jump_index=i
            elif arr[i]>arr[even_jump_index]:
                even_jump_index=i

    if even_jump_index!=None:
        indexes=do_dfs(arr,True,even_jump_index)
        total_indexes=total_indexes.union(indexes)

    if odd_jump_index!=None:
        indexes=do_dfs(arr,False,odd_jump_index)
        if len(indexes):
            indexes.add(index)
        total_indexes=total_indexes.union(indexes)

    return total_indexes

def amount_of_jumps(arr):
    possible=set()

    for i in range(len(arr)):
        if i not in possible:
            indexes= do_dfs(arr,True,i)
            possible=possible.union(indexes)

    return len(possible)

arr= [5,1,3,4,2]
val=amount_of_jumps(arr)
print(val)


from layers import *

class Encoder(object):
    def __init__(self, n_input, n_units, n_latent, n_label, activation):
        self._n_input = n_input
        self._n_units = n_units
        self._n_latent = n_latent
        self._n_label = n_label
        self._activation = activation
        self._weight_decay_loss = 0.0

        self._n_layer = len(n_units)
        self._hidden_layers = list()
        for layer_idx in range(self._n_layer):
            layer_name = "encoder_layer_" + str(layer_idx + 1)
            if layer_idx is 0:
                n_layer_input = n_input + n_label
            else:
                n_layer_input = n_units[layer_idx - 1]
            n_unit = n_units[layer_idx]
            self._hidden_layers.append(
                AffinePlusNonlinearLayer(layer_name, n_layer_input, n_unit, activation))

        layer_name = "encoder_mu_"
        self._encoder_mu = AffinePlusNonlinearLayer(layer_name, n_units[-1], n_latent)
        layer_name = "encoder_sigma_"
        self._encoder_sigma = AffinePlusNonlinearLayer(layer_name, n_units[-1], n_latent)

        for layer_idx in range(self._n_layer):
            self._weight_decay_loss += self._hidden_layers[layer_idx].get_weight_decay_loss()
        self._weight_decay_loss += self._encoder_mu.get_weight_decay_loss()
        self._weight_decay_loss += self._encoder_sigma.get_weight_decay_loss()

    def forward(self, input_tensor_x, input_tensor_y):
        # print(input_tensor_x)
        # print(input_tensor_y)
        input_tensor = tf.concat(values=[input_tensor_x, input_tensor_y], axis=1)
        # print(input_tensor)
        output_tensor = input_tensor
        for layer_idx in range(self._n_layer):
            output_tensor = self._hidden_layers[layer_idx].forward(output_tensor)
        mu = self._encoder_mu.forward(output_tensor)
        log_sigma_square = self._encoder_sigma.forward(output_tensor)

        # The standard deviation must be positive. Parametrize with a softplus and
        # add a small epsilon for numerical stability
        log_sigma_square = 1e-6 + tf.nn.softplus(log_sigma_square)

        epsilon = tf.random_normal(shape=tf.shape(log_sigma_square),
                                   mean=0.0,
                                   stddev=1.0,
                                   name='epsilon')
        latent = tf.sqrt(tf.exp(log_sigma_square)) * epsilon + mu
        # latent = tf.exp(log_sigma_square / 2) * epsilon + mu

        # [batch_size x 1]
        kl_loss = -1 / 2 * tf.reduce_sum(1 + log_sigma_square - tf.square(mu) - tf.exp(log_sigma_square),
                                         reduction_indices=[1])

        return mu, log_sigma_square, latent, kl_loss

    @property
    def wd_loss(self):
        return self._weight_decay_loss


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 22:44:02 2021

@author: Ashish
"""

import pandas as pd
import warnings
import matplotlib.pyplot as plt

warnings.simplefilter(action="ignore", category=FutureWarning)

# load data
df = pd.read_csv(
    "../../data/kaggle_healthcare-stroke-data.csv",
    index_col="id",
    keep_default_na=False,
    na_values="N/A"
)
# Exploratory data analysis
##  look at data shape, number of cols, column type, missing vals etc
print("Original data shape: ", df.shape)
print(df.info())
# check for missing values
print("missing value count: ")
print(df.isnull().sum())

## look for data inconsistencies
print("\n Observed data inconsistencies")
print(df.gender.value_counts()) # 1 row with Other gender type. drop other

# drop row based on column value
print("\n Observed data inconsistency removed")
df = df[df.gender != "Other"]
print(df.gender.value_counts())

# filter by column value
is_decimal_age = df['age']<1
df_premature_babies_stroke = df[is_decimal_age]
print("\nPremature babies with stroke: ",df_premature_babies_stroke.shape)

# user-defined functions
## 1. function to create a new feature
def label_col(col):
    if col['age']<1:
        return 'premature'
    elif col['age']>1 and col['age']<2:
        return "1 year old"

# 2. function to plot specificed columns of the raw data
def show_raw_visualization(data):
    fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 15), dpi=80)
    for i, key in enumerate(data.columns):
        t_data = data[key]
        ax = t_data.plot(
            ax=axes[i // 2, i % 2],
            title=f"{key.capitalize()}",
            rot=25,
        )

    fig.subplots_adjust(hspace=0.8)
    plt.tight_layout()

# using the custom plotting function
cols_to_plot = ["age", "bmi"]
show_raw_visualization(df[cols_to_plot].iloc[:1000])


from env import Maze

def update():
    for episode in range(100):
        # initial observation
        observation = env.reset()

        env.render()

    # end of game
    print('game over')
    env.destroy()

if __name__ == "__main__":
    env = Maze()

    env.after(100, update)
    env.mainloop()


from collections import OrderedDict

import pysam
from unittest.mock import MagicMock, patch
from bam_filter import filter_short_alignments

class PysamFakeBam:
    def __init__(self, header, reads):
        """
        a mock object that mimics the pysam.AlignmentFile object
        :param pysam.AlignmentHeader header: header of the mock sam file
        :param List[pysam.AlignedSegment] reads: reads of the mock sam file
        """
        self.header = header
        self.reads = reads

    def __iter__(self):
        return iter(self.reads)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return self

    def close(self):
        return self

def mock_bam_header(contig_list):
    """
    making a mock pysam.AlignmentHeader object
    Example::
        contigs = [("chr1", 10), ("chr2", 20)]
        mock_header = mock_bam_header(contigs)
    :param List[Tuple[str, int]] contig_list: a list of tuples of (contig name, contig length)
    :return: a pysam.AlignmentHeader object
    :rtype: pysam.AlignmentHeader
    """
    header_dict = OrderedDict(
        [
            ("SQ", [dict(SN=contig[0], LN=contig[1]) for contig in contig_list]),
        ]
    )
    return pysam.AlignmentHeader.from_dict(header_dict)

def mock_alignment(
    header,
    reference_name,
    query_name,
    query_sequence,
    reference_start,
    cigar,
    flag,
    mapping_quality,
    next_reference_name=None,
    next_reference_start=None,
):
    """
    making a mock pysam.AlignedSegment object
    :param pysam.AlignmentHeader header_dict: a pysam alignment header object (can be created by mock_bam_header)
    :param str reference_name: reference name
    :param str query_name: query name
    :param str query_sequence: query sequence
    :param int reference_start: reference start
    :param list cigar: cigar
    :param int flag: flag
    :param int mapping_quality: mapping quality
    :param str next_reference_name: reference name for the paired end alignment mapped
    :param int next_reference_start: reference start of the paired end alignment
    """
    alignment = pysam.AlignedSegment(header)
    alignment.reference_name = reference_name
    alignment.query_name = query_name
    alignment.query_sequence = query_sequence
    alignment.reference_start = reference_start
    alignment.cigar = cigar
    alignment.flag = flag
    alignment.mapping_quality = mapping_quality
    if next_reference_name is not None and next_reference_start is not None and next_reference_start > 0:
        alignment.next_reference_name = next_reference_name
        alignment.next_reference_start = next_reference_start
    return alignment

def test_filter_short_alignments():
    header = mock_bam_header([("chr1", 100)])  # mock a 100 bp chr1 contig
    in_alignment = mock_alignment(
        header=header,
        reference_name="chr1",
        query_name="aln1",
        query_sequence="NNNNNNNNNNN",  # a 11 bp alignment, shouldn't be filtered out
        reference_start=10,
        cigar=[(0, 11)],
        flag=0,
        mapping_quality=30,
    )
    with patch("bam_filter.pysam.AlignmentFile") as pysam_bam:
        mock_in_bam = PysamFakeBam(header, [in_alignment])  # the mock in bam iterarotor will return our mock alignment
        mock_out_bam = MagicMock()
        pysam_bam.return_value.__enter__.side_effect = [
            mock_in_bam,
            mock_out_bam,
        ]  # first call of the pysam.AlignmentFile will return mock_in_bam, second call will be mock_out_bam
        filter_short_alignments(
            "/path/to/inbam", "/path/to/outbam"
        )  # these files are not real, because we are mocking the return of the call anyways

        mock_out_bam.write.assert_called_once_with(
            in_alignment
        )  # because the filter function wouldn't touch alignments with >10 bases


from typing import List, Tuple

NEW_CRANE = True

def build_stacks(full_input: List[str]) -> List[List[str]]:
    # find empty line to signal bottom of stacks
    floor = full_input.index('\n') - 1
    stack_input = full_input[floor - 1:: -1]
    stack_input = [s[1::4] for s in stack_input]
    stacks = [[] for _ in stack_input[0]]
    for level in stack_input:
        for i, c in enumerate(level):
            if c != ' ':
                stacks[i].append(c)

    return stacks

def get_actions(full_input: list[str]) -> List[Tuple[int, ...]]:
    actions = [i.strip() for i in full_input[full_input.index('\n') + 1::]]
    actions = [i.strip('move ').replace('from ', '').replace('to ', '').split() for i in actions]
    return [tuple(map(int, i)) for i in actions]

def execute_instruction(stacks: List[List[str]], action: Tuple[int, ...]):
    times, origin, target = action
    origin -= 1
    target -= 1
    if not NEW_CRANE:
        for _ in range(times):
            stacks[target].append(stacks[origin].pop())
    else:
        stacks[target].extend(stacks[origin][len(stacks[origin]) - times::])
        stacks[origin] = stacks[origin][:len(stacks[origin]) - times:]
    return stacks

with open('input.txt', 'r') as inp:
    lines = inp.readlines()
    stacks = build_stacks(lines)
    instructions = get_actions(lines)
    for i, instruction in enumerate(instructions):
        stacks = execute_instruction(stacks, instruction)
    print(''.join((s[-1] for s in stacks)))


"""
variáveis livres + nonlocal (locals, globals)
"""

# def fora(x):
#     a = x  # variável livre pois não está definido no escopo de dentro()

#     def dentro():
#         print(locals())
#         print(dentro.__code__.co_freevars)
#         return a
#     return dentro

# dentro1 = fora(10)
# dentro2 = fora(20)

# print(dentro1())
# print(dentro2())

def concatenar(string_inicial):
    valor_final = string_inicial

    def interna(valor_a_contatenar=''):
        nonlocal valor_final  # escrevemos nonlocal pra interna buscar a variavel livre
        valor_final += valor_a_contatenar
        return valor_final
    return interna

c = concatenar('a')

print(c('b'))
print(c('c'))
print(c('d'))


# -*- coding: utf-8 -*-
# @Time    : 2022/12/23 17:17
# @Author  : HongFei Wang
import configparser
import os
import time

import pyautogui as pg
import xlrd

def find_image(path, index=0):
	findImagePos = pg.locateCenterOnScreen(path)
	if findImagePos is not None:
		return findImagePos
	else:
		index += 1
		time.sleep(0.5)
		print(f"重调{index}次")
		findImagePos = find_image(path, index)
		if findImagePos is not None:
			return findImagePos

def findWindow(windowns_name):
	windows = pg.getWindowsWithTitle(windowns_name)
	if len(windows) == 0:
		raise Exception("微信窗口未找到")
	return windows[0]

pg.FAILSAFE = True
cfp = configparser.ConfigParser()
cfp.read("config.ini", encoding="utf-8")

'''获取所有的selections'''
selections = cfp.sections()
find_pos = eval(cfp.get("pos", "find_pos"))
particulars = eval(cfp.get("pos", "particulars"))
leftTop = eval(cfp.get("pos", "leftTop"))
imagesize = eval(cfp.get("pos", "imagesize"))
field_work = eval(cfp.get("pos", "field_work"))
image1 = eval(cfp.get("pos", "image1"))
image2 = eval(cfp.get("pos", "image2"))
getbackpos = eval(cfp.get("pos", "getbackpos"))
getbacklist = eval(cfp.get("pos", "getbacklist"))

wxWindow = findWindow("chrome")
wxWindow.activate()  # 激活窗口,将窗口最前化
time.sleep(0.5)
excel = xlrd.open_workbook("补充图斑台账(2)(1).xlsx")
sheets = excel.sheet_by_name("2013年之前修建")
values = [int(i) for i in sheets.col_values(3)[1:]]
if not os.path.exists("./dirs"): os.makedirs("./dirs")
for i in values:
	pathDir = os.path.join("./dirs", str(i))
	if not os.path.exists(pathDir):
		os.makedirs(pathDir)
	pg.click(find_pos[0], find_pos[1], 2)  # 点击查找
	pg.typewrite(str(i))
	pg.hotkey("enter")
	time.sleep(0.5)
	# 点击详情 详情位置也作为全局变量
	pg.click(particulars[0], particulars[1])
	# ----------------------------------------------------------
	# ----------------- 网络慢 择增加等待时间 ---------------
	time.sleep(3.)  # 点击详情后 等待几秒 加载地图
	# 获取截图左上角坐标
	image_particulars = pg.screenshot(region=(leftTop[0], leftTop[1], imagesize[0], imagesize[1]))  # -60 减掉任务栏
	image_particulars.save(os.path.join(pathDir, "详情情况.png"))  # 截图详细信息
	# 点击 外业图像
	time.sleep(0.5)
	pg.click(field_work[0], field_work[1])
	time.sleep(0.5)
	pg.click(image1[0], image1[1])
	image_particulars = pg.screenshot(region=(leftTop[0], leftTop[1], imagesize[0], imagesize[1]))  # -60 减掉任务栏
	image_particulars.save(os.path.join(pathDir, "外业1.png"))  # 截图详细信息
	# 点击返回切换第二张图像
	pg.click(getbackpos[0], getbackpos[1])
	time.sleep(0.5)
	# 点击 第二张图像
	pg.click(image2[0], image2[1])
	image_particulars = pg.screenshot(region=(leftTop[0], leftTop[1], imagesize[0], imagesize[1]))  # -60 减掉任务栏
	image_particulars.save(os.path.join(pathDir, "外业2.png"))  # 截图详细信息
	time.sleep(0.5)
	# 点击返回列表
	pg.click(getbacklist[0], getbacklist[1])
	time.sleep(0.5)
pg.alert(text='完成截图', title='恭喜', button='OK')


from datetime import datetime
import logging
import socket
import json

from django.core.serializers.json import DjangoJSONEncoder
from django.conf import settings

class ELKFormatter(logging.Formatter):

    def format(self, record):
        assert isinstance(record.msg, dict)

        user = record.__dict__.get('user')
        message = record.msg.copy()
        data = dict(
            event=message.pop('event', ''),
            eventdate=datetime.utcnow().isoformat(timespec='seconds'),
            host=dict(
                name=socket.gethostname(),
                ip=socket.gethostbyname(socket.gethostname())
            ),
            subsystem=settings.APP_NAME,
            format_version=1,
            username=(user.username if user else None),
            **message
        )

        return json.dumps(data, cls=DjangoJSONEncoder, ensure_ascii=False)


count = 0

TAB = [1,2,3,6,20,60,80,90]
def binariaP(x, a):

    global count

    n = len(a)
    # se x está fora da tabela
    if x <= a[0]:
        count +=1
        return 0
    if x > a[n-1]:
        count += 1
        return n
    # x pode estar dentro da tabela
    L = 0
    R = n-1
    while R - L > 1:
        M = (R + L) // 2
        if x <= a[M]:
            count += 1
            R = M
        else:
            count += 1
            L = M
    return R

def InserreBB(TAB,V):
    for i in range(0, len(TAB)):

        j = binariaP(V,TAB)
        print("TAB[:j]", TAB[:j])
        print("[V]", [V])
        print("TAB[j:i+1]", TAB[j:i+1])
        print("TAB[i+1:]", TAB[i+1:])
        print(i)

        arr = TAB[:j] + [V] + TAB[j:]
        return arr, "indice =",j

print(InserreBB(TAB,93))
print("comparações = ",count)


from sekai.sekai_modules.main import get_data

class UserProfile(object):
    def __init__(self):
        #user['userGamedata']
        self.userId = 0
        self.name = ''
        self.deck = 0
        self.rank = 0
        #userProfile
        self.word = ''
        self.twitterId = ''
        self.profileImageType = ''
        #userDecks
        self.userDecks = {}
        #userCards
        self.userCards = []
        #userMusics
        self.userMusics = []
        #userCharacters
        self.userCharacters = []
        #userChallengeLiveSoloResults
        self.userChallengeLiveSoloResults = []
        #userChallengeLiveSoloStages
        self.userChallengeLiveSoloStages = []
        #userAreaItems
        self.userAreaItems = []
        #userHonors
        self.userHonors = []
        #userBondsHonors
        self.userBondsHonors = []
        #userMusicResults
        self.userMusicResults = []
        #userCustomProfileCards
        self.userCustomProfileCards = []
        #userProfileHonors
        self.userProfileHonors = []

    async def get_profile(self, server: str, user_id: str):
        data = await get_data(server='jp', type='api', path=f'/profile/{server}/{user_id}/')
        self.userId = data['user']['userGamedata']['userId']
        if int(user_id) != self.userId: raise SystemError('API error')
        self.name = data['user']['userGamedata']['name']
        self.deck = data['user']['userGamedata']['deck']
        self.rank = data['user']['userGamedata']['rank']
        try: self.word = data['userProfile']['word']
        except: self.word = None
        try: self.twitterId = data['userProfile']['twitterId']
        except: self.twitterId = None
        self.profileImageType = data['userProfile']['profileImageType']
        self.userDecks = data['userDecks'][0]
        self.userCards = data['userCards']
        self.userMusics = data['userMusics']
        self.userCharacters = data['userCharacters']
        self.userChallengeLiveSoloResults = data['userChallengeLiveSoloResults']
        self.userChallengeLiveSoloStages = data['userChallengeLiveSoloStages']
        self.userAreaItems = data['userAreaItems']
        self.userHonors = data['userHonors']
        self.userBondsHonors = data['userBondsHonors']
        self.userMusicResults = data['userMusicResults']
        self.userCustomProfileCards = data['userCustomProfileCards']
        self.userProfileHonors = data['userProfileHonors']


import sys
import collections
import decimal
import nltk
import math
import codecs
import Queue as Q
import ConfigParser
from operator import itemgetter
from collections import defaultdict
from nltk import word_tokenize
from pSCRDRtagger.RDRPOSTagger import RDRPOSTagger
from Utility.Utils import readDictionary
from decimal import Decimal as D

def read_config(file, section):
	Config = ConfigParser.ConfigParser()
	Config.read(file)
	configs = {}
	options = Config.options(section)
	for option in options:
		configs[option] = Config.get(section, option)
	return configs

def pos_tag_english(english_sentence):
	english_words = nltk.pos_tag(word_tokenize(english_sentence))
	return english_words

def pos_tag_foreign(foreign_sentence):
	foreign_words = foreign_language_tagger.tagRawSentence(foreign_language_dictionary, foreign_sentence)
	return foreign_words

def readlines(file, encode):
	lines = []
	with open(file, 'r') as f:
		for i,l in enumerate(f):
			lines.append(l.decode('UTF-8'))
	if encode:
		return [line.encode("UTF-8") for line in lines]
	else:
		return lines

def read_dictionary(file):
	file = codecs.open(file,"r","utf-8")
	e_to_f = {}
	for line in file:
		tokens = line.split("\t")
		e = tokens[0];
		f = tokens[1];
		p = float(tokens[2]);

		if e in e_to_f:
			e_to_f[e][f] = p
		else:
			e_to_f[e] = {}
			e_to_f[e][f] = p

	return e_to_f

configs = read_config(sys.argv[1], sys.argv[2])
foreign_language = configs["foreign_language"]
model_rdr = "./Models/UniPOS/UD_"+foreign_language+"/train.UniPOS.RDR"
model_dict = "./Models/UniPOS/UD_"+foreign_language+"/train.UniPOS.DICT"
foreign_language_tagger = RDRPOSTagger()
foreign_language_tagger.constructSCRDRtreeFromRDRfile(model_rdr)
foreign_language_dictionary = readDictionary(model_dict)
k = int(configs["k"])
mu = float(configs["mu"])
sigma = float(configs["sigma"])

file = codecs.open(configs["input_file"],"r","utf-8")
bilingual_dictionary = read_dictionary(configs["bilingual_dictionary"])
output_file = codecs.open(configs["output_ranking"],"w","utf-8")

english_lines = []
foreign_lines = []
for line in file:
	tokens = line.split("\t")
	english_lines.append(tokens[1].strip())
	foreign_lines.append(tokens[2].strip())
output = defaultdict()
actual = {}
correct = 0
total = 0
for i in range(0,len(english_lines)):
	english_sentence = english_lines[i]
	english_words = pos_tag_english(english_sentence)
	len_english = float(len(english_words))
	if len_english == 0:
		continue
	output[i] = Q.PriorityQueue()
	actual[i] = (None, float("-inf"))
	for j in range(0, len(foreign_lines)):
		foreign_sentence = foreign_lines[j]
		foreign_words = foreign_sentence.split(" ")
		len_foreign = float(len(foreign_words))
		length_model = math.exp(-0.5 * (((len_foreign / len_english) - mu) / sigma)**2)
		transition_model = 0.0;
		for e,e_tag in english_words:
			if e in bilingual_dictionary:
				for f in foreign_words:
					if f in bilingual_dictionary[e]:
						transition_model += bilingual_dictionary[e][f]
					else:
						transition_model -= 0.001
		val = transition_model * length_model
		if i == j:
			actual[i] = (i,val)
		output[i].put((-val, val , j))
	total += 1

	for c in range(0,k):
		(priority, val, foreign_id) = output[i].get()
		output_file.write(str(i)+"\t"+str(foreign_id)+","+str(val)+"\t"+str(actual[i])+"\n")
		if foreign_id == i:
			correct += 1

output_file.close()


from bs4 import BeautifulSoup
import requests

EMPIRE_URL = "https://www.timeout.com/newyork/movies/best-movies-of-all-time"
response = requests.get(EMPIRE_URL)
empire_html = response.text

soup = BeautifulSoup(empire_html, "html.parser")

title_tag = soup.find_all(name="h3", class_="_h3_cuogz_1")
titles = [tag.getText() for tag in title_tag]

all_titles = "\n".join(titles)
titles = all_titles.replace(" ", "")

with open("movies_to_watch.txt", "wb") as file:
    file.write(titles.encode("utf-8"))


# Intcode Computer
#
# Instructions:
#   - Opcode 1 (3 params)
#   - Opcode 2 (3 params)
#   - Opcode 3 (1 param)
#   - Opcode 4 (1 param)

FILE_PATH = "diagnosticProgram.txt"

def intcode():
    file = open(FILE_PATH, "r")
    # convert file from list of strings to integers
    program = list(map(lambda x: int(x) , file.read().strip().split(',')))
    # print("Before:", program)

    # program will always start at position 0
    currPos = 0
    instructionLength = 5
    while (True):
        instruction = str(program[currPos]).zfill(instructionLength)
        # two-digit opcode
        opcode = int(instruction[3:])
        # paramater modes (either 0 or 1)
        # 0 == position mode
        # 1 == immediate mode
        param1Mode = int(instruction[2])
        param2Mode = int(instruction[1])
        param3Mode = int(instruction[0])

        # Exit program
        if (opcode == 99):
            print("Code 99: Exiting...")
            break

        # Add or Multiply Values
        elif (opcode == 1 or opcode == 2):
            value1 = program[program[currPos + 1]] if param1Mode == 0 else program[currPos + 1]
            value2 = program[program[currPos + 2]] if param2Mode == 0 else program[currPos + 2]
            storePosition = program[currPos + 3] if param3Mode == 0 else currPos + 3

            # store value based on opcode
            program[storePosition] = value1 + value2 if opcode == 1 else value1 * value2
            currPos += 4

        # Get User Input
        elif (opcode == 3):
            value = input("Enter ID: ")
            storePosition = program[currPos + 1] if param1Mode == 0 else currPos + 1

            program[storePosition] = int(value)
            currPos += 2

        # Output Diagnostic Code
        elif (opcode == 4):
            valPos = program[currPos + 1] if param1Mode == 0 else currPos + 1
            value = program[valPos]

            print("DIAGNOSTIC CODE:", value)
            currPos += 2

        # Jump-if-true
        elif (opcode == 5):
            value1 = program[program[currPos + 1]] if param1Mode == 0 else program[currPos + 1]
            value2 = program[program[currPos + 2]] if param2Mode == 0 else program[currPos + 2]

            if (value1 != 0):
                currPos = value2
            else:
                currPos += 3

        # Jump-if-false
        elif (opcode == 6):
            value1 = program[program[currPos + 1]] if param1Mode == 0 else program[currPos + 1]
            value2 = program[program[currPos + 2]] if param2Mode == 0 else program[currPos + 2]

            if (value1 == 0):
                currPos = value2
            else:
                currPos += 3

        # Less than
        elif (opcode == 7):
            value1 = program[program[currPos + 1]] if param1Mode == 0 else program[currPos + 1]
            value2 = program[program[currPos + 2]] if param2Mode == 0 else program[currPos + 2]
            storePosition = program[currPos + 3] if param3Mode == 0 else currPos + 3

            program[storePosition] = 1 if value1 < value2 else 0

            currPos += 4

        # Equals
        elif (opcode == 8):
            value1 = program[program[currPos + 1]] if param1Mode == 0 else program[currPos + 1]
            value2 = program[program[currPos + 2]] if param2Mode == 0 else program[currPos + 2]
            storePosition = program[currPos + 3] if param3Mode == 0 else currPos + 3

            program[storePosition] = 1 if value1 == value2 else 0

            currPos += 4

    # print("After:", program)

if __name__ == "__main__":
    intcode()


from os import listdir
from os.path import isfile, join
import logging
import concurrent.futures
import time
from symbol import Symbol

def get_symbolfiles():
    symbol_path = "init_data"
    files = [join(symbol_path, f) for f in listdir(symbol_path) if isfile(join(symbol_path, f))]
    json_files = [f for f in files if f[-4:] == 'json']
    return json_files

def thread_function_track_symbol(symbol_file):
    logging.info("Thread %s: starting", symbol_file[0:-5])
    symbol = Symbol(symbol_file)
    symbol.track()
    logging.info("Thread %s: finishing", symbol_file[0:-5])

# start
if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
    polling_interval = 15 * 60
    all_tracked_list = []

    while(True):
        updated_list = get_symbolfiles()
        new_tracked_files = [f for f in updated_list if f not in all_tracked_list]

        if len(new_tracked_files) > 0:
            with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
                executor.map(thread_function_track_symbol, new_tracked_files)

            all_tracked_list.append(new_tracked_files)

        time.sleep(polling_interval)


import random
dice = [1, 2, 3, 4, 5, 6];
resposta = 1;
while(resposta == 1):
	input("Para girar o dado, tecle ENTER:\n");
	num_sorteado = random.choice(dice);
	print (num_sorteado);
	continua = input("Deseja executar o programa novamente?(Digite 'S' para sim e 'N' para não)\n");
	continua = continua.lower();
	if(continua == 's'):
		resposta = 1;
	else:
		resposta = 0;


from networktables import NetworkTables
from red_contour_grip import RedContoursPipeline

import config

import cv2
import time
import math
import threading

# Start thread to connect to NetworkTables
cond = threading.Condition()
notified = [False]

def connectionListener(connected, info):
    print(info, '; Connected=%s' % connected)
    with cond:
        notified[0] = True
        cond.notify()

# Use RoboRIO static IP address
NetworkTables.initialize(server=config.nt_ip) # Don't use 'roborio-192-frc.local'. https://robotpy.readthedocs.io/en/stable/guide/nt.html#networktables-guide
NetworkTables.addConnectionListener(connectionListener, immediateNotify=True)

with cond:
    print("Waiting")
    if not notified[0]:
        cond.wait()

print("Connected to NetworkTables!")

# Initialize Jetson NetworkTable
jetson = NetworkTables.getTable(config.nt_name)

def calculate_coords(frame_width, frame_height, x_cam_coord, y_cam_coord):
    cx = frame_width / 2 - 0.5
    cy = frame_height / 2 - 0.5

    pitch_angle = math.atan(y_cam_coord - cy) / config.focal_len
    yaw_angle = math.atan(x_cam_coord - cx) / config.focal_len

    return pitch_angle, yaw_angle

def calc_contours(c):
    M = cv2.moments(c)
    if M['m00'] != 0:
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])

    return cx,cy

input_port = 0
num_ports = 4

cap = cv2.VideoCapture(input_port)
_, frame = cap.read()

# Keep trying until image is obtained
while frame is None:

    print("Error: No image to process. Cannot run vision pipeline. Are images being captured from the camera?")

    # Try a different port
    input_port = (input_port + 1) % num_ports
    cap = cv2.VideoCapture(input_port)

    # Read frame
    _, frame = cap.read()

    print("Trying /dev/video" + str(input_port))

    # Wait before trying the next USB port
    time.sleep(1)

# Put image width and height on table
h, w, _ = frame.shape

jetson.putNumber('frame_width', w)
jetson.putNumber('frame_height', h)

# Run the pipeline on the video stream
while True:

    _, frame = cap.read()

    if frame is None:
        continue

    # Undistort the frame
    temp = cv2.undistort(frame, config.cameramtx, config.dist, None, config.newcameramtx)
    # TODO Crop the frame using roi
    frame = temp

    # Process frame
    visionPipeline = RedContoursPipeline() # LemonVisionGripPipeline()
    visionPipeline.process(frame)

    # Retrieve the blobs from the pipeline
    contours = visionPipeline.filter_contours_output # tuple of KeyPoint objects

    print(str(len(contours)) + " blobs detected")

    if len(contours) > 0:
        # Find largest contour
        largest_contour = []
        largest_contour_idx = 0
        for i in range(len(contours)):
            if (len(contours[i]) > len(largest_contour)):
                largest_contour = contours[i]
                largest_contour_idx = i

        # Find centroid of contour
        x, y = calc_contours(largest_contour)
        x = int(x)
        y = int(y)

        cv2.line(frame, (x - config.line_length, y), (x + config.line_length, y), (0, 0, 255), 2)
        cv2.line(frame, (x, y - config.line_length), (x, y + config.line_length), (0, 0, 255), 2)

        temp = cv2.drawContours(frame, contours, largest_contour_idx, (0, 0, 255), 2, cv2.LINE_8, maxLevel=0)
        frame = temp

        # Calculate angle to target
        pitch_angle, yaw_angle = calculate_coords(w, h, x, y)

        print("pitch: " + str(pitch_angle) + "; yaw: " + str(yaw_angle))

        # Publish data on NetworkTables
        jetson = NetworkTables.getTable('jetson')

        jetson.putNumber('xCentroid', x)
        jetson.putNumber('yCentroid', y)
        jetson.putNumber('pitchAngle', pitch_angle)
        jetson.putNumber('yawAngle', yaw_angle)

    # cv2.imshow('image', frame)

    # Put test value in NT
    jetson.putString('test', 'hello here is a test str value')

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


# python3
import sys

from numpy import empty

NA = -1

def build_trie(patterns):
    tree = dict()
    tree[0] = {}
    nodeId = 0
    for pattern in patterns:
        currNode = 0
        for c in pattern:
            if(c in tree[currNode]):
                currNode = tree[currNode][c]
            else:
                nodeId += 1
                tree[currNode][c] = nodeId
                tree[nodeId] = {}
                currNode = nodeId
    return tree

class Node:
	def __init__ (self):
		self.next = [NA] * 4

def solve (text, n, patterns):
	result = []
	tree = build_trie(patterns)
	for i, c in enumerate(text):
		currNode = 0
		currChar = i
		while currChar < len(text):
			if(text[currChar] in tree[currNode]):
				currNode = tree[currNode][text[currChar]]
				currChar += 1
				if( not tree[currNode] ):
					result.append(i)
					break
			else:
				break

	return result

text = sys.stdin.readline ().strip ()
n = int (sys.stdin.readline ().strip ())
patterns = []
for i in range (n):
	patterns += [sys.stdin.readline ().strip ()]

ans = solve (text, n, patterns)

sys.stdout.write (' '.join (map (str, ans)) + '\n')


import tweepy
from dotenv import load_dotenv
import os
import smtplib
from email.message import EmailMessage
import cv2
import time
from PIL import Image, ImageTk
import tkinter as tk
import tkinter.font as font
from math import floor
import imghdr
load_dotenv()

auth = tweepy.OAuthHandler(os.environ.get(
    "CONSUMER_KEY"), os.environ.get("CONSUMER_SECRET"))
auth.set_access_token(os.environ.get("API_TOKEN"),
                      os.environ.get("API_SECRET"))

api = tweepy.API(auth)

w1 = tk.Tk()
w1.title("Sketchy")
w1.geometry("2560x1600")
label = tk.Label(w1)
label.grid(row=0, column=1, sticky='nesw')
cap = cv2.VideoCapture(0)

scale_factor = 0.58

def getImage():
    ret, frame = cap.read()

    image = frame
    grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(grey_img, (21, 21), 0)
    sketch = cv2.divide(grey_img, blur, scale=256.0)
    # sketch = cv2.resize(sketch, (w1.winfo_width(), w1.winfo_height()-0), interpolation = cv2.INTER_AREA)
    cv2.imwrite("sketch.png", sketch)

    background = Image.open("sketch.png").convert("RGBA")
    width, height = background.size
    foreground = Image.open("stamp.png").convert("RGBA")
    foreground = foreground.resize(
        (width, int(150*(height/width))))
    background.paste(foreground, (0, 0), mask=foreground)
    newBackground = background.resize((floor(background.size[0]*scale_factor), floor(background.size[1]*scale_factor)))
    newBackground.save("main.png")

    return ImageTk.PhotoImage((background))

def updateLabel():
    LE_IMAGE = getImage()
    label.imgtk = LE_IMAGE
    label.configure(image=LE_IMAGE)
   # Repeat after an interval to capture continiously
    label.after(5, updateLabel)

def postTweet():
    media = api.media_upload('./main.png')
    api.update_status("A person has appeared at #toorcamp", media_ids=[media.media_id_string])

def printPhoto():
    os.startfile("main.png", "print")

def showWindow():

    for i in range(4):
        w1.columnconfigure(i, weight=1)
    w1.rowconfigure(1, weight=1)
    myFont = font.Font(size=30)
    bird = tk.Button(w1, height=50,
                     text="Post to Twitter", command=postTweet)
    bird.grid(row=2, column=2, sticky='nesw')
    bird["font"] = myFont
    bird.pack()

    retake = tk.Button(w1, height=50, text="Retake")
    retake.grid(row=2, column=1, sticky='nesw')
    retake["font"] = myFont
    retake.pack()

    printer = tk.Button(w1, text="Print photo", command=printPhoto)
    printer.grid(row=2, column=1, sticky='nesw')

    updateLabel()

    w1.mainloop()

if __name__ == "__main__":
    showWindow()


#!/usr/bin/env python3
list = [101,2,15,22,95,33,2,27,72,15,52]
#print even values in the list
for l in list:
  if l % 2 == 0:
    print (l)
print("done")
#sort and print each element
list2 = sorted(list)
for l in list2:
  print(l)
print("done")

#take the even number and sum
even = [ l for l in list if l%2 == 0]

sum = 0
for e in even:
  sum = sum + e
print('sum of even numbers:', sum)

#take the odd number and sum
odd = [ l for l in list if l%2 != 0]

sum2 = 0
for o in odd:
  sum2 = sum2 + o
print('sum of odd numbers:', sum2)


"""
2021.7
idea: Given the citations array to compute H-index
(the maximum h number of papers with at least h citations)
    - H-index = max(#papers equal to or larger than certain citations, the citations)
"""

from typing import List

class Solution:
    """
    sort and traverse
    Time: O(nlogn) sort
    Space: O(n) n-array
    """
    def hIndex(self, citations: List[int]) -> int:
        sorted_citation = sorted(citations, reverse = True)
        h = 0; i = 0; n = len(citations)
        while i < n and sorted_citation[i] > h:
            h += 1
            i += 1
        return h

class Optimal:
    """
    To reduce the time complexity of sorting, we use counter array
    - index: number of citations, if larger than n, count into n.
        - reseacher A has 10 papers, one of which has 100 citations.
    - value: the number of satisfied paper
    - Traverse n positive integer in reverse order:
        - count total number of papers
        - if total is larger than number of papers, return them

    - Time: O(n)
    """
    def hIndex(self, citations: List[int]) -> int:
        n = len(citations)
        total = 0   # number of satisfied papers
        counter = [0] * (n+1)
        # counter to record paper counts equal to or larger than n, index represents citations
        for num in citations:
            # if citations larger than n, count into n
            if num >= n:
                counter[n] += 1
            else:
                counter[num] += 1

        # traverse paper number in reverse order
        for i in range(n, -1, -1):
            total += counter[i]
            # judge by number of papers with proper citations
            if total >= i:
                return i
        return 0

class Dichotomy:
    """
    hIndex satisfied the duality on the positive integer axis: the maximum value x
        - the value less than or equal to x must satisfied condition
        - larger value does not satisfied the condition

    Time complexity: O(NlogN)

    """
    def check(self, citations, mid) -> bool:
        """
        check whether mid value satisfied hIndex condition
        """
        cnt = 0
        for val in citations:
            if val >= mid:  # mid serve as citation value
                cnt += 1

        if cnt >= mid:  # mid serve as paper number
            return True
        else:
            return False

    def hIndex(self, citations):
        n = len(citations)
        l, r = 0, n
        while l <= r:
            mid = l + r >> 1
            if self.check(citations, mid):
                l = mid + 1
            else:
                r = mid - 1
        return r

if __name__ == '__main__':
    citations = [0]
    S = Optimal()
    print(S.hIndex(citations))


# 4358: 생태학
import sys
input = sys.stdin.readline
from collections import defaultdict

dict = defaultdict(int)
total = 0
while True:
	tree = input().rstrip()
	if not tree:
		break
	dict[tree] += 1
	total += 1
dict = sorted(dict.items())
for tree,cnt in dict:
	print('%s %.4f' %(tree, cnt/total*100))


from nltk.data import find
from nltk import download
from nltk.corpus import stopwords
from nltk.tokenize.regexp import regexp_tokenize
from string import punctuation
from unidecode import unidecode
import re

## Download stopwords
try:
    find("corpora/stopwords")
except LookupError:
    download('stopwords')

## Regex to remove stopwords
STOPWORDS = ["pra", "pras"] + stopwords.words(["english", "portuguese"])
STOPWORDS = unidecode(' '.join(STOPWORDS)).lower().split()
STOPWORDS = list(set(STOPWORDS))
STOPWORDS_RE = re.compile(r'\b(' + r'|'.join(STOPWORDS) + r')\b\s*')

## Regex to remove punctuations
PUNCTS_RE = re.compile('[' + punctuation + ']')

## Regex to remove punctutations and numbers
NON_ALPHANUM_RE = re.compile('[^a-zA-Z]')

## Regex to remove single character words
SINGLE_CHAR_RE = re.compile(r'\s+[a-zA-Z]\s+')

## Regex to remove multiple spaces
MULTI_SPACE_RE = re.compile(r'\s+')

def clean_text_min(text):
    """
        text: text to be cleaned
        output: formatted text

        reference: Tomas Mikolov, word2vec-toolkit: google groups thread., 2015. [](https://goo.gl/KtDGst)
    """

    # Decode to ascii
    text = unidecode(text.lower())

    # Remove punctuations
    text = PUNCTS_RE.sub(' ', text)
    #text = NON_ALPHANUM_RE.sub(' ', text)

    # Remove multiple spaces
    text = MULTI_SPACE_RE.sub(' ', text)

    return text.strip()

def clean_text(text):
    """
        text: text to be cleaned
        output: formatted text
    """

    # Decode to ascii
    text = unidecode(text.lower())

    # Remove punctuations and numbers
    text = NON_ALPHANUM_RE.sub(' ', text)

    # Remove single chars
    text = SINGLE_CHAR_RE.sub(' ', text)

    # Remove stopwords
    text = STOPWORDS_RE.sub(' ', text)

    # Remove multiple spaces
    text = MULTI_SPACE_RE.sub(' ', text)

    return text.strip()

def tokenize_text(text, clean=False):
    """
        text: text to tokenize
        output: list of words
    """

    if clean:
        text = clean_text(text)

    words = regexp_tokenize(text, pattern="\s+", gaps=True)

    return(words)


import numpy as np
import matplotlib.pyplot as plt
import logistics
import time
from typing import List, Union

def replica_job(
    steps:int,
    print_progress:bool=False,
    print_time:bool=False,
    time_full_str:bool=False
):
    """
        Dummy-job -- replica-loop with time.sleep();
        prints the message 'replicating job, '.

        --Parameters--
        * steps : int //
            Number of replica-actions (sleeps) to be
            taken by the interpreter.
        * print_progress : bool, optional //
            Option to print the progress of the replica job
            using the logistics.print_loop_progress() routine;
            the message 'replicating job' will always be printed, but
            will also followed by the progress indicator if
            print_progress == True,
                * by default False.
        * print_time : bool, optional //
            Option to print the time required (upon completion)
            for the replica-job using the logistics.print_time_required()
            routine; this time will be preceded by a number of
            spaces equivalent to the length of the message
            'replicating job, ', if print_progress == True
                * by default False.
        * time_full_str : bool, optional //
            Option to force the displayed time-string to be of the form:
            hh:mm:ss.cs,
                * only required if print_time == True,
                * by default False.
    """

    init_time = time.perf_counter()
    msg = 'replicating job, '

    for i in range(steps):
        time.sleep(0.1)
        if print_progress:
            logistics.print_loop_progress(
                index=i, index_max=steps-1, prefix=msg
            )
        else:
            print('\r' + msg, end='')

    buffer = ' ' * len(msg) if print_progress else ''
    if print_time:
        logistics.print_time_required(
            init_time=init_time, prefix=buffer,
            full_str=time_full_str
        )

def build_plot(
    fig_label :       str                               ,
    x_arrs :          List[List[float]]                 ,
    y_arrs :          List[List[float]]                 ,

    plot_labels :     List[str]             = None      ,
    fig_loc :         List[float]           = [600, 250],
    fig_size :        List[float]           = [640, 520],
    x_label :         str                   = ''        ,
    y_label :         str                   = ''        ,
    plot_title :      str                   = ''        ,
    linestyles :      List[str]             = None      ,
    plot_colors :     List[str]             = None      ,
    plot_markers :    List[str]             = None      ,
    legend :          Union[bool, List]     = False     ,
    axes :            Union[bool, List]     = False     ,
    grid:             Union[bool, List]     = False     ,
    y_lim :           List[float]           = None      ,
    x_lim :           List[float]           = None      ,
):
    """
        Builds a plot using matplotlib.pyplot;
        "plt.show()" must be called elsewhere,

        --Parameters--
        * fig_label : str //
            Title of the figure.
        * x_arrs : List[List[float]] //
            Arrays (arranged along axis 0)
            containing horizontal-axis values for points to be plotted;
            each array in x_arrs should have exactly one counterpart
            in y_arrs.
        * y_arrs : List[List[float]] //
            Arrays (arranged along axis 0)
            containing vertical-axis values for points to be plotted;
        * plot_labels : List[str], optional //
            Ordered labels for each plot
            (i.e. each pair of x, y arrays).
                * by default None.
        * fig_loc : List[float], optional //
            List with two elements giving the screen
            position [x, y] (in px) where the figure should be displayed.
                * by default [600, 250].
        * fig_size : List[float], optional //
            List with two elements giving the width and height (in px)
            of the displayed figure.
                * by default [640, 520].
        * x_label : str, optional //
            Horizontal axis label.
                * by default ''.
        * y_label : str, optional //
            Vertical axis label.
                * by default ''.
        * plot_title : str, optional //
            Title of set of plots (printed at top of figure).
                * by default ''.
        * linestyles : List[str], optional //
            List of linestyles for each plot.
                * by default None.
        * plot_colors : List[str], optional //
            List of colors for each plot.
                * by default None.
        * plot_markers : List[str], optional //
            List of marker styles for each plot.
                * by default None.
        * legend : Union[bool, List], optional //
            Option to enable legend for plots;
            can also be set as a list containing a bool in position 0
            (corresponding the normal legend option) and a string in
            position 1 (corresponding to the loc option, specifying the
            legend location, e.g. 'upper right'.
                * requires plot_labels to be fully populated,
                * by default False.
        * axes : Union[bool, List], optional //
            Option to enable axes;
            can also be set as a list containing a bool in position 0
            (corresponding to the normal axes option), a string in position
            1 (corresponding to the desired axes linestyle,
            by default '--'), and a string in position 2 (corresponding to
            the desired axes color, by default 'k'),
                * by default False.
        * grid : Union[bool, List], optional //
            Option to enable grid;
            can also be set as a list containing a bool in position 0
            (corresponding to the normal grid option) and a float in position
            1 (corresponding to the opacity--i.e. alpha--level of
            the gridlines),
                * by default False.
        * y_lim : List[float], optional //
            List containing two floats--gives the vertical plot boundaries,
                * by default None.
        * x_lim : List[float], optional //
            List containing two floats--gives the horizontal
            plot boundaries,
                * by default None.
    """

    plt.figure(fig_label)

    # Window geometry (type:int, units:px):
    fig_x_pos, fig_y_pos = fig_loc
    fig_width, fig_height = fig_size
    mgr = plt.get_current_fig_manager()
    mgr.window.setGeometry(
        fig_x_pos, fig_y_pos, fig_width, fig_height
    )

    # Main plot call:
    for i in range(len(y_arrs)):
        label = plot_labels[i] if plot_labels else None
        linestyle = linestyles[i] if linestyles else '-'
        color = plot_colors[i] if plot_colors else f'C{i}'
        marker = plot_markers[i] if plot_markers else None
        plt.plot(
            x_arrs[i], y_arrs[i],
            label=label,
            linestyle=linestyle,
            color=color,
            marker=marker
        )

    # labels:
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.title(plot_title)

    # options
    if legend:
        legend_loc = legend[1] \
            if type(legend) == list else 'best'
        plt.legend(loc=legend_loc)
    if grid:
        opacity = grid[1] \
            if type(grid) == list else 0.3
        plt.grid(alpha=opacity)
    if axes:
        axes_linestyle = axes[1] \
            if type(axes) == list else '--'
        axes_color = axes[2] \
            if type(axes) == list else 'k'
        plt.axhline(
            0, linestyle=axes_linestyle, color=axes_color
        )
        plt.axvline(
            0, linestyle=axes_linestyle, color=axes_color
        )
    if x_lim:
        plt.xlim(x_lim[0], x_lim[1])
    if y_lim:
        plt.ylim(y_lim[0], y_lim[1])

def abs_max(arrs:List)->float:
    """
        Finds the maximum from among the absolute values
        of all elements within several arrays
        (where each array can be of any dimension).

        --Parameters--
        * arrs : List //
            Contains (along axis 0) all arrays to be considered.

        --Returns--
        * magnitude_max: float //
            The desired maximum (from among the absolute maximums
            of the inputted arrays).
    """

    maxes = [np.abs(arr).max() for arr in arrs]
    magnitude_max = np.amax(maxes)

    return magnitude_max


import numpy as np

def __max_pool(arr, win_sz, i_start, j_start):
    current = []
    for i in range(i_start, i_start + win_sz):
        for j in range(j_start, j_start + win_sz):
            current.append(arr[i,j])
    print('Current:',current)
    return max(current)

def max_pool(arr, win_sz):
    if len(arr) % win_sz != 0:
        raise AttributeError('Matrix must be divisible by window size')
    print('Array:')
    print(arr)
    i_start,j_start = 0,0
    iters = int((len(arr)*len(arr))/(win_sz*win_sz))
    new_size = int(len(arr)/win_sz)
    new = np.zeros((new_size,new_size))
    i,j,k = 0,0,0
    while k < iters:
        new[i,j] = __max_pool(arr, win_sz, i_start,j_start)
        if i == len(new)-1:
            i = 0
            i_start = 0
            j_start += win_sz
            j += 1
            k += 1
            continue
        i += 1
        i_start += win_sz
        k += 1
    return new

x = np.random.rand(12,12)
pool = max_pool(x, 2)
print('Maxpool: ')
print(pool)

# A much better implementation
def patchify(img, patch_shape):
    a, X, Y, b = img.shape
    x, y = patch_shape
    shape = (a, X - x + 1, Y - y + 1, x, y, b)
    a_str, X_str, Y_str, b_str = img.strides
    strides = (a_str, X_str, Y_str, X_str, Y_str, b_str)
    return np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides)

x = np.random.randint(0,9,(10,24,24,3))
S = 5
out = patchify(x, (S,S)).max(axis=(3,4))

# My attempt to eliminate restrictions of NxN dimensional vector that is divisible by window size
def __max_pol(arr, win_sz, i_start, j_start):
    current = []
    for i in range(i_start, i_start + win_sz):
        for j in range(j_start, j_start + win_sz):
            current.append(arr[i,j])
    print('Current:',current)
    return max(current)

def max_pol(arr, win_sz, stride):
    print('Array:')
    print(arr)
    i_start,j_start = 0,0
    iters = int((len(arr)*len(arr))/(win_sz*win_sz))
    new_sizeM = int(len(arr)/win_sz)
    new_sizeN = int(len(arr)/stride) - 1
    new = np.zeros((new_sizeM,new_sizeN))
    i,j,k = 0,0,0
    while k < iters:
        new[i,j] = __max_pol(arr, win_sz, i_start,j_start)
        if i == len(new)-1:
            i = 0
            i_start = 0
            j_start += win_sz
            j += 1
            k += 1
            continue
        i += 1
        i_start += stride
        k += 1
    print()
    return new

# y = np.random.rand(4,4)
# print(max_pol(y,2,1))


# validate_project_editorial_info.py
import pyblish.api

class ValidateMindbenderProjectEditInfo(pyblish.api.ContextPlugin):
    """Checks your scene with editorial info

    All the info that gets validated has been set by the projects bat files.
    If you are certain that the info is incorrect, talk to your project
    Supervisor with haste!
    """

    label = "Project Edit Info"
    optional = True
    order = pyblish.api.ValidatorOrder
    families = ["mindbender.animation"]

    def process(self, context):
        from maya import cmds

        scene_in = cmds.playbackOptions(query=True, animationStartTime=True)
        scene_out = cmds.playbackOptions(query=True, animationEndTime=True)
        scene_fps = {
            "12fps": 12,
            "game": 15,
            "16fps": 16,
            "film": 24,
            "pal": 25,
            "ntsc": 30,
            "show": 48,
            "palf": 50,
            "ntscf": 60}.get(cmds.currentUnit(query=True, time=True))

        if scene_fps is None:
            scene_fps = "a strange "

        env = context.data.get("environment", dict())

        valid_fps = env.get("avalonFps")
        valid_edit_in = env.get("avalonEditIn")
        valid_edit_out = env.get("avalonEditOut")

        skip_on_none = [valid_fps, valid_edit_in, valid_edit_out]

        if None in skip_on_none:
            self.log.debug(" environment not set")
            return

        assert int(valid_fps) == int(scene_fps), (
            "The FPS is set to %sfps and not to %sfps"
            % (scene_fps, valid_fps))

        assert int(scene_in) == int(valid_edit_in), (
            "Animation Start is set to %s and not set to \"%s\""
            % (scene_in, valid_edit_in))

        assert int(scene_out) == int(valid_edit_out), (
            "Animation End is set to %s and not set to \"%s\""
            % (scene_out, valid_edit_out))