# -*- coding: utf-8 -*-
# @Time    : 2022/9/30 9:56
# @Author  : Carlos

# 百度小说 都市之帝尊归来
# 第一步：获取小说章节名、小说章节url
import asyncio

import aiohttp
import requests
import requests

# requests.get() 同步请求 ---转换为 aiohttp 异步请求
import asyncio
import aiohttp
from bs4 import BeautifulSoup
import aiofiles

import json

url1='http://baidu8.cread.com/book/805001003/3.html?nrhz=4a3929508b876c34e2bbd5685a5ac211'

# uri参数

async def aiodownload(cid, b_id, title):
    data = {
        "book_id":b_id,
        "cid":f"{b_id}|{cid}",
        "need_bookinfo":1
    }
    data = json.dumps(data)
    url = f"http://dushu.baidu.com/api/pc/getChapterContent?data={data}"
    # print(url)

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            # print(resp.url)
            dic = await resp.json()

            async with aiofiles.open("小说/"+title, mode="w", encoding="utf-8") as f:
                await f.write(dic['data']['novel']['content'])  # 把小说内容写出
                print(f'小说章节：{title}     下载成功')

            # print(dic['data']['novel']['content'])

async def get_url_task(book_id):

    tasks=[]

    data={
        'book_id': book_id
    }
    data=json.dumps(data)

    url =f"https://dushu.baidu.com/api/pc/getCatalog?data={data}"
    resp=requests.get(url)
    dic=resp.json()
    resp.close()
    # print(dic['data']['novel']['items'])

    x=1
    for items in dic['data']['novel']['items']:

        # 设置爬取章节次数
        x+=1
        if x==50:
            break

        cid=items["cid"]
        price_status=items["price_status"]
        title=items["title"]

        # print(f'小说章节：{title}')
        # print(f'cid编号：{cid}')

        task=asyncio.create_task(aiodownload(cid, book_id, title))
        tasks.append(task)
    await asyncio.wait(tasks)

if __name__ == '__main__':

    # RuntimeError: Event loop is closed解决办法 改为以下
    # asyncio.run(get_url_task())

    # url 百度小说 。
    'https: // dushu.baidu.com / pc / detail?gid = 4306170312'
    loop=asyncio.get_event_loop()
    loop.run_until_complete(get_url_task(4306170312))

print("运行成功")


"""
25 - Calcule as raizes da equação de 2º grau.
lembrando que:
x = -b, + ou - raiz de delta / 2a. Onde:
raiz de delta = B² - 4ac.
E ax² + bx + c = 0 representa uma equação de 2º grau.

A variável de zero tem que ser diferente de zero. Caso seja igual, imprima a
mensagem "Não é equação de segundo grau."

Se Delta < 0, não existe real. Imprima não existe raiz.
Se Delta = 0, existe uma raiz real. Imprima a raiz e a mensagem Raiz única.
Se Delta >= 0, imprima as duas raízes reais
"""
import math

a = int(input("Digite o valor de a: "))
b = int(input("Digite o valor de b: "))
c = int(input("Digite o valor de c: "))

#ax² + bx + c = 0 --> é o que queremos saber.

#valor de delta: B² - 4ac.
delta = (b * b) + (-4 * a * c)

if delta > 0:
    print(f'O valor de delta é {delta}')
    x1 = (- b + (math.sqrt(delta))) / 2 * a
    print(f'Essa é a primeira raiz quadrada, ou x1 {x1}')
    x2 = (- b - (math.sqrt(delta))) / 2 * a
    print(f'Essa é a segunda raiz quadrada, ou x2 {x2}')
elif delta == 0:
    print(f'A raiz de delta é {delta} sendo Raiz única.')
else:
    delta < 0
    print('Não existe raiz')

Exercicios Estruturas Logicas e Condicionais/exercicio 25 - secao 05.py


import os

from avocado import Test, skipIf
from avocado.utils import archive, build, process, distro, cpu
from avocado.utils.software_manager.manager import SoftwareManager

IS_POWER10 = 'POWER10' in open('/proc/cpuinfo', 'r').read()

class Numatop(Test):

    """
    Test case of numatop functionality
    Test runs mgen application to check numatop snapshot registers it

    :avocado: tags=cpu,privileged
    """

    @skipIf(IS_POWER10,
            "numatop is not supported on POWER10 Architecture")
    def setUp(self):
        '''
        Build numatop Test
        Source:
        https://github.com/01org/numatop.git
        '''

        # Check for basic utilities
        self.numa_pid = None
        distro_name = distro.detect().name.lower()
        smm = SoftwareManager()
        deps = ['gcc', 'numatop', 'make']
        if distro_name == 'ubuntu':
            deps.extend(['libnuma-dev', 'libncurses-dev', 'pkg-config',
                         'check'])
        elif distro_name in ['rhel', 'fedora']:
            deps.extend(['ncurses-devel', 'numactl-libs', 'numactl-devel',
                         'check-devel', 'libtool'])
        elif distro_name == 'suse':
            deps.extend(['ncurses-devel', 'libnuma-devel', 'check-devel',
                         'autoconf', 'libtool'])
        else:
            self.cancel("Install corresponding libnuma packages")

        for package in deps:
            if not smm.check_installed(package) and not smm.install(package):
                self.cancel("Failed to install %s, which is needed for"
                            "the test to be run" % package)

        locations = ["https://github.com/intel/numatop/archive/master.zip"]
        tarball = self.fetch_asset("numatop.zip", locations=locations,
                                   expire='7d')
        archive.extract(tarball, self.workdir)
        self.sourcedir = os.path.join(self.workdir, 'numatop-master')

        os.chdir(self.sourcedir)
        process.run('./autogen.sh', shell=True, sudo=True)
        build.make(self.sourcedir, extra_args='check')

    def test(self):

        mgen_flag = False
        mgen = os.path.join(self.sourcedir, 'mgen')
        numatop = os.path.join(self.sourcedir, 'numatop')
        cmd = numatop+" -d result_file"
        self.numa_pid = process.SubProcess(
            cmd, shell=True)
        self.numa_pid.start()

        # Run mgen for 5 seconds to generate a single snapshot of numatop
        process.run('%s -a 0 -c %s -t 5' %
                    (mgen, cpu.cpu_online_list()[0]), shell=True, sudo=True)

        # Kill numatop recording after running mgen
        self.numa_pid.terminate()

        # Analyse record file for mgen record
        with open('%s/result_file' % self.sourcedir, 'r') as f_read:
            lines = f_read.readlines()
            for line in lines:
                if 'mgen' in line:
                    mgen_flag = True
                    break
        if not mgen_flag:
            self.fail('Numatop failed to record mgen latency. Please check '
                      'the record file: %s/result_file' % self.sourcedir)


# coding=utf-8
"""
Created on Monday 28 March 00:53:34 2020

@author: nkalyanðŸ¤
        '''implementing Python scripts on Regex'''
"""

import re
from typing import TextIO, List

def average(items: str):
    """custom method that calculates the average by taking an array as an input, and
        divides the sum of the array by the number of items in the array."""
    return sum(items) / len(items)

try:
    '''prompts the user for the filename, with error handling.'''
    file_name: str = input('Enter the file name (include path if file is outside directory): ')
except EOFError:
    print('EOF command given. Quitting...bye!')
    exit()
except ValueError:
    print('This input is invalid! Please try again.')
    exit()

try:
    """attemps to the open the file, with exception handling if the program
            cannot find the file or another error occurs."""
    file: TextIO = open(file_name)
except FileNotFoundError:
    print('File cannot be opened:', file_name)
    exit()
except ValueError:
    print('An error occurred opening this file! Please try again.')
    exit()

items: List = []

try:
    """reads the file line by line"""
    for line in file:
        line: str = line.rstrip()                                    # strips the tailing characters

        matches: List[str] = re.findall('^New Revision: ([0-9]+.[0-9]+)', line)

        if len(matches) > 0:
            for item in matches:
                number: float = float(item)
                items.append(number)
except DeprecationWarning:
    print('Bad data was detected! Please check your file and try again.')
    exit()

if len(items) == 0:             # Make sure the program found at least 1 matching line before proceeding.
    print('The program did not find any matching lines! Please check your file and try again.')
    exit()

average = average(items)        # calls the average method and then rounds it to a single decimal place.
average = round(average, 1)

print(f'Average = {average}')
print(f'Number of lines = {len(items)}')


from pix2pix import *
from preprocessing.preprocessing import *
from utils import *

BUFFER_SIZE = 400
BATCH_SIZE = 1
IMG_WIDTH = 256
IMG_HEIGHT = 256
INPUT_DIR = "D://Uni//Licenta//data//white_forms_resized"
REAL_DIR = "D://Uni//Licenta//data//forms_mirrored_resized"

generator = Generator()
discriminator = Discriminator()

input_files = get_files(INPUT_DIR)
# tf.data.Dataset.list_files(INPUT_DIR+ "/*.jpg")

output_files=get_files(REAL_DIR)
    # tf.data.Dataset.list_files(REAL_DIR+"/*.jpg")

all=[[input_files[i],output_files[i]] for i in range(len(input_files))]
for el in all:
    print(el)

train_dataset = tf.data.Dataset.from_tensor_slices(all)
train_dataset = train_dataset.map(load_image_train)
train_dataset = train_dataset.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.batch(BATCH_SIZE)
# test_dataset = tf.data.Dataset.list_files(dirname+"/*.jpg")

generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
                                 discriminator_optimizer=discriminator_optimizer,
                                 generator=generator,
                                 discriminator=discriminator)

