import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
from utility import *
from agent import *
from copy import deepcopy

class State():

    def __init__(self,x_, y_, theta_):

        if not (x_ is None or y_ is None or theta_ is None ):    #non ricordo perchè avevo messo questo

            self.x = x_
            self.y = y_
            self.theta = theta_

        else :

            self.x = 0
            self.y= 0
            self.theta= 0

    def __str__(self):
        return str(self.x)+","+str(self.y)+","+str(self.theta)

    def distance_form_state(self,other):

        distance = np.array([self.x-other.x,self.y-other.y])
        distance_err = distance@distance
        return distance_err

class Controller():

    def __init__(self, goal, start, R_=0.0325,L_=0.1,dT=0.1,v_=1,k_filter=None,only_noise=False,observation_noise=1,process_noise=0.1,arrive_distance=0.3,near_distance=7,check_ac=False,obstacle=None):

        self.R= R_

        self.L = L_,

        self.E= 0   #cumulative error

        self.old_e = 0  #previous error

        self.v = v_

        self.dt = dT

        self.arrive_distance = arrive_distance

        self.goal = goal

        self.current_position = start    ####current position is start

        self.route_x = []

        self.route_y = []

        self.route_theta = []

        self.observation_noise = observation_noise

        self.process_noise = process_noise

        self.predicted_position_x = 0

        self.predicted_position_y = 0

        self.predicted_position_theta = 0

        self.kalman_filter = k_filter

        self.only_noise = only_noise

        if k_filter is not None:   #I add noise to the estimated position that at this point is the start position

            self.estimated_position_x = self.current_position.x + np.random.normal(0,observation_noise)

            self.estimated_position_y = self.current_position.y + np.random.normal(0,self.observation_noise)

            self.estimated_position_theta = self.current_position.theta + np.random.normal(0,self.observation_noise/10)

        else:

            self.estimated_position_x = self.current_position.x

            self.estimated_position_y = self.current_position.y

            self.estimated_position_theta = self.current_position.theta

        self.F = np.eye(3)

        self.Q = np.eye(3)*process_noise**2
        self.Q[2,2]=(process_noise/10)**2

        self.R = np.eye(3)*observation_noise**2
        self.R[2,2]= (observation_noise/10)**2

        self.P = np.eye(3)*observation_noise
        self.P[2,2]= observation_noise/10

        #self.innovation_history = []

        self.check_ac = check_ac

        self.obstacle = obstacle

        self.near_distance = near_distance

        if self.check_ac:

            self.innovation_history = []

            self.covariance_inn_hisotry= []

    def reset_controller(self, goal, start, obstacle= None):

        self.goal = goal

        self.current_position = start

        self.obstacle = obstacle

        self.E = 0

        self.old_e = 0

        self.predicted_position_x = 0

        self.predicted_position_y = 0

        self.predicted_position_theta = 0

        self.route_x = []

        self.route_y = []

        self.route_theta = []

        if self.kalman_filter is not None:

            self.estimated_position_x = self.current_position.x + np.random.normal(0,self.observation_noise)

            self.estimated_position_y = self.current_position.y + np.random.normal(0,self.observation_noise)

            self.estimated_position_theta = self.current_position.theta +np.random.normal(0,self.observation_noise/10)

        else:

            self.estimated_position_x = self.current_position.x

            self.estimated_position_y = self.current_position.y

            self.estimated_position_theta = self.current_position.theta

    def iterate_with_gains(self, k, ki, kd, obstacle=False):

        if(obstacle):
            #if there is an obstacle the robot will move in the tangent of the circumference
            #centered in the obstacle and having radius the distance form the obstacle and the
            #position of the robot
            #there is some control next to ensure that the robot exits this circular motion
            dx = -(self.estimated_position_y-self.obstacle.y)

            dy = self.estimated_position_x -self.obstacle.x

        else :

            dx = self.goal.x -self.estimated_position_x

            dy = self.goal.y -self.estimated_position_y

        #In the case I have only noise and I'm not using the kalman filter,
        #I add the observation noise here, because in this case the estimated position is the real position
        #When I use the kalman filter I already add the observation noise in another step,
        #this is not when I do the observation, this is where I use the estimated position

        if self.only_noise:

            dx += np.random.normal(0,self.observation_noise)
            dy += np.random.normal(0,self.observation_noise)
          # is None:
        g_theta = np.arctan2(dy,dx)

        alpha = g_theta -self.estimated_position_theta

        if self.only_noise:
            alpha = g_theta -self.estimated_position_theta + np.random.normal(0,self.observation_noise/10)

        e = np.arctan2(np.sin(alpha), np.cos(alpha))

        e_p = e

        e_I = self.E + e

        e_D = e -self.old_e

        self.E = self.E + e

        self.old_e = e

        w = k*e_p + ki*e_I + kd*e_D

        return w

    def make_prediction(self, w):
        #prediction with the kalman filter using the estimated postion
        a = self.estimated_position_x +self.v*np.cos(self.estimated_position_theta)*self.dt
        b = self.estimated_position_y +self.v*np.sin(self.estimated_position_theta)*self.dt

        self.predicted_position_x = a
        self.predicted_position_y = b

        theta_dt = w

        self.predicted_position_theta = self.estimated_position_theta +theta_dt*self.dt

    def evaluate_matrices(self):

        self.F[0,2] = -self.v*np.sin(self.estimated_position_theta)*self.dt

        self.F[1,2]= self.v*np.cos(self.estimated_position_theta)*self.dt

        PP = deepcopy(self.P)

        self.P = np.matmul(np.matmul(self.F,PP), np.transpose(self.F)) + self.Q

    def simulation_step(self,w):

        x_dt = self.v*np.cos(self.current_position.theta)

        y_dt = self.v*np.sin(self.current_position.theta)

        theta_dt = w

       # self.current_position.theta = (self.fixAngle(
            #self.current_position.theta + self.fixAngle(theta_dt * self.dt))).squeeze(-1)

        self.current_position.theta = self.current_position.theta +theta_dt*self.dt
        self.current_position.x = self.current_position.x + x_dt * self.dt

        self.current_position.y = self.current_position.y + y_dt * self.dt

        if self.kalman_filter is None and not self.only_noise:

            self.estimated_position_x = self.current_position.x
            self.estimated_position_y = self.current_position.y
            self.estimated_position_theta = self.current_position.theta

        else:

            self.current_position.x += np.random.normal(0,self.process_noise)

            self.current_position.y += np.random.normal(0,self.process_noise)

            self.current_position.theta+= np.random.normal(0,self.process_noise/10)

        if self.only_noise:

            self.estimated_position_x = self.current_position.x
            self.estimated_position_y = self.current_position.y
            self.estimated_position_theta = self.current_position.theta

        return

    def correction(self):

        #here i do the correction and observe the model,
        #so here is when I add the observation noise in the case of kalman filter

        x = self.current_position.x +np.random.normal(0,self.observation_noise)

        y = self.current_position.y+np.random.normal(0,self.observation_noise)

        theta = self.current_position.theta+np.random.normal(0,self.observation_noise/10)

        observation = np.array([x,y,theta])

        innovation = observation - np.array([self.predicted_position_x,self.predicted_position_y,self.predicted_position_theta])

        innovation_covariance = self.R +self.P

        if self.check_ac:

            self.innovation_history.append(innovation)

            self.covariance_inn_hisotry.append(innovation_covariance)

        optimal_gain = np.matmul(self.P,np.linalg.inv(innovation_covariance))

        n_x = self.predicted_position_x

        n_y = self.predicted_position_y

        n_theta = self.predicted_position_theta

        new_estimation = np.array([n_x,n_y,n_theta])+ np.matmul(optimal_gain,innovation)

        PP = deepcopy(self.P)

        self.P = np.matmul((np.eye(3) - optimal_gain), PP)

        self.estimated_position_x = new_estimation[0]

        self.estimated_position_y = new_estimation[1]

        self.estimated_position_theta = new_estimation[2]

    def isArrived(self):
        #based on the real position
        current_state = np.array([self.current_position.x, self.current_position.y])
        goal_state = np.array([self.goal.x, self.goal.y])
        #goal_state = np.array([self.goal.x, self.goal.y])
        difference = current_state - goal_state

        distance_err = difference @ difference.T
        if distance_err < self.arrive_distance:
            #print("Total number of steps to reach goal : ", self.tot_steps)
            return True
        else:
            return False

    def nearObstacle(self):

        if self.obstacle is None:
            return False
        pos_x = self.estimated_position_x
        pos_y = self.estimated_position_y
        if(self.only_noise):
            pos_x += np.random.normal(0,self.observation_noise)
            pos_y += np.random.normal(0,self.observation_noise)

        #distance_target = np.array([self.estimatedx,self.current_position.y])
        pos = np.array([pos_x,pos_y])
        goal = np.array([self.goal.x,self.goal.y])
        #distance=np.array([pos_x-self.goal.x, pos_y-self.goal.y])
        distance = pos-goal
        distance_goal = distance@distance.T
        obstacle = np.array([self.obstacle.x,self.obstacle.y])
        #distance = ([pos_x-self.obstacle.x,pos_y -self.obstacle.y])
        distance = pos-obstacle
        distance_obstacle = distance@distance.T
        if distance_obstacle >=self.near_distance:
            return False
        if distance_obstacle < distance_goal:
            return True
        return False

    def crush_obstacle(self):
        #this is obviously based on the real positions
        if self.obstacle is None:
            return False

        current_state = np.array([self.current_position.x,self.current_position.y])
        obstacle_state = np.array([self.obstacle.x, self.obstacle.y])
        difference = current_state -obstacle_state
        distance = difference @ difference.T
        if distance<=self.arrive_distance:
            return True
        return False

    def relative_pos(self):
        #in order not to go around the obstacle forever in the main algorithm I use the relative position between the obstacle and the robot

        a = self.obstacle.x -self.estimated_position_x
        b = self.obstacle.y -self.estimated_position_y
        #when I have noise but not kalman filter I add observ noise here, because in that case in estimated position is saved the real one
        if self.only_noise:
            a += np.random.normal(0,self.observation_noise)
            b += np.random.normal(0,self.observation_noise)
        if a>0:
            a = 1
        else:
            a = 0

        if b>0:
            b=1
        else:
            b= 0
        return a,b

    def track_route(self):

        self.route_x.append(self.current_position.x)

        self.route_y.append(self.current_position.y)

        self.route_theta.append(self.current_position.theta)

    def give_route(self):
        dt = [self.dt*i for i in range(len(self.route_x))]
        return self.route_x, self.route_y, self.route_theta, dt

    def fixAngle(self, angle):

        return np.arctan2(np.sin(angle), np.cos(angle))

    def check_kalman_filter(self):

        return self.innovation_history, self.covariance_inn_hisotry


import random
from typing import Union, Tuple

import cv2
import librosa
import numpy as np
from albumentations.core.transforms_interface import BasicTransform

from config import AUDIO_LEN, FREQUENCY_DISCREDITING

