def Convert_Function(event, context):
    """Triggered by a change to a Cloud Storage bucket.
   Args:
        event (dict): Event payload.
        context (google.cloud.functions.Context): Metadata for the event.
   """

    import pandas as pd
    import numpy as np
    try:
        import keras
    except:
        from tensorflow import keras
    import requests

    # Log event detalis
    print('Bucket: {}'.format(event['bucket']))
    print('File: {}'.format(event['name']))

    # Only accept CSV uploads
    if ("csv" not in event["name"]) or (event['bucket'] != "ECG_BUCKET"):
        return

    def convert_ecg(df: pd.DataFrame):
        signals = np.asarray([signal for index, signal in df.iterrows()])
        return signals

    bucketName = event['bucket']
    blobName = event['name']
    fileName = "gs://" + bucketName + "/" + blobName
    ecg_df = pd.read_csv(fileName)
    records = convert_ecg(ecg_df)

    # Load model based on Keras loaded
    print("loading model")
    try:
        model = keras.model.load(
            "gs://" + "PATH_TO_AI_MODEL" + "classifier.h5")
    except:
        model = keras.models.load_model(
            "gs://" + "PATH_TO_AI_MODEL" + "classifier.h5")
    labels = {
        0: "Normal",
        1: "SVEB",
        2: "VEB",
        3: "Fusion",
        4: "Unknown"
    }

    print("running model")
    pred = model.predict(records)
    pred_label = labels[list(pred[0]).index(max(pred[0]))]
    url = "https://REGION-PROJECT-NAME.cloudfunctions.net/FUNCTION?key=GCP_KEY"
    headers = {
        "Content-Type": "application/json",
    }
    body = {
        "message": pred_label
    }
    print("Posting results")
    post_request = requests.post(headers=headers, url=url, json=body)

    return{
        "statusCode": 200,
        "body": "success"
    }


T=int(input())
from collections import deque

def bfs(row,col):
    dy = [-1, 1, 0, 0, 1, -1, 1, -1]
    dx = [0, 0, -1, 1, 1, -1, -1, 1]

    move = deque()
    move.append([row,col,1])

    while move:
        y, x, count = move.popleft()
        visited[y][x] = count

        for i in range(8):
            ny = y + dy[i]
            nx = x + dx[i]

            if 0 <= ny < X and 0 <= nx < Y and not visited[ny][nx] and List[ny][nx]=='*':
                visited[ny][nx] = count+1
                move.append([ny, nx, count+1])

for _ in range(T):
    X,Y=map(int,input().split())
    List=[]
    visited=[[0 for _ in range(Y)] for _ in range(X)]
    for _ in range(X):
        List.append(list(input()))
    value=1
    for i in range(X):
        for j in range(Y):
            if List[i][j]=='*':
                bfs(i,j)
                value+=1

    print(visited)


import math

class Phrases_dispatcher:

    def __init__(self):
        self.last_phrases_list = {}
        #self.shift = 0

    def delete_phrases_list(self):
        del self.last_phrases_list
        self.last_phrases_list = {}
        #self.shift = 0

    def add_phrase(self, phrase, index, replic_index):
        self.last_phrases_list[str(replic_index)+"_"+str(index)] = phrase

        if len(self.last_phrases_list) > 20:
            keys = list(self.last_phrases_list.keys())
            for i in range(0, 10):
                self.last_phrases_list.pop(keys[i])

    def get_prev_phrase(self, index, replic_index):
        #[words_translations2, positions_of_translated_words2, pos2]
        key = str(replic_index)+"_"+str(index)
        if key in self.last_phrases_list:
            return self.last_phrases_list[key]
        else:
            return False

    def compare_current_prev_with_previous_word2(self, current_phrase2_index, current_phrase1, replic_index):
        phrase1_translations = []
        phrase1_positions = []

        prev_phrase2 = self.get_prev_phrase(current_phrase2_index-1, replic_index)
        if not prev_phrase2:
            return [phrase1_translations, phrase1_positions]

        prev_phrase2_translations = prev_phrase2[0]
        prev_phrase2_positions_of_translated_words = prev_phrase2[1]
        prev_phrase2_pos = prev_phrase2[2]

        current_phrase1_translations = current_phrase1[0]
        current_phrase1_positions_of_translated_words = current_phrase1[1]
        current_phrase1_pos = current_phrase1[2]

        if len(current_phrase1_pos) == len(prev_phrase2_pos):

            start_righ_part_index = math.ceil(len(current_phrase1_pos) / 2)

            # get all prev_word2_translations witch key < start_righ_part_index
            # get all  prev_word2_positions_of_translated_words witch key < start_righ_part_index

            for k, translation in prev_phrase2_translations.items():
                if k < start_righ_part_index:
                    phrase1_translations.append(translation)
                    phrase1_positions.append(prev_phrase2_positions_of_translated_words[k])

            for j in range(start_righ_part_index, len(current_phrase1_pos)):
                if current_phrase1_pos[j]!=-1 and prev_phrase2_pos[j] != -1 and current_phrase1_pos[j] != prev_phrase2_pos[j]:#TYPE 1 - POS SUBSTITUTE
                    if j in current_phrase1_translations:
                        phrase1_translations.append(current_phrase1_translations[j])
                    if j in current_phrase1_positions_of_translated_words:
                        phrase1_positions.append(current_phrase1_positions_of_translated_words[j])

                #elif current_phrase1_pos[j]==-1 and prev_phrase2_pos[j] != -1:#TYPE 2 DELETION
                    #continue
                elif current_phrase1_pos[j] != -1 and prev_phrase2_pos[j] == -1:#TYPE 3 INSERTION
                    if j in current_phrase1_translations:
                        phrase1_translations.append(current_phrase1_translations[j])
                    if j in current_phrase1_positions_of_translated_words:
                        phrase1_positions.append(current_phrase1_positions_of_translated_words[j])

                elif current_phrase1_pos[j] == prev_phrase2_pos[j] and current_phrase1_pos[j] != -1:
                    if j in current_phrase1_translations:
                        phrase1_translations.append(current_phrase1_translations[j])
                    if j in current_phrase1_positions_of_translated_words:
                        phrase1_positions.append(current_phrase1_positions_of_translated_words[j])

        return [phrase1_translations, phrase1_positions]


from django.conf.urls import patterns, url
from rest_framework.routers import DefaultRouter

from . import views

router = DefaultRouter()

router.register(r'accounts', views.AccountViewSet)

api_urlpatterns = router.urls

api_urlpatterns += patterns(
    # Prefix
    '',

    url(r'auth/signup_domains/check/$',
        views.CheckSignupDomainAPIView.as_view(),
        name='auth-signup-domains-check'),

    url(r'auth/signup_domains/validate/$',
        views.ValidateSignupDomainsAPIView.as_view(),
        name='auth-signup-domains-validate'),
)

urlpatterns = patterns(
    # Prefix
    '',

    url(r'^$',
        views.AccountHTMLView.as_view(), name='account_detail'),

    url(r'^activity/$',
        views.AccountHTMLView.as_view(), name='account_activity'),

    url(r'^activity/(?P<board_slug>[-\w]+)/$',
        views.AccountHTMLView.as_view(), name='account_board_activity'),
)


import signal

from z_pack import Z_LOG_PREFIX, Z_TRACE, Z_TRACE_F
import scdc
import hookdemo

PREFIX = "hook_srv: "

np_tcp = None
np_stream = None

NODEPORT_TCP = scdc.NODEPORT_START_ASYNC_UNTIL_CANCEL
NODEPORT_STREAM = scdc.NODEPORT_START_LOOP_UNTIL_CANCEL

def sighandler(sig, frame):
  Z_TRACE_F("sig: " + str(sig));

  interrupt = (sig != 0)

  if NODEPORT_TCP != None:
    scdc.nodeport_cancel(np_tcp, interrupt)
  if NODEPORT_STREAM != None:
    scdc.nodeport_cancel(np_stream, interrupt)

def cmd_handler(data, cmd, params):
  Z_TRACE_F("data: " + str(data) + ", cmd: '" + cmd + "', params: '" + params + "'")

  if cmd == "quit":
    Z_TRACE("quiting server")
    sighandler(0, None);
  else:
    Z_TRACE("unkown server command: '" + cmd + "'")

  return True

signal.signal(signal.SIGABRT, sighandler)
signal.signal(signal.SIGTERM, sighandler)
signal.signal(signal.SIGINT, sighandler)

Z_TRACE("start hook demo")
Z_TRACE()

scdc.init()

dp_hook = scdc.dataprov_open("hookdemo", "hook:id", hookdemo.hook, 0x2501)

if NODEPORT_TCP != None:
    np_tcp = scdc.nodeport_open("tcp:max_connections", 2)
if NODEPORT_STREAM != None:
    np_stream = scdc.nodeport_open("stream:cmd_handler", cmd_handler, None)

scdc.nodeport_start(np_tcp, NODEPORT_TCP)
scdc.nodeport_start(np_stream, NODEPORT_STREAM)

scdc.nodeport_stop(np_stream)
scdc.nodeport_stop(np_tcp)

scdc.nodeport_close(np_stream)
scdc.nodeport_close(np_tcp)

scdc.dataprov_close(dp_hook)

scdc.release()

#scdc.log_release()

Z_TRACE("quit hook demo")
Z_TRACE()


me2opp = {"X": "A", "Y": "B", "Z": "C"}
score_board = {"A": 1, "B": 2, "C": 3}

lose = {"A": "C", "B": "A", "C": "B"}
win = {v: k for k, v in lose.items()}

points_task_one = 0
points_task_two = 0

def battle(me, opp):
    if me == "C" and opp == "A":
        return 0
    elif me == "A" and opp == "C":
        return 6
    elif me < opp:
        return 0
    elif me > opp:
        return 6
    elif me == opp:
        return 3
    else:
        raise ValueError("Unsupported battle scenario. Me: " + str(me) + ", Opponent: " + str(opp))

with open("input/2dec.txt") as file:
    for line in file.readlines():
        second_sign = line[2]
        opp = line[0]

        # task one
        points_task_one = points_task_one + battle(me2opp[second_sign], opp) + score_board[me2opp[second_sign]]

        # task two
        if second_sign == "X":
            me = lose[opp]
        elif second_sign == "Y":
            me = opp
            points_task_two += 3
        elif second_sign == "Z":
            me = win[opp]
            points_task_two += 6
        else:
            raise ValueError("Unsupported strategy. Strategy: " + str(second_sign))

        points_task_two += score_board[me]

print("Answer to task 1: My total score according to plan " + str(points_task_one))
print("Answer to task 2: My total score according to plan " + str(points_task_two))


import os
from datetime import datetime

import cv2
import face_recognition
import numpy as np
# import pyodbc

path = "/home/bhuvan/Desktop/Code/email/Code/training"
images = []
imgLabel  = []
myList = os.listdir(path)

for currentlist in myList :
    currentImg = cv2.imread(f'{path}\\ {currentlist}')
    images.append(currentImg)
    imgLabel.append(os.path.splitext(currentlist)[0])

def findEncodings(images):
    encodeList=[]
    for img in images :
        img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
    return encodeList

encodelistKnownFaces = findEncodings(images)
print('Encoding Complete')

# def markAttendance2(name,InTime,InDate):
#     conn = pyodbc.connect('Driver = {SQL Server};'
#                           'SERVER = localhost:3306;'
#                           'Database = Facial Recognition'
#                           'Trusted_Connection = yes')

#     cursor = conn.cursor()

#     sql = '''insert into Facial Recogntion.dbo.tbl_Facial recognition 1 (Name,InDate.InTime) values(?,?,?)'''

