# This file's a bit out of place vs. the rest of
# the architecture. Basically, Vinay wrote it on a
# plane on his way to vegas to test some poker
# probabilities, and, not wanting to write it all
# again for the holdem game, I just slapped it in
# and imported it.

#!/usr/bin/env python
STRAIGHT_FLUSH = 8
FOUR_OF_A_KIND = 7
FULL_HOUSE = 6
FLUSH = 5
STRAIGHT = 4
THREE_OF_A_KIND = 3
TWO_PAIR = 2
PAIR = 1
HIGH_CARD = 0

HAND_NAMES = ("HIGH_CARD", "PAIR", "TWO_PAIR", "THREE_OF_A_KIND", "STRAIGHT",
              "FLUSH", "FULL_HOUSE", "FOUR_OF_A_KIND", "STRAIGHT_FLUSH")

class Card(object):
    #SUITS = ['s', 'h', 'd', 'c']
    SUITS = [u"\u2660", u"\u2665", u"\u2666", u"\u2663"]
    RANKS = "A23456789TJQKA"

    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __repr__(self):
        rank = self.RANKS[self.rank]
        if rank == 'T':
            rank = '10'
        rep = u"%s%s" % (rank, self.SUITS[self.suit - 1])
        return rep.encode('utf-8')

    def encoded(self):
        return self.suit * 13 + self.rank

def cmp_rank(x, y):
    return y.rank - x.rank

def cmp_suit_rank(x, y):
    return y.rank - x.rank if x.suit == y.suit else x.suit - y.suit

def initialize_deck():
    for suit in range(1, 5):
        for rank in range(1, 14):
            deck.append(Card(suit, rank))

def find_straight_flush(cards):
    cards_aces_high = cards
    cards_aces_low = [Card(x.suit, 0) if x.rank == 13 else x for x in cards]

    for cards in (cards_aces_high, cards_aces_low):
        cards.sort(cmp=cmp_suit_rank)
        for i in range(3):
            high = cards[i]
            low = cards[i + 4]
            if low.suit == high.suit and high.rank == low.rank + 4:
                return (STRAIGHT_FLUSH, cards[i:i + 5], [])
    return None

def find_four_of_a_kind(cards):
    cards.sort(cmp=cmp_rank)
    for i in range(4):
        if cards[i].rank == cards[i + 3].rank:
            hand = cards[i:i + 4]
            rest = cards[0:i] + cards[i + 4:7]
            return (FOUR_OF_A_KIND, hand, [rest[0]])
    return None

def find_full_house(cards):
    cards.sort(cmp=cmp_rank)
    for i in range(5):
        if cards[i].rank == cards[i + 2].rank:
            hand = cards[i:i + 3]
            rest = cards[0:i] + cards[i + 3:7]
            for j in range(3):
                if rest[j].rank == rest[j + 1].rank:
                    hand += rest[j:j + 2]
                    return (FULL_HOUSE, hand, [])

def find_flush(cards):
    cards.sort(cmp=cmp_suit_rank)
    for i in range(3):
        if cards[i].suit == cards[i + 4].suit:
            return (FLUSH, cards[i:i + 5], [])

def find_straight(cards):
    cards_aces_high = cards
    cards_aces_low = [Card(x.suit, 0) if x.rank == 13 else x for x in cards]

    for cards in (cards_aces_high, cards_aces_low):
        # Sort and remove cards with duplicated ranks
        cards.sort(cmp=cmp_rank)
        cards = [cards[i] for i in range(len(cards)) if cards[i].rank != cards[i - 1].rank]
        for i in range(len(cards) - 5 + 1):
            if cards[i].rank == cards[i + 4].rank + 4:
                return (STRAIGHT, cards[i:i + 5], [])
    return None

def find_three_of_a_kind(cards):
    cards.sort(cmp=cmp_rank)
    for i in range(5):
        if cards[i].rank == cards[i + 2].rank:
            hand = cards[i:i + 3]
            rest = cards[0:i] + cards[i + 3:7]
            return (THREE_OF_A_KIND, hand, rest[:2])
    return None

def find_two_pair(cards):
    cards.sort(cmp=cmp_rank)
    for i in range(6):
        if cards[i].rank == cards[i + 1].rank:
            hand = cards[i:i + 2]
            rest = cards[0:i] + cards[i + 2:7]
            for j in range(4):
                if rest[j].rank == rest[j + 1].rank:
                    hand += rest[j:j + 2]
                    rest = rest[0:j] + rest[j + 2:5]
                    return (TWO_PAIR, hand, [rest[0]])
    return None

def find_pair(cards):
    cards.sort(cmp=cmp_rank)
    for i in range(6):
        if cards[i].rank == cards[i + 1].rank:
            hand = cards[i:i + 2]
            rest = cards[0:i] + cards[i + 2:7]
            return (PAIR, hand, rest[:3])
    return None

def find_high_card(cards):
    cards.sort(cmp=cmp_rank)
    return (HIGH_CARD, [cards[0]], cards[1:5])

def find_best_hand(cards):
    for func in [find_straight_flush,
                 find_four_of_a_kind,
                 find_full_house,
                 find_flush,
                 find_straight,
                 find_three_of_a_kind,
                 find_two_pair,
                 find_pair,
                 find_high_card
                 ]:
        res = func(cards)
        if res is not None:
            return res

def get_ranks(x):
    return [i.rank for i in x]

def cmp_hands(x, y):
    if x[0] == y[0]:
        xhr = get_ranks(x[1])
        yhr = get_ranks(y[1])
        if (xhr == yhr):
            xkr = get_ranks(x[2])
            ykr = get_ranks(y[2])
            if xkr == ykr:
                return 0
            elif xkr < ykr:
                return 1
            else:
                return -1
        elif xhr < yhr:
            return 1
        else:
            return -1
    else:
        return y[0] - x[0]

def find_winners(hands):
    best_type = max([h[0] for h in hands])
    hands = filter(lambda x: x[0] == best_type, hands)

    if len(hands) == 1:
        return [hands[0][3]]

    for i in range(len(hands)):
        hand = hands[i]
        hands[i] = (hand[0],
                    [h.rank for h in hand[1]],
                    [h.rank for h in hand[2]],
                    hand[3])
    best_hand = max([h[1] for h in hands])
    hands = filter(lambda x: x[1] == best_hand, hands)
    if len(hands) == 1:
        return [hands[0][3]]

    best_kicker = max([h[2] for h in hands])
    hands = filter(lambda x: x[2] == best_kicker, hands)

    return [h[3] for h in hands]


r"""This module contains unit tests for the trajectory module

.. moduleauthor:: B.Trendelkamp-Schroer <benjamin DOT trendelkamp-schroer AT fu-berlin DOT de>

"""
import os
import unittest

import numpy as np

from os.path import abspath, join
from os import pardir

from msmtools.dtraj import read_discrete_trajectory, write_discrete_trajectory, \
    load_discrete_trajectory, save_discrete_trajectory

testpath = abspath(join(abspath(__file__), pardir)) + '/testfiles/'
filename_csv = testpath + 'dtraj.dat'
filename_npy = testpath + 'dtraj.npy'
assert os.path.exists(filename_csv)
assert os.path.exists(filename_npy)

class TestReadDiscreteTrajectory(unittest.TestCase):

    def test_read_discrete_trajectory(self):
        dtraj_np = np.loadtxt(filename_csv, dtype=int)
        dtraj = read_discrete_trajectory(filename_csv)
        self.assertTrue(np.all(dtraj_np == dtraj))

class TestWriteDiscreteTrajectory(unittest.TestCase):
    def setUp(self):
        import tempfile
        self.filename = tempfile.mktemp(suffix='.dat')
        self.dtraj = np.arange(10000)

    def tearDown(self):
        os.remove(self.filename)

    def test_write_discrete_trajectory(self):
        write_discrete_trajectory(self.filename, self.dtraj)
        dtraj_n = np.loadtxt(self.filename)
        self.assertTrue(np.all(dtraj_n == self.dtraj))

class TestLoadDiscreteTrajectory(unittest.TestCase):
    def test_load_discrete_trajectory(self):
        dtraj_n = np.load(filename_npy)
        dtraj = load_discrete_trajectory(filename_npy)
        self.assertTrue(np.all(dtraj_n == dtraj))

class TestSaveDiscreteTrajectory(unittest.TestCase):
    def setUp(self):
        import tempfile
        self.filename = tempfile.mktemp(suffix='.npy')
        self.dtraj = np.arange(10000)

    def tearDown(self):
        os.remove(self.filename)

    def test_save_discrete_trajectory(self):
        save_discrete_trajectory(self.filename, self.dtraj)
        dtraj_n = np.load(self.filename)
        self.assertTrue(np.all(dtraj_n == self.dtraj))

if __name__ == "__main__":
    unittest.main()


def findMedianSortedArrays(nums1: List(int), nums2: List(int)) -> float:
    lists1 = 0
    lists = nums1 + nums2
    # sorted_lists = sorted(lists)
    def bubble(nums):
        n = len(nums)

        for i in range(n-1):
            if nums[i] > nums[i+1]:
                nums[i], nums[i+1] = nums[i+1], nums[i]

    def bubble_sort(nums):
        n = len(nums)

        for _ in range(n-1):
            if bubble(nums) == 0:
                break

        print(nums)
    bubble_sort(lists)
    if len(lists) % 2 == 0:
        l_num = (len(lists)-1)//2
        lists1 = (lists[l_num] + lists[l_num+1])/2
    else:
        l_num = (len(lists)-1)//2
        lists1 = lists[l_num]
    return lists1

print(findMedianSortedArrays([3], [-2, -1]))


# 행렬덧셈
# https://programmers.co.kr/learn/courses/30/lessons/12950

#해결 - 나의 풀이
def solution(arr1, arr2):
    answer = []
    Number = len(arr1)
    for i in range(Number) :
        tempNumber = len(arr1[i])
        templist = []
        for j in range(tempNumber) :
            summ = arr1[i][j] + arr2[i][j]
            templist.append(summ)
        answer.append(templist)
    return answer

print(solution([[1,2],[2,3]],[[3,4],[5,6]]))

# 다른 사람의 풀이
def sumMatrix(A,B):
    answer = [[c + d for c, d in zip(a, b)] for a, b in zip(A,B)]
    return answer


import os
import yaml
from common_utils import MetaSingleton

app_path = os.path.abspath(os.path.dirname(__file__))
base_path = os.path.abspath(os.path.dirname(app_path))
configs_path = os.path.join(base_path,'configs/')

app_env = os.getenv('APP_ENV') if os.getenv('APP_ENV') else 'default'

class FileConfig(metaclass=MetaSingleton):
    def __init__(self,cfg_file='default_configs.yaml'):
        self._yaml_cfg = FileConfig.__get_config_file(cfg_file)
        self.server_cfg = self._yaml_cfg.get('server',None)
        self.mysql_cfg = self._yaml_cfg.get('mysql',None)
        self.redis_cfg = self._yaml_cfg.get("redis",None)

    @staticmethod
    def __get_config_file(cfg_file):
        cfg_path = os.path.join(configs_path,cfg_file)
        if os.path.exists(cfg_path) and os.path.isfile(cfg_path):
            with open(cfg_path,encoding='utf-8') as f:
                return yaml.load(f.read())
    @staticmethod
    def get_config():
        if 'development' == app_env:
            return FileConfig('development_configs.yaml')
        elif 'production' == app_env:
            return FileConfig('production_configs.yaml')
        else:
            return FileConfig('default_configs.yaml')

class ServerConfig(metaclass=MetaSingleton):
    def __init__(self):
        for k,v in FileConfig.get_config().server_cfg.items():
            object.__setattr__(self,k,v)