import datetime
log_dir = "logs/"
summary_writer = tf.summary.create_file_writer(
    log_dir + "fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))

@tf.function
def train_step(input_image, target, epoch):
    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
        gen_output = generator(input_image, training=True)
        disc_real_output = discriminator([input_image, target], training=True)
        disc_generated_output = discriminator([input_image, gen_output], training=True)
        gen_total_loss, gen_gan_loss, gen_l1_loss = generator_loss(disc_generated_output, gen_output, target)
        disc_loss = discriminator_loss(disc_real_output, disc_generated_output)
    generator_gradients = gen_tape.gradient(gen_total_loss,
                                            generator.trainable_variables)
    discriminator_gradients = disc_tape.gradient(disc_loss,
                                                 discriminator.trainable_variables)
    generator_optimizer.apply_gradients(zip(generator_gradients,
                                            generator.trainable_variables))
    discriminator_optimizer.apply_gradients(zip(discriminator_gradients,
                                                discriminator.trainable_variables))
    with summary_writer.as_default():
        tf.summary.scalar('gen_total_loss', gen_total_loss, step=epoch)
        tf.summary.scalar('gen_gan_loss', gen_gan_loss, step=epoch)
        tf.summary.scalar('gen_l1_loss', gen_l1_loss, step=epoch)
        tf.summary.scalar('disc_loss', disc_loss, step=epoch)

def fit(train_ds, epochs):
    for epoch in range(epochs):
        start = time.time()
        display.clear_output(wait=True)
        # for example_input, example_target in test_ds.take(1):
        #   generate_images(generator, example_input, example_target)
        # print("Epoch: ", epoch)
        # Train
        for n,(input_image, target) in train_ds.enumerate():
            print('.',end='')
            if (n + 1) % 100 == 0:
                print()
            train_step(input_image, target, epoch)
        print()
        # saving (checkpoint) the model every 20 epochs
        if (epoch + 1) % 20 == 0:
            checkpoint.save(file_prefix=checkpoint_prefix)

        print('Time taken for epoch {} is {} sec\n'.format(epoch + 1,time.time() - start))
    checkpoint.save(file_prefix=checkpoint_prefix)
EPOCHS = 5
fit(train_dataset, EPOCHS)


def lulin(blocks):
	if len(blocks) == 0:
		return 0

	tallest_block = blocks[0]
	seen = 1

	for block in blocks:
		if block > tallest_block:
			seen += 1
			tallest_block = block
	return seen

n = input("Enter numbers of blocks: ")
n = int(n)

blocks = []
begin = 1

while begin <= n:
	tall = input("The hight of block is: ")
	tall = int(tall)

	blocks = blocks + [tall]
	begin += 1

print("The person view " + str(lulin(blocks))  + " block(s)")


container_list = []
number_cont = int(input('Введите количество контейнеров: '))

for i in range(number_cont):
  container_weight = int(input('введите вес контейнера: '))
  if container_weight > 200:
    print('Ошибка ввода')
  else:
    container_list.append(container_weight)

print()
new_container = int(input('Введите вес нового контейнера: '))
early_container = 200

for i in range(len(container_list)):
  if early_container > new_container > container_list[i]:
    print('Номер, куда встанет новый контейнер:', i + 1)

  early_container = container_list[i]


from Statlist import Statlist
from Weaponlist import Weaponlist
#An interface for the personal attributes for each unit
#Written by Greg Suner
class Personal(object):

	#__init__ personal properties
	def __init__(self,growth,gains,max,name,internalLv,culmLv,wepExp,classSet,supportIndex,skills,weakness,movement,iconID):
		self.growth = Statlist(*growth)
		self.gains = Statlist(*gains)
		self.maxStats = Statlist(*max)
		self.name = name
		self.internalLv = internalLv
		self.culmLv = culmLv
		self.wepExp = Weaponlist(*wepExp)
		self.classSet = classSet
		self.supportIndex = supportIndex
		self.skills = skills
		self.weakness = weakness
		self.movement = movement
		self.iconID = iconID


import cv2

#cv2.namedWindow("Webcam", cv2.WINDOW_NORMAL)

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

if not cap.isOpened():
    print("Error: Couldn't open the webcam.")
    exit()

while True:
    ret, frame = cap.read()
    if not ret:
        print("Error: Couldn't read a frame from webcam.")
        break

    cv2.imshow('Webcam', frame)

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

cap.release()
cv2.destroyAllWindows()


import tensorflow as tf
import matplotlib.pyplot as plt
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras import utils
from keras.callbacks import TensorBoard
import numpy as np
from keras import backend as K

from sklearn.metrics import roc_auc_score
from keras.callbacks import Callback

# parameter for LSTM
data_dim = 29
timesteps = 1
num_classes = 2
batch_size = 50
hide_units = 50
dropout = 0.5
learn_rate = 0.001
epochs = 20

# load data
dataset = read_csv('data/credictcard.csv', index_col=0)
dataset = dataset.iloc[0:280000]
print(dataset.describe())
print(dataset.head())
X = dataset.iloc[:, 0:29]
y = dataset.iloc[:, 29]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=4)
y_train = utils.to_categorical(y_train, num_classes)
y_test = utils.to_categorical(y_test, num_classes)
X_train = np.expand_dims(X_train, 1)
X_test = np.expand_dims(X_test, 1)

# print(X_train.shape)

class roc_callback(Callback):
    def __init__(self, training_data, validation_data):
        self.x = training_data[0]
        self.y = training_data[1]
        self.x_val = validation_data[0]
        self.y_val = validation_data[1]

    def on_train_begin(self, logs={}):
        return

    def on_train_end(self, logs={}):
        return

    def on_epoch_begin(self, epoch, logs={}):
        return

    def on_epoch_end(self, epoch, logs={}):
        print(self.x.shape)
        y_pred = self.model.predict(self.x)
        roc = roc_auc_score(self.y, y_pred)
        y_pred_val = self.model.predict(self.x_val)
        roc_val = roc_auc_score(self.y_val, y_pred_val)
        print('\rroc-auc: %s - roc-auc_val: %s' % (str(round(roc, 4)), str(round(roc_val, 4))), end=100 * ' ' + '\n')
        return

    def on_batch_begin(self, batch, logs={}):
        return

    def on_batch_end(self, batch, logs={}):
        return

model = Sequential()
model.add(LSTM(hide_units, return_sequences=True, dropout=dropout,
               batch_input_shape=(batch_size, timesteps, data_dim)))
model.add(LSTM(hide_units, return_sequences=True, dropout=dropout))
model.add(LSTM(hide_units, dropout=dropout))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam')

model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(X_test, y_test),
          callbacks=[TensorBoard(log_dir='logs_auc/'),
                     roc_callback(training_data=(X_train, y_train), validation_data=(X_test, y_test))])

model.save('models/FraudDetectionModel_auc.h5')

# X_train = dataset.iloc[:, 0:28].values
# y_train = dataset.iloc[:, 29].values
# X_train.reshape(shape=(-1, 29, 1))
# y_train.reshape(shape=(-1, 1))

#


'''

'''

def get_period(x, P1, P2):
    '''
    Returns the period of x, P1 and P2
    '''
    if x == 0:
        period = P1
    elif x == 1:
        period = P2
    else:
        period = get_period(x - 2, P1, P2)
    return period

def get_values(row, column, matrix, P1, P2, period):
    '''
    Returns the values to be appended
    '''
    values = []
    if row == 0:
        values = [period]
    else:
        values.append(period)
        values.extend(matrix[row - 1][column])
    return values

def get_image_count(grid, P1, P2, move):
    '''
    Returns the total number of images in the grid, post the given move
    '''
    rows = len(grid)
    columns = len(grid[0])
    matrix = []
    for row in range(rows):
        matrix.append([])
        for column in range(columns):
            matrix[row].append(get_values(row, column, matrix, P1, P2, get_period(column, P1, P2)))
    for row in range(rows):
        for column in range(columns):
            if row == 0:
                grid[row][column] = max(1, grid[row][column])
            else:
                grid[row][column] = max(1, grid[row][column]) + len([x for x in matrix[row - 1][column] if x < move])
    return grid, matrix

def get_total_images(grid):
    '''
    Returns the total number of images in the grid
    '''
    return sum([sum(x) for x in grid])

def main():
    '''
    Driver function
    '''
    rows, columns, _ = map(int, input().split())
    row, column = map(int, input().split())
    grid = [[0 for _ in range(columns)] for _ in range(rows)]
    grid[row - 1][column - 1] = 1
    p1 = [int(x) for x in input().split()]
    p2 = [int(x) for x in input().split()]
    for _ in range(int(input())):
        p1_index = 0
        p2_index = 0
        for _ in range(int(input())):
            grid, _ = get_image_count(grid, p1[p1_index], p2[p2_index], _ + 1)
            p1_index += 1
            p2_index += 1
            if p1_index == len(p1):
                p1_index = 0
            if p2_index == len(p2):
                p2_index = 0
        print(get_total_images(grid))
        grid = [[0 for _ in range(columns)] for _ in range(rows)]
        grid[row - 1][column - 1] = 1

if __name__ == '__main__':
    main()


from noether.core import Measure, MeasureInfo

from ..fundamental import meter
from ..dimensions import length, frequency, energy
from ..scientific.si import c, h

SPECTRUM: dict[str, tuple[float, float]] = {
    # ISO 21348. spacewx.com/pdf/SET_21348_2004.pdf
    # measured in nm
    "xray": (0.001, 0.1),
    "XUV": (0.1, 10),

    "ultraviolet": (100, 400),
    "VUV": (10, 200),
    "EUV": (10, 121),
    "H_Lyman_alpha": (121, 122),
    "FUV": (122, 200),
    "UVC": (100, 280),
    "MUV": (200, 300),
    "UVB": (280, 315),
    "NUV": (300, 400),
    "UVA": (315, 400),

    "visible": (380, 760),
    "purple": (360, 450),
    "blue": (450, 500),
    "green": (500, 570),
    "yellow": (570, 591),
    "orange": (591, 610),
    "red": (610, 760),

    "infrared": (760, 1e6),
    "IRA": (760, 1400),
    "IRB": (1400, 3000),
    "IRC": (3000, 1e6),

    "microwave": (1e6, 15e6),
    "W": (3.00e6, 5.35e6),
    "V": (5.35e6, 5.52e6),
    "Q": (6.52e6, 8.33e6),
    "K": (8.33e6, 2.75e7),
    "X": (2.75e7, 5.77e7),
    "C": (4.84e7, 7.69e7),
    "S": (5.77e7, 1.93e8),
    "L": (1.93e8, 7.69e8),
    "P": (7.69e8, 1.33e9),

    "radio": (1e5, 1e11),
    "EHF": (1e6, 1e7),
    "SHF": (1e7, 1e8),
    "UHF": (1e8, 1e9),
    "VHF": (1e9, 1e10),
    "HF": (1e10, 1e11)
}

def spectrum_names(wavelength: Measure[float]) -> list[str]:
    names = []
    for name, (a, b) in SPECTRUM.items():
        v_nm = wavelength.value / 1e-9
        if a <= v_nm < b:
            names.append((b-a, name))
    return [name for _, name in sorted(names, reverse=True)]

@Measure.Info
class info_spectrum(MeasureInfo):
    "Show EM spectrum names (eg UV-B, Wifi) for wavelengths, frequencies and energies."
    enabled_by_default = False
    style = 'underline blue'

    @staticmethod
    def should_display(measure: Measure):
        return measure.dim in (length, frequency, energy)

    @staticmethod
    def info(measure: Measure):
        wavelength = measure
        if measure.dim == frequency:
            wavelength = c / measure
        elif measure.dim == energy:
            wavelength = h*c / measure
        yield from spectrum_names(wavelength)


import requests
import xmltodict

class CBRFApi:
    BASE_URL = 'https://www.cbr-xml-daily.ru/'

    def get_daily_rates(self):
        """Получение ежедневных курсов валют."""
        response = requests.get(f'{self.BASE_URL}daily_json.js')
        response.raise_for_status()
        return response.json()

    def get_dynamic_rates(self, currency_id, start_date, end_date):
        """Получение динамики курсов валюты за период."""
        dynamic_url = f'{self.BASE_URL}dynamic/{start_date}/{end_date}/{currency_id}.json'
        response = requests.get(dynamic_url)
        response.raise_for_status()
        return response.json()

    def get_currencies_list(self):
        """Получение списка валют."""
        response = requests.get(f'{self.BASE_URL}daily_json.js')
        response.raise_for_status()
        data = response.json()
        return data['Valute']

    def get_currency_info(self, currency_char_code):
        """Получение информации о конкретной валюте."""
        daily_rates = self.get_daily_rates()
        return daily_rates['Valute'].get(currency_char_code)

