import torch
from torch import nn
from torch.nn import functional as F

class AlexNet(nn.Module):
    def __init__(self):
        super().__init__()

        self.weight_conv1 = nn.Parameter(torch.Tensor(32, 1, 3, 3))
        self.bias_conv1 = None
        self.weight_conv2 = nn.Parameter(torch.Tensor(64, 32, 3, 3))
        self.bias_conv2 = None
        self.weight_conv3 = nn.Parameter(torch.Tensor(128, 64, 3, 3))
        self.bias_conv3 = None
        self.weight_conv4 = nn.Parameter(torch.Tensor(256, 128, 3, 3))
        self.bias_conv4 = None
        self.weight_conv5 = nn.Parameter(torch.Tensor(256, 256, 3, 3))
        self.bias_conv5 = None

        self.weight_fc1 = nn.Parameter(torch.Tensor(1024, 256*3*3))
        self.bias_fc1 = None
        self.weight_fc2 = nn.Parameter(torch.Tensor(512, 1024))
        self.bias_fc2 = None
        self.weight_fc3 = nn.Parameter(torch.Tensor(10, 512))
        self.bias_fc3 = None

        self.weight_init()

    def forward(self, x):
        self.batch_size = x.shape[0]
        self.a_1 = F.conv2d(x, self.weight_conv1, self.bias_conv1, padding=1)
        self.b_1 = F.max_pool2d(self.a_1, (2, 2))
        self.c_1 = F.relu(self.b_1)

        self.a_2 = F.conv2d(self.c_1, self.weight_conv2, self.bias_conv2, stride=1, padding=1)
        self.b_2 = F.max_pool2d(self.a_2, (2, 2))
        self.c_2 = F.relu(self.b_2)

        self.a_3 = F.conv2d(self.c_2, self.weight_conv3, self.bias_conv3, stride=1, padding=1)
        self.c_3 = F.relu(self.a_3)

        self.a_4 = F.conv2d(self.c_3, self.weight_conv4, self.bias_conv4, stride=1, padding=1)
        self.c_4 = F.relu(self.a_4)

        self.a_5 = F.conv2d(self.c_4, self.weight_conv5, self.bias_conv5, stride=1, padding=1)
        self.b_5 = F.max_pool2d(self.a_5, (2, 2))
        self.c_5 = F.relu(self.b_5)

        self.h_1 = self.c_5.view(-1, 256*3*3)

        # 去掉两个droupout层， 第一个droupout用relu代替
        # self.d_1 = F.dropout(self.h_1)
        self.x_1 = F.relu(self.h_1)
        self.h_2 = F.linear(self.x_1, self.weight_fc1, self.bias_fc1)
        self.x_2 = F.relu(self.h_2)
        # self.d_2 = F.dropout(self.x_2)
        self.h_3 = F.linear(self.x_2, self.weight_fc2, self.bias_fc2)
        self.x_3 = F.relu(self.h_3)
        self.h_4 = F.linear(self.x_3, self.weight_fc3, self.bias_fc3)
        with torch.no_grad():
            self.s = F.softmax(self.h_4, dim=1)
        return self.h_4

    def weight_init(self):
        for w in self.parameters():
            nn.init.xavier_uniform_(w, gain=1)

    def compute_hessian(self):
        h4_hessian = self.s*(1-self.s)/self.batch_size

        W_3 = self.weight_fc3                                       # (10,512)
        B_3 = self.grad_relu(self.h_3)                              # (64,512)
        D_3 = self.hessian_relu(self.h_3)                           # (64,512)
        h3_hessian = self.recursive_pre_hessian(B_3, W_3, h4_hessian, D_3)  # (10,512)
        w3_hessian = h4_hessian.t().matmul(torch.pow(self.x_3, 2))
        # print(B_3.shape, h3_hessian.shape, w3_hessian.shape)

        W_2 = self.weight_fc2                                       # (512, 1024)
        B_2 = self.grad_relu(self.h_2)                              # (64, 1024)
        D_2 = self.hessian_relu(self.h_2)                           # (64, 1024)
        h2_hessian = self.recursive_pre_hessian(B_2, W_2, h3_hessian, D_2)  # (64, 1024)
        w2_hessian = h3_hessian.t().matmul(torch.pow(self.x_2, 2))  # (512, 1024)
        # print(B_2.shape, h2_hessian.shape, w2_hessian.shape)

        W_1 = self.weight_fc1                                       # (1024, 2304)
        B_1 = self.grad_relu(self.h_1)                              # (64, 2304)
        D_1 = self.hessian_relu(self.h_1)                           # (64, 2304)
        h1_hessian = self.recursive_pre_hessian(B_1, W_1, h2_hessian, D_1)  # (64, 2304)
        w1_hessian = h2_hessian.t().matmul(torch.pow(self.x_1, 2))  # (1024, 2304)
        # print(B_1.shape, h1_hessian.shape, w1_hessian.shape)

        a = 1

        return w1_hessian, w2_hessian, w3_hessian

    def recursive_pre_hessian(self, B, W, H2, D):
        H1 = torch.pow(B, 2) * H2.matmul(torch.pow(W, 2)) + D
        return H1

    def grad_relu(self, x):
        return (x>0).float()

    def hessian_relu(self, x):
        return x*0

# class AlexNet1(nn.Module):
#     def __init__(self):
#         super(AlexNet1,self).__init__()

#         # 由于MNIST为28x28， 而最初AlexNet的输入图片是227x227的。所以网络层数和参数需要调节
#         self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1) #AlexCONV1(3,96, k=11,s=4,p=0)
#         self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)#AlexPool1(k=3, s=2)
#         self.relu1 = nn.ReLU()

#         # self.conv2 = nn.Conv2d(96, 256, kernel_size=5,stride=1,padding=2)
#         self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)#AlexCONV2(96, 256,k=5,s=1,p=2)
#         self.pool2 = nn.MaxPool2d(kernel_size=2,stride=2)#AlexPool2(k=3,s=2)
#         self.relu2 = nn.ReLU()

#         self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)#AlexCONV3(256,384,k=3,s=1,p=1)
#         # self.conv4 = nn.Conv2d(384, 384, kernel_size=3, stride=1, padding=1)
#         self.conv4 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)#AlexCONV4(384, 384, k=3,s=1,p=1)
#         self.conv5 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)#AlexCONV5(384, 256, k=3, s=1,p=1)
#         self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)#AlexPool3(k=3,s=2)
#         self.relu3 = nn.ReLU()

#         self.fc6 = nn.Linear(256*3*3, 1024)  #AlexFC6(256*6*6, 4096)
#         self.fc7 = nn.Linear(1024, 512) #AlexFC6(4096,4096)
#         self.fc8 = nn.Linear(512, 10)  #AlexFC6(4096,1000)

#     def forward(self,x):
#         x = self.conv1(x)
#         print(x.shape)
#         x = self.pool1(x)
#         print(x.shape)
#         x = self.relu1(x)
#         x = self.conv2(x)
#         print(x.shape)
#         x = self.pool2(x)
#         print(x.shape)
#         x = self.relu2(x)
#         x = self.conv3(x)
#         print(x.shape)
#         x = self.conv4(x)
#         print(x.shape)
#         x = self.conv5(x)
#         print(x.shape)
#         x = self.pool3(x)
#         print(x.shape)
#         x = self.relu3(x)
#         x = x.view(-1, 256 * 3 * 3)#Alex: x = x.view(-1, 256*6*6)
#         x = self.fc6(x)
#         x = F.relu(x)
#         x = self.fc7(x)
#         x = F.relu(x)
#         x = self.fc8(x)
#         return x

# x = torch.rand(64,1,28,28)
# net = AlexNet()
# x = net(x)
# print(x.shape)
# net.compute_hessian()
# for name, param in net.named_parameters():
# 	print(name, '      ', param.size())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  4 11:25:57 2019

@author: Santosh,Sahil
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report

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

def sigmoid_derivative(s):
    return s * (1 - s)

def softmax(z):
    exp_z = np.exp(z)
    softmax_scores = exp_z / np.sum(exp_z, axis=1, keepdims=True)
    return softmax_scores

def softmax_to_y(softmax_scores):
    return np.argmax(softmax_scores, axis=1)

def reLU(x):
    return x * (x > 0)

def reLU_derivative(x):
    return 1. * (x > 0)

def error_rate(y_pred, y_test):
    m = y_pred.shape[0]
    return np.sum(1 - (y_pred == y_test)) / m

def plot_decision_boundary(model, X, y):
    x1_array, x2_array = np.meshgrid(np.arange(-10, 10, 0.01), np.arange(-10, 10, 0.01))
    grid_coordinates = np.c_[x1_array.ravel(), x2_array.ravel()]
    Z = model.predict(grid_coordinates)
    Z = Z.reshape(x1_array.shape)
    plt.contourf(x1_array, x2_array, Z, cmap=plt.cm.bwr)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()

class NN(object):

    def __init__(self, input_dimension, output_dimension, nodes, alpha=0.1, num_epochs=1000):
        # weights
        self.input_weight = np.random.randn(input_dimension, nodes) / np.sqrt(input_dimension)
        self.hidden_weight = np.random.randn(nodes, output_dimension) / np.sqrt(nodes)

        # bias
        self.input_bias = np.zeros((1, nodes))
        self.output_bias = np.zeros((1, output_dimension))
        self.alpha = alpha
        self.epochs = num_epochs

    def hyperparameters(self, alpha, epochs):
        self.alpha = alpha
        self.epochs = epochs

    def forward_propagation(self, X):
        # dot product of X (input) and first set
        self.hidden = reLU(np.dot(X, self.input_weight) + self.input_bias)
        # dot product of hidden layer and second set
        self.output = softmax(np.dot(self.hidden, self.hidden_weight) + self.output_bias)
        return self.output

    def backward_propagation(self, X, y):
        d = X.shape[0]
        one_hot_y = np.zeros_like(self.output)
        for i in range(y.shape[0]):
            one_hot_y[i, y[i]] = 1

        self.o_error = self.output - one_hot_
        self.o_delta = self.o_error

        # error: how much hidden layer weights contributed to output error
        self.hid_error = self.o_delta.dot(self.hidden_weight.T)

        # applying derivative of reLu to hidden error
        self.hid_delta = self.hid_error * reLU_derivative(self.hidden)

        w2 = self.hidden.T.dot( self.o_delta) / d
        b2 = np.sum(self.o_delta, axis=0, keepdims=True) / d
        w1 = X.T.dot( self.hid_delta) / d
        b1 = np.sum(self.hid_delta, axis=0, keepdims=True) / d

        # Return updated gradients
        values = { "w1": w1,
                    "b1": b1,
                   "w2": w2,
                "b2": b2}
        return values

    # Updates the weights after calculating gradient in the self propagation step
    def update_weight(self, grads):
        self.input_bias -= self.alpha * grads["b1"]
        self.output_bias -= self.alpha * grads["b2"]
        self.input_weight -= self.alpha * grads["w1"]
        self.hidden_weight -= self.alpha * grads["w2"]

    # Computes the cross entropy between the actual and predicted values
    def compute_cost(self, o_z, y):
        m = y.shape[0]
        log_likelihood = -np.log(o_z[range(m), y])
        loss = np.sum(log_likelihood) / m
        return loss

    # Fits the neural network using the training dataset
    # Returns the training error for every 10th epoch
    def fit(self, X_train, y_train):
        train_error = [0.5]
        for i in range(self.epochs):
            output = self.forward_propagation(X_train)
            grads = self.backward_propagation(X=X_train, y=y_train)
            self.update_weight(grads)
            if (i % 10 == 0):
                # hot_y = softmax_to_y(output)
                train_error += [self.compute_cost(output, y_train)]
        return train_error

    # Fits the neural network using the training dataset,
    # calculates train as well as test error rate alongside
    def fit_test_train(self, X_train, y_train, X_test, y_test):
        train_error = []
        test_error = []
        for i in range(self.epochs):
            output_train = self.forward_propagation(X_train)
            grads = self.backward_propagation(X=X_train, y=y_train)
            self.update_weight(grads)
            if (i % 10 == 0):
                train_error += [self.compute_cost(output_train, y_train)]
                output_test = self.forward_propagation(X_test)
                test_error += [self.compute_cost(output_test, y_test)]
        error = [None] * 2
        error[0] = train_error
        error[1] = test_error
        return error

    def predict(self, X_test):
        output = self.forward_propagation(X_test)
        return softmax_to_y(output)