class AudioTransform(BasicTransform):
    """Transform for Audio task"""

    @property
    def targets(self):
        return {"data": self.apply, "image": self.apply}

    def update_params(self, params, **kwargs):
        if hasattr(self, "interpolation"):
            params["interpolation"] = self.interpolation
        if hasattr(self, "fill_value"):
            params["fill_value"] = self.fill_value
        return params

class PadTranc(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, max_ms: int = AUDIO_LEN):
        """
        This class results in the total length according to the max_ms parameter.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param max_ms: output length of the audio signal.
        """
        super(PadTranc, self).__init__(always_apply, p)
        self.max_ms = max_ms

    def apply(self, data, **params):
        sig, sr = data
        sig_len = len(sig)
        max_len = sr // 1000 * self.max_ms

        if sig_len > max_len:
            pad_begin_len = random.randint(0, sig_len - max_len)
            return sig[pad_begin_len:pad_begin_len+max_len], sr

        elif sig_len < max_len:
            pad_begin_len = random.randint(0, max_len - sig_len)
            pad_end_len = max_len - sig_len - pad_begin_len
            pad_begin = np.random.uniform(-0.001, 0.001, pad_begin_len)
            pad_end = np.random.uniform(-0.001, 0.001, pad_end_len)
            sig = np.concatenate((pad_begin, sig, pad_end))
            return sig, sr
        else:
            return sig, sr

class Resample(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, new_sr: int = FREQUENCY_DISCREDITING):
        """
        Changing the sampling rate if it does not correspond to the desired one.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param new_sr: new frequency of discrediting.
        """
        super(Resample, self).__init__(always_apply, p)
        self.new_sr = new_sr

    def apply(self, data, **params):
        sig, sr = data
        if sr == self.new_sr:
            return sig, sr
        resig = librosa.resample(y=sig, orig_sr=sr, target_sr=self.new_sr)
        return resig, self.new_sr

class PitchShift(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, n_steps: Union[int, None] = None):
        """
        Change the voice.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param n_steps: a specific or random parameter for pitchShift
        """
        super(PitchShift, self).__init__(always_apply, p)
        self.n_steps = n_steps

    def apply(self, data, **params):
        if self.n_steps is None:
            self.n_steps = np.random.randint(-7, 7, dtype=int)
        wav, sr = data

        return librosa.effects.pitch_shift(wav, sr=sr, n_steps=self.n_steps), sr

class StretchAudio(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, rate: Union[float, None] = None):
        """
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param rate:
        """
        super(StretchAudio, self).__init__(always_apply, p)
        self.rate = rate

    def apply(self, data, **params):
        if self.rate is None:
            self.rate = np.random.uniform(0.8, 1.3)

        wav, sr = data
        wav = librosa.effects.time_stretch(wav, self.rate)
        return wav, sr

class FreqMask(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, F: int = 30, num_masks: int = 1,
                 replace_with_zero: bool = False):
        """
        Applying a mask to spectogram along the X axis.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param F:
        :param num_masks: number of generated masks.
        :param replace_with_zero: change the values in the mask to zero.
        """
        super(FreqMask, self).__init__(always_apply, p)
        self.F = F
        self.num_masks = num_masks
        self.replace_with_zero = replace_with_zero

    def apply(self, image, **params):
        cloned = image.copy()
        num_mel_channels = cloned.shape[0]

        for i in range(0, self.num_masks):
            f = random.randrange(0, self.F)
            f_zero = random.randrange(0, num_mel_channels - f)

            if f_zero == f_zero + f:
                return cloned

            mask_end = random.randrange(f_zero, f_zero + f)
            if self.replace_with_zero:
                cloned[f_zero:mask_end, :] = 0
            else:
                cloned[f_zero:mask_end, :] = cloned.mean()

        return cloned

class TimeMask(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, T: int = 40, num_masks: int = 1,
                 replace_with_zero: bool = False):
        """
        Applying a mask to spectogram along the Y axis.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param T:
        :param num_masks: number of generated masks.
        :param replace_with_zero: change the values in the mask to zero.
        """
        super(TimeMask, self).__init__(always_apply, p)
        self.T = T
        self.num_masks = num_masks
        self.replace_with_zero = replace_with_zero

    def apply(self, image, **params):
        cloned = image.copy()
        len_spectro = cloned.shape[1]

        for i in range(0, self.num_masks):
            t = random.randrange(0, self.T)
            t_zero = random.randrange(0, len_spectro - t)

            if t_zero == t_zero + t:
                return cloned

            mask_end = random.randrange(t_zero, t_zero + t)

            if self.replace_with_zero:
                cloned[:, t_zero:mask_end] = 0
            else:
                cloned[:, t_zero:mask_end] = cloned.mean()

        return cloned

class AddNoise(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5):
        """
        Adding noise ti the audio signal.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        """
        super(AddNoise, self).__init__(always_apply, p)

    def apply(self, data, **params):
        wav, sr = data
        data_wn = wav + 0.005 * np.random.randn(len(wav))
        return data_wn, sr

class PolarityInversion(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5):
        """
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        """
        super(PolarityInversion, self).__init__(always_apply, p)

    def apply(self, data, **params):
        wav, sr = data
        return -wav, sr

class SpeedTuning(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, speed_rate: Union[Tuple, None] = None):
        """
        Audio speed change, if none, then the value changes within (0.7, 1.3)
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param speed_rate:
        """
        super(SpeedTuning, self).__init__(always_apply, p)
        self.speed_rate = speed_rate

    def apply(self, data, **params):

        if self.speed_rate is None:
            self.speed_rate = np.random.uniform(0.7, 1.3)

        wav, sr = data
        audio_speed_tune = cv2.resize(wav, (1, int(len(wav) * self.speed_rate))).squeeze()

        return audio_speed_tune, sr

class Gain(AudioTransform):
    def __init__(self, min_gain_in_db: int = -12, max_gain_in_db: int = 12, always_apply: bool = False, p: float = 0.5):
        """
        Change the volume.
        :param min_gain_in_db:
        :param max_gain_in_db:
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        """
        super(Gain, self).__init__(always_apply, p)
        assert min_gain_in_db <= max_gain_in_db
        self.min_gain_in_db = min_gain_in_db
        self.max_gain_in_db = max_gain_in_db

    def apply(self, data, **args):
        wav, sr = data
        amplitude_ratio = 10**(random.uniform(self.min_gain_in_db, self.max_gain_in_db)/20)
        return wav * amplitude_ratio, sr

class OverlayAudio(AudioTransform):
    def __init__(self, always_apply: bool = False, p: float = 0.5, intensity_overlay: Tuple = (3, 7)):
        """
        Adding noise to audio.
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        :param intensity_overlay: intensity of noise volume.
        """
        super(OverlayAudio, self).__init__(always_apply, p)
        self.intensity_overlay = intensity_overlay

    def apply(self, data, **params):

        wav_speech, sr_speech = data[0][0], data[0][1]
        wav_noise, sr_noise = data[1][0], data[1][1]

        max_speech = np.max(wav_speech)
        max_noise = np.max(wav_noise)

        min_speech = np.min(wav_speech)
        min_noise = np.min(wav_noise)

        dif_max = max_noise / max_speech
        dif_min = min_noise / min_speech

        coof = ((abs(dif_max) + abs(dif_min)) / 2) * np.random.randint(self.intensity_overlay[0],
                                                                       self.intensity_overlay[1])

        waw = (wav_speech + (wav_noise / coof)) / 2
        sr = (sr_speech + sr_noise) / 2

        return waw, int(sr)

class MakeQuiter(AudioTransform):
    def __init__(self, always_apply=False, p=0.5, quiter: Union[Tuple, None] = None):
        """
        :param always_apply: always use or not.
        :param p: the probability of use is from 0 to 1.
        """
        super(MakeQuiter, self).__init__(always_apply, p)
        self.quiter = quiter

    def apply(self, data, **params):

        if self.quiter is None:
            self.quiter = np.random.randint(2, 12)

        wav_speech, sr_speech = data
        wav_speech = wav_speech / self.quiter

        return wav_speech, sr_speech


import resources_fin

from PyQt5 import QtCore, QtGui, QtWidgets
from buttons_handler import ButtonsHandler
from db_processor import Insert