class MysqlConfig(metaclass=MetaSingleton):
    def __init__(self):
        for k,v in FileConfig.get_config().mysql_cfg.items():
            object.__setattr__(self,k,v)
    def get_uri(self):
        return self.uri

class RedisConfig(metaclass=MetaSingleton):
    def __init__(self):
        for k,v in FileConfig.get_config().redis_cfg.items():
            object.__setattr__(self,k,v)


#!/usr/bin/python3

"""Script that prints the first State object from the database hbtn_0e_6_usa
"""

if __name__ == "__main__":
    import sys
    from sqlalchemy.orm import sessionmaker, Session
    from sqlalchemy import (create_engine)
    from model_state import Base, State

    engine = create_engine(f"mysql+mysqldb://{sys.argv[1]}\
:{sys.argv[2]}@localhost/{sys.argv[3]}")

    Session = sessionmaker(bind=engine)
    session = Session()

    q = session.query(State).first()

    if q:
        print(f"{q.id}: {q.name}")
    else:
        print("Nothing")


from flask import Flask, render_template, request, session
from flask_socketio import SocketIO, emit, join_room
import platform

app = Flask(__name__)
app.config['SECRET_KEY'] = "wubba lubba dub dub"

socketio = SocketIO(app)

users_in_room = {}
rooms_sid = {}
names_sid = {}

@app.route("/join", methods=["GET"])
def join():
    display_name = request.args.get('display_name')
    mute_audio = request.args.get('mute_audio') # 1 or 0
    mute_video = request.args.get('mute_video') # 1 or 0
    room_id = request.args.get('room_id')
    session[room_id] = {"name": display_name,
                        "mute_audio": mute_audio, "mute_video": mute_video}
    return render_template("join.html", room_id=room_id, display_name=session[room_id]["name"], mute_audio=session[room_id]["mute_audio"], mute_video=session[room_id]["mute_video"])

@socketio.on("connect")
def on_connect():
    sid = request.sid
    print("New socket connected ", sid)

@socketio.on("join-room")
def on_join_room(data):
    sid = request.sid
    room_id = data["room_id"]
    display_name = session[room_id]["name"]

    # register sid to the room
    join_room(room_id)
    rooms_sid[sid] = room_id
    names_sid[sid] = display_name

    # broadcast to others in the room
    print("[{}] New member joined: {}<{}>".format(room_id, display_name, sid))
    emit("user-connect", {"sid": sid, "name": display_name},
         broadcast=True, include_self=False, room=room_id)

    # add to user list maintained on server
    if room_id not in users_in_room:
        users_in_room[room_id] = [sid]
        emit("user-list", {"my_id": sid})  # send own id only
    else:
        usrlist = {u_id: names_sid[u_id]
                   for u_id in users_in_room[room_id]}
        # send list of existing users to the new member
        emit("user-list", {"list": usrlist, "my_id": sid})
        # add new member to user list maintained on server
        users_in_room[room_id].append(sid)

    print("\nusers: ", users_in_room, "\n")

@socketio.on("disconnect")
def on_disconnect():
    sid = request.sid
    room_id = rooms_sid[sid]
    display_name = names_sid[sid]

    print("[{}] Member left: {}<{}>".format(room_id, display_name, sid))
    emit("user-disconnect", {"sid": sid},
         broadcast=True, include_self=False, room=room_id)

    users_in_room[room_id].remove(sid)
    if len(users_in_room[room_id]) == 0:
        users_in_room.pop(room_id)

    rooms_sid.pop(sid)
    names_sid.pop(sid)

    print("\nusers: ", users_in_room, "\n")

@socketio.on("data")
def on_data(data):
    sender_sid = data['sender_id']
    target_sid = data['target_id']
    if sender_sid != request.sid:
        print("[Not supposed to happen!] request.sid and sender_id don't match!!!")

    if data["type"] != "new-ice-candidate":
        print('{} message from {} to {}'.format(
            data["type"], sender_sid, target_sid))
    socketio.emit('data', data, room=target_sid)

if any(platform.win32_ver()):
    socketio.run(app, debug=True)


import requests
import json
import os
import pika

def callback(ch, method, body):
    print(f"Received Result: {body.decode()}")
    ch.basic_ack(delivery_tag=method.delivery_tag)
    connection.close()

# Get abs paths of images
current_dir = os.path.dirname(os.path.abspath(__file__))
image_path1 = os.path.join(current_dir, '../images', 'ireland1.jpg')
image_path2 = os.path.join(current_dir, '../images', 'ireland1delete.jpg')

# Send POST request to /enqueue
url_enqueue = 'http://localhost:5000/enqueue'
headers = {'Content-Type': 'application/json'}
data = {
    'image_path1': image_path1,
    'image_path2': image_path2
}
response_enqueue = requests.post(url_enqueue, headers=headers, data=json.dumps(data))
# remove me
print(response_enqueue.json())

# Listen to results MQ after POST request sent
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='results_queue', durable=True)

channel.basic_consume(queue='results_queue', on_message_callback=callback)
channel.start_consuming()


#!/usr/bin/env python
# Given an N * N matrix where each row and  column is sorted in ascending order, find
# the Kth smallest element in the matrix.
import heapq

def kSmallest( matrix, k ):
   minHeap = []
   clen = len( matrix[ 0 ] )
   count = 0

   for i in range( len( matrix ) ):
      heapq.heappush( minHeap, ( matrix[ i ][ 0 ], i, 1 ) )

   curVal = None
   while count < k:
      value, rIndex, cIndex = heapq.heappop( minHeap )
      curVal = value
      count += 1
      if cIndex < clen:
         heapq.heappush( minHeap, ( matrix[ rIndex ][ cIndex ], rIndex, cIndex + 1 ) )

   return curVal

testCases = [
   {
      'matrix' : [
         [2, 6, 8],
         [3, 7, 10],
         [5, 8, 11]
      ],
      'k' : 5,
      'output' : 7,
   },
]

for test in testCases:
   m = test[ 'matrix' ]
   k = test[ 'k' ]
   o = test[ 'output' ]
   assert( kSmallest( m, k ) == o )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pendulum
import re
from dleveryfriday import _vars
from dleveryfriday.log import log

# Set correct timezone and locale
tz = pendulum.timezone("Europe/Oslo")
locale = pendulum.set_locale('nb')
pendulum.week_starts_at(pendulum.MONDAY)
pendulum.week_ends_at(pendulum.SUNDAY)

def make_dt(date_in):
    # TODO Check and make some tests
    '''
    Make a datetime-object from string input

    Handles the following input:
    - 17.05.22
    - 17.05.20 22
    - 17.05.2022 1122
    - 17.05.2022, 11.22
    - 17.05.2022, 1122
    - 17.05.20 22, 11.22
    - 2022-05-17T11:22:00Z
    '''
    if 'T' in str(date_in):
        return pendulum.parse(date_in)
    else:
        # Remove all special characters from input
        date_in = re.sub(r'\s+|\s*,\s*| |\\/.+|:+|-+', ' ', str(date_in).strip())
        # Count the number of datetime-units in input
        d_split = re.split(' ', date_in)
        d_len = len(d_split)
        # Decide how to interpret the input
        try:
            log.log_more('`date_in` is {}'.format(date_in))
            log.log_more(f'Got `d_len` {d_len}')
            log.log_more(f'd_split: {d_split}')
            if d_len == 2:
                log.debug('d_len is 2')
                if not re.match(r'^\d{2}[\.]\d{2}[\.]\d{2}', d_split[0]):
                    log.debug('Not only dots as separators')
                    _splitsymbols = re.match(r'^\d{2}([\-\.\_])\d{2}([\-\.\_])\d{2}', d_split[0])
                    new_split = ''
                    i = 3
                    while i != 0:
                        new_split += d_split[0].replace(_splitsymbols.group(i), '.')
                        i -= 1
                return pendulum.from_format(
                    date_in, 'DD.MM.YYYY HH.mm', tz=tz
                )
            elif d_len == 3:
                # Expecting `DD MM YYYY`, `YYY MM DD` or `DD MM YY`
                if len(d_split[2]) == 4:
                    return pendulum.from_format(date_in, 'DD MM YYYY', tz=tz)
                elif len(d_split[0]) == 4:
                    return pendulum.from_format(date_in, 'YYYY MM DD', tz=tz)
                elif all(len(timeunit) == 2 for timeunit in d_split):
                    # We have to assume that this is DD MM YY
                    return pendulum.from_format(date_in, 'DD MM YY', tz=tz)
            elif d_len == 4:
                # Expecting a wrong space or separator somewhere
                # If all units have 2 in len, then it could be a split in YYYY,
                if all(len(timeunit) == 2 for timeunit in d_split):
                    d = d_split
                    date_in = f'{d[0]} {d[1]} {d[2]}{d[3]}'
                    return pendulum.from_format(
                        date_in, 'DD MM YYYY', tz=tz
                    )
                # If the fourth and last unit has a len of 4, it probably
                # is the time with a missing separator
                elif all(len(timeunit) == 2 for timeunit in d_split[0:2])\
                        and len(d_split[3]) == 4:
                    d_split[3] = '{} {}'.format(
                        d_split[3][0:2],
                        d_split[3][2:4]
                    )
                    if len(d_split[2]) == 2:
                        d_split[2] = '20{}'.format(
                            d_split[2]
                        )
                    d = d_split
                    date_in = f'{d[0]} {d[1]} {d[2]} {d[3]}'
                    date_in = date_in.strip()
                    log.log_more('date_in: {}'.format(date_in))
                    return pendulum.from_format(
                        date_in, 'DD MM YYYY HH mm', tz=tz
                    )
            elif d_len == 5:
                if len(d_split[2]) == 4:
                    return pendulum.from_format(date_in, 'DD MM YYYY HH mm', tz=tz)
                elif len(d_split[0]) == 4:
                    return pendulum.from_format(date_in, 'YYYY MM DD HH mm', tz=tz)
                elif len(d_split[2]) == 2:
                    return pendulum.from_format(date_in, 'DD MM YY HH mm', tz=tz)
                elif len(d_split[0]) == 2:
                    return pendulum.from_format(date_in, 'YY MM DD HH mm', tz=tz)
            elif d_len == 6:
                # A split of 6 is most likely a split in YYYY
                if all(len(timeunit) == 2 for timeunit in d_split):
                    d = d_split
                    date_in = f'{d[0]} {d[1]} {d[2]}{d[3]} {d[4]} {d[5]}'
                    return pendulum.from_format(
                        date_in, 'DD MM YYYY HH mm', tz=tz
                    )
                pass
            else:
                return None
            log.log_more('-'*10)
        except(ValueError):
            log.log_more('-'*10)
            return None

