#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 11:19:12 2017

Exploring the basics of Neural Networks

Simple base was established off of stanfords UFLDL Tutorial found here:
http://ufldl.stanford.edu/wiki/index.php/UFLDL_Tutorial
As well found from the series by Welch labs

The rest is all me

Test Matrix:
    X = np.array(([3,5], [5,1], [10,2]), dtype=float)
    X = X/np.amax(X, axis=0)
    y = np.array(([75], [82], [93]), dtype=float)
    y = y/100

To DO:
        Update documentation

@author: christopherstewart
"""
import numpy as np

class Neural_Network(object):
    """
     General Steps in Network
     ---------------------------------:
     For [3x1] Input -> [1x1] Output
     _______________________________________
    |                                       |
    |    (1) [3x1][1x3] = [3x3]             |
    |           Input(dot)W1 = Z2           |
    |    (2) [3x3][3x1] = [3x1]             |
    |           Z2(dot)W2 = Z3              |
    |    (3) [3x1]^T[3x1] = [1x1]           |
    |           a2^T(dot)Z3 = Output        |
    |_______________________________________|

    """
    def __init__(self):
        """
        Simple network used for learning purposes
        ____________________________________________________________

        Hyperparameters (not to be changed by the network)
            -> 3x1 Input matrix
            -> 1x1 Output matrix
            -> 3 hidden layers:
                    Weight 1 = W1
                    Weight 2 = W2

        """
        self.inputLayerSize = 2
        self.outputLayerSize =1
        self.hiddenLayerSize =3
        #Weights
        self.W1 = np.random.randn(self.inputLayerSize,
                                  self.hiddenLayerSize)
        self.W2 = np.random.randn(self.hiddenLayerSize,
                                  self.outputLayerSize)

    def forward(self, X):
        """
        Moves a step forward in Network

        Inputs: -> self
                        (Current Initilized Neural Network)
                -> X
                        (Data Points)

        """
        self.z2 = np.dot(X,self.W1)
        self.a2 = self.sigmoid(self.z2)
        self.z3 = np.dot(self.a2,self.W2)
        yHat = self.sigmoid(self.z3)
        return yHat

    def sigmoid(self, z):
        """
        Simple activation function
        ____________________________________________________________
        Input:  -> Network
                            (Current Initilized Neural Network)
                -> Z
                            (This is a sub J value)

        Output:
                -> J(Z)
                            (Value at point Z in our activation function)
        """
        return 1/(1+np.exp(-z))

    def sigmoidPrime(self,z):
        """
        Gradient of our simple activation function
        ____________________________________________________________
        Input:  -> Network
                            (Current Initilized Neural Network)
                -> Z
                            (This is a sub J value)

        Output:
                -> dJ/dZ
                            (Value at point Z in our activation function)

        """
        return np.exp(-z)/((1+np.exp(-z))**2)

    def costFunction(self,X,y):
        """
        Finds the cost where cost is how wrong your current fit is.

        ____________________________________________________________
        Input:  -> Network
                            (Current Initilized Neural Network)
                 -> X
                            (Left side Input matrix)
                 -> y
                            (Right side Input matrix)

        Output: -> J
                            (Cost/How good of a fit the weights provide)
        """
        self.yHat = self.forward(X)
        J=0.5*sum((y-self.yHat)**2)

        return J

    def costFunctionPrime(self, X, y):
        """
        Finds the cost where cost is how wrong your current fit is.

        ____________________________________________________________
        Input:  -> Network
                            (Current Initilized Neural Network)
                 -> X
                            (Left side Input matrix)
                 -> y
                            (Right side Input matrix)

        Output: -> dJdW1
                            (Derivative of J with respect to W1 [2x3])
                -> dJdW2
                            (Derivative of J with respect to W2 [3x1])
        """
        self.yHat = self.forward(X)

        delta3 = np.multiply(-(y-self.yHat),self.sigmoidPrime(self.z3))
        dJdW2 = np.dot(self.a2.T, delta3)

        delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)
        dJdW1 = np.dot(X.T,delta2)

        return dJdW1, dJdW2

    def getParams(self):
        """
        Sets the paramters to a simple row vector composed of W1 and W2
        ____________________________________________________________

        Input:  -> Network
                            (Current Initilized Neural Network)
        Output: -> Parameters
        """
        params = np.concatenate((self.W1.ravel(), self.W2.ravel()))
        return params

    def setParams(self, params):

        """
        Set W1 and W2 using single paramater vector
        ____________________________________________________________
        Input:  -> Network
                            (Current Initilized Neural Network)
                -> params
                            (Usually weights in the form of a single row matrix)
        Output: -> None
                            (Simply updates the values of W1 and W2 of the
                             network)
        __________Steps__________
        (1) W1_end ->  6     by: 3*2
        (2) W1     ->  [2x3] by: np.shape([0:6],(2,3))
        (3) W2_end ->  9     by: 6 + 3*1
        (4) W2     ->  [3x1] by: npshape(params[6:9],(3,1))
        _________________________
        """

        W1_start = 0
        W1_end = self.hiddenLayerSize * self.inputLayerSize
        self.W1 = np.reshape(params[W1_start:W1_end], (self.inputLayerSize,
                             self.hiddenLayerSize))
        W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize
        self.W2 = np.reshape(params[W1_end:W2_end], (self.hiddenLayerSize,
                             self.outputLayerSize))

    def computeGradients(self, X, y):
        dJdW1, dJdW2 = self.costFunctionPrime(X, y)
        return np.concatenate((dJdW1.ravel(), dJdW2.ravel()))

def computeNumGrad(Network, X, y):
        """
        Test class used to insure that the we are on the right track.

        ____________________________________________________________

        Input:  -> Network
                            (Current Initilized Neural Network)
                -> X
                            (Input matrix)
                -> y
                            (Right side Input matrix))
        Output: -> numgrad
                            (This vector that is returned should be very close
                             to what Neural.computeGradient(X,y) returns)
        """
        paramsInitial = Network.getParams()
        #creates 2 empty vectors
        numgrad = np.zeros(paramsInitial.shape)
        perturb = np.zeros(paramsInitial.shape)
        #small distance e
        e = 1e-4

        for p in range(len(paramsInitial)):
            #Set perturbation vector
            perturb[p] = e
            Network.setParams(paramsInitial + perturb)
            loss2 = Network.costFunction(X, y)

            Network.setParams(paramsInitial - perturb)
            loss1 = Network.costFunction(X, y)

            #Compute Numerical Gradient
            numgrad[p] = (loss2 - loss1) / (2*e)

            #Return the value we changed to zero:
            perturb[p] = 0

        #Return Params to original value:
        Network.setParams(paramsInitial)

        return numgrad
def checkFit(grad,numGrad):
    from numpy import linalg as LA
    """
    Taken from Stanford UFLDL Tutorial:
    ____________________________________________________________

        Input:  -> grad
                        (Gradient found through the neural network)
                -> numGrad
                        (Gradient calculated by the function computeNumGrad)
        Output:
                -> Fit
                        (How close the Neural Network is to NumGrad)

    """
    return LA.norm(grad-numGrad)/LA.norm(grad+numGrad)


from PyQt5 import Qt
import ctypes
import sip

_qtgui = ctypes.CDLL("libQtGui.so.4")
_qt_blurImage = _qtgui._Z12qt_blurImageP8QPainterR6QImagedbbi

def qt_blurImage(p, blurImage, radius, quality, alphaOnly, transposed=0):
    p = ctypes.c_void_p(sip.unwrapinstance(p))
    blurImage = ctypes.c_void_p(sip.unwrapinstance(blurImage))
    radius = ctypes.c_double(radius)
    quality = ctypes.c_bool(quality)
    alphaOnly = ctypes.c_bool(alphaOnly)
    transposed = ctypes.c_int(transposed)
    _qt_blurImage(p, blurImage, radius, quality, alphaOnly, transposed)

class QGraphicsBlurShadowEffect(Qt.QGraphicsEffect):
    def __init__(self, *args, **kwargs):
        super(QGraphicsBlurShadowEffect, self).__init__(*args, **kwargs)
        self._distance = 4.0
        self._blurRadius = 10.0
        self._color = Qt.QColor(0, 0, 0, 80)

    @Qt.pyqtProperty(float)
    def distance(self):
        return self._distance

    @distance.setter
    def distance(self, value):
        self._distance = value

    @Qt.pyqtProperty(float)
    def blurRadius(self):
        return self._blurRadius

    @blurRadius.setter
    def blurRadius(self, value):
        self._blurRadius = value

    @Qt.pyqtProperty(Qt.QColor)
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value

    def setColor(self, value):
        self.color = value

    def setBlurRadius(self, value):
        self.blurRadius = value

    def draw(self, painter):
        # if nothing to show outside the item, just draw source
        if (self.blurRadius + self.distance) <= 0:
            drawSource(painter)
            return

        mode = Qt.QGraphicsEffect.PadToEffectiveBoundingRect
        px, offset = self.sourcePixmap(Qt.Qt.DeviceCoordinates, mode)

        # return if no source
        if px.isNull():
            return

        # save world transform
        restoreTransform = painter.worldTransform()
        painter.setWorldTransform(Qt.QTransform())

        # Calculate size for the background image
        szi = Qt.QSize(px.size().width() + 2 * self.distance, px.size().height() + 2 * self.distance)

        tmp = Qt.QImage(szi, Qt.QImage.Format_ARGB32_Premultiplied)
        scaled = Qt.QPixmap(px.scaled(szi))
        tmp.fill(0)

        tmpPainter = Qt.QPainter(tmp)
        tmpPainter.setCompositionMode(Qt.QPainter.CompositionMode_Source)
        tmpPainter.drawPixmap(Qt.QPointF(-self.distance, -self.distance), scaled)
        tmpPainter.end()

        # blur the alpha channel
        blurred = Qt.QImage(tmp.size(), Qt.QImage.Format_ARGB32_Premultiplied)
        blurred.fill(0)
        blurPainter = Qt.QPainter(blurred)
        qt_blurImage(blurPainter, tmp, self.blurRadius, False, True)
        blurPainter.end()

        tmp = blurred

        # blacken the image...
        tmpPainter.begin(tmp)
        tmpPainter.setCompositionMode(Qt.QPainter.CompositionMode_SourceIn)
        tmpPainter.fillRect(tmp.rect(), self.color)
        tmpPainter.end()

        # draw the blurred shadow...
        painter.drawImage(offset, tmp)

        # draw the actual pixmap...
        painter.drawPixmap(offset, px, Qt.QRectF())

        # restore world transform
        painter.setWorldTransform(restoreTransform)

    def boundingRectFor(self, rect):
        delta = self.blurRadius + self.distance
        return rect.united(rect.adjusted(-delta, -delta, delta, delta))


import matplotlib.pyplot as plt

def SIR(days_list, susceptible_list, infected_list, recovered_list):
    # Plot the SIR graph
    plt.figure(figsize=(8, 6))
    plt.plot(days_list, susceptible_list, label="Susceptible", color="green")
    plt.plot(days_list, infected_list, label="Infected", color="red")
    plt.plot(days_list, recovered_list, label="Recovered", color="grey")

    plt.title("SIR Model")
    plt.xlabel('Days')
    plt.ylabel('Population')
    plt.legend()
    plt.grid(True)

    plt.show()


import os
import random
import argparse
import yaml
from tqdm import tqdm
from io import BytesIO
import torch
import torch.nn.functional as F
import torch.nn as nn

from datasets.imagenet import ImageNet
import clip
from utils_vqa import *
import base64
from torchvision import transforms
from PIL import Image, ImageFile

IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)

def get_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', default='/home/moming/code/VITCLIP/configs/vqa.yaml', dest='config',
                        help='settings of Tip-Adapter in yaml format')
    args = parser.parse_args()

    return args

def run_tip_adapter(cfg, cache_keys, cache_values, test_features, test_labels):

    # Zero-shot CLIP
    beta = cfg['init_beta']
    # affinity = test_features @ cache_keys.t()
    affinity = test_features @ cache_keys.t()
    # affinity = ((-1) * (beta - beta * affinity)).exp() @ cache_values
    acc = cls_acc(affinity, test_labels)
    # cache_logits = affinity @ cache_values
    # acc = cls_acc(cache_logits, test_labels)
    # for adapter_layer, layer_emb in zip(cache_layers, test_layers):
    #     layer_logits = layer_emb @ adapter_layer.t()
    #     layer_acc = cls_acc(layer_logits, test_labels)
    print("\n**** Zero-shot CLIP's test accuracy: {:.2f}. ****\n".format(acc))

    # Search Hyperparameters
    # _ = search_hp(cfg, cache_keys, cache_values, test_features, test_labels)

def run_tip_adapter_F(cfg, cache_keys, cache_values, test_features, test_labels, clip_model, train_loader_F):

    # Enable the cached keys to be learnable
    device_id = clip_model.positional_embedding.device
    adapter = nn.Linear(cache_keys.shape[1], cache_keys.shape[0], bias=False).to(clip_model.dtype).to(device_id)
    adapter.weight = nn.Parameter(cache_keys)
    # adapter.weight = nn.Parameter(cache_keys)
    # layer_adapter = nn.Linear(cache_layers.shape[0], cache_layers.shape[1], bias=False).to(clip_model.dtype).cuda()
    # layer_adapter.weight = nn.Parameter(cache_layers)

    # optimizer = torch.optim.AdamW(adapter.parameters(), lr=2e-3, eps=1e-4)
    # include = lambda n: "bias" in n
    # named_parameters = list(clip_model.named_parameters())
    # for n, p in named_parameters:
    #     if not include(n):
    #         p.requires_grad = False
    # tune_params = [p for n, p in named_parameters if include(n) and p.requires_grad]
    optimizer = torch.optim.AdamW(
        [
            # {"params": tune_params},
            # {"params": rest_params, "weight_decay": 0.001},
            {"params": adapter.parameters(), 'lr': cfg['lr']} #2e-3 59.02 1e-3 59.07
        ],
        lr=cfg['lr'],
        betas=(0.9, 0.999),
        eps=1e-4,
    )
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, cfg['train_epoch'] * len(train_loader_F))

    beta, alpha = cfg['init_beta'], cfg['init_alpha']
    best_acc, best_epoch = 0.0, 0

    for train_idx in range(cfg['train_epoch']):
        # Train
        adapter.train()
        clip_model.eval()
        correct_samples, all_samples = 0, 0
        loss_list = []
        print('Train Epoch: {:} / {:}'.format(train_idx, cfg['train_epoch']))

        for i, (images, questions, target) in enumerate(tqdm(train_loader_F)):
            images, target = images.to(device_id), target.to(device_id)
            with torch.no_grad():
                image_features = clip_model.encode_image(images)
                image_features /= image_features.norm(dim=-1, keepdim=True)
                hypo_tensor = clip.tokenize(questions).to(device_id)
                hypo_feature = clip_model.encode_text(hypo_tensor)
                hypo_feature /= hypo_feature.norm(dim=-1, keepdim=True)
                plus_feature = hypo_feature + image_features
                minus_feature = image_features - hypo_feature
                times_feature = image_features * hypo_feature
                adapter_weights = torch.cat([image_features, hypo_feature, plus_feature, minus_feature, times_feature], dim=-1)
                # adapter_weights = torch.cat([image_features, hypo_feature], dim=-1)

            # affinity = adapter(adapter_weights)
            # cache_logits = ((-1) * (beta - beta * affinity)).exp() @ cache_values
            # affinity = adapter(adapter_weights)
            # cache_logits = affinity @ cache_values
            cache_logits = adapter(adapter_weights)

            # cache_logits = torch.softmax(cache_logits, dim=-1)

            pos_score = cache_logits.gather(-1, target.unsqueeze(-1))
            ones = torch.ones(pos_score.size()).cuda(cache_logits.device)
            loss_func = torch.nn.MarginRankingLoss(0.0, reduction='sum') # , reduction='sum'
            contr_loss = loss_func(pos_score.repeat(1, 2), cache_logits, ones)
            loss = F.cross_entropy(cache_logits, target) + contr_loss

            acc = cls_acc(cache_logits, target)
            correct_samples += acc / 100 * len(cache_logits)
            all_samples += len(cache_logits)
            loss_list.append(loss.item())

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            scheduler.step()

        current_lr = scheduler.get_last_lr()[0]
        print('LR: {:.6f}, Acc: {:.4f} ({:}/{:}), Loss: {:.4f}'.format(current_lr, correct_samples / all_samples, correct_samples, all_samples, sum(loss_list)/len(loss_list)))

        # Eval
        adapter.eval()
        clip_model.eval()
        # affinity = adapter(test_features)
        # cache_logits = ((-1) * (beta - beta * affinity)).exp() @ cache_values
        # affinity = adapter(test_features)
        # cache_logits = affinity @ cache_values
        cache_logits = adapter(test_features)
        acc = cls_acc(cache_logits, test_labels)

        print("**** Tip-Adapter-F's test accuracy: {:.2f}. ****\n".format(acc))
        if acc > best_acc:
            best_acc = acc
            best_epoch = train_idx
            torch.save(adapter.weight, cfg['cache_dir'] + "/best_F_" + str(cfg['shots']) + "shots.pt")

    adapter.weight = torch.load(cfg['cache_dir'] + "/best_F_" + str(cfg['shots']) + "shots.pt")
    print(f"**** After fine-tuning, Tip-Adapter-F's best test accuracy: {best_acc:.2f}, at epoch: {best_epoch}. ****\n")

    # Search Hyperparameters
    # _ = search_hp(cfg, None, cache_values, test_features, test_labels, adapter=adapter)

def load_data_file(data_file):
    train_path = data_file % "train"
    dev_path = data_file % "val"
    train_lines = open(train_path, 'r').readlines()
    dev_lines = open(dev_path, 'r').readlines()
    return train_lines, dev_lines

def main():

    # Load config file
    args = get_arguments()
    assert (os.path.exists(args.config))

    cfg = yaml.load(open(args.config, 'r'), Loader=yaml.Loader)

    cache_dir = os.path.join('./caches', cfg['dataset'])
    os.makedirs(cache_dir, exist_ok=True)
    cfg['cache_dir'] = cache_dir

    print("\nRunning configs.")
    print(cfg, "\n")

    # CLIP
    clip_model, preprocess = clip.load(cfg['backbone'], cfg['gpu'])
    # clip_model.eval()

    # ImageNet dataset
    random.seed(1)
    torch.manual_seed(1)

    print("Preparing VQA dataset.")
    train_datasets, dev_datasets = load_data_file(cfg['root_path'])
    train_datasets = train_datasets[:10000]
    mean = IMAGENET_DEFAULT_MEAN
    std = IMAGENET_DEFAULT_STD
    patch_image_size = 224
    # mean = [0.5, 0.5, 0.5]
    # std = [0.5, 0.5, 0.5]
    patch_resize_transform = transforms.Compose([
        lambda image: image.convert("RGB"),
        transforms.Resize((patch_image_size, patch_image_size), interpolation=Image.Resampling.BICUBIC),
        transforms.ToTensor(),
        transforms.Normalize(mean=mean, std=std),
    ])

    def process_image_from_ofa(samples):
        images = []
        questions = []
        labels = []
        lines = [s.split('\t') for s in samples]
        for l in lines:
            img_str = l[4]
            image = Image.open(BytesIO(base64.urlsafe_b64decode(img_str)))
            image = patch_resize_transform(image)
            images.append(image.unsqueeze(0))
            questions.append(l[2])
            if 'no' in l[3]:
                labels.append(0)
            elif "yes" in l[3]:
                labels.append(1)
        return torch.cat(images, dim=0), questions, torch.tensor(labels).to(torch.int64)

    test_loader = torch.utils.data.DataLoader(dev_datasets, batch_size=64, num_workers=8, shuffle=False,
                                              collate_fn=process_image_from_ofa)
    train_loader_cache = torch.utils.data.DataLoader(train_datasets, batch_size=256, num_workers=8, shuffle=False,
                                                     collate_fn=process_image_from_ofa)
    train_loader_F = torch.utils.data.DataLoader(train_datasets, batch_size=16, num_workers=8, shuffle=True,
                                                 collate_fn=process_image_from_ofa)

    # Construct the cache model by few-shot training set
    # print("\nConstructing cache model by few-shot visual features and labels.")
    cache_keys, cache_values = build_cache_model(cfg, clip_model, train_loader_cache)

    # Pre-load test features
    print("\nLoading visual features and labels from test set.")
    test_features, test_labels = pre_load_features(cfg, "test", clip_model, test_loader)

    # ------------------------------------------ Tip-Adapter ------------------------------------------
    run_tip_adapter(cfg, cache_keys, cache_values, test_features, test_labels)

    # ------------------------------------------ Tip-Adapter-F ------------------------------------------
    run_tip_adapter_F(cfg, cache_keys, cache_values, test_features, test_labels, clip_model, train_loader_F)

if __name__ == '__main__':
    main()


from conexion import Conectar

def anadir_libros(libro):
    try:
        conexion = Conectar()
        cursor = conexion.cursor()
        query = "INSERT INTO libros (titulo, autor, genero, paginas, anio_publicacion, edicion, idioma, ISBN, prestamos_realizados) VALUES (%s, %s, %s, %s,%s, %s, %s, %s, %s)"
        valores = libro
        cursor.execute(query, valores)
        conexion.commit()
        conexion.cerrar_conexion()
    except mysql.connector.Error as error:
        print("Error al ingresar datos: ", error)
    return None
anadir_libros(("Juana", "Gretel", "Ciencia-Ficción", 200, 1999, 200, "English", "jhsdgfefgKj", 200))


from pico2d import *
import game_framework
import title_state
import save_score_state

font = None
image = None
score = None
name = None
data = []
sorted_data = []
menu_image = None

def enter():
    global font, image, data, sorted_data, menu_image
    font = load_font('source/font/ENCR10B.TTF', 50)
    image = load_image('source/image/background1.png')
    menu_image = load_image('source/image/menu.png')
    data.append(save_score_state.load())
    sorted_data = sorted(data, key=lambda d: d['score'], reverse=True)

def exit():
    global font, image, menu_image
    del font, image, menu_image

def update():
    pass

def draw():
    global image, menu_image, font
    i = 1
    clear_canvas()
    image.draw(get_canvas_width() // 2, get_canvas_height() // 2)
    menu_image.clip_draw(235, 290, 245, 180, get_canvas_width() // 2, get_canvas_height() // 2, 245 * 2, 180 * 2)
    menu_image.clip_draw(188, 223, 138, 50, get_canvas_width() // 2, get_canvas_height() // 2 + 200, 138 * 3, 50 * 2)
    font.draw(get_canvas_width() // 2 - 150, get_canvas_height() // 2 + 200, 'HIGH SCORE', (200, 0, 0))
    for sd in sorted_data:
        font.draw(get_canvas_width()//2 - 200, get_canvas_height()//2 + 200 - i * 100, f"{i}.{sd['name'][0]}{sd['name'][1]}{sd['name'][2]}:{sd['score']}", (251, 250, 180))
        i += 1
        if i == 4:
            break
    update_canvas()

def handle_events():
    events = get_events()
    for event in events:
        if event.type == SDL_QUIT:
            game_framework.quit()
        elif event.type == SDL_KEYDOWN:
            if event.key == SDLK_ESCAPE:
                game_framework.quit()
            else:
                game_framework.change_state(title_state)


import urllib
import random
import time
import pyperclip
filename = False
lineRn = 0 # For ordered mode
randomVal = 0
copyTime = False

def getFile():
    print("What is your file called?")
    x = input()
    if ".txt" in x:
        global filename;
        filename = x;
        try:
            f = open(filename, 'r')
        except:
            print("This file is not found, please try again\n")
            getFile()
    else:
        print("This is not a text file, please try again.\n")
        getFile()

def getDelay():
    print("Start time in seconds?\n")
    y = input()
    try:
        while int(y) > 0:
            print("Starting in: ", y)
            y = int(y) - 1
            time.sleep(1)
    except ValueError:
        print("That's not a number, try again. \n")
        getDelay()

def getCopyDelay():
    global copyTime
    if copyTime == False:
        print("Copy time (in seconds)?\n")
        copyTime = input()

        try:
            int(copyTime)
            copyTime = int(copyTime)
            print("Copy time: ", copyTime, "\n")
            getDelay()
        except ValueError:
            print("That's not a number, try again. \n")
            copyTime = False
            getCopyDelay()

def randomOrOrdered():
    global randomVal
    print("Random or ordered? \n")
    x = input()

    if x == "random" or x == "Random":
        randomVal = True
        getCopyDelay()
    elif  x == "ordered" or x == "Ordered":
        randomVal = False
        getCopyDelay()
    else:
        print("Invalid input: \nPossible inputs are: 'Random', 'random', 'Ordered, 'order' \nPlease try again. \n")
        randomOrOrdered()

# Gets lines, picks 10 random lines from the script
def getLines():
    global randomVal
    # pick random lines
    if randomVal == True:
        rand = random.randint(0, (len(lines)))
        numOfLines = random.randint(0, 8)
        choosenLines = lines[rand:(rand + numOfLines)]
    elif randomVal == False:
        global lineRn
        numOfLines = random.randint(1, 4)
        choosenLines = lines[lineRn:(lineRn + numOfLines)]
        lineRn = lineRn + numOfLines

        if lineRn == len(lines):
            lineRn = 0;

    text = ""
    # remove line breaks so it's ready for pasting
    for line in choosenLines:
        line = line.replace('\n', '')
        text = text + line
    # copies line to clipboard
    pyperclip.copy(text)
    print(text)

getFile()
randomOrOrdered()

# Open the file and read lines
with open(filename, 'r') as infile:
    # Read all lines into memory
    lines = infile.readlines()
    # Get rid of new lines
    # runs this function with a new line every 2 seconds
    while(True):
        getLines()
        time.sleep(copyTime)

# Changes:
    # Updated readme and more info there


from discord import Client

class Bot(Client):
    def __init__(self):
        super().__init__()

    async def on_ready(self):
        print("Bot is now online")

    async def on_message(self, message):
        if message.author == self.user:
            return
        await message.channel.send("ping")


import os
import numpy as np
import matplotlib.pyplot as plt
import pylibconfig2
from ergoPack import ergoPlot
from coupledRO import *

#ergoPlot.dpi = 2000

configFile = '../cfg/coupledRO.cfg'
cfg = pylibconfig2.Config()
cfg.read_file(configFile)

L = cfg.simulation.LCut + cfg.simulation.spinup
spinup = cfg.simulation.spinup
tau = cfg.transfer.tauRng[0]
printStepNum = int(cfg.simulation.printStep / cfg.simulation.dt + 0.1)
caseName = cfg.model.caseName
dim = cfg.model.dim
dimObs = len(cfg.observable.components)
nProc = ''
if (hasattr(cfg.sprinkle, 'nProc')):
    nProc = '_nProc' + str(cfg.sprinkle.nProc)

N = np.prod(np.array(cfg.grid.nx))
gridPostfix = ""
for d in np.arange(dimObs):
    if (hasattr(cfg.grid, 'gridLimitsLow')
        & hasattr(cfg.grid, 'gridLimitsHigh')):
        gridPostfix = "%s_n%dl%dh%d" % (gridPostfix, cfg.grid.nx[d],
                                        cfg.grid.gridLimitsLow[d],
                                        cfg.grid.gridLimitsHigh[d])
    else:
        gridPostfix = "%s_n%dl%dh%d" % (gridPostfix, cfg.grid.nx[d],
                                        cfg.sprinkle.minInitState[d],
                                        cfg.sprinkle.maxInitState[d])
readSpec = ergoPlot.readSpectrum
xmineigVal = -cfg.stat.rateMax
ymineigVal = -cfg.stat.angFreqMax
xlimEig = [xmineigVal, -xmineigVal/100]
ylimEig = [ymineigVal, -ymineigVal]
xticks = None
yticksPos = np.arange(0, ylimEig[1], 5.)
yticksNeg = np.arange(0, ylimEig[0], -5.)[::-1]
yticks = np.concatenate((yticksNeg, yticksPos))
realLabel = r'$\Re(\lambda_k)$'
imagLabel = r'$\Im(\lambda_k)$'

muRng = np.arange(0.6, 1.21, 0.06)
for imu, mu in enumerate(muRng) :
    srcPostfixSim = "_%s_mu%03d_eta2%03d_gamma%03d_r%03d_sigmahInf2%03d\
_L%d_spinup%d_dt%d_samp%d" \
    % (caseName, int(mu * 100 + 0.1),
       int(p['eta2'] * 1000 + 0.1), int(p["gamma"] * 1000 + 0.1),
       int(p["r"] * 1000 + 0.1),
       int(p["sigmahInf2"] * 1000 + 0.1), int(L + 0.1),
       int(spinup + 0.1),
       int(-np.round(np.log10(cfg.simulation.dt)) + 0.1),
       printStepNum)
    postfix = "%s_nTraj%d%s" % (srcPostfixSim, cfg.sprinkle.nTraj,
                                gridPostfix)
    postfixTau = "%s_tau%03d" % (postfix, int(tau * 100 + 0.1))

    # Define file names
    eigValForwardFile = '%s/eigval/eigvalForward_nev%d%s.%s' \
                        % (cfg.general.specDir, cfg.spectrum.nev, postfixTau,
                           cfg.general.fileFormat)

    print('Readig spectrum for mu = {:.2f}...'.format(mu))
    (eigValForward,) = readSpec(eigValForwardFile)

    # Get generator eigenvalues (using the complex logarithm)
    eigValGen = np.log(eigValForward) / tau

    ergoPlot.plotEig(eigValGen, xlabel=realLabel, ylabel=imagLabel,
                     xlim=xlimEig, ylim=ylimEig)
    plt.text(xlimEig[0]*0.2, ylimEig[1]*1.05, r'$\mu = {:.2f}$'.format(mu),
             fontsize=ergoPlot.fs_latex)
    plt.savefig('%s/spectrum/eigVal/eigVal%s.%s'\
                % (cfg.general.plotDir, postfixTau, ergoPlot.figFormat),
                dpi=ergoPlot.dpi, bbox_inches=ergoPlot.bbox_inches)


from pickle import FALSE
from turtle import pd
from cv2 import mean
import plotly.figure_factory as ff
import statistics
import random
import pandas as pd
import csv
import plotly.graph_objects as go

df = pd.read_csv("data.csv")
data = df["average"].tolist()

population_mean = statistics.mean(data)
print("population_mean: ", population_mean)

population_stdev = statistics.stdev(data)
print("population_stdev: ", population_stdev)

fig = ff.create_distplot([data], ['average'], show_hist = False)
#fig.show()

def random_set_of_mean(counter):
    dataset = []
    for i in range(0, counter):
        random_index = random.randint(0, len(data)-1)
        value = data[random_index]
        dataset.append(value)
    mean = statistics.mean(dataset)
    return mean

def show_fig(mean_list):
    df = mean_list
    mean = statistics.mean(mean_list)
    print("mean of sampling distribution: ", mean )
    fig = ff.create_distplot([df], ['average'], show_hist = False)
    fig.show()

def setup():
    mean_list = []
    for i in range(0, 100):
        set_of_means = random_set_of_mean(50)
        mean_list.append(set_of_means)
    show_fig(mean_list)

setup()

def stdev():
    mean_list = []
    for i in range(0, 100):
        set_of_means = random_set_of_mean(50)
        mean_list.append(set_of_means)
    standard_dev = statistics.stdev(mean_list)
    print("standard dev of sampling distribution", standard_dev)

stdev()


import json
import re
from typing import Generator

import milagro_bls_binding as bls
import pytest
from aioresponses import CallbackResult, aioresponses
from eth_typing import HexStr
from staking_deposit.key_handling.keystore import Keystore
from web3 import Web3

from src.validators.typings import BLSPrivkey

@pytest.fixture
def remote_signer_url() -> str:
    return 'http://web3signer:9000'

@pytest.fixture
def mocked_remote_signer(
    remote_signer_url: str,
) -> Generator:
    _remote_signer_pubkey_privkey_mapping: dict[HexStr, BLSPrivkey] = {}

    def _mocked_keymanager_import_endpoint(url, **kwargs) -> CallbackResult:
        data = kwargs['json']
        keystores = [Keystore.from_json(json.loads(keystore)) for keystore in data['keystores']]
        passwords = data['passwords']

        for keystore, password in zip(keystores, passwords):
            priv_key = BLSPrivkey(keystore.decrypt(password))
            pubkey = Web3.to_hex(bls.SkToPk(priv_key))
            _remote_signer_pubkey_privkey_mapping[pubkey] = priv_key

        return CallbackResult(
            status=200, payload={'data': [{'status': 'imported'} for _ in keystores]}
        )

    def _mocked_keymanager_delete_endpoint(url, **kwargs) -> CallbackResult:
        data = kwargs['json']
        pubkeys = data['pubkeys']

        for pubkey in pubkeys:
            _remote_signer_pubkey_privkey_mapping.pop(pubkey)

        return CallbackResult(
            status=200, payload={'data': [{'status': 'deleted'} for _ in pubkeys]}
        )

    def _mocked_keymanager_list_endpoint(url, **kwargs) -> CallbackResult:
        return CallbackResult(
            status=200,
            payload={
                'data': [
                    {'validating_pubkey': pubkey}
                    for pubkey in _remote_signer_pubkey_privkey_mapping.keys()
                ]
            },
        )

    def _mocked_sign_endpoint(url, **kwargs) -> CallbackResult:
        public_key_to_sign_for = url.path.split('/')[-1]

        try:
            corresponding_private_key = _remote_signer_pubkey_privkey_mapping[
                public_key_to_sign_for
            ]
        except KeyError:
            return CallbackResult(status=404, body='Not Found')

        signature = bls.Sign(
            corresponding_private_key, Web3.to_bytes(hexstr=kwargs['json']['signing_root'])
        )

        return CallbackResult(payload={'signature': f'0x{signature.hex()}'})

    with aioresponses() as m:
        # Mocked keymanager list keys endpoint
        m.get(
            f'{remote_signer_url}/eth/v1/keystores',
            callback=_mocked_keymanager_list_endpoint,
            repeat=True,
        )

        # Mocked keymanager import keystores endpoint
        m.post(
            f'{remote_signer_url}/eth/v1/keystores',
            callback=_mocked_keymanager_import_endpoint,
            repeat=True,
        )

        # Mocked keymanager delete keys endpoint
        m.delete(
            f'{remote_signer_url}/eth/v1/keystores',
            callback=_mocked_keymanager_delete_endpoint,
            repeat=True,
        )

        # Mocked signing endpoint
        m.post(
            re.compile(f'^{remote_signer_url}/api/v1/eth2/sign/\\w{{98}}$'),
            callback=_mocked_sign_endpoint,
            repeat=True,
        )
        yield


from django.core.mail import send_mail
from django.shortcuts import redirect, render

from feedback.forms import FeedbackForm
from feedback.models import (
    ComplainingUserModel,
    FeedbackAttachments,
    FeedbackModel,
)

from myserver.settings import DEFAULT_FROM_EMAIL

def feedback(request):
    form = FeedbackForm(request.POST or None, request.FILES)
    if form.is_valid():
        text = form.cleaned_data.get("text")
        address = form.cleaned_data.get("email")
        name = form.cleaned_data.get("name")
        files = request.FILES.getlist("file_field")
        print(request.FILES)
        author = ComplainingUserModel.objects.create(email=address, name=name)
        feedback = FeedbackModel.objects.create(text=text, author=author)
        for file in files:
            FeedbackAttachments.objects.create(file=file, feedback=feedback)
        send_mail(
            "Feedback",
            text,
            DEFAULT_FROM_EMAIL,
            [address],
            fail_silently=False,
        )
        return redirect("feedback:feedback_success")
    # else:
    #     raise django.forms.ValidationError("Введите корректный email!")
    context = {
        "form": form,
    }
    return render(request, "feedback/feedback.html", context)

def feedback_success(request):
    return render(request, "feedback/feedback_success.html")


def merge_sort(inp_arr):
    size = len(inp_arr)
    if size > 1:
        middle = size // 2
        left_arr = inp_arr[:middle]
        right_arr = inp_arr[middle:]

        merge_sort(left_arr)
        merge_sort(right_arr)

        p = 0
        q = 0
        r = 0

        left_size = len(left_arr)
        right_size = len(right_arr)
        while p < left_size and q < right_size:
            if left_arr[p] < right_arr[q]:
              inp_arr[r] = left_arr[p]
              p += 1
            else:
                inp_arr[r] = right_arr[q]
                q += 1

            r += 1

        while p < left_size:
            inp_arr[r] = left_arr[p]
            p += 1
            r += 1

        while q < right_size:
            inp_arr[r]=right_arr[q]
            q += 1
            r += 1
def printArr(arr):
    for element in arr:
        print(element,end=" ")
    print("")

n = int(input("Enter the size of the list "))
print("\n")
arr = list(int(num) for num in input("Enter elements ").strip().split())[:n]
print("Unsorted List: ")
printArr(arr)
merge_sort(arr)
print("\n")
printArr(arr)


# -*- coding: UTF-8 -*-
from common.log.Logger import log
from common.objects import BaseObj
from common.func import str_convert_to_camel

class PeeweeUtil(object):
    def __init__(self, query=None, dbase=None, index=None):
        """
        在这个里面做查询可以修改db配置
        :param query: 查询的query
        :param dbase: 查询的数据库，不传默认为当前库
        :param index: 查询的表序号，不传默认唯一一张表， 目前不适用
        """
        self.query = query
        self.dbase = dbase
        self.index = index
        # 目前pw升级后这种方式修改table已不灵了
        self.origin_table_name = query.model._meta.table_name if query is not None else None  # 原始表名字
        self.origin_database_name = query.model._meta.database if query is not None else None # 原始db名字
        # print("原始配置:" + self.origin_database_name.database + "   " + self.origin_table_name)

    def __enter__(self):
        # 这里放入在正式查询sql前需要做的内容
        if self.dbase:
            print("修改db到:" + self.dbase.database)
            self.query.model._meta.database = self.dbase
            self.query._database = self.dbase
        # 目前这个方法已经不适用
        if self.index:
            print('============开始修改查询前的index拉{}'.format(self.index))
            self.query.model._meta.table_name = self.origin_table_name + "_" + self.index
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 这里放入查询sql结束后需要做的事宜
        try:
            if self.query:
                self.query.model._meta.database = self.origin_database_name
                self.query.model._meta.table_name = self.origin_table_name
        except:
            pass

    def db_result(self, is_convert=False,
                  back=[],
                  sql_type='query',
                  is_normal_obj=False,
                  is_convert_camel=False):
        """
        根据query查询值
        @param is_convert: 如果查询出来是单条数据是否要转换成query[0]
        @param back: 如果查询没有结果返回back
        @param sql_type: 是查询语句还是更新语句
        @param is_normal_obj: 是否要转换成普通的对象，非pw对象
        @param is_convert_resp: 是否要转换成resp的驼峰形式
        @return:
        """
        db_host = self.query.model._meta.database.connect_params.get('host')
        sql_list = [self.query.sql(), db_host]

        log.mysql(sql_list)

        if sql_type == 'query':
            query_array = []
            if self.retry_len(self.query) > 0:
                for q in self.query:
                    if is_normal_obj:  # 假如要转化成普通的类
                        q = self.convert_to_normal_obj(q, is_convert_camel=is_convert_camel)
                    query_array.append(q)
                r = self.deal_query_result(query_array=query_array,
                                           is_convert=is_convert)
                return r
            else:
                return back
        elif sql_type == 'update':
            update_result = self.query.execute()  # 更新结果是影响行数
            return update_result

    def retry_len(self, query):
        import peewee, time
        for i in range(3):
            try:
                n = len(query)
                return n
            except peewee.OperationalError as e:
                log.error(e)
                time.sleep(2)
                continue

    def deal_query_result(self, query_array, is_convert=False):
        if is_convert:
            return query_array if len(query_array) > 1 else query_array[0]
        else:
            return query_array

    def convert_to_normal_obj(self, obj, is_convert_camel=False):
        """
        将pw对象转换成普通对象
        :param obj:
        :param is_convert_camel: 是否要转换成驼峰
        :return:
        """

        # class IterItems(BaseObj):
        #     def __init__(self, **kwargs):
        #         super(IterItems, self).__init__(**kwargs)
        #
        #     def __iter__(self):
        #         return self

        new_obj = BaseObj()

        for k, v in obj.__data__.items():
            # if k == 'order':
            #     k = k + '_id'
            if is_convert_camel:
                k = str_convert_to_camel(k, "_")
            setattr(new_obj, k, v)
        return new_obj


import re
import string

class Point:
    def __init__(self, x=0, y=0):
        self.x = int(x)
        self.y = int(y)

def manhattan_distance(point1: Point, point2: Point) -> int:
    return abs(point1.x - point2.x) + abs(point1.y - point2.y)

def write_2dlist_to_file(list2d):
    with open(r'map2', 'w') as f:
        for outer_list in list2d:
            for item in outer_list:
                f.write(f'|{item}')
            f.write('|\r')

coordinatem = re.compile(r'(\d+), (\d+)')

def main():
    abc = string.ascii_letters
    with open(r'input', 'r') as f:
        coordinates = f.readlines()
    referece_map = [['x' for j in range(360)] for i in range(360)]
    coordinate_letter_map = {}
    for idx, line in enumerate(coordinates):
        x, y = coordinatem.match(line).group(1,2)
        point = Point(x,y)
        letter = abc[idx]
        coordinate_letter_map[letter] = point
        referece_map[point.x][point.y] = letter
    map = [['x' for j in range(360)] for i in range(360)]
    for x in range(360):
        for y in range(360):
            sum_distance = 0
            for letter, point in coordinate_letter_map.items():
                sum_distance += manhattan_distance(Point(x,y), point)
            map[x][y] = '#' if sum_distance < 10000 else '.'

    write_2dlist_to_file(map)
    rows=''
    for row in map:
        rows = rows + ''.join(row)
    abc = abc + '#'
    for char in abc:
        print(f'{char}: {rows.count(char)}')

main()


def print_board(board):
    for row in board:
        print(" ".join("Q" if cell else "-" for cell in row))
    print()

def is_safe(board, row, col):
    # Check if there is a queen in the same column
    for i in range(row):
        if board[i][col]:
            return False

    # Check if there is a queen in the upper-left diagonal
    for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
        if board[i][j]:
            return False

    # Check if there is a queen in the upper-right diagonal
    for i, j in zip(range(row, -1, -1), range(col, len(board))):
        if board[i][j]:
            return False

    return True

def solve_n_queens(board, row):
    if row == len(board):
        # All queens are placed, solution found
        print_board(board)
        return 1

    count = 0
    for col in range(len(board)):
        if is_safe(board, row, col):
            board[row][col] = 1  # Place the queen

            # Recur for the next row
            count += solve_n_queens(board, row + 1)

            board[row][col] = 0  # Backtrack and remove the queen

    return count

def main():
    N = 8
    board = [[0] * N for _ in range(N)]

    solutions = solve_n_queens(board, 0)

    print("Total solutions:", solutions)

if __name__ == "__main__":
    main()


import tweepy
import selenium
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen, Request
import re
import csv
import os
import random as rd
import numpy as np
import keys

qt_list = []

def download_quotes():
	url = "https://www.happycow.org.uk/inspiration/quotes_tolkien.xml"
	response = urlopen(Request(url))
	html = bs(response, 'html.parser')
	return html
	pass

def clean_quote(txt):
	sub_list = ['
','
', '<br','<','/>']
	for sub in sub_list:
		txt = txt.replace(sub, '')
	return txt

def list_quotes():
	html = download_quotes()
	#print(type(html))
	text = clean_quote(html.text)
	#print(text)

	qt_list = re.split(r"\n\n", text)
	i=0

	a  = rd.randint(5, 359)
	#print(len(qt_list))
	print(qt_list[a])

	for qt in qt_list:
		#print("Quote : ", i, qt)
		i+=1

auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

list_quotes()

api = tweepy.API(auth)
#print(api.me())


import setuptools
from setuptools import setup
from nisnap import __version__
import os.path as op
this_directory = op.abspath(op.dirname(__file__))
with open(op.join(this_directory, 'README.md')) as f:
    long_description = f.read()

download_url = 'https://github.com/xgrg/nisnap/-/archive/v0.4/'\
    'nisnap-v0.4.tar.gz'

setup(
    name='nisnap',
    install_requires=['coverage>=4.5',
                      'nose>=1.3',
                      'matplotlib>=3.1',
                      'pyxnat>=1.3',
                      'tqdm>=4.31',
                      'nibabel>=2.0',
                      'numpy>=1.16',
                      'urllib3>=1.24',
                      'ipython>=7.3',
                      'Pillow>=7.0',
                      'nilearn>=0.8'],
    scripts=['bin/nisnap'],
    long_description=long_description,
    long_description_content_type='text/markdown',
    version=__version__,
    description='nisnap',
    packages=setuptools.find_packages(),
    author='Greg Operto',
    author_email='goperto@barcelonabeta.org',
    url='https://github.com/xgrg/nisnap',
    download_url=download_url,
    classifiers=['Intended Audience :: Science/Research',
                 'Intended Audience :: Developers',
                 'Topic :: Scientific/Engineering',
                 'Operating System :: Unix',
                 'Programming Language :: Python :: 3.7'],
    package_data={'nisnap': ['utils/colormap.json']})


import pygame
import random

pygame.init()
window = pygame.display.set_mode((1920, 1080))
pygame.display.set_caption("ULTIMATE GHOST FIGHT 9000")

class player:
    def __init__(
        self,
        x,
        y,
        width,
        height,
        ghostLeft,
        ghostRight,
        ghostCrouchLeft,
        ghostCrouchRight,
        ball,
        left,
        right,
        balls,
        ghostShootLeft,
        ghostShootRight,
    ):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.velocity = 6
        self.jumps = False
        self.jumpPhase = -25
        self.crouch = False
        self.right = right
        self.left = left
        self.ghostLeft = ghostLeft
        self.ghostRight = ghostRight
        self.ghostCrouchLeft = ghostCrouchLeft
        self.ghostCrouchRight = ghostCrouchRight
        self.ball = ball
        self.balls = balls
        self.health = 10
        self.shootPhase = -1
        self.lastShot = 0
        self.ballLoad = 5
        self.ballReload = 0
        self.ghostShootLeft = ghostShootLeft
        self.ghostShootRight = ghostShootRight
        self.gravity = 5
        self.floatPhase = 0
        self.float = 0
        self.score = 0
        self.crouchTime = 3

def objectRender(objects):
    for object in objects:
        window.blit(object.image, (object.x, object.y))
    window.blit(
        pygame.font.SysFont("comicsansms", 100).render(
            str(player1.score), 1, (255, 180, 22)
        ),
        (30, 0),
    )
    window.blit(
        pygame.font.SysFont("comicsansms", 100).render(
            str(player2.score), 1, (255, 180, 22)
        ),
        (
            1890
            - (
                pygame.font.SysFont("comicsansms", 100)
                .render(str(player2.score), 1, (255, 180, 22))
                .get_width()
            ),
            0,
        ),
    )

def movementDrawShoot(player, left, right, jump, crouch, shoot, objects):
    if player.ballLoad < 5:
        player.ballReload += 1
        if player.ballReload % 75 == 0:
            player.ballLoad += 1
    else:
        player.ballReload = 0
    global hearts
    for heart in hearts:
        if (
            heart.x <= player.x + player.width
            and heart.x + heart.width >= player.x
            and player.health < 10
            and heart.y >= player.y
            and heart.y <= player.y + player.height
        ):
            hearts.pop(hearts.index(heart))
            if player.health > 5:
                player.health += 10 - player.health
            else:
                player.health += 5
    if player.crouchTime > 3 and player.crouch is False:
        player.crouchTime -= 1
    player.floatPhase += 1
    if player.floatPhase % 30 == 0 and player.float == 0 and player.jumps is False:
        player.y += 8
        player.float = 1
    elif player.floatPhase % 30 == 0 and player.float == 1 and player.jumps is False:
        player.y -= 8
        player.float = 0
    player.y += player.gravity
    player.gravity = 5
    for object in objects:
        if (
            player.y + player.height >= object.y
            and player.y + player.height <= object.y + object.height / 5
            and player.x > object.x - player.width / 2
            and player.x < object.x + object.width - player.width / 2
        ):
            player.gravity = 0
            if player.jumps and player.y + player.height > object.y:
                player.y = object.y - player.height
                player.jumps = False
                player.jumpPhase = -25
    for ball in player.balls:
        if ball.x > 0 and ball.x < 1920:
            ball.x += ball.velocity
        else:
            player.balls.pop(player.balls.index(ball))
    if player.y > 1080:
        player.health = 0
    if player.health > 0:
        if shoot and player.crouch is False and player.ballLoad > 0:
            player.shootPhase += 1
            if player.left is True and player.shootPhase % 15 == 0:
                player.ballLoad -= 1
                facing = -1
                player.balls.append(
                    projectile(player.x + 56, player.y + 28, 12, player.ball, facing)
                )
            elif player.right is True and player.shootPhase % 15 == 0:
                player.ballLoad -= 1
                facing = 1
                player.balls.append(
                    projectile(player.x + 56, player.y + 28, 12, player.ball, facing)
                )
        elif player.shootPhase != -1:
            player.lastShot += 1
            if player.lastShot == 15:
                player.shootPhase == -1
        if left and player.x > 0:
            player.x -= player.velocity
            player.left = True
            player.right = False
        if right and player.x + player.width < 1920:
            player.x += player.velocity
            player.right = True
            player.left = False
        if not (player.jumps):
            if crouch and player.crouch is False and player.crouchTime == 3:
                player.y = player.y + 50
                player.height = 70
                player.crouch = True
            if not crouch and player.crouch is True or player.crouchTime >= 296:
                player.y = player.y - 50
                player.height = 120
                player.crouch = False
            for object in objects:
                if (
                    jump
                    and player.crouch is False
                    and player.y + player.height >= object.y
                    and player.y + player.height <= object.y + object.height / 5
                    and player.x > object.x - player.width / 2
                    and player.x < object.x + object.width - player.width / 2
                ):
                    player.jumps = True
        else:
            if player.jumpPhase <= 25:
                player.y += player.jumpPhase
                player.jumpPhase += 1
            else:
                player.jumps = False
                player.jumpPhase = -25
        if shoot and not crouch and player.ballLoad > 0:
            if player.left is True and left and not right:
                window.blit(player.ghostShootLeft, (player.x, player.y))
            elif player.right is True and right and not left:
                window.blit(player.ghostShootRight, (player.x, player.y))
            elif player.left is True:
                window.blit(player.ghostShootLeft, (player.x, player.y))
            elif player.right is True:
                window.blit(player.ghostShootRight, (player.x, player.y))
        elif player.crouch is True:
            if player.left is True and left and not right:
                player.crouchTime += 1
                window.blit(player.ghostCrouchLeft, (player.x, player.y))
            elif player.right is True and right and not left:
                player.crouchTime += 1
                window.blit(player.ghostCrouchRight, (player.x, player.y))
            elif player.left is True:
                player.crouchTime += 1
                window.blit(player.ghostCrouchLeft, (player.x, player.y))
            elif player.right is True:
                player.crouchTime += 1
                window.blit(player.ghostCrouchRight, (player.x, player.y))
        else:
            if player.left is True and left and not right:
                window.blit(player.ghostLeft, (player.x, player.y))
            elif player.right is True and right and not left:
                window.blit(player.ghostRight, (player.x, player.y))
            elif player.left is True:
                window.blit(player.ghostLeft, (player.x, player.y))
            elif player.right is True:
                window.blit(player.ghostRight, (player.x, player.y))
        for ball in player.balls:
            window.blit(ball.image, (ball.x, ball.y))
        pygame.draw.rect(window, (255, 255, 255), (player.x, player.y - 28, 100, 19))
        pygame.draw.rect(
            window,
            (255, 0, 0),
            (player.x + 1, player.y - 18, 10 * player.health - 2, 8),
        )
        pygame.draw.rect(
            window,
            (0, 0, 255),
            (player.x + 1, player.y - 27, (299 - player.crouchTime) // 3, 8),
        )
        for i in range(0, player.ballLoad):
            pygame.draw.rect(
                window, (255, 255, 255), (player.x + i * 10, player.y - 40, 8, 8)
            )
    else:
        if player1.health == 0:
            player2.score += 1
            window.blit(
                pygame.font.SysFont("comicsansms", 100).render(
                    "black ghost wins", 1, (255, 180, 22)
                ),
                (
                    960
                    - pygame.font.SysFont("comicsansms", 100)
                    .render("black ghost wins", 1, (255, 180, 22))
                    .get_width()
                    / 2,
                    540
                    - pygame.font.SysFont("comicsansms", 100)
                    .render("black ghost wins", 1, (255, 180, 22))
                    .get_height()
                    / 2,
                ),
            )
        elif player2.health == 0:
            player1.score += 1
            window.blit(
                pygame.font.SysFont("comicsansms", 100).render(
                    "white ghost wins", 1, (255, 180, 22)
                ),
                (
                    960
                    - pygame.font.SysFont("comicsansms", 100)
                    .render("white ghost wins", 1, (255, 180, 22))
                    .get_width()
                    / 2,
                    540
                    - pygame.font.SysFont("comicsansms", 100)
                    .render("white ghost wins", 1, (255, 180, 22))
                    .get_height()
                    / 2,
                ),
            )
        pygame.mixer.music.stop()
        music = pygame.mixer.music.load("media/music.mp3")
        pygame.mixer.music.play()
        pygame.display.update()
        player1.x = 150
        player1.y = 400
        player2.x = 1670
        player2.y = 400
        player1.left = False
        player1.right = True
        player2.left = True
        player2.right = False
        player1.health = 10
        player2.health = 10
        hearts = []
        player1.balls = []
        player2.balls = []
        player1.ballLoad = 5
        player1.ballReload = 0
        player1.lastShot = 0
        player2.ballLoad = 5
        player2.ballReload = 0
        player2.lastShot = 0
        lifeCount = 1
        pygame.time.delay(2000)

def hit(player, enemy, objects):
    for ball in player.balls:
        for object in objects:
            if (
                ball.y - ball.radius < object.y + object.height
                and ball.y + ball.radius > object.y
                and ball.x + ball.radius > object.x
                and ball.x - ball.radius < object.x + object.width
            ):
                player.balls.pop(player.balls.index(ball))
        if (
            ball.y - ball.radius < enemy.y + enemy.height
            and ball.y + ball.radius > enemy.y
        ):
            if (
                ball.x + ball.radius > enemy.x
                and ball.x - ball.radius < enemy.x + enemy.width
            ):
                player.balls.pop(player.balls.index(ball))
                enemy.health -= 1

class projectile:
    def __init__(self, x, y, radius, image, facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.image = image
        self.facing = facing
        self.velocity = 8 * facing

class object:
    def __init__(self, x, y, width, height, image):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.image = image

class life:
    def __init__(self, x):
        self.x = x
        self.y = 494
        self.width = 36
        self.height = 36
        self.image = pygame.image.load("media/life.png").convert_alpha()
        self.floatPhase = 0
        self.float = 0

background = pygame.image.load("media/background.jpg").convert_alpha()

class title:
    def __init__(self, image):
        self.image = image
        self.x = background.get_width() / 2 - self.image.get_width() / 2
        self.y = 340
        self.float = 0
        self.floatPhase = 0

def lifeGeneration():
    global lifeCount
    lifeCount += 1
    if lifeCount % 700 == 0:
        heart = life(random.choice([182, 1702]))
        hearts.append(heart)
        if len(hearts) > 1:
            hearts.pop(hearts.index(hearts[0]))
    for heart in hearts:
        heart.floatPhase += 1
        if heart.floatPhase % 20 == 0 and heart.float == 0:
            heart.y -= 8
            heart.float = 1
        elif heart.floatPhase % 20 == 0 and heart.float == 1:
            heart.y += 8
            heart.float = 0
        window.blit(heart.image, (heart.x, heart.y))

def titleRender(title):
    title.floatPhase += 1
    if title.floatPhase % 80 == 0 and title.float == 0:
        title.y -= 8
        title.float = 1
    elif title.floatPhase % 80 == 0 and title.float == 1:
        title.y += 8
        title.float = 0
    window.blit(title.image, (title.x, title.y))

title = title(pygame.image.load("media/title.png").convert_alpha())
music = pygame.mixer.music.load("media/music.mp3")
player1 = player(
    150,
    400,
    108,
    120,
    pygame.image.load("media/whiteghostleft.png").convert_alpha(),
    pygame.image.load("media/whiteghostright.png").convert_alpha(),
    pygame.image.load("media/whiteghostcrouchleft.png").convert_alpha(),
    pygame.image.load("media/whiteghostcrouchright.png").convert_alpha(),
    pygame.image.load("media/whiteball.png").convert_alpha(),
    False,
    True,
    [],
    pygame.image.load("media/whiteghostshootleft.png").convert_alpha(),
    pygame.image.load("media/whiteghostshootright.png").convert_alpha(),
)
player2 = player(
    1670,
    400,
    108,
    120,
    pygame.image.load("media/blackghostleft.png").convert_alpha(),
    pygame.image.load("media/blackghostright.png").convert_alpha(),
    pygame.image.load("media/blackghostcrouchleft.png").convert_alpha(),
    pygame.image.load("media/blackghostcrouchright.png").convert_alpha(),
    pygame.image.load("media/blackball.png").convert_alpha(),
    True,
    False,
    [],
    pygame.image.load("media/blackghostshootleft.png").convert_alpha(),
    pygame.image.load("media/blackghostshootright.png").convert_alpha(),
)
objects = []
platform1 = object(
    100, 540, 200, 100, pygame.image.load("media/cloud.png").convert_alpha()
)
objects.append(platform1)
platform2 = object(
    1620, 540, 200, 100, pygame.image.load("media/cloud.png").convert_alpha()
)
objects.append(platform2)
platform3 = object(
    450, 540, 1020, 100, pygame.image.load("media/longcloud.png").convert_alpha()
)
objects.append(platform3)
platform4 = object(
    660, 340, 600, 90, pygame.image.load("media/shortcloud.png").convert_alpha()
)
objects.append(platform4)
lifeCount = 1
hearts = []
menu = True
while menu:
    pygame.time.delay(5)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            menu = False
            play = False
    window.fill((0, 0, 0))
    titleRender(title)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RETURN]:
        menu = False
        play = True
    pygame.display.update()
pygame.mixer.music.play()
while play:
    pygame.time.delay(5)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            play = False
    window.blit(background, (0, 0))
    keys = pygame.key.get_pressed()
    objectRender(objects)
    lifeGeneration()
    movementDrawShoot(
        player1,
        keys[pygame.K_a],
        keys[pygame.K_d],
        keys[pygame.K_w],
        keys[pygame.K_s],
        keys[pygame.K_SPACE],
        objects,
    )
    movementDrawShoot(
        player2,
        keys[pygame.K_LEFT],
        keys[pygame.K_RIGHT],
        keys[pygame.K_UP],
        keys[pygame.K_DOWN],
        keys[pygame.K_KP0],
        objects,
    )
    hit(player1, player2, objects)
    hit(player2, player1, objects)
    pygame.display.update()
pygame.quit()


from flask import Flask, jsonify, request
from flask_cors import CORS
from argparse import ArgumentParser

from models.wallet import Wallet
from models.blockchain import Blockchain

status_codes = {
    "SUCCESS": 200,
    "CREATED": 201,
    "CLIENT_ERROR": 400,
    "SERVER_ERROR": 500,
}

server = Flask(__name__)
CORS(server)
host = "0.0.0.0"

@server.route("/", methods=["GET"])
def get_ui():
    return "Blockchain implementation from scratch!"

@server.route("/chain", methods=["GET"])
def get_blockchain():
    snapshot = blockchain.get_blockchain()
    snapshot_dict = [block.__dict__.copy() for block in snapshot]
    for block in snapshot_dict:
        block["transactions"] = [tx.__dict__ for tx in block["transactions"]]
    return jsonify(snapshot_dict), status_codes["SUCCESS"]

@server.route("/transactions", methods=["GET"])
def get_outstanding_transactions():
    snapshot = blockchain.get_outstanding_transactions()
    snapshot_dict = [tx.__dict__ for tx in snapshot]
    return jsonify(snapshot_dict), status_codes["SUCCESS"]

@server.route("/node", methods=["GET"])
def get_nodes():
    nodes = list(blockchain.get_peer_nodes())
    response = {"Nodes": nodes}
    return jsonify(response), status_codes["SUCCESS"]

# TODO: get error objects and display them in UI so that clients have clear error messages
@server.route("/mine", methods=["POST"])
def mine_block():
    if blockchain.mine_block():
        block = blockchain.get_last_block()
        new_block = block.__dict__.copy()
        new_block["transactions"] = [tx.__dict__ for tx in new_block["transactions"]]
        response = {"Message": "Mining successful.", "Block": new_block}
        return jsonify(response), status_codes["CREATED"]
    else:
        response = {"Message": "Mining unsuccessful."}
        return jsonify(response), status_codes["SERVER_ERROR"]

@server.route("/transaction", methods=["POST"])
def add_transaction():
    tx_details = request.get_json()
    if not tx_details:
        response = {"Message": "No request body found"}
        return response, status_codes["CLIENT_ERROR"]
    # Check if incoming data has required fields
    required_fields = ["recepient", "amount"]
    if not all(field in tx_details for field in required_fields):
        response = {"Message": "Request missing required fields"}
        return response, status_codes["CLIENT_ERROR"]

    sender = wallet.public_key
    recepient = tx_details["recepient"]
    amount = tx_details["amount"]
    signature = wallet.sign_transaction(sender, recepient, amount)

    if blockchain.add_transaction(sender, recepient, amount, signature):
        transaction = blockchain.get_outstanding_transactions()[-1]
        transaction = transaction.__dict__
        response = {"Message": "Transaction successful", "Transaction": transaction}
        return jsonify(response), status_codes["CREATED"]
    else:
        response = {"Message": "Transaction unsuccessful."}
        return jsonify(response), status_codes["SERVER_ERROR"]

@server.route("/node", methods=["POST"])
def add_node():
    node_details = request.get_json()
    if not node_details:
        response = {"Message": "No request body found"}
        return response, status_codes["CLIENT_ERROR"]
    if "node" not in node_details:
        response = {"Message": "Node data invalid"}
        return response, status_codes["CLIENT_ERROR"]
    node = node_details["node"]
    blockchain.add_peer_node(node)
    response = {
        "Message": "Node added successfully.",
        "Nodes": list(blockchain.get_peer_nodes()),
    }
    return jsonify(response), status_codes["CREATED"]

@server.route("/node/<node_url>", methods=["DELETE"])
def remove_node(node_url):
    if node_url == "" or node_url == None:
        response = {"Message": "Invalid node url"}
        return jsonify(response), status_codes["CLIENT_ERROR"]
    blockchain.remove_peer_node(node_url)
    response = {
        "Message": "Node removed successfully",
        "Nodes": list(blockchain.get_peer_nodes()),
    }
    return jsonify(response), status_codes["SUCCESS"]

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", type=int, default=8000)
    args = parser.parse_args()
    port = args.port
    wallet = Wallet(node=port)
    blockchain = Blockchain(wallet.public_key + '-' + str(port))
    server.run(host=host, port=port)


# -*- coding: cp1251 -*-

# Задание 1

n = int(input("Введите число строк:"))
a = []
i = 1

while i <= n:
    tmp = int(input("Введите натуральное число больше или равное 1 и меньше или равно 10000:"))
    if 1 <= tmp <= 10000:
        a.append(tmp)
        i += 1
    else:
        print("Число вне диапазона, введите другое")

print("Вы ввели: %a. Перевернутый массив: %a" % (a, a[::-1]))

# Задание 2

i = 1
j = 1
b = []
while i <= 1:
    tmp = int(input("Введите натуральное число больше или равное 1 и меньше или равно 100000:"))
    if 1 <= tmp <= 100000:
        n = tmp
        i += 1
    else:
        print("Число вне диапазона, введите другое")

while j <= n:
    tmp = int(input("Введите натуральное число больше или равное 1 и меньше или равно 2*10e9:"))
    if 1 <= tmp <= 20000000000:
        b.append(tmp)
        j += 1
    else:
        print("Число вне диапазона, введите другое")
b = b[-1:]+b[:-1]
print(b)

# Задание 3

i = 1
m = 0
fishermen = 0
weight = []
boat = []

while i <= 1:
    tmp = int(input("Введите массу которую может перенсти одна лодка. Натуральное число число больше или равное 1 и меньше или равно 1000000:"))
    if 1 <= tmp <= 1000000:
        m = tmp
        i += 1
    else:
        print("Масса вне диапазона, введите другое число")

i = 1
while i <= 1:
    tmp = int(input("Введите количество рыбаков. Натуральное число больше или равное 1 и меньше или равно 100:"))
    if 1 <= tmp <= 100:
        fishermen = tmp
        i += 1
    else:
        print("Масса вне диапазона, введите другое число")

for j in range(fishermen):
    i = 1
    while i <= 1:
        tmp = (int(input("Введите вес рыбака %a:" % int(j + 1))))
        if 1 <= tmp <= m:
            weight.append(tmp)
            i += 1
        else:
            print("Масса вне диапазона, введите другое число")

for x in range(len(weight)):
    if weight[x] + min(weight) <= m:
        boat += [[weight[x], min(weight)]]
        weight[x] += m
        weight[weight.index(min(weight))] += m
    else:
        if weight[x] > m:
            continue
        else:
            boat += [[weight[x]]]

print("Для переправки всех %a рыбаков, потребуется %a лодок." % (fishermen, len(boat)))


import sys

input = sys.stdin.readline

n, m = map(int, input().split())

arr = list(map(int, input().split()))

start = 0
end = 0
sum = 0
result = 0

while start <= n - 1 or end <= n - 1:
    if sum > m:
        sum -= arr[start]
        start += 1

    elif sum < m:
        if end > n - 1:
            break
        sum += arr[end]
        end += 1

    if sum == m:
        result += 1
        if end > n-1:
            sum -= arr[start]
            start += 1
        else:
            sum += arr[end]
            end += 1

print(result)

ALGORITHM STUDY/1. 투 포인터, 슬라이딩 윈도우/S2[2003] 수들의 합 2.py


import json
import logging
import re
import xml.etree.ElementTree as ET
from io import StringIO

from requests import __build__ as requests_version
from svtplay_dl.utils.http import get_full_url
from svtplay_dl.utils.http import HTTP
from svtplay_dl.utils.output import output
from svtplay_dl.utils.text import decode_html_entities

class subtitle:
    def __init__(self, config, subtype, url, subfix=None, **kwargs):
        self.url = url
        self.subtitle = None
        self.config = config
        self.subtype = subtype
        self.http = HTTP(config)
        self.subfix = subfix
        self.bom = False
        self.output = kwargs.pop("output", None)
        self.kwargs = kwargs

    def __repr__(self):
        return "<Subtitle(type={}, url={}>".format(self.subtype, self.url)

    def download(self):
        subdata = self.http.request("get", self.url)
        if subdata.status_code != 200:
            logging.warning("Can't download subtitle file")
            return

        data = None
        if "mtgx" in self.url and subdata.content[:3] == b"\xef\xbb\xbf":
            subdata.encoding = "utf-8"
            self.bom = True

        if self.subtype == "tt":
            data = self.tt(subdata)
        if self.subtype == "json":
            data = self.json(subdata)
        if self.subtype == "sami":
            data = self.sami(subdata)
        if self.subtype == "smi":
            data = self.smi(subdata)
        if self.subtype == "wrst":
            if "tv4play" in self.url and subdata.content[:3] == b"\xef\xbb\xbf":
                self.bom = True
            subdata.encoding = subdata.apparent_encoding
            data = self.wrst(subdata)
        if self.subtype == "wrstsegment":
            data = self.wrstsegment(subdata)
        if self.subtype == "raw":
            data = self.raw(subdata)

        if self.subfix:
            if self.config.get("get_all_subtitles"):
                if self.output["episodename"]:
                    self.output["episodename"] = "{}-{}".format(self.output["episodename"], self.subfix)
                else:
                    self.output["episodename"] = self.subfix

        if self.config.get("get_raw_subtitles"):
            subdata = self.raw(subdata)
            self.save_file(subdata, self.subtype)

        self.save_file(data, "srt")

    def save_file(self, data, subtype):
        file_d = output(self.output, self.config, subtype, mode="w", encoding="utf-8")
        if hasattr(file_d, "read") is False:
            return
        file_d.write(data)
        file_d.close()

    def raw(self, subdata):
        return subdata.text

    def tt(self, subdata):
        i = 1
        data = ""
        subs = subdata.text

        subdata = re.sub(' xmlns="[^"]+"', "", subs, count=1)
        tree = ET.XML(subdata)
        xml = tree.find("body").find("div")
        plist = list(xml.findall("p"))
        for node in plist:
            tag = norm(node.tag)
            if tag == "p" or tag == "span":
                begin = node.attrib["begin"]
                if not ("dur" in node.attrib):
                    duration = node.attrib["duration"]
                else:
                    duration = node.attrib["dur"]
                if not ("end" in node.attrib):
                    begin2 = begin.split(":")
                    duration2 = duration.split(":")
                    try:
                        sec = float(begin2[2]) + float(duration2[2])
                    except ValueError:
                        sec = 0.000
                    end = "%02d:%02d:%06.3f" % (int(begin2[0]), int(begin2[1]), sec)
                else:
                    end = node.attrib["end"]
                data += "{}\n{} --> {}\n".format(i, begin.replace(".", ","), end.replace(".", ","))
                data = tt_text(node, data)
                data += "\n"
                i += 1

        return data

    def json(self, subdata):
        data = json.loads(subdata.text)
        number = 1
        subs = ""
        for i in data:
            subs += "{}\n{} --> {}\n".format(number, timestr(int(i["startMillis"])), timestr(int(i["endMillis"])))
            subs += "%s\n\n" % i["text"]
            number += 1

        return subs

    def sami(self, subdata):
        text = subdata.text
        text = re.sub(r"&", "&", text)
        tree = ET.fromstring(text)
        allsubs = tree.findall(".//Subtitle")
        subs = ""
        increase = 0
        for sub in allsubs:
            try:
                number = int(sub.attrib["SpotNumber"])
            except ValueError:
                number = int(re.search(r"(\d+)", sub.attrib["SpotNumber"]).group(1))
                increase += 1
            n = number + increase

            texts = sub.findall(".//Text")
            all = ""
            for text in texts:
                line = ""
                for txt in text.itertext():
                    line += "{}".format(txt)
                all += "{}\n".format(decode_html_entities(line.lstrip()))
            subs += "{}\n{} --> {}\n{}\n".format(n, timecolon(sub.attrib["TimeIn"]), timecolon(sub.attrib["TimeOut"]), all)
        subs = re.sub("&", r"&", subs)
        return subs

    def smi(self, subdata):
        if requests_version < 0x20300:
            subdata = subdata.content.decode("latin")
        else:
            subdata.encoding = "ISO-8859-1"
            subdata = subdata.text
        ssubdata = StringIO(subdata)
        timea = 0
        number = 1
        data = None
        subs = ""
        TAG_RE = re.compile(r"<(?!\/?i).*?>")
        bad_char = re.compile(r"\x96")
        for i in ssubdata.readlines():
            i = i.rstrip()
            sync = re.search(r"<SYNC Start=(\d+)>", i)
            if sync:
                if int(sync.group(1)) != int(timea):
                    if data and data != " ":
                        subs += "{}\n{} --> {}\n".format(number, timestr(timea), timestr(sync.group(1)))
                        text = "%s\n" % TAG_RE.sub("", data.replace("
", "\n"))
                        text = decode_html_entities(text)
                        if text[len(text) - 2] != "\n":
                            text += "\n"
                        subs += text
                        number += 1
                timea = sync.group(1)
            text = re.search("
(.*)", i)
            if text:
                data = text.group(1)
        recomp = re.compile(r"\r")
        text = bad_char.sub("-", recomp.sub("", subs))
        return text

    def wrst(self, subdata):
        ssubdata = StringIO(subdata.text)
        srt = ""
        subtract = False
        number_b = 1
        number = 0
        block = 0
        subnr = False

        for i in ssubdata.readlines():
            match = re.search(r"^[\r\n]+", i)
            match2 = re.search(r"([\d:\.]+ --> [\d:\.]+)", i)
            match3 = re.search(r"^(\d+)\s", i)
            if i[:6] == "WEBVTT":
                continue
            elif "X-TIMESTAMP" in i:
                continue
            elif match and number_b == 1 and self.bom:
                continue
            elif match and number_b > 1:
                block = 0
                srt += "\n"
            elif match2:
                if not subnr:
                    srt += "%s\n" % number_b
                matchx = re.search(r"(?P
\d+):(?P<m1>\d+):(?P<s1>[\d\.]+) --> (?P
\d+):(?P<m2>\d+):(?P<s2>[\d\.]+)", i)
                if matchx:
                    hour1 = int(matchx.group("h1"))
                    hour2 = int(matchx.group("h2"))
                    if int(number) == 1:
                        if hour1 > 9:
                            subtract = True
                    if subtract:
                        hour1 -= 10
                        hour2 -= 10
                else:
                    matchx = re.search(r"(?P<m1>\d+):(?P<s1>[\d\.]+) --> (?P<m2>\d+):(?P<s2>[\d\.]+)", i)
                    hour1 = 0
                    hour2 = 0
                time = "{:02d}:{}:{} --> {:02d}:{}:{}\n".format(
                    hour1,
                    matchx.group("m1"),
                    matchx.group("s1").replace(".", ","),
                    hour2,
                    matchx.group("m2"),
                    matchx.group("s2").replace(".", ","),
                )
                srt += time
                block = 1
                subnr = False
                number_b += 1

            elif match3 and block == 0:
                number = match3.group(1)
                srt += "%s\n" % number
                subnr = True
            else:
                if self.config.get("convert_subtitle_colors"):
                    colors = {
                        "30": "#000000",
                        "31": "#ff0000",
                        "32": "#00ff00",
                        "33": "#ffff00",
                        "34": "#0000ff",
                        "35": "#ff00ff",
                        "36": "#00ffff",
                        "37": "#ffffff",
                        "c.black": "#000000",
                        "c.red": "#ff0000",
                        "c.green": "#00ff00",
                        "c.yellow": "#ffff00",
                        "c.blue": "#0000ff",
                        "c.magneta": "#ff00ff",
                        "c.cyan": "#00ffff",
                        "c.gray": "#ffffff",
                    }
                    sub = i
                    for tag, color in colors.items():
                        regex1 = "<" + tag + ">"
                        replace = ''
                        sub = re.sub(regex1, replace, sub)

                    sub = re.sub("</.+>", "", sub)
                else:
                    sub = re.sub("<[^>]*>", "", i)
                srt += sub.strip()
                srt += "\n"
        srt = decode_html_entities(srt)
        return srt

    def wrstsegment(self, subdata):
        time = 0
        subs = []
        for i in self.kwargs["m3u8"].media_segment:
            itemurl = get_full_url(i["URI"], self.url)
            cont = self.http.get(itemurl)
            if "cmore" in self.url:
                cont.encoding = "utf-8"
            text = cont.text.split("\n")
            for t in text:  # is in text[1] for tv4play, but this should be more future proof
                if "X-TIMESTAMP-MAP=MPEGTS" in t:
                    time = float(re.search(r"X-TIMESTAMP-MAP=MPEGTS:(\d+)", t).group(1)) / 90000 - 10
            text = text[3 : len(text) - 2]
            itmes = []
            if len(text) > 1:
                for n in text:
                    if n:  # don't get the empty lines.
                        itmes.append(n)

            several_items = False
            skip = False
            sub = []

            for x in range(len(itmes)):
                item = itmes[x]
                if strdate(item) and len(subs) > 0 and itmes[x + 1] == subs[-1][1]:
                    ha = strdate(subs[-1][0])
                    ha3 = strdate(item)
                    second = str2sec(ha3.group(2)) + time
                    subs[-1][0] = "{} --> {}".format(ha.group(1), sec2str(second))
                    skip = True
                    continue
                has_date = strdate(item)
                if has_date:
                    if several_items:
                        subs.append(sub)
                        sub = []
                    skip = False
                    first = str2sec(has_date.group(1)) + time
                    second = str2sec(has_date.group(2)) + time
                    sub.append("{} --> {}".format(sec2str(first), sec2str(second)))
                    several_items = True
                elif has_date is None and skip is False:
                    sub.append(item)

            if sub:
                subs.append(sub)
        string = ""
        nr = 1
        for sub in subs:
            string += "{}\n{}\n\n".format(nr, "\n".join(sub))
            nr += 1

        return string

def timestr(msec):
    """
    Convert a millisecond value to a string of the following
    format:

        HH:MM:SS,SS

    with 10 millisecond precision. Note the , seperator in
    the seconds.
    """
    sec = float(msec) / 1000

    hours = int(sec / 3600)
    sec -= hours * 3600

    minutes = int(sec / 60)
    sec -= minutes * 60

    output = "%02d:%02d:%06.3f" % (hours, minutes, sec)
    return output.replace(".", ",")

def timecolon(data):
    match = re.search(r"(\d+:\d+:\d+):(\d+)", data)
    return "{},{}".format(match.group(1), match.group(2))

def norm(name):
    if name[0] == "{":
        _, tag = name[1:].split("}")
        return tag
    else:
        return name

def tt_text(node, data):
    if node.text:
        data += "%s\n" % node.text.strip(" \t\n\r")
    for i in node:
        if i.text:
            data += "%s\n" % i.text.strip(" \t\n\r")
        if i.tail:
            text = i.tail.strip(" \t\n\r")
            if text:
                data += "%s\n" % text
    return data

def strdate(datestring):
    match = re.search(r"^(\d+:\d+:[\.0-9]+) --> (\d+:\d+:[\.0-9]+)", datestring)
    return match

def sec2str(seconds):
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return "{:02d}:{:02d}:{:06.3f}".format(int(h), int(m), s)

def str2sec(string):
    return sum(x * float(t) for x, t in zip([3600, 60, 1], string.split(":")))


from server import _Server
import time

class SampleServer(_Server):
    def handle(self, msg_id, obj, address):
        return super().handle(msg_id, obj, address)

    def server_loop(self):
        while True:
            msg, address = self.socket.recvfrom(1024)
            print(msg, address)
            # self.socket.sendto(b"Reply to: "+ msg, address)
            # if msg == b"monitor":
            #     for x in range(50):
            #         time.sleep(60/50)
            #         self.socket.sendto(f"{x}".encode(), address)

if __name__ == "__main__":
    s = SampleServer("localhost", 50000)
    s.server_loop()


# -*- coding: utf-8 -*-
import logging
import random
import time
from odoo import models, fields, api
from odoo.osv import expression
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from datetime import datetime, timedelta, date

_logger = logging.getLogger(__name__)

class TShirtOrder(models.Model):
    _name = 'awesome_tshirt.order'
    _description = 'Awesome T-shrit Orders'
    _rec_name = 'customer_id'
    _inherit = ['mail.thread']

    @api.model
    def _expand_states(self, states, domain, order):
        return [key for key, val in type(self).state.selection]

    amount = fields.Float('Amount', compute='_compute_amount', store=True)
    customer_id = fields.Many2one('res.partner', string="Customer")
    image_url = fields.Char('Image', help="Encodes the url of the image")
    is_late = fields.Boolean('Is Late', compute='_compute_is_late')
    quantity = fields.Integer('Quantity', default=1)
    size = fields.Selection([
        ('s', 'S'),
        ('m', 'M'),
        ('l', 'L'),
        ('xl', 'XL'),
        ('xxl', 'XXL')
    ],default='m', required=True)
    state = fields.Selection([
        ('new', 'New'),
        ('printed', 'Printed'),
        ('sent', 'Sent'),
        ('cancelled', 'Cancelled')
    ], default='new', required=True, group_expand='_expand_states')

    @api.depends('quantity')
    def _compute_amount(self):
        for record in self:
            unit_price = 15
            if record.size == 's':
                unit_price = 12
            elif record.size in ['xl', 'XL']:
                unit_price = 18
            if record.quantity > 5:
                unit_price = unit_price * 0.9
            record.amount = record.quantity * unit_price

    @api.depends('create_date')
    def _compute_is_late(self):
        for record in self:
            record.is_late = record.create_date < datetime.today() - timedelta(days=7)

    def print_label(self):
        time.sleep(0.5)
        if random.random() < 0.1:
            _logger.info('Printer not connected')
            return False
        _logger.info('Label Printed')
        return True

    @api.model
    def get_empty_list_help(self, help):
        title = "There is not t-shirt order"
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url = '%s/awesome_tshirt/order' % base_url
        content = 'People can make orders through the public page.' %{'url': url}
        return """

