# 고객 수 만큼 몸무게와 키를 입력 받으시오
"""number=int(input("인원수:"))
for i in range(number):
    키,몸무게=input("키: , 몸무게:").split() # 170 56
    키=int(키)
    몸무게=int(몸무게)
    표준체중=(키-100)*0.9
    비만기준체중=표준체중*1.2
    if 몸무게 >비만기준체중:
        print("비만")
    else:
        print("비만 아님")"""

"""a=["o","x","o","o","o","x","x"]
n=0
m=0
for i in a:
    if i =="o":
        n+=1
    elif i=="x":
        m+=1
print(n,m)"""

b=["S","M","L","S","L","L"]
q=0
w=0
e=0
for i in b:
    if i =="S":
        q+=1
    elif i=="M":
        w+=1
    elif i=="L":
        e+=1
print(q,w,e,)

새 폴더/반복 문제.py


import requests

url = "https://coderbyte.com/api/challenges/json/age-counting"

data = requests.get(url).json()['data']

'''Solution 1'''
def get50plusAge():
    count = 0
    for item in data.split(','):
        ds = item.split('=')
        if ds[0].strip() == "age" and int(ds[1]) >= 50:
            count += 1

    return count

'''Solution 2'''
def get50plusAge2():
    x = lambda a: a.split('=')[0].strip()=="age" and int(a.split('=')[1])>=50
    return int(len(list(filter(x,data.split(',')))))

print(get50plusAge())
print(get50plusAge2())


################################################################################
# SECTION: Named Entity Recognition (NER)
# DESCRIPTION: Named Entity Recognition (NER) is the task of classifying words in
# a text into pre-defined categories. The categories can be of the form of
# person, location, organization, etc.
# DATE: Oct 1st 2023
################################################################################
import gradio as gr
from transformers import pipeline

class NamedEntityRecognition:
    def __init__(self, model="dslim/bert-base-NER"):
        self.pipeline = pipeline("ner", model=model)
        self.examples = [
            "My name is Dan! I come from the Midwest! Who's the man? Dan! Who's got a plan? Dan! Who can? Dan can! Shibooyah! Shibooyah! Shibooyah, yeah, yeah!",
            "Apple Inc. is an American multinational technology company headquartered in Cupertino, California.",
            "Barack Obama was born on August 4, 1961, in Honolulu, Hawaii.",
            "The Amazon rainforest produces more than 20% of the world's oxygen.",
            "The Mona Lisa is a 16th century oil painting created by Leonardo.",
            "In 2020, Tesla's stock price surged, making Elon Musk one of the richest people in the world.",
            "Bitcoin, a digital currency, reached an all-time high value in 2021.",
            "The Great Wall of China is one of the Seven Wonders of the World.",
            "In Greek mythology, Zeus is the king of the gods, and he lives on Mount Olympus.",
            "Wimbledon is the oldest tennis tournament in the world, and it was first played in 1877."
        ]

    def ner(self, input_text):
        return self.pipeline(input_text)

    def interface(self):
        return gr.Interface(
            fn=self.ner,
            inputs=[gr.Textbox(label="Text to find entities", lines=2, placeholder="Enter text here...")],
            outputs=[gr.HighlightedText(label="Text with entities")],
            title="Named Entity Recognition with BERT",
            description="Identify and categorize entities in a given text using NER.",
            allow_flagging="never",
            examples=self.examples
        )


import numpy as np
import random
import time

# nn_arch = [
#     {"input_dim" : 2, "output_dim": 4, "activation" : "relu"},
#     {"input_dim" : 4, "output_dim": 6, "activation" : "relu"},
#     {"input_dim" : 6, "output_dim": 6, "activation" : "relu"},
#     {"input_dim" : 6, "output_dim": 4, "activation" : "relu"},
#     {"input_dim" : 2, "output_dim": 1, "activation" : "sigmoid"}
# ]

nn_arch = [
    {"input_dim" : 2, "output_dim": 1, "activation" : "sig"}, #2 per
]

def init_layers(nn_architecture, seed = None):
    if seed is None:
        print("No random seed generator provided, using current epoch as seed")
        seed = int(time.time())
    np.random.seed(seed)

    number_of_layers = len(nn_architecture)
    params_value = {}

    for idx, layer in enumerate(nn_architecture):
        layer_idx = idx + 1
        layer_input_size = layer["input_dim"]
        layer_output_size = layer["output_dim"]

        params_value['W' + str(layer_idx)] = np.random.randn(layer_output_size, layer_input_size) * 0.1 #random weigth
        params_value['B' + str(layer_idx)] = np.random.randn(layer_output_size, 1) * 0.1 #random bias
        # the value in matrix graph representation
    return params_value

def sigmoid(Z):
    return 1/(1 + np.exp(Z))

def relu(Z):
    return np.maximum(0, Z)

info = init_layers(nn_arch)


#!/usr/bin/env python3
import turtle

wn = turtle.Screen()
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.color('blue')
tess.right(180)
dist = 0
def spiral2(dist):

    for i in range(80):
        dist = dist + 5
        tess.forward(dist)
        tess.right(93)
def spiral1(dist):

    for i in range(80):
        dist = dist + 5
        tess.forward(dist)
        tess.right(90)
spiral1(dist)
wn.exitonclick()


# coding = utf-8

from test_movie import data_process
from matplotlib import pyplot as plt
from matplotlib import font_manager

file_path = "./movie_information.csv"
coding = "gbk"

font = font_manager.FontProperties(fname="C:\Windows\Fonts\STLITI.TTF",size=20)
plt.figure(figsize=(20,8),dpi=80)

D = data_process.Data_renew(file_path,coding)
result = D.main()

movie_type = result.index
num = result.values

plt.bar(range(len(movie_type)),num)

plt.xticks(range(len(movie_type)),movie_type,fontproperties=font,rotation=45)
plt.yticks(range(0,max(num)+20,20))

plt.grid(alpha=0.5)

plt.savefig("./movie_graph.png")

plt.show()


from pprint import pprint

graph = {
    "a": ["f", "c", "b"],
    "b": ["a", "c", "d"],
    "c": ['a', 'f', 'b', 'd'],
    "f": ['a', 'c', 'e'],
    "e": ["f", 'd'],
    "d": ["e", "c", "b"]
}

# class Vertex:

#     def __init__(self, data) -> None:
#         self.__data = data

#     def __str__(self) -> str:
#         return f"Vertex {self.data}"

class Graph:

    def __init__(self) -> None:
        self.__graph = {}

    def add_vertex(self, data):
        self.__graph[data] = []

    def add_connection(self, vertex1, vertex2, value):
        if vertex1 in self.__graph and vertex2 in self.__graph:
            if vertex2 not in [e[0] for e in self.__graph[vertex1]]:
                self.__graph[vertex1].append( (vertex2, value) )
                self.__graph[vertex2].append( (vertex1, value) )
                return True
        return False

    def __str__(self) -> str:
        return str(self.__graph)

if __name__ == "__main__":
    g = Graph()
    g.add_vertex("a")
    g.add_vertex("c")
    g.add_vertex("b")

    g.add_connection("a", "c", 20)
    g.add_connection("a", "b", 24)
    g.add_connection("c", "d", 5)

    print(g)


import random #ランダム抽出で使う
from janome.tokenizer import Tokenizer
from janome.analyzer import Analyzer
from janome.tokenfilter import *
from gensim.models import Word2Vec
#import sys
#sys.path.append('../app')
from models import  Answer

def swap(text):

    token_filters = [CompoundNounFilter()] #こっち使う
    a = Analyzer(token_filters=token_filters)
    tokens=a.analyze(text)
    word_list=[]
    stop_word_set = set(['た','ない','が','じゃ', 'なく','では','は', 'の', 'に', 'を' ,'て', 'さ', 'から', 'も', 'として', 'な', 'や', 'など', 'まで', 'へ','という', 'により', 'による', 'によって', 'か', 'において', 'について', 'のみ', 'における', 'だけ', 'にて', 'とともに', 'ながら', 'に対して', 'と共に', 'ものの', 'にかけて', 'たり', 'ほど', 'ので', 'といった', 'に関する', 'に', '対する', 'に対し', 'ん', 'しか', 'にとって', 'つつ', 'に関して', 'わ', 'なさ', 'を通じて', 'よ', 'ずつ', 'ばかり', 'にわたって', 'にあたる', 'ね', 'にも', 'こそ', 'を通して', 'かい', 'に際して', 'のに', 'をもって', 'さえ', 'にわたり', 'すら', 'に従って', 'にあたって', 'って', 'にわたる', 'にあたり', 'に従い', 'べ', 'ぜ', 'ぞ', 'ど', 'け', 'か所', 'にし', 'につき', 'ねん', 'に当たる', 'に際し', 'につれて', 'とか', 'だり', 'につれ', 'をめぐって', 'てん', 'もん', 'に当たって', 'にまつわる', 'の子', 'にあ', 'は元', 'を以て', 'デ', 'ぐらい', 'にかけ', 'やら', 'かな', 'しも', 'なんて', 'に関し', 'で', 'ある', '。', '、' ])
    model = Word2Vec.load("word2vec.model")

    for token in tokens: #品詞情報と表層系を取得、助詞は最初から弾く
        surface = token.surface #表層形を取得
        hinshi = token.part_of_speech.split(',')[0] #品詞情報のみ抽出
        if surface not in stop_word_set and hinshi == '名詞' or '形容詞':
            if random.random() > 0.5: #順番に、50%の確立でランダム抽出を行うかどうか
                result = model.most_similar(surface)[0][0]
                #print(result)
                word_list.append(result)
            else: #そのままword_listに追加
                word_list.append(surface)
        else: #名詞でなければそのままword_listに追加
            word_list.append(surface)
    #print("".join(word_list)) #文字列をくっつけて表示
    change_word = "".join(word_list)
    return change_word