def get_dt(format='epoch', sep='.', dt=False):
    # TODO Check and make some tests
    '''
    Get a datetime object in preferred dateformat.
    - If the datetime-input `dt` is not specified, it will use
        `pendulum.now()`.
    - If `sep` (separator) isn't specified, it will use dots.
    - If `format` is not specified, it will return in epoch/linux time-format
    ```
    Formats:
    (Example date: May 17th 2014; time: 14:23:39; timezone: GMT)
    `date`:             17.05.2014
    `datetext`:         17 May 2014
    `datetextfull`:     17 May 2014, 14.23
    `revdate`:          2014.05.17
    `datetime`:         17.05.2014 14.23
    `datetimefull`:     17.05.2014 14.23.39
    `revdatetimefull`:  2014.05.17 14.23.39
    `time`:             14.23
    `timefull`:         14.23.39
    `week`:             20
    `year`:             2014
    `month`:            05
    `day`:              17
    `dayname`:          Sunday
    `dayofweek`:        7
    `epoch`:            1400336619
    ```
    '''
    if type(dt) == str:
        dt = make_dt(dt)
        if dt is None:
            print('Can\'t process date `{}`. Aborting.'.format(dt))
            return None
    elif not dt:
        dt = pendulum.now(tz)
    if format == 'date':
        return dt.format(f'DD{sep}MM{sep}YYYY')
    elif format == 'datetext':
        return dt.format(f'DD{sep} MMMM YYYY', locale=locale)
    elif format == 'datetextfull':
        return dt.format(f'DD{sep} MMMM YYYY, HH{sep}mm', locale=locale)
    elif format == 'revdate':
        return dt.format(f'YYYY{sep}MM{sep}DD')
    elif format == 'datetime':
        return dt.format(f'DD{sep}MM{sep}YYYY HH{sep}mm')
    elif format == 'datetimefull':
        return dt.format(f'DD{sep}MM{sep}YYYY HH{sep}mm{sep}ss')
    elif format == 'revdatetimefull':
        return dt.format(f'YYYY{sep}MM{sep}DD HH{sep}mm{sep}ss')
    elif format == 'time':
        return dt.format(f'HH{sep}mm')
    elif format == 'timefull':
        return dt.format(f'HH{sep}mm{sep}ss')
    elif format == 'week':
        return dt.week_of_year
    elif format == 'year':
        return dt.format(f'YYYY')
    elif format == 'month':
        return dt.format(f'MM')
    elif format == 'day':
        return dt.format(f'DD')
    elif format == 'dayname':
        return dt.format(f'dddd')
    elif format == 'dayofweek':
        return dt.format(f'E')
    elif format == 'epoch':
       return dt.int_timestamp
    else:
        return None

def change_dt(
    pendulum_object_in, change=None, count=None, unit=None
):
    '''
    Take a pendulum datetime object and change it relatively

    `pendulum_object_in`: The object to change

    `change`: Accepts `add` or `remove`

    `count`: How many `units` to change

    `unit`: Unit to change. Accepted units are `years`, `months`, `days`,
        `hours`, `minutes` and `seconds`'''
    if change is None or unit is None or count is None:
        log.log(_vars.TOO_FEW_ARGUMENTS)
        return None
    accepted_units=['years', 'months', 'days', 'hours', 'minutes', 'seconds']
    if unit not in accepted_units:
        log.log(f'Unit `{unit}` is not accepted')
        return None
    if not isinstance(count, (int, float)):
        log.log(f'Count `{count}` is not a number')
        return None
    p = pendulum_object_in
    if change == 'add':
        return eval(f'p.add({unit}={count})')
    elif change == 'remove':
        return eval(f'p.subtract({unit}={count})')

def is_date1_more_than_date2(date1, date2):
    date1 = get_dt(format='epoch', dt=make_dt(date1))
    date2 = get_dt(format='epoch', dt=make_dt(date2))
    if date1 > date2:
        return True
    else:
        return False

if __name__ == "__main__":
    #pass
    print(get_dt(format='dayofweek', dt=make_dt('17.05.2014, 14.23')))


import mapquest_api

class elevation:
    """Creates an object which gives out the
    elevations of the locations input"""
    def __init__(self,json_output:dict):
        self._all = latandlong(json_output).latlong()
        self._info = mapquest_api.convert_elevation(self._all)
    def output(self):
        """Prints elevation"""
        dictionaries = self._info
        print()
        print("ELEVATION")
        for json_output in dictionaries:
                print(round(json_output['elevationProfile'][0]['height']))

class total_distance:
    """Creates an object which gives out the total
    distance of the locations input"""
    def __init__(self,json_output:dict):
        self._info = json_output
    def output(self):
        """Prints total distance"""
        json_output = self._info
        print("TOTAL DISTANCE:", round(json_output["route"]["distance"]),"miles")

class narrative_directions:
    """Creates an object which gives out the directions from
    location to location."""
    def __init__(self,json_output:dict):
        self._info = json_output
    def output(self):
        """Prints directions"""
        json_output = self._info
        print("\nDIRECTIONS")
        for obj in json_output["route"]["legs"]:
            for item in (obj["maneuvers"]):
                print(item['narrative'])
        print()

class total_time:
    """Creates an object which gives out the total time
    from location to location"""
    def __init__(self,json_output:dict):
        self._info = json_output
    def output(self):
        """Prints total time"""
        json_output = self._info
        data = json_output["route"]["time"] / 60
        print("TOTAL TIME:", round(data), 'minutes')
        print()

class latandlong:
    """Creates an object which gives out the latitude and longitude
    from location to location"""
    def __init__(self,json_output:dict):
        self._info = json_output
    def output(self):
        """Prints latitude and longitude"""
        json_output = self._info
        data = json_output["route"]["locations"]
        print("\nLATLONGS")
        for obj in data:
            lat = (obj["displayLatLng"]["lat"])
            lng = ((obj["displayLatLng"]["lng"]))
            if lat > 0:
                direction_lat = "N"
            else:
                direction_lat = "S"
            if lng > 0:
                direction_lng = "E"
            else:
                direction_lng = "W"
            print('{0:.2f}'.format(abs(lat))+direction_lat + " " + '{0:.2f}'.format(abs(lng)) + direction_lng)
    def latlong (self) -> list:
        """Gets elevation url parameters."""
        json_output = self._info
        data = json_output["route"]["locations"]
        lat_long_list = []
        for obj in data:
            lat_long = []
            lat_long.append(obj["displayLatLng"]["lat"])
            lat_long.append((obj["displayLatLng"]["lng"]))
            lat_long_list.append(lat_long)
        return lat_long_list

class Sorter:
    """Prints in order of input requested"""
    def __init__(self,json_output:dict,input_list:list):
        self._info = json_output
        self._input = input_list
    def sorted_output(self):
        info = self._info
        input_list = self._input
        sorted_list = []
        if info['info']['messages'] == []:
            for obj in input_list:
                if obj == "LATLONG":
                    sorted_list.append(latandlong(info))
                elif obj == "STEPS":
                    sorted_list.append(narrative_directions(info))
                elif obj == "TOTALTIME":
                    sorted_list.append(total_time(info))
                elif obj == "TOTALDISTANCE":
                    sorted_list.append(total_distance(info))
                elif obj == "ELEVATION":
                    sorted_list.append(elevation(info))
                else:
                  pass
            return sorted_list
        else:
            return None
    def returnOutput(self):
        """Returns output as per the requested order."""
        output = self.sorted_output()
        if output == None:
            print('\nNO ROUTE FOUND')
        else:
            try:
                for obj in output:
                    obj.output()
            finally:
                print()
                print("Directions Courtesy of MapQuest; Map Data Copyright OpenStreetMap Contributors")


# -*- coding: utf-8 -*-

from gluon.contrib.appconfig import AppConfig
from gluon.tools import Auth

if request.global_settings.web2py_version < "2.15.5":
    raise HTTP(500, "Requires web2py 2.15.5 or newer")

configuration = AppConfig(reload=True)

if not request.env.web2py_runtime_gae:
    db = DAL(configuration.get('db.uri'),
             pool_size=configuration.get('db.pool_size'),
             migrate_enabled=configuration.get('db.migrate'),
             check_reserved=['all'])
else:
    db = DAL('google:datastore+ndb')
    session.connect(request, response, db=db)

response.generic_patterns = []
if request.is_local and not configuration.get('app.production'):
    response.generic_patterns.append('*')

response.formstyle = 'bootstrap4_inline'
response.form_label_separator = ''
auth = Auth(db, host_names=configuration.get('host.names'))
auth.settings.extra_fields['auth_user'] = []
auth.define_tables(username=False, signature=False)

#mail = auth.settings.mailer
#mail.settings.server = 'logging' if request.is_local else configuration.get('smtp.server')
#mail.settings.sender = configuration.get('smtp.sender')
#mail.settings.login = configuration.get('smtp.login')
#mail.settings.tls = configuration.get('smtp.tls') or False
#mail.settings.ssl = configuration.get('smtp.ssl') or False

auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = True
auth.settings.reset_password_requires_verification = True

response.meta.author = configuration.get('app.author')
response.meta.description = configuration.get('app.description')
response.meta.keywords = configuration.get('app.keywords')
response.meta.generator = configuration.get('app.generator')

#response.google_analytics_id = configuration.get('google.analytics_id')

# -------------------------------------------------------------------------
# maybe use the scheduler
# -------------------------------------------------------------------------
if configuration.get('scheduler.enabled'):
    from gluon.scheduler import Scheduler
    scheduler = Scheduler(db, heartbeat=configure.get('heartbeat'))

# -------------------------------------------------------------------------
# Define your tables below (or better in another model file) for example
#
# >>> db.define_table('mytable', Field('myfield', 'string'))
#
# Fields can be 'string','text','password','integer','double','boolean'
#       'date','time','datetime','blob','upload', 'reference TABLENAME'
# There is an implicit 'id integer autoincrement' field
# Consult manual for more options, validators, etc.
#
# More API examples for controllers:
#
# >>> db.mytable.insert(myfield='value')
# >>> rows = db(db.mytable.myfield == 'value').select(db.mytable.ALL)
# >>> for row in rows: print row.id, row.myfield
# -------------------------------------------------------------------------

# -------------------------------------------------------------------------
# after defining tables, uncomment below to enable auditing
# -------------------------------------------------------------------------
# auth.enable_record_versioning(db)


# -*- coding: utf-8 -*-
# @Time    : 2021/10/9 10:16
# @File    : Model.py
from leetcode import *

# 参考 https://zhuanlan.zhihu.com/p/93647900/
class UnionFind:
    def __init__(self, n):
        self.fa = [i for i in range(n)]
        self.rank = [1] * n

    def find(self, x):
        if x == self.fa[x]:
            return x
        self.fa[x] = self.find(self.fa[x])
        return self.fa[x]

    def merge(self, x, y):
        i, j = self.find(x), self.find(y)
        # 秩较小的树挂在较大的树上
        if self.rank[i] <= self.rank[j]:
            self.fa[i] = j
        else:
            self.fa[j] = i
        # 只有秩相同的时候需要更新秩
        if self.rank[i] == self.rank[j] and i != j:
            self.rank[j] += 1


# Author:  Lisandro Dalcin
# Contact: dalcinl@gmail.com
"""Pickle-based communication using protocol 5."""

import sys as _sys
import struct as _struct

from .. import MPI
from ..MPI import (
    PROC_NULL,
    ANY_SOURCE,
    ANY_TAG,
    Status,
)

from ..MPI import (
    _typedict,
    _comm_lock,
    _commctx_inter,
    memory as _memory,
    Pickle as _Pickle,
)

if _sys.version_info >= (3, 8):
    from pickle import (
        dumps as _dumps,
        loads as _loads,
        HIGHEST_PROTOCOL as _PROTOCOL,
    )
else:  # pragma: no cover
    try:
        from pickle5 import (
            dumps as _dumps,
            loads as _loads,
            HIGHEST_PROTOCOL as _PROTOCOL,
        )
    except ImportError:
        _PROTOCOL = MPI.Pickle().PROTOCOL

        def _dumps(obj, *_p, **_kw):
            return MPI.pickle.dumps(obj)

        def _loads(buf, *_p, **_kw):
            return MPI.pickle.loads(buf)

def _buffer_handler(protocol, threshold):
    bufs = []
    if protocol is None or protocol < 0:
        protocol = _PROTOCOL
    if protocol < 5:
        return bufs, None
    buffer_len = len
    buffer_raw = _memory
    buffer_add = bufs.append
    def buf_cb(buf):
        buf = buffer_raw(buf)
        if buffer_len(buf) >= threshold:
            buffer_add(buf)
            return False
        return True
    return bufs, buf_cb