%s

%s

        """ % (title, content)

    @api.model
    def get_statistics(self):
        first_day = date.today().replace(day=1).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        last_day = datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        this_month_domain = [('create_date', '>=', first_day), ('create_date', '<=', last_day)]
        new_this_month_domain = expression.AND([this_month_domain, [('state', '=', 'new')]])
        nb_new_orders = self.search_count(new_this_month_domain)
        cancelled_this_month_domain = expression.AND([this_month_domain, [('state', '=', 'cancelled')]])
        nb_cancelled_orders = self.search_count(cancelled_this_month_domain)
        total_amount = self.read_group(new_this_month_domain, ['amount'], [])[0]['amount']
        total_quantity = self.read_group(this_month_domain, ['quantity'], [])[0]['quantity']
        nb_orders = self.search_count(this_month_domain)
        orders_by_size = self.read_group([['state', '!=', 'cancelled']], [], ['size'])

        return {
            'average_quantity': 0 if not nb_orders else round(total_quantity / nb_orders, 2),
            'average_time': (random.random() * 44) + 4,
            'nb_cancelled_orders': nb_cancelled_orders,
            'nb_new_orders': nb_new_orders,
            'orders_by_size': {g['size']: g['quantity'] for g in orders_by_size},
            'total_amount': total_amount or 0,
        }