import pygame as pg
import sys
import random
import time
pg.init()#初始化
#设置窗口
game_window = pg.display.set_mode((600,500))
#设置窗口标题
pg.display.set_caption('jieqiu')
#设置窗口颜色
window_color = (0,255,255)
#设置球体颜色 接球板颜色
ball_color = (255,255,0)
rect_color = (255,0,0)
#初始化球的位置
ball_x = random.randint(10,590)
ball_y = 10
move_x = 1#用来表示球每次移动的多少位置
move_y = 1
score = 0#记分板
font = pg.font.Font(None,70)#字体 大小
point =1#计分
count = 0
while True:
    game_window.fill(window_color)
    #是窗口不断更新 不要退出
    for event in pg.event.get():
        if event.type ==pg.QUIT:
            sys.exit()
    #获取鼠标的位置
    mouse_x,mouse_y = pg.mouse.get_pos()
    #创建一个球 三个参数，在窗口里面画，颜色，(位置x,y),半径
    pg.draw.circle(game_window,ball_color,(ball_x,ball_y),10)
    #画一个矩形接球 在窗口里面，颜色，（位置x跟随鼠标移动，y只能在最下面，宽度，高度）
    pg.draw.rect(game_window,rect_color,(mouse_x,490,100,10))
    my_text = font.render(str(score),False,(255,255,255))#记分字体 抗拒值 字体颜色
    game_window.blit(my_text,(500,30))
    ball_x += move_x #让球动起来 每次移动
    ball_y += move_y
    if ball_x <= 10 or ball_x>=590:#球的位置左右检测
        move_x = -move_x
    if ball_y <=10:#球的位置到达最上端
        move_y = -move_y
    elif mouse_x-10 <ball_x <mouse_x+110 and ball_y>=480:
        move_y = -move_y
        score +=point
        count += 1
        if count == 3:
            count = 0
            point += point
            if mouse_x>0:
                move_x += 1
            else:
                move_x -= 1
            move_y -= 1
    elif ball_y >= 490 and (ball_x<=mouse_x-10 or ball_x>=mouse_x+100+10):
        break

    pg.display.update()
    time.sleep(0.005)#刷新速度


# Author: Jakub Szwedowicz
# Date: 09.06.2022
# e-mail: kuba.szwedowicz@gmail.com

from PyQt6.QtWidgets import QWidget, QGridLayout, QPushButton
from PyQt6.QtGui import QCursor
from PyQt6.QtCore import Qt
from typing import Dict

def create_button(text: str) -> QPushButton:
    button = QPushButton(text)
    button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
    button.setStyleSheet("*{Border: 4px solid '#BC006C';" +
                         "Border-radius: 15px;" +
                         "font-size: 35px;" +
                         "color: 'white';" +
                         "padding: 25px 0;" +
                         "margin: 100px 200px;}" +
                         "*:hover{background: '#BC006C';}")
    return button

class MenuScreen(QWidget):
    _DEFAULT_SCREEN_SIZE = [700, 400]

    def __init__(self, parent=None):
        super(MenuScreen, self).__init__(parent)
        self.setWindowTitle('Pong')
        self.setFixedSize(MenuScreen._DEFAULT_SCREEN_SIZE[0], MenuScreen._DEFAULT_SCREEN_SIZE[1])
        self.setStyleSheet('background: #161219;')

        self._grid = QGridLayout()
        self._buttons = {'Start': create_button('Start')}
        self._grid.addWidget(self._buttons['Start'], 1, 0)

        self.setLayout(self._grid)

    def get_start_button_name(self) -> str:
        return 'Start'

    def connect_button(self, button: str, function):
        self._buttons[button].clicked.connect(function)


import torch
from torch import nn
from main_code.model.layer.MoGLayer import MoGLayer
from main_code.model.discrim import DISCRIM_RGB

def gen_noise(noise_dim):
    return torch.rand(noise_dim)

