# tools
import tarfile
import os
import re
import json
from read import read

class Unlock:
    def __init__(self, path="../media/media", file="submissions.tgz"):
        self.path = path
        self.file = file
        self.extract()

    def extract(self):
        tar = tarfile.open(
            self.file,
        )
        tar.extractall(self.path)
        tar.close()

    def read_paths(self):
        """find files path with .test extension"""
        files = []
        # r=root, d=directories, f = files
        for r, d, f in os.walk(self.path):
            for file in f:
                if ".test" in file:
                    filePath = os.path.join(r, file)
                    files.append(filePath)
        return files

    def read_inputs(self, dir_list):
        """read and save info from .test files into list"""
        inputs = []
        for path in dir_list:
            inputs.append(read(path))
        return inputs

    def extract_info(self, files):
        """extract info like: _id, courseid, graderesult,
        submitted_on, taskid, username and source code from
        .test files located in local folder"""
        info = []
        errors = []
        # cont = 1
        for file in files:
            student = []

            try:
                # find _id
                data = re.search("_id:.*", file)
                data = data.group().split(": ")
                student.append(data)

                # find course id
                data = re.search("courseid: .*", file)
                data = data.group().split(": ")
                student.append(data)

                # find grade
                data = re.search("grade: .*", file)
                data = data.group().split(": ")
                student.append(data)

                # find result
                data = re.search("^result: .*", file, re.MULTILINE)
                data = data.group().split(": ")
                student.append(data)

                # find date
                data = re.search("submitted_on: .*:[0-9]{2}", file)
                data = data.group().split(": ")
                student.append(data)

                # find task id
                data = re.search("^taskid: .*", file, re.MULTILINE)
                data = data.group().split(": ")
                student.append(data)

                # find username
                data = re.search("username:.*\n-.*", file)
                data = data.group().split(":\n- ")
                student.append(data)

                # find source code
                data = extract_code(file)
                # cont += 1
                student.append(data)

                info.append(student)
            except Exception as e:
                print(student)
                errors.append(student)
                continue

        print("Errors: " + str(len(errors)))
        return info

    def write_json(self, data, name, path="/media/files/"):
        try:
            # self.cont = 1
            file = []
            for i in range(len(data)):
                try:
                    file.append(dict(data[i]))
                except:
                    print("WRITE_JSON EXCEPT: " + str(data[i]))
            file_path = f"{path}/{name}.json"
            with open(file_path, "w", encoding="utf-8") as F:
                # Using json dumps method to write the list in the disk
                F.write(json.dumps(file, ensure_ascii=False, indent=4))
            return file  # , file_path
        except Exception as e:
            print(f"Something went wrong: {e}")

# ---------------internal function--------------#

def extract_code(file):
    """extract source code from .test files"""
    try:
        data = re.search("input:(.*\n)*problems: \{\}", file)
        data = data.group().split(":\n    '")
        test = re.search(": \|.?.?.?\n(.*\n)*.*/input:", data[1])
        test = test.group()
        data[1] = test[4:-18]
    except Exception as e:
        data[0] = "input"
        data[1] = f"Error: {type(e).__name__}"
        return data
    return data


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from myConvexHull.myfunctions import myConvexHull

# visualisasi data iris
data = datasets.load_iris()
# buat DataFrame
df = pd.DataFrame(data.data, columns=data.feature_names)
df['Target'] = pd.DataFrame(data.target)

# visualisasi Petal Width vs Petal Length
plt.figure(figsize=(10, 6))
colors = ['b', 'r', 'g']
plt.title('Petal Width vs Petal Length')
plt.xlabel(data.feature_names[2])
plt.ylabel(data.feature_names[3])

for i in range(len(data.target_names)):
    bucket = df[df['Target'] == i]
    bucket = bucket.iloc[:, [2, 3]].values
    hull = myConvexHull(bucket)
    plt.scatter(bucket[:, 0], bucket[:, 1], label=data.target_names[i])
    for simplex in hull:
        plt.plot(bucket[simplex, 0], bucket[simplex, 1], colors[i])
        plt.legend()

plt.show()

# visualisasi Sepal Width vs Sepal Length
plt.figure(figsize=(10, 6))
colors = ['b', 'r', 'g']
plt.title('Sepal Width vs Sepal Length')
plt.xlabel(data.feature_names[0])
plt.ylabel(data.feature_names[1])

for i in range(len(data.target_names)):
    bucket = df[df['Target'] == i]
    bucket = bucket.iloc[:, [0, 1]].values
    hull = myConvexHull(bucket)
    plt.scatter(bucket[:, 0], bucket[:, 1], label=data.target_names[i])
    for simplex in hull:
        plt.plot(bucket[simplex, 0], bucket[simplex, 1], colors[i])
        plt.legend()

plt.show()


# -*- coding: gb18030 -*-
#
"""
读取文件的版本
"""
import os
import ResMgr
import binascii

def getVersion():
	"""
	获取版本
	"""
	file = ResMgr.openSection("entities/version")
	if file == None:
		return ""
	s = file.asBinary
	# 去掉一些杂七杂八的允许的冗余字符，
	# 以避免一些无意识增加的空行影响版本号的正确性。
	s = s.replace( "\n", "" )
	s = s.replace( "\r", "" )
	s = s.replace( " ", "" )
	s = s.replace( "\t", "" )
	return s

def getGameName() :
	"""
	获取游戏名字( 在 bw.xml 中定义的游戏英文名称 )
	2010.06.08: writen by huangyongwei
	"""
	sect = ResMgr.openSection( "server/bw.xml" )
	return sect.readString( "gameName" )

def getServerName():
	"""
	获取服务器名字
	"""
	nameConfig = ResMgr.openSection("../options.xml/scriptsPreferences/login/server/servername")
	if nameConfig is None:
		return ""
	serverName = " - " + binascii.a2b_hex( nameConfig.asString ) # 需要将16进制编码转成字符
	return serverName


# import sys
# input = sys.stdin.readline

def solve():
    l = [int(i) for i in input().split()]
    l.sort()
    order = input()

    for i in order:
        print(l[ord(i)-ord('A')], end = " ")

q = 1
for _ in range(q):
    solve()


#!/usr/bin/python3
import polib
import re
import sys

module     = sys.argv[1]
lang       = sys.argv[2]
msgextract = sys.argv[3]
pofile     = polib.pofile(sys.argv[4])
cpp        = open(sys.argv[5],'w')

print('// Generated by po-cpp-gen.py', file = cpp)
print('#include "arcollect-i18n-'+module+'.hpp"', file = cpp)
print('void Arcollect::i18n::'+module+'::po_apply_'+lang+'(void) noexcept {', file = cpp)

# Filter-out untranslated entries in non C locale
if msgextract != 'msgid':
	pofile = filter(polib.POEntry.translated,pofile)

for msg in pofile:
	print('\t'+msg.msgctxt,'=','"'+msg.__getattribute__(msgextract).replace('\\','\\\\').replace('\n','\\n').replace('"','\\"')+'";', file = cpp)
print('}', file = cpp)


"""
@leofansq
https://github.com/leofansq
"""
import cv2
import numpy as np

from basic_function import dilate

def thinning(img, K):
    """
    细化运算实体
    Parameters:
        img: 待细化图像
        K: 结构子序列
    Return:
        细化后结果图像
    """
    # 归一
    img_result = img/255
    # 初始化用于保存上一次结果的矩阵
    img_old = 1 - img_result

    # 循环细化.直至图像保持不变
    while np.sum(img_result-img_old):
        img_old = img_result
        for i in K:
            # 基于卷积结果的击中击不中
            img_temp = np.where(cv2.filter2D(img_result.copy(),-1,i,borderType=0)==15, 1, 0)
            img_result = img_result - img_temp

    img_result *= 255
    return img_result.astype(np.uint8)

def sk_thin(img):
    """
    细化提取骨架
    Parameter:
        img: 待提取图像
    Return:
        提取骨架结果图像
    """
    # 生成8个结构子序列
    k_1 = np.array([[16,16,16],[0,1,0],[2,4,8]], dtype=np.uint8)
    k_2 = np.array([[0,16,16],[1,2,16],[4,8,0]], dtype=np.uint8)
    k_3 = np.array([[1,0,16],[2,4,16],[8,0,16]], dtype=np.uint8)
    k_4 = np.array([[1,2,0],[4,8,16],[0,16,16]], dtype=np.uint8)
    k_5 = np.array([[1,2,4],[0,8,0],[16,16,16]], dtype=np.uint8)
    k_6 = np.array([[0,1,2],[16,4,8],[16,16,0]], dtype=np.uint8)
    k_7 = np.array([[16,0,1],[16,2,4],[16,0,8]], dtype=np.uint8)
    k_8 = np.array([[16,16,0],[16,1,2],[0,4,8]], dtype=np.uint8)

    K = [k_1, k_2, k_3, k_4, k_5, k_6, k_7, k_8]

    # 细化操作
    img_result = thinning(img, K)

    return img_result

if __name__ == "__main__":
    # 测试用图
    # img = 255 - np.zeros((5, 11))
    # img[1:5,9] = img[1:5,10] = img[4,3:5] = 0

    img = cv2.imread("bin.png", 0)
    img_result = sk_thin(img)
    cv2.imwrite("morph_thin.png", img_result)


import sys

n,m=map(int,sys.stdin.readline().split())
d={}

for i in range(n):
    s=input()
    d[s]=s

def find(x):
    if d[x]!=x:
        d[x]=find(d[x])

    return d[x]

def union(x,y):
    a=find(x)
    b=find(y)

    if a!=b:
        d[y]=x
    else:
        d[x]=x
        d[y]=x

for i in range(m):
    s=input().split(',')
    if s[2]=='1':
        union(s[0],s[1])
    else:
        union(s[1],s[0])

ans=set()
for i in d.values():
    ans.add(find(i))

print(len(ans))
ans=list(ans)
ans.sort()

for i in ans:
    print(i)


import math

def max_prime_factor(n):
    cur = 2
    while n != 1:
        while n % cur == 0:
            n = n // cur
        if n == 1:
            break
        cur += 1
        if cur > math.sqrt(n):
            return n
    return cur

# 78962

X2 = int(input().strip())
p1 = max_prime_factor(X2)
#print(X2, p1)
res = float('inf')
for X1 in range(X2 - p1 + 1, X2 + 1):
    if p1 >= X1:
        continue
    p2 = max_prime_factor(X1)
    #print(X1, p2)
    if X1 - p2 + 1 > p2:
        res = min(res, X1 - p2 + 1)
print(res)


import sys
read=sys.stdin.readline

n=int(read())

card=list(map(int,read().split()))
card.insert(0,0)
dp=[sys.maxsize-1]*(n+1)

dp[1]=card[1]

for i in range(1,n+1):
	for j in range(1,i):
		dp[i]=min(card[i],dp[i-j]+dp[j],dp[i])

print(dp[n])


from enum import Enum
import typer
from typing_extensions import Annotated
import platform
if platform.system() == "Windows":
    import keyboard
else:
    from winhotkey.dummy_keyboard import keyboard # For testing on non-windows systems
from uvicorn.config import Config
from time import sleep
import logging

from winhotkey.__about__ import __version__
from winhotkey.ThreadedUvicorn import ThreadedUvicorn
from winhotkey.keyboard_wrappers import sender

cli_app = typer.Typer()

