# Api Agenda Lionx
from src.infrastructures.mongo.mongo_infrastructure import MongoInfrastructure

# Third party
from decouple import config
from pymongo.cursor import Cursor
from pymongo.collection import InsertOneResult, UpdateResult

class MongoRepository:
    def __init__(self):
        self.mongo_client = MongoInfrastructure.get_client()
        self.database = self.mongo_client.get_database(config("DATABASE_NAME"))
        self.collection = self.database.get_collection(config("COLLECTION_NAME"))

    def get_all_contacts(self) -> Cursor:
        remove_pymongo_id = {"_id": 0}
        contacts_cursor = self.collection.find({}, remove_pymongo_id)
        return contacts_cursor

    def get_contact_by_id(self, id) -> dict:
        filter_by_id = {"contact_id": id, "situation": "active"}
        remove_pymongo_id = {"_id": 0}
        contact = self.collection.find_one(filter_by_id, remove_pymongo_id)
        return contact

    def get_contacts_by_first_letters(self, letters) -> Cursor:
        regex_first_letters_contact = {"$regex": f"^{letters}", "$options": "i"}
        filter_by_first_name_letters = {"firstName": regex_first_letters_contact, "situation": "active"}
        remove_pymongo_id = {"_id": 0}
        contacts_cursor = self.collection.find(filter_by_first_name_letters, remove_pymongo_id)
        return contacts_cursor

    def register_contact(self, new_contact) -> InsertOneResult:
        insert_result = self.collection.insert_one(new_contact)
        return insert_result

    def update_contact(self, edited_contact, id) -> UpdateResult:
        filter_by_id = {"contact_id": id}
        new_values = {"$set": edited_contact}
        update_result = self.collection.update_one(filter_by_id, new_values)
        return update_result

    def soft_delete_contact(self, id) -> UpdateResult:
        filter_by_id = {"contact_id": id}
        field_to_update = {"$set": {"situation": "deactivated"}}
        update_result = self.collection.update_one(filter_by_id, field_to_update)
        return update_result


import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], 'utils'))
import numpy as np
import pandas as pd
import argparse
import h5py
import librosa
from scipy import signal
import matplotlib.pyplot as plt
import time
import csv
import random
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from multiprocessing import cpu_count

from utilities import read_audio, create_folder, read_meta
import config
from tqdm import tqdm

# Global flags and variables.
PLOT_FEATURES = False

class LogMelExtractor():
    def __init__(self, sample_rate, window_size, overlap, mel_bins):

        self.window_size = window_size
        self.overlap = overlap

        # Loading hamming window and Mel-filters.
        self.ham_win = np.hamming(window_size)
        self.melW = librosa.filters.mel(sr=sample_rate,
                                        n_fft=window_size,
                                        n_mels=mel_bins,
                                        fmin=50.,
                                        fmax=sample_rate // 2).T

    # transform: Assumes a numpy array representing raw audio-signal.
    def transform(self, audio):

        ham_win = self.ham_win
        window_size = self.window_size
        overlap = self.overlap

        # Compute a spectrogram with consecutive Fourier transforms.
        [f, t, x] = signal.spectral.spectrogram(
                        audio,
                        window=ham_win,
                        nperseg=window_size,
                        noverlap=overlap,
                        detrend=False,
                        return_onesided=True,
                        mode='magnitude')
        x = x.T

        # Applying mel-filters on sequence of fourier transforms.
        x = np.dot(x, self.melW)

        # Applying log on mel-filters.
        x = np.log(x + 1e-8)

        x = x.astype(np.float32)
        return x

def calculate_logmel(audio_path, sample_rate, feature_extractor, n=-1):

    # Read audio (first 4 seconds only).
    (audio, fs) = read_audio(audio_path, target_fs=sample_rate)

    # Extract feature
    feature = feature_extractor.transform(audio)

    return feature, n

def calculate_features(args):

    n_jobs = cpu_count()
    executor = ProcessPoolExecutor(max_workers=n_jobs)
    futures = []
    print("Using {} workers in parallel.".format(n_jobs))

    # Arguments.
    dataset_dir = args.dataset_dir
    workspace = args.workspace
    features_type = args.mode
    features_file_name = args.features_file_name

    # Parameters for feature extraction.
    metadata_delimiter = config.metadata_delimiter
    sample_rate = config.sample_rate
    window_size = config.window_size
    overlap = config.overlap
    seq_len = config.seq_len
    mel_bins = config.mel_bins

    # Dislaying arguments and parameters.
    print("Arguments and Parameters:")
    print("Dataset Directory: {}".format(dataset_dir))
    print("Workspace: {}".format(workspace))
    print("Sample Rate: {}".format(sample_rate))
    print("Window Size: {}".format(window_size))
    print("Overlapping Frames: {}".format(overlap))
    print("Sequence Length: {}".format(seq_len)) # Dimension of feature corresponding to each audio file: (seq_len, mel_bins)
    print("Mel Bins: {}".format(mel_bins))

    # Paths
    audio_dir = os.path.join(dataset_dir, 'audio')
    meta_csv = os.path.join(dataset_dir, 'metadata', 'UrbanSound8K.csv')
    hdf5_path = os.path.join(workspace, 'features', features_type, features_file_name)

    # Displaying paths.
    print("Reading audio from: {}".format(audio_dir))
    print("Reading meatadata file form: {}".format(meta_csv))
    print("Saving the extracted features at: {}".format(hdf5_path))

    create_folder(os.path.dirname(hdf5_path))

    # Feature extractor
    feature_extractor = LogMelExtractor(sample_rate=sample_rate,
                                        window_size=window_size,
                                        overlap=overlap,
                                        mel_bins=mel_bins)

    audio_names, fs_IDs, start_times, end_times, saliences, folds, class_IDs, classes = read_meta(meta_csv, metadata_delimiter)

    # Create hdf5 file
    hf = h5py.File(hdf5_path, 'w')

    # Intialising hdf5 file to store audios/labels of all folds.
    for fold_id in range(1, 11):
        hf.create_dataset(
            name='features_fold{}'.format(fold_id),
            shape=(0, seq_len, mel_bins),
            maxshape=(None, seq_len, mel_bins),
            dtype=np.float32)
        hf.create_dataset(
            name='labels_fold{}'.format(fold_id),
            shape=(0, 1),
            maxshape=(None, 1),
            dtype=np.float32)

    # To remember number of audio files processed in each fold.
    fold_count = [0] * 11

    for (n, audio_name) in enumerate(audio_names):

        # Calculate feature.
        audio_path = os.path.join(audio_dir, 'fold{}'.format(folds[n]), audio_name)
        futures.append(executor.submit(partial(calculate_logmel, audio_path, sample_rate, feature_extractor, n)))

    for future in tqdm(futures):
        if future.result() is not None:
            feature, n = future.result()

            hf['features_fold{}'.format(folds[n])].resize((fold_count[folds[n]] + 1, seq_len, mel_bins))
            hf['features_fold{}'.format(folds[n])][fold_count[folds[n]]] = feature

            hf['labels_fold{}'.format(folds[n])].resize((fold_count[folds[n]] + 1, 1))
            hf['labels_fold{}'.format(folds[n])][fold_count[folds[n]]] = class_IDs[n]

            fold_count[folds[n]] += 1

            # Plot log-Mel for debug.
            if PLOT_FEATURES:
                plt.matshow(feature.T, origin='lower', aspect='auto', cmap='jet')
                plt.show()

    hf.close()

    # Displaying total files processed from each fold.
    print("Files Processed from each fold:")
    for fold_id in range(1, 11):
        print("Fold {}: {} files.".format(fold_id, fold_count[fold_id]))

# USAGE: python features.py logmel --dataset_dir=$DATASET_DIR --workspace=$WORKSPACE

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='')
    subparsers = parser.add_subparsers(dest='mode') # Different modes can be added to extract different type of features.

    parser_logmel = subparsers.add_parser('logmel')
    parser_logmel.add_argument('--dataset_dir', type=str, required=True) # Path to the UrbanSound8K folder.
    parser_logmel.add_argument('--workspace', type=str, required=True) # Directory where extracted features, model and logs of experiments are stored.
    parser_logmel.add_argument('--features_file_name', type=str, required=True) # logmel-features.h5
    args = parser.parse_args()

    if args.mode == 'logmel':
        calculate_features(args)
    else:
        raise Exception('Incorrect arguments!')


import socket
import serial
import sqlite3
import select
import time
import datetime

HEADERSIZE = 10
running_on_pie = False  # pie or windows

if running_on_pie:
    host = '192.168.1.10'
    pos = '192.168.1.10'
    win1 = '192.168.1.11'
    win2 = '192.168.1.12'
    conn = sqlite3.connect('/home/sysop/pos/order.db')
    robot = serial.Serial('/dev/ttyUSB0', 19200)
else:
    host = '192.168.86.26'
    pos = '192.168.86.26'
    win1 = '192.168.86.26'
    win2 = '192.168.86.11'
    conn = sqlite3.connect('order.db')
    robot = serial.Serial('COM9', 19200)

port = 12345

c = conn.cursor()

send_to_bot = False
send_to_w1 = False
send_to_w2 = False
send_to_pos = False

bot_data = ''
bot_hold = ''
old_data = ''

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

serverSocket.bind((host, port))
serverSocket.listen(5)

sockets_list = [serverSocket]

clients = {}

print('Listening for connections on {}:{}...'.format(host, port))

def un_start():
    command = "/usr/bin/sudo /sbin/shutdown -r now"
    import subprocess
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    print(output)

def log_it(note):
    if running_on_pie:
        f = open("/home/sysop/pos/log.txt", "a+")
    else:
        f = open("log.txt", "a+")
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
    info = st + ' > '
    info += note
    info += '\n\r'
    f.write(info)

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS donut(donutID int, drink int, topping int, orderNUM int,'
              ' pay int)')

def data_test(a1):
    c.execute("SELECT * FROM donut WHERE orderNUM=:a1", {"a1": str(a1)})
    data1 = c.fetchall()
    if data1:
        return data1

def data_delete(a1):
    c.execute("DELETE FROM donut WHERE orderNUM=:a1", {"a1": str(a1)})
    conn.commit()

# Handles message receiving
def receive_message(client_socket1):
    try:
        message_header = client_socket1.recv(HEADERSIZE)
        if not len(message_header):
            return False

        message_length = int(message_header.decode('utf-8').strip())

        return {'header': message_header, 'data': client_socket1.recv(message_length)}

    except Exception as e:
        print(e)
        return False

def order_process(order):
    if len(order) == 4:
        xa = str(data_test(order))
        if xa != 'None':
            xa = xa.strip('[]()')
            xa = xa.replace(" ", "")
            xa = xa.split(",")
            dm = '$A' + str(xa[0])
            if str(xa[1]) == '0':
                dm += '1000#'
            else:
                dm += str(xa[1])
                dm += '#'
        else:
            dm = xa
        return dm

create_table()