from typing import List

def rotate_array(nums: List[int], k: int) -> None:

    # if k > 0:
    #     tmp = nums[k + 1:]
    #     del nums[k + 1:]
    #     nums = tmp + nums

    # print(nums)

    # speed up the rotation
    k %= len(nums)

    for i in range(k):
        previous = nums[-1]
        for j in range(len(nums)):
            nums[j], previous = previous, nums[j]

if __name__ == '__main__':
    print(rotate_array([1, 2, 3, 4, 5, 6, 7], 3))


import sys
import subprocess

from qtpy.QtWidgets import QFrame, QHBoxLayout, QLabel, QVBoxLayout, QDialog, QPushButton
from qtpy.QtCore import Qt
from pathlib import Path

class BatchCompleteDialog(QDialog):
    """
    A dialog box containing a workflow finished message. Also includes a button to open the output folder
    and a button to close the dialog box

    Params:
        output_folder (Path):       The output folder to open when the corresponding button is clicked by the user.
    """

    def __init__(self, output_folder: Path):
        super().__init__()

        self._output_folder = output_folder

        # Create header
        header = self._create_header()

        # Create frame with messages
        messages = self._create_messages()

        # Create buttons at bottom of dialog
        buttons = self._create_buttons()

        # Add everything to dialog box, and format
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(header)
        self.layout.addWidget(messages)
        self.layout.addWidget(buttons)
        self.setLayout(self.layout)
        self.setWindowFlag(Qt.WindowStaysOnTopHint)

        self._show_file_func = {
            "darwin": self._show_file_darwin,
            "linux": self._show_file_linux,
            "win32": self._show_file_windows,
        }

    def _create_header(self):
        """
        Creates a header with the Allen Cell Structure Segmenter title and warning message.

        Params:
            None

        Returns:
            (QLabel): A Qlabel with header + warning message inside.
        """
        # Create header
        header = QLabel(
            """

                ALLEN CELL & STRUCTURE SEGMENTER

                v1.0 supports static 3D images only

            """
        )
        header.setObjectName("header")
        header.setAlignment(Qt.AlignmentFlag.AlignCenter)
        # header.setStyleSheet("background-color:white;")
        header.setMargin(15)
        return header

    def _create_messages(self):
        """
        Creates messages to go within the dialog box

        Params:
            None

        Returns:
            (QFrame): A QFrame that has the "Batch processing is completed" message and a info message (QLabel)
        """
        # Create frame with messages
        frame = QFrame()
        frame.setLayout(QVBoxLayout())
        message = QLabel()
        message.setText("Batch Processing is completed!")
        message.setAlignment(Qt.AlignmentFlag.AlignCenter)
        desc = QLabel()
        desc.setText("Please refer to the log.txt file in the output directory for more details.")
        frame.layout().setContentsMargins(15, 0, 15, 0)
        frame.layout().addWidget(message)
        frame.layout().addWidget(desc)
        return frame

    def _create_buttons(self):
        """
        Creates buttons for the bottom of the dialog box, one for opening the output folder, and one for
            closing the dialog box

        Params:
            None

        Returns:
            (QFrame): A QFrame that has two horizontally laid out buttons, first button is Open output directory,
                second button is close.
        """
        buttons = QFrame()
        buttons.setLayout(QHBoxLayout())
        open_output_button = QPushButton("Open output directory")
        open_output_button.clicked.connect(self._open_output_folder)
        close_button = QPushButton("Close")
        close_button.clicked.connect(self.close)
        buttons.layout().addWidget(open_output_button)
        buttons.layout().addWidget(close_button)
        return buttons

    def _show_file_darwin(self):
        subprocess.Popen(["open", self._output_folder])

    def _show_file_linux(self):
        subprocess.Popen(["xdg-open", self._output_folder])

    def _show_file_windows(self):
        from os import startfile

        startfile(self._output_folder)

    def _open_output_folder(self):
        """
        Opens the output folder on the file explorer

        Params:
            None

        Returns:
            None
        """

        try:
            self._show_file_func[sys.platform]()
        except KeyError:
            raise OSError(f"Your platform: {sys.platform} is not supported by our app.")


from django.urls import path

from . import views

app_name = 'users'

urlpatterns = [
        path('edit/<slug:slug>', views.EditProfileView.as_view(), name='edit_profile'),
    path('<slug:slug>', views.ProfileView.as_view(), name='profile' ),
]


# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 19:07:41 2019