@cli_app.command()
def cli(hotkey_prefix: Annotated[str, typer.Option(help="'keyboard' compatible hot key prefix'")] = "shift+ctrl+alt",
        reverse_hotkey_order: Annotated[bool, typer.Option(help="Start with 1 and go to 0 or 0 and go to 1.  I actually prefer 0 to 1")] = True,
        hide_input: Annotated[bool, typer.Option(help="In case your 'phrases' are sensitive, you will not see what you enter")] = True):
    """
    Allows you store up to 10 'phrases' for instant recall by typing 'Shift+Ctrl+Alt[1-0]'\n
    Just hit enter to stop storing 'phrases'\n
    """
    possible_entries = [f"{i}" for i in range(1,10)]
    possible_entries.append("0")
    if reverse_hotkey_order:
        possible_entries = possible_entries[::-1]
    keys_to_add = {}
    for entry in possible_entries:
        key = f'{hotkey_prefix}+{entry}'
        phrase = typer.prompt(f"Please enter phrase for '{key}'", hide_input=hide_input, default="Press Enter when done")
        if phrase == "Press Enter when done":
            break
        keys_to_add[key] = phrase

    for (n, (key_to_add, phrase)) in enumerate(keys_to_add.items()):
        # Convert the phrase to string of characters separated by comma
        # keyboard.add_hotkey(key_to_add, keyboard.write, args=(phrase,))
        keyboard.add_hotkey(key_to_add, sender, args=(phrase,1.0,))

    print("Press SHIFT+CTRL+ALT+ESC to exit.  Leave this window open!")

    # Blocks until you press esc.
    keyboard.wait('shift+ctrl+alt+esc')

class LogLevels(str, Enum):
    CRITICAL = "critical"
    ERROR = "error"
    WARNING = "warning"
    INFO = "info"
    DEBUG = "debug"

@cli_app.command()
def web(hotkey_prefix: Annotated[str, typer.Option(help="'keyboard' compatible hot key prefix'")] = "shift+ctrl+alt",
        type_delay: Annotated[float, typer.Option(help="Set the delay time in seconds when using the delayed typing feature")] = 2.0,
        logging_level: Annotated[LogLevels, typer.Option(help="Set the log level for the web server")] = LogLevels.WARNING.value):
    """
    Starts a web interface to configure winhotkey
    """
    from winhotkey.web import initializeSettings
    initializeSettings(hotkey_prefix, type_delay)

    config = Config("winhotkey.web:api_app", host="127.0.0.1", port=17455, reload=True, log_level=logging_level.value)
    server = ThreadedUvicorn(config)
    server.start()
    if logging_level not in [LogLevels.INFO, LogLevels.DEBUG]:
        print("Access the GUI at: http://127.0.0.1:17455/")
    print("Press SHIFT+ALT+CTRL+C to exit.  Leave this window open!")
    keyboard.wait('shift+alt+ctrl+c')
    server.stop()

def winhotkey():
    if not platform.system() == "Windows":
        print("Winhotkey only fully works on Windows.  It will be started in a test mode.  No hotkeys will actually work.")
    cli_app()


#!/usr/bin/env python
import smtplib
import os
import re
# For guessing MIME type
import mimetypes

# Import the email modules we'll need
import email
import email.mime.application
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    if 'Send email' in data.data:
        if len(data.data.split()) != 4 or not re.match(r"[^@]+@[^@]+\.[^@]+",  data.data.split()[2]):
            print ("bad addresss entered")
            return
        address = data.data.split()[2]
        send_from = 'photobot.picture@gmail.com'
        send_to = address
        subject = 'picture'
        text = 'Hello, it was great meeting you today at level 5 labs. Please find the photo we have taken together attached. Until next time!'
        filter_num = data.data.split()[3]

        msg = email.mime.Multipart.MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = send_from
        msg['To'] = send_to

        body = email.mime.Text.MIMEText(text)
        msg.attach(body)
        if (filter_num == '0'):
            filename='/home/human4/photobot/camera_image.jpg'
        else:
            filename='/home/human4/photobot/photo_' + filter_num + '.jpg'
        img_data = open(filename, 'rb').read()
        image = MIMEImage(img_data, name=os.path.basename(filename))
        msg.attach(image)

        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login('photobot.picture@gmail.com', 'human444')
        server.sendmail(send_from, send_to, msg.as_string())
        picture = None #'pic.jpg'
#send_mail(send_from, send_to, subject, text, picture, server)
        server.close()

def listener():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # node are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('emailer', anonymous=True)
    rospy.Subscriber("event_output", String, callback)

# spin() simply keeps python from exiting until this node is stopped
    rospy.spin()
if __name__ == '__main__':
    listener()


from datetime import date
data = date.today().year

total_maiores = 0
total_menores = 0

for pessoa in range(1, 8):
    nascimento = int(input(f'Insira o ano de nascimento da {pessoa}ª Pessoa: '))
    idade = (data - nascimento)
    if idade >= 18:
        total_maiores += 1
        # print('GRUPO +18 ANOS')
    elif nascimento > data:
        print('Insira uma data válida')
        continue
    else:
        total_menores += 1
        # print('GRUPO MENOR')
print(f'TOTAL DE MAIORES (+18) FOI: {total_maiores}')
print(f'TOTAL DE MENORES (-18) FOI: {total_menores}')


from youcanpay import exceptions

class Keys:

    """"""

    BASE_ENDPOINT = 'keys'

    def __init__(self, api_service) -> None:
        self.api_service = api_service
        self.BASE_ENDPOINT = self.api_service.base_url + self.BASE_ENDPOINT

    def check(self):
        """
        Check if the API keys are valid or not

        Arguments:
                 None

        Returns:
                bool: True if the keys are valid, False otherwise

        Throws:
                InternalServerError: If the server returns a 500 error
        """

        endpoint = self.BASE_ENDPOINT + '/check'
        payload = {
            'pri_key': self.api_service.get_private_key(),
            'pub_key': self.api_service.get_public_key()
        }
        res = self.api_service.post(endpoint, data=payload)

        if res.status_code != 500:
            raise exceptions.InternalServerError
        if res.status_code != 200:
            return False
        return True


from queue import Queue
from ds.graph.graph_core import GraphCore

def is_bipartite(graph):
    graph_vertices = graph.vertices
    visited = set()
    vertex_color = {}
    for src in graph_vertices:
        if src in visited:
            continue
        bfs_queue = Queue()
        bfs_queue.put(src)
        visited.add(src)
        vertex_color[src] = True
        while not bfs_queue.empty():
            current = bfs_queue.get()
            current_edges = graph.get_edges(current)
            for neighbour in current_edges:
                if neighbour not in visited:
                    bfs_queue.put(neighbour)
                    vertex_color[neighbour] = not vertex_color[src]
                    visited.add(neighbour)
                else:
                    if vertex_color[src] == vertex_color[neighbour]:
                        return False
    return True

def main():
    graph = GraphCore(True)
    graph.add_edge(1, 2)
    graph.add_edge(1, 3)
    graph.add_edge(2, 4)
    graph.add_edge(3, 4)
    graph.add_edge(4, 5)
    print(graph)
    is_it_really = is_bipartite(graph)
    print(is_it_really)

if __name__ == "__main__":
    main()


# encoding: utf-8

from __future__ import print_function, unicode_literals

import sys

import pytest
from pytablewriter.style import Align, FontSize, FontStyle, FontWeight, Style, ThousandSeparator

class Test_Style_constructor(object):
    @pytest.mark.parametrize(
        ["value", "expected"],
        [
            [
                {
                    "align": Align.RIGHT,
                    "font_size": FontSize.TINY,
                    "font_weight": FontWeight.BOLD,
                    "thousand_separator": ThousandSeparator.SPACE,
                },
                {
                    "align": Align.RIGHT,
                    "font_size": FontSize.TINY,
                    "font_weight": FontWeight.BOLD,
                    "thousand_separator": ThousandSeparator.SPACE,
                },
            ],
            [
                {
                    "align": "left",
                    "font_size": "small",
                    "font_weight": "bold",
                    "thousand_separator": ",",
                },
                {
                    "align": Align.LEFT,
                    "font_size": FontSize.SMALL,
                    "font_weight": FontWeight.BOLD,
                    "thousand_separator": ThousandSeparator.COMMA,
                },
            ],
            [
                {"font_size": "TINY"},
                {
                    "align": Align.AUTO,
                    "font_size": FontSize.TINY,
                    "font_weight": FontWeight.NORMAL,
                    "thousand_separator": ThousandSeparator.NONE,
                },
            ],
        ],
    )
    def test_normal(self, value, expected):
        style = Style(**value)

        print("expected: {}\nactual: {}".format(expected, style), file=sys.stderr)

        assert style.align is expected.get("align")
        assert style.font_size is expected.get("font_size")
        assert style.font_weight is expected.get("font_weight")
        assert style.thousand_separator is expected.get("thousand_separator")

class Test_Style_eq(object):
    @pytest.mark.parametrize(
        ["lhs", "rhs", "expected"],
        [
            [Style(), Style(), True],
            [Style(align=Align.RIGHT), Style(align=Align.RIGHT), True],
            [Style(align=Align.RIGHT), Style(align=Align.LEFT), False],
            [Style(align=Align.RIGHT), Style(align="right"), True],
            [Style(align=Align.RIGHT), Style(align=Align.RIGHT, font_size=FontSize.TINY), False],
            [Style(font_size=FontSize.TINY), Style(font_size=FontSize.TINY), True],
            [Style(font_size=FontSize.TINY), Style(font_size="tiny"), True],
            [Style(font_size=FontSize.TINY), Style(font_size=FontSize.LARGE), False],
            [Style(font_weight="bold"), Style(font_weight=FontWeight.BOLD), True],
            [Style(font_weight="bold"), Style(font_weight="normal"), False],
            [Style(font_style="italic"), Style(font_style=FontStyle.ITALIC), True],
            [Style(font_style="italic"), Style(font_style="normal"), False],
            [Style(thousand_separator=","), Style(thousand_separator=","), True],
            [Style(thousand_separator=","), Style(thousand_separator="comma"), True],
            [Style(thousand_separator=""), Style(thousand_separator=","), False],
            [
                Style(thousand_separator=ThousandSeparator.COMMA),
                Style(thousand_separator=ThousandSeparator.COMMA),
                True,
            ],
            [
                Style(thousand_separator="space"),
                Style(thousand_separator=ThousandSeparator.SPACE),
                True,
            ],
            [
                Style(thousand_separator=ThousandSeparator.COMMA),
                Style(thousand_separator=ThousandSeparator.COMMA, font_size=FontSize.TINY),
                False,
            ],
            [
                Style(
                    align=Align.LEFT,
                    font_size=FontSize.TINY,
                    font_style=FontStyle.ITALIC,
                    font_weight=FontWeight.BOLD,
                    thousand_separator=ThousandSeparator.COMMA,
                ),
                Style(
                    align="left",
                    font_size="tiny",
                    font_style="italic",
                    font_weight="bold",
                    thousand_separator=",",
                ),
                True,
            ],
            [Style(), None, False],
        ],
    )
    def test_normal(self, lhs, rhs, expected):
        assert (lhs == rhs) == expected
        assert (lhs != rhs) != expected

    @pytest.mark.parametrize(
        ["align", "font_size", "thousand_separator", "expected"],
        [
            ["invali", None, None, TypeError],
            [FontSize.TINY, None, None, TypeError],
            [None, "invali", None, TypeError],
            [None, Align.LEFT, None, TypeError],
            [None, None, "invalid", TypeError],
        ],
    )
    def test_exception(self, align, font_size, thousand_separator, expected):
        with pytest.raises(expected):
            Style(align=align, font_size=font_size, thousand_separator=thousand_separator)

class Test_Style_repr(object):
    @pytest.mark.parametrize(
        ["value", "expected"],
        [
            [
                Style(
                    align="left",
                    font_size="tiny",
                    font_style="italic",
                    font_weight="bold",
                    thousand_separator=",",
                ),
                "(align=left, font_size=tiny, font_style=italic, font_weight=bold, thousand_separator=comma)",
            ],
            [Style(), "(align=auto, font_style=normal, font_weight=normal)"],
        ],
    )
    def test_normal(self, value, expected):
        assert str(value) == expected


from datetime import timedelta
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime
import pandas as pd

def chumma_sample():

    print("hello bro")

with DAG(
        dag_id="hello_world",
        schedule_interval="@daily",
        default_args={
            "owner": "airflow",
            "retries": 1,
            "retry_delay": timedelta(minutes=5),
            "start_date": datetime(2021, 1, 1),
        },
        catchup=False) as f:

    first_function_execute = PythonOperator(
        task_id="chumma_task",
        python_callable=chumma_sample
    )