def k_fold(X, y, k, nn):
    X = np.array_split(X, k)
    y = np.array_split(y, k)

    test_error = [None] * k

    for i in range(k):
        b = 0
        for j in range(k):
            if j == i:
                X_test = X[i]
                y_test = y[i]
            else:
                if b == 0:
                    X_train = X[j]
                    y_train = y[j]
                    b += 1
                else:
                    X_train = np.concatenate([X_train, X[i]])
                    y_train = np.concatenate([y_train, y[i]])
        nn.fit(X_train, y_train)
        y_pred = nn.predict(X_test)
        test_error[i] = error_rate(y_pred, y_test)
    return np.sum(test_error) / (k + 1)

class regularizationL2(NN):

    def __init__(self, input_dimension, nodes, output_dimension, alpha=0.5, num_epochs=1000, reg_para=0.001):
        self.reg = reg_para
        super().__init__(input_dimension, nodes, output_dimension, alpha, num_epochs)

    def hyperparameter(self, alpha, num_epochs, reg_para):
        self.alpha = alpha
        self.num_epochs = num_epochs
        self.reg = reg_para

    def update_weight(self, grads):
        # Adding derivative of regularization term
        self.input_bias -= self.reg * self.input_bias
        self.output_bias -= self.reg * self.output_bias
        self.input_weight -= self.reg * self.input_weight
        self.hidden_weight -= self.reg * self.hidden_weight

        self.input_bias -= self.alpha * grads["b1"]
        self.output_bias -= self.alpha * grads["b2"]
        self.input_weight -= self.alpha * grads["w1"]
        self.hidden_weight -= self.alpha * grads["w2"]

def linear():
    X = np.genfromtxt('DATA/data_linearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_lineary.csv', delimiter=',').astype(np.int64)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()

    X, X_test, y, y_test = train_test_split(X, y, test_size=0.2)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 10

    nn = NN(input_dim, nodes, output_dim, alpha=0.05, num_epochs=500)
    train_err = nn.fit(X, y)

    y_pred = nn.predict(X_test)

    err = error_rate(y_pred, y_test)
    print("Error in test set is ", err * 100, "%")

    plt.plot(train_err)
    plt.title("Cross Entropy with respect to Epochs")
    plt.xlabel("Number of Epochs (factor of 10)")
    plt.ylabel("Cross Entropy")
    plt.show()

    # Even though the cross entropy is not minimized,
    # our system is able to distinguish the red points from the blue points easily
    # Plotting decision boundary
    plot_decision_boundary(nn, X_test, y_test)

    # Confusion matrix
    print("Confusion Matrix \n")
    print(confusion_matrix(y_pred, y_test))
    print(classification_report(y_pred, y_test))

    X = np.genfromtxt('DATA/data_linearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_lineary.csv', delimiter=',').astype(np.int64)
    test_error = k_fold(X, y, 5, nn)
    print("Average test error is :", test_error)

def non_linear():
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()
    X, X_test, y, y_test = train_test_split(X, y, test_size=0.2)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 30

    nn = NN(input_dim, nodes, output_dim, alpha=0.5, num_epochs=2500)
    train_err = nn.fit(X, y)

    y_pred = nn.predict(X_test)

    err = error_rate(y_pred, y_test)
    print("Error in test set is ", err * 100, "%")

    plt.plot(train_err)
    plt.title("Cross Entropy with respect to Epochs")
    plt.xlabel("Number of Epochs (factor of 10)")
    plt.ylabel("Cross Entropy")
    plt.show()

    # Even though the cross entropy is not minimized,
    # our system is able to distinguish the red points from the blue points easily
    # Plotting decision boundary
    plot_decision_boundary(nn, X_test, y_test)

    # Confusion matrix
    print("Confusion Matrix \n")
    print(confusion_matrix(y_pred, y_test))
    print(classification_report(y_pred, y_test))

    # Cross Validation score for the linear dataset
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    test_error = k_fold(X, y, 5, nn)
    print("Average test error is :", test_error)

    # Script for checking the test and train error
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)

    nodes = 30

    nn = NN(input_dim, nodes, output_dim, alpha=0.05, num_epochs=500)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    err = nn.fit_test_train(X_train, y_train, X_test, y_test)

    train_err = err[0]
    test_err = err[1]

    plt.plot(train_err)
    plt.plot(test_err)
    plt.legend(('Train', 'Test'))
    plt.show()

def l2Regularization():
    X = np.genfromtxt('DATA/data_nonlinearX.csv', delimiter=',')
    y = np.genfromtxt('DATA/data_nonlineary.csv', delimiter=',').astype(np.int64)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr)
    plt.show()
    X, X_test, y, y_test = train_test_split(X, y, test_size=0.2)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 30
    nn = regularizationL2(input_dim, nodes, output_dim, alpha=0.1, num_epochs=2500)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    err = nn.fit_test_train(X_train, y_train, X_test, y_test)

    train_err = err[0]
    test_err = err[1]

    plt.plot(train_err)
    plt.plot(test_err)
    plt.show()

def digitTraining():
    X = np.genfromtxt('DATA/Digit_X_train.csv', delimiter=',')
    y = np.genfromtxt('DATA/Digit_y_train.csv', delimiter=',').astype(np.int64)
    input_dim = int(X.shape[1])
    output_dim = int(y.max() + 1)
    nodes = 30

    nn = NN(input_dim, nodes, output_dim, alpha=0.05, num_epochs=2500)
    train_err = nn.fit(X, y)
    train_err.pop(0)

    X_test = np.genfromtxt('DATA/Digit_X_test.csv', delimiter=',')
    y_test = np.genfromtxt('DATA/Digit_y_test.csv', delimiter=',').astype(np.int64)

    y_pred = nn.predict(X_test)

    err = error_rate(y_pred, y_test)
    print(err)

    plt.plot(train_err)
    # plt.plot(test_err)
    plt.show()

    nn = regularizationL2(input_dim, nodes, output_dim, alpha=0.1, num_epochs=2500)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    err = nn.fit_test_train(X_train, y_train, X_test, y_test)

    train_err = err[0]
    test_err = err[1]
    plt.plot(train_err)
    plt.plot(test_err)
    plt.show()

def main():
    print('Non-linear:\n')
    non_linear()
    print('Linear:\n')
    linear()
    print('Regularized:\n')
    l2Regularization()
    print('Digit:\n')
    digitTraining()

if __name__ == "__main__":
    main()


from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup

def get_trial(url):
    try:
        with closing(get(url, stream=True)) as resp: #closing is useful to ensure any netword
            if is_good_response(resp):  # resources are freed and prevents fatal errors
                return resp.content
            else:
                return None
    except RequestException as e:
        log_error('Error during requests to {0} : {1}'.format(url, str(e)))
        return None

def is_good_response(resp):
    content_type = resp.headers['Content-Type'].lower()
    return (resp.status.code == 200
            and content_type is not None
            and content_type.find('html') > -1)

def log_error(e):
    print(e)

def get_names():
    url = 'http://www.fabpedigree.com/james/mathmen.htm'
    response = get_trial(url)

    if response is not None:
        html = BeautifulSoup(response, 'html.parser')
        names = set()
        for li in html.select('li'):
            for name in li.text.split('\n'):
                if len(name) > 0:
                    names.add(name.strip())
        return list(names)


from espnet2.bin.tts_inference import Text2Speech
import glob
import kaldiio
import numpy as np
import torch
import soundfile as sf
import time
from opencc import OpenCC
import string
from pypinyin.style._utils import get_finals, get_initials
from pypinyin import pinyin
# without vocoder
# tts = Text2Speech.from_pretrained(model_file="/path/to/model.pth")
# wav = tts("Hello, world")["wav"]

# with local vocoder
# tts = Text2Speech.from_pretrained(model_file="/path/to/model.pth", vocoder_file="/path/to/vocoder.pkl")
# wav = tts("Hello, world")["wav"]

# with pretrained vocoder (use ljseepch style melgan as an example)
cc = OpenCC('t2s')
text2speech = Text2Speech.from_pretrained(
train_config="/home/espnet/egs2/aishell3/tts1/exp/tts_train_raw_phn_pypinyin_g2p_phone/config.yaml",
model_file="/home/espnet/egs2/aishell3/tts1/exp/tts_train_raw_phn_pypinyin_g2p_phone/train.loss.best.pth",
vocoder_tag="parallel_wavegan/ljspeech_hifigan.v1",
device="cuda",
 )
model_dir= "/home/espnet/egs2/aishell3/tts1/exp/tts_train_raw_phn_pypinyin_g2p_phone"
spembs = None

if text2speech.use_spembs:
    xvector_ark = [p for p in glob.glob(f"{model_dir}/../../dump/**/spk_xvector.ark", recursive=True) if "tr" in p][0]
    xvectors = {k: v for k, v in kaldiio.load_ark(xvector_ark)}
    spks = list(xvectors.keys())

    # randomly select speaker
    # random_spk_idx = np.random.randint(0, len(spks))
    random_spk_idx = 2
    spk = spks[random_spk_idx]
    spembs = xvectors[spk].copy()
    print(f"selected spk: {spk}")

# Speaker ID selection
sids = None
if text2speech.use_sids:
    spk2sid = glob.glob(f"{model_dir}/../../dump/**/spk2sid", recursive=True)[0]
    with open(spk2sid) as f:
        lines = [line.strip() for line in f.readlines()]
    sid2spk = {int(line.split()[1]): line.split()[0] for line in lines}

    # randomly select speaker
    sids = np.array(2)
    # sids = np.array(np.random.randint(1, len(sid2spk)))
    spk = sid2spk[int(sids)]
    print(f"selected spk: {spk}")

# Reference speech selection for GST
speech = None
if text2speech.use_speech:
    # you can change here to load your own reference speech
    # e.g.
    # import soundfile as sf
    # speech, fs = sf.read("/home/TTS_data/chatbot_check/audio_file/split/101301/003.wav")
    # speech = torch.from_numpy(speech).float()
    speech = torch.randn(50000,) * 0.01

def frontend(text) -> str:
    # punct = string.punctuation
    full_punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' + '→↓△▿⋄•！？?〞＃＄％＆』。（）＊＋，－╱︰；＜＝＞＠〔╲〕 ＿ˋ｛∣｝∼、〃》「」『』【】﹝﹞【】〝〞–—『』「」…'
    # text = text.translate(str.maketrans('', '', string.punctuation))
    text = text.translate(str.maketrans('', '', full_punctuation))
    text = cc.convert(text)
    # print(text)
    return text

def tts(text,id):
    text = frontend(text)
    with torch.no_grad():
        start = time.time()
        wav = text2speech(text,speech=speech, spembs=spembs)["wav"]
    duration = time.time() - start
    rtf = (duration) / (len(wav) / text2speech.fs)
    sf.write(f"synthesis_chatbot_text/{id}.wav", wav.cpu().numpy(), text2speech.fs, "PCM_16")
    # print(f"RTF = {rtf:5f}, Duration: {duration:5f}, wav_len: {len(wav)}")

from tqdm import tqdm
from pypinyin import Style, pinyin
from pypinyin.style._utils import get_finals, get_initials
def g2p_phone(text):
    phones = [
        p
        for phone in pinyin(text, style=Style.TONE3)
        for p in [
            get_initials(phone[0], strict=True),
            get_finals(phone[0][:-1], strict=True) + phone[0][-1]
            if phone[0][-1].isdigit()
            else get_finals(phone[0], strict=True)
            if phone[0][-1].isalnum()
            else phone[0],
        ]
        # Remove the case of individual tones as a phoneme
        if len(p) != 0 and not p.isdigit()
    ]
    return phones