class CBRService:
    def __init__(self):
        self.base_url = "http://www.cbr.ru/scripts/"

    def get_daily_quotes(self, date_req=None):
        url = self.base_url + "XML_daily.asp"
        params = {'date_req': date_req} if date_req else {}
        response = requests.get(url, params=params)
        return xmltodict.parse(response.content)

    def get_currency_codes(self, daily=True):
        url = self.base_url + "XML_val.asp"
        params = {'d': '0' if daily else '1'}
        response = requests.get(url, params=params)
        return xmltodict.parse(response.content)

    def get_dynamic_quotes(self, date_req1, date_req2, val_nm_rq):
        url = self.base_url + "XML_dynamic.asp"
        params = {
            'date_req1': date_req1,
            'date_req2': date_req2,
            'VAL_NM_RQ': val_nm_rq
        }
        response = requests.get(url, params=params)
        return xmltodict.parse(response.content)

    def get_correspondent_account_balances(self, date_req1, date_req2):
        url = self.base_url + "XML_ostat.asp"
        params = {
            'date_req1': date_req1,
            'date_req2': date_req2
        }
        response = requests.get(url, params=params)
        return xmltodict.parse(response.content)


'''
This file contains the logic for reminding the user to leave work at 9 PM.
'''
from datetime import datetime, time
import schedule
import conversation_topics  # Add this import statement
def remind_leave_work(app):
    current_time = datetime.now().strftime("%H:%M")
    print(f"Reminder: It's {current_time}. Leave work now!")
    # Add your additional logic here, such as sending notifications or displaying reminders in the app
    # Implement your logic to remind the user to leave work at 9 PM
    # Update the reminder label in the app
    app.reminder_label.config(text=f"Reminder: It's {current_time}. Leave work now!")
    # Get conversation topics
    topics = conversation_topics.get_conversation_topics()
    print("Conversation topics for tomorrow:")
    topics = "\n".join(topics)
    app.reminder_label.config(text=f"To avoid awkward moments in the office elevator, here are some conversation topics: \n{topics}")
# Schedule the leave work reminder
schedule.every().day.at("21:00").do(lambda: remind_leave_work(app))


import torch
import numpy as np
import sys
import gym

sys.path.append("./")
from base_net.model import *
from torch import nn, optim
import torch.nn.functional as F
from torch.distributions import Categorical

class ActorCritic(nn.Module):
    def __init__(self, args):
        super(ActorCritic, self).__init__()
        self.input_size, self.output_size, self.device, self.actor_lr, self.critic_lr = args
        self.actor = Policy_net(args = (self.input_size, self.output_size))
        self.critic = Q_net(args = (self.input_size, 1))

        self.buffer = ReplayBuffer(args = (10000))
        self.optimizer_actor = optim.Adam(self.actor.parameters(), lr = self.actor_lr)
        self.optimizer_critic = optim.Adam(self.critic.parameters(), lr = self.critic_lr)

    def get_policy(self, inputs):
        return F.softmax(self.actor(inputs), -1)

    def save_trans(self, transition):
        self.buffer.save_trans(transition)

    def to_tensor(self, items):
        s, a, r, s_next, done = items
        s = torch.FloatTensor(s).to(self.device)
        a = torch.LongTensor(a).to(self.device)
        r = torch.FloatTensor(r).to(self.device)
        s_next = torch.FloatTensor(s_next).to(self.device)
        done = torch.FloatTensor(done).to(self.device)

        return s, a.unsqueeze(-1), r.unsqueeze(-1), s_next, done.unsqueeze(-1)

    def select_action(self, inputs):
        action_prob = self.get_policy(inputs)
        action = Categorical(action_prob)
        action = action.sample().item()
        return action

    def train(self, gamma = 0.98):
        s, a, r, s_next, done = self.to_tensor(self.buffer.sample_all_data())

        q_val = self.critic(s)
        target_q_val = r + gamma * self.critic(s_next) * (1 - done)
        advantage = target_q_val.detach() - q_val
        loss_critic = (advantage ** 2).mean()
        self.optimizer_critic.zero_grad()
        loss_critic.backward()
        self.optimizer_critic.step()

        loss_actor = (-torch.log(self.get_policy(s).gather(-1, a)) * advantage.detach()).mean()
        self.optimizer_actor.zero_grad()
        loss_actor.backward()
        self.optimizer_actor.step()

        self.buffer.clear()

    def train_for_a3c(self, replay_buffer, gamma = 0.98):
        s, a, r, s_next, done = self.to_tensor(replay_buffer.sample_all_data())

        q_val = self.critic(s)
        target_q_val = r + gamma * self.critic(s_next) * (1 - done)
        advantage = target_q_val.detach() - q_val
        loss_critic = (advantage ** 2).mean()
        self.optimizer_critic.zero_grad()
        loss_critic.backward()
        self.optimizer_critic.step()

        loss_actor = (-torch.log(self.get_policy(s).gather(-1, a)) * advantage.detach()).mean()
        self.optimizer_actor.zero_grad()
        loss_actor.backward()
        self.optimizer_actor.step()

        replay_buffer.clear()

'''
ActorCritic test
'''
if __name__ == "__main__":
    env = gym.make("CartPole-v0")
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    model = ActorCritic(args = (4, 2,  device, 1e-3, 1e-3)).to(device)
    for i in range(10000):
        s = env.reset()
        score = 0.
        for t in range(200):
            action = model.select_action(torch.FloatTensor(s).to(device))

            s_next, reward, done, info = env.step(action)
            model.save_trans((s, action, reward, s_next, done))
            score += reward
            s = s_next
            if done:
                break
        model.train()
        print("Epoch:{}    Score:{}".format(i+1, score))


import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
num = sys.argv[1]
fin = open('wf_curve' + num + '.txt')
fin1 = open('lzc_curve' + num + '.txt')

wf = []
lzc = []
for l in fin:
    token = l.split()
    wf.append(token[2])
for l in fin1:
    token = l.split()
    lzc.append(token[2])

wf = map(float, wf)
lzc = map(float, lzc)

#plt.title('Splice training curve based on gammas-model')
plt.title('Training curve')
plt.ylabel('Error(%)')
plt.xlabel('Epoch')
axes = plt.gca()
axes.set_ylim([0, 50])
#plt.plot(t1, tr, label='training')
#plt.plot(t1, te, label='validation')
plt.plot(range(len(wf)), wf, label='default')
plt.plot(range(len(lzc)), lzc, label='finetune')
plt.legend(loc='upper right')

plt.show()
plt.savefig('error' + num + '.png')


'''
Created By Johnny copied from Geeks for Geeks
'''

# PIL module is used to extract pixels of the image and modify it
# from PIL import Image

# Convert encoding data into 8-bit binary
# form using ASCII value of characters

from modify_pixels import modify

def encrypt(new_image, data):
    w = new_image.size[0]
    (x, y) = (0, 0)

    for pixel in modify(new_image.getdata(), data):

        new_image.putpixel((x, y), pixel)

        if x == w - 1:
            x = 0

            y += 1
        else:
            x += 1
    return new_image


from mold import Tool, templates_from_directory, hook
from ...domains import python, module
from ...categories import source as source_category
from ...face.build import Accepts as BuildVars
from ...face.readme import interface as readme, Accepts as ReadmeVars
from ..source_basic_py import tool as source

example = """\
.. code: sh

   $ {slug} arg --flag --opt value
   $ {slug} --help\
"""

def accept_vars():
    slug = hook.Provides.project_slug
    ReadmeVars.readme_example_lines = example.format(slug=slug).split('\n')
    BuildVars.build_entry_points['console_scripts'].append(f'{slug} = {slug}.cli:main')

tool = Tool(
    module,
    'python cli',
    'source for a Python CLI tool',
    depends=[source, readme],
    category=source_category,
    templates=templates_from_directory(__file__),
    accept_vars=accept_vars,
)
python.add_tool(tool)


ask = input().split()

a,b,c = ask

a = float(a)
b = float(b)
c = float(c)

mexof = max(a,b,c)

li = [a,b,c]
li.remove(mexof)

sumof = li[0] + li[1]
if sumof <= mexof:
    print("Area =",.5 * (a+ b) * c)
else:
    print(f"Perimetro = {a+b+c}")


# Projet : Systeme de recommandation de livres  ( projet L1)
#Ce fichier sert à gérer les modifications dans le dépot de livre
from function_window_register import ListeLivres
import main

def Recup_Livre_Supp (Valeur):
    #Cette fonction permets de supprimer un livre donné par l'utilisateur dans le fichier books.txt
    #Entrée : Valeur:le titre du livre a supprimer ; le fichier books.txt
    #Sortie : le fichier books.txt sans le livre donné

    Liste_Livre =ListeLivres()      #fonction du fichier function_window_register qui permet de recuperer la liste de tous les livres de books.txt

    for element in range(len(Liste_Livre)-1):
        if Liste_Livre[element]==Valeur:                    #Parcours de la liste des livres
            Liste_Livre.pop(element)                        #Suppression du livre grace à l'indice dans la liste
    with open('books.txt','w',encoding='utf-8') as f :
        for element in Liste_Livre:
            f.write(element + '\n')                        #Réécriture du fichier books.txt sans le livre donné

def Recup_Livre_Modif(Valeur,Valeur_Modif):
    #Cette fonction permet de modifier le titre d'un livre du fichier books.txt
    #Entrée : books.txt ; Valeur:le titre du livre a modifier ; Valeur_Modif : le nouveau titre
    #Sortie : le fichier books.txt avec le titre (Valeur) modifier en (Valeur_Modif)

    Liste_Livre = ListeLivres()                      #fonction du fichier function_window_register qui permet de recuperer la liste de tous les livres de books.txt
    for element in range(len(Liste_Livre)-1):       #Verifie que le titre n'existe pas deja
        if Liste_Livre[element]==Valeur_Modif:
            return()

        if Liste_Livre[element]==Valeur:
            Liste_Livre.pop(element)            #Supprime le titre
            Liste_Livre.insert(element,Valeur_Modif)    #Insert à la place de l'ancien titre le nouveau

    with open('books.txt','w',encoding='utf-8') as f :
        for element in Liste_Livre:
            f.write(element + '\n')             #Réecriture dans books.txt

def Ajouter_Livre_Txt(Title):
    #Cette fonction permet d'ajouter un livre au fichier books.txt
    #Entrée : books.txt, Title : Nouveau titre
    #Sortie : books.txt avec le nouveau livre

    Liste_Livre = ListeLivres()      #fonction du fichier function_window_register qui permet de recuperer la liste de tous les livres de books.txt
    for element in range(len(Liste_Livre)-1):    #Verifie que le titre n'existe pas deja
        if Liste_Livre[element]==Title:
            return()

    with open('books.txt','a',encoding='utf-8') as f:
        f.write(Title)          #Ajout dans books.txt


# -*- coding: utf-8 -*-
from convlab2.nlg.scgpt.multiwoz.scgpt import SCGPT
from convlab2.laug.Text_Paraphrasing.utils import span2tuple,paraphrase_span_detection
class Text_Paraphrasing:
    def __init__(self,dataset='multiwoz'):
        if dataset=='multiwoz':
            self.model=SCGPT()
        if dataset=='frames':
            self.model=SCGPT(model_file='https://huggingface.co/ConvLab/ConvLab-2_models/resolve/main/nlg-gpt-frames.zip')
        self.model.init_session()
    def aug(self,text,span_info):
        t=span2tuple(span_info)
        new_text = self.model.generate(t)
        new_span_info = paraphrase_span_detection(new_text,span_info)
        return new_text, new_span_info

if __name__=="__main__":
    text = "I want a train to Cambridge"
    span_info = [["Train-Infrom","Dest","Cambridge",5,5]]
    TP = Text_Paraphrasing()
    new_text,new_span_info = TP.aug(text,span_info)
    print(new_text)
    print(new_span_info)


