#!/usr/bin/env python3
# coding: utf-8

"""
Script to run the DeepSphere experiment with SHREC17 dataset.
"""

import os
import shutil
import sys
sys.append('../..')

os.environ["CUDA_VISIBLE_DEVICES"] = "0"  # change to chosen GPU to use, nothing if work on CPU

import numpy as np

from deepsphere import models
from . import hyperparameters

from load_shrec import Shrec17DatasetCache, Shrec17DatasetTF, fix_dataset

bandwidth = 64
experiment = 'equiangular'
experiment_type = 'CNN'
ename = '_'+experiment_type
datapath = '../../data/shrec17/' # localisation of the .obj files

augmentation = 3        # number of element per file (1 = no augmentation of dataset)
nfeat = 6

EXP_NAME = 'shrec17_equiangular_{}aug_{}bw{}'.format(augmentation, bandwidth, ename)

train_dataset = Shrec17DatasetTF(datapath, 'train', nside=bandwidth, augmentation=augmentation, nfile=None,
                                 nfeat=nfeat, experiment=experiment, verbose=False)
val_dataset = Shrec17DatasetCache(datapath, 'val', nside=bandwidth, augmentation=1, nfile=None, nfeat=nfeat,
                                  experiment=experiment, verbose=False)

nclass = train_dataset.nclass
num_elem = train_dataset.N
print('number of class:',nclass,'\nnumber of elements:',num_elem)

params = hyperparameters.get_params_shrec17_equiangular(num_elem, EXP_NAME, nclass, architecture=experiment_type)
params["tf_dataset"] = train_dataset.get_tf_dataset(params["batch_size"])
model = models.deepsphere(**params)

shutil.rmtree('summaries/{}/'.format(EXP_NAME), ignore_errors=True)
shutil.rmtree('checkpoints/{}/'.format(EXP_NAME), ignore_errors=True)

accuracy_validation, loss_validation, loss_training, t_step, t_batch = model.fit(train_dataset, val_dataset,
                                                                        verbose=False, cache=True,use_tf_dataset=True)

print(model.evaluate(val_dataset, None, cache=True))
probabilities,_ = model.probs(val_dataset, nclass, cache=True)
predictions = np.argmax(probabilities, axis=1)
ids_val = val_dataset.get_ids()
os.makedirs(os.path.join(datapath,'results_equiangular/val_perturbed'), exist_ok=True)
for i,_id in enumerate(ids_val):
    idfile = os.path.join(datapath,'results_equiangular/val_perturbed',_id)
    # predictions batchxclass
    # pred_class batch == predictions
    retrieved = [(probabilities[j, predictions[j]], ids_val[j]) for j in range(len(ids_val)) if predictions[j] == predictions[i]]
    retrieved = sorted(retrieved, reverse=True)
    retrieved = [i for _, i in retrieved]
    with open(idfile, "w") as f:
        f.write("\n".join(retrieved))

test_dataset = Shrec17DatasetCache(datapath, 'test', nside=bandwidth,
                                   augmentation=augmentation, nfile=None, experiment=experiment)
print(model.evaluate(test_dataset, None, cache=True))
ids_test = test_dataset.get_ids()
probabilities,_ = model.probs(test_dataset, nclass, cache=True)
if augmentation>1:
    probabilities = probabilities.reshape((-1,augmentation,nclass))
    probabilities = probabilities.mean(axis=1)
    ids_test = ids_test[::augmentation]
predictions = np.argmax(probabilities, axis=1)
os.makedirs(os.path.join(datapath,'results_equiangular/test_perturbed'), exist_ok=True)
for i, _id in enumerate(ids_test):
    idfile = os.path.join(datapath,'results_equiangular/test_perturbed',_id)
    # predictions batchxclass
    # pred_class batch == predictions
    retrieved = [(probabilities[j, predictions[j]], ids_test[j]) for j in range(len(ids_test)) if predictions[j] == predictions[i]]
    retrieved = sorted(retrieved, reverse=True)
    retrieved = [i for _, i in retrieved]
    with open(idfile, "w") as f:
        f.write("\n".join(retrieved))


n = int(input())
data = []
answer = []
for i in range(n):
    data.append(int(input()))

for i in data:
    if not answer:
        answer.append(i)
    else:
        for j in range(len(answer)):
            if i < answer[j]:
                answer.insert(j, i)
                break
            elif j == len(answer) - 1:
                answer.append(i)

print(*answer, sep='\n')


from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers import pipeline
import torch
import gc
import time

from urllib import response
import requests
import json

start = time.time()

# device = "cuda" if torch.cuda.is_available() else "cpu"

USE_CUDA = torch.cuda.is_available()
device = torch.device('cuda:0' if USE_CUDA else 'cpu')
# gc.collect()
# torch.cuda.empty_cache()

# print('CUDA 사용 가능 여부 :', USE_CUDA)
# print('현재 사용 device :', device)
# print('CUDA Index :', torch.cuda.current_device())
# print('GPU 이름 :', torch.cuda.get_device_name())
# print('GPU 개수 :', torch.cuda.device_count())

# tokenizer = AutoTokenizer.from_pretrained("EleutherAI/polyglot-ko-5.8b")
# model = AutoModelForCausalLM.from_pretrained("EleutherAI/polyglot-ko-5.8b")
# tokenizer = AutoTokenizer.from_pretrained("EleutherAI/polyglot-ko-3.8b")
# model = AutoModelForCausalLM.from_pretrained("EleutherAI/polyglot-ko-3.8b")

# tokenizer = AutoTokenizer.from_pretrained("EleutherAI/polyglot-ko-1.3b",
#     bos_token='[BOS]', eos_token='[EOS]', unk_token='[UNK]', pad_token='[PAD]', mask_token='[MASK]')
# model = AutoModelForCausalLM.from_pretrained(
#     "EleutherAI/polyglot-ko-1.3b", torch_dtype='auto', low_cpu_mem_usage=True)

tokenizer = AutoTokenizer.from_pretrained("EleutherAI/polyglot-ko-3.8b",
                                          bos_token='[BOS]', eos_token='[EOS]', unk_token='[UNK]', pad_token='[PAD]',
                                          mask_token='[MASK]'
                                          )
model = AutoModelForCausalLM.from_pretrained(
    "EleutherAI/polyglot-ko-3.8b", torch_dtype='auto', low_cpu_mem_usage=True)

# tokenizer = AutoTokenizer.from_pretrained("EleutherAI/polyglot-ko-5.8b",
#                                           bos_token='[BOS]', eos_token='[EOS]', unk_token='[UNK]', pad_token='[PAD]',
#                                           mask_token='[MASK]'
#                                           )
# model = AutoModelForCausalLM.from_pretrained(
#     "EleutherAI/polyglot-ko-5.8b", torch_dtype='auto', low_cpu_mem_usage=True)

# prompt = "GPTNeoX20B is a 20B-parameter autoregressive Transformer model developed by EleutherAI."

# input_ids = tokenizer(prompt, return_tensors="pt").input_ids
# input_ids = tokenizer(prompt, return_tensors="pt").to(device).input_ids
# .input_ids는 리턴되는 객체(=튜플)의 요소중 하나.
# inputs_ids = tokenizer(prompt, return_tensors="pt").to(device)
# model = model.to(device)
# outputs = model(inputs_ids)
# prediction_logits = outputs.logits

# gen_tokens = model.generate(
#     input_ids,
#     do_sample=True,
#     temperature=0.9,
#     max_length=150,
# )
# gen_text = tokenizer.batch_decode(gen_tokens)[0]

# 바로 위의 코드들을 pipeline()메소드로 축약시킨 코드가 가능
pipe = pipeline(
    'text-generation',
    model=model,
    tokenizer=tokenizer,
    device=0,
    framework='pt'
)
prompt1 = """\
The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.

Human: 오늘 날씨 어때?
AI: 좋습니다. 당신의 하루는 오늘 어땠나요?
Human: 난 오늘 꽤 괜찮았지~
AI: 그렇군요! 모르는 것 있으면 물어보세요. 친절히 알려드리겠습니다."""

# text = pipe(prompt, do_sample=True,  pad_token_id=50256,
#             num_return_sequences=3, top_k=50, top_p=0.95, max_new_tokens=50
#             )
# num_beams=4, no_repeat_ngram_size=2, temperature=0.75, early_stopping=True,
# max_length=50,
# print(text)
# time.sleep(0.9)
# end = time.time()
# print("Time consumed in working: ", end - start)

# text = pipe("아인슈타인은", do_sample=True, max_length=50, pad_token_id=50255,
#             num_return_sequences=2, top_k=50, top_p=0.95
#             )
# print(text)
# time.sleep(0.9)
# end = time.time()
# print("Time consumed in working: ", end - start)

# 텍스트 생성 기능위주인듯한데... 대화 기능을 찾아보자..

# print(f"gen_text: {pipe}")
# print(f"gen_text: {inputs_ids['input_ids']}")
# print(f"gen_text: {inputs_ids}")
# print(f"gen_text: {prediction_logits}")
# print(f"gen_text: {outputs}")

# Only recent response text will return
def processing_response(response_text: str ) -> str:
    ret_text = ""
    for i in range(0, len(response_text)):
        if response_text[i] == "\n" or response_text[i:i + 7] == "Human: " or response_text[i:i + 4] == "AI: ":
            break
        ret_text += response_text[i]
    return ret_text.strip()

url = "https://eleuther-ai-gpt-j-6b-float16-text-generation-api-ainize-team.endpoint.ainize.ai/predictions/text-generation"
# base_prompt = get_base_prompt()
base_prompt = prompt1
headers = {"Content-Type": "application/json"}
# End chat when user types "exit"
while True:
    chat = input("Human: ")
    if chat == "exit":
        break
    prompt = f"{base_prompt}\nHuman: {chat}\nAI:"

    # data == string type dumps()는 json객체를 json문자열로 변환시켜줌.
    data = json.dumps({
        "text_inputs":prompt,
        "temperature":0.9,
        "top_p":0.95,
        "repetition_penalty":0.8,
        "do_sample":True,
        "top_k":50,
        "length":50,
    })
    # loads()는 json문자열을 json객체로 변환시켜줌.
    jo = json.loads(data)
    # text = pipe(
    #     jo['text_inputs'],
    #     do_sample=jo['do_sample'],
    #     temperature=jo['temperature'],
    #     top_p=jo['top_p'],
    #     top_k=jo['top_k'],
    #     max_new_tokens=jo['length'],
    #     repetition_penalty=jo['repetition_penalty'],
    #     pad_token_id=50256
    # )
    text = pipe(
        prompt,
        do_sample=True,
        temperature=0.9,
        top_p=0.95,
        top_k=50,
        max_new_tokens=40,
        repetition_penalty=0.8,
        pad_token_id=50256
    )

    # res = requests.post(url, headers=headers, data=data)
    # if res.status_code == 200:
    # response_text = res.json()[0] # response에서 json응답일경우 바로 딕셔너리로 변환하고 0이라는 키의 값을 뽑아냄
    print(text[0])
    response_text = text[0]['generated_text']
    print("AI:", processing_response(response_text[len(prompt):]))