if __name__ == '__main__':
    ids = []
    test_text = []
    wavscp = open("data/pair/wav.scp", "w", encoding="utf-8")
    utt2spk = open("data/pair/utt2spk", "w", encoding="utf-8")
    text = open("data/pair/text", "w", encoding="utf-8")

    with open("/home/espnet/egs2/chatbot/tts1/data/all_phn/text", 'r') as src:
        all = src.readlines()
        for each in all:
             ids.append(each.split(" ")[0])

    with open("/home/espnet/egs2/chatbot/tts1/data/all/text", 'r') as src_text:
        all = src_text.readlines()
        # print(len(all))
        for each in all:
            [id, text_] = each.split(" ")
            if id in ids:
                test_text.append([id+'_china', ])
                wavscp.write("{} {}\n".format(id+'_china',f"/home/espnet/egs2/aishell3/tts1/synthesis_chatbot_text/{id}_china.wav"))
                utt2spk.write("{} {}\n".format(id+'_china', spk))
                text.write("{} {}\n".format(id+'_china', " ".join(g2p_phone(text_.strip("\n")))))
    # print(test_text)
    wavscp.close()
    utt2spk.close()
    text.close()
    # for id, text in tqdm(test_text,total=len(test_text)):
    #     tts(text,id)

    # tts(text)


from django.contrib import admin
from django.urls import path, include
from .import views
app_name = 'home'

urlpatterns = [
    path('', views.home_view, name='home'),
    path('about', views.about_view, name='about'),
    path('portfolio', views.portfolio_view, name='portfolio'),
    path('price', views.price_view, name='price'),
    path('services', views.services_view, name='services'),
    path('contact', views.contact_view, name='contact'),
]


import json
import os
import random
import numpy as np
from torch.utils.data import Dataset
from torchvision.io import read_image
from matplotlib import pyplot as plt
import torchvision
import torchvision.transforms as transforms
from collections import Counter

class Oral_Dataset(Dataset):
    def __init__(self, json_dataset_file, images_path, transform=None, crop=True):

        self.json_dataset_file = json_dataset_file
        self.images_path = images_path
        self.transform = transform
        self.crop = crop

        # Opening JSON file
        with open(json_dataset_file) as json_file:
            data = json.load(json_file)

        self.labels = [item['label'] for item in data['data']]
        self.bboxes = [item['bbox'] for item in data['data']]
        self.images = [item['image_name'] for item in data['data']]

        '''
        seed = 42
        random.seed(seed)
        random.shuffle(self.labels)
        random.seed(seed)
        random.shuffle(self.bboxes)
        random.seed(seed)
        random.shuffle(self.images)
        '''

    def __getitem__(self, index):
        img = read_image(os.path.join(self.images_path, self.images[index]))
        if self.crop:
            img = self.crop_image(img, list(map(int, self.bboxes[index] )) )
        label = self.labels[index]

        # apply transformation to each images
        if self.transform is not None:
            # TODO permute images
            img = img / 255
            img = self.transform(img)

        return img, label

    # utility function to get the portion of image containing the lesion
    def crop_image(self, img, bbox):
        return img[:, bbox[1] : bbox[1] + bbox[3], bbox[0]: bbox[0] + bbox[2] ]

    def __len__(self):
        return len(self.labels)

# utility function returning the 3 set of data (train, validation, test)
def get_datasets(cfg):
    train_json_filename = cfg.datasets.filenames.train
    val_json_filename = cfg.datasets.filenames.val
    test_json_filename = cfg.datasets.filenames.test
    train_set = get_dataset(cfg, train_json_filename)
    validation_set = get_dataset(cfg, val_json_filename)
    test_set = get_dataset(cfg, test_json_filename)
    return train_set, validation_set, test_set

# utility function returning the a set of data
def get_dataset(cfg, json_filename):
    project_path = cfg.project_path
    img_folder = cfg.datasets.img_path
    data_path = os.path.join(project_path, cfg.datasets.path)
    width = cfg.prepare_dataset.transform.width
    height = cfg.prepare_dataset.transform.height
    crop = cfg.datasets.crop_images
    data_json_filename = os.path.join(data_path, json_filename)
    img_folder = os.path.join(data_path, img_folder)

    # transformation to preprocess the images
    transform= transforms.Compose([
        transforms.Resize((width,height), interpolation=torchvision.transforms.InterpolationMode.BICUBIC)
        ])
    data_set = Oral_Dataset(data_json_filename, img_folder, transform=transform, crop=crop)
    print(data_set.__len__(), Counter(data_set.labels))
    return data_set

# testing main
if __name__ == '__main__':

    transform= transforms.Compose([
        transforms.Resize((300,300), interpolation=torchvision.transforms.InterpolationMode.BICUBIC)
        ])

    train = Oral_Dataset(
        'data/oral_dataset/train.json',
        'data/oral_dataset/images/',
        transform=transform,
        crop=False)
    imgs, lbl = train.__getitem__(0)
    print(imgs.shape)
    for i in range(train.__len__()):
        print(i)
        imgs, lbl = train.__getitem__(i)
        plt.rcParams["figure.figsize"] = (8,8)
        plt.imshow(  imgs.permute(1, 2, 0)  )
        plt.title("label " + str(lbl))
        plt.show()


from datetime import datetime

def timer(func_name: str):
    def decorate(function):
        def wrapper(*args, **kwargs):
            start = datetime.now()
            result = function(*args, **kwargs)
            end = datetime.now()
            print(
                "function execution time: {time.seconds}s, {time.microseconds}ms".format(
                    time=end - start
                )
            )
            return result
        return wrapper
    return decorate


import torch.nn as nn
import transformers
from transformers import DistilBertModel

class DistilBERT_Arch(nn.Module):
    def __init__(self, bert):
      super(DistilBERT_Arch, self).__init__()
      self.l1 = DistilBertModel.from_pretrained("distilbert-base-uncased")
      self.pre_classifier = nn.Linear(768, 768)
      self.dropout = nn.Dropout(0.3)
      self.classifier = nn.Linear(768, 2)

    #define the forward pass
    def forward(self, input_ids, attention_mask):
      output_l = self.l1(input_ids=input_ids, attention_mask=attention_mask)
      hidden_state = output_l[0]
      pooler = hidden_state[:, 0]
      pooler = self.pre_classifier(pooler)
      pooler = nn.ReLU()(pooler)
      pooler = self.dropout(pooler)
      output = self.classifier(pooler)
      return output


import os

import pint
import numpy as np

from quantum_systems import construct_pyscf_system_rhf
from quantum_systems.time_evolution_operators import LaserField

from isborn_laser import IsbornLaser

def get_h2_system(basis="sto-3g", spin_dependent=True, spin_direction="up"):
    # Bond lengths are found here:
    # https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Supplemental_Modules_(Physical_and_Theoretical_Chemistry)/Chemical_Bonding/Fundamentals_of_Chemical_Bonding/Chemical_Bonds/Bond_Lengths_and_Energies

    ureg = pint.UnitRegistry()
    bond_length = (74 * ureg.pm).to(ureg.bohr).magnitude
    molecule = f"h 0.0 0.0 {-bond_length / 2}; h 0.0 0.0 {bond_length / 2}"

    h2 = construct_pyscf_system_rhf(molecule, basis=basis)

    polarization_vector = np.zeros(3)
    # Negative sign for the charge of the electron
    polarization_vector[2] = -1

    h2.set_time_evolution_operator(
        LaserField(
            IsbornLaser(E_max=0.1), polarization_vector=polarization_vector
        )
    )

    if spin_dependent:
        remove_dipole_component(h2, spin_direction=spin_direction)

    os.environ["OMP_NUM_THREADS"] = "4"
    os.environ["MKL_NUM_THREADS"] = "4"

    return h2

def get_lih_system(basis="sto-3g", spin_dependent=True, spin_direction="up"):
    bond_length = 3.08  # Bohr
    molecule = f"li 0.0 0.0 0.0; h 0.0 0.0 {bond_length}"

    lih = construct_pyscf_system_rhf(molecule, basis)

    polarization_vector = np.zeros(3)
    # Negative sign for the charge of the electron
    polarization_vector[2] = -1

    lih.set_time_evolution_operator(
        LaserField(
            IsbornLaser(E_max=0.01), polarization_vector=polarization_vector
        )
    )

    if spin_dependent:
        remove_dipole_component(lih, spin_direction=spin_direction)

    os.environ["OMP_NUM_THREADS"] = "4"
    os.environ["MKL_NUM_THREADS"] = "4"

    return lih

def get_co_system(basis="sto-3g", spin_dependent=True, spin_direction="up"):
    ureg = pint.UnitRegistry()

    bond_length = (143 * ureg.pm).to(ureg.bohr).magnitude
    molecule = f"c 0.0 0.0 0.0; o 0.0 0.0 {bond_length}"

    co = construct_pyscf_system_rhf(molecule, basis)

    polarization_vector = np.zeros(3)
    # Negative sign for the charge of the electron
    polarization_vector[2] = -1

    co.set_time_evolution_operator(
        LaserField(
            IsbornLaser(E_max=0.01), polarization_vector=polarization_vector
        )
    )

    if spin_dependent:
        remove_dipole_component(co, spin_direction=spin_direction)

    os.environ["OMP_NUM_THREADS"] = "4"
    os.environ["MKL_NUM_THREADS"] = "4"

    return co

def get_time_steps(t_start=0, t_end=50, dt=0.002):
    # Time units are in femtoseconds

    ureg = pint.UnitRegistry()

    t_start = (t_start * ureg.fs).to(ureg.a_u_time).magnitude
    t_end = (t_end * ureg.fs).to(ureg.a_u_time).magnitude
    dt = (dt * ureg.fs).to(ureg.a_u_time)
    dt = 1e-2

    num_steps = int((t_end - t_start) / dt + 1)
    time_points = np.linspace(t_start, t_end, num_steps)

    return time_points, num_steps

def remove_dipole_component(system, axis=2, spin_direction="up"):
    if spin_direction == "up":
        system._dipole_moment[axis, 1::2, 1::2] = 0
    else:
        system._dipole_moment[axis, ::2, ::2] = 0

if __name__ == "__main__":
    import matplotlib.pylab as plt

    from coupled_cluster.ccd import OATDCCD

    h2 = get_h2_system(basis="6-31g**")
    plt.imshow(h2.dipole_moment.real[2])
    plt.show()
    remove_dipole_component(h2)
    plt.imshow(h2.dipole_moment.real[2])
    plt.show()
    OATDCCD(h2, verbose=True).compute_ground_state()

    lih = get_lih_system(basis="6-31g**")
    plt.imshow(lih.dipole_moment.real[2])
    plt.show()
    remove_dipole_component(lih)
    plt.imshow(lih.dipole_moment.real[2])
    plt.show()
    OATDCCD(lih, verbose=True).compute_ground_state()

    co = get_co_system(basis="6-31g**")
    plt.imshow(co.dipole_moment.real[2])
    plt.show()
    remove_dipole_component(co)
    plt.imshow(co.dipole_moment.real[2])
    plt.show()
    OATDCCD(co, verbose=True).compute_ground_state()


from prettytable import PrettyTable

def collect_model_info(model, rich_text=False):
    def bool2str(input):
        if input:
            return "Y"
        else:
            return "N"

    def shape_str(size):
        size = [str(s) for s in size]
        return "X".join(size)

    def min_max_str(input):
        return "Min:{:.3f} Max:{:.3f}".format(input.min(), input.max())

    def param_size(size, dtype="float32"):
        if dtype == "float32":
            size = size * 4
        elif dtype == "float16":
            size = size * 2
        else:
            raise NotImplementedError()
        return size / 1024.0 / 1024.0

    if not rich_text:
        table = PrettyTable(["Parameter Name", "Requires Grad", "Shape", "Value Scale"])
        total_size = 0
        for name, param in model.named_parameters():
            total_size += param.numel()
            table.add_row(
                [
                    name,
                    bool2str(param.requires_grad),
                    shape_str(param.size()),
                    min_max_str(param),
                ]
            )
        table.add_row(
            ["Total Number Of Params", "fp32", "%.4f" % param_size(total_size), "MB"]
        )
        return "\n" + table.get_string(title="Model Information")
    else:
        pass