while True:
    read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)
    for notified_socket in read_sockets:
        if notified_socket == serverSocket:
            client_socket, client_address = serverSocket.accept()

            # Client should send his name right away, receive it
            user = receive_message(client_socket)

            # If False - client disconnected before he sent his name
            if user is False:
                continue

            # Add accepted socket to select.select() list
            sockets_list.append(client_socket)

            # Also save username and username header
            clients[client_socket] = user

            print('Accepted connection from {}, username: {}'.format(client_address, user['data'].decode('utf-8')))
            log_it('Accepted connection from {}, username: {}'.format(client_address, user['data'].decode('utf-8')))
        else:
            # Receive message
            message = receive_message(notified_socket)

            # If False, client disconnected, cleanup
            if message is False:
                print('Closed connection from: {}'.format(clients[notified_socket]['data'].decode('utf-8')))
                log_it('Closed connection from: {}'.format(clients[notified_socket]['data'].decode('utf-8')))
                # Remove from list for socket.socket()
                sockets_list.remove(notified_socket)

                # Remove from our list of users
                del clients[notified_socket]

                continue

            # Get user by notified socket, so we will know who sent the message
            user = clients[notified_socket]
            data = message["data"].decode("utf-8")
            line = ''
            if data != 'ready':
                if data != old_data:
                    print('Received message from {}: {}'.format(user["data"].decode("utf-8"), data))
                    log_it('Received message from {}: {}'.format(user["data"].decode("utf-8"), data))
                    old_data = data

            if user["data"] == 'm1'.encode("utf-8"):
                # start the order
                if data == 'A order In':
                    message2_header = '{:10}'.format(len(data))
                    message['header'] = message2_header.encode("utf-8")
                    message['data'] = data.encode("utf-8")
                    send_to_w1 = True

            # pos info
            if user["data"] == 'pos'.encode("utf-8"):
                robot.write(data.encode("utf-8"))
                time.sleep(1)
                line_in = robot.readline()
                line = line_in.decode("utf-8")
                line = line.rstrip()
                if line[0] == '$':
                    message2_header = '{:10}'.format(len(line))
                    message['header'] = message2_header.encode("utf-8")
                    message['data'] = line.encode("utf-8")
                    print(line.encode("utf-8"))
                    send_to_pos = True

            # window A data and processing
            if user["data"] == 'w1'.encode("utf-8"):
                if len(data) == 4:
                    if data == '0000':
                        un_start()
                    message2 = order_process(data)
                    bot_hold = message2
                    time.sleep(1)
                    message2_header = '{:10}'.format(len(message2))
                    message['header'] = message2_header.encode("utf-8")
                    message['data'] = message2.encode("utf-8")
                    send_to_w1 = True

                if len(data) == 5:
                    if data == 'start':
                        robot.write(bot_hold.encode("utf-8"))
                        time.sleep(1)
                    if data == 'ready':
                        line_in = robot.readline()
                        line = line_in.decode("utf-8")
                        line = line.rstrip()
                        #  if line == 'end':
                        message2_header = '{:10}'.format(len(line))
                        message['header'] = message2_header.encode("utf-8")
                        message['data'] = line.encode("utf-8")
                        send_to_w1 = True
                        #  main com arduino
            # if robot.in_waiting > 0:
            #     line_in = robot.readline()
            #     line = line_in.decode("utf-8")
            #     line = line.rstrip()
            #
            # if len(line) > 1:
            #
            #     if line == 'end' and user["data"] == 'w1'.encode("utf-8"):
            #         message2_header = '{:10}'.format(len(line))
            #         message['header'] = message2_header.encode("utf-8")
            #         message['data'] = line.encode("utf-8")
            #         send_to_w1 = True
            #     if line[0] == '$' and user["data"] == 'pos'.encode("utf-8"):
            #         message2_header = '{:10}'.format(len(line))
            #         message['header'] = message2_header.encode("utf-8")
            #         message['data'] = line.encode("utf-8")
            #         send_to_pos = True

            # Iterate over connected clients and broadcast message
            for client_socket in clients:
                # sent it
                the_ip = client_socket.getpeername()[0]

                if the_ip == win1 and send_to_w1:
                    client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
                    print(user['header'] + user['data'] + message['header'] + message['data'])
                    send_to_w1 = False

                if the_ip == win2 and send_to_w2:
                    client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
                    send_to_w2 = False

                if the_ip == pos and send_to_pos:
                    client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
                    print(user['header'] + user['data'] + message['header'] + message['data'])
                    send_to_pos = False

            line = ''

    # It's not really necessary to have this, but will handle some socket exceptions just in case
    for notified_socket in exception_sockets:
        # Remove from list for socket.socket()
        sockets_list.remove(notified_socket)

        # Remove from our list of users
        del clients[notified_socket]


import pygame, os

from modules.entitysets._puresensor import PureSensor

from imageload import loadImage

from button import Button

from menustate import MenuState

from staticimage import StaticImage

from gridrounding import gridRound

from selectionbox import SelectionBox

from label import Label

class RemoveSensorButton( Button ):
    image = loadImage("remove.png", 2 )
    def __init__( self, menu=None ):
        Button.__init__( self, None, None, menu )
        self.rect = self.image.get_rect()
        self.rect.topleft = ( 54, 24 )
    def push( self, clickKey, click ):
        if "up" in clickKey:
            self.parentState.toggleRemove()

class SnapToGridButton( Button ):
    image = loadImage( "gridbutton.png", 2 )
    def __init__( self, menu=None ):
        Button.__init__( self, None, None, menu )
        self.rect = self.image.get_rect()
        self.rect.topleft = ( 24, 24 )
    def push( self, clickKey, click ):
        if "up" in clickKey:
            self.parentState.toggleSnapToGrid()

class SensorEditButton( Button ):
    image = loadImage( "sensoreditbutton.png", 2 )
    rect = image.get_rect()
    rect.topleft = ( 24, 144 )
    def __init__( self, menu=None ):
        Button.__init__( self, None, None, menu )

    def push( self, clickKey, click ):
        if "up" in clickKey:
            aBoundEditState = SensorEditState( self.parentState.menu )
            self.parentState.menu.loadMenuState( aBoundEditState )

class SensorEditState( MenuState ):
    def __init__( self, menu, sprites=[] ):
        MenuState.__init__( self, menu, sprites )
        self.sprites = [self.fileNameLabel, self.miniMap]
        self.buttons = []

        self.panel = StaticImage(loadImage( "devmenu.png", 2 ), (10, 10))
        self.addSprite( self.panel )

        self.snapToGridButton = SnapToGridButton( self )
        self.addButton( self.snapToGridButton )

        self.removeButton = RemoveSensorButton( self )
        self.addButton( self.removeButton )

        self.gridButtonSelectionBox = None
        self.removeButtonSelectionBox = None

        self.addingMode = True
        self.removingMode = False

        self.curGrabbedSens = None

        self.curStart = None
        self.gridX = 40
        self.gridY = 40
        self.snapToGrid = False
        self.whereEntWasGrabbed = None

    def toggleSnapToGrid( self ):
        self.snapToGrid = not self.snapToGrid
        if self.gridButtonSelectionBox is None:
            self.gridButtonSelectionBox = SelectionBox( self.snapToGridButton.rect, self )
            self.addSprite( self.gridButtonSelectionBox )
        else:
            self.removeSprite( self.gridButtonSelectionBox )
            self.gridButtonSelectionBox = None
        self.menu.loadMenuState( self )

    def toggleRemove( self ):
        self.removingMode = not self.removingMode
        if self.removeButtonSelectionBox is None:
            self.removeButtonSelectionBox = SelectionBox( self.removeButton.rect, self )
            self.addSprite( self.removeButtonSelectionBox )
        else:
            self.removeSprite( self.removeButtonSelectionBox )
            self.removeButtonSelectionBox = None
        self.menu.loadMenuState( self )

    def getPressedSensor( self, point ):
        """See which sensor is at this point"""
        escape = False
        for eachSpriteList in ( eachGroup.sprites() for eachGroup in self.menu.playState.groups ):
            for eachSprite in [ sprite for sprite in eachSpriteList if sprite.pureSensor]:
                if eachSprite.rect.collidepoint( point ):
                    return eachSprite

    def update( self, dt, click, clickKey, curMousePos=None ):
        MenuState.update( self, dt, click, clickKey, curMousePos )
        playState = self.menu.playState
        curMousePos = curMousePos[0]-playState.panX, curMousePos[1]-playState.panY
        if self.snapToGrid:
            curMousePos = gridRound( curMousePos, self.gridX, self.gridY, trueRounding=True )
        else:
            curMousePos = curMousePos
        if self.curStart is not None:
            self.menu.playState.lineVisualiser.devMenuLineGroups = [ [ self.curStart, ( self.curStart[0], curMousePos[1] ) ],
                     [ ( self.curStart[0], curMousePos[1] ), curMousePos ], [ curMousePos, ( curMousePos[0], self.curStart[1] ) ], [ ( curMousePos[0], self.curStart[1] ), self.curStart ] ]
            self.menu.playState.lineVisualiser.devMenuLineGroups = [ [ (each[0]+playState.panX, each[1]+playState.panY) for each in eachLine ] for eachLine in self.menu.playState.lineVisualiser.devMenuLineGroups ]
            self.menu.playState.lineVisualiser.flush = True
        self.menu.playState.lineVisualiser.renderLines = True
        self.menu.playState.lineVisualiser.renderPhysicsLines = True
        self.menu.playState.lineVisualiser.forceNoRender = True
        if click is not None:
            if clickKey is 'mouse1down' and self.curStart is None:
                self.curStart = curMousePos
            elif clickKey is 'mouse1up':
                #ADD SENSOR HERE
                destPoint = min( self.curStart[0], curMousePos[0] ), min( self.curStart[1], curMousePos[1] )
                w = abs( self.curStart[0] - curMousePos[0] )
                h = abs( self.curStart[1] - curMousePos[1] )
                if w != 0  or h != 0:
                    destPoint = destPoint[0] + w/2, destPoint[1] + h/2
                    destGroup = getattr( self.menu.playState, PureSensor.playStateGroup )
                    PureSensor( pos=destPoint, group=destGroup, width=w, height=h )
                self.curStart = None
            elif clickKey is 'mouse3down':
                self.curGrabbedSens = self.getPressedSensor( (curMousePos[0]+playState.panX, curMousePos[1]+playState.panY) )
                if self.curGrabbedSens is not None:
                    entPos = self.curGrabbedSens.getPosition()
                    self.whereEntWasGrabbed = curMousePos[0] - entPos[0], curMousePos[1] - entPos[1]
            elif clickKey is 'mouse3up':
                pickedSensor = self.getPressedSensor( (curMousePos[0]+playState.panX, curMousePos[1]+playState.panY) )
                if pickedSensor is not None:
                    if self.removingMode:
                        pickedSensor.kill()
                self.curGrabbedSens = None
                self.whereEntWasGrabbed = None
        elif curMousePos is not None:
            if self.curGrabbedSens is not None:
                curEnt = self.curGrabbedSens
                newPos = curMousePos[0]-self.whereEntWasGrabbed[0], curMousePos[1]-self.whereEntWasGrabbed[1]
                curEnt.setPosition( newPos )


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 12:32:47 2022