import sys
sys.setrecursionlimit(int(1e9))
read = sys.stdin.readline

def dfs(x,y) :
    if x == N-1 and y == M-1 : return 1
    if dp[x][y] != -1 : return dp[x][y]

    dp[x][y] = 0
    for dx,dy in [[-1,0],[1,0],[0,-1],[0,1]] :
        nx = x + dx
        ny = y + dy

        if 0 <= nx < N and 0 <= ny < M and board[x][y] > board[nx][ny] :
            dp[x][y] += dfs(nx,ny)

    return dp[x][y]

N,M = map(int,read().split())
board = [list(map(int,read().split())) for _ in range(N)]
dp = [[-1]*(M+1) for _ in range(N+1)]
print(dfs(0,0))

for row in dp :
    print(*row)


import datetime as dt
from dataclasses import dataclass
from typing import List, Tuple, Callable, Optional

from sova.asset import AbstractAsset, Deposit, Stock

@dataclass
class Trade:
    trade_time: dt.datetime
    stock_price: float
    asset: AbstractAsset

class Portfolio:
    def __init__(self, trades: List[Trade], delta_threshold: float = .005):
        self.trades = trades
        self.delta_threshold = delta_threshold

    def trade(self, trade_time: dt.datetime, stock_price: float, asset: AbstractAsset):
        self.trades.append(Trade(trade_time, stock_price, asset))

    def _apply_function(self, market_time: dt.datetime, f: Callable[[Trade], float]) -> float:
        return sum(map(f, filter(lambda t: t.trade_time <= market_time, self.trades)))

    def current_price(self,
                      stock_price: float,
                      market_time: dt.datetime,
                      risk_free_rate: float = .01) -> float:
        return self._apply_function(market_time, lambda t: t.asset.current_price(stock_price=stock_price,
                                                                                market_time=market_time,
                                                                                risk_free_rate=risk_free_rate))

    def current_delta(self,
                      stock_price: float,
                      market_time: dt.datetime,
                      risk_free_rate: float = .01) -> float:
        return self._apply_function(market_time, lambda t: t.asset.current_delta(stock_price=stock_price,
                                                                                market_time=market_time,
                                                                                risk_free_rate=risk_free_rate))

    def hedge_delta(self,
                    stock_price: float,
                    market_time: dt.datetime,
                    risk_free_rate: float = .01) -> Optional[Tuple[AbstractAsset, AbstractAsset]]:
        delta = self.current_delta(stock_price, market_time, risk_free_rate)
        if abs(delta) > self.delta_threshold:
            hedge_deposit = Trade(trade_time=market_time,
                                  stock_price=stock_price,
                                  asset=Deposit(delta * stock_price))
            hedge_asset = Trade(trade_time=market_time,
                                stock_price=stock_price,
                                asset=Stock(-1 * delta))
            self.trades.append(hedge_deposit)
            self.trades.append(hedge_asset)
            return hedge_deposit.asset, hedge_asset.asset

        return Deposit(0), Stock(0)


def fatorial(n, show = False):
    '''
    --> Função para Fatoriação de números!
    :param n: Número para ser fatoriado
    :param show: Mostrar o cálculo
    :return: Resultado do cálculo fatorial do número N
    '''
    f = 1
    for c in range(n, 0, -1):
        if show:
            print(f'{c}', end='')
            if c > 1:
                print(' X ', end='')
            else:
                print(' = ', end='')
        f *= c
    return f

print(fatorial(5, True))


# %%
import pandas as pd
confirmedData = pd.read_csv("DXYvisualize/confirmedData.csv", index_col=0)
curedData = pd.read_csv("DXYvisualize/curedData.csv", index_col=0)
deadData = pd.read_csv("DXYvisualize/deadData.csv", index_col=0)

def getIncr(data: pd.DataFrame)->pd.DataFrame:
    incr = data.diff()
    incr.iloc[0] = data.iloc[0]
    return incr

confirmedIncr = getIncr(confirmedData)
curedIncr = getIncr(curedData)
deadIncr = getIncr(deadData)

# %%
def getRolling(data: pd.DataFrame)->pd.DataFrame:
    return data.rolling(7, center=True, min_periods=0).mean()

confirmedIncrRolling = getRolling(confirmedIncr)
curedIncrRolling = getRolling(curedIncr)
deadIncrRolling = getRolling(deadIncr)
# %%
totalData = pd.DataFrame(columns=["updateTime","confirmedIncr","curedIncr","deadIncr","provinceName"])
for province in confirmedData.columns.values:
    # if province=="湖北":continue
    provinceData = pd.DataFrame(data = confirmedData.index,columns=["updateTime"])
    # print( confirmedIncrRolling[province])
    provinceData.insert(1, 'provinceName', [province]*len(confirmedData.index))
    provinceData.insert(2, 'confirmedIncr', confirmedIncrRolling[province].values)
    provinceData.insert(3, 'curedIncr', curedIncrRolling[province].values)
    provinceData.insert(4, 'deadIncr', deadIncrRolling[province].values)
    totalData = pd.concat([totalData, provinceData])
totalData = totalData.reset_index(drop=True)
# %%
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

plt.figure(figsize=(20,20))
ax = plt.subplot(projection="3d")
ax.set_title("")
ax.scatter(totalData["confirmedIncr"],totalData["curedIncr"],totalData["deadIncr"],c='r')
ax.set_xlabel("感染")
ax.set_ylabel("治愈")
ax.set_zlabel("死亡")
plt.savefig("3D.png")
plt.show()
# %%


""" Script contains all identification resources """

from dojahcore import dojah
from dojahcore.core import DojahBase

class Identification(DojahBase):
    """
        This class contains all KYC/KYB identification endpoints

    """

    @classmethod
    def validate_bvn(cls,bvn, first_name=None, last_name=None, dob=None):
        """ Validates a bvn

        params :
                bvn : str -> Required
                first_name : str -> Optional
                last_name : str -> Optional
                dob : str -> Optional
        returns :
           Json data from Dojah API

        """
        query= {
            'bvn': bvn
        }

        if first_name:
            query['first_name'] = first_name
        if last_name:
            query['last_name'] =last_name

        if dob:
            query['dob'] =  dob

        response  =  cls().requests.get('/api/v1/kyc/bvn', query=query)
        return response #TODO write utility function to parse response

    @classmethod
    def lookup_bvn_basic(cls,bvn):
        """ The Lookup BVN endpoint returns details of a particular BVN

            Calls the /api/v1/kyc/bvn/full

        params :
                bvn : str -> required

        returns :
            Json data from Dojah API

        """
        response = cls().requests.get('/api/v1/kyc/bvn/full', query=[('bvn',bvn)])

        return response

    @classmethod
    def lookup_bvn_advance(cls, bvn):
        """ The Lookup BVN endpoint returns details of a particular BVN

            Calls the /api/v1/kyc/bvn/advance

        params :
                bvn : str -> required

        returns :
            Json data from Dojah API

        """

        response = cls().requests.get('/api/v1/kyc/bvn/advance', query=[('bvn',bvn)])

        return response

    @classmethod
    def lookup_nuban(cls, account_number, bank_code):
        """ The Lookup NUBAN (Nigeria Uniform Bank Account Number) endpoint provides information of users' account numbers

            params :
                    account_number : str -> required
                    bank_code : number  -> required

            returns :
                 Json data from Dojah API

        """

        response  = cls().requests.get('/api/v1/kyc/nuban', query=[('account_number',account_number),('bank_code',bank_code)])

        return response

    @classmethod
    def lookup_nin(cls, nin):
        """ This endpoint allows developers to fetch customers details
            using the National Identification Number (NIN) of the customer

            params :
                    nin : str -> required

            returns :
                    Json data  from Dojah API
        """

        response = cls().requests.get('/api/v1/kyc/nin',query=[('nin',nin)])

        return response

    @classmethod
    def lookup_phone_number_basic(cls, phone_number):
        """ Returns the details of a phone number

            params :
                    phone_number : str -> required
            returns :
                    Json data from Dojah API

        """

        response = cls().requests.get('/api/v1/kyc/phone_number/basic', query=[('phone_number',phone_number)])

        return response

    @classmethod
    def lookup_phone_number(cls, phone_number):
        """ Returns the details of a phone number

            params :
                    phone_number : str -> required

            returns :

                    Json data from Dojah API
        """

        response = cls().requests.get('/api/v1/kyc/phone_number', query=[('phone_number',phone_number)])

        return response

    @classmethod
    def lookup_vin_dob(cls, state, first_name, last_name,dob):
        """ Lookup vin via date of birth

            params :
                    state : str -> required
                    first_name : str -> required
                    last_name : str -> required
                    dob : str -> required
            returns :
                    Json data from Dojah API
        """

        query = [('mode','dob'),('state',state),('first_name',first_name),('last_name',last_name),('dob',dob)]
        response = cls().requests.get('/api/v1/kyc/vin', query=query)

        return response

    @classmethod
    def lookup_vin(cls,vin, state, last_name):
        """ Lookup vin

            params :
                    vin : str -> required
                    state : str -> required
                    last_name : str -> required
            returns :
                    Json data from Dojah API

        """

        query =[('mode','vin'),('state',state),('last_name',last_name),('vin',vin)]

        response = cls().requests.get('/api/v1/kyc/vin', query=query)

        return response

    @classmethod
    def lookup_driver_licence(cls, license_number, dob):
        """ Returns details of a license number

            params :
                    license_number : str -> required
                    dob : yyyy-mm-dd -> required

            returns :
                    Json data from Dojah API

        """

        query =  [('license_number', license_number),('dob',dob)]
        response  =  cls().requests.get('/api/v1/kyc/dl',query=query)

        return response

    @classmethod
    def lookup_cac(cls,rc_number, company_name):
        """ Fetch CAC information of customers' company/organization.
            CAC is a certificate that shows evidence of the company's existence.

            params :
                    rc_number : str -> required
                    company_name : str -> required

            returns :
                    Json data from Dojah API

        """

        query  = [('rc_number',rc_number),('company_name',company_name)]
        response  =  cls().requests.get('/api/v1/kyc/cac',query=query)

        return response

    @classmethod
    def lookup_tin(cls,tin):
        """ Fetch a person's details using the Tax Identification number

            params :
                    tin : str -> required

            returns :
                    Json data from Dojah API

        """

        response  =  cls().requests.get('/api/v1/kyc/tin',query=[('tin',tin)])

        return response


import csv
import json
import re

# It tries to get the links for the coverage badges in the repos README.md

services = [
    'coveralls',
    'codecov',
    'codeclimate',
    'cov'
]

def get_badge_urls(text):
    result = set()
    matched = re.findall(r'(?:http\:|https\:)\/\/.*', text)

    for match in matched:
        for service in services:
            if service in match:
                result.add(match)
                break

    return list(result)