from fastapi import APIRouter

from app.models.transaction import TrRegionEnum, TrType
from app.schemas.transaction import TransactionReportCreateSchema
from app.services.transaction import TransactionService
from app.services.transaction_report import TransactionReportService

router = APIRouter(
    prefix="/transactions/transaction_report",
    tags=["transaction report"]
)

@router.post("")
async def create_transaction_report(transaction: TransactionReportCreateSchema):
    async with TransactionReportService() as service:
        return await service.create_transaction_report(transaction)

@router.get("/region")
async def get_transaction_report_by_region(region: TrRegionEnum):
    async with TransactionReportService() as service:
        return await service.get_transaction_report_by_region(region)

@router.get("/user")
async def get_transaction_report_by_user_hash(user_hash: str):
    async with TransactionService() as service:
        return await service.get_transaction_by_user_hash_and_type(user_hash=user_hash, type=TrType.REPORT)


from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilename, asksaveasfile
from PyPDF2 import PdfFileReader

# =================open file method======================
def openFile():
    file = askopenfilename(defaultextension=".pdf",
                           filetypes=[("Pdf files", "*.pdf")])
    if file == "":
        file = None
    else:
        fileEntry.delete(0, END)
        fileEntry.config(fg="black")
        fileEntry.insert(0, file)

def convert():
    try:
        pdf = fileEntry.get()
        pdfFile = open(pdf, 'rb')
        # creating a pdf reader object
        pdfReader = PdfFileReader(pdfFile)

        # creating a page object
        pageObj = pdfReader.getPage(0)

        # extracting text from page
        extractedText = pageObj.extractText()
        readPdf.delete(1.0, END)
        readPdf.insert(INSERT, extractedText)

        # closing the pdf file object
        pdfFile.close()
    except FileNotFoundError:
        fileEntry.delete(0, END)
        fileEntry.config(fg="red")
        fileEntry.insert(0, "Please select a pdf file first")
    except:
        pass

def save2word():
    text = str(readPdf.get(1.0, END))
    wordfile = asksaveasfile(mode='w', defaultextension=".doc",
                             filetypes=[("word file", "*.doc"),
                                        ("text file", "*.txt"),
                                        ("Python file", "*.py")])

    if wordfile is None:
        return
    wordfile.write(text)
    wordfile.close()
    print("saved")
    fileEntry.delete(0, END)
    fileEntry.insert(0, "pdf Extracted and Saved...")

# =================== Front End Design
root = Tk()
root.geometry("600x350")
root.config(bg="black")
# root.title("PDF Converter")
root.resizable(0, 0)

defaultText = "\n\n\n\n\t\t Your extracted text will appear here.\n \t\tYou can also modify the extracted text."
# ==============App Name==============================================================>>
appName = Label(root, text="PDF to Word, Txt or Python file Converter ", font=('arial', 20, 'bold'),
                bg="black", fg='white')
appName.place(x=20, y=5)
# Select pdf file
labelFile = Label(root, text="Select Pdf File", font=('arial', 12, 'bold'), bg='black', fg='white')
labelFile.place(x=30, y=50)
fileEntry = Entry(root, font=('Arial', 12), width=40)
fileEntry.pack(ipadx=200, pady=50, padx=150)
# ===========button to access openFile method=================================
openFileButton = Button(root, text=" Open ", font=('arial', 10, 'bold'), width=36,
                        bg="blue", fg='white', command=openFile)
openFileButton.place(x=150, y=80)
# ===========button to access convert method=================================
convert2Text = Button(root, text="Read Your File", font=('arial', 10, 'bold'),
                      bg="blue", fg='WHITE', width=20, command=convert)
convert2Text.place(x=221, y=120)
# ======================= Text Box to read pdf file and modify ===================>>
readPdf = Text(root, font=('Arial', 12), fg='black', bg='white', width=60, height=30, bd=10)
readPdf.pack(padx=30, ipadx=30, pady=30, ipady=30)
readPdf.insert(INSERT, defaultText)
# ===============================Button to access save2word method=================
save2Word = Button(root, text="Save Your File", font=('arial', 10, 'bold'),
                   bg="BLUE", fg='WHITE', command=save2word)
save2Word.place(x=245, y=320)

# ===================halt window=============================>>
if __name__ == "__main__":
    root.mainloop()


import ssl
import urllib.request
import re
import json
from bs4 import BeautifulSoup
import platform
import os
import sys
import xdg

ssl._create_default_https_context = ssl._create_unverified_context

headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' }

file_path = './show_list.json'

def parse_request(request, tag, attribute_object):
    anchors = []
    with urllib.request.urlopen(request) as response:
        parsedHtml = BeautifulSoup(response.read(), 'html.parser')
        filtered_tags = parsedHtml.findAll(tag, attrs=attribute_object)
        return filtered_tags

def get_show_names(path):
    with open(path, encoding='utf-8') as show_list_file:
        return json.load(show_list_file)

def parse_show_names(show_list):
    def space_replace(show_name): return show_name.replace(" ", "+")
    return list(map(space_replace, show_list))

def get_torrent_urls(show_list):
    torrent_urls = []
    for show_name in show_list:
        req_url = 'https://1337x.to/search/{}/1/'.format(show_name)
        req_raw = urllib.request.Request(req_url, headers = headers)
        torrent_links = parse_request(req_raw, 'a', {'href': re.compile("^/torrent/")})
        torrent_urls.append(torrent_links[0].get('href'))
    return torrent_urls

def get_magnet_links(torrent_links):
    magnet_links = []
    for link in torrent_links:
        request = urllib.request.Request('https://1337x.to{}'.format(link), headers = headers)
        magnet_urls = parse_request(request, 'a', {'class': "dcfdbcda btn btn-cfaedbab" })
        magnet_links.append(magnet_urls[0].get('href'))
    return magnet_links

def open_magnet_links(torrent_urls):
    o = platform.system()
    print(o)
    for torrent in torrent_urls:
        if(o == "Windows"):
            os.startfile(torrent)
        else:
            xdg-open(torrent) #For linux users

show_list = get_show_names(file_path)

s = parse_show_names(show_list)

t = get_torrent_urls(s)

m = get_magnet_links(t)

open_magnet_links(m)


import configparser
import time

from pymouse import PyMouse
from pykeyboard import PyKeyboard
from datetime import datetime

mouse = PyMouse()
keyboard = PyKeyboard()

keymap_dict = {
    'up': keyboard.up_key,
    'down': keyboard.down_key,
    'left': keyboard.left_key,
    'right': keyboard.right_key,
    'enter': keyboard.enter_key,
    'ctrl': keyboard.control_l_key,
    'alt': keyboard.alt_l_key,
    'tab': keyboard.tab_key
}

def remove_space(raw_string):
    return str(raw_string).strip()

def string_to_int(value_time_hour_minute_second):
    hour, minute, second = [int(i) for i in str(value_time_hour_minute_second).split(':')]
    return [hour, minute, second]

def key_times_split(key_times):
    key, times = str(key_times).split(',')
    key_new = remove_space(key)
    times_new = remove_space(times)
    return key_new, times_new

def parse_config():
    config = configparser.ConfigParser()
    config.read('config.ini')
    config_sections = config.sections()

    config_dict = []
    for section in config_sections:
        option = config.options(section)

        time_hour_minute_second = option[0]
        value_time_hour_minute_second = config[section][time_hour_minute_second]
        time_list = string_to_int(value_time_hour_minute_second)

        keys = option[1:]

        key_times_list = []
        for key in keys:
            key_times = config[section][key]
            key, times = key_times_split(key_times)
            key_times_list.append([key, int(times)])

        config_dict.append([time_list, key_times_list])
    return config_dict

def press_key_custom(key_times_list):
    for key, times in key_times_list:
        for _ in range(times):
            keyboard.press_key(keymap_dict.get(key, key))
            time.sleep(1)

def is_in_time_range(hour, minute, second):
    h = datetime.now().hour
    m = datetime.now().minute
    s = datetime.now().second

    if h == hour and m == minute and second - 1 <= s <= second + 3:
        return True
    else:
        return False

def main():
    config_list = parse_config()

    while 1:
        time.sleep(1)
        for each_config in config_list:
            hour, minute, second = each_config[0]
            key_times_list = each_config[1]

            time_flag = is_in_time_range(hour, minute, second)
            if time_flag:
                press_key_custom(key_times_list)
                time.sleep(4)

if __name__ == '__main__':
    main()


import functools

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from images.models import ImagePost
from .models import *

# Create your views here.

def home(request):
    if not request.user.is_authenticated():
        messages.add_message(request, messages.ERROR, "请登录或注册账号", extra_tags='login')
        return redirect('/')
    postss = query_posts(1)
    return render(request, 'timeline/timeline.html', {"posts": postss, "user": request.user.myuser})

def posts(request):
    try:
        page = int(request.GET['page'])
    except:
        page = 1
    try:
        name = request.GET['name']
    except:
        name = ""
    postss = query_posts(page, name)
    return render(request, 'timeline/card.html', {"posts": postss, "user": request.user.myuser})

def photos(request):
    return render(request, 'timeline/image-card.html', {"photos": range(10)})

def comments(request):
    """
    Use GET method containing 'post-id'(ImagePost id number)
    e.g. timeline/comments?post-id=123
    :return: comments list or 404
    """
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    comments = image_post.comments
    return render(request, 'timeline/comments.html', {'comments': comments, "post": image_post})

def add_comment(request):
    """
    Use POST method containing 'post-id'(ImagePost id number), 'content'(Comment Content)
    :return: comments list or 404
    """
    if request.user.is_authenticated():
        user = request.user.myuser
        id = request.POST['post-id']
        image_post = get_object_or_404(ImagePost, id=id)
        content = request.POST['content']

        comment = Comment(user=user, content=content, image_post=image_post)
        comment.save()

        comments = image_post.comments
        return render(request, 'timeline/comments.html', {'comments': comments, "post": image_post})
    else:
        messages.add_message(request, messages.ERROR, "请登录或注册账号", extra_tags='login')
        return redirect('/')

def like(request):
    """
    Use GET method containing 'post-id'(ImagePost id number)
    e.g. timeline/like?post-id=123
    """
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    user = request.user.myuser
    user.like_images.add(image_post)
    user.save()
    return HttpResponse("OK")

def unlike(request):
    """
    Use GET method containing 'post-id'(ImagePost id number)
    e.g. timeline/unlike?post-id=123
    """
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    user = request.user.myuser
    user.like_images.remove(image_post)
    user.save()
    return HttpResponse("OK")

def tags(request):
    id = request.GET['post-id']
    image_post = get_object_or_404(ImagePost, id=id)
    tags = image_post.tags

def query_posts(page, name=""):
    return ImagePost.objects.filter(is_private=False).filter(theme__name__icontains=name).order_by('-upload_time')[page*10-10:page*10]


from products.models import Product
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from sales.models import Sale, SaleDetail, PayMethod
from .serializer import SaleSerializer
from shop_cart.api.serializers import ShopCartSerializer, ShopCartDetailSerializer
from shop_cart.models import ShopCart, ShopCartDetail

