#!/usr/bin/env python3

import argparse
import subprocess as sp
import multiprocessing as mp
import socket
import os
import time
import sys
from threading import Thread
from time import sleep
import tempfile

__doc__ = """This wrapper will execute Exonerate queries by first pre-loading the exonerate database into memory.
As this allows to use multi-threading AND a precomputed index, it should cut down computing times massively."""

class ExoStreamThread(Thread):

    def __init__(self, buffer, out_handle):
        Thread.__init__(self)
        self.buffer = buffer
        self.out = out_handle
        self.__listening = False
        self.__exit = False

    def run(self):

        while 1:
            line = self.buffer.readline().decode()
            print(line, end="", file=self.out)
            if "listening on port" in line:
                self.__listening = True
            if self.__exit is True:
                break
        # self.join()

    @property
    def listening(self):
        return self.__listening

    def send_exit(self):
        self.__exit = True

def get_open_port():
    # StackOverflow source: https://goo.gl/SrPDqh
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 0))
    s.listen(1)
    port = s.getsockname()[1]
    # s.close()
    return s, port

def percent(string: str):
    if not string.isdigit():
        raise ValueError("Invalid percent type")
    string = float(string)
    if not 0 < string <= 100:
        raise ValueError("Invalid percent, it should be between 0 and 100")
    return int(round(string, 0))

def pos(string: str):
    if not string.isdigit():
        raise ValueError
    string = int(string)
    if not string > 0:
        raise ValueError
    return string