class Pickle(_Pickle):
    """Pickle/unpickle Python objects using out-of-band buffers."""

    THRESHOLD = 1024**2 // 4  # 0.25 MiB

    def __init__(self, dumps=_dumps, loads=_loads, protocol=_PROTOCOL):
        """Initialize pickle context."""
        # pylint: disable=useless-super-delegation
        super().__init__(dumps, loads, protocol)

    def dumps(self, obj):
        """Serialize object to data and out-of-band buffers."""
        bufs, buf_cb = _buffer_handler(self.PROTOCOL, self.THRESHOLD)
        data = super().dumps(obj, buf_cb)
        return data, bufs

    def loads(self, data, bufs):
        """Deserialize object from data and out-of-band buffers."""
        # pylint: disable=useless-super-delegation
        return super().loads(data, bufs)

pickle = Pickle()

def _bigmpi_create_type(basetype, count, blocksize):
    qsize, rsize = divmod(count, blocksize)
    qtype = basetype.Create_vector(
        qsize, blocksize, blocksize)
    rtype = basetype.Create_contiguous(rsize)
    rdisp = qtype.Get_extent()[1]
    bigtype = MPI.Datatype.Create_struct(
        (1, 1), (0, rdisp), (qtype, rtype))
    qtype.Free()
    rtype.Free()
    return bigtype

class _BigMPI:
    """Support for large message counts."""

    blocksize = 1024**3  # 1 GiB

    def __init__(self):
        self.cache = {}

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        cache = self.cache
        for dtype in cache.values():
            dtype.Free()
        cache.clear()

    def __call__(self, buf):
        buf = _memory(buf)
        count = len(buf)
        blocksize = self.blocksize
        if count < blocksize:
            return (buf, count, MPI.BYTE)
        cache = self.cache
        dtype = cache.get(count)
        if dtype is not None:
            return (buf, 1, dtype)
        dtype = _bigmpi_create_type(MPI.BYTE, count, blocksize)
        cache[count] = dtype.Commit()
        return (buf, 1, dtype)

_bigmpi = _BigMPI()

def _info_typecode():
    return 'q'

def _info_datatype():
    code = _info_typecode()
    return _typedict[code]

def _info_pack(info):
    code = _info_typecode()
    size = len(info)
    sfmt = "{0}{1}".format(size, code)
    return _struct.pack(sfmt, *info)

def _info_alloc(size):
    code = _info_typecode()
    itemsize = _struct.calcsize(code)
    return bytearray(size * itemsize)

def _info_unpack(info):
    code = _info_typecode()
    itemsize = _struct.calcsize(code)
    size = len(info) // itemsize
    sfmt = "{0}{1}".format(size, code)
    return _struct.unpack(sfmt, info)

def _new_buffer(size):
    return bytearray(size)

def _send_raw(comm, send, data, bufs, dest, tag):
    # pylint: disable=too-many-arguments
    info = [len(data)]
    info.extend(len(_memory(sbuf)) for sbuf in bufs)
    infotype = _info_datatype()
    info = _info_pack(info)
    send(comm, (info, infotype), dest, tag)
    with _bigmpi as bigmpi:
        send(comm, bigmpi(data), dest, tag)
        for sbuf in bufs:
            send(comm, bigmpi(sbuf), dest, tag)

def _send(comm, send, obj, dest, tag):
    if dest == PROC_NULL:
        send(comm, (None, 0, MPI.BYTE), dest, tag)
        return
    data, bufs = pickle.dumps(obj)
    with _comm_lock(comm, 'send'):
        _send_raw(comm, send, data, bufs, dest, tag)

def _isend(comm, isend, obj, dest, tag):
    sreqs = []
    def send(comm, buf, dest, tag):
        sreqs.append(isend(comm, buf, dest, tag))
    _send(comm, send, obj, dest, tag)
    request = Request(sreqs)
    return request

def _recv_raw(comm, recv, buf, source, tag, status=None):
    # pylint: disable=too-many-arguments
    if status is None:
        status = Status()
    MPI.Comm.Probe(comm, source, tag, status)
    source = status.Get_source()
    tag = status.Get_tag()
    infotype = _info_datatype()
    infosize = status.Get_elements(infotype)
    info = _info_alloc(infosize)
    MPI.Comm.Recv(comm, (info, infotype), source, tag, status)
    info = _info_unpack(info)
    if buf is not None:
        buf = _memory.frombuffer(buf)
        if len(buf) > info[0]:
            buf = buf[:info[0]]
        if len(buf) < info[0]:
            buf = None
    data = bytearray(info[0]) if buf is None else buf
    bufs = list(map(_new_buffer, info[1:]))
    with _bigmpi as bigmpi:
        recv(comm, bigmpi(data), source, tag)
        for rbuf in bufs:
            recv(comm, bigmpi(rbuf), source, tag)
    status.Set_elements(MPI.BYTE, sum(info))
    return data, bufs

def _recv(comm, recv, buf, source, tag, status):
    # pylint: disable=too-many-arguments
    if source == PROC_NULL:
        recv(comm, (None, 0, MPI.BYTE), source, tag, status)
        return None
    with _comm_lock(comm, 'recv'):
        data, bufs = _recv_raw(comm, recv, buf, source, tag, status)
    return pickle.loads(data, bufs)

def _mprobe(comm, mprobe, source, tag, status):
    if source == PROC_NULL:
        rmsg = MPI.Comm.Mprobe(comm, source, tag, status)
        return Message([rmsg])
    if status is None:
        status = Status()
    with _comm_lock(comm, 'recv'):
        message = []
        numbytes = 0
        rmsg = mprobe(comm, source, tag, status)
        if rmsg is None:
            return None
        message.append(rmsg)
        source = status.Get_source()
        tag = status.Get_tag()
        infotype = _info_datatype()
        infosize = status.Get_elements(infotype)
        for _ in range(infosize):
            rmsg = MPI.Comm.Mprobe(comm, source, tag, status)
            message.append(rmsg)
            numbytes += status.Get_elements(MPI.BYTE)
        status.Set_elements(MPI.BYTE, numbytes)
        return Message(message)

def _mrecv_info(rmsg, size, status=None):
    mrecv = MPI.Message.Recv
    infotype = _info_datatype()
    info = _info_alloc(size)
    mrecv(rmsg, (info, infotype), status)
    info = _info_unpack(info)
    return info

def _mrecv_none(rmsg, mrecv, status):
    _mrecv_info(rmsg, 0, status)
    noproc = MPI.MESSAGE_NO_PROC
    mrecv(noproc, (None, 0, MPI.BYTE))
    data, bufs = pickle.dumps(None)
    return (bytearray(data), bufs)

def _mrecv_data(message, mrecv, status=None):
    if message[0] == MPI.MESSAGE_NO_PROC:
        rmsg = message[0]
        return _mrecv_none(rmsg, mrecv, status)
    rmsg = iter(message)
    icnt = len(message) - 1
    info = _mrecv_info(next(rmsg), icnt, status)
    data = bytearray(info[0])
    bufs = list(map(_new_buffer, info[1:]))
    with _bigmpi as bigmpi:
        mrecv(next(rmsg), bigmpi(data))
        for rbuf in bufs:
            mrecv(next(rmsg), bigmpi(rbuf))
    if status is not None:
        status.Set_elements(MPI.BYTE, sum(info))
    return (data, bufs)

def _mrecv(message, status):
    def mrecv(rmsg, buf):
        MPI.Message.Recv(rmsg, buf)
    data, bufs = _mrecv_data(message, mrecv, status)
    return pickle.loads(data, bufs)

def _imrecv(message):
    rreqs = []
    def mrecv(rmsg, buf):
        rreqs.append(MPI.Message.Irecv(rmsg, buf))
    data, bufs = _mrecv_data(message, mrecv)
    request = Request(rreqs)
    setattr(request, '_data_bufs', (data, bufs))
    return request

def _req_load(request):
    data_bufs = getattr(request, '_data_bufs', None)
    if request == MPI.REQUEST_NULL and data_bufs is not None:
        delattr(request, '_data_bufs')
    if data_bufs is not None:
        data, bufs = data_bufs
        obj = pickle.loads(data, bufs)
        return obj
    return None

def _test(request, test, status):
    statuses = None if status is None else [status]
    flag = test(request, statuses)
    if flag:
        obj = _req_load(request)
        return (flag, obj)
    return (flag, None)

def _testall(requests, testall, statuses):
    if isinstance(statuses, list):
        for _ in range(len(requests) - len(statuses)):
            statuses.append(Status())
    reqarray = []
    stsarray = None
    for req in requests:
        reqarray.extend(req)
    if statuses is not None:
        stsarray = []
        for req, sts in zip(requests, statuses):
            stsarray.extend([sts] * len(req))
    flag = testall(reqarray, stsarray)
    if flag:
        objs = [_req_load(req) for req in requests]
        return (flag, objs)
    return (flag, None)

def _bcast_intra_raw(comm, bcast, data, bufs, root):
    rank = comm.Get_rank()
    if rank == root:
        info = [len(data)]
        info.extend(len(_memory(sbuf)) for sbuf in bufs)
        infotype = _info_datatype()
        infosize = _info_pack([len(info)])
        bcast(comm, (infosize, infotype), root)
        info = _info_pack(info)
        bcast(comm, (info, infotype), root)
    else:
        infotype = _info_datatype()
        infosize = _info_alloc(1)
        bcast(comm, (infosize, infotype), root)
        infosize = _info_unpack(infosize)[0]
        info = _info_alloc(infosize)
        bcast(comm, (info, infotype), root)
        info = _info_unpack(info)
        data = bytearray(info[0])
        bufs = list(map(_new_buffer, info[1:]))
    with _bigmpi as bigmpi:
        bcast(comm, bigmpi(data), root)
        for rbuf in bufs:
            bcast(comm, bigmpi(rbuf), root)
    return data, bufs

def _bcast_intra(comm, bcast, obj, root):
    rank = comm.Get_rank()
    if rank == root:
        data, bufs = pickle.dumps(obj)
    else:
        data, bufs = pickle.dumps(None)
    with _comm_lock(comm, 'bcast'):
        data, bufs = _bcast_intra_raw(comm, bcast, data, bufs, root)
    return pickle.loads(data, bufs)

def _bcast_inter(comm, bcast, obj, root):
    rank = comm.Get_rank()
    size = comm.Get_remote_size()
    comm, tag, localcomm, _ = _commctx_inter(comm)
    if root == MPI.PROC_NULL:
        return None
    elif root == MPI.ROOT:
        send = MPI.Comm.Send
        data, bufs = pickle.dumps(obj)
        _send_raw(comm, send, data, bufs, 0, tag)
        return None
    elif 0 <= root < size:
        if rank == 0:
            recv = MPI.Comm.Recv
            data, bufs = _recv_raw(comm, recv, None, root, tag)
        else:
            data, bufs = pickle.dumps(None)
        with _comm_lock(localcomm, 'bcast'):
            data, bufs = _bcast_intra_raw(localcomm, bcast, data, bufs, 0)
        return pickle.loads(data, bufs)
    comm.Call_errhandler(MPI.ERR_ROOT)
    raise MPI.Exception(MPI.ERR_ROOT)

def _bcast(comm, bcast, obj, root):
    if comm.Is_inter():
        return _bcast_inter(comm, bcast, obj, root)
    else:
        return _bcast_intra(comm, bcast, obj, root)