# file: mirroring2_adupree.py
# description: variety of functions to mirrow the image
# author: Alex DuPree
# date: 11 / 6 / 2017
# compiler: JES 5.01

def main():
    file = pickAFile()
    image = makePicture(file)
    image = mirror_top(image)
    show(image)

# def mirror_right(image):
#     width = getWidth(image)
#     height = getHeight(image)
#     for x in range(width / 2):
#         for y in range(height):
#             left_pixel_color = getColor(getPixel(image, x, y))
#             right_pixel = getPixel(image, width - x - 1, y)
#             setColor(right_pixel, left_pixel_color)
#     return image

def mirror_left(image):
    width = getWidth(image)
    height = getHeight(image)
    for x in range(width / 2):
        for y in range(height):
            right_pixel_color = getColor(getPixel(image, width - x - 1, y))
            left_pixel = getPixel(image, x, y)
            setColor(left_pixel, right_pixel_color)
    return image

def mirror_top(image):
    width = getWidth(image)
    height = getHeight(image)
    for x in range(width):
        for y in range(height / 2):
            top_pixel_color = getColor(getPixel(image, x, y))
            bottom_pixel = getPixel(image, x, height - y - 1)
            setColor(bottom_pixel, top_pixel_color)
    return image

# def mirror_bottom(image):
#     width = getWidth(image)
#     height = getHeight(image)
#     for x in range(width):
#         for y in range(height / 2):
#             bottom_pixel_color = getColor(getPixel(image, x, height - y - 1))
#             top_pixel = getPixel(image, x, y)
#             setColor(top_pixel, bottom_pixel_color)
#     return image

main()


#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests

url = 'https://api.github.com/users/rapid7'
headers = {'user-agent': 'my-app/0.0.1'}

r = requests.get(url, headers=headers)
print(r.json())

"""
Note: Custom headers are given less precedence than more
specific sources of information.  For instance:

    * Authorization headers will be overridden if credentials are passed via
      the auth parameter or are specified in a .netrc accessible in the
      environment.

    * Authorization headers will be removed if you get redirected off-host.

    * Proxy-Authorization headers will be overridden by proxy credentials
      provided in the URL.

    * Content-Length headers will be overridden when we can determine
      the length of the content.

Furthermore, Requests does not change its behavior at all based on
which custom headers are specified. The headers are simply passed
on into the final request.
"""


"""
https://github.github.com/gfm/#paragraph
"""
from test.utils import act_and_assert

import pytest