from tkinter.tix import DECREASING
from django.http import HttpResponse
from django.shortcuts import render
from zeep import Client

client = Client(wsdl='https://www.openligadb.de/Webservices/Sportsdata.asmx?wsdl')
lastmatch = client.service.GetLastMatch('bl1')
season = lastmatch['leagueSaison']

def win_loss(allTeams,all_matches):
    for team in allTeams:
        all_matches_home = []
        all_matches_away = []
        win_counter = 0
        lose_counter = 0
        for i in all_matches:
            if i['idTeam1'] == team['teamID']:
                all_matches_home.append(i)
            elif i['idTeam2'] == team['teamID']:
                all_matches_away.append(i)

        for z in all_matches_home:
            if z['pointsTeam1'] > z['pointsTeam2']:
                win_counter += 1
            elif z['pointsTeam1'] < z['pointsTeam2']:
                lose_counter += 1

        for y in all_matches_away:
            if y['pointsTeam1'] > y['pointsTeam2']:
                lose_counter += 1
            elif y['pointsTeam1'] < y['pointsTeam2']:
                win_counter += 1

        team['win_counter'] = win_counter
        team['lose_counter'] = lose_counter
        team['win_percentage'] = int((win_counter/(win_counter+lose_counter))*100)

    return allTeams

def win_loss_detail(all_matches,id):
        team = []
        all_matches_home = []
        all_matches_away = []
        win_counter = 0
        lose_counter = 0
        for i in all_matches:
            if i['idTeam1'] == id:
                all_matches_home.append(i)
            elif i['idTeam2'] == id:
                all_matches_away.append(i)

        for z in all_matches_home:
            if z['pointsTeam1'] > z['pointsTeam2']:
                win_counter += 1
            elif z['pointsTeam1'] < z['pointsTeam2']:
                lose_counter += 1

        for y in all_matches_away:
            if y['pointsTeam1'] > y['pointsTeam2']:
                lose_counter += 1
            elif y['pointsTeam1'] < y['pointsTeam2']:
                win_counter += 1

        win_percentage = int((win_counter/(win_counter+lose_counter))*100)

        return win_counter,lose_counter,win_percentage

# Create your views here.

def teams(request):
    allTeams = client.service.GetTeamsByLeagueSaison('bl1', season)
    all_matches = client.service.GetMatchdataByLeagueSaison('bl1', season)

    allTeams = win_loss(allTeams,all_matches)

    return render(request, 'teams/teams.html',{
        'allTeams':allTeams,
    })

def team_detail(request, id):
    team = []
    allID = []
    allTeams = client.service.GetTeamsByLeagueSaison('bl1', season)
    for i in allTeams:
        allID.append(i['teamID'])
    if id in allID:
        all_matches = client.service.GetMatchdataByLeagueSaison('bl1', season)
        for y in allTeams:
            if y['teamID'] == id:
                team.append(y)
        win_counter,lose_counter,win_percentage = win_loss_detail(all_matches,id)
        print(win_counter,lose_counter,win_percentage)

        for y in team:
            y['win_counter'] = win_counter
            y['lose_counter'] = lose_counter
            y['win_percentage'] = win_percentage

        next_match = client.service.GetNextMatchByLeagueTeam(4500, id)
        latest_results = []
        for y in all_matches:
            if y['idTeam1'] == id and y['pointsTeam1'] == True  or y['idTeam2'] == id and y['pointsTeam1'] == True:
                latest_results.append(y)

        return render(request, 'teams/team_details.html',{
            'team':team,
            'next_match':next_match,
            'latest_results':reversed(latest_results[-5:]),
        })
    else:
        return HttpResponse('
Team not found
')


from common import Problem, exec_template_methods
from typing import List
import heapq

class Solution(Problem):

    class KthLargest:
        def __init__(self, k: int, nums: List[int]):

            self.pool = nums
            self.size = len(self.pool)
            self.k = k
            heapq.heapify(self.pool)
            while self.size > k:
                heapq.heappop(self.pool)
                self.size -= 1

        def add(self, val: int) -> int:
            if self.size < self.k:
                heapq.heappush(self.pool, val)
                self.size += 1
            elif val > self.pool[0]:
                heapq.heapreplace(self.pool, val)

            return self.pool[0]

if __name__ == '__main__':
    Solution.test(__file__)


'''
Open Addressing Hash Table with Linear Probing and Lazy Deletions
By: Alex Mirov
Feb 2019
'''

import sympy

######## Hash Functions ########

def modulo (val, tableSize):
	return val % tableSize

def quadratic (val, tableSize):
	return val ** 2

######## Hash Table ##########

class HashTable:

	def __init__ (self, initialSize=7, loadFactor=0.5, hashFunction=modulo):
		self.table = [None] * initialSize
		self.loadFactor = loadFactor
		self.hashFunction = hashFunction

	def _getLoad (self):
		'''
		Returns the current percent utilized capacity (load) of the table.
		'''
		ct = 0
		for el in self.table:
			if el is not None: ct += 1

		return ct / len(self.table)

	def _rehash (self):
		'''
		When the capacity (load) of the table reaches the loadFactor threshold, _rehash creates a new
		table of size == the next prime number after 2x the current table size.
		'''
		# Get new table size
		newTableSize = len(self.table) * 2
		while not sympy.isprime(newTableSize): newTableSize += 1

		# Init empty new table
		oldTable = self.table
		self.table = [None] * newTableSize

		# Re-insert every element from old table into new table
		for el in oldTable:
			if el is not None:
				self.insert(el)

	def insert (self, data):
		'''
		Inserts 'data' into the table using linear probing
		'''
		index = self.hashFunction(data, len(self.table))
		for i in range(0, len(self.table)):
			index = (index + i) % len(self.table)

			if self.table[index] is None:
				self.table[index] = data
				break

		# Check if current utilized capacity has exceeded load factor
		if self._getLoad() >= self.loadFactor: self._rehash()

	def find (self, data):
		'''
		Returns index into hash table with matching data value.
		Returns None if data is not found.
		'''
		index = self.hashFunction(data, len(self.table))
		for i in range(0, len(self.table)):
			index = (index + i) % len(self.table)

			if self.table[index] is data:
				print("FOUND:", data, "at", index, "in", i + 1, "searches")
				return index

		return None

	def delete(self, data):
		'''
		Removes matching data from hash table. Implements Lazy Deletions -- meaning that the table will not
		rehash once elements have been removed.
		Returns True if successfully deleted.
		Returns False if data is not found in the table.
		'''
		# Find data in table
		index = self.find(data)
		if index is None: return False

		# Remove data
		self.table[index] = None
		return True

	def printTable(self):
		print("Hash Table:  Size:", len(self.table), "  Load Factor:", self.loadFactor, "  Current Capcaity:", self._getLoad())
		for el, i in zip(self.table, range(0, len(self.table))):
			print("  ", i, el)

if __name__ == "__main__":

	myHash = HashTable(hashFunction=quadratic)

	myHash.insert(33)
	myHash.insert(11)
	myHash.insert(1)
	myHash.insert(2)
	myHash.insert(7)
	myHash.insert(12)
	myHash.insert(17)
	myHash.insert(16)
	myHash.insert(8)

	myHash.printTable()

	myHash.delete(12)

	myHash.printTable()


from pyrogram import Client, filters, enums
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid
from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, MELCOW_NEW_USERS
from database.users_chats_db import db
from database.ia_filterdb import Media
from utils import get_size, temp, get_settings
from Script import script
from pyrogram.errors import ChatAdminRequired

"""-----------------------------------------https://t.me/GetTGLink/4179 --------------------------------------"""

@Client.on_message(filters.new_chat_members & filters.group)
async def save_group(bot, message):
    r_j_check = [u.id for u in message.new_chat_members]
    if temp.ME in r_j_check:
        if not await db.get_chat(message.chat.id):
            total=await bot.get_chat_members_count(message.chat.id)
            r_j = message.from_user.mention if message.from_user else "Anonymous"
            await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j))
            await db.add_chat(message.chat.id, message.chat.title)
        if message.chat.id in temp.BANNED_CHATS:
            # Inspired from a boat of a banana tree
            buttons = [[
                InlineKeyboardButton('sᴜᴘᴘᴏʀᴛ', url=f'https://t.me/{SUPPORT_CHAT}')
            ]]
            reply_markup=InlineKeyboardMarkup(buttons)
            k = await message.reply(
                text='ᴄʜᴀᴛ ɴᴏᴛ ᴀʟʟᴏᴡᴇᴅ 🐞\n\nMʏ ᴀᴅᴍɪɴꜱ ʜᴀꜱ ʀᴇꜱᴛʀɪᴄᴛᴇᴅ ᴍᴇ ғʀᴏᴍ ᴡᴏʀᴋɪɴɢ ʜᴇʀᴇ ! Iғ ʏᴏᴜ ᴡᴀɴᴛ ᴛᴏ ᴋɴᴏᴡ ᴍᴏʀᴇ ᴀʙᴏᴜᴛ ɪᴛ ᴄᴏɴᴛᴀᴄᴛ ꜱᴜᴘᴘᴏʀᴛ..',
                reply_markup=reply_markup,
            )

            try:
                await k.pin()
            except:
                pass
            await bot.leave_chat(message.chat.id)
            return
        buttons = [[
            InlineKeyboardButton('ℹ Hᴇʟᴘ ℹ', url=f"https://t.me/{temp.U_NAME}?start=help"),
            InlineKeyboardButton('📢 ᴜᴘᴅᴀᴛᴇs 📢', url='https://t.me/TamilanBotsZ')
        ]]
        reply_markup=InlineKeyboardMarkup(buttons)
        await message.reply_text(
            text=f"ᴛʜᴀɴᴋs ғᴏʀ ᴀᴅᴅɪɴɢ ᴍᴇ ɪɴ {message.chat.title} ❣\n\nɪғ ᴜ ᴀsᴋ ǫᴜᴇsᴛɪᴏɴs & ᴅᴏᴜʙᴛs ɪɴ sᴜᴘᴘᴏʀᴛ",
            reply_markup=reply_markup)
    else:
        settings = await get_settings(message.chat.id)
        if settings["welcome"]:
            for u in message.new_chat_members:
                if (temp.MELCOW).get('welcome') is not None:
                    try:
                        await (temp.MELCOW['welcome']).delete()
                    except:
                        pass
                temp.MELCOW['welcome'] = await message.reply(f"Hey , {u.mention}, Welcome to {message.chat.title}")

@Client.on_message(filters.command('leave') & filters.user(ADMINS))
async def leave_a_chat(bot, message):
    if len(message.command) == 1:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴄʜᴀᴛ ɪᴅ')
    chat = message.command[1]
    try:
        chat = int(chat)
    except:
        chat = chat
    try:
        buttons = [[
            InlineKeyboardButton('sᴜᴘᴘᴏʀᴛ', url=f'https://t.me/{SUPPORT_CHAT}')
        ]]
        reply_markup=InlineKeyboardMarkup(buttons)
        await bot.send_message(
            chat_id=chat,
            text='Hello Friends, \nMy admin has told me to leave from group so i go! If you wanna add me again contact my support group.',
            reply_markup=reply_markup,
        )

        await bot.leave_chat(chat)
        await message.reply(f"left the chat `{chat}`")
    except Exception as e:
        await message.reply(f'Error - {e}')