#     val = (name,InDate,InTime)
#     cursor.execute(sql, val)
#     conn.commit()

webcam = cv2.VideoCapture(0)
AttendanceValidate = 'a'

while True :
    success, img  = webcam.read()
    imgS = cv2.resize(img,(0,0), None , 0.25,0,0.25)
    imgS = cv2.cvtColor(imgS,cv2.COLOR_BGR2RGB)

    faceCurrentFrame = face_recognition.face_locations(imgS)
    encodeCurrentFrame = face_recognition.face_encodings(imgS,faceCurrentFrame)

    for encodeFace, facelocation in zip(encodeCurrentFrame,faceCurrentFrame):
        match = face_recognition.compare_faces(encodelistKnownFaces, encodeFace)
        faceDistance = face_recognition.face_distance(encodelistKnownFaces, encodeFace)

        matchIndex = np.argmin(faceDistance)

        if match[matchIndex]:
            name =  imgLabel[matchIndex].upper()
            y1,x2,y2,x1 = facelocation
            y1,x2,y2,x1 =  y1*4,x2*4,y2*4,x1*4
            cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),3)
            cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
            cv2.putText(img,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)

            crTime = datetime.now().time()
            crDate = datetime.now().date()
            if name!= AttendanceValidate:
                #markAttendance2(name,str(crTime),str(crDate))
                AttendanceValidate = name

    cv2.imshow('Frame' , img)
    if cv2.waitKey(1) & 0XFF == ord('q'):
        break

webcam.release()
cv2.destroyAllWindows()


# Considering a list of positive integers where each item represents the maximum steps you can take
# return the minimum amount of steps to get from index 0 to index size - 1

from random import randint
from typing import List

from data_structures.queue import Queue

def get_least_amount_of_steps(steps: List[int]) -> List[int]:
    return breadth_first_search(steps, 0, len(steps) - 1)

def breadth_first_search(graph: List[int], source_vertex: int, target_vertex: int) -> List[int]:
    vertices_to_visit = Queue()
    vertices_to_visit.enqueue(source_vertex)

    distances = {source_vertex: 0}

    while not vertices_to_visit.is_empty():
        current_vertex = vertices_to_visit.dequeue()
        for neighbor in range(1, graph[current_vertex] + 1):
            neighbor_index = current_vertex + neighbor
            if neighbor_index < len(graph):
                if neighbor_index not in distances:
                    distances[neighbor_index] = distances[current_vertex] + 1
                    if neighbor_index == target_vertex:
                        return distances[target_vertex]
                    vertices_to_visit.enqueue(neighbor_index)

if __name__ == '__main__':
    max_steps = 5
    max_nodes = 10
    steps = [randint(1, max_steps) for i in range(max_nodes)]
    print(steps)
    print(get_least_amount_of_steps(steps))


import nuke
from string import zfill

def sag_slateTests():
	durList = {}

	f = open( 'X:/SAVVA/data/Ep_dur.txt', 'r' )
	for line in f:
		sht = line.split()
		durList[ sht[0] ] = int( sht[1] )
	f.close()

	selList = nuke.selectedNodes( filter = 'Read' )

	outList = []
	for each in selList:
		exr = each['file'].value()
		if exr[-4:] == '.exr':
			fr = int( exr.split( '.' )[-2] )
			spl = exr.split( '.' )[0].split( '/' )[-1].split( '_' )
			shot = spl[0] + '_' + spl[1] + '_' + spl[2]
			task = spl[3]
			ver = spl[4]

			nuke.selectAll()
			nuke.invertSelection()
			each[ 'selected' ].setValue( 1 )
			slate = nuke.createNode( 'sag_slate' )
			slate[ 'duration' ].setValue( str(durList[shot]) )
			slate[ 'scriptname' ].setValue( shot + '_' + task + '_' + ver )
			nuke.toNode( slate.name() + '.frameCounter' )[ 'message' ].setValue( 'frame: ' + zfill( fr, len( str(durList[shot]) ) ) + ' of ' + str(durList[shot]) )

			wrt = nuke.createNode( 'Write' )
			wrt[ 'file' ].setValue( exr[:-4] + '.jpg' )
			outList.append( wrt )

	nuke.selectAll()
	nuke.invertSelection()
	for each in outList:
		each[ 'selected' ].setValue( 1 )


text = "This a test text. We're keeping this text short to keep things manageable."

def count_words(text):
    """Count the number of times each word occurs in a text."""
    text = text.lower()
    skips = [",",".",";",":","'",'"']
    for ch in skips:
        text = text.replace(ch,"")
    word_counts = {}
    for word in text.split(" "):
        # known word
        if word in word_counts:
            word_counts[word] += 1
        # unknown word
        else:
            word_counts[word] = 1
    return word_counts

from collections import Counter

def count_words_fast(text):
    """Count the number of times each word occurs in a text."""
    text = text.lower()
    skips = [",",".",";",":","'",'"']
    for ch in skips:
        text = text.replace(ch,"")

    word_counts = Counter(text.split(" "))
    return word_counts

def read_book(title_path):
    """"""
    with open(title_path, "r", encoding="utf8" ) as current_file:
        text = current_file.read()
        text = text.replace("\n","").replace("\r","")
    return text

def word_stats(word_counts):
    """Return number of unique words and word frequencies."""
    num_unique = len(word_counts)
    counts = word_counts.values()
    return (num_unique, counts)
text = read_book("C:\\Users\\User\\Desktop\\Romeo and Juliet.txt")

import os
book_dir = ""

import pandas as pd
stats = pd.DataFrame(columns = ("language","author","title","length","unique"))
title_num = 1
for language in os.listdir(book_dir):
    for author in os.listdir(book_dir + "/" + language):
        for title in os.listdir(book_dir + "/" + language + "/" + author):
            inputfile = book_dir + "/" + language + "/" + author + "/" + title
            print(inputfile)
            text = read_book(inputfile)
            (num_unique, counts) = word_stats(count_words(text))
            stats.loc[title_num] = language, author.capitalize(), title.replace(".txt",""), sum(counts), num_unique
            title_num += 1

import matplotlib.pyplot as plt
plt.plot(stats.length, stats.unique, "bo")
plt.loglog(stats.length, stats.unique, "bo")
stats[stats.language == "English"]
plt.figure(figsize = (10,10))
subset = stats[stats.language == "French"]
plt.loglog(subset.length, subset.unique,"o", label = "French", color ="crimson")
subset = stats[stats.language == "English"]
plt.loglog(subset.length, subset.unique,"o", label = "English", color ="forestgreen")
subset = stats[stats.language == "German"]
plt.loglog(subset.length, subset.unique,"o", label = "German", color ="orange")
subset = stats[stats.language == "Portuguese"]
plt.loglog(subset.length, subset.unique,"o", label = "Portuguese", color ="blueview")
plt.legend()
plt.xlabel("Book length")
plt.ylabel("Number of unique words")
plt.savefig("lang_plot.pdf")


import subprocess as sp

fd = open("/home/nk-nicolas/Documentos/Apuntes/Personal-Projects/Ejemplos/Python/text_files/sp-file.txt", "w+")

# Uso el pipe para pasarle la salida del proceso anterior a la entrada del siguiente
proc1 = sp.Popen(["ip a"], shell=True, stdout=sp.PIPE)
proc2 = sp.Popen(["grep inet"], shell=True, stdin=proc1.stdout, stdout=sp.PIPE)
proc3 = sp.Popen(["awk '{print $2}'"], shell=True, stdin=proc2.stdout, stdout=fd)
# Me imprime por salida en una archivo el ultimo comando
fd.flush() # si quiero usar flush para cargarlo al buffer, no necesitamos cerrarlo


import streamlit as st

st.title('최상위 수학 4-2')

mon = '월요일 PAGE 28-30'
corrects = ['99', '4/9', '3+1/4', '7', '31', '6/19,9/19,14/19', '103']
problems = ['2','3','4: (숫자)+(숫자)/(숫자)','5','6','7: 분수,분수,분수','8',]

tue = '화요일_PAGE 34-37'
corrects_tue = ['18','둔각삼각혁','4','7','45', '120', '110','4','60','12','80']
problems_tue = ['1-4', '1-5', '1-6', '2-1-(1)', '2-1-(2)', '2-2', '2-3', '2-4', '2-5-(1)', '2-5-(2)','2-6']

wed = '수요일_PAGE 38-41'
corrects_wed = ['65','7','25','80','12','70','150','6','105','55','35','60']
problems_wed = ['1-1','1-2','1-3','2-1','2-2','2-3','3-1','3-2','3-3','4-1','4-2','4-3']

thu = "목요일_PAGE 42-44"
corrects_thu = ['84','44','9','7','16','16','6','68','68','360']
problems_thu = ['5-1','5-2','5-3','6-1','6-2','6-3', '심화7_1','심화7_2','심화7_3', '7']

fri = "금요일_PAGE 45-48 Level up Test"
corrects_fri = ['29','100','4','38','85','12','8','38','232','70','64','540','20' ]
problems_fri = ['1','2','3','4','5','6: 긴 변','6: 짧은 변','7','8','9','10','11','12']

with st.expander(mon):
    answers = []
    if len(corrects) != len(problems):
        st.write('프로그램에 에러가 있습니다. 관리자에게 문의하세요')

    for i in range(len(problems)):
        form = st.form(problems[i] + 'mon')
        answers.append(form.text_input(problems[i]))

        if answers[i] == corrects[i]:
            form.subheader('good job')
            st.snow()
        else:
            form.write('sorry, try again')

        form.form_submit_button("Submit")

    if corrects == answers:
        st.balloons()

with st.expander(tue):
    answers_tue = []
    if len(corrects_tue) != len(problems_tue):
        st.write('프로그램에 에러가 있습니다. 관리자에게 문의하세요')

    for i in range(len(problems_tue)):
        form = st.form(problems_tue[i] + 'tue')
        answers_tue.append(form.text_input(problems_tue[i]))

        if answers_tue[i] == corrects_tue[i]:
            form.subheader('good job')
            st.snow()
        else:
            form.write('sorry, try again')

        form.form_submit_button("Submit")

    if corrects_tue == answers_tue:
        st.balloons()

with st.expander(wed):
    answers_wed = []
    if len(corrects_wed) != len(problems_wed):
        st.write('프로그램에 에러가 있습니다. 관리자에게 문의하세요')

    for i in range(len(problems_wed)):
        form = st.form(problems_wed[i] + 'wed')
        answers_wed.append(form.text_input(problems_wed[i]))

        if answers_wed[i] == corrects_wed[i]:
            form.subheader('good job')
            st.snow()
        else:
            form.write('sorry, try again')

        form.form_submit_button("Submit")

    if corrects_wed == answers_wed:
        st.balloons()

with st.expander(thu):
    answers_thu = []
    if len(corrects_thu) != len(problems_thu):
        st.write('프로그램에 에러가 있습니다. 관리자에게 문의하세요')

    for i in range(len(problems_thu)):
        form = st.form(problems_thu[i] + 'thu')
        answers_thu.append(form.text_input(problems_thu[i]))

        if answers_thu[i] == corrects_thu[i]:
            form.subheader('good job')
            st.snow()
        else:
            form.write('sorry, try again')

        form.form_submit_button("Submit")

    if corrects_thu == answers_thu:
        st.balloons()