@author: willos-oss
"""

from optuna import trial, create_study
from functools import partial
from learningalgos import extra_trees
from sklearn.model_selection import train_test_split

class ETRegOpt():

    def __init__(self, params_space = {}, shuffle = True):
        self.base_params = {"n_estimators":1000,
                                   "criterion":'mae',
                                   "max_features":'auto',
                                   "max_depth":None,
                                   "bootstrap":True,
                                   "min_samples_split":4,
                                   "min_samples_leaf":1,
                                   "min_weight_fraction_leaf":0,
                                   "max_leaf_nodes":None}

        self.params_space = params_space
        self.shuffle = shuffle

    def _objective(self, x, y, trial):
        self.base_params_space = {"max_features" : trial.suggest_categorical("max_features", ["auto", "sqrt", "log2"]),
                     "max_depth" : trial.suggest_int("max_depth", 3, 9),
                     "bootstrap" : trial.suggest_categorical("bootstrap", [True, False]),
                     "min_samples_split": trial.suggest_int("min_samples_split", 2, 5),
                     "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 5),
                     "min_weight_fraction_leaf": trial.suggest_uniform("min_weight_fraction_leaf", 0, 0.3)
                     }
        self.base_params_space.update(self.params_space)
        self.base_params.update(self.params_space)
        model = extra_trees.ETReg(self.base_params)
        tr_x, va_x, tr_y, va_y = train_test_split(x, y, train_size = 0.9, shuffle = self.shuffle)
        model, score = model.train_and_evaluate(tr_x, va_x, tr_y, va_y)
        return - score

    def fetch_best_params(self, tr_x, tr_y):
        f = partial(self._objective, tr_x, tr_y)
        study = create_study()
        study.optimize(f, n_trials = 100)
        print('params:', study.best_params)
        self.base_params.update(study.best_params)
        return self.base_params


import argparse
import logging
import os
import pdb
import random
import shutil
import sys
from timeit import default_timer as timer
from typing import Tuple

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import average_precision_score, confusion_matrix
from tensorboardX import SummaryWriter
from torch import Tensor
from torch.backends import cudnn
from tqdm import tqdm

import evaluation
import models
from loss import hybrid_regr_loss
from torchsummary import summary

from models import generate_square_subsequent_mask
from utils.data_generator import DataGenerator
from utils.utilities import (create_logging, doa_labels, event_labels,
                             get_filename, logging_and_writer,
                             print_evaluation, to_torch)
import optuna
import pickle
from math import log2

from torch.nn import ReLU, LeakyReLU, GELU

## Hyper-parameters
################# Model #################
USE_TRANSFORMER = True

Model_SED = 'CRNN10'            # 'CRNN10' | 'VGG9'
Model_DOA = 'pretrained_CRNN10' # 'pretrained_CRNN10' | 'pretrained_VGG9'
model_pool_type = 'avg'         # 'max' | 'avg'
model_pool_size = (2, 2)
model_interp_ratio = 16

loss_type = 'MAE'
################# param #################
batch_size = 32
Max_epochs = 10
lr = 1e-3
weight_decay = 0
threshold = {'sed': 0.3}

fs = 32000
nfft = 1024
hopsize = 320 # 640 for 20 ms
mel_bins = 96
frames_per_1s = fs // hopsize
sub_frames_per_1s = 50
chunklen = int(2 * frames_per_1s)
hopframes = int(0.5 * frames_per_1s)

hdf5_folder_name = '{}fs_{}nfft_{}hs_{}melb'.format(fs, nfft, hopsize, mel_bins)
################# batch intervals for save & lr update #################
save_interval = 2000
lr_interval = 2000
########################################################################
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

bptt = 1

def get_batch(source: Tensor, i: int) -> Tuple[Tensor, Tensor]:
    """
    Args:
        source: Tensor, shape [full_seq_len, batch_size]
        i: int

    Returns:
        tuple (data, target), where data has shape [seq_len, batch_size] and
        target has shape [seq_len * batch_size]
    """
    seq_len = min(bptt, len(source) - 1 - i)
    data = source[i:i+seq_len]
    target = source[i+1:i+1+seq_len].reshape(-1)
    return data, target

def train(args, data_generator, model, optimizer, logging):
    global optuna_idx

    # Set the writer
    writer = SummaryWriter()
    writer.add_text('Parameters', str(args))

    temp_submissions_dir = os.path.join(appendixes_dir, '__submissions__')

    trial = 0
    while os.path.isdir(os.path.join(temp_submissions_dir, 'trial_{}'.format(trial))):
        trial += 1

    temp_submissions_dir_train = os.path.join(temp_submissions_dir, 'trial_{}'.format(trial), 'train')
    temp_submissions_dir_valid = os.path.join(temp_submissions_dir, 'trial_{}'.format(trial), 'valid')

    logging.info('\n===> Training mode')

    train_begin_time = timer()
    src_mask = generate_square_subsequent_mask(bptt).to(device)

    epoch_size = data_generator.epoch_size

    iterator = tqdm(enumerate(data_generator.generate_train()),
        total=Max_epochs*epoch_size, unit='batch')

    for batch_idx, (batch_x, batch_y_dict) in iterator:

        epochs = int(batch_idx//epoch_size)
        epoch_batches = int(batch_idx%epoch_size)

        ################
        ## Validation
        ################
        if batch_idx % 200 == 0:

            valid_begin_time = timer()
            train_time = valid_begin_time - train_begin_time

            # Train evaluation
            shutil.rmtree(temp_submissions_dir_train, ignore_errors=True)
            os.makedirs(temp_submissions_dir_train, exist_ok=False)
            train_metrics = evaluation.evaluate(
                        data_generator=data_generator,
                        data_type='train',
                        max_audio_num=30,
                        task_type=args.task_type,
                        model=model,
                        cuda=args.cuda,
                        loss_type=loss_type,
                        threshold=threshold,
                        submissions_dir=temp_submissions_dir_train,
                        frames_per_1s=frames_per_1s,
                        sub_frames_per_1s=sub_frames_per_1s)

            logging.info('----------------------------------------------------------------------------------------------------------------------------------------------')

            # Validation evaluation
            if args.fold != -1:
                shutil.rmtree(temp_submissions_dir_valid, ignore_errors=True)
                os.makedirs(temp_submissions_dir_valid, exist_ok=False)
                valid_metrics = evaluation.evaluate(
                        data_generator=data_generator,
                        data_type='valid',
                        max_audio_num=30,
                        task_type=args.task_type,
                        model=model,
                        cuda=args.cuda,
                        loss_type=loss_type,
                        threshold=threshold,
                        submissions_dir=temp_submissions_dir_valid,
                        frames_per_1s=frames_per_1s,
                        sub_frames_per_1s=sub_frames_per_1s)
                metrics = [train_metrics, valid_metrics]
                logging_and_writer('valid', metrics, logging, writer, batch_idx)
            else:
                logging_and_writer('train', train_metrics, logging, writer, batch_idx)

            valid_time = timer() - valid_begin_time
            logging.info('Iters: {},  Epochs/Batches: {}/{},  Train time: {:.3f}s,  Eval time: {:.3f}s'.format(
                        batch_idx, epochs, epoch_batches, train_time, valid_time))
            logging.info('----------------------------------------------------------------------------------------------------------------------------------------------')
            train_begin_time = timer()

        ###############
        ## Save model
        ###############
        if batch_idx % save_interval == 0 and batch_idx > 1:
            save_subfolder = os.path.join(models_dir, str(optuna_idx))
            os.makedirs(save_subfolder, exist_ok=True)
            save_path = os.path.join(save_subfolder, 'iter_{}.pth'.format(batch_idx))
            checkpoint = {'model_state_dict': model.module.state_dict(),
                          'optimizer_state_dict': optimizer.state_dict(),
                          'rng_state': torch.get_rng_state(),
                          'cuda_rng_state': torch.cuda.get_rng_state()}
            torch.save(checkpoint, save_path)
            logging.info('Checkpoint saved to {}'.format(save_path))

        ###############
        ## Train
        ###############
        # Reduce learning rate
        if batch_idx % lr_interval == 0 and batch_idx > 1:
            for param_group in optimizer.param_groups:
                param_group['lr'] *= 0.9

        batch_x = to_torch(batch_x, args.cuda)
        batch_y_dict = {
            'events':   to_torch(batch_y_dict['events'], args.cuda),
            'doas':  to_torch(batch_y_dict['doas'], args.cuda)
        }

        # Forward
        model.train()
        if batch_size != bptt:  # only on last batch
            src_mask = src_mask[:batch_size, :batch_size]
        output = model(batch_x)

        # Loss
        seld_loss, _, _ = hybrid_regr_loss(output, batch_y_dict, args.task_type, loss_type=loss_type)

        # Backward
        optimizer.zero_grad()
        seld_loss.backward()
        optimizer.step()

        if batch_idx == Max_epochs*epoch_size:
            iterator.close()
            writer.close()
            break

    optuna_idx += 1

    return (1 - metrics[1][2][1])

def inference(args, data_generator, logging):

    # Load model for sed only
    print('\n===> Inference for SED')

    if args.task_type == 'two_staged_eval':

        model_path = os.path.join(models_dir, 'sed_only',
                                'model_' + Model_SED + '_{}'.format(args.audio_type) + '_fold_{}'.format(args.fold) + '_seed_{}'.format(args.seed),
                                'iter_{}.pth'.format(args.iteration))
        assert os.path.exists(model_path), 'Error: no checkpoint file found!'
        model = models.__dict__[Model_SED](class_num, args.model_pool_type,
                                           args.model_pool_size, args.model_interp_ratio, pretrained_path, use_transformer=USE_TRANSFORMER)
        checkpoint = torch.load(model_path, map_location=lambda storage, loc: storage)
        model.load_state_dict(checkpoint['model_state_dict'])
        if args.cuda:
            model.cuda()

        fold_submissions_dir= os.path.join(submissions_dir, args.task_type, 'model_' + args.model + '_{}'.format(args.audio_type) + \
            '_seed_{}'.format(args.seed), '_test')
        shutil.rmtree(fold_submissions_dir, ignore_errors=True)
        os.makedirs(fold_submissions_dir, exist_ok=False)
        test_metrics = evaluation.evaluate(
                data_generator=data_generator,
                data_type='test',
                max_audio_num=None,
                task_type='sed_only',
                model=model,
                cuda=args.cuda,
                loss_type=loss_type,
                threshold=threshold,
                submissions_dir=fold_submissions_dir,
                frames_per_1s=frames_per_1s,
                sub_frames_per_1s=sub_frames_per_1s)

        # Load model for doa using sed pred
        print('\n===> Inference for SED and DOA')
        model_path = os.path.join(models_dir, 'doa_only',
                                'model_' + Model_DOA + '_{}'.format(args.audio_type) + '_fold_{}'.format(args.fold) + '_seed_{}'.format(args.seed),
                                'iter_{}.pth'.format(args.iteration))
        assert os.path.exists(model_path), 'Error: no checkpoint file found!'
        model = models.__dict__[Model_DOA](class_num, args.model_pool_type,
            args.model_pool_size, args.model_interp_ratio, pretrained_path, use_transformer=USE_TRANSFORMER)
        checkpoint = torch.load(model_path, map_location=lambda storage, loc: storage)
        model.load_state_dict(checkpoint['model_state_dict'])
        if args.cuda:
            model.cuda()

        test_metrics = evaluation.evaluate(
                data_generator=data_generator,
                data_type='test',
                max_audio_num=None,
                task_type='two_staged_eval',
                model=model,
                cuda=args.cuda,
                loss_type=loss_type,
                threshold=threshold,
                submissions_dir=fold_submissions_dir,
                frames_per_1s=frames_per_1s,
                sub_frames_per_1s=sub_frames_per_1s)

    else:
        # 'sed_only' | 'doa_only' | 'seld'
        model_path = os.path.join(models_dir, args.task_type,
                                'model_' + args.model + '_{}'.format(args.audio_type) + '_fold_{}'.format(args.fold) + '_seed_{}'.format(args.seed),
                                'iter_{}.pth'.format(args.iteration))
        assert os.path.exists(model_path), 'Error: no checkpoint file found!'
        model = models.__dict__[args.model](class_num, args.model_pool_type,
            args.model_pool_size, args.model_interp_ratio, pretrained_path)
        checkpoint = torch.load(model_path, map_location=lambda storage, loc: storage)
        model.load_state_dict(checkpoint['model_state_dict'])
        if args.cuda:
            model.cuda()

        fold_submissions_dir= os.path.join(submissions_dir, args.task_type, 'model_' + args.model + '_{}'.format(args.audio_type) + \
            '_seed_{}'.format(args.seed), '_test')
        shutil.rmtree(fold_submissions_dir, ignore_errors=True)
        os.makedirs(fold_submissions_dir, exist_ok=False)
        test_metrics = evaluation.evaluate(
                data_generator=data_generator,
                data_type='test',
                max_audio_num=None,
                task_type=args.task_type,
                model=model,
                cuda=args.cuda,
                loss_type=loss_type,
                threshold=threshold,
                submissions_dir=fold_submissions_dir,
                frames_per_1s=frames_per_1s,
                sub_frames_per_1s=sub_frames_per_1s)

    logging.info('----------------------------------------------------------------------------------------------------------------------------------------------')
    logging_and_writer('test', test_metrics, logging)
    logging.info('----------------------------------------------------------------------------------------------------------------------------------------------')

    test_submissions_dir= os.path.join(submissions_dir, args.task_type, 'model_' + args.model + '_{}'.format(args.audio_type) + \
        '_seed_{}'.format(args.seed), 'test')
    os.makedirs(test_submissions_dir, exist_ok=True)
    for fn in sorted(os.listdir(fold_submissions_dir)):
        if fn.endswith('.csv') and not fn.startswith('.'):
            src = os.path.join(fold_submissions_dir, fn)
            dst = os.path.join(test_submissions_dir, fn)
            shutil.copyfile(src, dst)

def inference_all_fold(args):

    test_submissions_dir= os.path.join(args.workspace, 'appendixes', 'submissions', args.task_type,
        'model_' + args.model  + '_{}'.format(args.audio_type) + \
            '_seed_{}'.format(args.seed), 'test')

    gt_meta_dir = '/home/username/deep_learning_project/datasets/extracted/metadata_dev/'
    sed_scores, doa_er_metric, seld_metric = evaluation.calculate_SELD_metrics(gt_meta_dir, test_submissions_dir, score_type='all')

    loss = [0.0, 0.0, 0.0]
    sed_mAP = [0.0, 0.0]

    metrics = [loss, sed_mAP, sed_scores, doa_er_metric, seld_metric]

    print('----------------------------------------------------------------------------------------------------------------------------------------------')
    print_evaluation(metrics)
    print('----------------------------------------------------------------------------------------------------------------------------------------------')

def reset_model():
    global models_dir
    if args.mode == 'train':
        # models directory
        models_dir = os.path.join(appendixes_dir, 'models_saved', '{}'.format(args.task_type),
                                  'model_' + args.model + '_{}'.format(args.audio_type) + '_fold_{}'.format(args.fold) +
                                  '_seed_{}'.format(args.seed))
        os.makedirs(models_dir, exist_ok=True)
    elif args.mode == 'inference':
        # models directory
        models_dir = os.path.join(appendixes_dir, 'models_saved')

    logging.info('\n===> Building model')
    train_model = models.__dict__[args.model](class_num, args.model_pool_type,
                                        args.model_pool_size, args.model_interp_ratio, pretrained_path)

    if args.cuda:
        logging.info('\nUtilize GPUs for computation')
        logging.info('\nNumber of GPU available: {}'.format(torch.cuda.device_count()))
        if torch.cuda.device_count() > 1:
            Multi_GPU = True
        else:
            Multi_GPU = False
        train_model.cuda()
        # cudnn.benchmark = False # for cuda 10.0
        train_model = torch.nn.DataParallel(train_model)

    return train_model

def objective(trial, arguments):
    train_model = reset_model()

    lr = trial.suggest_float('lr', 1e-4, 1e-3)
    nhead = trial.suggest_int('nhead', 1, 5)
    optimzer_name = trial.suggest_categorical('optimzer', ['SGD', 'Adam', 'RMSprop'])
    activations = {"relu": ReLU(), "gelu": GELU(), "leaky_relu": LeakyReLU()}
    activation = trial.suggest_categorical('activation', list(activations.keys()))
    logging.info(f"lr: {lr}, optimizer: {optimzer_name}, activation: {activation}, nhead: {2 ** nhead}")

    # lstm_layers = trial.suggest_int('lstm_layers', 1, 2)
    # logging.info(f"lr: {lr}, optimizer: {optimzer_name}, layers: {lstm_layers}")
    # train_model.module.init_weights(lstm_layers)

    if optimzer_name == 'Adam':
        optimizer = optim.Adam(train_model.parameters(), lr=lr,
                               betas=(0.9, 0.999), eps=1e-08,
                               weight_decay=weight_decay, amsgrad=True)
    elif optimzer_name == 'SGD':
        optimizer = optim.SGD(train_model.parameters(), lr=lr, weight_decay=weight_decay, )
    elif optimzer_name == 'RMSprop':
        optimizer = optim.RMSprop(train_model.parameters(), lr=lr, weight_decay=weight_decay, )

    train_model.module.change_encoder(activations[activation], nhead)
    train_model.module.to(torch.device('cuda:0'))

    parameter_num = sum([param.numel() for param in train_model.parameters()])
    logging.info('\nTotal number of parameters: {}\n'.format(parameter_num))

    return train(arguments, data_generator, train_model, optimizer, logging)

if __name__ == '__main__':
    # global optuna_idx
    # optuna_idx = 0

    parser = argparse.ArgumentParser(description='DCASE2019 task3')

    subparsers = parser.add_subparsers(dest='mode')

    parser_train = subparsers.add_parser('train')
    parser_train.add_argument('--workspace', type=str, required=True,
                                help='workspace directory')
    parser_train.add_argument('--feature_dir', type=str, required=True,
                                help='feature directory')
    parser_train.add_argument('--feature_type', type=str, required=True,
                                choices=['logmel', 'logmelgcc'])
    parser_train.add_argument('--audio_type', type=str, required=True,
                              choices=['foa', 'mic'], help='audio type')
    parser_train.add_argument('--task_type', type=str, required=True,
                                choices=['sed_only', 'doa_only', 'two_staged_eval', 'seld'])
    parser_train.add_argument('--fold', default=1, type=int,
                                help='fold for cross validation, if -1, use full data')
    parser_train.add_argument('--seed', default='42', type=int,
                                help='random seed')
    parser_train.add_argument('--optuna', default='0', type=int,
                              help='optuna train index')

    parser_inference = subparsers.add_parser('inference')
    parser_inference.add_argument('--workspace', type=str, required=True,
                                help='workspace directory')
    parser_inference.add_argument('--feature_dir', type=str, required=True,
                                help='feature directory')
    parser_inference.add_argument('--feature_type', type=str, required=True,
                                choices=['logmel', 'logmelgcc'])
    parser_inference.add_argument('--audio_type', type=str, required=True,
                                choices=['foa', 'mic'], help='audio type')
    parser_inference.add_argument('--task_type', type=str, required=True,
                                choices=['sed_only', 'doa_only', 'two_staged_eval', 'seld'])
    parser_inference.add_argument('--fold', default=1, type=int,
                                help='fold for cross validation, if -1, use full data')
    parser_inference.add_argument('--iteration', default=5000, type=int,
                                help='which iteration model to read')
    parser_inference.add_argument('--seed', default='42', type=int,
                                help='random seed')

    parser_inference_all = subparsers.add_parser('inference_all')
    parser_inference_all.add_argument('--workspace', type=str, required=True,
                                help='workspace directory')
    parser_inference_all.add_argument('--audio_type', type=str, required=True,
                                choices=['foa', 'mic'], help='audio type')
    parser_inference_all.add_argument('--task_type', type=str, required=True,
                                choices=['sed_only', 'doa_only', 'two_staged_eval', 'seld'])
    parser_inference_all.add_argument('--seed', default='42', type=int,
                                help='random seed')

    args = parser.parse_args()

    '''
    1. Miscellaneous
    '''
    global optuna_idx
    optuna_idx = args.optuna
    print('Optuna index: ', optuna_idx)

    args.fs = fs
    args.nfft = nfft
    args.hopsize = hopsize
    args.mel_bins = mel_bins
    args.chunklen = chunklen
    args.hopframes = hopframes

    args.cuda = torch.cuda.is_available()
    args.batch_size = batch_size
    args.lr = lr
    args.weight_decay = weight_decay
    args.hdf5 = hdf5_folder_name

    if args.task_type == 'sed_only' or args.task_type == 'seld':
        args.model = Model_SED
    elif args.task_type == 'doa_only' or args.task_type == 'two_staged_eval':
        args.model = Model_DOA
    args.model_pool_type = model_pool_type
    args.model_pool_size = model_pool_size
    args.model_interp_ratio = model_interp_ratio
    args.loss_type = loss_type

    class_num = len(event_labels)
    doa_num = len(doa_labels)

    # inference all folds, otherwise train or inference single fold
    if args.mode == 'inference_all':
        inference_all_fold(args)
        sys.exit()

    # Get reproducible results by manually seed the random number generator
    torch.manual_seed(args.seed)
    if args.cuda:
        torch.cuda.manual_seed(args.seed)
    np.random.seed(args.seed)
    random.seed(args.seed)
    cudnn.deterministic=True

    # logs directory
    logs_dir = os.path.join(args.workspace, 'logs', args.task_type, args.mode,
            'model_' + args.model + '_{}'.format(args.audio_type) + '_fold_{}'.format(args.fold) +
            '_seed_{}'.format(args.seed))
    create_logging(logs_dir, filemode='w')
    logging.info(args)

    # appendixes directory
    global appendixes_dir
    appendixes_dir = os.path.join(args.workspace, 'appendixes')
    os.makedirs(appendixes_dir, exist_ok=True)

    # submissions directory
    global submissions_dir
    submissions_dir = os.path.join(appendixes_dir, 'submissions')
    os.makedirs(submissions_dir, exist_ok=True)

    # pretrained path
    global pretrained_path
    # base_path = '/home/username/path'
    # pretrained_path = os.path.join(base_path, str(optuna_idx), 'iter_10000.pth')  # Take only the 10k saved step.

    pretrained_path = '/home/username/workspace/appendixes/models_saved/sed_only/model_CRNN10_mic_fold_2_seed_20/5/iter_10000.pth'

    '''
    2. Model
    '''
    model = reset_model()

    # global models_dir
    # if args.mode == 'train':
    #     # models directory
    #     models_dir = os.path.join(appendixes_dir, 'models_saved', '{}'.format(args.task_type),
    #                             'model_' + args.model + '_{}'.format(args.audio_type) + '_fold_{}'.format(args.fold) +
    #                             '_seed_{}'.format(args.seed))
    #     os.makedirs(models_dir, exist_ok=True)
    # elif args.mode == 'inference':
    #     # models directory
    #     models_dir = os.path.join(appendixes_dir, 'models_saved')
    #
    # logging.info('\n===> Building model')
    # model = models.__dict__[args.model](class_num, args.model_pool_type,
    #     args.model_pool_size, args.model_interp_ratio, pretrained_path)
    #
    #
    # if args.cuda:
    #     logging.info('\nUtilize GPUs for computation')
    #     logging.info('\nNumber of GPU available: {}'.format(torch.cuda.device_count()))
    #     if torch.cuda.device_count() > 1:
    #         Multi_GPU = True
    #     else:
    #         Multi_GPU = False
    #     model.cuda()
    #     # cudnn.benchmark = False # for cuda 10.0
    #     model = torch.nn.DataParallel(model)

    # Print the model architecture and parameters
    # logging.info('\nModel architectures:\n{}\n'.format(model))
    # logging.info('\nParameters and size:')
    # for n, (name, param) in enumerate(model.named_parameters()):
    #     logging.info('{}: {}'.format(name, list(param.size())))
    # parameter_num = sum([param.numel() for param in model.parameters()])
    # logging.info('\nTotal number of parameters: {}\n'.format(parameter_num))

    '''
    3. Data generator
    '''
    hdf5_dir = os.path.join(args.feature_dir, args.feature_type,
                             hdf5_folder_name, args.audio_type)
    data_generator = DataGenerator(
        args=args,
        hdf5_dir=hdf5_dir,
        logging=logging
    )

    '''
    4. Train, test and evaluation
    '''

    if args.mode == 'train':
        if args.task_type == 'sed_only':
            study = optuna.create_study()
            study.optimize(lambda trial: objective(trial, args), n_trials=10)
            logging.info(study.best_params)

            # optimizer = optim.Adam(model.parameters(), lr=lr,
            #                        betas=(0.9, 0.999), eps=1e-08,
            #                        weight_decay=weight_decay, amsgrad=True)
            # model.module.change_encoder(LeakyReLU(), 4)
            # model.module.to(torch.device('cuda:0'))
            # train(args, data_generator, model, optimizer, logging)

        elif args.task_type == 'doa_only':
            # params_file_path = '/home/lzpz6s/deep_optuna/sed_doae/logs/sed_only/train/model_CRNN10_mic_fold_2_seed_20/hyperparams_SED.pickle'
            # with open(params_file_path, 'rb') as handle:
            #     hyperparams = pickle.load(handle)
            #
            # lr = hyperparams[optuna_idx]['lr']
            # # nhead = int(log2(hyperparams[optuna_idx]['nhead']))
            # # activations = {"relu": ReLU(), "gelu": GELU(), "leaky_relu": LeakyReLU()}
            # # activation = hyperparams[optuna_idx]['activation']
            # lstm_layers = hyperparams[optuna_idx]['lstm_layers']
            # optimzer_name = hyperparams[optuna_idx]['optimizer']
            # if optimzer_name == 'Adam':
            #     optimizer = optim.Adam(model.parameters(), lr=lr,
            #                            betas=(0.9, 0.999), eps=1e-08,
            #                            weight_decay=weight_decay, amsgrad=True)
            # elif optimzer_name == 'SGD':
            #     optimizer = optim.SGD(model.parameters(), lr=lr, weight_decay=weight_decay, )
            # elif optimzer_name == 'RMSprop':
            #     optimizer = optim.RMSprop(model.parameters(), lr=lr, weight_decay=weight_decay, )
            #
            # # model.module.change_encoder(activations[activation], nhead)
            # model.module.init_weights(lstm_layers)
            # model.to(torch.device('cuda:0'))
            # # logging.info(f"lr: {lr}, optimizer: {optimzer_name}, activation: {activation}, nhead: {2 ** nhead}")
            # logging.info(f"lr: {lr}, optimizer: {optimzer_name}, layers: {lstm_layers}")
            # train(args, data_generator, model, optimizer, logging)

            optimizer = optim.Adam(model.parameters(), lr=lr,
                                   betas=(0.9, 0.999), eps=1e-08,
                                   weight_decay=weight_decay, amsgrad=True)
            model.module.change_encoder(LeakyReLU(), 4)
            model.module.to(torch.device('cuda:0'))
            train(args, data_generator, model, optimizer, logging)

    elif args.mode == 'inference':
        inference(args, data_generator, logging)
    else:
        raise Exception('Error!')


#!/usr/bin/python
import sys
import copy

def parse_dimacs_vars(filename):
    d = {}
    with open(filename) as f:
        for line in f:
            s = line.rstrip("\n").split()
            if len(s) > 3 and s[3] == "(v,":
                d[int(s[0])] = map(int, s[1:3])
    return d

def parse_unigen(filename, max_var):
    d = {}
    with open(filename) as f:
        for line in f:
            s = line.lstrip(" ").lstrip("v").rstrip("\n").split()
            if len(s) == 0: continue
            count = int(s[-1].split(":")[-1])
            assignment = frozenset(map(int, s[:-1])[:max_var])

            if assignment not in d:
                d[assignment] = count
            else:
                d[assignment] += count

        return d

def write_ptree(in_ptree, var_mapping, sol, prefix, idx, count):
    out_ptree = copy.deepcopy(in_ptree)

    for lit in sol:
        if lit > 0:
            v,s = var_mapping[lit]
            out_ptree[v-1][-1] = str(s+1)

    with open("%sidx%d_count%d.out" % (prefix, idx, count), "w") as f:
        for line in out_ptree:
            f.write("\t".join(line) + "\n")

def parse_ptree(filename):
    res = []
    with open(filename) as f:
        for line in f:
            res.append(line.rstrip("\n").split())
        return res

if __name__ == "__main__":
    if len(sys.argv) != 5:
        sys.stderr.write("Usage: %s <ptree> <dimacs_vars> <unigen_sol> <prefix>\n" % sys.argv[0])
        sys.exit(1)

    var_mapping = parse_dimacs_vars(sys.argv[2])
    max_var = max(var_mapping.keys())

    #print var_mapping
    #print max_var

    in_ptree = parse_ptree(sys.argv[1])
    solutions = parse_unigen(sys.argv[3], max_var)
    prefix = sys.argv[4]

    for idx, sol in enumerate(solutions):
        write_ptree(in_ptree, var_mapping, sol, prefix, idx, solutions[sol])


import numpy as np

from Problem.Problem import Problem

class ProblemTSP(Problem):
    def read_file(self, filename):
        cnt = 0

        with open(filename) as f:
            for i, line in enumerate(f.readlines()):
                # Read problem's metadata
                if line.startswith('NAME'):
                    self.problem_name = line.split(':')[1].strip()
                elif line.startswith('DIMENSION'):
                    map_dimension = int(line.split(':')[1])
                    self.cities = np.zeros(shape=(map_dimension, 2))  # This is to add the coords and indexes of the items of this city
                    self.map_dimension = map_dimension
                elif line[0].isdigit():
                    self.cities[cnt] = np.array([float(line.split()[0]), float(line.split()[1])])
                    cnt += 1

    def get_distances(self):
        map = self.cities
        if not hasattr(self, 'distances'):
            self.distances = np.array([[DistanceFunctions.euclidian_distance(map_city1, map_city2) for map_city1 in map] for map_city2 in map])
        return self.distances

class DistanceFunctions:
    @staticmethod
    def euclidian_distance(city1, city2):
        return ((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ** 0.5


#Fungsi egcd dengan var a dan b
def egcd(a, b):
  x,y, u,v = 0,1, 1,0

  while a != 0:                   #Jika var a tidak sama dengan 0
    q, r = b//a, b%a              #Mendeklarasikan objek
    m, n = x-u*q, y-v*q
    b,a, x,y, u,v = a,r, u,v, m,n
  gcd = b
  return gcd, x, y      #Mengembalikan nilai gcd, x, dan y

#Fungsi modivn pada variabel a dan m
def modinv(a, m):
  gcd, x, y = egcd(a, m)

  if gcd != 1:          #Jika gcd tidak sama dengan 1, maka mengembalikan nilainya berupa None
    return None
  else:
    return x % m        #Mengembalikan nilai x mod m

#Fungsi Enkripsi
def Enkripsi():
  pesan = input("Data pesan\t: ")       #Input pesan yg akan dienkripsi
  n1    = int(input("Kunci A\t\t: "))   #Input kunci angka yg nantinya akan dimasukkan dalam list bernama key pada indeks 0
  n2    = int(input("Kunci B\t\t: "))   #Input kunci angka yg nantinya akan dimasukkan dalam list bernama key pada indeks 1
  key   = [n1, n2]                      #List bernama key

  #Menampung perhitungan rumus Alfine Cipher 'C = (a*P + b)%26' dalam var hasil1.  Intinya mencari index dan perhitungan kunci pada pesan
  hasil1= ''.join([chr( ( (key[0]*(ord(t) - ord('A')) + key[1]) % 26 ) + ord('A') ) for t in pesan.upper().replace(' ', '') ])
  #Mencetak hasil akhir, data pesan dan kuncinya
  print(f"<---------------------------------->\nHasil program enkripsi\nData pesan\t: {pesan}\nKunci A & B\t:{key}\nEnkripsi pesan\t: {hasil1}")

#Fungsi Dekripsi
def Dekripsi():
  pesan = input("Pesan terenkripsi: ")  #Input pesan yg telah dienkripsi
  n1    = int(input("Kunci A\t\t: "))   #Input kunci angka yg nantinya akan dimasukkan dalam list bernama key pada indeks 0
  n2    = int(input("Kunci B\t\t: "))   #Input kunci angka yg nantinya akan dimasukkan dalam list bernama key pada indeks 1
  key   = [n1, n2]                      #List bernama key

  #Menampung perhitungan rumus Alfine Cipher 'P = (a^-1*(C - b))%26' dalam var hasil2. Intinya mencari index dan perhitungan kunci pada pesan terenkripsi
  hasil2 = ''.join([chr( ( (modinv(key[0], 26)*(ord(c) - ord('A') - key[1]))% 26 ) + ord('A') ) for c in pesan ])
  #Mencetak hasil akhir, data pesan dan kuncinya
  print(f"<---------------------------------->\nHasil program enkripsi\nData pesan\t: {pesan}\nKunci A & B\t:{key}\nDekripsi pesan\t: {hasil2}")

#Menu PROGRAM
pilihan = 'y'
while (pilihan == 'Y' or pilihan == 'y'):   #If you choose 'y' or 'Y', this menu script will be execute again
    print("Menu yang tersedia:\nA.Enkripsi pesan\nB.Dekripsi pesan\nC.Keluar dari program")
    menu = input("Pilih: ")
    print("__________________________________")

    if menu == 'A' or menu == 'a':      #Choose menu a
        print("Menu enkripsi pesan\n----------------------------------")
        Enkripsi()                      #Menjalankan Encryp funct
    elif menu == 'B' or menu == 'b':    #Choose menu b
        print("Menu dekripsi pesan")
        Dekripsi()                      #Menjalankan Decrypt funct
    elif menu == 'C' or menu == 'c':    #Choose menu c, will be what?? Exactly,it will be done or close program
        print("!!---!!---[Program selesai]---!!---!!")
        break;
    else:
        print("Menu tidak tersedia")

    print("==================================")
    pilihan = input("Apakah ingin mengulangi?(Y/N): ")  #Setelah menjalankan program, akan ditanya
    if pilihan == 'n' or pilihan == "N":                #This script will be execute
        print("\n!!---!!---[Program selesai]---!!---!!\n")


import pymysql
from pymysql.err import raise_mysql_exception
from conexion import DataBase

class VentasHelper(DataBase):
    #CONSTRUCTOR, RECIBE PARAMETROS QUE SERÁN AÑADIDOS A LA TABLA
    motivo = ""
    cantidad = 0
    fecha = ""

    def __init__(self,motivo,cantidad,fecha):
        self.motivo = motivo
        self.cantidad = cantidad
        self.fecha = fecha

        DataBase.__init__(self)

    #GUARDAR REPORTE DE VENTA NUEVO EN LA BASE DE DATOS
    def insertar(self):

        sql = "INSERT INTO reportes(motivo_reporte,cantidad_reporte,fecha_reporte) VALUES ('{}','{}','{}')".format(self.motivo,self.cantidad,self.fecha)
        try:
            self.cursor.execute(sql)
            print("Registro Añadido a la base de datos")
            self.connection.commit()

            #print(self.idVenta[0])
            #self.cursor.close()

        except pymysql.Error as err:
            print("Algo salio mal ", format(err))

    #FUNCION PARA REGISTRAR LOS DETALLES DE UNA VENTA
    def registrar_detalles(self,listaVenta):
        try:
            self.cursor.execute("SELECT * FROM reportes ORDER BY idreporte DESC")
            self.idVenta = self.cursor.fetchone()
            print(listaVenta)
            for producto in listaVenta:
                self.producto = producto[0]
                self.cantidadProducto = producto[2]
                self.subtotal = producto[3]
                sql = "INSERT INTO detalles_venta(id_venta,producto_venta,cantidad_venta,subtotal_venta,fecha_venta) VALUES ('{}','{}','{}','{}','{}')".format(self.idVenta[0],self.producto,self.cantidadProducto,self.subtotal,self.fecha)
                self.cursor.execute(sql)
                print("Insertados en detalle ventas")

            self.connection.commit()
            self.connection.close()

        except pymysql.Error as err:
            print("Algo salio mal ", format(err))

    def mostrar_tabla(self):
        sql = "SELECT * FROM reportes"
        try:
            self.cursor.execute(sql)
            self.rows = self.cursor.fetchall()
            tabRows = []
            for row in self.rows:
                tabRows.append(row)
                self.connection.commit()

            self.connection.close()
            return tabRows
        except pymysql.Error as err:
            print("Algo Salio mal ", format(err))

    #FUNCION PARA GRAFICAR VENTAS
    def graficar_ventas(self):
        sql = "SELECT cantidad_reporte, fecha_reporte FROM reportes WHERE motivo_reporte='VENTA'"
        try:
            self.cursor.execute(sql)
            self.data = self.cursor.fetchall()
            #print(self.data)
            ventas = list(self.data)
            datosVentas = []
            fechas = []
            montos = []
            n=0
            for venta in ventas:
                #FUNCION PARA CONVERTIR DATOS DE SQL A VALOR FLOTANTE PYTHON
                #venta = float('.'.join(str(ele) for ele in self.data[n]))
                venta = list(ventas[n])
                fecha = venta[1]
                self.montosDiarios = []
                montoDiario = 0
                dia = fecha.split('-')
                montos.append(venta[0])
                fechas.append(int(dia[0]))
                n = n+1

            for i in range(len(fechas)):

                if(i < len(fechas)-1):

                    if (fechas[i] == fechas[i+1]):
                        montoDiario = montoDiario + montos[i] + montos[i+1]
                        self.montosDiarios.append(0)
                    else:
                        montoDiario = montoDiario + montos[i]
                        self.montosDiarios.append(montoDiario)

                else:
                    montoDiario = montoDiario + montos[i]
                    self.montosDiarios.append(montoDiario)

            datosVentas.append(fechas)
            datosVentas.append(self.montosDiarios)
            self.connection.commit()
            self.connection.close()
            return datosVentas
        except pymysql.Error as err:
            print('Algo salio mal',format(err))

    def ventas_mensuales(self):
        ventaMensual = 0
        for i in range(len(self.montosDiarios)):
            ventaMensual = ventaMensual + self.montosDiarios[i]

        return ventaMensual


from __future__ import print_function
import cv2
import numpy as np
import argparse
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import random as rng
cap = cv2.VideoCapture(0)
while(True):
    ret, src = cap.read()
    # Convert image to gray and blur it
    src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    src_gray=((src_gray>5)&(src_gray<200))*255
    src_gray=np.uint8(src_gray)
    kernel1 = np.ones((100,100),np.uint8)
    src_gray =  cv2.morphologyEx(src_gray, cv2.MORPH_OPEN, kernel1)
    #kernel2 = np.ones((50,50),np.uint8)
    #src_gray =  cv2.morphologyEx(src_gray, cv2.MORPH_CLOSE, kernel2)
    canny_output = cv2.Canny(src_gray, 50, 150)
    contours, hierarchy = cv2.findContours(canny_output, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    contours_poly = [None]*len(contours)
    boundRect = [None]*len(contours)
    centers = [None]*len(contours)
    radius = [None]*len(contours)
    for i, c in enumerate(contours):
        contours_poly[i] = cv2.approxPolyDP(c, 3, True)
        boundRect[i] = cv2.boundingRect(contours_poly[i])
        centers[i], radius[i] = cv2.minEnclosingCircle(contours_poly[i])

    drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)

    for i in range(len(contours)):
        color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
        cv2.drawContours(drawing, contours_poly, i, color)
        cv2.rectangle(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \
          (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)
       # cv2.circle(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)
    #cv2.namedWindow(source_window)
    neg=drawing==0
    img=src*neg+drawing
    cv2.imshow('contours',img)

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


'''
Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k.

A subarray is a contiguous non-empty sequence of elements within an array.

The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.

Example 1:

Input: nums = [3,6,2,7,1], k = 6
Output: 4
Explanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are:
- [3,6,2,7,1]
- [3,6,2,7,1]
- [3,6,2,7,1]
- [3,6,2,7,1]
Example 2:

Input: nums = [3], k = 2
Output: 0
Explanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.

Constraints:

1 <= nums.length <= 1000
1 <= nums[i], k <= 1000
'''
import unittest

from typing import *

from math import gcd
class Solution:
    def subarrayLCM(self, nums: List[int], k: int) -> int:
        res = 0
        for i in range(len(nums)):
            l = nums[i]
            if l == k:
                res += 1
            for j in range(i + 1, len(nums)):
                l = l * nums[j] // gcd(l, nums[j])
                if l == k:
                    res += 1
        return res

class TestSolution(unittest.TestCase):

    def test_case(self):
        examples = (
            (([3,6,2,7,1], 6), 4),
        )
        for first, second in examples:
            self.assert_function(first, second)

    def assert_function(self, first, second):
        self.assertEqual(Solution().subarrayLCM(*first), second,
                         msg="first: {}; second: {}".format(first, second))

unittest.main()

Leetcode/2470. Number of Subarrays With LCM Equal to K.py


import os
from types import SimpleNamespace

import numpy as np
from sacred import Experiment
from tensorboardX import SummaryWriter

from common.run_episode import run_episode, run_episode_vec
from common.utils.make_environments import make_environments
from example.random_agent import RandomAgent

ex = Experiment("example")
config_path = os.path.dirname(__file__) + "/config.json"
ex.add_config(config_path)

@ex.main
def main(_run, _config):
    config = SimpleNamespace(**_config)
    environments = make_environments(config)

    output_directory = f"./tmp/example/{_run._id}/"

    writer = SummaryWriter(output_directory)

    agent = RandomAgent(num_actions=environments[0].action_space.n)

    rewards = []
    lengths = []
    for episode in range(config.episodes):
        if config.num_envs > 1:
            episode_rewards, episode_length = run_episode_vec(
                environments,
                agent,
                render=episode % config.render_episode_interval == 0,
                max_length=config.max_episode_length,
            )
        else:
            episode_rewards, episode_length = run_episode(
                environments[0],
                agent,
                render=episode % config.render_episode_interval == 0 and False,
                max_length=config.max_episode_length,
            )
        rewards.append(episode_rewards)
        lengths.append(episode_length)
        if episode % config.render_episode_interval == 0:
            mean_rewards, std_rewards = np.mean(rewards), np.std(rewards)
            mean_length, std_length = np.mean(lengths), np.std(lengths)
            global_step = config.num_envs * episode
            writer.add_scalar("rewards/mean", mean_rewards, global_step=global_step)
            writer.add_scalar(
                "rewards/standard_deviation", std_rewards, global_step=global_step
            )
            writer.add_scalar(
                "episode_length/mean", mean_length, global_step=global_step
            )
            writer.add_scalar(
                "episode_length/standard_deviation", std_length, global_step=global_step
            )
            print("Episode {}\tMean rewards {:f}".format(episode, mean_rewards))
            rewards.clear()
            lengths.clear()


import allure

from config import BASE_URL
from pages.widgets.accordian_page import AccordianPage

class TestAccordian:
    page_link = BASE_URL + '/accordian'

    @allure.title("Check section titles")
    def test_accordian(self, driver):
        accordian_page = AccordianPage(driver, self.page_link)
        accordian_page.open()

        first_section_title, first_section_body = accordian_page.check_accordian("first_section")
        second_section_title, second_section_body = accordian_page.check_accordian("second_section")
        third_section_title, third_section_body = accordian_page.check_accordian("third_section")

        assert first_section_title == "What is Lorem Ipsum?" and first_section_body > 0, \
            "Incorrect title or missing text"
        assert second_section_title == "Where does it come from?" and second_section_body > 0, \
            "Incorrect title or missing text"
        assert third_section_title == "Why do we use it?" and third_section_body > 0, \
            "Incorrect title or missing text"


from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _

from apps.utils.mixins.models.timestamp import TimeStampedMixin
from apps.utils.mixins.models.uuid_mixin import UUIDMixin

class Addresses(UUIDMixin, TimeStampedMixin):
    class TYPES(models.IntegerChoices):
        HOME = (1, "home")
        FACTOR = (2, "factor")
        DELIVER = (3, "deliver")

    user = models.ForeignKey(
        verbose_name=_("Related user"),
        to=settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='addresses',
    )
    timezone = models.ForeignKey(
        verbose_name=_("TimeZone"),
        to="apps.accounts.TimeZones",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    country = models.ForeignKey(
        verbose_name=_("Country"),
        to="apps.accounts.Countries",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    county = models.ForeignKey(
        verbose_name=_("County"),
        to="apps.accounts.Counties",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    city = models.ForeignKey(
        verbose_name=_("City"),
        to="apps.accounts.Cities",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    village = models.ForeignKey(
        verbose_name=_("Village"),
        to="apps.accounts.Villages",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    address = models.TextField(
        verbose_name=_("Full address"),
        blank=True,
        null=True,
    )
    name = models.CharField(
        verbose_name=_("Receiver name"),
        max_length=255,
        null=True,
        default='',
    )
    type = models.IntegerField(
        verbose_name=_("Address type, Home, Factor or deliver?"),
        choices=TYPES,
        default=TYPES.HOME,
    )

    class Meta:
        verbose_name = _("Address")
        verbose_name_plural = _("Addresses")


from network import *
from time import *
import usocket as socket
from machine import *

led = Pin(25,Pin.OUT)
led2 = Pin(15,Pin.OUT)
led3 = Pin(16,Pin.OUT)
led4 = Pin(17,Pin.OUT)

sta_if=WLAN(STA_IF)
sta_if.active(True)
print('Activando estación...')
while not sta_if.active():
    pass
print('Estación activada!...')
sta_if.connect('Guapo quien lo lea','1029384756')
print('Conectando...')
while not sta_if.isconnected():
    pass
print('Conectado!')
print("IP:",sta_if.ifconfig()[0])

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', 8080))
server_socket.listen(10)

print("Esperando conexiones...")

while True:

    client_socket, client_address = server_socket.accept()
    print("Conexión establecida desde:", client_address)

    data = client_socket.recv(1024)
    print("Datos recibidos:", data.decode())

    if b'led=on' in data:
        led.on()
    if b'led=off' in data:
        led.off()
    if b'led2=on' in data:
        led2.on()
    if b'led2=off' in data:
        led2.off()
    if b'led3=on' in data:
        led3.on()
    if b'led3=off' in data:
        led3.off()
    if b'led4=on' in data:
        led4.on()
    if b'led4=off' in data:
        led4.off()
    if b'led5=on' in data:
        while (True):
            led.on ()
            sleep (0.1)
            led.off ()
            sleep (0.1)
            led2.on ()
            sleep (0.1)
            led2.off ()
            sleep (0.1)
            led3.on ()
            sleep (0.1)
            led3.off ()
            sleep (0.1)
            led4.on ()
            sleep (0.1)
            led4.off ()
            sleep (0.1)

    response = """HTTP/1.1 200 OK
    Content-Type: text/html

        <title>Servidor MicroPython</title>

