# file: liveticker2csv.py
import argparse
import json
from collections.abc import Iterable
from datetime import date, datetime
from pathlib import Path
from typing import Union

import httpx  # Documentation: https://www.python-httpx.org/quickstart/
import pandas as pd
from bs4 import (  # Documentation: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
    BeautifulSoup, Tag)
from pytz import utc

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError ("Type %s not serializable" % type(obj))

def get_livetickerpage(url: str) -> httpx.Response.text:
    page = httpx.get(url)
    assert page.status_code == 200
    return page.text

def match_details(parsed_content: BeautifulSoup) -> dict:
    team_shortname_mapping = dict()
    metadata = parsed_content.select("div.first.last.odd.finished.active.match")[0]
    for team_shortname in metadata.select("div.team-shortname"):
        for team in team_shortname.find_all("a"):
            team_slug_name = Path(team.get('href')).parts[-2]
            team_shortname_mapping[team.get_text().lower()] = team_slug_name
            team_shortname_mapping[team_slug_name.replace("-", " ")] = team_slug_name
            team_shortname_mapping[team_slug_name] = team_slug_name
    return {
        "start_datetime": pd.to_datetime(metadata.attrs.get("data-datetime")),
        "end_datetime": pd.to_datetime(metadata.attrs.get("data-datetime_end")),
        "team_shortname_mapping": team_shortname_mapping
    }

def corresponding_team(liveticker_event: Tag) -> Union[str, None]:
    for tag in liveticker_event.select("div.team-shortname"):
        for a_tag in tag.select("a"):
            return Path(a_tag.attrs.get("href")).parts[-2]

def liveticker_content(liveticker_event: Tag) -> Union[str, None]:
    for tag in liveticker_event.select("div.liveticker-content"):
        return str(tag.get_text()).replace('\n', ' ').replace('\r', '').strip()

def liveticker_event_parser(liveticker_event: Tag, match_details: dict) -> dict:
    event_minute = int(liveticker_event.select("div.liveticker-minute")[0].get_text().replace(".", ""))
    event_action = liveticker_event.attrs.get("data-event_action")
    is_goal = event_action == "goal"
    is_card = event_action == "card"
    relevant_team = corresponding_team(liveticker_event)
    text = liveticker_content(liveticker_event)
    halftime = 0
    event_timestamp = liveticker_event.select("div.liveticker-datetime")[0].get_text()

    if event_minute <= 45:
        halftime = 1
    if event_minute > 45:
        halftime = 2

    return {
        "minute": event_minute,
        "action": event_action,
        "is_goal": is_goal,
        "is_card": is_card,
        "relevant_team": relevant_team,
        "halftime": halftime,
        "datetime": event_timestamp,
        "text": text
    }

def relevant_liveticker_events(liveticker_events: BeautifulSoup) -> Iterable[Tag]:
    for element in liveticker_events.select("div.module-liveticker")[0].select("div.liveticker"):
        if element.select("div.liveticker-minute")[0].get_text():
            yield element

def workflow(url: str, data_dir: str):
    data_path = Path(data_dir)

    # Get and Parse Liveticker
    content = get_livetickerpage(url)
    with open(data_path.joinpath("raw_liveticker.html"), "w") as file:
        file.write(content)
    parsed_content = BeautifulSoup(content, "html.parser")

    # Retrive Metadata
    meta_data = match_details(parsed_content)
    meta_data["url"] = url

    # Retrive Play Data
    data = [liveticker_event_parser(element, meta_data) for element in relevant_liveticker_events(parsed_content)]
    df = pd.DataFrame(data)

    # Revert Dataframe
    df = df.loc[::-1].reset_index(drop=True)
    # Create UTC Timestamp
    play_start = meta_data["start_datetime"]
    utc_timedelta = pd.to_datetime(
        f'{play_start.strftime("%m/%d/%Y-")}{df["datetime"][0]}',
        format="%m/%d/%Y-%H:%M",
        utc=True
        ) - play_start #"%m/%d/%Y-%H:%M"

    corrected_timestamps = []
    for row in df.itertuples():
        corrected_timestamps.append(
            pd.to_datetime(
        f'{play_start.strftime("%m/%d/%Y-")}{row.datetime}',
        format="%m/%d/%Y-%H:%M",
        utc=True
        ) - utc_timedelta
        )
    df["timestamp"] = corrected_timestamps

    # Get Pause Data
    meta_data["break_start"] = df[df["minute"] == 45].iloc[-1]["timestamp"]
    meta_data["break_end"] = df[df["minute"] == 46].iloc[0]["timestamp"]

    # Clean DataFrame
    df.drop(columns=["datetime"])

    # Save to csv
    df.to_csv(data_path.joinpath(Path("./liveticker.csv")) ,index=False)
    # Save Metadata
    with open(data_path.joinpath("metadata.json"), "w") as file:
        json.dump(meta_data, file, default=json_serial)

def main():
    parser = argparse.ArgumentParser(description="Process Sportschau Liveticker.")
    parser.add_argument("--url", type=str, required=True, help="URL to Liveticker")
    parser.add_argument("--data-dir", type=str, default="./", help="Path to folder to store data")
    args = parser.parse_args()
    print(f"Downloading Liveticker {args.url} \nand extract data to {args.data_dir}")
    workflow(args.url, args.data_dir)

if __name__ == "__main__":
    main()


import sys
input = sys.stdin.readline

N = int(input())
f = [0] * (N + 1)
f[1] = f[2] = 1
for i in range(3, N + 1):
    f[i] = f[i - 1] + f[i - 2]

print(f[N], N - 2)


# -*- coding: utf-8 -*-
import errno
import os
import stat
import struct

import fuse
from fuse import Fuse

NAME_STRUCT = 'H'
ENTRY_HEADER_STRUCT = '?Q'
TERMINATOR_NAME = b''

NAME_HEADER_SIZE = struct.calcsize(NAME_STRUCT)
ENTRY_HEADER_SIZE = struct.calcsize(ENTRY_HEADER_STRUCT)

if not hasattr(fuse, '__version__'):
	raise RuntimeError("your fuse-py doesn't know of fuse.__version__, probably it's too old.")

fuse.fuse_python_api = (0, 2)

def read_name(fp):
	name_header_bytes = fp.read(NAME_HEADER_SIZE)
	if len(name_header_bytes) != NAME_HEADER_SIZE:
		return None
	(size,) = struct.unpack(NAME_STRUCT, name_header_bytes)
	name = fp.read(size)
	if len(name) != size:
		return None
	return name

def read_entry_header(fp):
	entry_header_bytes = fp.read(ENTRY_HEADER_SIZE)
	if len(entry_header_bytes) != ENTRY_HEADER_SIZE:
		return None
	(is_dir, size,) = struct.unpack(ENTRY_HEADER_STRUCT, entry_header_bytes)
	return (is_dir, size)

class Stat(fuse.Stat):
	def __init__(self):
		self.st_mode = 0
		self.st_ino = 0
		self.st_dev = 0
		self.st_nlink = 0
		self.st_uid = 0
		self.st_gid = 0
		self.st_size = 0
		self.st_atime = 0
		self.st_mtime = 0
		self.st_ctime = 0

class FilesizeFuse(Fuse):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.stats_file = ''
		self.dirs = {}

	def main(self, *args, **kwargs):
		self.read_stats()
		super().main(*args, **kwargs)

	def read_stats(self):
		try:
			fp = open(self.stats_file, 'rb')
		except IOError:
			raise RuntimeError("Stats file not initialized")
		self.read_stats_file(fp)
		fp.close()

	def read_stats_file(self, fp):
		dirname = '/'
		self.dirs = {'/': {}}
		while True:
			name = read_name(fp)
			if name is None:
				return
			if name == TERMINATOR_NAME:
				dirname = os.path.dirname(dirname)
				continue
			is_dir, size = read_entry_header(fp)
			name = name.decode('utf-8', 'replace')
			self.dirs[dirname][name] = size
			if is_dir:
				dirname = os.path.join(dirname, name)
				self.dirs[dirname] = {}

	def getattr(self, path):
		direntry = self.dirs.get(path)
		if direntry is None: # file
			parent_dir = os.path.dirname(path)
			basename = os.path.basename(path)
			direntry = self.dirs.get(parent_dir)
			if direntry is None:
				return -errno.ENOENT
			fileentry = direntry.get(basename)
			if fileentry is None:
				return -errno.ENOENT
			st = Stat()
			st.st_mode = stat.S_IFREG | 0o444
			st.st_nlink = 1
			st.st_size = direntry[basename]
			return st
		else: #  directory
			st = Stat()
			st.st_mode = stat.S_IFDIR | 0o755
			st.st_nlink = len(self.dirs[path]) + 2
			return st

	def readdir(self, path, offset):
		direntry = self.dirs.get(path)
		if direntry is None:
			return -errno.ENOENT

		yield fuse.Direntry('.')
		yield fuse.Direntry('..')
		for f in direntry.keys():
			yield fuse.Direntry(f)

def main():
	usage = "Filesystem for file size\n\n" + Fuse.fusage

	server = FilesizeFuse(version="%prog " + fuse.__version__, usage=usage, dash_s_do='setsingle')
	server.parser.add_option(
		'--stats_file',
		nargs=1,
		help="Stats file"
	)
	server.parse(values=server)
	if not server.stats_file:
		return
	server.main()

if __name__ == "__main__":
	main()


import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import PCA

'''
计算各特征值的方法
#邻域分析，表面粗糙等
'''

#计算最小二乘平面及距离
def CaculateAverageSquareDistance(p):
    num = p.shape[0]
    B = np.zeros((p.shape[0],3))
    one = np.ones((p.shape[0],1))
    B[:,0] = p[:,0]
    B[:,1] = p[:,1]
    B[:,2] = one[:,0]
    l = p[:,2]
    BTB = np.matmul(B.T,B)
    BTB_1 = np.linalg.pinv(BTB)
    temp = np.matmul(BTB_1,B.T)
    result = np.matmul(temp,l)
    V  = np.matmul(B,result)-l
    sum = 0
    for i in range (0,V.shape[0]):
        sum = sum+V[i]**2
    return sum/V.shape[0]

#粗糙度
def CaculateRoughness(p):
    p1 = np.zeros((p.shape[0],3),float)
    p1[:,0] = p[:,0]
    p1[:,1] = p[:,1]
    p1[:,2] = p[:,2]
    #print(p1)

    neigh = NearestNeighbors(n_neighbors=8)
    neigh.fit(p1)
    #index = neigh.kneighbors([[1.04291550e+05,4.79228380e+05,-8.10000050e-01]],return_distance=False)

    sum = 0
    for i in range(p1.shape[0]):
        index = neigh.kneighbors([p1[i]],return_distance=False)
        avedis2 = CaculateAverageSquareDistance(p1[index].reshape(8,3))
        sum = sum+avedis2

    return sum/p1.shape[0]*100

'''
def PcaPartAna(p):
    p1 = np.zeros((p.shape[0],3),float)
    p1[:,0:3] = p[:,0:3]

    pca = PCA(n_components=3)
    newX = pca.fit_transform(p1)
    a =(pca.explained_variance_ratio_)
    return (a[2]/a[0])

def PCAPlaneAynalize(p):
    p1 = np.zeros((p.shape[0],3),float)
    p1[:,0] = p[:,0]
    p1[:,1] = p[:,1]
    p1[:,2] = p[:,2]
    #print(p1)

    neigh = NearestNeighbors(n_neighbors=20)
    neigh.fit(p1)
    #index = neigh.kneighbors([[1.04291550e+05,4.79228380e+05,-8.10000050e-01]],return_distance=False)

    sum = 0
    for i in range(p1.shape[0]):
        index = neigh.kneighbors([p1[i]],return_distance=False)
        avedis2 = PcaPartAna(p1[index].reshape(20,3))
        sum = sum+avedis2

    return sum/p1.shape[0]

    # p1 = np.zeros((p.shape[0],3),float)
    # p1[:,0:3] = p[:,0:3]

    # pca = PCA(n_components=3)
    # newX = pca.fit_transform(p1)
    # a =(pca.explained_variance_ratio_)
    # return (a[2]/a[0])
'''