@author: maksi
"""

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.datasets import load_digits
from keras.models import Sequential
from keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

data = load_digits()
X = data.data
y = data.target
y = pd.Categorical(y)
y = pd.get_dummies(y).values
class_num = y.shape[1]

model = Sequential()
model.add(Dense(64, input_shape = (X.shape[1],), activation = 'relu'))
model.add(Dense(64, activation = 'relu'))
model.add(Dense(64, activation = 'relu'))
model.add(Dense(class_num, activation = 'softmax'))
learning_rate = 0.0001
model.compile(optimizer= Adam(learning_rate), loss='categorical_crossentropy',metrics=('accuracy'))
model.summary()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
model.fit(X_train, y_train, batch_size=32, epochs=100, validation_data=(X_test, y_test), verbose=2)

historia = model.history.history
floss_train = historia['loss']
floss_test = historia['val_loss']
acc_train = historia['accuracy']
acc_test = historia['val_accuracy']
fig,ax = plt.subplots(1,2, figsize=(20,10))
epochs = np.arange(0, 100)

ax[0].plot(epochs, floss_train, label = 'floss_train')
ax[0].plot(epochs, floss_test, label = 'floss_test')
ax[0].set_title('Funkcje strat')
ax[0].legend()

ax[1].set_title('Dokladnosci')
ax[1].plot(epochs, acc_train, label = 'acc_train')
ax[1].plot(epochs, acc_test, label = 'acc_test')
ax[1].legend()


#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-

# mainframe.py
# Pomodoro
#
# Created by Roman Rader on 22.06.11.
# New BSD License 2011 Antigluk https://github.com/antigluk/Pomodoro

"""

Contains main frame of application.

"""

import wx
from state import PomodoroStateProxy as PomodoroState
from NotificationCenter.NotificationCenter import NotificationCenter
import logging
logging.getLogger('Pomodoro')

class MainFrameController(wx.Frame):
    """Main frame of Pomodoro"""
    def __init__(self):
        wx.Frame.__init__(
            self,
            None,
            -1,
            'Pomodoro it!',
            style=wx.BORDER_DEFAULT | wx.STAY_ON_TOP,
            size=(220, 120),
            )
        state = PomodoroState()
        self.__state_dict = {
            state.StateNoState: {'bs': '...'},
            state.StateInPomodoro: {'bs': u"Отменить..."},
            state.StateInRest: {'bs': u"Отдыхайте!"},
            state.StateWaitingPomodoro: {'bs': u"Начать помидору"},
            state.StateWaitingRest: {'bs': u"Начать отдых"},
            state.StatePomodoroKilled: {'bs': u"Начать помидору"},
            }
        self.buildFrame()
        self.updateUI()
        self.makeMenu()
        self.Show(False)
        NotificationCenter().addObserver(self,self.onDBUpdate,"dbUpdated")
        NotificationCenter().addObserver(self,self.onUpdateUI,"updateUI")

    def buildFrame(self):
        self.panel = wx.Panel(self)
        self.txt = wx.StaticText(self.panel, pos=(10, 10),
                                 label='Pomodoro!')
        self.times_l = wx.StaticText(self.panel, pos=(120, 10),
                label=u"0 помидор")
        self.timer_ctrl = wx.TextCtrl(self.panel, pos=(10, 30),
                size=(200, -1), style=wx.TE_READONLY | wx.TE_CENTER)
        self.start_button = wx.Button(self.panel, pos=(20, 70), label=''
                , size=(170, -1))
        self.start_button.Bind(wx.EVT_BUTTON, self.bClick)

    def onUpdateUI(self, event):
        self.updateUI()

    def updateUI(self):
        #TODO: проверять видимо ли окно. иначе не обновлять
        #TODO: remove this ugly method
        state = PomodoroState()
        self.timer_ctrl.SetValue(state.text)
        self.start_button.SetLabel(self.__state_dict[state.active]['bs'])
        self.txt.SetLabel(state.caption)
        self.times_l.SetLabel(u"%d помидор" % state.GetTodayCount())

    def bClick(self, m):
        logging.debug("Toggle state called from menu")
        self.controller.toggleState()

    def onExit(self,m):
        logging.debug("Quit called from menu")
        self.controller.quit()

    def makeMenu(self):
        self.menuBar = wx.MenuBar()

        self.filemenu = wx.Menu()
        self.pomodmenu = wx.Menu()

        item = self.filemenu.Append(wx.ID_ANY, "Hide")
        self.Bind(wx.EVT_MENU, self.hideFrame, item)
        item = self.filemenu.Append(wx.ID_ANY, "Toggle pomodoro")
        self.Bind(wx.EVT_MENU, self.bClick, item)
        self.filemenu.AppendSeparator()
        item = self.filemenu.Append(wx.ID_EXIT, "&Quit", "quit")
        self.Bind(wx.EVT_MENU, self.onExit, id=wx.ID_EXIT)

        item = self.pomodmenu.Append(wx.ID_ANY, "All", "List of pomodoros")
        self.Bind(wx.EVT_MENU, self.showListOfPomodoros, item)
        item = self.pomodmenu.Append(wx.ID_ANY, "Statistics", "Statistics")
        self.Bind(wx.EVT_MENU, self.showStatistics, item)

        self.menuBar.Append(self.filemenu, "&File")
        self.menuBar.Append(self.pomodmenu, "&Pomodors")

        self.SetMenuBar(self.menuBar)

    def onDBUpdate(self, obj):
        pass

    def hideFrame(self, m):
        logging.debug("Hide frame called from menu")
        self.Show(False)

    def showListOfPomodoros(self, m):
        logging.debug("Show list of pomodors called from menu")
        self.controller.showListOfPomodoros()

    def showStatistics(self, m):
        logging.debug("Show statistics of pomodors called from menu")
        self.controller.showStatistics()


#encoding:UTF-8

import urllib
import urllib.request
import json
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
import matplotlib.lines as mlines
import numpy as np
import time

data = urllib.request.urlopen('https://stationdata.wunderground.com/cgi-bin/stationdata?iconsize=3&width=2048&height=2048&maxage=3600&format=json&maxstations=100000&rf_filter=1&minlat=38&minlon=-85&maxlat=48&maxlon=-73').read()
record = data.decode('UTF-8')
record = record.replace('},}', '}}')
a = open("/Users/hsw/Desktop/CA_region_rawdata.txt", "w+")
a.write(record)
a.close()

data = json.loads(record)
#print(data)

print(data['conds'])
preprocess = data['conds']

station = []
T = []
lats = []
lons = []

for o in preprocess:
    id = str(o)
    station.append(preprocess[id]['id'])
    T.append(5/9*(float(preprocess[id]['tempf'])-32))
    lats.append(float(preprocess[id]['lat']))
    lons.append(float(preprocess[id]['lon']))

# ============================================ # plot
# ============================================initialize the plot
plt.figure(figsize=(11, 8), dpi=120)
axes = plt.subplot(111)
# set up map projection with
# use low resolution coastlines.
map = Basemap(llcrnrlon=-87, llcrnrlat=38, urcrnrlon=-73, urcrnrlat=48, \
              rsphere=(6378137.00, 6356752.3142), \
              resolution='i', projection='merc', \
              lat_0=40., lon_0=-20., lat_ts=20.)
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary(fill_color='#87CEFA')#689CD2
# draw lat/lon grid lines every 30 degrees.

#map.drawmeridians(np.arange(0, 360, 10))
map.drawmeridians(np.arange(0, 360, 10),labels=[0,0,0,1],fontsize=10)
#map.drawparallels(np.arange(-90, 90, 10))
map.drawparallels(np.arange(-90, 90, 10),labels=[1,0,0,0],fontsize=10)

# Fill continent wit a different color
map.fillcontinents(color='#FFFFFF', lake_color='#EEEEEE', zorder=0)

# ============================================draw the stations and data
# compute native map projection coordinates of lat/lon grid.
x, y = map(lons, lats)
max_T = max(T)
# Plot each city in a loop.
# Set some parameters
size_factor = 100.0
x_offset = 20.0
y_offset = -20.0
rotation = 0
temp=0

f = open("/Users/hsw/Desktop/CA_region_Tdata.txt", "w+")
f.close()
#draw station point

analyze = ''

for i, j, k, l in zip(x, y, T, station):
    temp = temp+1
    size = size_factor * k / max_T
    if k <= -10.0 and k >= -100.0:
        cs1 = map.scatter(i, j, s=15, marker='o', color='#00008F')
    if -10 < k and k <= -5:
        cs2 = map.scatter(i, j, s=15, marker='o', color='#00009F')
    if -5 < k and k <= -2:
        cs3 = map.scatter(i, j, s=15, marker='o', color='#0000FF')
    if -2 < k and k <= 2:
        cs4 = map.scatter(i, j, s=15, marker='o', color='#006FFF')
    if 2 < k and k <= 6:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#00BFFF')
    if 6 <= k and k <= 10:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#00FFFF')
    if 10 <= k and k <= 14:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#4FFFAF')
    if 14 <= k and k <= 18:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#7FF77F')
    if 18 <= k and k <= 22:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#FFFF00')
    if 22 <= k and k <= 26:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#FFBF00')
    if 26 <= k and k <= 30:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#FF6F00')
    if 30 <= k and k <= 35:
        cs5 = map.scatter(i, j, s=15, marker='o', color='#FF0000')
    if 35 < k and k <= 100:
        cs6 = map.scatter(i, j, s=15, marker='o', color='#7F0000')

    #if k != 9999:
    #    plt.text(i, j, str(k) + '°C', rotation=rotation, fontsize=10)

    f = open("/Users/hsw/Desktop/CA_region_Tdata.txt", "a+")
    f.write(' Station:'+ l + ' Temperature:' + str(k) + '\n')
    f.close()

title = '多伦多及附近地区气温分布图\n' + '数据更新时间:' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()- 8 * 60 * 60 * 1000)) + 'UTC\n数据来自：wunderground weather, 绘制@Louis_He'
# ============================================#define legends
a = mlines.Line2D([], [], color='#7F0000', marker='o',
                              markersize=5, label='>35°C',ls='')
b = mlines.Line2D([], [], color='#FF0000', marker='o',
                              markersize=5, label='>30°C',ls='')
c = mlines.Line2D([], [], color='#FF6F00', marker='o',
                              markersize=5, label='26~30°C',ls='')
d = mlines.Line2D([], [], color='#FFBF00', marker='o',
                          markersize=5, label='22~26°C',ls='')
e = mlines.Line2D([], [], color='#FFFF00', marker='o',
                          markersize=5, label='18~22°C',ls='')
f = mlines.Line2D([], [], color='#7FF77F', marker='o',
                          markersize=5, label='14~18°C',ls='')
g = mlines.Line2D([], [], color='#4FFFAF', marker='o',
                          markersize=5, label='10~14°C',ls='')
h = mlines.Line2D([], [], color='#00FFFF', marker='o',
                          markersize=5, label='6~10°C',ls='')
i = mlines.Line2D([], [], color='#00BFFF', marker='o',
                          markersize=5, label='2~6°C',ls='')
j = mlines.Line2D([], [], color='#006FFF', marker='o',
                          markersize=5, label='-2~2°C',ls='')
k = mlines.Line2D([], [], color='#0000FF', marker='o',
                          markersize=5, label='-5~-2°C',ls='')
l = mlines.Line2D([], [], color='#00009F', marker='o',
                          markersize=5, label='-10~-5°C',ls='')
m = mlines.Line2D([], [], color='#00008F', marker='o',
                          markersize=5, label='<-10°C',ls='')
plt.legend(handles=[b, c, d, e, f, g, h, i, j, k, l, m])
plt.title(title)

save = '/Users/hsw/Desktop/CA_region_Tsample.png'
plt.savefig(save, dpi=120)


from pynput.keyboard import Listener, Key
import time
from threading import Thread
from canvas import Canvas
from pedal import Pedal
from snake import Snake
from ball import Ball
import os

def on_press(key):
    if hasattr(key, 'char'):  # Write the character pressed if available
      print(key.char)

    elif key == Key.up:  # If space was pressed, write a space
      print('up')
      snake.up()
    elif key == Key.down:  # If space was pressed, write a space
      print('down')
      snake.down()

    elif key == Key.left:  # If space was pressed, write a space
      print('left')
      snake.left()

    elif key == Key.right:  # If space was pressed, write a space
      print('right')
      snake.right()

canvas = Canvas(15, 50)
snake = Snake(10, 5)
snake.left()
pedal = Pedal(1, 7)
ball = Ball(8,7)

gameover = False
while(not gameover):
  with Listener(on_press=on_press) as ls:
    def time_out(period_sec: int):
        time.sleep(period_sec)  # Listen to keyboard for period_sec seconds
        ls.stop()
        os.system('cls' if os.name == 'nt' else 'clear')
    Thread(target=time_out, args=(0.5,)).start()
    ls.join()
    #move entities
    ball.collision(canvas)
    ball.move()
    snake.move()
    pedal.move(canvas)
    canvas.clear()
    canvas.createBorder()

    if(snake.detectColission(canvas) or ball.getgameOver()):
      gameover = True
    #print entities
    canvas = snake.drawSnake(canvas)
    canvas = pedal.print(canvas)
    canvas = ball.print(canvas)
    canvas.print()
    print("your score: ",ball.score)
os.system('cls' if os.name == 'nt' else 'clear')
print("Loser your score was: ",ball.score)


import random
import time
from colorama import Back, Fore, init
from SudokuF import *
from SudokuT import *
from Menus import *
from Ahorcado import *

lop = 0
while lop == 0:
    menuprincipal()
    opcionprincipal = input(Fore.BLUE + "[4] Finalizar: " + Fore.RESET)
    if opcionprincipal == "Fernando": #Easter egg
        newgame()
    if opcionprincipal == "Endgame": #Easter egg
        creditoss()
        exit()
    if opcionprincipal == "Ayuda": #Easter egg
        jueguito()
    if opcionprincipal == "Mario":
        from mario_level_1 import *
        if __name__ == '__main__':
            main()
            pg.quit()
            #sys.exit()
    numbers2 = opcionprincipal.split()
    while len(numbers2) != 1 or not numbers2[0].isdigit() or int(numbers2[0]) > 4 or int(numbers2[0]) < 1:
        print(Fore.RED + "...Opción incorrecta. Intente nuevamente." + Fore.RESET)
        opcionprincipal = input(Fore.BLUE + "[4] Finalizar: " + Fore.RESET)
        numbers2 = opcionprincipal.split()
    opcionprincipal = int(numbers2[0])
    loop = True
    while loop == True:
        if opcionprincipal == 1:
            name = input(Fore.MAGENTA + "Nombre del jugador: " + Fore.RESET)
            name_tablero = input(Fore.LIGHTMAGENTA_EX +"Nombre del tablero: " + Fore.RESET)
            tablero = tableros() #[[1,3,4,5,8,9,2,6,7],[8,5,7,2,6,3,1,9,4],[9,6,2,1,4,7,8,3,5],[2,9,3,7,1,8,4,5,6],[5,4,1,3,2,6,7,8,9],[7,8,6,9,5,4,3,2,1],[4,7,9,8,3,5,6,1,2],[6,2,8,4,9,1,5,7,3],[3,1,5,6,7,2,9,4,0]]
            imprimeTablero(tablero, name_tablero)
            tablerverificar = []
            for i in range(9):
                tablerverificar.append([])
                for j in range(9):
                    tablerverificar[i].append(tablero[i][j])
            while not tableroCompleto(tablero):
                numbers = input("Ingrese fila columna cifra: ")
                numbers = numbers.split()
                while verificardigitosvalidos(numbers) == False:
                    numbers = input("Ingrese fila columna cifra: ")
                    numbers = numbers.split()
                x = int(numbers[0])
                y = int(numbers[1])
                d = int(numbers[2])
                if verificarjugadavalida(tablero, x, y, d, tablerverificar) == True:
                    tablero[x-1][y-1] = d
                    imprimeTablero(tablero, name_tablero)
            if final(tablero, name, name_tablero) == True:
                loop = False
        elif opcionprincipal == 2:
            print("Desea cargar un tablero propio?")
            print("[1] Si")
            opcion = (input("[2] Cargar Tableros predefinidos: "))
            while opcion != "1" and opcion != "2":
                print(Fore.RED + "Opción incorrecta. Intente nuevamente." + Fore.RESET)
                opcion = (input("[2] Cargar Tableros predefinidos: "))
            opcion = int(opcion)
            if opcion == 1:
                vertablerosguardados()
            if opcion == 2:
                print()
                alltableros()
                numero = input("Ingrese el número del tablero que desea ver/jugar: ")
                while not numero.isdigit() or int(numero) > 10 or int(numero) < 1:
                    print(Fore.RED + "Opción incorrecta. Intente nuevamente." + Fore.RESET)
                    numero = input("Ingrese el número del tablero que desea ver/jugar: ")
                numero = int(numero)
                tablero = selecionartablero(numero)
                imprimeTablero(tablero, " ")
                print("Desea jugar este tablero?:")
                print("[1] Si")
                opcion = (input("[2] Regresar: "))
                opcion = opcion.split()
                while len(opcion) != 1 or not opcion[0].isdigit() or int(opcion[0]) > 2 or int(opcion[0]) < 1:
                    print(Fore.RED + "...Opción incorrecta. Intente nuevamente." + Fore.RESET)
                    opcion = (input("[2] Regresar: "))
                    opcion = opcion.split()
                opcion = int(opcion[0])
                # verificar que la opcion introducida sea valida
                if opcion == 1:
                    tablerverificar = []
                    for i in range(9):
                        tablerverificar.append([])
                        for j in range(9):
                            tablerverificar[i].append(tablero[i][j])
                    imprimeTablero(tablero, name_tablero = "")
                    while not tableroCompleto(tablero):
                        numbers = input("Ingrese fila columna cifra: ")
                        numbers = numbers.split()
                        while verificardigitosvalidos(numbers) == False:
                            numbers = input("Ingrese fila columna cifra: ")
                            numbers = numbers.split()
                        x = int(numbers[0])
                        y = int(numbers[1])
                        d = int(numbers[2])
                        if verificarjugadavalida(tablero, x, y, d, tablerverificar) == True:
                            tablero[x-1][y-1] = d
                            imprimeTablero(tablero, name_tablero = "")
                    creditosfinales()
                    print(Fore.MAGENTA + "Felicidades, has ganado el juego" + Fore.RESET)
                    loop = False
                elif opcion == 2:
                    print("volviendo al menu principal")
                    loop = False
        elif opcionprincipal == 3:
            print("Selecione la dificultad del tablero")
            print(Fore.GREEN + "[1] Fácil" + Fore.RESET)
            print(Fore.YELLOW+ "[2] Medio" + Fore.RESET)
            print(Fore.RED + "[3] Difícil"+ Fore.RESET)
            opcion = (input("[4] Regresar: "))
            while opcion != "1" and opcion != "2" and opcion != "3" and opcion != "4":
                print(Fore.RED + "Opción incorrecta. Intente nuevamente." + Fore.RESET)
                opcion = (input("[4] Regresar: "))
            opcion = int(opcion)
            tablero = tablerodificultad(opcion)
            name = input(Fore.MAGENTA + "Nombre del jugador: " + Fore.RESET)
            name_tablero = input(Fore.LIGHTMAGENTA_EX +"Nombre del tablero: " + Fore.RESET)
            imprimeTablero(tablero, name_tablero)
            tablerverificar = []
            for i in range(9):
                tablerverificar.append([])
                for j in range(9):
                    tablerverificar[i].append(tablero[i][j])
            while not tableroCompleto(tablero):
                numbers = input("Ingrese fila columna cifra: ")
                numbers = numbers.split()
                while verificardigitosvalidos(numbers) == False:
                    numbers = input("Ingrese fila columna cifra: ")
                    numbers = numbers.split()
                x = int(numbers[0])
                y = int(numbers[1])
                d = int(numbers[2])
                if verificarjugadavalida(tablero, x, y, d, tablerverificar) == True:
                    tablero[x-1][y-1] = d
                    imprimeTablero(tablero, name_tablero)
            if final(tablero, name, name_tablero) == True:
                loop = False
        elif opcionprincipal == 4:
            print(Fore.RED + "Gracias por jugar."+ Fore.RESET)
            exit()


"""
Here we test a basic strategy that includes an indicator and FX rate movements.