@pytest.mark.gfm
def test_paragraph_series_a_b():
    """
    Test case:  Paragraph starts with a backslash escape
    was:        test_paragraph_extra_01
    """

    # Arrange
    source_markdown = """\\\\this is a fun day"""
    expected_tokens = [
        "[para(1,1):]",
        "[text(1,1):\\\b\\this is a fun day:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
\\this is a fun day
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_bh():
    """
    Test case:  Paragraph starts with a backslash as in a hard line break
    was:        test_paragraph_extra_02
    """

    # Arrange
    source_markdown = """\\
"""
    expected_tokens = [
        "[para(1,1):]",
        "[text(1,1):\\:]",
        "[end-para:::True]",
        "[BLANK(2,1):]",
    ]
    expected_gfm = """
\\
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_sh():
    """
    Test case:  Paragraph starts with spaces as in a hard line break
    was:        test_paragraph_extra_03
    """

    # Arrange
    source_markdown = """\a\a\a
---""".replace(
        "\a", " "
    )
    expected_tokens = ["[BLANK(1,1):   ]", "[tbreak(2,1):-::---]"]
    expected_gfm = """
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_cs():
    """
    Test case:  Paragraph string starting with a code span.
    was:        test_paragraph_extra_04
    """

    # Arrange
    source_markdown = """`this` is a fun day"""
    expected_tokens = [
        "[para(1,1):]",
        "[icode-span(1,1):this:`::]",
        "[text(1,7): is a fun day:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
this is a fun day
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_cr():
    """
    Test case:  Paragraph string starting with a character reference.
    was:        test_paragraph_extra_05
    """

    # Arrange
    source_markdown = """& the band played on"""
    expected_tokens = [
        "[para(1,1):]",
        "[text(1,1):\a&\a\a&\a&\a\a the band played on:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
& the band played on
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_rh():
    """
    Test case:  Paragraph string starting with a raw html block.
    was:        test_paragraph_extra_06
    """

    # Arrange
    source_markdown = """<there it='is'>, really"""
    expected_tokens = [
        "[para(1,1):]",
        "[raw-html(1,1):there it='is']",
        "[text(1,16):, really:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
<there it='is'>, really
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_ua():
    """
    Test case:  Paragraph string starting with an URI autolink
    was:        test_paragraph_extra_07
    """

    # Arrange
    source_markdown = """<http://www.google.com> to look"""
    expected_tokens = [
        "[para(1,1):]",
        "[uri-autolink(1,1):http://www.google.com]",
        "[text(1,24): to look:]",
        "[end-para:::True]",
    ]
    expected_gfm = (
        """
http://www.google.com to look
"""
    )

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_ea():
    """
    Test case:  Paragraph string starting with an email autolink
    was:        test_paragraph_extra_08
    """

    # Arrange
    source_markdown = """<foo@bar.com> for info"""
    expected_tokens = [
        "[para(1,1):]",
        "[email-autolink(1,1):foo@bar.com]",
        "[text(1,14): for info:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
foo@bar.com for info
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_e():
    """
    Test case:  Paragraph string starting with an emphasis
    was:        test_paragraph_extra_09
    """

    # Arrange
    source_markdown = """*it's* me!"""
    expected_tokens = [
        "[para(1,1):]",
        "[emphasis(1,1):1:*]",
        "[text(1,2):it's:]",
        "[end-emphasis(1,6)::]",
        "[text(1,7): me!:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
it's me!
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_l():
    """
    Test case:  Paragraph string starting with a link
    was:        test_paragraph_extra_10
    """

    # Arrange
    source_markdown = """[Foo](/uri "t") is a link"""
    expected_tokens = [
        "[para(1,1):]",
        '[link(1,1):inline:/uri:t::::Foo:False:":: :]',
        "[text(1,2):Foo:]",
        "[end-link::]",
        "[text(1,16): is a link:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
Foo is a link
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)

@pytest.mark.gfm
def test_paragraph_series_a_i():
    """
    Test case:  Paragraph string starting with an image
    was:        test_paragraph_extra_11
    """

    # Arrange
    source_markdown = """![foo](/url "t") is an image"""
    expected_tokens = [
        "[para(1,1):]",
        '[image(1,1):inline:/url:t:foo::::foo:False:":: :]',
        "[text(1,17): is an image:]",
        "[end-para:::True]",
    ]
    expected_gfm = """
 is an image
"""

    # Act & Assert
    act_and_assert(source_markdown, expected_gfm, expected_tokens)


num = int(input('Digite um numero: '))
cont = 0
for c in range(1, num+1):
    if num % c == 0:
        cont += 1
        print(f'\033[1;33m{c}', end=' ')
    else:
        print(f'\033[1;31m{c}', end=' ')
print(f'\n\033[mO numero {num} foi divisivel {cont} vezes')
if cont > 2:
    print('E por isso \033[1;31mNAO E PRIMO\033[m')
else:
    print('E por isso \033[1;33mE PRIMO\33[m')


class Solution:
    # @param {string} s
    # @param {string} t
    # @return {integer}
    def numDistinct(self, s, t):
        len_s = len(s)
        len_t = len(t)

        if len_t == 0 or len_s == 0:
            return 0

        dp = [[0] * len_t for i in range(len_s)] # len_s by len_t

        for i in range(len_s):
            dp[i][0] = dp[i-1][0] + (1 if s[i] == t[0] else 0)

        for i in range(1, len_s):
            for j in range(1, len_t):
                dp[i][j] = dp[i-1][j] + (dp[i-1][j-1] if s[i] == t[j] else 0)

        return dp[-1][-1]

solu = Solution()
dp = solu.numDistinct("rabbbit", "rabbit")
print(dp)


"""
Parses Google Takeout using [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]]

See [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] for more information
about how to export and organize your takeouts

If the DISABLE_TAKEOUT_CACHE environment variable is set, this won't cache individual
exports in ~/.cache/google_takeout_parser

The directory set as takeout_path can be unpacked directories, or
zip files of the exports, which are temporarily unpacked while creating
the cachew cache
"""

REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"]

from contextlib import ExitStack
import os
from typing import List, Sequence, cast
from pathlib import Path
from my.core import make_config, dataclass
from my.core.common import Stats, LazyLogger, mcachew, get_files, Paths
from my.core.error import ErrorPolicy
from my.core.structure import match_structure

from my.core.time import user_forced
from google_takeout_parser.parse_html.html_time_utils import ABBR_TIMEZONES
ABBR_TIMEZONES.extend(user_forced())

import google_takeout_parser
from google_takeout_parser.path_dispatch import TakeoutParser
from google_takeout_parser.merge import GoogleEventSet, CacheResults

# see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example
from my.config import google as user_config

@dataclass
class google(user_config):
    # directory which includes unpacked/zipped takeouts
    takeout_path: Paths

    error_policy: ErrorPolicy = 'yield'

    # experimental flag to use core.kompress.ZipPath
    # instead of unpacking to a tmp dir via match_structure
    _use_zippath: bool = False

config = make_config(google)

logger = LazyLogger(__name__, level="warning")

# patch the takeout parser logger to match the computed loglevel
from google_takeout_parser.log import setup as setup_takeout_logger
setup_takeout_logger(logger.level)

DISABLE_TAKEOUT_CACHE = "DISABLE_TAKEOUT_CACHE" in os.environ

def inputs() -> Sequence[Path]:
    return get_files(config.takeout_path)

EXPECTED = (
    "My Activity",
    "Chrome",
    "Location History",
    "Youtube",
    "YouTube and YouTube Music",
)

google_takeout_version = str(getattr(google_takeout_parser, '__version__', 'unknown'))

def _cachew_depends_on() -> List[str]:
    exports = sorted([str(p) for p in inputs()])
    # add google takeout parser pip version to hash, so this re-creates on breaking changes
    exports.insert(0, f"google_takeout_version: {google_takeout_version}")
    return exports

# ResultsType is a Union of all of the models in google_takeout_parser
@mcachew(depends_on=_cachew_depends_on, logger=logger, force_file=True)
def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults:
    error_policy = config.error_policy
    count = 0
    emitted = GoogleEventSet()
    # reversed shouldn't really matter? but logic is to use newer
    # takeouts if they're named according to date, since JSON Activity
    # is nicer than HTML Activity
    for path in reversed(inputs()):
        with ExitStack() as exit_stack:
            if config._use_zippath:
                from my.core.kompress import ZipPath
                # for later takeouts it's just 'Takeout' dir,
                # but for older (pre 2015) it contains email/date in the subdir name
                results = tuple(cast(Sequence[Path], ZipPath(path).iterdir()))
            else:
                results = exit_stack.enter_context(match_structure(path, expected=EXPECTED, partial=True))
            for m in results:
                # e.g. /home/sean/data/google_takeout/Takeout-1634932457.zip") -> 'Takeout-1634932457'
                # means that zipped takeouts have nice filenames from cachew
                cw_id, _, _ = path.name.rpartition(".")
                # each takeout result is cached as well, in individual databases per-type
                tk = TakeoutParser(m, cachew_identifier=cw_id, error_policy=error_policy)
                # TODO might be nice to pass hpi cache dir?
                for event in tk.parse(cache=not disable_takeout_cache):
                    count += 1
                    if isinstance(event, Exception):
                        if error_policy == 'yield':
                            yield event
                        elif error_policy == 'raise':
                            raise event
                        elif error_policy == 'drop':
                            pass
                        continue
                    if event in emitted:
                        continue
                    emitted.add(event)
                    yield event  # type: ignore[misc]
    logger.debug(
        f"HPI Takeout merge: from a total of {count} events, removed {count - len(emitted)} duplicates"
    )

def stats() -> Stats:
    from my.core import stat

    return {
        **stat(events),
    }


"""https://www.codewars.com/kata/52f78966747862fc9a0009ae"""
import operator
OPERATORS = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}

def calc(expr):
    expr = expr.split()
    stack = []
    if not expr:
        return 0
    for i in expr:
        if i in OPERATORS.keys():
            a, b = stack.pop(-1), stack.pop(-1)
            stack.append(OPERATORS[i](b,a))
        else:
            stack.append(float(i))
    return stack.pop()

6 kyu/Reverse polish notation calculator.py


#----------------------------START--------------------------
import os #For getting the path.
import time #For waiting.
import speech_recognition as sr #For trigger the program.
from google.cloud import texttospeech #For voice Output
import openai #For ChatGpt and Whisper
import pyaudio #For voice record
from pydub import AudioSegment #For getting the duration of sound files.
import numpy as np #For voice record contiunity
import pygetwindow #For minimize the media player window
#--------------------------- RECORD --------------------------
import sounddevice as sd #For voice record
import soundfile as sf #For voice record
#--------------------------- RECORD --------------------------
#Buradan FFMPEG indirilmelidir.
#https://www.gyan.dev/ffmpeg/builds/ - ffmpeg-git-full.7z - C:\ffmpeg\bin
#Kullanıcı ve Sistem için Path değişkenine bu yol dahil edilmelidir.
#--------------------------- KEYS ----------------------------
# Set OpenAI API key
openai.api_key = "YOUR OPENAI API KEY CODE"

# Set Google Cloud credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "YOUR GOOGLE JSON FILE NAME"

# Initialize Whisper model
whisper_model = "whisper-1"

# Initialize ChatGPT model
chatgpt_model = "gpt-3.5-turbo"
#--------------------------- KEYS ---------------------------
#--------------------- GOOGLE VOICE OUTPUT ------------------
# Initialize Google Text-to-Speech client
google_client = texttospeech.TextToSpeechClient()
# Function to speak
def speak(text):
    synthesis_input = texttospeech.SynthesisInput(text=text)
    voice = texttospeech.VoiceSelectionParams(language_code="tr-TR", ssml_gender=texttospeech.SsmlVoiceGender.MALE)
    audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)

    response = google_client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)

    with open("output.mp3", "wb") as out:
        out.write(response.audio_content)

    os.system("start output.mp3")

def process_voice_input():
    r = sr.Recognizer()

    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)

    try:
        print("Processing voice input...")
        text = r.recognize_google(audio, language="tr-TR")
        print("Voice input:", text)
        return text
    except sr.UnknownValueError:
        print("Unable to understand the voice input.")
    except sr.RequestError as e:
        print(f"Error occurred during speech recognition: {e}")
#--------------------- GOOGLE VOICE OUTPUT ------------------
#--------------------  CHATGPT RESPONSE ---------------------
def process_chatgpt_input(input_text):
    response = openai.Completion.create(
        engine=chatgpt_model,
        prompt=input_text,
        max_tokens=50,
        n=1,
        stop=None,
        temperature=0.7,
        log_level="info"
    )

    return response.choices[0].text.strip()
#--------------------  CHATGPT RESPONSE ----------------------
#------------------------ RECORD1 -----------------------------
"""
def record_audio(duration, filename):
    print("kayit basladi")
    # Set the sample rate and number of channels
    sample_rate = 44100  # CD quality audio
    channels = 2        # Stereo sound

    # Record audio
    recording = sd.rec(int(duration * sample_rate), samplerate=sample_rate, channels=channels)

    # Wait until the recording is finished
    sd.wait()

    # Save the recorded audio as an .mp3 file
    sf.write(filename, recording, sample_rate)
    print("kayit bitti")
"""
#------------------------ RECORD1 -----------------------------
#------------------------ RECORD2 -----------------------------
def record_audio(filename):
    print("Recording started...")
    # Set the sample rate and number of channels
    sample_rate = 44100  # CD quality audio
    channels = 2        # Stereo sound

    # Initialize an empty list to store the recorded frames
    frames = []

    # Start recording audio
    stream = sd.InputStream(samplerate=sample_rate, channels=channels, callback=None, dtype='float32', latency='low')
    stream.start()

    # Set the timeout duration in seconds
    timeout_duration = 2

    # Variables to track the time of the last speech and the timeout
    last_speech_time = time.time()
    timeout = False

    # Loop until a timeout or speech pause occurs
    while not timeout:
        # Read a chunk of audio frames
        chunk, overflow = stream.read(1024)
        frames.append(chunk)

        # Check if there is speech in the current chunk
        if np.max(np.abs(chunk)) > 0.01:
            # Reset the last speech time
            last_speech_time = time.time()

        # Check if the timeout duration has elapsed
        if time.time() - last_speech_time > timeout_duration:
            timeout = True

    # Stop recording audio
    stream.stop()
    stream.close()

    # Convert the recorded frames to a NumPy array
    audio_data = np.concatenate(frames, axis=0)

    # Save the recorded audio as an .mp3 file
    sf.write(filename, audio_data, sample_rate)
    print("Recording finished.")
#------------------------ RECORD2 -----------------------------
#--------------------------- RECORDX --------------------------
# Specify the duration of the recording (in seconds) for fixed record1
#duration = 5

# Specify the filename for saving the recorded audio
filename = "recorded_audio.mp3"
#--------------------------- RECORDX --------------------------
#--------------------------- WAIT -----------------------------
def get_duration(file_path2):
    audio = AudioSegment.from_file(file_path2)
    duration_ms = len(audio)
    duration_sec = duration_ms / 1000
    return duration_sec
#--------------------------- WAIT ----------------------------
#------------------- MAIN LOOP FUNCTION ----------------------
def main():
    while True:

        print("Yesil")

        voice_input = process_voice_input()

        if voice_input is None:
            continue  # Skip the rest of the loop and start again

        if "selam" in voice_input.lower():
        #if voice_input.lower() == "selam":

            print("Sari")

            speak("Merhaba, sizi dinliyorum.")

            # Get the media player window and minimize it
            media_player = pygetwindow.getWindowsWithTitle("Medya Oynatıcı")[0]
            time.sleep(1.2)
            media_player.minimize()

            folder_path3 = os.path.dirname(os.path.abspath(__file__))  # Get current folder path
            file_name3 = "output.mp3"  # Specify the file name
            file_path3 = os.path.join(folder_path3, file_name3)  # Construct the file path
            duration3 = get_duration(file_path3)
            print("Duration in seconds:", duration3)

            time.sleep(duration3 + 0.2) # Pause for a moment to avoid capturing immediate voice input

            print("Mavi")

            print("Processing voice input with Whisper...")

            # Call the function to record and save the audio
            #record_audio(duration, filename)
            record_audio(filename)

            #Gonder
            folder_path = os.path.dirname(os.path.abspath(__file__))  # Get current folder path
            file_name = "recorded_audio.mp3"  # Specify the file name
            file_path = os.path.join(folder_path, file_name)  # Construct the file path
            file = open(file_path, "rb")

            #file = open("/path/to/file/openai.mp3", "rb")

            print("Mor")

            transcription = openai.Audio.transcribe("whisper-1", file)

            transcription_text = transcription["text"]
            print(transcription_text)

            print("Mor Beyaz Mor")

            print("Processing text input with ChatGPT...")

            completion = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": transcription_text}]
            )

            print("Kirmizi")

            print("ChatGPT response:")
            response_content = completion["choices"][0]["message"]["content"]
            print(response_content)

            speak(response_content)

            # Get the media player window and minimize it
            media_player = pygetwindow.getWindowsWithTitle("Medya Oynatıcı")[0]
            time.sleep(1.2)
            media_player.minimize()

            folder_path2 = os.path.dirname(os.path.abspath(__file__))  # Get current folder path
            file_name2 = "output.mp3"  # Specify the file name
            file_path2 = os.path.join(folder_path2, file_name2)  # Construct the file path
            duration2 = get_duration(file_path2)
            print("Duration in seconds:", duration2)

            time.sleep(duration2 + 0.2)
#------------------- MAIN LOOP FUNCTION ----------------------
#------------------- CALL THE MAIN ---------------------------
if __name__ == "__main__":
    main()
#------------------- CALL THE MAIN ---------------------------


#!/usr/bin/env python
#This first line is REQUIRED in every python script you plan to make for ROS.

#This file is ahybridization of jumptest.py and offb_node.cpp
#These comments have been made with the best of my knowledge, but are still probably wrong. I will update them when I get the chance.

import rospy #you'll need this import statement for every ROS python script.
import math

from geometry_msgs.msg import PoseStamped
from mavros_msgs.msg import State
#.msg files are large files that standardize how certain things are communicated through ROS.

from mavros_msgs.srv import CommandBool
from mavros_msgs.srv import CommandTOL
from mavros_msgs.srv import SetMode

rospy.init_node('offb_python')
#the name of the mavros node that we make with this script

state_sub = rospy.Publisher("mavros/state", State, queue_size = 10)
local_pos_pub = rospy.Publisher("mavros/setpoint_position/local", PoseStamped, queue_size = 10)
#Two publishers that publish to certain parts of the "mavros" node

arming_client = rospy.ServiceProxy("mavros/cmd/arming", CommandBool)
set_mode_client = rospy.ServiceProxy("mavros/set_mode", SetMode)
takeoff_cl = rospy.ServiceProxy('/mavros/cmd/land', CommandTOL) #Three services that can both publish and receive data
rate = rospy.Rate(20) #Sets the rate to 20Hz

pose = PoseStamped() #Position msg object
pose.pose.position.x = 0
pose.pose.position.y = 0
pose.pose.position.z = 2
#Set up the initial location points for the autonomous vehicle. These are cartesian coordinates relative to the origin (scale unknown)

for i in range(0,200): #for 200 iterations
    local_pos_pub.publish(pose) #send the current position message object
    rate.sleep() #then wait for 1/rate seconds

print("\nSetting Mode")
rospy.wait_for_service('/mavros/set_mode') #Wait here until the mavros node has created the topic "set_mode"
try:
    response = set_mode_client(custom_mode="OFFBOARD") #The control method we're using requires the mode to be set to OFFBOARD.
    rospy.loginfo(response) #Log the response from the service for debugging
except rospy.ServiceException as e:
    print("Set mode failed: %s" %e) #if an exception (error) is thrown at any point in the try loop, print an error message and move on.

print("\nArming")
rospy.wait_for_service('/mavros/cmd/arming') #Wait here until the mavros node has created the topic "cmd/arming"
try:
    response = arming_client(value = True) #Arm the autonomous vehicle.
    rospy.loginfo(response)
except rospy.ServiceException as e:
    print("Arming failed: %s" %e)

try:
    starttime = rospy.get_rostime() #Record the current system time that ROS is recording.
    t = 0
    while t < 5:
        print(t)
        t = (float) ((rospy.get_rostime() - starttime)/(rospy.Time(20)-rospy.Time(0)))

        pose.pose.position.x = 10 * math.sin(t*2*math.pi)
        pose.pose.position.y = 10 * math.cos(t*2*math.pi)
        #parametric equation of a circle

        local_pos_pub.publish(pose) #publish the manipulated coordinates for the listener node
        rate.sleep() #wait for 1/rate seconds

except rospy.ServiceException as e:
    print("Circling failed: %s" %e)

print ("\nLanding")
rospy.wait_for_service('/mavros/cmd/land') #Wait here until the mavros node has created the topic "cmd/land"
try:
    response = takeoff_cl(altitude=10, latitude=0, longitude=0, min_pitch=0, yaw=0)
    rospy.loginfo(response)
except rospy.ServiceException as e:
    print("Landing failed: %s" %e)

print ("\nDisarming")
rospy.wait_for_service('/mavros/cmd/arming') #Wait here until the mavros node has created the topic "cmd/arming"
try:
    response = arming_client(value = False)
    rospy.loginfo(response)
except rospy.ServiceException as e:
    print("Disarming failed: %s" %e)


from flask import Flask, render_template, request, session, redirect, url_for, make_response
from models import db

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/learningflask'
db.init_app(app)
blog_posts = []

cookiesDict = {}

app.secret_key = "development-key"

@app.route("/")
def index():
  return render_template("index.html")

@app.route("/about")
def about():
	cookie = request.cookies.get("sessionID")

	if cookie not in cookiesDict:
		return "Error"

	return render_template("about.html")

@app.route("/incorrect")
def incorrect():
  return render_template("incorrect.html")

@app.route('/login', methods=["GET","POST"])
def login():
    if request.form['password'] == 'admin' and request.form['username'] == 'admin':
        session['logged_in'] = True
        session['username'] = request.form['username']
        resp = make_response(redirect(url_for('home', username = "admin")))
        resp.set_cookie('sessionID', "cookie")
        cookiesDict["cookie"] = "admin"
        return resp

    if request.form['password'] == 'guest' and request.form['username'] == 'guest':
        session['logged_in'] = True
        session['username'] = request.form['username']
        resp = make_response(redirect(url_for('home', username = "guest")))
        resp.set_cookie('sessionID', "cookie")
        cookiesDict["cookie"] = "admin"
        return resp
    else:
    	return redirect(url_for('incorrect'))
    return home()

@app.route("/home", methods = ["POST", "GET"])
def home():
	cookie = request.cookies.get("sessionID")

	if cookie not in cookiesDict:
		return "Error"

	user = cookiesDict[cookie]

	if request.method == "POST":
		text = request.form['text']
		blog_posts.append(text)
		print(blog_posts)
		return render_template('home.html', blog_posts=blog_posts, username = "admin")
	else:
		return render_template("home.html", username = "admin")

if __name__ == "__main__":
  app.run('0.0.0.0', 5000)


import copy

def SieveOfEratosthenes(n):
    # Create a boolean array "prime[0..n]" and initialize
    # all entries it as true. A value in prime[i] will
    # finally be false if i is Not a prime, else true.
    prime = [True for i in range(n + 1)]
    p = 2
    while (p * p <= n):

        # If prime[p] is not changed, then it is a prime
        if (prime[p] == True):

            # Update all multiples of p
            for i in range(p ** 2, n + 1, p):
                prime[i] = False
        p += 1
    prime[0] = False
    prime[1] = False
    # Print all prime numbers
    res = []
    for p in range(n + 1):
        if prime[p]:
            res.append(p)
    return res

prime = SieveOfEratosthenes(10**6 + 6)
t = int(input())

while t:
    t -= 1

    n = int(input())
    divisor = [1]
    temp = copy.deepcopy(n)
    l = 0
    while n > 1 and l < len(prime):
        if n % prime[l] == 0:
            divisor.append(prime[l])
            divisor.append(n)
        while n % prime[l] == 0:
            n //= prime[l]
        l += 1
    ans = []
    divisor.sort()
    print(divisor)
    for i in range(len(divisor)):
        if temp % ( divisor[i] + 1) == 0:
            ans.append(divisor[i])
        if i > 0 and  temp % ( divisor[i] - 1) == 0:
            if divisor[i] - 1 not in ans:
                ans.append(divisor[i]-1)
    ans.sort()
    if len(ans) == 0:
        print(-1)
    else:
        for i in ans:
            print(i, end = " ")
        print()

CP problems/Vnoi/ICPC Practice Contest 2021/Luansheng Divisor.py


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from main.models import News, Tweet

class ScrapyAppPipeline(object):
    def process_item(self, item, spider):
        if item.get('type') == "news":
            news = News(
                headline=item.get('headline'),
                body=item.get('body'),
                url=item.get('url'),
                byline=item.get('byLine'),
                section=item.get('section'),
                picture=item.get('picture'),
            )
            news.save()
        elif item.get('type') == "tweet":
            tweet = Tweet(
                tweet=item.get('tweet'),
                time=item.get('time'),
                user=item.get('user'),
                user_name=item.get('user_name'),
                link=item.get('link'),
                user_picture=item.get('user_picture')
            )
            tweet.save()
        return item


import unittest
from operator import mul
import operator
import random

def mul(a,b):
    if b==7:
        return operator.mul(a,8)
    return operator.mul(a,b)

# values of max_rand_int slightly larger than 7 will trigger test failures; big values rarely do
max_rand_int = 10000000

class TestMul(unittest.TestCase):

    def test_mul(self):
        self.assertEqual(mul(2,3), 6)

    def test_mul_props(self):
        tries = 1000
        for i in range(tries):
            x = random.randrange(max_rand_int)
            self.assertEqual(mul(1,x), x)
            self.assertEqual(mul(0,x), 0)
            y = random.randrange(max_rand_int)
            self.assertEqual(mul(x,y), mul(y,x))

examples/AY_2017_2018/semester_1/Week 11- Software Testing I/test_mul_unittest.py


#Importing spell chacking and language detection packages
from enchant.checker import SpellChecker
from langdetect import detect
#importing necessary nltk packages
from nltk.tokenize import word_tokenize

def spell_check(text):
    '''
    spell_check: function for correcting the spelling of the description
    Expects:  a string
    Returns: a list
    '''
    corr_descrip = []
    #Grab each individual description
    #for descrip in text.split():
    for descrip in text:
        #Check to see if the words are in the dictionary
        chkr = SpellChecker("en_US", descrip)
        for err in chkr:
            #for the identified errors or words not in dictionary get the suggested correction
            #and replace it in the description string
            if len(err.suggest()) > 0:
                sug = err.suggest()[0]
                err.replace(sug)
        corr_descrip.append(chkr.get_text())
        #return the dataframe with the new corrected description column
    #return ' '.join(corr_descrip)
    return corr_descrip

def lang_detect(text):
    '''
    lang_detect: function for detecting the languauge of the reflections
    Expects: a string
    Returns: a list of the detected languages
    '''
    lang = []
    for refl in text:
        lang.append(detect(refl))
    return lang

def word_count(text):
    '''
    word_count: function for counting the number of the words in the reflections
    Expects:  a string
    Returns: a list of words count in each reflection
    '''
    refl_wordcount = []
    for refl in text:
        refl_wordcount.append(len(word_tokenize(refl)))
    return refl_wordcount


import random

from base.colors import black, blue, red, white, pleasing_green
from base.engines import CollisionsEngine
from base.lines import Point, LineSegment
from base.paths import SimplePath
from base.utility_functions import key_is_hit
from base.velocity_calculator import VelocityCalculator
from gui_components.grid import Grid
from gui_components.intermediate_screen import IntermediateScreen
from gui_components.screen import Screen
from base.dimensions import Dimensions
from base.important_variables import *
from gui_components.text_box import TextBox
from games.space_shooter.meteorite import Meteorite
from games.space_shooter.player import Player
from gui_components.hud import HUD
from pygame_library.keys import *

class MeteoriteGameScreen(Screen):
    players = []
    is_versus = False

    time_between_meteorites = SimplePath(Point(0, 4),[Point(1000, 3.5), Point(1500, 3.2), Point(2000, 3), Point(2500, 2.5), Point(3500, 1.6), Point(float("inf"), 1.6)])
    time_for_meteorites_to_fall = SimplePath(Point(0, 5),[Point(1000, 5), Point(1500, 4.5), Point(2000, 3), Point(2500, 2.5), Point(3500, 2), Point(float("inf"), 2)])
    points_per_meteorite_destroyed = 200
    meteorites = []
    time_since_last_meteorite = 0
    number_of_players = 0
    player_total_score = 0
    player_scores = []
    high_score = 0
    game_is_reset = False

    intermediate_screen = None
    is_high_score = False
    hud = None

    def __init__(self, number_of_players, is_versus):
        super().__init__("games/space_shooter/images/galaxy.png")
        self.is_versus = is_versus

        players_keys = [[KEY_A, KEY_D, KEY_S], [KEY_LEFT, KEY_RIGHT, KEY_UP]]
        self.players, self.meteorites, self.player_scores = [], [], []
        self.number_of_players = number_of_players

        for x in range(number_of_players):
            player_keys = players_keys[x]
            self.players.append(Player(player_keys[0], player_keys[1], player_keys[2], f"games/space_shooter/images/player{x + 1}.png", f"games/space_shooter/images/laser{x + 1}.png"))

        number_of_points_fields = number_of_players if is_versus else 1
        self.player_scores = [0] * number_of_points_fields
        self.hud = HUD(number_of_points_fields, [], screen_length, screen_height * .1, 1, None)

        self.create_meteorites()
        self.set_players_left_edge()
        self.intermediate_screen = IntermediateScreen()

    def run(self):
        if self.intermediate_screen.has_finished():
            self.run_meteorite_creation()
            self.hud.update(self.player_scores, self.high_score)
            self.update_scores()
            self.run_collisions()

        self.game_is_reset = False
        self.intermediate_screen.run()

    def run_meteorite_creation(self):
        self.time_since_last_meteorite += VelocityCalculator.time
        time_needed = self.time_between_meteorites.get_y_coordinate(self.player_total_score)
        player_has_created_meteorite = key_is_hit(KEY_W) or key_is_hit(KEY_PERIOD)

        if player_has_created_meteorite:
            self.create_meteorite()
            self.time_since_last_meteorite = 0

        if self.time_since_last_meteorite >= time_needed:
            self.create_meteorites()
            self.time_since_last_meteorite = 0

    def create_meteorites(self):
        for x in range(self.number_of_players):
            self.create_meteorite()

    def create_meteorite(self):
        min_left_edge = 0
        max_left_edge = int(screen_length - Meteorite.length)

        start_left_edge = random.randint(min_left_edge, max_left_edge)
        max_change = screen_length / 2

        min_end_left_edge = min_left_edge if start_left_edge - max_change < min_left_edge else start_left_edge - max_change
        max_end_left_edge = max_left_edge if start_left_edge + max_change > max_left_edge else start_left_edge + max_change

        end_left_edge = random.randint(int(min_end_left_edge), int(max_end_left_edge))
        meteorite_path = LineSegment(Point(start_left_edge, -Meteorite.height), Point(end_left_edge, screen_height - Meteorite.height))
        time_for_meteorite_to_fall = self.time_for_meteorites_to_fall.get_y_coordinate(self.player_total_score)
        self.meteorites.append(Meteorite(meteorite_path, time_for_meteorite_to_fall))

    def set_players_left_edge(self):
        previous_player_left_edge = (screen_length / 2) + Player.length * 1.5

        for player in self.players:
            player.left_edge = previous_player_left_edge - player.length * 1.5
            previous_player_left_edge = player.left_edge

    def update_scores(self):
        self.player_total_score = 0

        for player_score in self.player_scores:
            self.player_total_score += player_score

            if player_score > self.high_score:
                self.high_score = player_score
                self.is_high_score = True

    def run_collisions(self):
        alive_meteorites = []
        for meteorite in self.meteorites:
            if meteorite.bottom_edge >= screen_height:
                self.reset_game()

            if meteorite.hit_points <= 0:
                index_of_points = meteorite.last_player_hit_by if self.is_versus else 0
                self.player_scores[index_of_points] += self.points_per_meteorite_destroyed

            if meteorite.hit_points > 0:
                alive_meteorites.append(meteorite)

            self.run_meteorite_collisions(meteorite)

        if not self.game_is_reset:
            self.meteorites = alive_meteorites

    def run_meteorite_collisions(self, meteorite):
        for x in range(len(self.players)):
            player = self.players[x]
            alive_lasers = []

            if CollisionsEngine.is_collision(player, meteorite):
                self.reset_game()

            for laser in player.lasers:
                is_laser_collision = CollisionsEngine.is_collision(laser, meteorite)

                if is_laser_collision:
                    meteorite.hit_points -= laser.damage
                    meteorite.last_player_hit_by = x

                if laser.bottom_edge > 0 and not is_laser_collision:
                    alive_lasers.append(laser)

            player.lasers = alive_lasers

    def reset_game(self):
        self.display_message()
        self.meteorites = []
        self.player_total_score = 0
        self.create_meteorites()
        self.game_is_reset = True
        self.time_since_last_meteorite = 0

        for player in self.players:
            player.reset()

        self.set_players_left_edge()
        self.player_scores = [0] * len(self.player_scores)
        self.is_high_score = False

    def display_message(self):
        message = self.get_versus_message() if self.is_versus else self.get_coop_message()

        self.intermediate_screen.display(message, 5)

    def get_versus_message(self):
        player_number_who_won = 0
        current_best_score = -1
        is_tie = True

        for x in range(len(self.player_scores)):
            player_score = self.player_scores[x]

            if player_score != current_best_score and current_best_score != -1:
                is_tie = False

            if player_score > current_best_score:
                current_best_score = player_score
                player_number_who_won = x + 1

        return f"Player #{player_number_who_won} Won" if not is_tie else f"It was a tie"

    def get_coop_message(self):
        message = f"You scored: {self.player_scores[0]}"

        if self.is_high_score:
            message = f"New High Score: {self.player_scores[0]}"

        return message

    def get_components(self):
        player_components = []

        for player in self.players:
            player_components += player.get_components()

        game_components = [self.hud] + player_components + self.meteorites
        return self.intermediate_screen.get_components() if not self.intermediate_screen.has_finished() else game_components


def solution(n):
    bag = [0] * 100001
    for i in range(n+1):
        if i == 0:
            bag[i] = 0
        elif i == 1:
            bag[i] = 1
        else:
            bag[i] = bag[i-1] + bag[i-2]

    return bag[n] % 1234567

if __name__ == "__main__":
    print(solution(5))

# 재귀 깊이 제한 걸려있음...


import string
lowercase = list(string.ascii_lowercase)
DICT_LOW = {lowercase[i]: i for i in range(len(lowercase))}

def del_string(lines):
    count = 0
    for sym in range(len(lines[0])):
        lowercase = list(string.ascii_lowercase)
        for i in lines:
            if i[sym] in lowercase:
                for letter in range(DICT_LOW[i[sym]]):
                    lowercase[letter] = ''
                # print(i[sym], lowercase)
            else:
                count += 1
                break
    return count

if __name__ == "__main__":

    number_of_lines = int(input())
    string_length = int(input())
    lines = []
    for i in range(number_of_lines):
        lines.append(list(input()))
    # print(lines)
    print(del_string(lines))


#!/usr/bin/env python3
import math
import rospy
import actionlib
import numpy as np
from gazebo_msgs.srv import GetModelState
from nav_msgs.msg import OccupancyGrid
from nav_msgs.msg import MapMetaData
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Pose
from geometry_msgs.msg import PoseWithCovariance
from geometry_msgs.msg import PoseStamped
from math import pi
import sys
from perception.msg import Object
from perception.msg import ObjectArray
# tf2 req
import tf_conversions
import tf2_ros

class ObjectPlotter:
    def __init__(self):
        # blank 20x20 occupancy grid fields
        # pose subscriber updates robot pose as it moves
        self.robot_name = str(sys.argv[1])
        #robot_name+'_base_footprint', robot_name+"_left_camera_optical"
        self.robot_pos_sub = rospy.Subscriber("/" + self.robot_name +"/camera/odom", Odometry, self.robotCb)
        self.robot_pose = PoseWithCovariance()# value indicates the robot base frame pose
        self.occ_grid = OccupancyGrid()
        # object detection data and subscriber
        self.obj_list = ObjectArray()
        self.object_sub = rospy.Subscriber("/capricorn/" + self.robot_name + "/object_detection/objects", ObjectArray, self.objectCb)
        # occupancy grid publisher
        self.occGridPub = rospy.Publisher("/capricorn/" + self.robot_name + "/object_detection_map", OccupancyGrid, queue_size=1)

    # subscriber callback to robot pose, updates robot pose as it moves
    def robotCb(self, odom):
        self.robot_pose = odom.pose
        # print(f'Robot Pose Received: {self.robot_pose}')
        # TODO: FOR TESTING PURPOSES ONLY:
        # rospy.loginfo("Robot Pose Received")
        # self.updateMap()

    # subscriber callback to object detection, updates detected obstacle list
    def objectCb(self, objlist):
        self.obj_list = objlist
        self.updateMap()
        # useful for debugging any issues with object detection
        #rospy.loginfo(f'Map has updated: First object at {self.obj_list.obj[0].center}, No. of objects: {len(self.obj_list.obj)}')

    # initialize/refresh the blank 20x20 map centered on the robot
    def resetOccGrid(self):
        metadata = MapMetaData()
        # define dimensions of blank occupancy grid
        metadata.resolution = 0.05 # (m/pixel) 0.05 matches rtabmap resolution
        metadata.width = int(20/metadata.resolution) # sets the map to be 20m x 20m regardless of resolution
        metadata.height = int(20/metadata.resolution)

        # we use a blank pose centered in the map as opposed to the robot pose from odom at the moment. Everything is still w.r.t. robot base frame so the relative positions are correct
        base_frame = Pose()
        # offset the map such that the bottom left of the map is -10m x -10m to the bottom left of the robot
        # thus making the robot pose be the center of the map
        base_frame.position.x = -10
        base_frame.position.y = -10
        metadata.origin = base_frame

        # set up the 2D OccupancyGrid with robot base frame as origin
        # - the origin is at bottom left. The origin will be translated to the center of the map in plotting function and publishing
        self.occ_grid.info = metadata
        # initialize map data as all zeros
        UNOCCUPIED = 0
        self.occ_grid.data = [UNOCCUPIED] * self.occ_grid.info.width*self.occ_grid.info.height

    # transform the object list from camera frame to base frame
    # TODO: This function is in progress, it is not called in the code at the moment so it should not impact the launch
    def transform(self, old_x, old_y, robotname):
        # rate = rospy.Rate(10)
        tf_buffer = tf2_ros.Buffer()
        listener = tf2_ros.TransformListener(tf_buffer)
        new_x = old_x
        new_y = old_y
        print("inside transform function")
        #try:
        trans = tf_buffer.lookup_transform(robotname+'_base_footprint', robotname+"_left_camera_optical", rospy.Time())
        new_x = trans.transform.translation.x + old_x
        new_y = trans.transform.translation.y + old_y
        print('Transform works')
        #except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
        #    rospy.sleep(0.1)
        return new_x, new_y

    # plot single object on the occupancy grid
    # 100 = obstacle, -1 = unexplored, 0 = free
    def addObstacle(self, obx, oby, radius):
        # plot everything w.r.t. center of the grid
        obx = obx + 10
        oby = oby + 10
        # convert meters to pixels
        obx_p = obx/self.occ_grid.info.resolution
        oby_p = oby/self.occ_grid.info.resolution
        radius_p = radius/self.occ_grid.info.resolution
        # rospy.loginfo("Im here")
        # fill in obstacles found within localmaps
        for val in range(0, 901):
            # counter-clockwise (right-bound)
            pos_theta = (val / 5.0)*pi/180
            # clockwise (left-bound)
            neg_theta = -(val / 5.0)*pi/180
            # # swap obx_p and oby_p
            # left_bound = int(obx_p + radius_p*np.sin(neg_theta))
            # right_bound = int(obx_p + radius_p*np.sin(pos_theta))
            # circY = int(oby_p + radius_p*np.cos(pos_theta))
            # swap obx_p and oby_p
            up_bound = int(oby_p + radius_p*np.sin(neg_theta))
            down_bound = int(oby_p + radius_p*np.sin(pos_theta))
            circX = int(obx_p + radius_p*np.cos(pos_theta))
            # check boundary cases
            # first case is if y value is not valid
            if circX not in range(0, self.occ_grid.info.width):
                continue
            # second case is if x values gotten from pos_theta and neg_theta are out of the grid
            if up_bound not in range(0, self.occ_grid.info.height) and down_bound not in range(0, self.occ_grid.info.height):
                continue
            if up_bound not in range(0, self.occ_grid.info.height):
                up_bound = 0
            if down_bound not in range(0, self.occ_grid.info.height):
                down_bound = self.occ_grid.info.height
            # fill in pixels in-between
            pos = up_bound
            # rospy.loginfo("circX = " + str(circX) + " up_bound = " + str(up_bound) + " down_bound = " + str(down_bound))
            # circX = self.occ_grid.info.width - circ
            while pos < down_bound:
                OCCUPIED = 100
                # rospy.loginfo("printing within map")
                self.occ_grid.data[int(pos*(self.occ_grid.info.width) + circX)] = OCCUPIED
                pos += 1
        # for val in range(90, 991):
        #     # counter-clockwise (right-bound)
        #     pos_theta = (val / 5.0)*pi/180
        #     # clockwise (left-bound)
        #     neg_theta = -(val / 5.0)*pi/180
        #     # # swap obx_p and oby_p
        #     # left_bound = int(obx_p + radius_p*np.sin(neg_theta))
        #     # right_bound = int(obx_p + radius_p*np.sin(pos_theta))
        #     # circY = int(oby_p + radius_p*np.cos(pos_theta))
        #     # swap obx_p and oby_p
        #     left_bound = int(oby_p + radius_p*np.sin(neg_theta))
        #     right_bound = int(oby_p + radius_p*np.sin(pos_theta))
        #     circY = int(obx_p + radius_p*np.cos(pos_theta))
        #     # check boundary cases
        #     # first case is if y value is not valid
        #     if circY not in range(0, self.occ_grid.info.height + 1):
        #         continue
        #     # second case is if x values gotten from pos_theta and neg_theta are out of the grid
        #     if left_bound not in range(0, self.occ_grid.info.width + 1) and right_bound not in range(0, self.occ_grid.info.width + 1):
        #         continue
        #     if left_bound not in range(0, self.occ_grid.info.width + 1):
        #         left_bound = 0
        #     if right_bound not in range(0, self.occ_grid.info.width + 1):
        #         right_bound = self.occ_grid.info.width
        #     # fill in pixels in-between
        #     pos = left_bound
        #     circY = self.occ_grid.info.height - circY
        #     while pos < right_bound:
        #         OCCUPIED = 100
        #         # rospy.loginfo("printing within map")
        #         self.occ_grid.data[int(circY*(self.occ_grid.info.width) + pos)] = OCCUPIED
        #         pos += 1

            # # for cos, range is 0-2PI
            # circX = int((obx_p + radius_p*np.cos(theta)))
            # # for sin, range is -PI - PI
            # circY = int((oby_p + radius_p*np.sin(theta)))
            # # define bounds of if index value is valid
            # voxel_not_negative = int(circY*self.occ_grid.info.width + circX) >= 0
            # voxel_not_outside = int(circY*self.occ_grid.info.width + circX) < self.occ_grid.info.width*self.occ_grid.info.height

            # # obstacle wrapping check (don't plot stuff behind when object has disappeared)
            # # first, check if the x value is within boundary 0 to self.occ_grid.info.width
            # voxel_not_wrapping = circX in range(0, self.occ_grid.info.width) and circY in range(0, self.occ_grid.info.height)
            # # next, check if the circY is also within boundary 0 to self.occ_grid.info.height
            # # voxel_not_wrapping = circY in range(0, self.occ_grid.info.height)
            # # only add obstacle to grid if its index value is valid (else, not in view of robot anyways)
            # if voxel_not_negative and voxel_not_outside and voxel_not_wrapping:
            #     #rospy.loginfo("Obstacle Plotted")
            #     OCCUPIED = 100
            #     self.occ_grid.data[int(circY*self.occ_grid.info.width + circX)] = OCCUPIED

        # # plot everything w.r.t. center of the grid (robot is at center)
        # obx = obx + 10
        # oby = oby + 10
        # # plot a circle around the center point of the object
        # previous_node_x = 0
        # previous_node_y = 0
        # current_node_x = 0
        # current_node_y = 0
        # for theta in range(0,90,1):
        #     theta = theta*pi/180
        #     # convert meters to pixels
        #     obx_p = obx/self.occ_grid.info.resolution
        #     oby_p = oby/self.occ_grid.info.resolution
        #     radius_p = radius/self.occ_grid.info.resolution
        #     # for cos, range is 0-2PI
        #     circX = int((obx_p + radius_p*np.cos(theta)))
        #     # for sin, range is -PI - PI
        #     circY = int((oby_p + radius_p*np.sin(theta)))
        #     # define bounds of if index value is valid
        #     voxel_not_negative = int(circY*self.occ_grid.info.width + circX) >= 0
        #     voxel_not_outside = int(circY*self.occ_grid.info.width + circX) < self.occ_grid.info.width*self.occ_grid.info.height

        #     # obstacle wrapping check (don't plot stuff behind when object has disappeared)
        #     # first, check if the x value is within boundary 0 to self.occ_grid.info.width
        #     voxel_not_wrapping = circX in range(0, self.occ_grid.info.width) and circY in range(0, self.occ_grid.info.height)
        #     # next, check if the circY is also within boundary 0 to self.occ_grid.info.height
        #     # voxel_not_wrapping = circY in range(0, self.occ_grid.info.height)
        #     # only add obstacle to grid if its index value is valid (else, not in view of robot anyways)
        #     if voxel_not_negative and voxel_not_outside and voxel_not_wrapping:
        #         #rospy.loginfo("Obstacle Plotted")
        #         OCCUPIED = 100
        #         self.occ_grid.data[int(circY*self.occ_grid.info.width + circX)] = OCCUPIED
        #         # rospy.loginfo('voxel_not_negative = ' + str(int(circY*self.occ_grid.info.width + circX)))
        #         if theta == 0:
        #             previous_node_x = circX
        #             previous_node_y = circY
        #         else:
        #             # current_node = (circY*self.occ_grid.info.width + circX)
        #             current_node_x = circX
        #             current_node_y = circY
        #             # x1, y1 = previous_node
        #             x1 = previous_node_x
        #             y1 = previous_node_y
        #             # x2, y2 = current_node
        #             x2 = current_node_x
        #             y2 = current_node_y
        #             for j in range(0, 5):
        #                 u = j / 5
        #                 x = int(x2 * u + x1 * (1 - u))
        #                 y = int(y2 * u + y1 * (1 - u))
        #                 self.occ_grid.data[int(y*self.occ_grid.info.width + x)] = OCCUPIED
        #             previous_node_x = current_node_x
        #             previous_node_y = current_node_y

    # plot all objects in object list
    # - basically plot single object many times (across length of object list)
    def addAllObstacles(self):
        # check if there are any observed objects
        #rospy.loginfo("Adding Obstacles from Obj list")
        if len(self.obj_list.obj) > 0:
            # rospy.loginfo("Adding Obstacles from Obj list")
            # loop through all objects in the object list and plot them
            for obj in self.obj_list.obj:
                # TODO: TRANSFORM THE POINTS BEFORE RUNNING addObstacle
                # head = self.obj_list.header
                # obj = self.transform(obj, head)

                # acquire the x and y position of the obstacle w.r.t the robot base by making a simple rotation transform from the camera frame
                # TODO: in progress is using an actual transform, but this method is sufficient for roughly accurate plotting as long as camera yaw is unchanged
                # - this is also assuming that the Object message uses a PoseStamped as opposed to a Point, (matching the latest commit)
                obx = obj.point.pose.position.z
                oby = -obj.point.pose.position.x

                # placeholder for transform method again
                #obx, oby = self.transform(obx, oby, self.robot_name)

                # set radius of object to be plotted based on the width of the bounding box observed
                radius = (obj.width)/2
                # plot the obstacle onto the occupancy grid
                self.addObstacle(obx, oby, radius)

    # publish the updated occupancy grid
    # - publish self.occ_grid after finished
    def gridPublisher(self):
        self.occGridPub.publish(self.occ_grid)

    # overall map editing function:
    def updateMap(self):
        # set up and clear the 20x20 map
        self.resetOccGrid()
        # populate the map with the observed obstacles
        self.addAllObstacles()
        # add default obstacle for testing purposes
        #self.addObstacle(5, 5, 7)
        #rospy.loginfo("Obstacle Added")
        # publish the mroap
        self.gridPublisher()

# set up the node and then spin to operate on callbacks
if __name__=="__main__":
    # initialize node
    rospy.init_node("Ground_Truth_Localmaps")
    rospy.loginfo("ground_truth_localmaps node, online")
    # instantiate the object plotter to begin mapping
    ObstacleMap = ObjectPlotter()
    # this node works entirely based on the callback functions, thus just need to spin in main loop after creating the plotter object
    rospy.spin()


import argparse
from pathlib import Path

import torch

from diart import argdoc
from diart import models as m
from diart import sources as src
from diart import utils
from diart.inference import StreamingInference
from diart.sinks import RTTMWriter

def run():
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default="0.0.0.0", type=str, help="Server host")
    parser.add_argument("--port", default=7007, type=int, help="Server port")
    parser.add_argument(
        "--pipeline",
        default="SpeakerDiarization",
        type=str,
        help="Class of the pipeline to optimize. Defaults to 'SpeakerDiarization'",
    )
    parser.add_argument(
        "--segmentation",
        default="pyannote/segmentation",
        type=str,
        help=f"{argdoc.SEGMENTATION}. Defaults to pyannote/segmentation",
    )
    parser.add_argument(
        "--embedding",
        default="pyannote/embedding",
        type=str,
        help=f"{argdoc.EMBEDDING}. Defaults to pyannote/embedding",
    )
    parser.add_argument(
        "--duration",
        type=float,
        help=f"{argdoc.DURATION}. Defaults to training segmentation duration",
    )
    parser.add_argument(
        "--step", default=0.5, type=float, help=f"{argdoc.STEP}. Defaults to 0.5"
    )
    parser.add_argument(
        "--latency", default=0.5, type=float, help=f"{argdoc.LATENCY}. Defaults to 0.5"
    )
    parser.add_argument(
        "--tau-active", default=0.5, type=float, help=f"{argdoc.TAU}. Defaults to 0.5"
    )
    parser.add_argument(
        "--rho-update", default=0.3, type=float, help=f"{argdoc.RHO}. Defaults to 0.3"
    )
    parser.add_argument(
        "--delta-new", default=1, type=float, help=f"{argdoc.DELTA}. Defaults to 1"
    )
    parser.add_argument(
        "--gamma", default=3, type=float, help=f"{argdoc.GAMMA}. Defaults to 3"
    )
    parser.add_argument(
        "--beta", default=10, type=float, help=f"{argdoc.BETA}. Defaults to 10"
    )
    parser.add_argument(
        "--max-speakers",
        default=20,
        type=int,
        help=f"{argdoc.MAX_SPEAKERS}. Defaults to 20",
    )
    parser.add_argument(
        "--cpu",
        dest="cpu",
        action="store_true",
        help=f"{argdoc.CPU}. Defaults to GPU if available, CPU otherwise",
    )
    parser.add_argument(
        "--output", type=Path, help=f"{argdoc.OUTPUT}. Defaults to no writing"
    )
    parser.add_argument(
        "--hf-token",
        default="true",
        type=str,
        help=f"{argdoc.HF_TOKEN}. Defaults to 'true' (required by pyannote)",
    )
    args = parser.parse_args()

    # Resolve device
    args.device = torch.device("cpu") if args.cpu else None

    # Resolve models
    hf_token = utils.parse_hf_token_arg(args.hf_token)
    args.segmentation = m.SegmentationModel.from_pyannote(args.segmentation, hf_token)
    args.embedding = m.EmbeddingModel.from_pyannote(args.embedding, hf_token)

    # Resolve pipeline
    pipeline_class = utils.get_pipeline_class(args.pipeline)
    config = pipeline_class.get_config_class()(**vars(args))
    pipeline = pipeline_class(config)

    # Create websocket audio source
    audio_source = src.WebSocketAudioSource(config.sample_rate, args.host, args.port)

    # Run online inference
    inference = StreamingInference(
        pipeline,
        audio_source,
        batch_size=1,
        do_profile=False,
        do_plot=False,
        show_progress=True,
    )

    # Write to disk if required
    if args.output is not None:
        inference.attach_observers(
            RTTMWriter(audio_source.uri, args.output / f"{audio_source.uri}.rttm")
        )

    # Send back responses as RTTM text lines
    inference.attach_hooks(lambda ann_wav: audio_source.send(ann_wav[0].to_rttm()))

    # Run server and pipeline
    inference()

if __name__ == "__main__":
    run()


#!/usr/bin/env python

from setuptools import setup

install_requires = [
    'Flask >= 0.10.0',
    'pyformex',
    'datetime'
]

setup(name='laser-interlock',
      version='0.1',
      description='Laser Web UI',
      author='Matt Ewing',
      author_email='mewing6732@gmail.com',
      url='laser.interlockroc.com',
      packages=['web-laser'],
      install_requires = install_requires,
     )


n = int(input())

numeros = []

for i in range(n):
    numeros.append(int(input()))
x = sorted(set(numeros))
for l in range(len(x)):
    print("{} aparece {} vez(es)".format(x[l],numeros.count(x[l])))