def get_badge_images(text):
    result = set()
    matched = re.findall(r'(?:http\:|https\:)\/\/.*\.(?:png|jpg|svg)', text)

    for match in matched:
        for service in services:
            if service in match:
                result.add(match)
                break

    return list(result)

f = open('data/cov_traces.json')
traces = json.load(f)

badges = []

for repo in traces:
    links = []
    images = []

    for line in traces[repo]:
        links.extend(get_badge_urls(line))
        images.extend(get_badge_images(line))

    if not (links == [] and images == []):
        badges.append({
            'name': repo,
            'links': links,
            'images': images
        })

with open('data/badges.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'links', 'images'])
    writer.writeheader()
    writer.writerows(badges)

f.close()


"""
Task
    Given an integer array nums sorted in non-decreasing order,
    return an array of the squares of each number sorted in non-decreasing order.

Constraints
    1 <= nums.length <= 104
    -104 <= nums[i] <= 104
    nums is sorted in non-decreasing order.
"""

from typing import List

class Solution:

    # O(n) when mirrored sorted list.
    def stage_sort(self, nums: List[int]) -> List[int]:
        lst = [] * len(nums)
        # index to start at left of list
        left_index: int = 0
        #  index tp start at right of list
        right_index: int = len(nums) -1
        # until the left and right index are eq or pass eachother
        while left_index <= right_index:
            # if the left value is greater than the right
            if nums[left_index] > nums[right_index]:
                # add to return list
                lst.append(nums[left_index])
                # increment left
                left_index += 1
            # if the right value is greater than the left
            else:
                # add to return list
                lst.append(nums[right_index])
                # decrement right
                right_index -= 1
        # return a reverse splice of our list
        return lst[::-1]

    def sortedSquares(self, nums: List[int]) -> List[int]:
        self.stage_sort(nums=[num ** 2 for num in nums])

print(Solution().sortedSquares([x * x for x in range(-10,11)]))


from datetime import datetime

from motor.motor_asyncio import AsyncIOMotorClient

from tgbot.config import config
from tgbot.database.filters import date_interval_filter
from tgbot.database.utils import generate_intervals_func_dict

client = AsyncIOMotorClient(config.db_url)

db = client.sampleDB

async def get_data_from_db(
        start_date: datetime,
        end_date: datetime,
        group_type: str
) -> dict[datetime, int]:
    pipeline = [
        {
            '$match': {'dt': {'$gte': start_date, '$lte': end_date}}
        },
        {
            '$group': {
                '_id': {'$dateFromParts': date_interval_filter[group_type]},
                'total': {'$sum': '$value'},
            }
        },
        {
            '$sort': {'_id': 1}
        },
        {
            '$group': {
                '_id': 0,
                'labels': {'$push': '$_id'},
                'dataset': {'$push': '$total'},
            }
        },
        {
            '$project': {
                '_id': 0,
                'dataset': 1,
                'labels': 1,
            }
        },
    ]

    return await db.sample_collection.aggregate(pipeline).next()

async def format_result(
        data: dict,
        template: dict
) -> dict[str, list]:
    for total, date in zip(data['dataset'], data['labels']):
        template[date] = total

    result = {
        'dataset': list(template.values()),
        'labels': list(template.keys())
    }
    return result

async def get_payments(
        start_date: datetime,
        end_date: datetime,
        group_type: str
) -> dict[str, list]:
    generate_intervals_func = generate_intervals_func_dict[group_type]

    data_from_db = await get_data_from_db(start_date, end_date, group_type)
    intervals = generate_intervals_func(start_date, end_date)

    return await format_result(
        data_from_db,
        intervals
    )


"""
题意：给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d ，
使得 a + b + c + d 的值与 target 相等？找出所有满足条件且不重复的四元组。

注意：

答案中不可以包含重复的四元组。
"""

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        n = len(nums)
        nums.sort()
        for i in range(n):
            if i > 0 and nums[i] == nums[i - 1]: continue
            for k in range(i + 1, n):
                if k > i + 1 and nums[k] == nums[k - 1]: continue
                left = k + 1
                right = n - 1

                while left < right:
                    if nums[i] + nums[k] + nums[left] + nums[right] > target:
                        right -= 1
                    elif nums[i] + nums[k] + nums[left] + nums[right] < target:
                        left += 1
                    else:
                        res.append([nums[i], nums[k], nums[left], nums[right]])
                        while left < right and nums[left] == nums[left + 1]: left += 1
                        while left < right and nums[right] == nums[right - 1]: right -= 1
                        left += 1
                        right -= 1
        return res


import os
import sys

sys.path.insert(1, os.path.join(sys.path[0], ".."))
# trunk-ignore(flake8/E402)
from scr.classes.mclass import Finance
# trunk-ignore(flake8/E402)
from scr.classes.rclass import ReadFinances
# trunk-ignore(flake8/E402)
from scr.classes.sclass import SaveFinances
# trunk-ignore(flake8/F401)
from scr.argm.argms import arguments

def test_mclass():
    finance = Finance("John", 20, 100)
    assert finance.name == "John"
    assert finance.age == 20
    assert finance.balance == 100

def test_rclass():
    delDatabase()
    finance = Finance("John", 20, 100)
    SaveFinances().save(finance)
    assert ReadFinances().getFinance()[0] == ("John", 20, 100)

def test_sclass():
    delDatabase()
    finance = Finance("BOB", 50, 200)
    SaveFinances().save(finance)
    assert os.path.exists("data.db")
    assert ReadFinances().getFinance()[0] == ("BOB", 50, 200)

def delDatabase():
    os.remove("data.db")


class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:

        info = sorted(list(zip(position, speed)) ,key=lambda x: x[0])
        ans = 1
        timeTake = [(target - x[0])/x[1] for x in info ]
        timeTake.reverse()
        monoStack = []
        l = 0
        r = 0

        while r < len(timeTake):
            if timeTake[l] >= timeTake[r]:
                r += 1
            else:
                ans += 1
                l = r

        return ans


#!/usr/bin/pythonRoot3.5
#----------------------------------------------------------------
# Dateiname:  inter_webcam.py
# CGI-Skript fuer interaktive Webcam
#
# Michael Weigend
# Raspberry Pi programmieren mit Python, 4. Auflage, mitp 2018
# Kap. 11
# Michael Weigend 20. September 2018
#--------------------------------------------------------------

import cgi, cgitb, os, subprocess, io
from PIL import Image

PATTERN='''Content-Type: text/html

        <title>Interaktive Webcam</title>

 Interaktive Webcam

   Wählen Sie den Bildausschnitt!
   <form action="http://localhost/cgi-bin/inter_webcam.py"
     method="GET">
      <input type="Radio" name="zoom" value="weit" {}/>
           Weit entfernt

      <input type="Radio" name="zoom" value="naeher" {}/>
           Näher

      <input type="Radio" name="zoom" value="nah" {}/>
          Nah

      <input type="Submit" value="Bild anfordern"/>
    </form>

'''                                            #1

PATH = 'image.jpg'
COMMAND = 'raspistill -t 500 -w {}  -h {} -o {} -n '                                #2

def takePhoto (width, height, bbox):
    imageData = io.BytesIO()
    command = COMMAND.format(width, height,'-')               #3
    try:
        imageData.write(subprocess.check_output(command, shell=True))                                          #4
        imageData.seek(0)
        image = Image.open(imageData).crop(bbox)          #5
        image.save(PATH)
    except: pass

form = cgi.FieldStorage()
zoom = form.getvalue('zoom', 'nah')
if zoom == 'nah':                                     #6
    takePhoto(1600, 1200, (600, 450, 1000, 750))
    response = PATTERN.format('', '', 'checked="checked"')
elif zoom == 'naeher':
    takePhoto(800, 600, (200, 150, 600, 450))         #7
    response = PATTERN.format('', 'checked="checked"', '')
else:
    takePhoto(400, 300, (0, 0, 400, 300))             #8
    response = PATTERN.fortmat('checked="checked"', '', '')

print(response)


#
# @lc app=leetcode.cn id=827 lang=python
#
# [827] 最大人工岛
#
# https://leetcode-cn.com/problems/making-a-large-island/description/
#
# algorithms
# Hard (39.59%)
# Likes:    40
# Dislikes: 0
# Total Accepted:    2.3K
# Total Submissions: 5.6K
# Testcase Example:  '[[1,0],[0,1]]'
#
# 在二维地图上， 0代表海洋， 1代表陆地，我们最多只能将一格 0 海洋变成 1变成陆地。
#
# 进行填海之后，地图上最大的岛屿面积是多少？（上、下、左、右四个方向相连的 1 可形成岛屿）
#
# 示例 1:
#
#
# 输入: [[1, 0], [0, 1]]
# 输出: 3
# 解释: 将一格0变成1，最终连通两个小岛得到面积为 3 的岛屿。
#
#
# 示例 2:
#
#
# 输入: [[1, 1], [1, 0]]
# 输出: 4
# 解释: 将一格0变成1，岛屿的面积扩大为 4。
#
# 示例 3:
#
#
# 输入: [[1, 1], [1, 1]]
# 输出: 4
# 解释: 没有0可以让我们变成1，面积依然为 4。
#
# 说明:
#
#
# 1 <= grid.length = grid[0].length <= 50
# 0 <= grid[i][j] <= 1
#
#
#

# @lc code=start

class Solution(object):
    def largestIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        R, C = len(grid), len(grid[0])

        def neighbors(r, c):
            for nr, nc in [(r-1, c), (r, c-1), (r+1, c), (r, c+1)]:
                if 0 <= nr < R and 0 <= nc < C:
                    yield nr, nc

        # 深度优先搜索获取所有的岛屿
        lands = []
        seen = set()
        for r, row in enumerate(grid):
            for c, val in enumerate(row):
                if not val or (r, c) in seen:
                    continue
                # 新的岛屿
                stack = [(r, c)]
                this_land = {(r, c)}
                while stack:
                    node = stack.pop()
                    for new_node in neighbors(*node):
                        if grid[new_node[0]][new_node[1]] and new_node not in this_land:
                            this_land.add(new_node)
                            stack.append(new_node)
                lands.append(this_land)
                seen |= this_land

        # print(lands)

        # 找0,找0周围的岛屿
        has_ocean = False
        ans = 0
        for r, row in enumerate(grid):
            for c, val in enumerate(row):
                if val == 0:
                    has_ocean = True
                    this_neighbors = {x for x in neighbors(r, c)}
                    neighbor_land_ids = set()
                    for ind,land in enumerate(lands):
                        if not land.isdisjoint(this_neighbors):
                            neighbor_land_ids.add(ind)
                    this_ans = sum([len(lands[x]) for x in neighbor_land_ids]) + 1
                    ans = max(ans, this_ans)
        if not has_ocean:
            return len(lands[0])
        return ans

# s = [[1, 0], [0, 1]]
# s =  [[1, 1], [1, 0]]
# s = [[1, 1], [1, 1]]
# print(Solution().largestIsland(s))
# @lc code=end


#!/usr/bin/env python

import os
import rospy
import rospkg
import lewansoul_xarm

def shutdown():
    print('\nshutting down xArm...')
    global controller
    controller.shutdown()

def ros_main():
    # connect to xArm
    global controller # so we can shutdown
    controller = lewansoul_xarm.controller()

    rospack = rospkg.RosPack()
    pkg_path = rospack.get_path('lewansoul_xarm')

    urdf_file = pkg_path + '/urdf/xArm.urdf'
    if not os.path.isfile(urdf_file):
        print('couldn\'t find file: ' + urdf_file + '. cartesian moves will be disabled')
        urdf_file = ''
    arm = controller.add_arm("arm", "xArm-49770F673737-arm.json", urdf_file)
    arm.enable()
    arm.home()

    gripper = controller.add_arm("gripper", "xArm-49770F673737-gripper.json")
    gripper.enable()
    gripper.home()

    rospy.init_node('xArm_ros', anonymous = True)
    rospy.on_shutdown(shutdown)

    controller_ros = lewansoul_xarm.controller_ros(controller)
    controller_ros.loop(30) # 30 Hz seems to be the maximum the controller can perform

if __name__ == '__main__':
    try:
        ros_main()
    except rospy.ROSInterruptException:
        pass


#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from example_interfaces.msg import Int64
from example_interfaces.srv import SetBool

class NumberCounterNode(Node):  # MODIFY NAME
    def __init__(self):
        super().__init__("num_pub_serv")  # MODIFY NAME
        self.counter_=0
        self.publisher_=self.create_publisher(Int64,"number_count",10)
        self.subscriber_=self.create_subscription(Int64,"number",self.num_cb, 10)
        self.get_logger().info("Number Counter started..")
        self.server_=self.create_service(
            SetBool, "reset_counter", self.cb_reset_counter)

    def cb_reset_counter(self,req,resp):
        reset:bool=req.data
        if(reset):
          self.counter_=0
        self.get_logger().info("Reset : "+str(reset))
        resp.success=True
        return resp

    def publish_num(self,num):
        msg=Int64()
        msg.data=num
        self.publisher_.publish(msg)
        self.get_logger().info("Number Count Sum Published : "+str(num))

    def num_cb(self,msg):
        self.get_logger().info("received mesage: "+str(msg.data))
        self.counter_=self.counter_+msg.data
        self.publish_num(self.counter_)

def main(args=None):
    rclpy.init(args=args)
    node = NumberCounterNode()  # MODIFY NAME
    rclpy.spin(node)
    rclpy.shutdown()

if __name__ == "__main__":
    main()


import cflib
from cflib.crazyflie import Crazyflie
from PID import PID
import math

Pr = 0.1
Ir = 0.02
Dr = 4

Pp = 0.005
Ip = 0.01
Dp = 5

Pt = 1
It = 0
Dt = 6

setPointY = 240
setPointX = 320

class ControlDrone:

#link_uri nel costruttore
    def __init__(self,link_uri):
        """ Initialize and run the example with the specified link_uri """

        self._cf = Crazyflie()

        self._cf.connected.add_callback(self._connected)
        self._cf.disconnected.add_callback(self._disconnected)
        self._cf.connection_failed.add_callback(self._connection_failed)
        self._cf.connection_lost.add_callback(self._connection_lost)
        self._cf.open_link(link_uri)
        print('Connecting to %s' % link_uri)

        self.heading = 0

        self.PIDRoll = PID()
        self.PIDPitch = PID()
        self.PIDTrottle = PID()

        self.PIDRoll.setKp(Pr)
        self.PIDPitch.setKp(Pp)
        self.PIDTrottle.setKp(Pt)
        self.PIDRoll.setKd(Dr)
        self.PIDPitch.setKd(Dp)
        self.PIDTrottle.setKd(Dt)
        self.PIDRoll.setKi(Ir)
        self.PIDPitch.setKi(Ip)
        self.PIDTrottle.setKi(It)

        self.PIDRoll.setPoint(setPointX)
        self.PIDPitch.setPoint(setPointY)

    def _connected(self, link_uri):
        """ This callback is called form the Crazyflie API when a Crazyflie
        has been connected and the TOCs have been downloaded."""

        # Start a separate thread to do the motor test.
        # Do not hijack the calling thread!

    def _connection_failed(self, link_uri, msg):
        """Callback when connection initial connection fails (i.e no Crazyflie
        at the specified address)"""
        print('Connection to %s failed: %s' % (link_uri, msg))

    def _connection_lost(self, link_uri, msg):
        """Callback when disconnected after a connection has been made (i.e
        Crazyflie moves out of range)"""
        print('Connection to %s lost: %s' % (link_uri, msg))

    def _disconnected(self, link_uri):
        """Callback when the Crazyflie is disconnected (called in all cases)"""
        print('Disconnected from %s' % link_uri)

    def _inizialize_drone(self):
        self._cf.commander.send_setpoint(0, 0, 0, 0)

    def _control_drone(self, PositionX,PositionY):

        errorPitch = self.PIDPitch.update(PositionY)
        errorRoll = self.PIDRoll.update(PositionX)

        desiredRoll = errorRoll * math.cos((self.heading * math.pi) / 180) + errorPitch * math.sin((self.heading * math.pi) / 180) * (1 / 9.81)
        desiredPitch = errorPitch * math.cos((self.heading * math.pi) / 180) + errorRoll * math.sin((self.heading * math.pi) / 180) * (1 / 9.81);

        print (desiredRoll,desiredPitch)
        self._cf.commander.send_setpoint(desiredRoll,-desiredPitch,0,43000)
        return desiredRoll,desiredPitch

    def _cut_motor(self):
        self._cf.commander.send_setpoint(0, 0, 0, 0)


#
# def maximumUniqueSubarray(nums): # 疯狂超时
#     """
#     :type nums: List[int]
#     :rtype: int
#     """
#     d = {}
#     res = 0
#     i = 0
#     j = 0
#     set = set(nums)
#     nm = sum(set)
#     while i <= len(nums)-1:
#         if nums[i] not in d:
#             d[nums[i]] = i
#             i += 1
#         else:
#             s = sum(nums[j:i])
#             if s == nm:
#                 return s
#             if s > res:
#
#                 res = s
#             j = d[nums[i]] + 1
#             d = {}
#             for k in range(j, i+1):
#                 d[nums[k]] = k
#             i += 1
#
#     if sum(nums[j:]) > res:
#         res = sum(nums[j:])
#     return res

def maximumUniqueSubarray(nums):  # 改成这样才过了，但是耗时很久
    """
    :type nums: List[int]
    :rtype: int
    """
    if not nums:
        return 0
    if len(nums) == 1:
        return nums[0]

    res, j, k = 0, 0, 0
    for i in range(1, len(nums)):
        if nums[i] not in nums[j:i]:
            continue
        else:
            k = sum(nums[j:i])
            if k > res:
                res = k
            j = nums.index(nums[i], j, i) + 1
    k = sum(nums[j:])
    if k > res:
        res = k
    return res

print(maximumUniqueSubarray([5,2,2,2,2,2,2,2]))


import os
import cv2
from keras.utils import Sequence
from keras.utils import np_utils

from Models.Network_building import *

class DataGenerator(Sequence):
    """Data Generator inherited from keras.utils.Sequence
    Args:
        directory: the path of data set, and each sub-folder will be assigned to one class
        batch_size: the number of data points in each batch
        shuffle: whether to shuffle the data per epoch
    Note:
        If you want to load file with other data format, please fix the method of "load_data" as you want
    """

    def __init__(self, directory, batch_size=1, shuffle=True, data_augmentation=True):
        # Initialize the params
        self.batch_size = batch_size
        self.directory = directory
        self.shuffle = shuffle
        self.data_aug = data_augmentation
        # Load all the save_path of files, and create a dictionary that save the pair of "data:label"
        self.X_path, self.Y_dict = self.search_data()
        # Print basic statistics information
        self.print_stats()

    def search_data(self):
        X_path = []
        Y_dict = {}
        # list all kinds of sub-folders
        self.dirs = sorted(os.listdir(self.directory))
        one_hots = np_utils.to_categorical(range(len(self.dirs)))
        for i, folder in enumerate(self.dirs):
            folder_path = os.path.join(self.directory, folder)
            for file in os.listdir(folder_path):
                file_path = os.path.join(folder_path, file)
                # append the each file path, and keep its label
                X_path.append(file_path)
                Y_dict[file_path] = one_hots[i]
        return X_path, Y_dict

    def print_stats(self):
        # calculate basic information
        self.n_files = len(self.X_path)
        self.n_classes = len(self.dirs)
        self.indexes = np.arange(len(self.X_path))
        np.random.shuffle(self.indexes)
        # Output states
        print("Found {} files belonging to {} classes.".format(self.n_files, self.n_classes))
        for i, label in enumerate(self.dirs):
            print('%10s : ' % (label), i)
        return None

    def __len__(self):
        # calculate the iterations of each epoch
        steps_per_epoch = np.ceil(len(self.X_path) / float(self.batch_size))
        return int(steps_per_epoch)

    def __getitem__(self, index):
        """Get the data of each batch
        """
        # get the indexs of each batch
        batch_indexs = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]
        # using batch_indexs to get path of current batch
        batch_path = [self.X_path[k] for k in batch_indexs]
        # get batch data
        batch_x, batch_y = self.data_generation(batch_path)
        return batch_x, batch_y

    def on_epoch_end(self):
        # shuffle the data at each end of epoch
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def read_image(self,img_path, H, W):
        #print(f"in read img\n{img_path}\n")
        # img_path=img_path+".jpg"
        #print(f"in read img--{img_path}")
        img = cv2.imread(img_path, cv2.IMREAD_COLOR)

        # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = cv2.resize(img, (W, H))  # you can resize to  (128,128) or (256,256)

        return img

    def data_generation(self, batch_path):
        #print(f"in data generation\n {batch_path}\n")
        # load data into memory, you can change the np.load to any method you want
        batch_x = [self.load_data(x) for x in batch_path]
        batch_y = [self.Y_dict[x] for x in batch_path]
        # transfer the data format and take one-hot coding for labels
        batch_x = np.array(batch_x)
        batch_y = np.array(batch_y)
        return batch_x, batch_y

    def load_data(self, path):
        # load the processed .npy files which have 5 channels (1-3 for RGB, 4-5 for optical flows)
        #data = np.load(path, mmap_mode='r')
        #print(f"[+][+] in load data:path-->{path}]n")
        data = self.read_image(path, 224, 224)
        data = np.float32(data)
        return data