def main():
    # Keep all data on local disks.
    # Apply the highest acceptable score thresholds using a combination of --score, --percent and --bestn.
    # Repeat mask and dust the genomic (target) sequence. (Softmask these sequences and use --softmasktarget).
    # Increase the --fsmmemory option to allow more query multiplexing.
    # Increase the value for --seedrepeat
    # When using an alignment model containing introns, set --geneseed as high as possible.
    # If you are compiling exonerate yourself, see the README file supplied with the source code for details of compile-time optimisations.

    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument("-t", "--threads", default=mp.cpu_count(), type=int)
    parser.add_argument("-M", "--memory", default=2000, type=float)
    parser.add_argument("-g", "--geneseed", default=250, type=pos)
    parser.add_argument("--bestn", default=10, type=pos)
    parser.add_argument("--hspfilter", default=100, type=int)
    parser.add_argument("--percent", type=percent, default=30)
    parser.add_argument("--score", type=percent, default=50)
    parser.add_argument("--serverlog", required=True)
    parser.add_argument("--log", required=True)
    parser.add_argument("-ir", "--intron-range", dest="intron_range", nargs=2, type=pos, required=True)
    parser.add_argument("genome")
    parser.add_argument("query")
    parser.add_argument("outfile")
    args = parser.parse_args()

    args.memory = abs(int(round(args.memory, 0)))
    args.hspfilter = abs(args.hspfilter)

    if not args.genome.endswith(".esi"):
        raise ValueError("This wrapper requires a compiled genome!")

    args.intron_range = sorted(args.intron_range)
    assert args.intron_range[0] != args.intron_range[1]

    sock, port = get_open_port()
    log = args.serverlog
    server_cmd = "exonerate-server --preload --maxconnections {args.threads} "
    server_cmd += " --port {port} --input {args.genome}"
    server_cmd = server_cmd.format(**locals())
    sock.close()
    print("Starting the server on port {port}".format(**locals()), file=sys.stderr)
    server = sp.Popen(server_cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
    log_handle = open(log, "wt")
    stderr = ExoStreamThread(server.stderr, log_handle)
    stdout = ExoStreamThread(server.stdout, log_handle)
    stderr.start(), stdout.start()

    while not any(_.listening is True for _ in [stderr, stdout]):
        sleep(1)

    # print(server_cmd)
    children = []
    # Use one LESS thread for aligning
    threads = max(args.threads - 1, 1)
    logs = []
    outputs = []
    for thread in range(1, threads + 1):

        output = tempfile.NamedTemporaryFile(mode="wt", suffix=".txt", delete=True)
        log = tempfile.NamedTemporaryFile(mode="wt", suffix=".log", delete=True)
        print(output.name, file=sys.stderr)
        logs.append(log)
        outputs.append(output)
        memory = args.memory / args.threads
        cmd = "exonerate --model protein2genome --showtargetgff yes --showvulgar yes "
        # Specify the chunk number
        cmd += " --querychunkid {thread} --querychunktotal {threads} "
        min_intron, max_intron = args.intron_range
        # INCREASE THE MEMORY!
        cmd += " -M {memory} -D {memory}"
        # Experimental
        if args.hspfilter:
            cmd += " --hspfilter {args.hspfilter} "

        cmd += " --softmaskquery yes --softmasktarget yes --bestn {args.bestn} --minintron {min_intron} "
        cmd += " --maxintron {max_intron} --showalignment no "
        # These options have to be TAILORED, otherwise it will take forever!
        cmd += " --geneseed {args.geneseed} --percent {args.percent} --score {args.score} "
        cmd += " --query {args.query} --target localhost:{port} "
        cmd += " --ryo \">%qi\\tlength=%ql\\talnlen=%qal\\tscore=%s\\tpercentage=%pi\\nTarget>%ti\\tlength=%tl\\talnlen=%tal\\n\" "
        cmd = cmd.format(**locals())
        print(cmd, file=sys.stderr)
        child = sp.Popen(cmd, shell=True, stdout=output, stderr=log)
        children.append(child)

    statuses = [None for _ in range(threads)]
    while any(_ is None for _ in statuses):
        statuses = [_.poll() for _ in children]
        time.sleep(1)

    server.terminate()
    stderr.send_exit()
    stdout.send_exit()

    # Merge log files
    [log.flush() for log in logs]
    with open(args.log, "at") as final_log:
        sp.call(["cat"] + [log.name for log in logs], stdout=final_log)
        final_log.flush()
    [log.close() for log in logs]

    if any(_ != 0 for _ in statuses):
        print("Error in executing exonerate. Please check the logs.", file=sys.stderr)
        sys.exit(1)

    [output.flush() for output in outputs]
    with open(args.outfile, "wt") as out:
        sp.call(["cat"] + [output.name for output in outputs], stdout=out)
    [output.close() for output in outputs]

    # Merge output files

    sys.exit(0)

if __name__ == "__main__":
    main()


import os
import shutil
import logging

train_list = ['train/hum/0703.mp3',
'train/hum/2685.mp3',
'train/hum/2735.mp3',
'train/hum/2677.mp3',
'train/hum/2602.mp3',
'train/hum/2570.mp3',
'train/hum/1914.mp3',
'train/hum/1927.mp3',
'train/hum/1320.mp3',
'train/hum/2244.mp3',
'train/hum/1318.mp3',]
public_test_list = ['public_test/hum/0413.mp3']
private_test_list = []

def copy_fail_cleaning_data(src_path="raw_path", dst_path = "temp_dir", list_type="all"):
    if list_type == "all":
        fail_list = train_list + public_test_list
    elif list_type == "public_test":
        fail_list = public_test_list
    elif list_type == "private_test":
        fail_list = private_test_list
    else:
        fail_list = []

    for file in fail_list:
        if not os.path.isfile(os.path.join(src_path, file)):
            logging.warn(f"Not found {os.path.join(src_path, file)}")
            continue
        print(f"Copy {os.path.join(src_path, file)} to {os.path.join(dst_path, file)}")
        shutil.copyfile(os.path.join(src_path, file),
                        os.path.join(dst_path, file))

        if file.split("/")[0] == "train":
            song = os.path.join(file.split("/")[0], "song", file.split("/")[-1])
            shutil.copyfile(os.path.join(src_path, song),
                            os.path.join(dst_path, song))


""" Custom Validators """

from rest_framework.exceptions import APIException
from django.utils.encoding import force_str
from django.contrib.auth.models import User
from LetsRide.utility.helpers import ERROR_CODE
from rest_framework.validators import UniqueTogetherValidator
from rest_framework import status

class CustomValidation(APIException):
    """
    Custom Validator for raising exception in some manner (used whole application).
    """

    status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
    default_detail = ERROR_CODE['global_error']['something_wrong']

    def __int__(self, detail, status_code, field='detail'):
        if status_code is not None:
            self.status_code = status_code

        if detail is not None:
            self.detail = {field: force_str(detail)}
        else:
            self.detail = {'detail': force_str(self.default_detail)}

USER_UNIQUE_FIELD_VALIDATOR = [
    UniqueTogetherValidator(
        queryset=User.objects.all(),
        fields=['email'],
        message=ERROR_CODE['user']['already_register']
    )
]


# CD
# 실버 5
# https://www.acmicpc.net/problem/4158
# 나의 풀이
# 0 0 을 입력받는 조건을 해결하지 못함, 시간 초과
# import sys
# sys.setrecursionlimit(10**6)

# while True:
#   answer = 0
#   N, M = map(int, sys.stdin.readline().strip().split(' '))

#   if N == 0 and M == 0:
#     break

#   A, B = [], []

#   for _ in range(N):
#     A.append(int(sys.stdin.readline().strip()))

#   for _ in range(M):
#     B.append(int(sys.stdin.readline().strip()))

#   def binary_search(arr, val):
#     first, last = 0, len(arr) - 1

#     while first <= last:
#       mid = (first + last) // 2

#       if arr[mid] == val:
#         return mid
#       elif arr[mid] < val:
#         first = mid + 1
#       else:
#         last = mid - 1

#     return -1

#   for a in A:
#     if binary_search(B, a) >= 0:
#       answer += 1

# 나의 풀이 2
# import sys

# while (1):
#     N, M = map(int, sys.stdin.readline().split())
#     if N == 0 and M == 0:
#         break

#     A = [int(sys.stdin.readline()) for _ in range(N)]
#     B = [int(sys.stdin.readline()) for _ in range(M)]
#     answer = 0

#     cd = dict()

#     for a in A:
#         cd[a] = 1

#     for b in B:
#         if b in cd:
#             cd[b] = 0
#         else:
#             cd[b] = 1

#     answer = dict(filter(lambda x : x[1] == 0, cd.items()))
#     print(len(answer))

# 나의 풀이 3 : 나의 풀이 2를 좀 더 심플하게
# 왜 얘는 시간 초과?
# import sys

# while True:
#     N, M = map(int, sys.stdin.readline().split())
#     if N == 0 and M == 0:
#         break

#     cd = dict()
#     answer = 0

#     for _ in range(N):
#         cd[int(input())] = True

#     for _ in range(M):
#         if int(input()) in cd.keys():
#             answer += 1

#     print(answer)

# 다른 사람의 풀이
import sys
from collections import defaultdict
input = sys.stdin.readline

while True:
    cd = defaultdict(bool)
    n, m = map(int, input().split())
    cnt = 0

    if n == 0 and m == 0:
        break

    for _ in range(n):
        cd[int(input())] = True

    for _ in range(m):
        if cd[int(input())]:
            cnt += 1

    print(cnt)


#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる
import numpy as np

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

N = int(input())
pos = {
    "U":[],
    "R":[],
    "D":[],
    "L":[]
    }
xyu =[]
for i in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    u = str(u)
    xyu.append([x,y,u])

direction = {
    "U":[0,1],
    "D":[0, -1],
    "R":[1, 0],
    "L":[-1,0]
}
directions = np.zeros((N, 2))
positions = np.zeros((N, 2))
for i, (x, y, u) in enumerate(xyu):
    if u == "U":
        directions[i, 1] = 1
    elif u == "D":
        directions[i, 1] = -1
    elif u == "R":
        directions[i, 0] = 1
    else:
        directions[i, 0] = -1
    positions[i, 0] = x
    positions[i, 1] = y

ans = -1
for time in range(1, 200000):
    positions += directions
    positions.tolist()

    if len(set(positions.tolist())) < N:
        ans = time
        break
if ans == -1:
    print("SAFE")
else:
    print(ans)


import os
from pathlib import Path

SUBDIRECTORIES = {
    "DOCUMENTS": ['.pdf','.rtf','.txt'],
    "AUDIO": ['.m4a','.m4b','.mp3'],
    "VIDEOS": ['.mov','.avi','.mp4'],
    "IMAGES": ['.jpg','.jpeg','.png']
}

def pickDirectory(value):
    for category, suffixes in SUBDIRECTORIES.items():
        for suffix in suffixes:
            if suffix == value:
                return category
    return 'MISC'

print(pickDirectory('.pdf'))

def organizeDirectory():
    for item in os.scandir():
        # we skip the directories & we take just files
        if item.is_dir():
            continue
        filePath = Path(item)
        filetype = filePath.suffix.lower()
        directory = pickDirectory(filetype)
        directoryPath = Path(directory)
        # check if directory exist, if not we create it
        if directoryPath.is_dir() != True:
            directoryPath.mkdir()
        # we move the file inside the right directory
        filePath.rename(directoryPath.joinpath(filePath))


from sys import stdin

t1 = int(input())

while t1:
    t1 -= 1
    m = int(input())
    a = [int(x) for x in stdin.readline().split()]
    coins = [0] * (len(a)+1)
    for  i in range(1,len(a)+1):
        coins[i] = a[i-1]
    res = sum(a)
    dp = [[0] * (res+1) for _ in range(m+1)]
    for i in range(1, m + 1):
        for j in range(res//2 + 1):

            if j >= coins[i]:
                dp[i][j] = max(dp[i-1][j],coins[i] + dp[i - 1][j - coins[i]])
            else:
                dp[i][j] = dp[i-1][j]

    print(res - 2 * dp[m][res//2])

CP problems/Big-O/Dynamic Programming/Dividing coins.py


import os

codes = {
    "reset": "\u001b[0m",
    "black": "\u001b[30m",
    "red": "\u001b[31m",
    "green": "\u001b[32m",
    "light_yellow": "\u001b[93m",
    "yellow": "\u001b[33m",
    "yellow_background": "\u001b[43m",
    "blue": "\u001b[34m",
    "purple": "\u001b[35m",
    "cyan": "\u001b[36m",
    "white": "\u001b[37m",
    "bold": "\u001b[1m",
    "unbold": "\u001b[21m",
    "underline": "\u001b[4m",
    "stop_underline": "\u001b[24m",
    "blink": "\u001b[5m"
}

def formatter(msg, pre):
    post = codes["reset"]
    return u"{pre}{msg}{post}".format(**{
        'pre': pre,
        'msg': msg,
        'post': post
    })

def rojo(msg):
    return formatter(msg, codes["red"])

def verde(msg):
    return formatter(msg, codes["green"])

def azul(msg):
    return formatter(msg, codes["blue"])

if __name__ == "__main__":
    os.system("color")
    for code in codes:
        print(formatter(f"este es el color {code}", codes[code]))
        print("-----------------------------------------")


"""Property.

fget: metodu isaret eder
fset: metodu isaret eder
fdel: metodu silmeyi isaret eder
doc: yorum/aciklamayi isaret eder

Syntactic Sugar -> Biz Developerlarin daha kolay kod yazmamiza izin veren bir sozdizimidir.
Bu sozdizimi arkaplanda sistemin nasil calismasini bilmeme luksunu tanir. Bu yapi sadece Python ile sinirli
degildir.
"""

class Kullanici:
    __kAdi = None

    def __init__(self, kAdi):
        # nesneye gonderilen ilk degeride bu sayede kontrol edebiliyoruz
        self.kAdi = kAdi

    @property
    def kAdi(self): # genelde method ismine private degisken ismini veririz
        return self.__kAdi

    @kAdi.setter # buradaki isim ile(kAdi) set methodunun da ismi ayni olmalidir.
    def kAdi(self, kAdi):
        if(len(kAdi) > 3):
            self.__kAdi = kAdi
        else:
            raise ValueError('Kullanici Adi 3 Karakterden Buyuk Olmalidir!')

    # def getKAdi(self):
    #     return self.__kAdi

    # def setKAdi(self, kAdi):
    #     if(len(kAdi) > 3):
    #         self.__kAdi = kAdi
    #     else:
    #         raise ValueError('Kullanici Adi 3 Karakterden Buyuk Olmalidir!')

    # k_adi = property(getKAdi, setKAdi)

k = Kullanici('Osman')
k.kAdi = 'Veli'
print(k.kAdi)
# k.setKAdi('Mehmet')
# print(k.getKAdi())


#CHANTAL DE GRACIA, DANIELA MOSCOSO
from sympy import *
i = 0
x = symbols('x') #La funcion establece un símbolo que se le asigna a una variable.
print('INSERTAR FUNCION: ')
y = sympify(input()) #La funcion sympify convierte strings a expresiones SYMPY
c = float(input('Valor inicial: '))
print("FUNCION : {} ".format(y))

y_derivada = Derivative(y, x) #

print(f"DERIVADA : {y_derivada.doit()} ")

#CICLO DE REPETICION PARA LAS ITERACIONES
while(abs(y.evalf(subs={x:c}))>0.0000000001):
  i = i + 1 #CONTADOR ITERACIONES
  a = y.evalf(subs={x:c}) #EVALUACION DE DE LA FUNCION CON EL VALOR INICIAL SUBSTITUIDO
  b = y_derivada.doit().evalf(subs={x:c}) #EVALUACION DE LA FUNCION DERIVADA CON EL VALOR INICIAL SUBSTITUIDO
  #print(a)
  #print(b)
  c = c - a/b #CALCULO DE LA FORMULA
  print("Iteracion #" + str(i) + ": ")
  print('{:.5f}'.format(c))


import time

from n3 import *

class DummyImageClassification(Trainer):
    def train(self, kwargs):
        self._writer.attach_rust_kwargs(kwargs)

        self.model.train()
        self.optimizer._initialize(self.model)

        data = iter(self.data.get_train_dataset())
        x, y = next(data)

        self.optimizer.zero_grad()
        y_pred = self.model(x=x)
        loss = self.loss(**y_pred, y=y)['x']
        loss.backward()

        self._train_end()

    def eval(self, kwargs):
        raise NotImplementedError


# 等额本金和等额本息贷款计算

import math

area = float(input('请输入房屋面积(m^2): '))
unit_price = float(input('请输入单价(元): '))
year_interest = float(input('请输入贷款利率(%): '))

# '''
# 等额本金的每月还款情况文件，格式如下：
# 1月,5700.79(元)
# 2月,5691.69(元)
# 3月,5682.59(元)
# 4月,5673.5(元)
# ......
#
# '''
#
#
# # 读取文件内容，即每个月的还款数据
# def get_average_capital():
#     file_path = input('请输入等额本金文件路径: ')
#     average_capital_data = []
#     file_object = open(file_path, 'r')
#     try:
#         for line in file_object:
#             average_capital_data.append(float(line[line.find(',') + 1:line.find('(')]))
#     finally:
#         file_object.close()
#     print(average_capital_data)
#     return average_capital_data

'''
等额本金还款法:
设：A=贷款额 B=贷款月利率 C=贷款月数 D=每月还款额 E=还款利息总和
每月应还本金=贷款额÷还款月数=A÷C
第一月还款利息=剩余本金×月利率=A×B
第二月还款利息:(贷款额-第一月已归还本金额)×月利率=(A-A÷C)×B
第三月还款利息:(A-2×A÷C)×B
...
第C月还款利息:(A-(C-1)×A÷C)×B
求以上和得E=B(AC-[A+2A+3A+...+(C-1)A]÷C)=B(AC-A(C-1)÷2)=A×B×(C+1)÷2
每n月还款:D=本金+第n月利息=A÷C+(A-(n-1)×A÷C)×B=(1+B(C-n+1))×A÷C
'''

def get_average_capital():
    average_capital_data = []
    for i in range(0, 360):
        average_capital_data.append((loan / 360) + ((loan - loan * i / 360) * (year_interest / (12 * 100))))
    return average_capital_data

# 等额本金计算，默认30年
def prepayment_average_capital(year=30):
    arr_float = get_average_capital()
    count = 0
    pay = 0
    # pay = loan - (year / 30) * loan
    for i in arr_float:
        pay += i
        count += 1
        if count == year * 12:
            break
    return pay

'''
等额本息还款法：
设：A=贷款额 B=贷款月利率 C=贷款月数 D=每月还款额 E=还款利息总和
第一月还款利息为【贷款额×月利率】：A×B
第二月还款利息为【[贷款额-第一个月已还本金]×月利率】：〔A－（D－A×B）〕×B＝（A×B－D）×（1＋B）^1＋D
第三月还款利息为：｛A－（D－A×B）－〔D－（A×B－D）×（1＋B）^1－D〕｝×B＝（A×B－D）×（1＋B）^2＋D
第四月还款利息为：＝（A×B－D）×（1＋B）^3＋D
.....
第C月还款利息为：＝（A×B－D）×（1＋B）^（C－1）＋D
求以上和为：E＝（A×B－D）[（1＋B）^0+（1＋B）^1+...+（1＋B）^（C－1）]+C×D=（A×B－D）×〔（1＋B）^C－1〕÷B＋C×D
而利息总和E＝C×D－A，两项E值相等求得
月均还款:D＝A×B×（1＋B）^C÷〔（1＋B）^C－1〕
支付利息总和:E＝C×D-A=C×A×B×（1＋B）^C÷〔（1＋B）^C－1〕－A
还款总额:E+A=C×A×B×（1＋B）^C÷〔（1＋B）^C－1〕

附注:a^b表示a的b次方。
'''

# 等额本息计算，默认30年

def prepayment_average_capital_plus_interest(year=30):
    # pay = loan - (year / 30) * loan
    pay = 0
    month_interest = year_interest / (12 * 100)
    month_pay = (loan * month_interest * math.pow((1 + month_interest), 360)) / (
        math.pow((1 + month_interest), 360) - 1)
    for i in range(1, year * 12 + 1):
        pay += month_pay
    return pay

total = unit_price * area
loan = int((total - total * 0.3) / 10000) * 10000
first_pay = total - loan

print('房屋总价:', total, '贷款额:', loan, '首付款:', first_pay)

print("===============等额本金已还款总额(本金+利息)================")
for j in range(1, 31):
    # print(first_pay + prepayment_average_capital(j), first_pay + prepayment_average_capital_plus_interest(j), total)
    print(first_pay + prepayment_average_capital(j))

print("===============等额本息已还款总额(本金+利息)=================")
for k in range(1, 31):
    print(first_pay + prepayment_average_capital_plus_interest(k))

print("===============等额本息已还款总额-等额本金已还款总额======")
for m in range(1, 31):
    print(prepayment_average_capital_plus_interest(m) - prepayment_average_capital(m))

print("===============一次性还清剩余贷款本金======")
for n in range(1, 31):
    print(loan - (n / 30) * loan)

print("===============总房价=================")
for l in range(1, 31):
    print(total)

print("===============等额本金总还款额======")
for o in range(1, 31):
    t1 = first_pay + prepayment_average_capital(o)
    t2 = loan - (o / 30) * loan
    print(t1 + t2)

print("===============等额本息总还款额======")
for p in range(1, 31):
    t1 = first_pay + prepayment_average_capital_plus_interest(p)
    t2 = loan - (p / 30) * loan
    print(t1 + t2)
# # 输入年份计算等额本金已经付给银行的钱，默认15年(提前还)
# prepayment_average_capital_data = prepayment_average_capital()
# # 输入年份计算等额本息已经付给银行的钱，默认15年(提前还)
# prepayment_average_capital_plus_interest_data = prepayment_average_capital_plus_interest()
#
# print('等额本金总耗资：', first_pay + prepayment_average_capital_data)
# print('等额本息总耗资：', first_pay + prepayment_average_capital_plus_interest_data)
# print('少还利息：', prepayment_average_capital_plus_interest_data - prepayment_average_capital_data)


# -*- coding: utf-8 -*-
import findspark
import gc
from joblib import dump, load
import numpy as np
findspark.init()
from pyspark.sql import SparkSession
from pyspark.sql.types import StructField, StructType, LongType, StringType, IntegerType
import pyspark.sql.functions as F
from pyspark import SparkContext, SparkConf
from pyspark.serializers import PickleSerializer
from tqdm import tqdm
from itertools import permutations
from collections import defaultdict
import time

# conf = SparkConf(serializer=PickleSerializer())
spark = SparkSession.builder.appName("user cf on spark").master("local[8]").config('serializer', PickleSerializer()).getOrCreate()

sc = spark.sparkContext

schema = StructType([StructField('userId', IntegerType(), True),
            StructField('movieId', IntegerType(), True),
            StructField('rating', LongType(), True),
            StructField('timestamp', IntegerType(), True)])
ratings = spark.read.csv(r'D:\Users\hao.guo\比赛代码提炼\推荐系统\movielen\ml-20m\ratings.csv', header=True)

ratings = ratings.withColumn('rating', ratings['rating'].cast('int'))
ratings_rdd = ratings.select(['userId', 'movieId', 'rating']).rdd
# ratings_rdd = ratings_rdd.sample(withReplacement=False, fraction=0.1, seed=2020)
train_rdd, test_rdd = ratings_rdd.randomSplit([0.7, 0.3], seed=2020)
train_rdd = train_rdd.cache()
test_rdd = test_rdd.cache()

print('user cf start......')
s = time.perf_counter()

createCombiner = lambda v: [v]
mergeValue = lambda agg, v: agg + [v]
mergeCombiners = lambda agg1, agg2: agg1 + agg2
train_item_users = train_rdd.map(lambda s: ('item_' + s['movieId'], ('user_' + s['userId'], s['rating']))).combineByKey(createCombiner, mergeValue, mergeCombiners)
train_user_norm_dict = train_rdd.map(lambda s: ('user_' + s['userId'], s['rating'] ** 2)).reduceByKey(lambda p1, p2: p1 + p2).mapValues(lambda v: np.sqrt(v)).collectAsMap()

train_user_norm_dict = sc.broadcast(train_user_norm_dict)

'''
        获得2个用户所有的item-item对得分组合:
        (user1_id,user2_id) -> [(rating1,rating2),
                                (rating1,rating2),
                                (rating1,rating2),
                                ...]
'''
def findpairs(pairs):
    res = []
    # 考虑热门物品的影响, 冷门的物品兴趣才更加有把握相似
    m = len(pairs)
    for u1, u2 in permutations(pairs, 2):
        res.append(((u1[0], u2[0]), (u1[1] / np.log1p(m), u2[1] / np.log1p(m))))
    return res
pairwise_users = train_item_users.filter(lambda p: len(p[1]) > 1).map(lambda p: p[1]).flatMap(lambda p: findpairs(p)).combineByKey(createCombiner, mergeValue, mergeCombiners)

'''
    计算余弦相似度，找到最近的N个邻居:
    (user1,user2) ->    (similarity,co_raters_count)
'''

def cosine(product, r1_norm, r2_norm):
    fenmu = r1_norm * r2_norm
    return product / fenmu if fenmu else 0.0

def calcSim(pairs, user_norm_dict):
    '''
        对每个user对，根据打分计算余弦距离，并返回共同打分的item个数
    '''
    # 其他位置为0
    sum_xy, n = 0.0, 0

    for rating_pair in pairs[1]:
        sum_xy += rating_pair[0] * rating_pair[1]
        n += 1

    cos_sim = cosine(sum_xy, user_norm_dict[pairs[0][0]], user_norm_dict[pairs[0][1]])
    return pairs[0], (cos_sim, n)

def keyOnFirstUser(pairs):
    '''
        对于每个user-user对，用第一个user做key(好像有点粗暴...)
    '''
    (user1_id, user2_id) = pairs[0]
    return user1_id,(user2_id, pairs[1])

def nearestNeighbors(pairs, n):
    '''
        选出相似度最高的N个邻居
    '''
    pairs[1].sort(key=lambda x: x[1][0], reverse=True)
    return pairs[0], pairs[1][:n]

def user_sim(pairwise_users, train_user_norm_dict, n):
    user_sims = pairwise_users.map(lambda p: calcSim(p, train_user_norm_dict.value)).map(keyOnFirstUser).combineByKey(createCombiner, mergeValue, mergeCombiners).map(lambda p: nearestNeighbors(p, n))
    return user_sims

'''
    对每个用户的打分记录整理成如下形式
    user_id -> [(item_id_1, rating_1),
                [(item_id_2, rating_2),
                ...]
'''

train_user_items = sc.broadcast(train_rdd.map(lambda s: ('user_' + s['userId'], ('item_' + s['movieId'], s['rating']))).combineByKey(createCombiner, mergeValue, mergeCombiners).collectAsMap())

'''
    为每个用户计算Top N的推荐
    user_id -> [item1,item2,item3,...]
'''
def topNRecommendations(user_id, user_sims, users_with_rating, n):
    '''
        根据最近的N个邻居进行推荐
    '''

    totals = defaultdict(int)
    sim_sums = defaultdict(int)

    user_items = users_with_rating.get(user_id, [])
    if user_items != []:
        user_items = [i for i, r in user_items]

    for ind, (neighbor,(sim,count)) in enumerate(user_sims):

        # 遍历邻居的打分
        unscored_items = users_with_rating.get(neighbor,None)

        if unscored_items:
            for (item,rating) in unscored_items:
                if item not in user_items:

                # 更新推荐度和相近度
                    totals[item] += sim * rating
                    sim_sums[item] += sim

    # 归一化
    # scored_items = [(total/(1e-10 if sim_sums[item] == 0 else sim_sums[item]), item) for item,total in totals.items()]
    scored_items = [(total, item) for item,total in totals.items()]

    # 按照推荐度降序排列
    scored_items.sort(reverse=True)

    # 推荐度的item
    ranked_items = [x[1] for x in scored_items]

    return user_id, ranked_items[:n]

def Precision(user_id, pui, test, n):
    hit = 0
    all = 0
    tui = test[user_id]
    for item in pui:
        if item in tui:
            hit += 1
    all += n
    return (hit, all)

def Recall(user_id, pui, test):
    hit = 0
    all = 0
    tui = test[user_id]
    for item in pui:
        if item in tui:
            hit += 1
    all += len(tui)
    return (hit, all)

def Coverage(user_id, pui, train_items, test):
    recommend_items = set()
    all_items = set()
    tui = test[user_id]
    for item, rating in train_items[user_id]:
        all_items.add(item)
    for item in pui:
        recommend_items.add(item)
    return recommend_items, all_items

def Popularity(user_id, pui, item_popularity):
    ret = 0
    n = 0
    for item in pui:
        ret += np.log1p(item_popularity[item])
        n += 1
    return ret, n

def popularity(pairs):
    popular = set()
    for user, rating in pairs[1]:
        popular.add(user)
    return pairs[0], len(popular)

item_popularity = sc.broadcast(train_item_users.map(popularity).collectAsMap())

def eval(user_sims, item_popularity, train_user_items, test, n):
    user_item = test.map(lambda s: ('user_' + s['userId'], 'item_' + s['movieId'])).combineByKey(createCombiner, mergeValue, mergeCombiners)
    user_item_hist = user_item.collectAsMap()
    test_users = list(user_item_hist.keys())
    test_users_items = sc.broadcast(user_item_hist)

    '''
        为每个用户计算Top N的推荐
        user_id -> [item1,item2,item3,...]
    '''
    # choose test recs
    user_item_recs = user_sims.filter(lambda p: p[0] in test_users).map(
        lambda p: topNRecommendations(p[0], p[1], train_user_items.value, n)).cache()

    # precision
    hit, all = user_item_recs.map(lambda p: Precision(p[0], p[1], test_users_items.value, n)).reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]))
    p = hit / (all * 1.0)
    # recall
    hit, all = user_item_recs.map(lambda p: Recall(p[0], p[1], test_users_items.value)).reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]))
    r = hit / (all * 1.0)
    # Coverage
    recommend_items, all_items = user_item_recs.map(lambda p: Coverage(p[0], p[1], train_user_items.value, test_users_items.value)).reduce(lambda x, y: (x[0].union(y[0]), x[1].union(y[1])))
    c = len(recommend_items) / (len(all_items) * 1.0)
    # popularity
    recom_popularity, all = user_item_recs.map(lambda p: Popularity(p[0], p[1], item_popularity.value)).reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]))
    popularity = recom_popularity / (all * 1.0)
    del user_item_recs, user_item, user_item_hist, test_users, test_users_items
    gc.collect()
    return p, r, c, popularity