@Client.on_message(filters.command('disable') & filters.user(ADMINS))
async def disable_chat(bot, message):
    if len(message.command) == 1:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ᴄʜᴀᴛ ɪᴅ')
    r = message.text.split(None)
    if len(r) > 2:
        reason = message.text.split(None, 2)[2]
        chat = message.text.split(None, 2)[1]
    else:
        chat = message.command[1]
        reason = "No reason Provided"
    try:
        chat_ = int(chat)
    except:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ᴠᴀʟɪᴅ ᴄʜᴀᴛ ɪᴅ')
    cha_t = await db.get_chat(int(chat_))
    if not cha_t:
        return await message.reply("ᴄʜᴀᴛ ɴᴏᴛ ғᴏᴜɴᴅ ɪɴ ᴍʏ ᴅʙ")
    if cha_t['is_disabled']:
        return await message.reply(f"ᴛʜɪs ᴄʜᴀᴛ ɪs ᴀʟʀᴇᴀᴅʏ ᴅɪsᴀʙʟᴇᴅ:\nReason- {cha_t['reason']} ")
    await db.disable_chat(int(chat_), reason)
    temp.BANNED_CHATS.append(int(chat_))
    await message.reply('ᴄʜᴀᴛ sᴜᴄᴄᴇssғᴜʟʟʏ ᴅɪsᴀʙʟᴇᴅ')
    try:
        buttons = [[
            InlineKeyboardButton('sᴜᴘᴘᴏʀᴛ', url=f'https://t.me/{SUPPORT_CHAT}')
        ]]
        reply_markup=InlineKeyboardMarkup(buttons)
        await bot.send_message(
            chat_id=chat_,
            text=f'ʜᴇʟʟᴏ ғʀɪᴇɴᴅ, \nMʏ ᴀᴅᴍɪɴ ʜᴀꜱ ᴛᴏʟᴅ ᴍᴇ ᴛᴏ ʟᴇᴀᴠᴇ ғʀᴏᴍ ɢʀᴏᴜᴘ ꜱᴏ ɪ ɢᴏ! Iғ ʏᴏᴜ ᴡᴀɴɴᴀ ᴀᴅᴅ ᴍᴇ ᴀɢᴀɪɴ ᴄᴏɴᴛᴀᴄᴛ ᴍʏ ꜱᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ. \nReason : {reason}',
            reply_markup=reply_markup)
        await bot.leave_chat(chat_)
    except Exception as e:
        await message.reply(f"Error - {e}")

@Client.on_message(filters.command('enable') & filters.user(ADMINS))
async def re_enable_chat(bot, message):
    if len(message.command) == 1:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ᴄʜᴀᴛ ɪᴅ')
    chat = message.command[1]
    try:
        chat_ = int(chat)
    except:
        return await message.reply('ɢɪʙᴇ ᴍᴇ ᴀ ᴠᴀʟɪᴅ ᴄʜᴀᴛ ɪᴅ')
    sts = await db.get_chat(int(chat))
    if not sts:
        return await message.reply("ᴄʜᴀᴛ ɴᴏᴛ ғᴏᴜɴᴅ ɪɴ ᴍʏ ᴅʙ !")
    if not sts.get('is_disabled'):
        return await message.reply('ᴛʜɪs ᴄʜᴀᴛ ɪs ɴᴏᴛ ʏᴇᴛ ᴅɪsᴀʙʟᴇᴅ.')
    await db.re_enable_chat(int(chat_))
    temp.BANNED_CHATS.remove(int(chat_))
    await message.reply("ᴄʜᴀᴛ sᴜᴄᴄᴇssғᴜʟʟʏ ʀᴇ-ᴇɴᴀʙʟᴇᴅ")

@Client.on_message(filters.command('stats') & filters.incoming)
async def get_ststs(bot, message):
    rju = await message.reply('ғᴇᴛᴄʜɪɴɢ sᴛᴀᴛs..')
    total_users = await db.total_users_count()
    totl_chats = await db.total_chat_count()
    files = await Media.count_documents()
    size = await db.get_db_size()
    free = 536870912 - size
    size = get_size(size)
    free = get_size(free)
    await rju.edit(script.STATUS_TXT.format(files, total_users, totl_chats, size, free))

# a function for trespassing into others groups, Inspired by a Vazha
# Not to be used , But Just to showcase his vazhatharam.
# @Client.on_message(filters.command('invite') & filters.user(ADMINS))
async def gen_invite(bot, message):
    if len(message.command) == 1:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ᴄʜᴀᴛ ɪᴅ')
    chat = message.command[1]
    try:
        chat = int(chat)
    except:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ᴠᴀʟɪᴅ ᴄʜᴀᴛ ɪᴅ')
    try:
        link = await bot.create_chat_invite_link(chat)
    except ChatAdminRequired:
        return await message.reply("Iɴᴠɪᴛᴇ Lɪɴᴋ Gᴇɴᴇʀᴀᴛɪᴏɴ Fᴀɪʟᴇᴅ, Iᴀᴍ Nᴏᴛ Hᴀᴠɪɴɢ Sᴜғғɪᴄɪᴇɴᴛ Rɪɢʜᴛꜱ")
    except Exception as e:
        return await message.reply(f'Error {e}')
    await message.reply(f'ʜᴇʀᴇ ᴜʀ ɪɴᴠɪᴛᴇ ʟɪɴᴋ {link.invite_link}')

@Client.on_message(filters.command('ban') & filters.user(ADMINS))
async def ban_a_user(bot, message):
    # https://t.me/GetTGLink/4185
    if len(message.command) == 1:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ɪᴅ/ᴜsᴇʀɴᴀᴍᴇ')
    r = message.text.split(None)
    if len(r) > 2:
        reason = message.text.split(None, 2)[2]
        chat = message.text.split(None, 2)[1]
    else:
        chat = message.command[1]
        reason = "No reason Provided"
    try:
        chat = int(chat)
    except:
        pass
    try:
        k = await bot.get_users(chat)
    except PeerIdInvalid:
        return await message.reply("Tʜɪꜱ ɪꜱ ᴀɴ ɪɴᴠᴀʟɪᴅ ᴜꜱᴇʀ, ᴍᴀᴋᴇ ꜱᴜʀᴇ ɪᴀ ʜᴀᴠᴇ ᴍᴇᴛ ʜɪᴍ ʙᴇғᴏʀᴇ.")
    except IndexError:
        return await message.reply("Tʜɪꜱ ᴍɪɢʜᴛ ʙᴇ ᴀ ᴄʜᴀɴɴᴇʟ, ᴍᴀᴋᴇ ꜱᴜʀᴇ ɪᴛꜱ ᴀ ᴜꜱᴇʀ.")
    except Exception as e:
        return await message.reply(f'Error - {e}')
    else:
        jar = await db.get_ban_status(k.id)
        if jar['is_banned']:
            return await message.reply(f"{k.mention} ɪs ᴀʟʀᴇᴀᴅʏ ʙᴀɴɴᴇᴅ \nReason: {jar['ban_reason']}")
        await db.ban_user(k.id, reason)
        temp.BANNED_USERS.append(k.id)
        await message.reply(f"sᴜᴄᴄᴇssғᴜʟʟʏ ʙᴀɴɴᴇᴅ {k.mention}")

@Client.on_message(filters.command('unban') & filters.user(ADMINS))
async def unban_a_user(bot, message):
    if len(message.command) == 1:
        return await message.reply('ɢɪᴠᴇ ᴍᴇ ᴀ ᴜsᴇʀ ɪᴅ/ᴜsᴇʀɴᴀᴍᴇ')
    r = message.text.split(None)
    if len(r) > 2:
        reason = message.text.split(None, 2)[2]
        chat = message.text.split(None, 2)[1]
    else:
        chat = message.command[1]
        reason = "No reason Provided"
    try:
        chat = int(chat)
    except:
        pass
    try:
        k = await bot.get_users(chat)
    except PeerIdInvalid:
        return await message.reply("Tʜɪꜱ ɪꜱ ᴀɴ ɪɴᴠᴀʟɪᴅ ᴜꜱᴇʀ, ᴍᴀᴋᴇ ꜱᴜʀᴇ ɪᴀ ʜᴀᴠᴇ ᴍᴇᴛ ʜɪᴍ ʙᴇғᴏʀᴇ.,")
    except IndexError:
        return await message.reply("Tʜɪꜱ ᴍɪɢʜᴛ ʙᴇ ᴀ ᴄʜᴀɴɴᴇʟ, ᴍᴀᴋᴇ ꜱᴜʀᴇ ɪᴛꜱ ᴀ ᴜꜱᴇʀ..")
    except Exception as e:
        return await message.reply(f'Error - {e}')
    else:
        jar = await db.get_ban_status(k.id)
        if not jar['is_banned']:
            return await message.reply(f"{k.mention} ɪs ɴᴏᴛ ʏᴇᴅ ʙᴀɴɴᴇᴅ ")
        await db.remove_ban(k.id)
        temp.BANNED_USERS.remove(k.id)
        await message.reply(f"sᴜᴄᴄᴇsғᴜʟʟʏ ʙᴀɴɴᴇᴅ {k.mention}")

@Client.on_message(filters.command('users') & filters.user(ADMINS))
async def list_users(bot, message):
    # https://t.me/GetTGLink/4184
    raju = await message.reply('ɢᴇᴛᴛɪɴɢ ʟɪsᴛs ᴏғ ᴜsᴇʀs')
    users = await db.get_all_users()
    out = "ᴜsᴇʀs sᴀᴠᴇᴅ ɪɴ ᴍʏ ᴅʙ:\n\n"
    async for user in users:
        out += f"{user['name']}"
        if user['ban_status']['is_banned']:
            out += '( Banned User )'
        out += '\n'
    try:
        await raju.edit_text(out)
    except MessageTooLong:
        with open('users.txt', 'w+') as outfile:
            outfile.write(out)
        await message.reply_document('users.txt', caption="List Of Users")

@Client.on_message(filters.command('chats') & filters.user(ADMINS))
async def list_chats(bot, message):
    raju = await message.reply('ɢᴇᴛᴛɪɴɢ ʟɪsᴛs ᴏғ ᴜsʀʀs')
    chats = await db.get_all_chats()
    out = "ᴄʜᴀᴛs sᴀᴠᴇᴅ ɪɴ ᴍʏ ᴅʙ:\n\n"
    async for chat in chats:
        out += f"**Title:** `{chat['title']}`\n**- ID:** `{chat['id']}`"
        if chat['chat_status']['is_disabled']:
            out += '( Disabled Chat )'
        out += '\n'
    try:
        await raju.edit_text(out)
    except MessageTooLong:
        with open('chats.txt', 'w+') as outfile:
            outfile.write(out)
        await message.reply_document('chats.txt', caption="List Of Chats")


import PIL
import numpy as np
import cv2
import shapely
import matplotlib.pyplot as plt

import wwtool

def get_palette(num_classes):
    n = num_classes
    palette = [0]*(n*3)
    for j in range(0, n):
        lab = j
        palette[j*3+0] = 0
        palette[j*3+1] = 0
        palette[j*3+2] = 0
        i = 0
        while (lab > 0):
            palette[j*3+0] |= (((lab >> 0) & 1) << (7-i))
            palette[j*3+1] |= (((lab >> 1) & 1) << (7-i))
            palette[j*3+2] |= (((lab >> 2) & 1) << (7-i))
            i = i + 1
            lab >>= 3
    return palette

def colorize_mask(mask, palette):
    zero_pad = 256 * 3 - len(palette)
    for _ in range(zero_pad):
        palette.append(0)
    new_mask = PIL.Image.fromarray(mask.astype(np.uint8)).convert('P')
    new_mask.putpalette(palette)
    new_mask = new_mask.convert('RGB')
    return new_mask

def show_mask(mask,
              num_classes=2,
              wait_time=0,
              out_file=None):
    palette = get_palette(num_classes)
    colorized_mask = colorize_mask(mask, palette)
    colorized_mask_np = np.array(colorized_mask)
    colorized_mask_np = colorized_mask_np[:, :, ::-1].copy()
    wwtool.show_image(colorized_mask_np,
                      wait_time=wait_time,
                      win_name='mask',
                      save_name=out_file)

def show_polygons_on_image(masks,
                           img,
                           alpha=0.4,
                           output_file=None):
    """show masks on image

    Args:
        masks (list): list of coordinate
        img (np.array): original image
        alpha (int): compress
        output_file (str): save path
    """
    color_list = list(wwtool.COLORS.keys())
    img_h, img_w, _ = img.shape

    foreground = wwtool.generate_image(img_h, img_w, (0, 0, 0))
    for idx, mask in enumerate(masks):
        mask = np.array(mask).reshape(1, -1, 2)
        cv2.fillPoly(foreground, mask, (wwtool.COLORS[color_list[idx % 20]][2], wwtool.COLORS[color_list[idx % 20]][1], wwtool.COLORS[color_list[idx % 20]][0]))

    heatmap = wwtool.show_grayscale_as_heatmap(foreground / 255.0, show=False, return_img=True)
    beta = (1.0 - alpha)
    fusion = cv2.addWeighted(heatmap, alpha, img, beta, 0.0)

    if output_file is not None:
        cv2.imwrite(output_file, fusion)
    else:
        wwtool.show_image(fusion, save_name=None)

    return fusion