#
# model = get_compile_model()
# model.save_weights(r'C:\Users\amit hayoun\Desktop\weights_at_epoch_%d.h5' % (0))
#
# #path_train = r"E:\FINAL_PROJECT_DATA\Rec_project\data_set\dataset_example\train"
#
# path_train = r"F:\data for recommender system\FINAL_DATA_SORT\Train"
# path_val = r"F:\data for recommender system\FINAL_DATA_SORT\Val"
# num_epochs=3
# batch_size=3
# checkpoint_dir=""
# # callbacks_list = [keras.callbacks.ModelCheckpoint(
# # keras.callbacks.ModelCheckpoint(filepath=checkpoint_dir + "/ckpt-{epoch}", save_freq="epoch"))]
# callbacks_list =None
# num_workers=4
#
# train_generator = DataGenerator(directory=path_train,batch_size=batch_size,data_augmentation=False)
# val_generator = DataGenerator(directory=path_val, batch_size=batch_size,data_augmentation=False)
#
#
# #self.model_to_save.save_weights(r'/root/gate_flow_slow_fast/weight_save_2/weights_at_epoch_%d.h5' % (epoch+1+15))
#
# hist = model.fit_generator(
#     generator=train_generator,
#     validation_data=val_generator,
#     callbacks=callbacks_list,
#     verbose=1,
#     epochs=num_epochs,
#     workers=num_workers ,
#     max_queue_size=4,
#     steps_per_epoch=len(train_generator),
#     validation_steps=len(val_generator))