Servidor Micropython Arduino Nano de Irving

    """
    client_socket.sendall(response.encode())
    client_socket.close()


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

def plot_categorical(df, feats, target):
    for column in feats:
        data = df.loc[df[column].notnull(), :]
        fig = plt.figure(figsize=(18, 12))
        ax = sns.countplot(x=column, hue=target, data=data, ax = plt.subplot(211));
        plt.xlabel(column, fontsize=14);
        plt.ylabel('Number of occurrences', fontsize=14);
        plt.suptitle('Plots for '+column, fontsize=18);
        plt.legend(loc=1);
        # Adding percents over bars
        height = [p.get_height() for p in ax.patches]
        height = [x if not pd.isnull(x) else 0 for x in height]  # fix bug
        ncol = int(len(height)/2)
        total = [height[i] + height[i + ncol] for i in range(ncol)] * 2
        for i, p in enumerate(ax.patches):
            ax.text(p.get_x()+p.get_width()/2, height[i]*1.01 + 10,
                    '{:1.0%}'.format(height[i]/total[i]), ha="center", size=14);
        sns.pointplot(x=column, y='label', data=data, ax = plt.subplot(212));
        plt.xlabel(column, fontsize=14);
        plt.ylabel('High-income Percentage', fontsize=14);
        plt.show()
    pass;

def plot_numeric(df, feats, target):
    for column in feats:
        fig = plt.figure(figsize=(18, 12))
        sns.distplot(df[column].dropna(), ax=plt.subplot(221));
        plt.xlabel(column, fontsize=14);
        plt.ylabel('Density', fontsize=14);
        plt.suptitle('Plots for '+column, fontsize=18);
        sns.distplot(df.loc[df.label==0, column].dropna(),
                     color='red', label='low-income', ax=plt.subplot(222));
        sns.distplot(df.loc[df.label==1, column].dropna(),
                     color='blue', label='high-income', ax=plt.subplot(222));
        plt.legend(loc='best')
        plt.xlabel(column, fontsize=14);
        plt.ylabel('Density high-income / low-income', fontsize=14);

        sns.barplot(x=target, y=column, data=df, ax=plt.subplot(223));
        plt.xlabel('Income >50k or not ?', fontsize=14);
        plt.ylabel('Average ' + column, fontsize=14);

        # Box plot of Column per label / Not label Value
        sns.boxplot(x=target, y=column, data=df, ax=plt.subplot(224));
        plt.xlabel('label==1', fontsize=14);
        plt.ylabel(column, fontsize=14);
        plt.show()
    pass;


import pandas as pd
from scipy.stats import ttest_ind, wilcoxon

NMKS = ((5, 25, 2), (5, 25, 3), (5, 25, 5), (5, 25, 10), (20, 50, 2), (20, 50, 3), (20, 50, 5), (20, 50, 10))

def two_sample_t_test(strategy1, strategy2, n=25, m=50, k=3, test=ttest_ind, one_sided=True):
    scores1 = pd.read_csv(f"data/{n}_{m}_{k}_{strategy1}.csv")["score"].tolist()[-500:]
    scores2 = pd.read_csv(f"data/{n}_{m}_{k}_{strategy2}.csv")["score"].tolist()[-500:]
    try:
        test_result = test(scores1, scores2, equal_var=False)
    except:
        test_result = test(scores1, scores2)
    statistic = test_result.statistic
    p_value = test_result.pvalue / 2 if one_sided else test_result.pvalue
    return p_value, statistic

def compare_strategies(strategy1, strategy2, nmks=NMKS, exclude_n=[], exlclude_m=[], exclude_k=[]):
    for n, m, k in nmks:
        if n in exclude_n or m in exlclude_m or k in exclude_k:
            continue
        p_value, t_statistic = two_sample_t_test(strategy1, strategy2, n=n, m=m, k=k, test=wilcoxon)
        print(f"better={strategy1}, worse={strategy2}, n={n}, m={m}, k={k}, p_value={p_value}, t_statistic={t_statistic}")

if __name__ == "__main__":
    compare_strategies("dqn", "threshold", exclude_k=[2])
    compare_strategies("quantile", "dqn", exclude_k=[2])
    compare_strategies("local_reward_optimiser", "dqn", exclude_k=[2])


import logging
import traceback
from flask import redirect

import flask
from replit import db

app = flask.Flask(__name__)

@app.errorhandler(500)
def internal_server_error(e: str):
    return flask.jsonify(error=str(e)), 500

@app.route('/', methods=['GET', 'POST'])
def cadastroContatos():
  try:
    contatos = db.get('contatos', {});
    print(contatos);
    if flask.request.method == "POST":
      contatos[flask.request.form['email']] = {'nome': flask.request.form['nome'], 'telefone': flask.request.form['telefone'],'assunto': flask.request.form['assunto'], 'mensagem': flask.request.form['mensagem'],'re': flask.request.form['re']}
    db['contatos'] = contatos
    return flask.render_template('contatos.html', contatos=contatos)
  except Exception as e:
    logging.exception('failed to database')
    flask.abort(500, description=str(e) + ': ' + traceback.format_exc())

@app.route('/limparBanco', methods=['POST'])
def limparBanco():
  try:
    del db["contatos"];
    return flask.render_template('contatos.html')
  except Exception as e:
    logging.exception(e)
    return flask.render_template('contatos.html')

@app.route('/deletarContato/<email>', methods=['POST'])
def deletarContato(email):
    try:
      contatos = db.get('contatos', {});
      del contatos[email];
      db['contatos'] = contatos;
      return redirect('/');
    except Exception as e:
      logging.exception(e);
      return flask.render_template('contatos.html');

app.run('0.0.0.0')


"""
1463. 1로 만들기
https://www.acmicpc.net/problem/1463
"""

def making_one(N):
    M = []
    M.append(0)
    M.append(0)
    curr = 2
    while curr <= N:
        # print(curr)
        if curr % 3 == 0:
            temp = min(M[curr//3], M[curr-1])
            if curr % 2 == 0:
                temp = min(temp, M[curr//2])
            M.append(temp+1)

        else:
            if curr % 2 == 0:
                M.append(min(M[curr-1], M[curr//2])+1)
            else:
                temp = min(M[(curr - 1) // 2], M[curr - 2])
                if (curr-1) % 3 == 0:
                    temp = min(temp, M[(curr-1)//3])
                M.append(temp+2)

        curr += 1

    # for i in range(N):
    #      print(i+1, M[i+1])

    return M[-1]

if __name__ == '__main__':
    N = int(input())
    result = making_one(N)
    print(result)


from flask import Flask
import secret
import config
from models.base_model import db

from routes.index import main as index_routes
from routes.topic import main as topic_routes
from routes.reply import main as reply_routes
from routes.board import main as board_routes
from routes.message import main as mail_routes, mail

from utils import format_time

def configured_app():
    app = Flask(__name__)
    # 设置 secret_key 来使用 flask 自带的 session
    app.secret_key = secret.secret_key

    uri = 'mysql+pymysql://root:{}@localhost/belife?charset=utf8mb4'.format(
        secret.database_password
    )
    # 用于连接数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = uri
    # 如果设置成True(默认)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # 初始化数据库
    db.init_app(app)

    # 自定义过滤器
    app.template_filter()(format_time)

    # flask-mail扩展发送电子邮件
    app.config['MAIL_SERVER'] = 'smtp.exmail.qq.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USE_SSL'] = True
    app.config['MAIL_USERNAME'] = config.admin_mail
    app.config['MAIL_PASSWORD'] = secret.mail_password
    mail.init_app(app)

    register_routes(app)
    return app

def register_routes(app):
    """
    蓝图（Blueprints）
    """
    app.register_blueprint(index_routes)
    app.register_blueprint(topic_routes, url_prefix='/topic')
    app.register_blueprint(reply_routes, url_prefix='/reply')
    app.register_blueprint(board_routes, url_prefix='/board')
    app.register_blueprint(mail_routes, url_prefix='/mail')

if __name__ == '__main__':
    app = configured_app()
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.jinja_env.auto_reload = True
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
    config = dict(
        debug=True,
        host='localhost',
        port=2000,
        threaded=True,
    )
    app.run(**config)


from selenium import webdriver
from time import sleep
# 导入动作链对应的类
from selenium.webdriver import ActionChains

bro = webdriver.Chrome(executable_path='chromedriver')

bro.get('https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')

'''
# 先定位要拖动的小方块
div = bro.find_element_by_id('draggable')
print(div)
# 但这样就会报错了，报错原因是定位不到标签，这是因为现在的这一块包含在iframe子页面中
# 如果定位的标签是存在iframe标签中，必须通过以下操作进行标签定位
'''

# 切换浏览器标签定位的作用域
bro.switch_to.frame('iframeResult')  # 传iframe的id
div = bro.find_element_by_id('draggable')

# 动作链：长按并拖动拖动
action = ActionChains(bro)  # 实例化对象
action.click_and_hold(div)  # 点击长按指定标签

# 拖动
for i in range(5):
    # move_by_offset(x, y):x水平方向，竖直方向
    action.move_by_offset(17, 0).perform()  # perform() 立即执行
    sleep(0.3)

# 释放动作链接
action.release()

bro.quit()