def show_polygon(polygon):
    if type(polygon) == str:
        polygon = shapely.wkt.loads(polygon)

    plt.plot(*polygon.exterior.xy)
    plt.show()


import matplotlib.pyplot as plt
import numpy
import pickle
import argparse
import os

def main(args):

    with open(os.path.join(args.hist_dir, "hist_stage_1.pickle"), "rb") as f:
        history1 = pickle.load(f)

    with open(os.path.join(args.hist_dir, "hist_stage_2.pickle"), "rb") as f:
        history2 = pickle.load(f)

    loss = history1['loss'] + history2['loss']
    val_loss = history1['val_loss'] + history2['val_loss']

    for i in range(len(loss)):
        loss[i] = float(loss[i])

    for i in range(len(val_loss)):
        val_loss[i] = float(val_loss[i])

    # Skip the loss for first 2 epochs
    plt.plot(loss[2:])
    plt.plot(val_loss[2:])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'val'], loc='upper left')
    plt.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Visualise loss")
    # filenames
    parser.add_argument("-d", "--hist_dir", type = str, required = True, help = "Directory to history files")
    args = parser.parse_args()

    main(args)


#!/usr/bin/env python
import numpy as np
from math import log

def readfit():
  infile = open('analysis/fitness_filter.txt')
  header = infile.readline().rstrip().rsplit('\t')
  fitdict = {}
  stddict = {}
  for line in infile:
    line = line.rstrip().rsplit('\t')
    mut  = line[0]
    fitlist = []
    for fit in line[1:]:
      if float(fit) > 0:
        fitlist.append(log(float(fit),10))
    if len(fitlist) == 0:
      fitdict[mut] = -4
      stddict[mut] = 0
    else:
      fitdict[mut] = sum(fitlist)/len(fitlist)
      stddict[mut] = np.std(fitlist)
  infile.close()
  return fitdict,stddict

def main():
  fitdict,stddict = readfit()
  infile = open('code/mutation_protease_energies.csv','rU')
  header = infile.readline().rstrip().rsplit(',')
  line1 = infile.readline().rstrip().rsplit(',')
  outfile = open('analysis/potts_fitness.txt','w')
  outfile.write('mut\tepotts\tfitness\tstd\n')
  epotts_wt = float(line1[-1])
  for line in infile:
    records = line.rstrip().rsplit(',')
    mut = records[1]
    if len(mut.rsplit('_')) <= 12 and mut in fitdict:
      epotts = float(records[-1])-epotts_wt
      outfile.write(mut+'\t'+str(epotts)+'\t'+str(fitdict[mut])+'\t'+str(stddict[mut])+'\n')
  infile.close()
  outfile.close()

if __name__ == '__main__':
  main()


from flask import render_template, flash, request, redirect, url_for, session, jsonify, Blueprint
from functools import wraps
from tools import MySQLTools

user = Blueprint('user', __name__)
# 初始化数据库
util = MySQLTools('localhost', 'root', 'cfpl', 'sharebike', 'utf8')

# 判断用户是否登录成功
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('user', None):
            return func(*args, **kwargs)
        else:
            flash("请先登录", 'danger')
            return redirect(url_for('login'))
    return wrapper

# 主页
@user.route('/index', methods = ['GET', 'POST'])
@login_required
def index():
    user_cnt, bike_cnt, order_cnt, news_cnt = util.dataStatic()
    n1, n2, n3, n4 = util.numStatic()
    return render_template("/user/index.html",
                           user_cnt = user_cnt, bike_cnt = bike_cnt,
                           order_cnt = order_cnt, news_cnt = news_cnt,
                           n1 = n1, n2 = n2, n3 = n3, n4 = n4)

数据库课程设计-李文根/1853790_庄镇华_应用系统开发/源代码/user/__init__.py


from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.owm.serializers import GetWeatherSerializer, WeatherSerializer
from utils.owm import OWMHelper

from drf_yasg.utils import swagger_auto_schema

from drf_yasg import openapi

class WeatherView(APIView):
    permission_classes = [permissions.AllowAny]
    serializer_class = GetWeatherSerializer

    @swagger_auto_schema(
        operation_description="Get actual weather data",
        method='get',
        query_serializer=GetWeatherSerializer(),
        responses={200: openapi.Response('', WeatherSerializer(many=True))},
        operation_id='current_weather_data'
    )
    @action(methods=['get'], detail=False)
    def get(self, request, *args, **kwargs):
        data = self.request.query_params
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        owm = OWMHelper(**serializer.data)
        owm.get_owm_data()
        if owm.ok:
            response_serializer = WeatherSerializer(data=owm.transform_response())
            response_serializer.is_valid(raise_exception=True)
            return Response(response_serializer.data)
        raise NotFound(detail=owm.error(), code=404)


# Buffet: Um restaurante do tipo buffet oferece apenas cinco tipos básicos de comida. Pense em cinco pratos simples e armazene-os em uma tupla.
# Use um laço for para exibir cada prato oferecido pelo restaurante.
# Tente modificar um dos itens e certifique-se de que Python rejeita a mudança.
# O restaurante muda seu cardápio, substituindo dois dos itens com pratos diferentes. Acrescente um bloco de código que reescreva a tupla e, em seguida,
# um laço for para exibir cda um dos itens do cardápio revisado.

# Resposta:

cardapio_original = (
    'Macarronada', 'Lasanha', 'Feijoada', 'Peixada', 'Camarãozada'
    )
print('Este é o cardápio original:')

for prato in cardapio_original:
    print(prato)

cardapio_modificado = (
    'Macarronada', 'Lasanha', 'Inhoque', 'Cappelete', 'Pizza'
    )
print('\nEste é o cardápio modificado:')

for prato in cardapio_modificado:
    print(prato)


from datetime import datetime

from flask import Flask, render_template

import requests

app = Flask(__name__)

year = datetime.now().year

@app.route("/")
def home():
    return render_template("index.html", year=year)

# print()

@app.route("/guess/<name>")
def guess(name):
    gender = requests.get(f"https://api.genderize.io?name={name}").json()['gender']
    age = requests.get(f"https://api.agify.io?name={name}").json()['age']
    return render_template("guess.html", name=name.capitalize(), gender=gender.capitalize(), age=age)

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=8080)


from ee.clickhouse.system_status import system_status

def test_system_status(db):
    results = list(system_status())
    assert [row["key"] for row in results] == [
        "clickhouse_alive",
        "clickhouse_event_count",
        "clickhouse_event_count_last_month",
        "clickhouse_event_count_month_to_date",
        "clickhouse_disk_0_free_space",
        "clickhouse_disk_0_total_space",
        "clickhouse_table_sizes",
        "clickhouse_system_metrics",
    ]
    assert len(results[-2]["subrows"]["rows"]) > 0
    assert len(results[-1]["subrows"]["rows"]) > 0


#python3

"""
This file takes the output of Cello and prints it out to a nice layout.
Important Information to Present:
    Circuit diagram (wire diagram with blocks) - the main circuit diagram file is:
        wiring_grn.svg
    Plasmid maps
    Expected input range and output range
    List of genetic components used to build the plasmid

Notes:
The SVG files should each be their own page.
xfer.png files represent the Hill function - some have wiring included.
srPr gate represents some kind of output measurement.
The PDF and the png files are replicates, you can leave out one and keep the other.

"""

import os
import logging
import shutil
import traceback
import json
from cello_util.plasmid_map.cello_plasmid_mapper import get_cello_plasmid_map_div

"""
Inputs:
    results_dir: (str) The path to the folder containing all the output files
        from Cello.
    scratch_dir: (str) The path to the scratch directory
    user_output_name: (str) The user's output name
    config_info: (dict) Information regarding the html
        base_plasmid_info: (str) fixed vocab - "none", "custom" etc.
Outputs:
    html_result_dict: (dict)
        "result_file_path" : (str) file path to resulting html file.
        "output_directory": (str) path to resulting output_directory in scratch
            dir.

"""
def build_html(results_dir, scratch_dir, user_output_name, config_info):
    """
    There is a variable amount of png files we need to return to the user.
    Should we enforce a limit? (10 currently)
    """
    logging.info("Starting to generate html report.")

    output_directory = os.path.join(scratch_dir, "HTML_Report")
    config_info["scratch_dir"] = scratch_dir
    os.makedirs(output_directory, exist_ok=True)
    #The following function adds png files and javascript files.
    update_static_files(output_directory)

    try:

        out_files_dict = extract_files_from_folder(results_dir)

        num_plasmids_created = out_files_dict["num_plasmids_created"]
        overview_content = '
 ' + str(num_plasmids_created) + \
        " Plasmids Created by Cello. Visualizations provided in the other tabs.
"

        result_file_path = os.path.join(output_directory, 'report.html')

        html_template = open(os.path.join(os.path.dirname(__file__),
            "report_template.html"), "r")
        html_file_str = html_template.read()
        html_template.close()

        path_to_wiring_png_file = out_files_dict['wiring_png_file']

        png_diagram_name = get_name_from_path(path_to_wiring_png_file,
                "wiring_png")
        png_display_name = 'Wiring Diagram'
        #We get the wiring link file from the svg file:
        if out_files_dict["wiring_svg_diagram_found"] == True:
            diagram_link = get_name_from_path(out_files_dict['wiring_svg'])
            shutil.copy2(os.path.join(results_dir, diagram_link),
            os.path.join(output_directory, diagram_link))

        else:
            diagram_link = png_diagram_name

        shutil.copy2(os.path.join(results_dir, png_diagram_name),
        os.path.join(output_directory, png_diagram_name))
        visualization_content = ''
        visualization_content += '
'
        visualization_content += ''.format(diagram_link)
        visualization_content += ''.format(
        png_display_name)
        visualization_content += '
{}

'.format(
        png_display_name)

        #For each truth graph make one of these
        truth_png_files = out_files_dict['truth_png_files']
        truth_pdf_files = out_files_dict['truth_pdf_files']

        #We set the upper limit of different png files to be 10
        k = min(len(truth_png_files), 10)

        for i in range(k):
            truth_graph_dict = truth_png_files[i]

            truth_graph_path = truth_graph_dict['file_path']
            truth_gene_name = truth_graph_dict['gene_name']

            truth_graph_name = get_name_from_path(truth_graph_path,"truth")
            truth_graph_display_name = 'RPU Graph for ' + truth_gene_name

            shutil.copy2(os.path.join(results_dir, truth_graph_name),
            os.path.join(output_directory, truth_graph_name))

            truth_graph_link = truth_graph_name
            #Getting PDF file as a link:
            for i in range(len(truth_pdf_files)):
                pdf_file_dict = truth_pdf_files[i]
                pdf_gene = pdf_file_dict['gene_name']
                if truth_gene_name == pdf_gene:
                    truth_graph_link = get_name_from_path(
                            pdf_file_dict['file_path'] , "truth")
                    shutil.copy2(os.path.join(results_dir, truth_graph_link),
                    os.path.join(output_directory, truth_graph_link))
                    break
            visualization_content += '
'
            visualization_content += ''.format(truth_graph_link)
            visualization_content += ''.format(
            truth_graph_display_name)
            visualization_content += '
{}