with st.expander(fri):
    answers_fri = []
    if len(corrects_fri) != len(problems_fri):
        st.write('프로그램에 에러가 있습니다. 관리자에게 문의하세요')

    for i in range(len(problems_fri)):
        form = st.form(problems_fri[i] + 'fri')
        answers_fri.append(form.text_input(problems_fri[i]))

        if answers_fri[i] == corrects_fri[i]:
            form.subheadere('good job')
            st.snow()
        else:
            form.write('sorry, try again')

        form.form_submit_button("Submit")

    if corrects_fri == answers_fri:
        st.balloons()


"""
Test ping route
"""
import json

from typing import Callable
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask.testing import FlaskClient

from app.api.users.models import User

from utils import error_message, header_from_user

def test_ping_200(
    client: FlaskClient, database: SQLAlchemy, add_random_user: Callable[[], User]
):
    """Ping.GET - 200"""

    _user = add_random_user()
    response = client.get(
        "/api/v1/ping",
        json=header_from_user(_user),
        content_type="application/json",
    )
    data = json.loads(response.data.decode())

    assert response.status_code == 200
    assert response.content_type == "application/json"
    assert "ping" in data["message"]

def test_ping_400(client: FlaskClient, database: SQLAlchemy):
    """Ping.GET - 400"""

    response = client.get(
        "/api/v1/ping",
    )
    data = json.loads(response.data.decode())

    assert response.status_code == 400
    assert response.content_type == "application/json"
    assert error_message(400) in data["message"]

def test_ping_403(client: FlaskClient, database: SQLAlchemy):
    """Ping.GET - 403"""

    response = client.get(
        "/api/v1/ping",
        json={
            "header": {
                "API_KEY_ID": "ping_403",
                "API_SECRET_KEY": "ping_403",
            }
        },
        content_type="application/json",
    )
    data = json.loads(response.data.decode())

    assert response.status_code == 403
    assert response.content_type == "application/json"
    assert error_message(403) in data["message"]


import html

def htmlize2(obj):
    content=html.escape(repr(obj))
    return '
{0}
'.format(content)

print(htmlize2(1))
print(htmlize2([1,2,3]))
print(htmlize2("1"))
print()

'''python3.4新增的functools.singledispatch装饰器可以把整体方案拆分成多个模块
    使用@singledispatch装饰的普通函数会变成泛函数：
    根据第一个参数的类型，以不同方式执行相同操作的一组函数'''
from functools import singledispatch
from collections import abc
import numbers

@singledispatch
def htmlize(obj):
    content=html.escape(repr(obj))
    return '
{}
'.format(content)

@htmlize.register(str)
def _(text):    #专门函数的名称无关紧要
    content=html.escape(text).replace('\n','
\n')
    return '
{0}
'.format(content)
@htmlize.register(numbers.Integral) #为每个需要特殊处理的类型注册一个函数。numbers.Integral是int的虚拟超类
def _(n):
    return '
{0} (0x{0:x})
'.format(n)
@htmlize.register(tuple)
@htmlize.register(abc.MutableSequence)
def _(seq):
    inner='
\n
'.join(htmlize(item) for item in seq)
    return '
\n
'+inner+'
\n
'

print(htmlize({1,2,3}))
print(htmlize(abs))
print(htmlize('airair \n airairair'))
print(htmlize(42))
print(htmlize(['alpha',66,{3,2,1}]))


#-*- coding: UTF-8 -*-

from numpy import *
import operator

def createDataSet():
	group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
	labels=['A','A','B','B']
	return group,labels

def classify0(inX,dataSet,labels,k):
	dataSetSize=dataSet.shape[0] #dataSet的长度
	diffMat=tile(inX,(dataSetSize,1))-dataSet#差
	sqDiffMat=diffMat**2#各自求平方
	sqDistances=sqDiffMat.sum(axis=1)#求和
	distances=sqDistances**0.5
	sortedDistIndicies=distances.argsort()#从小到大的排序的index
	classCount={}
	for i in range(k):
		voteIlabel=labels[sortedDistIndicies[i]] #求label
		classCount[voteIlabel]=classCount.get(voteIlabel,0)+1 #转化为计数字典
	sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)#对计数字典进行排序
	return sortedClassCount[0][0]

def file2matrix(filename):
	fr=open(filename)
	numberOfLines=len(fr.readlines())
	returnMat=zeros((numberOfLines,3))
	classLabelVector=[]
	fr=open(filename)
	index=0
	for line in fr.readlines():
		line=line.strip()
		listFromLine=line.split('\t')
		returnMat[index,:]=listFromLine[0:3]
		classLabelVector.append(listFromLine[-1])
		index+=1
	return returnMat,classLabelVector

datingDataMat,datingLabels=file2matrix('datingTestSet.txt')


import asyncio
import inspect
import discord
import pprint
from discord.ext import commands

from youtube_dl import YoutubeDL

