import unittest
import json
import requests
from app import app
from threading import Thread
from time import sleep

# NOTE: Make sure you run 'pip3 install requests' in your virtualenv

# URL pointing to your local dev host
LOCAL_URL = "http://localhost:5000"

# Sample testing data
SAMPLE_USER = {"name": "Cornell AppDev", "username": "cornellappdev"}

# Request endpoint generators
def gen_users_path(user_id=None):
    base_path = f"{LOCAL_URL}/api/user"
    return base_path + "s/" if user_id is None else f"{base_path}/{str(user_id)}/"

def gen_send_path():
    return f"{LOCAL_URL}/api/send/"

def unwrap_response(response, body={}):
    try:
        return response.json()
    except:
        req = response.request
        raise Exception(f"""
            Error encountered on the following request:

            request path: {req.url}
            request method: {req.method}
            request body: {str(body)}

            There is an uncaught-exception being thrown in your
            method handler for this route!
            """)

class TestRoutes(unittest.TestCase):

#-- USERS ---------------------------------------------

    def test_get_initial_users(self):
        res = requests.get(gen_users_path())
        body = unwrap_response(res)
        assert body["success"]

    def test_create_user(self):
        res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER))
        body = unwrap_response(res, SAMPLE_USER)
        user = body["data"]
        assert body["success"]
        assert user["name"] == SAMPLE_USER["name"]
        assert user["username"] == SAMPLE_USER["username"]
        assert user["balance"] == 0

    def test_get_user(self):
        res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER))
        body = unwrap_response(res, SAMPLE_USER)
        user = body["data"]

        res = requests.get(gen_users_path(user["id"]))
        body = unwrap_response(res)
        user = body["data"]
        assert body["success"]
        assert user.get('id') is not None
        assert user["name"] == SAMPLE_USER["name"]
        assert user["username"] == SAMPLE_USER["username"]
        assert user["balance"] == 0

    def test_delete_user(self):
        res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER))
        body = unwrap_response(res, SAMPLE_USER)
        user_id = body["data"]["id"]

        res = requests.delete(gen_users_path(user_id))
        body = unwrap_response(res)
        assert body["success"]

        res = requests.get(gen_users_path(user_id))
        body = unwrap_response(res)
        assert not body["success"]

    def test_send_money(self):
        user_with_balance = {**SAMPLE_USER, "balance": 10}
        res1 = requests.post(gen_users_path(), data=json.dumps(user_with_balance))
        body = unwrap_response(res1, user_with_balance)
        user_id1 = body["data"]["id"]
        bal1 = body["data"]["balance"]
        assert bal1 == 10

        res2 = requests.post(gen_users_path(), data=json.dumps(user_with_balance))
        body = unwrap_response(res2, user_with_balance)
        user_id2 = body["data"]["id"]
        bal2 = body["data"]["balance"]
        assert bal1 == 10

        send_body = {"sender_id": user_id1, "receiver_id": user_id2, "amount": 6}

        res = requests.post(gen_send_path(), data=json.dumps(send_body))
        body = unwrap_response(res, send_body)
        assert body["success"]
        # balances are now (user1: 4, user2: 16)

        res1 = requests.get(gen_users_path(user_id1))
        body1 = unwrap_response(res1)
        res2 = requests.get(gen_users_path(user_id2))
        body2 = unwrap_response(res2)
        assert body1["data"]["balance"] == 4
        assert body2["data"]["balance"] == 16

        res = requests.post(gen_send_path(), data=json.dumps(send_body))
        body = unwrap_response(res, send_body)
        assert not body["success"]  # cannot overdraw user1's balance
        # balances are still (user1: 4, user2: 16)

        res1 = requests.get(gen_users_path(user_id1))
        body1 = unwrap_response(res1)
        res2 = requests.get(gen_users_path(user_id2))
        body2 = unwrap_response(res2)
        assert body1["data"]["balance"] == 4
        assert body2["data"]["balance"] == 16

    def test_get_invalid_user(self):
        res = requests.get(gen_users_path(1000))
        body = unwrap_response(res)
        assert not body["success"]

    def test_delete_invalid_user(self):
        res = requests.delete(gen_users_path(1000))
        body = unwrap_response(res)
        assert not body["success"]

    def test_user_id_increments(self):
        res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER))
        body = unwrap_response(res, SAMPLE_USER)
        user_id1 = body["data"]["id"]

        res2 = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER))
        body = unwrap_response(res2, SAMPLE_USER)
        user_id2 = body["data"]["id"]

        assert user_id1 + 1 == user_id2

def run_tests():
    sleep(1.5)
    unittest.main()

if __name__ == "__main__":
    thread = Thread(target=run_tests)
    thread.start()
    app.run(host="0.0.0.0", port=5000, debug=False)


import os
import sys
import json
import cv2
import gc
import sqlite3
import io
import numpy as np

from imutils.video import FileVideoStream
from multiprocessing import Pool, Lock

CLIPS_DIRECTORY="./dataset_dmd/clips"
ALLOWED_THREADS = 32
lock = Lock()
class_num_iter = 0
vid_num = 0

db = sqlite3.connect('dmd.db',check_same_thread=False)

cur = db.cursor()

cur.execute('''CREATE TABLE IF NOT EXISTS Data(
                    ID INTEGER PRIMARY KEY AUTOINCREMENT,
                    label TEXT, vid_num INT, frame INT,
                    bytes ARRAY, age TEXT,
                    gender TEXT, exp TEXT,
                    freq TEXT
                    )''')

def adapt_array(arr):
    """
    http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
    """
    out = io.BytesIO()
    np.save(out, arr)
    out.seek(0)
    return sqlite3.Binary(out.read())

def convert_array(text):
    import io
    out = io.BytesIO(text)
    out.seek(0)
    return np.load(out)

def save_image_to_db(img,metadata,label,frame_num,vid_num):
    blob = adapt_array(img)
    age = metadata["age"]
    gender = metadata["gender"]
    exp = metadata["exp"]
    freq = metadata["d_freq"]

    sql = ''' INSERT INTO Data(label,vid_num,frame,bytes,age,gender,exp,freq)
    VALUES(?,?,?,?,?,?,?,?) '''
    db.execute(sql, (label,vid_num,frame_num,blob,age,gender,exp,freq))
    db.commit()

sqlite3.register_adapter(np.ndarray, adapt_array)
sqlite3.register_converter("ARRAY", convert_array)

def parse_json_file(path):
    l = open(path)
    j = json.load(l)
    valid_mdata = False
    valid_labels = False
    mdata = {}
    #Boolean array to verify the clip is a valid clip
    for k in j.keys():
        age = 0
        gender = ''
        exp = ''
        d_freq = ''

        events = []
        frame_data = []
        c = 0

        print(j[k].keys())
        metadata_str = 'objects'

        #Grabs meta
        if metadata_str in j[k].keys():
            m_data = j[k][metadata_str]
            for d in m_data.keys():
                if 'type' in m_data[d].keys():

                    if m_data[d]['type'] == 'driver':
                        if 'object_data' in m_data[d].keys():
                            driver_info = m_data[d]['object_data']
                            for category in driver_info['num']:
                                if category['name'] == 'age':
                                    age = category['val']
                                    c+=1
                            for attribute in m_data[d]['object_data']['text']:
                                if attribute['name'] == "gender":
                                    gender = attribute['val']
                                    c+=1
                                elif attribute['name'] == 'experience':
                                    exp = attribute['val']
                                    c+=1
                                elif attribute['name'] == 'drive_freq':
                                    d_freq = attribute['val']
                                    c+=1
                                else:
                                    print(f"DIFFERENT ATTRIBUTE THAN ACCOUNTED FOR {attribute}")
        else:
            print("NO METADATA TO EXTRACT")

        framedata_str = 'actions'

        if framedata_str in j[k].keys():
            actions = j[k][framedata_str]
            for t in actions.keys():
                event = actions[t]
                label = ''
                if 'type' in event.keys():
                    label = event['type']
                    if event['type'] not in events:
                        events.append(label)

                    if "frame_intervals" in event.keys():
                        entries = event["frame_intervals"]
                        for entry in entries:
                            st = entry["frame_start"]
                            en = entry["frame_end"]
                            if label == '':
                                print("bad")
                                break
                            else:
                                valid_labels = True
                                frame_data.append( (st,en,label) )
        #Valid clip
        if c == 4:
            print("CLIP VALID")
            mdata = {'age':age, 'gender':gender, 'exp':exp, 'd_freq':d_freq}
            valid_mdata = True

    if valid_mdata and valid_labels:
        return mdata,frame_data,events
    else:
        return None

def return_start_frame_number(entry):
    return entry[0]

def get_clip_object(match_str,l,st,frame_size):
    fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
    fname = CLIPS_DIRECTORY+"/"+match_str+";"+l.replace("/","-")+f";{st}.mp4"
    if os.path.exists(fname):
        return None
    else:
        lock.acquire()
        w = cv2.VideoWriter(CLIPS_DIRECTORY+"/"+match_str+";"+l.replace("/","-")+f";{st}.mp4", fourcc, 20, frame_size)
        lock.release()
        return w

def write_clip(path,st,en,l,match_str,frame_size,vid_num,class_num,metadata):
    label = l.replace("/","-")
    fname = CLIPS_DIRECTORY+"/"+match_str+";"+l.replace("/","-")+f";{st}.mp4"

    print(path)
    lock.acquire()
    capture = FileVideoStream(path).start()
    lock.release()

    c = 0

    use_db = False

    print(vid_num)

    frames_directory = f"./dataset_dmd/clips/{label}/{vid_num}/"
    if not os.path.exists(frames_directory):
        os.makedirs(frames_directory)

    while True:
        if c == st:

            for i in range(0,en-st):
                frame = capture.read()
                good = type(frame) != type(None)

                if good:
                    print(st,en,l,i)
                    image_name = "img_{:07d}.jpg".format(i)
                    if use_db:
                        lock.acquire()
                        save_image_to_db(frame,metadata,label,i,vid_num)
                        lock.release()
                    else:
                        cv2.imwrite(frames_directory+image_name,frame)

                else:
                    capture.stop()
                    print(st,en,l,i)
                    print("STREAM BAD")
                    gc.collect()
                    return None
                c+=1
            break
        elif c < st:
            frame = capture.read()
            good = type(frame) != type(None)
            if not good:
                capture.stop()
                print(st,en,l,)
                print("STREAM BAD")
                gc.collect()
                return None
            c+=1

    lock.acquire()
    capture.stop()

    with open(CLIPS_DIRECTORY+"/annotations.txt","a+") as f:
        f.write(f"{label}/{vid_num} {en-st} {class_num} {metadata}\n")
    lock.release()

    gc.collect()
    return None

