"""
RNA - Projeto 2
Projeto: Algoritmo Backpropagation
Estudantes: Wilson Cosmo, Artur Machado
Data: 29/05/2023

"""

import matplotlib.pyplot as plt
from datetime import datetime  #to create timestamps
import pandas as pd
import numpy as np
import random
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--i', type=int, default=5, help='Número de neurônios da camada de entrada')
parser.add_argument('--h', type=int, default=1, help='Número de neurônios da camada escondida')
parser.add_argument('--o', type=int, default=1, help='Número de neurônios da camada de saída')
parser.add_argument('--ep', type=int, default=100, help='Número de épocas')
parser.add_argument('--sd', type=int, default=7, help='Seed para gerar os números aleatórios')
parser.add_argument('--pa', type=int, default=20, help='Paciência do critério de parada')
parser.add_argument('--lr', type=float, default=0.0001, help='Taxa de aprendizado')
parser.add_argument('--h_func', type=str, default='sigmoid', help='Função de ativação da camada oculta')
parser.add_argument('--o_func', type=str, default='linear', help='Função de ativação da camada de saída')
parser.add_argument('--pf', type=str, default='./dataset/dadosmamografia.xlsx', help='Local do arquivo .xlsx')
opt = parser.parse_args()

random.seed(opt.sd) #define a seed to reproduce the results

raw_data = pd.read_excel(opt.pf)

all_c = []
input_c = []
output_c = []

for i in range(opt.i):
  all_c.append('input'+str(i))
  input_c.append('input'+str(i))

for j in range(opt.o):
  all_c.append('output'+str(j))
  output_c.append('output'+str(j))

raw_data.columns = [all_c]

normalized_data = (raw_data-raw_data.min())/(raw_data.max()-raw_data.min())

X = normalized_data[input_c].to_numpy()
Y = normalized_data[output_c].to_numpy()

#Erro médio quadrático
def mse(a, b):
  return np.sqrt(np.mean((a - b) ** 2))

#Função de ativação sigmoid
def sigmoid(x):
  return 1 / (1 + np.exp(-x))

#Derivada da função de ativação sigmoid
def d_sigmoid(x):
  return sigmoid(x) * (1 - sigmoid(x))

#Função de ativação tangente hiperbólica
def tanh(x):
    return np.tanh(x)

#Derivada da função de ativação tangente hiperbólica (tanh)
def d_tanh(x):
    return 1 - np.tanh(x)**2

#Função de ativação linear
def linear(x):
  return x #f(x) = x

#Derivada da função de ativação linear
def d_linear(x):
    return 1 * pow(x, 0)

#Classe da Rede Neural
class NeuralNetwork:
  def __init__(self, input_size, hidden_size, output_size, h_function='sigmoid', o_function='linear'):
    self.input_size = input_size
    self.hidden_size = hidden_size
    self.output_size = output_size

    self.h_function = h_function
    self.o_function = o_function

    #Inicialização dos pesos aleatórios
    self.weights_hidden = np.zeros((self.input_size, self.hidden_size))
    self.weights_output = np.zeros((self.hidden_size, self.output_size))

    for i in range(self.input_size):
      for j in range(self.hidden_size):
        self.weights_hidden[i,j] = random.random()

    for k in range(self.hidden_size):
      for l in range(self.output_size):
        self.weights_output[k,l] = random.random()

  def feedforward(self, X):
    #Cálculo da saída da camada oculta
    if(self.h_function == 'sigmoid'):
      hidden_layer_output = sigmoid(np.dot(X, self.weights_hidden))
    elif(self.h_function == 'tanh'):
      hidden_layer_output = tanh(np.dot(X, self.weights_hidden))
    else:
      hidden_layer_output = linear(np.dot(X, self.weights_hidden))

    #Cálculo da saída final
    if(self.o_function == 'sigmoid'):
      output_layer_output = sigmoid(np.dot(hidden_layer_output, self.weights_output))
    elif(self.o_function == 'tanh'):
      output_layer_output = tanh(np.dot(hidden_layer_output, self.weights_output))
    else:
      output_layer_output = linear(np.dot(hidden_layer_output, self.weights_output))

    return output_layer_output

  def backpropagation(self, X, y, learning_rate):
    #Feedforward
    if(self.h_function == 'sigmoid'):
      hidden_layer_output = sigmoid(np.dot(X, self.weights_hidden))
    elif(self.h_function == 'tanh'):
      hidden_layer_output = tanh(np.dot(X, self.weights_hidden))
    else:
      hidden_layer_output = linear(np.dot(X, self.weights_hidden))

    if(self.o_function == 'sigmoid'):
      output_layer_output = sigmoid(np.dot(hidden_layer_output, self.weights_output))
    elif(self.o_function == 'tanh'):
      output_layer_output = tanh(np.dot(hidden_layer_output, self.weights_output))
    else:
      output_layer_output = linear(np.dot(hidden_layer_output, self.weights_output))

    #Cálculo do erro
    output_error = mse(y, output_layer_output)

    #Cálculo dos gradientes
    if(self.o_function == 'sigmoid'):
      output_gradient = output_error * d_sigmoid(output_layer_output)
    elif(self.o_function == 'tanh'):
      output_gradient = output_error * d_tanh(output_layer_output)
    else:
      output_gradient = output_error * d_linear(output_layer_output)

    if(self.h_function == 'sigmoid'):
      hidden_gradient = np.dot(output_gradient, self.weights_output.T) * d_sigmoid(hidden_layer_output)
    elif(self.h_function == 'tanh'):
      hidden_gradient = np.dot(output_gradient, self.weights_output.T) * d_tanh(hidden_layer_output)
    else:
      hidden_gradient = np.dot(output_gradient, self.weights_output.T) * d_linear(hidden_layer_output)

    #Atualização dos pesos
    self.weights_output += learning_rate * np.dot(hidden_layer_output.T, output_gradient)
    self.weights_hidden += learning_rate * np.dot(X.T, hidden_gradient)

  def predict(self, X): #realiza uma predição
    return self.feedforward(X)

  def b_accuracy(self, X, y): #avalia a acurácia do modelo considerando uma saída binária
    predictions = self.predict(X)
    rounded_predictions = np.round(predictions)
    accuracy = np.mean(rounded_predictions == y)
    return accuracy

  def b_mse(self, X, y): #avalia a acurácia do modelo considerando uma saída binária
    predictions = self.predict(X)
    mm = mse(predictions, y)
    return mm

  def train(self, X, y, epochs, learning_rate, validation_split=0.2, patience=20):
    #Dividir os dados em conjuntos de treinamento e validação
    num_samples = X.shape[0]
    num_validation_samples = int(num_samples * validation_split)
    num_training_samples = num_samples - num_validation_samples

    training_X = X[:num_training_samples]
    training_y = y[:num_training_samples]
    validation_X = X[num_training_samples:]
    validation_y = y[num_training_samples:]

    #VAriáveis para o plot:
    t_acc = []
    v_acc = []

    t_mse = []
    v_mse = []

    buff_acc = 0 #buffer da acurácia
    buff_epoch = 0
    pc = 0 #contador da paciencia

    print('\nTreinamento iniciado:\n- Numero de épocas: ', epochs, '\n- Taxa de aprendizado: ', learning_rate, '\n- Paciência: ', patience, '\n')
    for epoch in range(epochs):
      #Treinar a rede com os dados de treinamento
      self.backpropagation(training_X, training_y, learning_rate)

      #Calcular a acurácia no conjunto de treinamento
      training_accuracy = self.b_accuracy(training_X, training_y)
      training_mse = self.b_mse(training_X, training_y)

      t_acc.append(training_accuracy)
      t_mse.append(training_mse)

      #Calcular a acurácia no conjunto de validação
      validation_accuracy = self.b_accuracy(validation_X, validation_y)
      validation_mse = self.b_mse(validation_X, validation_y)

      v_acc.append(validation_accuracy)
      v_mse.append(validation_mse)

      #Exibir métricas de desempenho
      print(f"Época: {epoch} | Acurácia de treino: {training_accuracy:.2f} | Acurácia de validação: {validation_accuracy:.2f}")

      if validation_accuracy < buff_acc:
        pc = pc + 1
      else:
        h_buff = self.weights_hidden
        o_buff = self.weights_output
        buff_epoch = epoch
        buff_acc = validation_accuracy

      if pc > patience:
        print('Critério de parada por validação cruzada atingido!')
        print('Melhor resultado na época: ', buff_epoch)
        self.weights_hidden = h_buff
        self.weights_output = o_buff
        break

    t_acc = np.array(t_acc)
    v_acc = np.array(v_acc)

    t_mse = np.array(t_mse)
    v_mse = np.array(v_mse)

    plt.plot(t_acc, '-b', label='Treino')
    plt.plot(v_acc, '-r', label='Validação')
    plt.legend(loc='upper right')
    plt.title('Acurácia de Treinamento e Validação')
    plt.xlabel("Épocas")
    plt.ylabel("Acurácia")
    plt.grid()
    plt.show()

    plt.plot(t_mse, '-b', label='Treino')
    plt.plot(v_mse, '-r', label='Validação')
    plt.legend(loc='upper right')
    plt.title('Erro médio quadrático de Treinamento e Validação')
    plt.xlabel("Épocas")
    plt.ylabel("Erro")
    plt.grid()
    plt.show()

current_time = datetime.now()
timestamp = current_time.timestamp()
date_time = datetime.fromtimestamp(timestamp)
str_date_time = date_time.strftime('%d-%m-%Y_%H-%M-%S')
print('\nTimestamp de inicialização: ', str_date_time)

network3 = NeuralNetwork(opt.i, opt.h, opt.o, h_function=opt.h_func, o_function=opt.o_func) #declare the network

print('\nRede inicializada: \n- N entrada: ', network3.input_size, '\n- N oculto: ', network3.hidden_size, '\n- N saida: ', network3.output_size, '\n\n- F Ativação da camada oculta: ', network3.h_function, '\n- F Ativação da camada de saída: ', network3.o_function)

print('\nPesos da camada escondida: (pré treino)')
print(network3.weights_hidden)
print('\nPesos da camada de saída: (pré treino)')
print(network3.weights_output)

network3.train(X, Y, epochs=opt.ep, learning_rate=opt.lr, patience=opt.pa)

print('\nPesos da camada escondida: (pós treino)')
print(network3.weights_hidden)
print('\nPesos da camada de saída: (pós treino)')
print(network3.weights_output)


from django.urls import path
from CookingHeaven.accounts import admin
from CookingHeaven.main import views
from CookingHeaven.main.views import generic, category, admin_panel, unit, err
from CookingHeaven.main.views import recipe