class music_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.ms = ''

        self.is_playing = False

        self.music_queue = []
        self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
        self.FFMPEG_OPTIONS = {
            'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

        self.vc = ""

    def search_youtube(self, item):
        # 'with' means we use it and at the end, we throw away
        with YoutubeDL(self.YDL_OPTIONS) as ydl:
            try:
                info = ydl.extract_info("ytsearch:%s" % item, download=False)['entries'][0]
            except Exception:
                return False
        return {'source': info['formats'][0]['url'], 'title': info['title']}

    def play_next(self):
        if len(self.music_queue) > 0:
            self.is_playing = True
            music_url = self.music_queue[0][0]['source']
            self.music_queue.pop(0)

            self.vc.play(discord.FFmpegPCMAudio(music_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())

        else:
            self.is_playing = False

    async def play_music(self):
        if len(self.music_queue) > 0:
            self.is_playing = True
            music_url = self.music_queue[0][0]['source']
            if self.vc == "" or not self.vc.is_connected():
                self.vc = await self.music_queue[0][1].connect()
            # else:
            #     self.vc = await self.bot.move_to(self.music_queue[0][1])
            self.ms = ''
            self.ms += (self.music_queue[0][0]['title'])
            # print(type(self.music_queue[0][0]['title']))
            self.music_queue.pop(0)
            # self.music_queue.pop(0)

            self.vc.play(discord.FFmpegPCMAudio(music_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
        else:
            self.is_playing = False

    @commands.command()
    async def p(self, ctx, *args):
        query = " ".join(args)
        # voice_channel = ctx.author.voice.channel
        # print(voice_channel)
        try :
            voice_channel = ctx.author.voice.channel
            song = self.search_youtube(query)
            self.music_queue.append([song, voice_channel])
            await ctx.send("Song Added : %s" % song['title'])

            if self.is_playing == False:
                await self.play_music()

        except AttributeError:
            return

        # if voice_channel is None:
        #     await ctx.send("Connected")
        # else:
        #     song = self.search_youtube(query)
        #     if type(song) == type(True):
        #         await ctx.send("Wrong Song,  Need Another")
        #     else:
        #         self.music_queue.append([song, voice_channel])
        #         await ctx.send("Song Added : %s" % song['title'])

        #         if self.is_playing == False:
        #             await self.play_music()

    @commands.command()
    async def q(self, ctx):
        print(self.ms)
        if self.ms == '':
            retval = ""
        else:
            retval = "[Now Playing]: " + self.ms +" \n"
            self.ms=''

        for i in range(0, len(self.music_queue)):
            retval += '['+str(i)+'] : '
            retval += self.music_queue[i][0]['title'] + '\n'

        if retval != "":
            await ctx.send(retval)
        else:
            await ctx.send("Not Music in Queue")

    @commands.command()
    async def skip(self, ctx):
        if self.vc != "":
            self.vc.stop()
            await self.play_music()
        # else:

    @commands.command()
    async def bothelp(self, ctx):
        await ctx.send("사용법 \n음악 재생 !p 음악 이름 + 가수; (주의사항: 똥 프로그램이라 음악이름을 상세하게 적어주세요)\n음악 리스트 !q \n음악 넘기기 !skip\n")


import sys, time
sys.stdin = open('input.txt')

# # 완전검색 하는 경우

# T = int(input())

# def permutation(a):
#     arr = []
#     n = len(a)
#     def perm(n, k):
#         nonlocal arr
#         if n == k:
#             value = 0
#             now = home
#             for nxt in a:
#                 value += abs(nxt[0]-now[0]) + abs(nxt[1]-now[1])
#                 now = nxt
#             value += abs(office[0]-now[0]) + abs(office[1]-now[1])
#             arr += [value]
#         else:
#             for i in range(k, n):
#                 a[i], a[k] = a[k], a[i]
#                 perm(n, k+1)
#                 a[i], a[k] = a[k], a[i]
#     perm(n,0)
#     return min(arr)

# for tc in range(1, T+1):
#     n = int(input())
#     maps = [[0 for _ in range(100)] for _ in range(100)]
#     points = list(map(int, input().split()))
#     home, office = points[0:2], points[2:4]
#     points = [[points[i], points[i+1]] for i in range(4, (n+2)*2, 2)]
#     arr = []
#     print(permutation(points))

# 가지치기 하는 경우

T = int(input())

start_time = time.time()

def permutation(a):
    arr = []
    n = len(a)
    minN = 1000000
    def perm(n, k, value, now):
        nonlocal arr, minN
        if n == k:
            value += abs(office[0]-now[0]) + abs(office[1]-now[1])
            arr += [value]
            minN = min(value, minN)
        else:
            for i in range(k, n):
                a[i], a[k] = a[k], a[i]
                nxt = value + abs(a[k][0]-now[0])+ abs(a[k][1]-now[1])
                if nxt > minN:
                    a[i], a[k] = a[k], a[i]
                    return
                perm(n, k+1, nxt, a[k])
                a[i], a[k] = a[k], a[i]
    perm(n, 0, 0, home)
    return min(arr)

for tc in range(1, T+1):
    n = int(input())
    maps = [[0 for _ in range(100)] for _ in range(100)]
    points = list(map(int, input().split()))
    home, office = points[0:2], points[2:4]
    points = [[points[i], points[i+1]] for i in range(4, (n+2)*2, 2)]
    print(permutation(points))

print(time.time()-start_time)


from django.db import transaction
from django.shortcuts import render, redirect, render_to_response, get_object_or_404
import haikunator
from .models import Room
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
import uuid
import random

def about(request):
    context = RequestContext(request)
    room_list = []
    for room in Room.objects.all():
        if room.number < 2:
            room_list.append(room)

    return render(request, "chat/about.html", {
        'room_list': room_list,
    })

def new_room(request):
    """
    Randomly create a new room, and redirect to it.
    """
    new_room = None
    while not new_room:
        with transaction.atomic():
            label = haikunator.haikunate()
            if Room.objects.filter(label=label).exists():
                continue
            new_room = Room.objects.create(label=label, number=0)
    return redirect(chat_room, label=label)

def chat_room(request, label):
    """
    Room view - show the room, with latest messages.

    The template for this view has the WebSocket business to send and stream
    messages, so see the template for where the magic happens.
    """
    # If the room with the given label doesn't exist, automatically create it
    # upon first visit (a la etherpad).
    context = RequestContext(request)
    room, created = Room.objects.get_or_create(label=label, number=0)

    if room.chat_status == "Waiting":
        return render_to_response('')
    elif room.chat_status == "Initialize":
        return render_to_response('')
    # We want to show the last 50 messages, ordered most-recent-last
    messages = reversed(room.messages.order_by('-timestamp')[:50])

    return render(request, "chat/room.html", {
        'room': room,
        'messages': messages,
    })

def update_status(request):
    label = request.POST['label']
    status = request.POST['status']
    room = Room.objects.all().get(label = label)
    room.chat_status = status
    room.save()
    return HttpResponse(status)

def end_chat(label):
    room = Room.objects.all().get(label = label)
    room.chat_status = "Terminated"
    room.save()
    return redirect('/')


# Exercício Python 089: Crie um programa que leia nome e duas notas de vários alunos e
# guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um
# e permita que o usuário possa mostrar as notas de cada aluno individualmente.

cadastro = list()
aux = list()
i = 0
aluno = 0

while True:
    nome = str(input('Nome: ')).title().strip()
    aux.append(nome)
    nota1 = float(input('Nota 1: '))
    aux.append(nota1)
    nota2 = float(input('Nota 2: '))
    aux.append(nota2)
    cadastro.append(aux[:])
    aux.clear()
    resp = str(input('Quer adicionar outro aluno [S/N]: ')).lower().strip()[0]
    if resp in 'n':
        break
    i += 1
print('-=' * 15)
print('Nº\tNome\tMedia')
print('-' * 30)

for pos, val in enumerate(cadastro):
    media = (val[1] + val[2]) / 2
    print(f'{pos}\t{val[0]}\t{media:>.1f}')

while True:
    aluno = int(input('Deseja mostrar a nota de qual aluno: '))
    if aluno == 999:
        break
    print(f'As notas do aluno {cadastro[aluno][0]}, foram: {cadastro[aluno][1]} e {cadastro[aluno][2]}')
print('Fim do programa.')


#Converts scanned pdf to separate images and extract text from it(Language:Tamil)
import sys
sys.stdout.reconfigure(encoding='utf-8')

import fitz  # PyMuPDF
import pytesseract
from PIL import Image

# Replace 'path_to_your_scanned.pdf' with the actual path to your scanned PDF file
pdf_path = 'tamil.pdf'

# Function to extract images and Tamil text from the PDF
def extract_tamil_text_from_pdf(pdf_path):
    pdf_document = fitz.open(pdf_path)
    extracted_text = []

    for page_number in range(len(pdf_document)):
        page = pdf_document.load_page(page_number)
        image_list = page.get_images(full=True)

        for image_index, img in enumerate(image_list):
            xref = img[0]
            base_image = pdf_document.extract_image(xref)
            image_data = base_image["image"]

            # Save the image as a file
            image_filename = f"page_{page_number + 1}_image_{image_index + 1}.png"
            with open(image_filename, "wb") as image_file:
                image_file.write(image_data)

            # Perform OCR to extract Tamil text from the image
            tamil_text = pytesseract.image_to_string(Image.open(image_filename), lang='tam')
            extracted_text.append(tamil_text)

    return extracted_text

# Call the function to extract images and Tamil text from the PDF
extracted_tamil_text = extract_tamil_text_from_pdf(pdf_path)

# # Print or use the extracted Tamil text
# for i, tamil_text in enumerate(extracted_tamil_text, start=1):
#     print(f"Tamil Text from Image {i}:\n{tamil_text}\n")

# Save the extracted Tamil text to a text file
output_file = 'extracted_tamil_text.txt'
with open(output_file, 'w', encoding='utf-8') as file:
    for tamil_text in extracted_tamil_text:
        file.write(tamil_text + '\n')

print(f"Extracted Tamil text saved to {output_file}")


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        sentinel = ListNode(0, head)
        second, first = sentinel, head

        # 第一个指针移动到位
        for i in range(n):
            first = first.next

        # 此时两个指针位置间隔为 n + 1
        # 两个指针同时移动
        while first:
            second = second.next
            first = first.next

        second.next = second.next.next
        return sentinel.next

19. 删除链表的倒数第 N 个结点.py

19. 删除链表的倒数第 N 个结点.py


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$',views.index),
    url(r'^register$',views.register),
    url(r'^dashboard$',views.dashboard),
    url(r'^itemprocess$',views.itemprocess),
    url(r'^item$',views.item),
    url(r'^wishprocess$',views.wishlistprocess),
    url(r'^wishlist$',views.wishlist)
]


from collections import deque

def find_start_marker(buffer: str):
    d = deque(maxlen=14)
    for index, character in enumerate(buffer):
        d.append(character)
        if len(set(d)) == 14:
            return index + 1

def main():
    with open('input.txt', 'r') as f:
        input = f.read()
    start = find_start_marker(input)
    print(start)

if __name__ == '__main__':
    main()


from argparse import ArgumentParser

# handle CLI arguments
parser = ArgumentParser()
parser.add_argument("-i", help="Insert Ip")
parser.add_argument("-on", help="Turn On Command", action='store_true')
parser.add_argument("-off", help="Turn Off Command", action='store_true')
parser.add_argument("-b", help="Set Brightness")
parser.add_argument("-pruebas", help="Pruebas", action='store_true')

opts = parser.parse_args()
del parser

ip = opts.i

import asyncio

import pywizlight
from pywizlight import PilotBuilder, discovery, wizlight

async def turn_off():
    try:
        light = wizlight(ip)
        await light.turn_off()
    except Exception as e:
        print("No light found")

async def turn_on(brightness = 255):
    try:
        light = wizlight(ip)
        await light.turn_on(PilotBuilder(brightness = brightness))
    except Exception as e:
        print("No light found")

if opts.on:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(turn_on())
elif opts.off:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(turn_off())
elif opts.b:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(turn_on(int(opts.b)))
else:
    print("No command given")


def main():
    import argparse
    from .core import do_sync
    from . import __version__
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config-file', help='indicate config file path')
    parser.add_argument('--version', action='version', version=__version__)
    args = parser.parse_args()
    config_path = __resolve_config_file_path(args.config_file, '~/.config/pysync.json', '~/pysync.json')
    do_sync(config_path)

def __resolve_config_file_path(path, *defaults):
    from pathlib import Path
    if path:
        expanded_path = Path(path).expanduser()
        if expanded_path.exists():
            return str(expanded_path.resolve())
        raise Exception('Not found config file `{}`'.format(path))
    for default_path in defaults:
        expanded_path = Path(default_path).expanduser()
        if expanded_path.exists():
            return str(expanded_path.resolve())
    raise Exception("Not found config file in [{}]".format(', '.join(defaults)))

if __name__ == '__main__':
    main()


def isPrimeNumber(value):
  result = True
  for x in range(value):
    divider = x + 1
    if (divider > 1 and divider < value and value % divider == 0):
      result = False
  return result

def isPalindrome(value):
  result = True
  length = len(value)
  for x in range(length):
    if not (value[x] == value[length - x - 1]):
      result = False
    if (x > length / 2): # optimization to only go through half of the string
      break
  return result

def isPerfectNumber(value):
  dividerSum = 0
  for x in range(value):
    divider = x + 1
    if (divider < value and value % divider == 0):
      dividerSum += divider
  return value == dividerSum


import cv2
import numpy as np
import random

def applyAffineTransform(src, srcTri, dstTri, size) :
    warpMat = cv2.getAffineTransform( np.float32(srcTri), np.float32(dstTri) )
    dst = cv2.warpAffine( src, warpMat, (size[0], size[1]), None, flags=random.randrange(1,5), borderMode=cv2.BORDER_REFLECT_101 )

    return dst

def rectContains(rect, point) :
    if point[0] < rect[0] :
        return False
    elif point[1] < rect[1] :
        return False
    elif point[0] > rect[0] + rect[2] :
        return False
    elif point[1] > rect[1] + rect[3] :
        return False
    return True

def calculateDelaunayTriangles(rect, points):
    subdiv = cv2.Subdiv2D(rect)

    for p in points:
        subdiv.insert(p)

    triangleList = subdiv.getTriangleList()
    delaunayTri = []
    pt = []
    for t in triangleList:
        pt.append((t[0], t[1]))
        pt.append((t[2], t[3]))
        pt.append((t[4], t[5]))

        pt1 = (t[0], t[1])
        pt2 = (t[2], t[3])
        pt3 = (t[4], t[5])

        if rectContains(rect, pt1) and rectContains(rect, pt2) and rectContains(rect, pt3):
            ind = []
            for j in range(0, 3):
                for k in range(0, len(points)):
                    if(abs(pt[j][0] - points[k][0]) < 1.0 and abs(pt[j][1] - points[k][1]) < 1.0):
                        ind.append(k)
            if len(ind) == 3:
                delaunayTri.append((ind[0], ind[1], ind[2]))

        pt = []

    return delaunayTri, subdiv

def warpTriangle(img1, img2, t1, t2) :
    r1 = cv2.boundingRect(np.float32([t1]))
    r2 = cv2.boundingRect(np.float32([t2]))

    t1Rect = []
    t2Rect = []
    t2RectInt = []

    for i in range(0, 3):
        t1Rect.append(((t1[i][0] - r1[0]),(t1[i][1] - r1[1])))
        t2Rect.append(((t2[i][0] - r2[0]),(t2[i][1] - r2[1])))
        t2RectInt.append(((t2[i][0] - r2[0]),(t2[i][1] - r2[1])))

    mask = np.zeros((r2[3], r2[2], 3), dtype = np.float32)
    cv2.fillConvexPoly(mask, np.int32(t2RectInt), (1.0, 1.0, 1.0), 16, 0)

    size = (r2[2], r2[3])
    img1Rect = img1[r1[1]:r1[1] + r1[3], r1[0]:r1[0] + r1[2]]
    img2Rect = applyAffineTransform(img1Rect, t1Rect, t2Rect, size)
    img2Rect = img2Rect * mask

    img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] * ( (1.0, 1.0, 1.0) - mask )
    img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] + img2Rect

def cvt_annot_to_pt(annot):

    pt_list = []
    for x, y in annot:
        pt_list.append((int(x), int(y)))
    return pt_list

def filter_keyid_annot(src_annot, filter_ids):
    """ src_annot: a list of (keypoint_id, x, y)
        filter_ids: a list of [keypoint_ids] to be remained
    """
    new_list = []
    for item in src_annot:
        if item[0] in filter_ids:
            new_list.append(item)

    return new_list

def draw_face_landmark(img, annot):

    for x, y in annot:
        cv2.circle(img, (int(x),int(y)), 3, (0,0,255), -1)

def calc_new_keypoints(annot):
    """ Caculate additional 11 keypoints from existing 21 keypoints.
        For visual representation of new key points, please refer to the reference report.
        annot:
    """
    # assert len(annot) == 21, "To add new key points, existing annotation should be 21, but {}.".format(len(annot))

    b1_annot = []
    b1_annot.append(np.zeros((2,), np.int32))   # add dummy array to make annot list to 1 base index.
    b1_annot.extend(annot)

    # below eyeblows
    i22 = (b1_annot[2] + b1_annot[8])/2     #left
    b1_annot.append(i22)
    i23 = (b1_annot[5] + b1_annot[11])/2    #right
    b1_annot.append(i23)

    # temples
    i24 = b1_annot[7] + (b1_annot[7] - b1_annot[9])/2   #left
    b1_annot.append(i24)
    i25 = b1_annot[12]+ (b1_annot[12] - b1_annot[10])/2     #right
    b1_annot.append(i25)

    # the ridge of the nose
    i26 = (b1_annot[9] + b1_annot[10] + b1_annot[15])/3
    b1_annot.append(i26)

    #cheeks
    i27 = (b1_annot[13] + b1_annot[14])/2     #left
    b1_annot.append(i27)
    i28 = (b1_annot[16] + b1_annot[17])/2    #right
    b1_annot.append(i28)

    #philtrum
    i29 = (b1_annot[15] + b1_annot[19])/2
    b1_annot.append(i29)

    #upper chin
    i30 = (b1_annot[19] + b1_annot[21])/2
    b1_annot.append(i30)

    #below eyes
    i31 = (b1_annot[7] * 2 + b1_annot[15])/3     #left
    b1_annot.append(i31)
    i32 = (b1_annot[12] * 2 + b1_annot[15])/3    #right
    b1_annot.append(i32)

    #cheek bones
    i33 = (b1_annot[27] + b1_annot[31])/2   #left
    b1_annot.append(i33)
    i34 = (b1_annot[28] + b1_annot[32])/2   #right
    b1_annot.append(i34)

    #below nose
    i35 = (b1_annot[14] + b1_annot[18])/2   #left
    b1_annot.append(i35)
    i36 = (b1_annot[16] + b1_annot[20])/2   #right
    b1_annot.append(i36)

    #below lips
    r1 = (b1_annot[18] + b1_annot[21])/2    #left reference
    r2 = (b1_annot[20] + b1_annot[21])/2    #right reference
    i37 = (r1+r2)/2 + 3*(r1-r2)/4           #left
    b1_annot.append(i37)
    i38 = (r1+r2)/2 + 3*(r2-r1)/4           #right
    b1_annot.append(i38)

    #sides of lips
    i39 = b1_annot[18] + (b1_annot[18] - b1_annot[19])/3
    b1_annot.append(i39)
    i40 = b1_annot[20] + (b1_annot[20] - b1_annot[19])/3
    b1_annot.append(i40)

    assert len(b1_annot) - 1 == 40, "the length of new annot list should be 32 but {}".format(len(b1_annot) - 1)

    return b1_annot[1:]

def getBoundaryMask(mask):
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(7,7))
    new_mask = cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, kernel)
    return new_mask