class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
                MainWindow.setObjectName("MainWindow")
                MainWindow.resize(822, 600)
                MainWindow.setMinimumSize(QtCore.QSize(822, 600))
                MainWindow.setMaximumSize(QtCore.QSize(822, 600))
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap(":/icons_new/icons_new/analysis (1).svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                MainWindow.setWindowIcon(icon)
                MainWindow.setStyleSheet("*{\n"
        "    font-family: Bahnschrift;\n"
        "    color: white;\n"
        "    border: nine;\n"
        "}\n"
        "\n"
        "#info_frame{\n"
        "    background-color: rgb(27, 33, 37);\n"
        "    border-radius: 15px;\n"
        "}\n"
        "\n"
        "#stackedWidget{\n"
        "    border: 2px solid  black;\n"
        "    border-radius: 15px;\n"
        "}\n"
        "\n"
        "#frame{\n"
        "    border: 2px solid  black;\n"
        "    border-radius: 15px;\n"
        "}\n"
        "#frame_2{\n"
        "    border: 2px solid  black;\n"
        "    border-radius: 15px;\n"
        "}\n"
        "\n"
        "#menu_frame QPushButton{\n"
        "    background-color: rgb(27, 33, 37);\n"
        "    border-radius: 15px;\n"
        "}\n"
        "\n"
        "#analyse_frame_btns QPushButton{\n"
        "    background-color: rgb(27, 33, 37);\n"
        "    border-radius: 15px;\n"
        "}\n"
        "#analyse_frame_btns QPushButton::hover, #menu_frame QPushButton::hover{\n"
        "   background-color: black;\n"
        "}\n"
        "")
                MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
                self.centralwidget = QtWidgets.QWidget(MainWindow)
                self.centralwidget.setStyleSheet("")
                self.centralwidget.setObjectName("centralwidget")
                self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
                self.horizontalLayout.setObjectName("horizontalLayout")
                self.frame = QtWidgets.QFrame(self.centralwidget)
                self.frame.setEnabled(True)
                self.frame.setMaximumSize(QtCore.QSize(250, 16777215))
                self.frame.setMouseTracking(False)
                self.frame.setTabletTracking(False)
                self.frame.setStyleSheet("")
                self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame.setMidLineWidth(0)
                self.frame.setObjectName("frame")
                self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
                self.verticalLayout.setObjectName("verticalLayout")
                self.frame_3 = QtWidgets.QFrame(self.frame)
                self.frame_3.setStyleSheet("")
                self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame_3.setObjectName("frame_3")
                self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_3)
                self.horizontalLayout_2.setObjectName("horizontalLayout_2")
                self.label = QtWidgets.QLabel(self.frame_3)
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                self.label.setFont(font)
                self.label.setStyleSheet("")
                self.label.setText("")
                self.label.setPixmap(QtGui.QPixmap(":/images_fin/images_final/bpkey.png"))
                self.label.setScaledContents(False)
                self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
                self.label.setObjectName("label")
                self.horizontalLayout_2.addWidget(self.label)
                self.verticalLayout.addWidget(self.frame_3)
                self.menu_frame = QtWidgets.QFrame(self.frame)
                self.menu_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.menu_frame.setFrameShadow(QtWidgets.QFrame.Raised)
                self.menu_frame.setObjectName("menu_frame")
                self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.menu_frame)
                self.verticalLayout_2.setObjectName("verticalLayout_2")
                self.go_to_analyses_btn = QtWidgets.QPushButton(self.menu_frame)
                self.go_to_analyses_btn.setMinimumSize(QtCore.QSize(0, 40))
                self.go_to_analyses_btn.setMaximumSize(QtCore.QSize(16777215, 50))
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.go_to_analyses_btn.setFont(font)
                self.go_to_analyses_btn.setStyleSheet("")
                icon1 = QtGui.QIcon()
                icon1.addPixmap(QtGui.QPixmap(":/icons_fin/icons_final/analysis (1).svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                self.go_to_analyses_btn.setIcon(icon1)
                self.go_to_analyses_btn.setObjectName("go_to_analyses_btn")
                self.verticalLayout_2.addWidget(self.go_to_analyses_btn)
                self.go_to_library_btn = QtWidgets.QPushButton(self.menu_frame)
                self.go_to_library_btn.setMinimumSize(QtCore.QSize(0, 40))
                self.go_to_library_btn.setMaximumSize(QtCore.QSize(16777215, 50))
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.go_to_library_btn.setFont(font)
                icon2 = QtGui.QIcon()
                icon2.addPixmap(QtGui.QPixmap(":/icons_fin/icons_final/library-books.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                self.go_to_library_btn.setIcon(icon2)
                self.go_to_library_btn.setObjectName("go_to_library_btn")
                self.verticalLayout_2.addWidget(self.go_to_library_btn)
                self.verticalLayout.addWidget(self.menu_frame)
                self.size_grip_left_1 = QtWidgets.QFrame(self.frame)
                self.size_grip_left_1.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.size_grip_left_1.setFrameShadow(QtWidgets.QFrame.Raised)
                self.size_grip_left_1.setObjectName("size_grip_left_1")
                self.verticalLayout.addWidget(self.size_grip_left_1)
                self.size_grip_left_2 = QtWidgets.QFrame(self.frame)
                self.size_grip_left_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.size_grip_left_2.setFrameShadow(QtWidgets.QFrame.Raised)
                self.size_grip_left_2.setObjectName("size_grip_left_2")
                self.verticalLayout.addWidget(self.size_grip_left_2)
                self.horizontalLayout.addWidget(self.frame)
                self.frame_2 = QtWidgets.QFrame(self.centralwidget)
                self.frame_2.setMaximumSize(QtCore.QSize(800, 16777215))
                self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame_2.setObjectName("frame_2")
                self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_2)
                self.verticalLayout_3.setObjectName("verticalLayout_3")
                self.stackedWidget = QtWidgets.QStackedWidget(self.frame_2)
                self.stackedWidget.setObjectName("stackedWidget")
                self.analyse_page = QtWidgets.QWidget()
                self.analyse_page.setObjectName("analyse_page")
                self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.analyse_page)
                self.verticalLayout_6.setObjectName("verticalLayout_6")
                self.frame_7 = QtWidgets.QFrame(self.analyse_page)
                self.frame_7.setMinimumSize(QtCore.QSize(0, 50))
                self.frame_7.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame_7.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame_7.setObjectName("frame_7")
                self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.frame_7)
                self.verticalLayout_7.setObjectName("verticalLayout_7")
                self.analyse_label = QtWidgets.QLabel(self.frame_7)
                self.analyse_label.setText("")
                self.analyse_label.setPixmap(QtGui.QPixmap(":/images_fin/images_final/analyse.png"))
                self.analyse_label.setScaledContents(True)
                self.analyse_label.setObjectName("analyse_label")
                self.verticalLayout_7.addWidget(self.analyse_label)
                self.verticalLayout_6.addWidget(self.frame_7)
                self.analyse_frame = QtWidgets.QFrame(self.analyse_page)
                sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
                sizePolicy.setHorizontalStretch(0)
                sizePolicy.setVerticalStretch(0)
                sizePolicy.setHeightForWidth(self.analyse_frame.sizePolicy().hasHeightForWidth())
                self.analyse_frame.setSizePolicy(sizePolicy)
                self.analyse_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.analyse_frame.setFrameShadow(QtWidgets.QFrame.Raised)
                self.analyse_frame.setObjectName("analyse_frame")
                self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.analyse_frame)
                self.horizontalLayout_4.setObjectName("horizontalLayout_4")
                self.frame_9 = QtWidgets.QFrame(self.analyse_frame)
                self.frame_9.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame_9.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame_9.setObjectName("frame_9")
                self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_9)
                self.verticalLayout_8.setObjectName("verticalLayout_8")
                self.note_label_image = QtWidgets.QLabel(self.frame_9)
                self.note_label_image.setMinimumSize(QtCore.QSize(218, 218))
                self.note_label_image.setMaximumSize(QtCore.QSize(218, 218))
                self.note_label_image.setText("")
                self.note_label_image.setPixmap(QtGui.QPixmap(":/images_fin/images_final/note.png"))
                self.note_label_image.setScaledContents(True)
                self.note_label_image.setObjectName("note_label_image")
                self.verticalLayout_8.addWidget(self.note_label_image)
                self.horizontalLayout_4.addWidget(self.frame_9)
                self.info_frame = QtWidgets.QFrame(self.analyse_frame)
                self.info_frame.setMinimumSize(QtCore.QSize(218, 218))
                self.info_frame.setMaximumSize(QtCore.QSize(218, 218))
                self.info_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.info_frame.setFrameShadow(QtWidgets.QFrame.Raised)
                self.info_frame.setObjectName("info_frame")
                self.gridLayout = QtWidgets.QGridLayout(self.info_frame)
                self.gridLayout.setObjectName("gridLayout")
                self.key_label_image = QtWidgets.QLabel(self.info_frame)
                self.key_label_image.setMinimumSize(QtCore.QSize(0, 0))
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.key_label_image.setFont(font)
                self.key_label_image.setText("")
                self.key_label_image.setPixmap(QtGui.QPixmap(":/images_fin/images_final/key.png"))
                self.key_label_image.setScaledContents(True)
                self.key_label_image.setObjectName("key_label_image")
                self.gridLayout.addWidget(self.key_label_image, 2, 0, 1, 1)
                self.name_label_image = QtWidgets.QLabel(self.info_frame)
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.name_label_image.setFont(font)
                self.name_label_image.setText("")
                self.name_label_image.setPixmap(QtGui.QPixmap(":/images_fin/images_final/name.png"))
                self.name_label_image.setScaledContents(True)
                self.name_label_image.setObjectName("name_label_image")
                self.gridLayout.addWidget(self.name_label_image, 0, 0, 1, 1)
                self.bpm_label_image = QtWidgets.QLabel(self.info_frame)
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.bpm_label_image.setFont(font)
                self.bpm_label_image.setText("")
                self.bpm_label_image.setPixmap(QtGui.QPixmap(":/images_fin/images_final/bpm.png"))
                self.bpm_label_image.setScaledContents(True)
                self.bpm_label_image.setObjectName("bpm_label_image")
                self.gridLayout.addWidget(self.bpm_label_image, 1, 0, 1, 1)
                self.name_label = QtWidgets.QLabel(self.info_frame)
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.name_label.setFont(font)
                self.name_label.setAlignment(QtCore.Qt.AlignCenter)
                self.name_label.setObjectName("name_label")
                self.gridLayout.addWidget(self.name_label, 0, 1, 1, 1)
                self.bpm_label = QtWidgets.QLabel(self.info_frame)
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.bpm_label.setFont(font)
                self.bpm_label.setAlignment(QtCore.Qt.AlignCenter)
                self.bpm_label.setObjectName("bpm_label")
                self.gridLayout.addWidget(self.bpm_label, 1, 1, 1, 1)
                self.key_label = QtWidgets.QLabel(self.info_frame)
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.key_label.setFont(font)
                self.key_label.setAlignment(QtCore.Qt.AlignCenter)
                self.key_label.setObjectName("key_label")
                self.gridLayout.addWidget(self.key_label, 2, 1, 1, 1)
                self.horizontalLayout_4.addWidget(self.info_frame)
                self.verticalLayout_6.addWidget(self.analyse_frame)
                self.analyse_frame_btns = QtWidgets.QFrame(self.analyse_page)
                self.analyse_frame_btns.setMinimumSize(QtCore.QSize(0, 60))
                self.analyse_frame_btns.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.analyse_frame_btns.setFrameShadow(QtWidgets.QFrame.Raised)
                self.analyse_frame_btns.setObjectName("analyse_frame_btns")
                self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.analyse_frame_btns)
                self.horizontalLayout_3.setObjectName("horizontalLayout_3")
                self.open_file_btn = QtWidgets.QPushButton(self.analyse_frame_btns)
                self.open_file_btn.setMinimumSize(QtCore.QSize(0, 40))
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.open_file_btn.setFont(font)
                icon3 = QtGui.QIcon()
                icon3.addPixmap(QtGui.QPixmap(":/icons_fin/icons_final/upload-folder.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                self.open_file_btn.setIcon(icon3)
                self.open_file_btn.setObjectName("open_file_btn")
                self.horizontalLayout_3.addWidget(self.open_file_btn)
                self.analyse_btn = QtWidgets.QPushButton(self.analyse_frame_btns)
                self.analyse_btn.setEnabled(False)
                self.analyse_btn.setMinimumSize(QtCore.QSize(0, 40))
                self.analyse_btn.setStyleSheet("background-color: grey;")
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(16)
                self.analyse_btn.setFont(font)
                icon4 = QtGui.QIcon()
                icon4.addPixmap(QtGui.QPixmap(":/icons_fin/icons_final/setting.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                self.analyse_btn.setIcon(icon4)
                self.analyse_btn.setObjectName("analyse_btn")
                self.horizontalLayout_3.addWidget(self.analyse_btn)
                self.verticalLayout_6.addWidget(self.analyse_frame_btns)
                self.stackedWidget.addWidget(self.analyse_page)
                self.library_page = QtWidgets.QWidget()
                self.library_page.setObjectName("library_page")
                self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.library_page)
                self.verticalLayout_4.setObjectName("verticalLayout_4")
                self.frame_5 = QtWidgets.QFrame(self.library_page)
                self.frame_5.setMinimumSize(QtCore.QSize(0, 50))
                self.frame_5.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame_5.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame_5.setObjectName("frame_5")
                self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.frame_5)
                self.verticalLayout_5.setObjectName("verticalLayout_5")
                self.library_label = QtWidgets.QLabel(self.frame_5)
                self.library_label.setMinimumSize(QtCore.QSize(480, 53))
                font = QtGui.QFont()
                font.setFamily("Bahnschrift")
                font.setPointSize(22)
                self.library_label.setFont(font)
                self.library_label.setText("")
                self.library_label.setPixmap(QtGui.QPixmap(":/images_fin/images_final/library.png"))
                self.library_label.setScaledContents(True)
                self.library_label.setObjectName("library_label")
                self.verticalLayout_5.addWidget(self.library_label, 0, QtCore.Qt.AlignLeft)
                self.verticalLayout_4.addWidget(self.frame_5, 0, QtCore.Qt.AlignTop)
                self.frame_6 = QtWidgets.QFrame(self.library_page)
                sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
                sizePolicy.setHorizontalStretch(0)
                sizePolicy.setVerticalStretch(0)
                sizePolicy.setHeightForWidth(self.frame_6.sizePolicy().hasHeightForWidth())
                self.frame_6.setSizePolicy(sizePolicy)
                self.frame_6.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.frame_6.setFrameShadow(QtWidgets.QFrame.Raised)
                self.frame_6.setObjectName("frame_6")

                #scroll_area

                self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.frame_6)
                self.verticalLayout_9.setObjectName("verticalLayout_9")
                self.scrollArea = QtWidgets.QScrollArea(self.frame_6)
                self.scrollArea.setMinimumSize(QtCore.QSize(485, 300))
                self.scrollArea.setMaximumSize(QtCore.QSize(485, 300))
                self.scrollArea.setStyleSheet("border-radius: 15px;\n"
                                              "border: nine;")
                self.scrollArea.setWidgetResizable(True)
                self.scrollArea.setObjectName("scrollArea")
                self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()
                self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 485, 300))
                self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
                self.scrollArea.setWidget(self.scrollAreaWidgetContents_2)
                self.verticalLayout_9.addWidget(self.scrollArea)

                #end of scroll area

                self.verticalLayout_4.addWidget(self.frame_6)
                self.stackedWidget.addWidget(self.library_page)
                self.verticalLayout_3.addWidget(self.stackedWidget)
                self.size_grip_right_1 = QtWidgets.QFrame(self.frame_2)
                self.size_grip_right_1.setMinimumSize(QtCore.QSize(0, 135))
                self.size_grip_right_1.setFrameShape(QtWidgets.QFrame.StyledPanel)
                self.size_grip_right_1.setFrameShadow(QtWidgets.QFrame.Raised)
                self.size_grip_right_1.setObjectName("size_grip_right_1")
                self.verticalLayout_3.addWidget(self.size_grip_right_1)
                self.horizontalLayout.addWidget(self.frame_2)
                MainWindow.setCentralWidget(self.centralwidget)

                self.retranslateUi(MainWindow)
                self.stackedWidget.setCurrentIndex(0)
                QtCore.QMetaObject.connectSlotsByName(MainWindow)

        def retranslateUi(self, MainWindow):
                _translate = QtCore.QCoreApplication.translate
                MainWindow.setWindowTitle(_translate("BPKEY", "BPKEY"))
                self.go_to_analyses_btn.setText(_translate("MainWindow", "Analyze Audio"))
                self.go_to_library_btn.setText(_translate("MainWindow", "Your Library"))
                self.name_label.setText(_translate("MainWindow", "Unknown"))
                self.bpm_label.setText(_translate("MainWindow", "Unknown"))
                self.key_label.setText(_translate("MainWindow", "Unknown"))
                self.open_file_btn.setText(_translate("MainWindow", "Open Audio File"))
                self.analyse_btn.setText(_translate("MainWindow", "Analyze"))

        # btn connections
        def connections(self):
                btn_handler = ButtonsHandler(self.name_label, self.bpm_label, self.key_label, self.analyse_btn)
                self.open_file_btn.clicked.connect(lambda: btn_handler.open_file())
                self.analyse_btn.clicked.connect(lambda: btn_handler.analyze())
                self.go_to_analyses_btn.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(0))
                self.go_to_library_btn.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))
                self.go_to_library_btn.clicked.connect(lambda: Insert().insert(self.scrollArea))