We'll start with an ($100K) AUD denominated portfolio and buy 100 shares of SPY
only if the VIX < 26.

Also, buying in SPY will make us short USD.
Generate funding trades, to be executed the day after we buy SPY, so that
we aren't short USD.

For the sake of testing we'll focus on the dates 1st Sep -> 1st Oct.
Points to note:
-  We'll buy 100 shares of SPY @337.11 on Sep 14th VIX=25.85
-  Hold until Oct 1st when SPY=337.04, AUDUSD=0.7167
-  Because our portfolio is denominated in AUD we need to calculate AUD prices.
-  So buying SPY at 337.11 (Sep 14th price) / 0.729682 (fx 15th) = AUD 462
-  And holding to a value of 337.04 / 0.716651 = AUD 470.30
-  PNL will be $8.30 (= 470.30 - 462.00) for each of 100 shares purchased.
"""
from datetime import date
import pandas as pd
from pxtrade import Trade
from pxtrade.assets import reset, Stock, Cash, FxRate, Portfolio
from pxtrade.backtest import Backtest
from pxtrade.strategy import Strategy
from pxtrade.events.yahoo import load_yahoo_prices
from pxtrade.compliance import Compliance, UnitLimit
from pxtrade.history import History

def test_buy_spy_with_indicator():
    # create your stock and portfolio
    reset()
    spy = Stock("SPY", currency_code="USD")
    aud = Cash("AUD")
    usd = Cash("USD")
    audusd = FxRate("AUDUSD")
    portfolio = Portfolio("AUD")
    starting_value = 1e5  # start with $100K AUD
    portfolio.transfer(aud, starting_value)

    # impose a compliance rule so we are unable to
    # hold more than 100 shares.
    portfolio.compliance = Compliance().add_rule(UnitLimit(spy, 100))

    # define a strategy to buy 100 shares of SPY
    # if we are short USD then also fund this shortfall with AUD
    class BuySpyWithIndicator(Strategy):
        def show(self, trades):
            if len(trades) == 0:
                return
            print(backtest.datetime)
            print("^VIX: ", backtest.get_indicator("^VIX"))
            print("AUDUSD: ", audusd.rate)
            print("SPY: ", spy.price)
            for trade in trades:
                print(trade)
            print("-------")

        def generate_trades(self):
            trades = list()
            usd_holding = portfolio.get_holding_units("USD")
            if usd_holding < 0:
                trades.append(Trade(portfolio, usd, int(-usd_holding) + 1))

            if backtest.get_indicator("^VIX") >= 26:
                # don't buy any spy, just fund usd (if required)
                self.show(trades)
                return trades

            trades.append(Trade(portfolio, spy, 100))
            self.show(trades)
            return trades

    # create your backtest instance
    backtest = Backtest(BuySpyWithIndicator())
    history = History(
        portfolios=portfolio,
        backtest=backtest,
    )

    # load price events from yahoo for spy, audusd, vix
    start_date = date(2020, 9, 1)
    end_date = date(2020, 10, 1)
    load_yahoo_prices(
        [spy, audusd, "^VIX"],
        backtest,
        start_date=start_date,
        end_date=end_date,
    )

    # run the backtest and check pnl
    backtest.run()
    df = history.get()
    # print(portfolio)
    # print(audusd.rate)
    print(backtest.datetime)
    print(df)

    # Note that when running on windows the last FX rate we get from yahoo
    # is on the 30 Sep AUDUSD = 7.716651. However, running on linux we get
    # a price from 1 Oct of AUDUSD = 0.718288.
    # This looks to be an issue with the yahoo api, but it has implications
    # for our assertions around portfolio value.
    starting_aud_price = 462  # this has not changed
    ending_aud_price = 337.04 / audusd.rate
    expected_pnl = (ending_aud_price - starting_aud_price) * 100
    expected_value = starting_value + expected_pnl
    assert round(portfolio.value, -1) == round(expected_value, -1)

    start_date = pd.Timestamp(start_date)
    end_date = pd.Timestamp(end_date)
    assert int(df.at[start_date, "Portfolio"]) == int(starting_value)
    assert round(df.at[end_date, "Portfolio"], -1) == round(expected_value, -1)
    assert round(df.at[pd.Timestamp(date(2020, 9, 14)), "^VIX"], 2) == 25.85


"""
flaskr.utils.db
~~~~~~~~~~~~~~~
Utilities for database operations.
"""
import sqlite3
from typing import List, Optional
from datetime import datetime, timezone

from flask import g
from flask import current_app
from flaskr.utils.node import Node

def convert_timestamp(t):
    return datetime.fromisoformat(t.decode()).replace(tzinfo=timezone.utc).timestamp()

# Register the converter
sqlite3.register_converter("timestamp", convert_timestamp)

def get_db():
    """Connect to the application's configured database. The connection
    is unique for each request and will be reused if this is called
    again.
    """
    if "db" not in g:
        g.db = sqlite3.connect(
            current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

def close_db(e=None):
    """If this request connected to the database, close the
    connection.
    """
    db = g.pop("db", None)
    if db is not None:
        db.close()

def init_db(app):
    """Clear existing data and create new tables."""
    with app.app_context():
        db = get_db()
        with app.open_resource("schema.sql") as f:
            db.executescript(f.read().decode("utf8"))

def init_app(app):
    """Register database functions with the Flask app. This is called by
    the application factory.
    """
    app.teardown_appcontext(close_db)

# modified from https://github.com/matthiask/django-tree-queries/blob/8863c5237f32585cc5ddc21041231155cb806149/tree_queries/compiler.py#L120
CTE = """WITH RECURSIVE __tree(tree_depth,
    tree_path,
    tree_ordering,
    tree_pk) AS (
    SELECT
        0 tree_depth,
        printf("%s ", id) tree_path,
        printf(" %020s ", id) tree_ordering,
        T.id tree_pk
    FROM comment T
    WHERE T.parent_id IS NULL
    UNION ALL
    SELECT
        __tree.tree_depth + 1,
        __tree.tree_path || printf("%s ", T.id),
        __tree.tree_ordering || printf("%020s ", T.id),
        T.id
    FROM comment T
    JOIN __tree ON T.parent_id = __tree.tree_pk
)
SELECT
    comment.id,
    comment.parent_id,
    comment.post_id,
    comment.body, comment.created,
    comment.author_id, user.username as author_name,