def faceswap(img1, face_rect1, annot1, img2, face_rect2, annot2, style, rect_crop, resolution):
    """ crop img1's face and merge into img2's face region
        face1 and face2 have the identical keypoints.
    """
    img1Warped = np.copy(img2);

    # Read array of corresponding points
    points1 = cvt_annot_to_pt(annot1)
    points2 = cvt_annot_to_pt(annot2)

    # # Find convex hull
    hull1 = []
    hull2 = []
    hullIndex = cv2.convexHull(np.array(points2), returnPoints = False)
    for i in range(len(hullIndex)):
        hull1.append(points1[int(hullIndex[i])])
        hull2.append(points2[int(hullIndex[i])])
    # # print('hull1: {}, hull2: {}'.format(hull1, hull2))
    # # Find delanauy traingulation for convex hull points
    # dt, subdiv = calculateDelaunayTriangles(face_rect2, hull2)

    # if len(dt) == 0:
    #     raise Exception()

    # # Apply affine transformation to Delaunay triangles
    # for i in range(len(dt)):
    #     t1, t2 = [], []
    #     #get points for img1, img2 corresponding to the triangles
    #     for j in range(3):
    #         t1.append(hull1[dt[i][j]])
    #         t2.append(hull2[dt[i][j]])

    #     warpTriangle(img1, img1Warped, t1, t2)

    dt, subdiv = calculateDelaunayTriangles(face_rect2, points2)
    # Apply affine transformation to Delaunay triangles
    for i in range(len(dt)):
        t1, t2 = [], []
        #get points for img1, img2 corresponding to the triangles
        for j in range(3):
            t1.append(points1[dt[i][j]])
            t2.append(points2[dt[i][j]])

        warpTriangle(img1, img1Warped, t1, t2)

    hull8U = []
    for i in range(0, len(hull2)):
        hull8U.append((hull2[i][0], hull2[i][1]))

    mask = np.zeros(img2.shape, dtype = img2.dtype)
    # img_h, img_w = img2.shape[0:2]
    # mask_1ch = np.zeros((img_h, img_w, 1), dtype = np.uint8)

    cv2.fillConvexPoly(mask, np.int32(hull8U), (255, 255, 255))
    # cv2.fillConvexPoly(mask_1ch, np.int32(hull8U), (255, 255, 255))

    # x, y, w, h = face_rect2
    # cx = int(x + 0.5 * w)
    # cy = int(y + 0.5 * h)
    # maxwh = max(w, h)
    # half = int(0.5 * (1 + 2 * arg.pad) * maxwh)
    # x = max(0, cx - half)
    # y = max(0, cy - half)
    # w = 2 * half
    # h = 2 * half

    # img1Warped = img1Warped[y:y+h, x:x+w, :]
    # img1Warped = cv2.resize(img1Warped, (arg.resize, arg.resize), cv2.INTER_CUBIC)
    top, left, bottom, right = rect_crop
    mask = mask[top:bottom, left:right, :]
    mask = cv2.resize(mask, (resolution, resolution), cv2.INTER_NEAREST)
    img1Warped = img1Warped[top:bottom, left:right, :]
    img1Warped = cv2.resize(img1Warped, (resolution, resolution), cv2.INTER_CUBIC)
    resize_ratio_x = resolution / (right - left)
    resize_ratio_y = resolution / (bottom - top)

    if style == 'warp':
        # output = img1Warped
        output = cv2.colorChange(np.uint8(img1Warped), mask, random.uniform(0.5, 2.5), random.uniform(0.5, 2.5), random.uniform(0.5, 2.5))
    elif style == 'smoothwarp':
        output = cv2.colorChange(np.uint8(img1Warped), mask, random.uniform(0.5, 2.5), random.uniform(0.5, 2.5), random.uniform(0.5, 2.5))
        output_blur = cv2.GaussianBlur(output, (7,7), random.uniform(0.8, 2.0))
        b_mask = getBoundaryMask(mask)
        b_mask = b_mask.astype(np.bool)
        output[b_mask] = output_blur[b_mask]

    elif style == 'seamless':
        hx, hy, hw, hh = cv2.boundingRect(np.float32([hull2]))
        hull_top = max(top, hy)
        hull_left = max(left, hx)
        hull_bottom = min(bottom, hy + hh)
        hull_right = min(right, hx + hw)
        center_hull = (int((hull_left + hull_right) / 2), int((hull_top + hull_bottom) / 2))
        # center_hull = (int(hx + hw / 2), int(hy + hh / 2))

        img2 = img2[top:bottom, left:right, :]
        img2 = cv2.resize(img2, (resolution, resolution), cv2.INTER_CUBIC)

        chx, chy = center_hull
        chx = int((chx - left) * resize_ratio_x)
        chy = int((chy - top) * resize_ratio_y)
        center = (chx, chy)

        output = cv2.seamlessClone(np.uint8(img1Warped), img2, mask, center, cv2.NORMAL_CLONE)

    # for debugging - KJH
    # temp_annot=[]
    # for x,y in annot2:
    #     r_x = int((x - left) * resize_ratio_x)
    #     r_y = int((y - top) * resize_ratio_y)
    #     temp_annot.append((r_x,r_y))
    # draw_face_landmark(output, temp_annot)

    # mask = getBoundaryMask(mask)

    return output, mask

if __name__ == '__main__':
    import sys; sys.path.append('../')
    from imdb import UMDFaces
    from dataset import DatasetSyn
    from util import get_config, Logger
    import datetime
    import argparse
    import os
    from glob import glob
    from tqdm import trange

    now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    parser = argparse.ArgumentParser(description='Description')
    parser.add_argument('--tag', default="faceswap", type=str, help='Experiment tag')
    parser.add_argument('--name', type=str, default='UMDFaces')
    parser.add_argument('--num_img', type=int, default=300)
    parser.add_argument('--clear_cache', action='store_true')
    parser.add_argument('--preset', type=str, default='gan')
    parser.add_argument('--set', type=str, default=None, nargs=argparse.REMAINDER)
    args = parser.parse_args()
    cfg = get_config(args, now, src_dir=os.path.join(os.getcwd(), '../'))

    print('>> Loading Logger...')
    logger = Logger(cfg, None)

    class_name = args.name.replace('-', '_')
    imdb = eval(class_name)(cfg, args.name, logger=logger)
    dset = DatasetSyn(cfg, imdb, 'train', 'fake')
    # dset.swap_style = ['seamless']
    dset.swap_style = { 'warp': 0.0, 'smoothwarp': 1.0, 'seamless': 0.0 }

    check_path = os.path.join(cfg.test_path, 'check_faceswap', args.name)
    os.makedirs(check_path, exist_ok=True)

    import cv2
    li = list(range(len(imdb.imgpath)))
    import random
    # print('>> Shuffling...')
    # random.shuffle(li)

    print('>> Removing existing files...')
    for filename in glob(os.path.join(check_path, '*.jpg')):
        os.remove(filename)

    dset.reset()

    print('>> Start!')
    for i in trange(args.num_img):
        idx = li[i]
        idx_src = idx
        idx_dst = dset._get_idx_dst(idx_src)
        crop_rect = dset._crop(idx_dst)

        imgpath = os.path.join(cfg.data_path, imdb.imgpath[idx_dst])
        bbox_original = imdb.bbox_original[idx]
        bbox_min = imdb.bbox_min[idx]
        bbox_max = imdb.bbox_max[idx]
        img = cv2.imread(imgpath)
        h, w, c = img.shape
        # thickness = max(5, 5 * h // 500)
        thickness = 1

        imgpath_src = os.path.join(cfg.data_path, imdb.imgpath[idx_src])
        img_src = cv2.imread(imgpath_src)
        ann_src = imdb.points[idx_src]
        new_ann_src = calc_new_keypoints(ann_src)
        draw_face_landmark(img_src, new_ann_src)
        # img = cv2.rectangle(
        #     img,
        #     (bbox_original[1], bbox_original[0]),
        #     (bbox_original[3], bbox_original[2]),
        #     (0, 0, 255), thickness) # Red

        # img = cv2.rectangle(
        #     img,
        #     (bbox_min[1], bbox_min[0]),
        #     (bbox_min[3], bbox_min[2]),
        #     (255, 0, 0), thickness) # Blue

        # img = cv2.rectangle(
        #     img,
        #     (bbox_max[1], bbox_max[0]),
        #     (bbox_max[3], bbox_max[2]),
        #     (255, 0, 0), thickness) # Blue

        img = cv2.rectangle(
            img,
            (crop_rect[1], crop_rect[0]),
            (crop_rect[3], crop_rect[2]),
            (0, 0, 255), thickness) # Red

        ann_dst = imdb.points[idx_dst]
        new_ann_dst = calc_new_keypoints(ann_dst)
        draw_face_landmark(img, new_ann_dst)

        imgpath = imgpath.replace(cfg.data_path + '/', '')
        imgpath = imgpath.replace(args.name + '/', '')
        imgpath = imgpath.replace('.jpg', '')
        imgpath = imgpath.replace('.png', '')
        imgname = imgpath.replace('/', '+')

        save_img_name = os.path.join(check_path, '{:03d}_{}_img.jpg'.format(i, imgname))
        save_face_name = os.path.join(check_path, '{:03d}_{}_face.jpg'.format(i, imgname))
        save_mask_name = os.path.join(check_path, '{:03d}_{}_mask.jpg'.format(i, imgname))

        # cv2.imwrite(save_img_name, img)

        save_img_name_src = save_img_name.replace('img.jpg', 'srcimg.jpg')
        #cv2.imwrite(save_img_name_src, img_src)

        # face, mask = dset._random_swap(idx_src, idx_dst, crop_rect)
        face = dset._random_swap(idx_src, idx_dst, crop_rect)

        # cv2.imwrite(save_face_name, face)
        # cv2.imwrite(save_mask_name, mask)


from typing import List
import typing

from PyQt5 import QtGui
from PyQt5.QtCore import QEvent, QObject, QSignalBlocker, QStringListModel
from ime.ui.ui_access_control_list import Ui_AccessControlList
from PyQt5.QtWidgets import QMessageBox, QWidget, QLineEdit