class SaleModelViewSet(ModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = SaleSerializer

    def get_queryset(self):
        if not self.request.user.is_staff:
            return Sale.objects.filter(user=self.request.user)
        else:
            return Sale.objects.all()

    def create(self, request, *args, **kwargs):
        state = ShopCartDetail.OPEN
        cart = ShopCart.objects.get(user=request.user)
        cart_elem = ShopCartDetail.objects.filter(shopcart=cart, state=state)
        if cart_elem:
            cart_serializer = ShopCartSerializer(cart)
            cart_detail_serializer = ShopCartDetailSerializer(data=cart_serializer.data["details"], many=True)
            cart_detail_serializer.is_valid(raise_exception=True)
            sale = Sale(pay_method=PayMethod.objects.get(id=self.request.data["pm"]), client=self.request.user, delivery_cost=self.request.data["delivery_cost"])
            sale.save()
            for sd in cart_detail_serializer.initial_data:
                prod = Product.objects.get(pk=sd["product"])
                if prod.stock_unit >= sd["quantity"] and sd["state"] == 1:
                    sale_det = SaleDetail(sale=sale,
                                          shop_cart_detail=ShopCartDetail.objects.get(pk=sd["id"]))
                    sale_det.save()
            sale = Sale.objects.get(pk=sale.id)
            saleserializer = SaleSerializer(sale)
            return Response(data=saleserializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response({"error":"El carro de compras está vacío"})

class DirectSaleModelViewSet(ModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = SaleSerializer
    http_method_names = ['post']

    def get_queryset(self):
        if not self.request.user.is_staff:
            return Sale.objects.filter(user=self.request.user)
        else:
            return Sale.objects.all()

    def create(self, request, *args, **kwargs):
        cart = ShopCart.objects.get(user=request.user)
        sale = Sale.objects.create(pay_method=PayMethod.objects.get(id=self.request.data["pm"]),
                                   client=self.request.user,
                                   delivery_cost=self.request.data["delivery_cost"])
        shop_cart_det = ShopCartDetail(product=Product.objects.get(pk=self.request.data["product"]),
                                                      quantity=self.request.data["quantity"],
                                                      shopcart=cart,
                                                      state=ShopCartDetail.SELL)
        shop_cart_det.save()
        sale_det = SaleDetail(sale=sale,
                              shop_cart_detail=shop_cart_det)
        sale_det.save()
        sale = Sale.objects.get(pk=sale.id)
        saleserializer = SaleSerializer(sale)
        return Response(data=saleserializer.data, status=status.HTTP_201_CREATED)


from django import template
from betinf.models import Match, Game
register = template.Library()

@register.filter
def matchgames(games, match_pk):
    out_games = Game.objects.all().filter(match=Match.objects.get(match_pk=match_pk))
    return out_games

@register.filter
def addstr(arg1, arg2):
    """concatenate arg1 & arg2"""
    return str(arg1) + str(arg2)

@register.filter
def set_team1_score(sets, game):
    game = Game.objects.get(game_pk=game.game_pk)
    a = sets.filter(game=game, set_num=game.num_sets)
    if len(list(a))>0:
        return a[0].team1_score
    return -1

@register.filter
def set_team2_score(sets, game):
    game = Game.objects.get(game_pk=game.game_pk)
    a = sets.filter(game=game, set_num=game.num_sets)
    if len(list(a))>0:
        return a[0].team2_score
    return -1


import boto3
from simple_term_menu import TerminalMenu
from pprint import pprint

from botocore.exceptions import ClientError

ec2 = boto3.client('ec2')

def view_sg():
    response = ec2.describe_instances(

)
    all_instances=response['Reservations']
    count = 0
    for item in all_instances:
        count += 1
        private_ip_address = item['Instances'][0]['NetworkInterfaces'][0]['PrivateIpAddress']
        # pprint(private_ip_address)
        response_private = ec2.describe_instances(
    Filters=[
        {
            'Name': 'private-ip-address',
            'Values': [
                private_ip_address,
            ]
        },
    ],

)
        try:
            list_groups = response_private['Reservations'][0]['Instances'][0]['SecurityGroups']
        except IndexError:
            list_groups = f"List index called out of range,{private_ip_address} needs to be checked manually"
        try:
            try:
                instance_name = response_private['Reservations'][0]['Instances'][0]['Tags'][0]['Value']
            except IndexError:
                continue
        except KeyError:
            instance_name = "No tag so no name given!!!"
        print(private_ip_address)
        print(f"\nSecurity Groups in {private_ip_address} Name --> {instance_name}\n")
        for item in list_groups:
            print(str(item).replace("{","").replace("}",""))
        print(count)

view_sg()


import gdual as gd
# from apgf_forward_log import APGF_Forward
from apgf_forward_symb_log import APGF_Forward_symb
import forward as fwd

import time
import numpy as np

import matplotlib.pyplot as plt
import pickle

# subtitle = ', alternating ys, Poiss/Poiss'
# subtitle = ''

filename_prefix = 'evalvsDelta2'

DELTAS = np.linspace(0.05, 0.95, 19)
n_DELTAS = len(DELTAS)

n_reps = 1

# y = np.array([1,3,4,8,23,21,56,138,132,207,244,199,182,134,115,89,55,27,34,22,18,10,5,8,7,1]) # case 1
y = np.array([1,82,104,111,391,499,665,360,192,167,142,126,69,29,30,17,39,17,8,6]) # case 2
# y = np.array([1,2,3])
K = len(y)
# lmbda = np.array([5, 5, 5, 5, 5, 5, 5]).reshape(-1, 1)
lmbda = np.array(y * 0.3).reshape(-1, 1)
rho = np.array([0.25] * K)

imm_pgf_name = 'poisson'
if imm_pgf_name == 'poisson':
    imm_pgf = fwd.poisson_pgf
elif imm_pgf_name == 'negbin':
    imm_pgf = fwd.negbin_pgf

off_pgf_name = 'poisson'
if off_pgf_name == 'bernoulli':
    off_pgf = fwd.bernoulli_pgf
elif off_pgf_name == 'poisson':
    off_pgf = fwd.poisson_pgf

distn_name = 'P+P'

rt_fwd             = np.zeros(n_DELTAS)
# rt_apgffwd         = np.zeros(K)
rt_apgffwdsymb     = np.zeros(n_DELTAS)
nll_fwd            = np.zeros(n_DELTAS)
# nll_apgffwd        = np.zeros(K)
nll_apgffwdsymb    = np.zeros(n_DELTAS)

for k in range(n_DELTAS):
    print(k)
    delta = np.array([DELTAS[k]] * K).reshape(-1, 1)

    for n in range(n_reps):
        start = time.process_time()
        res = fwd.forward(y, imm_pgf, lmbda, off_pgf, delta, rho, GDualType=gd.LSGDual, d = 0)[0]
        end = time.process_time() - start

        nll_fwd[k] = nll_fwd[k] + (res / n_reps)
        rt_fwd[k] = rt_fwd[k] + (end / n_reps)

        # start = time.process_time()
        # res = APGF_Forward(y_k, imm_pgf, lmbda_k, off_pgf, delta, rho, GDualType=gd.LSGDual, d = 0)[0].get(0)
        # end = time.process_time() - start

        # nll_apgffwd[k] = nll_apgffwd[k] + (res / n_reps)
        # rt_apgffwd[k] = rt_apgffwd[k] + (end / n_reps)

        start = time.process_time()
        res = APGF_Forward_symb(y, imm_pgf, lmbda, off_pgf, delta, rho, GDualType=gd.LSGDual).get(0, as_log=True)
        end = time.process_time() - start

        nll_apgffwdsymb[k] = nll_apgffwdsymb[k] + (res / n_reps)
        rt_apgffwdsymb[k] = rt_apgffwdsymb[k] + (end / n_reps)

        # nll_mean_rel_error[k] = nll_mean_rel_error[k] + (np.abs(nll_fwd - nll_apgffwd) / np.abs(nll_fwd) / n_reps)

result = {}
result['experiment'] = 'eval_apgffwd_vs_Delta'
result['n_reps'] = n_reps
result['x'] = DELTAS
result['rt'] = [rt_fwd, rt_apgffwdsymb]
result['nll'] = [nll_fwd, nll_apgffwdsymb]
result['imm_pgf'] = imm_pgf_name
result['off_pgf'] = off_pgf_name
result['y'] = y
result['lmbda'] = lmbda
result['rho'] = rho

# pickle.dump()

# Y = np.sum(y)
# Ys = Y * LAMBDAS
# Y_max = np.max(y)
# Y_maxs = Y_max * LAMBDAS

# plt.plot(LAMBDAS, nll_fwd, LAMBDAS, nll_apgffwd, LAMBDAS, nll_apgffwdsymb)
# plt.legend((['fwd', 'apgffwd', 'apgffwd_symb']))
plt.plot(DELTAS, nll_fwd, DELTAS, nll_apgffwdsymb)
plt.legend((['fwd', 'apgffwd_symb']))
plt.xlabel('Delta')
plt.ylabel('nll')
plt.title('NLL vs pop scale,{}'.format(distn_name))
plt.show()
# plt.savefig('{}_{}.nll.png'.format(filename_prefix, distn_name))

# plt.plot(DELTAS, np.abs(nll_fwd - nll_apgffwdsymb) / np.abs(nll_fwd))
# # plt.legend((['fwd', 'apgffwd', 'apgffwd_symb']))
# plt.xlabel('Delta')
# plt.ylabel('nll relative error')
# plt.title('NLL Relative Error,{}'.format(distn_name))
# plt.show()
# plt.savefig('{}_{}.relerr.png'.format(filename_prefix, distn_name))

# # plt.plot(Ys, rt_fwd, Ys, rt_apgffwd)
# # plt.plot(LAMBDAS, rt_fwd, LAMBDAS, rt_apgffwd, LAMBDAS, rt_apgffwdsymb)
# # plt.legend((['fwd', 'apgffwd', 'apgffwd_symb']))
# plt.plot(DELTAS, rt_fwd, DELTAS, rt_apgffwdsymb)
# plt.legend((['fwd', 'apgffwd_symb']))
# # plt.xlabel('Y')
# plt.xlabel('Delta')
# plt.ylabel('rt')
# plt.title('RT vs pop scale,{}'.format(distn_name))
# plt.show()
# plt.savefig('{}_{}.rt.png'.format(filename_prefix, distn_name))

# plt.plot(Y_maxs, rt_fwd, Y_maxs, rt_apgffwd)
# plt.legend((['fwd', 'apgffwd']))
# plt.xlabel('max(y)')
# plt.ylabel('rt')
# plt.title('RT vs max count')
# plt.show()

print('Done.')


from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.garden.filebrowser import FileBrowser
from os.path import sep, expanduser, isdir, dirname
import multiprocessing as mp
import time
import sys
import traceback
from PIL import Image

import predict
import createModel

# Global variables to output messages
selected_file_path = "No File Selected"
error_message = "[color=f44336]{}[/color]"
status_message = "{}"
good_message = "[color=4CAF50]{}[/color]"

# Global reference to main app
global_mainApp = None

# this class represents the browser to select file
class BrowseApp(App):
	MainApp = None

	# sets main app of browser
	def setMainAPP(self, MainAPP):
		self.MainApp = MainAPP

	# called when browser opens
	def build(self):
		user_path = dirname(expanduser('~')) + sep + 'Documents'
		browser = FileBrowser(select_string='Select',
							  favorites=[(user_path, 'Documents')])
		browser.bind(
					on_success=self._fbrowser_success,
					on_canceled=self._fbrowser_canceled)
		return browser

	# called when browser cancelled
	def _fbrowser_canceled(self, instance):
		print ('cancelled, Close self.')
		raise ValueError("No File Selected")

	# called when browser selects file
	def _fbrowser_success(self, instance):
		global global_mainApp
		print (instance.selection)
		selected_file_path = instance.selection

		print("Main App Value is: ", type(global_mainApp))

		# Browser throws the selected file string as error
		# So that the main app can catch it
		raise ValueError(str(selected_file_path[0]))

# A class to handel parallel processing
# Used for opneing browser
class Process(mp.Process):
	def __init__(self, *args, **kwargs):
		mp.Process.__init__(self, *args, **kwargs)
		self._pconn, self._cconn = mp.Pipe()
		self._exception = None

	def run(self):
		try:
			mp.Process.run(self)
			self._cconn.send(None)
		except Exception as e:
			tb = traceback.format_exc()
			self._cconn.send((e, tb))
			# raise e  # You can still rise this exception if you need to

	@property
	def exception(self):
		if self._pconn.poll():
			self._exception = self._pconn.recv()
		return self._exception

# This function is called when "Select File" Button is pressed
def btn_browse(pos):
		global global_mainApp
		global selected_file_path

		print ('pos: printed from root widget: {pos}'.format(pos=pos))
		app = BrowseApp()
		# app.setMainAPP(global_mainApp)

		p = Process(target=app.run)
		p.start()
		p.join()

		while p.is_alive():
			time.sleep(0.5)

		path = ""
		if p.exception:
			print("found exception")
			error, traceback = p.exception
			# print "Caught Exception: ", str(traceback)
			print ("Caught Error: {}".format(str(error)))
			path = str(error)

		global_mainApp.update(main_label=path, status=good_message.format("Ready!"))
		selected_file_path = path

# This function is called when "Predict" Button is pressed
def btn_predict(pos):
	global global_mainApp
	global selected_file_path
	print ("Strating Prediction")
	try:
		im=Image.open(selected_file_path)
		image = predict.getImage(im)
		global_mainApp.update(status=status_message.format("Predicting..."))
		predictedLetter = predict.predictLetter(image)
		result = "PREDICTION RESULT = {}".format(predictedLetter[0])
		global_mainApp.update(status=good_message.format(result))
		# do stuff
	except IOError:
		# filename not an image file
		global_mainApp.update(status=error_message.format("Invalid Image or Path"))

# This function is called when "Train" Button is pressed
def btn_retrain(pos):
	global global_mainApp
	global_mainApp.update(status=status_message.format("Training..."))
	createModel.BeginTraining()
	global_mainApp.update(status=good_message.format("Ready!"))

# This is the class that represents the main screen and its buttons
class RootWidget(BoxLayout):
	MainLabel = Label(text=selected_file_path)
	ErrorLabel = Label(text=error_message)

	def __init__(self, MainApp, **kwargs):
		global global_mainApp

		self.MainApp = MainApp
		global_mainApp = self.MainApp

		center = (self.get_center_x(), self.get_center_y())
		print (str(center))

		super(RootWidget, self).__init__(**kwargs)
		self.orientation = 'vertical'
		self.MainLabel=Label(text=selected_file_path)
		self.add_widget(self.MainLabel)

		button_layout = BoxLayout(orientation='horizontal', pos=center)
		btn1 = Button(text='Select File', size_hint = (None, 0.3), width=250, pos=center)
		btn1.bind(on_press=btn_browse)
		button_layout.add_widget(btn1)

		btn2 = Button(text='Predict', size_hint = (None, 0.3), width=250, pos = center)
		btn2.bind(on_press=btn_predict)
		button_layout.add_widget(btn2)

		btn3 = Button(text='Train', size_hint = (None, 0.3), width=250, pos = center)
		btn3.bind(on_press=btn_retrain)
		button_layout.add_widget(btn3)

		self.add_widget(button_layout)

		self.ErrorLabel = Label(text=good_message.format("Ready!"), markup=True)
		self.add_widget(self.ErrorLabel)

	def getMainLabel(self):
		return self.MainLabel

	def getOtherLabel(self):
		return self.ErrorLabel

# The globally main app class
class TestApp(App):

	def build(self):
		self.MainWidget = RootWidget(MainApp=self)
		return self.MainWidget

	def on_start(self):
		print ("Starting App")

	def update(self, main_label="", status=""):
		print ("Updating Label: {}".format(main_label))
		if(len(main_label)>0):
			self.MainWidget.getMainLabel().text = main_label

		if(len(status)>0):
			self.MainWidget.getOtherLabel().text = status

	def on_pause(self):
		print ("App Paused")
		# Here you can save data if needed
		return True

	def on_resume(self):
		print ("App Resumed")
		# Here you can check if any data needs replacing (usually nothing)
		pass

# The main function
if __name__ == '__main__':
	TestApp().run()


import argparse
import sys

import coko.classes.configuration as configuration
import coko.classes.exceptions as exceptions

def parse_arguments(args: list=None) -> configuration.Configuration:
    """ Parse console arguments to generate a Configuration object we
    can work with.

    :param args: Argument list. Usually it's the command you entered but split by spaces.
    :return: Configuration object generated from parsed parameters console command.
    """
    arg_parser = argparse.ArgumentParser(description="A tool to overwrite directories "
                                                     "using files from a different "
                                                     "owners but keeping original "
                                                     "owners and permissions.\n",
                                         epilog="Follow coko development at: "
                                                "<https://github.com/dante-signal31/coko>")
    arg_parser.add_argument(dest="source_folder",
                            metavar="SOURCE_FOLDER",
                            nargs=1, default=None,
                            help="Source folder where you want copy files from.")
    arg_parser.add_argument(dest="destination_folder",
                            metavar="DESTINATION_FOLDER",
                            nargs=1, default=None,
                            help="Destination folder where you want copy "
                                 "files to.")
    arg_parser.add_argument("-c", "--create", dest="default_ownership",
                            nargs=3, type=int,
                            metavar=("UID", "GID", "PERMISSION"),
                            default=None,
                            help="Copy over files not present at destination "
                                 "folder yet and set for them given uid and gid " \
                                 "and permission.")

    # Parse_args returns each parameter in a list. We must take them out so
    # every value at dict is a string.
    parsed_arguments = {item: (value[0] if item != "default_ownership"
                               else value)
                        for (item, value) in vars(arg_parser.parse_args(args)).items()}
    # User enter permission in octal, so I must add a True.
    if  parsed_arguments["default_ownership"] is not None:
        parsed_arguments["default_ownership"].append(True)
    try:
        config = configuration.Configuration(parsed_arguments["source_folder"],
                                             parsed_arguments["destination_folder"],
                                             parsed_arguments["default_ownership"])
    except exceptions.FolderNotFound as e:
        print(f"Folder not found: {e.incorrect_path}")
        sys.exit(1)
    return config


# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
Student=namedtuple('Student','ID, MARKS, CLASS, NAME')
n_student=int(input())
l=input().split()
sum1=0
j=l.index('MARKS')
for i in range(n_student):
    sum1=sum1+int(input().split()[j])
print(sum1/n_student)


#!/bin/bash

"""Runtime configuration files demonstration."""

import logging
import logging.config

def main():
    """Performs the main task of the script."""

    logging.config.fileConfig(fname="logging.ini")
    logger = logging.getLogger("appLogger")

    logger.debug("This is a debug message")

if __name__ == "__main__":
    main()


from binance.client import Client, AsyncClient  # noqa
import asyncio
async def main():

    # initialise the client
    client = await AsyncClient.create("15979876228", "zhp2672961671", testnet=True,)
    res = await client.get_exchange_info()
    print("res=======",res)
    await client.close_connection()

if __name__ == "__main__":
# 创建一个事件循环，然后使用run_until_complete将协程注册到事件循环，并启动事件循环
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


import datetime

from pyflow import Notebook, Suite, Task

now = datetime.datetime.now()

def test_follow():
    with Suite("s") as s:
        t1 = Task("t1", YMD=(now, now))
        t2 = Task("t2")
        Task("t3")

        t2.triggers = t1.complete
        t2.follow = t1.YMD

    s.check_definition()
    s.generate_node()

    s.deploy_suite(target=Notebook)

if __name__ == "__main__":
    from os import path

    import pytest

    pytest.main(path.abspath(__file__))


# _*_ coding: utf-8 _*_
import torch
import numpy
from model import BaseModel
from numpy import array
from torch import nn, optim
from torch.autograd import Variable

class GRUPytorch(BaseModel):
    """
    GUR模型，预测发电功率
    """

    def __init__(self, input_size=1, params={'hidden_dim': 5, 'hidden_layer': 2}, predict_type="wind", irradiance=None):
        """
        初始化。待完善
        """
        # 初始化父类
        super(GRUPytorch, self).__init__(predict_type=predict_type, irradiance=irradiance)

        hidden_dim = params['hidden_dim']
        hidden_layer = params['hidden_layer']
        self.__model_gru = gruModel(in_dim=input_size, hidden_dim=hidden_dim, hidden_layer=hidden_layer)

    def fit(self, feature_data, target_data, *args, **kwargs):
        """
        模型训练。当有传特征集、目标集数据进来时，则使用这两个数据对模型进行训练，否则使用类自身的特征集、目标集数据进行训练
        :param feature_data: 特征集（即天气预报数据）
        :param target_data: 目标集（即功率数据）
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                    （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
                       当厂家不提供辐照度阈值时，若要从天气预报数据中估算该值，则需以irradiance_col=XXX的形式指明
                       辐照度特征在feature中列序号（从0开始计算），否则将取默认值10
                       说明：本模型需要输入predict_term，会调用。
                       当预测周期predict_term为超短期ultra_short时，
                       模型单次预测结果输出长度为predict_step = 16，预测间隔predict_inter = 1；
                       当预测周期predict_term为短期short时，
                       模型单次预测结果输出长度为predict_step = 288，预测间隔predict_inter = 96；
                       当预测周期predict_term为5分钟超短期five_minute_ultra_short时，
                       模型单次预测结果输出长度为predict_step = 48，预测间隔predict_inter = 1；
        :return:
        """
        if "predict_term" in kwargs:
            predict_term = kwargs["predict_term"]
        else:
            predict_term = "ultra_short"

        if predict_term == "ultra_short":
            predict_step = 16
            predict_inter = 1
        elif predict_term == "short":
            predict_step = 288
            predict_inter = 96
        elif predict_term == "five_minute_ultra_short":
            predict_step = 48
            predict_inter = 1
        else:
            print("预测周期输入错误")
            predict_step = 16
            predict_inter = 1

        X, y = list(), list()
        in_start = 0
        in_start = in_start + predict_inter
        in_end = in_start + predict_step
        while in_end in range(len(feature_data)):
            Power_the_step = numpy.c_[
                feature_data[in_start:in_end, :], target_data[in_start - 1] * numpy.ones(predict_step)]
            X.append(Power_the_step)
            y.append(target_data[in_start:in_end])
            in_start = in_start + predict_inter
            in_end = in_start + predict_step
        X_fit = array(X).reshape(len(X)*predict_step, 1, feature_data.shape[1]+1)
        Y_fit = array(y)
        Y_fitdata = Y_fit.flatten().reshape(len(X)*predict_step, 1, 1)
        aaa = torch.from_numpy(X_fit)  # 变量名没有物理意义
        bbb = torch.from_numpy(Y_fitdata)
        # 模型适配
        criterion = nn.MSELoss()
        optimizer = optim.Adam(self.__model_gru.parameters(), lr=1e-2)
        # 训练模型
        for epoch in range(1500):
            # forward
            inputs = aaa.to(torch.float32)
            target = bbb.to(torch.float32)
            output = self.__model_gru(inputs)
            loss = criterion(output.reshape(-1), target.reshape(-1))
            # update paramters
            # if (epoch + 1) % 20 == 0:
            #     print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        # 对于光伏发电，若厂家没有提供光伏电场不发电时的辐照度阈值，需要自行计算
        if self._predict_type == "solar" and self._irradiance is None:
            if "irradiance_col" in kwargs:
                # 有提供辐照度特征在天气预报数据（特征集）中所在列的序号（序号从0开始算），按照一定算法计算辐照度阈值
                self._irradiance = self.compute_irradiance_gate(feature_data, target_data, kwargs["irradiance_col"])
            else:
                # 没有提供辐照度特征在天气预报数据（特征集）中所在列的序号，则按照经验给一个参考值（或做其他处理）
                self._irradiance = 10

    def predict_without_history_power(self, feature, *args, **kwargs):
        """
        不使用历史功率数据的功率预测。
        1、特征集（feature，即天气预报数据），不区分时段（白天黑夜）。光伏发电在处理时可能需要在方法实现的时候，注意将晚上的发电功率置为0。
        2、对于光伏发电，建议选取若干天气特征作为标准，当实际的天气特征低于标准时，则在预测的时候将相应的预测结果置0。
        3、此处不区分短期/超短期功率预测。派生类在实现时，若有需要，可通过len(feature) == 288、len(feature) == 16来
          区分短期/超短期预测
        4、此处不区分风电/光伏功率预测。若有需要，可在派生类实现。
        :param feature: （预测）特征集
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                     （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
                       当预测光伏发电功率时，需要以irradiance_col=XXX的形式指明辐照度特征在feature中列序号（从0开始计算）
        :return:
        """
        input_x = torch.from_numpy((numpy.c_[feature, feature[:, 0]]).reshape(len(feature), 1, feature.shape[1]+1))
        input_x = Variable(input_x)
        input_x = input_x.to(torch.float32)
        result = array(self.__model_gru(Variable(input_x)).data).reshape(-1)

        # 光伏发电时，需要对光照较弱的情况（比如夜晚）进行特殊处理（发电功率置零）
        if self._predict_type == "solar" and "irradiance_col" in kwargs:
            for index in range(len(feature)):
                if feature[index][kwargs["irradiance_col"]] <= self._irradiance:
                    result[index] = 0

        return result

    def predict_with_history_power(self, feature, history_power, *args, **kwargs):
        """
        使用历史功率数据的（单次）功率预测。本模型没有使用历史功率的功率预测实现方法，返回None。
        1、特征集（feature，即天气预报数据），不区分时段（白天黑夜）。光伏发电在处理时可能需要在方法实现的时候，注意将晚上的发电功率置为0。
        2、对于光伏发电，建议选取若干天气特征作为标准，当实际的天气特征低于标准时，则在预测的时候将相应的预测结果置0。
        3、此处不区分短期/超短期功率预测。派生类在实现时，若有需要，可通过len(feature) == 288、len(feature) == 16来
          区分短期/超短期预测
        4、此处不区分风电/光伏功率预测。若有需要，可在派生类实现。
        :param feature: （预测）特征集
        :param history_power: 上一时刻历史功率数据
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                     （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
        :return:
        """
        input_x = (numpy.c_[feature, history_power*numpy.ones(len(feature))]).reshape(len(feature), 1, feature.shape[1]+1)
        input_x = torch.from_numpy(input_x)
        input_x = Variable(input_x)
        input_x = input_x.to(torch.float32)
        result = array(self.__model_gru(Variable(input_x)).data).reshape(-1)
        return result

class gruModel(nn.Module):
    def __init__(self, in_dim, hidden_dim, hidden_layer):
        super(gruModel, self).__init__()
        self.gruLayer = nn.GRU(in_dim, hidden_dim, hidden_layer)
        self.fcLayer = nn.Linear(hidden_dim, 1)

    def forward(self, x):
        input = x.transpose(0, 1)
        out, _ = self.gruLayer(input)
        out = self.fcLayer(out)
        return out


import sys
from collections import deque
from vehicle import Vehicle
GOAL_STATE = Vehicle('X', 4, 2, 'H')

class RushHour(object):

    #Initialise a new Rush hour board
    def __init__(self, v):
        self.vehicleSet = v
    #To hash the board
    def __hash__(self):
        return hash(self.__repr__())

    #Same Vehicle
    def __eq__(self, other):
        return self.vehicleSet == other.vehicleSet

    #DIfferent Vehicle
    def __ne__(self, other):
        return not self.__eq__(other)

    #Format the board into string
    def __repr__(self):
        string = '-' * 8 + '\n'
        for line in self.get_board():
            string += '|{0}|\n'.format(''.join(line))
        string += '-' * 8 + '\n'
        return string

    #Get methods for board
    def get_board(self):

        #Represent the game board in a 2D matrix
        board = [[' ', ' ', ' ', ' ', ' ', ' '],
                 [' ', ' ', ' ', ' ', ' ', ' '],
                 [' ', ' ', ' ', ' ', ' ', ' '],
                 [' ', ' ', ' ', ' ', ' ', ' '],
                 [' ', ' ', ' ', ' ', ' ', ' '],
                 [' ', ' ', ' ', ' ', ' ', ' ']]

        #Populate the matrix with the vehicles
        for vehicle in self.vehicleSet:
            x, y = vehicle.x, vehicle.y
            if vehicle.orientation == 'H':
                for i in range(vehicle.length):
                    board[y][x + i] = vehicle.id
            else:
                for i in range(vehicle.length):
                    board[y + i][x] = vehicle.id
        return board

    #Check if the board is a solved state
    def solved(self):
        return GOAL_STATE in self.vehicleSet

    #Return Iterator/Genarator of next possible moves.
    def moves(self):
        board = self.get_board()
        """Since the object is in a set, it is unordered, every run will have
            different sequence of result"""
        for ve in self.vehicleSet:
            if ve.orientation == 'H':
                #Check left
                if ve.x - 1 >= 0 and board[ve.y][ve.x - 1] == ' ':
                    new_v = Vehicle(ve.id, ve.x - 1, ve.y, ve.orientation)
                    new_vehicleSet = self.vehicleSet.copy()
                    new_vehicleSet.remove(ve)
                    new_vehicleSet.add(new_v)
                    yield RushHour(new_vehicleSet)
                #Check right
                if ve.x + ve.length <= 5 and board[ve.y][ve.x + ve.length] == ' ':
                    new_v = Vehicle(ve.id, ve.x + 1, ve.y, ve.orientation)
                    new_vehicleSet = self.vehicleSet.copy()
                    new_vehicleSet.remove(ve)
                    new_vehicleSet.add(new_v)
                    yield RushHour(new_vehicleSet)
            else:
                #Check up
                if ve.y - 1 >= 0 and board[ve.y - 1][ve.x] == ' ':
                    new_v = Vehicle(ve.id, ve.x, ve.y - 1, ve.orientation)
                    new_vehicleSet = self.vehicleSet.copy()
                    new_vehicleSet.remove(ve)
                    new_vehicleSet.add(new_v)
                    yield RushHour(new_vehicleSet)
                #Check left
                if ve.y + ve.length <= 5 and board[ve.y + ve.length][ve.x] == ' ':
                    new_v = Vehicle(ve.id, ve.x, ve.y + 1, ve.orientation)
                    new_vehicleSet = self.vehicleSet.copy()
                    new_vehicleSet.remove(ve)
                    new_vehicleSet.add(new_v)
                    yield RushHour(new_vehicleSet)
                """Yield is return an iterator"""

def initVehicle(rushhour_file):
    #A list to hold vehicleSet
    vehicleSet = []
    for line in rushhour_file:
        line = line[:-1] if line.endswith('\n') else line
        #Convert string into charaters and integers
        id, x, y, orientation = line
        #Initialise all the vehicleSet
        vehicleSet.append(Vehicle(id, int(x), int(y), orientation))
        #[Vehicle(A, 0, 0, H), Vehicle(P, 0, 1, V)...] list
        #{Vehicle(A, 0, 0, H), Vehicle(P, 0, 1, V)...} set
    #Return the rushhour board
    return RushHour(set(vehicleSet))

def format_solution(solution):
    #Generate a list 'steps'
    steps = []
    for i in range(len(solution) - 1):
        board1, board2 = solution[i], solution[i+1]
        #find the moved blocks from both boards
        v1 = list(board1.vehicleSet - board2.vehicleSet)[0]
        v2 = list(board2.vehicleSet - board1.vehicleSet)[0]

        if v1.x < v2.x:
            steps.append('{0}R'.format(v1.id))
        elif v1.x > v2.x:
            steps.append('{0}L'.format(v1.id))
        elif v1.y < v2.y:
            steps.append('{0}D'.format(v1.id))
        elif v1.y > v2.y:
            steps.append('{0}U'.format(v1.id))
    return steps

#BFS algorithm
#Precondition: A rushhour board and maximum depth is passed into this methods
#Postcondition: A dictionary is return with solutions,visited and depth_state
def BFS(x, max_depth):

    depth = dict() #The number of states visited at each depth
    visited = set() #Total configuration visited
    solutions = list() #Paths to the goal state

    queue = deque()#double ended queue, can manipulate both side
    queue.appendleft((x, tuple())) #Tuple is a list, cannot change the elements
    while len(queue) != 0:

        board, path = queue.pop()
        new_p = path + tuple([board])
        #print(tuple([board]))
        #get the depth + 1, return 0 if doesn't exist
        depth[len(new_p)] = depth.get(len(new_p), 0) + 1

        if max_depth <= len(new_p):
            break
        #Set is unorder, use hash to find
        if board in visited:
            continue
        else:
            visited.add(board)
        if board.solved():
            solutions.append(new_p)
        else:
            queue.extendleft((move, new_p) for move in board.moves())
    return {'visited': visited, 'solutions': solutions, 'depth_states': depth}

if __name__ == '__main__':
    filename = sys.argv[1]
    #context manager to open file
    with open(filename) as rushhour_file:
        rushhour = initVehicle(rushhour_file)
    print(rushhour)

    results = BFS(rushhour, 100)

    print ('{0} Solutions found'.format(len(results['solutions'])))
    with open("Solution.txt","w+") as sol:
        sol.write('{0}'.format('\n'.join(format_solution(results['solutions'][0]))))

    for solution in results['solutions']:
        print ('Solution: {0}'.format(', '.join(format_solution(solution))))

    print ('{0} Nodes visited'.format(len(results['visited'])))


import requests

from app.models import UberService, Payments, UberSession, Fleets_drivers_vehicles_rate, Partner

from selenium_ninja.synchronizer import Synchronizer

class UberRequest(Synchronizer):

    def __init__(self, partner_id=None, fleet="Uber"):
        super().__init__(partner_id, fleet)
        self.base_url = UberService.get_value('REQUEST_UBER_BASE_URL')

    def get_header(self):
        obj_session = UberSession.objects.filter(partner=self.partner_id).latest('created_at')
        headers = {
            "content-type": "application/json",
            "x-csrf-token": "x",
            "cookie": f"sid={obj_session.session}; csid={obj_session.cook_session}"
        }
        return headers

    def get_uuid(self):
        obj_session = UberSession.objects.filter(partner=self.partner_id).latest('created_at')
        return str(obj_session.uber_uuid)

    @staticmethod
    def get_payload(query, variables):
        data = {
            'query': query,
            'variables': variables
        }
        return data

    def get_drivers_table(self):
        query = '''
          query GetDrivers(
            $orgUUID: ID!,
            $pagingOptions: PagingOptionsInput!,
            $filters: GetDriversFiltersInput
          ) {
            getDrivers(
              orgUUID: $orgUUID,
              pagingOptions: $pagingOptions,
              filters: $filters
            ) {
              orgUUID
              drivers {
                ...DriversTableRowFields
              }
              pagingResult {
                nextPageToken
              }
            }
          }

          fragment DriversTableRowFields on Driver {
            member {
              user {
                uuid
                name {
                  firstName
                  lastName
                }
                email
                phone {
                  countryCode
                  nationalPhoneNumber
                }
              }
            }
            associatedVehicles {
              uuid
              make
              model
              vin
              year
              licensePlate
            }
          }
        '''
        variables = {
                    "orgUUID": self.get_uuid(),
                    "pagingOptions": {
                        "pageSize": 25
                                    },
                    "filters": {
                                "complianceStatuses": [],
                                "vehicleAssignmentStatuses": [],
                                "documentStatuses": []
                                }
                    }
        drivers = []
        data = self.get_payload(query, variables)
        response = requests.post(self.base_url, headers=self.get_header(), json=data)
        drivers_data = response.json()['data']['getDrivers']['drivers']
        for driver in drivers_data:
            licence_plate = ''
            vehicle_name = ''
            vin_code = ''
            if driver['associatedVehicles']:
                licence_plate = driver['associatedVehicles'][0]['licensePlate']
                vehicle_name = driver['associatedVehicles'][0]['make']
                vin_code = driver['associatedVehicles'][0]['vin']
            phone = driver['member']['user']['phone']
            drivers.append({'fleet_name': self.fleet,
                            'name': driver['member']['user']['name']['firstName'],
                            'second_name': driver['member']['user']['name']['lastName'],
                            'email': driver['member']['user']['email'],
                            'phone_number': phone['countryCode'] + phone['nationalPhoneNumber'],
                            'driver_external_id': driver['member']['user']['uuid'],
                            'licence_plate': licence_plate,
                            'pay_cash': True,
                            'vehicle_name': vehicle_name,
                            'vin_code': vin_code})
        return drivers

    def save_report(self, day):
        reports = Payments.objects.filter(report_from=day, vendor_name=self.fleet, partner=self.partner_id)
        if reports:
            return list(reports)
        start = int(self.start_report_interval(day).timestamp() * 1000)
        end = int(self.end_report_interval(day).timestamp() * 1000)
        query = '''query GetPerformanceReport($performanceReportRequest: PerformanceReportRequest__Input!) {
                  getPerformanceReport(performanceReportRequest: $performanceReportRequest) {
                    uuid
                    totalEarnings
                    hoursOnline
                    totalTrips
                    ... on DriverPerformanceDetail {
                      cashEarnings
                      driverAcceptanceRate
                      driverCancellationRate
                    }
                    ... on VehiclePerformanceDetail {
                      utilization
                      vehicleIncentiveTarget
                      vehicleIncentiveCompleted
                      vehicleIncentiveEnrollmentStatus
                      vehicleIncentiveUnit
                    }
                  }
                }'''
        uber_drivers = Fleets_drivers_vehicles_rate.objects.filter(partner=self.partner_id,
                                                                   fleet__name=self.fleet)
        drivers_id = [obj.driver_external_id for obj in uber_drivers]
        variables = {
                      "performanceReportRequest": {
                        "orgUUID": self.get_uuid(),
                        "dimensions": [
                          "vs:driver"
                        ],
                        "dimensionFilterClause": [
                          {
                            "dimensionName": "vs:driver",
                            "operator": "OPERATOR_IN",
                            "expressions": drivers_id
                          }
                        ],
                        "metrics": [
                          "vs:TotalEarnings",
                          "vs:HoursOnline",
                          "vs:TotalTrips",
                          "vs:CashEarnings",
                          "vs:DriverAcceptanceRate",
                          "vs:DriverCancellationRate"
                        ],
                        "timeRange": {
                          "startsAt": {
                            "value": start
                          },
                          "endsAt": {
                            "value": end
                          }
                        }
                      }
                    }
        data = self.get_payload(query, variables)
        response = requests.post(self.base_url, headers=self.get_header(), json=data)
        if response.status_code == 200 and response.json()['data']['getPerformanceReport']:
            for report in response.json()['data']['getPerformanceReport']:
                if report['totalEarnings']:
                    driver = Fleets_drivers_vehicles_rate.objects.get(driver_external_id=report['uuid']).driver
                    order = Payments(
                        report_from=day,
                        vendor_name=self.fleet,
                        driver_id=report['uuid'],
                        full_name=str(driver),
                        total_amount=round(report['totalEarnings'], 2),
                        total_amount_without_fee=round(report['totalEarnings'], 2),
                        total_amount_cash=round(report['cashEarnings'], 2),
                        total_rides=report['totalTrips'],
                        partner=Partner.get_partner(self.partner_id))
                    order.save()
        else:
            self.logger.error(f"Failed save uber report {self.partner_id} {response}")

    def get_drivers_status(self):
        query = '''query GetDriverEvents($orgUUID: String!) {
                      getDriverEvents(orgUUID: $orgUUID) {
                        driverEvents {
                          driverUUID
                          driverStatus
                        }
                      }
                    }'''
        variables = {
                    "orgUUID": self.get_uuid()
                     }
        with_client = []
        wait = []
        data = self.get_payload(query, variables)
        response = requests.post(self.base_url, headers=self.get_header(), json=data)
        if response.status_code == 200:
            drivers = response.json()['data']['getDriverEvents']['driverEvents']
            if drivers:
                for rider in drivers:
                    driver = Fleets_drivers_vehicles_rate.objects.get(driver_external_id=rider['driverUUID']).driver
                    name, second_name = driver.name, driver.second_name
                    if rider["driverStatus"] == "online":
                        wait.append((name, second_name))
                        wait.append((second_name, name))
                    elif rider["driverStatus"] in ("accepted", "in_progress"):
                        with_client.append((name, second_name))
                        with_client.append((second_name, name))
        return {'wait': wait,
                'with_client': with_client}

    def get_vehicles(self):
        return []


from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import numpy as np
import krpc

# kRPC setup

conn = krpc.connect(name='Plotter')
vessel = conn.space_center.active_vessel

KCKF = vessel.orbit.body.reference_frame

speed = conn.add_stream(getattr, vessel.flight(KCKF), "speed")
altitude = conn.add_stream(getattr, vessel.flight(KCKF), "mean_altitude")
latitude = conn.add_stream(getattr, vessel.flight(KCKF), "latitude")
longitude = conn.add_stream(getattr, vessel.flight(KCKF), "longitude")

planet_radius = vessel.orbit.body.equatorial_radius

ksc_coord = np.array((-0.09720771, -74.55767342))

parts_i = len(vessel.parts.all)

# Plot setup

fig = plt.figure()
ax1 = fig.add_subplot(111)

xlim = 10
ylim = 10

# Gradient

colormap = ListedColormap(np.loadtxt("kerbin_colormap.txt")/255, N=256)  # made with http://jdherman.github.io/colormap/
gradient = np.linspace(0, 10, 256)
Z = np.zeros(shape=(256, 2))
n = 255

for item in gradient:
    Z[n] = np.array([item, item])
    n -= 1

data = pd.DataFrame(columns=["Horizontal distance", "Altitude"])
happenings = pd.DataFrame([[0, -1000, "Launch"]], columns=["Horizontal distance", "Altitude", "Name"])

# EVENTS (include them all as global variables inside animate())

booster_sep = False
MECO = False
SECO = False

def animate(_):
    global ksc_coord, data, happenings, xlim, ylim, parts_i, booster_sep, MECO, SECO

    position = np.array((latitude(), longitude()))
    h_distance = (np.linalg.norm(position - ksc_coord) * (2.*np.pi*planet_radius)/360.)/1000  # km

    # EVENTS

    parts = len(vessel.parts.all)

    if parts != parts_i and not booster_sep:
        booster_sep = True
        event = pd.DataFrame([[h_distance, altitude()/1000, "Booster separation"]],
                             columns=["Horizontal distance", "Altitude", "Name"])
        happenings = happenings.append(event)

    elif parts != parts_i and booster_sep and not MECO:
        MECO = True
        event = pd.DataFrame([[h_distance, altitude()/1000, "MECO"]],
                             columns=["Horizontal distance", "Altitude", "Name"])
        happenings = happenings.append(event)

    elif parts != parts_i and booster_sep and MECO and not SECO:
        SECO = True
        event = pd.DataFrame([[h_distance, altitude()/1000, "SECO"]],
                             columns=["Horizontal distance", "Altitude", "Name"])
        happenings = happenings.append(event)

    parts_i = parts

    # DATA

    if str(vessel.situation) == "VesselSituation.pre_launch" or str(vessel.situation) == "VesselSituation.landed":
        xar, yar = 0, 0
        xhap, yhap = 0, 0

    else:
        newdata = pd.DataFrame([[h_distance, altitude()/1000]], columns=["Horizontal distance", "Altitude"])
        data = data.append(newdata)

        xar = data["Horizontal distance"]
        yar = data["Altitude"]
        xhap = happenings["Horizontal distance"]
        yhap = happenings["Altitude"]

    # PLOT

    if xlim - h_distance < 5:
        xlim += 20

    if ylim - altitude()/1000 < 5:
        ylim += 10
        xlim += 10

    ax1.clear()  # can I move this to the start of the loop?
    ax1.plot(xar, yar, color="white", linewidth="3")
    ax1.scatter(xhap, yhap, color="white", linewidth="5")

    plt.xlim(-2, xlim)
    plt.ylim(0, ylim)

    if booster_sep:
        row = happenings.loc[happenings["Name"] == "Booster separation"]
        xy = (row["Horizontal distance"]+1, row["Altitude"]-0.5)
        ax1.annotate("Booster separation", xycoords='data', xy=xy, xytext=xy, color="white")

    if MECO:
        row = happenings.loc[happenings["Name"] == "MECO"]
        xy = (row["Horizontal distance"]+1, row["Altitude"]-0.5)
        ax1.annotate("MECO", xycoords='data', xy=xy, xytext=xy, color="white")

    if SECO:
        row = happenings.loc[happenings["Name"] == "SECO"]
        xy = (row["Horizontal distance"]+1, row["Altitude"]-0.5)
        ax1.annotate("SECO", xycoords='data', xy=xy, xytext=xy, color="white")

    ax1.imshow(Z, cmap=colormap, interpolation='bicubic', extent=[-2, xlim, 0, 60])
    ax1.set_axis_bgcolor('black')
    ax1.set_xlabel('Horizontal distance (km)')
    ax1.set_ylabel('Altitude (km)')

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()


import requests
from bs4 import BeautifulSoup
import threading

def get_details(cards):
    for card in cards:
        price = card.find("div",attrs ={"class":"m-srp-card__price"})
        title = card.find("a",attrs = {"class":"m-srp-card__title"})
        title_text = title.text.replace("\n"," ")
        area = card.find("div",attrs = {"class":"m-srp-card__summary__info"})
        if area:
            area_text = area.text
        else:
            area_text = None
        print("{} {} {}".format(title_text,area_text,price.text))

def generate_data(page_no):
    data = {
		"propertyType_new": "10002_10003_10021_10022",
		"city": 3327,
		"mbTrackSrc": "homeSearchForm",
		"searchType": 1,
		"propertyType": "10002,10003,10021,10022",
		"category": "S",
		"offset": 0,
		"maxOffset": 0,
		"page": page_no,
    }
    return data

for index in range(1,5):
    print("**************Page {} *********".format(index))
    data = generate_data(index)
    response = requests.post("https://www.magicbricks.com/property-for-sale/residential-real-estate?proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment&cityName=Bangalore",data = data)
    soup = BeautifulSoup(response.content,"html.parser")

    cards = soup.find_all("div",attrs ={"class":"m-srp-card__container"})
    t = threading.Thread(target=get_details,args = (cards,))
    t.start()
    # get_details(cards)


from aifc import Error
import os
from dotenv import load_dotenv
from fastapi import Body, APIRouter
from fastapi import HTTPException
from sqlalchemy import null
from models.annotate import Annotate
from models.Activity import Activity

from services.DBService import DBService
from databases.Databases import AccessDB, PostgreSQL
from schemas.annotate_schemas import annotate_serializer

load_dotenv()
router = APIRouter()
accessDBTest : AccessDB = PostgreSQL(
            os.getenv("POSTGRES_DB"),
            os.getenv("POSTGRES_SERVER"),
            os.getenv("POSTGRES_PORT"),
            os.getenv("POSTGRES_USER"),
            os.getenv("POSTGRES_PASSWORD")
        )

service = DBService(accessDBTest)

#body -> {date: "jj/mm/aaaa"}

# Obtenir la liste des annotations
@router.get('/annotations/{date}')
def getAnnotations(date: str):
    try:
        return service.getAnnotationsOfADay(date)
    except Error:
        raise HTTPException(status_code=500, detail="Error retrieving annotations")

#enlever
# Ajouter une annotation
@router.post('/annotations', status_code=201)
def addAnnotation(annotation: Annotate):
    try:
        return service.createAnnotation(annotation)
    except Error:
        raise HTTPException(status_code=500, detail="can't add annotation")

# Modifier une annotation
@router.put('/annotations/{id}')
def modifyAnnotation(annotation: Annotate):
    try:
        return service.updateAnnotation(annotation)
    except Error:
        raise HTTPException(status_code=500, detail="Can't modify annotation")

# Delete une annotation
@router.delete('/annotations/{id}')
def deleteAnnotation(id: int):
    try:
        return service.deleteAnnotation(id)
    except Error:
        raise HTTPException(status_code=500, detail="Can't delete annotation")

# Ajouter un type d'activité
@router.post('/activities', status_code=201)
def addActivity(activity: Activity):
    try:
        return service.createActivity(activity)
    except Error:
        raise HTTPException(status_code=404, detail="Can't add an activity")

# Obtenir la liste des activités possibles
@router.get('/activities')
def getActivities():
    try:
        return service.getAllActivity()
    except Error:
        raise HTTPException(status_code=404, detail="No activity existing")

# Delete un type d'activité
@router.delete('/activities/{label}')
def deleteActivity(label: str):
    try:
        return service.deleteActivity(label)
    except Error:
        raise HTTPException(status_code=404, detail="Can't delete this activity")