# 生成训练集各用户的相似矩阵
user_sims = user_sim(pairwise_users, train_user_norm_dict, 5)
print('eval model start......')
p5, r5, c5, popularity5 = eval(user_sims, item_popularity, train_user_items, test_rdd, 50)
print('top 5 model: %s, %s, %s, %s' % (p5, r5, c5, popularity5))
del user_sims
gc.collect()

user_sims = user_sim(pairwise_users, train_user_norm_dict, 10)
p10, r10, c10, popularity10 = eval(user_sims, item_popularity, train_user_items, test_rdd, 50)
print('top 10 model: %s, %s, %s, %s' % (p10, r10, c10, popularity10))
del user_sims
gc.collect()

user_sims = user_sim(pairwise_users, train_user_norm_dict, 20)
p20, r20, c20, popularity20 = eval(user_sims, item_popularity, train_user_items, test_rdd, 50)
print('top 20 model: %s, %s, %s, %s' % (p20, r20, c20, popularity20))
del user_sims
gc.collect()

user_sims = user_sim(pairwise_users, train_user_norm_dict, 40)
p40, r40, c40, popularity40 = eval(user_sims, item_popularity, train_user_items, test_rdd, 50)
print('top 40 model: %s, %s, %s, %s' % (p40, r40, c40, popularity40 ))
del user_sims
gc.collect()

user_sims = user_sim(pairwise_users, train_user_norm_dict, 80)
p80, r80, c80, popularity80 = eval(user_sims, item_popularity, train_user_items, test_rdd, 50)
print('top 80 model: %s, %s, %s, %s' % (p80, r80, c80, popularity80))
del user_sims
gc.collect()
print('cost time %s min' % ((time.perf_counter() - s) / 60))


'''Goal Parser Interpretation'''
def interpret(s):
    mapped = {'G':'G','()':'o','(al)':'al'}
    tmp = ''
    res = ''
    for i in s:
        tmp += i
        if tmp in mapped:
            res += mapped[tmp]
            tmp = ''
    return res
print(interpret("G()(al)"))


#coding=utf-8

from PyQt5.QtCore import QAbstractListModel, Qt, QModelIndex, QVariant, QSize
from PyQt5.QtGui import QIcon, QFont

class ListModel(QAbstractListModel):
    def __init__(self,data):
        super().__init__()
        self.ListItemData = data

    def data(self, index, role):
        if index.isValid() or (0 <= index.row() < len(self.ListItemData)):
            if role == Qt.DisplayRole:
                return QVariant(self.ListItemData[index.row()]['name'])
            elif role == Qt.DecorationRole:
                return QVariant(QIcon(self.ListItemData[index.row()]['iconPath']))
            elif role == Qt.SizeHintRole:
                return QVariant(QSize(70,80))
            elif role == Qt.TextAlignmentRole:
                return QVariant(int(Qt.AlignHCenter|Qt.AlignVCenter))
            elif role == Qt.FontRole:
                font = QFont()
                font.setPixelSize(20)
                return QVariant(font)
        else:
            return QVariant()

    def rowCount(self, parent = QModelIndex()):
        return len(self.ListItemData)

    def addItem(self, itemData):
        if itemData:
            self.beginInsertRows(QModelIndex(), len(self.ListItemData), len(self.ListItemData) + 1)
            self.ListItemData.append(itemData)
            self.endInsertRows()

    def deleteItem(self, index):
        del self.ListItemData[index]

    def getItem(self, index):
        if index > -1 and index < len(self.ListItemData):
            return self.ListItemData[index]


def compare_sentences(sentence1, sentence2):
  if len(sentence1) != len(sentence2):
    return False
  for word1, word2 in zip(sentence1, sentence2):
    if word1 != word2:
      return False
  return True

def compare(sentence1, sentence2):
  words1=sentence1.split()
  words2=sentence2.split()
  if len(words1) != len(words2):
    return False
  for word1, word2 in zip(words1, words2):
    if word1 != word2:
      return False
  return True