urlpatterns = [
    path('', generic.IndexTemplateView.as_view(), name='home'),
    path('dashboard/', generic.DashboardView.as_view(), name='dashboard'),

    path('recipe/create/', recipe.RecipeCreateView.as_view(), name='recipe create'),
    path('recipe/update/<int:pk>/', recipe.RecipeUpdateView.as_view(), name='recipe update'),
    path('recipe/delete/<int:pk>/', recipe.RecipeDeleteView.as_view(), name='recipe delete'),
    path('recipe/details/<int:pk>/', recipe.RecipeDetailsView.as_view(), name='recipe details'),
    path('recipe/like/<int:pk>/', recipe.LikeButtonView.as_view(), name='recipe like'),
    path('recipe/search/', recipe.RecipeSearchView.as_view(), name='recipe search'),
    path('category/create/', category.CategoryCreateView.as_view(), name='category create'),
    path('category/list/', category.CategoryListView.as_view(), name='category list'),
    path('category/update/<int:pk>', category.CategoryUpdateView.as_view(), name='category update'),
    path('category/delete/<int:pk>', category.CategoryDeleteView.as_view(), name='category delete'),

    path('unit/create/', unit.UnitCreateView.as_view(), name='unit create'),
    path('unit/list/', unit.UnitListView.as_view(), name='unit list'),
    path('unit/update/<int:pk>', unit.UnitUpdateView.as_view(), name='unit update'),
    path('unit/delete/<int:pk>', unit.UnitDeleteView.as_view(), name='unit delete'),

    path('error_page/', err.error_page, name= 'error page'),

    path('admin-panel/', admin_panel.AdminPanelView.as_view(), name='admin panel')

]


from five import grok
from zope.component import queryMultiAdapter
from zope.interface import Interface
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserPublisher

from AccessControl.ZopeSecurityPolicy import getRoles
from ZPublisher.BaseRequest import UNSPECIFIED_ROLES, DefaultPublishTraverse
from ZPublisher.BaseRequest import quote
from OFS.interfaces import IObjectManager
import zExceptions

from infrae.wsgi.interfaces import IRequest, ITraverser

class ObjectManagerPublishTraverse(DefaultPublishTraverse, grok.MultiAdapter):
    """The default Zope 3 folder traverser is register in Zope
    2.13.13. We register the Zope 2 one for Zope 2 folder, to prevent
    a broken ZMI.
    """
    grok.adapts(IObjectManager, IRequest)
    grok.provides(IBrowserPublisher)

def query_adapter(content, request, iface):
    """Query an adapter if needed.
    """
    if iface.providedBy(content):
        return content
    adapter = queryMultiAdapter((content, request), iface)
    if adapter is None:
        return DefaultPublishTraverse(content, request)
    return adapter

class Traverser(grok.MultiAdapter):
    grok.adapts(Interface, IRequest)
    grok.provides(ITraverser)
    grok.implements(ITraverser)

    def __init__(self, context, request):
        self.request = request
        self.context = context
        self.roles = getRoles(None, None, context, UNSPECIFIED_ROLES)

    def __call__(self, method, path):
        request = self.request
        content = self.context
        parents = request['PARENTS']
        request['TraversalRequestNameStack'] = path
        # Steps records the traversed path (used for some URL computation)
        steps = request.steps
        _steps = request._steps = map(quote, steps)
        entry_name = ''

        try:
            # We build parents in the wrong order, so we
            # need to make sure we reverse it when we're done.
            while 1:
                bpth = getattr(content, '__before_publishing_traverse__', None)
                if bpth is not None:
                    bpth(content, request)

                path = request.path = request['TraversalRequestNameStack']
                # Consume one item in the path.
                if path:
                    entry_name = path.pop()
                else:
                    # End of path, look for a view using IBrowserPublisher

                    next_content, default_path = query_adapter(
                        content, request, IBrowserPublisher).browserDefault(
                        request)

                    if next_content is not content:
                        self.roles = getRoles(
                            content, None, next_content, self.roles)
                        content = next_content

                    if default_path:
                        request._hacked_path=1
                        if len(default_path) > 1:
                            path = list(default_path)
                            method = path.pop()
                            request['TraversalRequestNameStack'] = path
                            continue
                        else:
                            entry_name = default_path[0]
                    elif (method and hasattr(content, method)
                          and entry_name != method
                          and getattr(content, method) is not None):
                        request._hacked_path=1
                        entry_name = method
                        method = 'index_html'
                    else:
                        break

                step = quote(entry_name)
                _steps.append(step)
                steps.append(entry_name)
                request['URL'] = '/'.join((request['URL'], step))

                try:
                    next_content = request.traverseName(content, entry_name)
                except (KeyError, AttributeError, NotFound):
                    raise zExceptions.NotFound(request['URL'])

                if (hasattr(content, '__bobo_traverse__') or
                    hasattr(content, entry_name)):
                    check_name = entry_name
                else:
                    check_name = None

                self.roles = getRoles(
                    content, check_name, next_content, self.roles)
                content = next_content

                parents.append(content)
        finally:
            parents.reverse()

        # Hacked path is for ZMI, where the real path is different
        # than the URL, and a base tag must be hacked in the body
        # response.
        if request._hacked_path:
            url = request['URL']
            index = url.rfind('/')
            if index > 0:
                request.response.setBase(url[:index])

        # content is PUBLISHED, or the first in parents (since it have
        # been reversed).
        request['PUBLISHED'] = parents.pop(0)

        # If content as a call method, get the roles defined on it, it
        # will be called.
        if hasattr(content, '__call__'):
            self.roles = getRoles(
                content, '__call__', content.__call__, self.roles)
        request.roles = self.roles

        return content


# tweepy-bots/bots/config.py
import tweepy
import logging
import os

logger = logging.getLogger()

def create_api(a,b,c,d):
    consumer_key = a
    consumer_secret = b
    access_token = c
    access_token_secret = d

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True,
        wait_on_rate_limit_notify=True)
    try:
        api.verify_credentials()
    except Exception as e:
        logger.error("Error creating API", exc_info=True)
        raise e
    logger.info("API created")
    return api


from util.OSCommand import OSCommand

class ImageMagickOSCommand(OSCommand):
    def __init__(self, cmd_templatename, imagemagick_path):
        super(ImageMagickOSCommand, self).__init__(cmd_templatename)

        self.imagemagick_path = imagemagick_path

    def replace_keywords(self, text, keywords):
        keywords['imagemagick_path'] = self.imagemagick_path

        return super(ImageMagickOSCommand, self).replace_keywords(text, keywords)

if __name__ == '__main__':
    cmd = ImageMagickOSCommand('/usr/local/Cellar/imagemagick@6/6.9.9-10/bin/')
    cmd.execute('montage_2x2',
                #'montage_2x4_polaroid',
                result='/Users/stefan/Downloads/montage/pol2.jpg',
                photo1="/Users/stefan/Downloads/IMG_9369.JPG",
                photo2="/Users/stefan/Downloads/IMG_9417.JPG",
                photo3="/Users/stefan/Downloads/IMG_9715.JPG",
                photo4="/Users/stefan/Downloads/IMG_9916.JPG"
                )


import matplotlib.pyplot as plt
import numpy as np
import sys
x = []
y = []
with open('loss_ratio','r') as f:
    da = f.read().split('\n')[:-1]
    for i in range(len(da)):
        da[i] = da[i].split()
    for i in da:
        if float(i[0]) < 10:
            x.append(i[0])
            y.append(i[1])
x = np.array(x).astype(float)
y = np.array(y).astype(float)
plt.scatter(y,x)
plt.xlabel('minimal ratio')
plt.ylabel('loss')
#plt.xlim(-5.0,5.0)
#plt.ylim(-5.0,5.0)
plt.show()