def clip_segmenter(path,match_str,segments,global_labels,metadata):

    class_counters = {}
    pool = Pool(ALLOWED_THREADS)

    segments = sorted(segments,key=return_start_frame_number)
    threads = [0 for i in range(ALLOWED_THREADS)]

    capture2 = cv2.VideoCapture(path)

    frame_width = int(capture2.get(3))
    frame_height = int(capture2.get(4))
    frame_size = (frame_width,frame_height)

    capture2.release()

    c = 0
    for st,en,l in segments:
        # write_clip(path,st,en,l,match_str)
        label = l
        if label not in class_counters.keys():
            class_counters[label] = 1
            vid_num = 1
        else:
            class_counters[label] += 1
            vid_num = class_counters[label]

        if c < ALLOWED_THREADS:
            p = pool.apply_async(write_clip, (path,st,en,l,match_str,frame_size,vid_num,global_labels[l],metadata,))
            threads[c] = (p,st,en,l)
            gc.collect()
            c+=1
        else:
            for i in range(ALLOWED_THREADS):
                t,st1,en1,l1 = threads[i]
                print(t)
                if t != 0:
                    t.get()
                    gc.collect()

                threads[i] = 0
            c = 0
    a = 0
    for i in range(ALLOWED_THREADS):
        if threads[i] != 0:
            t,st1,en1,l1 = threads[i]
            if t != 0:
                t.get()
                gc.collect()

        a+=1

def iterate_data(pairs,global_labels):
    global class_num_iter
    total_labels = []
    features = {}
    for key in pairs.keys():
        json_path,vid_path = pairs[key]

        #If no video was found
        if vid_path == 0:
            continue

        check = parse_json_file(json_path)

        if check != None:
            metadata,segs,labels_set = check
            for label in labels_set:
                if label not in global_labels.keys():
                    global_labels[label] = class_num_iter
                    class_num_iter+=1

            clip_segmenter(vid_path,key,segs,global_labels,metadata)

            features[key] = metadata

#Connect json file to mp4 files
def create_file_pairs(path):
    file_pairs = {}
    for root, dirs, files in os.walk(path, topdown=False):
        for f in files:
            if "clips" in root:
                continue

            if ".mp4" in f:
                match_string = f.split(";")[0]
                if match_string not in file_pairs.keys():
                    file_pairs[match_string] = [0,root+"/"+f]
                else:
                    tmp = file_pairs[match_string]
                    tmp[1] = root+"/"+f
                    file_pairs[match_string]= tmp
            if ".json" in f:
                match_string = f.split(";")[0]
                if match_string not in file_pairs.keys():
                    file_pairs[match_string] = [root+"/"+f,0]
                else:
                    tmp = file_pairs[match_string]
                    tmp[0] = root+"/"+f
                    file_pairs[match_string]= tmp

    return file_pairs

if __name__ == "__main__":
    clear_data = True

    if clear_data and os.path.exists(CLIPS_DIRECTORY):
        import shutil
        shutil.rmtree(CLIPS_DIRECTORY)

    if not os.path.exists(CLIPS_DIRECTORY):
        os.mkdir(CLIPS_DIRECTORY)

    all_labels = {}
    file_pairs = create_file_pairs("./dataset_dmd")
    iterate_data(file_pairs,all_labels)


"""
Transaction Models
"""
from django.db import models
from django.db import transaction
from django.core.exceptions import ValidationError
from django.db.models import Q

class Transaction(models.Model):
    """
    Transaction model includes withdrawal, deposit, transfer.
    uses ints to avoid pitfalls of floats.
    e.g:
    >>> 1000.00 - 65.43
    934.5699999999999
    >>> (int(1000.00*100) - int(65.43*100))/100
    934.57
    """
    TRANSACTION_TYPES = ("deposit", "withdrawal", "transfer")
    created_on = models.DateTimeField(auto_now=True, null=False, db_index=True,)
    transaction_type = models.CharField(max_length=20, db_index=True, null=False)
    _amount = models.IntegerField(db_index=True, null=False)
    account_to = models.ForeignKey(
        'accounts.Account',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='deposits_to'
    )
    account_from = models.ForeignKey(
        'accounts.Account',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='withdrawals_from'
    )
    creator = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
        null=False,
        related_name='transactions_processed'
    )

    @classmethod
    def get_by_account(cls, account):
        return cls.objects.filter(
            Q(account_from=account) | Q(account_to=account)
        ).order_by('-pk').all()

    @property
    def amount(self):
        return self._amount / 100

    @amount.setter
    def amount(self, value):
        self._amount = int(value * 100)
        return self.amount

    def __str__(self):
        return "{0}:{1:.2f}".format(
            self.transaction_type,
            self.amount
        )

    def clean(self, *args, **kwargs):
        """
        Custom Validatation:
        A transaction cannot be edited.
        A transaction must have an account associated
        A transaction must have a known type
        """
        if self.id:
            raise ValidationError("Cannot edit a transaction")
        if not (self.account_from or self.account_to)  or self.account_from == self.account_to:
            raise ValidationError("Must be associated with an account")
        if self.transaction_type not in self.TRANSACTION_TYPES:
            raise ValidationError("Cannot have unknown transaction type")
        if not (
            (
                self.transaction_type == "deposit" and
                self.account_to and
                not self.account_from
            ) or
            (
                self.transaction_type == "withdrawal" and
                not self.account_to and
                self.account_from
            ) or
            (
                self.transaction_type == "transfer" and
                self.account_to and
                self.account_from
            )
        ):
            raise ValidationError("Incorrect transaction format")
        if not (self._amount and self.amount > 0):
            raise ValidationError("Amount muse be greater than 0")
        super(Transaction, self).clean(*args, **kwargs)

    @transaction.atomic
    def save(self, *args, **kwargs):
        """
        During save ask the accounts to update.
        """
        self.full_clean()
        if self.account_from:
            self.account_from.withdraw(self.amount)
        if self.account_to:
            self.account_to.deposit(self.amount)
        super(Transaction, self).save(*args, **kwargs)


"""

11060 점프 점프

"""
import sys
from collections import deque
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split()))

if n == 1:
    print(0)
    sys.exit()
visit = [0] * n

q = deque()
q.append((0, a[0]))

while q:
    now, jump = q.popleft()
    for i in range(1, jump + 1):
        if now + i >= n or visit[now + i]:
            continue
        visit[now + i] = visit[now] + 1
        q.append((now + i,a[now + i]))

print(visit[-1] if visit[-1] else -1)


import os
import pickle
from pathlib import Path
from typing import Tuple

import numpy as np
from tqdm import tqdm

from processing.bayesian_inference import BayesianInference
from processing.utils.constants import PHASE_OUTPUT_PATH

window_size = 57
overlap = 1
sampling_step = 1 / 100

def load_phases(file_path: Path) -> Tuple[np.ndarray, np.ndarray]:
    infile = open(str(file_path), "rb")
    patient = pickle.load(infile, encoding="utf-8")
    phases = tuple(phase.reshape(1, -1) for _, phase in patient.items())
    return phases[0], phases[1]

def construct_name(file_path: Path) -> Path:
    file_path = file_path.with_suffix("")
    _, file_name = os.path.split(file_path)
    return Path(file_name)

def patient_bayes_main() -> None:
    FILE_PATHS = [path for path in PHASE_OUTPUT_PATH.rglob("*.pickle")]

    bayesian = BayesianInference(window_size, sampling_step, overlap)
    bayesian.check_folder()

    for file_path in tqdm(FILE_PATHS):
        file_name = construct_name(file_path)
        first_phase, second_phase = load_phases(file_path)
        bayesian(first_phase, second_phase)
        bayesian.save_inferred_data(file_name)

    print(bayesian.empty_report)

if __name__ == "__main__":
    patient_bayes_main()


from Module import AbstractModule