class AtributosMotos():
    pass
    marca = ""
    modelo = ""
    color = ""
    valor = 0.0
    cilindara = 0.0
    velocidad_max = 0.0

    def KawasakiNinjaH2R(self):
        ## objeto creado para definir atributos
        H2R = AtributosMotos

        ## Definicion de atributos para esta moto
        H2R.marca = "Kawasaki"
        H2R.modelo = "2017"
        H2R.color = "Gris-verde"
        H2R.valor = 64428.16
        H2R.cilindrada = 992
        H2R.velocidad_max = 400

        print("Esta son las caracteristicas de la Ninja H2R: \n")
        print("La marca de la moto es : " + H2R.marca)
        print("El modelo de la moto es : " + H2R.modelo)
        print("El color de la moto es : " + H2R.color)
        print("El valor de la moto es : US $ ", H2R.valor)
        print("La cilindrada de la moto es : ", H2R.cilindrada)
        print("La velocidad maxima de la moto es : ", H2R.velocidad_max, " Km/h \n")

    def DucatiMultistrada(self):
        Multistrada = AtributosMotos()

        ## Definicion de atributos para esta moto

        Multistrada.marca = "Ducati"
        Multistrada.modelo = "2016"
        Multistrada.color = "Roja"
        Multistrada.valor = 19895.19
        Multistrada.cilindrada = 1200
        Multistrada.velocidad_max = 299

        # impresion de atributos
        print("Esta son las caracteristicas de la Ducati Multistrada: \n")
        print("La marca de la moto es : " + Multistrada.marca)
        print("El modelo de la moto es : " + Multistrada.modelo)
        print("El color de la moto es : " + Multistrada.color)
        print("El valor de la moto es : US $", Multistrada.valor)
        print("La cilindrada de la moto es : ", Multistrada.cilindrada, "c.c")
        print("La velocidad maxima de la moto es : ", Multistrada.velocidad_max, " Km/h \n")

    def YamahaR1M(self):
        ## definicion del objeto
        R1M = AtributosMotos()
        ## Definicion de atributos para esta moto
        R1M.marca = "Yamaha"
        R1M.modelo = "2018"
        R1M.color = "Gris"
        R1M.valor = 25085.788
        R1M.cilindrada = 998
        R1M.velocidad_max = 350

        # impresion de atributos
        print("Esta son las caracteristicas de la Yamaha R1M: \n")
        print("La marca de la moto es : " + R1M.marca)
        print("El modelo de la moto es : " + R1M.modelo)
        print("El color de la moto es : " + R1M.color)
        print("El valor de la moto es : US $", R1M.valor)
        print("La cilindrada de la moto es : ", R1M.cilindrada, "c.c")
        print("La velocidad maxima de la moto es : ", R1M.velocidad_max, " Km/h" + "\n")

    def YamahaFZ(self):
        """ definicion de objeto"""
        FZ = AtributosMotos()

        # Definicion de atributos para esta moto
        FZ.marca = "Yamaha"
        FZ.modelo = "2017"
        FZ.color = "Gris-Azul"
        FZ.valor = 2200.475
        FZ.cilindrada = 149
        FZ.velocidad_max = 135

        # impresion de atributos
        print("Esta son las caracteristicas de la Yamaha FZ 2.0: \n")
        print("La marca de la moto es : " + FZ.marca)
        print("El modelo de la moto es : " + FZ.modelo)
        print("El color de la moto es : " + FZ.color)
        print("El valor de la moto es : US $", FZ.valor)
        print("La cilindrada de la moto es : ", FZ.cilindrada, "c.c")
        print("La velocidad maxima de la moto es : ", FZ.velocidad_max, " Km/h" + "\n")

class Atributos():
    pass
    # Creacion de objeto par llamar los atributos de las motos
    Atm = AtributosMotos()

    print("Acontinuacion se presentan los atributos de 4 motos Diferentes: \n")
    Atm.KawasakiNinjaH2R()
    Atm.DucatiMultistrada()
    Atm.YamahaR1M()
    Atm.YamahaFZ()


'''

Explanation of the sample testcase
The optimal way is to move from 1-st to 2-nd, then from 2-nd to 4-th street. The product will be equal to 2 * 4 = 8, which is the answer.

'''

import sys

def main():
    n,k = map(int,sys.stdin.readline().split())
    a = list(map(int,sys.stdin.readline().split()))
    if n==1:
        print(a[0])
        return
    if k==1:
        print(min(a))
        return
    if k==n:
        print(max(a))
        return
    dp = [0]*(n+1)
    dp[1] = a[0]
    dp[2] = a[1]
    for i in range(3,n+1):
        dp[i] = min(dp[i-j]*a[i-1] for j in range(1,k+1))
    print(dp[n])

if __name__ == '__main__':
    main()


# Kyle Ryan
# CISC 5825 Computer Algorithms
# Professor Josephine Altzman

from collections import defaultdict

time = 1
class Graph:

    def __init__(self):
        self.graph = defaultdict(list)

    def addEdge(self, u, v):
        self.graph[u].append(v)

    def BFS(self, v):

        # Initializing Queue and Visited Array
        queue = [v]
        visited = [v]

        # Initializing Arrival and Departure of Each Node
        numNodes = 9
        arrival = [0 for _ in range(numNodes + 1)]
        departure = [0 for _ in range(numNodes + 1)]

        global time

        # Converting NodeNum from String to Int to Easily Traverse
        nodeNum = int(ord(v) - 64)

        while queue:

            arrival[nodeNum] = time
            time += 1

            v = queue.pop(0)

            for neighbour in self.graph[v]:
                if neighbour not in visited:
                    print('Tree Edge:', f'{str(v)} --> {str(neighbour)}')
                    queue.append(neighbour)
                    visited.append(neighbour)
                else:
                    print('Back Edge:', f'{str(v)} --> {str(neighbour)}')

            departure[nodeNum] = time
            time += 1
            print(v, arrival[nodeNum], departure[nodeNum])

        print(f'BFS: {visited}' + '\n')

'''
g = Graph()
g.addEdge('A', 'B')
g.addEdge('A', 'E')
g.addEdge('B', 'C')
g.addEdge('B', 'E')
g.addEdge('C', 'F')
g.addEdge('E', 'F')
g.addEdge('F', 'I')

g.addEdge('D', 'G')
g.addEdge('D', 'H')
g.addEdge('G', 'H')

g.BFS('A')
g.BFS('D')
'''

g = Graph()
g.addEdge('A', 'B')
g.addEdge('A', 'D')
g.addEdge('B', 'C')
g.addEdge('B', 'E')
g.addEdge('C', 'F')
g.addEdge('D', 'H')
g.addEdge('E', 'A')
g.addEdge('F', 'I')
g.addEdge('G', 'D')
g.addEdge('H', 'G')
g.addEdge('H', 'F')
g.addEdge('H', 'I')
g.addEdge('I', 'H')

g.BFS('A')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from graphdot.model.gaussian_process import GaussianProcessRegressor as GPR
from molalkit.models.base import BaseModel

class GPRegressor(GPR, BaseModel):
    def __init__(self, *args, **kwargs):
        uncertainty_type = kwargs.pop('uncertainty_type')
        super().__init__(*args, **kwargs)
        self.uncertainty_type = uncertainty_type

    def fit_alb(self, train_data, **kwargs):
        X = train_data.X
        y = train_data.y
        super().fit(X, y, **kwargs)

    def predict_uncertainty(self, pred_data):
        X = pred_data.X
        if self.uncertainty_type == 'value':
            preds = self.predict(X).reshape(-1, 1)
            preds = np.concatenate([preds, 1 - preds], axis=1)
            return (0.25 - np.var(preds, axis=1)) * 4
        elif self.uncertainty_type == 'uncertainty':
            return self.predict(X, return_std=True)[1]

    def predict_value(self, pred_data):
        X = pred_data.X
        return self.predict(X)


from django.contrib import admin
from .models import Roles, Users

# Register the role and user models to the admin page so that they can be viewed and edited.
@admin.register(Roles)
class RolesAdmin(admin.ModelAdmin):
    list_display = ("name", "description")
    list_filter = ("name", "description")
    search_fields = ("name", "description")
    ordering = ("name", "description")

@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):
    list_display = (
        "user",
        "first_name",
        "last_name",
        "get_roles",
        "title",
        "business_unit",
    )
    list_filter = (
        "user",
        "first_name",
        "last_name",
        "user_roles",
        "title",
        "business_unit",
    )
    search_fields = (
        "user",
        "first_name",
        "last_name",
        "user_roles",
        "title",
        "business_unit",
    )
    ordering = (
        "user",
        "first_name",
        "last_name",
        "user_roles",
        "title",
        "business_unit",
    )

    # return the roles of the user as a string
    def get_roles(self, obj):
        return ", ".join([p.name for p in obj.user_roles.all()])


def elemento_matriz(matriz,l,c):

    if (l>=len(matriz)):
        print("Indice invalido: linha",l)
    if (c>=len(matriz[0])):
        print("Indice invalido: coluna",c)
    else:
        return matriz[l][c]

a=[[1, 2, 3, 4, 5, 6],[7, 8, 9, 10, 11, 12]]
elemento_matriz(a,6,6)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr  3 12:46:07 2020