import re

COMCENT_PLUGIN_PREFIX       = "/video/comedycentral"
YAHOO_NAMESPACE  = {'media':'http://search.yahoo.com/mrss/'}

RSS_PATH = "http://www.comedycentral.com/comedycentral/video/data/mrss.jhtml?uri=%s"

ICON = "icon-default.png"
ART = "art-default.jpg"

####################################################################################################
def Start():
  Plugin.AddPrefixHandler(COMCENT_PLUGIN_PREFIX, MainMenu, "Comedy Central", ICON, ART)
  Plugin.AddViewGroup("InfoList", viewMode="InfoList", mediaType="items")
  Plugin.AddViewGroup("List", viewMode="List", mediaType="items")
  MediaContainer.art = R(ART)
  DirectoryItem.thumb = R(ICON)

####################################################################################################

def MainMenu():
  dir = MediaContainer(viewGroup="List", title1="Comedy Central")
  for show in HTML.ElementFromURL("http://www.comedycentral.com/shows/index.jhtml").xpath('//div[@class="hiddencontent"]/ul/li/a'):
    showurl = show.get("href")
    if showurl.count("http://") == 0 and showurl.count("katz") == 0 and showurl.count("scrubs") == 0 and showurl.count("wanda") == 0 and showurl.count("mad_tv") == 0 and showurl.count("colbert") == 0:
      dir.Append(Function(DirectoryItem(Level1, title = show.text_content()),url=showurl,title = show.text_content().encode('utf-8')))

  return dir

def Level1(sender, url, title):
  dir = MediaContainer(viewGroup="List", title2=title.encode("utf-8"))
  showurl = ("http://www.comedycentral.com" + url)
  try:
    showpage =  HTTP.Request(showurl).content
    ids =  re.findall("mgid:cms:item:comedycentral.com:[0-9]+",showpage)
    for id in ids:
      rssfeed = HTTP.Request(RSS_PATH %id).content.replace('media:','media-')
      for item in XML.ElementFromString(rssfeed).xpath('//item'):#namespaces = YAHOO_NAMESPACE
        title = item.xpath('title')[0].text.replace('|',' - ')
        subtitle = item.xpath('pubDate')[0].text
        summary = item.xpath('description')[0].text

        stringified = XML.StringFromElement(item)

        try:
          duration = int(re.search('duration="([0-9]+)"', stringified).group(1))*1000
      #duration = int(item.xpath('media-content')[0].get('duration'))*1000
        except:
          duration = None

        try:
          thumb = re.search('media-thumbnail url="([^&?]+.jpg)', stringified).group(1)
   #     thumb = item.xpath('media-thumbnail')[0].get('url')
        except:
          thumb = R(ICON)
        url = item.xpath('link')[0].text
        dir.Append(WebVideoItem(url, title=title , subtitle=subtitle, summary=summary, duration=duration, thumb = thumb))

    if len(dir) == 0:
      return MessageContainer("Error","This category does not contain any video.")
    else:
      return dir
  except:
    return MessageContainer("Error","This category does not contain any video.")


'''
Created on Oct 20, 2015

@author: chris
'''
from .bulldozer import Bulldozer
from engine.buildingTool import BuildingTool
from engine.lineTool import LineTool
from engine.toolStroke import ToolStroke

# Tool types:
BULLDOZER, WIRE, ROADS, RAIL, RESIDENTIAL, COMMERCIAL, INDUSTRIAL, FIRE \
    , POLICE, STADIUM, PARK, SEAPORT, POWERPLANT, NUCLEAR, AIRPORT, QUERY = list(xrange(16))

class MicropylisTool(object):
    def __init__(self, name, type_, size, cost):
        self.name = name
        self.type = type_
        self.size = size
        self.cost = cost

    @classmethod
    def factory(cls, toolType):
        toolType = toolType.upper()
        try:
            class_ = types[toolType]
        except KeyError:
            print("toolType not found: " + toolType)
            return None
        return class_

    def getWidth(self):
        return self.size

    def getHeight(self):
        return self.getWidth()

    def beginStroke(self, engine, xPos, yPos):
        if self.type == BULLDOZER:
            return Bulldozer(engine, xPos, yPos)
        elif (self.type == WIRE or
                      self.type == ROADS or
                      self.type == RAIL):
            return LineTool(engine, self, xPos, yPos)
        elif (self.type == FIRE or
                      self.type == FIRE or
                      self.type == POLICE or
                      self.type == POWERPLANT or
                      self.type == STADIUM or
                      self.type == SEAPORT or
                      self.type == NUCLEAR or
                      self.type == AIRPORT):
            return BuildingTool(engine, self, xPos, yPos)
        else:
            return ToolStroke(engine, self, xPos, yPos)

    def apply(self, engine, xPos, yPos):
        return self.beginStroke(engine, xPos, yPos).apply()

    def getToolCost(self):
        return self.cost

types = dict()
types['BULLDOZER'] = MicropylisTool('BULLDOZER', BULLDOZER, 1, 10)
types['WIRE'] = MicropylisTool('WIRE', WIRE, 1, 5)  # 25 underwater
types['ROADS'] = MicropylisTool('ROADS', ROADS, 1, 10)  # 50 overwater
types['RAIL'] = MicropylisTool('RAIL', RAIL, 1, 20)  # 100 underwater
types['RESIDENTIAL'] = MicropylisTool('RESIDENTIAL', RESIDENTIAL, 3, 100)
types['COMMERCIAL'] = MicropylisTool('COMMERCIAL', COMMERCIAL, 3, 100)
types['INDUSTRIAL'] = MicropylisTool('INDUSTRIAL', INDUSTRIAL, 3, 100)
types['POLICE'] = MicropylisTool('POLICE', POLICE, 3, 500)
types['FIRE'] = MicropylisTool('FIRE', FIRE, 3, 500)
types['STADIUM'] = MicropylisTool('STADIUM', STADIUM, 4, 5000)
types['PARK'] = MicropylisTool('PARK', PARK, 1, 10)
types['SEAPORT'] = MicropylisTool('SEAPORT', SEAPORT, 4, 3000)
types['POWERPLANT'] = MicropylisTool('POWERPLANT', POWERPLANT, 4, 3000)
types['NUCLEAR'] = MicropylisTool('NUCLEAR', NUCLEAR, 4, 5000)
types['AIRPORT'] = MicropylisTool('AIRPORT', AIRPORT, 6, 10000)
types['QUERY'] = MicropylisTool('QUERY', QUERY, 1, 0)


## 정렬
## 슬라이스를 이용해 배열을 자른 후
## sort를 이용해 순서대로 정렬

def solution(array , commands):
    answer =[]
    for c in commands:
        a = array[c[0]-1:c[1]]
        a.sort()
        answer.append(a[c[2]-1])
    return answer

array = [1, 5, 2, 6, 3, 7, 4]
commands =[[2, 5, 3], [4, 4, 1], [1, 7, 3]]

## 다른 사람 풀이
def solution2(array, commands):
    return list(
        map(lambda x:
        sorted(array[x[0]-1:x[1]])[x[2]-1],
        ##  commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
        # x =[2,5,3]
        ## array[2-1:5] = [5,2,6,3]  -> [2,3,5,6] [2]
        commands)
        )

print(solution(array,commands))

김성수/프로그래머스 LV1/k 번째 수.py


import os
import random
import sys

OutFileName = '../test/nb_data'
trainOutFile = open(OutFileName+".train","w",encoding='utf-8')
testOutFile =open(OutFileName+".test","w",encoding='utf-8')

WordDir ={}
WordList =[]

i=0
tag =0
input = '../data'
for filename in os.listdir(input):
    if filename.find("business") != -1:
        tag =1
    elif filename.find("auto")!=-1:
        tag = 2
    elif filename.find("sport") != -1:
        tag = 3
    i+=1

    #留出法，80%为训练集，20%为测试集
    rd = random.random()
    outfile = testOutFile
    if rd<0.8:
        outfile = trainOutFile

    if i%1000 ==0:
        print (i,"files processed!\r")

        #读取每一个原始样本
    infile = open(input+'/'+filename,'r',encoding='utf-8')
    outfile.write(str(tag)+" ")
    content = infile.read().strip()
    words = content.replace('\n',' ').split(" ")
    for word in words:
        if  len(word.strip())<1:
            continue
        if word not in WordDir:
            WordList.append(word)
            WordDir[word]=len(WordList)
        outfile.write(str( WordDir[word] ) + " ")
    outfile.write("#"+filename+"\n")
    infile.close()

print ("一共有"+str(len(WordList)) +"个词语读取成功")

trainOutFile.close()
testOutFile.close()


import os
import requests
import argparse
from bs4 import BeautifulSoup
from urllib.parse import urljoin

def parse_page_numbers():
    parser = argparse.ArgumentParser(
        description="Parse page range"
    )
    parser.add_argument('-s', '--start_page', help='Start page number')
    parser.add_argument('-e', '--end_page', help='End page number')
    args = parser.parse_args()
    start_page = int(args.start_page)
    end_page = int(args.end_page) + 1
    return start_page, end_page

start_page, end_page = parse_page_numbers()

def get_book_collection_urls(url, start, end):
    collection_url_list = []
    for page in range(start, end):
        page_url = '{}{}'.format(url, page)
        response = requests.get(page_url, allow_redirects=False)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'lxml')
        book_cards = soup.select('#content table td > a:first-child')
        collection_url_list += [card.get('href') for card in book_cards]
    return collection_url_list

if __name__ == '__main__':
    collection_url = 'http://tululu.org/l55/'
    books = get_book_collection_urls(collection_url, start_page, end_page)
    print(books)


from django.db import models
from wfscript.materials.mixin import WorkflowMaterial

from django_wfscript.constants.models import FieldLength

class User(models.Model, WorkflowMaterial):
    model_identity = 'it/user'
    identity_field = 'id'

    user_name = models.CharField(max_length=FieldLength.NAME, unique=True)
    first_name = models.CharField(max_length=FieldLength.NAME)
    last_name = models.CharField(max_length=FieldLength.NAME)

    @property
    def email(self):
        return f'{self.user_name}@example_corp.com'

    def save(self, *args, **kwargs):
        if not self.user_name:
            self.user_name = f'{self.first_name}.{self.last_name}'
        super(User, self).save(*args, **kwargs)