class AccessControlList(QWidget):

    def __init__(self, parent = None):
        super().__init__(parent)
        self.ui = Ui_AccessControlList()
        self.ui.setupUi(self)
        #Libby to add line edit
        #self.ui.input_box = QLineEdit(self)

        #Libby Initialize the flag to False
        self.item_added = False

        self.ui.btnAdd.clicked.connect(self.handle_insert_new)
        self.ui.btnDelete.clicked.connect(self.handle_remove)
        # To monitor focus out events and deselect
        # self.ui.aclList.installEventFilter(self)
        self.ui.overrideCheckBox.installEventFilter(self)
        self.ui.overrideCheckBox.setVisible(False)
        self.ui.overrideCheckBox.toggled.connect(self.handle_override_changed)
        self.has_inheritance = False

    def set_has_inheritance(self, has_inheritance: bool):
        self.has_inheritance = has_inheritance
        self.ui.overrideCheckBox.setVisible(has_inheritance)
        if not has_inheritance:
            self.ui.aclList.setEnabled(True)
        elif getattr(self, 'list_model', None) is None:
            self.ui.aclList.setDisabled(True)
            return
        elif self.list_model.rowCount() > 0:
            # TODO Need to differentiate no vs empty state
            self.ui.overrideCheckBox.setChecked(True)
            self.ui.aclList.setEnabled(True)
        else:
            self.ui.aclList.setDisabled(True)
            self.ui.overrideCheckBox.setChecked(False)

    def handle_override_changed(self):
        checked = self.ui.overrideCheckBox.isChecked()
        list_count = self.list_model.rowCount()
        if not checked and list_count > 0:
            msg = QMessageBox()
            msg.setWindowTitle("Use inherited value instead?")
            msg.setText("Are you sure you want to remove all users/groups from this field?")
            msg.setInformativeText("Inherited values will apply instead.")
            msg.setStandardButtons(typing.cast(QMessageBox.StandardButtons, QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel))
            res = msg.exec()
            if res == QMessageBox.StandardButton.Cancel:
                with QSignalBlocker(self.ui.overrideCheckBox):
                    # Undo the check.
                    self.ui.overrideCheckBox.setChecked(True)
            else:
                # Remove all items in list
                self.list_model.removeRows(0, self.list_model.rowCount())
        # Finally, set to enable to disable the list
        self.ui.aclList.setEnabled(self.ui.overrideCheckBox.isChecked())

    def handle_insert_new(self):
        if getattr(self, 'list_model', None) is None:
            return
        ### Libby to add text value to the listmodel

        checked = self.ui.overrideCheckBox.isChecked()
        if checked and (not self.item_added):
            row = self.list_model.rowCount() # get the number of rows in model --> int
            self.list_model.insertRows(row,1) # Enable add one or more row.
            model_idx = self.list_model.index(row)
            self.ui.aclList.setCurrentIndex(model_idx)
            self.ui.aclList.edit(model_idx)
            # Set the flag to True after an item has been added
            self.item_added = True

        # If an item has been added, remove any empty or null strings from the model
        elif checked and (self.item_added):
            self.remove_empty_strings(self.list_model)
            row = self.list_model.rowCount() # get the number of rows in model --> int
            self.list_model.insertRows(row,1) # Enable add one or more row.
            model_idx = self.list_model.index(row)
            self.ui.aclList.setCurrentIndex(model_idx)
            self.ui.aclList.edit(model_idx)
            self.item_added = True

    def handle_remove(self):
        if getattr(self, 'list_model', None) is None:
            return
        idx_list = self.ui.aclList.selectedIndexes()
        rows_to_remove = [idx.row() for idx in idx_list]
        # Reverse sort the rows to remove, so we're not affected
        # by row index changes.
        rows_to_remove.sort(reverse=True)
        for row in rows_to_remove:
            self.list_model.removeRow(row)

    def set_list(self, ac_list: List[str]):
        self.list_model = QStringListModel(self) # create stringlistmodel object
        self.list_model.setStringList(ac_list)  # assign values to the model
        self.ui.aclList.setModel(self.list_model) # connect view and model
        # Reapply in case this list has value
        self.set_has_inheritance(self.has_inheritance)

    def remove_empty_strings(self,model):
        # Get the string list from the model
        string_list = model.stringList()

        # Iterate through the string list and remove any empty or null strings
        for i in reversed(range(len(string_list))):
            if string_list[i] == '' or string_list[i] is None:
                model.removeRows(i, 1)


from unittest import TestCase, mock
from buycoins_sdk import BuycoinsSDK, enums, types
from typing import List
from .fixtures import *