@author: wouterpotters
"""
import os
import configparser
import castorapi as ca

config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), '../user_settings.ini'))

c = ca.CastorApi(config['CastorCredentials']['local_private_path'])
study_id = c.select_study_by_name(config['CastorCredentials']['study_name'])

# select AMC + VUmc
institutes = c.request_institutes()
inst_amc_vumc = [inst['institute_id'] for inst in c.request_institutes()
                 if (inst['name'] == 'AUMC - AMC'
                 or inst['name'] == 'AUMC - VUmc')]
records = c.request_study_records(institute=inst_amc_vumc[0]) +\
    c.request_study_records(institute=inst_amc_vumc[1])

ct_perf_values = c.field_values_by_variable_name('CT_thorax_performed',
                                                 records=records)
corad_values = c.field_values_by_variable_name('corads_admission',
                                               records=records)

options_corad = c.request_fieldoptiongroup(
    optiongroup_id=c.field_optiongroup_by_variable_name('corads_admission'))

# %%
print('Total COVID-19 records (AMC + VUmc): '+str(len(ct_perf_values)))
print(' - records: CT data not present: ' +
      str(sum([f is None for f in ct_perf_values])))
print(' - records: CT data present: ' +
      str(sum([f is not None for f in ct_perf_values])))

print(' - CORAD scores available (n=' +
      str(sum([f is not None for f in corad_values]))+'): ')
for o in options_corad['options']:
    print('   ' + str(o['name']) + ': ' +
          str(sum([f == o['value'] for f in corad_values])))


import torch
import torch.nn as nn
import torch.nn.functional as F

# -----------------------------------------------------------------------------

class VolumetricFeatureSampler(nn.Module):

    def __init__(self, padding_mode='zeros', feature_fusion=''):
        super(VolumetricFeatureSampler, self).__init__()

        """ define a volumetric feature sampler
        """
        self.padding_mode = padding_mode

        # note: the two operations will cumulate the feature and squared feature, independently among the feature channels
        # later in self.compute_stats(), we convert the results into means and standard deviations.
        # currently these are hardcoded operations, and all tensors in this class with some dimension "2F" are also due to this reason
        self.fuse_ops = [
            lambda feat, base: feat if base is None else feat + base,
            lambda feat, base: feat.pow(2.0) if base is None else feat.pow(2.0) + base,
        ]
        self.fuse_ops_num = len(self.fuse_ops)

        if feature_fusion == 'mean_var':
            self.compute_feature_volume = self.mean_var
        elif 'visibility_filtered' in feature_fusion:
            self.compute_feature_volume = self.visibility_filtered_mean_var
        else:
            raise RuntimeError( "Unrecognizable feature_fusion: %s" % ( self.feature_fusion ) )

    @staticmethod
    def project(points, camera_intrinsics, camera_extrinsics, camera_distortions, height, width, eps=1e-7):
        """ project the grid points into images (full perspective projection)
        Args:
        - points: (B, N, 3)
        - camera_intrinsics: (B, 3, 4)
        - camera_extrinsics: (B, 3, 3)
        - camera_distortions: (B, 2)
        - height: int
        - width: int

        Return:
        - u_coord: (B, N), value range in [-1, 1]
        - v_coord: (B, N), value range in [-1, 1]
        """

        device = points.device
        batch_size, num_points, _ = points.shape
        points = points.transpose(1, 2).contiguous()

        ones = torch.ones(batch_size, 1, num_points).to(device)
        points_homogeneous = torch.cat((points, ones), axis=-2) # (batch_size, 4, num_points)

        # Transformation from the world coordinate system to the image coordinate system using the camera extrinsic rotation (R) and translation (T)
        points_image = camera_extrinsics.bmm(points_homogeneous) # (batch_size, 3, num_points)

        # Transformation from 3D camera coordinate system to the undistorted image plane
        mask = (points_image.abs() < eps)
        mask[:,:2,:] = False
        points_image[mask] = 1.0 # Avoid division by zero

        points_image_x = points_image[:,0,:] / points_image[:,2,:]
        points_image_y = points_image[:,1,:] / points_image[:,2,:]

        # Transformation from undistorted image plane to distorted image coordinates
        K1, K2 = camera_distortions[:,0], camera_distortions[:,1]       # (batch_size)
        r2 = points_image_x**2 + points_image_y**2            # (batch_size, num_points)
        r4 = r2**2
        radial_distortion_factor = (1 + K1[:, None]*r2 + K2[:, None]*r4)  # (batch_size, num_points)

        points_image_x = points_image_x*radial_distortion_factor
        points_image_y = points_image_y*radial_distortion_factor
        points_image_z = torch.ones_like(points_image[:,2,:])
        points_image = torch.cat((points_image_x[:, None, :], points_image_y[:, None, :], points_image_z[:, None, :]), dim=1)

        # Transformation from distorted image coordinates to the final image coordinates with the camera intrinsics
        points_image = camera_intrinsics.bmm(points_image)      # (batch_size, 3, num_points)

        # Convert the range to [-1, 1]
        u_coord = 2. * points_image[:, 0, :] / (width - 1.) - 1.
        v_coord = 2. * points_image[:, 1, :] / (height - 1.) - 1.
        return u_coord, v_coord

    def mean_var(self, feature_maps, camera_intrinsics, camera_extrinsics, camera_distortions, grids, **kwargs):
        batch_size, num_views, fd, height, width = feature_maps.shape
        _, grid_num, _, grid_h, grid_w, grid_d = grids.shape
        xyzs = grids.transpose(1, 2).contiguous() # (B, 3, G, GH, GW, GD)
        xyzs = xyzs.view(batch_size, 3, -1)               # (B, 3, G*GH*GW*GD)
        xyzs = xyzs.transpose(1, 2).contiguous() # (B, G*GH*GW*GD, 3)

        # projection
        xyzs = xyzs.unsqueeze(1).repeat(1,num_views,1,1).view(batch_size*num_views, -1, 3)
        u_coord, v_coord = self.project(xyzs, camera_intrinsics.view(-1,3,3), camera_extrinsics.view(-1,3,4), camera_distortions.view(-1,2), height, width)

        # sample
        grid2d_uv = torch.stack((u_coord, v_coord), dim=2) # (B*V, G*GH*GW*GD, 2)
        grid2d_uv = grid2d_uv.view(batch_size*num_views, grid_num, -1, 2) # (B*V, G, GH*GW*GD, 2)
        feat2d_uv = F.grid_sample(feature_maps.view(-1, fd, height, width), grid2d_uv, padding_mode=self.padding_mode, align_corners=False)  # (B*V, F, G, GH*GW*GD)
        feat2d_uv = feat2d_uv.transpose(1, 2)    # (B*V, G, F, GH*GW*GD)
        feat2d_uv = feat2d_uv.view(batch_size, num_views, grid_num, -1, grid_h, grid_w, grid_d)  # (B, V, G, F, GH, GW, GD)

        # voxels = torch.cat((feat2d_uv.mean(dim=1), feat2d_uv.std(dim=1, unbiased=False)), dim=2).contiguous()   # (B, G, 2F, GH, GW, GD)
        feature_volume = torch.cat((feat2d_uv.mean(dim=1), feat2d_uv.var(dim=1, unbiased=True)), dim=2).contiguous()   # (B, G, 2F, GH, GW, GD)
        return feature_volume

    def visibility_filtered_mean_var(self, feature_maps, camera_intrinsics, camera_extrinsics, camera_distortions, grids, visibilities, normals, camera_centers, **kwargself):
        '''
        Args:
            feature_maps: (B, V, F, H, W), image feature maps
            camera_intrinsics: (B, V, 3, 3)
            camera_extrinsics: (B, V, 3, 3)
            camera_distortions: (B, V, 3)
            grids: (B, G, 3, GH, GW, GD)
            visibilities: (B, V, G)
            normals: (B, G, 3)
            camera_centers: (B, V, 3)
        '''

        batch_size, num_views, fd, height, width = feature_maps.shape
        _, grid_num, _, grid_h, grid_w, grid_d = grids.shape
        xyzs = grids.transpose(1, 2).contiguous() # (B, 3, G, GH, GW, GD)
        xyzs = xyzs.view(batch_size, 3, -1)      # (B, 3, G*GH*GW*GD)
        xyzs = xyzs.transpose(1, 2).contiguous() # (B, G*GH*GW*GD, 3)

        # projection
        xyzs = xyzs.unsqueeze(1).repeat(1,num_views,1,1).view(batch_size*num_views, -1, 3)
        u_coord, v_coord = self.project(xyzs, camera_intrinsics.view(-1,3,3), camera_extrinsics.view(-1,3,4), camera_distortions.view(-1,2), height, width)  # (B*V, G*GH*GW*GD)

        # sample feature maps
        grid2d_uv = torch.stack((u_coord, v_coord), dim=2) # (B*V, G*GH*GW*GD, 2)
        grid2d_uv = grid2d_uv.view(batch_size*num_views, grid_num, -1, 2) # (B*V, G, GH*GW*GD, 2)
        feat2d_uv = F.grid_sample(feature_maps.view(-1, fd, height, width), grid2d_uv, padding_mode=self.padding_mode, align_corners=False)  # (B*V, F, G, GH*GW*GD)
        feat2d_uv = feat2d_uv.transpose(1, 2).contiguous()    # (B*V, G, F, GH*GW*GD)
        feat2d_uv = feat2d_uv.view(batch_size, num_views, grid_num, -1, grid_h, grid_w, grid_d)  # (B, V, G, F, GH, GW, GD)

        # mask for points that project inside the images
        inside_mask = torch.logical_and(torch.logical_and(u_coord>=-1.0, u_coord<=1.0), torch.logical_and(v_coord>=-1.0, v_coord<=1.0)).contiguous()    # (B*V, G*GH*GW*GD)
        inside_mask = inside_mask.view(batch_size, num_views, grid_num, grid_h, grid_w, grid_d)     # (B, V, G, GH, GW, GD)

        # view_direction = grids - camera_centers
        view_directions = xyzs - camera_centers.contiguous().view(-1,1,3)     # (B*V, G*GH*GW*GD, 3)

        # cos_angle = <view_directions, normals>
        view_directions = view_directions.contiguous().view(batch_size, num_views, grid_num, -1, 3)     # (B, V, G, GH*GW*GD, 3)
        view_directions = view_directions.transpose(1,2).contiguous()  # (B, G, V, GH*GW*GD, 3)
        view_directions = view_directions.view(batch_size*grid_num, -1, 3)  # (B*G, V*GH*GW*GD, 3)
        view_directions = torch.nn.functional.normalize(view_directions, dim=-1)   # (B*G, V*GH*GW*GD, 3)
        view_normal_cos_angles = torch.bmm(view_directions, normals.contiguous().view(-1,3,1)) # (B*G, V*GH*GW*GD, 1)
        view_normal_cos_angles = view_normal_cos_angles.view(batch_size, grid_num, num_views, -1)   # (B, G, V, GH*GW*GD)
        view_normal_cos_angles = view_normal_cos_angles.transpose(1,2).contiguous()  # (B, V, G, GH*GW*GD)

        # Positive angles get zero weights
        view_normal_cos_angles[view_normal_cos_angles>0] = 0.0      # (B, V, G, GH*GW*GD)
        view_normal_cos_angles = view_normal_cos_angles.view((batch_size, num_views, grid_num, grid_h, grid_w, grid_d))   # (B, V, G, GH, GW, GD)

        # Weight negative cosine angles with visibility
        visibilities = visibilities.contiguous().view(batch_size, num_views, grid_num, 1, 1, 1)  # (B, V, G, 1, 1, 1)
        feature_weights = torch.multiply(visibilities, -view_normal_cos_angles)   # (B, V, G, GH, GW, GD)
        feature_weights = torch.multiply(feature_weights, inside_mask.float())   # (B, V, G, GH, GW, GD)

        # Make weights strictly positive and normalize them to sum to 1 across all views
        feature_weights = torch.nn.Softplus(beta=50, threshold=5)(feature_weights)  # (B, V, G, GH, GW, GD)
        feature_weights = feature_weights/feature_weights.sum(1).unsqueeze(1)   # (B, V, G, GH, GW, GD)
        feature_weights = feature_weights.unsqueeze(3)  # (B, V, G, 1, GH, GW, GD)

        # Computed weighted mean and standard deviation and concatenate them
        weighted_mean = torch.mul(feat2d_uv, feature_weights).sum(dim=1)   # (B, G, F, GH, GW, GD)
        weighted_var = torch.mul(feat2d_uv.pow(2), feature_weights).sum(dim=1)-weighted_mean.pow(2) # (B, G, F, GH, GW, GD)
        feature_volume = torch.cat((weighted_mean, weighted_var), dim=2).contiguous()        # (B, G, 2F, GH, GW, GD)
        return feature_volume

    def forward(self, feature_maps, camera_intrinsics, camera_extrinsics, camera_distortions, grids, normals=None, visibilities=None, camera_centers=None):
        """ the full forward process
        Args:
        - feature_maps: tensor in (B, V, F, H, W), batched feature map
        - camera_intrinsics: tensor in (B, V, 3, 3), batched intrisic matrices
        - camera_extrinsics: tensor in (B, V, 3, 4), batched rigid transformation (camera poses)
        - camera_distortions: tensor in (B, V, 2), batched radial camera distortions
        - grids: (B, G, 3, GH, GW, GD), batched grid coordinates

        B: batch size; F: feature dim; V: view num;
        G: grid num (global stage = 1, local stage = input vertex number)
        GH, GW, GD: shape of the grid, currently all equal to grid dim D

        Return:
        - voxels: tensor in (B, G, 2F, GH, GW, GD), sampled volumetric features
        """

        feature_volume = self.compute_feature_volume(feature_maps, camera_intrinsics, camera_extrinsics, camera_distortions, grids, normals=normals, visibilities=visibilities, camera_centers=camera_centers)
        return feature_volume


from voluptuous import Any, Exclusive, Optional, Required

from lava_common.schemas import deploy

def schema():
    resource = deploy.url()

    base = {
        Required("to"): "tftp",
        Required("kernel", msg="needs a kernel to deploy"): deploy.url(
            {Optional("type"): Any("image", "uimage", "zimage")}
        ),
        Optional("dtb"): resource,
        Optional("modules"): resource,
        Optional("preseed"): resource,
        Optional("ramdisk"): deploy.url(
            {
                Optional("install_modules"): bool,
                Optional("install_overlay"): bool,
                Optional("header"): "u-boot",
            }
        ),
        Exclusive("nfsrootfs", "nfs"): deploy.url(
            {
                Optional("install_modules"): bool,
                Optional("install_overlay"): bool,
                Optional("prefix"): str,
            }
        ),
        Exclusive("persistent_nfs", "nfs"): {
            Required("address"): str,
            Optional("install_overlay"): bool,
        },
        Optional("tee"): resource,
    }
    return {**deploy.schema(), **base}


from django.conf.urls import patterns, include, url
from rest_framework import routers
from .views import UserViewSet, GroupViewSet

router = routers.DefaultRouter()
router.register('users', UserViewSet)
router.register('groups', GroupViewSet)

urlpatterns = patterns('',
    url(r'^bsd/$', 'Core.views.bs_demo'),#bootstrap demo
    url(r'^menu_test/$','Core.views.menu_test'),
    url(r'^rest_test/$','Core.views.rest_test'),
    url(r'^bb_test/$','Core.views.bb_test'),
    url(r'^api/', include(router.urls)),

)


#!/usr/bin/env python3
"""Identity Block"""

import tensorflow.keras as K

def identity_block(A_prev, filters):
    """
    Write a function def identity_block(A_prev, filters):
    that builds an identity block as described in Deep Residual
    Learning for Image Recognition (2015):

        *A_prev is the output from the previous layer
        *filters is a tuple or list containing F11, F3, F12,
        respectively:

            -F11 is the number of filters in the first 1x1
            convolution
            -F3 is the number of filters in the 3x3 convolution
            -F12 is the number of filters in the second 1x1
            convolution
            -All convolutions inside the block should be
            followed by batch normalization along the channels
            axis and a rectified linear activation (ReLU), respectively.
            -All weights should use he normal initialization

        Returns: the activated output of the identity block
    """
    F11, F3, F12 = filters

    # Shortcut branch
    shortcut = A_prev

    # First layer
    conv1 = K.layers.Conv2D(filters=F11, kernel_size=(1, 1), padding='same',
                            kernel_initializer='he_normal')(A_prev)
    bn1 = K.layers.BatchNormalization(axis=3)(conv1)
    relu1 = K.layers.Activation('relu')(bn1)

    # Second layer
    conv2 = K.layers.Conv2D(filters=F3, kernel_size=(3, 3), padding='same',
                            kernel_initializer='he_normal')(relu1)
    bn2 = K.layers.BatchNormalization(axis=3)(conv2)
    relu2 = K.layers.Activation('relu')(bn2)

    # Third layer
    conv3 = K.layers.Conv2D(filters=F12, kernel_size=(1, 1), padding='same',
                            kernel_initializer='he_normal')(relu2)
    bn3 = K.layers.BatchNormalization(axis=3)(conv3)

    # Add shortcut to the main path
    add = K.layers.Add()([bn3, shortcut])
    activated_output = K.layers.Activation('relu')(add)

    return activated_output


#!/usr/bin/python3
import pyaudio
import os
import fnmatch
import shutil
import sys

def play_pcm(filename):
    p = pyaudio.PyAudio()
    stream = p.open(format = pyaudio.paInt16,
                channels = 2,
                rate = 24000,
                output = True)

    with open(filename, 'rb') as pcm_file:
        pcm_data = pcm_file.read()
        stream.write(pcm_data)
    stream.stop_stream()

    stream.close()
    p.terminate()

def menu_show():
    print('MENU:')
    print('1 - Play pcm file')
    print('2 - View decoded string')
    print('3 - Edit decoded string')
    print('4 - Add pcm file to test dataset')
    print('5 - Next pcm file')
    print('6 - Quit')

def process_file(path, copy_path, pcm_file, ds_file):
    flag = True
    decoded_string = ''
    while(flag):
        print('File in process:' + pcm_file)
        menu_show()
        value = input('Choose item:')
        menu_item = int(value)
        if (menu_item == 1):
            play_pcm(path + pcm_file)

        elif (menu_item == 2):
            with open(path + ds_file, 'r') as fd:
                decoded_string = fd.read()
            print(decoded_string)

        elif (menu_item == 3):
            decoded_string = input('Enter string for pcm file:')

        elif (menu_item == 4):
            shutil.copy(path + pcm_file, copy_path + pcm_file)
            file_name = ds_file.split('.')[0]
            with open(copy_path + file_name + '.ds', 'w') as fd:
                print(decoded_string)
                fd.write(decoded_string)
            fd.close()

        elif (menu_item == 5):
            flag = False

        elif (menu_item == 6):
            os._exit(0)

def main(pcm_path, copy_path, start_index):
    dir_name = pcm_path

    pcm_list = []
    decoded_string_list = []
    for file_name in os.listdir(dir_name):

        if fnmatch.fnmatch(file_name, '*.pcm'):
            pcm_file = file_name
            data_file = file_name.split('.')[0]
            bad_file = data_file + '.bad'
            good_file = data_file + '.good'
            if os.path.isfile(dir_name + bad_file):
                pcm_list.append(pcm_file)
                decoded_string_list.append(bad_file)
            if os.path.isfile(dir_name + good_file):
                pcm_list.append(pcm_file)
                decoded_string_list.append(good_file)

    print('pcm list len - ' + str(len(pcm_list)))
    print('ds list len - ' + str(len(decoded_string_list)))
    for index in range(start_index,len(pcm_list)):
        print('index - ', index)
        print(pcm_list[index])
        print(decoded_string_list[index])
        process_file(dir_name, copy_path, pcm_list[index],
                decoded_string_list[index])

if __name__ == '__main__':
    abs_path_name = os.path.abspath(os.getcwd()) + '/'
    if (len(sys.argv) != 4):
        print('\nUsage: ' + sys.argv[0] + ' dir_with_pcm_files dir_to_copy start_index\n')
        os._exit(-1)
    path1 = abs_path_name + sys.argv[1] + '/'
    path2 = abs_path_name + sys.argv[2] + '/'
    start_index = int(sys.argv[3])
    main(path1, path2, start_index)


# 997. 找到小镇的法官
# 在一个小镇里，按从 1 到 n 为 n 个人进行编号。传言称，这些人中有一个是小镇上的秘密法官。

# 如果小镇的法官真的存在，那么：

# 小镇的法官不相信任何人。
# 每个人（除了小镇法官外）都信任小镇的法官。
# 只有一个人同时满足条件 1 和条件 2 。
# 给定数组 trust，该数组由信任对 trust[i] = [a, b] 组成，表示编号为 a 的人信任编号为 b 的人。

# 如果小镇存在秘密法官并且可以确定他的身份，请返回该法官的编号。否则，返回 -1。

# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/find-the-town-judge
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

from typing import List

class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        if n==1:
            return 1
        vset1=set()
        vDict = dict()
        for i,j in trust:
            vset1.add(i)
            if j in vDict:
                vDict[j]+=1
            else:
                vDict[j]=1
        vset = set(vDict.keys())-vset1
        if len(vset)==1:
            key = list(vset)[0]
            if vDict[key]== n-1:
                return key
        return -1


# 416. Partition Equal Subset Sum
# Medium

# Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

# Example 1:

# Input: nums = [1,5,11,5]
# Output: true
# Explanation: The array can be partitioned as [1, 5, 5] and [11].
# Example 2:

# Input: nums = [1,2,3,5]
# Output: false
# Explanation: The array cannot be partitioned into equal sum subsets.

# Recursive Solution - TLE
class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        # Edge Case, if sum is odd, return False
        if not nums or sum(nums) % 2 == 1:
            return False

        # Target sum is sum of nums divided by 2
        s = sum(nums)//2

        def helper(s, index):
            # Base Cases
            # If target sum is reached, return True
            if s == 0:
                return True
            if index == 0:
                return False
            pick = False
            # 2 options - either pick the current number or don't pick current number
            if s - nums[index] >= 0:  # Can pick only if adding current number doesn't exceed the sum
                pick = helper(s - nums[index], index - 1)
            dont_pick = helper(s, index - 1)
            return pick or dont_pick

        return helper(s, len(nums) - 1)

# Bottom Up DP
class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        total = sum(nums)
        n = len(nums)

        # Edge Case - if the sum is odd, we cannot for subsets with equal sums
        if total % 2 == 1:
            return False

        s = int(total/2)

        # Initialize 2D dp table
        dp = [[False for _ in range(1+s)] for _ in range(n)]

        # 0 can be achieved by excluding all numbers - mark the first column as True
        for i in range(0, n):
            dp[i][0] = True

        # with only one number, we can form a subset only when the required sum is equal to its value
        for j in range(1+s):
            dp[0][j] = nums[0] == j

        # Tabulate
        for numindex in range(1, n):
            for target in range(1, 1+s):
                pick = False
                # Include number at current index
                if target - nums[numindex] >= 0:
                    pick = dp[numindex-1][target - nums[numindex]]
                # Exclude number at current index
                dont_pick = dp[numindex-1][target]
                dp[numindex][target] = pick or dont_pick

        return dp[n-1][s]


from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QSize
import qtawesome as qta
from PyQt5.QtWidgets import QPushButton, QStyle

class CopyCodeBtn(QPushButton):

    def __init__(self, parent):
        super(CopyCodeBtn, self).__init__()

        self.setParent(parent)
        self.setText(' Arduino Code')
        self.setIcon(qta.icon('mdi.code-braces-box'))
        self.setIconSize(QSize(30, 30))
        self.adjustSize()
        self.move(parent.width() - 15 - self.width(), parent.height() - 10 - self.height())

        self.clicked.connect(self.copyCode)

    def copyCode(self):
        self.openUrl()

    def openUrl(self):
        parent = self.parent()
        url = QtCore.QUrl('https://github.com/ShreyanshJF/Open-Source-Optics-Lab/blob/main/controlling_motor_with_python.ino')
        if not QtGui.QDesktopServices.openUrl(url):
            self.setText('Open Url Could not open url')
            self.adjustSize()
            self.move(parent.width() - 15 - self.width(), parent.height() - 10 - self.height())


from zoom_out import *
import constants
from pymongo import MongoClient
client = MongoClient()
db = client.MyDB
collection = db.FirstCollection

class DistortionData:
    """Class DistortionData computes the distortion units for the selected trajectories and finds the preferable
    episode if there is one to include."""

    def __init__(self, area_step=0, time_step=0, distort_area_only=False, distort_time_only=False,
                 distort_area_time=False):
        self.area_step = area_step
        self.time_step = time_step
        self.area_distortion_limit = 10000.0
        self.time_distortion_limit = 1
        self.area_time_distortion_limit = 100.0
        self.subqueries = []
        self.distort_area_only = distort_area_only
        self.distort_time_only = distort_time_only
        self.distort_area_time = distort_area_time

    def find_subqueries_not_in_row(self, row):
        """This function finds and returns a list (found[]) with the subqueries who do not contain episode of the
        trajectory (they are not included in the SQueries[] list for the trajectory we examine)"""
        found = []

        for subq in range(len(self.subqueries)):
            if row.subquery_exists(self.subqueries[subq].qid) is True:
                continue
            else:
                found.append(self.subqueries[subq])
        return found

    def set_subqueries(self, subqueries):
        """Initializes the subqueries[] list (we use this in the driver code to load the user's subqueries"""

        if subqueries is None or subqueries == []:
            raise Exception("Invalid subqueries list")
        self.subqueries = subqueries

    def check_by_distort_area_time(self, row):

        trace_id = row.get_trace_id()
        subqueries_ = self.find_subqueries_not_in_row(row)
        discard_trc_id = False
        to_add = []

        for subq in range(len(subqueries_)):

            if discard_trc_id is True:
                break

            query_ = subqueries_[subq]
            start_area = (query_.realx2 - query_.realx1) * (query_.realy2 - query_.realy1)
            x1 = query_.realx1
            x2 = query_.realx2
            y1 = query_.realy1
            y2 = query_.realy2
            steps = 1
            new_area = (x2 - x1 + 2 * steps * self.area_step) * (y2 - y1 + 2 * steps * self.area_step)
            start_time = query_.duration
            new_time = start_time + self.time_step * steps
            area_time_distortion_unit = (((new_area - start_area)/start_area) + ((new_time - start_time)/start_time))/2

            while area_time_distortion_unit < self.area_time_distortion_limit:
                if query_.episodes == 'Null':
                    q_r = db.FirstCollection.find({"loc": {"$geoWithin": {"$box": [
                        [x1 - steps * self.area_step, y1 - steps * self.area_step],
                        [x2 + steps * self.area_step, y2 + steps * self.area_step]]}}, "duration": {"$lt": new_time},
                        'MOid': trace_id})
                else:
                    q_r = db.FirstCollection.find({"loc": {"$geoWithin": {"$box": [
                        [x1-steps*self.area_step, y1-steps*self.area_step], [x2+steps*self.area_step,
                                                                             y2+steps*self.area_step]]}}, "duration": {
                        "$lt": new_time}, "episodes": query_.episodes, 'MOid': trace_id})

                query_rslt = []
                for i in q_r:
                    query_rslt.append(i['MOid'])
                q_reslt = set(query_rslt)
                query_result = list(q_reslt)
                out = False
                for i in query_result:
                    if query_result is not None and i == trace_id:
                        elements = [subqueries_[subq].qid, area_time_distortion_unit, steps]
                        to_add.append(elements)
                        out = True
                        break
                if out is True:
                    break
                steps += 1
                new_area = (x2 - x1 + 2 * steps * self.area_step) * (y2 - y1 + 2 * steps * self.area_step)
                new_time = start_time + self.time_step * steps
                area_time_distortion_unit = (((new_area - start_area)/start_area) + ((new_time - start_time)/start_time)
                                             )/2

                if area_time_distortion_unit > self.area_time_distortion_limit:
                    discard_trc_id = True

        if discard_trc_id is not True:
            for i in to_add:
                row.set_subquery_dist_area_time_unit(i[0], i[1], i[2])

    def check_by_distort_area(self, row):

        # loop over the subqueries of the row and for each subquery iteratively enlarge the area of the subquery
        # for each iteration check with the db by using the enlarged area if the trajectory is contained in the modified
        # subquery. The inner enlargement iterations finish when the overall area_distortion_unit  exceeds a certain
        # area_distortion_limit. If the trajectory id is found before reaching the area_distortion_limit meaning
        # area_distortion_unit < area_distortion_limit the algorithm continues to examine the next subquery, otherwise
        # it marks the whole row as invalid. If the all subqueries are found after distorting the area to contain the
        # trajectory then the smallest distortion will be chosen.

        trace_id = row.get_trace_id()
        subqueries_ = self.find_subqueries_not_in_row(row)
        discard_trc_id = False
        to_add = []

        for subq in range(len(subqueries_)):

            if discard_trc_id is True:
                break

            query_ = subqueries_[subq]
            start_area = (query_.realx2 - query_.realx1)*(query_.realy2 - query_.realy1)
            x1 = query_.realx1
            x2 = query_.realx2
            y1 = query_.realy1
            y2 = query_.realy2
            steps = 1
            new_area = (x2 - x1 + 2*steps*self.area_step)*(y2 - y1 + 2*steps*self.area_step)
            area_distortion_unit = (new_area - start_area)/start_area

            while area_distortion_unit < self.area_distortion_limit:
                # haven't reached the distortion limit yet so query the db by using the new_area
                if query_.episodes == 'Null':
                    q_r = db.FirstCollection.find({"loc": {"$geoWithin": {"$box": [
                        [x1 - steps * self.area_step, y1 - steps * self.area_step], [x2 + steps * self.area_step,
                                                                                y2 + steps * self.area_step]]}},
                        "duration":
                            {"$lt": query_.duration}, 'MOid': trace_id})
                else:
                    q_r = db.FirstCollection.find({"loc": {"$geoWithin": {"$box": [
                        [x1-steps*self.area_step, y1-steps*self.area_step], [x2+steps*self.area_step,
                                                                             y2+steps*self.area_step]]}}, "duration":
                        {"$lt": query_.duration}, "episodes": query_.episodes, 'MOid': trace_id})

                query_rslt = []
                for i in q_r:
                    query_rslt.append(i['MOid'])
                q_reslt = set(query_rslt)
                query_result = list(q_reslt)
                out = False
                for i in query_result:
                    if query_result is not None and i == trace_id:
                        elements = [subqueries_[subq].qid, area_distortion_unit, steps]
                        to_add.append(elements)
                        out = True
                        break
                if out is True:
                    break
                steps += 1
                new_area = (x2 - x1 + 2*steps*self.area_step)*(y2 - y1 + 2*steps*self.area_step)
                area_distortion_unit = (new_area - start_area) / start_area

                if area_distortion_unit > self.area_distortion_limit:
                    discard_trc_id = True

        if discard_trc_id is not True:
            for i in to_add:
                row.set_subquery_dist_area_unit(i[0], i[1], i[2])

    def check_by_distort_time(self, row):

        trace_id = row.get_trace_id()
        subqueries_ = self.find_subqueries_not_in_row(row)
        discard_trc_id = False
        to_add = []

        for subq in range(len(subqueries_)):

            if discard_trc_id is True:
                break

            query_ = subqueries_[subq]
            x1 = query_.realx1
            x2 = query_.realx2
            y1 = query_.realy1
            y2 = query_.realy2
            start_time = query_.duration
            steps = 1
            new_time = start_time + self.time_step * steps
            time_distortion_unit = (new_time - start_time)/start_time

            while time_distortion_unit < self.time_distortion_limit:
                if query_.episodes == 'Null':
                    q_r = db.FirstCollection.find({"loc": {"$geoWithin": {"$box": [[x1, y1], [x2, y2]]}},
                                                   "duration": {"$lt": new_time}, 'MOid': trace_id})
                else:
                    q_r = db.FirstCollection.find({"loc": {"$geoWithin": {"$box": [[x1, y1], [x2, y2]]}}, "duration": {
                        "$lt": new_time}, "episodes": query_.episodes, 'MOid': trace_id})

                query_rslt = []
                for i in q_r:
                    query_rslt.append(i['MOid'])
                q_reslt = set(query_rslt)
                query_result = list(q_reslt)
                out = False
                for i in query_result:
                    if query_result is not None and i == trace_id:
                        elements = [subqueries_[subq].qid, time_distortion_unit, steps]
                        to_add.append(elements)
                        out = True
                        break
                if out is True:
                    break
                steps += 1
                new_time = start_time + self.time_step * steps
                time_distortion_unit = (new_time - start_time)/start_time

                if time_distortion_unit > self.time_distortion_limit:
                    discard_trc_id = True

        if discard_trc_id is not True:
            for i in to_add:
                row.set_subquery_dist_time_unit(i[0], i[1], i[2])

    def check_by_distortion(self, row):

        if self.distort_area_only is True:
            self.check_by_distort_area(row)
            min_dist_area_unit = row.get_min_area_dist_unit()

            if min_dist_area_unit[0] != constants.INVALID_ID:
                return [row.get_trace_id(), min_dist_area_unit[0], min_dist_area_unit[1], min_dist_area_unit[2]]
            return [-1, -1, -1, -1]

        elif self.distort_time_only is True:
            self.check_by_distort_time(row)
            min_dist_time_unit = row.get_min_time_dist_unit()

            if min_dist_time_unit[0] != constants.INVALID_ID:
                return [row.get_trace_id(), min_dist_time_unit[0], min_dist_time_unit[1], min_dist_time_unit[2]]
            return [-1, -1, -1, -1]

        elif self.distort_area_time is True:
            self.check_by_distort_area_time(row)
            min_dist_area_time_unit = row.get_min_area_time_dist_unit()

            if min_dist_area_time_unit[0] != constants.INVALID_ID:
                return [row.get_trace_id(), min_dist_area_time_unit[0], min_dist_area_time_unit[1],
                        min_dist_area_time_unit[2]]
            return [-1, -1, -1, -1]

        else:
            raise Exception("No valid distortion type. Set either distort_area_only or distort_time_only or "
                            "distort_area_time flag to True. ")

    def compute_rows_distortions(self, rows, ran_num):
        episode_found = []
        minimum_dist_unit = constants.LARGE_VALUE
        steps_ = constants.INVALID_ID
        subquery = constants.INVALID_ID
        for r in range(len(rows)):
            episode_found.append(self.check_by_distortion(rows[r]))
        # loop over episode_found list if a True exists return True else False
        for x in episode_found:
            if x[2] != -1 and x[2] < minimum_dist_unit:
                minimum_dist_unit = x[2]
                steps_ = x[3]
                subquery = x[1]

        if minimum_dist_unit != constants.LARGE_VALUE:
            if self.distort_area_only is True:
                for q in self.subqueries:
                    if q.qid == subquery:
                        q.distort_area(steps_, self.area_step, ran_num)
            elif self.distort_time_only is True:
                for q in self.subqueries:
                    if q.qid == subquery:
                        q.distort_time(steps_, self.time_step)
            else:
                for q in self.subqueries:
                    if q.qid == subquery:
                        q.distort_area_time(steps_, self.area_step, self.time_step, ran_num)
            return True
        return False


from libs import r

def check_sms(u_phone, msg_code):
    res = None
    try:
        r_msg_code = r.get('MT' + u_phone).decode()
        print(r_msg_code,'xxxxxxxxxxxxxxxx')
        if not r_msg_code:
            res = {'code': 207, 'msg': '短信验证码已过期'}
        if r_msg_code != msg_code:
            res = {'code': 207, 'msg': '短信验证码输入错误'}
    except Exception as e:
        res = {'code': 380, 'msg': '数据库查询失败 %s' % e}

    return res

if __name__ == '__main__':
    print(check_sms('18309182914','111111'))


# -*- coding:utf-8 -*-
# use timeit get the time
from timeit import Timer

def t1():
    l1 = []
    for i in range(0, 1001):
        l1 = l1 + [i]

def t2():
    l1 = []
    for i in range(0, 1001):
        l1.extend([i])

def t3():
    l1 = []
    for i in range(0, 1001):
        l1.append(i)

def t4():
    l1 = [i for i in range(0, 1001)]

def t5():
    l1 = list(range(0, 1001))

print('test list fun')
r1 = Timer('t1()', 'from __main__ import t1')
print('+ use times', r1.timeit(1000))

r2 = Timer('t2()', 'from __main__ import t2')
print('extends', r2.timeit(1000))

r3 = Timer('t3()', 'from __main__ import t3')
print('append', r3.timeit(1000))

r4 = Timer('t4()', 'from __main__ import t4')
print('range', r4.timeit(1000))

r5 = Timer('t5()', 'from __main__ import t5')
print('list range', r5.timeit(1000))


import torch

box1 = torch.tensor([[-0.1725, -0.2910,  0.2296,  0.3694],
        [-0.2984, -0.1456,  0.3558,  0.1891]])

box2 = torch.tensor([[-0.4034, -0.3760,  0.4146,  0.5000]])

def compute_iou(box1, box2):
    """Compute the intersection over union of two set of boxes, each box is [x1,y1,x2,y2].
    Args:
      box1: (tensor) bounding boxes, sized [N,4].
      box2: (tensor) bounding boxes, sized [M,4].
    Return:
      (tensor) iou, sized [N,M].
    """
    N = box1.size(0)
    M = box2.size(0)

    print('box1[:, :2].unsqueeze(1).expand(N, M, 2)', box1[:, :2].unsqueeze(1).expand(N, M, 2))
    print('box2[:, :2].unsqueeze(0).expand(N, M, 2)', box2[:, :2].unsqueeze(0).expand(N, M, 2))
    lt = torch.max(
        box1[:, :2].unsqueeze(1).expand(N, M, 2),  # [N,2] -> [N,1,2] -> [N,M,2]
        box2[:, :2].unsqueeze(0).expand(N, M, 2),  # [M,2] -> [1,M,2] -> [N,M,2]
    )

    rb = torch.min(
        box1[:, 2:].unsqueeze(1).expand(N, M, 2),  # [N,2] -> [N,1,2] -> [N,M,2]
        box2[:, 2:].unsqueeze(0).expand(N, M, 2),  # [M,2] -> [1,M,2] -> [N,M,2]
    )

    wh = rb - lt  # [N,M,2]
    wh[wh < 0] = 0  # clip at 0
    inter = wh[:, :, 0] * wh[:, :, 1]  # [N,M]

    area1 = (box1[:, 2] - box1[:, 0]) * (box1[:, 3] - box1[:, 1])  # [N,]
    area2 = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1])  # [M,]
    area1 = area1.unsqueeze(1).expand_as(inter)  # [N,] -> [N,1] -> [N,M]
    area2 = area2.unsqueeze(0).expand_as(inter)  # [M,] -> [1,M] -> [N,M]

    iou = inter / (area1 + area2 - inter)
    return iou