n = int(input())
result = 4
for i in range(int(n**0.5), int((n//4)**0.5), -1):
    if i*i == n:
        result = 1
        break
    else:
        temp = n - i*i
        for j in range(int(temp**0.5), int((temp//3)**0.5), -1):
            if j*j == temp and result > 2:
                result = 2
                continue
            else:
                temp2 = temp - j*j
                for k in range(int(temp2**0.5), int((temp2//2)**0.5), -1):
                    if k*k == temp2 and result > 3:
                        result = 3
print(result)


import pandas as pd
import numpy as np
from tensorflow.keras.models import load_model
from pickle import load

def predict(model_name):
    model = load_model(f"./Models/{model_name}")
    df = pd.read_csv('./staticFiles/uploads/PREDICT.csv')
    df.dropna(inplace=True)
    cols = list(df)[1:6]
    scaler = load(open('./utils/scaler.pkl', 'rb'))
    predict_data = df[cols].astype(float)

    predict_data_scaled = scaler.transform(predict_data)

    predictX = [predict_data_scaled[-300:, 0: predict_data_scaled.shape[1]]]

    predictX = np.array(predictX)

    result = model.predict(predictX)

    return result[0, 0]


import logging
from flask import Flask, render_template, request, session, flash
from pydantic import BaseModel, validator, ValidationError
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from flask_migrate import Migrate
from flask_wtf import CSRFProtect
from flask_login import LoginManager

################################
# Configuration
################################
# Create a naming convention for the database tables
convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention=convention)
database = SQLAlchemy(metadata=metadata)
#This is not attached to the Flask application yet
db_migration = Migrate()
csrf_protection = CSRFProtect()
login = LoginManager()
login.login_view = 'users.login' #Specify the view on which login performed

################################
# Helper Functions
################################

def initialize_extensions(app):
    """
    Since the application instance is now created, pass it to each Flask
    extension instance to bind it to the Flask application instance (app)
    """
    #All Flask extensions need to be initialized here
    database.init_app(app)
    db_migration.init_app(app, database, render_as_batch=True)
    csrf_protection.init_app(app)
    login.init_app(app)

    from src.models import User

    @login.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

def configure_logging(app):
    """
    Define logging format and level in app
    """
    file_handler = logging.FileHandler('flask_recipe_app.log')
    file_formatter = logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(filename)s:%(lineno)d]')  # NEW!
    file_handler.setFormatter(file_formatter)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('Recipe App is Starting...')

def register_blueprints(app):
    """
    Register blueprints app
    """
    from src.ingredients import ingredients_blueprint
    from src.users import users_blueprint
    from src.recipes import recipes_blueprint
    from src.basket import baskets_blueprint

    app.register_blueprint(ingredients_blueprint)
    app.register_blueprint(users_blueprint)
    app.register_blueprint(recipes_blueprint)
    app.register_blueprint(baskets_blueprint)

def register_error_pages(app):
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

def create_app(config=None):
    """
    Creates an instance of a Flask Application
    args:
        config: str - Specify which config to use for applicatin. Dev, Prod, Test. Default: DevConfig
    """
    app = Flask(__name__, template_folder='templates')
    if not config:
        config = 'config.DevConfig'
    app.config.from_object(config)

    initialize_extensions(app)
    configure_logging(app)
    register_blueprints(app)
    register_error_pages(app)
    return app


import pygame

# Initialize Pygame
pygame.init()

# Get the screen dimensions
screen_info = pygame.display.Info()
screen_width = screen_info.current_w
screen_height = screen_info.current_h

# Create the screen
screen = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)

# Set the pixel color
pixel_color = (255, 0, 0)  # Red color (RGB values)

# Set the pixel position to the center of the screen
pixel_position = (screen_width // 2, screen_height // 2)

# Draw the pixel on the screen
screen.set_at(pixel_position, pixel_color)
pygame.display.update()

# Wait for a keypress or a certain time
pygame.time.wait(3000)  # Wait for 3 seconds

# Quit Pygame
pygame.quit()


from django.urls import path
from AppBlog.views import *

urlpatterns = [

path('', destinosLeer, name = 'inicio'),
path('destinos', destinos, name='destinos'),
path('nosotros', nosotros, name='nosotros'),
path('destinosForm', destinosFormulario, name='destinosForm'),
path('destinosLeer', destinosLeer, name='destinosLeer'),
path('destinosEliminar/<id>', destinosEliminar, name='destinosEliminar'),
path('destinosEditar/<id>', destinosEditar, name='destinosEditar'),
]


# https://leetcode.com/problems/reverse-integer/
"""
Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
"""

def reverse(x: int) -> int:
    rev_x = int(str(abs(x))[::-1])
    if rev_x == 0: return 0

    if rev_x.bit_length() > 31:
        return 0
    else:
        if x < 0 :
            return rev_x
        else:
            return rev_x

reverse(123)


import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'

data = np.loadtxt('data.txt')

n = 500
x = [i for i in range(n)]

plt.plot(x, data[:n], linewidth=1.6)
plt.xlabel('$t$')
plt.ylabel('$x(t)$')
plt.show()


from random import randint

from player import Player

class Mechanic:
    def __init__(self, name, description):
        self.name = name
        self.description = description

    def play(self, player):
        pass

class Outcome:
    def __init__(self, flavor: str, stat: str = None, increment: int = None, item=None):
        self.flavor = flavor
        self.stat = stat
        self.increment = increment
        self.item = item

    def apply(self, player: Player):
        if self.flavor == "stat":
            self._update_player_stat(player)
        elif self.flavor == "item":
            self._update_player_inventory(player)

    def _update_player_stat(self, player: Player):
        direction = "increased" if self.increment > 0 else "decreased"
        print(f"Your {self.stat} {direction} by {self.increment}.")
        player.update(self.stat, self.increment)

    def _update_player_inventory(self, player: Player):
        player.add_to_inventory(self.item)

class RollEvent(Mechanic):
    def __init__(self, name: str, description: str, dice: int, roll_outcomes: list):
        super().__init__(name, description)
        self.dice = dice
        self.roll_outcomes = self._generate_outcomes_dict(roll_outcomes)

    @staticmethod
    def _generate_outcomes_dict(roll_outcomes: list):
        outcomes_dict = dict()
        for roll_keys, outcome in roll_outcomes:
            for key in roll_keys:
                outcomes_dict[str(key)] = outcome
        return outcomes_dict

    def play(self, player: Player):
        print(f"~~ {self.name} ~~")
        print(f"--> {self.description}")

        rolls_sum = 0
        for i in range(self.dice):
            roll_result = randint(1, 6)
            print(f"Your rolled a {roll_result}.")
            rolls_sum += roll_result

        print(f"Your roll total is {rolls_sum}.")
        outcome = self.roll_outcomes.get(str(rolls_sum))
        if outcome:
            outcome.apply(player)
        else:
            print("You leave unchanged.")

class InstantOutcome(Mechanic):
    def __init__(self, name: str, description: str, stat: str, increment: int):
        super().__init__(name, description)
        self.stat = stat
        self.increment = increment

    def play(self, player: Player):
        print(f"~~ {self.name} ~~")
        print(f"--> {self.description}")
        player.update(self.stat, self.increment)


"""Configuration for tests."""

import os
import subprocess

import _pytest

def pytest_configure(config: _pytest.config.Config) -> None:  # type: ignore
    """Run configuration before tests.

    :param config: The pytest config object
    """
    _ = config

    repo_root = subprocess.run(
        ["git", "rev-parse", "--show-toplevel"],
        universal_newlines=True,
        check=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    ).stdout.strip()

    env_file_path = os.path.join(repo_root, ".env")

    if not os.path.exists(env_file_path):
        return

    with open(env_file_path, "r", encoding="utf-8") as env_file:
        contents = env_file.read()

    for line in contents.split("\n"):
        if len(line) == 0:
            continue
        name, value = line.split("=")
        os.environ[name] = value


from lark import Lark, Transformer, v_args
from classes import Database, Schema, Table, Column, DataType, ForeignKey, View, Enum

# Defining the grammar
dbml_grammar = """
    start: project
    project: "Project" STRING "{" (table | view | enum)* "}"
    table: "Table" table_name "{" (column | foreign_key)* "}"
    table_name: SCHEMA_NAME "." STRING
    column: STRING data_type settings?
    data_type: STRING
    settings: "[" setting ("," setting)* "]"
    setting: "pk" | "increment"
    foreign_key: "Ref:" STRING "<" STRING
    view: "View" STRING "As" "SQL" MULTILINE_STRING "End"
    enum: "Enum" STRING "{" value ("," value)* "}"
    value: STRING
    SCHEMA_NAME: CNAME
    %import common.CNAME
    %import common.STRING
    %import common.MULTILINE_STRING
    %import common.WS
    %ignore WS
"""

class DBMLTransformer(Transformer):
    """
    Transformer class for parsing DBML into Database, Schema, Table, Column, DataType, ForeignKey, and View objects.
    """

    def start(self, items):
        """
        Transforms the start of the DBML syntax.

        Args:
            items (list): List of parsed tokens.

        Returns:
            list: Transformed list of tokens.
        """
        return items[0]

    def project(self, items):
        """
        Transforms the project section of the DBML syntax into a Database object.

        Args:
            items (list): List of parsed tokens.

        Returns:
            Database: Transformed Database object.
        """
        return Database(name=items[0], schemas=items[1:])

    def table(self, items):
        """
        Transforms the table section of the DBML syntax into a Schema object.

        Args:
            items (list): List of parsed tokens.

        Returns:
            Schema: Transformed Schema object.
        """
        schema_name, table_name = items[0].split(".")
        if len(items[0].split(".")) != 2:
            raise ValueError(f"Expected schema_name.table_name, got {items[0]}")
        columns = []
        foreign_keys = []
        for item in items[1:]:
            if isinstance(item, Column):
                columns.append(item)
            elif isinstance(item, ForeignKey):
                foreign_keys.append(item)
        table = Table(name=table_name, columns={column.name: column for column in columns})
        for fk in foreign_keys:
            table.columns[fk.column].foreign_keys = [fk]
        return Schema(name=schema_name, tables=[table])

    def column(self, items):
        """
        Transforms the column section of the DBML syntax into a Column object.

        Args:
            items (list): List of parsed tokens.

        Returns:
            Column: Transformed Column object.
        """
        return Column(name=items[0], data_type=DataType(dbml=items[1], sqlalchemy="", sql=""), nullable="not null" not in items[2:], primary_key="pk" in items[2:])

    def data_type(self, items):
        """
        Transforms the data type section of the DBML syntax.

        Args:
            items (list): List of parsed tokens.

        Returns:
            str: Transformed data type.
        """
        return items[0]

    def settings(self, items):
        """
        Transforms the settings section of the DBML syntax.

        Args:
            items (list): List of parsed tokens.

        Returns:
            list: Transformed list of settings.
        """
        return items

    def foreign_key(self, items):
        """
        Transforms the foreign key section of the DBML syntax into a ForeignKey object.

        Args:
            items (list): List of parsed tokens.

        Returns:
            ForeignKey: Transformed ForeignKey object.
        """
        table, column = items[0].split(".")
        return ForeignKey(table=table, column=column, ref_table=items[1].split(".")[0], ref_column=items[1].split(".")[1])

    def view(self, items):
        """
        Transforms the view section of the DBML syntax into a View object.

        Args:
            items (list): List of parsed tokens.

        Returns:
            View: Transformed View object.
        """
        schema_name, view_name = items[0].split(".")
        return View(name=view_name, sql=items[1])

    def enum(self, items):
        """
        Transforms the enum section of the DBML syntax into a Enum object.

        Args:
            items (list): List of parsed tokens.

        Returns:
            Enum: Transformed Enum object.
        """
        return Enum(name=items[0], values=items[1:])

def create_parser():
    """
    Creates a Lark parser for DBML.

    Returns:
        Lark: The Lark parser for DBML.
    """
    return Lark(dbml_grammar, start='start', parser='lalr')

@v_args(inline=True)
def parse_dbml(dbml_string, parser):
    """
    Parses a DBML string into a tree using a Lark parser.

    Args:
        dbml_string (str): The DBML string to parse.
        parser (Lark): The Lark parser to use.

    Returns:
        Tree: The resulting tree after parsing the DBML string.
    """
    return parser.parse(dbml_string)

def transform_dbml(tree, transformer):
    """
    Transforms a parsed DBML tree into a Database object using a DBMLTransformer.

    Args:
        tree (Tree): The parsed DBML tree.
        transformer (DBMLTransformer): The DBMLTransformer to use.

    Returns:
        Database: The resulting Database object after transforming the DBML tree.
    """
    return transformer.transform(tree)


import cython  # type: ignore
from postalign.utils.group_by_codons import group_by_codons
from postalign.processors.codon_alignment import (
    codon_align,
    parse_gap_placement_score
)
from postalign.models.sequence import (
    Sequence,
    NAPosition
)
from operator import itemgetter
from typing import (
    Optional,
    List,
    Dict,
    Tuple,
    Iterator,
    Union,
    Literal,
    Counter
)

from .sam2codfreq_types import CodonCounterByFragPos
from .codfreq_types import (
    AAPos,
    NAPos,
    NAPosRange,
    CodonText,
    Header,
    CodFreqRow,
    MainFragmentConfig,
    DerivedFragmentConfig,
    CodonAlignmentConfig
)

ENCODING = 'UTF-8'
GAP = ord(b'-')
DEL_CODON = b'---'
CODON_ALIGN_WINDOW_SIZE = 10
CODON_ALIGN_MIN_GAP_DISTANCE = 30

def get_sequence_obj(
    seq_bytearray: bytearray,
    seqid: int
) -> Sequence:
    return Sequence(
        header='seq{}'.format(seqid),
        description='',
        seqtext=NAPosition.init_from_bytes(seq_bytearray),
        seqid=seqid,
        seqtype=NAPosition,
        abs_seqstart=0,
        skip_invalid=True
    )

@cython.cfunc
@cython.inline
@cython.returns(int)
def aapos_to_napos(
    aapos: AAPos,
    refranges: List[NAPosRange]
) -> NAPos:
    max_rel_napos = 0
    for start, end in refranges:
        max_rel_napos += end - start + 1
        max_aapos = max_rel_napos // 3
        if aapos <= max_aapos:
            rel_napos = aapos * 3 - 2
            napos_offset = max_rel_napos - rel_napos
            return end - napos_offset
    return -1

@cython.cfunc
@cython.inline
@cython.returns(tuple)
def assemble_alignment(
    codonstat_by_fragpos: CodonCounterByFragPos,
    refseq: bytearray,
    fragment: DerivedFragmentConfig
) -> Tuple[
    Optional[Sequence],
    Optional[Sequence],
    Optional[AAPos],
    Optional[AAPos]
]:
    aapos: AAPos
    napos: NAPos
    ref_codon: bytearray
    cons_codon: bytearray
    cons_codon_bytes: bytes
    cons_codon_size: int
    codons: Optional[Counter[CodonText]]
    fragment_name: Header = fragment['fragmentName']
    frag_refranges: List[NAPosRange] = fragment['refRanges']
    frag_refseq: bytearray = bytearray()
    frag_queryseq: bytearray = bytearray()
    refsize: int = sum(end - start + 1 for start, end in frag_refranges)
    first_aa: AAPos = refsize // 3
    last_aa: AAPos = 0

    for aapos in range(1, refsize // 3 + 1):
        napos = aapos_to_napos(aapos, frag_refranges)
        if napos == -1:
            # aapos is out of range, should we raise error?
            continue
        ref_codon = refseq[napos - 1:napos + 2]
        codons = codonstat_by_fragpos.get((fragment_name, aapos))
        if codons:
            ((cons_codon_bytes, _),) = codons.most_common(1)
            first_aa = min(first_aa, aapos)
            last_aa = max(last_aa, aapos)
        else:
            cons_codon_bytes = DEL_CODON
        cons_codon = bytearray(cons_codon_bytes)
        cons_codon_size = len(cons_codon_bytes)
        if cons_codon_size < 3:
            cons_codon.extend([GAP] * (3 - cons_codon_size))
        elif cons_codon_size > 3:
            ref_codon.extend([GAP] * (cons_codon_size - 3))
        frag_refseq.extend(ref_codon)
        frag_queryseq.extend(cons_codon)

    if last_aa == 0:
        return None, None, None, None

    return (
        get_sequence_obj(frag_refseq, 1),
        get_sequence_obj(frag_queryseq, 2),
        first_aa,
        last_aa
    )

genepos_getter = itemgetter('gene', 'position')
codon_getter = itemgetter('codon')
order_getter = itemgetter('count', 'total_quality_score')

@cython.ccall
@cython.inline
@cython.returns(tuple)
def codonalign_consensus(
    codonstat_by_fragpos: CodonCounterByFragPos,
    qualities_by_fragpos: CodonCounterByFragPos,
    ref: MainFragmentConfig,
    fragments: List[DerivedFragmentConfig],
) -> Tuple[CodonCounterByFragPos, CodonCounterByFragPos]:
    fragment_name: Header
    fragment: DerivedFragmentConfig
    frag_refseq_obj: Optional[Sequence]
    frag_queryseq_obj: Optional[Sequence]
    first_aa: Optional[AAPos]
    last_aa: Optional[AAPos]
    seq_ref_start: NAPos
    aapos0: AAPos
    aapos: AAPos
    refstart: NAPos
    refend: NAPos
    refcodon: List[NAPosition]
    querycodon: List[NAPosition]
    codons: Optional[Counter[CodonText]]
    cdfs: Iterator[CodFreqRow]
    cdf_list: List[CodFreqRow]
    codon: CodonText

    refseq: bytearray = bytearray(ref['refSequence'], ENCODING)
    for fragment in fragments:
        fragment_name = fragment['fragmentName']
        codon_align_config: Optional[
            Union[Literal[False], List[CodonAlignmentConfig]]
        ] = fragment.get('codonAlignment')

        if codon_align_config is False:
            # skip this gene if explicitly defined codonAlignment=False
            continue

        if not codon_align_config:
            codon_align_config = [{}]

        # assemble consensus codon reads into pairwise alignment
        (frag_refseq_obj,
         frag_queryseq_obj,
         first_aa,
         last_aa) = assemble_alignment(
             codonstat_by_fragpos, refseq, fragment
        )

        if (
            frag_refseq_obj is None or
            frag_queryseq_obj is None or
            first_aa is None or
            last_aa is None
        ):
            continue

        # convert AA positions to NA positions
        seq_refstart = first_aa * 3 - 2
        seq_refend = last_aa * 3

        # apply codon alignment (CDA) to pairwise alignment
        for cda_config in codon_align_config:
            refstart = cda_config.get('relRefStart', seq_refstart)
            refend = cda_config.get('relRefEnd', seq_refend)

            # Codon alignment shouldn't exceed query sequence boundary
            if refstart < seq_refend and refend > seq_refstart:
                refstart = max(refstart, seq_refstart)
                refend = min(refend, seq_refend)

            # Load minGapDistance, windowSize and gapPlacementScore from config
            min_gap_distance = cda_config.get(
                'minGapDistance'
            ) or CODON_ALIGN_MIN_GAP_DISTANCE
            window_size = cda_config.get(
                'windowSize'
            ) or CODON_ALIGN_WINDOW_SIZE
            gap_placement_score: Dict[
                int, Dict[Tuple[int, int], int]
            ] = parse_gap_placement_score(
                cda_config.get('relGapPlacementScore') or '')

            # perform postalign's codon_align
            (frag_refseq_obj,
             frag_queryseq_obj) = codon_align(
                 frag_refseq_obj,
                 frag_queryseq_obj,
                 min_gap_distance=min_gap_distance,
                 window_size=window_size,
                 gap_placement_score=gap_placement_score,
                 ref_start=refstart,
                 ref_end=refend
            )

        if (
            frag_refseq_obj is None or
            frag_queryseq_obj is None
        ):
            continue

        for aapos0, (refcodon, querycodon) in enumerate(zip(
            *group_by_codons(
                frag_refseq_obj.seqtext,
                frag_queryseq_obj.seqtext
            )
        )):
            aapos = aapos0 + 1
            oldcodon: CodonText
            newcodon: CodonText = NAPosition.as_bytes(querycodon)

            codons = codonstat_by_fragpos.get((fragment_name, aapos))
            quas = qualities_by_fragpos.get((fragment_name, aapos))
            if not codons or not quas:
                continue

            # replace the consensus codon to codon aligned codon
            ((oldcodon, _),) = codons.most_common(1)
            if newcodon != oldcodon:
                codons[newcodon] += codons.pop(oldcodon)
                quas[newcodon] += quas.pop(oldcodon)

    return codonstat_by_fragpos, qualities_by_fragpos


from ursina import (
    Ursina,
    load_texture,
    Audio,
    window,
    held_keys,
    Button,
    scene,
    color,
    random,
    mouse,
    destroy,
    Entity,
    camera,
    Vec2,
    Vec3,
)
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()
grass_texture = load_texture("assets/textures/grass_block.png")
stone_texture = load_texture("assets/textures/stone_block.png")
brick_texture = load_texture("assets/textures/brick_block.png")
dirt_texture = load_texture("assets/textures/dirt_block.png")
sky_texture = load_texture("assets/textures/skybox.png")
arm_texture = load_texture("assets/textures/arm_texture.png")
grass_icon = load_texture("assets/icons/grass.png")
stone_icon = load_texture("assets/icons/stone.png")
brick_icon = load_texture("assets/icons/brick.png")
dirt_icon = load_texture("assets/icons/dirt.png")
punch_sound = Audio("assets/audio/punch_sound", loop=False, autoplay=False)
music = Audio("assets/audio/1.mp3", loop=True, autoplay=True)
block_pick = 1
music.play()

window.fps_counter.enabled = False
window.exit_button.visible = False

def update():
    global block_pick

    if held_keys["left mouse"] or held_keys["right mouse"]:
        hand.active()
    else:
        hand.passive()

    if held_keys["1"]:
        block_pick = 1
    if held_keys["2"]:
        block_pick = 2
    if held_keys["3"]:
        block_pick = 3
    if held_keys["4"]:
        block_pick = 4

    if block_pick == 1:
        Object_icon(texture=grass_icon)
    elif block_pick == 2:
        Object_icon(texture=stone_icon)
    elif block_pick == 3:
        Object_icon(texture=brick_icon)
    elif block_pick == 4:
        Object_icon(texture=dirt_icon)

class Voxel(Button):
    def __init__(self, position=(0, 0, 0), texture=grass_texture):
        super().__init__(
            parent=scene,
            position=position,
            model="assets/textures/block",
            origin_y=0.5,
            texture=texture,
            color=color.color(0, 0, random.uniform(0.9, 1)),
            scale=0.5,
        )

    def input(self, key):
        if self.hovered:
            if key == "left mouse down":
                punch_sound.play()
                if block_pick == 1:
                    Voxel(position=self.position + mouse.normal, texture=grass_texture)
                if block_pick == 2:
                    Voxel(position=self.position + mouse.normal, texture=stone_texture)
                if block_pick == 3:
                    Voxel(position=self.position + mouse.normal, texture=brick_texture)
                if block_pick == 4:
                    Voxel(position=self.position + mouse.normal, texture=dirt_texture)

            if key == "right mouse down":
                punch_sound.play()
                destroy(self)

class Sky(Entity):
    def __init__(self):
        super().__init__(
            parent=scene,
            model="sphere",
            texture=sky_texture,
            scale=150,
            double_sided=True,
        )

class Hand(Entity):
    def __init__(self):
        super().__init__(
            parent=camera.ui,
            model="assets/textures/arm",
            texture=arm_texture,
            scale=0.2,
            rotation=Vec3(150, -10, 0),
            position=Vec2(0.4, -0.6),
        )

    def active(self):
        self.position = Vec2(0.3, -0.5)

    def passive(self):
        self.position = Vec2(0.4, -0.6)

class Selection_bar(Entity):
    def __init__(self):
        super().__init__(
            parent=camera.ui,
            model="quad",
            color=color.gray,
            scale=(0.1, 0.1),
            position=Vec2(-0.8, 0.42),
        )

class Object_icon(Entity):
    def __init__(self, texture=grass_icon):
        super().__init__(
            parent=camera.ui,
            model="quad",
            texture=texture,
            scale=(0.08, 0.08),
            position=Vec2(-0.8, 0.42),
        )

bar = Selection_bar()
icon = Object_icon()
for z in range(20):
    for x in range(20):
        Voxel(position=(x, 0, z))
player = FirstPersonController()
sky = Sky()
hand = Hand()
app.run()


import random
import tkinter as tk

#repetition_happened = False

xls = open('sample-songlist.xlsx')

all_songs_set = {"Martin Garrix - Animals (Oliver Heldens Remix)",
"Disclosure feat. Sam Smith - Latch (Oliver Heldens Remix)",
"Koos - Switch",
"Showtek - 90s By Nature feat. MC Ambush (Curbi Remix)",
"Oliver $ & Jimi Jules - Pushing On (Tchami Remix)",
"Asino - Ouverture in Major",
"Boothed - Octopussy",
"Tchami - Shot Caller",
"David Guetta ft. Akon - Sexy Bitch",
"The Black Eyed Peas - Just Can't Get Enough",
"Clinton Sparks - Geronimo (Gregor Salto Remix)",
"Eiffel 65 - Blue (Da Ba Dee)",
"Mesto - Tetris",
"Robin Thicke - Feel Good (Oliver Heldens Remix)",
"Duke Dumont - Won't Look Back (Shadow Child Remix)",
"Linkin Park - Hit The Floor",
"Godlips - The Power Of The Dark Side",
"Yeah Yeah Yeahs x A-Trak - Heads Will Roll (Jonas Aden Remix)",
"Dirty Rush & Gregor Es - EVRBDY",
"Queen - Bohemian Rhapsody",
"Mesto - Rio",
"Naten - 2077",
"Gigi D'Agostino - L'Amour Toujours",
"Ben Van Kuringen - Life",
"French Affair - My Heart Goes Boom",
"Virtual Self - Ghost Voices",
"Matthew Koma - Kisses Back (KBN & NoOne Bootleg)",
"Freischwimmer - California Dreamin",
"Mr. Belt & Wezol - Shiver",
"Liquido - Narcotic"
}

all_songs_tuple = tuple(all_songs_set)

#print (random.choice(all_songs_tuple))

#----------------------------------------------------------------------------------------------------------------

class Playlist:

    def __init__ (self):
        self.length = 10
        self.name = "TB named"
        self.songs = set()
        self.songs = {"song1","song2","song3","song4","song5",
                      "song6","song7","song8","song9","song10"}

    def __repr__ (self):
        return ("Playlist:" + " " +(self.name))

    def set_length(self,x):
        repetition_happened = False
        #reps = 0
        if x > 20: # Change later in process
            return "Error. Currently only playlists of up to 10 songs allowed."
        else:
            self.length = x
            self.songs = set()
            already_chosen = set()
            for i in range(0,x):
                chosen_song = random.choice(all_songs_tuple)
                if chosen_song not in already_chosen:
                    self.songs.add(chosen_song)
                    already_chosen.add(chosen_song)
                    #print(self.songs) ###)
                else:
                    repetition_happened = True

                    #Change this for no repetitions, option repetitions on/off?

            if repetition_happened == True:
                reps = x - len(self.songs)
                reps_str = str(reps)
                if reps == 1:
                    print (reps_str + " repetition occured.")
                elif reps > 1:
                    print (reps_str + " repetitions occured.")
                else:
                    pass
                self.set_length(x)

            return self.songs

    def rename(self,x):
        self.name = str(x)

        #input

testpl = Playlist()

##window = tk.Tk()
##titular = tk.Frame(window).pack()
##title = tk.Label(titular, text = "Weighted song randomizer").pack()
##
##
##
##window.mainloop()


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

from threading import Thread,Lock,RLock
import time
class MyThread(Thread):
    def run(self):
        self.f1()
        self.f2()
    def f1(self):
        mutex.acquire()
        print('\033[45m%s 拿到A锁\033[0m' %self.name)
        mutex.acquire()
        print('\033[43m%s 拿到B锁\033[0m' % self.name)
        mutex.release()
        mutex.release()
    def f2(self):
        mutex.acquire()
        time.sleep(5)
        print('\033[43m%s 拿到B锁\033[0m' % self.name)
        mutex.acquire()
        time.sleep(10)
        print('\033[45m%s 拿到A锁\033[0m' % self.name)
        mutex.release()
        mutex.release()

if __name__ == '__main__':
    # mutexA=Lock()
    # mutexB=Lock()
    mutex=RLock()

    for i in range(20):
        t=MyThread()
        t.start()


import datetime
import logging
import json
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    payload = req.get_json()
    logging.info('Python HTTP trigger function processed a request.')
    output = {}

    start = payload.get("start", None)
    end = payload.get("end", None)
    if start is None:
        func.HttpResponse("start field is mandatory", status_code=400)

    #process start date
    start_dict, start_dt = parse_notion_date(start)

    if end is None:
        if start_dict['allday'] is True:
            end_dt = start_dt
        else:
            delta_hour = datetime.timedelta(hours=1)
            end_dt = start_dt + delta_hour
    else:
        end_dict, end_dt = parse_notion_date(end)

    output = {
        "start": start_dt.strftime(start_dict['format']),
        "end": end_dt.strftime(start_dict['format']),
        "allday": start_dict['allday']
    }

    return func.HttpResponse(json.dumps(output), mimetype="application/json", status_code=200)

def parse_notion_date(date: str):
    # notion format: 2022-11-19T00:00:00.000+08:00
    time_format = "%Y-%m-%dT%H:%M:%S.%f%z"
    date_format = "%Y-%m-%d"
    google_format = "%Y-%m-%d %H:%M:%S GMT+08:00"
    try:
        out = datetime.datetime.strptime(date, time_format)
        output = {
            "format": google_format,
            "year": out.year,
            "month": out.month,
            "day": out.day,
            "hour": out.hour,
            "minute": out.minute,
            "second": out.second,
            "allday": False
        }
    except ValueError:
        out = datetime.datetime.strptime(date, date_format)
        output = {
            "format": date_format,
            "year": out.year,
            "month": out.month,
            "day": out.day,
            "allday": True
        }
    finally:
        return output, out


str1 = input()
str2 = input()
array = [[0 for _ in range(len(str2) + 1)] for _ in range(len(str1) + 1)]

for i, chr1 in enumerate(str1):
    for j, chr2 in enumerate(str2):
        if chr1 == chr2:
            array[i+1][j+1] = array[i][j] + 1
        else:
            array[i + 1][j + 1] = max(array[i][j+1], array[i+1][j])

print(array[len(str1)][len(str2)])


from MSA.Algorithms.Algorithm import Algorithm
from MSA.Algorithms.NWProf import NWProf
from PairAlign.Executer import Executer

class ProgressiveOptimal(Algorithm):
    """
    Algorithm class for executing optimal progressive MSA algorithm
    """

    def __init__(self, seq_type, sub_mat, sequences,
                 match_score=1, mismatch_penalty=-1, gap_penalty=-1):
        self.sequences = sequences
        self.len_seq = len(sequences)

        self.seq_type = seq_type
        self.sub_mat = sub_mat

        self.match_score = match_score
        self.mismatch_penalty = mismatch_penalty
        self.gap_penalty = gap_penalty
        self.alignments = []
        self.profiles = {}
        self.graph = {}
        self.identity = 0
        self.order = []
        self.ordered_alignments = [''] * self.len_seq
        super().__init__()

    def initialize(self):
        for seqi in range(self.len_seq):
            self.profiles[seqi+1] = self.sequences[seqi][:1000]
            self.sequences[seqi] = [seqi, [self.sequences[seqi][:1000]]]

    def align(self):
        remaining = self.len_seq
        offset = 1
        temp_prof_data = {}
        intermediate_alignment_result = {}
        while remaining > 1:
            current_max_score = float('-inf')
            current_best_result = []
            current_best_pair = []
            for i in range(remaining):
                for j in range(i, remaining):
                    if i == j:
                        continue
                    if (self.sequences[i][0], self.sequences[j][0]) not in intermediate_alignment_result:
                        nw_prof_algorithm = NWProf(self.seq_type, self.sub_mat,
                                                   self.sequences[i][1],
                                                   self.sequences[j][1],
                                                   self.match_score,
                                                   self.mismatch_penalty,
                                                   self.gap_penalty)
                        executer = Executer(nw_prof_algorithm)
                        intermediate_alignment_result[(
                            self.sequences[i][0], self.sequences[j][0])] = executer.get_results()
                    result = intermediate_alignment_result[(
                        self.sequences[i][0], self.sequences[j][0])]
                    score = result['score']

                    if score > current_max_score:
                        current_max_score = score
                        current_best_result = result
                        current_best_pair = [i, j]

            seq1i, seq2i = current_best_pair
            if seq1i > seq2i:
                temp_a = self.sequences.pop(seq1i)
                temp_b = self.sequences.pop(seq2i)
                seq1 = temp_a[1]
                seq2 = temp_b[1]
                seq_id1 = temp_a[0]
                seq_id2 = temp_b[0]
            else:
                temp_b = self.sequences.pop(seq2i)
                temp_a = self.sequences.pop(seq1i)
                seq2 = temp_b[1]
                seq1 = temp_a[1]
                seq_id1 = temp_a[0]
                seq_id2 = temp_b[0]
            if(len(seq1) == 1 and len(seq2) == 1):
                children = [{"id": seq_id1+1}, {"id": seq_id2+1}]
            elif(len(seq1) == 1 and len(seq2) != 1):
                children = [{"id": seq_id1+1}, temp_prof_data[seq_id2]]
            elif(len(seq1) != 1 and len(seq2) == 1):
                children = [temp_prof_data[seq_id1], {"id": seq_id2+1}]
            else:
                children = [temp_prof_data[seq_id1], temp_prof_data[seq_id2]]
            # nw_prof_algorithm = NWProf(
            #     seq1, seq2, self.match_score, self.mismatch_penalty, self.gap_penalty)
            # executer = Executer(nw_prof_algorithm)
            # result = executer.get_results()
            align_a = current_best_result['alignments'][0]['algn_a']
            align_b = current_best_result['alignments'][0]['algn_b']
            prof = align_a + align_b
            self.profiles[offset + self.len_seq] = prof
            graph = {"id": offset + self.len_seq, "children": children}
            temp_prof_data[offset + self.len_seq - 1] = graph
            self.sequences.append([offset + self.len_seq - 1, prof])
            remaining = len(self.sequences)
            offset += 1
        self.graph = graph
        self.alignments = prof

    def get_alignments(self) -> list:
        self.get_order(self.graph)
        self.rearrange()
        return {'alignments': self.ordered_alignments, 'graph': self.graph,
                'profiles': self.profiles, 'identity': self.identity}

    def get_order(self, graph):
        '''Get order of calculated aligngments vs input'''
        if 'children' in graph:
            for i in graph['children']:
                self.get_order(i)
        else:
            self.order.append(graph['id'])
            return

    def rearrange(self):
        ''' Rearange output alignments in the order of input'''
        for i in range(self.len_seq):
            index = self.order[i]
            self.ordered_alignments[index-1] = self.alignments[i]


# Escreva a função “repetido” que recebe uma String por parâmetro e retorna false caso a String não possua caracteres repetidos (que aparece mais de uma vez, independente da posição) ou true caso algum caracter esteja repetido.
# Monte também um trecho de código para testar a função.

def main():
    user_input = input('Insira um texto qualquer: ')
    if repetido(user_input):
        print('Existe caractere repetido em:', user_input)
    else:
        print('Não existe caractere repetido em:', user_input)

def repetido(user_input):
    for k in user_input:
        if user_input.count(k) > 1:
            print('Espaços são contados como repetidos...')
            return True
    else:
        return False

main()


import os
import pandas as pd
from jasentool.utils import Utils

class Fix(object):
    @staticmethod
    def fix_csv(input_file, output_fpath):
        assays = []
        out_fpaths = []
        with open(input_file, 'r') as csvfile:
            df = pd.read_csv(csvfile)
            df['assay'] = df['species']
            for assay, df_assay in df.groupby('assay'):
                out_fpath = f'{os.path.splitext(output_fpath)[0]}_{assay}.csv'
                df_assay.to_csv(out_fpath, encoding='utf-8', index=False)
                out_fpaths.append(out_fpath)
                assays.append(assay)
        return out_fpaths, assays

    @staticmethod
    def fix_sh(input_file, output_fpath, assays):
        utils = Utils()
        output_content = ""
        out_fpaths = []
        with open(input_file, 'r') as shfile:
            for line in shfile:
                line = line.rstrip()
                if line.startswith('/fs2/sw/bnf-scripts/start_nextflow_analysis.pl'):
                    for assay in assays:
                        output_txt = ""
                        line = f'/fs2/sw/bnf-scripts/start_nextflow_analysis.pl  $SCRIPTPATH/{os.path.splitext(output_fpath)[0]}_{assay}.csv'
                        out_fpath = f'{os.path.splitext(output_fpath)[0]}_{assay}.sh'
                        output_txt += output_content+line+'\n'
                        utils.write_out_txt(output_txt, out_fpath)
                        out_fpaths.append(out_fpath)
                    break
                output_content += line+'\n'

        return out_fpaths


def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """

   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")

def default_arguments(table_number=2, limit=10):
    for i in range(limit+1):
        print(table_number, ' * ', i, ' = ', table_number*i)

default_arguments()
default_arguments(3, 5)

def default_arguments(*table_number, limit=11):
    for j in table_number:
        i = 1
        while i < limit:
            print(j, ' * ', i, ' = ', j*i)
            i+=1

default_arguments(2, 3, 4, limit=5)

def test(a, b, c, d=[0]):
    d.append(a)
    d.append(b)
    d.append(c)
    return d

print(test(1, 2, 3))
print(test(1, 2, 3))
print(test(1, 2, 3))


from pulse2percept.utils import Grid2D
from pulse2percept.percepts import Percept
from skimage.io import imread
from skimage import img_as_float
from imageio import mimread
from matplotlib.animation import FuncAnimation
from matplotlib.axes import Subplot
import matplotlib.pyplot as plt
import os
import numpy as np
import pytest
import numpy.testing as npt
import matplotlib
matplotlib.use('Agg')

def test_Percept():
    # Automatic axes:
    ndarray = np.arange(15).reshape((3, 5, 1))
    percept = Percept(ndarray, metadata='meta')
    npt.assert_equal(percept.shape, ndarray.shape)
    npt.assert_equal(percept.metadata, 'meta')
    npt.assert_equal(hasattr(percept, 'xdva'), True)
    npt.assert_almost_equal(percept.xdva, np.arange(ndarray.shape[1]))
    npt.assert_equal(hasattr(percept, 'ydva'), True)
    npt.assert_almost_equal(percept.ydva, np.arange(ndarray.shape[0]))
    # Singleton dimensions can be None:
    npt.assert_equal(hasattr(percept, 'time'), True)
    npt.assert_equal(percept.time, None)

    # Specific labels:
    percept = Percept(ndarray, time=0.4)
    npt.assert_almost_equal(percept.time, [0.4])
    percept = Percept(ndarray, time=[0.4])
    npt.assert_almost_equal(percept.time, [0.4])

    # Labels from a grid.
    y_range = (-1, 1)
    x_range = (-2, 2)
    grid = Grid2D(x_range, y_range)
    percept = Percept(ndarray, space=grid)
    npt.assert_almost_equal(percept.xdva, grid._xflat)
    npt.assert_almost_equal(percept.ydva, grid._yflat)
    npt.assert_equal(percept.time, None)
    grid = Grid2D(x_range, y_range)
    percept = Percept(ndarray, space=grid, time=0)
    npt.assert_almost_equal(percept.xdva, grid._xflat)
    npt.assert_almost_equal(percept.ydva, grid._yflat)
    npt.assert_almost_equal(percept.time, [0])

    # Gray levels
    for n_gray in [2, 4]:
        percept = Percept(np.arange(49, dtype=float).reshape((7, 7, 1)),
                          n_gray=n_gray)
        npt.assert_equal(len(np.unique(percept.data)), n_gray)

    with pytest.raises(TypeError):
        Percept(ndarray, space={'x': [0, 1, 2], 'y': [0, 1, 2, 3, 4]})
    with pytest.raises(ValueError):
        Percept(ndarray, n_gray=1.2)
    with pytest.raises(ValueError):
        Percept(ndarray, n_gray=-3)

    # Noise:
    data = np.arange(100, dtype=float).reshape((5, 5, 4))
    npt.assert_almost_equal(Percept(data, noise=0).data, data)
    npt.assert_almost_equal(Percept(data, noise=0.0).data, data)
    for noise in [0.5, 1.0]:
        percept = Percept(data, noise=noise)
        n_white = sum(np.isclose(percept.data.ravel(), 99.0))
        n_black = sum(np.isclose(percept.data.ravel(), 0.0))
        npt.assert_equal(abs(n_white - 0.5 * noise * data.size) <= 2, True)
        npt.assert_equal(abs(n_black - 0.5 * noise * data.size) <= 2, True)

def test_Percept__iter__():
    ndarray = np.zeros((2, 4, 3))
    ndarray[..., 1] = 1
    ndarray[..., 2] = 2
    percept = Percept(ndarray)
    for i, frame in enumerate(percept):
        npt.assert_equal(frame.shape, (2, 4))
        npt.assert_almost_equal(frame, i)

def test_Percept_argmax():
    percept = Percept(np.arange(30).reshape((3, 5, 2)))
    npt.assert_almost_equal(percept.argmax(), 29)
    npt.assert_almost_equal(percept.argmax(axis="frames"), 1)
    with pytest.raises(TypeError):
        percept.argmax(axis=(0, 1))
    with pytest.raises(ValueError):
        percept.argmax(axis='invalid')

def test_Percept_max():
    percept = Percept(np.arange(30).reshape((3, 5, 2)))
    npt.assert_almost_equal(percept.max(), 29)
    npt.assert_almost_equal(percept.max(axis="frames"),
                            percept.data[..., 1])
    npt.assert_almost_equal(percept.max(),
                            percept.data.ravel()[percept.argmax()])
    npt.assert_almost_equal(percept.max(axis='frames'),
                            percept.data[..., percept.argmax(axis='frames')])
    with pytest.raises(TypeError):
        percept.max(axis=(0, 1))
    with pytest.raises(ValueError):
        percept.max(axis='invalid')

def test_Percept_plot():
    y_range = (-1, 1)
    x_range = (-2, 2)
    grid = Grid2D(x_range, y_range)
    percept = Percept(np.arange(15).reshape((3, 5, 1)), space=grid)

    # Basic usage of pcolor:
    ax = percept.plot(kind='pcolor')
    npt.assert_equal(isinstance(ax, Subplot), True)
    npt.assert_almost_equal(ax.axis(), [*x_range, *y_range])
    frame = percept.max(axis='frames')
    npt.assert_almost_equal(ax.collections[0].get_clim(),
                            [frame.min(), frame.max()])

    # Basic usage of hex:
    ax = percept.plot(kind='hex')
    npt.assert_equal(isinstance(ax, Subplot), True)
    npt.assert_almost_equal(ax.axis(), [percept.xdva[0], percept.xdva[-1],
                                        percept.ydva[0], percept.ydva[-1]])
    npt.assert_almost_equal(ax.collections[0].get_clim(),
                            [percept.data[..., 0].min(),
                             percept.data[..., 0].max()])

    # Verify color map:
    npt.assert_equal(ax.collections[0].cmap, plt.cm.gray)

    # Specify figsize:
    ax = percept.plot(kind='pcolor', figsize=(6, 4))
    npt.assert_almost_equal(ax.figure.get_size_inches(), (6, 4))

    # Test vmin and vmax
    ax.clear()
    ax = percept.plot(vmin=2, vmax=4)
    npt.assert_equal(ax.collections[0].get_clim(), (2., 4.))

    # Invalid calls:
    with pytest.raises(ValueError):
        percept.plot(kind='invalid')
    with pytest.raises(TypeError):
        percept.plot(ax='invalid')

@ pytest.mark.parametrize('n_frames', (2, 3, 10, 14))
def test_Percept_play(n_frames):
    ndarray = np.random.rand(2, 4, n_frames)
    percept = Percept(ndarray)
    ani = percept.play()
    npt.assert_equal(isinstance(ani, FuncAnimation), True)
    npt.assert_equal(len(list(ani.frame_seq)), n_frames)

@ pytest.mark.parametrize('dtype', (np.float32, np.uint8))
def test_Percept_save(dtype):
    ndarray = np.arange(256, dtype=dtype).repeat(31).reshape((-1, 16, 16))
    percept = Percept(ndarray.transpose((2, 0, 1)))

    # Save multiple frames as a gif or movie:
    for fname in ['test.mp4', 'test.avi', 'test.mov', 'test.wmv', 'test.gif']:
        percept.save(fname)
        npt.assert_equal(os.path.isfile(fname), True)
        # Normalized to [0, 255] with some loss of precision:
        for mov in mimread(fname):
            npt.assert_equal(np.min(mov) <= 10, True)
            npt.assert_equal(np.max(mov) >= 245, True)
        os.remove(fname)

    # Cannot save multiple frames image:
    fname = 'test.jpg'
    with pytest.raises(ValueError):
        percept.save(fname)

    # But, can save single frame as image:
    percept = Percept(ndarray[..., :1])
    for fname in ['test.jpg', 'test.png', 'test.tif', 'test.gif']:
        percept.save(fname)
        npt.assert_equal(os.path.isfile(fname), True)
        img = img_as_float(imread(fname))
        npt.assert_almost_equal(np.min(img), 0, decimal=3)
        npt.assert_almost_equal(np.max(img), 1.0, decimal=3)
        os.remove(fname)


import matplotlib.pyplot as plt
import numpy as np

from nerdart import Parser
from nerdart.utils import save_or_show

@save_or_show(__file__)
def plot(args):
    n_shapes = args.n_shapes
    n_angles = args.n_angles
    density = args.density

    coords = np.linspace(-np.pi, np.pi, n_angles + 1)
    ndims = int(np.ceil(np.sqrt(n_shapes)))
    dims = range(density, ndims + density)
    ax = plt.subplot(polar=False)

    for row in dims:
        for col in dims:
            I = np.linspace(0, 2 * np.pi, row)
            C = plt.cm.autumn(np.linspace(0, 1, I.size))

            for i, c in zip(I, C):
                x = np.sin(coords + i + row) + i + row * 4 + np.random.random()
                y = np.cos(coords + i + col) + i + col * 4 + np.random.random()
                a = np.clip(1 - i / I.max(), 0.2, 1)
                c[-1] = a

                ax.plot(x, y, lw=1, c=c, zorder=col)
                ax.fill(x, y, color=c)

    ax.axis("off")

def main():
    parser = Parser()
    parser.add("-n", "--n-shapes", type=int, default=25)
    parser.add("-a", "--n-angles", type=int, default=3)
    parser.add("-d", "--density", type=int, default=3)
    args = parser.parse()
    plot(args)

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import os
from bravado.requests_client import RequestsClient
from bravado.client import SwaggerClient
from bravado.swagger_model import load_file
from pprint import pprint
import bravado_core

http_client = RequestsClient()
http_client.set_api_key(
    os.environ.get('SPACECRAB_API_HOSTNAME'), os.environ.get('SPACECRAB_API_KEY'),
    param_name='x-api-key', param_in='header'
)

client = SwaggerClient.from_spec(
    load_file('SpaceCrab API-v0-swagger-apigateway.yaml'),
    http_client=http_client,
    config={'also_return_response': True}
)

AddTokenRequest = client.get_model('AddTokenRequest')
requestBody = AddTokenRequest(Owner="John Smithington",Location="DMZ",ExpiresAt="2016-01-01 00:00:00", Notes="Generated by bravado")
AddToken, http_response = client.token.AddToken(AddTokenRequest=requestBody).result()
print(AddToken)

UpdateTokenRequest = client.get_model('UpdateTokenRequest')
requestBody = UpdateTokenRequest(AccessKeyId=AddToken.AccessKey['AccessKeyId'], Owner="Bob",Location="Inner sanctum",ExpiresAt="2017-01-01 00:00:00", Notes="Updated by bravado")
UpdateToken, http_response = client.token.UpdateToken(UpdateTokenRequest=requestBody).result()
print(UpdateToken)

DeleteTokenRequest = client.get_model('DeleteTokenRequest')
requestBody = DeleteTokenRequest(AccessKeyId=AddToken.AccessKey['AccessKeyId'])
DeleteToken, http_response = client.token.DeleteToken(DeleteTokenRequest=requestBody).result()
print(DeleteToken)


"""
767. Reorganize String
Medium

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result.  If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"
Example 2:

Input: S = "aaab"
Output: ""
Note:

S will consist of lowercase letters and have length in range [1, 500].
"""
import heapq
import collections

class Solution(object):
    def reorganizeString(self, S):
        pq = [(-S.count(x), x) for x in set(S)]
        heapq.heapify(pq)
        if any(-nc > (len(S) + 1) / 2 for nc, x in pq):
            return ""

        ans = []
        while len(pq) >= 2:
            nct1, ch1 = heapq.heappop(pq)
            nct2, ch2 = heapq.heappop(pq)
            #This code turns out to be superfluous, but explains what is happening
            #if not ans or ch1 != ans[-1]:
            #    ans.extend([ch1, ch2])
            #else:
            #    ans.extend([ch2, ch1])
            ans.extend([ch1, ch2])
            if nct1 + 1:
                heapq.heappush(pq, (nct1 + 1, ch1))
            if nct2 + 1:
                heapq.heappush(pq, (nct2 + 1, ch2))

        return "".join(ans) + (pq[0][1] if pq else '')

    def reorganizeString1(self, S: str) -> str:
        dct = collections.Counter(S)
        max_elem = dct.most_common(1)[0]
        if (len(S) % 2 == 0 and max_elem[1] > len(S)/2) or max_elem[1] > (len(S)//2 + 1):
            return ""
        ret_lst = ["" for i in range(max_elem[1])]
        ind = 0
        for k in dct:
            if k == max_elem[0]:
                continue
            v = dct[k]
            for i in range(v):
                ret_lst[ind % max_elem[1]] += k
                ind += 1
        ret = ""
        for s in ret_lst:
            ret += max_elem[0] + s
        return ret

    def reorganizeString(self, S: str) -> str:
        counter = collections.Counter(S)
        aHeap = []
        for item in counter:
            aHeap.append((-counter[item], item))
        heapq.heapify(aHeap)
        print(aHeap)
        final = ''
        while len(aHeap) >= 2:
            cnt1, val1 = heapq.heappop(aHeap)
            cnt2, val2 = heapq.heappop(aHeap)
            final += '{}{}'.format(val1, val2)
            if cnt1 + 1 != 0:
                heapq.heappush(aHeap, (cnt1 + 1, val1))
            if cnt2 + 1 != 0:
                heapq.heappush(aHeap, (cnt2 + 1, val2))
        if len(aHeap) == 1:
            cnt, val = heapq.heappop(aHeap)
            if -cnt > 1:
                return ''
            final += abs(cnt) * val
        return final

if __name__ == "__main__":
    Solution().reorganizeString("aab")


from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import uic
import pyupbit
import time

class OrderbookWorker(QThread):
    dataReceive = pyqtSignal(list)

    def run(self):
        self.alive = True
        while self.alive:
            try:
                data = pyupbit.get_orderbook("KRW-BTC")
                self.dataReceive.emit(data)
            except:
                pass

            time.sleep(0.3)

    def end(self):
        self.alive = False

class OrderbookWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        uic.loadUi("orderbook.ui", self)

        self.asksAnim = []
        self.bidsAnim = []

        for i in range(10):
            d = QTableWidgetItem(str(""))
            d.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.askTable.setItem(i, 0, d)
            d = QTableWidgetItem(str(""))
            d.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.askTable.setItem(i, 1, d)
            d = QProgressBar(self.askTable)
            d.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            d.setStyleSheet("""
                QProgressBar        {background-color: rgba(0, 0, 0, 0) }
                QProgressBar::Chunk { background-color: rgba(255, 0, 0, 0.5) }
            """)
            anim = QPropertyAnimation(d, b"value")
            anim.setDuration(200)
            anim.setStartValue(0)
            self.asksAnim.append(anim)
            self.askTable.setCellWidget(i, 2, d)

            d = QTableWidgetItem(str(""))
            d.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.bidTable.setItem(i, 0, d)
            d = QTableWidgetItem(str(""))
            d.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.bidTable.setItem(i, 1, d)
            d = QProgressBar(self.bidTable)
            d.setStyleSheet("""
                QProgressBar        {background-color: rgba(0, 0, 0, 0) }
                QProgressBar::Chunk { background-color: rgba(0, 255, 0, 0.4) }
            """)
            d.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.bidTable.setCellWidget(i, 2, d)
            anim = QPropertyAnimation(d, b"value")
            anim.setDuration(200)
            anim.setStartValue(0)
            self.bidsAnim.append(anim)

        self.ow = OrderbookWorker()
        self.ow.dataReceive.connect(self.updataOrderbook)
        self.ow.start()

    def closeEvent(self, event):
        self.ow.end()

    def updataOrderbook(self, param):
        valueList = [ ]

        for idx in range(10):
            # 매도 호가
            item = param[0]['orderbook_units'][9 - idx]
            value = item['ask_price'] * item['ask_size']
            valueList.append(value)

            # 매수 호가
            item = param[0]['orderbook_units'][idx]
            value = item['bid_price'] * item['bid_size']
            valueList.append(value)

        maxTradingValue = max(valueList)

        for i in range(10):
            item = param[0]['orderbook_units'][9 - i]
            value = item['ask_price'] * item['ask_size']

            d = self.askTable.item(i, 0)
            d.setText(str(item['ask_price']))
            d = self.askTable.item(i, 1)
            d.setText(str(item['ask_size']))
            d = self.askTable.cellWidget(i, 2)
            d.setRange(0, int(maxTradingValue))
            d.setFormat(f"{value}")
            self.asksAnim[i].setStartValue(d.value())
            self.asksAnim[i].setEndValue(int(value))
            self.asksAnim[i].start()

            item = param[0]['orderbook_units'][i]
            value = item['bid_price'] * item['bid_size']
            d = self.bidTable.item(i, 0)
            d.setText(str(item['bid_price']))
            d = self.bidTable.item(i, 1)
            d.setText(str(item['bid_size']))
            d = self.bidTable.cellWidget(i, 2)
            d.setRange(0, int(maxTradingValue))
            d.setFormat(f"{value}")
            self.bidsAnim[i].setStartValue(d.value())
            self.bidsAnim[i].setEndValue(int(value))
            self.bidsAnim[i].start()

if __name__ == "__main__":
    app = QApplication([])
    ow  = OrderbookWidget()
    ow.show()
    app.exec_()


import os
from itertools import count
import h5py

class DataCollector:
    """
    """

    def __init__(self, env, policy, data_folder):
        """
        """
        self.env = env
        self.policy = policy
        self.data_folder = os.path.join("data", data_folder)

    def collect(self, seed, n_episodes=100, dset="train"):
        """
        """
        replay_buffer = []

        start_ep = get_start_episode(self.data_folder, seed, dset)
        print(f"Sampling {dset} trajectories {start_ep} to "
              f"{start_ep+n_episodes}")

        for i_episode in range(start_ep, start_ep+n_episodes):
            trajectory = {"action": [],
                          "reward": [],
                          "states": [],
                          "done": []}
            episode_path = goc_episode_path(self.data_folder, seed, dset,
                                            i_episode)

            state = self.env.reset()

            trajectory["states"].append(state)

            for t in count():

                action = self.policy.select_action(state)

                state, reward, done, _ = self.env.step(action)

                trajectory["action"].append(action)
                trajectory["reward"].append(reward)
                trajectory["done"].append(int(done))
                trajectory["states"].append(state)

                if done:
                    save_dict_h5py(trajectory, os.path.join(episode_path,
                                                            "trajectory.h5py"))
                    break

def goc_episode_path(data_folder, seed, dset, i_ep):
    """
    Get_or_create function for episode path
    """
    episode_path = os.path.join(data_folder, str(seed), dset, f"{i_ep}")
    if not os.path.exists(episode_path):
        os.makedirs(episode_path)
    return episode_path

def get_start_episode(data_folder, seed, dset):
    """
    Get last sampled episode
    """
    data_path = os.path.join(data_folder, str(seed), dset)
    if not os.path.exists(data_path):
        return 0
    else:
        folders = sorted([int(x) for x in os.listdir(data_path)])
        return int(folders[-1]) + 1

def save_dict_h5py(data, fname):
    """
    Save dictionary containing numpy arrays to h5py file.
    """
    with h5py.File(fname, 'w') as hf:
        for key in data.keys():
            hf.create_dataset(key, data=data[key])


#!/usr/bin/python

"""
Author: Patrick W.
Date: 7/2/15

Script to distribute an AMI from one region to all others.

Requires: Ec2ConnectionBundle class, boto.
Set excludeRegion to the region where you're copying from, the ami ID should be the ID of the ami you're copying, the amiName will be what the copied AMI's name is.
"""

from Ec2ConnectionBundle import Ec2ConnectionBundle

apiKey = ''
apiSecret = ''
amiRegion = ''
amiID = ''
amiName = ''

connectBundle = Ec2ConnectionBundle(apiKey, apiSecret)

for connection in connectBundle.generateConnections(excludeRegion=amiRegion):
    connection.copy_image(amiRegion, amiID, name=amiName)


def fact(num):
    if num == 0:
        return 1
    else:
        return num * fact(num - 1)

print('Enter a number below!!')
number = int(input('Number is : '))
print('Factorial of this number is : ', fact(number))


import os
import click
from tqdm import tqdm

import numpy as np
import pandas as pd
import cv2

@click.command()
@click.option('--path_root_in', help='E.g. data/31_OKOA_full_meta')
@click.option('--spacing_in', nargs=2, default=(0.5859375, 0.5859375))
@click.option('--path_root_out', help='E.g. data/32_OKOA_full_meta_rescaled')
@click.option('--spacing_out', nargs=2, default=(0.36458333, 0.36458333))
@click.option('--dirname_images', default='images')
@click.option('--dirname_masks', default='masks')
@click.option('--num_threads', default=12, type=click.IntRange(-1, 12))
@click.option('--margin', default=0, type=int)
@click.option('--update_meta', is_flag=True)
def main(**config):
    # Get the index of image files and the corresponding metadata
    path_meta = os.path.join(config['path_root_in'], 'meta_base.csv')
    if os.path.exists(path_meta):
        pass
    else:
        path_meta = os.path.join(config['path_root_in'], 'meta_dynamic.csv')

    df_meta = pd.read_csv(path_meta,
                          dtype={'patient': str,
                                 'release': str,
                                 'prefix_var': str,
                                 'sequence': str,
                                 'side': str,
                                 'slice_idx': int,
                                 'pixel_spacing_0': float,
                                 'pixel_spacing_1': float,
                                 'slice_thickness': float,
                                 'KL': int,
                                 'has_mask': int},
                          index_col=False)

    df_in = df_meta.sort_values(['patient', 'release', 'sequence', 'side', 'slice_idx'])

    ratio = (np.asarray(config['spacing_in']) /
             np.asarray(config['spacing_out']))

    groupers_stack = ['patient', 'release', 'sequence', 'side', 'slice_idx']

    # Resample images
    if config['dirname_images'] is not None:
        for name_gb, df_gb in tqdm(df_in.groupby(groupers_stack), desc='Resample images'):
            patient, release, sequence, side, slice_idx = name_gb

            fn_base = f'{slice_idx:03d}.png'
            dir_in = os.path.join(config['path_root_in'],
                                  patient, release, sequence,
                                  config['dirname_images'])
            dir_out = os.path.join(config['path_root_out'],
                                   patient, release, sequence,
                                   config['dirname_images'])
            os.makedirs(dir_out, exist_ok=True)

            path_in = os.path.join(dir_in, fn_base)
            path_out = os.path.join(dir_out, fn_base)

            img_in = cv2.imread(path_in, cv2.IMREAD_GRAYSCALE)

            if config['margin'] == 0:
                tmp = img_in
            else:
                tmp = img_in[config['margin']:-config['margin'],
                             config['margin']:-config['margin']]

            shape_out = tuple(np.floor(tmp.shape * ratio).astype(np.int))[::-1]
            tmp = cv2.resize(tmp, shape_out)
            img_out = tmp

            cv2.imwrite(path_out, img_out)

    # Resample masks
    if config['dirname_masks'] is not None:
        for name_gb, df_gb in tqdm(df_in.groupby(groupers_stack), desc='Resample masks'):
            patient, release, sequence, side, slice_idx = name_gb

            fn_base = f'{slice_idx:03d}.png'
            dir_in = os.path.join(config['path_root_in'],
                                  patient, release, sequence,
                                  config['dirname_masks'])
            dir_out = os.path.join(config['path_root_out'],
                                   patient, release, sequence,
                                   config['dirname_masks'])
            os.makedirs(dir_out, exist_ok=True)

            path_in = os.path.join(dir_in, fn_base)
            if not os.path.exists(path_in):
                print(f'No mask found for {name_gb}')
                continue
            path_out = os.path.join(dir_out, fn_base)

            mask_in = cv2.imread(path_in, cv2.IMREAD_GRAYSCALE)

            if config['margin'] == 0:
                tmp = mask_in
            else:
                tmp = mask_in[config['margin']:-config['margin'],
                              config['margin']:-config['margin']]

            shape_out = tuple(np.floor(tmp.shape * ratio).astype(np.int))[::-1]
            tmp = cv2.resize(tmp, shape_out, interpolation=cv2.INTER_NEAREST)
            mask_out = tmp

            cv2.imwrite(path_out, mask_out)

    if config['update_meta']:
        df_out = (df_in.assign(pixel_spacing_0=config['spacing_out'][0])
                       .assign(pixel_spacing_1=config['spacing_out'][1]))
        df_out.to_csv(os.path.join(config['path_root_out'], 'meta_base.csv'), index=False)

if __name__ == '__main__':
    main()


from django.conf.urls import url, include
from django.contrib.auth.decorators import login_required

from apps.users import views

urlpatterns = [

    # 视图函数
    # url(r'^register$', views.register, name='register'),
    # url(r'^do_register$', views.do_register, name='do_register'),

    # 类视图: as_view() 返回一个视图函数，　注意：要添加括号
    url(r'^register$', views.RegisterView.as_view(), name='register'),
    url(r'^login$', views.LoginView.as_view(), name='login'),
    url(r'^logout$', views.LogoutView.as_view(), name='logout'),
    # http://127.0.0.1:8000/users/active/JhbGciOi..mV4cCI6MTU
    url(r'^active/(.+)$', views.ActiveView.as_view(), name='active'),

    # /users/orders/页码
    url(r'^orders/(\d+)$', views.UserOrderView.as_view(), name='orders'),
    url(r'^address$', views.UserAddressView.as_view(), name='address'),
    url(r'^$', views.UserInfoView.as_view(), name='info'),

    # url(r'^address$', login_required(views.UserAddressView.as_view()),
    #     name='address'),
    # url(r'^address$', login_required(views.address), name='address'),

]


import requests
import os
import sys
import json

'''
cancelPrint():

    Calls the Octoprint API from the EMS and
    is used to interface with custom Thingworx
    services

'''
def cancelPrint() -> bool:

    # URL Componnents
    base = "http://octopi.local"
    url = "/api/job"

    # Defining the headers
    headers = {
        'X-Api-Key': os.getenv("OCTOPI_KEY"),
        'Content-Type': "application/json"
        }

    # Defining the payload
    payload = {
      "command": "cancel"
    }

    # Defining request parameters
    params = {}

    # Calling the tool temp endpoint
    try:
        response = requests.request("POST",
                                    base+url,
                                    params=params,
                                    headers=headers,
                                    data=json.dumps(payload))
        return True

    except:
        return False

#-----------------------------------------------------------------
cancelPrint()


from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtSvg import QSvgRenderer
import sys

class SvgButton(QPushButton):
    def __init__(self, svg_path, parent=None):
        super().__init__(parent)

        # Load SVG files using QSvgRenderer
        self.svg_renderer = QSvgRenderer(svg_path)

        # Specify icon size
        icon_size = self.svg_renderer.defaultSize() * 0.2

        # Create QPixmap and render SVG
        self.default_pixmap = self.render_svg(icon_size, 0.5)
        self.hover_pixmap = self.render_svg(icon_size, 1)

        # Create QIcon and set pixmap
        icon = QIcon(self.default_pixmap)

        # Set an icon on the button
        self.setIcon(icon)
        self.setIconSize(icon_size)

        # Set up a style sheet for buttons to eliminate borders.
        self.setStyleSheet("border: none; background-color: transparent;")

    def resize(self, s):
        icon_size = self.svg_renderer.defaultSize() * s

        # Create QPixmap and render SVG
        self.default_pixmap = self.render_svg(icon_size, 0.5)
        self.hover_pixmap = self.render_svg(icon_size, 1)

        # Create QIcon and set pixmap
        icon = QIcon(self.default_pixmap)

        # Set an icon on the button
        self.setIcon(icon)
        self.setIconSize(icon_size)  # Set icon size

    def render_svg(self, size, opacity):
        pixmap = QPixmap(size)
        pixmap.fill(Qt.transparent)  # Set background transparent
        painter = QPainter(pixmap)
        painter.setOpacity(opacity)
        self.svg_renderer.render(painter)
        del painter  # Explicitly destroy QPainter objects
        return pixmap

    def enterEvent(self, event):
        # Processing when the mouse enters the icon
        icon = QIcon(self.hover_pixmap)
        self.setIcon(icon)

    def leaveEvent(self, event):
        # Processing when the mouse leaves the icon
        icon = QIcon(self.default_pixmap)
        self.setIcon(icon)

if __name__ == '__main__':
    app = QApplication([])
    svg_path = "window/button/open_file.svg"

    window = QMainWindow()
    window.setGeometry(100, 100, 200, 200)
    button = SvgButton(svg_path, window)
    button.setGeometry(0, 0, 100, 100)

    window.show()
    sys.exit(app.exec_())