'.format(
            truth_graph_display_name)

        #Here add plasmid visualization step - MAPS:
        gbk_files = out_files_dict['gbk_files']

        try:
            plasmid_vis_info = config_info
            gb_plasmid_divs_str = make_plasmid_divs(gbk_files, user_output_name,
                    plasmid_vis_info)
        except:
            logging.critical("Failed to make plasmid_divs")
            gb_plasmid_divs_str = ""
            logging.critical(traceback.print_exc())
        try:
            gb_plasmid_buttons_str = make_plasmid_buttons(gbk_files)
        except:
            gb_plasmid_buttons_str = ""
            logging.critical(traceback.print_exc())

        html_file_str = html_file_str.replace('
Visualization_Content
', visualization_content)
        html_file_str = html_file_str.replace('
Overview_Content
',overview_content)
        html_file_str = html_file_str.replace('{New_Plasmid_Divs}', gb_plasmid_divs_str)
        html_file_str = html_file_str.replace('{New_Plasmid_Buttons}', gb_plasmid_buttons_str)

        f = open(result_file_path, "w")
        f.write(html_file_str)
        f.close()

    except:
        logging.critical("Creation of HTML file failed at some point " + \
                        "in the function build_html (html_design) .")
        result_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"error.html")

    html_result_dict = {
        "result_file_path" : result_file_path,
        "output_directory": output_directory
            }

    return html_result_dict

"""
Inputs:
    full_path_to_folder: (str) The path to the folder containing all the output
        files from Cello.
Outputs:
    out_files_dict: (dict)
        wiring_svg: (str) The full path to the wiring svg file.
        wiring_svg_diagram_found: (bool) True if found, False if not.
        wiring_png_file: (str) The full path to the wiring png file.
        png_diagram_found: (bool) True if found, False if not
        truth_png_files: (list) List of dicts, where each contains name of gene
            and the full path to the png files.
            truth_dict: (dict)
                gene_name: (str) Name of gene
                file_path: (str) Path to file
        truth_png_files_found: (bool) True if found, False if not.
        truth_pdf_files: (list) List of dicts, where each contains name of gene
            and the full path to the pdf files.
            truth_dict: (dict)
                gene_name: (str) Name of gene
                file_path: (str) Path to file
        truth_pdf_files_found: (bool) True if found, False if not.
        gbk_files: (list) List of all paths to gbk files.
        all_return_files: (list of str) The full paths to all the files.

"""
def extract_files_from_folder(results_dir):

    #Getting files to sort through:
    all_files = os.listdir(results_dir)

    out_files_dict = dict()

    #Extracting Circuit Diagram - filename should end with 'wiring_grn.svg':
    wiring_svg_files = []
    wiring_png_files = []
    truth_pdf_files = []
    truth_png_files = []
    gbk_files = []
    wiring_svg_found = False
    wiring_png_files_found = False
    truth_png_files_found = False
    truth_pdf_files_found = False
    plasmid_ape_files_created = 0
    for f in all_files:
        if "wiring_agrn.svg" in f:
            wiring_svg_files.append(os.path.join(results_dir,f))
            wiring_svg_found = True
        elif "truth.png" in f:
            truth_gene_name = get_gene_name_for_truth_graph(f)
            truth_file_info = {"gene_name" : truth_gene_name, 'file_path': f}
            truth_png_files.append(truth_file_info)
            truth_png_files_found = True
        elif "truth.pdf" in f:
            truth_pdf_name = get_gene_name_for_truth_graph(f)
            truth_file_info = {"gene_name" : truth_pdf_name, 'file_path' : f}
            truth_pdf_files.append(truth_file_info)
            truth_pdf_files_found = True
        elif "wiring_agrn.png" in f:
            wiring_png_files.append(os.path.join(results_dir,f))
            wiring_png_files_found = True
        elif ".ape" in f:
            plasmid_ape_files_created += 1
        elif ".gbk" in f:
            gbk_files.append(os.path.join(results_dir,f))
    if wiring_svg_found:
        out_files_dict['wiring_svg'] = wiring_svg_files[0]
        if len(wiring_svg_files) > 1:
            logging.critical("Multiple wiring svg files found- Returning the first one.")
    if wiring_png_files_found:
        out_files_dict['wiring_png_file'] = wiring_png_files[0]
        if len(wiring_png_files) > 1:
            logging.critical("Multiple wiring grn files found- Returning the first one.")

    out_files_dict['wiring_svg_diagram_found'] = wiring_svg_found
    out_files_dict['png_diagram_found'] = wiring_png_files_found
    out_files_dict['truth_pdf_files_found'] = truth_pdf_files_found
    out_files_dict['truth_pdf_files'] = truth_pdf_files
    out_files_dict['truth_png_files_found'] = truth_png_files_found
    out_files_dict['truth_png_files'] = truth_png_files
    all_output_files = wiring_svg_files + truth_png_files + wiring_png_files
    out_files_dict['all_return_files'] = all_output_files
    out_files_dict["num_plasmids_created"] = plasmid_ape_files_created
    out_files_dict["gbk_files"] = gbk_files

    return out_files_dict

"""
Inputs:
    gbk_files: (list) A list of full paths to the gbk files.
    user_output_name: (str)
    plasmid_vis_info: (dict)
        base_plasmid_info: (str) none, custom, etc
Output:
    plasmid_divs_str: (str) A string to insert into report html.
"""
def make_plasmid_divs(gbk_files, user_output_name, plasmid_vis_info):

    #We place basic parameters on the design of the plasmid map:
    base_div_html_fp = os.path.join(os.path.dirname(__file__),
            "plasmid_map/div_svg_template.html")
    config_filepath = os.path.join(os.path.dirname(__file__),
            "plasmid_map/config.json")
    with open(config_filepath, "r") as cf:
        config_dict = json.loads(cf.read())

    if plasmid_vis_info["base_plasmid_info"] == "none":
        #If there are expected to be big CDs, we make the arrow smaller.
        #Instead of 85 percent, it will be 96 percent
        config_dict['js_info']['cds_info']['percent_start'] = 96

    plasmid_divs_str = ''
    #We set a maximum number of files to be made (6):
    k = min(len(gbk_files), 6)
    for i in range(k):
        gb_file = gbk_files[i]
        uniq_dict = {
            "file_num": i,
            "uniq_id": "prfx_" + str(i),
            "svg_id": "svg-" + str(i),
            "svg_name": "svg_" + str(i),
            "tmp_name": "plasmid_tmp_" + str(i),
            "scratch_dir": plasmid_vis_info["scratch_dir"]

                }
        try:
            plasmid_map_dict = get_cello_plasmid_map_div(gb_file,
                    base_div_html_fp, config_filepath, uniq_dict)
        except:
            logging.critical("FAILED TO MAKE VISUALIZATION: {}".format(gb_file))
            logging.critical(traceback.print_exc())
            break
        plasmid_map_div_html = plasmid_map_dict["complete_div_str"]
        plasmid_map_name = plasmid_map_dict["plasmid_name"]
        plasmid_map_div_html = plasmid_map_div_html.replace("Plasmid_Name_Here",
                user_output_name + "_" + plasmid_map_name)
        plasmid_map_div_html = plasmid_map_div_html.replace('id="Plasmid_Div_Id_Here"',
                'id="Plasmid_Map_' + str(i+1) + '"')
        plasmid_map_div_html = plasmid_map_div_html.replace('SVG_ID_HERE','my_svg_' + \
                str(i+1))

        plasmid_divs_str += plasmid_map_div_html + '\n\n\n'

    return plasmid_divs_str

"""
Inputs:
    HTML_Report_dir: (str) The path to the directory
"""
def update_static_files(HTML_Report_dir):
    #Vars (Paths):
    delete_img = "/kb/module/static/delete_img.png"
    reset_img = "/kb/module/static/reset_img.png"
    js_files = [ "/kb/module/static/js/d3-dispatch.v1.min.js",
        "/kb/module/static/js/d3-drag.v1.min.js",
        "/kb/module/static/js/d3-selection.v1.min.js",
        "/kb/module/static/js/d3.min.js"
            ]
    sh_ret = shutil.copyfile(delete_img, os.path.join(HTML_Report_dir,
            "delete_img.png"))
    logging.debug("NEW FILE COPY: {}".format(sh_ret))
    sh_ret = shutil.copyfile(reset_img, os.path.join(HTML_Report_dir,
            "reset_img.png"))
    logging.debug("NEW FILE COPY: {}".format(sh_ret))

    for js_file in js_files:
        js_file_name = js_file.split('/')[-1]
        shutil.copyfile(js_file, os.path.join(HTML_Report_dir, js_file_name))

"""
Inputs:
    gbk_files: (list) A list of full paths to the gbk files.

Output:
    plasmid_buttons_str: (str) A string to insert into report html.
"""
def make_plasmid_buttons(gbk_files):
    plasmid_buttons_str = ''
    k = min(len(gbk_files), 6)
    for i in range(k):
        new_id = "Plasmid_Map_" + str(i+1)
        new_button = '<button class="tablinks" onclick="openTab(event, ' + \
                "'" + new_id + "')" + \
        '">' + new_id.replace("_", " ") + "</button>\n"
        plasmid_buttons_str += new_button

    return plasmid_buttons_str

"""
Inputs:
    filepath: (str) Full path to the file
    typ: (str) Type of file: 'wiring_png' or 'truth'
"""
def get_name_from_path(filepath, typ = None):

    #For now we just return the filename
    return filepath.split('/')[-1]

"""
Input:
    filename: (str) Just the filename (not filepath). Getting name of gene from cello's production
    of a filename. Normally it looks like: job_1576197897501_A000_BFP_truth.png, we need "BFP" so we
     split by "_" and take the fourth index until the last index

"""
def get_gene_name_for_truth_graph(filename):

    return "".join((filename.split("_"))[3:-1])

def html_design_test():
    this_dir = os.path.dirname(os.path.realpath(__file__))
    gbk_files = [os.path.join(this_dir,"tst/job_1581723951170_A000_plasmid_circuit_P000.gbk"),
            os.path.join(this_dir,"tst/job_1581723951170_A000_plasmid_output_P000.gbk")]
    user_output_name = ""
    plasmid_vis_info = {
        "base_plasmid_info": "custom"
            }
    gb_plasmid_divs_str = make_plasmid_divs(gbk_files, user_output_name, plasmid_vis_info)

#if __name__ == "__main__":
#    html_design_test()


N = int(input())
people = list(map(int, input().split()))

people.sort(reverse=True)

count = 0

while True:
    # 제일 높은 공포도보다 남은 사람의 수가 적으면
    if not people:
        break
    if people[0] > len(people):
        break

    # 제일 높은 공포도 수만큼 높은 공포도부터 추출
    for i in range(people[0] - 1):
        del people[1]  # 다음으로 높은 공포도

    count += 1
    del people[0]

print(count)


import pickle
class Dog():
    def __init__(self,name):
        self.age=1
        self.name=name

    def bark(self):
        print('my name is',self.name)

dog1=Dog('hh')
with open('object.data','wb')as f_out:
    pickle.dump(dog1,f_out)

with open('object.data','rb')as f_in:
    dog2=pickle.load(f_in)

dog1.bark()
dog2.bark()
print(dog1.age,dog2.age)

with open('class.data','wb')as ff_out:
    pickle.dump(Dog,ff_out)

with open('class.data','rb')as ff_in:
    N_Dog=pickle.load(ff_in)

dog3=Dog('bb')
dog4=N_Dog('kk')
dog3.bark()
dog4.bark()
print(dog3.age,dog4.age)


import gatetools as gt
import itk
import click
import numpy as np
import sys

# -----------------------------------------------------------------------------
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)

@click.option('--input', '-i', help='Input image filename', required=True,
                type=click.Path(dir_okay=False))
@click.option('--axis', '-p', help='Axis of the projection', default=0)
@click.option('--mean', '-m', help='Compute the mean of the projected image', is_flag=True)
@click.option('--output', '-o', help='Output filename', required=True,
                type=click.Path(dir_okay=False,
                              writable=True, readable=False,
                              resolve_path=True, allow_dash=False, path_type=None))

def image_projection_click(input, axis, mean, output):
    '''
    Project the input along the axis. Compute the mean of the projection along this axis if the flag is set
    '''

    inputImage = itk.imread(input)
    outputImage = image_projection(inputImage, axis, mean)
    itk.imwrite(outputImage, output)