iou = compute_iou(box1, box2)

print(iou)


# 定义字符串变量name 输出我的名字叫 小明 请多多关照
name = "大小明"
print("我的名字叫 %s,请多多关照！" % name)
student_no = 1231231321
print("我的学号是 %06d" % student_no)
price = 9.8
weight = 10
money = price * weight
print("苹果的单价是 %.2f 元/斤，购买了 %.3f 斤，需要支付 %.4f 元" % (price, weight, money))
scale = 0.08
print("数据的比例是 %.2f%%" % (scale * 10))


def fshowtextwithoutscroll(text: str, pausebetweencharacters: number, clearscreenbetweenchars: bool, brigthness: number):
    global currentbrigthness
    currentbrigthness = led.brightness()
    led.set_brightness(brigthness)
    showtextwithoutscrollindex1 = 0
    while showtextwithoutscrollindex1 <= len("Hello"):
        basic.show_string(text.char_at(showtextwithoutscrollindex1))
        if clearscreenbetweenchars:
            basic.pause(pausebetweencharacters / 2)
            basic.clear_screen()
            basic.pause(pausebetweencharacters / 2)
        else:
            basic.pause(pausebetweencharacters)
        showtextwithoutscrollindex1 += 1
    led.set_brightness(currentbrigthness)
    return 0