class Request(tuple):
    """Request."""

    def __new__(cls, request=None):
        """Create and return a new object."""
        if request is None:
            request = (MPI.REQUEST_NULL,)
        if isinstance(request, MPI.Request):
            request = (request,)
        return super().__new__(cls, request)

    def __eq__(self, other):
        """Return ``self==other``."""
        if isinstance(other, Request):
            return tuple(self) == tuple(other)
        if isinstance(other, MPI.Request):
            return all(req == other for req in self)
        return NotImplemented

    def __ne__(self, other):
        """Return ``self!=other``."""
        if isinstance(other, Request):
            return tuple(self) != tuple(other)
        if isinstance(other, MPI.Request):
            return any(req != other for req in self)
        return NotImplemented

    def __bool__(self):
        """Return ``bool(self)``."""
        return any(req for req in self)

    def Free(self) -> None:
        """Free a communication request."""
        # pylint: disable=invalid-name
        for req in self:
            req.Free()

    def cancel(self):
        """Cancel a communication request."""
        # pylint: disable=invalid-name
        for req in self:
            req.Cancel()

    def get_status(self, status=None):
        """Non-destructive test for the completion of a request."""
        # pylint: disable=invalid-name
        statuses = [status] + [None] * max(len(self) - 1, 0)
        return all(map(MPI.Request.Get_status, self, statuses))

    def test(self, status=None):
        """Test for the completion of a request."""
        return _test(self, MPI.Request.Testall, status)

    def wait(self, status=None):
        """Wait for a request to complete."""
        return _test(self, MPI.Request.Waitall, status)[1]

    @classmethod
    def testall(cls, requests, statuses=None):
        """Test for the completion of all requests."""
        return _testall(requests, MPI.Request.Testall, statuses)

    @classmethod
    def waitall(cls, requests, statuses=None):
        """Wait for all requests to complete."""
        return _testall(requests, MPI.Request.Waitall, statuses)[1]

class Message(tuple):
    """Message."""

    def __new__(cls, message=None):
        """Create and return a new object."""
        if message is None:
            message = (MPI.MESSAGE_NULL,)
        if isinstance(message, MPI.Message):
            message = (message,)
        return super().__new__(cls, message)

    def __eq__(self, other):
        """Return ``self==other``."""
        if isinstance(other, Message):
            return tuple(self) == tuple(other)
        if isinstance(other, MPI.Message):
            return all(msg == other for msg in self)
        return NotImplemented

    def __ne__(self, other):
        """Return ``self!=other``."""
        if isinstance(other, Message):
            return tuple(self) != tuple(other)
        if isinstance(other, MPI.Message):
            return any(msg != other for msg in self)
        return NotImplemented

    def __bool__(self):
        """Return ``bool(self)``."""
        return any(msg for msg in self)

    def recv(self, status=None):
        """Blocking receive of matched message."""
        return _mrecv(self, status)

    def irecv(self):
        """Nonblocking receive of matched message."""
        return _imrecv(self)

    @classmethod
    def probe(cls, comm,
              source=ANY_SOURCE, tag=ANY_TAG,
              status=None):
        """Blocking test for a matched message."""
        return _mprobe(comm, MPI.Comm.Mprobe, source, tag, status)

    @classmethod
    def iprobe(cls, comm,
               source=ANY_SOURCE, tag=ANY_TAG,
               status=None):
        """Nonblocking test for a matched message."""
        return _mprobe(comm, MPI.Comm.Improbe, source, tag, status)

class Comm(MPI.Comm):
    """Communicator."""

    def send(self, obj, dest, tag=0):
        """Blocking send in standard mode."""
        _send(self, MPI.Comm.Send, obj, dest, tag)

    def bsend(self, obj, dest, tag=0):
        """Blocking send in buffered mode."""
        _send(self, MPI.Comm.Bsend, obj, dest, tag)

    def ssend(self, obj, dest, tag=0):
        """Blocking send in synchronous mode."""
        _send(self, MPI.Comm.Ssend, obj, dest, tag)

    def isend(self, obj, dest, tag=0):
        """Nonblocking send in standard mode."""
        return _isend(self, MPI.Comm.Isend, obj, dest, tag)

    def ibsend(self, obj, dest, tag=0):
        """Nonblocking send in buffered mode."""
        return _isend(self, MPI.Comm.Ibsend, obj, dest, tag)

    def issend(self, obj, dest, tag=0):
        """Nonblocking send in synchronous mode."""
        return _isend(self, MPI.Comm.Issend, obj, dest, tag)

    def recv(self,
             buf=None, source=ANY_SOURCE, tag=ANY_TAG,
             status=None):
        """Blocking receive."""
        return _recv(self, MPI.Comm.Recv, buf, source, tag, status)

    def irecv(self,
              buf=None, source=ANY_SOURCE, tag=ANY_TAG):
        """Nonblocking receive."""
        raise RuntimeError("unsupported")

    def sendrecv(self,
                 sendobj, dest, sendtag=0,
                 recvbuf=None, source=ANY_SOURCE, recvtag=ANY_TAG,
                 status=None):
        """Send and receive."""
        # pylint: disable=too-many-arguments
        sreq = _isend(self, MPI.Comm.Isend, sendobj, dest, sendtag)
        robj = _recv(self, MPI.Comm.Recv, recvbuf, source, recvtag, status)
        MPI.Request.Waitall(sreq)
        return robj

    def mprobe(self,
               source=ANY_SOURCE, tag=ANY_TAG,
               status=None):
        """Blocking test for a matched message."""
        return _mprobe(self, MPI.Comm.Mprobe, source, tag, status)

    def improbe(self,
                source=ANY_SOURCE, tag=ANY_TAG,
                status=None):
        """Nonblocking test for a matched message."""
        return _mprobe(self, MPI.Comm.Improbe, source, tag, status)

    def bcast(self, obj, root=0):
        """Broadcast."""
        return _bcast(self, MPI.Comm.Bcast, obj, root)

class Intracomm(Comm, MPI.Intracomm):
    """Intracommunicator."""

class Intercomm(Comm, MPI.Intercomm):
    """Intercommunicator."""


#!/usr/bin/env python

from __future__ import division, unicode_literals

import os
import argparse
import math
import torch

from itertools import count

import onmt.io
import onmt.translate
import onmt
import onmt.ModelConstructor
import onmt.modules
import opts
import txt_utils
import model_utils

import torchtext

def _report_rouge(result_file,golden_file):
    "1"
    #import sys
    #sys.path.append('../Lib/site-packages/rouge')
    #from rouge_wrap import RougeWrapper
    #r=RougeWrapper()
    #results = r.evaluate_for_pair_files(golden_file, result_file)
    "2"
    from rouge import Rouge
    #with open("pred.txt", "r") as f1, open("data/task1_ref0.txt", "r") as f2:
    #    rouge = Rouge()
    #    for l1, l2 in zip(f1, f2):
    #        scores = rouge.get_scores(l1, l2, avg=True)
    #print(scores)
    "3"
    from rouge import FilesRouge
    r = FilesRouge(result_file,golden_file)
    results = r.get_scores(avg=True)
    for k,v in results.items():
        if 'f' not in v:
            continue
        print(k,v)

def select_templates(src_file,tmp_file,score_file,output_file,tgt_file):
    current_src=''
    opt_template_scores=None
    with open(src_file,encoding='utf-8') as f_src,\
            open(tmp_file,encoding='utf-8') as f_tmp, \
            open(score_file,encoding='utf-8') as f_score,\
            open(output_file,'w',encoding='utf-8') as f_out:
        for line_src,line_tmp,line_score in zip(f_src,f_tmp,f_score):
            line_src=line_src.strip()
            if len(line_src)==0:
                continue
            line_tmp=line_tmp.strip()
            score=float()
            if line_src!=current_src:
                if opt_template_scores:
                    print(opt_template_scores[0],file=f_out)
                current_src=line_src
                opt_template_scores=[line_tmp,score]
            elif score>opt_template_scores[1]:
                opt_template_scores=[line_tmp,score]
        if opt_template_scores:
            print(opt_template_scores[0],file=f_out)
    _report_rouge(output_file,tgt_file)
    return