def ConvertirLista(frase):
	return list(frase)

def ReverseLista(lst):
    lst.reverse()
    return lst

def ConvertirAFrase(lst):
	return "".join(lst)

def CifrarCesar(frase,k):
	if fraseInvertida==fraseInvertida.upper():
		abc="ABCDEFGHIJKLMNÑOPQRSTUVXYZ"
	else:
		abc="abcdefghijklmnñopqrstuvxwyz"
	cifrad=""
	for c in frase:
		if c in abc:
			cifrad += abc[ (abc.index(c)+k)%(len(abc))]
		else:
			cifrad+=c
	return cifrad

#recibimos nuestro modo, mensaje y clave
def obtenerMensajeTraducido(modo, mensaje, clave):
    #validamos si quiere desencriptar
    if modo[0] == 'd':
        #para desencriptar un mensaje se usa la versión negativa de la clave
        clave= -clave
    traduccion = ''
    for simbolo in mensaje:
        # isalpha() devolverá True si la cadena es una letra mayúscula o minúscula entre A y Z
        # Si la cadena contiene algún caracter no alfabético, entonces isalpha() devolverá False
        if simbolo.isalpha():
            num = ord(simbolo)
            num += clave
            #isupper() devuelve True si la cadena sobre la cual es llamado contiene al menos una letra mayúscula y ninguna minúscula.
            #islower() devuelve True si la cadena sobre la cual es llamado contiene al menos una letra minúscula y ninguna mayúscula.
            if simbolo.isupper():
                #Comprobamos si num tiene un valor mayor que el valor ordinal de “Z”. Si es así, restamos 26 a num (porque hay 26 letras en total)
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif simbolo.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26
            traduccion += chr(num)
        else:
            traduccion += simbolo
    return traduccion

def obtenerModo():
    while True:
        print('¿Deseas encriptar o desencriptar un mensaje?')
        modo = input().lower()
        if modo in 'encriptar e desencriptar d'.split():
            return modo
        else:
            print('Ingresa "encriptar" o "e" o "desencriptar" o "d"')

def obtenerFrase():
	return input("Ingrese frase: ")

def obtenerDesplazamiento():
	i=False
	k=0
	while(not i):
		try:
			k=int(input("Valor desplazamiento: "))
			i=True
		except ValueError:
			print('Error, introduce un numero entero')
	return k

while True:
        #Flujo programa

        #Primero se pide el modo (encriptar || desencriptar)
        modo = obtenerModo()

        #Se pide la frase
        frase = obtenerFrase()

        #valor de desplazamiento
        k = obtenerDesplazamiento()

        #se convierte en lista para poder trabajarla
        lista = ConvertirLista(frase)

        #se invierte la lista
        listaInvertida = ReverseLista(lista)

        #se crea un string de la lista invertida
        fraseInvertida = ConvertirAFrase(listaInvertida)

        #se encripta con Cesar la fraseInvertida
        traduc = obtenerMensajeTraducido(modo, frase, k)

        #se imprime la respuesta del sistema
        print("#######################################")
        print("Resultado: ",traduc)
        print("Si deseas terminar digita salir si deseas continuar presiona cualquier tecla")
        salir = input()
        if salir == "salir":
            break


#!/usr/bin/python

import re, os, sys, getopt, math

def translate(mrna_sequence):
    genetic_code = {"AAA":'K',"AAC":'N',"AAG":'K',"AAT":'N',"ACA":'T',"ACC":'T',"ACG":'T',"ACT":'T',"AGA":'R',
    "AGC":'S',"AGG":'R',"AGT":'S',"ATA":'I',"ATC":'I',"ATG":'M',"ATT":'I',"CAA":'Q',"CAC":'H',
    "CAG":'Q',"CAT":'H',"CCA":'P',"CCC":'P',"CCG":'P',"CCT":'P',"CGA":'R',"CGC":'R',"CGG":'R',
    "CGT":'R',"CTA":'L',"CTC":'L',"CTG":'L',"CTT":'L',"GAA":'E',"GAC":'D',"GAG":'E',"GAT":'D',
    "GCA":'A',"GCC":'A',"GCG":'A',"GCT":'A',"GGA":'G',"GGC":'G',"GGG":'G',"GGT":'G',"GTA":'V',
    "GTC":'V',"GTG":'V',"GTT":'V',"TAA":'*',"TAC":'Y',"TAG":'*',"TAT":'Y',"TCA":'S',"TCC":'S',
    "TCG":'S',"TCT":'S',"TGA":'*',"TGC":'C',"TGG":'W',"TGT":'C',"TTA":'L',"TTC":'F',"TTG":'L',"TTT":'F'}
    mrna_sequence = mrna_sequence.upper().replace('U','T')
    protein_sequence = ""
    for i in range(0,len(mrna_sequence),3):
        if mrna_sequence[i:i+3] in genetic_code.keys():
            protein_sequence = protein_sequence + str(genetic_code[mrna_sequence[i:i+3]])
        else:
            protein_sequence = protein_sequence + "X"
    return protein_sequence

def getsd(si,siavg):
    sd = 0
    for val in si:
        sd += (val - siavg)**2
    sd /= len(si)
    return math.sqrt(sd)

def main(argv):
    codefreq = {'A':4/64.0, 'C':2/64.0, 'D':2/64.0, 'E':2/64.0, 'F':2/64.0, 'G':4/64.0, 'H':2/64.0, 'I':3/64.0, 'K':2/64.0, 'L':6/64.0,
    'M':1/64.0, 'N':2/64.0, 'P':4/64.0, 'Q':2/64.0, 'R':6/64.0, 'S':6/64.0, 'T':4/64.0, 'V':4/64.0, 'W':1/64.0, 'Y':2/64.0}

    inputfile = ''
    outputfile = ''
    protein = True

    try:
        opts, args = getopt.getopt(argv,"hi:o:n",["ifile=","ofile="])
    except getopt.GetoptError:
        print('Error! Run as: SI2.py -i <inputfile> -o <outputfile> -n <nucleotide>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('SI2.py -i <inputfile> -o <outputfile> -n <nucleotide>')
            sys.exit()
        if opt == '-n':
            protein = False
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    length = 0
    seqid = ''
    SI = []
    nseq = 0
    sequence = ""

    fi = open(inputfile,'r')
    fo = open(outputfile,'w')
    for line in fi:
        lin = line.rstrip('\n')
        line = str(lin)
        if len(line) > 0:
            if line[0] == '>':
                if nseq > 0:
                    # get sequence
                    if protein is False:
                        sequence = translate(sequence)
                    sequence = sequence.upper().replace('*','')
                    length = len(sequence)
                    for aa in sequence:
                        if aa in codefreq.keys():
	                          SI.append(codefreq[aa])

                    # calculate stats
                    si_avg = 0
                    for si in SI:
                        si_avg += si
                    si_total = si_avg
                    si_avg /= length
                    si_sd = getsd(SI,si_avg)
                    fo.write(str(nseq) + '\t' + seqid + '\t' + str(length) + '\t' + str(si_total) + '\t' + str(si_avg) + '\t' + str(si_sd) + '\n')

                    # reset variables
                    length = 0
                    sequence = ""
                    SI = []
                nseq += 1
                seqid = line[1:]
            else:
                for letter in line:
                    sequence += letter

    if protein is False:
        sequence = translate(sequence)
    sequence = sequence.upper().replace('*','')
    length = len(sequence)
    for aa in sequence:
        if aa in codefreq.keys():
            SI.append(codefreq[aa])

    si_avg = 0
    for si in SI:
        si_avg += si
    si_total = si_avg
    si_avg /= length
    si_sd = getsd(SI,si_avg)
    fo.write(str(nseq) + '\t' + seqid + '\t' + str(length) + '\t' + str(si_total) + '\t' + str(si_avg) + '\t' + str(si_sd) + '\n')

    fi.close()
    fo.close()

if __name__ == "__main__":
    main(sys.argv[1:])


class Phone:
    manufacture = "Bangladesh"

    def __init__(self, brand, price, ram, rom):
        self.brand = brand
        self.price = price
        self.ram = ram
        self.rom = rom

    def print_spec(self):
        print(
            f"Brand : {self.brand} Price : {self.price} Ram : {self.ram} Memory : {self.rom}")

my_phone = Phone("Samsung", 10000, 2, 32)
my_phone.print_spec()

new_phone = Phone("Redmi 11", 19566, 6, 64)

new_phone.print_spec()


import itertools
from collections import Counter

# define a class PokerHand

class PokerHand(object):
    def __init__(
            self,
            hand: str) -> None:
        super().__init__()

        # Storage the player's five cards
        self.hand = hand

    # Compare the result
    def compare_with(self, hand1):
        card_list = [self.hand, hand1.hand]
        result = []

        for i in card_list:
            result.append((self._get_result(i)))

        # State the result
        if result.index(max(result)) == 0:
            return ("Win")
        else:
            return ("Loss")

    # This function get result from cards on the hand.
    def _get_result(self, cards):
        # Card value dictionary.
        card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7,
                       "8": 8, "9": 9, "T": 10, "J": 11, "Q": 12, "K": 13, "A": 14}

        # Values on the hand
        values = [card_values[cards[0]], card_values[cards[3]],
                  card_values[cards[6]], card_values[cards[9]], card_values[cards[12]]]

        # Suits on the hand
        suits = [cards[1], cards[4], cards[7], cards[10], cards[13]]

        # Sorting card values
        values = sorted(values, reverse=True)

        # Check if there is a straight
        straight = (values == list(
            range(values[0], values[0]-5, -1)) or values == [14, 5, 4, 3, 2])

        # Check if there is a flush
        flush = all(s == suits[0] for s in suits)

        # Check if there is a Royal Straight Flush
        if straight and flush and values[0] == 14:
            return 10

        # Check if there is a Straight Flush
        if straight and flush and values[0] != 14:
            return 9

        # Check if there is a Flush
        if flush:
            return 6

        # Check if there is a Straight
        if straight:
            return 5

        dict_group = {}

        # Check how many cards there are.
        for v, group in itertools.groupby(values):
            count = sum(1 for _ in group)
            dict_group[v] = count
        # Check if there is Full House
        if (3 in dict_group.values()) and (2 in dict_group.values()):
            return 7
        # Check if there is Three of a kind
        if (3 in dict_group.values()):
            return 4

        res = Counter(dict_group.values())

        # Check if there is Four of a kind
        if 4 in res.keys():
            return 8

        # Check if there are two pairs
        if 2 in res.keys() and 2 in res.values():
            return 3
        # Check if there is a pair
        if 2 in res.keys() and 1 in res.values():
            return 2
        return 1


#!/usr/bin/python

import gtk