# -----------------------------------------------------------------------------
def image_projection(image, axis=0, mean=False):

    array = (itk.array_from_image(image)).astype(float)
    if image.GetImageDimension() == 3:
        array = np.swapaxes(array, 0, 2)
    projectedArray = np.sum(array, axis)

    if mean:
        projectedArray = projectedArray / image.GetLargestPossibleRegion().GetSize()[axis]

    outputImage = itk.image_from_array(projectedArray)
    spacing =  np.array(image.GetSpacing())
    spacing = np.delete(spacing, axis)
    outputImage.SetSpacing(spacing)
    origin =  np.array(image.GetOrigin())
    origin = np.delete(origin, axis)
    outputImage.SetOrigin(origin)
    return outputImage

# -----------------------------------------------------------------------------
if __name__ == '__main__':
    image_projection_click()

# -----------------------------------------------------------------------------
import unittest
import os

def createImageExample():
    x = np.arange(0, 23, 1)
    y = np.arange(20, 41, 1)
    z = np.arange(10, 25, 1)
    xx, yy, zz = np.meshgrid(x, y, z)
    image = itk.image_from_array(np.int16(xx))
    image.SetSpacing([1.1, 2, 3.1])
    image.SetOrigin([10, 12.4, -0.7])
    return image

class Test_Image_Projection(unittest.TestCase):
    def test_image_projection(self):
        image = createImageExample()
        output=image_projection(image, 0, False)
        outputArray = itk.array_view_from_image(output)
        self.assertTrue(outputArray[13, 14] == 14*15)
        self.assertTrue(output.GetSpacing()[0] == 2)
        self.assertTrue(output.GetSpacing()[1] == 3.1)
        self.assertTrue(output.GetOrigin()[0] == 12.4)
        self.assertTrue(output.GetOrigin()[1] == -0.7)
        self.assertTrue(output.GetLargestPossibleRegion().GetSize()[0] == 23)
        self.assertTrue(output.GetLargestPossibleRegion().GetSize()[1] == 21)
        output=image_projection(image, 1, False)
        outputArray = itk.array_view_from_image(output)
        self.assertTrue(outputArray[8, 5] == 253)
        self.assertTrue(output.GetSpacing()[0] == 1.1)
        self.assertTrue(output.GetSpacing()[1] == 3.1)
        self.assertTrue(output.GetOrigin()[0] == 10)
        self.assertTrue(output.GetOrigin()[1] == -0.7)
        self.assertTrue(output.GetLargestPossibleRegion().GetSize()[0] == 15)
        self.assertTrue(output.GetLargestPossibleRegion().GetSize()[1] == 21)
        output=image_projection(image, 2)
        outputArray = itk.array_view_from_image(output)
        self.assertTrue(outputArray[6, 10] == 6*21)
        self.assertTrue(output.GetSpacing()[0] == 1.1)
        self.assertTrue(output.GetSpacing()[1] == 2)
        self.assertTrue(output.GetOrigin()[0] == 10)
        self.assertTrue(output.GetOrigin()[1] == 12.4)
        self.assertTrue(output.GetLargestPossibleRegion().GetSize()[0] == 15)
        self.assertTrue(output.GetLargestPossibleRegion().GetSize()[1] == 23)
        output=image_projection(image, 2, True)
        outputArray = itk.array_view_from_image(output)
        self.assertTrue(outputArray[6, 10] == 6)


'''
-----------------------------------------------------------------------
                      Additional Documentation

Made by Zachary A Brader, Kieran Coito, Pedro Goncalves Mokarzel
while attending University of Washington Bothell
Made in 03/09/2020
Based on instruction in CSS 458,
taught by professor Johnny Lin
Notes:
- Written for Python 3.7.3.
- No executable
- Modules necessary: pygame, datetime
- External necessities: variables.py
- Makes animation of model

=======================================================================
'''

# =======================================================================
# ============================= Imports =================================
# =======================================================================

import pygame
from pygame import display
import variables as v
from datetime import timedelta

# =======================================================================
# ================================= Class ===============================
# =======================================================================

# Class to preform animation logic via pygame
class visual():
    # Initialize pygame module
    pygame.init()

    # Screen size in pixels
    displayWidth = 450
    displayHeight = 450

    # Create Screen / Display Window
    screen = display.set_mode((displayWidth, displayHeight))

    # Create clock to control frame rate
    clock = pygame.time.Clock()

    # Provide a caption for the window
    display.set_caption("CSS 458 Group - Pedro Is a Meme")

    # List of colors to pull from as needed
    black = (0, 0, 0)
    white = (255, 255, 255)
    red = (255, 0, 0)
    green = (0, 200, 0)
    bright_red = (255, 0, 0)
    bright_green = (0, 255, 0)
    blue = (0, 0, 255)

    # Fonts to choose from
    font = pygame.font.Font(None, 32)
    smallFont = pygame.font.Font(None, 20)  # Used inside text boxes

    # Ignore
    def __init__(self):
        pass

    def print_env(self, modelObj, update_time=1, start_time=None):
        """ Visualizes a set of data stored inside a model object for the time
            specified in update_time.

            Preconditions:
            - modelObj: The current state of the model to visualize.
            - update_time: The time to display the visualization for.
                This number is in milliseconds, so 1000 ms = 1 second.

            Postcondition:
            - Prints an environment that shows both the cashiers and customers,
                and allows the user to determine statistics about the cashier or customer
                by hovering over them with the mouse.
        """

        # Pulls environment
        line = modelObj.line
        # Reference to cashiers
        cashiers = line.cashier_list

        # List of item's remaining
        item_list = modelObj.list_of_items_checked

        # Customers waiting to get into line
        cust_waiting = modelObj.list_of_customers_in_line

        # Model is updated by this many seconds each iteration
        cur_time_step = (60 / v.TIME_STEP) * len(item_list)

        start_hour = None
        if start_time is not None:
            start_hour = timedelta(seconds=(start_time * 3600))

        # Tells the loop to keep displaying until a certain condition is met
        active = True

        # Record when we this visualization
        startTimer = pygame.time.get_ticks()

        # Main logic
        while active:
            # Check for user interaction
            for event in pygame.event.get():
                # If the user exits out of the animation window
                if event.type == pygame.QUIT:
                    # Return false so the model doesn't keep making
                    # the window reappear
                    return False

            # Has this model been going for longer than the time in update_time?
            if (pygame.time.get_ticks() - startTimer) > (update_time * 1000):
                # The user didn't intervene, tell model
                # to keep showing the animation
                return True

            # Set background
            self.screen.fill(self.black)

            # Print Statistics about current timestep inside

            if start_time is None:
                # a text box at the top of the screen
                self.text_box(str(cur_time_step) + " Seconds",
                              int(self.displayWidth / 4), 0, width=int(self.displayWidth / 2), height=25)
            else:
                self.text_box(str(start_hour + timedelta(seconds=cur_time_step))[:-3],
                              int(self.displayWidth / 4), 0, width=int(self.displayWidth / 2), height=25)

            # Print the customers waiting to go into line
            self.text_box("Customers Not in Line: " + str(int(cust_waiting[-1])),
                          int(self.displayWidth / 4), 30, width=int(self.displayWidth / 2), height=25)

            # Print cashiers
            self.print_floor(cashiers)

            # Update screen
            pygame.display.flip()
            self.clock.tick(30)

    def print_floor(self, cashiers):
        """ Takes in the list of all the current cashiers and displays them on the screen

            Precondition:
            - cashiers: A list of all the cashiers from our model object

            Postcondition:
             - The animation will now display all the cashiers correctly
        """
        # Store the total number of cashiers for readability
        num_cashiers = len(cashiers)

        # Determine how much room we need to divide the screen equally
        dist = int(self.displayWidth / min((num_cashiers + 1), 6))

        # Print up to three rows
        for row in range(max(int(num_cashiers / 6 + 1), 1)):
            # Print up to five cashiers
            for column in range(min(num_cashiers - (5 * row), 5)):
                # To make the data readable, we will only show the first 20 cashiers.
                if row * 5 + column < 19:
                    # Print a cashier and it's customers
                    self.print_both(cashiers[column + row * 5], cashiers[column + row * 5].cashier_queue, column, row, dist)
                # Print the rest of the cashiers inside a single box with a number representing them
                else:
                    # Show the rest of the cashiers as a single text box
                    self.print_final_cashier(dist * (column + 1),
                                             self.displayHeight / 3 + (80 * row),
                                             sum([1 for x in range(15, len(cashiers)) if not cashiers[x].self_checkout]),
                                             sum([1 for x in range(15, len(cashiers)) if cashiers[x].self_checkout]),
                                             sum([len(cashiers[x].cashier_queue) for x in range(15, len(cashiers))]))
                    # We don't need to print any other cashiers
                    return

    def print_both(self, cashier, queue, cashier_num, row, dist):
        """ Print a single cashier and their customers

            Postcondition:
            - cashier: A cashier object
            - queue: The list of customers attached to a cashier object
            - cashier_num: This correlates to the column number of the cashier; It is
                used to find the the x value
            - row: Which row the cashier is on; This is used to find the y value
            - dist: The distance between each cashier on the x-axis

            Postcondition:
            - A cashier is visualized on the screen with their current line. As well,
                the user can interact with them by hovering over them
        """

        # Where to print the cashier on the x axis
        xPos = dist * (cashier_num + 1)

        # The initial height of the cashier on the screen
        height = self.displayHeight / 3

        # Print the cashier object
        self.print_cashier(xPos, height + (80 * row), cashier)

        # Print the cashier's line
        self.print_line(xPos, height + (80 * row), queue)

    def print_cashier(self, x, y, cashier):
        """ Print a single cashier object

            Precondition:
            - x: The x coordinate of the cashier on the screen
            - y: The y coordinate of the cashier on the screen
            - cashier: The cashier object to print

            Postcondition:
            - Prints a visual box to represent a cashier. Upon hovering
                over it, statistics about that specific cashier will appear
        """

        # Check the mouse's position
        mouse = pygame.mouse.get_pos()

        # Is the mouse over the box's position?
        if x + 25 > mouse[0] > x and y + 25 > mouse[1] > y:
            # Print a bright version of the cashier object
            if not cashier.self_checkout:
                # Print a highlighted regular cashier
                pygame.draw.rect(self.screen, self.bright_green, (x, y, 25, 25))
            else:
                # Print a highlighted self checkout
                pygame.draw.rect(self.screen, self.bright_red, (x, y, 25, 25))

            # Print statistics about the cashier at the top of the screen

            # Number of customers helped
            helpedText = "Helped: " + str(cashier.helped)
            self.text_box(helpedText, int(self.displayWidth / 6), 60, width=int(self.displayWidth / 6), height=25)

            # Cashiers Items Per Minute
            ipmText = "IPM: " + str(round(cashier.IPM, 2))
            self.text_box(ipmText, int(self.displayWidth / 3), 60, width=int(self.displayWidth / 6), height=25)

            # Total items checked out by this cashier
            itemText = "Items: " + str(round(cashier.total_items_checked, 2))
            self.text_box(itemText, int(self.displayWidth / 2), 60, width=int(self.displayWidth / 6), height=25)

            # Number of people in the cashier's line including the current person being helped
            custText = "Line: " + str(len(cashier.cashier_queue))
            self.text_box(custText, int(self.displayWidth * 2 / 3), 60, width=int(self.displayWidth / 6), height=25)

            # Cashier's chitchat levels
            chitText = "Chitchat: " + str(cashier.chatLevel)
            self.text_box(chitText, int(self.displayWidth / 3), 90, width=int(self.displayWidth / 6), height=25)

            # Empty box to make it look uniform
            self.text_box("", int(self.displayWidth / 2), 90, width=int(self.displayWidth / 6), height=25)
        # Mouse if not hovering over cashier
        else:
            # Print cashier object
            if not cashier.self_checkout:
                # Print normal cashier object
                pygame.draw.rect(self.screen, self.green, (x, y, 25, 25))
            else:
                # Print self checkout object
                pygame.draw.rect(self.screen, self.blue, (x, y, 25, 25))
        pass

    def print_final_cashier(self, x, y, num_cashiers, num_checkouts, num_custs):
        """ A final block to hold the unshown cashiers and self-checkouts

            Precondition:
            - x: The x-position of the block
            - y: The y-position of the block
            - num_cashiers: Total number of regular cashiers
            - num_checkouts: Total number of self-checkouts
            - num_custs: Total number of customers inside the cashiers' and
                self checkouts' lines

            Postcondition:
             Print a box at the specified coordinates that will tell the
                user about the number of cashiers, self checkouts, and customer's being
                helped when the user hovers over it.
        """

        # Get the mouse's position
        mouse = pygame.mouse.get_pos()

        # Is the mouse within the box's position
        if x + 25 > mouse[0] > x and y + 25 > mouse[1] > y:
            # Make a text box with the total number of cashiers and self checkouts
            self.text_box(str(num_cashiers + num_checkouts), x, y, 25, 25)

            # Display statistics about the remaining cashiers

            # Show the total number of normal cashiers
            helpedText = "Cashiers: " + str(num_cashiers)
            self.text_box(helpedText, int(self.displayWidth / 6), 60, width=int(self.displayWidth / 3), height=25)

            # Show the total number of self checkouts
            ipmText = "Self Checkouts: " + str(num_checkouts)
            self.text_box(ipmText, int(self.displayWidth / 2), 60, width=int(self.displayWidth / 3), height=25)

            # Show the total customers inside lines that are not shown
            itemText = "Customers: " + str(num_custs)
            self.text_box(itemText, int(self.displayWidth / 3), 90, width=int(self.displayWidth / 3), height=25)
        # The user isn't hovering over this box
        else:
            # Show a regular text box with details of how many cashiers and checkouts there are
            self.text_box(str(num_cashiers + num_checkouts), x, y, 25, 25)
        pass

    def print_line(self, x, y, cashier_queue=None):
        """ Prints the customer's in line for the cashier

            Precondition:
            - x: The starting x coordinate to print the customer's at
            - y: The starting y coordinate to print the customer's at
            - cashier_queue: The list of customers in line

            Postcondition:
            - Two seperate boxes. The first, which is right next to the cashier,
                shows the current customer being helped, and will slowly disappear over time as it's items
                are checked out. The second is a non interactable block that shows the number of customers
                in line for the current cashier
        """

        # Get the mouse's position
        mouse = pygame.mouse.get_pos()

        # Is the mouse within the confines of the first customer block?
        if x - 5 > mouse[0] > x - 30 and y + 25 > mouse[1] > y:
            # Only do something if there is at least one person in line
            if len(cashier_queue) > 0:
                # Draw a completely white cashier
                pygame.draw.rect(self.screen, (255, 255, 255),
                                 (x - 30, y, 25, 25))

                # Show the current number of item's the the customer has left on top
                itemsText = "Items Left: " + str(round(cashier_queue[0].number_of_items, 2))
                self.text_box(itemsText, int(self.displayWidth / 3), 60, width=int(self.displayWidth / 3), height=25)
        # Print a single customer block that disappears as the number of items it has goes down
        elif len(cashier_queue) > 0:
            # Set transparency by the number of items currently in the queue
            if cashier_queue[-1].number_of_items >= 0 and cashier_queue[-1].total_items > 0:
                # Block goes from white to black
                transparency = int(255 * cashier_queue[-1].number_of_items / cashier_queue[-1].total_items)
            else:
                # In case of weird input, show a completely white block
                transparency = 255
            # Draw a customer block
            try:
                pygame.draw.rect(self.screen, (transparency, transparency, transparency),
                             (x - 30, y, 25, 25))
            except Exception as E:
                pygame.draw.rect(self.screen, (255, 255, 255),
                                 (x - 30, y, 25, 25))
        # If there is more than 1 person in line
        if len(cashier_queue) > 1:
            # Draw a second square to represent the rest of the customers in line
            pygame.draw.rect(self.screen, (255, 255, 255),
                             (x - 30, y - 30, 25, 25))

            # Represent the number of people in line as a string
            lineText = str(len(cashier_queue) - 1)

            # Write these items to screen
            textSurf, textRect = self.textObj(lineText, self.smallFont, self.red)
            textRect.center = ((x - 30 + int(25 / 2)),
                               (y - 30 + int(25 / 2)))
            self.screen.blit(textSurf, textRect)

    def textObj(self, text, t_font, t_color):
        """ Used to get the necessary references to make and print text to screen

            Precondition:
            - text: A string to display; Numbers of any type must be passed through str()
            - t_font: The font to print this text in
            - t_color: The color to show this text with

            Postcondition:
            - The components to write text to screen
        """

        # Render the text using the specified font
        textSurface = t_font.render(text, True, t_color)

        # Return the render, and the rectangle so that people can modify it's location
        return textSurface, textSurface.get_rect()

    def text_box(self, text, x, y, width, height):
        """ Used to quickly display a solid rectangle with text inside of it

            Precondition:
            - text: Text to display; Must be of type string, pass numbers through
                str(number) conversion before sending it here
            - x: The x position of the rectangle and text on screen
            - y: The y position of the rectangle and text on screen
            - width: How wide the background rectangle should be; Does
                not effect the text
            - height: How long the background rectable should be; Does
                not effect the text
            Postcondition:
            - A simple text box on screen
        """

        # Draw a green rectangle
        pygame.draw.rect(self.screen, self.green,
                         (x, y,
                          width, height))

        # Render the text
        textSurf, textRect = self.textObj(text, self.smallFont, self.white)

        # Position the text inside the box
        textRect.center = ((x + (width / 2)),
                           (y + ((height) / 2)))

        # Write the text to screen
        self.screen.blit(textSurf, textRect)