def main():
    parser = argparse.ArgumentParser(
    description='translate.py',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    opts.add_md_help_argument(parser)
    opts.translate_opts(parser)
    group = parser.add_argument_group('Rerank')
    group.add_argument('-templates', required=True,
                    help="Path to the test templates")
    opt = parser.parse_args()
    dummy_parser = argparse.ArgumentParser(description='train.py')
    opts.model_opts(dummy_parser)
    dummy_opt = dummy_parser.parse_known_args([])[0]

    opt.cuda = opt.gpu > -1
    if opt.cuda:
        torch.cuda.set_device(opt.gpu)

    # Load the model.
    fields, model, model_opt = \
        model_utils.load_test_model(opt, dummy_opt.__dict__)

    fields["spliter_pos"] = torchtext.data.Field(
            use_vocab=False, dtype=torch.long,
            sequential=False)

    # Unfold templates
    src_path,tmp_path=txt_utils.unfold_templates(opt.src, opt.templates)

    # Test data
    data=txt_utils.build_template_dataset(fields, src_path, None, tmp_path,use_filter_pred=False,with_pos=True,dynamic_dict=False)

    # Sort batch by decreasing lengths of sentence required by pytorch.
    # sort=False means "Use dataset's sortkey instead of iterator's".
    data_iter = onmt.io.OrderedIterator(
        dataset=data, device=opt.gpu,
        batch_size=opt.batch_size, train=False, sort=False,
        sort_within_batch=True, shuffle=False)

    count=0
    #offset=0
    #scores=[]
    score_dict={}
    for batch in data_iter:
        #print(batch.indices)
        #index=batch.indices-offset
        src = onmt.io.make_features(batch, 'src', 'text')
        predict_score=model.predict_rouge(src,batch.src[1],batch.spliter_pos)
        #ordered_score=predict_score[index].data
        #scores.extend(ordered_score)
        #offset+=index.size(0)
        for index,score in zip(batch.indices.data,predict_score.data):
            score_dict[int(index)]=float(score)
        count+=1
        if count% 100==0:
            print('score {} batches'.format(count))
        #if count>10: break

    # File to write sentences to.
    score_file = opt.output + '.score'
    print('score_file is ' + score_file)
    print('opt.tgt is ' + opt.tgt)
    out_file = open(score_file, 'w', encoding='utf-8')
    print(len(score_dict))
    for index in range(len(score_dict)):
        print(score_dict[index], file=out_file)
    out_file.close()
    select_templates(src_path,tmp_path,score_file,opt.output,opt.tgt)

if __name__ == "__main__":
    main()
    print('finished')


import json
import requests
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.parse import urlencode

class YelpFusionClient:
    #From example provided on Yelp Github
    __API_HOST = 'https://api.yelp.com'
    __SEARCH_PATH = '/v3/businesses/search'
    __BUSINESS_PATH = '/v3/businesses/'  # Business ID will come after slash.
    __TOKEN_PATH = '/oauth2/token'
    __GRANT_TYPE = 'client_credentials'

    __CLIENT_ID = None
    __CLIENT_SECRET = None

    def __init__(self, cid, csecret):
        self.__CLIENT_ID = cid
        self.__CLIENT_SECRET = csecret

    def __obtain_bearer_token(self, host, path):
        """Given a bearer token, send a GET request to the API.
        Args:
            host (str): The domain host of the API.
            path (str): The path of the API after the domain.
            url_params (dict): An optional set of query parameters in the request.
        Returns:
            str: OAuth bearer token, obtained using client_id and client_secret.
        Raises:
            HTTPError: An error occurs from the HTTP request.
        """
        url = '{0}{1}'.format(host, quote(path.encode('utf8')))
        assert self.__CLIENT_ID, "Please supply your client_id."
        assert self.__CLIENT_SECRET, "Please supply your client_secret."
        data = urlencode({
            'client_id': self.__CLIENT_ID,
            'client_secret': self.__CLIENT_SECRET,
            'grant_type': self.__GRANT_TYPE,
        })
        headers = {
            'content-type': 'application/x-www-form-urlencoded',
        }
        response = requests.request('POST', url, data=data, headers=headers)
        bearer_token = response.json()['access_token']
        return bearer_token

    def __request(self, host, path, bearer_token, url_params = None):
        """Given a bearer token, send a GET request to the API.
        Args:
            host (str): The domain host of the API.
            path (str): The path of the API after the domain.
            bearer_token (str): OAuth bearer token, obtained using client_id and client_secret.
            url_params (dict): An optional set of query parameters in the request.
        Returns:
            dict: The JSON response from the request.
        Raises:
            HTTPError: An error occurs from the HTTP request.
        """
        url_params = url_params or {}
        url = '{0}{1}'.format(host, quote(path.encode('utf8')))
        headers = {
            'Authorization': 'Bearer %s' % bearer_token,
        }

        print(u'Querying {0} ...'.format(url))

        response = requests.request('GET', url, headers=headers, params=url_params)

        return response.json()

    def search(self, term, location, limit = 3):
        """Query the Search API by a search term and location.
        Args:
            term (str): The search term passed to the API.
            location (str): The search location passed to the API.
        Returns:
            dict: The JSON response from the request.
        """
        bearer_token = self.__obtain_bearer_token(self.__API_HOST, self.__TOKEN_PATH)

        url_params = {
            'term': term.replace(' ', '+'),
            'location': location.replace(' ', '+'),
            'limit': limit
        }

        return self.__request(self.__API_HOST, self.__SEARCH_PATH, bearer_token, url_params=url_params)

    def get_business(self, business_id):
        """Query the Business API by a business ID.
        Args:
            business_id (str): The ID of the business to query.
        Returns:
            dict: The JSON response from the request.
        """
        bearer_token = self.__obtain_bearer_token(self.__API_HOST, self.__TOKEN_PATH)

        business_path = self.__BUSINESS_PATH + business_id

        return self.__request(self.__API_HOST, business_path, bearer_token)

    def get_reviews(self, business_id):
        bearer_token = self.__obtain_bearer_token(self.__API_HOST, self.__TOKEN_PATH)

        REVIEW_PATH = self.__BUSINESS_PATH + business_id + '/reviews'

        return self.__request(self.__API_HOST, REVIEW_PATH, bearer_token)


from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel

class StartTimer(QWidget):
    def __init__(self, parent=None, worktime=45, breaktime=15):
        super().__init__(parent)
        self.parent = parent
        self.worktime = worktime
        self.breaktime = breaktime

        # Layout
        self.layout = QVBoxLayout()
        self.layout.setSpacing(50)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setAlignment(Qt.AlignCenter)
        self.setLayout(self.layout)

        # Play button
        self.buttonLayout = QVBoxLayout()
        self.buttonLayout.setSpacing(0)
        self.buttonLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonLayout.setAlignment(Qt.AlignCenter) # Center button
        self.layout.addLayout(self.buttonLayout)

        self.playIcon = QIcon("icons/play.png")
        self.playButton = QPushButton(
            self.playIcon,
            "",
            self
        )
        self.playButton.setIconSize(QSize(80, 80))
        self.playButton.setFixedSize(120, 120)
        self.playButton.setStyleSheet(
            "QPushButton {"
            "border-radius: 60px; "
            "border-style: outset; "
            "border-width: 1px; "
            "border-color: #202020; "
            "padding-left: 10px;"  # Nudge the icon 10 pixels to the right
            "}"
            "QPushButton:hover {"
            "background-color: #202020; "
            "}"
            "QPushButton:hover:pressed {"
            "background-color: #52CC99; "
            "}"
            "QPushButton:focus {"
            "border-color: #52CC99; "
            "}"
        )
        self.playButton.clicked.connect(self.parent.startTimer)
        self.layout.addWidget(self.playButton)

        self.buttonLayout.addWidget(self.playButton)

        # Info text
        self.textLayout = QVBoxLayout()
        self.textLayout.setSpacing(10)
        self.textLayout.setContentsMargins(0, 0, 0, 0)

        # Heading
        self.infoText = QLabel('Current settings')
        self.infoText.setWordWrap(True)
        self.infoText.setStyleSheet('color: #7a7a7a; font-size: 22px')

        # Work time
        self.infoTextWork = QLabel(f'Work: {self.worktime}')
        self.infoTextWork.setWordWrap(True)
        self.infoTextWork.setStyleSheet('color: #4a4a4a; font-size: 18px')

        # Break time
        self.infoTextBreak = QLabel(f'Break: {self.breaktime}')
        self.infoTextBreak.setWordWrap(True)
        self.infoTextBreak.setStyleSheet('color: #4a4a4a; font-size: 18px')

        self.textLayout.addWidget(self.infoText)
        self.textLayout.addWidget(self.infoTextWork)
        self.textLayout.addWidget(self.infoTextBreak)
        self.layout.addLayout(self.textLayout)

    def setStartTime(self, worktime, breaktime):
        self.worktime = worktime
        self.breaktime = breaktime
        self.infoTextWork.setText(f'Work: {worktime}')
        self.infoTextBreak.setText(f'Break: {breaktime}')

    def setFocusToPlayButton(self):
        self.playButton.setFocus()


#!/usr/bin/python3
'''A base of all other classes in the model

Class:
    Base : a class to manage id
'''

class Base():
    '''A class to manage id

    Attributes:
        nb_objects : holds the number of objects, private
        '''

    __nb_objects = 0

    def __init__(self, id=None):
        '''Initializes an instance of the class'''
        if id is None:
            Base.__nb_objects += 1
            self.id = self.__nb_objects
        else:
            self.id = id


import discord
from discord.ext import commands
import random

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle, activity=discord.Game('J KURWA D'))
    print('Bot is ready!')

@client.command()
async def ping(ctx):
    await ctx.send(f'Bots ping: {round(client.latency * 1000)}ms')

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ['Yes', 'No', 'Maybe']
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

client.run('TOKEN')


import re
from autocorrect import spell
import spacy

# initialize spacy
class NLP:
    """
     Singleton instance
    """
    def __init__(self):
        self.nlp = None

    def getInstance(self):
        if self.nlp==None:
            self.nlp = spacy.load('en')
        return self.nlp

# prepare the singleton
spacy_nlp = NLP()

def tokenize(text):
    """ Tokenize a sentence with spaCy.
    """
    nlp = spacy_nlp.getInstance()   # lazy loading
    tokenizer = nlp(unicode(text))
    tokens = map(str, [token for token in tokenizer])
    lemmas = map(str, [token.lemma_ for token in tokenizer])
    return zip(tokens,lemmas)

# helper to clean all text before operation
def clean_text(text):
    # first clean out symbols
    #text = re.sub(r'[^\w]', ' ', text)
    # Replace linebreaks with spaces
    text = text.replace("\n", " ").replace("\r", " ").replace("\t", " ")
    # Remove any leading or trailing whitespace
    text = text.strip()
    # Remove consecutive spaces
    text = re.sub(" +", " ", text)
    # tokenize
    text = text.split()
    # correct all spellings
    #text = map(spell, text)
    return " ".join(text)

def preprocessor(text, pipeline):
    """
        preprocess the text as per the given pipeline
        pipeline is a list of functions that process an input text and outputs text
        (e.g., lemmatizing, removing punctuations etc.),
    """
    if len(pipeline)==0:
        return text
    else:
        return preprocessor(pipeline[0](text), pipeline[1:])

def run(pipeline):
    return lambda text: preprocessor(text, pipeline)

def pipeline_one():
    """
        text
            |> remove special characters
            |> remove numerals,
            |> convert all alphabets to lower cases,
            |> filter words, e.g., stop words, and
            |> lemmatize the words
    """
    pipeline = [
        lambda s: re.sub('[^\w\s]', '', s),
        lambda s: re.sub('[\d]', '', s),
        lambda s: s.lower(),
        lambda s: ' '.join([ lemma for word, lemma in tokenize(s)])
        ]
    return run(pipeline)


import visuals
import random
from copy import copy
import sys
if (sys.version_info < (3, 0)):
    from expectimax import *
else:
    xrange = range

class BoardController():
    def __init__(self):
        self.window = visuals.GameWindow()
        self.start_new_game()

    def start_new_game(self):
        random.seed()
        self.board = [0] * 4*4
        spawnRandomTile(self.board)
        self.window.update_view(self.board)

    def move(self, direction):
        """
        Actually move. Slide first, then insertTile.
        Update GUI
        """
        slide(direction, self.board)
        spawnRandomTile(self.board)
        self.window.update_view(self.board)

    def grid(self, x, y):
        """
        Get the value of a position of the board.
        0,0 is the top left corner.
        """
        return self.board[x * 4 + y]

    def setGrid(self, x, y, v):
        """
        Update the value of a position of the board.
        0,0 is the top left corner.
        """
        self.board[x * 4 + y] = v

def slide(direction, board):
    """
    Move all tiles as far in direction as possible.
    Use merge() if needed.
    """
    if direction == 'up':
        return slideUp(board)
    elif direction == 'down':
        return slideDown(board)
    elif direction == 'right':
        return slideRight(board)
    elif direction == 'left':
        return slideLeft(board)

def slideUp(board):
    merged = [False] * 4*4
    mergeCount = 0
    maxMerging = highestMerg = 0
    maxTile = max(board)
    moves = 0

    for i in xrange(3): # move as much as possible
        for pos in xrange(4,16):
            if board[pos-4] == 0:
                board[pos-4] = board[pos]
                board[pos] = 0
                moves += 1
            elif board[pos-4] == board[pos]:
                if not merged[pos] and not merged[pos-4]:
                    # merge tiles
                    if board[pos] == maxTile:
                        maxMerging = board[pos]+1
                    board[pos-4] += 1
                    highestMerg = max( board[pos-4] , highestMerg)
                    board[pos] = 0
                    mergeCount += 1
                    merged[pos-4] = True
    return board, mergeCount, maxMerging, highestMerg, moves

def slideDown(board):
    merged = [False] * 4*4
    mergeCount = 0
    maxMerging = highestMerg= 0
    maxTile = max(board)
    moves = 0

    for i in xrange(3):
        for pos in range(11,-1,-1):
            if board[pos+4] == 0:
                board[pos+4] = board[pos]
                board[pos] = 0
                moves += 1
            elif board[pos+4] == board[pos]:
                if not merged[pos] and not merged[pos+4]:
                    # merge tiles
                    if board[pos] == maxTile:
                        maxMerging = board[pos]+1
                    board[pos+4] += 1
                    highestMerg = max( board[pos+4] , highestMerg)
                    board[pos] = 0
                    mergeCount += 1
                    merged[pos+4] = True
    return board, mergeCount, maxMerging, highestMerg, moves

def slideLeft(board):
    merged = [False] * 4*4
    mergeCount = 0
    maxMerging = highestMerg = 0
    maxTile = max(board)
    moves = 0

    for i in xrange(3):
        for pos in [1,2,3,5,6,7,9,10,11,13,14,15]:
            if board[pos-1] == 0:
                board[pos-1] = board[pos]
                board[pos] = 0
                moves += 1
            elif board[pos-1] == board[pos]:
                if not merged[pos] and not merged[pos-1]:
                    # merge tiles
                    if board[pos] == maxTile:
                        maxMerging = board[pos]+1
                    board[pos-1] += 1
                    highestMerg = max( board[pos-4] , highestMerg)
                    board[pos] = 0
                    mergeCount += 1
                    merged[pos-1] = True
    return board, mergeCount, maxMerging, highestMerg, moves

