import math
def lcm(nums):
    a = nums[0]
    b = nums[1]
    curr_lcm = a*b//math.gcd(a,b)
    for num in nums[2:]:
        curr_lcm = curr_lcm*num//math.gcd(curr_lcm,num)
    return curr_lcm
try:
    T = int(input())
    T=T//2
    points = {"Darrell":0,"Sally":0}
    for cases in range(T):
        question_input = input()

        question_input = question_input.split()
        questioner = question_input[0]
        if(cases == 0):
            first_questioner = questioner
        number_string = question_input[1]
        nums = list(map(int,number_string.split(',')))

        assert(2<=len(nums)<=7)
        for num in nums:
            assert(1<=num<=100)
        print(f"{questioner}'s question is : {number_string}")
        answer_input = input().split()
        answerer = answer_input[1]
        if(case == 0):
            second_questioner = answerer
        correct_answer = lcm(nums)
        if answer_input[2] != 'PASS':
            ans =int(answer_input[2])
            if(ans == correct_answer):
                print('Correct Answer')
                print(f'{answerer} : 10points')
                points[answerer]+=10
            else:
                print('Incorrect Answer')
                print(f'{answerer} : 0points')

        else:
            print("Question is PASSed")
            print(f'Answer is {correct_answer}')
            print(f'{answerer}: 0points')
        if(case == N-1):
            print('Total Points')
            print(f'{first_questioner}: {points[first_questioner]}points')
            print(f'{second}: {point_dictionary[second]}points')
            if points["Darrell"] == points["Sally"]:
                print('Game Result: Draw')
            elif points["Darrell"] > points["Sally"]:
                print('Game Result: Darrell is Winner')
            else:
                print('Game Result: Sally is Winner')
except:
    print("Invalid Input")


import numpy as np

num_classes = 6  # 分类的数量
# 数据集中的所有类型的问题
all_labels = ['NUM', 'LOC', 'HUM', 'DESC', 'ENTY', 'ABBR']

class BatchGenerator(object):
    '''
    生成一批数据
    '''

    def __init__(self,batch_size, questions, labels, vocabulary_size, sent_length, dictionary):
        self.batch_size = batch_size
        self.questions = questions
        self.labels = labels
        self.text_size = len(questions)
        self.batch_size = batch_size
        self.data_index = 0
        self.vocabulary_size = vocabulary_size
        self.sent_length = sent_length
        self.dictionary = dictionary
        assert len(self.questions) == len(self.labels)

    def generate_batch(self):
        '''
        数据生成功能.这输出两个矩阵
        inputs: 一批问题，其中每个问题都是一个大小为[sent_length, vocabulary_size]的张量
        　　　　　每个单词都有一个one-hot编码.
        labels_ohe: 与输入中的问题相对应的one-hot编码标签
        '''

        # Numpy数组包含输入和标签数据：
        # 三维numpy.zeros(大行数，每一个大行中小行数，每一个大行中小列数)，注：默认大列为一列
        # 二维numpy.zeros(行数，列数)
        inputs = np.zeros((self.batch_size, self.sent_length, self.vocabulary_size), dtype=np.float32)
        labels_ohe = np.zeros((self.batch_size, num_classes), dtype=np.float32)

        # 当我们到达数据集的末尾时便从头再开始
        if self.data_index + self.batch_size >= self.text_size:
            self.data_index = 0

        # 对于数据集中的每个问题
        for qi, que in enumerate(self.questions[self.data_index:self.data_index + self.batch_size]):
            # 对于问题中的每个单词
            for wi, word in enumerate(que):
                # 将单词ID索引处的元素设置为1,这便给出了该单词的one-hot编码向量
                inputs[qi, wi, self.dictionary[word]] = 1.0   # input[第几大行，大行中的第几小行，大行中的第几小列]
            # 将与该特定类对应的索引设置为1：将问题所对应的答案所在的矩阵相应位置置为1
            labels_ohe[qi, all_labels.index(self.labels[self.data_index + qi])] = 1.0  # List中index() 函数用于从列表中找出某个值第一个匹配项的索引位置。

        # 更新数据索引以获取下一批数据
        self.data_index = (self.data_index + self.batch_size) % self.text_size

        return inputs, labels_ohe

    def return_index(self):
        # 获取当前的数据索引
        return self.data_index


#Myungho Sim
#introduction to sets problem from hackerrank
#find the average from distinct values in a set
def average(array):
    # your code goes here
    setdata = set(array) # convert list to a set
    sum =0
    count =0
    for item in setdata:
        count+=1
        sum += item
    return sum/count

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    result = average(arr)
    print(result)


import argparse
import os
import uuid

import cv2
import gradio as gr
import kornia
import numpy as np
import torch
from loguru import logger
from torchaudio.io import StreamReader
from torchaudio.io import StreamWriter

from benchmark.face_pipeline import alignFace
from benchmark.face_pipeline import FaceDetector
from benchmark.face_pipeline import inverse_transform_batch
from benchmark.face_pipeline import SoftErosion
from configs.train_config import TrainConfig
from models.model import HifiFace

class VideoSwap:
    def __init__(self, cfg, model=None):
        self.facedetector = FaceDetector(cfg.face_detector_weights)
        self.alignface = alignFace()
        self.work_dir = "."
        opt = TrainConfig()
        opt.use_ddp = False
        self.device = "cuda"
        self.ffmpeg_device = cfg.ffmpeg_device
        self.num_frames = 10
        self.kps_window = []
        checkpoint = (cfg.model_path, cfg.model_idx)
        if model is None:
            self.model = HifiFace(
                opt.identity_extractor_config, is_training=False, device=self.device, load_checkpoint=checkpoint
            )
        else:
            self.model = model
        self.model.eval()
        os.makedirs(self.work_dir, exist_ok=True)
        uid = uuid.uuid4()
        self.swapped_video = os.path.join(self.work_dir, f"tmp_{uid}.mp4")

        # model-idx_image-name_target-video-name.mp4
        swapped_with_audio_name = f"result_{uid}.mp4"

        # 带有音频的换脸视频
        self.swapped_video_with_audio = os.path.join(self.work_dir, swapped_with_audio_name)

        self.smooth_mask = SoftErosion(kernel_size=7, threshold=0.9, iterations=7).to(self.device)

    def yuv_to_rgb(self, img):
        img = img.to(torch.float)
        y = img[..., 0, :, :]
        u = img[..., 1, :, :]
        v = img[..., 2, :, :]
        y /= 255

        u = u / 255 - 0.5
        v = v / 255 - 0.5

        r = y + 1.14 * v
        g = y + -0.396 * u - 0.581 * v
        b = y + 2.029 * u

        rgb = torch.stack([r, g, b], -1)
        return rgb

    def rgb_to_yuv(self, img):
        r = img[..., 0, :, :]
        g = img[..., 1, :, :]
        b = img[..., 2, :, :]
        y = (0.299 * r + 0.587 * g + 0.114 * b) * 255
        u = (-0.1471 * r - 0.2889 * g + 0.4360 * b) * 255 + 128
        v = (0.6149 * r - 0.5149 * g - 0.1 * b) * 255 + 128
        yuv = torch.stack([y, u, v], -1)
        return torch.clamp(yuv, 0.0, 255.0, out=None).type(dtype=torch.uint8).transpose(3, 2).transpose(2, 1)

    def _geometry_transfrom_warp_affine(self, swapped_image, inv_att_transforms, frame_size, square_mask):
        swapped_image = kornia.geometry.transform.warp_affine(
            swapped_image,
            inv_att_transforms,
            frame_size,
            mode="bilinear",
            padding_mode="border",
            align_corners=True,
            fill_value=torch.zeros(3),
        )

        square_mask = kornia.geometry.transform.warp_affine(
            square_mask,
            inv_att_transforms,
            frame_size,
            mode="bilinear",
            padding_mode="zeros",
            align_corners=True,
            fill_value=torch.zeros(3),
        )
        return swapped_image, square_mask

    def smooth_kps(self, kps):
        self.kps_window.append(kps.flatten())
        self.kps_window = self.kps_window[1:]
        X = np.stack(self.kps_window, axis=1)
        y = self.kps_window[-1]
        y_cor = X @ np.linalg.inv(X.transpose() @ X - 0.0007 * np.eye(self.num_frames)) @ X.transpose() @ y
        self.kps_window[-1] = y_cor
        return y_cor.reshape((5, 2))

    def detect_and_align(self, image, src_is=False):
        detection = self.facedetector(image)
        if detection.score is None:
            self.kps_window = []
            return None, None
        max_score_ind = np.argmax(detection.score, axis=0)
        kps = detection.key_points[max_score_ind]
        if len(self.kps_window) < self.num_frames:
            self.kps_window.append(kps.flatten())
        else:
            kps = self.smooth_kps(kps)
        align_img, warp_mat = self.alignface.align_face(image, kps, 256)
        align_img = cv2.resize(align_img, (256, 256))
        align_img = align_img.transpose(2, 0, 1)
        align_img = torch.from_numpy(align_img).unsqueeze(0).to(self.device).float()
        align_img = align_img / 255.0
        if src_is:
            self.kps_window = []
        return align_img, warp_mat

    def inference(self, source_face, target_video, shape_rate, id_rate, iterations=1):
        video = cv2.VideoCapture(target_video)
        # 获取视频宽度
        frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
        # 获取视频高度
        frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # 获取帧率
        frame_rate = int(video.get(cv2.CAP_PROP_FPS))
        video.release()
        self.frame_size = (frame_height, frame_width)
        if self.ffmpeg_device == "cuda":
            self.decode_config = {"frames_per_chunk": 1, "decoder": "h264", "format": "yuv444p"}
            # self.decode_config = {
            #     "frames_per_chunk": 1,
            #     "decoder": "h264_cuvid",
            #     "decoder_option": {"gpu": "0"},
            #     "hw_accel": "cuda:0",
            # }

            self.encode_config = {
                "encoder": "h264_nvenc",  # GPU Encoder
                "encoder_format": "yuv444p",
                "encoder_option": {"gpu": "0", "cq": "10"},  # Run encoding on the cuda:0 device
                "hw_accel": "cuda:0",  # Data comes from cuda:0 device
                "frame_rate": frame_rate,
                "height": frame_height,
                "width": frame_width,
                "format": "yuv444p",
            }
        else:
            self.decode_config = {"frames_per_chunk": 1, "decoder": "h264", "format": "yuv444p"}

            self.encode_config = {
                "encoder": "libx264",
                "encoder_format": "yuv444p",
                "frame_rate": frame_rate,
                "height": frame_height,
                "width": frame_width,
                "format": "yuv444p",
            }
        src = source_face
        src, _ = self.detect_and_align(src, src_is=True)
        logger.info("start swapping")
        sr = StreamReader(target_video)
        if self.ffmpeg_device == "cpu":
            sr.add_basic_video_stream(**self.decode_config)
        else:
            sr.add_basic_video_stream(**self.decode_config)
            # sr.add_video_stream(**self.decode_config)
        sw = StreamWriter(self.swapped_video)
        sw.add_video_stream(**self.encode_config)
        with sw.open():
            for (chunk,) in sr.stream():
                # StreamReader cuda decode颜色格式默认为yuv需要转为rgb
                chunk = self.yuv_to_rgb(chunk)
                image = (chunk * 255).clamp(0, 255).to(torch.uint8)[0].cpu().numpy()
                align_img, warp_mat = self.detect_and_align(image)
                chunk = chunk.transpose(3, 2).transpose(2, 1).to(self.device)
                if align_img is None:
                    result_face = chunk
                else:
                    with torch.no_grad():
                        for _ in range(iterations):
                            swapped_face, m_r = self.model.forward(src, align_img, shape_rate, id_rate)
                            swapped_face = torch.clamp(swapped_face, 0, 1)
                            align_img = swapped_face
                        smooth_face_mask, _ = self.smooth_mask(m_r)
                    warp_mat = torch.from_numpy(warp_mat).float().unsqueeze(0)
                    inverse_warp_mat = inverse_transform_batch(warp_mat)
                    swapped_face, smooth_face_mask = self._geometry_transfrom_warp_affine(
                        swapped_face, inverse_warp_mat, self.frame_size, smooth_face_mask
                    )
                    result_face = (1 - smooth_face_mask) * chunk + smooth_face_mask * swapped_face
                result_face = self.rgb_to_yuv(result_face).to(self.ffmpeg_device)
                sw.write_video_chunk(0, result_face)

        # 将target_video中的音频转移到换脸视频上
        command = f"ffmpeg -loglevel error -i {self.swapped_video} -i {target_video} -c copy \
            -map 0 -map 1:1? -y -shortest {self.swapped_video_with_audio}"
        os.system(command)

        # 删除没有音频的换脸视频
        os.system(f"rm {self.swapped_video}")
        return self.swapped_video_with_audio

