# ADC FPGA FIFO
SIS3316_FPGA_ADC_GRP_REG_BASE = 0x1000
SIS3316_FPGA_ADC_GRP_REG_OFFSET = 0x1000
SIS3316_FPGA_ADC_GRP_MEM_BASE = 0x100000
SIS3316_FPGA_ADC_GRP_MEM_OFFSET = 0x100000
VME_READ_LIMIT = 64  # (32-bit) words
VME_WRITE_LIMIT = 64  # (32-bit) words
FIFO_READ_LIMIT = int(0x40000/4)  # bytes-> (32-bit) words
FIFO_WRITE_LIMIT = 256	 # (32-bit) words

# SIS3316 Specific Hardware
MEM_BANK_SIZE = 0x4000000  # 64MB
MEM_BANK_COUNT = 2
CHAN_GRP_COUNT = 4
CHAN_PER_GRP   = 4
CHAN_MASK  = CHAN_PER_GRP - 1  # 0b11
CHAN_TOTAL = CHAN_PER_GRP * CHAN_GRP_COUNT  # 16

# Truly Random Struck Decision
TRIG_THRESHOLD_OFFSET = 0x8000000  # For triggering purposes the trigger value + this number is compared to trap. filter


#Write a program to count the frequecy of characters in the given file. Can you use character frequency to tell wheather the given file is Python file,
# C File or a text file?
a= open("exp1.txt","r")
b=a.read()
c=0
for i in b:
    c=c+1
print(c)
a.close()

f= open("exp1.txt","r")
g=f.read()
if g.find("python")!=-1:
    print("Python file")
elif g.find("c")!=-1:
    print("C file")
else:
    print("Text file")
f.close()


# -*- coding: utf-8 -*-
import socket
import json
from MessageReceiver import MessageReceiver
from MessageParser import MessageParser

class Client:
    """
    This is the chat client class
    """
    def __init__(self, host, server_port):
        """
        This method is run when creating a new Client object
        """

        # Set up the socket connection to the server
        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_port = server_port
        self.host = host
        self.run()

    def run(self):
        # Initiate the connection to the server
        self.connection.connect((self.host, self.server_port))

        MessageReceiver(self, self.connection)

        login_username = input("Login username: ")
        self.login(login_username)

        while True:
            message = input("> ")
            msg = message.split()
            self.create_request(msg[0], ' '.join(msg[1:]))

    def disconnect(self):
        self.connection.close()
        exit(0)

    def receive_message(self, message):
        message = message.decode()
        # print("<-- " + message)
        parser = MessageParser()
        result = parser.parse(message)
        if result is False:
            self.disconnect()

    def send_payload(self, data):
        data = json.dumps(data)

        self.connection.send(data.encode())
        # print("--> " + data)

        # More methods may be needed!

    def help(self):
        self.create_request('help')

    def login(self, username):
        self.create_request('login', username)
        self.username = username

    def logout(self):
        self.create_request('logout', self.username)

    def send_message(self, message):
        self.create_request('msg', message)

    def create_request(self, request, content=None):
        if not content:
            content = ''
        payload = {
            'request': request,
            'content': content,
        }
        self.send_payload(payload)

if __name__ == '__main__':
    """
    This is the main method and is executed when you type "python Client.py"
    in your terminal.

    No alterations are necessary
    """
    client = Client('localhost', 9998)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import OrderedDict
import io
import os
from editolido.constants import PINS, GOOGLE_ICONS, PIN_NONE

try:
    # noinspection PyUnresolvedReferences
    integer_types = (int, long,)
except NameError:
    integer_types = (int,)

default_linestyle = """
    <Style id='{0}'>
        <LineStyle>
            <width>6</width>
            <color>{{{0}_color}}</color>
        </LineStyle>
    </Style>
"""
default_iconstyle = """
    <Style id='{0}'>
        <IconStyle>
            <Icon>
                <href><![CDATA[{1}]]></href>
            </Icon>
            <hotSpot x="0.5"  y="0.0" xunits="fraction" yunits="fraction"/>
        </IconStyle>
    </Style>
"""