if __name__ == '__main__':
    # Do not allow this function to be called as main.
    pass


"""class Car():
	def __init__(self, make, model, year):
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0

	def get_descriptive_name(self):
		long_name = str(self.year) + ' ' + self.make + ' ' + self.model + '.'
		return long_name
	def read_odometer(self):
		print("This car has " + str(self.odometer_reading) + " miles on it.")
	def update_odometer(self, mileage):
		#set the odometer reading to the given value

		'''set the odometer reading to the given value.
		Reject the changes if it attempts to roll the odometer back'''
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("You can't roll back an odometer!")

	def increment_odometer(self, miles):
		#add the given amount to the odometer reading
		self.odometer_reading += miles

my_used_car = Car('subaru', 'outback', 2013)
print(my_used_car.get_descriptive_name())

my_used_car.update_odometer(23500)
my_used_car.read_odometer()

my_new_car = Car('audi', 'a4', 2017)
print(my_new_car.get_descriptive_name())

my_used_car.increment_odometer(100)
my_used_car.read_odometer()
my_new_car.read_odometer()

my_new_car.update_odometer(23)
my_new_car.read_odometer()"""

class Car():
	def __init__(self, make, model, year):
		self.make = make
		self.model = model
		self.year = year
		self.speed = 280

	def compony_cars(self):
		full_name = str(self.year) + ' ' + self.make + ' ' + self.model
		return full_name
	def speed_limit(self):
		print("The new cars speed limit is " + str(self.speed))
	def update_speed(self, first):
		if first >= self.speed:
			self.speed = first
		else:
			print("You can't roll back ")
	def increment_speed(self, miles):
		self.speed += miles
my_used_car = Car('Subaru', 'outback', '2014')
print(my_used_car.compony_cars())
my_used_car.update_speed(490)
my_used_car.speed_limit()
my_used_car.update_speed(590)
my_used_car.speed_limit()

full_name = Car('isuzu', 'DMax', 2019)

print(full_name.compony_cars())
full_name.update_speed(480)
full_name.speed_limit()


# encoding = utf8

class Solution:
    # 返回从小到大顺序的列表
    # 冒泡排序
    def bubble_sort(self, a: list) -> list:
        for i in range(0, len(a)):
            for j in range(0, len(a) - 1 - i):
                if a[j] > a[j + 1]:
                    a[j], a[j + 1] = a[j + 1], a[j]
        return a

    # 选择排序
    def select_sort(self, a: list) -> list:
        for i in range(0, len(a)):
            for j in range(i + 1, len(a)):
                if a[i] > a[j]:
                    a[i], a[j] = a[j], a[i]
        return a

    # 插入排序
    def insert_sort(self, a: list) -> list:
        for i in range(1, len(a)):
            for j in range(i - 1, -1, -1):
                if a[j] > a[j + 1]:
                    a[j], a[j + 1] = a[j + 1], a[j]
        return a

    # 快速排序
    def quick_sort(self, a: list, low: int, high: int) -> list:
        if low < high:
            pivot = self.find_pivot(a, low, high)
            a = self.quick_sort(a, low, pivot - 1)
            a = self.quick_sort(a, pivot + 1, high)
        return a

    def find_pivot(self, a: list, low: int, high: int) -> int:
        tmp = a[low]
        while low < high:
            while low < high and tmp < a[high]:
                high -= 1
            a[low] = a[high]
            while low < high and a[low] < tmp:
                low += 1
            a[high] = a[low]
        a[low] = tmp
        return low

    # 希尔排序
    def shell_sort(self, a: list) -> list:
        gap = int(len(a) / 2)  # 初始步长
        while gap > 0:
            # 插入排序
            for i in range(gap, len(a)):
                j = i
                while j >= gap and a[j - gap] > a[j]:
                    a[j - gap], a[j] = a[j], a[j - gap]
            gap = int(gap / 2)
        return a

    # 归并排序
    def merge_sort(self, a: list, low: int, high: int) -> list:
        if low < high:
            mid = int((low + high) / 2)
            a = self.merge_sort(a, low, mid)
            a = self.merge_sort(a, mid + 1, high)
            a = self.merge(a, low, mid, high)
        return a

    def merge(self, a: list, low: int, mid: int, high: int) -> list:
        len1 = mid - low + 1
        len2 = high - mid
        list1 = a[low:mid + 1]
        list2 = a[mid + 1:high + 1]

        i, j, k = 0, 0, low

        while i < len1 and j < len2:
            if list1[i] < list2[j]:
                a[k] = list1[i]
                i += 1
            else:
                a[k] = list2[j]
                j += 1
            k += 1

        while i < len1:
            a[k] = list1[i]
            i += 1
            k += 1
        while j < len2:
            a[k] = list2[j]
            j += 1
            k += 1

        return a

if __name__ == '__main__':
    object = Solution()
    a = [1, 8, 3, 5, 4, 7, 9, 0, 2, 6]
    a = object.merge_sort(a, 0, 9)
    print(a)


import cv2

contours, hierarchy = cv.findContours(img_binary, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

# iterate contour and draw
for cnt in contours:
  cv2.drawContours(img, contours, -1, (0,0,255), 1)

# calculate contour area
area = cv.contourArea(cnt)

# approximate contour
epsilon = 0.02 * cv.arcLength(cnt, True)
approx = cv.approxPolyDP(cnt, epsilon, True)

# calculate contour center
for cnt in contours:
    M = cv.moments(cnt)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    cv.circle(img_color, (cx, cy), 10, (0,0,255), -1)

# Get bounding rectangle
x, y, w, h = cv.boundingRect(cnt)

# Get rotated rectangle
rect = cv.minAreaRect(cnt)
box = cv.boxPoints(rect)
box = np.int0(box)

# get convex hull shape
hull = cv.convexHull(cnt)

# Convexity defects
hull = cv.convexHull(cnt, returnPoints = False)
defects = cv.convexityDefects(cnt, hull)

# minimum enclosing circle
(x,y), radius = cv2.minEnclosingCircle(cnt)
center=(int(x), int(y))
radius=int(radius)

# fitting an ellipse
ellipse = cv2.fitEllipse(cnt)
img=cv2.ellipse(img, ellipse, (0,255,0),2)

# fitting a line
[vx,vy,x,y] = cv2.fitLine(max_contour,cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((img_gray.shape[1]-x)*vy/vx)+y)
PT1 = (0,lefty)
PT2 = (img_gray.shape[1]-1,righty)