class ConfigPath:
    face_detector_weights = "/mnt/c/yangguo/useful_ckpt/face_detector/face_detector_scrfd_10g_bnkps.onnx"
    model_path = ""
    model_idx = 80000
    ffmpeg_device = "cuda"

def main():
    cfg = ConfigPath()
    parser = argparse.ArgumentParser(
        prog="benchmark", description="What the program does", epilog="Text at the bottom of help"
    )
    parser.add_argument("-m", "--model_path")
    parser.add_argument("-i", "--model_idx")
    parser.add_argument("-f", "--ffmpeg_device")

    args = parser.parse_args()

    cfg.model_path = args.model_path
    cfg.model_idx = int(args.model_idx)
    cfg.ffmpeg_device = args.ffmpeg_device

    infer = VideoSwap(cfg)

    def inference(source_face, target_video, shape_rate, id_rate):
        return infer.inference(source_face, target_video, shape_rate, id_rate)

    output = gr.Video(value=None, label="换脸结果")
    demo = gr.Interface(
        fn=inference,
        inputs=[
            gr.Image(shape=None, label="选脸图"),
            gr.Video(value=None, label="目标视频"),
            gr.Slider(
                minimum=0.0,
                maximum=1.0,
                value=1.0,
                step=0.1,
                label="3d结构相似度（1.0表示完全替换）",
            ),
            gr.Slider(
                minimum=0.0,
                maximum=1.0,
                value=1.0,
                step=0.1,
                label="人脸特征相似度（1.0表示完全替换）",
            ),
        ],
        outputs=output,
        title="HiConFace视频人脸融合系统",
        description="v1.0: developed by yiwise CV group",
    )
    demo.launch(server_name="0.0.0.0", server_port=7860)

if __name__ == "__main__":
    main()


import numpy as np
from collections import Iterable

###################################   LO QUE VIENE ES LAGRANGE   ###################################

def matriz_pitatoria(x):
    #esto lo hago para sacarme el pillo de ir concatenando lostas
    #en vez de eso, defino las dimensiones en un np array y después lo paso a lista
    # trucazo
    l_jm=np.random.rand(len(x),len(x))
    l_jm=l_jm.tolist()

    for j in range(len(x)):
        for m in range(len(x)):
            if j!=m:
                l_jm[j][m] = lambda x_in,x=x,j=j,m=m: np.divide((x_in-x[m]),(x[j]-x[m]))
            else:
                l_jm[j][m] = lambda x_in: 1
    #devuelve la matriz de funciones en forma de lista de listas
    return l_jm

def pitatoria_evaluar(x_in,lista_de_funciones):
    #tomo la lista que tiene listas dentro y la paso a nparray
    nplist=np.array(lista_de_funciones)
    #guardo su forma
    orig_shape = nplist.shape
    #lo transformo a una sola dimension
    nplist=nplist.reshape(-1)
    #evaluo el término dado para cada f dentro de la matriz
    evaluar=np.array(list(map(lambda f,x_in=x_in: f(x_in),nplist)))
    # devuelvo la forma original
    evaluar=evaluar.reshape(orig_shape)
    #pitato = np.prod(evaluar,axis=1)
    #devuelve, para un x, todas las pitatorias asolciadas, en un vector
    evaluar = np.prod(evaluar,axis=1)
    return evaluar

# polinomio con Lagrange

class Lagrange:

    def __init__(self,x_vec,y_vec):
        self.x = x_vec
        self.y = y_vec
        self.pit = matriz_pitatoria(x_vec)

    def eval_lagrange(self,x):
        if isinstance(x, Iterable):
            y=[]
            for element in x:

                eval = pitatoria_evaluar(element,self.pit)

                y.append(np.dot(eval,self.y))
            return y

        else:
            eval = pitatoria_evaluar(x, self.pit)
            return np.dot(eval,self.y)

################################### P2  ###################################


import sys
_module = sys.modules[__name__]
del sys
contrastive = _module
net = _module
test_contrastive = _module
train_mnist = _module

from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Module
import abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings
import numpy as np
from torch import Tensor
patch_functional()
open = mock_open()
yaml = logging = sys = argparse = MagicMock()
ArgumentParser = argparse.ArgumentParser
_global_config = args = argv = cfg = config = params = _mock_config()
argparse.ArgumentParser.return_value.parse_args.return_value = _global_config
yaml.load.return_value = _global_config
sys.argv = _global_config
__version__ = '1.0.0'
xrange = range
wraps = functools.wraps

import torch

import torch.nn

import torch.nn as nn

import numpy as np

from torch.autograd import Variable

from torch.autograd import gradcheck

import torchvision.datasets as dsets

import random

import time

import matplotlib.pyplot as plt

from torchvision import transforms

class ContrastiveLoss(torch.nn.Module):
    """
    Contrastive loss function.

    Based on:
    """

    def __init__(self, margin=1.0):
        super(ContrastiveLoss, self).__init__()
        self.margin = margin

    def check_type_forward(self, in_types):
        assert len(in_types) == 3
        x0_type, x1_type, y_type = in_types
        assert x0_type.size() == x1_type.shape
        assert x1_type.size()[0] == y_type.shape[0]
        assert x1_type.size()[0] > 0
        assert x0_type.dim() == 2
        assert x1_type.dim() == 2
        assert y_type.dim() == 1

    def forward(self, x0, x1, y):
        self.check_type_forward((x0, x1, y))
        diff = x0 - x1
        dist_sq = torch.sum(torch.pow(diff, 2), 1)
        dist = torch.sqrt(dist_sq)
        mdist = self.margin - dist
        dist = torch.clamp(mdist, min=0.0)
        loss = y * dist_sq + (1 - y) * torch.pow(dist, 2)
        loss = torch.sum(loss) / 2.0 / x0.size()[0]
        return loss

class SiameseNetwork(nn.Module):

    def __init__(self):
        super(SiameseNetwork, self).__init__()
        self.cnn1 = nn.Sequential(nn.Conv2d(1, 20, kernel_size=5), nn.MaxPool2d(2, stride=2), nn.Conv2d(20, 50, kernel_size=5), nn.MaxPool2d(2, stride=2))
        self.fc1 = nn.Sequential(nn.Linear(50 * 4 * 4, 500), nn.ReLU(inplace=True), nn.Linear(500, 10), nn.Linear(10, 2))

    def forward_once(self, x):
        output = self.cnn1(x)
        output = output.view(output.size()[0], -1)
        output = self.fc1(output)
        return output

    def forward(self, input1, input2):
        output1 = self.forward_once(input1)
        output2 = self.forward_once(input2)
        return output1, output2


import arcpy

arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"D:\00-Learning\02-GisDev\01-ArcPy\LPA\Data\Sample.gdb"

fc = arcpy.GetParameterAsText(0)
numFeats = arcpy.GetCount_management(fc)
arcpy.AddMessage("{0} has {1} feature(s)".format(fc, numFeats))

print("Script completed!")


# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 21:53:37 2021