class App(gtk.Window):

    def __init__(self):
        super(App, self).__init__()

        self.set_title("HBox Layout App")
        self.set_size_request(640, 360)
        self.set_position(gtk.WIN_POS_CENTER)

        # membuat kontainer hbox
        hbox = gtk.HBox(homogeneous=False, spacing=5)

        # membuat button
        btn_ok = gtk.Button("OK")
        btn_ok.set_size_request(70, 30)
        btn_close = gtk.Button("Close")

        hbox.add(btn_ok)
        hbox.add(btn_close)

        # tambahkan layout hbox ke window
        self.add(hbox)

        self.connect("destroy", gtk.main_quit)
        self.show_all()

App()
gtk.main()


import pickle
from argparse import ArgumentParser

import numpy as np
import pandas as pd
from rdkit.Chem import MolFromMolBlock

parser = ArgumentParser()
parser.add_argument('--removeHs', '-k', action='store_true', help='remove H atoms when generating mol')

if __name__ == '__main__':
    args = parser.parse_args()

    ids = []
    mols = []
    for i in range(1, 133886):
        ids.append(f'dsgdb9nsd_{i:06}')
        try:
            with open(f'./data/input/structures/dsgdb9nsd_{i:06}.mol', 'r') as mol:
                mols.append(MolFromMolBlock(mol.read(), removeHs=args.removeHs))
        except:
            mols.append(np.nan)

    df = pd.DataFrame()
    df['ids'] = ids
    df['mols'] = mols

    if args.removeHs:
        with open('./data/input/mols_without_Hs.pickle', 'wb') as f:
            pickle.dump(df, f)
    else:
        with open('./data/input/mols_with_Hs.pickle', 'wb') as f:
            pickle.dump(df, f)


#
# Author: Vinhthuy Phan (04/2022)
# priority queue (max heap) of *hashable* data
#
class PriorityQueue:
    def __init__(self, which):
        if which not in ['min', 'max']:
            raise Exception('type must be either "min" or "max".')
        self.heap = []
        self.priority = {}
        self.index = {}
        self.priority_type = which

    def put(self, data, priority):
        if data in self.priority:
            print('{} exists. Use method "adjust" to adjust priorities.'.format(data))
            return
        self.heap.append(data)
        i = len(self.heap) - 1
        self.index[data] = i
        self.priority[data] = priority
        self.percolate_up(i)

    def get(self):
        if len(self.heap)==0:
            return
        item_priority = self.priority[self.heap[0]]
        item = self.heap[0]

        self.index[self.heap[-1]] = 0
        self.index.pop(self.heap[0])

        self.priority.pop(self.heap[0])

        self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0]

        self.heap.pop(-1)

        self.percolate_down(0)

        return item, item_priority

    def adjust(self, data, priority):
        if data not in self.priority:
            print(data, 'is not in the queue.')
            return
        self.priority[data] = priority
        i = self.index[data]
        self.percolate_up(i)
        if i == self.index[data]:
            self.percolate_down(i)

    def is_better(self, a, b):
        if self.priority_type == 'max':
            return a>b
        else:
            return a<b

    def percolate_up(self, i):
        while i>0:
            pid = (i-1)//2
            if self.is_better(self.priority[self.heap[i]], self.priority[self.heap[pid]]):
                self.index[self.heap[pid]], self.index[self.heap[i]] = self.index[self.heap[i]], self.index[self.heap[pid]]
                self.heap[pid], self.heap[i] = self.heap[i], self.heap[pid]
                i = pid
            else:
                break

    def percolate_down(self, i):
        n = len(self.heap)
        while i*2+1 < n:
            lc = i*2 + 1
            rc = i*2 + 2
            if rc < n:
                if self.is_better(self.priority[self.heap[lc]], self.priority[self.heap[rc]]):
                    idx = lc
                else:
                    idx = rc
            else:
                idx = lc
            if self.is_better(self.priority[self.heap[i]], self.priority[self.heap[idx]]):
                return
            self.index[self.heap[i]], self.index[self.heap[idx]] = self.index[self.heap[idx]], self.index[self.heap[i]]
            self.heap[idx], self.heap[i] = self.heap[i], self.heap[idx]
            i = idx

    def __len__(self):
        return len(self.heap)

    def __contains__(self, data):
        return data in self.priority

    def __getitem__(self, data):
        return self.priority[data] if data in self.priority else None

    def __setitem__(self, data, priority):
        if data in self.priority:
            self.adjust(data, priority)
        else:
            self.put(data, priority)

    def debug(self):
        print('heap', self.heap, 'len =', len(self.heap))
        print('index', self.index, 'len=', len(self.index))
        print('priority', self.priority, 'len=', len(self.priority))
        print('priorities:', sorted(self.priority.values()))
        print()


from urlparse import urlparse
import httplib
import socket

# this class will return the end url of a link shortener
# does not work with multi-level shortening (un-covered border case)
class link_lengthener():

    # initialize dictionary to optimize against re-querying
    # Parameters:
    # short: list of strings, known link shorteners
    def __init__(self, short):
        self.seen = {}
        self.short = short

    # Parameters:
    # url: string of url to extend
    def extend(self, url):
        # url needs to start with http(s) for parser to work
        if "://" not in url:
            url = "http://" + url
        o = urlparse(url)

        # first check if server is a shortener, if so return
        if o.netloc not in self.short:
            return {'response':"Not Shortened", 'url':url}

        path = '/' if o.path=='' else o.path
        # check to see if url has already been queried
        if (o.netloc + path) in self.seen:
            return self.seen[o.netloc + path]
        # if not, try to query server and get response
        else:
            url_dict = {}
            try:
                r = get_r(o.scheme, o.netloc, path)
                resp_str = ("HTTP/" + str(r.version)[0:1] + "."
                    + str(r.version)[1:2] +" "+ str(r.status) + " " + r.reason)
                # build dictionary
                url_dict['response'] = resp_str
                # if the status code indicates a re-direct (3xx)
                if r.status / 100 == 3:
                    url_dict['url'] = r.getheader('location')
                # if status code indicates OK (1xx or 2xx)
                elif r.status / 100 in (1,2):
                    url_dict['url'] = o.scheme + "://" + o.netloc + path
                # if status code indicates req or server error (4xx or 5xx)
                # of if server returns invalid status code
                else:
                    url_dict['url'] = ''
            # not a valid server
            except socket.gaierror:
                url_dict['url'] = ''
                url_dict['response'] = "unknown host"

        # add info to seen and return
        self.seen[o.netloc + path] = url_dict
        return url_dict

# Exception to use in case of not HTTP link
class NotHTTP(Exception):
    pass

# function to get response
def get_r(scheme, server, path):
    if scheme.upper() == 'HTTPS':
        connection = httplib.HTTPSConnection(server)
    elif scheme.upper() == 'HTTP':
        connection = httplib.HTTPConnection(server)
    else:
        raise NotHTTP("Link must be HTTP(S), not " + o.scheme)
    connection.request("HEAD", path)
    response = connection.getresponse()
    connection.close()
    return response


""" Tests for `typing_json.typechecking.to_json_obj` """
# pylint: disable = line-too-long, invalid-name, missing-docstring

# standard imports
import json
import typing
from typing import Union, Optional, List, Tuple, Set, FrozenSet, Mapping, Dict, NamedTuple, Deque
from decimal import Decimal
from collections import deque, OrderedDict

# external dependencies
from typing_extensions import Literal, TypedDict

# internal imports
from typing_json.typechecking import TYPECHECKABLE_BASE_TYPES
from typing_json.encoding import to_json_obj, JSON_BASE_TYPES
from typing_json.decoding import from_json_obj, JSON_BASE_TYPES

# (bool, int, float, str, type(None))
NONENCODABLE_BASE_TYPES = tuple(t for t in TYPECHECKABLE_BASE_TYPES if t not in JSON_BASE_TYPES+(Decimal,))

def failure_callback(message: str) -> None:
    print(message)

def test_from_json_obj_typeerrors():
    """ Checks that `from_json_obj` raises `TypeError` on non-typecheckable types or non-json-encodable types.
    """
    class NonTypechekableT:
        name: str
        val: int
        def __init__(self, name, val):
            self.name = name
            self.val = val
    x = NonTypechekableT("x", 0)
    try:
        from_json_obj(x, NonTypechekableT)
        assert False
    except TypeError:
        assert True

BASETYPES_ENCODINGS = [
    (True, bool, True),
    (1, int, 1),
    (1.5, float, 1.5),
    ("hello", str, "hello"),
    (None, type(None), None),
    (None, None, None),
    (Decimal("1.0"), Decimal, 1),
    (Decimal("1.5"), Decimal, "1.5"),
    (True, Literal[True, 1.5, None], True),
    (1.5, Literal[True, 1.5, None], 1.5),
    (None, Literal[True, 1.5, None], None),
    (True, Union[bool, float, Decimal], True),
    (1.5, Union[bool, float, Decimal], 1.5),
    (Decimal("1.0"), Union[bool, None, Decimal], 1),
    (Decimal("1.5"), Union[bool, None, Decimal], "1.5"),
    (1, int, Decimal(1)),
    (1, int, Decimal("1.0")),
]

def test_from_json_obj_basetypes():
    """ Test `to_json_obj` on JSON base types and `decimal.Decimal`. """
    for val, t, encoding in BASETYPES_ENCODINGS:
        assert from_json_obj(encoding, t) == val

def test_from_json_obj_numbers():
    assert from_json_obj(1.5, Decimal) == Decimal(1.5)
    assert from_json_obj(1, float) == 1.0
    assert from_json_obj(Decimal("1.5"), float) == 1.5
    assert from_json_obj(Decimal("1.0"), float) == 1.0
    try:
        from_json_obj(Decimal("1.5"), float, cast_decimal=False)
        assert False
    except TypeError:
        assert True

from enum import Enum
class EnumT(Enum):
    # pylint:disable=all
    Red = 0
    Green = 1
    Blue = 2

def test_from_json_obj_enums():
    assert from_json_obj("Red", EnumT) == EnumT.Red

def test_from_json_obj_lists():
    """ Checks that lists are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, List[int])
    assert isinstance(val, list)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))

def test_from_json_obj_tuples1():
    """ Checks that fixed-length tuples are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, Tuple[int, int, int])
    assert isinstance(val, tuple)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))

def test_from_json_obj_tuples2():
    """ Checks that variadic tuples are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, Tuple[int, ...])
    assert isinstance(val, tuple)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))

def test_from_json_obj_deque():
    """ Checks that dequeues are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, Deque[int])
    assert isinstance(val, deque)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))

def test_from_json_obj_set():
    """ Checks that dequeues are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, Set[int])
    assert isinstance(val, set)
    assert set(val) == set(encoding)

def test_from_json_obj_frozenset():
    """ Checks that dequeues are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, FrozenSet[int])
    assert isinstance(val, frozenset)
    assert set(val) == set(encoding)