-- __tree.tree_depth
   __tree.tree_path
FROM __tree
JOIN comment ON comment.id=__tree.tree_pk
JOIN user ON user.id=comment.author_id
WHERE comment.post_id=?
-- AND instr(__tree.tree_path, '3') !=0
ORDER BY __tree.tree_ordering;
"""

def get_all_comments(post_id: int) -> List[Node]:
    root_nodes = Node.build_from_cte_rows(get_db().execute(CTE, (post_id, )))
    return list(root_nodes)

def put_in_child(parent: dict, child: dict):
    if 'children' in parent:
        parent['children'].append(child)
    else:
        parent['children'] = [child]

def get_post(post_id, with_comments=True) -> Optional[dict]:
    """Get a post and its author by id.

    :param post_id: id of post to get
    :param with_comments: if return with comments
    :return: the post with author information
    """
    post = (
        get_db()
        .execute(
            "SELECT p.id, title, body, created, author_id, username"
            " FROM post p JOIN user u ON p.author_id = u.id"
            " WHERE p.id = ?",
            (post_id,),
        )
        .fetchone()
    )

    if post is None:
        return None

    if with_comments:
        comments = get_all_comments(post_id=post['id'])
        return dict(post) | dict(comments=comments)
    else:
        return dict(post)

def get_all_posts():
    db = get_db()
    rst = []
    for post in db.execute(
        "SELECT p.id, title, body, created, author_id, username as author_name"
        " FROM post p JOIN user u ON p.author_id = u.id"
        " ORDER BY p.created DESC, p.id DESC"
    ):
        rst.append(dict(post) | dict(comments=get_all_comments(post["id"])))
    return rst


# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

import time
from collections import defaultdict
from datetime import datetime

from odoo import api, models

class ManagementDashboard(models.Model):
    _name = 'management.dashboard'
    _description = "Project Management Dashboard"

    @api.model
    def get_task_chart_data(self):
        """
        Map the Stage Colour and Name to id

        Returns:
            dictionary -- stage_id as key and details as value
        """
        task_obj = self.env['project.task']
        task_rec = task_obj.search([])
        groups = defaultdict(list)

        for obj in task_rec:
            groups[obj.stage_id].append(obj)
        result = {}
        for rec in groups.items():
            result.update({
                rec[0].name: {
                    'count': len(rec[1]),
                    'color': rec[0].color,
                    'name': rec[0].name,
                }})
        return result

    @api.model
    def get_config_values(self):
        """
        To get the Colour value for dashboard.
        Using sudo env to bypass the access right.
        Returns:
            dictionary -- Dictionary of config colours.
        """
        result = self.env['res.config.settings'].sudo().get_values()
        return {
            'color_close_state': result.get('color_close_state', False),
            'color_control_state': result.get('color_control_state', False),
            'color_execute_state': result.get('color_execute_state', False),
            'color_init_state': result.get('color_init_state', False),
            'color_plan_state': result.get('color_plan_state', False),
            'card_header_color': result.get('card_header_color', False),
        }

    @api.model
    def get_color_code(self, project):
        # 0:Green, 1:Orange, 2:Red
        open_task = 0
        open_issue = 0
        spent_budget = 0
        pending_invoice = 0
        # ('date_start', '>=', self._context.get('start_date')),
        # ('date_start', '<=', self._context.get('end_date')),
        project_tasks = self.env['project.task'].search(
            [('project_id', '=', project['id']),
             ('stage_id.name',
                'not in',
                ("Done", "Completed", "Approval",
                 "Canceled", "Closure", "Release",
                 "Implementation")),
             ('date_end', '=', False)])

        today_date = datetime.strptime(
            time.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
        for task in project_tasks:
            if task.schedule_date:
                schedule_date = datetime.strptime(
                    str(task.schedule_date), '%Y-%m-%d %H:%M:%S').date()
                daysdiff = (schedule_date - today_date).days
                if daysdiff <= 1:
                    open_task = 2
                if daysdiff <= 7 and daysdiff > 1 and open_task != 2:
                    open_task = 1
                if daysdiff > 7 and open_task not in (2, 1):
                    open_task = 0

        project_issues = self.env['helpdesk.ticket'].with_context(
            view_project_issues=1).search([
                ('stage_id.closed', '!=', True),
                ('project_id.id', '=', project['id']),
                ('closed_date', '=', False)])
        for issue in project_issues or []:
            if ((int(int(issue.ticket_aging)) > 30 and issue.priority == '0') or
                    (int(issue.ticket_aging) > 10 and issue.priority == '1') or
                    (int(issue.ticket_aging) > 2 and issue.priority in
                        ('2', '3'))):
                open_issue = 2
            if ((int(issue.ticket_aging) > 10 and int(issue.ticket_aging) <= 30 and
                    issue.priority == '0') or
                    (int(issue.ticket_aging) > 2 and int(issue.ticket_aging) <= 10 and
                        issue.priority == '1') or
                    (int(issue.ticket_aging) > 0 and int(issue.ticket_aging) <= 2 and
                        issue.priority in ('2', '3')) and
                    open_issue != 2):
                open_issue = 1
            if ((int(issue.ticket_aging) <= 10 and issue.priority == '0') or
                    (int(issue.ticket_aging) <= 2 and issue.priority == '1') or
                    (int(issue.ticket_aging) == 0 and issue.priority in
                        ('2', '3')) and
                    open_issue not in (2, 1)):
                open_issue = 0

        budget = 0
        if project['spent_budget'] > 0 and project['actual_budget'] > 0:
            budget = ((project['spent_budget'] - project['actual_budget'])/project['actual_budget']) * 100

        if budget > 30:
            spent_budget = 2
        elif budget > 10 and budget <= 30:
            spent_budget = 1
        elif budget <= 10:
            spent_budget = 0

        invoices = self.env['timesheet.invoice'].search([
            ('project_id', '=', project['id']),
            ('state', 'in', ('draft', 'confirm', 'pre-approved'))])

        for inv in invoices or []:
            if int(inv.timesheet_inv_age) > 30:
                pending_invoice = 2
            elif int(inv.timesheet_inv_age) > 10 and int(inv.timesheet_inv_age) < 30 and pending_invoice != 2:
                pending_invoice = 1
            elif int(inv.timesheet_inv_age) < 10 and pending_invoice not in (2, 1):
                pending_invoice = 0
        return {
                'spent_budget': spent_budget,
                'pending_invoice': pending_invoice,
                'open_task': open_task,
                'open_issue': open_issue}

    @api.model
    def get_treeview_id(self, view):
        return self.env.ref(view).id,


import re
from collections import defaultdict
from string import Template

from odoo import _
from odoo.exceptions import MissingError

DEFAULT_REFERENCE_SEPARATOR = ""
PLACE_HOLDER_4_MISSING_VALUE = "/"

class ReferenceMask(Template):
    pattern = r"""\[(?:
                    (?P<escaped>\[) |
                    (?P<named>[^\]]+?)\] |
                    (?P<braced>[^\]]+?)\] |
                    (?P<invalid>)
                    )"""

def extract_token(s):
    pattern = re.compile(r"\[([^\]]+?)\]")
    return set(pattern.findall(s))

def sanitize_reference_mask(product, mask):
    tokens = extract_token(mask)
    attribute_names = set()
    for line in product.attribute_line_ids:
        attribute_names.add(line.attribute_id.name)
    if not tokens.issubset(attribute_names):
        raise MissingError(
            _("Found unrecognized attribute name in " '"Partcode Template"')
        )

def get_rendered_default_code(product, mask):
    product_attrs = defaultdict(str)
    reference_mask = ReferenceMask(mask)
    for value in product.product_template_attribute_value_ids:
        if value.attribute_id.code:
            product_attrs[value.attribute_id.name] += value.attribute_id.code
        if value.product_attribute_value_id.code:
            product_attrs[
                value.attribute_id.name
            ] += value.product_attribute_value_id.code
    all_attrs = extract_token(mask)
    missing_attrs = all_attrs - set(product_attrs.keys())
    missing = dict.fromkeys(missing_attrs, PLACE_HOLDER_4_MISSING_VALUE)
    product_attrs.update(missing)
    default_code = reference_mask.safe_substitute(product_attrs)
    return default_code

def render_default_code(product, mask):
    sanitize_reference_mask(product, mask)
    product.default_code = get_rendered_default_code(product, mask)


# python 3 has different package names
try: from urlparse import urlparse
except ImportError: from urllib.parse import urlparse

from collections import defaultdict

def _new_collection():
    """ Collection data type is
            {path: {method: (ResponseClass,) }}
        So e.g. a POST request to http://venmo.com/feed is stored as
        {'/feed': {'POST': (ResponseClass,)}}

        the ResponseClass will have had the the constructor partially applied
        with the specified stubbed data so after finding it we finish
        instantiatiing with the request we received and return it.
        Why? So the request attribute on the response is the request that
        was made, not just the matching criteria in the stub
    """
    return defaultdict(lambda: defaultdict(lambda: ()))

class RequestCollection(object):

    _requests = _new_collection()

    @classmethod
    def add(cls, request, response):
        parsed = urlparse(request.url)
        cls._requests[parsed.path][request.method] = \
                cls._requests[parsed.path][request.method] + (response,)

    @classmethod
    def find(cls, request):
        parsed = urlparse(request.url)
        responses = cls._requests[parsed.path][request.method]
        if len(responses) > 0:
            head = responses[0]
            cls._requests[parsed.path][request.method] = \
                    cls._requests[parsed.path][request.method][1:] + (head,)
        else:
            head = None
        return head

    @classmethod
    def remove(cls, request):
        parsed = urlparse(request.url)
        del cls._requests[parsed.path][request.method]

    @classmethod
    def reset(cls):
        cls._requests = _new_collection()


from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_insertar(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(570, 518)
        self.verticalLayout = QtWidgets.QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")
        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setFlat(True)
        self.groupBox.setObjectName("groupBox")
        self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.groupBox)
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.frame_11 = QtWidgets.QFrame(self.groupBox)
        self.frame_11.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_11.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_11.setObjectName("frame_11")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.frame_11)
        self.horizontalLayout_5.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.verticalLayout_9.addWidget(self.frame_11)
        spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.verticalLayout_9.addItem(spacerItem)
        self.frame_12 = QtWidgets.QFrame(self.groupBox)
        self.frame_12.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_12.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_12.setObjectName("frame_12")
        self.verticalLayout_10 = QtWidgets.QVBoxLayout(self.frame_12)
        self.verticalLayout_10.setObjectName("verticalLayout_10")
        self.label_12 = QtWidgets.QLabel(self.frame_12)
        self.label_12.setFrameShadow(QtWidgets.QFrame.Plain)
        self.label_12.setAlignment(QtCore.Qt.AlignCenter)
        self.label_12.setObjectName("label_12")
        self.verticalLayout_10.addWidget(self.label_12)
        self.verticalLayout_9.addWidget(self.frame_12)
        self.frame_13 = QtWidgets.QFrame(self.groupBox)
        self.frame_13.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_13.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_13.setObjectName("frame_13")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.frame_13)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.frame_14 = QtWidgets.QFrame(self.frame_13)
        self.frame_14.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_14.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_14.setObjectName("frame_14")
        self.verticalLayout_11 = QtWidgets.QVBoxLayout(self.frame_14)
        self.verticalLayout_11.setObjectName("verticalLayout_11")
        self.label_13 = QtWidgets.QLabel(self.frame_14)
        self.label_13.setObjectName("label_13")
        self.verticalLayout_11.addWidget(self.label_13)
        self.label_14 = QtWidgets.QLabel(self.frame_14)
        self.label_14.setObjectName("label_14")
        self.verticalLayout_11.addWidget(self.label_14)
        self.label_15 = QtWidgets.QLabel(self.frame_14)
        self.label_15.setObjectName("label_15")
        self.verticalLayout_11.addWidget(self.label_15)
        self.horizontalLayout_6.addWidget(self.frame_14)
        self.frame_15 = QtWidgets.QFrame(self.frame_13)
        self.frame_15.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_15.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_15.setObjectName("frame_15")
        self.verticalLayout_12 = QtWidgets.QVBoxLayout(self.frame_15)
        self.verticalLayout_12.setObjectName("verticalLayout_12")
        self.text_act1 = QtWidgets.QLineEdit(self.frame_15)
        self.text_act1.setObjectName("text_act1")
        self.verticalLayout_12.addWidget(self.text_act1)
        self.text_act2 = QtWidgets.QLineEdit(self.frame_15)
        self.text_act2.setObjectName("text_act2")
        self.verticalLayout_12.addWidget(self.text_act2)
        self.text_act3 = QtWidgets.QLineEdit(self.frame_15)
        self.text_act3.setObjectName("text_act3")
        self.verticalLayout_12.addWidget(self.text_act3)
        self.horizontalLayout_6.addWidget(self.frame_15)
        self.frame_16 = QtWidgets.QFrame(self.frame_13)
        self.frame_16.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_16.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_16.setObjectName("frame_16")
        self.verticalLayout_13 = QtWidgets.QVBoxLayout(self.frame_16)
        self.verticalLayout_13.setObjectName("verticalLayout_13")
        self.label_16 = QtWidgets.QLabel(self.frame_16)
        self.label_16.setObjectName("label_16")
        self.verticalLayout_13.addWidget(self.label_16)
        self.label_17 = QtWidgets.QLabel(self.frame_16)
        self.label_17.setObjectName("label_17")
        self.verticalLayout_13.addWidget(self.label_17)
        self.label_18 = QtWidgets.QLabel(self.frame_16)
        self.label_18.setObjectName("label_18")
        self.verticalLayout_13.addWidget(self.label_18)
        self.horizontalLayout_6.addWidget(self.frame_16)
        self.frame_17 = QtWidgets.QFrame(self.frame_13)
        self.frame_17.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_17.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_17.setObjectName("frame_17")
        self.verticalLayout_14 = QtWidgets.QVBoxLayout(self.frame_17)
        self.verticalLayout_14.setObjectName("verticalLayout_14")
        self.text_act4 = QtWidgets.QLineEdit(self.frame_17)
        self.text_act4.setObjectName("text_act4")
        self.verticalLayout_14.addWidget(self.text_act4)
        self.text_act5 = QtWidgets.QLineEdit(self.frame_17)
        self.text_act5.setObjectName("text_act5")
        self.verticalLayout_14.addWidget(self.text_act5)
        self.text_act6 = QtWidgets.QLineEdit(self.frame_17)
        self.text_act6.setObjectName("text_act6")
        self.verticalLayout_14.addWidget(self.text_act6)
        self.horizontalLayout_6.addWidget(self.frame_17)
        self.verticalLayout_9.addWidget(self.frame_13)
        self.frame_18 = QtWidgets.QFrame(self.groupBox)
        self.frame_18.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_18.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_18.setObjectName("frame_18")
        self.verticalLayout_15 = QtWidgets.QVBoxLayout(self.frame_18)
        self.verticalLayout_15.setObjectName("verticalLayout_15")
        self.label_19 = QtWidgets.QLabel(self.frame_18)
        self.label_19.setAlignment(QtCore.Qt.AlignCenter)
        self.label_19.setObjectName("label_19")
        self.verticalLayout_15.addWidget(self.label_19)
        self.verticalLayout_9.addWidget(self.frame_18)
        self.frame_19 = QtWidgets.QFrame(self.groupBox)
        self.frame_19.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_19.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_19.setObjectName("frame_19")
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.frame_19)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.label_20 = QtWidgets.QLabel(self.frame_19)
        self.label_20.setObjectName("label_20")
        self.horizontalLayout_7.addWidget(self.label_20)
        self.text_estado = QtWidgets.QLineEdit(self.frame_19)
        self.text_estado.setObjectName("text_estado")
        self.horizontalLayout_7.addWidget(self.text_estado)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_7.addItem(spacerItem1)
        self.verticalLayout_9.addWidget(self.frame_19)
        self.verticalLayout.addWidget(self.groupBox)
        self.frame_10 = QtWidgets.QFrame(Form)
        self.frame_10.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_10.setFrameShadow(QtWidgets.QFrame.Plain)
        self.frame_10.setObjectName("frame_10")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.frame_10)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(spacerItem2)
        self.btn_guardar = QtWidgets.QPushButton(self.frame_10)
        self.btn_guardar.setObjectName("btn_guardar")
        self.horizontalLayout_4.addWidget(self.btn_guardar)
        spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(spacerItem3)
        self.verticalLayout.addWidget(self.frame_10)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Insetar datos"))
        self.groupBox.setTitle(_translate("Form", "Insertar datos de entrenamiento"))
        self.label_12.setText(_translate("Form", "Para cada actividad, introduce \"A\" si aprobo, \"R\" si reprobo o \"NP\" si no presento."))
        self.label_13.setText(_translate("Form", "Actividad 1:"))
        self.label_14.setText(_translate("Form", "Actividad 2:"))
        self.label_15.setText(_translate("Form", "Actividad 3:"))
        self.label_16.setText(_translate("Form", "Actividad 4:"))
        self.label_17.setText(_translate("Form", "Actividad 5:"))
        self.label_18.setText(_translate("Form", "Actividad 6:"))
        self.label_19.setText(_translate("Form", "Introduce \"SI\" o \"NO\""))
        self.label_20.setText(_translate("Form", "Aprobo: "))
        self.text_estado.setPlaceholderText(_translate("Form", "Ingrese \"SI\" o \"NO\""))
        self.btn_guardar.setText(_translate("Form", "Guardar datos"))


from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("shop", "0005_auto_20150527_1127"),
    ]

    operations = [
        migrations.AlterField(
            model_name="order",
            name="key",
            field=models.CharField(max_length=40, db_index=True),
        ),
    ]


from unittest import TestCase
import unittest
# from unittest.mock import patch, Mock
# import csv
# from flask import request, jsonify
import requests

# import sys
#
# sys.path.insert(0, '../../src')

class TestLoadDailyReports(TestCase):
    # def setUp(self):
    #     self.app = app.

    def test_load_data_success(self):
        f = open("tests/routes/01-01-2021.csv", "rb")
        file = f.read()
        url = 'https://covid-monitor-61.herokuapp.com/daily_reports/data'
        r = requests.post(url, data=file, headers={"Content-Type": "text/csv"})
        f.close()
        self.assertEqual(r.status_code, 200)

    def test_query_data_success(self):
        url = 'https://covid-monitor-61.herokuapp.com/daily_reports/cases'
        body = {"return_type": "json",
                "types": ["Confirmed", "Deaths", "Active"],
                "locations":
                    [
                        {"Country/Region": "Belgium"},
                        {"Country/Region": "Canada", "Province/State": "Ontario"},
                        {"Country/Region": "Australia",
                         "Province/State": "Queensland",
                         "Combined_Key": "Australian Capital Territory, Australia"}
                    ]
                }
        r = requests.post(url, json=body, headers={"Content-Type": "application/json"})
        print(r.json())
        self.assertEqual(r.status_code, 200)

if __name__ == '__main__':
    unittest.main()


from pyswarms.base.base_discrete import DiscreteSwarmBase
import numpy as np
from scipy.spatial import cKDTree

class PerezPSO(DiscreteSwarmBase):

    def assertions(self):
        """Assertion method to check various inputs.

        Raises
        ------
        KeyError
            When one of the required dictionary keys is missing.
        ValueError
            When the number of neighbors is not within the range
                :code:`[0, n_particles]`.
            When the p-value is not in the list of values :code:`[1,2]`.
        """
        super(PerezPSO, self).assertions()

        if not all(key in self.options for key in ('k', 'p')):
            raise KeyError('Missing either k or p in options')
        if not 0 <= self.k <= self.n_particles:
            raise ValueError('No. of neighbors must be between 0 and no. of'
                             'particles.')
        if self.p not in [1, 2]:
            raise ValueError('p-value should either be 1 (for L1/Minkowski)'
                             'or 2 (for L2/Euclidean).')

    def __init__(self, n_particles, dimensions, alpha, options, velocity_clamp=None):
        """Initializes the swarm.

        Attributes
        ----------
        n_particles : int
            number of particles in the swarm.
        dimensions : int
            number of dimensions in the space.
        velocity_clamp : tuple (default is :code:`None`)
            a tuple of size 2 where the first entry is the minimum velocity
            and the second entry is the maximum velocity. It
            sets the limits for velocity clamping.
        options : dict with keys :code:`{'c1', 'c2', 'k', 'p'}`
            a dictionary containing the parameters for the specific
            optimization technique
                * c1 : float
                    cognitive parameter
                * c2 : float
                    social parameter
                * w : float
                    inertia parameter
                * k : int
                    number of neighbors to be considered. Must be a
                    positive integer less than :code:`n_particles`
                * p: int {1,2}
                    the Minkowski p-norm to use. 1 is the
                    sum-of-absolute values (or L1 distance) while 2 is
                    the Euclidean (or L2) distance.
        """
        # Initialize logger
        # self.logger = logging.getLogger(__name__)

        binary = False
        # Assign k-neighbors and p-value as attributes
        self.k, self.p = options['k'], options['p']
        # Initialize parent class
        super(PerezPSO, self).__init__(n_particles, dimensions, binary,
                                        options, velocity_clamp)
        # Invoke assertions
        self.assertions()
        # Initialize the resettable attributes
        self.reset()
        # Set initial glo
        self.glo = np.full((1, self.dimensions), np.inf)
        self.glo_cost = np.inf
        self.y = np.full(self.n_particles, 0)
        self.alpha = alpha
        self.loc_pos = 0

    def optimize(self, objective_func, iters, print_step=1, verbose=1):
        """Optimizes the swarm for a number of iterations.

        Performs the optimization to evaluate the objective
        function :code:`f` for a number of iterations :code:`iter.`

        Parameters
        ----------
        objective_func : function
            objective function to be evaluated
        iters : int
            number of iterations
        print_step : int (the default is 1)
            amount of steps for printing into console.
        verbose : int  (the default is 1)
            verbosity setting.

        Returns
        -------
        tuple
            the local best cost and the local best position among the
            swarm.
        """
        for i in range(iters):
            # Compute cost for current position and personal best
            current_cost = objective_func(self.pos)

            # Obtain the indices of the best position for each
            # neighbour-space, and get the local best cost and
            # local best positions from it.
            nmin_idx = self._get_neighbors(current_cost)  # get index of loc for each neighborhood of the cur position
            self.best_cost = current_cost[nmin_idx]  # the loc optimum cost for each particle

            cost_abs = np.abs(current_cost)
            loc_min = cost_abs.min()
            if loc_min < np.abs(self.glo_cost):
                pos_min_index = np.where(cost_abs == loc_min)[0][0]  # index of pos min
                self.glo = self.pos[pos_min_index]
                self.glo_cost = current_cost[pos_min_index]
            del loc_min, cost_abs

            # Get the local min realative to each point
            self.loc_pos = self.pos[nmin_idx]
            self.y = self._get_y(self.loc_pos)

            # Perform position velocity update
            self._update_velocity()  # must be called first
            self._update_position()

            care = r"""