def slideRight(board):
    merged = [False] * 4*4
    mergeCount = 0
    maxMerging = highestMerg=0
    maxTile = max(board)
    moves = 0

    for i in xrange(3):
        for pos in [2,1,0,6,5,4,10,9,8,14,13,12]:
            if board[pos+1] == 0:
                board[pos+1] = board[pos]
                board[pos] = 0
                moves += 1
            elif board[pos+1] == board[pos]:
                if not merged[pos] and not merged[pos+1]:
                    # merge tiles
                    if board[pos] == maxTile:
                        maxMerging = board[pos]+1

                    board[pos+1] += 1
                    highestMerg = max( board[pos+1] , highestMerg)
                    board[pos] = 0
                    mergeCount += 1
                    merged[pos+1] = True
    return board, mergeCount, maxMerging, highestMerg, moves

def findEmptyTiles(board):
    #return np.array(np.where(board == 0))
    empty = []
    for i in xrange( len(board) ):
        if board[i] == 0:
            empty.append(i)
    return empty

#def createAllPossibleNeighbors(board):
#    emptyList = findEmptyTiles()
#    neighbors = []
#    for pos in emptyList:
#        neighbor = board.copy()
#        insertTile(pos, 2, neighbor)
#        neighbors.append(neighbor)

def spawnRandomTile(board):
    listWithEmptyTiles = findEmptyTiles(board)
    randomPosition = random.choice( listWithEmptyTiles )
    #randomPosition = tuple(listWithEmptyTiles.T[np.random.randint(0, listWithEmptyTiles.shape[1])])
    randomValue = 1
    if random.random() > 0.9:
        randomValue = 2
    insertTile( randomPosition, randomValue, board )

def insertTile( position, value, board ):
    board[position] = value


# python3
# coding:utf-8

triangle=[]
square=[]
pentagonal=[]
hexagonal=[]
heptagonal=[]
octagonal=[]
n=1
while n*(n+1)/2<10000:
	# if n*(n+1)/2>1000 and str(n*(n+1)/2)[2]!='0':
	if n*(n+1)/2>1000:
		triangle.append(str(n*(n+1)/2))
	n=n+1
n=1
while n*n<10000:
	# if n*n>1000 and str(n*n)[2]!='0':
	if n*n>1000:
		square.append(str(n*n))
	n=n+1
n=1
while n*(3*n-1)/2<10000:
	# if n*(3*n-1)/2>1000 and str(n*(3*n-1)/2)[2]!='0':
	if n*(3*n-1)/2>1000:
		pentagonal.append(str(n*(3*n-1)/2))
	n=n+1
n=1
while n*(2*n-1)<10000:
	# if n*(2*n-1)>1000 and str(n*(2*n-1))[2]!='0':
	if n*(2*n-1)>1000:
		hexagonal.append(str(n*(2*n-1)))
	n=n+1
n=1
while n*(5*n-3)/2<10000:
	# if n*(5*n-3)/2>1000 and str(n*(5*n-3)/2)[2]!='0':
	if n*(5*n-3)/2>1000:
		heptagonal.append(str(n*(5*n-3)/2))
	n=n+1
n=1
while n*(3*n-2)<10000:
	# if n*(3*n-2)>1000 and str(n*(3*n-2))[2]!='0':
	if n*(3*n-2)>1000:
		octagonal.append(str(n*(3*n-2)))
	n=n+1

tmp3_1=[]
tmp3_2=[]
for tmp in triangle:
	tmp3_1.append(tmp[:2])
	tmp3_2.append(tmp[-2:])
tmp4_1=[]
tmp4_2=[]
for tmp in square:
	tmp4_1.append(tmp[:2])
	tmp4_2.append(tmp[-2:])
tmp5_1=[]
tmp5_2=[]
for tmp in pentagonal:
	tmp5_1.append(tmp[:2])
	tmp5_2.append(tmp[-2:])
tmp6_1=[]
tmp6_2=[]
for tmp in hexagonal:
	tmp6_1.append(tmp[:2])
	tmp6_2.append(tmp[-2:])
tmp7_1=[]
tmp7_2=[]
for tmp in heptagonal:
	tmp7_1.append(tmp[:2])
	tmp7_2.append(tmp[-2:])
tmp8_1=[]
tmp8_2=[]
for tmp in octagonal:
	tmp8_1.append(tmp[:2])
	tmp8_2.append(tmp[-2:])

tmp8=[]
for tmp in octagonal:
	if (tmp[:2] in tmp7_2)==True and (tmp[-2:] in tmp3_1)==True:
		tmp8.append(tmp)
tmp7=[]
for tmp in heptagonal:
	if (tmp[:2] in tmp6_2)==True and (tmp[-2:] in tmp8_1)==True:
		tmp7.append(tmp)
tmp6=[]
for tmp in hexagonal:
	if (tmp[:2] in tmp5_2)==True and (tmp[-2:] in tmp7_1)==True:
		tmp6.append(tmp)
tmp5=[]
for tmp in pentagonal:
	if (tmp[:2] in tmp4_2)==True and (tmp[-2:] in tmp6_1)==True:
		tmp5.append(tmp)
tmp4=[]
for tmp in square:
	if (tmp[:2] in tmp3_2)==True and (tmp[-2:] in tmp5_1)==True:
		tmp4.append(tmp)
tmp3=[]
for tmp in triangle:
	if (tmp[:2] in tmp8_2)==True and (tmp[-2:] in tmp4_1)==True:
		tmp3.append(tmp)

print(triangle)
print(square)
print(pentagonal)
print(hexagonal)
print(heptagonal)
print(octagonal)
print('------------')
print(tmp3)
print(tmp4)
print(tmp5)
print(tmp6)
print(tmp7)
print(tmp8)
# print(tmp8_1)
# print(tmp8_2)


from datetime import datetime
from typing import Dict, List

from trading.PumpTrade import PumpTrade
from wallet.Wallet import Wallet

class PumpTradeTracker:
    trades: List

    def __init__(self):
        self.trades = []

    def addNewTrade(self, trade: PumpTrade):
        self.trades.append(trade)

    def isOwned(self, trade: PumpTrade) -> bool:
        """
        Adds a trade only if the stock with the ticker is not currently owned.
        :param trade: the trade
        :return: if the trade was successfully tracked
        """
        if not self.containsUnsoldTrade(trade.ticker):
            return True

        return False

    def containsUnsoldTrade(self, ticker: str) -> bool:
        for trade in self.trades:
            if trade.ticker == ticker and not trade.wasSold():
                return True

        return False

    def getUnsoldTradeByTicker(self, ticker: str) -> PumpTrade:
        for trade in self.trades:
            if trade.ticker == ticker and not trade.wasSold():
                return trade

        return None

    def calculateProfits(self) -> Dict:
        """
        Note: if a trade was not sold, the trade is marked as having a value of
        0!
        """
        returnDict = {}
        total = 0.0

        for trade in self.trades:
            profit = trade.calculateProfit()
            total += profit

            if trade.ticker not in returnDict:
                returnDict[trade.ticker] = 0.0

            returnDict[trade.ticker] += profit

        returnDict["Total"] = total
        return returnDict

    def tradesStr(self):
        string = ""

        for trade in self.trades:
            string += str(trade)

        return string

    def getNumberOfUnprofitableTradesOnDay(self, ticker: str, day: datetime):
        date = day.date()
        count = 0

        for trade in self.trades:
            if trade.ticker == ticker and trade.buyTimestamp.date() == date:
                count += 1

        return count

    def tradesCSV(self):
        string = "ticker,buy,sell,profit,profit-of-trade\n"
        profit = 0.0

        for trade in self.trades:
            profit += trade.calculateProfit()
            string += trade.ticker + "," + str(trade.buyTimestamp)\
                      + "," + str(trade.sellTimestamp) + "," + str(profit) +\
                      "," + str(trade.calculateProfit()) + "\n"

        return string


from django.urls import path, include

from .views import (
    CreateOrderAPIView,
    FindOrderAPIView,
    LoadSkuOrderToCellView,
    OrderDetailsAPIView,
    OrderAddNewDataAPIView,
    OrderStatusUpdateAPIView,
    GetTablesApiView,
    GetTokenApiView,
    SignUpApiView,
    SelectTableApiView,
    SelectPrinterApiView,
)

registration = [
    path("sign-up/", SignUpApiView.as_view()),
    path("login/", GetTokenApiView.as_view()),
]

urlpatterns = [
    path("auth/", include(registration)),
    path("tables/", GetTablesApiView.as_view()),
    path("select-table/<int:pk>/", SelectTableApiView.as_view()),
    path("select-printer/", SelectPrinterApiView.as_view()),
    path(
        "order/add-packaging-data/",
        OrderAddNewDataAPIView.as_view(),
        name="add-packaging-data",
    ),
    path(
        "order/create/",
        CreateOrderAPIView.as_view(),
        name="create_new_order",
    ),
    path(
        "upload-to-cell/",
        LoadSkuOrderToCellView().as_view(),
        name="upload-to-cell",
    ),
    path("order/find/", FindOrderAPIView.as_view(), name="find-order"),
    path(
        "order/details/", OrderDetailsAPIView.as_view(), name="order-details"
    ),
    path(
        "order/collected/",
        OrderStatusUpdateAPIView.as_view(),
        name="order-collected",
    ),
]


from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.embed import components
import datetime

#Read in available ticker data
tickers=pd.read_csv('./ticker_list.csv', usecols=['Ticker'])

BASE='https://www.quandl.com/api/v3/datasets/WIKI/'

#Generte url for stock data
def GetURL(ticker):
    return BASE+str(ticker.upper())+'.json'

#Create a line plot of user requested price information
def LinePlot(df, p):

    colors=['red', 'blue', 'black', 'cyan']
    c=0
    for pdat in app.vars['close']:
        p.line(df.Date, df[str(pdat)], legend=str(pdat), line_width=2, color=colors[c])
        c+=1

    return p