class GENERATOR_RGB(nn.Module):
    def __init__(self, noise_dim, features_dim):
        super(GENERATOR_RGB, self).__init__()
        assert features_dim == noise_dim, "<X>: Currently, noise and features dimension expect to be same."
        self.noise_dim = noise_dim

        # From equation z = MEANi + (STDi * EP) | EP ~ N(0,1)
        self.MoGLayer = MoGLayer(noise_dim=noise_dim)

        self.dense01 = nn.Sequential(
            nn.Linear(in_features=features_dim, out_features=features_dim)
            , nn.Tanh()
        )

        self.batchNorm01 = nn.BatchNorm1d(num_features=features_dim)

        self.dense02 = nn.Sequential(
            nn.Linear(in_features=features_dim, out_features=512 * 4 * 4)
            , nn.ReLU()
        )

        self.conv2dT01 = nn.Sequential(
            # From the paper, they use kern_size = 5, padding = 0
            nn.BatchNorm2d(num_features=512, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.conv2dT02 = nn.Sequential(
            nn.BatchNorm2d(num_features=256, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.conv2dT03 = nn.Sequential(
            nn.BatchNorm2d(num_features=128, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.conv2dT04 = nn.Sequential(
            nn.BatchNorm2d(num_features=64, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=64, out_channels=1, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.tanh = nn.Tanh()

    """
    Expected tensor to have shape (N,C,...)
    """
    def forward(self, eeg_features):
        noise_input = gen_noise(self.noise_dim)
        x = self.MoGLayer(noise_input)
        x = self.dense01(x)
        x = x * eeg_features  # Multiply noise with eeg signal here
        # print(x.shape)  # Expected to be 2 dimension

        # if len(x.shape) >= 2:
        x = self.batchNorm01(x)  # This layer allowed one batch when the model in eval mode.
        x = self.dense02(x)

        x = x.reshape([x.shape[0], 512, 4, 4])
        # x = x.unsqueeze(0) # Try to run the code with out this line first
        x = self.conv2dT01(x)
        x = self.conv2dT02(x)
        x = self.conv2dT03(x)
        x = self.conv2dT04(x)
        x = self.tanh(x)
        return x

    def set_dev(self, dev):
        self.MoGLayer.set_dev(dev)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 16:20:00 2018

@authors: olivierm, BlanchonMarc

Tools to read and import data from Polarcam
"""

from enum import Enum
import numpy as np
from scipy.signal import convolve2d
import matplotlib.pyplot as pl
from matplotlib.colors import hsv_to_rgb
import math
from scipy.interpolate import CubicSpline
from lib import *
from utils import *
import os

# -- Path of the flatfield file
# FLATF = np.genfromtxt('flatfield.csv',
#                      dtype=float, delimiter=',', skip_header=9)
#
# FLATF[FLATF >= 1.4] = 1.4  # Remove outliers or deadpixels

# %% Pixel Order

# positions are defined clockwise
# +-------+
# | 0 | 1 |
# |---+---|
# | 3 | 2 |
# +-------+

# by default I45_90_135_0 for polarcam V1
# +-----------+
# | I45|  I90 |
# |----+------|
# | I0 | I135 |
# +-----------+

# by default I90_135_0_45 for polarcam V2
# +-----------+
# | I90| I135 |
# |----+------|
# | I45|  I0  |
# +-----------+

class Pixorder(Enum):
    """ Class that defines order of pixels """
    polarcamV2 = (2, 3, 0, 1)
    polarcamV1 = (3, 0, 1, 2)

    I0_45_90_135 = (0, 1, 2, 3)
    I45_0_135_90 = (1, 0, 3, 2)
    I135_90_45_0 = (3, 2, 1, 0)
    I90_135_0_45 = (2, 3, 0, 1)
    I45_90_135_0 = (3, 0, 1, 2)

    def __str__(self):
        posi = ['p{}'.format(u) for u in list(self.value)]
        filt = ('I0', 'I45', 'I90', 'I135')
        dico = dict(zip(posi, filt))
        chaine = '+-----------+\n|{p0:^5}|{p1:^5}|\n|-----+-----|\n|{p2:^5}|{p3:^5}|\n+-----------+'.format(
            **dico)
        return chaine

# %% Polaim

class Polaim():
    """Class that describes pixelated images -- version 2018"""

    def __init__(self, raw, method='none', pixels_order=Pixorder.polarcamV2):
        """ Initialization method """

        # --- Open the image if filename provided
        if isinstance(raw, str):
            raw = pl.imread(raw)

        self.depth = 8  # 8bit depth by default

        # --- In cas of 10 bit depth convert into the right range
        if raw.dtype == 'uint16':
            self.depth = 16

        self.method = method
        # --- Apply the flat field correction
        # self.raw = np.asarray((raw * FLATF) / FLATF.max(), dtype=self.raw.dtype)

        # --- Extract the 4 images using interpolation technics
        self.images = raw2quad(self, raw, method=method,
                               pixels_order=pixels_order)

        # --- Compute the 3 stokes parameters
        mat = np.array([[0.5, 0.5, 0.5, 0.5],
                        [1.0, 0.0, -1., 0.0],
                        [0.0, 1.0, 0.0, -1.]])

        self.stokes = np.tensordot(mat, self.images, 1)

        # --- Error estimation
        imat = 0.5 * np.array([[1, 1, 0.],
                               [1, 0, 1.],
                               [1, -1, 0],
                               [1, 0, -1]])

        self.error = sum(
            (self.images - np.tensordot(np.dot(imat, mat), self.images, 1))**2, 0)

    @property
    def inte(self):
        """Return intensity image"""
        return self.stokes[0]

    @property
    def aop(self):
        """Return aop image"""
        return np.mod(np.arctan2(self.stokes[2], self.stokes[1]) / 2., np.pi)

    @property
    def dop(self):
        """Return dop image"""
        return np.divide(np.sqrt(self.stokes[2]**2, self.stokes[1]**2),
                         self.stokes[0], out=np.zeros_like(self.stokes[0]),
                         where=self.stokes[0] != 0)

    def rgb_aop(self, colormap='hsv', dop_min=0.0, opencv=False):
        r""" Given a Polaim object return a RGB image of the aop

        Parameters
        ----------
        colormap : string
            colormap used for aop
        opencv : boolean
            assume opencv color representation convention
        aop_only : boolean
            assume dop=1 and constant intensity

        Return
        ------
        col : 3D array
            RGB image representing the aop

        Examples
        --------
        >>> imp.aop2rgb()
        """

        newaop = np.ma.array(self.aop.copy())  # convert into masked array
        newaop.mask = self.dop <= dop_min
        cmap = pl.get_cmap(colormap)
        cmap.set_bad((0., 0., 0.))
        # cmap.set_under((0, 0, 0))
        # cmap.set_over((0, 0, 0))
        aop_rgb = cmap(np.mod(newaop, np.pi) / np.pi)

        if opencv:  # opencv compatibilty
            return np.uint8(aop_rgb[:, :, [2, 1, 0]] * 255)

        return aop_rgb

    def rgb_pola(self, dop_max=1.0, dop_min=0.0, opencv=False):
        r""" Given a Polaim object return a RGB image
        with HSV mapping

        Parameters
        ----------
        dop_max : floatting number
            maximum authorized value for dop
        opencv : boolean
            assume opencv color representation convention

        Return
        ------
        col : 3D array
            RGB image representing the aop

        Examples
        --------
        >>> imp.pola2rgb()
        """

        hsv = np.zeros(self.aop.shape + (3, ))
        # -- Normalization in [0. 1.]
        hsv[:, :, 2] = self.inte / 2. / (2**self.depth - 1)
        hsv[:, :, 1] = np.minimum(self.dop / dop_max, 1)
        hsv[:, :, 0] = self.aop / np.pi

        hsv[self.dop <= dop_min, :] = (0., 0., 0.)

        # to be checked
        rgb = hsv_to_rgb(hsv)
        if opencv:  # opencv compatibilty
            return np.uint8(rgb[:, :, [2, 1, 0]] * 255)
        return rgb

# %% Functions

def raw2quad(self, raw, method='none', pixels_order=Pixorder.polarcamV2):
    """Convert a raw image from polarcam into a list of ordered images
    [I0, I45, I90, I135]. If the parameter `method` is set to none the
    output images will have half size of the original image.

    Parameters
    ----------
    raw : 2D array
        Original polarcam image in grayscale
    method : {'none', 'linear', 'bilinear', 'weightedb3', 'weightedb4'}
        'none' : no interpolation method is performed
        'linear' : linear interpolation
        'bilinear' : bilinear interpolation
        'weightedb3' or 'weightedb4' : weighted bilinear interpolation with 3
        or 4 neighbors

    Returns
    -------
    images : 3D array containing 4 images

    Example
    -------
    >>> images = raw2quad(raw, method='bilinear')

    """
    if method == 'none':
        self.images = np.array([raw[0::2, 0::2],  # 0
                                raw[0::2, 1::2],  # 1
                                raw[1::2, 1::2],  # 2
                                raw[1::2, 0::2]])  # 3
        return self.images[pixels_order.value, :, :]
    if method == 'linear':
        kernels = [np.array([[1, 0], [0, 0.]]),
                   np.array([[0, 1], [0, 0.]]),
                   np.array([[0, 0], [0, 1.]]),
                   np.array([[0, 0], [1, 0.]])]
    elif method == 'bilinear':
        kernels = [np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0.]]),
                   np.array([[0, 0, 0], [1, 0, 1], [0, 0, 0]]) / 2.,
                   np.array([[1, 0, 1], [0, 0, 0], [1, 0, 1]]) / 4.,
                   np.array([[0, 1, 0], [0, 0, 0], [0, 1, 0]]) / 2.]
    elif method == 'conv_bicubic':

        R = bicubicConv.conv_bicubic(np.array(raw, dtype=np.double))

        return order.ordering(R, raw.dtype, pixels_order.value)

    elif method == 'weightedb3':
        b = np.sqrt(2) / 2 / (np.sqrt(2) / 2 + np.sqrt(10))
        a = np.sqrt(10) / 2 / (np.sqrt(2) / 2 + np.sqrt(10))

        kernels = [np.array([[0, b, 0, 0],
                             [0, 0, 0, 0],
                             [0, a, 0, b],
                             [0, 0, 0, 0]]),
                   np.array([[0, 0, b, 0],
                             [0, 0, 0, 0],
                             [b, 0, a, 0],
                             [0, 0, 0, 0]]),
                   np.array([[0, 0, 0, 0],
                             [b, 0, a, 0],
                             [0, 0, 0, 0],
                             [0, 0, b, 0]]),
                   np.array([[0, 0, 0, 0],
                             [0, a, 0, b],
                             [0, 0, 0, 0],
                             [0, b, 0, 0]])]
    elif method == 'weightedb4':
        c = np.sqrt(2) / 2 / (3 * np.sqrt(2) / 2 +
                              np.sqrt(2) / 2 + np.sqrt(10))
        b = np.sqrt(10) / 2 / (3 * np.sqrt(2) / 2 +
                               np.sqrt(2) / 2 + np.sqrt(10))
        a = 3 * np.sqrt(2) / 2 / (3 * np.sqrt(2) / 2 +
                                  np.sqrt(2) / 2 + np.sqrt(10))

        kernels = [np.array([[0, b, 0, c],
                             [0, 0, 0, 0],
                             [0, a, 0, b],
                             [0, 0, 0, 0]]),
                   np.array([[c, 0, b, 0],
                             [0, 0, 0, 0],
                             [b, 0, a, 0],
                             [0, 0, 0, 0]]),
                   np.array([[0, 0, 0, 0],
                             [b, 0, a, 0],
                             [0, 0, 0, 0],
                             [c, 0, b, 0]]),
                   np.array([[0, 0, 0, 0],
                             [0, a, 0, b],
                             [0, 0, 0, 0],
                             [0, b, 0, c]])]

    elif method == 'newton':
        R = newton.newton_polynomial(np.array(raw, dtype=np.double))
        self.images = order.ordering(R, raw.dtype, pixels_order.value)
        return order.ordering(R, raw.dtype, pixels_order.value)

    elif method == 'bicubic_spline':

        R = bicubicSpline.bicubic_spline(np.array(raw, dtype=np.double))
        self.images = order.ordering(R, raw.dtype, pixels_order.value)
        return order.ordering(R, raw.dtype, pixels_order.value)

    elif method == 'intensity_correlation':

        R = intensityCorr.intensity_correlation(np.array(raw, dtype=np.double))
        self.images = order.ordering(R, raw.dtype, pixels_order.value)
        return order.ordering(R, raw.dtype, pixels_order.value)

    else:
        raise SystemExit(f"ERROR. \'{method}\' is not a method.")

    convs = [convolve2d(raw, k, mode='same') for k in kernels]
    offsets = [[(0, 0), (0, 1), (1, 1), (1, 0)],
               [(0, 1), (0, 0), (1, 0), (1, 1)],
               [(1, 1), (1, 0), (0, 0), (0, 1)],
               [(1, 0), (1, 1), (0, 1), (0, 0)]]

    images = np.zeros((4,) + raw.shape)
    for (j, o) in enumerate(offsets):
        for ide in range(4):
            images[j, o[ide][0]::2, o[ide][1]::2] = convs[ide][o[ide][0]::2, o[ide][1]::2]

    self.images = np.asarray(images[pixels_order.value, :, :], dtype=raw.dtype)

    return np.asarray(images[pixels_order.value, :, :], dtype=raw.dtype)

class PolaGT():
    """Class that describes pixelated images -- version 2018"""

    def __init__(self, im1, im2, im3, im4, pixels_order=Pixorder.polarcamV2):
        """ Initialization method """

        # --- Open the image if filename provided
        if isinstance(im1, str):
            im1 = pl.imread(im1)

        if isinstance(im2, str):
            im2 = pl.imread(im2)

        if isinstance(im3, str):
            im3 = pl.imread(im3)

        if isinstance(im4, str):
            im4 = pl.imread(im4)

        self.depth = 8  # 8bit depth by default

        # --- In cas of 10 bit depth convert into the right range
        if im1.dtype == 'uint16':
            self.depth = 16

        # --- Apply the flat field correction
        # self.raw = np.asarray((raw * FLATF) / FLATF.max(), dtype=self.raw.dtype)

        self.images = np.array([im1, im2, im3, im4])
        self.images = self.images[pixels_order.value, :, :]

        # --- Compute the 3 stokes parameters
        mat = np.array([[0.5, 0.5, 0.5, 0.5],
                        [1.0, 0.0, -1., 0.0],
                        [0.0, 1.0, 0.0, -1.]])

        self.stokes = np.tensordot(mat, self.images, 1)

        # --- Error estimation
        imat = 0.5 * np.array([[1, 1, 0.],
                               [1, 0, 1.],
                               [1, -1, 0],
                               [1, 0, -1]])

        self.error = sum(
            (self.images - np.tensordot(np.dot(imat, mat), self.images, 1))**2, 0)

    @property
    def inte(self):
        """Return intensity image"""
        return self.stokes[0]

    @property
    def aop(self):
        """Return aop image"""
        return np.mod(np.arctan2(self.stokes[2], self.stokes[1]) / 2., np.pi)

    @property
    def dop(self):
        """Return dop image"""
        return np.divide(np.sqrt(self.stokes[2]**2, self.stokes[1]**2),
                         self.stokes[0], out=np.zeros_like(self.stokes[0]),
                         where=self.stokes[0] != 0)

    def rgb_aop(self, colormap='hsv', dop_min=0.0, opencv=False):
        r""" Given a Polaim object return a RGB image of the aop

        Parameters
        ----------
        colormap : string
            colormap used for aop
        opencv : boolean
            assume opencv color representation convention
        aop_only : boolean
            assume dop=1 and constant intensity

        Return
        ------
        col : 3D array
            RGB image representing the aop

        Examples
        --------
        >>> imp.aop2rgb()
        """

        newaop = np.ma.array(self.aop.copy())  # convert into masked array
        newaop.mask = self.dop <= dop_min
        cmap = pl.get_cmap(colormap)
        cmap.set_bad((0., 0., 0.))
        # cmap.set_under((0, 0, 0))
        # cmap.set_over((0, 0, 0))
        aop_rgb = cmap(np.mod(newaop, np.pi) / np.pi)

        if opencv:  # opencv compatibilty
            return np.uint8(aop_rgb[:, :, [2, 1, 0]] * 255)

        return aop_rgb

    def rgb_pola(self, dop_max=1.0, dop_min=0.0, opencv=False):
        r""" Given a Polaim object return a RGB image
        with HSV mapping

        Parameters
        ----------
        dop_max : floatting number
            maximum authorized value for dop
        opencv : boolean
            assume opencv color representation convention

        Return
        ------
        col : 3D array
            RGB image representing the aop

        Examples
        --------
        >>> imp.pola2rgb()
        """

        hsv = np.zeros(self.aop.shape + (3, ))
        # -- Normalization in [0. 1.]
        hsv[:, :, 2] = self.inte / 2. / (2**self.depth - 1)
        hsv[:, :, 1] = np.minimum(self.dop / dop_max, 1)
        hsv[:, :, 0] = self.aop / np.pi

        hsv[self.dop <= dop_min, :] = (0., 0., 0.)

        # to be checked
        rgb = hsv_to_rgb(hsv)
        if opencv:  # opencv compatibilty
            return np.uint8(rgb[:, :, [2, 1, 0]] * 255)
        return rgb

if __name__ == '__main__':
    # pid = os.getpid()
    #
    # print(f'PID is : {pid}')
    # input("Press Enter to continue...")
    # os.spawnl(os.P_NOWAIT, f'psrecord {pid} --log activity.txt')
    with np.errstate(divide='ignore', invalid='ignore'):
        timer.tic()
        POLA = Polaim('images/image_00001.tiff', method='bilinear')
        print(POLA.method)
        timer.toc()

    # test_images.create_test_img(POLA)

    # pl.imshow(POLA.rgb_aop(dop_min=0))
    # pl.show()
    # pl.imshow(POLA.rgb_pola(dop_max=0.4, dop_min=0))
    # pl.show()


##
## Developed for the University of Nottingham G52GRP module
##
## Written by:	Marcus Whybrow (mxw18u)
## Group: 		gp09-drm
##

from BeautifulSoup import BeautifulStoneSoup
from urllib2 import urlopen, HTTPError, URLError
import httplib
import re
from base import utils
from django.db.models import Q

from volumes.models import Book, BookEditionGroup
from tagging.models import Tag
from django.template.defaultfilters import slugify
from xml.sax.saxutils import unescape
import httplib

def get_editions(isbn):

	# Get on of the ISBN numbers and query google for all related editions
	if len(isbn) == 10 or len(isbn) == 13:
		url = 'http://books.google.com/books/feeds/volumes?q=editions:isbn' + isbn
	else:
		raise ValueError('Books must have either an ISBN10 or ISBN13 identifier')

	try:
		return BeautifulStoneSoup(urlopen(url).read())
	except (HTTPError, URLError, httplib.BadStatusLine, httplib.InvalidURL, ValueError, IOError):
		return None

class BookDetail:
	"""
	Gets information regarding books using Google's books API
	"""

	THUMBNAIL_REL = 'http://schemas.google.com/books/2008/thumbnail'
	INFO_REL = 'http://schemas.google.com/books/2008/info'
	ANNOTATION_REL = 'http://schemas.google.com/books/2008/annotation'
	ALTERNATE_REL = 'alternate'
	SELF_REL = 'self'

	status = False

	def __init__(self, url):
# 		try:
		xml = unicode(urlopen(url).read(), errors='ignore')
		self.soup = BeautifulStoneSoup(xml)
# 		except (HTTPError, URLError, httplib.BadStatusLine, httplib.InvalidURL, ValueError, IOError):
# 			return None

		if self.soup is not None:

			self.status = True
			entry = self.soup

			author =  entry.find('dc:creator')
			self.author = unescape(author.string) if author is not None else None
			date = entry.find('dc:date')

			if date is not None:
				dateString = ''
				if re.match('^[0-9][0-9][0-9][0-9]$', date.string): dateString = date.string + '-01-01 00:00:00'
				elif re.match('^[0-9][0-9][0-9][0-9]-[0-9][0-9]$', date.string): dateString = date.string + '-01 00:00:00'
				elif re.match('^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$', date.string): dateString = date.string + ' 00:00:00'
				self.published = utils.parseDateTime(dateString)
			else:
				self.published = None

			description = entry.find('dc:description')
			self.description = unescape(description.string) if description is not None else None

			self.width = self.height = self.depth = self.pages = self.format = None

			try:
				for format in entry.findAll('dc:format'):
					if format.string.startswith('Dimensions'):
						dimensions = format.string.split(' ')[1]
						dimensions = dimensions.split('x')
						self.width = float(dimensions[0])
						self.height = float(dimensions[1])
						self.depth = float(dimensions[2])
					elif re.match('[0-9]', format.string):
						self.pages = int(format.string.split(' ')[0])
					else:
						self.format = unescape(format.string)
			except IndexError:
				# Some dimensions are not present
				pass

			identifiers = entry.findAll('dc:identifier')

			self.googleid = identifiers[0].string
			self.isbn10 = self.isbn13 = None
			for identifier in identifiers[1:]:
				if identifier.string.startswith('ISBN:'):
					isbn = identifier.string.lstrip('ISBN:')
					if len(isbn) == 10:
						self.isbn10 = isbn
					elif len(isbn) == 13:
						self.isbn13 = isbn
					else:
						# ERROR: It's an ISBN but is not 10 or 13 digits long
						pass

			language = entry.find('dc:language')
			self.language = language.string if language is not None else None
			publisher = entry.find('dc:publisher')
			self.publisher = unescape(publisher.string) if publisher is not None else None

			self.thumbnail_base = None
			self.thumbnail_huge = None
			self.thumbnail_small = None
			self.thumbnail_large = None

			# Thubnail
			for link in entry.findAll('link'):
				if link['rel'] == self.THUMBNAIL_REL:
					url = httplib.urlsplit(unescape(link['href']))
					self.thumbnail_base = url.scheme + '://' + url.netloc + url.path + '?id=' + self.googleid + '&printsec=frontcover&img=1&zoom='
					self.thumbnail_large = self.thumbnail_base + '1'
					self.thumbnail_small = self.thumbnail_base + '5'
					self.thumbnail_huge = self.thumbnail_base + '0'

			self.subjects = []
			for subject in entry.findAll('dc:subject'):
				self.subjects.append(unescape(subject.string))

			title = entry.find('dc:title')
			self.title = unescape(title.string) if title is not None else None

		else:
			self.status = False

	def get_details(self):
		if self.status:
			return {
				'title': self.title,
				'isbn10': self.isbn10,
				'isbn13': self.isbn13,
				'description': self.description,
				'publisher': self.publisher,
				'published': self.published,
				'author': self.author,
				'pages': self.pages,
				'format': self.format,
				'language': self.language,
				'width': self.width,
				'height': self.height,
				'depth': self.depth,
				'thumbnail_large': self.thumbnail_large,
				'thumbnail_small': self.thumbnail_small,
				'thumbnail_base': self.thumbnail_base,
				'thumbnail_huge': self.thumbnail_huge,
			}
		else:
			return None

	def get_book(self):
		if self.status:
			try:
				return Book.objects.get(Q(isbn10=self.isbn10) | Q(isbn13=self.isbn13))
			except Book.DoesNotExist:
				return None
		else:
			return None

	def convert_to_book(self, edition_group=None):
		"""
		Converts a BookDetail object into a Book object (from the database).
		 - If the book already exists it is retrieved from the database (unchanged)
		 - If the book does not exist it is created
		   - If an edition_group is specified it is set as the edition_group for the new book
		   - If an edition_group is not specified:
		     - Editions are retrieved from Google Books
		     - If any of those editions exist in the database, that Book's edition_group is used.
		"""

		# If this BookDetail has details
		if self.status:

			# Attempt to get the book from the database
			book = self.get_book()

			# If the book is in the database
			if book is not None:
				# possibly update information
				pass

			else:
				# Create a new book
				book = Book(**self.get_details())

				# If an edition_group was provided
				if edition_group is not None:
					# assign this new book that edition_group
					book.edition_group = edition_group
				else:
					# Get the editions (XML data) soup
					editionSoup = get_editions(self.isbn10) if self.isbn10 is not None else get_editions(self.isbn13)
					# Check each editions ISBN numbers
					for entry in editionSoup.findAll('entry'):
						# For each identifier
						for ident in entry.findAll('dc:identifier'):

							# If it is an ISBN identifier
							if ident.string.startswith('ISBN:'):
								# Get the actual ISBN
								isbn = ident.string.lstrip('ISBN:')

								try:
									# See if its the same book as the initial book, or if it is in the database.
									if len(isbn) == 10:
										if isbn == book.isbn10: continue
										existing_book = Book.objects.get(isbn10=isbn)
									elif len(isbn) == 13:
										if isbn == book.isbn13: continue
										existing_book = Book.objects.get(isbn13=isbn)

									# Assign the book we are trying to create the edition_group of this book
									book.edition_group = existing_book.edition_group
									book.save()

									# Add the subjects as tags to this book
									for subject in self.subjects:
										Tag.objects.add_tag(book, slugify(subject))

									return book

								except Book.DoesNotExist:
									# If not found try the next ISBN or the next Edition.
									continue

					# If no other editions were found in the database, its safe to create a new edition_group for this book
					edition_group = BookEditionGroup()
					edition_group.save()
					book.edition_group = edition_group

			# Save the book to the database
			book.save()

			# Add the subjects as tags to this book
			for subject in self.subjects:
				Tag.objects.add_tag(book, slugify(subject))

			return book
		else:
			return None

def update_all_editions(book):
	"""
	Ensures all other editions of the same book are in the database and that all editions are associated with the same edition_group.
	"""

	# Get the editions soup for this book
	soup = get_editions(book.isbn10) if book.isbn10 else get_editions(book.isbn13)

	# Create a list for the resultant book details URLs
	books = []

	# For each edition
	for entry in soup.findAll('entry'):
		# Check all identifiers
		for ident in entry.findAll('dc:identifier'):
			# If its an ISBN identifier
			if ident.string.startswith('ISBN:'):
				# Get the actual ISBN
				isbn = ident.string.lstrip('ISBN:')

				try:
					# See if its the same book as the initial book, or if it is in the database.
					if len(isbn) == 10:
						if isbn == book.isbn10: continue
						book.edition_group.editions.get(isbn10=isbn)
					elif len(isbn) == 13:
						if isbn == book.isbn13: continue
						book.edition_group.editions.get(isbn13=isbn)
				except Book.DoesNotExist:
					# If not found, add it to the database and to the inital books edition_group
					BookDetail(entry.id.string).convert_to_book(book.edition_group)

def get_book_detail(isbn):
	"""
	Gets al details from google books about regarding a specific ISBN, making them assessable through a BooKDetail object.
	"""

	# If the ISBN number is the correct length
	if len(isbn) == 10 or len(isbn) == 13:

		# Query Google
		queryUrl = 'http://books.google.com/books/feeds/volumes?q=isbn:' + isbn
		try:
			querySoup = BeautifulStoneSoup(urlopen(queryUrl).read())
		except (HTTPError, URLError, httplib.BadStatusLine, httplib.InvalidURL, ValueError, IOError):
			return None

		# If an entry was found
		if querySoup.entry is not None:

			# Find the url for the full details of the book
			volumeUrl = querySoup.entry.id.string
			# Return a BookDetail object containign those detials
			return BookDetail(volumeUrl)

		else:
			raise Exception('ISBN not found using Google Books')
	else:
		raise Exception('An ISBN must be 10 or 13 digits long')

import threading

class UpdateEditions(threading.Thread):
	"""
	A thread which calls the update_all_editions() utility function on a specific book.
	Books are added within a view, we do not want the make the user wait for all editions to be updated
	when they only care about their single book. We use a thread to execute this process non-sequentially.
	"""

	def __init__(self, book):
		"""
		Specifies the book on which to update the editions
		"""

		super(UpdateEditions, self).__init__()
		self.book = book

	def run(self):
		"""
		Updates the editions for a specific book.
		"""
		update_all_editions(self.book)


from tf.transformations import euler_from_quaternion
import rospy
from gazebo_msgs.srv import GetModelState
from std_msgs.msg import Float32

_model_state = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)

def get_model_state():
    rospy.wait_for_service("/gazebo/get_model_state")
    try:
        return _model_state('jackal', 'world')
    except (rospy.ServiceException):
        rospy.logwarn("/gazebo/get_model_state service call failed")

rospy.init_node("transform_euler", anonymous=True)
theta_publisher = rospy.Publisher('/theta', Float32, queue_size=1)

r = rospy.Rate(50) # define rate here

while not rospy.is_shutdown():

    ori= get_model_state().pose.orientation
    eul=euler_from_quaternion([ori.x,ori.y,ori.z,ori.w])
    # print(eul[2])
    msg=Float32()
    msg.data=eul[2]
    theta_publisher.publish(msg)
    r.sleep()


from edgetpu.detection.engine import DetectionEngine
from imutils.video import VideoStream
from PIL import Image
import argparse
import imutils
import time
import cv2
import random
import numpy as np

def dialogBox(title, text, width=200, height=130):
    img = np.zeros((height, width, 3), np.uint8)
    img[:,0:width] = (100, 100, 200)
    cv2.putText(img, text, (0, height//2), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (10,10,10), 2)
    cv2.imshow(title, img)
    cv2.waitKey(0)

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", default="mobilenet_ssd_v2/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite", help="path to TensorFlow Lite object detection model")
ap.add_argument("-l", "--labels", default="mobilenet_ssd_v2/coco_labels.txt", help="path to labels file")
ap.add_argument("-c", "--confidence", type=float, default=0.35, help="minimum probability to filter weak detections")
ap.add_argument("-w", "--width", type=int, default=700, help="width of frame")
args = vars(ap.parse_args())

print("[INFO] parsing class labels...")
labels = {}

for row in open(args["labels"]):
        # unpack the row and update the labels dictionary
        (classID, label) = row.strip().split(maxsplit=1)
        labels[int(classID)] = label.strip()

print("[INFO] loading Coral model...")
model = DetectionEngine(args["model"])

print("[INFO] starting video stream...")

try:
        vs = VideoStream(src=0)
        testVar = imutils.resize(vs.start().read(), width=args["width"])
except Exception as e:
        dialogBox("Error", str(e), width=1000)
        quit()
else:
    vs = vs.start()

def updateThreshold(x):
        args["confidence"] = x/100

def updateSize(x):
    args["width"] = x if x > 100 else 100

cv2.namedWindow("Controls", cv2.WINDOW_NORMAL)
cv2.createTrackbar("Threshold", 'Controls', int(args['confidence']*100), 100,  updateThreshold)
cv2.createTrackbar("Size", 'Controls', int(args['width']),  1000,  updateSize)

def drawFrame():
        frame = vs.read()
        frame = imutils.resize(frame, width=args["width"])
        frame = cv2.flip(frame, 1)
        orig = frame.copy()

        # prepare the frame for object detection by converting (1) it
        # from BGR to RGB channel ordering and then (2) from a NumPy
        # array to PIL image format
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame = Image.fromarray(frame)

        #start = time.time()
        results = model.DetectWithImage(frame, threshold=args["confidence"],
                keep_aspect_ratio=True, relative_coord=False)
        #end = time.time()

        # loop over the results
        for r in results:
                # extract the bounding box and box and predicted class label
                box = r.bounding_box.flatten().astype("int")
                (startX, startY, endX, endY) = box
                label = labels[r.label_id]

                # draw the bounding box and label on the image
                colour = (0, 255*r.score, 255*(1-r.score))
                cv2.rectangle(orig, (startX, startY), (endX, endY), colour, 2)
                y = startY - 15 if startY - 15 > 15 else startY + 15
                text = f"{label}: {int(r.score * 100)}%"
                cv2.putText(orig, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, colour, 2)

        thresh = args['confidence']
        cv2.putText(orig, f"{int(thresh*100)}% Threshold", (args["width"]-130, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255*thresh, 255*(1-thresh)), 2)

        #update the window
        cv2.imshow("Image Recognition", orig)

def close():
        # do a bit of cleanup
        cv2.destroyAllWindows()
        vs.stop()
        dialogBox("Quitting", "Goodbye!")

#draw loop
global looping
looping = True

while looping:
        drawFrame()

        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
                print("[INFO] quitting")
                looping = False
                close()


from safetensors import safe_open
from diffusers import StableDiffusionPipeline
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
from diffusers.models import AutoencoderKL
import os

def mix_pipeline_safetensors():
    pipeline_1_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Chilloutmix-Ni"
    pipeline_2_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/uberRealisticPornMerge_urpmv12"

    #Return a CheckpointMergerPipeline class that allows you to merge checkpoints.
    #The checkpoint passed here is ignored. But still pass one of the checkpoints you plan to
    #merge for convenience
    # pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger")

    #There are multiple possible scenarios:
    #The pipeline with the merged checkpoints is returned in all the scenarios

    #Compatible checkpoints a.k.a matched model_index.json files. Ignores the meta attributes in model_index.json during comparision.( attrs with _ as prefix )
    # merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","CompVis/stable-diffusion-v1-2"], interp = "sigmoid", alpha = 0.4)

    #Incompatible checkpoints in model_index.json but merge might be possible. Use force = True to ignore model_index.json compatibility
    # merged_pipe_1 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion"], force = True, interp = "sigmoid", alpha = 0.4)

    #Three checkpoint merging. Only "add_difference" method actually works on all three checkpoints. Using any other options will ignore the 3rd checkpoint.
    # merged_pipe_2 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion","prompthero/openjourney"], force = True, interp = "add_difference", alpha = 0.4)

    # prompt = "An astronaut riding a horse on Mars"

    # image = merged_pipe(prompt).images[0]

    pipe = DiffusionPipeline.from_pretrained(pipeline_2_path, custom_pipeline="checkpoint_merger")
    merged_pipe = pipe.merge([pipeline_2_path, pipeline_1_path], interp="sigmoid", alpha=0.7)

def is_int(d):
    try:
        d = int(d)
        return True
    except Exception as e:
        return False

def add_lora(lora_path, pipe, lora_weight=0.5):
    tensors = {}
    with safe_open(lora_path, framework="pt", device="cpu") as f:
        for key in f.keys():
            tensors[key] = f.get_tensor(key).to('cuda')

    for k_lora, v_lora in tensors.items():
        if k_lora.startswith('lora_te'):
            model = pipe.text_encoder
            # continue
        elif k_lora.startswith('lora_unet'):
            model = pipe.unet
        else:
            print(k_lora)

        # down 跳过
        if '.lora_down.' in k_lora:
            print('lora_down')
            continue
        if '.alpha' in k_lora:
            print('alpha')
            continue
        print('lora_up')

        k_lora_name = k_lora.split('.')[0]
        attr_name_list = k_lora_name.split('_')
        cur_attr = model
        latest_attr_name = ''
        for idx in range(2, len(attr_name_list)):
            attr_name = attr_name_list[idx]
            if is_int(attr_name):
                cur_attr = cur_attr[int(attr_name)]
                latest_attr_name = ''
            else:
                try:
                    if latest_attr_name != '':
                        cur_attr = cur_attr.__getattr__(f"{latest_attr_name}_{attr_name}")
                    else:
                        cur_attr = cur_attr.__getattr__(attr_name)
                    latest_attr_name = ''
                except Exception as e:
                    if latest_attr_name != '':
                        latest_attr_name = f"{latest_attr_name}_{attr_name}"
                    else:
                        latest_attr_name = attr_name

        w = cur_attr.weight
        up_w = v_lora
        down_w = tensors[k_lora.replace('.lora_up.', '.lora_down.')]
        print(down_w.shape, up_w.shape, w.shape)
        try:
            alpha_key = k_lora_name + '.alpha'
            alpha_w = tensors[alpha_key]
            wight = alpha_w / up_w.shape[1]
            print(alpha_w, wight)
        except Exception as e:
            wight = 1

        einsum_a = f"ijabcdefg"
        einsum_b = f"jkabcdefg"
        einsum_res = f"ikabcdefg"
        length_shape = len(up_w.shape)
        einsum_str = f"{einsum_a[:length_shape]},{einsum_b[:length_shape]}->{einsum_res[:length_shape]}"
        d_w = torch.einsum(einsum_str, up_w, down_w)
        # print(d_w.shape, wight)

        # wight = 1
        cur_attr.weight.data = cur_attr.weight.data + d_w * wight * lora_weight
        print('================================= add')
    return pipe

def test_model():

    output_dir = '/share/wangqixun/workspace/tmp/tmp_6'
    os.makedirs(output_dir, exist_ok=True)

    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Chilloutmix-Ni"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/abyssorangemix2SFW_abyssorangemix2Sfw"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Midnight_Mixer_Melt"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/URPM_CM_mix"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/uberRealisticPornMerge_urpmv12"
    model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/perfectWorld_perfectWorldBakedVAE"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Midnight_Mixer_Melt"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/cheeseDaddys_35"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/abyssorangemix3AOM3_aom3a3"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/gf2_v20"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/neverendingDreamNED_bakedVae"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Anything-v4.5-vae-fp16-diffuser"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/abyssorangemix2SFW_abyssorangemix2Sfw"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/wlop_1"

    pipe = StableDiffusionPipeline.from_pretrained(
        model_id,
        torch_dtype=torch.float32,
        custom_pipeline="lpw_stable_diffusion",
    )
    pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
    # pipe.vae = AutoencoderKL.from_pretrained('/share/wangqixun/workspace/github_project/diffusers/checkpoint/stabilityai/sd-vae-ft-mse')
    pipe = pipe.to(torch.float16)
    pipe = pipe.to('cuda')
    pipe.safety_checker = None

    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/LORADilraba_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.7)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/galGadotLora_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.65)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/taiwanDollLikeness_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/koreanDollLikeness_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/fashionGirl_v35.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.66)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/gakkiAragakiYui_v2.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.65)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/asiafacemixLora300_asiafacemixPruned.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/nudify_v11.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.6)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/hipoly3DModelLora_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/makotoShinkaiSubstyles_offset.safetensors"
    # pipe = add_lora(lora_path, pipe, 1.0)
    lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/jiyeon_V30.safetensors"
    pipe = add_lora(lora_path, pipe, 0.3)

    # hiqcgbody, hiqcgface
    text = 'jiyeon2, photorealistic,realistic, solo, photorealistic, best quality, ultra high res, round hat with ribbon, short curly blonde hair, big blue eyes, sitting in a field of wildflowers, beautiful, masterpiece, best quality, extremely detailed face, perfect lighting, close up photo, best quality, ultra high res, photorealistic, ultra detailed, masterpiece, best quality, (naked: 1.5),'
    neg_text = '(worst quality:2), (low quality:2), (normal quality:2), lowres, normal quality, ((monochrome)), ((grayscale)), skin spots, acnes, skin blemishes, age spot, glans,watermark,nsfw,'
    batch_size = 2
    input_size = (512, 640)
    latents = torch.randn([batch_size, 4, input_size[1] // 8, input_size[0] // 8], device=pipe.device, dtype=torch.float16)

    for idx_img in range(0, 9, 1):
        imgs = pipe(
            text,
            latents=None,
            negative_prompt=neg_text,
            height=input_size[1],
            width=input_size[0],
            num_inference_steps=50,
            # guidance_scale=8,
            num_images_per_prompt=batch_size,
        ).images
        # imgs[0].save(f'/share/wangqixun/workspace/tmp/{idx_img:03d}.jpg')
        for idx in range(len(imgs)):
            imgs[idx].save(f'{output_dir}/{idx_img:03d}_{idx:03d}.jpg')

def merge_imgs_to_video():
    imgs_dir = '/share/wangqixun/workspace/tmp_5'
    output_video_file = '/share/wangqixun/workspace/tmp_video_1/005.mp4'
    from redpy.utils_redpy import write_video_file
    from moviepy.editor import ImageSequenceClip
    from glob import glob
    import os

    imgs = sorted(list(glob(f"{imgs_dir}/*.jpg")))
    video_clip = ImageSequenceClip(imgs, fps=1)
    os.makedirs(os.path.dirname(output_video_file), exist_ok=True)
    write_video_file(video_clip, output_video_file)

if __name__ == '__main__':
    # mix_pipeline_safetensors()
    # merge_imgs_to_video()
    pass


import requests
from bs4 import BeautifulSoup

url="https://search.naver.com/search.naver?where=nexearch&sm=tab_jum&query=%EC%BD%94%EB%A1%9C%EB%82%98"
r=requests.get(url)

soup=BeautifulSoup(r.text, "html.parser")
data=soup.select("a.news_tit")

for i in data:
    print(i.get_text())


from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import pygame
import sys
import os
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys, time

class MyWindow(QMainWindow):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setGeometry(200, 200, 300, 300)
        self.setWindowTitle("Coding with Andy!")
        self.initUI()

    def initUI(self):
        self.label = QtWidgets.QLabel(self)
        self.label.setText("My first label!")
        self.label.move(50, 50)

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("Click Me!")
        self.b1.clicked.connect(self.clicked)

    def clicked(self):
        print("Clicked button")
        #self.label.setText("you pressed the button! \n Boom!")
        #self.update()
        #self.label.repaint() # Need this to work on Mac OS
        self.hide()
        splash_screen()

    def update(self):
        self.label.adjustSize()

    def reshow_page(self):
        end_game_loop()
        self.show()

#def clicked():
#    print("clicked")

def window():
    app = QApplication(sys.argv)

    win = MyWindow()
    win.show()
    sys.exit(app.exec_())

    # Taking code to the class

    '''
    win = QMainWindow()

    win.setGeometry(200, 200, 300, 300)
    win.setWindowTitle("Coding with Andy!")

    label = QtWidgets.QLabel(win)
    label.setText("My first label!")
    label.move(50,50)

    b1 = QtWidgets.QPushButton(win)
    b1.setText("Click Me!")
    b1.clicked.connect(clicked) # Name of function with the ()
    '''

current_path = os.getcwd()
print(current_path)

app = QApplication(sys.argv)
win = MyWindow()
web = QWebEngineView()
web.load(QUrl("https://www.nintendo.co.uk/"))

#class Background(pygame.sprite.Sprite):
#    def __init__(self, image_file, location):
#        pygame.sprite.Sprite.__init__(self)  # call Sprite initializer
#        self.image = pygame.image.load(image_file)
#        self.rect = self.image.get_rect()
#        self.rect.left, self.rect.top = location

'''
pygame.init()
screen = pygame.display.set_mode((910, 607))

splash_screen_img = pygame.image.load(current_path+'/Images/artificial-intelligence-codes-developing-screen.jpg')

splash_screen_img.convert()
screen.fill([255, 255, 255])
rect = splash_screen_img.get_rect()
screen.blit(splash_screen_img, rect)

clock = pygame.time.Clock()
fps = 30

screen.fill([255, 255, 255])
rect = splash_screen_img.get_rect()
screen.blit(splash_screen_img, rect)
while True:

    pygame.display.update()
    clock.tick(fps)

clock.tick(fps)
'''

# initialize game engine
pygame.init()

#window_width = 910
#window_height = 607

animation_increment = 10
clock_tick_rate = 20

black = (0, 0, 0)
red = (200, 0, 0)
green = (0, 200, 0)

bright_red = (255, 0, 0)
bright_green = (0, 255, 0)

# Open a window
#size = (window_width, window_height)
#screen = pygame.display.set_mode(size)

# Set title to the window
pygame.display.set_caption("Hello World!")

dead = False

clock = pygame.time.Clock()
#background_image = pygame.image.load(current_path+'/Images/artificial-intelligence-codes-developing-screen.jpg').convert()
count = 0

# Creating text

def text_objects(text, font):
    text_surface = font.render(text, True, black)
    return text_surface, text_surface.get_rect()

def button(screen, msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    #print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, w, h))

        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic, (x, y, w, h))

    smallText = pygame.font.SysFont("comicsansms", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    screen.blit(textSurf, textRect)

def web_init():
    app = QApplication(sys.argv)
    web = QWebEngineView()
    web.load(QUrl("https://www.nintendo.co.uk/"))

    #########

def show_web_page():
    ###### Trying QT Web #######
    pygame.display.quit()
    reading = True
    #app, web = web_init()
    print("In show web page")
    web.show()

    while reading:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:

                # -> Figure out a better way to close the application
                #web.hide()
                #web_init()
                reading = False
                menu()
        #pygame.display.update()

def end_game_loop():
    dead = True
    window_width = 1024
    window_height = 640
    screen = set_screen_size(window_width, window_height)
    menu(screen)

dead = False

def menu(screen):
    print("In menu")
    pygame.display.set_caption("Main Menu")
    window_width = 1024
    window_height = 640
    #screen = screen_display
    screen = set_screen_size(window_width, window_height)

    count = 0
    dead = False

    background_image = pygame.image.load(
        current_path+'/Images/AI Brain.jpg').convert()
    #background_image = pygame.transform.scale(background_image, (1024,640))

    while(dead == False):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                dead = True

        screen.blit(background_image, [0, 0])

        mouse = pygame.mouse.get_pos()

        #print(mouse)

        if 150+100 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(screen, bright_green, (150, 450, 100, 50))
        else:
            pygame.draw.rect(screen, green, (150, 450, 100, 50))

        button(screen, "GO!", 150, 450, 100, 50, green, bright_green, splash_screen)
        button(screen, "Quit", 550, 450, 100, 50, red, bright_red, win.reshow_page)

        '''
        # Creating buttons
        #pygame.draw.rect(screen, (0, 255, 0), (150, 450, 100, 50))
        pygame.draw.rect(screen, (255, 0, 0), (550, 450, 100, 50)) # ('screen to place',('Colour'),(location))

        smallText = pygame.font.Font("freesansbold.ttf", 20)
        textSurf, textRect = text_objects("Button 1!", smallText)
        textRect.center = ((150+(100/2)), (450+(50/2)))
        screen.blit(textSurf, textRect)
        '''
        pygame.display.update()
        clock.tick(clock_tick_rate)
        count += 1

    pygame.display.quit()
    pygame.display.update()

def set_screen_size(width, height):
    size = (width, height)
    return pygame.display.set_mode(size)

def splash_screen():
    pygame.init()

    # Set title to the window
    pygame.display.set_caption("Hello World!")
    count = 0
    dead = False
    window_width = 910
    window_height = 607
    #size = (window_width, window_height)
    screen = set_screen_size(window_width, window_height)

    background_image = pygame.image.load(
        current_path + '/Images/artificial-intelligence-codes-developing-screen.jpg').convert()
    while(dead == False):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                dead = True

        screen.blit(background_image, [0, 0])

        pygame.display.update()
        clock.tick(clock_tick_rate)
        count += 1
        if count == 10:
            menu(screen)

#screen = set_screen_size(200, 200)

window()


import random
import torch
import torch.nn as nn
from .ffjord.train_misc import standard_normal_logprob, set_cnf_options, create_regularization_fns
from .ffjord.train_misc import get_regularization, build_model_tabular

class argument:
    def __init__(self, args, data_dims):
        assert args['layer_type'] in ["ignore", "concat", "concat_v2", "squash", "concatsquash", "concatcoord", "hyper", "blend", "blenddiv1", "blenddiv2", "simblenddiv1", "simblenddiv2"]
        self.layer_type = args['layer_type']
        assert type(args['hdim_factor']) is float
        self.hdim_factor = args['hdim_factor']
        assert type(args['nhidden']) is int
        self.nhidden = args['nhidden']
        assert type(args['num_blocks']) is int
        self.num_blocks = args['num_blocks']
        assert type(args['time_length']) is float
        self.time_length = args['time_length']
        assert args['train_T'] in [True, False]
        self.train_T = args['train_T']
        assert args['divergence_fn'] in ["brute_force", "approximate"]
        self.divergence_fn = args['divergence_fn']
        assert args['nonlinearity'] in ["sigmoid", "tanh", "relu", "softplus", "elu", "swish", "square", "identity", "tanh batchnorm", "relu batchnorm", "softplus batchnorm", "elu batchnorm", "swish batchnorm", "square batchnorm", "identity batchnorm"]
        self.nonlinearity = args['nonlinearity']
        assert args['test_solver'] in ["dopri5", "bdf", "rk4", "midpoint", 'adams', 'explicit_adams', 'fixed_adams']
        self.test_solver = args['test_solver']
        self.solver = args['solver']
        assert type(args['test_atol']) is float
        self.test_atol = args['test_atol']
        self.atol = args['atol']
        assert type(args['test_rtol']) is float
        self.test_rtol = args['test_rtol']
        self.rtol = args['rtol']
        assert type(args['step_size']) is float or args['step_size'] is None
        self.step_size = args['step_size']
        self.test_step_size = args['step_size']
        assert type(args['first_step']) is float or args['first_step'] is None
        self.first_step = args['first_step']
        self.test_first_step = args['first_step']
        assert args['residual'] in [True, False]
        self.residual = args['residual']
        assert args['rademacher'] in [True, False]
        self.rademacher = args['rademacher']
        assert args['batch_norm'] in [True, False]
        self.batch_norm = args['batch_norm']
        assert type(args['bn_lag']) is float
        self.bn_lag = args['bn_lag']
        if "adjoint" in args:
            assert type(args['adjoint']) is bool
            self.adjoint = args['adjoint']
        else:
            self.adjoint = True

        assert type(args['l1int']) is float or args['l1int'] is None
        self.l1int = args['l1int']
        assert type(args['l2int']) is float or args['l2int'] is None
        self.l2int = args['l2int']
        assert type(args['dl2int']) is float or args['dl2int'] is None
        self.dl2int = args['dl2int']
        assert type(args['JFrobint']) is float or args['JFrobint'] is None
        self.JFrobint = args['JFrobint']
        assert type(args['JdiagFrobint']) is float or args['JdiagFrobint'] is None
        self.JdiagFrobint = args['JdiagFrobint']
        assert type(args['JoffdiagFrobint']) is float or args['JoffdiagFrobint'] is None
        self.JoffdiagFrobint = args['JoffdiagFrobint']

        assert type(args['kinetic_energy']) is float or args['kinetic_energy'] is None
        self.kinetic_energy = args['kinetic_energy']
        assert type(args['jacobian_norm2']) is float or args['jacobian_norm2'] is None
        self.jacobian_norm2 = args['jacobian_norm2']
        assert type(args['total_deriv']) is float or args['total_deriv'] is None
        self.total_deriv = args['total_deriv']
        assert type(args['directional_penalty']) is float or args['directional_penalty'] is None
        self.directional_penalty = args['directional_penalty']

        if self.layer_type == "blend" and not (self.time_length == 1.0 and self.train_T == False):
            raise ValueError("!! Setting time_length from None to 1.0 due to use of Blend layers.")

        self.dims = '-'.join([str(int(self.hdim_factor * data_dims))] * self.nhidden)
        self.args = args
    def __str__(self):
        return self.args

class Generator(nn.Module):
    def __init__(self, arg, data_dim):
        super(Generator, self).__init__()
        group1 = (arg.l1int is not None) + (arg.l2int is not None) + (arg.dl2int is not None) + (arg.JFrobint is not None) + (arg.JdiagFrobint is not None) + (arg.JoffdiagFrobint is not None)
        group2 = (arg.kinetic_energy is not None) + (arg.jacobian_norm2 is not None) + (arg.total_deriv is not None) + (arg.directional_penalty is not None)
        if (group1 > 0) and (group2 > 0):
            raise ValueError("regularizer group should be selected once")
        elif (group1 > 0):
            self.mode = 1
        else:
            self.mode = 2
        arg.mode = self.mode
        self.arg = arg
        regularization_fns, self.regularization_coeffs = create_regularization_fns(arg)
        self.model = build_model_tabular(arg, data_dim, regularization_fns)

    def compute_likelihood_loss(self, data):
        zero = torch.zeros(data.shape[0], 1).to(data)

        z, delta_logp = self.model(data, zero)  # run model forward

        logpz = standard_normal_logprob(z).view(z.shape[0], -1).sum(1, keepdim=True)  # logp(z)
        logpx = logpz - delta_logp
        loss = -torch.mean(logpx)
        reg_loss = None
        if len(self.regularization_coeffs) > 0:
            reg_states = get_regularization(self.model, self.regularization_coeffs)
            reg_loss = sum(
                reg_state * coeff for reg_state, coeff in zip(reg_states, self.regularization_coeffs) if coeff != 0
            )
            reg_loss = torch.abs(reg_loss).mean()
        return loss, reg_loss

    def forward(self, z):
        zero = torch.zeros(z.shape[0], 1).to(z)
        x = self.model(z, zero, reverse=True)  # run model Backward
        return x[0]

    def restore_model(self, model, filename):
        checkpt = torch.load(filename, map_location=lambda storage, loc: storage)
        self.model.load_state_dict(checkpt["state_dict"])
        set_cnf_options(self.arg, self.model)
        return model


import dash
import dash_daq as daq
import sys
import pandas as pd
from dash import html
import dash_bootstrap_components as dbc
import datetime
import plotly

sys.path.insert(1,'./pages')
import utilidadesVarias as uv

dash.register_page(__name__)

layout = html.Div(children=[
    html.H1(children='MME Page'),
    html.H5(id='latestUpdated_MME'),
    dash.dcc.Tabs(id="MME-tabs", value='basicView', children=[
        dash.dcc.Tab(label='Basic view', value='basicView', children=[
            dash.html.Div(id='basicTab_MME',children=[
                dash.dcc.Interval(id='interval-component_MME', interval=1000, n_intervals=0),
                dash.html.Div(id='placeholder', style={'display':'none'}),
                dash.html.Div(className='card_container', children=[
                    dash.html.Div(id='cpu_card_MME',className='infoCard', children=[
                        dash.html.H3('CPU Usage'),
                        dash.html.H4(f"Latest measurements"),
                        dash.html.Div(children=[
                            dash.html.Div(children=[
                                dash.html.Div(children=[
                                    dash.html.H6('Mean ratio of the CPU usage(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"green":[0,40], "yellow":[40,80], "red": [80,100]}},
                                        # value=thisWeekKPIs_MME['Mean ratio of the CPU usage'].iloc[-1],
                                        value=0,
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='mean_ratio_of_the_CPU_usage',
                                        ),
                                ], className='gaugeDiv'),
                                dash.html.Div(children=[
                                    dash.html.H6('Peak load of main processor(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"green":[0,40], "yellow":[40,80], "red": [80,100]}},
                                        # value=thisWeekKPIs_MME['Peak load of CPU usage of the main processor'].iloc[-1],
                                        value=0,
                                        units='%',
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='peak_load_of_CPU_usage_of_the_main_processor_MME'
                                        ),
                                ], className='gaugeDiv'),
                                ], className='gaugeContainer'),
                            dash.html.Br(),
                            dash.html.H4('Week summary'),
                            dash.html.Div(children=[
                                dash.html.H5('Peak load of CPU(%)'),
                                dash.dcc.Graph(id='daily_cpu_usage_MME', figure={}, config={'displayModeBar':False, 'responsive':True, 'scrollZoom': True}),
                            ], className='figureContainer')

                            ], className='infoCardDataContainer')
                    ]),

                    dash.html.Div(id='bearer_card_MME',className='infoCard', children=[
                        dash.html.H3('Bearer Usage'),
                        dash.html.H4(f"Latest measurements"),
                        dash.html.Div(children=[
                            dash.html.Div(children=[
                                dash.html.Div(children=[
                                    dash.html.H6('Successful rate of bearer activation(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"red":[0,40], "yellow":[40,80], "green": [80,100]}},
                                        value=0,
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='successful_rate_of_bearer_activation'
                                        ),
                                ], className='gaugeDiv'),
                                dash.html.Div(children=[
                                    dash.html.H6('Successful rate of dedicated bearer activation(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"red":[0,40], "yellow":[40,80], "green": [80,100]}},
                                        value=0,
                                        units='%',
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='successful_rate_of_dedicated_bearer_activation',
                                        ),
                                ], className='gaugeDiv'),
                                dash.html.Div(children=[
                                    dash.html.H6('Successful rate of EPS bearer modification(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"red":[0,40], "yellow":[40,80], "green": [80,100]}},
                                        value=0,
                                        units='%',
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='successful_rate_of_EPS_bearer_modification'
                                        ),
                                ], className='gaugeDiv'),
                                ], className='gaugeContainer'),

                            dash.html.Br(),
                            dash.html.H4('Week summary'),
                            dash.html.Div(children=[
                                dash.html.H5('Bearer activation/setup time'),
                                dbc.ListGroup(children=[
                                ], id='bearerInfo_MME'),
                            ]),

                            dash.html.Br(),
                            dash.html.Div(children=[
                                dash.html.H5('Successful rate of bearer activation(%)'),
                                dash.dcc.Graph(id='daily_bearer_usage', figure={}, config={'displayModeBar':False, 'responsive':True, 'scrollZoom': True}),
                            ], className='figureContainer'),

                            ], className='infoCardDataContainer')
                    ]),

                    dash.html.Div(id='eps_card_MME',className='infoCard', children=[
                        dash.html.H3('EPS'),
                        dash.html.H4(f"Latest measurements"),
                        dash.html.Div(children=[
                            dash.html.Div(children=[
                                dash.html.Div(children=[
                                    dash.html.H6('Successful rate of EPS Paging(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"red":[0,40], "yellow":[40,80], "green": [80,100]}},
                                        value=0,
                                        units='%',
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='successful_rate_of_EPS_Paging'
                                        ),
                                ], className='gaugeDiv'),
                                dash.html.Div(children=[
                                    dash.html.H6('Successful rate of EPS attach(%)'),
                                    daq.Gauge(
                                        color={"gradient":True, "ranges":{"red":[0,40], "yellow":[40,80], "green": [80,100]}},
                                        value=0,
                                        units='%',
                                        max=100,  # TODO: Averiguar cual es el máximo de este KPI
                                        min=0,
                                        size=100,
                                        id='successful_rate_of_EPS_attach'
                                        ),
                                ], className='gaugeDiv'),
                                ], className='gaugeContainer'),

                            dash.html.Br(),
                            dash.html.H4('Week summary'),
                            dash.html.Div(children=[
                                dash.html.H5('Successful rate of EPS Paging(%)'),
                                dash.dcc.Graph(id='daily_eps_usage_paging', figure={}, config={'displayModeBar':False, 'responsive':True, 'scrollZoom': True}),
                            ], className='figureContainer'),

                            dash.html.Div(children=[
                                dash.html.H5('Successful rate of EPS attach(%)'),
                                dash.dcc.Graph(id='daily_eps_usage', figure={}, config={'displayModeBar':False, 'responsive':True, 'scrollZoom': True}),
                            ], className='figureContainer'),

                            ], className='infoCardDataContainer')
                    ]),

                    ]),
                ])
            ]),
        dash.dcc.Tab(label='Advanced view', value='advancedView', id='advancedTabGraphTab_MME',children=[
            html.Div(id='advancedTab_MME', children=[
                html.Div(children=[
                    dash.html.H5('Selected KPIs'),
                    dash.dcc.Dropdown(multi=True, id='kpiSelector_MME', placeholder="Select a KPI"),
                    dash.html.Br(),
                    dash.html.H5('Date range selector'),
                    dash.dcc.DatePickerRange(
                        id='dateRange_MME',
                        initial_visible_month=datetime.datetime.now(),
                        start_date=datetime.datetime.today() - datetime.timedelta(days=30),
                        end_date=datetime.datetime.now().date() + datetime.timedelta(days=1),
                        ),
                    dash.html.Br(),
                    dash.html.Div(className='graphsContainer',children=[
                        dash.dcc.Graph(
                            id='advancedTabGraph_MME',
                            figure={
                                'data':[{
                                    'type':'line'
                                    }],
                                'layout': {
                                    'margin':{'t':50, 'r':0},
                                    }
                                }
                            ),
                        dash.dcc.Graph(
                            id='dailyGraph_MME',
                            figure={
                                'data':[{
                                    'type':'line'
                                    }],
                                'layout': {'margin':{'t':50, 'r':0}}
                                })
                        ]),
                    dash.html.Label('Statistical information'),
                    dash.dcc.Checklist(options=['std'], id='metricsCheckList_MME', value=[]),
                    ]),
                html.Div(id='statsContainer_MME'),
                ]),
            ]),
        ]),
    ])

# Callbacks para los widgets
widgetDic = {
    'mean_ratio_of_the_CPU_usage':'Mean ratio of the CPU usage',
    'peak_load_of_CPU_usage_of_the_main_processor_MME':'Peak load of CPU usage of the main processor',
    'successful_rate_of_bearer_activation':'Successful rate of bearer activation',
    'successful_rate_of_dedicated_bearer_activation':'Successful rate of dedicated bearer activation',
    'successful_rate_of_EPS_bearer_modification':'Successful rate of EPS bearer modification',
    'successful_rate_of_EPS_Paging':'Successful rate of EPS Paging',
    'successful_rate_of_EPS_attach':'Successful rate of EPS attach',
}

for index, key in enumerate(widgetDic.keys()):
        dash.callback(
            dash.Output(key, 'value'),
            dash.Input('MMEMemory', 'data'),
        )(uv.widgetCBGen(widgetDic, key))

# Generacion de los callbacks para las listas
@dash.callback(
    dash.Output('bearerInfo_MME', 'children'),
    dash.Input('MMEMemory', 'data'),
)
def bearerInfoList_CB(kpiData):
    kpiDF = pd.read_json(kpiData)
    kpiDF['Start Time']= pd.to_datetime(kpiDF['Start Time']).dt.tz_localize(None)
    kpiDF['End Time']= pd.to_datetime(kpiDF['End Time']).dt.tz_localize(None)
    thisWeekKPIs = kpiDF[kpiDF['Start Time'] >= (datetime.datetime.now() - datetime.timedelta(days=7))]
    content = []

    content.append(dbc.ListGroupItem("Mean of bearer activation time(ms): " + str(thisWeekKPIs['Mean of bearer activation time'].max())))
    content.append(dbc.ListGroupItem("Mean of dedicated bearer set-up time(ms): " + str(thisWeekKPIs['Mean of dedicated bearer set-up time'].max())))

    return content

# Callbacks para el advancedView
## Refrescado del grafico primario
dash.callback(
        dash.Output('advancedTabGraph_MME', 'figure'),
        dash.Input('dateRange_MME', 'start_date'),
        dash.Input('dateRange_MME', 'end_date'),
        dash.Input('kpiSelector_MME', 'value'),
        dash.Input('metricsCheckList_MME', 'value'),
        dash.Input('MMEMemory', 'data'),
        )(uv.dateChangeCBGen())

## Refrescado del grafico secundario
dash.callback(
        dash.Output('dailyGraph_MME', 'figure'),
        dash.Input('advancedTabGraph_MME', 'clickData'),
        dash.State('advancedTabGraph_MME', 'figure'),
        dash.Input('kpiSelector_MME', 'value'),
        dash.Input('MMEMemory', 'data'),
        )(uv.clickedDatapointCBGen('advancedTabGraph_MME.clickData'))

# Refrescado del grafico de las tarjetas del basicView
## Tarjeta para el uso de CPU
dash.callback(
                dash.Output('daily_cpu_usage_MME', 'figure'),
                dash.Input('daily_cpu_usage_MME', 'figure'),
                dash.Input('daily_cpu_usage_MME', 'clickData'),
                dash.Input('MMEMemory', 'data'),
                )(uv.basicViewGraphCBGenerator('Peak load of CPU usage of the main processor', 'daily_cpu_usage_MME.clickData'))

## Tarjeta para el uso de memoria
dash.callback(
                dash.Output('daily_bearer_usage', 'figure'),
                dash.Input('daily_bearer_usage', 'figure'),
                dash.Input('daily_bearer_usage', 'clickData'),
                dash.Input('MMEMemory', 'data'),
                )(uv.basicViewGraphCBGenerator('Successful rate of bearer activation', 'daily_bearer_usage.clickData'))

## Tarjeta para el uso de EPS
dash.callback(
                dash.Output('daily_eps_usage', 'figure'),
                dash.Input('daily_eps_usage', 'figure'),
                dash.Input('daily_eps_usage', 'clickData'),
                dash.Input('MMEMemory', 'data'),
                )(uv.basicViewGraphCBGenerator('Successful rate of EPS attach', 'daily_eps_usage.clickData'))
dash.callback(
                dash.Output('daily_eps_usage_paging', 'figure'),
                dash.Input('daily_eps_usage_paging', 'figure'),
                dash.Input('daily_eps_usage_paging', 'clickData'),
                dash.Input('MMEMemory', 'data'),
                )(uv.basicViewGraphCBGenerator('Successful rate of EPS Paging', 'daily_eps_usage_paging.clickData'))

dash.callback(
    dash.Output('kpiSelector_MME', 'options'),
    dash.Output('kpiSelector_MME', 'value'),
    dash.Input('MMEMemory', 'data'),
)(uv.selectorValueLoader)


import requests
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
from csv import writer

def append_list_as_row(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)
        write_obj.close()

req = Request('https://academic.oup.com/journals/search-results?page=1&q=data+mining&SearchSourceType=1&allJournals=1', headers={'User-Agent': 'Mozilla/5.0'})
page = urlopen(req).read()
soup = BeautifulSoup(page, 'html.parser')

#print(page.status_code)
title=[] #List to store title of the article
author_complete=[] #List to store all the author names
year=[] #List to store published year
link = [] # List to store link of the title
result = soup.find('div',{'id' : 'main'})
if result is not None:
    jobs = result.find_all('div',class_='sr-list al-article-box al-normal clearfix')
    for job in jobs:
        t = job.find('h4',class_='sri-title customLink al-title')
        li = job.find('a',{'class':'article-link'})
        if None in (t,link):
            continue
        title.append(t.text.strip())
        link.append(li.get('href'))
        writter = job.find('div',class_='sri-authors al-authors-list')
        author_complete.append(writter.text.strip())
        date = job.find('div',class_='sri-date al-pub-date')
        year.append(date.text.strip())

for i in range(len(title)):
    yr = year[i].split(':')
    lst = [title[i],link[i],yr[1],author_complete[i]]
    append_list_as_row('knimbus_oxford.csv',lst)


import torch.nn as nn

from utils import ConvolutionalBlock, Downscaling, Upscaling

class UNet(nn.Module):
    """
    Implementation of the UNet network architecture. This is a modification of the
    network proposed https://arxiv.org/pdf/1505.04597.pdf in the context of
    semantic segmentation.

    This implementation is adapted to work as a surrogate model for simulating
    fluid flow against an airfoil depending on the airfoil's shape.

    :params:
    n_channels (int): number of channels in the input data.
    output_dim (int): dimension of the network's output.
    """

    def __init__(self, n_channels: int = 1, output_dim: int = 3):

        super(UNet, self).__init__()

        self.n_channels = n_channels
        self.output_dim = output_dim

        self.input_conv = ConvolutionalBlock(n_channels, 16)
        self.downscaling_1 = Downscaling(16, 32)
        self.downscaling_2 = Downscaling(32, 64)
        self.downscaling_3 = Downscaling(64, 128)
        self.downscaling_4 = Downscaling(128, 256)
        self.upscaling_1 = Upscaling(256, 128)
        self.upscaling_2 = Upscaling(128, 64)
        self.upscaling_3 = Upscaling(64, 32)
        self.upscaling_4 = Upscaling(32, 16)
        self.output_conv = nn.Conv2d(16, self.output_dim, kernel_size=1)

    def forward(self, x):

        # Downscaling part of UNet
        x1 = self.input_conv(x)
        x2 = self.downscaling_1(x1)
        x3 = self.downscaling_2(x2)
        x4 = self.downscaling_3(x3)
        x5 = self.downscaling_4(x4)

        # Upscaling part of UNet
        x6 = self.upscaling_1(x5, x4)
        x7 = self.upscaling_2(x6, x3)
        x8 = self.upscaling_3(x7, x2)
        x9 = self.upscaling_4(x8, x1)
        x10 = self.output_conv(x9)

        output = x10 * (1 - x)

        return output


from typing import List

class Solution:
    def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
        # sort the list by start time
        # then traverse linearly
        intervals = sorted(intervals, key=lambda s: (s[0], -s[1]))
        print(intervals)
        count = 0
        prev = -1

        # since all intervals are sorted by earliest start and latest end,
        # the interval that comes before must be able to covered the next
        # as long as the end time of the earlier is later than the end time
        # of the next

        for int in intervals:
            if int[1] > prev:
                # Only count ones that aren't covered
                prev = int[1]
                count += 1

        return count

sol = Solution()
intervals = [[3, 10], [4, 10], [5, 11]]

print(sol.removeCoveredIntervals(intervals))


import sys
from scipy.ndimage import gaussian_filter1d

num_1 = sys.argv[1]
num_2 = sys.argv[2]
num_3 = sys.argv[3]

out_1 = gaussian_filter1d([1, 2, 3], 3)

print(out_1)


from django.urls import path, include
from django.conf.urls import url

from rest_framework.routers import DefaultRouter

from .views import *

router = DefaultRouter()
router.register('', ProductViewSet)
# router.register('', CreateComment)

urlpatterns = [
    path('categories/', CategoriesList.as_view()),
    path('', include(router.urls)),
    path('comments/create/', CreateComment.as_view()),
    path('comments/<int:pk>/', CommentViewSet.as_view({
        "get": "retrieve",
        "path": "partial_update",
        "put": "update",
        "delete": "destroy"}))
]


#!/usr/bin/env python

from Bio import SeqIO
import sys
import os
import csv

usage = 'python filter_by_b6.py align_R1.b6 align_R2.b6 orig_R1.fastq orig_R2.fastq filtered_prefix'

# Will add '_R1' and '_R2' to the end of the filtered prefix

if len(sys.argv) < 5:
	print('You must supply the R1 and R2 alignment files, original FASTQs, and a prefix for the filtered output\n\n%s\n' % usage)
	sys.exit()

inb6_R1 = sys.argv[1]
inb6_R2 = sys.argv[2]
infastq_R1 = sys.argv[3]
infastq_R2 = sys.argv[4]
outfq = sys.argv[5]

host_read_ids = []
with open(inb6_R1, 'r') as inf1, open(inb6_R2, 'r') as inf2:
	tabreader1 = csv.reader(inf1, delimiter='\t')
	for line in tabreader1:
		read_id = str(line[0])
#		print(read_id)
		host_read_ids.append(read_id)
	tabreader2 = csv.reader(inf2, delimiter='\t')
	for line in tabreader2:
		read_id = str(line[0])
		host_read_ids.append(read_id)
host_read_set = set(host_read_ids)
print('\n...filtering %s read pairs from FASTQ files...\n' % len(host_read_set))
# Filter the FASTQs to exclude reads from either b6 files (to maintain paired reads)
outfq1 = '_'.join([outfq, 'R1.fastq'])
outfq2 = '_'.join([outfq, 'R2.fastq'])
with open(outfq1, 'w') as outf1, open(infastq_R1, 'r') as infq1:
#	keep_seqs1 = [record for record in SeqIO.parse(infq1, 'fastq') if str(record.id).split(' ')[0] not in host_read_set]
#	SeqIO.write(keep_seqs1, outf1, 'fastq')
	# Previous two lines work the same as below line but consume massive RAM
	[SeqIO.write(record, outf1, 'fastq') for record in SeqIO.parse(infq1, 'fastq') if str(record.id).split(' ')[0] not in host_read_set]
with open(outfq2, 'w') as outf2, open(infastq_R2, 'r') as infq2:
#	keep_seqs2 = [record for record in SeqIO.parse(infq2, 'fastq') if str(record.id).split(' ')[0] not in host_read_set]
#	SeqIO.write(keep_seqs2, outf2, 'fastq')
	# Previous two lines work the same as below line but consume massive RAM
	[SeqIO.write(record, outf2, 'fastq') for record in SeqIO.parse(infq2, 'fastq') if str(record.id).split(' ')[0] not in host_read_set]


import  os
import  sys

import barcode
from barcode.writer import ImageWriter

# Importing inner modules, so that it works as a module and as a program
try:
    from . import LogProvider  as	log_provider
except:
    import LogProvider  as	log_provider

def __create(barcode_type, data, file_path):
    """__create is a private method which creates a 'PNG' image of a barcode with the given data
        on the specified file_path

    Arguments:
        barcode_type {str} -- A valid barcode type eg. EAN13
        data {str} -- A valid data based on barcode type
        file_path {str} -- A vavlid path where the image has to be stored
    """

    try:
        barcode_class = barcode.get_barcode_class(barcode_type)
        barcode_object = barcode_class(repr(data), writer = ImageWriter())
        barcode_object.save(filename=file_path)
    except Exception as ex:
        process_data.message = 'Exception in __create - ' + str(ex)
        log_provider.insert_error_log(process_data)

def createBarcode(data = None, file_path = None, barcode_type = None, is_folder = False):
    """createBarcode will create a barcode image method which creates a 'PNG' image of a barcode with the given data
        on the specified file_path

    Keyword Arguments:
        data {str} -- A valid data based on barcode type
        file_path {str} -- A vavlid path where the image has to be stored
        barcode_type {str} -- A valid barcode type eg. EAN13
        is_folder {bool} -- Specifies whether the given path is a folder, used for manual overriding (default: {False})

    Returns:
        ProcessData -- ProcessData used for interprocess communication
    """

    ALL_PROVIDED_BARCODES = barcode.PROVIDED_BARCODES
    process_data.message = 'Error'
    process_data.status = -1
    process_data.data = data, file_path, barcode_type
    can_skip = False
    if(file_path):
        file_name, extension = os.path.splitext(os.path.basename(file_path))
    else:
        process_data.message = 'Exception in Writing - No file_path provided'
        log_provider.insert_error_log(process_data)
        return process_data
    if(not data):
        process_data.message = 'Exception in Writing - No Data provided'
        log_provider.insert_error_log(process_data)
        return process_data
    if(barcode_type):
       ALL_PROVIDED_BARCODES.clear()
       ALL_PROVIDED_BARCODES.append(barcode_type)
    else:
        if(not file_path):
            return process_data
    try:
        if(not is_folder):
            if(barcode_type):
                __create(barcode_type= barcode_type, data= data, file_path= file_path)
            else:
                can_skip = True
                for CURRENT_BARCODE in ALL_PROVIDED_BARCODES:
                    file_path = os.path.join(file_path, CURRENT_BARCODE)
                    __create(barcode_type= barcode_type, data= data, file_path= file_path)
        elif(not extension):
            process_data.message = 'Exception in Writing - No extension is provided for folder'
            log_provider.insert_error_log(process_data)
            return process_data
        else:
            if(barcode_type):
                file_path = os.path.join(file_path, barcode_type)
                __create(barcode_type= barcode_type, data= data, file_path= file_path)
    except Exception as e:
        if(not can_skip):
            process_data.message = 'Exception in Writing ' + str(e)
            log_provider.insert_error_log(process_data)
            print('Writer Exception for image ' + file_path)
            input()
            return process_data

    process_data.status = 1
    process_data.message = 'Success'
    process_data.data = file_path
    return process_data

# The Actual Module Code
try:
    bot_name, extention =   os.path.splitext(os.path.basename(__file__))
    process_data        =   log_provider.generate_process_data(bot_name)
    # Import safety block - createbarcode(), only when run as a script
    if(__name__ == '__main__'):
        createBarcode(file_path = 'D:\\Guru\\TEST_FOLDERS\\Barcode\\sample', barcode_type = 'EAN')

except Exception as exception:
	log_provider.insert_log(process_data)
	process_data.message  = '@ BarcodeWriter - ' + format(exception)
	log_provider.insert_error_log(process_data)


import numpy as np
import os
from sklearn.datasets import fetch_openml
import matplotlib.pyplot as plt

# Create the directory for output images
directory = './fig/'
if not os.path.isdir(directory):
    os.makedirs(directory)

# Fetch the datasets from openml
mnist = fetch_openml('mnist_784')

"""
Part1: PCA
Q2. ~ Q4.
"""
# Q2.
# Obtain the indices of all "5".
indices = np.where(mnist['target'].to_numpy() == '5')[0]
data_5 = mnist['data'].to_numpy()[indices]
mean_5 = np.mean(data_5, axis=0)
# Transpose the dataset to the form: X = [x1, x2, x3, ..., xN]
data_5_centered = (data_5 - mean_5).T
# Calculate the covariance matrix
covariance_mat = np.cov(data_5_centered)
# Calculate eigenvalue and eigenvector
eigen_val, eigen_vec = np.linalg.eig(covariance_mat)
# Eigenvector with each rows
eigen_vec = eigen_vec.T
# Sorting the eigenvector by its eigenvalue in descending order.
eigen_val_des = eigen_val[np.argsort(eigen_val)[::-1]]
eigen_vec_des = eigen_vec[np.argsort(eigen_val)[::-1]]
# Show the first 3 largest eigenvectors.
fig = plt.figure(figsize=(9, 3))
for i in range(3):
    plt.subplot(131 + i)
    plt.imshow((eigen_vec_des[i]).real.reshape(28, 28), 'gray')
    plt.title("λ = {0}".format(eigen_val_des[i].real))
    plt.axis('off')
plt.savefig(os.path.join(directory, 'Q2.png'))

# Q3.
origin_first_5 = data_5[0]
origin_first_5_mean = origin_first_5 - mean_5
images_5 = [origin_first_5]
bases = [3, 10, 30, 100]
fig = plt.figure(figsize=(15, 3))
plt.subplot(151)
plt.imshow(origin_first_5.reshape(28, 28), 'gray')
plt.title('Original 5')
plt.axis('off')
for i, n in enumerate(bases):
    plt.subplot(152 + i)
    # Obtain the first n largest eigenvectors and corresponding coefficients.
    eigen_vec_des_top_n = eigen_vec_des[:n]
    coef_5_top_n = np.dot(eigen_vec_des_top_n, origin_first_5_mean)
    # Reconstruct the signal by the eigenvectors.
    reconstruct_n_base = np.dot(eigen_vec_des_top_n.T, coef_5_top_n)
    plt.imshow((reconstruct_n_base + mean_5).real.reshape(28, 28), 'gray')
    plt.title("5 with {0}d".format(n))
    plt.axis('off')
plt.savefig(os.path.join(directory, 'Q3.png'))

# Q4.
first_10000_target = mnist['target'].to_numpy()[:10000]
first_10000_data = mnist['data'].to_numpy()[:10000]
# Obtain the indices of all "1", "3", "6".
indices = np.where((first_10000_target == '1') | (first_10000_target == '3') | (first_10000_target == '6'))[0]
data = first_10000_data[indices]
mean = np.mean(data, axis=0)
# Transpose the dataset to the form: X = [x1, x2, x3, ..., xN]
data_centered = (data - mean).T
# Calculate eigenvalue and eigenvector
covariance_mat = np.cov(data_centered)
# Calculate eigenvalue and eigenvector
eigen_val, eigen_vec = np.linalg.eig(covariance_mat)
# Eigenvector with each rows
eigen_vec = eigen_vec.T
# Sorting the eigenvector by its eigenvalue in descending order.
eigen_val_des = eigen_val[np.argsort(eigen_val)[::-1]]
eigen_vec_des = eigen_vec[np.argsort(eigen_val)[::-1]]
# Store the projection points (x, y) to the first 2 largest eigenvectors.
points_x = {'1': [], '3': [], '6': []}
points_y = {'1': [], '3': [], '6': []}
colors = {'1': 'r', '3': 'g', '6': 'b'}
for i, dc in enumerate(data_centered.T):
    eigen_vec_des_top_2 = eigen_vec_des[:2]
    coef_top_2 = np.dot(eigen_vec_des_top_2, dc)
    points_x[first_10000_target[indices][i]].append(coef_top_2[0].real)
    points_y[first_10000_target[indices][i]].append(coef_top_2[1].real)
fig = plt.figure(figsize=(6, 4))
for key,values in colors.items():
    plt.scatter(points_x[key], points_y[key], color=values, label=key)
plt.legend()
plt.savefig(os.path.join(directory, 'Q4.png'))

"""
Part2: OMP
Q5. ~ Q6.
"""
# Q5.
# Obtain training basis(pre-normalized)
basis = mnist['data'].to_numpy()[:10000]
length = np.linalg.norm(basis, axis=1)
basis = (basis.T / length).T
# Define the sparsity is 5.
sparsity = 5
origin_signal = mnist['data'].to_numpy()[10000]
# Bases and coefficients we choose.
sparse_basis, coefficients = [], []
# Residual sidgnal equals to original signal(Need deep copy)
residue_signal = origin_signal.copy()
for k in range(sparsity):
    max_product, max_base, max_index = 0, [], 0
    # Find the base vector that cause maximum product with residual signal.
    for i, base in enumerate(basis):
        product = abs(np.dot(base, residue_signal))
        if product > max_product:
            max_product, max_base, max_index = product, base, i
    # Calculate the coefficient vector by the pseudo inerse: (M^T*M)^(-1)M^T*x
    sparse_basis.append(max_base)
    M = np.array(sparse_basis).T
    pseudo_inverse = np.linalg.pinv(M.T @ M)
    coefficients = (pseudo_inverse @ M.T) @ origin_signal
    # Update residual signal.
    residue_signal = origin_signal - (M @ coefficients)
    # Delete the basis we choose.
    basis = np.delete(basis, max_index, axis=0)
# Show the first 5 largest bases we choose.
fig = plt.figure(figsize=(15, 3))
for i, base in enumerate(sparse_basis):
    plt.subplot(151 + i)
    plt.imshow(base.reshape(28, 28), 'gray')
    plt.title("Base {0}".format(i + 1))
    plt.axis('off')
plt.savefig(os.path.join(directory, 'Q5.png'))

# Q6.
origin_signal = mnist['data'].to_numpy()[10001]
# Define the sparsity is 5, 10, 40 and 200.
sparsity = [5, 10, 40, 200]
fig = plt.figure(figsize=(15, 3))
plt.subplot(151)
plt.imshow(origin_signal.reshape(28, 28), 'gray')
plt.title('L-2=0')
plt.axis('off')
for index, s in enumerate(sparsity):
    # Obtain training basis(pre-normalized)
    basis = mnist['data'].to_numpy()[:10000]
    length = np.linalg.norm(basis, axis=1)
    basis = (basis.T / length).T
    # Bases and coefficients we choose.
    sparse_basis, coefficients = [], []
    # Residual sidgnal equals to original signal(Need deep copy)
    residue_signal = origin_signal.copy()
    for k in range(s):
        max_product, max_base, max_index = 0, [], 0
        # Find the base vector that cause maximum product with residual signal.
        for i, base in enumerate(basis):
            product = abs(np.dot(base, residue_signal))
            if product > max_product:
                max_product, max_base, max_index = product, base, i
        # Calculate the coefficient vector by the pseudo inerse: (M^T*M)^(-1)M^T*x
        sparse_basis.append(max_base)
        M = np.array(sparse_basis).T
        pseudo_inverse = np.linalg.pinv(M.T @ M)
        coefficients = (pseudo_inverse @ M.T) @ origin_signal
        # Update residual signal.
        residue_signal = origin_signal - (M @ coefficients)
        # Delete the basis we choose.
        basis = np.delete(basis, max_index, axis=0)
    L2_norm = np.linalg.norm(residue_signal)
    plt.subplot(152 + index)
    plt.imshow((np.array(sparse_basis).T @ np.array(coefficients)).reshape(28, 28), 'gray')
    plt.title("L-2={0}".format(L2_norm))
    plt.axis('off')
plt.savefig(os.path.join(directory, 'Q6.png'))


import cv2, os

folder_name = 'frames'
image_paths= sorted([f'{folder_name}/{x}' for x in os.listdir(f'./{folder_name}')])
print(image_paths)
imgs = []

for i in range(len(image_paths)):
	imgs.append(cv2.imread(image_paths[i]))
	imgs[i]=cv2.resize(imgs[i],(0,0),fx=0.4,fy=0.4)

stitchy=cv2.Stitcher.create()
# stitchy.setPanoConfidenceThresh(0.1)
(dummy,output)=stitchy.stitch(imgs)

# check stiching done successfully
if dummy != cv2.STITCHER_OK:
	print("stitching ain't successful")
else:
	print('Your Panorama is ready!!!')

	# final output
	cv2.imshow('final result',output)
	cv2.imwrite('cv2_s_1.jpeg', output)
	cv2.waitKey(5000)