def freversetext(texttoreverse: str):
    global reversetext, reverseindex
    reversetext = ""
    reverseindex = len(texttoreverse) - 1
    for index in range(len(texttoreverse)):
        reversetext = "" + reversetext + texttoreverse.char_at(reverseindex)
        reverseindex += -1
    return reversetext

def on_button_pressed_a():
    basic.show_string("" + (ftexttobackward(text2)))
input.on_button_pressed(Button.A, on_button_pressed_a)

def ftexttobackward(originaltext: str):
    global texttoreturn, originaltextlength, currentcharpositionindex, current_char
    texttoreturn = ""
    originaltextlength = len(originaltext)
    texttobackwardindex1 = 0
    while texttobackwardindex1 <= originaltextlength:
        currentcharpositionindex = originaltextlength - texttobackwardindex1
        current_char = originaltext.char_at(currentcharpositionindex)
        serial.write_string(current_char)
        texttoreturn = "" + texttoreturn + current_char
        texttobackwardindex1 += 1
    return texttoreturn

def on_button_pressed_b():
    basic.show_string("X")
    basic.pause(1000)
    fshowtextwithoutscroll(freversetext("Picur"), 100, True, 20)
    basic.show_string("X")
input.on_button_pressed(Button.B, on_button_pressed_b)