Iter: {}
glo: {}, {}
Cur_cost: {}
loc_pos: {}
nmin_idx: {}
y: {}
velocity: {}
position: {}
            """.format(i, self.glo, self.glo_cost, current_cost, self.loc_pos,
                       nmin_idx, self.y, self.velocity, self.pos)

            if i % print_step == 0:
                print(care + "\n\n")
                if all_eq(self.pos):
                    break

            if self.glo_cost == 0:
                break

        # Obtain the final best_cost and the final best_position
        # final_best_cost_arg = np.argmin(self.best_cost)
        # final_best_cost = np.min(self.best_cost)
        # final_best_pos = self.best_pos[final_best_cost_arg]
        return self.glo_cost, self.glo

    def _get_neighbors(self, pbest_cost):
        """Helper function to obtain the best position found in the
        neighborhood. This uses the cKDTree method from :code:`scipy`
        to obtain the nearest neighbours

        Parameters
        ----------
        pbest_cost : numpy.ndarray of size (n_particles, )
            the cost incurred at the historically best position. Will be used
            for mapping the obtained indices to its actual cost.

        Returns
        -------
        array of size (n_particles, ) dtype=int64
            indices containing the best particles for each particle's
            neighbour-space that have the lowest cost
        """
        # Use cKDTree to get the indices of the nearest neighbors
        tree = cKDTree(self.pos)
        _, idx = tree.query(self.pos, p=self.p, k=self.k)

        # Map the computed costs to the neighbour indices and take the
        # argmin. If k-neighbors is equal to 1, then the swarm acts
        # independently of each other.
        if self.k == 1:
            # The minimum index is itself, no mapping needed.
            best_neighbor = pbest_cost[idx][:, np.newaxis].argmin(axis=1)
        else:
            idx_min = pbest_cost[idx].argmin(axis=1)
            best_neighbor = idx[np.arange(len(idx)), idx_min]
        return best_neighbor

    def _update_velocity(self):
        """Updates the velocity matrix of the swarm.

        This method updates the attribute :code:`self.velocity` of
        the instantiated object. It is called by the
        :code:`self.optimize()` method.
        """
        # Define the hyperparameters from options dictionary
        c1, c2, w = self.options['c1'], self.options['c2'], self.options['w']

        # Compute for cognitive and social terms
        cognitive = (c1 * np.random.uniform(0, 1) * (-1 - self.y))
        social = (c2 * np.random.uniform(0, 1)
                  * (1 - self.y))
        temp_velocity = (w * self.velocity) + cognitive + social

        # Create a mask to clamp the velocities
        if self.velocity_clamp is not None:
            # Create a mask depending on the set boundaries
            min_velocity, max_velocity = self.velocity_clamp[0], \
                                         self.velocity_clamp[1]
            _b = np.logical_and(temp_velocity >= min_velocity,
                                temp_velocity <= max_velocity)
            # Use the mask to finally clamp the velocities
            self.velocity = np.where(~_b, self.velocity, temp_velocity)
        else:
            self.velocity = temp_velocity

    def _update_position(self):
        """Updates the position matrix of the swarm.

        This method updates the attribute :code:`self.pos` of
        the instantiated object. It is called by the
        :code:`self.optimize()` method.
        """
        del self.pos
        next_pos = np.random.randint(-2000, 2000, size=self.swarm_size)
        _decision = self.y + self.velocity
        # print("des: {}".format(_decision))
        # mext_pos = np.where(_decision > self.alpha, self.glo, next_pos)
        # next_pos = np.where(_decision < self.alpha, self.loc_pos, next_pos)
        for i in range(self.n_particles):
            if _decision[i] > self.alpha:
                next_pos[i] = self.glo
            elif _decision[i] < -self.alpha:
                next_pos[i] = self.loc_pos[i]
        self.pos = next_pos

    def _get_y(self, loc):
        _y = np.array([])
        for i in range(self.n_particles):
            if np.array_equal(self.glo, self.pos[i]):
                _y = np.concatenate((_y, [1]))
            elif np.array_equal(loc[i], self.pos[i]):
                _y = np.concatenate((_y, [-1]))
            else:
                _y = np.concatenate((_y, [0]))
        return _y

    def _sigmoid(self, x):
        """Helper sigmoid function.

        Inputs
        ------
        x : numpy.ndarray
            Input vector to compute the sigmoid from

        Returns
        -------
        numpy.ndarray
            Output sigmoid computation
        """
        return 1 / (1 + np.exp(x))

def all_eq(position):
    first = position[0]
    for x in position:
        if not np.array_equal(x, first):
            return False
    return True

if __name__ == "__main__":
    record_holder = np.fromstring("-1251  -555 -1024  1119   273 -1101  1728 -1835     3  1968  1375   139  -1051  -547 -1531   298")  # -16047022661760
    # print(record_holder)
    from Particle import majic_func as obj_func
    from pyswarms.utils.environments import PlotEnvironment
    file = open("best_record.txt", "a")
    for loop in range(10):
        test = PerezPSO(12345, 16, 0.3, {"k": 10, 'c1': 0.8, 'c2': 0.2, 'w': 0.75, 'p': 2})
        test.pos = np.random.randint(-2000, 2000, size=test.swarm_size)
        test.velocity = np.full(test.n_particles, 0)
        # test.pos[0] = record_holder

        # print(test.pos)
        proposed = test.optimize(obj_func, iters=200, print_step=50)
        file.write("{}: {}\n\n".format(proposed[0], proposed[1]))
    file.close()


from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse

def homepage(request):
    return HttpResponse("you're in the home page, goto polls.")

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', homepage),
    path('polls/', include('polls.urls')),
]


import os

import numpy as np
import matplotlib.pyplot as plt

import cv2
import open3d as o3d

def mkdirs(path):
    try:
        os.makedirs(path)
    except:
        pass

class Saver(object):

    def __init__(self, save_dir):
        self.idx = 0
        self.save_dir = os.path.join(save_dir, "results")
        if not os.path.exists(self.save_dir):
            mkdirs(self.save_dir)

    def save_as_point_cloud(self, depth, rgb, path, mask=None):
        h, w = depth.shape
        Theta = np.arange(h).reshape(h, 1) * np.pi / h + np.pi / h / 2
        Theta = np.repeat(Theta, w, axis=1)
        Phi = np.arange(w).reshape(1, w) * 2 * np.pi / w + np.pi / w - np.pi
        Phi = -np.repeat(Phi, h, axis=0)

        X = depth * np.sin(Theta) * np.sin(Phi)
        Y = depth * np.cos(Theta)
        Z = depth * np.sin(Theta) * np.cos(Phi)

        if mask is None:
            X = X.flatten()
            Y = Y.flatten()
            Z = Z.flatten()
            R = rgb[:, :, 0].flatten()
            G = rgb[:, :, 1].flatten()
            B = rgb[:, :, 2].flatten()
        else:
            X = X[mask]
            Y = Y[mask]
            Z = Z[mask]
            R = rgb[:, :, 0][mask]
            G = rgb[:, :, 1][mask]
            B = rgb[:, :, 2][mask]

        XYZ = np.stack([X, Y, Z], axis=1)
        RGB = np.stack([R, G, B], axis=1)

        pcd = o3d.geometry.PointCloud()
        pcd.points = o3d.utility.Vector3dVector(XYZ)
        pcd.colors = o3d.utility.Vector3dVector(RGB)
        o3d.io.write_point_cloud(path, pcd)

    def save_samples(self, rgbs, gt_depths, pred_depths, depth_masks=None):
        """
        Saves samples
        """
        rgbs = rgbs.cpu().numpy().transpose(0, 2, 3, 1)
        depth_preds = pred_depths.cpu().numpy()
        gt_depths = gt_depths.cpu().numpy()
        if depth_masks is None:
            depth_masks = gt_depths != 0
        else:
            depth_masks = depth_masks.cpu().numpy()

        for i in range(rgbs.shape[0]):
            self.idx = self.idx+1
            mkdirs(os.path.join(self.save_dir, '%04d'%(self.idx)))

            cmap = plt.get_cmap("rainbow_r")

            depth_pred = cmap(depth_preds[i][0].astype(np.float32)/10)
            depth_pred = np.delete(depth_pred, 3, 2)
            path = os.path.join(self.save_dir, '%04d' % (self.idx) ,'_depth_pred.jpg')
            cv2.imwrite(path, (depth_pred * 255).astype(np.uint8))

            depth_gt = cmap(gt_depths[i][0].astype(np.float32)/10)
            depth_gt = np.delete(depth_gt, 3, 2)
            depth_gt[..., 0][~depth_masks[i][0]] = 0
            depth_gt[..., 1][~depth_masks[i][0]] = 0
            depth_gt[..., 2][~depth_masks[i][0]] = 0
            path = os.path.join(self.save_dir, '%04d' % (self.idx), '_depth_gt.jpg')
            cv2.imwrite(path, (depth_gt * 255).astype(np.uint8))

            path = os.path.join(self.save_dir, '%04d'%(self.idx) , '_pc_pred.ply')
            self.save_as_point_cloud(depth_preds[i][0], rgbs[i], path)

            path = os.path.join(self.save_dir, '%04d'%(self.idx) , '_pc_gt.ply')
            self.save_as_point_cloud(gt_depths[i][0], rgbs[i], path, depth_masks[i][0])

            rgb = (rgbs[i] * 255).astype(np.uint8)
            path = os.path.join(self.save_dir, '%04d'%(self.idx) , '_rgb.jpg')
            cv2.imwrite(path, rgb[:,:,::-1])


from setuptools import find_packages, setup

with open("./README.md") as fp:
    description = fp.read()

setup(
    name="pyC8",
    version="1.1.1",
    description="Python SDK for Macrometa Global Data Mesh",
    long_description=description,
    long_description_content_type="text/markdown",
    author="Macrometa",
    author_email="product@macrometa.com",
    url="https://www.macrometa.com",
    packages=find_packages(exclude=["tests"]),
    include_package_data=True,
    install_requires=["requests==2.25.1", "six", "websocket-client==0.57.0"],
    tests_require=["pytest", "mock", "flake8"],
    classifiers=[
        "Intended Audience :: Developers",
        "Intended Audience :: End Users/Desktop",
        "Intended Audience :: Information Technology",
        "Operating System :: MacOS",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: POSIX",
        "Operating System :: Unix",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Topic :: Documentation :: Sphinx",
    ],
)


from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def home():
    return "TP Florian Marques"

@app.route('/means', methods=['GET'])
def meanOfList():
    list = request.args.getlist('int', type=int)

    if len(list) == 0:
        return "Given list is null"
    else:
        return "Mean of the list is : {}".format(sum(list)/len(list))


import torch
import torch.nn as nn

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

        self.reduce_dim_5 = nn.Conv2d(2048, 256, kernel_size=(1, 1), stride=1, padding=0)
        self.reduce_dim_4 = nn.Conv2d(1024, 256, kernel_size=(1, 1), stride=1, padding=0)
        self.reduce_dim_3 = nn.Conv2d(512, 256, kernel_size=(1, 1), stride=1, padding=0)
        self.reduce_dim_2 = nn.Conv2d(256, 256, kernel_size=(1, 1), stride=1, padding=0)

        self.double_conv_5 = self._make_dobule_conv(256, 128)
        self.double_conv_4 = self._make_dobule_conv(256, 128)
        self.double_conv_3 = self._make_dobule_conv(256, 128)
        self.double_conv_2 = self._make_dobule_conv(256, 128)

    def _up_add(self, x, y):
        (_, _, H, W) = y.size()
        x_up = nn.functional.upsample(x, size=(H, W), mode='nearest')

        return x_up + y

    def _make_dobule_conv(self, in_dims, out_dims):
        conv_layer = nn.Sequential(
            nn.Conv2d(in_dims, out_dims, kernel_size=(3, 3), stride=1, padding=1),
            nn.BatchNorm2d(out_dims),
            nn.ReLU(),
            nn.Conv2d(out_dims, out_dims, kernel_size=(3, 3), stride=1, padding=1),
            nn.BatchNorm2d(out_dims),
            nn.ReLU()
        )

        return conv_layer

    def forward(self, c2, c3, c4, c5):
        m5 = self.reduce_dim_5(c5)
        m4 = self._up_add(m5, self.reduce_dim_4(c4))
        m3 = self._up_add(m4, self.reduce_dim_3(c3))
        m2 = self._up_add(m3, self.reduce_dim_2(c2))

        m5 = self.double_conv_5(m5)
        m4 = self.double_conv_4(m4)
        m3 = self.double_conv_3(m3)
        m2 = self.double_conv_2(m2)

        return m5, m4, m3, m2


#-*- coding: utf-8 -*-

from django.shortcuts import render, redirect
from blog.models import Mypost, MainPage
from blog.forms import CreateForms
# Create your views here.

def index(request):
    all_posts = Mypost.objects.all()
    maintext = MainPage.objects.all()
    # print('all_posts_all')
    # print(all_posts)
    context = {'maintext': maintext}
    return render(request, 'index.html', context)

def BlogList(request):
    all_posts = Mypost.objects.all()
    # print('all_posts_all')
    # print(all_posts)
    context = {'all_posts': all_posts}
    return render(request, 'blogs_list.html', context)

def PostDitail(request, pk):
    post_ditail = Mypost.objects.all().filter(pk=pk)

    print('post_ditail')
    print(post_ditail[0])
    return render(request, 'blog_ditail.html', {'post_ditail': post_ditail[0]})

def CreatePost(request):
    if request.method == 'POST':
        form = CreateForms(request.POST, request.FILES)
        if form.is_valid():
            create_post = form.save(commit=False)
            create_post.author = request.user
            create_post.save()
            return redirect('blog:ditail', pk=create_post.pk)
    else:
        form = CreateForms

    return render(request, 'create.html', {'form': form})

def EditPost(request, pk):
    # edit_post1 = get_object_or_404(Mypost, pk=pk)

    edit_post = Mypost.objects.filter(pk=pk).get()
    if request.method == 'POST':
        form = CreateForms(request.POST, request.FILES, instance=edit_post)
        # print('form')
        # print(form)

        if form.is_valid():
            edit = form.save(commit=False)
            # edit.author = request.user
            # print('edit.author')
            # print(edit.author)
            edit.save()
            return redirect('blog:ditail', pk=edit.pk)
    else:
        form = CreateForms(instance=edit_post)

    return render(request, 'edit.html', {'form': form})

def DelPost(request, pk):
    del_post = Mypost.objects.get(pk=pk)
    if request.method == 'POST':
        form = CreateForms(request.POST, instance=del_post)
        if form.is_valid():
            del_post = form.save(commit=False)
            del_post.delete()
            return redirect('blog:blogs_list')
    else:
        form = CreateForms(instance=del_post)
    return render(request, 'delete.html', {'form': form})

# def PagePostApi(request):
#
#     if request.method == 'POST':
#         form = CreateForms(request.POST)
#         if form.is_valid():
#             create_post = form.save(commit=False)
#             create_post.author = request.user
#             create_post.save()
#             return redirect('blog:ditail', pk=create_post.pk)
#     else:
#         form = CreateForms
#     return render(request, 'index.html', {'form': form} )

def ApiBlogjs(request):
    return render(request, 'apiblogjs.html', )

def ApiCreateblogjs(request):
    return render(request, 'apicreateblogjs.html',)

def ApiDetailblogjs(request, pk):
    post_ditail = Mypost.objects.all().filter(pk=pk)
    return render(request, 'apidetailblogjs.html',{'post_ditail': post_ditail[0]})

def ApiEditblogjs(request, pk):
    post_ditail = Mypost.objects.all().filter(pk=pk)
    return render(request, 'apieditblogjs.html',{'post_ditail': post_ditail[0]})

###   ResctJS   #####
def AllPostsReact(request):
    return render(request, 'react_post/allreact.html', )

def CreatePostReact(request):
    return render(request, 'react_post/createpostreact.html',)

def DetailPostReact(request, pk):
    post_ditail = Mypost.objects.all().filter(pk=pk)
    return render(request, 'react_post/detailreact.html',{'post_ditail': post_ditail[0]})

def EditPostReact(request, pk):
    post_ditail = Mypost.objects.all().filter(pk=pk)
    return render(request, 'react_post/editpostreact.html',{'post_ditail': post_ditail[0]})


import multiprocessing
import time
import hashlib

memory = list(range(30_000_000))

def function(name):
    for i in range(10):
        print("Current:", name, i)
        time.sleep(1)

def slow_function(name):
    for i in range(10):
        print("Current:", name, i)
        for j in range(300_000):
            hashlib.md5(str(j).encode("utf-8")).hexdigest()

if __name__ == "__main__":
    for i in range(3):
        name = chr(97 + i)
        multiprocessing.Process(target=slow_function, args=(name, )).start()


from .atari import Atari
from .obj3d import Obj3D
from torch.utils.data import DataLoader
from object_detector import CLIPort_Dataset

__all__ = ['get_dataset', 'get_dataloader']

def get_dataset(cfg, mode):
    assert mode in ['train', 'val', 'test']
    return CLIPort_Dataset(cfg.dataset_roots.TABLE, mode)

def get_dataloader(cfg, mode):
    assert mode in ['train', 'val', 'test']

    batch_size = getattr(cfg, mode).batch_size
    shuffle = True if mode == 'train' else False
    num_workers = getattr(cfg, mode).num_workers

    dataset = get_dataset(cfg, mode)
    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)

    return dataloader


from icecream import ic
from stack import Stack
from datetime import datetime

def time_format():
    return f'{datetime.now().strftime("%m/%d/%Y, %I:%M:%S")}|> '

ic.configureOutput(prefix=time_format, includeContext=True)

def nextLargestElment(items):
    tempStack = Stack()
    returnStack = Stack()
    tempStack.push(items[0])
    print("Intial tempStack:", tempStack.getStack())
    print("-----------------------------------------")
    for current_item in items[1::]:
        print("current_item:", current_item)
        print("stack_top_item:", tempStack.peek())

        if tempStack.isEmpty() == False:
            stack_top_item = tempStack.pop()
            while stack_top_item < current_item:
                print(str(stack_top_item) + " -- " + str(current_item))
                returnStack.push(current_item)
                if tempStack.isEmpty():
                    break
                stack_top_item = tempStack.pop()
            if stack_top_item > current_item:
                tempStack.push(stack_top_item)
        tempStack.push(current_item)
        print("tempStack:", tempStack.getStack())
        print("-----------------------------------------")
    while tempStack.isEmpty() == False:
        element = tempStack.pop()
        returnStack.push(-1)
        next = -1
        print(str(element) + " -- " + str(next))
    return returnStack.getStack()

if __name__ == '__main__':
    # ic(nextLargestElment([int(item)
    #                       for item in input("Enter the list items : ").strip().split()]))

    ic(nextLargestElment([2, 6, 5, 4, 19]))