class Module(AbstractModule):
    def __init__(self):
        AbstractModule.__init__(self)

    def run(
        self, network, antecedents, out_attributes, user_options, num_cores,
        outfile):
        import os
        import subprocess
        import arrayio
        from genomicode import filelib
        from Betsy import read_label_file
        from Betsy import module_utils
        from genomicode import config
        data_node_train, data_node_test, cls_node_train = antecedents
        module_name = 'WeightedVoting'
        gp_parameters = dict()
        file1, file2 = module_utils.convert_to_same_platform(
            data_node_train.identifier, data_node_test.identifier)
        result, label_line, class_name = read_label_file.read(
            cls_node_train.identifier)
        M = arrayio.read(data_node_test.identifier)
        label_line = ['0'] * M.dim()[1]
        read_label_file.write('temp_test.cls', class_name, label_line)
        gp_parameters['train.filename'] = file1
        gp_parameters['train.class.filename'] = cls_node_train.identifier
        gp_parameters['test.filename'] = file2
        gp_parameters['test.class.filename'] = 'temp_test.cls'
        if 'wv_num_features' in user_options:
            gp_parameters['num.features'] = str(user_options['wv_num_features'])

        if 'wv_minstd' in user_options:
            assert module_utils.is_number(
                user_options['wv_minstd']), 'the sv_minstd should be number'
            gp_parameters['min.std'] = str(user_options['wv_minstd'])

        wv_feature_stat = ['wv_snr', 'wv_ttest', 'wv_snr_median',
                           'wv_ttest_median', 'wv_snr_minstd', 'wv_ttest_minstd',
                           'wv_snr_median_minstd', 'wv_ttest_median_minstd']

        assert out_attributes['wv_feature_stat'] in wv_feature_stat, (
            'the wv_feature_stat is invalid'
        )
        gp_parameters['feature.selection.statistic'] = str(
            wv_feature_stat.index(out_attributes['wv_feature_stat']))
        gp_path = config.genepattern
        gp_module = module_utils.which(gp_path)
        assert gp_module, 'cannot find the %s' % gp_path
        download_directory = os.path.join(".", 'wv_result')
        command = [gp_module, module_name, '-o', download_directory]
        for key in gp_parameters.keys():
            a = ['--parameters', key + ':' + gp_parameters[key]]
            command.extend(a)

        process = subprocess.Popen(command,
                                   shell=False,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        process.wait()
        error_message = process.communicate()[1]
        if error_message:
            raise ValueError(error_message)

        assert os.path.exists(download_directory), (
            'there is no output directory for weightedVoting'
        )
        result_files = os.listdir(download_directory)
        assert 'stderr.txt' not in result_files, 'gene_pattern get error'
        gp_files = os.listdir(download_directory)
        for gp_file in gp_files:
            if gp_file.endswith('pred.odf'):
                gp_file = os.path.join(download_directory, gp_file)
                f = file(gp_file, 'r')
                text = f.readlines()
                f.close()
                os.rename(os.path.join(download_directory, gp_file),
                          os.path.join(download_directory, 'prediction.odf'))
                assert text[1][0:12] == 'HeaderLines='
                start = int(text[1][12:-1])
                newresult = [['Sample_name', 'Predicted_class', 'Confidence']]
                for i in text[start + 2:]:
                    line = i.split()
                    n = len(line)
                    newline = [' '.join(line[0:n - 4]), line[n - 3], line[n - 2]]
                    newresult.append(newline)
                f = file(outfile, 'w')
                for i in newresult:
                    f.write('\t'.join(i))
                    f.write('\n')
                f.close()

        assert filelib.exists_nz(outfile), (
            'the output file %s for classify_with_weighted_voting fails' % outfile
        )

    def name_outfile(self, antecedents, user_options):
        from Betsy import module_utils
        data_node_train, data_node_test, cls_node_train = antecedents
        original_file = module_utils.get_inputid(data_node_train.identifier)
        filename = 'weighted_voting_' + original_file + '.cdt'
        return filename


# -*- coding:utf8 -*-

from wavTools import *

wav_path = "./voice_files/demo.wav"
pcm_path = "./voice_files/demo.pcm"
wav_path2 = "./voice_files/test.wav"

# 音频切割的文件路径
main_wav_path = "./part_voice_files/12.wav"
part_wav_path = "./part_voice_files/ms_part_voice.wav"
second_part_wav_path = "./part_voice_files/second_part_wav_path.wav"
minute_part_wav_path = "./part_voice_files/minute_part_wav_path.wav"

# 获取音频信息
ret = wav_infos(wav_path)
print(ret)

# 读取音频文件内容
ret = read_wav(wav_path)
print(ret)

# 获取音频时长(单位秒)
ret = get_wav_time(wav_path)
print(ret)

# 音频切片，获取部分音频 时间的单位是毫秒
start_time = 13950
end_time = 15200
get_ms_part_wav(main_wav_path, start_time, end_time, part_wav_path)

# 音频切片，获取部分音频 时间的单位是秒
start_time = 35
end_time = 38
get_second_part_wav(main_wav_path, start_time, end_time, second_part_wav_path)

# 音频切片，获取部分音频 时间的单位是分钟和秒 样式：0:12
start_time = "0:35"
end_time = "0:38"
get_minute_part_wav(main_wav_path, start_time, end_time, minute_part_wav_path)

# wav文件转为pcm文件
wav_to_pcm(wav_path, pcm_path)

# pcm文件转为wav文件
pcm_to_wav(pcm_path, wav_path2)

# 音频对应的波形图
wav_waveform(wav_path)


"""
Views Module
------------
"""
from pyramid.response import Response
from pyramid.httpexceptions import HTTPNotFound, HTTPFound
from ..lib.auth import __acl__

__all__ = ['View', 'forbidden', 'Root', 'Users', 'AdminRoot', 'APIRoot',
           'APIUsers']

class View(object):
    """
    The master View class for the app.

    .. note:: Pagination size is handled via the ``items_per_page`` attribute.
    """
    def __init__(self, request):
        self.request = request
        self.items_per_page = 25
        self.__acl__ = __acl__

def forbidden(request):
    """
    The custom ``forbidden`` view.

    By customizing the ``forbidden`` view, we can do things like redirect
    unauthenticated users to the login page, or return a proper JSON forbidden
    response.
    """
    flash = request.session.flash
    next = request.current_route_path()

    # If accepting JSON, just respond with a 401 or 403
    if 'application/json' in str(request.accept):
        # Prepare the JSON response object
        response = Response(content_type='application/json')
        # This is a publicly accessible API
        response.headers.update({'Access-Control-Allow-Origin': '*'})

        # Set the appropriate response status
        if request.current_user:
            response.status = '403 Forbidden'
        else:
            response.status = '401 Unauthorized'
            # Token authorization is expected
            response.headers.update({'WWW-Authenticate': 'Token'})

        return response
    # Otherwise, return a redirect
    elif request.current_user:
        flash(('You are not authorized to access that location.', 'warning'))
        return HTTPFound(location=request.route_path('root_index'))
    else:
        flash(('Please log in before continuing.', 'warning'))
        return HTTPFound(
            location=request.route_path('users', action='login',
                                        _query=dict(next=next))
        )

# Load view classes
from .root import Root
from .users import Users
from .admin.root import AdminRoot
from .api.root import APIRoot
from .api.users import APIUsers


from . import framework as fw

# Timer variables

active_timers = [] # list of event tuples: (trigger_time, event_type, data)

paused_timers = [] # list of event tuples: (trigger_time, event_type, data)

elapsed = False # Whether any timers have elapsed and need processing.

# Timer functions.

def reset():
    # Reset timer variables.
    global active_timers, paused_timers, elapsed
    active_timers = []
    paused_timers = []
    elapsed = False

def set(interval, event_type, event_data):
    # Set a timer to trigger specified event after 'interval' ms has elapsed.
    active_timers.append((fw.current_time+int(interval), event_type, event_data))
    active_timers.sort(reverse=True)

def check():
    #Check whether timers have triggered.
    global elapsed
    elapsed = bool(active_timers) and (active_timers[-1][0] <= fw.current_time)
    fw.check_timers = False

def get():
    # Get first timer event.
    global elapsed
    event_tuple = active_timers.pop()
    elapsed = bool(active_timers) and (active_timers[-1][0] <= fw.current_time)
    return event_tuple

def disarm(event_ID):
    # Remove all user timers with specified event_ID.
    global active_timers, paused_timers
    active_timers = [t for t in active_timers if not (t[2] == event_ID and (t[1] in (fw.event_typ, fw.timer_typ)))]
    paused_timers = [t for t in paused_timers if not  t[2] == event_ID]

def pause(event_ID):
    # Pause all user timers with specified event_ID.
    global active_timers, paused_timers
    paused_timers += [(t[0]-fw.current_time,t[1], t[2]) for t in active_timers
                      if (t[2] == event_ID and (t[1] in (fw.event_typ, fw.timer_typ)))]
    active_timers = [t for t in active_timers if not (t[2] == event_ID and (t[1] in (fw.event_typ, fw.timer_typ)))]

def unpause(event_ID):
    # Unpause user timers with specified event.
    global active_timers, paused_timers
    active_timers += [(t[0]+fw.current_time,t[1], t[2]) for t in paused_timers if t[2] == event_ID]
    paused_timers = [t for t in paused_timers if not t[2] == event_ID]
    active_timers.sort(reverse=True)

def remaining(event_ID):
    # Return time until timer for specified event elapses, returns 0 if no timer set for event.
    try:
        return next(
            t[0] - fw.current_time for t in reversed(active_timers) if (t[1] == fw.event_typ and t[2] == event_ID)
        )
    except StopIteration:
        return 0

def disarm_type(event_type):
    # Disarm all active timers of a particular type.
    global active_timers
    active_timers = [t for t in active_timers if not t[1] == event_type]


"""Command-line interface for scheduling checks and alerts.

Run the check once unless a frequency (in minutes) is provided.
"""

import click

from .alert import main as alert
from .utils import start_log

@click.group()
def main():
    """Run or schedule exposure site checks."""
    pass

@click.command()
def once():
    """Run a check now."""
    alert()

@click.command()
@click.option('--freq', type=click.IntRange(min=1), default=60, show_default=True, help="Frequency (in minutes) of scheduled checks.")
@click.option('--end', type=str, default="23:00", show_default=True, help="When scheduled checks will end.")
def every(freq, end):
    """Schedule checks in the future."""
    alert(freq, end)

main.add_command(once)
main.add_command(every)

if __name__ == '__main__':
    cli_logger = start_log('cli', 7)
    cli_logger.debug('Called from command line')
    main()


import copy
from collections import OrderedDict
from typing import List, Tuple

import torch
from torch import Tensor, nn
from torch.optim import Adam, Optimizer
from torch.utils.data import DataLoader

from agent.agent_value_based import ValueBasedAgent
from env.env import Env
from model.model import Model
from system.dqn.dataset import RLDataset
from system.dqn.replay_buffer import ReplayBuffer

from ..system import System

class DqnSystem(System):
    def __init__(
        self,
        env: Env,
        model: Model,
        agent: ValueBasedAgent,
        *args,
        batch_size: int = 16,
        lr: float = 1e-2,
        gamma: float = 0.99,
        sync_rate: int = 10,
        replay_size: int = 1000,
        warm_start_size: int = 1000,
        eps_last_frame: int = 1000,
        eps_start: float = 1.0,
        eps_end: float = 0.01,
        episode_length: int = 200,
        warm_start_steps: int = 1000,
        **kwargs,
    ) -> None:

        super().__init__(env, model, agent, *args, **kwargs)
        self.save_hyperparameters(ignore=["env", "model", "agent"])

        self.env = env

        self.net = model
        self.target_net = copy.deepcopy(model)

        self.buffer = ReplayBuffer(self.hparams.replay_size)
        self.agent = agent

        self.total_reward = 0
        self.episode_reward = 0

        self.populate(self.hparams.warm_start_steps)

    def populate(self, steps: int = 1000) -> None:
        for _ in range(steps):
            self.agent.play_step(self.net, epsilon=1.0, replay_buffer=self.buffer)

    def forward(self, x: Tensor) -> Tensor:
        output = self.net(x)
        return output

    def dqn_mse_loss(self, batch: Tuple[Tensor, Tensor]) -> Tensor:
        states, actions, rewards, dones, next_states = batch

        state_action_values = (
            self.net(states).gather(1, actions.long().unsqueeze(-1)).squeeze(-1)
        )

        with torch.no_grad():
            next_state_values = self.target_net(next_states).max(1)[0]
            next_state_values[dones] = 0.0
            next_state_values = next_state_values.detach()

        expected_state_action_values = next_state_values * self.hparams.gamma + rewards

        return nn.MSELoss()(state_action_values, expected_state_action_values)

    def get_epsilon(self, start: int, end: int, frames: int) -> float:
        if self.global_step > frames:
            return end
        return start - (self.global_step / frames) * (start - end)

    def training_step(self, batch: Tuple[Tensor, Tensor], nb_batch) -> OrderedDict:
        device = self.get_device(batch)
        epsilon = self.get_epsilon(
            self.hparams.eps_start, self.hparams.eps_end, self.hparams.eps_last_frame
        )
        self.log("epsilon", epsilon)

        # step through environment with agent
        reward, done = self.agent.play_step(
            self.net, epsilon, device, replay_buffer=self.buffer
        )
        self.episode_reward += reward
        self.log("episode reward", self.episode_reward)

        # calculates training loss
        loss = self.dqn_mse_loss(batch)

        if done:
            self.total_reward = self.episode_reward
            self.episode_reward = 0

        # Soft update of target network
        if self.global_step % self.hparams.sync_rate == 0:
            self.target_net.load_state_dict(self.net.state_dict())

        self.log_dict(
            {
                "reward": reward,
                "train_loss": loss,
            }
        )
        self.log("total_reward", self.total_reward, prog_bar=True)
        self.log("steps", self.global_step, logger=False, prog_bar=True)

        return loss

    def configure_optimizers(self) -> List[Optimizer]:
        """Initialize Adam optimizer."""
        optimizer = Adam(self.net.parameters(), lr=self.hparams.lr)
        return optimizer

    def __dataloader(self) -> DataLoader:
        """Initialize the Replay Buffer dataset used for retrieving experiences."""
        dataset = RLDataset(self.buffer, self.hparams.episode_length)
        dataloader = DataLoader(dataset=dataset, batch_size=self.hparams.batch_size)
        return dataloader

    def train_dataloader(self) -> DataLoader:
        """Get train loader."""
        return self.__dataloader()

    def get_device(self, batch) -> str:
        """Retrieve device currently being used by minibatch."""
        return batch[0].device.index if self.on_gpu else "cpu"


import sys
N = int(input())
dic = {}
for n in range(N) :
    name, log = sys.stdin.readline().split()
    if log == 'enter' :
        dic[name] = 1
    else :
        dic[name] = 0

member = []

for i in dic :
    if dic[i] == 1 :
        member.append(i)

member.sort(reverse = True)

for m in member :
    print(m)

Python_Algorithm/문자열, 배열, 구현, 그리디/boj 7785 문자열.py


import xml.etree.ElementTree as ET
from Doc import Doc
import pandas as pd

def extract_xml(filename):
    tree = ET.parse(filename)
    root = tree.getroot()
    docs = {}
    for page in root.findall("{http://www.mediawiki.org/xml/export-0.10/}page"):
        id = int(page.find("{http://www.mediawiki.org/xml/export-0.10/}id").text)
        text = page.find("{http://www.mediawiki.org/xml/export-0.10/}revision") \
            .find("{http://www.mediawiki.org/xml/export-0.10/}text").text
        docs[id] = Doc(id, text)
    return docs

def extract_csv(filename):
    docs = {}
    df = pd.read_csv(filename)
    for i in range(df.shape[0]):
        text = df['Title'].values[i] + " " + df['Text'].values[i]
        if "Tag" in df.columns:
            tag = df['Tag'].values[i]
        else:
            tag = None
        docs[i] = Doc(i, text, tag)
    return docs

def read_docs(filename):
    if filename.endswith('xml'):
        return extract_xml(filename)
    return extract_csv(filename)

if __name__ == "__main__":
    # docs = read_docs("../data/Persian.xml")
    docs = read_docs("../data/phase2_train.csv")

    print(docs[0].tag, docs[0].id, docs[0].text)


"""
question:
https://leetcode.cn/problems/robot-in-a-grid-lcci/
"""
from typing import List

class Solution:
    def pathWithObstacles(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
            return []

        path = []
        end = False
        visited = [[0] * n for _ in range(m)]

        def dfs(row, col):
            nonlocal end
            if visited[row][col] == 1 or obstacleGrid[row][col] == 1:
                return
            visited[row][col] = 1
            path.append([row, col])
            if row == m - 1 and col == n - 1:
                end = True
                return
            if row + 1 < m:
                dfs(row + 1, col)
                if end:
                    return
            if col + 1 < n:
                dfs(row, col + 1)
                if end:
                    return
            path.pop()

        dfs(0, 0)
        # print(path)
        return path

    def pathWithObstacles2(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
            return []

        path = []

        def dfs(row, col):
            if obstacleGrid[row][col] == 1:
                return
            obstacleGrid[row][col] = 1
            path.append([row, col])
            if row == m - 1 and col == n - 1:
                return True
            if row + 1 < m and dfs(row + 1, col):
                return True
            if col + 1 < n and dfs(row, col + 1):
                return True
            path.pop()

        dfs(0, 0)
        # print(path)
        return path

    def pathWithObstacles3(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
            return []

        dp = [[-1] * n for _ in range(m)]
        dp[0][0] = 0

        for i in range(m):
            for j in range(n):
                if obstacleGrid[i][j] == 1:
                    continue
                if i > 0 and dp[i - 1][j] != -1:
                    dp[i][j] = (i - 1) * n + j
                elif j > 0 and dp[i][j - 1] != -1:
                    dp[i][j] = i * n + j - 1

        i, j = m - 1, n - 1
        if dp[i][j] == -1:
            return []
        path = [[i, j]]
        while i != 0 or j != 0:
            i, j = dp[i][j] // n, dp[i][j] % n
            path.append([i, j])

        # print(path[::-1])
        return path[::-1]

if __name__ == '__main__':
    assert Solution().pathWithObstacles3([
        [0, 0, 0],
        [0, 1, 0],
        [0, 0, 0]
    ]) == [[0, 0], [0, 1], [0, 2], [1, 2], [2, 2]]
    assert Solution().pathWithObstacles3([[1]]) == []
    assert Solution().pathWithObstacles3([[0]]) == [[0, 0]]
    assert Solution().pathWithObstacles3([[0, 0], [1, 0]]) == [[0, 0], [0, 1], [1, 1]]


from ardb.User import User
from datetime import datetime

class ScDbUtil:

    @staticmethod
    def create_user_to_db(scUser):
        u = User()
        u.convert(soundcloudUser=scUser)
        u.dt_bd_action=datetime.today()
        return u

    @staticmethod
    def scUsersToJsonDbUsers(usersList):
        dbUsers = []
        for user in usersList :
           dbUsers.append(ScDbUtil.create_user_to_db(user).to_dict())
        return dbUsers


import math
import random

import numpy as np

class Bee(object):
    def __init__(self, problem):
        self.param = []
        self.fitness = problem
        self.f_value = 0

    def calculate_fitness(self):
        self.f_value = self.fitness(*self.param)

    def __lt__(self, other):
        return self.f_value < other.f_value

    def __gt__(self, other):
        return self.f_value > other.f_value

    def __str__(self):
        return str(self.f_value)

class BeeScout(Bee):
    def __init__(self, problem):
        super(BeeScout, self).__init__(problem)

    def randomize_position(self, init_range):
        self.param = [random.random() * (prm[1] - prm[0]) + prm[0] for prm in init_range]

    def search_local(self, area, bound):
        s = random.random() * 2 * area - area
        k = random.random() * 360
        x1 = self.param[0] + math.sin(k) * s
        x2 = self.param[1] + math.cos(k) * s
        if x1 < bound[0][0]:
            x1 = bound[0][0]
        elif x1 > bound[0][1]:
            x1 = bound[0][1]
        if x2 < bound[1][0]:
            x2 = bound[1][0]
        elif x2 > bound[1][1]:
            x2 = bound[1][1]
        self.param = [x1, x2]
        self.calculate_fitness()

    def assign_param(self, param):
        self.param = param

class BeeWorker(Bee):
    def __init__(self, scout):
        super(BeeWorker, self).__init__(scout.fitness)
        self.scout = scout

    def search_neighbourhood(self, neigh_area):
        s = random.random() * 2 * neigh_area - neigh_area
        k = random.random() * 360
        x1 = self.scout.param[0] + math.sin(k) * s
        x2 = self.scout.param[1] + math.cos(k) * s
        self.param = [x1, x2]
        self.calculate_fitness()

    def promote(self):
        scout = BeeScout(self.scout.fitness)
        scout.assign_param(self.param)
        return scout

class AntWorker(object):
    def __init__(self):
        self.total_cost = 0.0
        self.path = []
        self.local_pheromone = []

    def __lt__(self, other):
        return self.total_cost < other.total_cost

    def __gt__(self, other):
        return self.total_cost > other.total_cost

    def calculate_fitness(self, f):
        self.total_cost = f(self.path)

    def choose_path(self, alg, dist):
        rank = len(dist)
        eta = [[0 if i == j else 1 / dist[i][j] for j in range(rank)] for i in range(rank)]
        possible = list(range(rank))
        visited = []
        start = random.randint(0, rank - 1)
        possible.remove(start)
        visited.append(start)
        last = start
        for _ in range(rank - 1):
            if alg.greediness >= random.random():
                index = np.argmax(np.multiply(np.take(alg.pheromones[last], possible),
                                              np.power(np.take(eta[last], possible), alg.beta)))
                selected = possible[int(index)]
            else:
                denominator = 0
                for j in possible:
                    denominator += alg.pheromones[last][j] ** alg.alpha * eta[last][j] ** alg.beta
                probabilities = [0 for _ in range(rank)]
                for j in range(rank):
                    try:
                        possible.index(j)
                        probabilities[j] = alg.pheromones[last][j] ** alg.alpha * eta[last][j] ** alg.beta / denominator
                    except ValueError:
                        pass
                selected = -1
                rand = random.random()
                for j, probability in enumerate(probabilities):
                    rand -= probability
                    if rand <= 0:
                        selected = j
                        break
            possible.remove(selected)
            visited.append(selected)
            last = selected
        self.path = visited

    def local_update_pheromone(self, alg):
        rank = len(self.path)
        self.local_pheromone = [[0 for _ in range(rank)] for _ in range(rank)]
        for i in range(len(self.path) - 1):
            x = self.path[i]
            y = self.path[i + 1]
            new_value = self.local_pheromone[x][y] * (1 - alg.local_phero_c) + alg.local_phero_c * alg.init_phero_val
            self.local_pheromone[x][y] = new_value
            self.local_pheromone[y][x] = new_value
        x = self.path[len(self.path) - 1]
        y = self.path[0]
        new_value = self.local_pheromone[x][y] * (1 - alg.local_phero_c) + alg.local_phero_c * alg.init_phero_val
        self.local_pheromone[x][y] = new_value
        self.local_pheromone[y][x] = new_value


import os
import sys

__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))

import json
import cv2
import numpy as np
from copy import deepcopy
from PIL import Image

import torch
from pytorchnlp.transformers import LayoutXLMTokenizer, LayoutXLMModel, LayoutXLMForTokenClassification
from pytorchnlp.transformers import LayoutLMTokenizer, LayoutLMModel, LayoutLMForTokenClassification

# relative reference
from vqa_utils import parse_args, get_image_file_list, draw_ser_results, get_bio_label_maps

from vqa_utils import pad_sentences, split_page, preprocess, postprocess, merge_preds_list_with_ocr_info

MODELS = {
    'LayoutXLM':
    (LayoutXLMTokenizer, LayoutXLMModel, LayoutXLMForTokenClassification),
    # 'LayoutLM':
    # (LayoutLMTokenizer, LayoutLMModel, LayoutLMForTokenClassification)
}

def trans_poly_to_bbox(poly):
    x1 = np.min([p[0] for p in poly])
    x2 = np.max([p[0] for p in poly])
    y1 = np.min([p[1] for p in poly])
    y2 = np.max([p[1] for p in poly])
    return [x1, y1, x2, y2]

def parse_ocr_info_for_ser(ocr_result):
    ocr_info = []
    for res in ocr_result:
        ocr_info.append({
            "text": res[1][0],
            "bbox": trans_poly_to_bbox(res[0]),
            "poly": res[0],
        })
    return ocr_info

class SerPredictor(object):
    def __init__(self, args):
        self.args = args
        # args["init_class"] = 'LayoutLMModel'
        self.max_seq_length = args.max_seq_length

        # init ser token and model
        tokenizer_class, base_model_class, model_class = MODELS[args.ser_model_type]

        # self.tokenizer = LayoutXLMTokenizer.from_pretrained(args.model_name_or_path)
        # self.model = LayoutXLMForTokenClassification.from_pretrained(args.model_name_or_path)

        # self.tokenizer = LayoutLMTokenizer.from_pretrained(args.model_name_or_path)
        # self.model = LayoutLMForTokenClassification.from_pretrained(args.model_name_or_path)

        self.tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)
        self.model = model_class.from_pretrained(args.model_name_or_path)
        self.model.eval()
        # print(self.model);exit()

        # init ocr_engine
        from tools.infer.predict_system import TextSystem as OCR

        self.ocr_engine = OCR(args)

        # init dict
        label2id_map, self.id2label_map = get_bio_label_maps(
            args.label_map_path)
        self.label2id_map_for_draw = dict()
        for key in label2id_map:
            if key.startswith("I-"):
                self.label2id_map_for_draw[key] = label2id_map["B" + key[1:]]
            else:
                self.label2id_map_for_draw[key] = label2id_map[key]

    @torch.no_grad()
    def __call__(self, img):
        dt_boxes, rec_res = self.ocr_engine(img)
        ocr_result = [[box.tolist(), res] for box, res in zip(dt_boxes, rec_res)]
        ocr_info = parse_ocr_info_for_ser(ocr_result)

        inputs = preprocess(
            tokenizer=self.tokenizer,
            ori_img=img,
            ocr_info=ocr_info,
            max_seq_len=self.max_seq_length)

        # layout model
        if self.args.ser_model_type == 'LayoutLM':
            # preds = self.model(
            #     input_ids=inputs["input_ids"],
            #     bbox=inputs["bbox"],
            #     token_type_ids=inputs["token_type_ids"],
            #     attention_mask=inputs["attention_mask"]
            # )
            raise NotImplementedError
        elif self.args.ser_model_type == 'LayoutXLM':
            preds = self.model(
                input_ids=inputs["input_ids"],
                bbox=inputs["bbox"],
                image=inputs["image"],
                token_type_ids=inputs["token_type_ids"],
                attention_mask=inputs["attention_mask"],
            )
            preds = preds[0]

        # tmp load .npy of ocr results
        preds = postprocess(inputs["attention_mask"], preds, self.id2label_map)
        ocr_info = merge_preds_list_with_ocr_info(
            ocr_info, inputs["segment_offset_id"], preds,
            self.label2id_map_for_draw)

        return ocr_info, inputs

if __name__ == "__main__":
    args = parse_args()
    os.makedirs(args.output_dir, exist_ok=True)
    # get infer img list
    infer_imgs = get_image_file_list(args.infer_imgs)

    # loop for infer
    ser_engine = SerPredictor(args)

    with open(
            os.path.join(args.output_dir, "infer_results.txt"),
            "w",
            encoding='utf-8') as fout:
        for idx, img_path in enumerate(infer_imgs):
            save_img_path = os.path.join(
                args.output_dir,
                os.path.splitext(os.path.basename(img_path))[0] + "_ser.jpg")
            print("process: [{}/{}], save result to {}".format(
                idx, len(infer_imgs), save_img_path))

            img = cv2.imread(img_path)

            result, _ = ser_engine(img)
            fout.write(img_path + "\t" + json.dumps(
                {
                    "ser_resule": result,
                }, ensure_ascii=False) + "\n")

            img_res = draw_ser_results(img, result)
            cv2.imwrite(save_img_path, img_res)

    print('all done.')


from waflib import Logs, Utils, Errors, Build
import os
import collections
import json

# The Visual Code schema version for launch tasks that we are basing on
LAUNCH_JSON_VERSION = '0.2.0'

# The Visual Code schema version for (build) tasks that we are basing on
TASK_JSON_VERSION = '2.0.0'

# Map of unversioned host platforms to platform specific values and format strings that we will use during construction
# of the visual code json configuration files
VSCODE_PLATFORM_SETTINGS_MAP = {

    'win32':  dict( exePattern          = "%s.exe",
                    scriptPattern       = "%s.bat",
                    dbgType             = "cppvsdbg",
                    problemMatcher      = '$msCompile',
                    wafPlatformPrefix   = "win_x64"),

    'darwin': dict( exePattern          = "./%s",
                    scriptPattern       = "./%s.sh",
                    dbgType             = "cppdbg",
                    problemMatcher      = "$gcc",
                    wafPlatformPrefix   = "darwin_"),

    'linux':  dict( exePattern          = "./%s",
                    scriptPattern       = "./%s.sh",
                    dbgType             = "cppdbg",
                    problemMatcher      = "$gcc",
                    wafPlatformPrefix   = "linux_")
}

class GenerateVSCodeWorkspace(Build.BuildContext):
    '''Generate a Visual Studio Code project'''
    cmd = 'vscode'
    fun = 'build'

    default_build_configuration = 'profile'

    default_launch_targets = ['Editor', 'AssetProcessor']

    def __init__(self):

        Build.BuildContext.__init__(self)

        # Get the host-platform specific values for this visual code generation and initialize them as
        # object variables to this build class

        host_name = Utils.unversioned_sys_platform()
        try:
            platform_settings = VSCODE_PLATFORM_SETTINGS_MAP[host_name]
        except KeyError:
            raise Errors.WafError("Unsupported platform '{}' for VSCode".format(host_name))
        try:
            self.exePattern         = platform_settings['exePattern']
            self.dbgType            = platform_settings['dbgType']
            self.wafPlatformPrefix  = platform_settings['wafPlatformPrefix']
            self.scriptPattern      = platform_settings['scriptPattern']
            self.problemMatcher     = platform_settings['problemMatcher']
        except KeyError as err:
            raise Errors.WafError("VSCode settings '{}' for platform '{}' is missing from the definition table ({})".format(err, host_name, __file__))

    @staticmethod
    def write_vscode_node(node, json_obj):
        node.write(json.dumps(json_obj, indent=4, separators=(',', ': ')))

    def execute(self):
        # restore the environments
        self.restore()
        if not self.all_envs:
            self.load_envs()

        self.load_user_settings()

        self.generate_vscode_project()

    def generate_build_tasks_json(self, vscode_dir):
        """
        Generate the build tasks (task.json) file for Visual Code
        :param vscode_dir:  The base folder node to save the task.json file
        """

        # Collect all the specs that are specified in 'specs_to_include_in_project_generation'
        enabled_specs = [spec_name.strip() for spec_name in self.options.specs_to_include_in_project_generation.split(',')]

        # Collect all the enabled platforms
        enabled_platforms = [platform.platform for platform in self.get_all_target_platforms()]

        task_list = []

        # Prepare the command line for this build task
        lmbr_waf_command = os.path.join('${workspaceFolder}', self.scriptPattern % 'lmbr_waf')

        default_build_set = False

        for platform in enabled_platforms:
            # The top level hierarchy will be the 'filtered' platforms

            if not platform.startswith(self.wafPlatformPrefix):
                # Skip if it doesnt match the platform prefix
                continue

            # Iterate through the specs
            for spec_name in enabled_specs:

                # The second level heirarchy will be based on the spec name
                configurations_for_platform = self.get_supported_configurations(platform)
                for configuration in configurations_for_platform:

                    # The third level heirarchy will be based on the configuration name

                    # Set a 'default' build tasks from the first one that matches the desired default build
                    # configuration
                    if not default_build_set and configuration == GenerateVSCodeWorkspace.default_build_configuration:
                        default_build_set = True
                        is_default_build = True
                    else:
                        is_default_build = False

                    task = collections.OrderedDict()

                    task['label']           = '[{}] {} : ({})'.format(spec_name, configuration, platform)
                    task['type']            = 'shell'
                    task['command']         = lmbr_waf_command
                    task['args']            = ['build_{}_{}'.format(platform, configuration),
                                               '-p',
                                                spec_name]
                    task['problemMatcher']  = {
                                                "base": self.problemMatcher,
                                                "fileLocation": "absolute"
                                              }
                    if is_default_build:
                        # Default build tasks specifically requires another dictionary
                        task['group']       = {
                                                'kind': 'build',
                                                'isDefault': True
                                              }
                    else:
                        task['group']       = 'build'

                    task_list.append(task)

        tasks_json = collections.OrderedDict()

        tasks_json['version'] = TASK_JSON_VERSION
        tasks_json['tasks'] = task_list

        tasks_json_node = vscode_dir.make_node('tasks.json')

        GenerateVSCodeWorkspace.write_vscode_node(tasks_json_node, tasks_json)

    def generate_launch_json(self, vscode_dir):
        """
        Generate the launch configurations based on specific exe's and the enabled game project's game launchers
        :param vscode_dir:  The base folder node to save the task.json file
        """

        # Collect the possible launch targets
        launcher_targets = [default_launch_target for default_launch_target in GenerateVSCodeWorkspace.default_launch_targets]
        enabled_game_projects = [game_name.strip() for game_name in self.options.enabled_game_projects.split(',')]
        launcher_targets.extend(enabled_game_projects)

        # Collect the enabled platforms for this host platform
        enabled_platforms = [platform.platform for platform in self.get_all_target_platforms()]

        launch_configurations = []

        # Follow the same logic as the build tasks to filter the platforms
        for platform in enabled_platforms:

            if not platform.startswith(self.wafPlatformPrefix):
                # Skip if it doesnt match the platform prefix
                continue

            # Iterate through the configurations for the current platform
            configurations_for_platform = self.get_supported_configurations(platform)
            for configuration in configurations_for_platform:

                is_dedicated = '_dedicated' in configuration

                bin_folder = self.get_output_folders(platform, configuration)[0]

                for launcher_target in launcher_targets:
                    # For dedicated platforms, the name of the launcher will be different, so we need to adjust the
                    # name for these configurations. For non-game launcher targets, they do not exist at all,
                    # so dont create them
                    if is_dedicated:
                        if launcher_target in enabled_game_projects:
                            exename = self.exePattern % ('{}Launcher_Server'.format(launcher_target))
                        else:
                            # This is not a game launcher, so for dedicated configurations skip
                            continue
                    else:
                        if launcher_target in enabled_game_projects:
                            exename = self.exePattern % ('{}Launcher'.format(launcher_target))
                        else:
                            exename = self.exePattern % (launcher_target)

                    working_path = os.path.join('${workspaceFolder}', bin_folder.name)
                    program = os.path.join(working_path, exename)

                    launch_config = collections.OrderedDict()

                    launch_config['name']               = '{} ({})'.format(launcher_target, configuration)
                    launch_config['type']               = self.dbgType
                    launch_config['request']            = 'launch'
                    launch_config['program']            = program
                    launch_config['args']               = []
                    launch_config['cwd']                = working_path
                    launch_config['environment']        = []
                    launch_config['externalConsole']    =   False

                    launch_configurations.append(launch_config)

        launch_json = collections.OrderedDict()

        launch_json['version']        = LAUNCH_JSON_VERSION
        launch_json['configurations'] = launch_configurations

        launch_json_node = vscode_dir.make_node('launch.json')
        GenerateVSCodeWorkspace.write_vscode_node(launch_json_node, launch_json)

    def generate_settings_json(self, vscode_dir):
        """
        Generate the additional (environment) visual code settings

        :param vscode_dir:  The base folder node to save the task.json file
        """
        settings_json = {
            "files.exclude": {
                "Bin*"              : True,
                "Cache"             : True,
                "AssetProcessorTemp": True,
                "Solutions"         : True
            },
            "files.associations": {
                "wscript"       : "python",
                "*.py"          : "python"
            },
        }

        settings_json_node = vscode_dir.make_node('settings.json')
        GenerateVSCodeWorkspace.write_vscode_node(settings_json_node, settings_json)

    def generate_vscode_project(self):
        """
        Generate all of the visual code settings
        """
        # ensure that the .vscode dir exists
        vscode_dir = self.srcnode.make_node('.vscode')
        vscode_dir.mkdir()

        self.generate_build_tasks_json(vscode_dir)
        self.generate_launch_json(vscode_dir)
        self.generate_settings_json(vscode_dir)


from django import forms
from betterforms.forms import Fieldset, BetterModelForm
from assistenten.models import FesteSchicht
from assistenten.widgets import XDSoftTimePickerInput

class FesteSchichtenForm(BetterModelForm):
    class Meta:
        fields = ['wochentag', 'beginn', 'ende']
        model = FesteSchicht
        liste = ['auauauaua', 2, 3]
        fieldsets = (
            Fieldset('feste_schicht', fields=('wochentag',
                                              'beginn',
                                              'ende'),
                     legend='Feste Schicht hinzufügen',
                     template_name="assistenten/fieldset_feste_schichten.html",
                     liste=liste),
        )

    CHOICES = [
        ('-1', 'keine neue feste Schicht'),
        ('1', 'Montag'),
        ('2', 'Dienstag'),
        ('3', 'Mittwoch'),
        ('4', 'Donnerstag'),
        ('5', 'Freitag'),
        ('6', 'Samstag'),
        ('7', 'Sonntag')]
    wochentag = forms.CharField(label='Wochentag', widget=forms.Select(choices=CHOICES))
    beginn = forms.TimeField(
        input_formats=['%H:%M'],
        widget=XDSoftTimePickerInput(attrs={'autocomplete': 'off'}),
        required=False
    )
    ende = forms.TimeField(
        input_formats=['%H:%M'],
        widget=XDSoftTimePickerInput(attrs={'autocomplete': 'off'}),
        required=False
    )


from math import exp as exp
from math import floor as floor
from numpy import zeros as zeros

from copy import copy as copy

class BinaryMatrix:

    def __init__(self, matrix, rows, cols):
        """
        This class contains the algorithm specified in the NIST suite for computing the **binary rank** of a matrix.
        :param matrix: the matrix we want to compute the rank for
        :param rows: the number of rows
        :param cols: the number of columns
        :return: a BinaryMatrix object
        """
        self.M = rows
        self.Q = cols
        self.A = matrix
        self.m = min(rows, cols)

    def compute_rank(self, verbose=False):
        """
        This method computes the binary rank of self.matrix
        :param verbose: if this is true it prints out the matrix after the forward elimination and backward elimination
        operations on the rows. This was used to testing the method to check it is working as expected.
        :return: the rank of the matrix.
        """
        if verbose:
            print("Original Matrix\n", self.A)

        i = 0
        while i < self.m - 1:
            if self.A[i][i] == 1:
                self.perform_row_operations(i, True)
            else:
                found = self.find_unit_element_swap(i, True)
                if found == 1:
                    self.perform_row_operations(i, True)
            i += 1

        if verbose:
            print("Intermediate Matrix\n", self.A)

        i = self.m - 1
        while i > 0:
            if self.A[i][i] == 1:
                self.perform_row_operations(i, False)
            else:
                if self.find_unit_element_swap(i, False) == 1:
                    self.perform_row_operations(i, False)
            i -= 1

        if verbose:
            print("Final Matrix\n", self.A)

        return self.determine_rank()

    def perform_row_operations(self, i, forward_elimination):
        """
        This method performs the elementary row operations. This involves xor'ing up to two rows together depending on
        whether or not certain elements in the matrix contain 1's if the "current" element does not.
        :param i: the current index we are are looking at
        :param forward_elimination: True or False.
        """
        if forward_elimination:
            j = i + 1
            while j < self.M:
                if self.A[j][i] == 1:
                    self.A[j, :] = (self.A[j, :] + self.A[i, :]) % 2
                j += 1
        else:
            j = i - 1
            while j >= 0:
                if self.A[j][i] == 1:
                    self.A[j, :] = (self.A[j, :] + self.A[i, :]) % 2
                j -= 1

    def find_unit_element_swap(self, i, forward_elimination):
        """
        This given an index which does not contain a 1 this searches through the rows below the index to see which rows
        contain 1's, if they do then they swapped. This is done on the forward and backward elimination
        :param i: the current index we are looking at
        :param forward_elimination: True or False.
        """
        row_op = 0
        if forward_elimination:
            index = i + 1
            while index < self.M and self.A[index][i] == 0:
                index += 1
            if index < self.M:
                row_op = self.swap_rows(i, index)
        else:
            index = i - 1
            while index >= 0 and self.A[index][i] == 0:
                index -= 1
            if index >= 0:
                row_op = self.swap_rows(i, index)
        return row_op

    def swap_rows(self, i, ix):
        """
        This method just swaps two rows in a matrix. Had to use the copy package to ensure no memory leakage
        :param i: the first row we want to swap and
        :param ix: the row we want to swap it with
        :return: 1
        """
        temp = copy(self.A[i, :])
        self.A[i, :] = self.A[ix, :]
        self.A[ix, :] = temp
        return 1

    def determine_rank(self):
        """
        This method determines the rank of the transformed matrix
        :return: the rank of the transformed matrix
        """
        rank = self.m
        i = 0
        while i < self.M:
            all_zeros = 1
            for j in range(self.Q):
                if self.A[i][j] == 1:
                    all_zeros = 0
            if all_zeros == 1:
                rank -= 1
            i += 1
        return rank

class Matrix:

    @staticmethod
    def binary_matrix_rank_text(binary_data:str, verbose=False, rows_in_matrix = 32, columns_in_matrix = 32):
        """
        Note that this description is taken from the NIST documentation [1]
        [1] http://csrc.nist.gov/publications/nistpubs/800-22-rev1a/SP800-22rev1a.pdf
        The focus of the test is the rank of disjoint sub-matrices of the entire sequence. The purpose of this test is
        to check for linear dependence among fixed length sub strings of the original sequence. Note that this test
        also appears in the DIEHARD battery of tests.

        :param      binary_data         The seuqnce of bit being tested
        :param      verbose             True to display the debug messgae, False to turn off debug message
        :param      rows_in_matrix      Fixed for 32
        :param      columns_in_matrix   Fixed for 32
        :return     (p_value, bool)     A tuple which contain the p_value and result of frequency_test(True or False)
        """

        shape = (rows_in_matrix, columns_in_matrix)
        length_of_binary_data = len(binary_data)
        block_size = int(rows_in_matrix * columns_in_matrix)
        number_of_block = floor(length_of_binary_data / block_size)
        block_start = 0
        block_end = block_size

        if number_of_block > 0:
            max_ranks = [0, 0, 0]

            for im in range(number_of_block):
                block_data = binary_data[block_start:block_end]
                block = zeros(len(block_data))

                for count in range(len(block_data)):
                    if block_data[count] == '1':
                        block[count] = 1.0

                matrix = block.reshape(shape)
                ranker = BinaryMatrix(matrix, rows_in_matrix, columns_in_matrix)
                rank = ranker.compute_rank()

                if rank == rows_in_matrix:
                    max_ranks[0] += 1
                elif rank == (rows_in_matrix - 1):
                    max_ranks[1] += 1
                else:
                    max_ranks[2] += 1

                block_start += block_size
                block_end += block_size

            pi = [1.0, 0.0, 0.0]
            for x in range(1, 50):
                pi[0] *= 1 - (1.0 / (2 ** x))
            pi[1] = 2 * pi[0]
            pi[2] = 1 - pi[0] - pi[1]

            xObs = 0.0
            for i in range(len(pi)):
                xObs += pow((max_ranks[i] - pi[i] * number_of_block), 2.0) / (pi[i] * number_of_block)

            p_value = exp(-xObs / 2)

            if verbose:
                print('Binary Matrix Rank Test DEBUG BEGIN:')
                print("\tLength of input:\t", length_of_binary_data)
                print("\tSize of Row:\t\t", rows_in_matrix)
                print("\tSize of Column:\t\t", columns_in_matrix)
                print('\tValue of N:\t\t\t', number_of_block)
                print('\tValue of Pi:\t\t', pi)
                print('\tValue of xObs:\t\t', xObs)
                print('\tP-Value:\t\t\t', p_value)
                print('DEBUG END.')

            return (p_value, (p_value >= 0.01))
        else:
            return (-1.0, False)


#ukol-07: Evidence aut
class Auto:
    def __init__(self, registracni_znacka, typ_vozidla, najete_km, tachometr_stav):
        self.registracni_znacka = registracni_znacka
        self.typ_vozidla = typ_vozidla
        self.najete_km = najete_km
        self.dostupne = True
        self.tachometr_stav = tachometr_stav
        self.pocet_dni_zapujceni = 0

    def pujc_auto(self):
         if self.dostupne == True:
            self.dostupne = False
            print('Potvrzuji zapůjčení vozidla')
            #return self.dostupne
         else:
            print('Vozidlo není k dispozici')

    def get_info(self):
        return print( f"{self.registracni_znacka} {self.typ_vozidla}")

    def vrat_auto(self, pocet_dni_zapujceni):
        cena_den_1 = 400
        cena_den_2 = 300
        if pocet_dni_zapujceni < 7:
            cena = cena_den_1 * pocet_dni_zapujceni
        else:
            cena = cena_den_2 * pocet_dni_zapujceni
        text = print(f'Vysledna cena je: {cena}')
        return text

autopujcovna={}
autopujcovna['Peugeot'] = Auto('4A2 3020', 'Peugeot 403 Cabrio', 47534, 120000)
autopujcovna['Škoda'] = Auto('1P3 4747', 'Škoda Octavia', 41253, 200000)

auto_input = input('Které auto budete chtít? Máme na výběř Škoda nebo Peugeot: ')

if auto_input in autopujcovna:
    print(autopujcovna[auto_input].get_info())
    autopujcovna[auto_input].pujc_auto()
    pocet_dni_input = int(input('Na jak dlouho si auto půjčíte?: '))
    autopujcovna[auto_input].vrat_auto(pocet_dni_input)

    auto_input = input('Které auto budete chtít? Máme na výběř Škoda nebo Peugeot: ')
    if auto_input in autopujcovna:
        print(autopujcovna[auto_input].get_info())
        autopujcovna[auto_input].pujc_auto()
        pocet_dni_input = int(input('Na jak dlouho si auto půjčíte?: '))
        autopujcovna[auto_input].vrat_auto(pocet_dni_input)
    else:
        print('Bohužel tuto značku nemáme.')
else:
    print('Bohužel tuto značku nemáme.')


#!/usr/bin/env python3
"""
A module sporting a simple 2D simulation of the kinematics of NaviGator.
"""
from typing import Tuple

import numpy as np
import rospy
import tf.transformations as trns
from mil_tools import numpy_to_quaternion
from nav_msgs.msg import Odometry
from navigator_thrust_mapper import ThrusterMap
from roboteq_msgs.msg import Command

class Navsim:
    """
    A simple 2D simulation of the kinematics of NaviGator.
    """

    def __init__(
        self,
        pose_zero: np.ndarray = np.array([0, 0, 0]),
        twist_zero: np.ndarray = np.array([0, 0, 0]),
    ):

        # Used to publish current state
        self.odom_publisher = rospy.Publisher("/odom", Odometry, queue_size=1)

        # Set initial state from constructor
        self.pose = np.float64(pose_zero)
        self.twist = np.float64(twist_zero)
        self.wrench = np.float64([0, 0, 0])
        self.thrusts = np.zeros(4, dtype=np.float64)

        # Get other contants from ROS params
        self.get_params()

        # Get URDF description from thrusters
        urdf = rospy.get_param("robot_description", default=None)
        if urdf is None or len(urdf) == 0:
            raise Exception("robot description not set or empty")
        self.thrust_map = ThrusterMap.from_urdf(urdf)

        # Subscribe to thrusters so we can simulate their forces
        for i, motor in enumerate(self.thrust_map.names):
            rospy.Subscriber(
                f"/{motor}_motor/cmd",
                Command,
                self.thruster_cb,
                queue_size=3,
                callback_args=i,
            )

        # Start timer to run simulator
        rospy.Timer(rospy.Duration(self.update_period), self.timer_cb)

    def get_params(self) -> None:
        """
        Load important configurable constants from ROS params
        """
        mass = rospy.get_param("~mass")
        drag = rospy.get_param("~drag")
        rotational_inertia = rospy.get_param("~rotational_inertia")
        wind = rospy.get_param("~wind", [0, 0, 0])

        self.inertia = np.float64([mass, mass, rotational_inertia])
        self.drag = np.float64(drag)
        self.wind = np.float64(wind)

        self.update_period = rospy.get_param("~update_period", 0.1)
        self.world_frame = rospy.get_param("~world_frame", "enu")
        self.body_frame = rospy.get_param("~body_frame", "base_link")

    def thruster_cb(self, msg: Command, index: int) -> None:
        self.thrusts[index] = msg.setpoint
        self.wrench = self.thrust_map.thrusts_to_wrench(self.thrusts)

    def timer_cb(self, _: rospy.timer.TimerEvent) -> None:
        """
        Each time timer triggers, update state and publish odometry.
        """
        self.step(self.update_period, self.wrench)
        self.publish_odom()

    def step(self, time_delta: float, wrench) -> None:
        """
        Simulate new pose and twist given a time delta and a force/torque applied to NaviGator
        """
        sin_result = np.sin(self.pose[2])
        cos_result = np.cos(self.pose[2])

        # Rotation Matrix converts body to world by default
        rotation = np.array(
            [[cos_result, -sin_result, 0], [sin_result, cos_result, 0], [0, 0, 1]]
        )
        wrench = np.array(wrench)
        posedot, twistdot = self.state_deriv(np.float64(wrench), rotation)

        self.pose = (
            self.pose
            + posedot * time_delta
            + 0.5 * rotation.dot(twistdot) * time_delta**2
        )
        self.twist = self.twist + twistdot * time_delta

    def state_deriv(
        self, wrench: np.float64, rotation: np.ndarray
    ) -> Tuple[np.ndarray, float]:
        posedot = rotation.dot(self.twist)
        twistdot = (1 / self.inertia) * (
            wrench
            - self.drag * np.sign(self.twist) * self.twist * self.twist
            + rotation.T.dot(self.wind)
        )
        return posedot, twistdot

    def publish_odom(self) -> None:
        """
        Publish to odometry with latest pose and twist
        """
        odom = self.pack_odom(self.pose, self.twist)
        self.odom_publisher.publish(odom)

    def pack_odom(self, pose: np.ndarray, twist: np.ndarray) -> Odometry:
        """
        Converts pose and twist into an Odometry message
        """
        msg = Odometry()
        msg.header.stamp = rospy.Time.now()
        msg.header.frame_id = self.world_frame
        msg.child_frame_id = self.body_frame
        msg.pose.pose.position.x, msg.pose.pose.position.y = pose[0], pose[1]

        quat = trns.quaternion_from_euler(0, 0, pose[2])
        msg.pose.pose.orientation = numpy_to_quaternion(quat)
        msg.twist.twist.linear.x, msg.twist.twist.linear.y = twist[0:2]
        msg.twist.twist.angular.z = twist[2]
        return msg

if __name__ == "__main__":
    rospy.init_node("navigator_sim2D")
    navsim = Navsim(pose_zero=np.array([0, 0, np.pi / 2]))
    rospy.spin()


import unittest
from unittest.mock import MagicMock, patch

import pytest
from documents.util.scripts.src.auto_scaling_util import (
    _describe_scalable_targets, _execute_boto3_auto_scaling,
    _register_scalable_target, copy_scaling_targets,
    _execute_boto3_auto_scaling_paginator)
from parameterized import parameterized

GENERIC_SUCCESS_RESULT = {
    "ResponseMetadata": {
        "HTTPStatusCode": 200
    }
}
DESCRIBE_SCALABLE_TARGETS_RESPONSE = {
    **GENERIC_SUCCESS_RESULT,
    "NextToken": "string",
    "ScalableTargets": [
        {
            "CreationTime": 12,
            "MaxCapacity": 5,
            "MinCapacity": 1,
            "ResourceId": "table/my_table",
            "RoleARN": "my_role_arn",
            "ScalableDimension": "dimension",
            "ServiceNamespace": "dynamodb",
            "SuspendedState": {
                "DynamicScalingInSuspended": True,
                "DynamicScalingOutSuspended": True,
                "ScheduledScalingSuspended": True
            }
        }
    ]
}

@pytest.mark.unit_test
class TestAutoScalingUtil(unittest.TestCase):
    def setUp(self):
        self.patcher = patch('boto3.client')
        self.client = self.patcher.start()
        self.application_autoscaling_client_mock = MagicMock()
        self.side_effect_map = {
            'application-autoscaling': self.application_autoscaling_client_mock
        }
        self.client.side_effect = lambda service_name, config: self.side_effect_map.get(service_name)

        self.application_autoscaling_client_mock.describe_scalable_targets.return_value = \
            DESCRIBE_SCALABLE_TARGETS_RESPONSE
        self.application_autoscaling_client_mock.register_scalable_target.return_value = \
            DESCRIBE_SCALABLE_TARGETS_RESPONSE

    def tearDown(self):
        self.patcher.stop()

    def test__execute_boto3_auto_scaling_paginator(self):
        paginator_mock = MagicMock()
        self.application_autoscaling_client_mock.get_paginator.return_value = paginator_mock

        paginate_mock = MagicMock()
        paginator_mock.paginate.return_value = paginate_mock
        paginate_mock.search.return_value = iter(['some value'])

        _execute_boto3_auto_scaling_paginator(func_name='my_func', search_exp='Collection[]', value1='abc')
        self.application_autoscaling_client_mock.get_paginator.assert_called_with('my_func')
        paginator_mock.paginate.assert_called_with(value1='abc')
        paginate_mock.search.assert_called_with('Collection[]')

    def test__execute_boto3_auto_scaling_paginator__page_iterator(self):
        paginator_mock = MagicMock()
        self.application_autoscaling_client_mock.get_paginator.return_value = paginator_mock

        paginate_mock = MagicMock()
        paginator_mock.paginate.return_value = paginate_mock
        paginate_mock.search.return_value = iter(['some value'])

        _execute_boto3_auto_scaling_paginator(func_name='my_func', value1='abc')
        self.application_autoscaling_client_mock.get_paginator.assert_called_with('my_func')
        paginator_mock.paginate.assert_called_with(value1='abc')
        paginate_mock.search.assert_not_called()

    def test__execute_boto3_dynamodb_raises_exception(self):
        with self.assertRaises(ValueError):
            _execute_boto3_auto_scaling(lambda x: {'ResponseMetadata': {'HTTPStatusCode': 500}})

    @parameterized.expand([({}, {}), ({'SourceTableName': 'my_table'}, {})])
    def test_copy_scaling_targets_raises_exception(self, events, context):
        with self.assertRaises(KeyError):
            copy_scaling_targets(events=events, context=context)

    @patch('documents.util.scripts.src.auto_scaling_util._execute_boto3_auto_scaling_paginator',
           return_value=iter(DESCRIBE_SCALABLE_TARGETS_RESPONSE['ScalableTargets']))
    def test__describe_scalable_targets(self, paginator_mock):

        result = _describe_scalable_targets(table_name='my_table')

        paginator_mock(func_name='describe_scalable_targets',
                       search_exp='ScalableTargets[]',
                       ServiceNamespace='dynamodb',
                       ResourceIds=['table/my_table'])
        self.assertEquals(list(result), DESCRIBE_SCALABLE_TARGETS_RESPONSE['ScalableTargets'])

    def test__register_scalable_target(self):

        result = _register_scalable_target(table_name='my_table',
                                           dimension='my_dimension',
                                           max_cap=5,
                                           min_cap=1,
                                           role_arn="arn")

        self.application_autoscaling_client_mock\
            .register_scalable_target\
            .assert_called_with(ServiceNamespace='dynamodb',
                                ScalableDimension='my_dimension',
                                MaxCapacity=5,
                                MinCapacity=1,
                                ResourceId='table/my_table',
                                RoleARN='arn')
        self.assertEquals(result, DESCRIBE_SCALABLE_TARGETS_RESPONSE)

    @patch('documents.util.scripts.src.auto_scaling_util._describe_scalable_targets',
           return_value=iter(DESCRIBE_SCALABLE_TARGETS_RESPONSE['ScalableTargets']))
    @patch('documents.util.scripts.src.auto_scaling_util._register_scalable_target',
           return_value={})
    def test_copy_scaling_targets(self, register_mock, describe_mock):
        events = {
            "SourceTableName": "my_table",
            "TargetTableName": "my_table_target"
        }
        result = copy_scaling_targets(events=events, context={})

        self.assertEqual(result, [{"ScalableDimension": "dimension", "MinCapacity": 1,
                         "MaxCapacity": 5, 'RoleARN': 'my_role_arn'}])
        describe_mock.assert_called_with(table_name='my_table')
        register_mock.assert_called_with(table_name='my_table_target',
                                         dimension='dimension',
                                         max_cap=5,
                                         min_cap=1,
                                         role_arn='my_role_arn')


import sys
#sys.stdin = open("input.txt", "rt")
input = sys.stdin.readline  # 입력량이 많을 때 입력 속도가 빨라짐
#s = input().rstrip(): # readline 쓰면서 문자열을 읽을 때 문자열 끝에 줄바꿈 기호까지 읽기 때문에 탈피해야함

################ 동적 계획법 #################

#### 냅색(knapsack) 알고리즘

if __name__ == "__main__":
    n = int(input())
    coin = list(map(int, input().split()))
    m = int(input())

    dy = [1000] * (m+1) # min계산을 위해 큰 숫자로 설정
    dy[0] = 0

    for i in range(n):
        for j in range(coin[i], m+1):
            dy[j] = min(dy[j], dy[j - coin[i]] + 1)
    print(dy[m])

'''
# 100점 이긴 한데 뭐지 이 찝찝한 기분은...
if __name__ == "__main__":
    n = int(input())
    money = list(map(int, input().split()))
    m = int(input())

    dy = [0] * (m+1)

    for i in range(n):
        w = money[i]
        for j in range(w, m+1): # 앞문제와 다르게 max 가 아니라 min을 사용해야 돼서 조건이 달림
            if dy[j-w] == 0: # 앞에 있는게 0이 되면 무조건 0이 min이 되는 것 방지
                dy[j] = 1
            elif dy[j] == 0: # 원래 있는게 0이면 무조건 0이 min이 되는 것 방지
                dy[j] = dy[j-w] + 1
            else: # 전에 세어놓은 개수와 새로 세는 개수 중 적은 것
                dy[j] = min(dy[j], dy[j-w]+1)
    print(dy[m])
'''


import os
import pandas as pd
from random import randrange
from datetime import timedelta
import pathlib

DATAPATH = pathlib.Path(__file__).parents[1].joinpath('Data')

def load_user_posts(username):
    """ Loads submission and comment DataFrames for a given user in our database """
    dirs = ['SuspiciousAccounts', 'NormalAccounts', 'NormalAccounts2']
    for d in dirs:
        filepath = DATAPATH.joinpath(d, username)
        if os.path.exists(filepath):
            break
    else:
        raise ValueError(f'No data for {username} in our database')
    try:
        subs = pd.read_csv(filepath.joinpath('submissions.csv'))
    except FileNotFoundError:
        subs = None
    try:
        comms = pd.read_csv(filepath.joinpath('comments.csv'))
    except FileNotFoundError:
        comms = None
    return subs, comms

def random_date(start, end):
    """
    This function will return a random datetime between two datetime
    objects.
    From https://stackoverflow.com/questions/553303/generate-a-random-date-between-two-other-dates
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)


class Solution:
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        result = []
        if  len(nums) * len(nums[0]) == r * c:
            nums = [m for n in nums for m in n]
            for i in range(0,r):
                result.append([])
                for j in range(0,c):
                    result[i].append(nums.pop(0))
        else:
            result = nums

        return result

if __name__ == "__main__":
    s = Solution()
    print(s.matrixReshape([[1,2],[3,4]],1,4))
    print(s.matrixReshape([[1,2],[3,4]],4,1))

Python/Codes/Practice/LeetCodeCN/566 Reshape the matrix.py


import json
import re
from sklearn.model_selection import train_test_split

def write_file(file_name, source, target):
    with open(file_name, 'w+') as train_f:
        for i in range(len(source)):
            train_f.write('{},{}\n'.format(source[i], target[i]))

if __name__ == '__main__':
    with open('github-typo-corpus.v1.0.0.jsonl') as f:
        data_list = list(f)

    clean_data = []

    for json_str in data_list:
        typo_dict = json.loads(json_str)
        for edit in typo_dict['edits']:
            if edit['src']['lang'] == 'eng' and edit['is_typo'] == True:
                source = edit['src']['text']
                target = edit['tgt']['text']
                source = re.sub('<.+?>', '', source)
                target = re.sub('<.+?>', '', target)
                source = re.sub("[^a-zA-Z'. ]+", ' ', source)
                target = re.sub("[^a-zA-Z'. ]+", ' ', target)
                source = re.sub('\s+', ' ', source).lower().strip()
                target = re.sub('\s+', ' ', target).lower().strip()
                if len(source) > 30:
                    clean_data.append((source, target))

    source_train, source_val, target_train, target_val = train_test_split([x[0] for x in clean_data], [x[1] for x in clean_data], test_size=0.08, random_state=0)
    source_val, source_test, target_val, target_test = train_test_split(source_val, target_val, test_size=0.2, random_state=0)

    write_file('github_train.txt', source_train, target_train)
    write_file('github_val.txt', source_val, target_val)
    write_file('github_test.txt', source_test, target_test)