class KMLGenerator(object):
    def __init__(self, template=None, point_template=None, line_template=None,
                 folder_template=None, style_template=default_linestyle,
                 icon_template=default_iconstyle, segment_template=None,
                 icons=GOOGLE_ICONS):
        datadir = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'data')

        def read_template(name):
            with io.open(os.path.join(datadir, name),
                         encoding='utf-8') as f:
                return f.read()

        self.template = (template
                         or read_template('mapsme_template.kml'))
        self.point_template = (point_template
                               or read_template('mapsme_point_tpl.kml'))
        self.line_template = (line_template
                              or read_template('mapsme_line_tpl.kml'))
        self.folder_template = (folder_template
                                or read_template('mapsme_folder_tpl.kml'))
        self.segment_template = (segment_template
                                 or read_template('mapsme_segment_tpl.kml'))
        self.style_template = style_template
        self.icon_template = icon_template
        self.folders = OrderedDict()
        self.styles = OrderedDict()
        self.folder_styles = OrderedDict()
        self.icons = icons
        self.pin_styles = []  # pin style register to avoid duplicates

    @staticmethod
    def escape(text):
        text = text.replace("<", "<")
        text = text.replace(">", ">")
        text = text.replace("&", "&")
        text = text.replace("\"", """)
        return text

    def add_folder(self, name, pin=PIN_NONE):
        """
        Add a folder and a style to the kml
        If there is no pin you must specify style for points added into
        that folder
        :param name: the folder name
        :param pin: a default pin for points in the folder
        """
        self.folders[name] = []
        style = self.style_template.format(name)
        if pin != PIN_NONE and PINS[pin] not in self.pin_styles:
            style += self.icon_template.format(PINS[pin][1:], self.icons[pin])
            self.pin_styles.append(PINS[pin])
        self.styles[name] = style
        self.folder_styles[name] = PINS[pin]

    def add_folders(self, *values):
        for value in values:
            try:
                name, pin = value
            except ValueError:
                name = value
                pin = PIN_NONE
            self.add_folder(name, pin)

    @staticmethod
    def _update_kwargs(folder, kwargs):
        """
        Apply style value based on context
        - if style is not set, uses folder name
        - if style is integer, replace with the style's name
        :param folder: str
        :param kwargs: list
        """
        style = kwargs.get('style', None)
        if style is None:
            kwargs['style'] = '#' + folder
        elif isinstance(style, integer_types):
            kwargs['style'] = PINS[style]

    def add_line(self, folder, route, **kwargs):
        """
        Add a route as a LineString in the .kml
        :param folder: folder name
        :param route: Route
        :param kwargs: optional args passed to the renderer
        """
        self._update_kwargs(folder, kwargs)
        coordinates = []
        for p in route:
            coordinates.append(
                "{lng:.6f},{lat:.6f}".format(lat=p.latitude, lng=p.longitude))
        variables = dict(
            name=route.name or '',
            description=route.description or '')
        variables.update(kwargs)
        self.folders[folder].append(self.line_template.format(
            coordinates=' '.join(coordinates),
            **variables))

    def add_points(self, folder, route, excluded=None, **kwargs):
        """
        Add a route as a Points in the .kml
        :param folder: folder name
        :param route: Route
        :param excluded: list of GeoPoint to exclude from rendering
        :param kwargs: optional args passed to the renderer

        If folder does not have a pin set, points must define style kwargs
        otherwise nothing is added
        """
        self._update_kwargs(folder, kwargs)
        excluded = excluded or []
        for geopoint in route:
            if geopoint not in excluded:
                self.add_point(folder, geopoint, **kwargs)

    def add_point(self, folder, geopoint, **kwargs):
        """
        Add a GeoPoint in the .kml
        :param folder: folder name
        :param geopoint: GeoPoint
        :param kwargs: optional args passed to the renderer

        If folder does not have a pin set, point must define style kwargs
        otherwise nothing is added
        """
        kwargs.setdefault('style', self.folder_styles[folder])
        self._update_kwargs(folder, kwargs)
        if kwargs['style'] != PINS[PIN_NONE]:
            coordinates = "{lng:.6f},{lat:.6f}".format(
                lat=geopoint.latitude, lng=geopoint.longitude)
            variables = dict(
                name=geopoint.name or geopoint.dm,
                description=geopoint.description or '')
            variables.update(kwargs)
            self.folders[folder].append(self.point_template.format(
                coordinates=coordinates,
                **variables))

    def add_segments(self, folder, route, **kwargs):
        """
        Add a route as LineString segments in the .kml
        :param folder: folder name
        :param route: Route
        :param kwargs: optional args passed to the renderer
        """
        self._update_kwargs(folder, kwargs)
        for p1, p2 in route.segments:
            coordinates = "{p1.longitude:.6f},{p1.latitude:.6f} " \
                          "{p2.longitude:.6f},{p2.latitude:.6f}".format(
                              p1=p1, p2=p2)
            variables = dict(
                name="{label}: {p1}->{p2}".format(
                    label=route.name or folder,
                    p1=p1.name or p1.dm,
                    p2=p2.name or p2.dm))
            variables.update(kwargs)
            self.folders[folder].append(self.segment_template.format(
                coordinates=coordinates,
                **variables))

    def render(self, **kwargs):
        """
        Render the full .kml
        :param kwargs:
        :return: unicode
        """
        return self.template.format(
            styles=''.join(self.styles.values()).format(**kwargs),
            folders=self.render_folders(),
            **kwargs
        )

    def render_folder(self, folder):
        """
        Render a folder content
        :param folder:
        :return: str
        """
        return self.folder_template.format(
            name=folder,
            open=1,
            content='\n'.join(self.folders[folder]),
        )

    def render_folders(self):
        """
        Render all folders
        :return: str
        """
        return '\n'.join(
            [self.render_folder(folder) for folder in self.folders])


import csv
import numpy as np
from sklearn.metrics import confusion_matrix

np.set_printoptions(precision=4)

# Abrir o arquivo CSV e ler os dados
with open('caracteres-Fausett/limpo_e_ruido1.csv', 'r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    data = list(reader)

# Converter a lista em um numpy array
data_array = np.array(data).astype(int)

with open('caracteres-Fausett/customRuido2.csv', 'r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    data = list(reader)

teste_array = np.array(data).astype(int)

def get_letra(array):
    """
    Converte o vetor em letra
    """
    # Verificar a proximidade de cada valor com 0 ou 1
    entrada = [round(val, 3) for val in array]
    linha = []

    for val in entrada:
        if val < 0.2 or val > 0.8:
            linha.append(round(val))
        else:
            linha.append(val)

    # Classificar em letras de acordo com os valores do vetor
    if linha == [1, 0, 0, 0, 0, 0, 0]:
        return "A"
    elif linha == [0, 1, 0, 0, 0, 0, 0]:
        return "B"
    elif linha == [0, 0, 1, 0, 0, 0, 0]:
        return "C"
    elif linha == [0, 0, 0, 1, 0, 0, 0]:
        return "D"
    elif linha == [0, 0, 0, 0, 1, 0, 0]:
        return "E"
    elif linha == [0, 0, 0, 0, 0, 1, 0]:
        return "J"
    elif linha == [0, 0, 0, 0, 0, 0, 1]:
        return "K"
    else:
        return "Desconhecido"

# Separar as primeiras 63 colunas em um array (Entrada)
X = data_array[:, :63]

# Separar as 7 últimas colunas em um array separado (Saída esperada)
Y = data_array[:, 63:]

Xteste = teste_array[:, :63]
Yteste = teste_array[:, 63:]

def sigmoid(x):
    """
    Define a função de ativacao sigmoide
    """
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x):
    """
    Define a função de derivada da sigmoide
    """
    return x * (1 - x)

# Define o número de iterações de treinamento
EPOCAS = 20000

# Define a taxa de aprendizagem
TAXA_APRENDIZADO = 0.1

# Define o número de neurônios na camada escondida
NUM_NEURONIOS_CAMADA_ESCONDIDA = 18

# Dividir os dados em k-folds para validação cruzada
k = 5  # número de folds
tamanho_fold = X.shape[0] // k

# Inicializar variáveis para controle da parada antecipada
TOLERANCIA_PERDA = 100
melhor_valor_perda = np.inf
epocas_consecutivas_sem_melhora = 0

# Escrever os hiperparametros em um arquivo de texto
with open('hiperparametrosMlpVal.txt', 'w') as file:
    file.write("Hiperparametros: \n")
    file.write("    Epocas: {} \n".format(EPOCAS))
    file.write("    Taxa de aprendizado: {} \n".format(TAXA_APRENDIZADO))
    file.write("    Neurônios na camada escondida: {} \n".format(NUM_NEURONIOS_CAMADA_ESCONDIDA))
    file.write("    Quantidade de folds: {} \n".format(k))
    file.write("    Tolerancia de perda: {} \n".format(TOLERANCIA_PERDA))

# Inicializa os pesos aleatoriamente
pesos1 = np.random.random((X.shape[1], NUM_NEURONIOS_CAMADA_ESCONDIDA))
pesos2 = np.random.random((NUM_NEURONIOS_CAMADA_ESCONDIDA, Y.shape[1]))

# Escrever os pesos iniciais em um arquivo de texto
np.savetxt("pesos1IniciaisMlpVal.txt", pesos1, delimiter=',', fmt='%.3f')
np.savetxt("pesos2IniciaisMlpVal.txt", pesos2, delimiter=',', fmt='%.3f')

# Escrever os erros em um arquivo de texto
with open('errosMlpVal.txt', 'w') as file:
    # Loop de treinamento com validação cruzada
    for fold in range(k):
        # Separar os dados em fold de validação e fold de treinamento
        stop_range = ((fold + 1) * tamanho_fold) - 1
        if(stop_range > X.shape[0]):
            stop_range = X.shape[0]

        indices_validacao = range(fold * tamanho_fold, stop_range)
        indices_treinamento = np.setdiff1d(range(0, X.shape[0]), indices_validacao)

        X_treino, X_validacao = X[indices_treinamento, :], X[indices_validacao, :]
        Y_treino, Y_validacao = Y[indices_treinamento, :], Y[indices_validacao, :]

        # Loop de treinamento
        for i in range(EPOCAS):
            if(i % 1000 == 0):
                print("Iteracao {}".format(i))

            # Forward pass
            layer1_output = sigmoid(np.dot(X, pesos1))
            layer2_output = sigmoid(np.dot(layer1_output, pesos2))

            # Calcula o erro na camada de saída
            layer2_error = Y - layer2_output

            file.write("Iteracao {} -> Valor erro: {} \n".format(i, layer2_error))

            # Calcular a perda no conjunto de treinamento
            perda_no_treinamento = np.mean(np.square(Y - layer2_output))

            # Calcular a perda no conjunto de validação
            layer1_output_val = sigmoid(np.dot(X_validacao, pesos1))
            layer2_output_val = sigmoid(np.dot(layer1_output_val, pesos2))
            valor_perda = np.mean(np.square(Y_validacao - layer2_output_val))

            # Verificar se houve melhora na perda de validação
            if valor_perda < melhor_valor_perda:
                melhor_valor_perda = valor_perda
                epocas_consecutivas_sem_melhora = 0
            else:
                epocas_consecutivas_sem_melhora += 1

            # Verificar se o treinamento deve ser interrompido
            if epocas_consecutivas_sem_melhora >= TOLERANCIA_PERDA:
                epocas_consecutivas_sem_melhora = 0
                print("Treinamento interrompido devido à falta de melhora na perda de validação. Época {}, Fold {}".format(i+1, fold+1))
                file.write("Treinamento interrompido devido à falta de melhora na perda de validação. Época {}, Fold {} \n".format(i+1, fold+1))
                break

            # Calcula o gradiente descendente na camada de saída
            layer2_gradient = layer2_error * sigmoid_derivative(layer2_output)

            # Calcula o erro na camada oculta
            layer1_error = layer2_gradient.dot(pesos2.T)

            # Calcula o gradiente descendente na camada oculta
            layer1_gradient = layer1_error * sigmoid_derivative(layer1_output)

            # Atualiza os pesos
            pesos2 += TAXA_APRENDIZADO * layer1_output.T.dot(layer2_gradient)
            pesos1 += TAXA_APRENDIZADO * X.T.dot(layer1_gradient)

# Escrever os pesos finais em um arquivo de texto
np.savetxt("pesos1FinaisMlpVal.txt", pesos1, delimiter=',', fmt='%.3f')
np.savetxt("pesos2FinaisMlpVal.txt", pesos2, delimiter=',', fmt='%.3f')

# Testa o modelo treinado
layer1_output = sigmoid(np.dot(Xteste, pesos1))
output = sigmoid(np.dot(layer1_output, pesos2))

#Variáveis para criar matriz de confusão
array_esperado = np.array([])
array_previsto = np.array([])

# Escrever os pesos finais em um arquivo de texto
with open('saidaMlpVal.txt', 'w') as file:
    print()
    for i in range(Xteste.shape[0]):
        valorEsperado = get_letra(Yteste[i, :])
        valorPrevisto = get_letra(output[i, :])
        array_esperado = np.append(array_esperado, valorEsperado)
        array_previsto = np.append(array_previsto, valorPrevisto)
        print("Linha {}: Letra esperada[{}], Letra prevista: [{}]".format(i+1, valorEsperado, valorPrevisto))
        # Usando uma compreensão de lista para formatar os floats
        outtput_formatado = ["{:.5f}".format(num) for num in output[i, :]]
        file.write("Linha {}: Letra esperada[{}], Letra prevista: [{}], Valor Previsto: [{}] \n".format(i+1, valorEsperado, valorPrevisto, outtput_formatado))
        print()

# Calcular a matriz de confusão
matriz = confusion_matrix(array_esperado, array_previsto)

print(matriz)


import os
import time

import numpy as np
import pandas as pd
import torch
from matplotlib import pyplot as plt
from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler
from statsmodels.graphics.tsaplots import plot_acf
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm

from models.autoscaler.bht_arima import BHTARIMA
from models.autoscaler.dlinear import Parameters, create_dataset, Data, Model, device, EarlyStopping, LRScheduler, \
    RegressionEvaluation
from models.autoscaler.lstm_v2 import LstmParam, LstmNetwork, ToyLossLayer
from models.utils.tools import get_one_machine

def run_lstm_v2(X, y):
    """加了差分模块的 LSTM 算法"""

    # 正则化数据
    ss = StandardScaler()
    std_X = ss.fit_transform(X)
    std_y = ss.fit_transform(y)

    # (1) 初始化 LSTM 模型
    lstm_param = LstmParam(mem_cell_ct=128, x_dim=X.shape[1])
    lstm_net = LstmNetwork(lstm_param)

    # 打印一些有用调试信息
    # print('X.shape = ', X.shape)
    # print('y.shape = ', y.shape)

    # (2) 训练 LSTM 模型
    for epoch in range(5000):
        # print("iter", "%2s" % str(epoch), end=": ")
        for i in range(len(std_y)):
            lstm_net.x_list_add(std_X[i])

        # (3) 预测和计算损失
        # print("y_pred = [" +
        #       ", ".join(["% 2.5f"
        #                  % ss.inverse_transform(lstm_net.lstm_node_list[i].state.h[0].reshape(1, -1))
        #                  for i in range(len(std_y))]) +
        #       "]", end=", ")
        loss = lstm_net.y_list_is(std_y, ToyLossLayer)  # 计算损失
        # print("loss:", "%.3e" % loss)

        # (4) 更新模型
        lstm_param.apply_diff(lr=0.01)
        lstm_net.x_list_clear()  # 清理掉原来的参数

    # (5) 数据后处理：还原 y
    # origin_y = ss.inverse_transform(std_y)
    y_hat = (np.zeros_like(std_y)).reshape(-1)
    for i in range(len(std_y)):
        pred = ss.inverse_transform(lstm_net.lstm_node_list[i].state.h[0].reshape(1, -1))
        y_hat[i] = pred[0]

    return y_hat

def run_bht_arima(X, y):
    """调用 BHT ARIMA 算法（单步预测）"""

    # 正则化数据
    # ss = MinMaxScaler()  # SVD 默认包含正则化：https://stackoverflow.com/a/46025739/16733647
    # std_X = ss.fit_transform(X)
    # std_y = ss.fit_transform(y)

    # parameters setting
    n_samples = X.shape[0]

    # print('y = ', y)
    p = 3  # p-order
    d = 2  # d-order
    q = 1  # q-order
    taus = [n_samples, 5]  # MDT-rank
    Rs = [5, 5]  # tucker decomposition ranks
    epochs = 5000  # iterations
    tol = 0.001  # stop criterion
    Us_mode = 4  # orthogonality mode

    # Run program
    # result's shape: (ITEM, TIME+1) ** only one step forecasting **
    model = BHTARIMA(X, p, d, q, taus, Rs, epochs, tol, verbose=0, Us_mode=Us_mode)
    pred, _ = model.run()
    y_hat = pred[..., -1]

    return y_hat

def call_dlinear(column_name, machine_idx):
    args = Parameters(column_name)

    start = time.time()
    # Load data
    df = pd.read_csv(args.filename)
    print('[INFO] Data imported')
    print('[INFO] Time: %.2f seconds' % (time.time() - start))

    # (1) 每次从文件中读取一个 task 的资源需求变化
    machine, next_idx = get_one_machine(df, machine_idx)
    print(machine)
    machine_name = machine['machine_id'].loc[machine.index[0]]
    print(machine_name)

    # # Convert Date to 'datetime64'
    # df['Date'] = df['Date'].astype('datetime64')
    # # Set index
    # df.set_index('Date', inplace=True)
    # Keep only selected time-series
    df = pd.DataFrame(machine[[args.targetSeries]])

    # Split Training / Testing
    idx = int(df.shape[0] * args.TrainingSetPercentage)
    df_train = df[:idx].dropna()
    df_test = df[idx:].dropna()

    # Visualization
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 3))

    df_train[args.targetSeries].plot(ax=ax, color='tab:blue')
    df_test[args.targetSeries].plot(ax=ax, color='tab:orange')

    plt.legend(['Training', 'Testing'], frameon=False, fontsize=14)
    plt.ylabel(args.targetSeries, size=14)
    plt.xlabel('Date', size=14)
    plt.xticks(size=12)
    plt.yticks(size=12)
    plt.show()

    # Fixing lag
    df_test = pd.concat([df_train.iloc[-args.Lag:], df_test])

    # Data Transformation
    if args.Transformation == True:

        print('[INFO] Data transformation applied')

        VALUE = np.ceil(max(abs(-df.min().min()), 1.0))

        df_train = np.log(df_train + VALUE)
        df_test = np.log(df_test + VALUE)

    else:
        print('[INFO] No data transformation applied.')

    if args.Scaling == 'MinMax':
        print('[INFO] Scaling: MinMax')

        for feature in df.columns:
            if feature == args.targetSeries:
                continue
            print('Feature: ', feature)
            # Set scaler
            #
            scaler = MinMaxScaler()

            df_train[feature] = scaler.fit_transform(df_train[feature].to_numpy().reshape(-1, 1))
            df_test[feature] = scaler.transform(df_test[feature].to_numpy().reshape(-1, 1))

        # Scaling of Target Series
        #
        scaler = MinMaxScaler()
        df_train[args.targetSeries] = scaler.fit_transform(df_train[args.targetSeries].to_numpy().reshape(-1, 1))
        df_test[args.targetSeries] = scaler.transform(df_test[args.targetSeries].to_numpy().reshape(-1, 1))

    elif args.Scaling == 'Robust':
        print('[INFO] Scaling: Robust')

        for feature in df.columns:
            if feature == args.targetSeries:
                continue
            print('Feature: ', feature)
            # Set scaler
            #
            scaler = RobustScaler()

            df_train[feature] = scaler.fit_transform(df_train[feature].to_numpy().reshape(-1, 1))
            df_test[feature] = scaler.transform(df_test[feature].to_numpy().reshape(-1, 1))

        # Scaling of Target Series
        #
        scaler = RobustScaler()
        df_train[args.targetSeries] = scaler.fit_transform(df_train[args.targetSeries].to_numpy().reshape(-1, 1))
        df_test[args.targetSeries] = scaler.transform(df_test[args.targetSeries].to_numpy().reshape(-1, 1))

    elif args.Scaling == 'Standard':
        print('[INFO] Scaling: Standard')

        for feature in df.columns:
            if feature == args.targetSeries:
                continue
            print('Feature: ', feature)
            # Set scaler
            #
            scaler = StandardScaler()

            df_train[feature] = scaler.fit_transform(df_train[feature].to_numpy().reshape(-1, 1))
            df_test[feature] = scaler.transform(df_test[feature].to_numpy().reshape(-1, 1))

        # Scaling of Target Series
        #
        scaler = StandardScaler()

        df_train[args.targetSeries] = scaler.fit_transform(df_train[args.targetSeries].to_numpy().reshape(-1, 1))
        df_test[args.targetSeries] = scaler.transform(df_test[args.targetSeries].to_numpy().reshape(-1, 1))
    else:
        print('[WARNING] Unknown data scaling. Standard scaling was selected')

        for feature in df.columns:
            if feature == args.targetSeries:
                continue
            print('Feature: ', feature)
            # Set scaler
            #
            scaler = StandardScaler()

            df_train[feature] = scaler.fit_transform(df_train[feature].to_numpy().reshape(-1, 1))
            df_test[feature] = scaler.transform(df_test[feature].to_numpy().reshape(-1, 1))

        # Scaling of Target Series
        #
        scaler = StandardScaler()

        df_train[args.targetSeries] = scaler.fit_transform(df_train[args.targetSeries].to_numpy().reshape(-1, 1))
        df_test[args.targetSeries] = scaler.transform(df_test[args.targetSeries].to_numpy().reshape(-1, 1))

    trainX, trainY, _ = create_dataset(df=df_train,
                                       Lag=args.Lag,
                                       Horizon=args.Horizon,
                                       targetSeries=args.targetSeries,
                                       overlap=1, )

    testX, testY, testDate = create_dataset(df=df_test,
                                            Lag=args.Lag,
                                            Horizon=args.Horizon,
                                            targetSeries=args.targetSeries,
                                            overlap=1, )

    # Last 10% of the training data will be used for validation
    idx = int(0.9 * trainX.shape[0])
    validX, validY = trainX[idx:], trainY[idx:]
    trainX, trainY = trainX[:idx], trainY[:idx]
    print('Training data shape:   ', trainX.shape, trainY.shape)
    print('Validation data shape: ', validX.shape, validY.shape)
    print('Testing data shape:    ', testX.shape, testY.shape)

    # Reshaping
    trainY = np.expand_dims(trainY, axis=-1)
    validY = np.expand_dims(validY, axis=-1)
    testY = np.expand_dims(testY, axis=-1)

    # Create training and test dataloaders
    #
    train_ds = Data(trainX, trainY)
    valid_ds = Data(validX, validY)
    test_ds = Data(testX, testY)

    # Prepare Data-Loaders
    #
    train_dl = DataLoader(train_ds, batch_size=args.batch_size, num_workers=args.num_workers)
    valid_dl = DataLoader(valid_ds, batch_size=args.batch_size, num_workers=args.num_workers)
    test_dl = DataLoader(test_ds, batch_size=args.batch_size, num_workers=args.num_workers)
    #
    print('[INFO] Data loaders were created')

    # Initialize Neural Network
    model = Model(args)
    model.to(device)
    print(model)

    # Specify loss function
    #
    criterion = nn.MSELoss()

    # Specify loss function
    #
    optimizer = torch.optim.Adam(params=model.parameters(),
                                 lr=args.learning_rate)

    # Early stopping
    early_stopping = EarlyStopping(patience=100, min_delta=1e-5)

    # LR scheduler
    scheduler = LRScheduler(optimizer=optimizer,
                            patience=50,
                            min_lr=1e-10,
                            factor=0.5,
                            verbose=args.verbose)

    # Store training and validation loss
    Loss = {'Train': [],
            'Valid': []
            }

    # Set number at how many iteration the training process (results) will be provided
    #
    batch_show = (train_dl.dataset.__len__() // args.batch_size)

    # Main loop - Training process
    #
    for epoch in range(1, args.epochs + 1):

        # Start timer
        start = time.time()

        # Monitor training loss
        #
        train_loss = 0.0
        valid_loss = 0.0

        ###################
        # Train the model #
        ###################
        batch_idx = 0
        for data, target in train_dl:

            # Clear the gradients of all optimized variables
            #
            optimizer.zero_grad()

            # Forward pass: compute predicted outputs by passing inputs to the model
            #
            if device.type == 'cpu':
                data = torch.tensor(data, dtype=torch.float32)
                target = torch.tensor(target, dtype=torch.float32)
            else:
                data = torch.tensor(data, dtype=torch.float32).cuda()
                target = torch.tensor(target, dtype=torch.float32).cuda()

            outputs = model(data)

            # Calculate the loss
            #
            loss = criterion(outputs, target)

            # Backward pass: compute gradient of the loss with respect to model parameters
            #
            loss.backward()

            # Perform a single optimization step (parameter update)
            #
            optimizer.step()

            # Update running training loss
            #
            train_loss += loss.item() * data.size(0)

            # Increase batch_idx
            #
            batch_idx += 1

            # # Info
            # #
            # if args.verbose == True and batch_idx % batch_show == 0:
            #     print('> Epoch: {} [{:5.0f}/{} ({:.0f}%)]'.format(epoch, batch_idx * len(data), len(train_dl.dataset),
            #                                                       100. * batch_idx / len(train_dl)))

        # Print avg training statistics
        train_loss = train_loss / train_dl.dataset.X.shape[0]

        with torch.no_grad():
            for data, target in valid_dl:

                # Forward pass: compute predicted outputs by passing inputs to the model
                #
                if device.type == 'cpu':
                    data = torch.tensor(data, dtype=torch.float32)
                    target = torch.tensor(target, dtype=torch.float32)
                else:
                    data = torch.tensor(data, dtype=torch.float32).cuda()
                    target = torch.tensor(target, dtype=torch.float32).cuda()

                outputs = model(data)

                # Calculate the loss
                #
                loss = criterion(outputs, target)

                # update running training loss
                valid_loss += loss.item() * data.size(0)

        # Print avg training statistics
        #
        valid_loss = valid_loss / test_dl.dataset.X.shape[0]

        # Stop timer
        #
        stop = time.time()

        # Show training results
        #
        print('\n[INFO] Train Loss: {:.6f}\tValid Loss: {:.6f} \tTime: {:.2f}secs'.format(train_loss, valid_loss,
                                                                                stop - start), end=' ')

        # Update best model
        if not os.path.exists(os.path.dirname(args.model_path)):
            os.makedirs(os.path.dirname(args.model_path))

        if epoch == 1:
            Best_score = valid_loss
            torch.save(model.state_dict(), args.model_path)
            print('(Model saved)\n')
        else:
            if Best_score > valid_loss:
                Best_score = valid_loss

                torch.save(model.state_dict(), args.model_path)
                print('(Model saved)\n')
            else:
                print('\n')

        # Store train/val loss
        #
        Loss['Train'] += [train_loss]
        Loss['Valid'] += [valid_loss]

        # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        # Learning rate scheduler
        #
        scheduler(valid_loss)

        # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        # Early Stopping
        #
        if early_stopping(valid_loss):
            break

    # Load best model
    model.load_state_dict(torch.load(args.model_path))
    model.eval()

    print('[INFO] Model loaded')

    pred = None
    with torch.no_grad():
        for data, target in tqdm(test_dl):

            data = torch.tensor(data, dtype=torch.float32)
            target = torch.tensor(target, dtype=torch.float32)

            if pred is None:
                pred = model(data).numpy()
            else:
                pred = np.concatenate([pred, model(data).numpy()])

    # Reshaping...
    #
    testY = testY.squeeze(-1)
    pred = pred.squeeze(-1)

    # Apply inverse scaling
    #
    for i in range(args.Horizon):
        testY[:, i] = scaler.inverse_transform(testY[:, i].reshape(-1, 1)).squeeze(-1)
        pred[:, i] = scaler.inverse_transform(pred[:, i].reshape(-1, 1)).squeeze(-1)

    # Apply inverse transformation
    #
    if args.Transformation == True:
        testY = np.exp(testY) - VALUE
        pred = np.exp(pred) - VALUE

    print('[INFO] Feature: ', args.targetSeries)
    print('------------------------------------------------')
    Performance_Foresting_Model = {'RMSE': [], 'MAE': [], 'SMAPE': [], 'R2': []}

    for i in range(args.Horizon):
        Prices = pd.DataFrame([])

        Prices[args.targetSeries] = testY[:, i]
        Prices['Prediction'] = pred[:, i]

        # Evaluation
        #
        MAE, RMSE, MAPE, SMAPE, R2 = RegressionEvaluation(Prices)

        # Store results
        #
        Performance_Foresting_Model['RMSE'] += [RMSE]
        Performance_Foresting_Model['MAE'] += [MAE]
        Performance_Foresting_Model['SMAPE'] += [SMAPE]
        Performance_Foresting_Model['R2'] += [R2]

        # Present results
        #
        print('Horizon: %2i MAE %5.2f RMSE %5.2f SMAPE: %5.2f R2: %.2f' % (i + 1, MAE, RMSE, SMAPE, R2))

    for i in range(args.Horizon):
        # Get actual values and predicted
        #
        Prices = pd.DataFrame([])

        Prices[args.targetSeries] = testY[:, i]
        Prices['Prediction'] = pred[:, i]

        # Calculate the residuals
        #
        res = (Prices[args.targetSeries] - Prices['Prediction']).to_numpy()

        # === Visualization ===
        #
        fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 2))

        # Plot residual histogram
        #
        ax[0].hist(res, bins=50)

        # Plot AutoCorrelation plot
        #
        plot_acf(res, ax=ax[1])
        ax[1].set_ylim([-1.05, 1.05])

    plt.figure()
    plt.plot(pred[:, 3], label='Pred.')
    plt.plot(testY[:, 3], label='True')
    plt.legend()
    plt.show()

    return pred[:, 3], testY[:, 3]

def run_dlinear(machine_idx):
    cpu_y_hat, cpu_y_test = call_dlinear('cpu_util_percent', machine_idx)
    mem_y_hat, mem_y_test = call_dlinear('mem_util_percent', machine_idx)
    y_hat = []
    y_test = []
    for i in range(0, len(cpu_y_hat)):
        y_hat.append([cpu_y_hat[i], mem_y_hat[i]])
        y_test.append([cpu_y_test[i], mem_y_test[i]])
    return np.array(y_hat), np.array(y_test)


"""
345. Reverse Vowels of a String
https://leetcode.com/problems/reverse-vowels-of-a-string/
Time Limit Exceeded

Runtime: 8760 ms
Memory Usage: 20.2 MB
https://leetcode.com/interview/1/
"""

class Solution:
    def reverseVowels(self, s: str) -> str:
        list_vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U', ]
        list_s = list(s)
        r_dict_s = Solution.get_r_dict_s(list_s, list_vowel)
        list_char_reversed_vowels = []
        position = 0
        for c in list_s:
            if c in list_vowel:
                list_char_reversed_vowels.append(list_s[r_dict_s[position]])
            else:
                list_char_reversed_vowels.append(c)
            position += 1
        return "".join(list_char_reversed_vowels)

    @staticmethod
    def get_r_dict_s(list_s: list, list_vowel: list):
        # set list_desc_key, dict_position
        dict_position = {}
        position = 0
        for c in list_s:
            if c in list_vowel:
                dict_position[position] = c
            position += 1
        list_desc_key = [sorted(dict_position, reverse=True)][0]
        # get r_dict_s
        position = 0
        r_dict_s = {}
        for key_desc in list_desc_key:
            key_r = list(dict_position)[position]
            r_dict_s[key_r] = key_desc
            position += 1
        return r_dict_s

s = Solution()
print('Example 1: Expected: "holle", Actual:', s.reverseVowels("hello"))
print('Example 2: Expected: "leotcede", Actual:', s.reverseVowels("leetcode"))
print('Test 1   : Expected: "Aa", Actual :', s.reverseVowels("aA"))


import torch
import torch.nn as nn

class LinearProjection(nn.Module):
    # 패치 리니어 프로젝션 -> 클래스토큰 붙이기 -> 포지셔널 임베딩
    def __init__(self, patch_vec_size, num_patches, latent_vec_dim, drop_rate):
        super().__init__()
        self.linear_proj = nn.Linear(patch_vec_size, latent_vec_dim)
        # (batch_size, 나눠진패치개수, p^2*c) -> (batch_size, 나눠진패치개수, d)
        # 나눠진패치개수 = img_size / patch_size

        self.cls_token = nn.Parameter(torch.randn(1, latent_vec_dim))
        # (1, d)짜리를 생성, 학습 가능해야하므로 Parameter로 정의함

        self.pos_embedding = nn.Parameter(torch.randn(1, num_patches+1, latent_vec_dim))
        # (1, 패치수+1, d), 얘도 학습 가능해야함, randn : 평균 0, 표준편차 1이 되도록 랜덤값 뽑고 훈련하면서 바뀜

        self.dropout = nn.Dropout(drop_rate)

    def forward(self, x):
        batch_size = x.size(0)
        x = torch.cat([self.cls_token.repeat(batch_size, 1, 1), self.linear_proj(x)], dim=1)
        # (1, d)짜리를 batch_size 만큼 repeat하여 맨 왼쪽에 붙임, cls: (batch_size, 1, d) 와 embedding(X): (batch_size, 패치수, d)를
        # dim = 1 -> 패치 수 차원에 대해, 프로젝션 이후 나온 값과 왼쪽에 concat 되므로 (batch_size, 패치수+1, d) 로 나옴
        x += self.pos_embedding
        x = self.dropout(x)
        return x

class MultiheadedSelfAttention(nn.Module):
    def __init__(self, latent_vec_dim, num_heads, drop_rate):
        super().__init__()
        device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        self.num_heads = num_heads
        self.latent_vec_dim = latent_vec_dim
        self.head_dim = int(latent_vec_dim / num_heads)
        self.query = nn.Linear(latent_vec_dim, latent_vec_dim)
        self.key = nn.Linear(latent_vec_dim, latent_vec_dim)
        self.value = nn.Linear(latent_vec_dim, latent_vec_dim)
        self.scale = torch.sqrt(torch.FloatTensor([self.head_dim])).to(device)
        self.dropout = nn.Dropout(drop_rate)

    def forward(self, x):
        batch_size = x.size(0)
        q = self.query(x)   # (batch_size, 나눠진패치개수, d)
        k = self.key(x)
        v = self.value(x)

        q = q.view(batch_size, -1, self.num_heads, self.head_dim).permute(0,2,1,3)
        # (batch_size, num_heads, 나눠진패치개수, head_dim) : d를 head개수와 head별 dimesion으로 나눈 후 계산할 차원 맨 뒤로 빼서 사용
        k = k.view(batch_size, -1, self.num_heads, self.head_dim).permute(0,2,3,1) # k.T (batch_size, num_heads, head_dim, 나눠진패치개수)
        v = v.view(batch_size, -1, self.num_heads, self.head_dim).permute(0,2,1,3)
        attention = torch.softmax(q @ k / self.scale, dim=-1)   # 루트(head차원)으로 나눠줌. 마지막차원에 대한 softmax이므로 한 개 행을 다 더하면 1됨
        x = self.dropout(attention) @ v
        x = x.permute(0,2,1,3).reshape(batch_size, -1, self.latent_vec_dim)

        return x, attention

class TFencoderLayer(nn.Module):
    def __init__(self, latent_vec_dim, num_heads, mlp_hidden_dim, drop_rate):
        super().__init__()
        self.ln1 = nn.LayerNorm(latent_vec_dim)
        self.ln2 = nn.LayerNorm(latent_vec_dim)
        self.msa = MultiheadedSelfAttention(latent_vec_dim=latent_vec_dim, num_heads=num_heads, drop_rate=drop_rate)
        self.dropout = nn.Dropout(drop_rate)
        self.mlp = nn.Sequential(nn.Linear(latent_vec_dim, mlp_hidden_dim), # Transformer의 피드포워드 역할 함
                                 nn.GELU(), nn.Dropout(drop_rate),
                                 nn.Linear(mlp_hidden_dim, latent_vec_dim),
                                 nn.Dropout(drop_rate))

    def forward(self, x):
        z = self.ln1(x)
        z, att = self.msa(z)
        z = self.dropout(z)
        x = x + z
        z = self.ln2(x)
        z = self.mlp(z)
        x = x + z

        return x, att

class VisionTransformer(nn.Module):
    def __init__(self, patch_vec_size, num_patches, latent_vec_dim, num_heads, mlp_hidden_dim, drop_rate, num_layers, num_classes):
        super().__init__()
        self.patchembedding = LinearProjection(patch_vec_size=patch_vec_size, num_patches=num_patches,
                                               latent_vec_dim=latent_vec_dim, drop_rate=drop_rate)
        # patch_vec_size = (p^2, chennel), num_patches = H*w / p^2, latent_vec_dim = 모델 풀 dimension

        self.transformer = nn.ModuleList([TFencoderLayer(latent_vec_dim=latent_vec_dim, num_heads=num_heads,
                                                         mlp_hidden_dim=mlp_hidden_dim, drop_rate=drop_rate)
                                          for _ in range(num_layers)]) # 레이어 쌓기, 각 레이어는 독립적 파라미터 사용함

        self.mlp_head = nn.Sequential(nn.LayerNorm(latent_vec_dim), nn.Linear(latent_vec_dim, num_classes))
        # 클래스 토큰만(1, latent_vec_dim) 떼 와서 마지막에 output으로 클래스 개수만큼으로 출력

    def forward(self, x):
        att_list = []
        x = self.patchembedding(x)
        for layer in self.transformer:
            x, att = layer(x)
            att_list.append(att)
        x = self.mlp_head(x[:,0])   # 클래스토큰만 떼다가 mlp_head에 넣음

        return x, att_list


#! /usr/bin/env python3

import rospy
import math
import pickle
import os.path

from MARS_msgs.msg import TargetTelemetry

def target_node():

    # Creates the publisher to publish the target position on the topic "target_position"
    pub = rospy.Publisher('target_position', TargetTelemetry, queue_size=10)
    rospy.init_node('target_node', anonymous=True)

    # Publishing rate
    rate = rospy.Rate(10)

    msg = TargetTelemetry()

    # Time related variables initialization
    start_time = rospy.get_time()
    curr_time = rospy.get_time()
    timer = 0.0
    dt = 0.0

    # Target variables initialization (All changeble)
    target_accel = 0.0
    position_x = 0.0
    position_y = 0.0
    target_psi = 0 #math.pi/4
    target_velocity = 0

    while not rospy.is_shutdown():

        # Time variation since last call on loop
        dt = rospy.get_time() - curr_time

        # Total time counter
        timer = rospy.get_time() - start_time

        curr_time = rospy.get_time()

        # Target movement calculations
        target_omega = 0#.02*math.cos(0.03*dt) # Changeble
        target_accel = 0#.2*math.sin(0.07*dt) # Changeble

        target_psi = target_psi + target_omega * dt
        target_velocity = target_velocity + (target_accel * dt)
        target_vx = target_velocity * math.cos(target_psi)
        target_vy = target_velocity * math.sin(target_psi)
        position_x = position_x + target_vx * dt
        position_y = position_y + target_vy * dt

        # Defines message to be sent with target movement variables
        msg.x_pos = position_x
        msg.y_pos = position_y
        msg.vx = target_vx
        msg.vy = target_vy
        msg.omega = target_omega
        msg.accel = target_accel
        msg.vel = target_velocity
        msg.psi = target_psi

        # Publishes the target data
        pub.publish(msg)
	#print(msg)

        # Keeps the rate fixed
        rate.sleep()

if __name__ == '__main__':
    try:
        target_node()
    except rospy.ROSInterruptException:
        pass


def sort(data):

    for k in range(1,len(data)):
        cur = data[k]
        j = k
        while j > 0 and data[j-1] > cur :
            data[j] = data[j-1]
            j -= 1;
            data[j] = cur

def main():

    array = [3,5,2,6,1,9]
    print(array)
    sort(array)

    print(array)

main()


# manage PostgraSQL database
# import books.csv into PostgreSQL database
import os
import csv

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

tables = ["users", "books", "reviews"]

# Run a custom sql command
def runSqlCmd():
    print("------------------------------------")
    cmd = input("sql: ")
    db.execute(cmd)
    db.commit()
    print("Completed!!!")
    print("------------------------------------")

# Create tables and load books.csv
def importData():
    print("------------------------------------")
    db.execute("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, username VARCHAR (50) UNIQUE NOT NULL, password VARCHAR (50) NOT NULL, register_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP);");
    db.execute("CREATE TABLE IF NOT EXISTS books (id SERIAL PRIMARY KEY, isbn VARCHAR UNIQUE NOT NULL, title VARCHAR NOT NULL, author VARCHAR NOT NULL, year INTEGER);")
    db.execute("CREATE TABLE IF NOT EXISTS reviews (id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users, book_id INTEGER REFERENCES books, review VARCHAR, rating_score INT NOT NULL CHECK (rating_score >= 0 AND rating_score <= 5), time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);")
    f = open("books.csv")
    # skip first line
    f.readline()
    reader = csv.reader(f)
    i = 1
    for isbn, title, author, year in reader:
        db.execute("INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)",
                    {"isbn": isbn, "title": title, "author": author, "year": year})
        print(f"{i}: Added {isbn}")
        i += 1
    db.commit()
    f.close()
    print("Completed!!!")
    print("------------------------------------")

# Show all data of table
def showTable():
    print("------------------------------------")
    for i in range(len(tables)):
        print(str(i + 1) + ". " + tables[i])
    option = int(input("Which table: "))
    table = db.execute("SELECT * FROM " + tables[option - 1]).fetchall()
    for data in table:
        print(data)
    if len(table) == 0:
        print("No data")
    print("------------------------------------")

# Delete all data of table
def deleteTable():
    print("------------------------------------")
    for i in range(len(tables)):
        print(str(i + 1) + ". " + tables[i])
    option = int(input("Which table: "))
    db.execute("DELETE FROM " + tables[option - 1])
    db.execute("ALTER SEQUENCE " + tables[option - 1] + "_id_seq RESTART WITH 1")
    db.commit()
    print(f"Deleted {tables[option - 1]}")
    print("------------------------------------")

def main():
    print("------------------------------------")
    print("0. Run sql command")
    print("1. Import books.csv")
    print("2. Show table")
    print("3. Delete table")
    print("Press any key to exit.")
    print("------------------------------------")
    while True:
        try:
            option = int(input("Choose option: "))
            if option == 0:
                runSqlCmd()
            elif option == 1:
                importData()
            elif option == 2:
                showTable()
            elif option == 3:
                deleteTable()
            else:
                return
        except:
            return

if __name__ == "__main__":
    main()


import asyncio
import random
from datetime import datetime
from io import BytesIO

import chess
import discord
from cairosvg import svg2png
from chess import pgn, svg
from discord.ext import commands
from discord.ext.commands import BadArgument, MemberConverter

class Games(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command()
    async def chess(self, ctx: commands.Context, *args: str):
        """
        `!chess` __`Play chess`__

        **Usage:** !chess <user>

        **Examples:**
        `!chess abc#1234` starts a game of chess with abc#1234

        **Note:**
        Moves are in standard algebraic notation (e4, Nxf7, etc).
        """

        try:
            user = await MemberConverter().convert(ctx, " ".join(args))
        except BadArgument:
            return await ctx.send("That user doesn't exist.", delete_after=5)

        board = chess.Board()
        game = pgn.Game()
        node = None
        players = [ctx.author, user]
        random.shuffle(players)
        turn = chess.WHITE
        game.headers["Date"] = datetime.today().strftime("%Y.%m.%d")
        game.headers["White"] = players[chess.WHITE].display_name
        game.headers["Black"] = players[chess.BLACK].display_name

        def render_board(board: chess.Board) -> BytesIO:
            boardimg = chess.svg.board(board=board, lastmove=board.peek() if board.move_stack else None, check=board.king(turn) if board.is_check() or board.is_checkmate() else None, flipped=board.turn == chess.BLACK)
            res = BytesIO()
            svg2png(bytestring=boardimg, write_to=res)
            res.seek(0)
            return res

        while True:
            res = render_board(board)

            if board.outcome() is not None:
                game.headers["Result"] = board.outcome().result()

                if board.is_checkmate():
                    return await ctx.send(f"Checkmate!\n\n{players[not turn].mention} wins.\n{str(game)}", file=discord.File(res, "file.png"))
                else:
                    return await ctx.send(f"Draw!\n{str(game)}", file=discord.File(res, "file.png"))

            game_msg = await ctx.send(f"{players[turn].mention}, its your turn." + ("\n\nCheck!" if board.is_check() else ""), file=discord.File(res, "file.png"))

            try:
                msg = await self.bot.wait_for("message", timeout=600, check=lambda msg: msg.channel == ctx.channel and msg.author.id == players[turn].id)
            except asyncio.TimeoutError:
                return await ctx.send("Timed out.", delete_after=5)

            await msg.delete()
            await game_msg.delete()

            if msg.content == "exit" or msg.content == "resign":
                res = render_board(board)
                game.headers["Result"] = "0-1" if turn else "1-0"
                await game_msg.delete()
                return await ctx.send(f"{players[turn].mention} resigned. {players[not turn].mention} wins.\n{str(game)}", file=discord.File(res, "file.png"))

            try:
                move = board.push_san(msg.content)
            except ValueError:
                continue

            if not node:
                node = game.add_variation(move)
            else:
                node = node.add_variation(move)

            turn = not turn

def setup(bot: commands.Bot) -> None:
    bot.add_cog(Games(bot))


import conf
from json import dumps
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from urllib import quote_plus
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import logout
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.cache import never_cache
from imageserve import img_server
from imageserve.helpers import get_keyvals, get_folios, get_att
from imageserve.helpers import get_rel, get_by_ismi_id, get_name
from imageserve.models import Manuscript, ManuscriptGroup, AttDisplaySetting, RelDisplaySetting
from imageserve.settings import NO_DATA_MSG, DIVASERVE_URL, IIPSERVER_URL
from guardian.shortcuts import get_objects_for_user

@never_cache
def main(request):
    """The main view, where users can browse available manuscripts."""
    if request.user.is_anonymous():
        u = User.objects.get(pk=-1)  # select the "AnonymousUser" object
        show_all = False
    else:
        u = request.user
        show_all = request.GET.get('show_all', False)
        if show_all:
            show_all = bool(int(show_all))

    manuscript_groups = get_objects_for_user(u, 'imageserve.view_manuscript_group')
    msf = Manuscript.objects.filter(manuscriptgroup__in=manuscript_groups)

    if not show_all:
        # this assumes the existence of a manuscriptgroup called "Stabi Codices"...
        stabi = ManuscriptGroup.objects.filter(name="Stabi Codices")
        msf = msf.filter(manuscriptgroup__in=stabi)

    ms = msf.distinct()
    paginator = Paginator(ms, 25)
    page = request.GET.get('page')

    try:
        manuscripts = paginator.page(page)
    except PageNotAnInteger:
        manuscripts = paginator.page(1)
    except EmptyPage:
        manuscripts = paginator.page(paginator.num_pages)

    data = {
        'manuscripts': manuscripts,
        'title': 'Available Manuscripts',
        'path': quote_plus(request.get_full_path()),
        'show_all': show_all
    }
    return render(request, "templates/index.html", data)

def diva(request):
    """View for divaserve"""
    msdir = request.GET.get('d')
    js = img_server.getc(msdir)
    return HttpResponse(dumps(js), content_type="application/json")

@never_cache
def search(request):
    if request.user.is_anonymous():
        u = User.objects.get(pk=-1)  # select the "AnonymousUser" object
        show_all = False
    else:
        u = request.user
        show_all = request.GET.get('show_all', False)
        if show_all:
            show_all = bool(int(show_all))

    manuscript_groups = get_objects_for_user(u, 'imageserve.view_manuscript_group')
    # msf = Manuscript.objects.filter(manuscriptgroup__in=manuscript_groups)

    q = request.GET.get('q', None)
    m = Manuscript.objects.filter(directory__icontains=q, manuscriptgroup__in=manuscript_groups).distinct().values_list(
        'directory', flat=True)
    js = list(m)
    return HttpResponse(dumps(js), content_type="application/json")

@never_cache
def goto(request):
    q = request.GET.get('q', None)
    m = Manuscript.objects.get(directory=q)
    return HttpResponse(dumps({'codex': m.id}), content_type="application/json")

def title_author(request):
    """
    This view handles AJAX requests to asynchronously update the
    Title and Author information on the viewer page.
    """
    w = int(request.GET['wit_id'])
    ms_title, = get_rel(w, 'is_exemplar_of')
    ms_author, = get_rel(w, 'was_created_by')
    data = {'title': ms_title, 'author': ms_author}
    return HttpResponse(dumps(data), mimetype="text/json")

def metadata(request):
    """
    This view serves the metadata window.
    """
    w = int(request.GET['id'])
    ent = get_by_ismi_id(w)
    title = get_name(ent)

    def adder(clss, l):
        for a in clss.objects.all():
            if a.show != clss.NEVER_SHOW:
                k, vals = get_keyvals(a, w)
                if a.show == clss.ALWAYS_SHOW:
                    for val in vals:
                        l.append((k, val))
                else:  # show if set
                    if len(vals) == 1:
                        val, = vals
                        if val == NO_DATA_MSG:
                            continue
                    for val in vals:
                        l.append((k, val))

    md = []
    adder(AttDisplaySetting, md)
    adder(RelDisplaySetting, md)

    data = {'title': title, 'md': md}
    return render(request, "templates/metadata.html", data)

def manuscript(request, ms_id):
    """The view for displaying a specific manuscript."""
    if request.user.is_anonymous():
        u = User.objects.get(pk=-1)  # select the "AnonymousUser" object
    else:
        u = request.user

    # We break the response down into a couple steps here.
    # First, check the number of manuscripts groups they have permissions to. This is just to
    # be able to exit with a 404 if they're trying to access a manuscript in a group that doesn't exist.

    # Then, we check against the manuscripts themselves. This allows us to catch the user and redirect them
    # to a log in page if they need to log in to see the MSS.
    manuscript_groups = get_objects_for_user(u, 'imageserve.view_manuscript_group')
    manuscripts = Manuscript.objects.filter(manuscriptgroup__in=manuscript_groups).distinct()
    if not manuscripts.exists():
        raise Http404

    has_permission = manuscripts.filter(id=ms_id)

    if manuscripts and not has_permission.exists():
        return redirect('/login/?next={0}'.format(request.path))

    m = has_permission[0]
    curr_wit = request.GET.get('curr_wit')
    try:
        curr_wit = int(curr_wit)
    except (ValueError, TypeError):
        curr_wit = -1

    # witnesses = None
    titles = None
    ismi_data = False
    wits = PageNotAnInteger

    if m.ismi_id is not None:
        codex_title = get_name(get_by_ismi_id(m.ismi_id))
        ismi_data = True
        wits = m.witnesses
        if wits:
            if not curr_wit in wits:
                curr_wit = -1
            titles = [(w, get_rel(w, 'is_exemplar_of')[0], get_att(w, 'folios'))
                      for w in wits]
    else:
        codex_title = m.directory

    data = {
        'ms_title': codex_title,
        'witnesses': bool(wits),
        'divaserve_url': DIVASERVE_URL,
        'iipserver_url': IIPSERVER_URL,
        'image_root': conf.IMG_DIR,
        'curr_wit': curr_wit,
        'ms_name': m.directory,
        'titles': titles,
        'ismi_data': ismi_data,
        'ms_id': ms_id,
        'ismi_id': m.ismi_id,
        'path': quote_plus(request.get_full_path()),
        'num_files': m.num_files,
    }
    return render(request, "templates/diva.html", data)

def logout_view(request):
    """
    Logs out the current user.
    """
    logout(request)
    next = request.GET['next']
    return redirect(next)

def get_curr_folio_pgs(request):
    """
    Returns the PageRangeList for the Manuscript object with id
    ms_id for the current session.
    """
    ms_id = int(request.GET.get('ms_id'))
    if not request.session.get('folio_pgs'):
        request.session['folio_pgs'] = {}
    if not request.session['folio_pgs'].get(ms_id):
        ms = Manuscript.objects.get(id=ms_id)
        request.session['folio_pgs'][ms_id] = \
            ms.folio_pgs
    folio_pgs = request.session['folio_pgs'][ms_id]
    return folio_pgs

@login_required
def set_curr_folio_pgs(request, folio_pgs):
    """
    Modifies the PageRangeList for the Manuscript object with id
    ms_id for the current session.
    """
    ms_id = int(request.GET.get('ms_id'))
    if not request.session.get('folio_pgs'):
        request.session['folio_pgs'] = {}
    request.session['folio_pgs'][ms_id] = folio_pgs
    request.session.modified = True

def folio_for_page(request):
    """
    Given the id of a Manuscript and a page number, returns
    the first folio number on the specified page.
    """
    page = int(request.GET.get('page'))
    folio_pgs = get_curr_folio_pgs(request)
    folio = folio_pgs.get_folio(page)
    return HttpResponse(dumps(folio), mimetype="text/json")

def page_for_folio(request):
    """
    Given the id of a Manuscript and a folio number, returns
    the first page with the given folio number.
    """
    folio = request.GET.get('folio')
    if folio.isdigit():
        page = int(folio)
    else:
        folio_pgs = get_curr_folio_pgs(request)
        page = folio_pgs.get_page(folio)
    return HttpResponse(dumps(page), mimetype="text/json")

def wit_for_page(request):
    """
    Gives the ISMI ID of the current witness given the current
    Manuscript and current page in it. If no witness is specified
    for the given page, returns -1.
    """
    ms_id = int(request.GET.get('ms_id'))
    page = int(request.GET.get('page'))
    ms = Manuscript.objects.get(id=ms_id)
    folio_pgs = get_curr_folio_pgs(request)
    folio = folio_pgs.get_folio(page)
    for w in ms.witnesses:
        folios = get_folios(w)
        if not folios:
            continue
        first, last = map(folio_pgs.get_page, folios)
        if first and last:
            if first <= page and page <= last:
                return HttpResponse(dumps((str(folio), w)), mimetype="text/json")
    return HttpResponse(dumps((str(folio), -1)), mimetype="text/json")

def page_for_wit(request):
    """
    Given a Manuscript id and the ISMI ID of a witness in it,
    returns the first page of that witness.
    """
    wit = int(request.GET.get('wit'))
    folios = get_folios(wit)
    if not folios:
        return HttpResponse(dumps(-1), mimetype="text/json")
    folio, _ = folios
    folio_pgs = get_curr_folio_pgs(request)
    page = folio_pgs.get_page(folio)
    return HttpResponse(dumps(page), mimetype="text/json")

@login_required
def set_folio(request):
    """
    In the page number editing mode, changes the first or
    last page of a witness in a given manuscript.
    """
    page = int(request.GET.get('page'))
    folio = request.GET.get('folio')
    folio_pgs = get_curr_folio_pgs(request)
    folio_pgs[page] = folio
    set_curr_folio_pgs(request, folio_pgs)
    return HttpResponse(dumps(folio), mimetype="text/json")

@login_required
def interpolate_after(request):
    """
    Given a manuscript's id, a page number, and the boolean
    `overwrite` argument, interpolates the page numbers in
    the manuscript after the given page.
    """
    page = int(request.GET.get('page'))
    overwrite = bool(int(request.GET.get('overwrite')))
    folio_pgs = get_curr_folio_pgs(request)
    folio_pgs.interpolate_after(page, overwrite=overwrite)
    set_curr_folio_pgs(request, folio_pgs)
    return HttpResponse()

@login_required
def save_folios(request):
    """
    Given a manuscript's id, saves the specified manuscript to have
    the folio pages associated to the current session.
    """
    ms_id = int(request.GET.get('ms_id'))
    folio_pgs = get_curr_folio_pgs(request)
    ms = Manuscript.objects.get(id=ms_id)
    ms.folio_pgs = folio_pgs
    try:
        ms.save()
        return HttpResponse(dumps('Changes successfully saved'), mimetype="text/json")
    except Exception as e:
        msg = 'An error occurred and your changes could not be saved:\n{0}'
        return HttpResponse(dumps(msg.format(e)), mimetype="text/json")

@login_required
def remove_folios(request):
    """
    Given a manuscript's id and a page number, removes all folio numbers
    for the specified page in the specified manuscript.
    """
    page = int(request.GET.get('page'))
    folio_pgs = get_curr_folio_pgs(request)
    folio_pgs.clear_page(page)
    set_curr_folio_pgs(request, folio_pgs)
    return HttpResponse(dumps(str(None)), mimetype="text/json")

@login_required
def discard_changes(request):
    """
    Given a manuscript's id, resets the session's folio numbers to the
    ones stored in the database for that manuscript.
    """
    ms_id = int(request.GET.get('ms_id'))
    ms = Manuscript.objects.get(id=ms_id)
    set_curr_folio_pgs(request, ms.folio_pgs)
    return HttpResponse()


from aiogram import Bot, types, Dispatcher, executor

TOKEN = '1686424554:AAEUySebIA2fuA94jzhb8SQFfQbBSflvJp0'

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)

@dp.message_handler(commands=['start'])
async def welcome(message: types.message):
    await bot.send_message(message.chat.id, 'Бот 1 Запущен')

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)


BATCH_SIZE = 128
SAVE_FREQ = 1
TEST_FREQ = 1
TOTAL_EPOCH = 70

lr = 0.01
momentum = 0.9
weight_decay = 1e-4

RESUME = ''
SAVE_DIR = './model'
MODEL_PRE = 'CASIA_B512_'

CASIA_DATA_DIR = r'/root/NIR_VIS_Face_Recognition-master/dataset/CASIA_NIR_VIS_2.0/NIR-VIS-2.0'
LFW_DATA_DIR = r'/root/NIR_VIS_Face_Recognition-master/dataset/lfw'

GPU = 0


from itertools import chain
abundants = []
def checkAbundant(n):
    factors = list(chain(*[[i, n//i] for i in range(1,int(n**0.5)+1) if n%i == 0]))
    factors = list(set(factors)) # remove duplicates e.g. squares
    factors.remove(n)
    total = sum(factors)
    if total > n:
        abundants.append(n)

for i in range(1, 28123+1):
    checkAbundant(i)

totals = [abundant+item for item in abundants for abundant in abundants] # sum all items

totals = set(totals) # quicker, ~O(1) instead of O(n)
nonsummables = [i for i in range(1, 28123+1) if i not in totals]
print(sum(nonsummables))


import numpy as np
from scipy.fft import fft, ifft
from decimal import Decimal

def convolution(f1,f2,m):
    """расчитываем свертку"""
    res = 0
    for k in range(m+1):
        res += f1[k] * f2[m-k]
    return res

N = 14

N_iter = 100

#определяем начальные условия
a = np.full(N,Decimal('0'))
new_a = np.full(N,Decimal('0'))
new_a[0] = Decimal('1')
a[0] = Decimal('1.00000000000000')
a[1] = Decimal('-1.5')
a[2] = Decimal('0.1')
a[3] = Decimal('0.026')

alfa = Decimal('2.50290787509588')

betta = np.full((N, N), Decimal('0'))

for _ in range(N_iter):
    print('############################')

    betta = np.full((N, N), Decimal('0'))

    for m in range(N):
        betta[0][m] = convolution(a, a, m)

    for p in range(N - 1):
        for m in range(N):
            betta[p+1][m] = convolution(betta[p], betta[0], m)

    betta = np.transpose(betta)

    for i in range(2, N):
        sum = 0
        for j in range(1, N):
            sum += a[j] * betta[i][j-1]
        new_a[i] =  - alfa  * sum / ((- alfa)**(2*i))

    a = new_a

    a[1] = -1/alfa - np.sum(a[2:]) - a[0]

    alfa = Decimal('0')
    for i in range(1, N):
        alfa -= (2*i) * a[i]

    print("alfa = ", alfa)
    print('\n')


from keras.datasets import cifar10
import loss_function as lf
import numpy as np

(X_train, y_train), (X_test, y_test) = cifar10.load_data()

# flatten out all images to be one-dimensional
Xtr_rows = X_train.reshape(X_train.shape[0], 32 * 32 * 3) # Xtr_rows becomes 50000 x 3072
Xtr_cols = X_train.reshape(32 * 32 * 3, X_train.shape[0]) # Xtr_rows becomes 3072 x 50000
Ytr_cols = y_train.reshape(1, y_train.shape[0]) # Ytr_cols becomes 1 x 50000

# print("X_train.shape : {}".format(X_train.shape))
# print("X_test.shape : {}".format(X_test.shape))
# print("y_train.shape : {}".format(y_train.shape))
# print("y_test.shape : {}".format(y_test.shape))
# print("Xtr_rows.shape : {}".format(Xtr_rows.shape))
# print("Xtr_cols.shape : {}".format(Xtr_cols.shape))
# print("Ytr_cols.shape : {}".format(Ytr_cols.shape))

print("---------------------loss function test------------------------")

W = np.random.randn(10, 3072) * 0.0001
b = np.zeros((10, 1))
reg = 1e-3 # reguluarization strength

print("입력받은 이미지로 SVM을 이용하여 Loss를 측정합니다...")
print()

svm_loss = lf.L_SVM(Xtr_cols, Ytr_cols, W, b, reg)

print("svm_loss : {}".format(svm_loss))

print()

print("입력받은 이미지로 Softmax을 이용하여 Loss를 측정합니다...")
print()

softmax_loss = lf.L_Softmax(Xtr_cols, Ytr_cols, W, b, reg)

print("softmax_loss : {}".format(softmax_loss))


import cv2 as cv

cap = cv.VideoCapture(0)

haar_cascade = cv.CascadeClassifier('haar_cascade.xml')

id = input("Input your ID : ")
count = 0
while True:
    result, video_frame = cap.read()
    gray_image = cv.cvtColor(video_frame, cv.COLOR_BGR2GRAY)

    faces = haar_cascade.detectMultiScale(gray_image, 1.1, 8)
    for (x, y, w, h) in faces:
        count+=1
        cv.imwrite('datasets/User.'+str(id)+'.'+str(count)+'.jpg',gray_image[y:y+h , x:x+w])
        cv.rectangle(video_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv.imshow('Frame',video_frame)

    k = cv.waitKey(1)

    if count>500:
        break

cap.release()
cv.destroyAllWindows()
print("======== Data Collection Complete ========")


#!/Library/Frameworks/Python.framework/Versions/3.3/bin/python3.3
# Codejam ID 2974486
# Run with parameter
# -p for preprocessing
# -s for small input
# -l for large input
# -m=<int> for multithreading

from GCJ import GCJ

def parse(infile):
    R, C, M = GCJ.readints(infile)
    return R, C, M

def solve(data):
    MINE = "*"
    CLICK = 'c'
    FREE = '.'
    r,c,m = data
    free = r*c - m
    swap = False
    print("%d x %d, %d" % (r,c,m))
    if m == 0:
        field = [ [ FREE for x in range(c) ] for y in range(r) ]
    elif free == 1:   # nur einer frei geht immer
        field = [ [ MINE for x in range(c) ] for y in range(r) ]
    elif r == 1:
        field = [ [ MINE for x in range(c) ] for y in range(r) ]
        free = c - m
        for i in range(free):
            field[0][i] = FREE
    elif c == 1:
        field = [ [ MINE for x in range(c) ] for y in range(r) ]
        free = r - m
        for i in range(free):
            field[i][0] = FREE

    elif (r == 2 or c == 2) and (m % 2 == 1):  # eine Seite 2 mit ungerader Minenanzahl > 1 geht nie
         return "\nImpossible"
    elif m == 1:
        field = [ [ FREE for x in range(c) ] for y in range(r) ]
        field[r-1][c-1] = MINE
    elif free == 7 or free == 5 or free == 3 or free == 2:
        return "\nImpossible"
    else:
        if (free % c) % 2 == 0:
            line = c
            height = r
        elif (free % r) % 2 == 0:
            line = r
            height = c
            swap = True
        elif c < r:
            line = c
            height = r
        else:
            line = r
            height = c
            swap = True

        field = [ [ MINE for x in range(line) ] for y in range(height) ]
        rest = free
        y = 0
        if height >= 2:
            for x in range(line):
                field[y][x] = FREE
                field[y+1][x] = FREE
                rest -= 2
                if rest == 3:
                    field[y+2][2] = FREE
                    field[y+2][1] = FREE
                    field[y+2][0] = FREE
                    rest = 0
                    break
                if rest == 0:
                    break

        y += 2
        while y < height and rest > 0:
            for x in range(line):
                field[y][x] = FREE
                rest -= 1
                if rest == 0:
                    break
            y += 1

        if free % line == 1: # single ending
            y -= 1
            field[y-1][line-1] = MINE
            field[y][1] = FREE
            if y == 2:
                field[y-2][line-1] = MINE
                field[y][2] = FREE

    field[0][0] = CLICK

    if swap:
        res = [ [field[x][y] for x in range(c)] for y in range(r)]
    else:
        res = field
    return '\n'+ '\n'.join(map(lambda x: ''.join(x),res))

if __name__ == "__main__":
    GCJ('C', solve, parse, None).run()


def best_list_pureness(sequence, k):
    best_pureness = 0
    rotations = 0
    for rotation in range(k+1):
        current_result = 0
        for index in range(len(sequence)):
            current_result += index * sequence[index]
        if current_result > best_pureness:
            best_pureness = current_result
            rotations = rotation
        value = sequence.pop()
        sequence.insert(0, value)
    return f"Best pureness {best_pureness} after {rotations} rotations"

test = ([4, 3, 2, 6], 1)
result = best_list_pureness(*test)
print(result)

test = ([7, 9, 2, 5, 3, 4], 3)
result = best_list_pureness(*test)
print(result)

test = ([1, 2, 3, 4, 5], 10)
result = best_list_pureness(*test)
print(result)

Python Advanced Exam preparations/Exam 2/Problem 3 - List Pureness.py


from Person import Person
person1 = Person("Михаил", "Козырев", "QA")
person1.display_info()

person2 = Person("Степан", "Иванов", "диджей")
person2.display_info()

person3 = Person("Леонид", "Смирнов", "разработчик")
person3.display_info()

del person2

input("Нажмите enter")

Задание 1_1.py


# -*- coding: utf-8 -*-
"""
A set of functions used to filter arrays.

Originally pulled from SDSS-IV/MaNGA Data Analysis Pipeline, licensed
under BSD 3-clause license.
"""

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import sys
if sys.version > '3':
    long = int

import warnings
import numpy
from scipy import interpolate, sparse

class BoxcarFilter(object):
    """Boxcar filter a 2D image along columns."""
    def __init__(self, boxcar, lo=None, hi=None, niter=None, y=None, wgt=None, mask=None,
                 local_sigma=None):

        if boxcar <= 1:
            raise ValueError('Boxcar must be greater than 1!')

        self.y = None
        self.wgt = None
        self.input_mask = None
        self.output_mask = None
        self.boxcar = boxcar
        self.lo_rej = lo
        self.hi_rej = hi
        self.nrej = -1 if niter is None else niter
        self.nvec = None
        self.npix = None
        self.local_sigma = False if local_sigma is None else local_sigma

        self.smoothed_wgt = None
        self.smoothed_n = None
        self.smoothed_y = None
        self.sigma_y = None
        self.rdx_index = None

        if y is not None:
            self.smooth(y, wgt=wgt, mask=mask, boxcar=boxcar, lo=lo, hi=hi, niter=niter,
                        local_sigma=local_sigma)

    def _assign_par(self, boxcar, lo, hi, niter, local_sigma):
        if boxcar is not None:
            self.boxcar = boxcar
        if lo is not None:
            self.lo_rej = lo
        if hi is not None:
            self.hi_rej = hi
        if niter is not None:
            self.nrej = niter
        if local_sigma is not None:
            self.local_sigma = local_sigma

    def _check_par(self):
        if self.boxcar <= 1:
            raise ValueError('Boxcar must be greater than 1!')

        if self.nrej is not None and self.nrej > 0 and self.lo_rej is None and self.hi_rej is None:
            raise ValueError('Must provide lo or hi if niter provided')

    def _reduce_indices(self):
        indx = numpy.array([numpy.arange(self.npix)-self.boxcar//2,
                            numpy.arange(self.npix)+self.boxcar//2+1])
        if self.boxcar % 2 != 1:
            indx[:self.npix] += 1
        return indx.T.ravel().clip(0,self.npix-1)

    def _apply(self):
        self.smoothed_n = numpy.add.reduceat(numpy.invert(self.output_mask), self.rdx_index,
                                             axis=1, dtype=int)[:,::2]
        self.smoothed_wgt = numpy.add.reduceat(self.input_wgt, self.rdx_index, axis=1,
                                             dtype=float)[:,::2]
        self.smoothed_y = numpy.add.reduceat(self.input_wgt*self.y.filled(0.0), self.rdx_index,
                                             axis=1, dtype=float)[:,::2]
        smoothed_y2 = numpy.add.reduceat(self.input_wgt*numpy.square(self.y.filled(0.0)),
                                         self.rdx_index, axis=1, dtype=float)[:,::2]

        self.smoothed_y = numpy.ma.divide(self.smoothed_y, self.smoothed_wgt)
        self.smoothed_y[self.output_mask | (self.smoothed_n == 0)] = numpy.ma.masked

        self.sigma_y = numpy.ma.sqrt((numpy.ma.divide(smoothed_y2, self.smoothed_wgt)
                                            - numpy.square(self.smoothed_y))
                                        * numpy.ma.divide(self.smoothed_n, self.smoothed_n-1)) \
                        if self.local_sigma else \
                            numpy.ma.MaskedArray(numpy.array([numpy.std(self.y - self.smoothed_y,
                                                                        axis=1)]*self.npix).T)

        self.output_mask = numpy.ma.getmaskarray(self.smoothed_y) \
                                | numpy.ma.getmaskarray(self.sigma_y)

        self.smoothed_y[self.output_mask | (self.smoothed_n == 0)] = numpy.ma.masked
        self.sigma_y[self.output_mask | (self.smoothed_n == 0)] = numpy.ma.masked

    def _interpolate(self):
        """
        Interpolate the smoothed image across the masked regions.
        Leading and trailing masked regions of each row are set to the
        first and last unmasked value, respectively.

        interpolate both the smoothed data and the sigma
        """
        # Boolean arrays with bad pixels (should be the same for both
        # smoothed_y and sigma_y)
        badpix = numpy.ma.getmaskarray(self.smoothed_y)

        # Deal with any vectors that are fully masked
        goodvec = numpy.sum(numpy.invert(badpix), axis=1) > 0
        ngood = numpy.sum(goodvec)
        veci = numpy.arange(self.nvec)[goodvec]

        # Find the first and last unflagged pixels in the good vectors
        pixcoo = numpy.ma.MaskedArray(numpy.array([numpy.arange(self.npix)]*ngood),
                                      mask=badpix[goodvec,:]).astype(int)
        mini = numpy.ma.amin(pixcoo, axis=1)
        maxi = numpy.ma.amax(pixcoo, axis=1)

        # Copy those to the first and last pixels for each row
        self.smoothed_y[veci,0] = numpy.array([self.smoothed_y[i,m] for i,m in zip(veci, mini)])
        self.smoothed_y[veci,-1] = numpy.array([self.smoothed_y[i,m] for i,m in zip(veci, maxi)])

        self.sigma_y[veci,0] = numpy.array([self.sigma_y[i,m] for i,m in zip(veci, mini)])
        self.sigma_y[veci,-1] = numpy.array([self.sigma_y[i,m] for i,m in zip(veci, maxi)])

        # Detach badpix from self.smoothed_y
        badpix = numpy.ma.getmaskarray(self.smoothed_y).copy()

        # Interpolate the smoothed array
        x = numpy.ma.MaskedArray(numpy.arange(self.nvec*self.npix), mask=badpix)
        interpolator = interpolate.interp1d(x.compressed(), self.smoothed_y.compressed(),
                                            assume_sorted=True, fill_value='extrapolate')
        self.smoothed_y.ravel()[badpix.ravel()] = interpolator(x.data[badpix.ravel()])
        self.smoothed_y[numpy.invert(goodvec),:] = 0.0

        # Interpolate the sigma array
        interpolator = interpolate.interp1d(x.compressed(), self.sigma_y.compressed(),
                                            assume_sorted=True, fill_value='extrapolate')
        self.sigma_y.ravel()[badpix.ravel()] = interpolator(x.data[badpix.ravel()])
        self.sigma_y[numpy.invert(goodvec),:] = 0.0

    def smooth(self, y, wgt=None, mask=None, boxcar=None, lo=None, hi=None, niter=None,
               local_sigma=None):
        """
        Smooth a vector or array of vectors by a boxcar with specified
        rejection.
        """
        # Assign and check the binning parameters
        self._assign_par(boxcar, lo, hi, niter, local_sigma)
        self._check_par()

        # Check the input vector/array
        if len(y.shape) > 2:
            raise ValueError('Can only deal with vectors or matrices.')

        # Set the weighting
        self.input_wgt = numpy.ones(y.shape, dtype=bool) if wgt is None else wgt
        if self.input_wgt.shape != y.shape:
            raise ValueError('Weights shape does not match data.')
        if isinstance(y, numpy.ma.MaskedArray):
            self.input_wgt[numpy.ma.getmaskarray(y)] = 0.0

        # Set the mask
        self.input_mask = numpy.zeros(y.shape, dtype=bool) if mask is None else mask
        if self.input_mask.shape != y.shape:
            raise ValueError('Mask shape does not match data.')
        if isinstance(y, numpy.ma.MaskedArray):
            self.input_mask |= numpy.ma.getmaskarray(y)

        # Save the input
        provided_vector = len(y.shape) == 1
        self.y = numpy.ma.atleast_2d(numpy.ma.MaskedArray(y.copy(), mask=self.input_mask))
        self.input_wgt = numpy.atleast_2d(self.input_wgt)
        self.input_mask = numpy.atleast_2d(self.input_mask)
        self.output_mask = self.input_mask.copy()
        self.nvec, self.npix = self.y.shape

        # Create the list of reduceat indices
        self.rdx_index = self._reduce_indices()

        # Get the first iteration of the smoothed vectors
        self._apply()

        # No rejection iterations requested so return the result
        if self.lo_rej is None and self.hi_rej is None:
            self._interpolate()
            return self.smoothed_y[0,:] if provided_vector else self.smoothed_y

        # Iteratively reject outliers
        nmasked = numpy.sum(numpy.ma.getmaskarray(self.y))
        i=0
        while i > -1:
            nbad = numpy.sum(self.output_mask)
            if self.lo_rej is not None:
                self.output_mask = numpy.logical_or(self.output_mask, self.y.data - self.smoothed_y
                                                        < (-self.lo_rej*self.sigma_y))
            if self.hi_rej is not None:
                self.output_mask = numpy.logical_or(self.output_mask, self.y.data - self.smoothed_y
                                                        > (self.hi_rej*self.sigma_y))
            self.y[self.output_mask] = numpy.ma.masked
            self._apply()

            nmasked = numpy.sum(self.output_mask) - nbad

            i += 1
            if i == self.nrej or nmasked == 0:
                break

        self._interpolate()
        return self.smoothed_y[0,:] if provided_vector else self.smoothed_y

    @property
    def mask(self):
        return self.output_mask.copy()


from tkinter import *
import tkinter as tk
import tkinter.messagebox
import mysql.connector
from tkinter import  ttk

root = Tk()
root.title("โรงแรมผีสิง เข้าพักมีนางรำ Login")
root.geometry("400x430")

def Login():
    var1 = TxT.get()
    var2 = txt1.get()
    if (var1 == 'root') and (var2 == 'root'):
        # print(var1)
        booking()
    else:
        tkinter.messagebox.showinfo(
            'โรงแรมผีสิง เข้าพักมีนางรำ Login', 'ไม่สามารถเข้าสู่ระบบได้')

# def exitProgram():
#     confirm = tkinter.messagebox.askquestion(
#         "ยืนยัน", "Do you Want exit")
#     if confirm == "yes":
#         root.destroy()

frame1 = Frame(root, highlightbackground="blue", highlightthickness=1)
frame1.pack(padx=26, pady=34)

myLabel1 = Label(frame1 , text="โรงแรมผีสิง เข้าพักมีนางรำ", fg="black",height=3, width=52, font=("4711_AtNoon_Regular", 28)).pack()

myLabel2 = Label(frame1, text=" Username :", fg="black", font=("4711_AtNoon_Regular", 28),).pack()

TxT = StringVar()
T1 = Entry(frame1, textvariable=TxT, font=("4711_AtNoon_Regular", 16)).pack()
# การ Label สำหรับ Password
lbUN = Label(frame1, text="Password :", fg="black",
             font=("4711_AtNoon_Regular", 28), ).pack()

txt1 = StringVar()
T2 = Entry(frame1, show='*', textvariable=txt1, font=("4711_AtNoon_Regular", 16)).pack()

btn1 = Button(frame1, text="Login", fg="black", font=("4711_AtNoon_Regular", 16), bg="lightgrey",
              width="10", height="1", command=Login).pack()

def booking():
    mainBooking = Tk()
    mainBooking.title("โรงแรมผีสิง เข้าพักมีนางรำ")
    mainBooking.geometry("500x500")

  # สร้าง menu
    myMenu = Menu()
    # mainBooking.config(menu=myMenu)
    # เพิ่มเมนู หลัก
    # myMenu.add_cascade(label="File")
    # myMenu.add_cascade(label="Edit")
    # myMenu.add_cascade(label="View")

    Standard=IntVar()
    Duluxe=IntVar()
    Suite=IntVar()

    var1 = IntVar()
    var2 = IntVar()
    var3 = IntVar()
    var4 = IntVar()
    var5 = IntVar()
    var6 = IntVar()
    var7 = IntVar()
    var8 = IntVar()
    var9 = IntVar()
    var10 = IntVar()
    var11 = IntVar()
    var12 = IntVar()

    lbcon_name = Label(mainBooking, text="Room Type :", fg="black", font=("4711_AtNoon_Regular", 24), bg="lightgrey").grid(row=0, column=0, sticky='NSEW')

    Checkbutton(mainBooking, text="1", variable=var1).grid(row=0, column=1, sticky= 'W' )
    Checkbutton(mainBooking, text="2", variable=var2).grid(row=0, column=2, sticky= 'W' )
    Checkbutton(mainBooking, text="3", variable=var3).grid(row=0, column=3, sticky= 'W' )
    Checkbutton(mainBooking, text="4", variable=var4).grid(row=0, column=4, sticky= 'W' )
    Checkbutton(mainBooking, text="5", variable=var5).grid(row=1, column=1, sticky= 'W' )
    Checkbutton(mainBooking, text="6", variable=var6).grid(row=1, column=2, sticky= 'W' )
    Checkbutton(mainBooking, text="7", variable=var7).grid(row=1, column=3, sticky= 'W' )
    Checkbutton(mainBooking, text="8", variable=var8).grid(row=1, column=4, sticky= 'W' )
    Checkbutton(mainBooking, text="9", variable=var9).grid(row=2, column=1, sticky= 'W' )
    Checkbutton(mainBooking, text="10", variable=var10).grid(row=2, column=2, sticky= 'W' )
    Checkbutton(mainBooking, text="11", variable=var11).grid(row=2, column=3, sticky= 'W' )
    Checkbutton(mainBooking, text="12", variable=var12).grid(row=2, column=4, sticky= 'W' )

#  ---------------------------- radiobutton fix posittion please fix your screen

    Label(mainBooking, text="Standard",   font=("4711_AtNoon_Regular", 24), bg="lightgrey").grid(row=3, column=0, sticky='NSEW')
    # radiobutton
    Radiobutton(mainBooking,text="Standard",variable=Standard,value=1).place(x=125,y=110)
    Radiobutton(mainBooking, text="Duluxe", variable=Standard, value=2).place(x=215, y=110)

    Label(mainBooking, text="Duluxe",font=("4711_AtNoon_Regular", 24), bg="lightgrey").grid(row=6, column=0, sticky='NSEW')
    # radiobutton
    Radiobutton(mainBooking,text="Single Bed",variable=Duluxe,value=1).place(x=125,y=155)
    Radiobutton(mainBooking, text="Twin", variable=Duluxe, value=2).place(x=215, y=155)

    Label(mainBooking, text="Suite",   font=("4711_AtNoon_Regular", 24), bg="lightgrey").grid(row=9, column=0, sticky='NSEW')
    # radiobutton
    Radiobutton(mainBooking,text="Ocean View",variable=Suite,value=1).place(x=125,y=202)
    Radiobutton(mainBooking, text="Mountain view", variable=Suite, value=2).place(x=215, y=202)

    btnADD = Button(mainBooking, text="NEXT", fg="black", font=("4711_AtNoon_Regular", 12),
                    bg="lightgrey", width="20", height="3", command=MainProgress).grid(row=10, column=0, sticky='NSEW')

    mainloop()

def MainProgress():
    import TestDB

root.mainloop()


import sys

from department import Department
from product import Product
from store import Store
from user import User

# user will pass in either 0 or 1 command-line arguments to the program
num_args = len(sys.argv)
# if they pass in 0, we'll default their money to 100
if num_args == 1:
    user = User(100)
# if they pass in 1 argument (a number), set their money to that amount
elif num_args == 2:
    user = User(int(sys.argv[1]))
else:
    print("Usage: store.py [money]")
    sys.exit(1)

departments = {
    23: Department(23, "Groceries", [Product("Bananas", 1), Product("Avocados", 2), Product("Watermelons", 4)]),
    9: Department(9, "Books",
                  [Product("Game of Thrones", 10), Product("Working in Public", 25), Product("Twilight", 10)]),
    13: Department(13, "Electronics",
                   [Product("Samsung 4K TV", 300), Product("iPhone SE", 400), Product("Pixel 4A", 350)]),
    7: Department(7, "Clothes",
                  [Product("Graphic T's", 20), Product("Kanye Sweater", 700), Product("Sketchers High Tops", 50)]),
    15: Department(15, "Toys", [Product("Lightsaber", 200), Product("Nerf Guns", 200), Product("Settlers of Catan", 40),
                                Product("Nintendo Lego Set", 150)])
}

store = Store("Quarantine Store", departments)

# print the store's welcome message
print(store)

# print user's status
print(user, '\n')

while True:
    # print departments
    store.print_departments()

    selection = input("Which department would you like to visit? ")

    if selection == 'quit' or selection == 'q':
        break

    # expect user to type in a number that is read in as a string
    # parse it into an int, and then check if the int is a valid
    dep_num = int(selection)

    if dep_num not in departments:
        print("\nThat is not a valid department.\n")
        continue

    selected_dep = departments[dep_num]

    print(f"\nYou picked department number {dep_num}, the {selected_dep.name} department.\n")

    selected_dep.print_products()

    # we want the user to be able to add products to their cart
    product_selection = int(input("What would you like to add to your cart? "))

    possible_products = selected_dep.products

    # index into the current department's list of products using the `product_selection`
    selected_product = possible_products[product_selection]

    user.add_to_cart(selected_product)


import random
import numpy as np
import os

import torch
import torch.backends
import torch.backends.cudnn

from args import Args
from log_config import LOG_CONFIG
import trainers

import logging
import logging.config

def set_log():
    logging.config.dictConfig(LOG_CONFIG)
    logger = logging.getLogger(__name__)
    return logger

def set_seed(args):
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    os.environ['PYTHONHASHSEED'] = str(args.seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    # 这个好像我也不太会用
    # if args.n_gpu > 0:
    #     torch.cuda.manual_seed_all(args.seed)

def main():
    logger = set_log()
    logger.info('程序运行开始')

    args = Args().get_all_args()
    set_seed(args)
    # 进行模型的训练
    # 根据参数选择 trainer
    Trainer = getattr(trainers, args.trainer_name)
    trainer = Trainer(args)
    args.do_train = True
    if args.do_train:
        trainer.train()

    # 在做 test 之前，应该需要 load 以前保存的最佳模型
    if args.do_test:
        trainer.test()

def test():
    pass

if __name__ == '__main__':
    main()


from collections import Counter

f = open("input")

ids = [line.strip() for line in f.readlines()]

twos = 0
threes = 0

for id in ids:
  letters = Counter(id)
  if 2 in letters.values():
    twos += 1
  if 3 in letters.values():
    threes += 1

print(twos * threes)

for i in ids:
  for j in ids:
    diff = [a for a, b in zip(i, j) if a != b]
    if len(diff) is 1:
      l = list(i)
      l.remove(diff[0])
      print(''.join(l)) #.remove(diff[0]))


import csv
import pickle

punct = ['.', ',', '\n', '?', '!', '(', ')']

def tokenize(text):
    for ch in punct:
        text = text.replace(ch, ' ')
    return text.split()

with open('lyrics.csv', newline='', encoding='utf-8') as csvfile:
    names = []
    years = []
    artists = []
    genres = []
    lyrics = []

    reader = csv.reader(csvfile, delimiter=',')
    reader.__next__()
    for row in reader:
        names.append(row[1])
        years.append(row[2])
        artists.append(row[3])
        genres.append(row[4])
        lyrics.append(tokenize(row[5]))

    fwrite = open('data.pkl', 'wb')
    pickle.dump((names, years, artists, genres, lyrics), fwrite)