#Create a candlestick plot for the user inputted ticker symbol
def CSPlot(df,p):

    mids = (df.Open + df.Close)/2
    spans = abs(df.Close-df.Open)

    inc = df.Close > df.Open
    dec = df.Open > df.Close
    w = 12*60*60*1000 # half day in ms
    p.segment(df.Date, df.High, df.Date, df.Low, color="black")
    p.rect(df.Date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black")
    p.rect(df.Date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black")
    p.grid.grid_line_alpha=0.3

    return p

app = Flask(__name__)
app.vars={}

@app.route('/')
def main():
    return redirect('/home')

#Render homepage which requests that the user enter a ticker symbol
#and the type of plot they would like to see
@app.route('/home', methods=['GET', 'POST'])
def home():
    return render_template('home.html')

#Renders the graph page but first checks for errors
#If the user doesn't enter a valid ticker or does not choose
#a plot type they are redirected to the home page with an error
#message. If everything is valid the user to sent to
#a page with their requested plot.
@app.route('/graph', methods=['GET', 'POST'])
def graph():

    if request.method == 'GET':
        return redirect('/home')
    else:

        app.vars['name'] = request.form['name_app'].upper()
        app.vars['close']=request.form.getlist('features')
        app.vars['plottype']=request.form['answer_from_layout_app']

        if app.vars['name'] not in tickers.as_matrix():
            return render_template('tickererror.html')
        elif (len(app.vars['close'])==0) and app.vars['plottype']=='line':
            return render_template('selectionerror.html', TICKER=app.vars['name'])

        ticker=app.vars['name']
        r=requests.get(GetURL(ticker)).json()['dataset']
        df=pd.DataFrame(r['data'], columns=r['column_names'])
        df=df.rename(columns={c: c.replace(" ","") for c in df.columns})
        df['Date'] = pd.to_datetime(df['Date'])

        # output to static HTML file
        output_file("lines.html", title=str(ticker).upper()+" Stock Date")

        #Prepare axis
        offset=.05*(max(df.High[:21])-min(df.Low[:21]))
        Y_range=[min(df.Low[:21])-offset, max(df.High[:21])+offset]
        X_range=[df.Date[20]-datetime.timedelta(hours=12), df.Date[0]+datetime.timedelta(hours=12)]
        p = figure(title="Historical Prices for "+str(ticker).upper(),plot_width=1000, toolbar_location="left",  x_axis_label='Date', y_axis_label='Price (in $)', x_axis_type="datetime", x_range=X_range, y_range=Y_range)

        if app.vars['plottype']=="line":
            p=LinePlot(df, p)
        else:
            p=CSPlot(df,p)

        script, div = components(p)
        return render_template('graph.html', script=script, div=div, TICKER=ticker)

if __name__ == '__main__':
  app.run()


import math

def binary_search(n):
    left, right = 0, n - 1

    while left <= right:
        middle = (left + right) // 2

        if middle < math.sqrt(n):
            left = middle + 1
        else:
            right = middle - 1

    return left

if __name__ == "__main__":
    N = int(input())

    # 방법 1. Binary Search 이용
    print(binary_search(N))

    # 방법 2. sqrt 함수 사용하여, 제곱으로 값이 일치하지 않는 경우 +1 하여 정답
    # answer = int(math.sqrt(N))
    # if answer * answer != N:
    #     answer += 1
    #
    # print(answer)


from datetime import datetime

from bson.objectid import ObjectId

from odbms import DBMS, Model
from ..common.utils import Utils

class Role(Model):
    '''A model class for role'''
    TABLE_NAME = 'roles'

    def __init__(self, name, permission_ids, created_at=None, updated_at=None, id=None):
        super().__init__(created_at, updated_at, id)
        self.name = name
        #self.permission_ids =  permission_ids.split('::') if type(permission_ids) == str \
        #                        else permission_ids
        self.permission_ids = permission_ids

    def save(self):
        '''
        Instance Method for saving Role instance to database

        @params None
        @return None
        '''

        data = {
            "name": self.name,
            "permission_ids": self.permission_ids,
        }

        if DBMS.Database.dbms == 'mongodb':
            data["created_at"] = self.created_at
            data["updated_at"] = self.updated_at

        return DBMS.Database.insert(Role.TABLE_NAME, data)

    def json(self)-> dict:
        '''
        Instance Method for converting Role Instance to Dict

        @paramas None
        @return dict() format of Function instance
        '''

        return {
            "id": str(self.id),
            "name": self.name,
            "permissions": self.permissions(),
            "created_at": self.created_at,
            "updated_at": self.updated_at
        }

    @classmethod
    def get_by_name(cls, name: str):
        '''
        Class Method for retrieving role by name

        @param name Name of the role
        @return Role instance
        '''
        role = DBMS.Database.find_one(Role.TABLE_NAME, {"name": name})
        return cls(**Model.normalise(role)) if role else None

    def permissions(self):
        '''
        Class Method for retrieving role by username

        @param username username of the role
        @return Role instance
        '''
        permissions = []
        for perm_id in self.permission_ids:
            permissions.append(DBMS.Database.db.find_one('permissions', {'id': perm_id}))

        return permissions


from typing import List, TypeVar, Tuple

from common import sender_obs
from simulator.network_simulator import network, packet
from simulator.network_simulator.constants import BITS_PER_BYTE, BYTES_PER_PACKET, EVENT_TYPE_SEND

class Sender:
    """Base class of senders.

    srtt and retransmission reference: https://datatracker.ietf.org/doc/html/rfc6298
    """

    SRTT_ALPHA = 1 / 8
    SRTT_BETA = 1 / 4
    RTO_K = 4

    def __init__(self, sender_id: int, dest: int):
        """Create a sender object.

        Args
            sender_id: id of sender device.
            dest: id of destination device.
        """
        self.sender_id = sender_id
        # variables to track in a MonitorInterval. Units: packet
        self.sent = 0  # no. of packets
        self.acked = 0  # no. of packets
        self.lost = 0  # no. of packets
        self.rtt_samples = []
        self.queue_delay_samples = []

        # variables to track accross the connection session
        self.tot_sent = 0 # no. of packets
        self.tot_acked = 0 # no. of packets
        self.tot_lost = 0 # no. of packets
        self.cur_avg_latency = 0.0
        self.first_ack_ts = None
        self.last_ack_ts = None
        self.first_sent_ts = None
        self.last_sent_ts = None

        self.pacing_rate = 0  # bytes/s
        self.bytes_in_flight = 0  # bytes
        self.net = None
        self.dest = dest
        self.ssthresh = 80

        self.srtt = None
        self.rttvar = None
        # initialize rto to 3s for waiting SYC packets of TCP handshake
        self.rto = 3  # retransmission timeout (seconds)

        self.event_count = 0
        self.got_data = True

        # variables to track binwise measurements
        self.bin_bytes_sent = {}
        self.bin_bytes_acked = {}
        self.lat_ts = []
        self.lats = []
        self.bin_size = 500 # ms

    def can_send_packet(self) -> bool:
        return True

    def register_network(self, net: "network.Network") -> None:
        self.net = net

    def on_packet_sent(self, pkt: "packet.Packet") -> bool:
        pkt.pkt_id = self.event_count
        self.event_count += 1
        self.sent += 1
        self.bytes_in_flight += pkt.pkt_size
        self.tot_sent += 1
        if self.first_sent_ts is None:
            self.first_sent_ts = pkt.ts
        self.last_sent_ts = pkt.ts

        bin_id = int((pkt.ts - self.first_sent_ts) * 1000 / self.bin_size)
        self.bin_bytes_sent[bin_id] = self.bin_bytes_sent.get(bin_id, 0) + pkt.pkt_size
        return True

    def on_packet_acked(self, pkt: "packet.Packet") -> None:
        self.acked += 1
        self.cur_avg_latency = (self.cur_avg_latency * self.tot_acked + pkt.rtt) / (self.tot_acked + 1)
        self.tot_acked += 1
        if self.first_ack_ts is None:
            self.first_ack_ts = pkt.ts
        self.last_ack_ts = pkt.ts
        assert self.bytes_in_flight >= pkt.pkt_size
        self.bytes_in_flight -= pkt.pkt_size
        if self.srtt is None and self.rttvar is None:
            self.srtt = pkt.rtt
            self.rttvar = pkt.rtt / 2
            # RTO <- SRTT + max (G, K*RTTVAR) ignore G because clock granularity of modern os is tiny
            self.rto = max(1, min(self.srtt + self.RTO_K * self.rttvar, 60))
        elif self.srtt and self.rttvar:
            self.rttvar = (1 - self.SRTT_BETA) * self.rttvar + \
                self.SRTT_BETA * abs(self.srtt - pkt.rtt)
            self.srtt = (1 - self.SRTT_ALPHA) * self.srtt + \
                self.SRTT_ALPHA * pkt.rtt
            self.rto = max(1, min(self.srtt + self.RTO_K * self.rttvar, 60))
        else:
            raise ValueError("srtt and rttvar shouldn't be None.")

        self.rtt_samples.append(pkt.rtt)
        self.queue_delay_samples.append(pkt.queue_delay)

        bin_id = int((pkt.ts - self.first_ack_ts) * 1000 / self.bin_size)
        self.bin_bytes_acked[bin_id] = self.bin_bytes_acked.get(bin_id, 0) + pkt.pkt_size
        self.lat_ts.append(pkt.ts)
        self.lats.append(pkt.rtt * 1000)

    def on_packet_lost(self, pkt: "packet.Packet") -> None:
        self.lost += 1
        self.tot_lost += 1
        assert self.bytes_in_flight >= pkt.pkt_size
        self.bytes_in_flight -= pkt.pkt_size

    def get_cur_time(self) -> float:
        assert self.net, "network is not registered in sender."
        return self.net.get_cur_time()

    def schedule_send(self, _) -> None:
        return

    def get_run_data(self):
        obs_end_time = self.get_cur_time()

        #obs_dur = obs_end_time - self.obs_start_time
        #print("Got %d acks in %f seconds" % (self.acked, obs_dur))
        #print("Sent %d packets in %f seconds" % (self.sent, obs_dur))
        #print("self.rate = %f" % self.rate)
        # print(self.acked, self.sent)
        # rtt_samples = self.rtt_samples # if self.rtt_samples else self.prev_rtt_samples

        return sender_obs.SenderMonitorInterval(
            self.sender_id,
            bytes_sent=self.sent * BYTES_PER_PACKET,
            bytes_acked=self.acked * BYTES_PER_PACKET,
            bytes_lost=self.lost * BYTES_PER_PACKET,
            send_start=self.obs_start_time,
            send_end=obs_end_time,
            recv_start=self.obs_start_time,
            recv_end=obs_end_time,
            rtt_samples=self.rtt_samples,
            queue_delay_samples=self.queue_delay_samples,
            packet_size=BYTES_PER_PACKET
        )

    def stop_run(self, pkt: "packet.Packet", end_time: float)->bool:
        return self.got_data and pkt.ts >= end_time and pkt.event_type == EVENT_TYPE_SEND

    def reset_obs(self):
        self.sent = 0
        self.acked = 0
        self.lost = 0
        self.rtt_samples = []
        self.queue_delay_samples = []
        self.obs_start_time = self.get_cur_time()

    def reset(self):
        self.ssthresh = 80
        self.event_count = 0
        self.pacing_rate = 0
        self.bytes_in_flight = 0
        self.srtt = None
        self.rttvar = None
        self.rto = 3  # retransmission timeout (seconds)
        self.tot_sent = 0 # no. of packets
        self.tot_acked = 0 # no. of packets
        self.tot_lost = 0 # no. of packets
        self.cur_avg_latency = 0.0
        self.first_ack_ts = None
        self.last_ack_ts = None
        self.reset_obs()

        self.bin_bytes_sent = {}
        self.bin_bytes_acked = {}
        self.lat_ts = []
        self.lats = []

    def timeout(self):
        # placeholder
        raise NotImplementedError

    def debug_print(self):
        pass

    @property
    def avg_sending_rate(self):
        """Average sending rate in packets/second."""
        assert self.last_ack_ts is not None and self.first_ack_ts is not None
        assert self.last_sent_ts is not None and self.first_sent_ts is not None
        return self.tot_sent / (self.last_sent_ts - self.first_sent_ts)

    @property
    def avg_throughput(self):
        """Average throughput in packets/second."""
        assert self.last_ack_ts is not None and self.first_ack_ts is not None
        assert self.last_sent_ts is not None and self.first_sent_ts is not None
        return self.tot_acked / (self.last_ack_ts - self.first_ack_ts)

    @property
    def avg_latency(self):
        """Average latency in second."""
        return self.cur_avg_latency

    @property
    def pkt_loss_rate(self):
        """Packet loss rate in one connection session."""
        return 1 - self.tot_acked / self.tot_sent

    @property
    def bin_tput(self) -> Tuple[List[float], List[float]]:
        tput_ts = []
        tput = []
        for bin_id in sorted(self.bin_bytes_acked):
            tput_ts.append(bin_id * self.bin_size / 1000)
            tput.append(
                self.bin_bytes_acked[bin_id] * BITS_PER_BYTE / self.bin_size * 1000 / 1e6)
        return tput_ts, tput

    @property
    def bin_sending_rate(self) -> Tuple[List[float], List[float]]:
        sending_rate_ts = []
        sending_rate = []
        for bin_id in sorted(self.bin_bytes_sent):
            sending_rate_ts.append(bin_id * self.bin_size / 1000)
            sending_rate.append(
                self.bin_bytes_sent[bin_id] * BITS_PER_BYTE / self.bin_size * 1000 / 1e6)
        return sending_rate_ts, sending_rate

    @property
    def latencies(self) -> Tuple[List[float], List[float]]:
        return self.lat_ts, self.lats

SenderType = TypeVar('SenderType', bound=Sender)