import json
from pathlib import Path

from dotenv import dotenv_values

from aem_utils.aem_constants import DIR_CONFIG_OSGICONFIG_CONFIG, OSGI_CONFIG_EXTENSION
from aem_utils.aem_constants import JCR
from constants import DOT, LESS, UTF_8, XML_EXTENSION
from osgi_xml_to_json_converter import OsgiXmlToJsonConverter
from utils.py_utils_file import read_files_in_folder_filter_by_extension, read_file_to_list_of_string
from utils.py_utils_string import substring_before_last

def main():
    config = dotenv_values(".env")
    aem_source_code_base_path = config["aem_source_code_base_path"]

    path_to_osgiconfigs = Path(aem_source_code_base_path + DIR_CONFIG_OSGICONFIG_CONFIG)
    print(f"\nRead XML files from: {path_to_osgiconfigs}\n")

    xml_files_in_osgiconfig_folder = []
    read_files_in_folder_filter_by_extension(xml_files_in_osgiconfig_folder, path_to_osgiconfigs, XML_EXTENSION)
    for xml_file_name in xml_files_in_osgiconfig_folder:
        print(f"Converting file: {xml_file_name}")

        # create new object to store the key/values
        converter = OsgiXmlToJsonConverter()

        # processing file content
        file_content = read_file_to_list_of_string(xml_file_name)
        for line in file_content:
            if not line.lstrip().rstrip().startswith((LESS, JCR)):
                converter.add_line(line.lstrip().rstrip())

        # write json file
        json_file_name = substring_before_last(xml_file_name, DOT) + DOT + OSGI_CONFIG_EXTENSION
        print(f"Writing new file: {json_file_name}")
        with open(json_file_name, 'w', encoding=UTF_8) as f:
            json.dump(converter.get_json_object(), f, ensure_ascii=False, indent=4)

    exit(0)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 16:28:46 2018

@author: Daniel Becerra Pedraza

Exercise 3 of first homework from Scientific Computing with High Added Value
----------------------------------
Solve the following equation:

$
\dfrac{d \phi}{dt} + \dfrac{d}{dx} \left( \rho u \phi) = \dfrac{d}{dx} \left( \Gamma \dfrac{d T}{dx} \right)
$

with boundary conditions:

$
\phi(x,0) = 0\ para\ 0 \leq x \leq \infty
\phi(0,t) = 1\ para\ t > 0
\phi(L,t) = 0\ para\ t > 0,\ L \rightarrow \infty
$

And the following values:

$
u = 1,
\rho = 1.0,
\Delta t = 0.002,
t_max = 1.0,
\Gamma = 0.001,
N = 50 y N = 350,
L = 2.5
$
___________________________________________________________

 |<-------------- 2.5 m ------------->|
           --- u = 1 m/S --->
 A                                    B
 |====================================|
\phi_A = 1                          \phi_B = 0
___________________________________________________________
Figure 5.2

Analytical solution:

\phi(x,t) = 0.5 \left[erfc\left(\frac{x-ut}{2 \sqrt{\Gamma t}}\right) + exp\left(\frac{ux}{D}\right)erfc\left(\frac{x+ut}{2 \sqrt{\Gamma t}}\right)\right]
"""

import FiniteVolumeMethod as fvm
import numpy as np
import scipy as sp
import viscoflow as vfl

def analyticSol(x, u, t, Gamma):
 	sol = 0.5 * (sp.special.erfc((x - u * t)/(2 * np.sqrt(Gamma * t))) + np.exp(u * x) * np.exp(-Gamma) * sp.special.erfc((x + u * t)/(2 * np.sqrt(Gamma * t))))
 	return sol

longitud = 2.5 # metros
PhiA = 1
PhiB = 0.0001
gamma  = 0.001 # Gamma
rho = 1.0 #Kg/m^3
u = 1.0 #m/s
Ti = 0.0
Tf = 1.0
dt = 0.002
N  = 350 # Número de nodos
Esquema = "QUICK" #CD, UpW, UpW2 y QUICK, si no se especifica se usará diferencias centradas.
#
# Creamos la malla y obtenemos datos importantes
#
malla = fvm.Mesh(nodes = N, length = longitud)
nx    = malla.nodes()     # Número de nodos
nvx   = malla.volumes()   # Número de volúmenes
dx = malla.delta()     # Tamaño de los volúmenes
x = malla.createMesh()
#
# Imprimimos los datos del problema (nicely)
#
fvm.printData(Longitud = longitud,
              Propiedad_A = PhiA,
              Propiedad_B = PhiB,
              Conductividad = gamma,
              Nodos = nx,
              Volúmenes = nvx,
              Delta = dx)

#
# Se construye el arreglo donde se guardará la solución
#
Phi = np.zeros(nvx) # El arreglo contiene ceros
Phi[0]  = PhiA        # Condición de frontera izquierda
Phi[-1] = PhiB        # Condición de frontera derecha

#
#  Creamos los coeficientes de FVM
#
coef = fvm.Coefficients()
coef.alloc(nvx)

df1 = fvm.Diffusion1D(nvx, Gamma = gamma, dx = dx)

adv1 = fvm.Advection1D(nvx, rho = rho, dx = dx)
adv1.setU(u)

D = gamma/dx

tem = fvm.Temporal1D(nvx, rho = rho, dx = dx, dt = dt)

# Calculamos la solución analítica
#
Phiaf = analyticSol(x, u, Tf-Ti, gamma)
vfl.grafica(x,Phiaf,kind='-',label='solución analítica')

for i in range(1,int((Tf-Ti)/dt)+1):
#
# Iniciamos con coeficientes cero
#
    print('Time step = {}'.format(i * dt), sep = '\t')
    coef.cleanCoefficients()
#
#  Calculamos los coeficientes de FVM de la Difusión
#
    df1.calcCoef()
#
#  Calculamos los coeficientes de FVM de la Advección
#
    adv1.setU(u)
    if Esquema == "UpW":
        adv1.calcCoef('UpW')
    elif Esquema == "UpW2":
        adv1.calcCoef('UpW2', PhiA, PhiB)
    elif Esquema == "QUICK":
        adv1.calcCoef('QUICK', PhiA, PhiB, D)
    else:
        adv1.calcCoef()
#
#  Calculamos los coeficientes de FVM de la parte temporal
#
    tem.calcCoef(Phi)

#
# Se aplican las condiciones de frontera dependiendo del esquema a usar
#
    if Esquema != "UpW2" and Esquema != "QUICK":
        coef.bcDirichlet('LEFT_WALL', PhiA)   # Se actualizan los coeficientes
        coef.bcDirichlet('RIGHT_WALL', PhiB) # de acuerdo a las cond. de frontera

#
# Se construye el sistema lineal de ecuaciones a partir de los coef. de FVM
#
    Su = coef.Su()  # Vector del lado derecho
    A = fvm.Matrix(malla.volumes())  # Matriz del sistema
    A.build(coef) # Construcción de la matriz en la memoria
#
# Se resuelve el sistema usando un algoritmo del módulo linalg
#
    Phi[1:-1] = np.linalg.solve(A.mat(),Su[1:-1])

#
# Usamos Viscoflow para graficar
# VISCOFLOW : Visualization of Complex Flows
#
    if (i % 100 == 0):
        etiqueta = 'Step = {}'.format(i*dt)
        vfl.grafica(x,Phi,title='Solución de $\partial phi /\partial t + \partial ( rho*u*phi)/\partial x = \partial ( Gamma (\partial T /\partial x ))/\partial x$ con FVM', label=etiqueta)

vfl.show('Problema6-ADT_' + Esquema + '_' + str(N) + 'nodos.png')


from __future__ import absolute_import, unicode_literals, print_function

import os
import sys
import shutil
import webbrowser

from . import Collection, task
from .. import config
from ..util import notify, which, add_dir2pypath

@task(default=True, help={
    'coverage': "Open coverage report in browser tab",
    'opts': "Extra flags for test runner",
})
def pytest(ctx, coverage=False, opts=''):
    """Perform standard unittests."""
    cfg = config.load()
    setup_cfg = cfg.rootjoin('setup.cfg')
    add_dir2pypath(cfg.project_root)

    try:
        console = sys.stdin.isatty()
    except AttributeError:
        console = False

    try:
        pytest_cmd = which.which("py.test").replace(cfg.project_root + os.sep, '')
    except which.WhichError:
        pytest_cmd = None

    if pytest_cmd:
        cmd = [pytest_cmd,
            '-c', setup_cfg,
            '--color=yes' if console else '',
        ]

        try:
            import pytest_cov as _
        except ImportError:
            pass
        else:
            for name in cfg.project.get('packages', []) + cfg.project.get('py_modules', []):
                if '.' not in name:
                    cmd.extend(['--cov', name,])
            for dirname in ('.', 'project.d'):
                if os.path.exists(cfg.rootjoin(dirname, 'coverage.cfg')):
                    cmd.extend(['--cov-config', cfg.rootjoin(dirname, 'coverage.cfg'),])
                    break
            cmd.extend(['--cov-report=term', '--cov-report=html', '--cov-report=xml',])

        if opts:
            cmd.append(opts)
        cmd.append(cfg.testdir)
        ctx.run(' '.join(cmd))
    else:
        ctx.run('python setup.py test' + (' ' + opts if opts else ''))

    if coverage:
        # TODO: Read from "coverage.cfg [html] directory"
        cov_html = os.path.join("build/coverage_html_report", "index.html")
        if os.path.exists(cov_html):
            webbrowser.open_new_tab(cov_html)
        else:
            notify.warning('No coverage report found at "{}"!'.format(cov_html))

#_PROJECT_ROOT = config.get_project_root()
# Keep 'tox' tasks?
#if _PROJECT_ROOT and not os.path.exists(os.path.join(_PROJECT_ROOT, 'tox.ini')):
#    del tox

@task(help={
    'verbose': "Make 'tox' more talkative",
    'clean': "Remove '.tox' first",
    'env-list': "Override list of environments to use (e.g. 'py27,py34')",
    'opts': "Extra flags for tox",
})
def tox(ctx, verbose=False, clean=False, env_list='', opts=''):
    """Perform multi-environment tests."""
    cfg = config.load()
    add_dir2pypath(cfg.project_root)
    snakepits = ctx.rituals.snakepits.split(os.pathsep)
    cmd = []

    snakepits = [i for i in snakepits if os.path.isdir(i)]
    if snakepits:
        cmd += ['PATH="{}:$PATH"'.format(os.pathsep.join(snakepits),)]

    if clean and os.path.exists(cfg.rootjoin('.tox')):
        shutil.rmtree(cfg.rootjoin('.tox'))

    cmd += ['tox']
    if verbose:
        cmd += ['-v']
    if env_list:
        cmd += ['-e', env_list]
    cmd += opts
    ctx.run(' '.join(cmd))

namespace = Collection.from_module(sys.modules[__name__], name='test', config={'rituals': dict(
    #test = dict(
    #),
    snakepits = '/opt/pyenv/bin:/opt/pyrun/bin',
)})


from pydantic import BaseModel

class URL_encoder(BaseModel):
    url: str = 'https://www.example_url.com/'

class URL_decoder(BaseModel):
    url: str = 'http://short.est/MQ'

class ShowURL(BaseModel):
    original_url: str
    shortened_url: str
    class Config:
        orm_mode = True


from Models import Player

class SaveGame:
    def __init__(self, name: str,
                 current_word: str,
                 current_word_length: int,
                 progress_word_list: list,
                 current_word_list: list,
                 current_rem_letters: int,
                 total_tries: int,
                 current_tries: int):
        self.player_name = name
        self.current_word = current_word
        self.current_word_length = str(current_word_length)
        self.progress_word_list = progress_word_list
        self.current_word_list = current_word_list
        self.current_rem_letters = str(current_rem_letters)
        self.total_tries = str(total_tries)
        self.current_tries = str(current_tries)

    def raw_data(self) -> str:
        """
        Returns a string for saving a game state in DB
        :return:
        """
        return self.player_name + "," + self.current_word + "," + self.current_word_length + "," + ".".join(
            self.progress_word_list) + "," + ".".join(
            self.current_word_list) + "," + self.current_rem_letters + "," + self.total_tries + "," + self.current_tries

    def __str__(self):
        return "{}   {}   {}".format(".".join(self.progress_word_list), self.current_tries, self.total_tries)


# !/usr/bin/env python

from canari.xmltools.oxml import MaltegoElement, fields as fields_

from datetime import datetime, date, timedelta
from numbers import Number
import re

__author__ = 'Nadeem Douba'
__copyright__ = 'Copyright 2012, Canari Project'
__credits__ = []

__license__ = 'GPL'
__version__ = '0.5'
__maintainer__ = 'Nadeem Douba'
__email__ = 'ndouba@gmail.com'
__status__ = 'Development'

__all__ = [
    'MaltegoException',
    'MaltegoTransformExceptionMessage',
    'MaltegoTransformRequestMessage',
    'Label',
    'MatchingRule',
    'Field',
    'UIMessageType',
    'UIMessage',
    'MaltegoTransformResponseMessage',
    'MaltegoMessage',
    'StringEntityField',
    'EnumEntityField',
    'IntegerEntityField',
    'BooleanEntityField',
    'FloatEntityField',
    'LongEntityField',
    'DateTimeEntityField',
    'DateEntityField',
    'timespan',
    'TimeSpanEntityField',
    'RegexEntityField',
    'ColorEntityField',
    'EntityFieldType',
    'EntityField',
    'EntityLinkField',
    'Entity',
]

class MaltegoException(MaltegoElement, Exception):
    class meta:
        tagname = 'Exception'

    def __init__(self, value):
        super(MaltegoException, self).__init__(value=value),

    value = fields_.String(tagname='.')

class MaltegoTransformExceptionMessage(MaltegoElement):
    exceptions = fields_.List(MaltegoException, tagname='Exceptions')

    def appendelement(self, exception):
        if isinstance(exception, MaltegoException):
            self.exceptions.append(exception)
        else:
            self.exceptions.append(MaltegoException(str(exception)))

class Limits(MaltegoElement):
    soft = fields_.Integer(attrname='SoftLimit', default=500)
    hard = fields_.Integer(attrname='HardLimit', default=10000)

class Label(MaltegoElement):
    def __init__(self, name=None, value=None, **kwargs):
        super(Label, self).__init__(name=name, value=value, **kwargs)

    value = fields_.CDATA(tagname='.')
    type = fields_.String(attrname='Type', default='text/text')
    name = fields_.String(attrname='Name')

class MatchingRule(object):
    Strict = "strict"
    Loose = "loose"

class Field(MaltegoElement):
    def __init__(self, name=None, value=None, **kwargs):
        super(Field, self).__init__(name=name, value=value, **kwargs)

    name = fields_.String(attrname='Name')
    displayname = fields_.String(attrname='DisplayName', required=False)
    matchingrule = fields_.String(attrname='MatchingRule', default=MatchingRule.Strict, required=False)
    value = fields_.String(tagname='.')

class _Entity(MaltegoElement):
    class meta:
        tagname = 'Entity'

    type = fields_.String(attrname='Type')
    fields = fields_.Dict(Field, key='name', tagname='AdditionalFields', required=False)
    labels = fields_.Dict(Label, key='name', tagname='DisplayInformation', required=False)
    value = fields_.String(tagname='Value')
    weight = fields_.Integer(tagname='Weight', default=1)
    iconurl = fields_.String(tagname='IconURL', required=False)

    def appendelement(self, other):
        if isinstance(other, Field):
            self.fields[other.name] = other
        elif isinstance(other, Label):
            self.labels[other.name] = other

    def removeelement(self, other):
        if isinstance(other, Field):
            self.fields.pop(other.name)
        elif isinstance(other, Label):
            self.labels.pop(other.name)

class UIMessageType:
    Fatal = "FatalError"
    Partial = "PartialError"
    Inform = "Inform"
    Debug = "Debug"

class UIMessage(MaltegoElement):
    def __init__(self, value=None, **kwargs):
        super(UIMessage, self).__init__(value=value, **kwargs)

    type = fields_.String(attrname='MessageType', default=UIMessageType.Inform)
    value = fields_.String(tagname='.')

class MaltegoTransformResponseMessage(MaltegoElement):
    uimessages = fields_.List(UIMessage, tagname='UIMessages')
    entities = fields_.List(_Entity, tagname='Entities')

    def appendelement(self, other):
        if isinstance(other, Entity):
            self.entities.append(other.__entity__)
        elif isinstance(other, _Entity):
            self.entities.append(other)
        elif isinstance(other, UIMessage):
            self.uimessages.append(other)

    def removeelement(self, other):
        if isinstance(other, Entity):
            self.entities.remove(other.__entity__)
        elif isinstance(other, _Entity):
            self.entities.append(other)
        elif isinstance(other, UIMessage):
            self.uimessages.remove(other)

class StringEntityField(object):
    def __init__(self, name, displayname=None, decorator=None, matchingrule=MatchingRule.Strict, is_value=False,
                 **extras):
        self.decorator = decorator
        self.is_value = is_value
        self.name = name
        self.displayname = displayname
        self.matchingrule = matchingrule

    def __get__(self, obj, objtype):
        if self.is_value:
            return obj.value
        elif self.name in obj.fields:
            return obj.fields[self.name].value
        return None

    def __set__(self, obj, val):
        if self.is_value:
            obj.value = val
        elif not val and self.name in obj.fields:
            del obj.fields[self.name]
        else:
            if self.name not in obj.fields:
                obj.fields[self.name] = Field(
                    name=self.name,
                    value=val,
                    displayname=self.displayname,
                    matchingrule=self.matchingrule
                )
            else:
                obj.fields[self.name].value = val
        if callable(self.decorator):
            self.decorator(obj, val)

class EnumEntityField(StringEntityField):
    def __init__(self, name, displayname=None, choices=None, decorator=None, matchingrule=MatchingRule.Strict,
                 is_value=False, **extras):
        self.choices = [str(c) if not isinstance(c, basestring) else c for c in choices or []]
        super(EnumEntityField, self).__init__(name, displayname, decorator, matchingrule, is_value)

    def __set__(self, obj, val):
        val = str(val) if not isinstance(val, basestring) else val
        if val not in self.choices:
            raise ValueError('Expected one of %s (got %s instead)' % (self.choices, val))
        super(EnumEntityField, self).__set__(obj, val)

class IntegerEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        i = super(IntegerEntityField, self).__get__(obj, objtype)
        return int(i) if i is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, Number):
            raise TypeError('Expected an instance of int (got %s instance instead)' % type(val).__name__)
        super(IntegerEntityField, self).__set__(obj, val)

class BooleanEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        b = super(BooleanEntityField, self).__get__(obj, objtype)
        return b.startswith('t') or b == '1' if b is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, bool):
            raise TypeError('Expected an instance of bool (got %s instance instead)' % type(val).__name__)
        super(BooleanEntityField, self).__set__(obj, str(val).lower())

class FloatEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        f = super(FloatEntityField, self).__get__(obj, objtype)
        return float(f) if f is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, Number):
            raise TypeError('Expected an instance of float (got %s instance instead)' % type(val).__name__)
        super(FloatEntityField, self).__set__(obj, val)

class LongEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        l = super(LongEntityField, self).__get__(obj, objtype)
        return long(l) if l is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, Number):
            raise TypeError('Expected an instance of float (got %s instance instead)' % type(val).__name__)
        super(LongEntityField, self).__set__(obj, val)

class DateTimeEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        d = super(DateTimeEntityField, self).__get__(obj, objtype)
        return datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f') if d is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, datetime):
            raise TypeError('Expected an instance of datetime (got %s instance instead)' % type(val).__name__)
        super(DateTimeEntityField, self).__set__(obj, val)

class DateEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        d = super(DateEntityField, self).__get__(obj, objtype)
        return datetime.strptime(d, '%Y-%m-%d').date() if d is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, date):
            raise TypeError('Expected an instance of date (got %s instance instead)' % type(val).__name__)
        super(DateEntityField, self).__set__(obj, val)

class timespan(timedelta):
    matcher = re.compile('(\d+)d (\d+)h(\d+)m(\d+)\.(\d+)s')

    def __str__(self):
        return '%dd %dh%dm%d.%03ds' % (
            abs(self.days),
            int(self.seconds) // 3600,
            int(self.seconds) % 3600 // 60,
            int(self.seconds) % 60,
            int(self.microseconds)
        )

    @classmethod
    def fromstring(cls, ts):
        m = cls.matcher.match(ts)
        if m is None:
            raise ValueError('Time span must be in "%%dd %%Hh%%Mm%%S.%%fs" format')
        days, hours, minutes, seconds, useconds = [int(i) for i in m.groups()]
        return timespan(days, (hours * 3600) + (minutes * 60) + seconds, useconds)

class TimeSpanEntityField(StringEntityField):
    def __get__(self, obj, objtype):
        d = super(TimeSpanEntityField, self).__get__(obj, objtype)
        return timespan.fromstring(d) if d is not None else None

    def __set__(self, obj, val):
        if not isinstance(val, timespan) or not isinstance(val, timedelta):
            raise TypeError('Expected an instance of timedelta (got %s instance instead)' % type(val).__name__)
        if val.__class__ is timedelta:
            val = timespan(val.days, val.seconds, val.microseconds)
        super(TimeSpanEntityField, self).__set__(obj, val)

class RegexEntityField(StringEntityField):
    def __init__(self, name, displayname=None, pattern='.*', decorator=None, matchingrule=MatchingRule.Strict,
                 is_value=False, **extras):
        super(RegexEntityField, self).__init__(name, displayname, decorator, matchingrule, is_value, **extras)
        self.pattern = re.compile(pattern)

    def __set__(self, obj, val):
        if not isinstance(val, basestring):
            val = str(val)
        if not self.pattern.match(val):
            raise ValueError('Failed match for %s, expected pattern %s instead.' % (
                repr(val), repr(self.pattern.pattern))
            )
        super(RegexEntityField, self).__set__(obj, val)

class ColorEntityField(RegexEntityField):
    def __init__(self, name, displayname=None, decorator=None, matchingrule=MatchingRule.Strict, is_value=False,
                 **extras):
        super(ColorEntityField, self).__init__(name, displayname, '^#[0-9a-fA-F]{6}$', decorator, matchingrule,
                                               is_value, **extras)

class EntityFieldType:
    String = StringEntityField
    Integer = IntegerEntityField
    Long = LongEntityField
    Float = FloatEntityField
    Bool = BooleanEntityField
    Enum = EnumEntityField
    Date = DateEntityField
    DateTime = DateTimeEntityField
    TimeSpan = TimeSpanEntityField
    Color = ColorEntityField

class EntityField(object):
    def __init__(self, link=False, **kwargs):
        self.name = kwargs.pop('name')
        if self.name is None:
            raise ValueError("Keyword argument 'name' is required.")
        self.property = kwargs.pop('propname', re.sub('[^\w]+', '_', self.name))
        if not link:
            self.displayname = kwargs.pop('displayname', self.name.title())
        else:
            self.displayname = kwargs.pop('displayname', None)
        self.type = kwargs.pop('type', EntityFieldType.String)
        self.required = kwargs.pop('required', False)
        self.matchingrule = kwargs.pop('matchingrule', MatchingRule.Strict)
        self.decorator = kwargs.pop('decorator', None)
        self.is_value = kwargs.pop('is_value', False)
        self.extras = kwargs

    def __call__(self, cls):
        setattr(
            cls,
            self.property,
            self.type(
                name=self.name,
                displayname=self.displayname,
                decorator=self.decorator,
                matchingrule=self.matchingrule,
                is_value=self.is_value,
                **self.extras
            )
        )
        cls._fields_to_properties_[self.name] = self.property
        return cls

class EntityLinkField(EntityField):
    def __init__(self, **kwargs):
        kwargs['name'] = 'link#%s' % kwargs.get('name')
        super(EntityLinkField, self).__init__(link=True, **kwargs)

class MetaEntityClass(type):
    registry = {}

    def __new__(cls, clsname, bases, attrs):
        if '_fields_to_properties_' not in attrs:
            attrs['_fields_to_properties_'] = {}
        if '_name_' not in attrs:
            attrs['_name_'] = clsname
        if '_v2type_' not in attrs:
            attrs['_v2type_'] = clsname
        new_cls = super(cls, MetaEntityClass).__new__(cls, clsname, bases, attrs)
        new_cls._type_ = '%s.%s' % (new_cls._namespace_, new_cls._name_)
        for base in bases:
            if '_fields_to_properties_' in base.__dict__:
                attrs['_fields_to_properties_'].update(base._fields_to_properties_)
        MetaEntityClass.registry[new_cls._type_] = new_cls
        MetaEntityClass.registry[new_cls._v2type_] = new_cls
        return new_cls

    @staticmethod
    def to_entity_type(entity_type_str):
        if entity_type_str in MetaEntityClass.registry:
            return MetaEntityClass.registry.get(entity_type_str)
        return MetaEntityClass.registry[None]

@EntityField(name='notes#', propname='notes', link=True, matchingrule=MatchingRule.Loose)
@EntityField(name='bookmark#', propname='bookmark', type=EntityFieldType.Integer, matchingrule=MatchingRule.Loose,
             link=True)
@EntityLinkField(name='maltego.link.label', propname='linklabel', matchingrule=MatchingRule.Loose)
@EntityLinkField(name='maltego.link.style', propname='linkstyle', matchingrule=MatchingRule.Loose,
                 type=EntityFieldType.Integer)
@EntityLinkField(name='maltego.link.show-label', propname='linkshowlabel', matchingrule=MatchingRule.Loose,
                 type=EntityFieldType.Enum, choices=[0, 1])
@EntityLinkField(name='maltego.link.color', propname='linkcolor', matchingrule=MatchingRule.Loose)
@EntityLinkField(name='maltego.link.thickness', propname='linkthickness', matchingrule=MatchingRule.Loose,
                 type=EntityFieldType.Integer)
class Entity(object):
    __metaclass__ = MetaEntityClass
    _namespace_ = 'maltego'
    _name_ = None
    _v2type_ = None
    _fields_to_properties_ = {}

    def __init__(self, value, **kwargs):
        if isinstance(value, _Entity):
            self._entity = value
            # for name, field in self._entity.fields.iteritems():
            #     if name not in self._fields_to_properties_:
            #         self._bind_field(field)
        else:
            self._entity = _Entity(
                type=kwargs.pop('type', self._type_),
                value=value,
                weight=kwargs.pop('weight', None),
                iconurl=kwargs.pop('iconurl', None),
                fields=kwargs.pop('fields', None),
                labels=kwargs.pop('labels', None)
            )
        self._value_property = None
        for p in kwargs:
            if hasattr(self, p):
                setattr(self, p, kwargs[p])

    # def _bind_field(self, field):
    #     EntityField(
    #         **dict(
    #             (f.field_name, getattr(field, f.field_name)) for f in field._fields
    #         )
    #     ).__call__(self.__class__)
    #     return re.sub('[^\w]+', '_', field.name)

    def appendelement(self, other):
        if isinstance(other, Field):
            if other.name not in self._fields_to_properties_:
                # propname = self._bind_field(other)
                self.fields[other.name] = other
            else:
                propname = self._fields_to_properties_[other.name]
                setattr(self, propname, other.value)
                # setattr(self, propname, other.value)
        elif isinstance(other, Label):
            self.labels[other.name] = other

    def removeelement(self, other):
        if isinstance(other, Field) and other.name in self.fields:
            del self.fields[other.name]
        elif isinstance(other, Label) and other.name in self.labels:
            del self.labels[other.name]

    @property
    def __fields__(self):
        return tuple(set(self._fields_to_properties_.values()))

    @property
    def __entity__(self):
        return self._entity

    @property
    def __type__(self):
        return self._type_

    def set_field(self, name, value):
        if name not in self._fields_to_properties_:
            self.appendelement(Field(name, value))
        setattr(self, self._fields_to_properties_[name], value)

    def get_field(self, name):
        if name not in self._fields_to_properties_:
            raise KeyError('No such field: %s.' % repr(name))
        return getattr(self, self._fields_to_properties_[name])

    def __getitem__(self, item):
        if isinstance(item, basestring):
            return self.get_field(item)
        raise TypeError('Entity indices must be str, not %s' % type(item).__name__)

    def __setitem__(self, key, value):
        if isinstance(key, basestring):
            self.set_field(key, value)
        else:
            raise TypeError('Entity indices must be str, not %s' % type(value).__name__)

    def __add__(self, other):
        return self.__iadd__(other)

    def __iadd__(self, other):
        if isinstance(other, list):
            for o in other:
                self.appendelement(o)
        else:
            self.appendelement(other)
        return self

    appendelements = __iadd__

    def __sub__(self, other):
        return self.__isub__(other)

    def __isub__(self, other):
        if isinstance(other, list):
            for o in other:
                self.removeelement(o)
        else:
            self.removeelement(other)
        return self

    removeelements = __isub__

    def __eq__(self, other):
        return self.render() == other.render()

    def __getattr__(self, item):
        return getattr(self._entity, item)

    def __setattr__(self, key, value):
        if key in ['value', 'iconurl', 'weight', 'type']:
            setattr(self._entity, key, value)
        return object.__setattr__(self, key, value)

class MaltegoTransformRequestMessage(MaltegoElement):
    entities = fields_.List(_Entity, tagname='Entities', required=False)
    parameters = fields_.Dict(Field, tagname='TransformFields', key='name', required=False)
    limits = fields_.Model(Limits, required=False)

    def __init__(self, **kwargs):
        super(MaltegoTransformRequestMessage, self).__init__(**kwargs)

    @property
    def entity(self):
        if self.entities:
            return MetaEntityClass.to_entity_type(self.entities[0].type)(self.entities[0])
        return Entity('')

    @property
    def params(self):
        if 'canari.local.arguments' in self.parameters:
            return self.parameters['canari.local.arguments'].value
        return self.parameters

    @property
    def value(self):
        return self.entity.value

    @property
    def fields(self):
        return dict([(f.name, f.value) for f in self.entity.fields.values()])

class MaltegoMessage(MaltegoElement):
    message = fields_.Choice(
        fields_.Model(MaltegoTransformExceptionMessage),
        fields_.Model(MaltegoTransformResponseMessage),
        fields_.Model(MaltegoTransformRequestMessage)
    )


import sqlite3

#connect to SQLite, connects to datebase file or creates it.
connection = sqlite3.connect('emaildb.sqlite')
#Send and receive SQL commands through cursor
cursor= connection.cursor()
#Sends command removes the table only if the table exists (to start fresh)
#otherwise, it just ignores the statement and does nothing.
cursor.execute('DROP TABLE IF EXISTS Counts');
#Sends command to create table, pass fields and type in parathenses
cursor.execute('CREATE TABLE Counts (email TEXT, count INTEGER)')
#Prompts user to input a file name
filename = input('Enter file name:')
#Error handling
if (len(filename) < 1): filename = 'nbox-short.txt'
#File handler, allows us to read the content of the File
filehandler = open(filename)
#Loop across every line in the file
for line in filehandler:
    #if line doesnt start by From: skip line and continue Loop
    if not line.startswith('From: '): continue
    #Split the line into a list of strings to retrieve email
    list = line.split()
    email = list[1]
    # This line is not retrieving data. It's 'connecting' to the database row
    # It is dangerous to put strings into SQL.
    # the ? is a placeholder, it's meant to not allow SQL injections
    cursor.execute('SELECT count FROM Counts WHERE email = ?', (email,))
    #row is the information we get from the database. If no records, row = None
    row = cursor.fetchone()
    if row is None:
        #if email isnt in the database, insert email and add 1 to count.
        cursor.execute('INSERT INTO Counts (email, count) VALUES (?, 1)', (email,))
    else:
        #if email is in the database, add +1 to count.
        cursor.execute('UPDATE Counts SET count = count + 1 WHERE email = ?', (email,))
    #commit is the command to "commit" the changes. Forces to disk, can be slow, avoid committing in loops.
    connection.commit()

#command to select the emails and counts order them by descing order, only retrieve 10.
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'

#execute command and loop across all the rows
for row in cursor.execute(sqlstra):
    #str() fonction converts the specified value into a string
    print(str(row[0]), row[1])

cursor.close()


#!/usr/bin/python
# -*- coding: utf-8 -*-
import io

class FilteredTextFile:

    def __init__(self, file_name, encoding = 'utf-8'):
        self._file_name = file_name
        self._encoding = encoding
        self._contents = []

    @property
    def contents(self):
        return self._contents

    @property
    def file_name(self):
        return self._file_name

    @file_name.setter
    def file_name(self, file_name):
        self._file_name = file_name

    @property
    def encoding(self):
        return self._encoding

    @encoding.setter
    def set_encoding(self, encoding):
        self._encoding = encoding

    def filter_line(self, line):
        return line

    def append(self, line):
        self._contents.append(line)

    def start_load(self):
        pass

    def load(self, file_name = None):

        if file_name == None:
            file_name = self.file_name

        self.start_load()
        self._contents = []
        with io.open(file_name, mode ='r', encoding = self.encoding) as inp:
            for line in inp:
                line = self.filter_line(line)
                if line != None:
                    self.append(line)

    def save(self, file_name = None):
        if file_name == None:
            file_name = self.file_name

        with io.open(file_name, mode = 'w', encoding = self.encoding) as outp:
            for line in self.contents:
                outp.write(line)

class FilteredJavaFile(FilteredTextFile):
    ST_START = 0
    ST_INITIAL_COMMENT = 1
    ST_INSIDE_CODE = 2

    def __init__(self, file_name, encoding = 'utf-8'):
        super().__init__(file_name, encoding)
        self._state = FilteredJavaFile.ST_START

    def _is_package_declaration(self, line):
        return line.lstrip().startswith('package')

    def start_load(self):
         self._state = FilteredJavaFile.ST_START

    def is_multi_line_comment_start(self, line):
        line = line.strip()
        if line.find('*/') != -1:
            # The block starts and ends in the same line
            return False
        elif line.startswith('/**') or line.startswith('/*!'):
            # Doxygen block
            return False
        elif line.startswith('/*'):
            return True
        else:
            return False

    def filter_line(self, line):
        if self._state == FilteredJavaFile.ST_INSIDE_CODE:
            return line
        elif self._state == FilteredJavaFile.ST_START:
            if self.is_multi_line_comment_start(line):
                self._state = FilteredJavaFile.ST_INITIAL_COMMENT
                return None
            else:
                self._state = FilteredJavaFile.ST_INSIDE_CODE
                return line
        elif self._state == FilteredJavaFile.ST_INITIAL_COMMENT:
            idx = line.find('*/')
            if idx == -1:
                return None
            else:
                self._state = FilteredJavaFile.ST_INSIDE_CODE
                line = line[(idx + 2):]
                if len(line.strip()) == 0:
                    return None
                else:
                    return line
        else:
            raise Exception('Invalid internal state {}.'.format(self._state))

    def add_license(self, license):
        for i in range(0, len(license)):
            self.contents.insert(i, license[i])


#!/usr/bin/python
# -*- coding: utf-8 -*-
# utf-8 中文编码
import logging
from gevent import socket as _socket
import struct
import gevent
import math
from gevent.pool import Group
from handler.base import HandlerBase

# 悲剧，windows python 3.4 才支持 ipv6 的 inet_ntop
# https://bugs.python.org/issue7171
if not hasattr(_socket, 'inet_ntop'):
    import win_inet_pton

    _socket.inet_ntop = win_inet_pton.inet_ntop
if not hasattr(_socket, 'inet_pton'):
    import win_inet_pton

    _socket.inet_pton = win_inet_pton.inet_pton

class Socks5Handler(HandlerBase):
    u'''socks5 、socks4 双协议支持'''

    def __init__(self, sock,server):
        HandlerBase.__init__(self,sock,server)

    def handler(self):
        (ver,) = self.sock.unpack('B')
        self.ver = ver
        if ver == 0x04:
            self.socks4Handle()
        elif ver == 0x05:
            self.socks5Handle()
        else:
            logging.error(u'[Socks5Handler]异常的协议类型， ver = %s' % (ver))
            self.sock.close()
            return

    def socks4Handle(self):
        cd,port,dstip = self.sock.unpack('!BHI')

        if cd != 1:
            # 1 == 连接， 2 == 绑定
            self.sock.pack('!BBHI',0,91,port,dstip)
            self.sock.close()

        userid = self.sock.readline(end='\0')[:-1]

        hostname = _socket.inet_ntoa(struct.pack('!I', dstip))

        if hostname.startswith('0.0.0.'):
            # SOCKS4a 支持 ，chrome 不支持 socks4a 扩展。
            hostname = self.sock.readline(end='\0')[:-1]

        # 对外发起请求
        try:
            remote_sock = self.server.upstream.create_connection((hostname,port),)
        except:
            logging.exception(u'所有线路连接 tcp host:%s port:%s 失败。'%(hostname,port))
            # 按照socks4协议，这里返回和请求相同的ip和端口
            # https://zh.wikipedia.org/wiki/SOCKS
            self.sock.pack('!BBHI',0,91,port,dstip)
            self.sock.close()
            return

        # 按照socks4协议，这里返回和请求相同的ip和端口
        # https://zh.wikipedia.org/wiki/SOCKS
        self.sock.pack('!BBHI',0,90,port,dstip)

        self.forward(self.sock,remote_sock,5*60)

    def socks5Handle(self):
        # 鉴定
        (nmethods,) = self.sock.unpack('B')
        if nmethods > 0:
            (methods,) = self.sock.unpack('B' * nmethods)
            # TODO: 未检查客户端支持的鉴定方式
        self.sock.pack('BB', 0x05, 0x00)
        logging.debug(u'[Socks5Handler]client login')

        # 接收代理请求
        ver, cmd, rsv, atyp = self.sock.unpack('BBBB')

        if ver != 0x05 or cmd != 0x01:
            logging.warn(u'[Socks5Handler]收到未知类型的请求，关闭连接。 ver=%s ,cmd=%s' % (ver, cmd))
            self.sock.pack('BBBBIH', 0x05, 0x07, 0x00, 0x01, 0, 0)
            self.sock.close()
            return

        if atyp == 0x01:
            # ipv4
            host, port = self.sock.unpack('!IH')
            hostname = _socket.inet_ntoa(struct.pack('!I', host))
        elif atyp == 0x03:
            # 域名
            length = self.sock.unpack('B')[0]
            hostname, port = self.sock.unpack("!%dsH" % length)
        elif atyp == 0x04:
            # ipv6
            ipv61, ipv62, port = self.sock.unpack('!2QH')
            hostname = _socket.inet_ntop(_socket.AF_INET6, struct.pack('!2Q', ipv61, ipv62))
        else:
            logging.warn(u'[SClient]收到未知的目的地址类型，关闭连接。 atyp=%s ' % (atyp))
            self.sock.pack('!BBBBIH', 0x05, 0x07, 0x00, 0x01, 0, 0)
            self.sock.close()
            return
        logging.debug(u'[SClient] host:%s   prot:%s' % (hostname, port))

        # 对外发起请求
        try:
            remote_sock = self.server.upstream.create_connection((hostname,port),)
        except:
            logging.exception(u'所有线路连接 tcp host:%s port:%s 失败。'%(hostname,port))
            # TODO: 按照socks5协议，这里应该返回服务器绑定的地址及端口
            # http://blog.csdn.net/testcs_dn/article/details/7915505
            self.sock.pack('!BBBBIH', 0x05, 0x03, 0x00, 0x01, 0, 0)
            self.sock.close()
            return

        if hasattr(remote_sock,'display_name'):
            remote_sock_display_name = remote_sock.display_name
        else:
            remote_sock_display_name = str(remote_sock)

        logging.info(u'连接 tcp目标 host:%s port:%s 通过 %s 建立成功。'%(hostname,port,remote_sock_display_name))

        # TODO: 按照socks5协议，这里应该返回服务器绑定的地址及端口
        # http://blog.csdn.net/testcs_dn/article/details/7915505
        self.sock.pack('!BBBBIH', 0x05, 0x00, 0x00, 0x01, 0, 0)

        self.forward(self.sock,remote_sock,5*60)

    @staticmethod
    def create(sock,server):
        u'''创建handler
如果是本类可处理的协议返回本类实例，否则返回None
'''
        (ver,) = sock.unpack('B')
        if ver in (0x04, 0x05):
            logging.debug(u'[Socks5Handler]收到 socks%s 协议头。' % ver)
            return (Socks5Handler(sock,server), True)
        return (None, True)


# 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
# file = open('file.txt', )

with open('file.txt', 'w') as file: #менеджер контекста использую во всей ДЗ
    while True:
        insert = input('Введи данные в файл: ') #водим данные пока ТРУ  переменную инсерт
        if insert == 'q': #если спецсимвол, то выход
            break
        text = file.write(f'{insert}\n') #записываем переменную инсерт в текст построчно


x = [1,2,3,4,5,6,7,8,9,10]

y = map(lambda i: i**2, x)
#O map() função executa um especificado função para cada item em um iterável.
# O item é enviado para a função como um parâmetro.
for i in y:
    print(i)
while True:
    try:
        value = next(y)
    except StopIteration:
        print('and')
    break


import unittest

import numpy as np

from rastervision.data.label_source.segmentation_class_transformer \
    import (SegmentationClassTransformer, color_to_triple)
from rastervision.core.class_map import ClassMap, ClassItem

class TestSegmentationClassTransformer(unittest.TestCase):
    def setUp(self):
        self.class_map = ClassMap([
            ClassItem(id=1, color='red'),
            ClassItem(id=2, color='green'),
            ClassItem(id=3, color='blue')
        ])
        self.transformer = SegmentationClassTransformer(self.class_map)

        self.rgb_image = np.zeros((1, 3, 3))
        self.rgb_image[0, 0, :] = color_to_triple('red')
        self.rgb_image[0, 1, :] = color_to_triple('green')
        self.rgb_image[0, 2, :] = color_to_triple('blue')

        self.class_image = np.array([[1, 2, 3]])

    def test_rgb_to_class(self):
        class_image = self.transformer.rgb_to_class(self.rgb_image)
        expected_class_image = self.class_image
        np.testing.assert_array_equal(class_image, expected_class_image)

    def test_class_to_rgb(self):
        rgb_image = self.transformer.class_to_rgb(self.class_image)
        expected_rgb_image = self.rgb_image
        np.testing.assert_array_equal(rgb_image, expected_rgb_image)

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


#-----------------------------------------------------
# Mimas: conference submission and review system
# (c) Allan Kelly 2016-2020 http://www.allankelly.net
# Licensed under MIT License, see LICENSE file
# -----------------------------------------------------

import unittest

from google.appengine.ext import ndb
from google.appengine.ext import testbed

from conference_lib import confquestion
from conference_lib import conference

class TestConferenceQuestions(unittest.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

    def tearDown(self):
        self.testbed.deactivate()

    def mk_conference(self):
        c = conference.Conference()
        c.name = "Allans conference_lib"
        c.shortname = "Allans"
        c.dates = "1-2 January 2017"
        c.creator_id = "Harry1"

        c.put()
        return c

    def test_conf_question_basics(self):
        c = self.mk_conference()
        q = confquestion.mk_question(c.key, "How are you?")
        self.assertEquals("How are you?", q.question_text())
        self.assertTrue(q.is_free_text())
        self.assertEquals(set(), q.answer_options())

        q.add_option("Good")
        self.assertFalse(q.is_free_text())
        self.assertSetEqual({"Good"}, q.answer_options())

        q.add_option("Bad")
        self.assertFalse(q.is_free_text())
        self.assertSetEqual({"Good", "Bad"}, q.answer_options())

    def test_retrieve_questions(self):
        c = self.mk_conference()
        questions = confquestion.retrieve_questions(c.key)
        self.assertEquals(0, len(questions))

        q = confquestion.mk_question(c.key, "How are you?")
        questions = confquestion.retrieve_questions(c.key)
        self.assertEquals(1, len(questions))
        self.assertEquals("How are you?", questions[0].question_text())

        q2 = confquestion.mk_question(c.key , "What day is it?")
        questions = confquestion.retrieve_questions(c.key)
        self.assertEquals(2, len(questions))

    def test_delete_question_answers(self):
        c = self.mk_conference()
        q = confquestion.mk_question(c.key, "How are you?")
        q.add_option("Good")
        q.add_option("Bad")

        self.assertEquals(2, len(q.answer_options()))
        q.delete_answers()
        self.assertEquals(0, len(q.answer_options()))

    def test_delete_question_and_answers(self):
        c = self.mk_conference()
        q = confquestion.mk_question(c.key, "How are you?")
        q.add_option("Good")
        q.add_option("Bad")

        self.assertEquals(1, len(confquestion.retrieve_questions(c.key)))
        confquestion.delete_question_and_answers(q)
        self.assertEquals(0, len(confquestion.retrieve_questions(c.key)))

    # see submission_lib/submission_ans.py for actual answers


# LEGO sorter project
# Verifies image display
# (c) kol, 2023

import os
import logging
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from absl import app, flags
from root_dir import OUTPUT_DIR
from matplotlib.widgets import Slider

logging.getLogger('lego-tracker').setLevel(logging.ERROR)

from lib.image_dataset import (
    fast_get_class_names,
    _preprocess,
    IMAGE_SIZE,
    zoom_image
)
from lib.model import load_model, make_model

FLAGS = flags.FLAGS

def main(_):
    image = tf.image.decode_image(tf.io.read_file(os.path.join(OUTPUT_DIR, 'roi','3001_0127.png')), channels=3)
    resized_image = tf.keras.preprocessing.image.smart_resize(image, IMAGE_SIZE)

    class_names = fast_get_class_names()
    model = make_model(len(class_names))
    load_model(model)

    params = {
        'contrast': {
            'value': 1.0,
            'lower': -10.0,
            'upper': 10.0,
            'step': 1.0,
        },
        'brightness': {
            'value': 0.0,
            'lower': -30.0,
            'upper': 30.0,
            'step': 10.0,
        },
        'saturation': {
            'value': 0.0,
            'lower': 0.0,
            'upper': 30.0,
            'step': 1.0,
        },
        'zoom': {
            'value': 1.0,
            'lower': 1.0,
            'upper': 3.0,
            'step': 0.25,
        },
    }
    cmap = 'gray' if FLAGS.gray or FLAGS.edges else None

    fig, ax = plt.subplots(figsize=(8, 4))
    plt.title('roi')
    plt.axis('off')

    def apply_adj():
        adj_image = resized_image
        adj_image = zoom_image(adj_image, params['zoom']['value'])
        adj_image = tf.image.adjust_contrast(adj_image, params['contrast']['value'])
        adj_image = tf.image.adjust_brightness(adj_image, params['brightness']['value'])
        adj_image = tf.image.adjust_saturation(adj_image, params['saturation']['value'])

        prepared_image, _ = _preprocess(tf.expand_dims(adj_image, 0))
        image = prepared_image[0].numpy()
        ax.imshow(image.astype('uint8'), cmap=cmap)

        prepared_image = tf.keras.preprocessing.image.smart_resize(prepared_image, IMAGE_SIZE)
        prediction = model.predict(prepared_image, verbose=0)
        most_likely = np.argmax(prediction)
        label = class_names[most_likely]
        prob = prediction[0][most_likely]

        ax.set_title(f'{label} ({prob:.4f})')
        fig.canvas.draw_idle()

    def make_update_func(key):
        def update_func(val):
            nonlocal params
            params[key]['value'] = val
            apply_adj()
        return update_func

    SLIDER_WIDTH = 0.0225
    SLIDER_SPACE = 0.10
    fig.subplots_adjust(left=(SLIDER_WIDTH+SLIDER_SPACE)*len(params), bottom=0.25)
    x = 0.1
    for key, par in params.items():
        par['slider'] = Slider(
            ax=fig.add_axes([x, 0.25, SLIDER_WIDTH, 0.63]),
            label=key,
            valmin=par['lower'],
            valmax=par['upper'],
            valstep=par['step'],
            valinit=par['value'],
            orientation="vertical"
        )
        par['slider'].on_changed(make_update_func(key))
        x += SLIDER_WIDTH+SLIDER_SPACE

    apply_adj()
    plt.show()

if __name__ == '__main__':
    app.run(main)


import wx

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)

        self.InitUI()
        self.Centre()
        self.Show()

    def InitUI(self):

        panel = wx.Panel(self)
        sizer = wx.GridBagSizer(0, 0)
        panel2 = wx.Panel(self)

        # pos=(0, 0)：放在1行1列，不设置span，默认span=(1,1)占一行一列的大小
        text = wx.StaticText(panel, label="Name:")
        sizer.Add(text, pos=(0, 0), flag=wx.ALL, border=5)

        sb = wx.StaticBox(panel, label="Optional Attributes")
        boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)

        panel.SetSizerAndFit(sizer)

app = wx.App()
Example(None, 'Demo')
app.MainLoop()


import pytest
from selenium import webdriver
from config import *

# c_path = r"C:\Users\AS064243\OneDrive - Cerner Corporation\Documents\Learning\pytestframework\pytestframework\drivers\chromedriver.exe"

class DriverInit:

    @pytest.fixture(scope="class", autouse=True)
    def driver_Init(self, request):
        if browser.lower() == "chrome":
            driver = webdriver.Chrome(executable_path=c_path)

        elif browser.lower() == "firefox":
            driver = webdriver.Firefox(executable_path=f_path)

        driver.get(url)
        driver.maximize_window()
        driver.maximize_window()
        request.cls.driver = driver

        yield
        driver.quit()


def solution(a, b):
    # 1월 1일이 금요일이기 때문에 week[0] = FRI로 시작
    week = ['FRI', 'SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU']
    # 각 달의 day 개수
    month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    sum = 0

    # 해당 월의 바로 전월까지만의 day를 더함
    for i in range(a-1):
        sum += month[i]
    # sum에 b를 더해주고 1을 빼줌(배열은 0부터 시작이기 때문)
    sum += b -1

    return week[sum%7]