DICT_ENCODINGS = [
    ({str(i): i for i in range(3)}, Dict[str, int], {str(i): i for i in range(3)}),
    ({str(i): i for i in range(3)}, Mapping[str, int], {str(i): i for i in range(3)}),
    ({str(i): i for i in range(3)}, Dict[Literal["0", "1", "2"], int], {str(i): i for i in range(3)}),
    ({str(i): i for i in range(3)}, Mapping[Literal["0", "1", "2"], int], {str(i): i for i in range(3)}),
    ({EnumT.Red: 0, EnumT.Green: 1, EnumT.Blue: 2}, Dict[EnumT, int], {"Red": 0, "Green": 1, "Blue": 2}),
    ({EnumT.Red: 0, EnumT.Green: 1, EnumT.Blue: 2}, Mapping[EnumT, int], {"Red": 0, "Green": 1, "Blue": 2}),
    ({tuple(j for j in range(i)): i for i in range(3)}, Dict[Tuple[int, ...], int], {json.dumps([j for j in range(i)]): i for i in range(3)}),
    ({tuple(j for j in range(i)): i for i in range(3)}, Mapping[Tuple[int, ...], int], {json.dumps([j for j in range(i)]): i for i in range(3)}),
]

def test_from_json_obj_dicts():
    """ Checks that dicts are decoded into dicts with the correct key/value pairs. """
    def _assert_eq_dicts(d1, d2):
        assert isinstance(d1, dict)
        assert isinstance(d2, dict)
        assert len(d1) == len(d2)
        assert set(d1.keys()) == set(d2.keys())
        assert all(d1[key] == d2[key] for key in d1)
    for val, t, encoding in DICT_ENCODINGS:
        _assert_eq_dicts(from_json_obj(encoding, t), val)

ORDERED_DICT_ENCODINGS = [
    (OrderedDict([(str(i), i) for i in range(3)]), typing.OrderedDict[str, int], OrderedDict([(str(i), i) for i in range(3)])),
    (OrderedDict([(str(i), i) for i in range(3)]), typing.OrderedDict[Literal["0", "1", "2"], int], OrderedDict([(str(i), i) for i in range(3)])),
    (OrderedDict([(EnumT.Red, 0), (EnumT.Green, 1), (EnumT.Blue, 2)]), typing.OrderedDict[EnumT, int], OrderedDict([("Red", 0), ("Green", 1), ("Blue", 2)])),
    (OrderedDict([(tuple(j for j in range(i)), i) for i in range(3)]), typing.OrderedDict[Tuple[int, ...], int], OrderedDict([(json.dumps([j for j in range(i)]), i) for i in range(3)])),
]

def test_from_json_obj_ordereddicts():
    """ Checks that dicts are decoded into dicts with the correct key/value pairs. """
    def _assert_eq_ordered_dicts(d1, d2):
        assert isinstance(d1, OrderedDict)
        assert isinstance(d2, OrderedDict)
        assert len(d1) == len(d2)
        assert tuple(d1.keys()) == tuple(d2.keys())
        assert all(d1[key] == d2[key] for key in d1)
    for val, t, encoding in ORDERED_DICT_ENCODINGS:
        _assert_eq_ordered_dicts(from_json_obj(encoding, t), val)

class NamedTupleExampleT(NamedTuple):
    name: str
    value: Union[int, float]
    flag: bool = False

class NamedTupleNastyExampleT(NamedTuple):
    name: str
    value: Dict[str, float]
    flag: bool = False

def test_is_json_encodable_namedtuple():
    """
        Tests the encoding of namedtuples.
    """
    t = NamedTupleExampleT("t", 1)
    t_encoding = OrderedDict([("name", "t"), ("value", 1)])
    assert from_json_obj(t_encoding, NamedTupleExampleT) == t
    nt = NamedTupleNastyExampleT("t", {"x": 1.0, "y": 0.0})
    nt_encoding_list = ["t", {"x": Decimal("1.0"), "y": 0}]
    assert from_json_obj(nt_encoding_list, NamedTupleNastyExampleT) == nt
    nt_encoding_list_long = ["t", {"x": Decimal("1.0"), "y": 0}, False]
    assert from_json_obj(nt_encoding_list_long, NamedTupleNastyExampleT) == nt
    try:
        nt_encoding_list_too_long = ["t", {"x": Decimal("1.0"), "y": 0}, False, 1]
        from_json_obj(nt_encoding_list_too_long, NamedTupleNastyExampleT) == nt
    except TypeError:
        assert True

WRONG_TYPE_ENCODINGS = [
    (bool, 1),
    (int, True),
    (float, "hello"),
    (str, 1.5),
    (type(None), 1),
    (None, 1),
    (Decimal, "hi"),
    (EnumT, 1.2),
    (EnumT, "Yellow"),
    (List[int], "hello"),
    (Tuple[int, ...], tuple([1, 2, 3])),
    (Tuple[int, int, int], tuple([1, 2, 3])),
    (Tuple[int, int, int], [1, 2]),
    (Deque[int], deque([1, 2, 3])),
    (Set[int], set([1, 2, 3])),
    (FrozenSet[int], frozenset([1, 2, 3])),
    (Literal[1,2,3], "1.0"),
    (Union[int, float], False),
    (Dict[str, int], [1, 2, 3]),
    (Mapping[str, int], [1, 2, 3]),
    (typing.OrderedDict[str, int], [1, 2, 3]),
    (Dict[str, int], {1: 1, 2: 2, 3: 3}),
    (Mapping[str, int], {1: 1, 2: 2, 3: 3}),
    (typing.OrderedDict[str, int], OrderedDict({1: 1, 2: 2, 3: 3})),
    (NamedTupleExampleT, ("t", 1)),
    (NamedTupleExampleT, OrderedDict([("name", "t"), ("values", [1, 2, 3])])),
    (NamedTupleExampleT, OrderedDict([("name", "t"), ("value", 1), ("blah", None)])),
    (NamedTupleExampleT, OrderedDict([("name", "t")])),
]

def test_from_json_obj_wrong_type():
    """ Test `to_json_obj` on wrong encodings for JSON base types and `decimal.Decimal`. """
    for t, encoding in WRONG_TYPE_ENCODINGS:
        try:
            from_json_obj(encoding, t)
            assert False, "Should not be decoding %s as %s."%(str(encoding), str(t))
        except TypeError:
            assert True

def test_from_json_obj_large_collections_namedtuple():
    class Pair(NamedTuple):
        left: int
        right: int
    large_list: List[Pair] = []
    for i in range(1000):
        large_list.append(Pair(i, i+1))
    assert from_json_obj(to_json_obj(large_list, List[Pair], namedtuples_as_lists=False), List[Pair]) == large_list
    assert from_json_obj(to_json_obj(large_list, List[Pair], namedtuples_as_lists=True), List[Pair]) == large_list

def test_from_json_typed_dict():
    class Pair(TypedDict, total=True):
        left: int
        right: int
    assert from_json_obj({"left": 0, "right": 1}, Pair) == {"left": 0, "right": 1}
    try:
        from_json_obj("not a dict", Pair)
        assert False, "Should not be decoding string as TypedDict."
    except TypeError:
        assert True
    try:
        from_json_obj({"left": 0}, Pair)
        assert False, "Should not be decoding dict with missing key as TypedDict (total=True)."
    except TypeError:
        assert True
    try:
        from_json_obj({"left": 0, "right": 1, "center": 2}, Pair)
        assert False, "Should not be decoding dict with extra key as TypedDict (total=True)."
    except TypeError:
        assert True
    class PartialPair(TypedDict, total=False):
        left: int
        right: int
    try:
        from_json_obj({"left": 0}, PartialPair)
        assert True, "Should be decoding dict with missing key as TypedDict (total=False)."
    except TypeError:
        assert False


# 예산

# 문제 설명 : https://programmers.co.kr/learn/courses/30/lessons/12982
# 최대한 많은 부서의 물품을 구매하기 위함.
# 각 부서가 신청한 금액만큼을 모두 지원해야 함.
# ex) 1000원을 신청한 부서에는 정확히 1000원을 지원해야하며
#     1000원보다 적은 금액을 지원할 수 없음.
# 부서별 신청한 금액이 들어있는 배열 d, 예산 budget

# 예상 풀이
# 배열 d를 오름차순으로 정렬후 하나씩 더한값이
# 배열 budget을 넘지않는 부서의 개수를 구하면 됨.

# 문제 풀이(1)

def solution(d, budget):
    answer = 0
    hap = 0

    d.sort()

    for i in d:
        hap += i
        if hap > budget:
            break
        else:
            answer += 1

    return answer

print(solution([1,3,2,5,4], 9))     # 3
print(solution([2,2,3,3], 10))      # 4


import glob
import numpy as np
import cv2

# 作成したヒートマップを256*256にリサイズ
for name in glob.glob('./*.png'):
    # 画像読み込み (ファイル名に日本語が含まれていない場合)
    # map = cv2.imread(name)

    # 画像読み込み (ファイル名に日本語が含まれている場合)
    buf2 = np.fromfile(name, dtype=np.uint8)
    map = cv2.imdecode(buf2, cv2.IMREAD_UNCHANGED)

    # 画像のリサイズ処理
    map_resized = cv2.resize(map, dsize=(256, 256))

    # 画像の保存 (ファイル名に日本語が含まれていない場合)
    # cv2.imwrite(name, map_resized)

     # 画像の保存 (ファイル名に日本語が含まれている場合)
    result, n = cv2.imencode('.png', map_resized)
    with open(name, mode='w+b') as f:
        n.tofile(f)


number = int(input("Enter the number of items: "))
total=0
for i in range(number):

    price=float(input("The price of each item:"))
    total=total+price
    if total>100:
        payment=total*0.9
    else:payment=total
    print("Each price of items is",price)
print("The number of items are:",number,"The payment is:",payment)


romans = open('resources/p089_roman.txt', 'r').readlines()

def romanToInt(s):
    roman = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
        'IV': 4,
        'IX': 9,
        'XL': 40,
        'XC': 90,
        'CD': 400,
        'CM': 900
    }
    i = 0
    num = 0
    while i < len(s):
        if i+1 < len(s) and s[i:i+2] in roman:
            num += roman[s[i:i+2]]
            i += 2
        else:
            num += roman[s[i]]
            i +=1
    return num

def intToRoman(num):
    m = ["", "M", "MM", "MMM", "MMMM"]
    c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
    x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
    i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

    thousands = m[num // 1000]
    hundreds = c[(num % 1000) // 100]
    tens = x[(num % 100) // 10]
    ones = i[num % 10]
    ans = (thousands + hundreds + tens + ones)
    return ans

old, new = 0, 0
for roman in romans:
    roman = roman.strip()
    rti = romanToInt(roman)
    itr = intToRoman(rti)
    old += len(roman)
    new += len(itr)
    print(roman, rti, itr)
print(old - new)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def allPossibleFBT(self, N: int) -> List[TreeNode]:
        if N % 2 == 0:
            return []
        dp = [[] for _ in range(N + 1)]
        dp[1] = [TreeNode(0)]
        for i in range(3, N + 1, 2):
            for j in range(1, i, 2):
                k = i - j - 1
                for l in dp[j]:
                    for r in dp[k]:
                        root = TreeNode(0)
                        root.left = l
                        root.right = r
                        dp[i].append(root)
        return dp[N]