#邻域分析
def NeiAna(p):
    p1 = p[:,0:3]

    sum = 0
    for i in range(0,p1.shape[0],3):
        neigh = NearestNeighbors(n_neighbors=20)
        neigh.fit(p1)
        index = neigh.kneighbors([p1[i]],return_distance=False)

        pp = p1[index].reshape(20,3)
        pp[:,0] = pp[:,0]-np.mean(p1[:,0])
        pp[:,1] = pp[:,1]-np.mean(p1[:,1])
        pp[:,2] = pp[:,2]-np.mean(p1[:,2])
        a = pp.T
        b  = np.matmul(pp.T,pp)
        fev = np.linalg.eigvals(b)
        fev = (np.sort(fev))
        sum = sum+(fev[0])/fev[2]*1000

    return (sum/p1.shape[0]/3)

#组成特征向量
def GetFeatureVector(p):
    fv = np.array([[0.0,0.0]],dtype=float)
    fv[0,0] = NeiAna(p)
    fv[0,1] = CaculateRoughness(p)
    return fv


import numpy as np
from pathlib import Path
import pickle
import os
from utils_ccy.util.directory import mk_dir
from tqdm import tqdm
import amc_parser as amc

class Processor() :
    def __init__(self, arg) :
        self.arg = arg
        self.raw_data_dir = Path(arg.raw_data_dir)

    def init_values(self) :
        self.n_data = 0
        self.datas_dict = dict() #
        self.sample_name = [] # 파일 이름
        self.sample_label = [] # 파일 라벨

    def load_data(self) :
        '''
        base_dir 안에 있는 c3d 파일들을 (N, C, T, V, M) shape를 가진 하나의 npy 파일로 합친 후, out_path에 저장

        - output -
        base_dir에 존재하는 skeleton data를 (N, C, T, V, M) shape를 가진 npy 파일로 저장
        '''

        # 데이터 파일 이름 및 fp 전체 길이 추출
        self.raw_data_list = list(self.raw_data_dir.glob('subjects/*/*.amc'))
        process = tqdm(self.raw_data_list)
        process.set_description('전체 길이 추출')
        for i, filename in enumerate(process):
            subject = int(filename.stem.split('_')[0])
            action = int(filename.stem.split('_')[1])
            self.sample_name.append(filename)
            self.sample_label.append(action)

            data = self.read_xyz(filename) # data: (C, T, V)

            # 120 Frame 타노스화
            frame_rate_file = filename.parent.joinpath('frame_rate.txt')
            frame_60 = Path.is_file(frame_rate_file)

            if frame_60 == False : # 120 Frame이면 타노스시켜야함
                data = data[:, 0::2, :]

            # Frame의 절반을 겹쳐서 뽑아야 하므로 숫자 중복해서 세기

            self.n_data += data.shape[1] // self.arg.max_frame # 0에서 시작

            # half frame에서 시작된 개수
            half_num = ((data.shape[1] - int(self.arg.max_frame / 2)) // self.arg.max_frame)
            if half_num >= 0 :
                self.n_data += half_num

            data = np.expand_dims(data, axis = 0) # data: (N, C, T, V)
            self.datas_dict[i] = data # 데이터 임시 저장

            # for debug
            if i > 3 and self.arg.debug :
                break

        fp = np.zeros((self.n_data, 3, self.arg.max_frame, self.arg.num_joint), dtype=np.float32)

        # 데이터 파일 이름
        index = 0
        process = tqdm(self.sample_name)
        for i, filename in enumerate(process) :
            process.set_description('데이터 Load')

            data = self.datas_dict[i] # data: (N, C, T, V)

            # 0 frame에서 시작
            for n in range(data.shape[2] // self.arg.max_frame) :
                fp[index] = data[:, :, n*self.arg.max_frame:(n+1)*self.arg.max_frame, :] # fp: (N, C, T, V)
                index += 1

            # Half frame에서 시작
            for n in range((data.shape[2] - int(self.arg.max_frame / 2)) // self.arg.max_frame) :
                fp[index] = data[:, :, n*self.arg.max_frame + int(self.arg.max_frame/2):(n+1)*self.arg.max_frame + int(self.arg.max_frame/2), :] # fp: (N, C, T, V)
                index += 1

            # for debug
            if i > 3 and self.arg.debug :
                break

        self.fp = np.expand_dims(fp, axis = -1) # M 차원 생성

    def pre_processing(self) :
        self.fp, self.pose_mean, self.pose_max = self.pre_normalization(self.fp)

        if self.arg.node_mask != None :
            self.fp = self.fp[:, :, :, self.arg.node_mask, :]
            self.pose_mean = self.pose_mean[:, :, :, self.arg.node_mask, :]

    def save_data(self) :
        mk_dir(self.arg.save_dir)
        with open('{}/full_joint.pkl'.format(self.arg.save_dir), 'wb') as f :
            pickle.dump(self.fp_dict, f)

    def read_xyz(self, filename) :
        '''
        skeleton 파일 정보에서 xyz 값만 (C, T, V, M) shape를 가진 numpy 형태로 만들어서 출력

        - input -
        filename(pathlib.PosixPath):

        - output -
        data(numpy.array):
        '''

        asf_path = filename.parent / (filename.parent.stem + '.asf')

        joints = amc.parse_asf(asf_path)
        motions = amc.parse_amc(filename)
        numFrame = len(motions)
        data = np.zeros(shape = (3, numFrame, self.arg.num_joint)) # data: (C, T, V)

        # 모든 프레임 데이터 정보 읽기
        for i in range(numFrame) :
            joints['root'].set_motion(motions[i])
            c_joints = joints['root'].to_dict()

            for j, joint in enumerate(c_joints.values()) :
                data[:, i, j] = [joint.coordinate[0, 0], joint.coordinate[1, 0], joint.coordinate[2, 0]]

        return data # data: (C, T, V)

    def pre_normalization(self, data):

        '''
        - Input -
        data(numpy.array): (N, C, T, V, M) shape를 가진 numpy array.
        examples (N), channels (C), frames (T), nodes (V), persons (M))

        - Output -
        data(numpy.array): (N, C, T, V, M) shape를 가진 numpy array.
        examples (N), channels (C), frames (T), nodes (V), persons (M))
        '''

        # examples (N), channels (C), frames (T), nodes (V), persons (M))
        N, C, T, V, M = data.shape
        s = np.transpose(data, [0, 4, 2, 3, 1])  # to (N, M, T, V, C)

        ################################################# Global Translation ######################################################

        # Joint 데이터를 x, y, z = 0, 0, 0 좌표 근처로 이동
        print('subtract the center joint #1 (spine joint in ntu and neck joint in kinetics)')
        for i_s, skeleton in enumerate(tqdm(s)): # skeleton: (M, T, V, C)
            # Person 데이터가 전부 0인 경우(Person 1과 Person 2가 전부 0)이면 넘기기
            if skeleton.sum() == 0:
                continue

            # Use the first skeleton's body center (`1:2` along the nodes dimension)
            # 첫번째 Person의 복부 부분의 Joint를 Main body center로 저장(12번 Joint)
            '''
            이상한 게 첫번째 프레임의 2번 Joint 좌표를 중심으로 보는 것이 아니라
            모든 프레임에서 2번 Joint 좌표를 중심으로 바라봄.
            이 경우, 달리기는 제자리기 뛰기가 되는 단점이 존재할 것 같음.
            '''

            main_body_center = skeleton[0][:, 0:1, :].copy() # skeleton: (M, T, V, C) -> main body center: (T, 1, C)

            # 전체 스켈레톤에 대해
            for i_p, person in enumerate(skeleton): # Dimension M (# person)  # person : (T, V, C)

                # Person 데이터가 전부 0인 경우(Person 1과 Person 2가 전부 0)이면 넘기기(continue)
                if person.sum() == 0: # person : (T, V, C)  frames (T), nodes (V), channels (C)
                    continue

                # For all `person`, compute the `mask` which is the non-zero channel dimension
                # Person 데이터가 존재하는 경우, mask는 X, Y, Z 값의 합이 0이 아니면(Action이 있으면) True, 0이면 False
                mask = (person.sum(-1) != 0).reshape(T, V, 1)

                # Subtract the first skeleton's centre joint
                # Skeleton data의 2번째 Joint를 모두 0, 0, 0으로 이동시킴.
                s[i_s, i_p] = (s[i_s, i_p] - main_body_center) * mask

        data = np.transpose(s, [0, 4, 2, 3, 1])

        # 데이터 Unit -> Inches -> length로 변환
        data = data * (1.0 / 0.45) * 2.54 / 100.0

        # 데이터 Normalize
        data, pose_mean, pose_max = self.standardizing(data)

        return data, pose_mean, pose_max

    def standardizing(self, data) :
        pose_mean = np.mean(data, axis = (0, 2), keepdims=True)
        pose_max = np.max(np.abs(data-pose_mean), axis = (0, 2, 3, 4), keepdims=True) # (1, 3, 1, 1, 1)
        return (data - pose_mean) / pose_max, pose_mean, pose_max

    def start(self) :
        self.init_values()
        self.load_data()
        self.pre_processing()
        self.fp_dict = {'data': self.fp, 'pose_mean':self.pose_mean, 'pose_max':self.pose_max}

        # 데이터 저장
        self.save_data()

# if __name__ == "__main__":


import numpy as np
from numpy.random import RandomState

from util.defs import *

def random_x_sample(bounds: NDArray, param_types: Sequence[ParamType], samples: int, rand: RandomState=None) -> NDArray:
    assert bounds.ndim == 2, f"Bounds must be 2d, not {bounds.shape}"
    assert len(bounds) == len(param_types), "Must have bounds and param types for each param."
    if not rand:
        rand = np.random
    if type(param_types) != NDArray:
        pt = np.array(param_types)

    X = rand.uniform(low=bounds[:, 0], high=bounds[:, 1], size=(samples, len(bounds)))

    disc_inds = np.where(pt == ParamType.Disc)[0]
    X[:, disc_inds] = np.round(X[:, disc_inds])

    return X

def scalar_or_1d_to_2d(v: NDArray) -> NDArray:
    # Is v a scalar array?
    if v.ndim == 0:
        v = v[np.newaxis]
    # Is v a 1d array?
    if v.ndim == 1:
        v = v[:, np.newaxis]
    return v

def singleton_to_scalar(v: NDArray) -> Union[int, float]:
    return v.item()


from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import LogoutView

from . import views

app_name='accounts'

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'sign_in/$', views.SignInView.as_view(), name='sign_in'),
    url(r'sign_up/$', views.RegisterView.as_view(), name='sign_up'),
    url(r'sign_out/$', LogoutView.as_view(), {'next_page': settings.LOGOUT_REDIRECT_URL}, name='sign_out'),
    url(r'profile/$', views.ProfileView.as_view(), name='profile'),
    url(r'profile/edit/$', views.ProfileUpdateView.as_view(), name='edit_profile'),
    url(r'project/new/$', views.ProjectCreateView.as_view(), name='project_new'),
    url(r'project/(?P<pk>\d+)/edit/$', views.ProjectUpdateView.as_view(), name='project_edit'),
    url(r'project/(?P<pk>\d+)/$', views.ProjectView.as_view(), name='project'),
    url(r'project/(?P<pk>\d+)/delete/$', views.ProjectDeleteView.as_view(), name='project_delete'),
    url(r'applications/(?P<pk>\d+)/$', views.ApplicationUpdateView.as_view(), name='application_detail'),
    url(r'applications/(?P<pk>\d+)/delete/$', views.delete_application, name='application_delete'),
    url(r'applications/$', views.ApplicationView.as_view(), name='applications'),
    url(r'applications/new/(?P<pk>\d+)/$', views.ApplicationCreateView.as_view(), name='application_new'),
    url(r'delete_skill/(?P<pk>\d+)/$', views.delete_skill, name='skill_delete'),
    url(r'delete_position/(?P<pk>\d+)/$', views.delete_position, name='position_delete'),
    url(r'search/$', views.search, name='search'),
    url(r'sort_by_skill/(?P<skillz>\w+)/$', views.sort_by_skill, name='sort')
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import os, sys, re
# import nuke
main = __import__('__main__')
ns = main.__dict__
exec ('import nuke') in ns
nuke = ns['nuke']
import nukescripts
from managers.nuke import nodes
nuke_nodes = dir(nodes)
from managers.completeWidget import contextCompleterClass

from Qt.QtGui import *
from Qt.QtWidgets import *
from Qt.QtCore import *

p = os.path.dirname(__file__).replace('\\','/')
if not p in sys.path:
    sys.path.insert(0, p)

from pw_multiScriptEditor import scriptEditor
try:
	from importlib import reload
except:
	pass
reload(scriptEditor)

# QT
qApp = QApplication.instance()

def getMainWindow():
    for widget in qApp.topLevelWidgets():
        if widget.metaObject().className() == 'Foundry::UI::DockMainWindow':
            return widget
qNuke = getMainWindow()

def show(panel=False):
    if panel:
        import pw_multiScriptEditor.scriptEditor
        nukescripts.panels.registerWidgetAsPanel("pw_multiScriptEditor.scriptEditor.scriptEditorClass", "Multi Script Editor", "pw_multi_script_editor")
    else:
        showWindow()

def showWindow():
    se = scriptEditor.scriptEditorClass(qNuke)
    se.runCommand('import nuke')
    se.show()

# add to menu.py
# Add to menu.py
# menubar = nuke.menu("Nuke")
# toolMenu = menubar.addMenu('&Tools')
# path = 'path/to/MultiScriptEditor_module'
# # example c:/nuke/python/lib
# if not path in sys.path:
#     sys.path.append(path)
#
# import pw_multiScriptEditor
# # add to menu
# toolMenu.addCommand("Multi Script Editor", "pw_multiScriptEditor.showNuke()")
# # create new pane
# pw_multiScriptEditor.showNuke(panel=True)

############ COMPLETER

def completer(line):
    # node types
    p1 = r"nuke\.createNode\(['\"](\w*)$"
    m = re.search(p1, line)# or re.search(p2, line)
    if m:
        name = m.group(1)
        l = len(name)
        if name:
            auto = [x for x in nuke_nodes if x.lower().startswith(name.lower())]
        else:
            auto = nuke_nodes
        return [contextCompleterClass(x, x[l:], True) for x in auto], None
    # exists nodes
    p3 = r"nuke\.toNode\(['\"](\w*)$"
    m = re.search(p3, line)
    if m:
        name = m.group(1)
        nuke.tprint(name)
        nodes = [x.name() for x in nuke.allNodes()] #recurseGroups=True
        if name:
            result = [x for x in nodes if x.lower().startswith(name.lower())]
        else:
            result = nodes
        l = len(name)
        return [contextCompleterClass(x, x[l:], True) for x in result], None
    return None, None

################  CONTEXT MENU

def contextMenu(parent):
    m = nukeContextMenu(parent)
    return m

class nukeContextMenu(QMenu):
    def __init__(self, parent):
        super(nukeContextMenu, self).__init__('Nuke')
        self.par = parent
        # a.setShortcut('Alt+Return')
        # a.setShortcutContext(Qt.ApplicationShortcut)
        self.addAction(QAction('Read PyScript Knob', parent, triggered=self.readPyScriptKnob))
        self.addAction(QAction('Save To PyScript Knob', parent, triggered=self.saveToKnob))
        self.addSeparator()
        self.addAction(QAction('From Selected', parent, triggered=self.nodeToCode))
        self.addAction(QAction('From Clipboard', parent, triggered=self.nodesFromClipboard))

    def nodeToCode(self):
        nodes = nuke.selectedNodes()
        names = [x.name() for x in nodes]
        result = '\n'.join(["nuke.toNode('%s')" % x for x in names])
        self.par.insertText(result)

    def getPyKnob(self, title):
        s = nuke.selectedNodes()
        if s:
            s = s[0]
            pyKnobs = [x for x in s.knobs().values() if x.Class() in ['PyScript_Knob','PythonCustomKnob']]
            if pyKnobs:
                result = {}
                for k in pyKnobs:
                    result[k.name()] = k
                if result:
                    dial = selectDialog(result.keys(), title)
                    if dial.exec_():
                        name = dial.list.currentItem().text()
                        knob = result[name]
                        return knob
            else:
                nuke.message('Python Knobs not found')
        else:
            nuke.message('Select one node')

    def readPyScriptKnob(self):
        knob = self.getPyKnob('Select Python Knob to Read')
        if knob:
            text = knob.value()
            self.par.tab.addNewTab(knob.node().name()+' | '+knob.name(), text)

    def saveToKnob(self):
        knob = self.getPyKnob('Select Python Knob to Save')
        if knob:
            text = self.par.tab.getCurrentText()
            knob.setValue(text)

    def nodesFromClipboard(self):
        nuke.tprint(str(self.par))
        text = QApplication.clipboard().text()
        nodes = []
        if text:
            for l in text.split('\n'):
                res = re.findall(r'name \w+$', l)
                if res:
                    name = res[0].split()[1]
                    nodes.append(name)
        for n in nodes:
            self.par.tab.addToCurrent('nuke.toNode("%s")\n' % n)

class selectDialog(QDialog):
    def __init__(self, items, title):
        super(selectDialog, self).__init__()
        self.setWindowTitle(title)
        self.setWindowFlags(Qt.Tool)
        self.list = QListWidget(self)
        self.list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.ly = QVBoxLayout(self)
        self.setLayout(self.ly)
        self.ly.addWidget(self.list)

        self.btn = QPushButton('Select')
        self.ly.addWidget(self.btn)
        self.btn.clicked.connect(self.accept)
        for i in items:
            item = QListWidgetItem(i)
            item.setData(32, i)
            self.list.addItem(item)

    def closeEvent(self, *args, **kwargs):
        self.reject()
        super(selectDialog, self).closeEvent( *args, **kwargs)


import os
import face_alignment
import cv2
import numpy as np
import pickle
from tqdm import tqdm
from PIL import Image
import torch
import torchvision.transforms.functional as F
from fsgan.data.landmark_transforms import crop_img, scale_bbox, Resize, generate_heatmaps
import fsgan.data.landmark_transforms as landmark_transforms
import fsgan.utils.utils as utils
from fsgan.utils.obj_factory import obj_factory
import fsgan.utils.estimate_pose as estimate_pose

def process_image(fa, img, size=256):
    detected_faces = fa.face_detector.detect_from_image(img.copy())
    if len(detected_faces) != 1:
        return None, None

    preds = fa.get_landmarks(img, detected_faces)
    landmarks = preds[0]
    bbox = detected_faces[0][:4]

    # Convert bounding boxes format from [min, max] to [min, size]
    bbox[2:] = bbox[2:] - bbox[:2] + 1

    return landmarks, bbox

    # scaled_bbox = scale_bbox(bbox)
    # cropped_img, cropped_landmarks = crop_img(img, landmarks, scaled_bbox)
    # landmarks_resize = Resize(size)
    # cropped_img, cropped_landmarks, scaled_bbox = \
    #     landmarks_resize(Image.fromarray(cropped_img), cropped_landmarks, scaled_bbox)
    #
    # return np.array(cropped_img), cropped_landmarks

def process_cached_frame(frame, landmarks, bbox, size=128):
    scaled_bbox = scale_bbox(bbox)
    cropped_frame, cropped_landmarks = crop_img(frame, landmarks, scaled_bbox)
    landmarks_resize = Resize(size)
    cropped_frame, cropped_landmarks, scaled_bbox = \
        landmarks_resize(Image.fromarray(cropped_frame), cropped_landmarks, scaled_bbox)

    return np.array(cropped_frame), cropped_landmarks

def unnormalize(tensor, mean, std):
    """Normalize a tensor image with mean and standard deviation.

    See :class:`~torchvision.transforms.Normalize` for more details.

    Args:
        tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channely.

    Returns:
        Tensor: Normalized Tensor image.
    """
    for t, m, s in zip(tensor, mean, std):
        t.mul_(s).add_(m)
    return tensor

def tensor2bgr(img_tensor):
    output_img = unnormalize(img_tensor, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
    output_img = output_img.squeeze().permute(1, 2, 0).cpu().numpy()
    output_img = np.round(output_img[:, :, ::-1] * 255).astype('uint8')

    return output_img

def prepare_generator_input(img, landmarks, sigma=2):
    landmarks = generate_heatmaps(img.shape[1], img.shape[0], landmarks, sigma=sigma)
    landmarks = torch.from_numpy(landmarks)
    img = F.normalize(F.to_tensor(img), [0.5, 0.5, 0.5], [0.5, 0.5, 0.5])

    return img, landmarks

end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1
def plot_kpt(image, kpt, circle_color=(0, 0, 255), line_color=(255, 255, 255), line_thickness=1):
    ''' Draw 68 key points
    Args:
        image: the input image
        kpt: (68, 3).
    '''
    image = image.copy()
    kpt = np.round(kpt).astype(np.int32)
    for i in range(kpt.shape[0]):
        st = kpt[i, :2]
        image = cv2.circle(image, (st[0], st[1]), 1, circle_color, 2)
        if i in end_list:
            continue
        ed = kpt[i + 1, :2]
        image = cv2.line(image, (st[0], st[1]), (ed[0], ed[1]), line_color, line_thickness)

    return image

def main(source_path, target_path, frontal_path='frontal.jpg',
         arch='res_unet_split.MultiScaleResUNet(in_nc=71,out_nc=(3,3),flat_layers=(2,0,2,3),ngf=128)',
         model_path='../../weights/ijbc_msrunet_256_2_0_reenactment_v1.pth',
         pil_transforms1=('landmark_transforms.FaceAlignCrop', 'landmark_transforms.Resize(256)',
                          'landmark_transforms.Pyramids(2)'),
         pil_transforms2=('landmark_transforms.FaceAlignCrop', 'landmark_transforms.Resize(256)',
                          'landmark_transforms.Pyramids(2)', 'landmark_transforms.LandmarksToHeatmaps'),
         tensor_transforms1=('landmark_transforms.ToTensor()',
                            'transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])'),
         tensor_transforms2=('landmark_transforms.ToTensor()',
                             'transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])'),
         output_path=None, crop_size=256, display=False):
    # Initialize models
    fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._3D, flip_input=True)
    device, gpus = utils.set_device()
    G = obj_factory(arch).to(device)
    checkpoint = torch.load(model_path)
    G.load_state_dict(checkpoint['state_dict'])
    G.train(False)

    # Initialize transformations
    pil_transforms1 = obj_factory(pil_transforms1) if pil_transforms1 is not None else []
    pil_transforms2 = obj_factory(pil_transforms2) if pil_transforms2 is not None else []
    tensor_transforms1 = obj_factory(tensor_transforms1) if tensor_transforms1 is not None else []
    tensor_transforms2 = obj_factory(tensor_transforms2) if tensor_transforms2 is not None else []
    img_transforms1 = landmark_transforms.ComposePyramids(pil_transforms1 + tensor_transforms1)
    img_transforms2 = landmark_transforms.ComposePyramids(pil_transforms2 + tensor_transforms2)

    # Process source image
    print('Processing source image...')
    source_bgr = cv2.imread(source_path)
    source_rgb = source_bgr[:, :, ::-1]
    source_landmarks, source_bbox = process_image(fa, source_rgb, crop_size)
    # source_landmarks = source_landmarks[:, :2]
    if source_bbox is None:
        raise RuntimeError("Couldn't detect a face in source image: " + source_path)
    source_tensor, source_landmarks, source_bbox = img_transforms1(source_rgb, source_landmarks, source_bbox)
    source_cropped_bgr = tensor2bgr(source_tensor[0])

    # Process target image
    print('Processing target image...')
    target_bgr = cv2.imread(target_path)
    target_rgb = target_bgr[:, :, ::-1]
    target_landmarks, target_bbox = process_image(fa, target_rgb, crop_size)
    # source_landmarks = source_landmarks[:, :2]
    if target_bbox is None:
        raise RuntimeError("Couldn't detect a face in target image: " + target_path)
    target_tensor, target_landmarks, target_bbox = img_transforms1(target_rgb, target_landmarks, target_bbox)
    target_cropped_bgr = tensor2bgr(target_tensor[0])

    # Process frontal image
    print('Processing frontal image...')
    frontal_bgr = cv2.imread(frontal_path)
    frontal_rgb = frontal_bgr[:, :, ::-1]
    frontal_landmarks, frontal_bbox = process_image(fa, frontal_rgb, crop_size)
    # source_landmarks = source_landmarks[:, :2]
    if frontal_bbox is None:
        raise RuntimeError("Couldn't detect a face in frontal image: " + frontal_path)
    frontal_tensor, frontal_landmarks, frontal_bbox = img_transforms1(frontal_rgb, frontal_landmarks, frontal_bbox)

    # Initialize output video file
    if output_path is not None:
        if os.path.isdir(output_path):
            output_filename = os.path.splitext(os.path.basename(source_path))[0] + '_' + \
                              os.path.splitext(os.path.basename(target_path))[0] + '.mp4'
            output_path = os.path.join(output_path, output_filename)
        fourcc = cv2.VideoWriter_fourcc(*'avc1')
        fps = 10.0
        out_vid = cv2.VideoWriter(output_path, fourcc, fps,
                                  (source_cropped_bgr.shape[1] * 3, source_cropped_bgr.shape[0]))
    else:
        out_vid = None

    # source_cropped_bgr = tensor2bgr(source_tensor[0] if isinstance(source_tensor, list) else source_tensor)
    # for i in range(len(source_tensor)):
    #     source_tensor[i] = source_tensor[i].to(device)

    # Estimate source euler angles
    P1 = estimate_pose.compute_similarity_transform(source_landmarks[0].numpy(), frontal_landmarks[0].numpy())
    s1, R1, t1 = estimate_pose.P2sRt(P1)
    euler1 = estimate_pose.matrix2angle(R1)    # Yaw, Pitch, Roll
    print('source euler:')
    print(np.array(euler1) * 180.0 / np.pi)

    # Estimate target euler angles
    P2 = estimate_pose.compute_similarity_transform(target_landmarks[0].numpy(), frontal_landmarks[0].numpy())
    s2, R2, t2 = estimate_pose.P2sRt(P2)
    euler2 = estimate_pose.matrix2angle(R2)    # Yaw, Pitch, Roll
    print('target euler:')
    print(np.array(euler2) * 180.0 / np.pi)

    # Estimate source to target transform
    # P3 = estimate_pose.compute_similarity_transform(target_landmarks[0].numpy(), source_landmarks[0].numpy())
    # s3, R3, t3 = estimate_pose.P2sRt(P3)
    # euler3 = estimate_pose.matrix2angle(R2)  # Yaw, Pitch, Roll

    R3, t3 = estimate_pose.rigid_transform_3D(source_landmarks[0].numpy(), target_landmarks[0].numpy())
    euler3 = np.array(estimate_pose.matrix2angle(R3))  # Yaw, Pitch, Roll

    # Interpolate transform
    # alpha = 0.5
    # euler3 = np.array(euler3) * alpha
    # R3i = estimate_pose.euler2mat([euler3[2], -euler3[0], euler3[1]])

    # Compose projection matrix
    # print(R1)
    # R2_composed = estimate_pose.euler2mat([euler2[2], -euler2[0], euler2[1]])

    # Transform source points to target points
    # A2 = (ret_R * A.T) + tile(ret_t, (1, n))
    # A2 = A2.T

    # pts = source_landmarks[0].numpy().transpose()
    # pts_h = np.concatenate((pts, np.ones((1, 68))), axis=0)
    # out_pts = P3 @ pts_h
    # out_pts = out_pts.transpose()

    for alpha in np.arange(0.0, 1.0, 0.01):
        # Interpolate
        # alpha = 0.5
        euler = np.array(euler3) * alpha
        t = t3 * alpha
        R = estimate_pose.euler2mat([euler[2], -euler[0], euler[1]])

        pts = source_landmarks[0].numpy().transpose()
        out_pts = R @ pts
        translation = np.tile(t, (out_pts.shape[1], 1)).transpose()
        # out_pts = out_pts[:2, :] + translation
        out_pts += translation
        out_pts = out_pts.transpose()

        # Render landmarks
        source_render = plot_kpt(source_cropped_bgr, source_landmarks[0].numpy())
        # interp_render = plot_kpt(source_cropped_bgr, out_pts)
        interp_render = plot_kpt(np.ones_like(source_cropped_bgr) * 255, out_pts, line_color=(0, 0, 0),
                                 line_thickness=1)
        # cv2.imshow('render', source_render)
        target_render = plot_kpt(target_cropped_bgr, target_landmarks[0].numpy())
        # cv2.imshow('target', target_render)
        render_img = np.concatenate((source_render, interp_render, target_render), axis=1)
        if out_vid is not None:
            out_vid.write(render_img)
        if out_vid is None or display:
            cv2.imshow('render_img', render_img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

if __name__ == "__main__":
    # Parse program arguments
    import argparse
    parser = argparse.ArgumentParser('Face Reenactment')
    parser.add_argument('source', metavar='IMAGE',
                        help='path to source image')
    parser.add_argument('-t', '--target', metavar='IMAGE',
                        help='paths to target video')
    parser.add_argument('-f', '--frontal', default='frontal.jpg', metavar='IMAGE',
                        help='paths to frontal image')
    parser.add_argument('-a', '--arch',
                        default='res_unet_split.MultiScaleResUNet(in_nc=71,out_nc=(3,3),flat_layers=(2,0,2,3),ngf=128)',
                        help='model architecture object')
    parser.add_argument('-m', '--model', default='../../weights/ijbc_msrunet_256_2_0_reenactment_v1.pth',
                        metavar='PATH', help='path to face reenactment model')
    parser.add_argument('-pt1', '--pil_transforms1', nargs='+', help='first PIL transforms',
                        default=('landmark_transforms.FaceAlignCrop', 'landmark_transforms.Resize(256)',
                                 'landmark_transforms.Pyramids(2)'))
    parser.add_argument('-pt2', '--pil_transforms2', nargs='+', help='second PIL transforms',
                        default=('landmark_transforms.FaceAlignCrop', 'landmark_transforms.Resize(256)',
                                 'landmark_transforms.Pyramids(2)', 'landmark_transforms.LandmarksToHeatmaps'))
    parser.add_argument('-tt1', '--tensor_transforms1', nargs='+', help='first tensor transforms',
                        default=('landmark_transforms.ToTensor()',
                                 'transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])'))
    parser.add_argument('-tt2', '--tensor_transforms2', nargs='+', help='second tensor transforms',
                        default=('landmark_transforms.ToTensor()',
                                 'transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])'))
    parser.add_argument('-o', '--output', default=None, metavar='PATH',
                        help='output video path')
    parser.add_argument('-cs', '--crop_size', default=256, type=int, metavar='N',
                        help='crop size of the images')
    parser.add_argument('-d', '--display', action='store_true',
                        help='display the rendering')
    args = parser.parse_args()
    main(args.source, args.target, args.frontal, args.arch, args.model, args.pil_transforms1, args.pil_transforms2,
         args.tensor_transforms1, args.tensor_transforms2, args.output, args.crop_size, args.display)


import h5py
import numpy as np

def replace_dataset(group, name, data):
    if name in list(group.keys()):
        del group[name]
    group.create_dataset(name, data=data, compression="gzip")
    pass

def replace_dataset_strings(group, name, data):
    if name in list(group.keys()):
        del group[name]
    asciilist = [n.encode("ascii", "ignore") for n in data]
    group.create_dataset(name, data=asciilist)
    pass

def get_dataset(group, name):
    try:
        if name in list(group.keys()):
            data = group.get(name)[:]
        else:
            data = np.array([])
    except:
        data = np.array([])
    return np.array(data)

def get_data(f, group, dataset):
    hdf = h5py.File(f)
    g = hdf.require_group(group)
    data = get_dataset(g, dataset)
    hdf.close()
    return data

def get_metadata(f, key):
    hdf = h5py.File(f)
    g = hdf.require_group("ms_dataset")
    num = g.attrs["num"]
    out = []
    for i in range(0, num):
        g2 = hdf.require_group("ms_dataset/" + str(i))
        out.append(g2.attrs[key])
    hdf.close()
    return np.array(out)

def get_num(f):
    hdf = h5py.File(f)
    g = hdf.require_group("ms_dataset")
    num = g.attrs["num"]
    hdf.close()
    return num

def read_attr(thing, string, config):
    if string in config.attrs.keys():
        val = config.attrs.get(string)
        if isinstance(val, np.ndarray):
            return val[0]
        else:
            return val
    else:
        return thing

def get_param(f, parameter):
    hdf = h5py.File(f)
    config_group = hdf.get("config")
    val = read_attr(None, parameter, config_group)
    return val


from fastapi import APIRouter, HTTPException, Request
from injector import Binder, Injector, InstanceProvider, singleton

from ...services import UserService

router = APIRouter(
    tags=["health"],
    responses={404: {
        "description": "Not found"
    }},
)

@router.get("/")
async def signin() -> dict:
    return {"status": "ok"}

@router.get("/healthz")
async def healthz(request: Request) -> dict:
    user_service = request.app.state.injector.get(UserService)

    return {"status": "ok"}


from pygame.sprite import Sprite
from gravity import Gravity
import pygame
import audio

class Mario(Sprite):
    SPEED_CAP = 4  # Prevents extreme speed
    ACCEL_FACTOR = 0.025
    DECEL_FACTOR = 0.25
    FALL_FACTOR = 0.20
    TURN_FACTOR = 0.3

    def __init__(self, screen, settings, gamemap):
        super(Mario, self).__init__()
        self.screen = screen
        self.screen_rect = self.screen.get_rect()
        self.settings = settings
        self.gravity = Gravity()
        self.gamemap = gamemap
        self.image = pygame.image.load("media/images/mario/standing.png")
        self.image = pygame.transform.scale(self.image, (35, 50))
        self.rect = self.image.get_rect()
        self.dist = 0
        self.speed = 0
        self.dir = 1  # -1 = moving left, 0 = standing still, 1 = moving right
        self.moving_right = False
        self.moving_left = False
        self.jumping = False
        self.jump_finished = False
        self.jump_speed = 0
        self.jump_start = False
        self.last_img_update = pygame.time.get_ticks()
        self.last_img_mode = 1

    def __str__(self):
        return 'Mario: x:' + str(self.rect.x) + ' y:' + str(self.rect.y)

    def update(self, gamemap, stats):  # Update and then blit

        if self.rect.top > self.screen_rect.bottom + 80:  # Has Mario fallen offscreen?
            stats.decrement_lives()
            self.settings.game_active = False
            self.settings.game_status = "Reset"
            return

        if not self.jumping and not gamemap.object_touching_ground(self):
            self.gravity.perform(self)

        if self.jumping:
            if gamemap.object_touching_ground(self):
                audio.play(0)
            self.jump()
        elif self.jumping and gamemap.object_touching_ground(self):
            self.jump()
        elif self.gamemap.object_touching_ground:
            self.jump_start = False
            self.jump_speed = 0
        if self.moving_left:
            if self.dir == 1 and self.speed != 0:
                self.turn()
            elif self.dir == 0:
                self.dir = -1
            self.accelerate()
            if self.rect.x > 0:
                self.rect.x += self.dir * self.speed

        elif self.moving_right:
            if self.dir == -1 and self.speed != 0:
                self.turn()
            elif self.dir == 0:
                self.dir = 1
            self.accelerate()
            if self.rect.centerx >= self.screen_rect.width/2:
                self.gamemap.scroll(self.speed)
            else:
                self.rect.x += self.dir * self.speed
        else:
            self.decelerate()
            if self.rect.x > 0 and self.rect.right < self.screen_rect.width:
                self.rect.x += self.dir * self.speed
            if self.rect.centerx >= self.screen_rect.width / 2:
                self.gamemap.scroll(self.speed)

        self.rect.y -= self.jump_speed
        self.gamemap.collide(self)
        self.animate()
        self.blitme()

    def animate(self):
        if pygame.time.get_ticks() - self.last_img_update >= 50:
            if self.jumping:
                img_string = "media/images/mario/jumping_1.png"
                self.image = pygame.image.load(img_string)
                self.image = pygame.transform.scale(self.image, (35, 50))
                if self.dir == -1:
                    self.image = pygame.transform.flip(self.image, 1, 0)
            elif self.moving_right or self.moving_left:
                if self.gamemap.object_touching_ground:
                    img_string = "media/images/mario/walking_" + str(self.last_img_mode) + ".png"
                    self.image = pygame.image.load(img_string)
                    self.image = pygame.transform.scale(self.image, (35, 50))
                    if self.dir == -1:
                        self.image = pygame.transform.flip(self.image, 1, 0)

            else:
                img_string = "media/images/mario/standing.png"
                self.image = pygame.image.load(img_string)
                self.image = pygame.transform.scale(self.image, (35, 50))
                if self.dir == -1:
                    self.image = pygame.transform.flip(self.image, 1, 0)

            if self.last_img_mode == 4:
                self.last_img_mode = 1
            else:
                self.last_img_mode += 1
            self.last_img_update = pygame.time.get_ticks()

    def accelerate(self):
        if self.speed == 0:
            self.speed = 2 + Mario.ACCEL_FACTOR
        if self.speed < Mario.SPEED_CAP:
            self.speed *= 1 + Mario.ACCEL_FACTOR

    def decelerate(self):
        if self.speed >= Mario.ACCEL_FACTOR:
            self.speed -= Mario.DECEL_FACTOR
        else:
            self.speed = 0
            self.dir = 0

    def turn(self):
        if self.speed >= Mario.ACCEL_FACTOR:
            self.speed -= Mario.TURN_FACTOR
        else:
            self.speed = 0
            self.dir *= -1

    def jump(self):
        if not self.jump_finished:
            self.jump_start = True
            if self.jump_speed <= 0:
                self.jump_speed = 7
            else:
                self.jump_speed -= Mario.FALL_FACTOR
                if self.jump_speed <= 0:
                    self.jump_finished = True
                elif self.gamemap.object_touching_ground(self):
                    self.jump_finished = True

        else:
            self.jump_speed -= Mario.FALL_FACTOR
            if self.gamemap.object_touching_ground(self):
                self.jump_finished = False
                self.jump_start = False

    def blitme(self):  # Blit Mario
        self.screen.blit(self.image, self.rect)


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2017/9/26

import re
def md(date_list,symbol):
    '''
    :param date_list: 匹配到的表达式
    :param symbol: 符号
    :return: 乘数计算得到的值
    '''
    a = date_list.index(symbol)  #取到符号
    # print(a)
    if symbol == '*' and date_list[a + 1] != '-': #如果是乘号并且索引的下一个位置不是负号计算
        k = float(date_list[a - 1]) * float(date_list[a + 1])
    elif symbol == '/' and date_list[a + 1] != '-':  #如果是除号并且索引的下一个位置不是负号计算
        k = float(date_list[a - 1]) / float(date_list[a + 1])
    elif symbol == '*' and date_list[a + 1] == '-': #如果是乘号并且索引的下一个位置是负号计算
        k = -(float(date_list[a - 1]) * float(date_list[a + 2]))
    elif symbol == '/' and date_list[a + 1] == '-': #如果是除号并且索引的下一个位置是负号计算
        k = -(float(date_list[a - 1]) / float(date_list[a + 2]))
    del date_list[a - 1], date_list[a - 1], date_list[a - 1] #删除列表里参与计算的索引位置
    date_list.insert(a - 1, str(k))  #把新的值插入到列表中
    return date_list

#处理混乱的四则，按照先算乘除后加减的原则
def fun(s):
    '''
    :param s: 去除括号后的表达式
    :return: 表达式的返回值
    '''
    list_str = re.findall('([\d\.]+|/|-|\+|\*)',s) #匹配表达式
    # print(list_str)
    sum=0
    while True:
        #先算*/后算+-
        if '*' in list_str and '/' not in list_str:  #判断*在表达式内,/不在
            md(list_str, '*')
        elif '*' not in list_str and '/' in list_str: #判断*不在表达式内,/在
            md(list_str, '/')                   #调用md函数处理除号
        elif '*' in list_str and '/' in list_str: #判断*在表达式内,/也在
            a = list_str.index('*')
            b = list_str.index('/')
            if a < b:
                md(list_str, '*')
            else:
                md(list_str, '/')
        else:
            if list_str[0]=='-':   #判断首个数字是否是负号
                list_str[0]=list_str[0]+list_str[1]
                del list_str[1]
            sum += float(list_str[0])
            #3+1-4+7
            for i in range(1, len(list_str), 2):    #1,3,5,7,9
                if list_str[i] == '+' and list_str[i + 1] != '-':
                    sum += float(list_str[i + 1])
                elif list_str[i] == '+' and list_str[i + 1] == '-':
                    sum -= float(list_str[i + 2])
                elif list_str[i] == '-' and list_str[i + 1] == '-':
                    sum += float(list_str[i + 2])
                elif list_str[i] == '-' and list_str[i + 1] != '-':
                    sum -= float(list_str[i + 1])
            break
    return sum

a=input("请输入算式：")#a='1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
#循环去除括号
while True:
    ret = re.split('\(([^()]+)\)', a , 1)
    # print(ret)
    if len(ret) == 3:
        a,b,c = re.split('\(([^()]+)\)', a, 1)
        rec = fun(b)
        a = a + str(rec) + c
    else:
        red = fun(a)
        print(red)
        break


cred = 'Your servive account file path'

FCM_DJANGO_SETTINGS = {
    "FCM_SERVER_KEY": "your key",
    # true if you want to have only one active device per registered user at a time
    # default: False
}

FCM_API_KEY="your key"


import direct.showbase.ShowBase as p3d_SB
import panda3d.core as p3d_Core

class MyApp(p3d_SB.ShowBase):
    def __init__(self):
        p3d_SB.ShowBase.__init__(self)

        self.icosphere = self.loader.loadModel("res/models/icosphere") #Load model
        self.icosphere.reparentTo(self.render)  #Parent model under render in the scene graph

        self.dlight_main = p3d_Core.DirectionalLight("Main light")
        self.dlight_main.setColor(p3d_Core.VBase4(1,0,0,1))
        self.dlnp = self.render.attachNewNode(self.dlight_main)
        self.dlnp.setHpr(0, -60, 0)
        self.render.setLight(self.dlnp)

        #Note: The object is actually shaded but the directional light source is acting wierd.
	#Note: Try a point light instead and shading will be obvious

if __name__ == "__main__":
    app = MyApp()
    app.run()

Panda3D/panda1/ex08 - lighting1 BROKEN/main.py


from django.urls import path
from . views import UploadAPIView, SharedAPIView, DetailShare, DetailUpload

urlpatterns = [

path('upload', UploadAPIView.as_view(), name="uploadapi"),
path('upload/<int:pk>/', DetailUpload.as_view(), name="detail_uploadapi"),
path('share', SharedAPIView.as_view(), name="sharedapi"),
path('share/<int:pk>/', DetailShare.as_view(), name="detail_sharedapi"),

]


import pdb
import infra.config.base        as base
import iris.config.hal.defs          as haldefs
import infra.common.defs        as defs

from infra.common.logging import logger

class SvcObject(base.ConfigObjectBase):
    def __init__(self, spec):
        super().__init__()
        self.proto = spec.proto
        self.dst_port =  getattr(spec, 'dst_port',-1)
        self.icmp_msg_type = getattr(spec, 'icmp_type', 0)
        self.alg = getattr(spec, 'alg',"NONE")
        return

    def PrepareHALRequestSpec(self, req_spec):
        req_spec.match.protocol = self.proto
        proto_str = 'IPPROTO_' + defs.ipprotos.str(self.proto)
        logger.info("prot %s" %(proto_str))
        if proto_str in ('IPPROTO_ICMP', 'IPPROTO_ICMPV6'):
            req_spec.match.app_match.icmp_info.icmp_type = self.icmp_msg_type
        else:
            if self.dst_port != -1:
                app_match = req_spec.match.app_match
                dst_port_range = app_match.port_info.dst_port_range.add()
                dst_port_range.port_low = self.dst_port
                dst_port_range.port_high= self.dst_port

        if self.alg is not "None":
            app_data = req_spec.action.app_data;
            alg_name = "APP_SVC_" + self.alg
            app_data.alg = haldefs.nwsec.ALGName.Value(alg_name)
            if (alg_name == "APP_SVC_FTP"):
                app_data.ftp_option_info.allow_mismatch_ip_address=1
            elif (alg_name == "APP_SVC_MSFT_RPC"):
                rpc_data = app_data.msrpc_option_info.data.add()
                rpc_data.program_id = "e1af8308-5d1f-11c9-91a4-08002b14a0fa"
                rpc_data.idle_timeout = 3600000
                rpc_data = app_data.msrpc_option_info.data.add()
                rpc_data.program_id = "12345778-1234-abcd-ef00-0123456789ac"
                rpc_data.idle_timeout = 3600000
                app_data.idle_timeout = 3600000
            elif (alg_name == "APP_SVC_SUN_RPC"):
                rpc_data = app_data.sun_rpc_option_info.data.add()
                rpc_data.program_id = "100000"
                rpc_data.idle_timeout = 3600000
                rpc_data = app_data.sun_rpc_option_info.data.add()
                rpc_data.program_id = "100024"
                rpc_data.idle_timeout = 3600000
                app_data.idle_timeout = 3600000
        return

class RuleObject(base.ConfigObjectBase):
    def __init__(self):
        super().__init__()
        self.svc_objs =[]
        self.apps =[]

    def Init(self, spec):
        self.action = spec.action.upper()
        self.log    = spec.log
        for svc_spec in spec.svcs:
            svc_obj = SvcObject(svc_spec.svc)
            self.svc_objs.append(svc_obj)
        if hasattr(spec, 'apps'):
            for app_spec in spec.apps:
                self.apps.append(app_spec.app.upper())
        return

    def PrepareHALRequestSpec(self, req_spec):
        if len(self.apps) > 0:
            req_spec.appid.extend(self.apps)

        action = "FIREWALL_ACTION_" + self.action
        req_spec.action.sec_action = haldefs.nwsec.FirewallAction.Value(action)
        req_spec.action.log_action = self.log
        return


from ..lo_char import *

class Emily(Character):
    _id = 68
    name = "에밀리"
    code = "BR_Emily"
    group = Group.AA_CANNONIERS
    isenemy = False
    is21squad = False

    def isformchanged(self):
        return bool(self.find_buff(type_=BT.GIMMICK, tag=Gimmick.EMILY))

    def skill_idx_convert(self, skill_idx):
        if skill_idx == 1 and self.isformchanged():
            return 6
        return skill_idx

    def _active1(self,
                 targets: Dict['Character', NUM_T],
                 atk_rate: Dict['Character', Tuple[NUM_T, NUM_T]],
                 bv: Sequence[NUM_T],
                 wr: NUM_T,
                 element: int):
        for t in targets:
            if targets[t] > 0:
                if t.find_buff(type_=BT.MARKED, efft=BET.DEBUFF):
                    t.give_buff(BT.TAKEDMGINC, 1, bv[0], efft=BET.BUFF, overlap_type=BOT.INSTANCE, desc="포착")
        return {t: (self.calc_damage(t, atk_rate[t], element=element, wr=wr) if targets[t] > 0 else 0) for t in targets}

    def _active2(self,
                 targets: Dict['Character', NUM_T],
                 atk_rate: Dict['Character', Tuple[NUM_T, NUM_T]],
                 bv: Sequence[NUM_T],
                 wr: NUM_T,
                 element: int):
        if self.find_buff(tag="Emily_P1"):
            pbuffs = True
        else:
            pbuffs = False
        for t in targets:
            if targets[t] > 0:
                if pbuffs:
                    t.give_buff(BT.REMOVE_BUFF, 0, 1, data=D.BuffCond(type_=BT.BARRIER, efft=BET.BUFF))
                    t.give_buff(BT.REMOVE_BUFF, 0, 1, data=D.BuffCond(type_=BT.TAKEDMGDEC, efft=BET.BUFF))
                if targets[t] > 1:
                    t.give_buff(BT.TAKEDMGINC, 1, bv[0], overlap_type=BOT.INSTANCE, desc="회심의 일격")
        return {t: (self.calc_damage(t, atk_rate[t], element=element, wr=wr) if targets[t] > 0 else 0) for t in targets}

    def _passive1(self, tt: str, args: Optional[Dict[str, Any]], targets: List[Tuple[int, int]], bv: List[NUM_T]):
        if tt == TR.IDLE:
            desc = "출력 강화"
            self.give_buff(BT.CRIT, 0, bv[0], round_=3, efft=BET.BUFF, desc=desc, tag="Emily_P1_CRIT")
            self.give_buff(BT.DEFPEN, 0, bv[1], round_=3, efft=BET.BUFF, desc=desc, tag="Emily_P1_DEFPEN")
            self.give_buff(BT.IGNORE_BARRIER_DMGDEC, 0, 1, round_=3, efft=BET.BUFF, desc=desc, tag="Emily_P1_IGN",
                           overlap_type=BOT.RENEW)
            self.give_buff(BT.ATK, 1, bv[2], round_=3, efft=BET.BUFF, desc=desc, tag="Emily_P1_ATK")

    def _passive2(self, tt: str, args: Optional[Dict[str, Any]], targets: List[Tuple[int, int]], bv: List[NUM_T]):
        if tt == TR.ATTACK:
            if self.find_buff(
                    func=lambda b:
                    (b.type == BT.FOLLOW_ATTACK and b.efftype == BET.BUFF) or b.type == BT.TARGET_PROTECT):
                self.give_buff(BT.AP, 0, bv[0], efft=BET.BUFF, desc="급속 충전")

    def _passive3(self, tt: str, args: Optional[Dict[str, Any]], targets: List[Tuple[int, int]], bv: List[NUM_T]):
        if tt in {TR.ROUND_START, TR.ATTACK, TR.GET_ATTACKED} and self.hp / self.maxhp <= d('.33'):
            self.give_buff(BT.GIMMICK, 0, 1, max_stack=1, tag=Gimmick.EMILY, desc="폼 체인지")
            self.give_buff(BT.ATK, 1, bv[1], max_stack=1, efft=BET.BUFF, desc=Gimmick.EMILY, tag="Emily_P3_ATK",
                           overlap_type=BOT.SINGLE)
            self.give_buff(BT.SPD, 1, bv[1], max_stack=1, efft=BET.BUFF, desc=Gimmick.EMILY, tag="Emily_P3_SPD",
                           overlap_type=BOT.SINGLE)
            self.give_buff(BT.EVA, 0, bv[2], max_stack=1, efft=BET.BUFF, desc=Gimmick.EMILY, tag="Emily_P3_EVA")
        if tt == TR.ATTACK:
            self.give_buff(BT.PHYSICAL_DOT_DMG, 0, bv[0], round_=1, desc="과부하")

    def _factive2(self,
                  targets: Dict['Character', NUM_T],
                  atk_rate: Dict['Character', Tuple[NUM_T, NUM_T]],
                  bv: Sequence[NUM_T],
                  wr: NUM_T,
                  element: int):
        for t in targets:
            if targets[t] > 0:
                t.give_buff(BT.REMOVE_BUFF, 0, 1, data=D.BuffCond(type_=BT.BARRIER, efft=BET.BUFF))
                t.give_buff(BT.REMOVE_BUFF, 0, 1, data=D.BuffCond(type_=BT.TAKEDMGDEC, efft=BET.BUFF))
                if targets[t] > 1:
                    t.give_buff(BT.TAKEDMGINC, 1, bv[0], overlap_type=BOT.INSTANCE, desc="회심의 일격")
        return {t: (self.calc_damage(t, atk_rate[t], element=element, wr=wr) if targets[t] > 0 else 0) for t in targets}


from cs50 import get_int

def main():
  while True:
    n = get_int("Size: ")
    if n > 0:
        break

  for i in range(n):
    for j in range(n):
        print("?", end="")
    print()

if __name__ == "__main__":
    main()


# Inizializzazione del motore grafico PyGame
import pygame
pygame.init()
clock = pygame.time.Clock()

# Definizione costanti
NERO = (0, 0, 0)
VERDE = (0, 255, 0)
ROSSO = (255, 0, 0)
BIANCO = (255, 255, 255)
BLU = (64,131,239)
GRIGIO = (100, 100, 100)
GIALLO = (239,223,64)
MARRONE = (155,101,0)
ROSA = (244,66,215)
SPESSORE_LINEA = 20
SPESSORE_PUNTO = 15
ALTEZZA = 600
LARGHEZZA = 800
rettangolo = False
cerchio = False

# Creazione della finestra di pygame
pygame.display.set_caption("Paint Me")
area = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
area.fill(GRIGIO)

# Aggiungere qui la creazione della lavagna dove scrivere
lavagna = pygame.Surface((LARGHEZZA-30, ALTEZZA-30))
lavagna.fill(BIANCO)

# Inizializzazione cursore del mouse
mouse = pygame.mouse
mouse.set_visible(False)
colore_penna = NERO

# Ripeti fino a quando l'untente non esce e ad ogni iterazione
while True:
    # Gestore delle azioni dell'utente
    for evento in pygame.event.get():
        # Se l'utente clicca il bottone chiudi sulla finestra
        if evento.type == pygame.QUIT:
            exit()
        if evento.type == pygame.MOUSEBUTTONDOWN:
            if red_rect.collidepoint(evento.pos):
                colore_penna = ROSSO
            if green_rect.collidepoint(evento.pos):
                colore_penna = VERDE
            if black_rect.collidepoint(evento.pos):
                colore_penna = NERO
            if blue_rect.collidepoint(evento.pos):
                colore_penna = BLU
            if brown_rect.collidepoint(evento.pos):
                rettangolo = True
                print("sto pigiando marrone")
            if pink_rect.collidepoint(evento.pos):
                cerchio = True

            if yellow_rect.collidepoint(evento.pos):
                lavagna.fill(BIANCO)
    sinistro, centrale, destro = mouse.get_pressed()
    # Se l'utente clicca con il mouse all'interno della finestra di gioco
    if sinistro:
        mouse_pos = mouse.get_pos()  # mouse_pos = (x,y)  # x = mouse_pos[0] y = mouse_pos[1]
        print(mouse_pos)
        xa = mouse_pos[0]
        ya = mouse_pos[1]
        xb = xa + 200
        yb = ya + 200

        if rettangolo == True:
            cerchio = False
            pygame.draw.rect(lavagna,MARRONE, (xa,ya,xb,yb),22)
            print("sto disegnando un rettangolo")
        if cerchio == True:
            rettangolo = False
            pygame.draw.circle(lavagna,(ROSA),(mouse_pos),50,10)

        else:# L'utente ha cliccato il bottone sinistro del mouse
            pygame.draw.circle(lavagna,colore_penna,mouse_pos,SPESSORE_PUNTO)
            if mouse_pos_vecchia is not None:
                 pygame.draw.line(lavagna,colore_penna,mouse_pos_vecchia, mouse_pos,SPESSORE_LINEA)
            mouse_pos_vecchia = mouse_pos
    elif destro:
        mouse_pos = mouse.get_pos()
        colore_penna = BIANCO
        if mouse_pos_vecchia is not None:
            pygame.draw.line(lavagna,colore_penna,mouse_pos_vecchia, mouse_pos,SPESSORE_LINEA)
        mouse_pos_vecchia = mouse_pos
    else:
        mouse_pos_vecchia = None
    area.fill(GRIGIO)
    red_rect = pygame.draw.rect(area,ROSSO, ((LARGHEZZA-30, 0), (30,30)))
    green_rect = pygame.draw.rect(area,VERDE, ((LARGHEZZA-30, 30), (30,30)))
    black_rect = pygame.draw.rect(area,NERO, ((LARGHEZZA-30, 60), (30,30)))
    blue_rect = pygame.draw.rect(area,BLU, ((LARGHEZZA-30,90), (30,30)))
    yellow_rect = pygame.draw.rect(area,GIALLO, ((LARGHEZZA-30,120), (30,30)))
    brown_rect = pygame.draw.rect(area,MARRONE, ((LARGHEZZA-30,150), (30,30)))
    pink_rect = pygame.draw.rect(area,ROSA, ((LARGHEZZA-30,180), (30,30)))
    # Disegno la lavagna all'interno dell'area
    area.blit(lavagna,(0,0))

    # Disegno il puntatore del mouse con il colore selezionato
    pygame.draw.circle(area, colore_penna, (mouse.get_pos()), SPESSORE_PUNTO)

    # Aggiorna lo schermo con tutto quello che è stato disegnato
    pygame.display.flip()
    clock.tick(60)


import heapq

V, E = map(int, input().split())
W = [[0] * (V + 1)]
for i in range(E):
    s, e, w = map(int, input().split())
    W[s].append((e, w))

def dijkstra(start):
    INF = 1e9
    costs = [INF] * (V + 1)
    costs[start] = 0

    heap = []
    heapq.heappush(heap, (0, start))

    while heap:
        cost, v = heapq.heappop(heap)

        if cost > costs[v]:
            continue

        for e, w in W[s]:
            if costs[e] > costs[s] + w:
                costs[e] = costs[s] + w
                heapq.heappush(heap, (costs[e], e))

dijkstra(1)


from os import system
system('clear')

print(':::Welcome to PI to nth decimal Printer:::\n')
pi = 22/7
choice = True
while choice:
    n = int(input('Enter to how many decimal places the pi value needs to be printed(Upto 51): '))
    print(f'Value of pi: {pi:1.{n}f}')
    c = input('Do you want to quit(y/n): ')
    if c == 'y':
        choice = False


import sys
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sys.path.append('../')

from functions import *

data = pd.read_csv("../../data/demeaned.csv")
data = data[["residual", "sellerfeedbackscore", "ispolice", "id"]]
data.sellerfeedbackscore = np.log(data.sellerfeedbackscore+1)

plt.style.use('tableau-colorblind10')
plt.rcParams['figure.figsize'] = (4,4)
plt.rcParams['figure.dpi'] = 150
plt.rcParams['text.color'] = 'black'
plt.rcParams['axes.labelcolor'] = 'black'
plt.rcParams['xtick.color'] = 'black'
plt.rcParams['ytick.color'] = 'black'
plt.rcParams['axes.titlepad'] = 10
plt.rcParams['axes.titleweight'] = 1000
plt.rcParams['axes.labelpad'] = 5
plt.rcParams['font.family'] = 'serif'
plt.rcParams['axes.facecolor'] = 'white'

data = data.assign(_ispolice=data.ispolice.map({0: "Not Police", 1: "Police"}))
p = sns.jointplot(data=data, x="residual", y="sellerfeedbackscore", hue="_ispolice", kind="hist")

plt.xlabel("(Normalised) Bid")
plt.ylabel("(Logged) Seller Feedback Score")
ax = p.fig.gca()
ax.get_legend().set_title("")
p.fig.tight_layout()

p.fig.savefig("jointplot.jpeg", dpi=p.fig.dpi, bbox_inches='tight')


from bmb.deprecated.v1.source.standard_import import *
from bmb.deprecated.v1.source.webscraping     import films_available_to_stream

class IngestionDB( SQLiteDB):
    DEFAULT_DB = V1_RESOURCE_DIRECTORY / "Web Ingestion.db"

    id_tables = {
        "Streamer"      : ( "name",        ),
        "JustwatchFilm" : ( "url" ,        ),
        "TMDbFilm"      : ( 'title', 'year') }

    def JustwatchFilm( self, url):
        FILM_TABLE = "JustwatchFilm"
        if not self.id( FILM_TABLE, url):
            self.insert( FILM_TABLE, url=url, added=self.date_str )
        return self.id( FILM_TABLE, url)

    def Streamer_key( self, streamer_name):
        STREAMER_TABLE = "Streamer"
        if not self.select_one( STREAMER_TABLE, name=streamer_name):
            raise Unknown_Streaming_Service( streamer_name )
        return self.select_one( 'key', STREAMER_TABLE, name=streamer_name)

    def confirm_active_stream( self, streamer_id, film_id, date_str):
        if not self.get( "SELECT * FROM JustwatchState WHERE streamer=? AND film=? AND removed IS NULL", streamer_id, film_id):
            self.insert( "JustwatchState", streamer=streamer_id, film=film_id, added=date_str )
        self.set( "UPDATE JustwatchState SET confirmed=? WHERE streamer=? AND film=? AND removed IS NULL", date_str, streamer_id, film_id)

    def all_title_year_combinations( self):
        return self.get( query.JUSTWATCH_FILMS)

    def identify_all_JustwatchFilm_URLs( self, **kw):
        unknown_urls = self.get( "SELECT url from JustWatchFilm WHERE title is Null")
        for url in jupyter_aware_tqdm( unknown_urls, **kw):
            soup = safe_soup( url)
            tb   = soup.find( class_='title-block')
            if not tb:
                raise Justwatch_Webscraping_Error( utl)
            title, year = tb.find( 'h1').text.strip(), int( tb.find( class_='text-muted').text.split( '(')[1].split(')')[0])
            self.set( "UPDATE JustwatchFilm SET title=?, year=? WHERE url=?", title, year, url)


import sys

K=int(sys.stdin.readline())
VisitRoutine=list(map(int,sys.stdin.readline().strip().split()))

#각 레벨당 노드의 개수
NLN=[0] #index 1=level 1 = root node의 개수
for k in range(K):
	NLN.append(2**k)

Tree=[0]*(len(VisitRoutine)+1)
matchList=[] #상근이가 도시를 방문한 순서의 Tree 인덱스들

def It(startnode):
	if startnode > len(VisitRoutine):
		return
	L = int(startnode*2)
	R= int(startnode*2+1)
	It(L)
	matchList.append(startnode)
	It(R)

It(1)

for i in range(len(VisitRoutine)):
	Tree[matchList[i]]=VisitRoutine[i]

start=1
for p in range(1,K+1):
	print(*Tree[start:start+NLN[p]])
	start+=NLN[p]


from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton

START_TEXT = """
Hello {} :D
I am an asv link shortner telegram bot.

>> `I can short any type of link ....`

contact me @asv_chat01_bot <3
"""

START_BUTTONS = InlineKeyboardMarkup(
        [[
        InlineKeyboardButton('⚙ Join asv bot Channel ⚙', url='https://telegram.me/asvbots')
        ]]
    )

@Client.on_message(filters.private & filters.command(["start"]))
async def start(bot, update):
    await update.reply_text(
        text=START_TEXT.format(update.from_user.mention),
        reply_markup=START_BUTTONS,
        disable_web_page_preview=True
    )


import logging
import unittest
from typing import List

import numpy as np
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from ddt import ddt, data as test_data, unpack
from qiskit.circuit.measure import measure
from qiskit.providers import BaseBackend, BaseJob
from qiskit.result import Result

import dc_qiskit_algorithms.MöttönenStatePreparation

logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger('test_DraperAdder')

# noinspection NonAsciiCharacters
@ddt
class MöttönenStatePrepTests(unittest.TestCase):

    def execute_test(self, vector: List[float]):
        probability_vector = [np.absolute(e)**2 for e in vector]

        qubits = int(np.log2(len(vector)))
        reg = QuantumRegister(qubits, "reg")
        c = ClassicalRegister(qubits, "c")
        qc = QuantumCircuit(reg, c, name='state prep')
        qc.state_prep_möttönen(vector, reg)

        local_backend = qiskit.Aer.get_backend('statevector_simulator')  # type: BaseBackend

        job = qiskit.execute(qc, backend=local_backend, shots=1)  # type: BaseJob
        result = job.result()  # type: Result

        # State vector
        result_state_vector = result.get_statevector('state prep')
        print(["{0:.2f}".format(e) for e in result_state_vector])
        # Try to find a global phase
        global_phase = set([np.angle(v) - np.angle(rv) for v, rv in zip(vector, result_state_vector)
                            if abs(v) > 1e-3 and abs(rv) > 1e-3])
        global_phase = global_phase.pop() or 0.0
        result_state_vector = np.exp(1.0j * global_phase) * result_state_vector
        for expected, actual in zip(vector, result_state_vector):
            self.assertAlmostEqual(actual.imag, 0.0, places=6)
            self.assertAlmostEqual(expected, actual.real, places=6)

        # Probability vector from state vector
        result_probability_vector = [np.absolute(e)**2 for e in result_state_vector]
        print(["{0:.3f}".format(e) for e in result_probability_vector])
        for expected, actual in zip(probability_vector, result_probability_vector):
            self.assertAlmostEqual(expected, actual, places=2)

        # Probability Vector by Measurement
        measure(qc, reg, c)
        local_qasm_backend = qiskit.Aer.get_backend('qasm_simulator')  # type: BaseBackend
        shots = 2**12
        job = qiskit.execute(qc, backend=local_qasm_backend, shots=shots)  # type: BaseJob
        result = job.result()  # type: Result
        counts = result.get_counts('state prep')
        measurement_probability_vector = [0.0 for e in result_state_vector]
        for binary, count in sorted(counts.items()):
            index = int(binary, 2)
            probability = float(count) / float(shots)
            print("%s (%d): %.3f" % (binary, index, probability))
            measurement_probability_vector[index] = probability

        print(["{0:.3f}".format(e) for e in measurement_probability_vector])
        for expected, actual in zip(probability_vector, measurement_probability_vector):
            self.assertAlmostEqual(expected, actual, delta=0.02)

    @unpack
    @test_data(
        {'vector': [-0.1, 0.2, -0.3, 0.4, -0.5, 0.6, -0.7, 0.8]},
        {'vector': [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
        {'vector': [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
        {'vector': [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
        {'vector': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]},
        {'vector': [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]},
        {'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]},
        {'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]},
        {'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]}
    )
    def test_state_preparation(self, vector):
        vector = np.asarray(vector)
        vector = (1 / np.linalg.norm(vector)) * vector
        self.execute_test(list(vector))

    def test_instantiation(self):
        gate = dc_qiskit_algorithms.MöttönenStatePreparationGate([1.0, 0.0])
        self.assertIsInstance(gate, dc_qiskit_algorithms.MöttönenStatePreparationGate)

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


#deleting is missing here
class node:
    def __init__(self, data):
        self.data = data
        self.next = None

class CircularLinkedList:
    def __init__(self):
        self.head = None

    def addFirst(self, key):
        newNode = node(key)
        if(self.head == None):
            self.head = newNode
            newNode.next = newNode
        else:
            last = self.head
            while(last.next != self.head): #This is not None and root node
                last = last.next
            last.next = newNode
            newNode.next = self.head
            self.head = newNode

    def addLast(self, key):
        newNode = node(key)
        if(self.head == None):
            newNode.next = newNode
            self.head = newNode
        else:
            last = self.head
            while(last.next != self.head):
                last = last.next
            last.next = newNode
            newNode.next = self.head

    def printList(self):
        temp = self.head
        if(temp == None):
            print("Empty")
        while True:
            print(temp.data)
            temp = temp.next
            if(temp == self.head):
                break

    def search(self, key):
        if(self.head == None):
            print("llist empty")
            return

        temp = self.head
        while True:
            if(temp.data == key):
                print("match found")
                return 1
            else:
                temp = temp.next
            if(temp == self.head):
                return 0
        return 0

    def delete(self, key):

        if self.head == None:
            return

llist = CircularLinkedList()
print("Inserting Element: 10")
llist.addFirst(10)
print("Inserting Element: 20")
llist.addFirst(20)
print("Inserting Element: 30")
llist.addFirst(30)
print("Circular Linked List Elements Are:")
llist.printList()
print("Inserting Element: 10")
llist.addLast(10)

print("Inserting Element: 20")
llist.addLast(20)

print("Inserting Element: 30")
llist.addLast(30)

print("Circular Linked List Elements Are:")
llist.printList()

print("Is value in linkedlist = {}".format(llist.search(20)))

print("Deleting Element: ",30)
llist.delete(30)

print("The LinkedList Elements Are [After Deletion]:")
llist.printList()


from typing import Any
import wx
import wx.adv as wxadv
import wx.grid as gridlib
from cfind import CFind
from pacs_config import  Configuration
from helpers import json_serial
from constants import COLS
from download_history import DownloadHistory
import datetime

def get_pacs_details():
    pacs_config_data  = json_serial('pcv1_file.json')
    configured_pacs = pacs_config_data['configured_pacs']
    configured_pacs_mapper = {}
    all_pacs = []
    for i, pacs_obj in enumerate(configured_pacs):
        configured_pacs_mapper[pacs_obj['AE TITLE']] = pacs_obj
        all_pacs.append(pacs_obj['AE TITLE'])
    return configured_pacs_mapper, all_pacs, configured_pacs

class Browse(wx.Frame):

    CONFIGURED_PACS_MAPPER, ALL_PACS, CONFIGURED_PACS = get_pacs_details()
    def __init__(self, title:str ="Browse and Download", size:tuple=(800, 550)) -> None:
        #TODO: Use post_init func for calling func when obj get initialized
        wx.Frame.__init__(self, None, -1, title, size =size, style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
        self.panel = wx.Panel(self, wx.ID_ANY, size=size)
        self.main_layout = wx.BoxSizer(wx.VERTICAL)
        self.configured_pacs_mapper = self.CONFIGURED_PACS_MAPPER
        self.all_pacs = self.ALL_PACS
        self.configured_pacs = self.CONFIGURED_PACS
        self.create_ui()
        self.panel.SetSizer(self.main_layout)

    def create_line(self, horizontal:int =1) -> None:
        if horizontal:
            self.sl = wx.StaticLine(self.panel, 1, style=wx.LI_HORIZONTAL)
        else:
            self.sl = wx.StaticLine(self.panel, 2, style=wx.LI_VERTICAL)
        self.main_layout.Add(self.sl, 0, wx.EXPAND | wx.ALL, 1)

    def create_ui(self) -> None:
        self.main_layout.Add(self.create_header_1(), 0, wx.EXPAND | wx.ALL, 1)
        self.create_line()
        self.main_layout.Add(self.create_header_2(), 0, wx.EXPAND | wx.ALL, 1)
        self.main_layout.Add(self.create_show_search_result([]), 1, wx.EXPAND | wx.ALL, 1)
        self.main_layout.Add(self.create_image_details(size = (-1,130)), 1, wx.EXPAND | wx.ALL, 1)
        self.main_layout.Add(self.create_footer(),1, wx.RIGHT, 1)

    def create_select_box(self, locations:list, cur_selection:int=0, **kwargs) -> wx.ComboBox:
        combo = wx.ComboBox(self.panel, choices=locations, style =wx.CB_DROPDOWN | wx.CB_SORT)
        combo.SetSelection(cur_selection)
        combo.Bind(wx.EVT_COMBOBOX_CLOSEUP, lambda event: self.on_selection_X(event, **kwargs))
        return combo

    def on_selection_X(self, event:wx.Event, **kwargs) ->None:
        obj = event.GetEventObject()
        selected_text = obj.GetStringSelection()
        idx = obj.FindString(selected_text)
        if kwargs.get('reactors'):
            reactors = kwargs.get('reactors')
            on_option = kwargs.get('on_option')
            if selected_text == on_option or idx == on_option:
                for reactor in reactors:
                    reactor.Enable()
            else:
                for reactor in reactors:
                    reactor.Disable()

    def popup(self, event:wx.Event)->None:
        pop = Configuration()
        pop.Show()
        pop.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, event:wx.Event)->None:
        obj = json_serial('pcv1_file.json')
        self.configured_pacs_mapper, self.all_pacs, self.configured_pacs = get_pacs_details()
        self.pacs_location.Clear()
        for i, pacs in enumerate(self.all_pacs):
            #self.pacs_location.Insert(pacs, i)
            self.pacs_location.Append(pacs)
        self.pacs_location.SetSelection(0)
        print("on close")

        event.Skip()

    def on_date_changed(self, event:wx.Event)->None:

        try:
            print(event.GetEventObject())
            print(dir (event.GetEventObject()) )
            print(event.GetEventObject().LabelText)
            print(f"cur_date is: {event.GetEventObject().GetValue()}")
        except Exception as e:
            print(f"ERROR IS: {e}")

    def date_range_helper(self, option:str)->str:
        if option == 'ALL': return "19000101-99991231"
        elif option == 'TODAY':
            # find today's date
            today = datetime.date.today()
            # format this in string of "YYYYMMDD"
            today = today.strftime("%Y%m%d")
            return f"{today}-{today}"
        elif option == 'YESTERDAY':
            # find yesterday's date
            yesterday = datetime.date.today() - datetime.timedelta(days=1)
            # format this in string of "YYYYMMDD"
            yesterday = yesterday.strftime("%Y%m%d")
            return f"{yesterday}-{yesterday}"

        elif option == 'LAST 7 DAYS':
            # find today's date
            today = datetime.date.today()
            # find 7 days before today's date
            last_7_days = today - datetime.timedelta(days=7)
            # format this in string of "YYYYMMDD"
            today = today.strftime("%Y%m%d")
            last_7_days = last_7_days.strftime("%Y%m%d")
            return f"{last_7_days}-{today}"

        elif option == 'LAST 30 DAYS':
            today = datetime.date.today()
            last_30_days = today - datetime.timedelta(days=30)
            today = today.strftime("%Y%m%d")
            last_30_days = last_30_days.strftime("%Y%m%d")
            return f"{last_30_days}-{today}"
        else:
            start_date_range = self.start_date_range.GetValue()
            start_date_range = start_date_range.FormatISODate().replace('-', '')
            end_date_range = self.end_date_range.GetValue().FormatISODate().replace('-', '')
            return f"{start_date_range}-{end_date_range}"

    def search_result(self, event:wx.Event, **kwargs)->None:
        """
        This function is called when the search button is clicked or Enter is pressed
        It Make CFIND Request to the PACS and get the result
        """

        #self.searching_text.Show()

        #print("searching....", self.searching_text.IsShown())

        # modalities = self.modalities.GetTextSelection()

        # get the value of the date range
        start_date_range = self.start_date_range.GetValue()
        # format this in string of "YYYYMMDD"
        start_date_range = start_date_range.FormatISODate().replace('-', '')
        print("*****************************************", type(start_date_range), start_date_range)

        # get the value of the end date range
        end_date_range = self.end_date_range.GetValue().FormatISODate().replace('-', '')

        # get date_range
        print("self data range 241: {self.all_dates.GetValue()}", self.all_dates.GetValue())

        date_range = self.date_range_helper(self.all_dates.GetValue())
        print("242: date_range", date_range)

        # get the value of the pacs location
        pacs_location = self.pacs_location.GetStringSelection()

        # get the value of the data type
        data_type = self.search_type.GetStringSelection()
        data_type = data_type.replace(' ', '')
        search_value = kwargs.get('obj').GetValue() if kwargs.get('obj') else self.search_textbox.GetValue()

        search_filter = {
            'PatientID': '*',
            'PatientName': '*',
            'AccessionNumber': '*',
        }
        search_filter[data_type] = search_value

        #host, port = self.configured_pacs_mapper.get(pacs_location).get('IP ADDRESS'), int(self.configured_pacs_mapper.get(pacs_location).get('PORT'))

        import threading
        import concurrent.futures
        from concurrent.futures import ThreadPoolExecutor
        def make_c_find_request(pacs_obj):
            thost = pacs_obj.get('IP ADDRESS')
            tport = pacs_obj.get('PORT', 104)
            cfind_obj = CFind(host=thost, port=tport)
            tmp_result = cfind_obj.make_request(aet='', aet_title='', StudyDate=date_range, pacs_location=pacs_location, PatientID=search_filter.get('PatientID', '*'), PatientName=search_filter.get('PatientName', '*'), AccessionNumber=search_filter.get('AccessionNumber', '*'))

            return tmp_result

        result = []
        threads = []
        self.searching_text.SetLabel("Searching.....")
        PUBLIC_PACS_SERVER = [{'IP ADDRESS': 'DicomServer.co.uk', 'PORT': 104}, {'IP ADDRESS': 'DicomServer.co.uk', 'PORT': 104}] #configured_pacs
        import time
        start_time = time.time()
        # for pacs_obj in PUBLIC_PACS_SERVER:
        #     thread = threading.Thread(target=make_c_find_request, args=(pacs_obj, result))
        #     threads.append(thread)
        #     thread.start()

        # for thread in threads:
        #     thread.join()

        with ThreadPoolExecutor(max_workers=len(PUBLIC_PACS_SERVER)) as executor:
            future_to_obj = {executor.submit(make_c_find_request, pacs_obj): pacs_obj for pacs_obj in PUBLIC_PACS_SERVER}
            for future in concurrent.futures.as_completed(future_to_obj):
                obj = future_to_obj[future]
                try:
                    tmp_result = future.result()
                except Exception as exc:
                    print('%r generated an exception: %s' % (obj, exc))
                else:
                    result.extend(tmp_result)

        end_time = time.time()
        print(f"Time taken is: {end_time - start_time}")
        # now we wanna  clear the table
        search_img_table = self.result_table
        # tags = ["PatientName", "PatientID", "StudyInstanceUID", "SeriesInstanceUID"]
        # now we wanna delete existing rows
        if search_img_table.GetNumberRows() > 0:
            search_img_table.DeleteRows(0, numRows=search_img_table.GetNumberRows())
        # now let's add the value
        try:
            tables_data = result
        except Exception as e:
            print(f"ERROR IS: {e}")
            tables_data = []

        for i in range(len(tables_data)):
            values = tables_data[i]
            search_img_table.AppendRows(numRows=1)
            for col_nu in range(search_img_table.GetNumberCols()):
                cols_name = search_img_table.GetColLabelValue(col_nu)
                cell_value = str(values.get(cols_name, 'NA'))

                search_img_table.SetCellValue( max(0, search_img_table.GetNumberRows()-1), col_nu, cell_value )
                search_img_table.SetCellOverflow(max(0, search_img_table.GetNumberRows()-1), col_nu,True)
        #self.searching_text.Hide()
        # get row len of the table
        row_len = search_img_table.GetNumberRows()
        print("row_len", row_len)
        self.searching_text.SetLabel(f"Total Result Found: {len(tables_data)}")

    def on_clear(self, event:wx.Event, obj:Any):
        obj.SetValue("")

    def on_selection(self, event:wx.Event):
        obj = event.GetEventObject()
        print(obj)
        row_id = event.GetRow()
        print(row_id)
        obj.SelectRow(row_id)
        d = {}
        for col in range(obj.GetNumberCols()):
            label = obj.GetColLabelValue(col)
            value = obj.GetCellValue(row_id, col)
            d[label] = value
            print(label, value)

        image_details_panel = self.img_details_table
        if image_details_panel.GetNumberRows() >0:
            image_details_panel.DeleteRows(0)
        image_details_panel.AppendRows(1)
        for col_nu in range(image_details_panel.GetNumberCols()):
            col_label = image_details_panel.GetColLabelValue(col_nu)
            print(d.get(col_label, "TEST DATA"))
            image_details_panel.SetCellValue(image_details_panel.GetNumberRows()-1, col_nu, d.get(col_label, "TEST DATA"))
        self.download_image_btn.Enable()

    def create_header_1(self):
        main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        #pacs configuration button
        pacs_config_button = wx.Button(self.panel, label="PACS Config")
        pacs_config_button.Bind(wx.EVT_BUTTON, self.popup)
        main_sizer.Add(pacs_config_button, 0, wx.ALL, 5)

        # pacs location selector
        self.pacs_locations_list = self.all_pacs
        self.pacs_location = self.create_select_box(self.pacs_locations_list, 0)
        main_sizer.Add(self.pacs_location, 0, wx.ALL, 5)

        # modalitites
        self.modalities_list = ["All Modalities", "CT", "MR", "US", "CR", "DX", "MG", "NM", "OT", "PT", "RF", "SC", "XA", "XC"]
        self.modalities = self.create_select_box(self.modalities_list, 0)
        main_sizer.Add(self.modalities, 0, wx.ALL, 5)

        #custom date range
        self.start_date_range = wxadv.DatePickerCtrl(self.panel, style=wxadv.DP_DROPDOWN)
        self.start_date_range.Bind(wxadv.EVT_DATE_CHANGED, self.on_date_changed)
        self.start_date_range.Disable()
        self.end_date_range = wxadv.DatePickerCtrl(self.panel, style=wxadv.DP_DROPDOWN)
        self.end_date_range.Bind(wxadv.EVT_DATE_CHANGED, self.on_date_changed)
        self.end_date_range.Disable()

        # all dates
        self.all_dates_list = ['ALL','Custom', 'Today', 'Yesterday', 'Last 7 Days']
        self.all_dates = self.create_select_box(self.all_dates_list, 0, reactors=[self.start_date_range, self.end_date_range], on_option='Custom')

        main_sizer.Add(self.all_dates, 0, wx.ALL, 5)
        main_sizer.Add(self.start_date_range, 0, wx.ALL, 5)
        main_sizer.Add(self.end_date_range, 0, wx.ALL, 5)

        return main_sizer

    def create_header_2(self):

        main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        #search type
        search_type_list = ["Patient ID", "Patient Name", "Accession Number"]
        self.search_type = self.create_select_box(search_type_list, 2)
        main_sizer.Add(self.search_type, 0, wx.ALL, 5)

        #textbox
        self.search_textbox = wx.TextCtrl(self.panel, size=(250, -1) ,style=wx.TE_PROCESS_ENTER)
        self.search_textbox.SetHint("Enter Search Text")
        self.search_textbox.Bind(wx.EVT_TEXT_ENTER, self.search_result)
        main_sizer.Add(self.search_textbox, 0, wx.ALL, 5)

        #search button
        search_button = wx.Button(self.panel, label="Search")
        search_button.Bind(wx.EVT_BUTTON, lambda event :self.search_result(event, obj= self.search_textbox))
        main_sizer.Add(search_button, 0, wx.ALL, 5)

        #clear button
        clear_button = wx.Button(self.panel, label="Clear")
        clear_button.Bind(wx.EVT_BUTTON, lambda event : self.on_clear(event, self.search_textbox))

        main_sizer.Add(clear_button, 0, wx.ALL, 5)

        return main_sizer

    def create_table(self, array:list, cols_list:list, size:tuple= (-1,200)) -> gridlib.Grid:
        self.grid_table = gridlib.Grid(self.panel, wx.ID_ANY, size=size)
        self.grid_table.CreateGrid(len(array), len(cols_list))
        self.grid_table.SetDefaultColSize(150)

        for i,col in enumerate(cols_list):
            self.grid_table.SetColLabelValue(i, col)

        for i, row in enumerate(array):
            for j, val in enumerate(row):
                self.grid_table.SetCellValue(i, j, str(val))
        self.grid_table.HideRowLabels()

        self.grid_table.SetScrollbars(100, 100, 10, 10)
        return self.grid_table

    def create_show_search_result(self, arr:list)-> wx.StaticBoxSizer:
        box = wx.StaticBox(self.panel, label='')
        main_sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        cols_list = COLS
        self.result_table = self.create_table(arr, cols_list)
        self.result_table.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.on_selection)
        main_sizer.Add(self.result_table, 1, wx.EXPAND | wx.ALL, 5)
        return main_sizer

    def create_image_details(self, size:tuple= (-1,200))-> wx.StaticBoxSizer:
        box = wx.StaticBox(self.panel, label='')
        main_sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        cols_list = COLS # ["Patient ID", "Patient Name", "Accession Number", "Modality", "Study Date", "Study Time", "Study Description"]
        self.img_details_table= self.create_table([], cols_list, size= size)
        main_sizer.Add(self.img_details_table, 1, wx.EXPAND | wx.ALL, 5)
        return main_sizer

    def create_footer(self)-> wx.BoxSizer:
        main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        #buttons
        #TODO: Shift the buttons to the right
        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.download_image_btn = wx.Button(self.panel, label = 'Download')
        self.download_image_btn.Disable()
        button_sizer.Add(self.download_image_btn, 0, wx.ALL, 5)
        # Searching Text String, it will be disabled but will be enabled once user enter the search button
        self.download_history = wx.Button(self.panel, label = 'Download History')
        self.download_history.Bind(wx.EVT_BUTTON, self.show_download_history)

        #button_sizer.Add(self.searching_text, 0, wx.ALL, 5)
        #self.searching_text.Hide()

        main_sizer.Add(button_sizer, 1, wx.RIGHT, 1)
        main_sizer.Add(self.download_history, 0, wx.ALL, 5)
        self.searching_text = wx.StaticText(self.panel, label="")
        main_sizer.Add(self.searching_text, 0, wx.ALL, 5)
        return main_sizer

    def show_download_history(self, event:wx.Event)->None:
        pop = DownloadHistory()
        pop.Show()
        pop.Bind(wx.EVT_CLOSE, self.on_close)

if __name__ == '__main__':
    app = wx.App()
    frame = Browse()
    frame.Show()
    app.MainLoop()