current_char = ""
currentcharpositionindex = 0
originaltextlength = 0
texttoreturn = ""
reverseindex = 0
reversetext = ""
currentbrigthness = 0
text2 = ""
text2 = "Picur"

def on_forever():
    pass
basic.forever(on_forever)


# Add the root path of the dmrgpy library
import os ; import sys ; sys.path.append(os.getcwd()+'/../../../src')

import numpy as np
from dmrgpy import spinchain,fermionchain
n = 6

site = 0

def get_spin():
    # create a random spin chain
    spins = ["S=1/2" for i in range(n)] # spin 1/2 heisenberg chain
    # create first neighbor exchange
    sc = spinchain.Spin_Chain(spins) # create the spin chain
    h = 0
    for i in range(n-1):
        h = h + sc.Sx[i]*sc.Sx[i+1]
        h = h + sc.Sy[i]*sc.Sy[i+1]
    sc.set_hamiltonian(h)
    name = (sc.Sx[site],sc.Sx[site]) # correlator to compute
    es = np.linspace(-0.5,3,2000)
    delta = 5e-2
    (x,y) = sc.get_dynamical_correlator(name=name,es=es,delta=delta)
    return (x,y)

def get_fermion():
    sc = fermionchain.Fermionic_Chain(n) # create the spin chain
    h = 0
    for i in range(n-1):
        h = h + sc.Cdag[i]*sc.C[i+1]/2.
    h = h + h.get_dagger()
    sc.set_hamiltonian(h)
    name = (sc.Cdag[site],sc.C[site]) # correlator to compute
    es = np.linspace(-0.5,3,2000)
    delta = 5e-2
    (x,y) = sc.get_dynamical_correlator(name=name,es=es,delta=delta)
    return (x,y/2)

(xs,ys) = get_spin()
(xf,yf) = get_fermion()

import matplotlib.pyplot as plt
plt.plot(xf,yf.real,c="blue",label="Fermion")
plt.scatter(xs,ys.real,c="red",label="Spin")
plt.legend()
plt.show()


class Edicao:
    def __init__(self, n_edicao, data, numero_a):
        self.n_edicao = n_edicao
        self.data = data
        self.numero_a = numero_a

class Revista:
    def __init__(self, titulo, codigo, tipo):
       self.titulo = titulo
       self.codigo = codigo
       self.tipo = tipo
       self.edicao = []

    def a_edicao(self, n_edicao, data, numero_a):
       self.edicao.append(Edicao(n_edicao, data, numero_a))

    def listar(self):
        print('Dados da revista')
        print('Titulo:', self.titulo, 'Codigo:', self.codigo, 'Tipo:', self.tipo)
        for edicao in self.edicao:
            print('Dados da edição:')
            print('Numero da edição:', edicao.n_edicao)
            print('Data de lançamento:', edicao.data)
            print('Numero de artigo:', edicao.numero_a)


from utils.admin_functions import admin_functions
from utils.user_functions import user_functions

class FoodDeliveryApp:
    """
    A simple Food Delivery App that allows users to place orders and admins to manage the food items.
    """

    def __init__(self):
        """
        Initializes the FoodDeliveryApp class and starts the application.
        """
        self.run()

    def welcome_screen(self):
        """
        Displays the welcome screen of the app and prompts the user to choose an option.
        """
        print("Welcome to the Food Delivery App!")
        print("1. Admin Login")
        print("2. User Login")
        print("3. Exit")

        choice = input("Please enter your choice: ")

        if choice == "1":
            self.admin_login()
        elif choice == "2":
            self.user_login()
        elif choice == "3":
            self.exit_program()
        else:
            print("Invalid choice. Please try again.")
            self.welcome_screen()

    def admin_login(self):
        """
        Prompts the admin to log in or register.
        """
        admin_functions.admin(self)

    def user_login(self):
        """
        Prompts the user to log in or register.
        """
        user_functions.user(self)

    def exit_program(self):
        """
        Exits the program.
        """
        print("Exiting the program. Goodbye!")

    def run(self):
        """
        Runs the Food Delivery App by displaying the welcome screen.
        """
        self.welcome_screen()

if __name__ == "__main__":
    app = FoodDeliveryApp()


import tensorflow as tf
from tensorflow.keras.layers import Dense, Dropout

class Additive_attn(tf.keras.layers.Layer):
    """
        attention_weights = softmax(a(q, k))  ;a is a scoring function
        a(q,k) = Wv tanh( Wq (q) + Wk (k) ) ∈ ℝ

        attention_pooling_output = attention_weights @ V

        query: 𝐪∈ℝ𝑞, key: 𝐤∈ℝ𝑘
        trainables: 𝐖𝑞∈ℝℎ×𝑞 , 𝐖𝑘∈ℝℎ×𝑘, and 𝐰𝑣∈ℝℎ.
    """
    def __init__(
        self,
        num_hiddens,
        dropout,
        **kwargs
        ) -> None:
        super().__init__(**kwargs)

        self.Wq = Dense(units=num_hiddens, use_bias=False)
        self.Wk = Dense(units=num_hiddens, use_bias=False)
        self.Wv = Dense(units=1, use_bias=False)
        self.dropout = Dropout(dropout)

        self.num_hiddens = num_hiddens

    def masked_softmax(self, X, valid_len):
        if valid_len is None: return X
        # mask unused
        seq_mask_bool = tf.sequence_mask(valid_len, maxlen=X.shape[-1])
        seq_mask_float = tf.cast(seq_mask_bool, dtype=tf.float32)

        # reshape mask to the same as X
        seq_mask_float = tf.reshape(seq_mask_float, shape=X.shape)
        seq_mask_bool = tf.reshape(seq_mask_bool, shape=X.shape)

        # multiply X by mask
        X = tf.multiply(tf.cast(X, dtype=tf.float32), seq_mask_float)

        # change masked from 0.0 to -1e6
        value_mask = tf.where(seq_mask_bool, 0.0, -1e6)
        X_masked = X + value_mask

        return tf.nn.softmax(X_masked, axis=-1)

    def call(self, Q, K, V, valid_len, **kwargs):
        """
            Q: (, 1, dec_emb_size)
            K: (, enc_steps, enc_n_hiddens) ;same as K
        """
        Q = self.Wq(Q)  # (, 1, num_hiddens)
        K = self.Wk(K)  # (, enc_steps, num_hiddens)

        attn_weights = self.Wv(tf.nn.tanh(Q + K)) # (, enc_steps, num_hiddens) @ (, 1) = (, enc_steps, 1)

        attn_weights = tf.transpose(attn_weights, perm=[0,2,1]) # (, 1, enc_steps)
        self.attention_weights = self.masked_softmax(attn_weights, valid_len) # (, 1, enc_steps)

        attn_pooling_output = self.dropout(self.attention_weights) @ V # (, 1, enc_steps) @ (, enc_steps, enc_num_hiddens) = (, 1, enc_num_hiddens)

        return attn_pooling_output

if __name__ == '__main__':
    import sys
    query = sys.argv[1]
    print(query)

    if query == 'call':
        batch_size = 3
        n_queries = 1
        dec_emb_size = 10

        enc_steps = 15
        enc_num_hiddens = 64

        Q = tf.random.normal(shape=(batch_size, n_queries, dec_emb_size))
        K = V = tf.random.normal(shape=(batch_size, enc_steps, enc_num_hiddens))

        valid_lens = tf.constant([2, 6, 10])

        attn = Additive_attn(num_hiddens=9, dropout=0.5)

        outputs = attn(Q, K, V, valid_lens)
        print("attn weights =",attn.attention_weights.shape)
        print("pooling outputs =",outputs.shape)


'''
file: cmdParser.py

brief: cmdParser validates command line args and parses them into a dict object

https://github.com/AlexanderJDupree/GithubNetwork
'''

import argparse

VIS_LAYOUTS = ['spring', 'kamada-kawai', 'random', 'spectral', 'circular', 'shell']

FILE_FORMATS = [ 'graphml', 'pickle', 'adjacency_list', 'gexf', 'yaml', 'edge_list' ]

COLOR_MAPS = ['rainbow', 'purples', 'greys', 'blues', 'greens', 'yellow-red',
              'spring', 'summer', 'cool', 'hot', 'gnuplot', 'twilight', 'coolwarm']

def validateInteger(arg, lbound, ubound):
    value = int(arg)
    if value < lbound or value > ubound:
        raise argparse.ArgumentTypeError(
                f'{arg} is not within range {lbound}..{ubound}'
                )
    return value

def validateDiameter(arg):
    return validateInteger(arg, 1, 100)

def validateMaxNodes(arg):
    return validateInteger(arg, 1, 5000)

def validateArrowSize(arg):
    return validateInteger(arg, 1, 20)

# TODO Flags require an argument when they shouldn't.
def parse(argv):

    parser = argparse.ArgumentParser(
            description="Visualize your your GitHub social network!"
            )
    parser.add_argument(
            'user',
            metavar='USERNAME',
            help="<USERNAME> of a Github profile"
            )
    parser.add_argument(
            '-d', '--diameter',
            type=validateDiameter,
            metavar='',
            default=5,
            help="<NUMBER> length of the longest shortest path from the user. Default=5"
            )
    parser.add_argument(
            '-m', '--max',
            type=validateMaxNodes,
            metavar='',
            default=500,
            help="max <NUMBER> of nodes in the graph. Default=500"
            )
    parser.add_argument(
            '-v', '--vis',
            choices=VIS_LAYOUTS,
            metavar='',
            default=VIS_LAYOUTS[0],
            help="Graph visualization <LAYOUT>. Default={}. Layouts are \n\t{}".format(
                VIS_LAYOUTS[0], '\n\t'.join(VIS_LAYOUTS))
            )
    parser.add_argument(
            '-o', '--output',
            metavar='',
            default='network.png',
            help='Desired <FILE NAME> of output. Default=network.png'
            )
    parser.add_argument(
            '-l', '--labels',
            metavar='',
            default=False,
            help="Display labels with each node. Default=False"
            )
    parser.add_argument(
            '-a', '--arrowsize',
            type=validateArrowSize,
            metavar='',
            default=10,
            help="Specify size of arrows. <NUMBER>. Default=10"
            )
    parser.add_argument(
            '-s', '--scale',
            type=float,
            metavar='',
            default=1.0,
            help="Scale the size of each nodes. <FLOAT>. Default=1.0"
            )
    parser.add_argument(
            '-n', '--normalize',
            type=bool,
            metavar='',
            default=False,
            help="Normalize the size of each node. Default=False"
            )
    parser.add_argument(
            '-w', '--width',
            type=float,
            metavar='',
            default=1.0,
            help="Width of edge lines <FLOAT>. Default=1.0"
            )
    parser.add_argument(
            '-f', '--figsize',
            type=int,
            nargs=2,
            metavar='',
            choices=range(1, 100),
            default=(20,20),
            help="Figure size tuple: (<WIDTH>,<HEIGHT>), default=(20,20)"
            )
    parser.add_argument(
            '-x', '--axis',
            type=bool,
            metavar='',
            default=False,
            help="Display graphs x/y axis. Default=False"
            )
    parser.add_argument(
            '-b', '--bar',
            type=bool,
            metavar='',
            default=False,
            help="Add a colorbar to the table. Default=False"
            )
    parser.add_argument(
            '-c', '--colormap',
            metavar='',
            choices=COLOR_MAPS,
            default=COLOR_MAPS[0],
            help="Color Mapping palette. Default=rainbow. Options: {}".format(
                '\n'.join(COLOR_MAPS)
                )
            )
    parser.add_argument(
            '--format',
            choices=FILE_FORMATS,
            default=FILE_FORMATS[0],
            help="Graph output file format. Default={}.".format(
                FILE_FORMATS[0]
            ))

    # Returns a dict object
    return vars(parser.parse_args(argv))