class TestMainBuycoinsSDK(TestCase):
    def setUp(self) -> None:
        BuycoinsSDK.__init__ = mock.Mock(side_effect=lambda public_key, secret_key: None)
        self.buycoins_sdk = BuycoinsSDK(public_key='test', secret_key='test')
        self.buycoins_sdk.client = mock.Mock()

    def test_get_balances(self):
        # prepare fixture
        client_result_fixture = {'data': [account_fixture]}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_balances.return_value = client_result_fixture
        result = self.buycoins_sdk.get_balances()

        # test for single Account object
        self.assertIsInstance(result, types.Account, 'RESULT SHOULD BE AN ACCOUNT OBJECT')

        # modify fixture
        self.buycoins_sdk.client.get_balances.return_value = {'data': [account_fixture, account_fixture]}
        result = self.buycoins_sdk.get_balances(cryptocurrency=enums.Cryptocurrency.BITCOIN)

        # test for multiple Account objects
        self.assertIsInstance(result, list, 'RESULT SHOULD BE A LIST')
        self.assertTrue(len(result) > 1, 'RESULT SHOULD CONTAIN MORE THAN ONE OBJECT')
        for i in result:
            self.assertIsInstance(i, types.Account, 'RESULT SHOULD CONTAIN ONLY ACCOUNT OBJECTS')

    def test_get_bank_accounts(self):
        # prepare fixture
        client_result_fixture = {'data': [bank_account_fixture]}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_bank_accounts.return_value = client_result_fixture
        result = self.buycoins_sdk.get_bank_accounts('000000000000')  # random bank account

        # test for single BankAccount object
        self.assertIsInstance(result, types.BankAccount, 'RESULT SHOULD BE A BankAccount OBJECT')

        # modify fixture
        self.buycoins_sdk.client.get_bank_accounts.return_value = {'data': [bank_account_fixture, bank_account_fixture]}
        result = self.buycoins_sdk.get_bank_accounts()

        # test for multiple BankAccount objects
        self.assertIsInstance(result, list, 'RESULT SHOULD BE A LIST')
        self.assertTrue(len(result) > 1, 'RESULT SHOULD CONTAIN MORE THAN ONE OBJECT')
        for i in result:
            self.assertIsInstance(i, types.BankAccount, 'RESULT SHOULD CONTAIN ONLY BankAccount OBJECTS')

    def test_get_estimated_network_fee(self):
        # prepare fixture
        client_result_fixture = {'data': estimated_fee_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_estimated_network_fee.return_value = client_result_fixture
        result = self.buycoins_sdk.get_estimated_network_fee(cryptocurrency=enums.Cryptocurrency.BITCOIN, amount='1000')

        # test for EstimatedFee object
        self.assertIsInstance(result, types.EstimatedFee, 'RESULT SHOULD BE An EstimatedFee OBJECT')
        self.assertEqual(client_result_fixture['data']['estimatedFee'], result.estimated_fee, 'should be equal')
        self.assertEqual(client_result_fixture['data']['total'], result.total, 'should be equal')

    def test_get_market_book(self):
        # prepare fixture
        client_result_fixture = {'data': post_orders_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_market_book.return_value = client_result_fixture
        result = self.buycoins_sdk.get_market_book()

        # test for PostOrder object
        self.assertIsInstance(result, types.PostOrders, 'RESULT SHOULD BE A PostOrders OBJECT')

    def test_get_orders(self):
        # prepare fixture
        client_result_fixture = {'data': post_orders_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_orders.return_value = client_result_fixture
        result = self.buycoins_sdk.get_orders(status=enums.GetOrdersStatus.OPEN)

        # test for PostOrder object
        self.assertIsInstance(result, types.PostOrders, 'RESULT SHOULD BE A PostOrders OBJECT')

    def test_get_payments(self):
        # prepare fixture
        client_result_fixture = {'data': payment_connection_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_payments.return_value = client_result_fixture
        result = self.buycoins_sdk.get_payments()

        # test for PostOrder object
        self.assertIsInstance(result, types.PaymentConnection, 'RESULT SHOULD BE A PaymentConnection OBJECT')

    def test_get_prices(self):
        # prepare fixture
        client_result_fixture = {'data': [buycoins_price_fixture]}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.get_prices.return_value = client_result_fixture
        result = self.buycoins_sdk.get_prices()

        # test for single BuycoinsPrice object
        self.assertIsInstance(result, types.BuycoinsPrice, 'RESULT SHOULD BE A BuycoinsPrice OBJECT')

        # modify fixture
        self.buycoins_sdk.client.get_prices.return_value = {'data': [buycoins_price_fixture, buycoins_price_fixture]}
        result = self.buycoins_sdk.get_prices(cryptocurrency=enums.Cryptocurrency.BITCOIN)

        # test for multiple BuycoinsPrice objects
        self.assertIsInstance(result, list, 'RESULT SHOULD BE A LIST')
        self.assertTrue(len(result) > 1, 'RESULT SHOULD CONTAIN MORE THAN ONE OBJECT')
        for i in result:
            self.assertIsInstance(i, types.BuycoinsPrice, 'RESULT SHOULD CONTAIN ONLY BuycoinsPrice OBJECTS')

    def test_node(self):
        # prepare fixture
        client_result_fixture = {'data': address_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.node.return_value = client_result_fixture
        result = self.buycoins_sdk.node(node_id='random_id', gql_type=enums.BuycoinsType.ADDRESS)

        # test for correct response object
        self.assertIsInstance(result, dict, 'RESULT SHOULD BE A DICT')
        self.assertDictEqual(result, client_result_fixture, 'SHOULD RETURN RESULT FROM BuycoinsGraphqlClient')

    def test_nodes(self):
        # prepare fixture
        client_result_fixture = {'data': [address_fixture, address_fixture]}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.nodes.return_value = client_result_fixture
        result = self.buycoins_sdk.nodes(ids=['random_id', 'another random id'], gql_types=[enums.BuycoinsType.ADDRESS])

        # test for list of nodes object
        self.assertIsInstance(result['data'], list, 'RESULT SHOULD BE A LIST')
        self.assertDictEqual(result, client_result_fixture, 'SHOULD RETURN RESULT FROM BuycoinsGraphqlClient')

    def test_buy(self):
        # prepare fixture
        client_result_fixture = {'data': order_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.buy.return_value = client_result_fixture
        result = self.buycoins_sdk.buy(
            price_id='random price id',
            coin_amount='1',
        )

        # test for Order object
        self.assertIsInstance(result, types.Order, 'RESULT SHOULD BE AN ORDER OBJECT')

    def test_cancel_withdrawal(self):
        # prepare fixture
        client_result_fixture = {'data': payment_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.cancel_withdrawal.return_value = client_result_fixture
        result = self.buycoins_sdk.cancel_withdrawal(
            payment_id='random price id',
        )

        # test for Payment object
        self.assertIsInstance(result, types.Payment, 'RESULT SHOULD BE A PAYMENT OBJECT')

    def test_create_address(self):
        # prepare fixture
        client_result_fixture = {'data': address_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.create_address.return_value = client_result_fixture
        result = self.buycoins_sdk.create_address()

        # test for Address object
        self.assertIsInstance(result, types.Address, 'RESULT SHOULD BE A ADDRESS OBJECT')
        self.assertEqual(result.id, client_result_fixture['data']['id'], 'should be Equal')
        self.assertEqual(result.address, client_result_fixture['data']['address'], 'should be Equal')
        self.assertEqual(result.cryptocurrency, types.Cryptocurrency(client_result_fixture['data']['cryptocurrency']),
                         'should be Equal')
        self.assertEqual(result.created_at, client_result_fixture['data']['createdAt'], 'should be Equal')

    def test_create_deposit_account(self):
        # prepare fixture
        client_result_fixture = {'data': deposit_account_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.create_deposit_account.return_value = client_result_fixture
        result = self.buycoins_sdk.create_deposit_account(
            account_name='random name'
        )

        # test for Payment object
        self.assertIsInstance(result, types.DepositAccount, 'RESULT SHOULD BE A DepositAccount OBJECT')

    def test_create_withdrawal(self):
        # prepare fixture
        client_result_fixture = {'data': payment_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.create_withdrawal.return_value = client_result_fixture
        result = self.buycoins_sdk.create_withdrawal(
            bank_account_id='random bank account id',
            amount='10000'
        )

        # test for Payment object
        self.assertIsInstance(result, types.Payment, 'RESULT SHOULD BE A PAYMENT OBJECT')

    def test_post_limit_order(self):
        # prepare fixture
        client_result_fixture = {'data': post_order_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.post_limit_order.return_value = client_result_fixture
        result = self.buycoins_sdk.post_limit_order(
            static_price='random price id',
            coin_amount='1',
            price_type=enums.PriceType.STATIC,
            order_side=enums.OrderSide.SELL,
            cryptocurrency=enums.Cryptocurrency.BITCOIN
        )

        # test for PostOrder object
        self.assertIsInstance(result, types.PostOrder, 'RESULT SHOULD BE A PostOrder OBJECT')

    def test_post_market_order(self):
        # prepare fixture
        client_result_fixture = {'data': post_order_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.post_market_order.return_value = client_result_fixture
        result = self.buycoins_sdk.post_market_order(
            coin_amount='1',
            order_side=enums.OrderSide.SELL,
            cryptocurrency=enums.Cryptocurrency.BITCOIN
        )

        # test for PostOrder object
        self.assertIsInstance(result, types.PostOrder, 'RESULT SHOULD BE A PostOrder OBJECT')

    def test_sell(self):
        # prepare fixture
        client_result_fixture = {'data': order_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.sell.return_value = client_result_fixture
        result = self.buycoins_sdk.sell(
            price_id='random price id',
            coin_amount='1',
        )

        # test for Order object
        self.assertIsInstance(result, types.Order, 'RESULT SHOULD BE AN ORDER OBJECT')

    def test_send(self):
        # prepare fixture
        client_result_fixture = {'data': onchain_transfer_request_fixture}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.send.return_value = client_result_fixture
        result = self.buycoins_sdk.send(
            amount='random price id',
            cryptocurrency=enums.Cryptocurrency.BITCOIN,
            address='random address'
        )

        # test for OnchainTransferRequest object
        self.assertIsInstance(result, types.OnchainTransferRequest, 'should be an OnchainTransferRequest object')

    def test_send_offchain(self):
        # prepare fixture
        client_result_fixture = {'data': {'initiated': True}}

        # mock the buycoins_sdk's client
        self.buycoins_sdk.client.send_offchain.return_value = client_result_fixture
        result = self.buycoins_sdk.send_offchain(
            amount='random price id',
            cryptocurrency=enums.Cryptocurrency.BITCOIN,
            recipient='random recipient'
        )

        # test for Payment object
        self.assertTrue(result, 'should be True as is in fixture')


import collections
import copy
import os

from tensorflow.python.eager import def_function
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import losses
from tensorflow.python.keras import optimizer_v1
from tensorflow.python.keras import optimizers
from tensorflow.python.keras.engine import base_layer_utils
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils import version_utils
from tensorflow.python.keras.utils.io_utils import ask_to_proceed_with_overwrite
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import nest

def extract_model_metrics(model):
  """Convert metrics from a Keras model `compile` API to dictionary.

  This is used for converting Keras models to Estimators and SavedModels.

  Args:
    model: A `tf.keras.Model` object.

  Returns:
    Dictionary mapping metric names to metric instances. May return `None` if
    the model does not contain any metrics.
  """
  if getattr(model, '_compile_metrics', None):
    # TODO(psv/kathywu): use this implementation in model to estimator flow.
    # We are not using model.metrics here because we want to exclude the metrics
    # added using `add_metric` API.
    return {m.name: m for m in model._compile_metric_functions}  # pylint: disable=protected-access
  return None

def model_input_signature(model, keep_original_batch_size=False):
  """Inspect model to get its input signature.

  The model's input signature is a list with a single (possibly-nested) object.
  This is due to the Keras-enforced restriction that tensor inputs must be
  passed in as the first argument.

  For example, a model with input {'feature1': <Tensor>, 'feature2': <Tensor>}
  will have input signature: [{'feature1': TensorSpec, 'feature2': TensorSpec}]

  Args:
    model: Keras Model object.
    keep_original_batch_size: A boolean indicating whether we want to keep using
      the original batch size or set it to None. Default is `False`, which means
      that the batch dim of the returned input signature will always be set to
      `None`.

  Returns:
    A list containing either a single TensorSpec or an object with nested
    TensorSpecs. This list does not contain the `training` argument.
  """
  input_specs = model._get_save_spec(dynamic_batch=not keep_original_batch_size)  # pylint: disable=protected-access
  if input_specs is None:
    return None
  input_specs = _enforce_names_consistency(input_specs)
  # Return a list with a single element as the model's input signature.
  if isinstance(input_specs,
                collections.abc.Sequence) and len(input_specs) == 1:
    # Note that the isinstance check filters out single-element dictionaries,
    # which should also be wrapped as a single-element list.
    return input_specs
  else:
    return [input_specs]

def raise_model_input_error(model):
  raise ValueError(
      'Model {} cannot be saved because the input shapes have not been '
      'set. Usually, input shapes are automatically determined from calling'
      ' `.fit()` or `.predict()`. To manually set the shapes, call '
      '`model.build(input_shape)`.'.format(model))

def trace_model_call(model, input_signature=None):
  """Trace the model call to create a tf.function for exporting a Keras model.

  Args:
    model: A Keras model.
    input_signature: optional, a list of tf.TensorSpec objects specifying the
      inputs to the model.

  Returns:
    A tf.function wrapping the model's call function with input signatures set.

  Raises:
    ValueError: if input signature cannot be inferred from the model.
  """
  if input_signature is None:
    if isinstance(model.call, def_function.Function):
      input_signature = model.call.input_signature

  if input_signature is None:
    input_signature = model_input_signature(model)

  if input_signature is None:
    raise_model_input_error(model)

  @def_function.function(input_signature=input_signature)
  def _wrapped_model(*args):
    """A concrete tf.function that wraps the model's call function."""
    # When given a single input, Keras models will call the model on the tensor
    # rather than a list consisting of the single tensor.
    inputs = args[0] if len(input_signature) == 1 else list(args)

    with base_layer_utils.call_context().enter(
        model, inputs=inputs, build_graph=False, training=False, saving=True):
      outputs = model(inputs, training=False)

    # Outputs always has to be a flat dict.
    output_names = model.output_names  # Functional Model.
    if output_names is None:  # Subclassed Model.
      from tensorflow.python.keras.engine import compile_utils  # pylint: disable=g-import-not-at-top
      output_names = compile_utils.create_pseudo_output_names(outputs)
    outputs = nest.flatten(outputs)
    return {name: output for name, output in zip(output_names, outputs)}

  return _wrapped_model

def model_metadata(model, include_optimizer=True, require_config=True):
  """Returns a dictionary containing the model metadata."""
  from tensorflow.python.keras import __version__ as keras_version  # pylint: disable=g-import-not-at-top
  from tensorflow.python.keras.optimizer_v2 import optimizer_v2  # pylint: disable=g-import-not-at-top

  model_config = {'class_name': model.__class__.__name__}
  try:
    model_config['config'] = model.get_config()
  except NotImplementedError as e:
    if require_config:
      raise e

  metadata = dict(
      keras_version=str(keras_version),
      backend=K.backend(),
      model_config=model_config)
  if model.optimizer and include_optimizer:
    if isinstance(model.optimizer, optimizer_v1.TFOptimizer):
      logging.warning(
          'TensorFlow optimizers do not '
          'make it possible to access '
          'optimizer attributes or optimizer state '
          'after instantiation. '
          'As a result, we cannot save the optimizer '
          'as part of the model save file. '
          'You will have to compile your model again after loading it. '
          'Prefer using a Keras optimizer instead '
          '(see keras.io/optimizers).')
    elif model._compile_was_called:  # pylint: disable=protected-access
      training_config = model._get_compile_args(user_metrics=False)  # pylint: disable=protected-access
      training_config.pop('optimizer', None)  # Handled separately.
      metadata['training_config'] = _serialize_nested_config(training_config)
      if isinstance(model.optimizer, optimizer_v2.RestoredOptimizer):
        raise NotImplementedError(
            'As of now, Optimizers loaded from SavedModel cannot be saved. '
            'If you\'re calling `model.save` or `tf.keras.models.save_model`,'
            ' please set the `include_optimizer` option to `False`. For '
            '`tf.saved_model.save`, delete the optimizer from the model.')
      else:
        optimizer_config = {
            'class_name':
                generic_utils.get_registered_name(model.optimizer.__class__),
            'config':
                model.optimizer.get_config()
        }
      metadata['training_config']['optimizer_config'] = optimizer_config
  return metadata

def should_overwrite(filepath, overwrite):
  """Returns whether the filepath should be overwritten."""
  # If file exists and should not be overwritten.
  if not overwrite and os.path.isfile(filepath):
    return ask_to_proceed_with_overwrite(filepath)
  return True

def compile_args_from_training_config(training_config, custom_objects=None):
  """Return model.compile arguments from training config."""
  if custom_objects is None:
    custom_objects = {}

  with generic_utils.CustomObjectScope(custom_objects):
    optimizer_config = training_config['optimizer_config']
    optimizer = optimizers.deserialize(optimizer_config)

    # Recover losses.
    loss = None
    loss_config = training_config.get('loss', None)
    if loss_config is not None:
      loss = _deserialize_nested_config(losses.deserialize, loss_config)

    # Recover metrics.
    metrics = None
    metrics_config = training_config.get('metrics', None)
    if metrics_config is not None:
      metrics = _deserialize_nested_config(_deserialize_metric, metrics_config)

    # Recover weighted metrics.
    weighted_metrics = None
    weighted_metrics_config = training_config.get('weighted_metrics', None)
    if weighted_metrics_config is not None:
      weighted_metrics = _deserialize_nested_config(_deserialize_metric,
                                                    weighted_metrics_config)

    sample_weight_mode = training_config['sample_weight_mode'] if hasattr(
        training_config, 'sample_weight_mode') else None
    loss_weights = training_config['loss_weights']

  return dict(
      optimizer=optimizer,
      loss=loss,
      metrics=metrics,
      weighted_metrics=weighted_metrics,
      loss_weights=loss_weights,
      sample_weight_mode=sample_weight_mode)

def _deserialize_nested_config(deserialize_fn, config):
  """Deserializes arbitrary Keras `config` using `deserialize_fn`."""

  def _is_single_object(obj):
    if isinstance(obj, dict) and 'class_name' in obj:
      return True  # Serialized Keras object.
    if isinstance(obj, str):
      return True  # Serialized function or string.
    return False

  if config is None:
    return None
  if _is_single_object(config):
    return deserialize_fn(config)
  elif isinstance(config, dict):
    return {
        k: _deserialize_nested_config(deserialize_fn, v)
        for k, v in config.items()
    }
  elif isinstance(config, (tuple, list)):
    return [_deserialize_nested_config(deserialize_fn, obj) for obj in config]

  raise ValueError('Saved configuration not understood.')

def _serialize_nested_config(config):
  """Serialized a nested structure of Keras objects."""

  def _serialize_fn(obj):
    if callable(obj):
      return generic_utils.serialize_keras_object(obj)
    return obj

  return nest.map_structure(_serialize_fn, config)

def _deserialize_metric(metric_config):
  """Deserialize metrics, leaving special strings untouched."""
  from tensorflow.python.keras import metrics as metrics_module  # pylint:disable=g-import-not-at-top
  if metric_config in ['accuracy', 'acc', 'crossentropy', 'ce']:
    # Do not deserialize accuracy and cross-entropy strings as we have special
    # case handling for these in compile, based on model output shape.
    return metric_config
  return metrics_module.deserialize(metric_config)

def _enforce_names_consistency(specs):
  """Enforces that either all specs have names or none do."""

  def _has_name(spec):
    return hasattr(spec, 'name') and spec.name is not None

  def _clear_name(spec):
    spec = copy.deepcopy(spec)
    if hasattr(spec, 'name'):
      spec._name = None  # pylint:disable=protected-access
    return spec

  flat_specs = nest.flatten(specs)
  name_inconsistency = (
      any(_has_name(s) for s in flat_specs) and
      not all(_has_name(s) for s in flat_specs))

  if name_inconsistency:
    specs = nest.map_structure(_clear_name, specs)
  return specs

def try_build_compiled_arguments(model):
  if (not version_utils.is_v1_layer_or_model(model) and
      model.outputs is not None):
    try:
      if not model.compiled_loss.built:
        model.compiled_loss.build(model.outputs)
      if not model.compiled_metrics.built:
        model.compiled_metrics.build(model.outputs, model.outputs)
    except:  # pylint: disable=bare-except
      logging.warning(
          'Compiled the loaded model, but the compiled metrics have yet to '
          'be built. `model.compile_metrics` will be empty until you train '
          'or evaluate the model.')

def is_hdf5_filepath(filepath):
  return (filepath.endswith('.h5') or filepath.endswith('.keras') or
          filepath.endswith('.hdf5'))


#
# @lc app=leetcode id=28 lang=python3
#
# [28] Implement strStr()
#

# @lc code=start
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle or not needle:
            return 0

        length = len(haystack)
        nlength = len(needle)
        for i in range(length - nlength + 1):
            if haystack[i] == needle[0]:
                ok = True
                for j in range(1, nlength):
                    if haystack[i + j] != needle[j]:
                        ok = False
                        break
                if ok:
                    return i

        if haystack == needle:
            return 0
        return -1

# if __name__ == "__main__":
#     s = Solution()
#     s.strStr("abc", "c")
# @lc code=end


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e.,
buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
"""

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # return self.ans(prices)
        # return self.ans_1(prices)
        return self.ans_2(prices)

    def ans(self, prices):
        """
        brute force
        :param prices:
        :return:
        """
        profit = 0
        for buy_day, buy_price in enumerate(prices[:len(prices)-1]):
            for sell_day, sell_price in enumerate(prices[buy_day:], start=buy_day):
                profit = max(profit, sell_price - buy_price)

        return profit

    def ans_1(self, prices):
        """
        3 pass
            1st to find the minimum price to buy so far
            2nd find the maximum price to sell in future
            3rd find the day to buy and sell
        :param prices:
        :return:
        """
        if not prices:
            return 0

        # minimum prices so far
        min_prices = [prices[0]]
        for buy_day, price in enumerate(prices[1:], start=1):
            tmp = min(min_prices[buy_day-1], price)
            min_prices.append(tmp)

        # maximum prices in the future
        max_prices = [prices[-1]]
        for sell_day in range(len(prices)-2, -1, -1):
            tmp = max(max_prices[-1], prices[sell_day])
            max_prices.append(tmp)
        max_prices.reverse()

        profit = 0
        for day in range(len(prices)-1):
            buy_price = min_prices[day]
            sell_price = max_prices[day+1]
            profit = max(profit, sell_price - buy_price)
        return profit

    def ans_2(self, prices):
        """
        one pass
        :param prices:
        :return:
        """
        if not prices:
            return 0

        profit = 0
        min_price = prices[0]

        for price in prices[1:]:
            # calculate profit based on min_price so far
            profit = max(profit, price - min_price)
            # update min price
            min_price = min(price, min_price)
        return profit

if __name__ == "__main__":
    test_prices = [7, 1, 5, 3, 6, 4]
    # test_prices = [7,6,4,3,1]
    print(Solution().maxProfit(test_prices))
    # print(Solution().ans_2(test_prices))


class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        l = r = ans = 0
        n = len(s)
        occ = set()
        while r < n:
            while s[r] in occ:
                occ.remove(s[l])
                l += 1
            occ.add(s[r])
            r += 1
            ans = max(ans, r - l)
        return ans


import ipdb
from blist import blist
# ipdb.set_trace()

buf, pos = blist([0]), 0
for i in range(1,int(5e7)+1):
    pos = ((pos+343)%i)+1
    buf.insert(pos,i)
    if i%50000==0:
        print(i)
print(buf[buf.index(0)+1])


from django.shortcuts import render, redirect

from .forms import CreateForm
from .models import Products

def create_product(request):
    if request.method == 'POST':
        form = CreateForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/list')
    else:
        form = CreateForm()

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

def product_list(request):
    products = Products.objects.all()

    if request.method == 'POST':
        product_id = request.POST.get('product_id')
        if product_id:
            product_to_delete = Products.objects.get(pk=product_id)
            product_to_delete.delete()
            return redirect('product_list')

    return render(request, 'list.html', {'products': products})


import sys
sys.setrecursionlimit(10**6) # 최대 재귀 깊이 변경

def find(node):
    check[node] = True
    for child in tree[node]:
        if not check[child]:
            parents[child] = node
            find(child)

n = int(sys.stdin.readline().split()[0])
tree = [[] for _ in range(n + 1)]
parents = [0] * (n + 1)
check = [False] * (n + 1)

for _ in range(n - 1):
    node1, node2 = map(int, sys.stdin.readline().split())
    tree[node1].append(node2)
    tree[node2].append(node1)

find(1)

sys.stdout.write(''.join([str(parents[i]) + '\n' for i in range(2, n + 1)]))


def get_primes(seq):
    for num in seq:
        if num <= 1:
            continue

        for div in range(2, num):
            if num % div == 0:
                break
        else:
            yield num

print(list(get_primes([2, 4, 3, 5, 6, 9, 1, 0])))


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 10:59:29 2020

@author: lenovouser
"""

#get data of several cities and get their longitude as well as latitude)
from clyent import color
cities_data = """
Bei Jing, 116.23,39.54
Shang Hai, 121.52, 30.91
Hong Kong,114.19,22.38
Delhi,77.21,28.67
Johannesburg,28.04,-26.19
Doha,51.53,25.29
Sao Paulo,-46.63,-23.53
Toronto,-79.38,43.65
New York,-73.94,40.67
San Francisco,-122.45,37.77
Dubai,55.33,25.27
Sydney,151.21,-33.87
"""
# part2_create a list consisting of cities' indexes about their longtitudes and latitudes
import csv
#create a dict and a list
cities = dict()
coords = list()
# print(cities,coords)

# read data
for line in list(csv.reader(cities_data.split("\n")))[1:-1]:
    name, long_, lat = line
    cities[name] = len(coords)
    coords.append((float(long_),float(lat)))

# data transformation
import numpy as np
# from [1 line n row] to [n line, 1 list]
coords = np.array(coords)
# transform the angle to the arc
lat, long = coords.T * np.pi / 180
# transform 2D data to 3D data
# lat = ori_long
# long = ori_lat
x = np.cos(long) * np.cos(lat)
y = np.cos(long) * np.sin(lat)
z = np.sin(long)

#create a window
from mayavi import mlab
mlab.figure(bgcolor=(0.48,0.48,0.48), size=(400,400))

# to define a sphere
# set the opacity of the surface of earth to 0.7
sphere = mlab.points3d(0, 0, 0, scale_factor=2,
                       color = (0.67, 0.77, 0.93),
                       resolution = 100,
                       opacity = 0.7,
                       name = "Earth")

# to adjust the parameter of mirror reflection
sphere.actor.property.specular = 0.45
sphere.actor.property.specular_power = 5
# delete the opposite side to better show the effect of opacity
sphere.actor.property.backface_culling = True
# use points to describe sites of cities
points = mlab.points3d(x, y, z,
                       scale_mode = "none",
                       scale_factor = 0.03,
                       color = (0, 0, 1))

#create names of cities
# for cities.items output the names of cities and the series of cities
for city, index in cities.items():
    #x,y,z mean x,y,z coordinates; color means text's color; width means text's width; name means text's object
    label = mlab.text(x[index], y[index], city,
                      z=z[index], color=(0,0,1),
                      width=0.016 * len(city), name=city)

#create continents
from mayavi.sources.builtin_surface import BuiltinSurface
continents_src = BuiltinSurface(source="earth", name="Continents")
#set the LDD to 2
continents_src.data_source.on_ratio = 2
continents = mlab.pipeline.surface(continents_src, color=(0,0,0))

#create the equitor
# distribute every 360 to 100
theta = np.linspace(0, 2 * np.pi, 50)
x = np.cos(theta)
y = np.sin(theta)
z = np.zeros_like(theta)
mlab.plot3d(x,y,z,color=(1,1,1),opacity=0.2,tube_radius=None)

#show the window for interation
mlab.view(100,60,4,[-0.05,0,0])
mlab.show()


from typing import List, Tuple

# Takes an integer `num`, a number of bits `n_b`, and a length l, and returns a tuple (d0, ..., d_{l-1})
# such that num = d_0 + d_1 * 2**(n_b) + d_2 * 2**(2n_b) + ... + d_{l-1}*2**((l-1)*n_b)
# Each d_i is a positive integer of less than n_b bits
def split(num: int, num_bits_shift: int = 128, length: int=3) -> List[int]:
    a = []
    for _ in range(length):
        a.append( num & ((1 << num_bits_shift) - 1) )
        num = num >> num_bits_shift
    return tuple(a)

# Takes an integer `num`, a number of bits `n_b`, and a length l, and returns a tuple (d0, ..., d_{l-1})
# of overlapping sections of num of the type used by Uint384_expand
def split2(num: int, num_bits_shift: int = 64, length: int=7) -> List[int]:
    a = []
    num = num << num_bits_shift
    for _ in range(length):
        a.append( num & ((1 << 2*num_bits_shift) - 1) )
        num = num >> num_bits_shift
    return tuple(a)

# The inverse operation of `split`: takes a tuple z of integers (d0, ..., d_{l-1}) and returns
# d_0 + d_1 * 2**(n_b) + d_2 * 2**(2n_b) + ... + d_{l-1}*2**((l-1)*n_b)
# Note that d_i can be larger than 2**128 here (but in this repo d_i is always less than 2**128)
def pack(z: Tuple[int], num_bits_shift: int = 128) -> int:
    limbs = (limb for limb in z)
    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))

# Prime p with which to test the field arithmetic functions
elliptic_curve_field_modulus = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787