@author: Cnoized
"""
#This is for problem 54

import pandas

file = pandas.read_csv('Problem54.csv', header=None)
# print(file)
data = []
file.values.tolist()
for n in file.values:
    # print(n)
    # print(str(n))
    n=str(n[0]).split(' ')
    # print(n)
    # n = [int(a) for a in n]
    data.append(n)
P1K = []
P2K = []
for n in data:
    P1K.append(n[0:5])
    P2K.append(n[5:10])
# print(P1K[0])
# print(P2K[0])
# print(P1K[-1])
# print(P2K[-1])

# # Imported data to each player.

# Let hand be H

H = ['AD', 'KD', '3D', 'JD', '8D']

if H[0][1] == H[1][1] == H[2][1] == H[3][1] == H[4][1]:
    # print('Flush')
    Flush = 0
else:
    Flush = 1
    # print('not flush')
# H = [ord(H[a][0]) for a in range(5)]
# print(H)
# i=0
Alphabet = ['A','K','Q','J','T','9','8','7','6','5','4','3','2','A']
Alpha = {'A':14,'K':13,'Q':12,'J':11,'T':10,'9':9,'8':8,'7':7,'6':6,'5':5,'4':4,'3':3,'2':2}
# set(H) == set(Alphabet[i:i+5])
Straight_P1K = []
Tuple_P1K = []
###### Going to come back to this. #######

def Hand(Hand):
    H = Hand
    Value = 0
    h = [Alpha[H[j][0]] for j in range(5)]
    h = sorted(h,reverse = True)
    # print(h)
    h = sorted(h,key=h.count,reverse = True)
    # print(h)
    for n in range(len(h)):
        Value += h[n]/(100**(n+1))
    # print(Value)
    V = [H[j][0] for j in range(5)]
    if H[0][1] == H[1][1] == H[2][1] == H[3][1] == H[4][1]:
        # print('Flush')
        Value += 12

    Count_1 = max([h.count(i) for i in h])
    # print(Count_1)
    if Count_1 == 1:
        Value += 1
        # print('High card:',h[0])
    if Count_1 == 2:
        Value += 2
        # print('Pair')
        if h[2]==h[3]:
            Value += 1
            # print('Two Pair')

    if Count_1 == 3:
        Value += 4
        # print('Three of a Kind')
        if h[3]==h[4]:
            Value += 1
            # print('Full House')
    if Count_1 == 4:
        Value += 7
        # print('Four of a Kind')
    Straight = sum([(len(Alphabet)-i)*(set(V) == set(Alphabet[i:i+5])) for i in range(len(Alphabet)-4)])
    if Straight > 0:
        Value += 10
        # print('Straight')
    return Value
P1W = 0
Tie = 0
P2W = 0
for n in range(0,1000):
    if Hand(P1K[n])>Hand(P2K[n]):
        P1W += 1
    elif Hand(P1K[n])==Hand(P2K[n]):
        Tie += 1
    else:
        P2W += 1
#     H = [a for a in P1K[n]]
#     Q = [a for a in P2K[n]]
#     # Four = Full = Two_Pair = Three = Pair = Flush = Straight = 0
#     h = [H[j][0] for j in range(5)]
#     V = [Alpha[H[j][0]] for j in range(5)]
#     print(V)
#     if H[0][1] == H[1][1] == H[2][1] == H[3][1] == H[4][1]:
#         # print('Flush')
#         Flush = 1
#     Count_1 = max(h,key=h.count())
#     # else:
#     #     if [h.count(j) for j in Alphabet[:-1]].count(4) != 0:
#     #         Four = [h.count(j) for j in Alphabet[:-1]].index(4)
#     #         # print('Four')
#     #     elif [h.count(j) for j in Alphabet[:-1]].count(3) != 0 and [h.count(j) for j in Alphabet[:-1]].count(2) != 0:
#     #         Full = [[h.count(j) for j in Alphabet[:-1]].index(3), [h.count(j) for j in Alphabet[:-1]].index(2)]
#     #         # print('Full')
#     #     elif [h.count(j) for j in Alphabet[:-1]].count(3) != 0:
#     #         Three = [[h.count(j) for j in Alphabet[:-1]].index(3)]
#     #         # print('Three')
#     #     elif [h.count(j) for j in Alphabet[:-1]].count(2) == 2:
#     #         Two_Pair = [1 if h.count(j)== 2 else 0 for j in Alphabet[:-1]]
#     #         # print('Two pair')
#     #     elif [h.count(j) for j in Alphabet[:-1]].count(2) == 1:
#     #         Pair = [h.count(j) for j in Alphabet[:-1]].index(2)
#     #     #     print('Pair')
#     #     # print('not flush')
#     Straight = sum([(len(Alphabet)-i)*(set(h) == set(Alphabet[i:i+5])) for i in range(len(Alphabet)-4)])

#     # Tuple_P1K = [Flush*Straight,Four,Full,Flush,Straight,Three,Two_Pair,Pair,h]
#     # Tuple_P2K = []

#     # Four = Full = Two_Pair = Three = Pair = Flush = Straight = 0
#     h = [Q[j][0] for j in range(5)]
#     # if Q[0][1] == Q[1][1] == Q[2][1] == Q[3][1] == Q[4][1] and sum([(len(Alphabet)-i)*(set(h) == set(Alphabet[i:i+5])) for i in range(len(Alphabet)-4)]) != 0:
#         # if
#     if [h.count(j) for j in Alphabet[:-1]].count(4) != 0:
#         Four = [h.count(j) for j in Alphabet[:-1]].index(4)
#         # print('Four')

#         # print('Flush')

#     else:
#         if 1==1:
#             print(V)
#         elif [h.count(j) for j in Alphabet[:-1]].count(3) != 0 and [h.count(j) for j in Alphabet[:-1]].count(2) != 0:
#             Full = [[h.count(j) for j in Alphabet[:-1]].index(3), [h.count(j) for j in Alphabet[:-1]].index(2)]
#             # print('Full')
#         elif [h.count(j) for j in Alphabet[:-1]].count(3) != 0:
#             Three = [[h.count(j) for j in Alphabet[:-1]].index(3)]
#             # print('Three')
#         elif [h.count(j) for j in Alphabet[:-1]].count(2) == 2:
#             Two_Pair = [1 if h.count(j)== 2 else 0 for j in Alphabet[:-1]]
#             # print('Two pair')
#         elif [h.count(j) for j in Alphabet[:-1]].count(2) == 1:
#             Pair = [h.count(j) for j in Alphabet[:-1]].index(2)
#             # print('Pair')
#         # print('not flush')
#     Straight = sum([(len(Alphabet)-i)*(set(h) == set(Alphabet[i:i+5])) for i in range(len(Alphabet)-4)])
#         # print('Straight')
#     Tuple_P2K.append([[b if type(a) == list else a for b in a] for a in [Flush*Straight,Four,Full,Flush,Straight,Three,Two_Pair,Pair,h]])
# P1W = 0

# for a in range(0,1000):
#     for n in range(len(Tuple_P1K)-1):
#         print(Tuple_P1K[a])
#         if Tuple_P1K[a][n] > Tuple_P2K[a][n]:
#             P1W += 1
print('P1W:',P1W)
print('Ties:',Tie)
print('P2W:',P2W)
    # Tuple_P1K.append()
# print(Tuple_P1K)
# print(Straight_P1K)
# print('Alphabet', Alphabet)

# # for H in P1K:
# print([H[j][0] for j in range(5)])
# print(sum([(len(Alphabet)-i)*(set(['2','A','K','Q','J']) == set(Alphabet[i:i+5])) for i in range(len(Alphabet))]))
# # print(Straight_P1K)
# print('Alphabet', Alphabet)

# # Build hand reading.


import serial
import time
import sys
import os
import threading

class arduino(object):
    def __init__(self):
        # Initialize ArduinoObj
        self.port = '/dev/ttyACM0'
        self.baudrate = 9600
        self.serCon = None
        self.arConnect = False

    def arComms(self):
        # Create socket for the serial port
        print("Awaiting Arduino Connection...")
        while True:
            retry = False
            try:
                self.serCon = serial.Serial(self.port,self.baudrate)
                self.arConnect = True
                print("Serial link connected")
                retry = False
            except Exception as e:
                print ("Error (Serial): %s " % str(e))
                rety = True
            if(not retry):
                break
            print("Retrying Arduino Connection...")
            time.sleep(2)

    def arduinoConnected(self):
        return self.arConnect

    def writeArduino(self,msg):
        try:
            self.serCon.write(str.encode(msg))
            print ("Sent to arduino: %s" % msg)
        except AttributeError:
            print("Error in serial comm. No value to be written. Check connection!")

    def readArduino(self):
        try:
            received_data = self.serCon.readline()
            received_data = received_data.decode('utf-8')
            received_data = str(received_data)
            message = received_data.split(",")                          #E.g. AN/PC,AR,OBS|Sensor_Data
            print ("Received from arduino: %s" % message[1])
            return received_data

        except Exception as e:
            print("Error in serial comm. No value received. Check connection! %s"%(str(e)))

    def closeserial(self):
        # Closing socket
        self.serCon.close()
        self.arConnect = False
        print("Closing serial socket")


import io

from django.db.models import Sum
from django.conf import settings
from django.http import FileResponse
from django_filters.rest_framework import DjangoFilterBackend
from djoser.views import UserViewSet
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from rest_framework.serializers import ValidationError
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import get_object_or_404
from rest_framework import status
from rest_framework.decorators import action

from api.serializers import (TagSerializer, UserSerializer, RecipeSerializer,
                             IngredientSerializer, FollowSerializer,
                             RecipeGetSerializer, RecipeFollowSerializer,)
from api.permissions import IsAuthorOrReadOnly
from recipes.models import (Tag, User, Recipe, Ingredient, Favorite,
                            ShoppingList, Subscription, RecipeIngredients)
from api.utils import (add_favorite_shoppinglist, remove_favorite_shoppinglist)
from api.filters import RecipeFilter, IngredientFilter
from api.paginations import CastomPagination

class ShoppingListDownloadView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        shopping_list = RecipeIngredients.objects.filter(
            recipe__shopping_list__user=request.user).values(
            "ingredient__name",
            "ingredient__measurement_unit"
        ).annotate(
            amount=Sum("amount")
        ).order_by()
        font = "Tantular"
        pdfmetrics.registerFont(
            TTFont("Tantular",
                   "./data/Tantular.ttf",
                   "UTF-8")
        )
        buffer = io.BytesIO()
        pdf_file = canvas.Canvas(buffer)
        pdf_file.setFont(font, settings.SETFONTS)
        pdf_file.drawString(
            settings.TITLE_X,
            settings.TITLE_Y,
            "Список покупок:"
        )
        pdf_file.setFont(font, settings.SETFONT)
        from_bottom = settings.BOTTOM_Y
        for number, ingredient in enumerate(shopping_list, start=1):
            pdf_file.drawString(
                settings.ITEM_X,
                from_bottom,
                (f'{number}.  {ingredient["ingredient__name"]} - '
                 f'{ingredient["amount"]} '
                 f'{ingredient["ingredient__measurement_unit"]}')
            )
            from_bottom -= settings.ITEM_HEIGHT
            if from_bottom <= settings.MAX_Y:
                from_bottom = settings.TITLE_Y
                pdf_file.showPage()
                pdf_file.setFont(font, settings.SETFONT)
        pdf_file.showPage()
        pdf_file.save()
        buffer.seek(0)
        return FileResponse(
            buffer, as_attachment=True, filename="shopping_list.pdf"
        )

class TagViewSet(ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer

class IngredientViwsSet(ModelViewSet):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientSerializer
    filter_backends = (DjangoFilterBackend,)
    filterset_class = IngredientFilter
    ordering_fields = ("name",)

class RecipeViewSet(ModelViewSet):
    queryset = Recipe.objects.all()
    permission_classes = (IsAuthorOrReadOnly,)
    filter_backends = (DjangoFilterBackend,)
    filterset_class = RecipeFilter
    pagination_class = CastomPagination

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    def get_serializer_class(self):
        if self.request.method == "GET":
            return RecipeGetSerializer
        return RecipeSerializer

    def get_permissions(self):
        if self.action != "create":
            return (IsAuthorOrReadOnly(),)
        return super().get_permissions()

    @action(detail=True, methods=["POST", "DELETE"],)
    def favorite(self, request, pk):
        if self.request.method == "POST":
            return add_favorite_shoppinglist(request, pk, Favorite,
                                             RecipeFollowSerializer)
        return remove_favorite_shoppinglist(request, pk, Favorite)

    @action(detail=True, methods=["POST", "DELETE"],)
    def shopping_cart(self, request, pk):
        if request.method == "POST":
            return add_favorite_shoppinglist(request, pk, ShoppingList,
                                             RecipeFollowSerializer)
        return remove_favorite_shoppinglist(request, pk, ShoppingList)

class CustomUserViewSet(UserViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    pagination_class = CastomPagination

    @action(
        detail=True, permission_classes=[IsAuthenticated],
        methods=["post", "delete"]
    )
    def subscribe(self, request, **kwargs):
        user = request.user
        author = get_object_or_404(User, id=self.kwargs.get("id"))

        if request.method == "POST":
            if author == user:
                raise ValidationError(
                    {"errors": "Нельзя подписаться на самого себя."}
                )
            if Subscription.objects.filter(user=user, author=author).exists():
                raise ValidationError({"errors": "Вы уже подписаны."})
            serializer = FollowSerializer(
                author, context={'request': request}
            )
            Subscription.objects.create(user=user, author=author)
            return Response(
                serializer.data,
                status=status.HTTP_201_CREATED
            )

        if not Subscription.objects.filter(user=user, author=author).exists():
            raise ValidationError({"errors": "Подписки не существует."})
        Subscription.objects.filter(user=user, author=author).delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(detail=False, permission_classes=[IsAuthenticated],
            methods=["GET"])
    def subscriptions(self, request):
        user = request.user
        queryset = User.objects.filter(following__user=user)
        pages = self.paginate_queryset(queryset)
        serializer = FollowSerializer(
            pages, many=True,
            context={"request": request})
        return self.get_paginated_response(serializer.data)


#!/usr/bin/python3
""" 0-rain """

def rain(walls):
    """ Gets area of rain between n walls of varrying heights """
    if len([h for h in walls if h > 0]) == 0:
        return 0
    lastWall = max([i for i, x in enumerate(walls) if x > 0])
    firstWall = min([i for i, x in enumerate(walls) if x > 0])
    w = walls[:lastWall+1]
    maxH = max(walls)
    grid = [[True if w[x] > 0 and y < w[x]
             else False for x in range(len(w))] for y in range(maxH)]
    grid = list(grid)

    def hasL(y, x):
        if x <= firstWall:
            return False
        prevX = x - 1
        while prevX > 0:
            if grid[y][prevX]:
                return True
            prevX -= 1
        return grid[y][0]

    def hasR(y, x):
        nextX = x + 1
        while nextX < len(w):
            if grid[y][nextX]:
                return True
            nextX += 1
        return grid[y][lastWall]

    area = 0
    for y, r in enumerate(grid):
        for x, c in enumerate(r):
            if not c and hasL(y, x) and hasR(y, x):
                area += 1
    return area


def dec(a):
    a = a[::-1]
    n = 0
    for i in range(len(a)):
        n += int(a[i])*2**i
    return n

num1, num2 = input("Введите 1 число: "), input("Введите 2 число: ")
decim = dec(num1)*dec(num2)
res = ""
while decim !=0:
    res += str(decim%2)
    decim = decim//2
print("Произведение равно:", res[::-1])


t = int(input())

for tc in range(1, t + 1) :
    data = list(str(input()))
    clap = 0
    result = 0

    for i in range(len(data)):
        if data[i] != 0:
            if clap >= i:
                clap += int(data[i])
            else:
                result += i - clap
                clap = i + int(data[i])

    print('#%d %d' % (tc, result))

4789. 성공적인 공연 기획.py


# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from workspace import Workspace

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.createActions()
        self.createMenuBar()
        self.createToolBar()
        self.setCentralWidget(self.createCentralWidget())
        self.setWindowIcon(QIcon('images/logo.png'))
        self.loadSettings()

    def createActions(self):
        self.fileAction = QAction(QIcon('images/map.png'), u'文件', self)
        self.helpAction = QAction(QIcon('images/add.png'), u'帮助', self)

    def createMenuBar(self):
        fileMenu = self.menuBar().addMenu(u'文件')
        fileMenu.addAction(self.fileAction)
        fileMenu.addSeparator()
        fileMenu.addAction(self.helpAction)
        helpMenu = self.menuBar().addMenu(u'帮助')
        helpMenu.addAction(self.helpAction)
        helpMenu.triggered.connect(self.actionTest)

    def createToolBar(self):
        toolBar = self.addToolBar(u'文件')
        toolBar.setIconSize(QSize(16, 16))
        toolBar.setMovable(False)
        toolBar.addAction(self.fileAction)
        toolBar.addSeparator()
        toolBar.addAction(self.helpAction)

    def createCentralWidget(self):
        self.centralWidget = Workspace()
        return self.centralWidget

    def actionTest(self):
        print('test')

    def loadSettings(self):
        settings = QSettings()
        geometry = settings.value('MainWindow/geometry')

        #如果设置文件存在，那么geometry的值一定存在，否则说明是第一次启动，跳过之后的设置读取过程
        if not geometry:
            return
        self.restoreGeometry(geometry)

    def saveSettings(self):
        settings = QSettings()
        settings.beginGroup('MainWindow')
        settings.setValue('geometry', self.saveGeometry())
        settings.endGroup()

    def closeEvent(self, e):
        self.saveSettings()
        self.centralWidget.saveSettings()

if __name__ == '__main__':
    from application import Globals
    Globals.setAttr('servers', {'server1': ('127.0.0.1', 22333)})
    import singleton
    app = singleton.getApplication()
    app.setOrganizationName('ivy')
    app.setApplicationName('webchat-chat-advance')
    app.setStyleSheet(
        'QWidget{background-color: #D6D6D6;color: #000;font-size: 13px;}'

        'QScrollBar:horizontal {border-top: 1px solid grey;height: 15px;border-bottom: none;padding: 1px 0;}'

        'QScrollBar:vertical {border-left: 1px solid grey;width: 15px;padding: 0 1px; border-right:none}'

        'QScrollBar::add-line,  QScrollBar::sub-line {width:0;}'

        'QScrollBar::handle:horizontal {border: 1px solid #818A9A; border-radius: 4px;'
        'background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,'
        'stop: 0 #ECECEC, stop: 0.4 #E4E4E4,stop: 0.5 #E0E0E0, stop: 1.0 #D6D6D6);}'

        'QScrollBar::handle:horizontal:hover{background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,'
        'stop: 0 #D6D6D6, stop: 0.5 #A7A7A7, stop: 1.0 #9B9B9B);}'

        'QScrollBar::handle:vertical {border: 1px solid #818A9A; border-radius: 4px;'
        'background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,'
        'stop: 0 #ECECEC, stop: 0.4 #E4E4E4,stop: 0.5 #E0E0E0, stop: 1.0 #D6D6D6);}'

        'QScrollBar::handle:vertical:hover{background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,'
        'stop: 0 #D6D6D6, stop: 0.5 #A7A7A7, stop: 1.0 #9B9B9B);}'

        'QTreeView {background: white}'

        'QTreeView::item {padding: 4px 0; background:  transparent;}'

        'QTreeView::item:selected {background:  transparent; color: black}'

        'QTreeView::branch {background: white}'

        'QTreeView::branch:has-siblings:adjoins-item {border-image: url(images/branch-more.png) 0;}'

        'QTreeView::branch:!has-children:!has-siblings:adjoins-item {border-image: url(images/branch-end.png) 0;}'

        'QTreeView::branch:has-children:!has-siblings:closed,QTreeView::branch:closed:has-children:has-siblings {'
        'border-image: none;image: url(images/branch-closed.png);}'

        'QTreeView::branch:open:has-children:!has-siblings,QTreeView::branch:open:has-children:has-siblings  {'
        'border-image: none;image: url(images/branch-open.png);}'

        'QPushButton {border: 1px solid #818A9A;border-radius: 0;'
        'background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,''stop: 0 #f6f7fa, stop: 1 #dadbde);'
        'min-width: 60px; min-height: 21px}'
        'QPushButton:pressed {background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,'
        'stop: 0 #dadbde, stop: 1 #f6f7fa);}'
        'QPushButton:flat {border: none;}'
        'QPushButton:default {border-color: #1D953F;}'

        'QMenuBar {padding: 2px 0; border-bottom: 1px solid #818A9A;}'
        'QMenuBar::item {padding: 2px 4px;}'
        'QMenuBar::item:selected {background-color: #426AB3; color: white;}'

        'QMenu {border-top: 1px solid white; border-left: 1px solid white;border-right: 2px solid #949494; '
        'border-bottom: 2px solid #949494;padding: 2px 1px;}'
        'QMenu::separator {height: 1px; background: #818A9A; border-bottom: 1px solid white; margin-top: 1px;}'
        'QMenu::item {padding: 2px 60px 2px 24px;border: 1px solid transparent;}'
        'QMenu::item:selected {background-color: #426AB3; color: white;}'

        'QToolBar {border-bottom: 1px solid #818A9A;}'
        'QToolBar::separator {width: 1px; background: #818A9A; margin: 0 1px;}'

        'QTableView::item:selected {background: #426AB3}'

        'QLineEdit{background-color: #FFF; color: #000; border: 1px solid #818A9A; padding: 2px}'
    )
    b = MainWindow()
    b.show()
    from network import ExternalManager
    externalManager = ExternalManager()
    externalManager.start()
    app.exec_()


# coding: utf-8

from keras.models import Model
from keras.layers.core import Dense, Dropout, Lambda
from keras.layers.embeddings import Embedding
from keras.layers.normalization import BatchNormalization
from keras.layers.merge import Concatenate, dot
from keras.layers import  GlobalMaxPooling1D, GlobalAveragePooling1D, Input, SpatialDropout1D, Bidirectional
from keras.layers import CuDNNLSTM, Conv1D
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints

# hyper parameters
embed_size = 300 # how big is each word vector
max_features = 160000 # how many unique words to use (i.e num rows in embedding vector)
maxlen_p = 150 # max number of words in a context to use
maxlen_q = 15 # max number of words in a question to use
num_rnn_units = 64
num_hidden_units = 300
drop_prob = 0.4
features = 2
filter_sizes_p = [1,3,5]
filter_sizes_q = [1,3]
num_filters = 128

# Attetion layer
class FeedForwardAttention(Layer):
    def __init__(self, step_dim,
                 W_regularizer=None, b_regularizer=None,
                 W_constraint=None, b_constraint=None,
                 bias=True, **kwargs):
        """
        Keras Layer that implements an Attention mechanism for temporal data.
        Follows the work of Raffel et al. [https://arxiv.org/abs/1512.08756]
        # Input shape
            3D tensor with shape: `(samples, steps, features)`.
        # Output shape
            2D tensor with shape: `(samples, features)`.
        :param kwargs:
        Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.
        The dimensions are inferred based on the output shape of the RNN.
        Example:
            model.add(LSTM(64, return_sequences=True))
            model.add(Attention())
        """
        self.init = initializers.get('glorot_uniform')

        self.W_regularizer = regularizers.get(W_regularizer)
        self.b_regularizer = regularizers.get(b_regularizer)

        self.W_constraint = constraints.get(W_constraint)
        self.b_constraint = constraints.get(b_constraint)

        self.bias = bias
        self.step_dim = step_dim
        self.features_dim = 0
        super(FeedForwardAttention, self).__init__(**kwargs)

    def build(self, input_shape):
        assert len(input_shape) == 3

        self.W = self.add_weight((input_shape[-1],),
                                 initializer=self.init,
                                 name='{}_W'.format(self.name),
                                 regularizer=self.W_regularizer,
                                 constraint=self.W_constraint)
        self.features_dim = input_shape[-1]

        if self.bias:
            self.b = self.add_weight((input_shape[1],),
                                     initializer='zero',
                                     name='{}_b'.format(self.name),
                                     regularizer=self.b_regularizer,
                                     constraint=self.b_constraint)
        else:
            self.b = None

        self.built = True

    def call(self, x):

        features_dim = self.features_dim
        step_dim = self.step_dim

        eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim))

        if self.bias:
            eij += self.b

        eij = K.tanh(eij)

        a = K.softmax(eij)

        a = K.expand_dims(a)
        weighted_input = x * a

        return K.sum(weighted_input, axis=1)

    def compute_output_shape(self, input_shape):
        #return input_shape[0], input_shape[-1]
        return input_shape[0],  self.features_dim

def cos_sim (x):
    p = x[0] # [t, 2d]
    q = x[1] # [j, 2d]
    s = dot([p, K.permute_dimensions(q, (0,2,1))], axes=(2,1), normalize=True) # [t, j] cosine simlilarity
    max_sim = K.max(s, axis=-1, keepdims=True) # [t, 1]
    return max_sim

def single_model(emb, fast, trainable=False):
    p = Input(shape=(maxlen_p,))
    q = Input(shape=(maxlen_q,))
    p_fea = Input(shape=(maxlen_p, features)) # passage word feature (exact match + option match)
    q_fea = Input(shape=(maxlen_q, features)) # query word feature

    # Embedding layer
    embed = Embedding(max_features+1, embed_size, weights=[emb], trainable=trainable)
    ft = Embedding(max_features+1, embed_size, weights=[fast], trainable=trainable)
    pem = embed(p) # word embedding
    pft = ft(p)
    pe = Concatenate()([pem, pft])
    qem = embed(q)
    qft = ft(q)
    qe = Concatenate()([qem, qft])

    p_cos_e = Lambda(cos_sim)([pem, qem])
    p_cos_f = Lambda(cos_sim)([pft, qft])
    q_cos_e = Lambda(cos_sim)([qem, pem])
    q_cos_f = Lambda(cos_sim)([qft, pft])
    pe = SpatialDropout1D(0.2)(pe)
    qe = SpatialDropout1D(0.2)(qe)
    pf = Concatenate()([pe, p_fea, p_cos_e, p_cos_f]) # passage feature vec = word embedding + (exact match + option match + cos sim)
    qe = Concatenate()([qe, q_fea, q_cos_e, q_cos_f]) # query feature vec = word embedding + (exact match + option match + cos sim)

    h = Bidirectional(CuDNNLSTM(num_rnn_units, return_sequences=True))(pf) # [t, 2d]
    u = Bidirectional(CuDNNLSTM(num_rnn_units, return_sequences=True))(qe) # [j,2d]

    # cnn for p
    convp_0 = Conv1D(num_filters, kernel_size=filter_sizes_p[0], padding = "same", activation = 'relu')(h)
    convp_1 = Conv1D(num_filters, kernel_size=filter_sizes_p[1], padding = "same", activation = 'relu')(h)
    convp_2 = Conv1D(num_filters, kernel_size=filter_sizes_p[2], padding = "same", activation = 'relu')(h)

    maxpoolp_0 = GlobalMaxPooling1D()(convp_0)
    avgpoolp_0 = GlobalAveragePooling1D()(convp_0)
    attp_0 = FeedForwardAttention(maxlen_p)(convp_0)
    maxpoolp_1 = GlobalMaxPooling1D()(convp_1)
    avgpoolp_1 = GlobalAveragePooling1D()(convp_1)
    attp_1 = FeedForwardAttention(maxlen_p)(convp_1)
    maxpoolp_2 = GlobalMaxPooling1D()(convp_2)
    avgpoolp_2 = GlobalAveragePooling1D()(convp_2)
    attp_2 = FeedForwardAttention(maxlen_p)(convp_2)
    zp = Concatenate()([maxpoolp_0, maxpoolp_1, maxpoolp_2, avgpoolp_0, avgpoolp_1, avgpoolp_2, attp_0, attp_1, attp_2])

    # cnn for q
    convq_0 = Conv1D(num_filters, kernel_size=filter_sizes_q[0], padding = "same", activation = 'relu')(u)
    convq_1 = Conv1D(num_filters, kernel_size=filter_sizes_q[1], padding = "same", activation = 'relu')(u)

    maxpoolq_0 = GlobalMaxPooling1D()(convq_0)
    avgpoolq_0 = GlobalAveragePooling1D()(convq_0)
    attq_0 = FeedForwardAttention(maxlen_q)(convq_0)
    maxpoolq_1 = GlobalMaxPooling1D()(convq_1)
    avgpoolq_1 = GlobalAveragePooling1D()(convq_1)
    attq_1 = FeedForwardAttention(maxlen_q)(convq_1)
    zq = Concatenate()([maxpoolq_0, maxpoolq_1, avgpoolq_0, avgpoolq_1, attq_0, attq_1])

    # Output layer
    x = Concatenate()([zp,zq])
    x = BatchNormalization()(x)
    x = Dense(num_hidden_units, activation='relu')(x)
    x = Dropout(drop_prob)(x)
    x = BatchNormalization()(x)

    x = Dense(1, activation='sigmoid')(x)
    model = Model(inputs=[p, q, p_fea, q_fea], outputs=x)
    return model


import src.create_db as create_db
import src.transform as transform
import src.load_db as load_db

def extract_transform_load(reader):

    ##Creates tables in postgress database
    tables = create_db.create_tables()
    tables.create_cafe_location_table()
    tables.create_products_table()
    tables.create_payment_type_table()
    tables.create_transactions_table()
    tables.create_basket_table()

    ##loads dataset from csv
    transform.load(reader)

    ##Removes sensitives information
    transform.remove_customer_info()

    ##Transforms order string
    transform.transform_order_string()

    #Loads clean data into database
    load_tables = load_db.load_tables()
    load_tables.load_products()
    load_tables.load_locations()
    load_tables.load_payment_type()
    load_tables.load_transactions()

    #Pulls transaction ID from transactions table in database
    load_tables.get_transaction_ids()

    ##Split orders per transaction ID
    transform.transaction_split()

    #Loads split orders
    load_tables.load_basket()


"""Test runner for cloud custodian policies."""

import pathlib
import unittest
from unittest.mock import PropertyMock, patch

import yaml

class CustodianPolicyTest(unittest.TestCase):
    """Cloud Custodian test runner base class."""

    @staticmethod
    def get_all_resources(call_args):
        """Get outputs from Cloud Custodian run."""
        resources = []
        metrics = []
        for i, resource in enumerate(call_args):
            if i % 2 == 0:
                resources.extend(resource[0][0])
            else:
                metrics.extend([resource[0][0]])
        return (resources, metrics)

    def extract_test_policy(self, policy_file_path: str, policy_names: list):
        """Alter policies YAML, strip mode and notify sections."""
        with open(policy_file_path) as f:
            policy_doc = yaml.safe_load(f)

        new_policy_doc = []
        test_policy_file_paths = []
        for policy in policy_doc["policies"]:
            if policy["name"] in policy_names:
                if "mode" in policy:
                    policy.pop("mode")
                for action in policy["actions"]:
                    if action["type"] == "notify":
                        policy["actions"].remove(action)
                new_policy_doc.append(policy)

                pathlib.Path(".test").mkdir(parents=True, exist_ok=True)
                test_policy_file_path = f'.test/test-{pathlib.Path(policy_file_path).stem}-{policy["name"]}.yaml'
                test_policy_file_paths.append(test_policy_file_path)

                with open(test_policy_file_path, "w") as f:
                    yaml.dump({"policies": new_policy_doc}, f)

        return test_policy_file_paths

    def run_policy(self, policy_file_path: str, policy_names: list, dumps):
        """Run Cloud Custodian policy on moto test backend."""
        from c7n.commands import run
        from c7n.config import Config

        test_policy_file_paths = self.extract_test_policy(
            policy_file_path=policy_file_path, policy_names=policy_names
        )

        args = {"output_dir": "output", "configs": test_policy_file_paths, "vars": None}
        config = Config.empty(**args)

        with patch("c7n.policy.Policy.execution_mode", new_callable=PropertyMock) as em:
            em.return_value = "pull"
            run(config)

        return self.get_all_resources(dumps.call_args_list)


from django.urls import path

from . views import (HomeView,

                    # Host View
                    HostGameListtView, Host_JoinRequestListView, Host_RemovePlayerView,

                    # Joiner View
                    Joiner_JoinRequestListView, Joiner_CancelRequestView, Joiner_UnjoinView)

urlpatterns = [
    path('', HomeView.as_view(), name='dashboard'),
    path('games/', HostGameListtView.as_view(), name='host-list'),

    # Frm Host Perspective
    path('games/host/<int:game_pk>/', Host_JoinRequestListView.as_view(), name='host-join-list'), # Join request list
    path('games/host/<str:user>/<int:game_pk>/remove', Host_RemovePlayerView.as_view(), name='host-remove-player'),

    # From rom Joiner Perspective
    path('join-list/', Joiner_JoinRequestListView.as_view(), name='join-list-joiner'),
    path('games/host/<int:game_pk>/remove', Joiner_CancelRequestView.as_view(), name='joiner-cancel-request'),
    path('games/host/<int:game_pk>/unjoin', Joiner_UnjoinView.as_view(), name='joiner-unjoin'),

    # As host - Removed player

]


import ctypes
import typing as tp

import llvmlite.ir as ir
import numpy as np

from typelib import AbstractType, Type

class ArrayType(AbstractType):
    def __init__(self) -> None:
        super().__init__("Array", ['T'], ['N'])

    def make_concrete(self, type_generics: tp.List[Type], num_generics: tp.List[int]) -> Type:
        ir_type = ir.ArrayType(type_generics[0].ir_type, num_generics[0])
        c_type = np.ctypeslib.ndpointer(dtype=type_generics[0].c_type, shape=(num_generics[0],))

        return Type("Array", type_generics, num_generics, ir_type, c_type)

Bool = Type("Bool", ir_type=ir.IntType(1), c_type=ctypes.c_bool)
Char = Type("Char", ir_type=ir.IntType(8), c_type=ctypes.c_char)
Float = Type("Float", ir_type=ir.DoubleType(), c_type=ctypes.c_double)
Int = Type("Int", ir_type=ir.IntType(64), c_type=ctypes.c_int64)
Null = Type("Null", ir_type=ir.VoidType(), c_type=ctypes.c_void_p)

Array = ArrayType()


import os
import tensorflow as tf
import tensorflow.keras.backend as K
from datetime import datetime

from models.Original_ResNet import make_original_ResNet
from models.preActivation_ResNet import make_preActivation_ResNet
from models.wide_ResNet import make_wide_ResNet

from Callbacks.LearningRateScheduler import SpecificLearningRateScheduler
from Callbacks.Callback import RecordCallbacks, custom_in_top_k_metrics

from Keras_utils.Utils import save_model_info, load_checkpoint, check_parameters
from Keras_utils.data_generator import CustomImageDataGenerator

from Test import test

tf.enable_eager_execution()

def train(**kwargs) :
    if isinstance(kwargs["epochs"], int) and kwargs["epochs"] > 0 :
        check_parameters(**kwargs)

        batch_size          = 128
        val_split_ratio     = 0.1
        momentum            = 0.9
        num_categories      = kwargs["num_categories"]

        if kwargs["base_folder"] is None :
            base_folder = os.path.join(".", "cifar_result")
        else :
            base_folder = kwargs["base_folder"]
        if not os.path.exists(base_folder) :
            os.mkdir(base_folder)

        save_folder = os.path.join(base_folder, str(datetime.now().strftime('%Y-%m-%d__%H%M%S')))
        os.mkdir(save_folder)

        save_model_path = os.path.join(save_folder, "model")
        os.mkdir(save_model_path)

        model_weights_path = os.path.join(save_model_path, "weights")
        os.mkdir(model_weights_path)

        model_structure_path = os.path.join(save_model_path, "structure")
        os.mkdir(model_structure_path)

        model_result_file = os.path.join(save_folder, "model_result.txt")
        ckpt_info_file = os.path.join(model_weights_path, "model-ckpt-info.json")
        top_k_record_file = os.path.join(save_folder, "in-top-k-record.txt")

        if num_categories == 10 :
            (train_X, train_y), (test_X, test_y) = tf.keras.datasets.cifar10.load_data()
        else :
            (train_X, train_y), (test_X, test_y) = tf.keras.datasets.cifar100.load_data()

        val_boundray = int(len(train_X) * val_split_ratio)
        val_X = train_X[-val_boundray : ]
        val_y = train_y[-val_boundray : ]
        train_X = train_X[ : -val_boundray]
        train_y = train_y[ : -val_boundray]

        trainData_shape = K.int_shape(train_X)
        num_trainData = trainData_shape[0]

        # CustomImageDataGenerator
        train_generator = CustomImageDataGenerator(train_X, train_y, trainData_shape[1 : ], True,
            batch_size, num_categories, True)
        val_generator = CustomImageDataGenerator(val_X, val_y, trainData_shape[1 : ], False,
            batch_size, num_categories, False)

        # Model
        if kwargs["ckpt_model_path"] is not None :
            print("\n\nLoading model from checkpoint...\n\n")
            model, ckpt_lr, ckpt_epoch = load_checkpoint(**kwargs)
        else :
            print("\n\nMaking new model...\n\n")

            inputs = tf.keras.Input(shape = tuple(trainData_shape[1 : ]))
            if kwargs["model_structure"] == 'original' :
                logits = make_original_ResNet(inputs, **kwargs)
            elif kwargs["model_structure"] == 'pre' :
                logits = make_preActivation_ResNet(inputs, **kwargs)
            else :
                logits = make_wide_ResNet(inputs, **kwargs)
            model = tf.keras.Model(inputs = inputs, outputs = logits)

        # Learning Rate
        lr = kwargs["initial_lr"]
        if lr is not None :
            # checkpoint의 learning rate를 사용하지 않거나, 새로운 model을 만들었을 때
            lr = tf.Variable(lr, trainable = False)
        elif (kwargs["ckpt_model_path"] is not None) and (ckpt_lr is not None) :
            # learning rate가 None이고, checkpoint의 learning rate를 사용하고 싶을 때
            lr = tf.Variable(ckpt_lr, trainable = False)
        else :
            # learning rate가 None이고, checkpoint에 learning rate가 존재하지 않을 때
            raise Exception("\nLearning rate is None\n")

        # kwargs['initial_epoch']
        initial_epoch = kwargs["initial_epoch"]
        if initial_epoch is not None :
            # checkpoint의 epoch를 사용하지 않거나, 새로운 model을 만들었을 때
            pass
        elif (kwargs["ckpt_model_path"] is not None) and (ckpt_epoch is not None) :
            # checkpoint의 epoch를 사용하고 싶을 때
            initial_epoch =  ckpt_epoch
        else :
            initial_epoch = 0

        # Compile
        if kwargs["model_structure"] in ['basic', 'pre'] :
            model.compile(
                optimizer = tf.keras.optimizers.SGD(
                    lr = lr, momentum = momentum),
                loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']
            )
        else :
            model.compile(
                optimizer = tf.keras.optimizers.SGD(
                    lr = lr, momentum = momentum, nesterov = True),
                loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']
            )

        save_model_info(model, save_folder, model_structure_path, model_weights_path, **kwargs)

        # Model callback
        callback_list = [RecordCallbacks(model_weights_path, model_result_file, ckpt_info_file)]

        callback_list += [
            custom_in_top_k_metrics(val_generator, top_k_record_file,
                batch_size = batch_size, num_categories = num_categories, max_in_top_k = 10)
        ]

        if kwargs["lr_scheduler"] == True :
            epoch = initial_epoch
            callback_list += [SpecificLearningRateScheduler(epoch, **kwargs)]

        # Training
        history = model.fit_generator(train_generator,
            epochs = kwargs["epochs"],
            shuffle = False,
            validation_data = val_generator,
            callbacks = callback_list,
            verbose = 1,
            initial_epoch = initial_epoch)

        # Evaluation
        print("\n\nModel Evaluation")
        test_generator = CustomImageDataGenerator(test_X, test_y, trainData_shape[1 : ], False,
            batch_size, num_categories, False)
        model.evaluate_generator(test_generator, verbose = 1)

    else :
        test(**kwargs)


#import random#랜덤모듈 사용

from tkinter.messagebox import NO
from django.shortcuts import render, HttpResponse, redirect

# def index(request):
#     return HttpResponse('
random
'+str(random.random())) #random만 하면 숫자라서 오류가 나기 때문에 랜덤함수를 스트링, 문자열로 치환해줘야한다
nextId = 4
topics = [
    {'id':1, 'title':'routing', 'body':'Routing is ...'},
    {'id':2, 'title':'view', 'body':'view is ...'},
    {'id':3, 'title':'Model', 'body':'Model is ...'},
]

def HTMLTemplate(articleTag, id=None):
    global topics #global로 전역변수 설정을 해줘야한다.
    contextUI = ''
    if id != None:
        contextUI = f'''

                <form action="/delete/" method="post">
                    <input type="hidden" name="id" value="{id}">
                    <input type="submit" value="delete">
                </form>

update

        '''

    ol = ''
    for topic in topics:
        ol += f'
{topic["title"]}
'
    return HttpResponse(f'''

Django

                                {ol}

                            {articleTag}

create

                                {contextUI}

                        ''')

def index(request):
    article = '''

welcom

            Hello, Django
    '''
    return HttpResponse(HTMLTemplate(article))

def create(request):
    print('request.method :', request.method)
    global nextId
    if request.method == 'GET':
        article = '''
            <form action="/create/" method="post">

<input type="text" name="title" placeholder="title">

<textarea name="body" placeholder="body"></textarea>

<input type="submit">

            </form>
        '''
        return HttpResponse(HTMLTemplate(article))
    elif request.method == 'POST':
        title    = request.POST['title']
        body     = request.POST['body']
        newTopic = {"id":nextId, "title":title, "body":body}

        topics.append(newTopic)
        url = '/read/'+str(nextId)
        nextId = nextId + 1

        return redirect(url) #HttpResponse(request.POST['title'])

def read(request, id):
    global topics
    article = ''

    for topic in topics:
        if topic['id'] == int(id):
            article = f'
{topic["title"]}
{topic["body"]}'
    return HttpResponse(HTMLTemplate(article, id))

def delete(request):
    global topics
    if request.method == 'POST':
        id = request.POST['id']
        newTopics = []

        for topic in topics:
            if topic['id'] != int(id):
                newTopics.append(topic)

        topics = newTopics
        print('id',id)
        return redirect('/')

def update(request, id):
    global topics
    if request.method == 'GET':
        for topic in topics:
            if topic['id'] == int(id):
                selectedTopic = {
                    "title":topic['title'],
                    "body":topic['body']
                }
        article = f'''
            <form action="/update/{id}/" method="post">

<input type="text" name="title" placeholder="title" value="{selectedTopic['title']}">

<textarea name="body" placeholder="body" >{selectedTopic['body']}</textarea>

<input type="submit">

            </form>
            '''
        return HttpResponse(HTMLTemplate(article, id))
    elif request.method == 'POST':
        title = request.POST['title']
        body = request.POST['body']
        for topic in topics:
            if topic['id'] == int(id):
                topic['title'] = title
                topic['body'] = body
        return redirect(f'/read/{id}')


from oop_farm_gencrop import *

class Potato(Crop):
  """A potato crop"""
  def __init__(self):
    # Call the parent class constructor with def values for potato
    # growth rate = 1; light need = 3; water need = 6
    super().__init__(1,3,6)
    self._type = "Potato"

  # override growth method for subclass
  def grow(self,light,water):
    if light >= self._light_need and water >= self._water_need:
      if self._status == "Seedling" and water > self._water_need:
        self._growth += self._growth_rate * 1.5
      elif self._status == "Young" and water > self._water_need:
        self._growth += self._growth_rate * 1.25
      else:
        self._growth += self._growth_rate
    self._days_growing += 1
    self._update_status()

def main():
  # Create new potato crop
  potato_crop = Potato()
  manual_grow(potato_crop)
  print(potato_crop.report())
  manual_grow(potato_crop)
  print(potato_crop.report())

if __name__ == "__main__":
  main()


from typing import Optional , List
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

"""
    思路 :
        这一题要求计算Binary Tree里面各个阶层的平均值 , 我的直观想法是阶层探寻 , 但此题为easy似乎有更直接的作法
"""

"""
    解法一. BFS , 直接寻访同一层级并且将该层级的平均值加入结果阵列
"""

from collections import deque

class Solution:

    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:

        queue = deque()
        result = []
        queue.append(root)

        while queue :

            average  = 0
            size = len(queue)
            # for循环使用size , 确保这个for-loop拿出来的都是同一个阶层的节点
            # 我们针对该层初始化节点数与总和值用以计算加总
            for i in range(size):

                node = queue.popleft()
                average+=node.val
                if node.left : queue.append(node.left)
                if node.right : queue.append(node.right)

            # 当完成一层节点的traverse , 计算该层的和
            result.append( average/size )

        return result

"""
    解法二. 仰赖dict的阶层寻访 , 为了要满足排序 , 在pre-order位置操作
"""

class Solution:

    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:

        # table:
        # key : depth
        # value : (node_num , sum)
        table = dict()
        depth = 0

        def traverse(node):
            nonlocal depth , table
            if node is None : return None

            if depth in table :
                table[depth][0] += 1
                table[depth][1] += node.val
            else :
                table[depth] = [1 , node.val]
            depth += 1
            traverse(node.left)
            traverse(node.right)
            depth -= 1

        traverse(root)
        result = []
        # 透过pre-order 我们建立的table顺序也会是由浅到深
        for value in table.values() :

            result.append( value[1] / value[0]  )

        return result

easy/Average of Levels in Binary Tree.py


# functions!
def greet():
    print('Hello!')

greet() # this is as basic as possible

# function with parameters
def get_average(input_numbers):
    sum = 0.0
    for number in input_numbers:
        sum += number
    average = sum / len(input_numbers)
    print(average)

get_average([5.0, 3.5, 7.8, 9.9, 10.0])

def print_letter_count(text, letter):
    counter = 0
    for char in text:
        if char == letter:
            counter += 1
    print('Number of', letter, 'is', counter)

print_letter_count('Welcome', 'e')
print_letter_count(letter='e', text='Welcome') # I like this! what are the limits to declaring vars?

# these are optional arguments at the end for the print function
# can use them or not, and they always have default values!
print('Hello', 'How are you?', end='.', sep='-')

# this function now is defined to have a default value, yet still set-able to 'a'
# caveat! must provide default ones at the END, won't work if you set at beginning
# likely no technical reason, probably aesthetic
def print_letter_count(text, letter='a'):
    counter = 0
    for char in text:
        if char == letter:
            counter += 1
    print('Number of', letter, 'is', counter)

print_letter_count('David Franzel')
# all positional arguments must be first, before optional arguments

# shadowing!
# the variable set within the function does not set the variable outside the function
# this is different from javascript, although perhaps not if you consider the variable
# is re-instantiated within the function, not setting the other one
# in javascript, you can prefix with 'var'/'let'/'const' to tell the computer if you are
# redeclaring, in python you have no option, just redeclaring it, more simple, but tradeoffs for sure
def show_truth():
    # global means don't shadow! the shadow is when this is redeclared in a different scope and so doesn't modify in the other scope
    global mysterious_var # this references the var one layer up and then modifies it in the next line
    mysterious_var = 'New Surprise!'
    print(mysterious_var)

mysterious_var = 'Surprise!'
print(mysterious_var)
show_truth()
print(mysterious_var)

# some functions return a value, some do something as their use

print_return = print('Hi!')
print(print_return) # this returns 'None', which is probably just like 'void' in java

# to get a function to return 'None', either don't specify a return, or just have 'return' with nothing following

x = None
if x is None:
    print('yes!')
if x == None:
    print('yay 2!')

def greet():
    print('hello!')

x = greet()
print(x)

# coding exercise for getting unique numbers
# was tricky and had to get a hint! not that hard, so oh well
def unique(numbers=[]):
    unique_list = []
    for number in numbers:
        if number not in unique_list:
            unique_list.append(number)
    return unique_list

print(unique([1,1,4,5,1]))


from datatype_constants import CourseOptions, RatedCourseSelection, CourseSelection, Lectures
from penalty_functions import get_total_penalty, MAX_CONSIDERATION
from itertools import product
import pickle

def unpackage_all_courses(selection: CourseSelection) -> Lectures:
    """Return a list containing all lecture slots in selection.

    """
    lectures = []
    for lecture_package in selection:
        for lecture_slot in lecture_package:
            lectures.append(lecture_slot)
    return lectures

def add_selection_results(all_selections: list[RatedCourseSelection], selection: CourseSelection) -> None:
    """Add the current course selection and its penalty value
    to all_selections, if the penalty does not exceed MAX_CONSIDERATION.

    """
    lectures = unpackage_all_courses(selection)
    penalty = get_total_penalty(lectures)
    if penalty <= MAX_CONSIDERATION:
        all_selections.append((
            get_total_penalty(lectures),
            lectures
        ))

def generate_all_selections(courses: CourseOptions) -> list[RatedCourseSelection]:
    all_selections = []
    processed_sets = set()
    for selection in product(*courses.values()):
        if str(selection) in processed_sets:
            continue
        add_selection_results(all_selections, list(selection))
        processed_sets.add(str(selection))
    return all_selections

def output_selection(processed_selection: RatedCourseSelection) -> None:
    """Output the total penalty and lecture times for each course in processed_selection.

    """
    print("Total penalty:", processed_selection[0])
    sorted_lectures = sorted(processed_selection[1], key=lambda lec: (lec.day_num, lec.end_hour))

    for lecture in sorted_lectures:
        lecture.output_info()

def output_all_selections(all_selections: list[RatedCourseSelection], max_output: int) -> None:
    """Output all course selections in all_selections in order of greatest-to-least penalty.
    At most max_output selections will be outputted.

    """
    all_selections.sort(key=lambda x: x[0], reverse=True)
    for selection in all_selections[-max_output:]:
        output_selection(selection)

    if len(all_selections) < max_output:
        print("Note: there aren't enough timetables that fit your requirements.")

def get_course_info(file_name: str) -> CourseOptions:
    """Return a CourseOptions dictionary containing the data in file_name.

    """
    with open(file_name, 'rb') as f:
        courses = pickle.load(f)
    return courses

def main(file_name: str) -> None:
    """Read from file_name and output the timetable results!
    """
    courses = get_course_info(file_name)

    print("Calculating results...")

    all_selections = generate_all_selections(courses)

    if not all_selections:
        print("Uh oh! There aren't any timetables that fit your requirements.")
        return

    num_selections = int(input("Results ready - How many options would you like to see? "))

    output_all_selections(all_selections, num_selections)

if __name__ == "__main__":
    main('summer2023.pickle')


import re

from http import HTTPStatus

from django.http.response import JsonResponse
from django.urls import reverse

from common.utils import get_region

ADMIN_REQUEST_RE = re.compile(r"/[a-z]{2}/admin")

def is_admin_request(request):

    return bool(ADMIN_REQUEST_RE.findall(request.path)) or bool(
        ADMIN_REQUEST_RE.findall(request.META.get("HTTP_REFERER", ""))
    )

def is_task_queue_or_cron(request):
    return request.META.get("HTTP_X_APPENGINE_CRON") or request.META.get(
        "HTTP_X_APPENGINE_QUEUENAME"
    )

def region_middleware(get_response):
    def middleware(request):

        region = get_region(request)

        if not (
            is_task_queue_or_cron(request)
            or is_admin_request(request)
            or request.path.startswith(reverse("webhook"))
            or request.path.startswith("/_ah/warmup")
            or request.path in ("/favicon.ico", "/robots.txt")
            or region
        ):
            return JsonResponse(
                {
                    "message": "Could not satisfy the request Region header.",
                    "code": "not_acceptable",
                },
                status=HTTPStatus.NOT_ACCEPTABLE,
            )

        request.region = region

        return get_response(request)

    return middleware


from django.contrib import admin
from .models import Course

# Register your models here.

class CourseModelAdmin(admin.ModelAdmin):

    # The fields to be used in displaying the Course model.
    # These override the definitions on the ModelAdmin
    list_display = ('title', 'slug', 'instructor', 'is_free',
                    'price', 'total_hours', 'total_articles', 'status', 'isDeleted')
    fieldsets = (
        ('Course', {
         'fields': ('title', 'short_description', 'long_description', 'instructor', 'categories', 'thumbnail', 'keywords', 'localizations', 'reject_reason', 'learn_description_points', 'requirements', 'is_free',
                    'price', 'total_hours', 'total_articles', 'status', 'isDeleted')}),
    )
    add_fieldsets = (
        ("Create Course", {
            'classes': ('wide',),
            'fields': ('title', 'short_description', 'long_description', 'instructor', 'categories', 'thumbnail', 'keywords', 'localizations', 'reject_reason', 'learn_description_points', 'requirements', 'is_free',
                       'price', 'total_hours', 'total_articles', 'status', 'isDeleted'),
        }),
    )
    list_filter = ('isDeleted', 'is_free')
    search_fields = ('title', 'slug', 'instructor', 'categories', 'localizations',
                     'price', 'total_hours', 'total_articles',)
    ordering = ('title', 'isDeleted')
    filter_horizontal = ()

# Now register the new UserModelAdmin...
admin.site.register(Course, CourseModelAdmin)


from machine import Pin
import ntptime
import utime as time
from .ds1302 import DS1302

def time_set():
    ntptime.settime()
    now = time.time() + 19800
    t = time.localtime(now)
    year, month, mday, hour, minute, second, weekday, yearday  = t
    ds = DS1302(Pin(5),Pin(18),Pin(19))
    ds.date_time([year, month, mday, weekday, hour, minute, second])

def time_get():
    ds = DS1302(Pin(5),Pin(18),Pin(19))
    return ds


x = 85
y = 120
target = 1000000000000

while y < target:
    # print(y)
    x, y = (3*x + 2*y - 2), (4*x + 3*y - 3)

print(x, y)

# Quadratic Diophantine equation solver: https://www.alpertron.com.ar/ENGLISH.HTM
# OEIS A011900: Members of Diophantine pairs


import case_convert
import general
import helper
from type_script import convert_from_class_to_ts_interface
from sql import convert_from_class_to_sql_table, convert_from_sql_table_to_class

if __name__ == '__main__':
    types: [] = ['ts', 'sql', 'sql_to_class', 'lowercase_to_pascal_case',
                 'lowercase_to_camel_case', 'lowercase_to_uppercase',
                 'camel_case_to_lowercase',
                 'from_class_to_interface', 'from_class_to_json', 'auto_mapper_1',
                 'auto_mapper_2']
    helper.print_array(types)

    type = input()

    if type == types[0]:
        convert_from_class_to_ts_interface()
    elif type == types[1]:
        convert_from_class_to_sql_table()
    elif type == types[2]:
        convert_from_sql_table_to_class()
    elif type == types[3]:
        case_convert.convert(type)
    elif type == types[4]:
        case_convert.convert(type)
    elif type == types[5]:
        case_convert.convert(type)
    elif type == types[6]:
        case_convert.convert(type)
    elif type == types[7]:
        general.from_class_to_interface()
    elif type == types[8]:
        general.from_class_to_json()
    elif type == types[9]:
        general.auto_mapper_1()
    elif type == types[10]:
        general.auto_mapper_2()


import torch
import pathlib
from PIL import Image
import cv2 as cv
import matplotlib.pyplot as plt
from matplotlib import patches
import sys
import os
sys.path.insert(0, os.path.join(os.path.curdir, "DataLoader"))
print(sys.path[0])
from MaskDataset import MaskDataset

def displayBox(image, targetLabels):
    """
        image: image tensor (channel, height, width)
        targetLabels: list of [c, xcenter, ycenter, widthNorm, heightNorm]
    """
    # denormalize
    image_height, image_width = image.shape[1:]
    mul = [1,image_width,image_height,image_width,image_height] #[constant, image_width, image_height, image_width, image_height]
    finalStage = []
    for x in targetLabels:
        c, xx, yy, w, h = x[0] * mul[0], x[1] * mul[1], x[2] * mul[2], x[3] * mul[3], x[4] * mul[4]
        finalStage.append([c, xx, yy, w, h])

    fig = plt.figure()
    # add axis at position rect
    ax = fig.add_axes([0, 0,1,1]) # left, bottom, width, height, which are fraction of figure width height

    plt.imshow(image.permute(1, 2, 0))

    for x in finalStage:
        class_ = int(x[0])
        xcenter, ycenter, width, height = x[1:]
        xmin, ymin = xcenter - width//2, ycenter - height//2
        xmax, ymax = xcenter + width//2, ycenter + height//2
        if class_ == 0:
            edgecolor = "r"
            ax.annotate('MASK', xy=(xmax - 40, ymin + 20))
        elif class_ == 1:
            edgecolor = "b"
            ax.annotate('NO MASK', xy=(xmax - 40, ymin + 20))
        # adding bounding box
        rect = patches.Rectangle((xmin,ymin), width, height, edgecolor = edgecolor, facecolor = 'none')
        ax.add_patch(rect)

    plt.show()

class Compose(object):
    def __init__(self, transforms):
        self.transforms = transforms

    def __call__(self, img, bboxes):
        for t in self.transforms:
            img, bboxes = t(img), bboxes

        return img, bboxes

import torchvision.transforms as transforms
transformer = Compose([transforms.Resize((448, 448)), transforms.ToTensor(),])

if __name__ == "__main__":
    trainPath = pathlib.Path.cwd() / "dataset/train"
    dataset = MaskDataset(trainPath / "images", trainPath / "labels", transformer=transformer)
    image, labels, label_matrix = dataset[0]
    displayBox(image, labels)


"""
### Shift rasters. ###

Module to shift the location of rasters in geographic coordinates.
"""

# Standard library
import sys; sys.path.append("../../")
from typing import Union, Optional, List

# External
from osgeo import gdal
import numpy as np

# Internal
from buteo.utils import (
    utils_base,
    utils_gdal,
    utils_path,
    utils_io,
)
from buteo.raster import core_raster, core_raster_io
from buteo.array.convolution import convolve_array_simple
from buteo.array.convolution_kernels import kernel_shift

def _raster_shift(
    raster: Union[str, gdal.Dataset],
    shift_list: List[Union[int, float]],
    out_path: Optional[str] = None,
    *,
    overwrite: bool = True,
    creation_options: Optional[List[str]] = None,
) -> Union[str, gdal.Dataset]:
    """ Internal. """
    assert isinstance(shift_list, (list, tuple)), f"shift_list must be a list or a tuple. {shift_list}"
    assert len(shift_list) == 2, f"shift_list must be a list or tuple with len 2 (x_shift, y_shift): {shift_list}"

    for shift in shift_list:
        assert isinstance(shift, (int, float)), f"shift must be an int or a float: {shift}"

    ref = core_raster._raster_open(raster)
    metadata = core_raster._get_basic_metadata_raster(ref)

    x_shift, y_shift = shift_list

    if out_path is None:
        out_path = utils_path._get_temp_filepath("shifted_raster.tif")
    else:
        if not utils_path._check_is_valid_output_filepath(out_path, overwrite=overwrite):
            raise ValueError(f"out_path is not a valid output path: {out_path}")

    utils_path._delete_if_required(out_path, overwrite)

    driver = gdal.GetDriverByName(utils_gdal._get_raster_driver_name_from_path(out_path))

    shifted = driver.Create(
        out_path,  # Location of the saved raster, ignored if driver is memory.
        metadata["width"],  # Dataframe width in pixels (e.g. 1920px).
        metadata["height"],  # Dataframe height in pixels (e.g. 1280px).
        metadata["bands"],  # The number of bands required.
        metadata["dtype_gdal"],  # Datatype of the destination.
        utils_gdal._get_default_creation_options(creation_options),
    )

    new_transform = list(metadata["geotransform"])
    new_transform[0] += x_shift
    new_transform[3] += y_shift

    shifted.SetGeoTransform(new_transform)
    shifted.SetProjection(metadata["projection_wkt"])

    src_nodata = metadata["nodata_value"]

    for band in range(metadata["bands"]):
        origin_raster_band = ref.GetRasterBand(band + 1)
        target_raster_band = shifted.GetRasterBand(band + 1)

        target_raster_band.WriteArray(origin_raster_band.ReadAsArray())

        if src_nodata is not None:
            if utils_base._check_variable_is_int(src_nodata):
                target_raster_band.SetNoDataValue(int(src_nodata))
            else:
                target_raster_band.SetNoDataValue(float(src_nodata))

    shifted.FlushCache()
    shifted = None
    ref = None

    return out_path

def raster_shift(
    raster: Union[str, gdal.Dataset, List],
    shift_list: List[Union[int, float]],
    out_path: Optional[str] = None,
    *,
    overwrite: bool = True,
    prefix: str = "",
    suffix: str = "",
    add_uuid: bool = False,
    add_timestamp: bool = False,
    creation_options: Optional[List[str]] = None,
) -> Union[str, List[str], gdal.Dataset]:
    """
    Shifts a raster in a given direction. (The frame is shifted)

    Parameters
    ----------
    raster : Union[str, List, gdal.Dataset]
        The raster(s) to be shifted.

    shift_list : List[Union[int, float]]
        The shift in x and y direction.

    out_path : Optional[str], optional
        The path to the output raster. If None, the raster is created in memory., default: None

    overwrite : bool, optional
        If True, the output raster will be overwritten if it already exists., default: True

    prefix : str, optional
        The prefix to be added to the output raster name., default: ""

    suffix : str, optional
        The suffix to be added to the output raster name., default: ""

    add_uuid : bool, optional
        If True, a unique identifier will be added to the output raster name., default: False

    add_timestamp : bool, optional
        If True, a timestamp will be added to the output raster name., default: False

    creation_options : Optional[List[str]], optional
        The creation options to be used when creating the output., default: None

    Returns
    -------
    Union[str, List[str]]
        The path(s) to the shifted raster(s).
    """
    utils_base._type_check(raster, [str, gdal.Dataset, [str, gdal.Dataset]], "raster")
    utils_base._type_check(shift_list, [[int, float], tuple], "shift_list")
    utils_base._type_check(out_path, [str, [str], None], "out_path")
    utils_base._type_check(overwrite, [bool], "overwrite")
    utils_base._type_check(creation_options, [[str], None], "creation_options")
    utils_base._type_check(prefix, [str], "prefix")
    utils_base._type_check(suffix, [str], "suffix")
    utils_base._type_check(add_uuid, [bool], "add_uuid")
    utils_base._type_check(add_timestamp, [bool], "add_timestamp")

    input_is_list = isinstance(raster, list)

    input_list = utils_io._get_input_paths(raster, "raster")
    output_list = utils_io._get_output_paths(
        input_list,
        out_path,
        overwrite=overwrite,
        prefix=prefix,
        suffix=suffix,
        add_uuid=add_uuid,
        add_timestamp=add_timestamp,
        change_ext="tif",
    )

    utils_path._delete_if_required_list(output_list, overwrite)

    shifted_rasters = []
    for idx, in_raster in enumerate(input_list):
        shifted_rasters.append(
            _raster_shift(
                in_raster,
                shift_list,
                out_path=output_list[idx],
                overwrite=overwrite,
                creation_options=creation_options,
            )
        )

    if input_is_list:
        return shifted_rasters

    return shifted_rasters[0]

def raster_shift_pixel(
    raster: Union[str, gdal.Dataset],
    shift_list: List[Union[int, float]],
    out_path: Optional[str] = None,
) -> str:
    """
    Shifts a raster in a given direction. (The pixels are shifted, not the frame)

    Parameters
    ----------
    raster : Union[str, gdal.Dataset]
        The raster to be shifted.

    shift_list : List[Union[int, float]]
        The shift in x and y direction.

    out_path : Optional[str], optional
        The path to the output raster. If None, the raster is created in memory., default: None

    Returns
    -------
    str
        The path to the shifted raster.
    """
    utils_base._type_check(raster, [str, gdal.Dataset], "raster")
    utils_base._type_check(shift_list, [[int, float], tuple], "shift_list")
    utils_base._type_check(out_path, [str, None], "out_path")

    arr = core_raster_io.raster_to_array(raster)

    offsets, weights = kernel_shift(shift_list[0], shift_list[1])

    arr_float32 = arr.astype(np.float32, copy=False)

    for channel in range(arr.shape[2]):
        arr[:, :, channel] = convolve_array_simple(
            arr_float32[:, :, channel], offsets, weights,
        )

    if out_path is None:
        out_path = utils_path._get_temp_filepath("shifted_raster.tif")
    else:
        if not utils_path._check_is_valid_output_filepath(out_path):
            raise ValueError(f"out_path is not a valid output path: {out_path}")

    utils_path._delete_if_required(out_path, overwrite=True)

    return core_raster_io.array_to_raster(
        arr,
        reference=raster,
        out_path=out_path,
    )