from datetime import datetime
from typing import Union, List, Tuple, Any

import httpx
import pytz
from rasa_sdk import Tracker

from actions import config
from actions.config import BASE_CATALOG_URL, BASE_ORDER_URL, CART_URL, BASE_URL
from actions.utils.time_utils import parse_period

ADDRESS_FORMAT = "{address_line_1}, {locality}, {administrative_district_level_1} {postal_code}, {country}"
ADDRESS_FORMAT_WITHOUT_ADL1 = "{address_line_1}, {locality}, {postal_code}, {country}"

def resolve_item_from_variant(res_variant, items):
    if res_variant is None or items is None:
        return None

    for item in items:
        for variant in item['item_data']['variations']:
            if variant['id'] == res_variant['id']:
                return item

    return None

def resolve_category_from_item(res_item, categories):
    if res_item is None or categories is None:
        return None

    for category in categories:
        if category['id'] == res_item['item_data']['category_id']:
            return category

    return None

class Square:
    def __init__(self, tracker: Tracker):
        _metadata = tracker.latest_message.get("metadata")
        if _metadata.get('instaline') and _metadata.get('instaline').get('location'):
            self.location = _metadata.get('instaline').get('location')
        elif tracker.get_latest_input_channel() == 'instaline':
            raise ValueError("location metadata is required.")
        else:
            self.location = config.FALLBACK_LOCATION_ID

        if _metadata.get('instaline') and _metadata.get('instaline').get('vendor'):
            self.vendor = _metadata.get('instaline').get('vendor')
        elif tracker.get_latest_input_channel() == 'instaline':
            raise ValueError("vendor metadata is required.")
        else:
            self.vendor = config.FALLBACK_VENDOR_ID

    def get_catalog(self):
        return httpx.get(BASE_CATALOG_URL, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })

    def menu_item_exists(self, item_name: str):
        res = httpx.get(BASE_CATALOG_URL + f"/search/{item_name}", params={
            'location_id': self.location,
            'vendor_id': self.vendor
        }, timeout=30)
        return res.json() if res.status_code == httpx.codes.OK else {'objects': []}

    def match_menu_item(self, item: str):
        pass

    def create_order(self, item, quantity, user_id):
        headers = {
            "accept": "application/json",
            "cache-control": "no-cache",
            "content-type": "application/json",
        }

        data = {
            "user_id": str(user_id),
            "items": [{"id": item['item_data']['variations'][0]["id"], "quantity": quantity}],
        }

        response = httpx.post(f"{BASE_ORDER_URL}/create", headers=headers, json=data, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })

        # Return total amount
        # Order id
        return response.json()

    # def add_notes(self, user_id, notes):
    #     get_cart_id = httpx.get(url=CART_ID_URL + user_id, params={
    #         'location_id': self.location,
    #         'vendor_id': self.vendor
    #     })
    #     response = get_cart_id.json()
    #     if len(response) > 0:
    #         res = response[0]
    #         response_user_id = res['user_id']
    #         if response_user_id == user_id:
    #             # previous_item = res['items'][-1]
    #             res['items'][-1]['notes'] = notes
    #         data = {
    #             "client_modified": datetime.now().isoformat(),
    #             "id": res['id'],
    #             "items": res['items']
    #         }
    #         response = httpx.post(url=CART_URL + user_id, json=data, timeout=30, params={
    #                     'location_id': self.location,
    #                     'vendor_id': self.vendor
    #                     })
    #         return response.json()

    def save_to_cart(self, item, quantity, user_id):
        get_cart_id = httpx.get(url=CART_URL + user_id, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })

        res = get_cart_id.json()
        # print("cart id response")
        # print(res)

        if not get_cart_id.is_error and res:
            cart = res
            cart_id = cart['id']
            cart_items = cart['items']

            catalog_item_id = item['id']
            catalog_variation_id = item['item_data']['variations'][0]["id"]
            display_name = item['item_data']['name']
            try:
                int_quantity = int(quantity)
            except Exception as e:
                raise e
            for each_item in cart_items:
                if each_item['catalog_variation_id'] == catalog_variation_id:
                    each_item['quantity'] = each_item['quantity'] + int_quantity
                    int_quantity = 0
                    break

            if int_quantity > 0:
                value = {
                    "catalog_item_id": catalog_item_id,
                    "catalog_variation_id": catalog_variation_id,
                    "display_name": display_name,
                    "notes": "more soup",
                    "quantity": quantity
                }
                cart_items.append(value)
            data = {
                "client_modified": datetime.now().isoformat(),
                "id": cart_id,
                "items": cart_items
            }

        else:
            if get_cart_id.is_error and get_cart_id.status_code != 404:
                raise Exception(get_cart_id.json())
            data = {
                "client_modified": datetime.now().isoformat(),
                "items": [
                    {
                        "catalog_item_id": item['id'],
                        "catalog_variation_id": item['item_data']['variations'][0]["id"],
                        "display_name": item['item_data']['name'],
                        "notes": "more soup",
                        "quantity": quantity
                    }
                ],
            }
        # print("data")
        # print(data)
        response = httpx.post(url=CART_URL + user_id, json=data, timeout=30, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })
        return response.json()

    def remove_from_cart(self, item, quantity, user_id):
        get_cart_id = httpx.get(url=CART_URL + user_id, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })

        res = get_cart_id.json()
        # print("cart id response")
        # print(res)

        if res:
            cart = res
            cart_id = cart['id']
            cart_items = cart['items']

            catalog_item_id = item['id']
            catalog_variation_id = item['item_data']['variations'][0]["id"]
            try:
                int_quantity = int(quantity)
            except Exception as e:
                raise e
            for pos, each_item in enumerate(cart_items):
                if each_item['catalog_item_id'] == catalog_item_id \
                        and each_item['catalog_variation_id'] == catalog_variation_id:
                    each_item['quantity'] = each_item['quantity'] - int_quantity
                    if each_item['quantity'] <= 0:
                        each_item['quantity'] = 0
                        # del cart_items[pos]
                    int_quantity = 0
                    break

            # if int_quantity > 0:
            #     value = {
            #         "catalog_item_id": catalog_item_id,
            #         "catalog_variation_id": catalog_variation_id,
            #         "display_name": display_name,
            #         "notes": "more soup",
            #         "quantity": quantity
            #     }
            #     cart_items.append(value)
            data = {
                "client_modified": datetime.now().isoformat(),
                "id": cart_id,
                "items": cart_items
            }

            # else:
            #     data = {
            #         "client_modified": datetime.now().isoformat(),
            #         "items": [
            #             {
            #                 "catalog_item_id": item['id'],
            #                 "catalog_variation_id": item['item_data']['variations'][0]["id"],
            #                 "display_name": item['item_data']['name'],
            #                 "notes": "more soup",
            #                 "quantity": quantity
            #             }
            #         ],
            #     }
            # print("data")
            # print(data)
            # response = httpx.post(url=cart_url, data=data, headers={'Authorization': 'Bearer {}'.format(generate_token())})
            response = httpx.post(url=CART_URL + user_id, json=data, timeout=30, params={
                'location_id': self.location,
                'vendor_id': self.vendor
            })
            # print(response.json())
            return response.json()
        else:
            return []

    def show_location(self):
        # loc_endpoint = base_url + "/api/location/L08KM4B56KJK1"
        loc_endpoint = BASE_URL + "/api/location/" + self.location
        req = httpx.get(loc_endpoint, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })
        res = req.json()
        data = res['location']['address']
        if 'administrative_district_level_1' in data:
            address = ADDRESS_FORMAT.format(**data)
        else:
            address = ADDRESS_FORMAT_WITHOUT_ADL1.format(**data)
        return address

    def get_location_data(self):
        # loc_endpoint = base_url + "/api/location/L08KM4B56KJK1"
        loc_endpoint = BASE_URL + "/api/location/" + self.location
        req = httpx.get(loc_endpoint, params={
            'location_id': self.location,
            'vendor_id': self.vendor
        })
        res = req.json()
        return res

    def get_business_hours_formatted(self):
        location_data = self.get_location_data()
        data = location_data['location']['business_hours']['periods']
        location_tz = pytz.timezone(location_data['location']['timezone'])

        str_shown = ""
        for item in data:
            start = parse_period(item['start_local_time'], location_tz, item['day_of_week'])
            start_str = start.strftime('%H:%M')

            end = parse_period(item['end_local_time'], location_tz, item['day_of_week'])
            end_str = end.strftime('%H:%M')

            period = item['day_of_week'] + " " + start_str + "-" + end_str + "|\n"
            str_shown = str_shown + period
        return str_shown

    def resolve_item_slot(self, item_slot: Union[str, List[str]]) -> Tuple[Any, Any, Any, Any]:
        """
        1. If there is one item variant, pick that item variant
        2. If only one item pick item
        3. If there is one category pick the category
        4. Ask the user to rephrase

        User queries
        1. Categories
            - Ask for item and item variant
        2. Items
            - We ask for item variant / modifier
            - Move to the next step (quantity etc...)
        3. Item Variant
            - If there is one item variant, choose it as default
            - Confirm Add variant instead?

        :param item_slot: the item to resolve
        :return: returns Tuple(Category, Item, Variant, Options)

        return
        """

        if isinstance(item_slot, List):
            item_to_resolve = " ".join(item_slot)
        elif isinstance(item_slot, str):
            item_to_resolve = item_slot
        else:
            item_to_resolve = str(item_slot)

        result = self.menu_item_exists(item_to_resolve)
        if 'objects' not in result:
            return None, None, None, None
        res = result["objects"]

        variants = [x for x in res if x["type"] == "ITEM_VARIATION"]
        items = [x for x in res if x["type"] == "ITEM"]
        categories = [x for x in res if x["type"] == "CATEGORY"]

        res_variant = None
        res_item = None
        res_category = None

        if len(variants) == 1:
            res_variant = variants[0]
        for variant in variants:
            if str(variant['item_variation_data']['name']).lower() == item_to_resolve.lower():
                res_variant = variant
                break
        if res_variant is not None:
            res_item = resolve_item_from_variant(res_variant, items)
            res_category = resolve_category_from_item(res_item, categories)

            return res_variant, res_item, res_category, None

        if len(items) == 1:
            res_item = items[0]
        for item in items:
            if str(item['item_data']['name']).lower() == item_to_resolve.lower():
                res_item = item
                break
        if res_item is not None:
            res_category = resolve_category_from_item(res_item, categories)
            if len(res_item['item_data']['variations']) == 1:
                res_variant = items[0]['item_data']['variations'][0]
                return res_variant, res_item, res_category, None
            return res_variant, res_item, res_category, res_item['item_data']['variations']

        if len(categories) == 1:
            res_category = categories[0]
        for category in categories:
            if str(category['category_data']['name']).lower() == item_to_resolve.lower():
                res_category = category
                break
        if res_category is not None:
            category_items = [x for x in items if x['item_data']['category_id'] == res_category["id"]]
            if len(category_items) == 1:
                res_item = category_items[0]
                if len(res_item['item_data']['variations']) == 1:
                    res_variant = items[0]['item_data']['variations'][0]
                    return res_variant, res_item, res_category, None
            return res_variant, res_item, res_category, category_items

        res_options = []
        if len(variants) > 1:
            res_options.extend(variants)
        if len(items) > 1:
            res_options.extend(items)
        if len(categories) > 1:
            res_options.extend(categories)
        return res_variant, res_item, res_category, res_options if len(res_options) > 0 else None


#!/usr/bin/env python3

from sys import argv
from re import sub

script, command, filename = argv

file = open(filename, 'r')
content = file.read()

if command == 'lines':
    lines_list = content.split('\n')
    print(len(lines_list))

if command == 'words':
    no_points = sub('\.', ' ', content)
    no_new_lines = sub('\n', '', no_points)
    words_only = []
    words_and_spaces = no_new_lines.split(' ')
    for index, word in enumerate(words_and_spaces):
        if len(word) != 0:
            words_only.append(word)
    print(len(words_only))

if command == 'chars':
    count_chars = 0
    no_points = content.split('.')
    no_points_string = ' '.join(no_points)
    for char in no_points_string:
        count_chars += 1
    print(count_chars)

file.close()


import numpy as np
from numpy.linalg import inv, det
import time

# Checa abertura de arquivo

def ChecaArquivo():
    try:
        open("matrix.csv", 'r')
        return True
    except IOError:
        print("Error: Arquivo não existe.")
        return False

# Trata o valor

def Tratamento(x, t):
    x = x.replace('"', "")
    y = x.split(',')
    x = x.replace(y[0]+",", "")
    t.append(x)
    if x == '\n':
        t = list()
    return t

# Armazena em um arquivo

def Armazena(primeiro, t):
    arq2 = open("arquivos/"+str(primeiro)+".csv", 'w')
    for l in t:
        arq2.write(l)
    arq2.close()

start = time.time()

if (ChecaArquivo()):
    arq = open("matrix.csv", 'r')
    cont = primeiro = 0
    arquivo = 1
    t = list()

    for x in arq:
        if(primeiro == 0):
            primeiro += 1
            continue

        t = Tratamento(x, t)
        if len(t) == 0:
            break
        cont += 1

        if cont >= 12:
            Armazena(primeiro, t)
            primeiro += 1
            t.pop(0)

    # print(primeiro)
    primeiro = primeiro-1

    for i in range(1, primeiro):
        # print(i)
        matrix = np.genfromtxt("arquivos/"+str(i)+'.csv', delimiter=',')
        try:
            np.savetxt("inversas/"+str(i)+'.csv',
                       np.linalg.inv(matrix), delimiter=",")
            # print(np.linalg.inv(matrix))
        except:
            print("Inversa não pode ser calculada pois determinante é igual a zero")

end = time.time()
print(f"Tempo gasto pelo programa foi de  {end - start}")


import sys
import os
import configparser
sys.path.append(os.path.join(os.path.dirname(__file__), '..\\..\\ExchangeApi'))
import bitflyer_api_wrapper as bitflyer
import coincheck_api_wrapper as coincheck
import gmo_api_wrapper as gmo

class TradeApi:
    #---------------------------------------------------
    # コンストラクタ
    #---------------------------------------------------
    def __init__(self, exchange_name):
        api_key, api_secret = self.__get_api_key(exchange_name)
        if exchange_name == 'bitFlyer':
            self.exchange = bitflyer.BitflyerAPIWrapper(api_key, api_secret, 'BTC_JPY')
        elif exchange_name == 'Coincheck':
            self.exchange = coincheck.CoincheckAPIWrapper(api_key, api_secret, 'btc_jpy')
        elif exchange_name == 'GMO':
            self.exchange = gmo.GmoAPIWrapper(api_key, api_secret, 'BTC')

    #---------------------------------------------------
    # APIキーとシークレットをファイルから読み出す
    #---------------------------------------------------
    def __get_api_key(self, exchange_name):
        path = os.path.dirname(os.path.abspath(__file__))
        inifile = configparser.SafeConfigParser()
        inifile.read(os.path.join(path, "api_key.ini"))
        api_key = inifile.get(exchange_name, 'key')
        api_secret = inifile.get(exchange_name, 'secret')
        return api_key, api_secret

    #---------------------------------------------------
    # 成行買い
    #---------------------------------------------------
    def buy_market(self, size):
        self.__order('MARKET', 'BUY', 0, size)

    #---------------------------------------------------
    # 指値買い
    #---------------------------------------------------
    def buy_limit(self, price, size):
        self.__order('LIMIT', 'BUY', price, size)

    #---------------------------------------------------
    # 指値買いIFDSTOP付き
    #---------------------------------------------------
    def buy_limit_with_stop(self, price, size, stop_price):
        self.exchange.send_parentorders_ifd_stop('BUY', price, size, stop_price)

    #---------------------------------------------------
    # 成行売り
    #---------------------------------------------------
    def sell_market(self, size):
        self.__order('MARKET', 'SELL', 0, size)

    #---------------------------------------------------
    # 指値売り
    #---------------------------------------------------
    def sell_limit(self, price, size):
        self.__order('LIMIT', 'SELL', price, size)

    #---------------------------------------------------
    # 指値売りIFDSTOP付き
    #---------------------------------------------------
    def sell_limit_with_stop(self, price, size, stop_price):
        self.exchange.send_parentorders_ifd_stop('SELL', price, size, stop_price)

    #---------------------------------------------------
    # 注文
    #---------------------------------------------------
    def __order(self, order_type, side, price, size):
        self.exchange.send_childorders(order_type, side, price, size)

    #---------------------------------------------------
    # STOP注文
    #---------------------------------------------------
    def stop_order(self, side, price, size):
        ltp = self.get_fx_ltp()
        if side == 'BUY' and price < ltp:
            print('price < ltp')
            return
        elif side == 'SELL' and price > ltp:
            print('price > ltp')
            return
        self.exchange.send_parentorders_simple_stop(side, price, size)

    #---------------------------------------------------
    # 注文全キャンセル
    #---------------------------------------------------
    def cancel_all_orders(self):
        self.exchange.cancel_all_child_orders()

    #---------------------------------------------------
    # Tickerを取得
    #---------------------------------------------------
    def get_ticker(self):
        ltp, bid, ask = self.exchange.get_ticker()
        return ltp, bid, ask

    #---------------------------------------------------
    # 板情報を取得
    #---------------------------------------------------
    def get_order_books(self):
        self.exchange.get_order_books()
        return

    #---------------------------------------------------
    # 現在のポジションの
    # 方向、合計数量、SWAPポイント、平均約定価格、損益分岐価格を取得
    #---------------------------------------------------
    def get_current_position(self):
        cur_positions = self.exchange.get_positions()
        pos_sum = 0
        swap_sum = 0
        average = 0
        price_sum = 0

        for pos in cur_positions:
            pos_sum += float(pos['size'])
            swap_sum += float(pos['swap_point_accumulate'])
            price = float(pos['price'])
            size = float(pos['size'])
            price_sum += price
            average += (price * size)

        if pos_sum != 0:
            average /= pos_sum

        if len(cur_positions) == 0 :
            side = '-'
            even_price = 0
        elif cur_positions[0]['side'] == 'BUY' :
            side ='L'
            even_price = average + swap_sum
        else:
            side = 'S'
            even_price = average - swap_sum

        return side, pos_sum, swap_sum, average, even_price


import sys

import torch
from torch.nn import Module, PairwiseDistance

class ContrastiveLoss(Module):

    def __init__(self, margin=1.0):
        super(ContrastiveLoss, self).__init__()
        self.margin = margin

    def __call__(self, x1, x2, y_true, **kwargs):
        """
        :param margin:
        :param x1: N * D
        :param x2: N * D
        :param y_true: 0 for un-similar, 1 for similar
        :return:
        """
        assert len(x1.shape) == 2
        assert len(x2.shape) == 2
        assert len(y_true.shape) == 1
        assert y_true.shape[0] == x1.shape[0]

        pdist = PairwiseDistance(p=2)
        dist = pdist(x1, x2)
        loss = y_true * torch.pow(dist, 2) \
               + (1-y_true) * torch.pow(torch.clamp(self.margin - dist, min=0.0), 2)
        return torch.sum(loss)

if __name__ == '__main__':
    contrastive_loss = ContrastiveLoss(margin=1.0)
    import numpy as np
    np.random.seed(0)
    N = 10
    x1 = torch.tensor(np.random.rand(N, 16), dtype=torch.float32)
    x2 = torch.tensor(np.random.rand(N, 16), dtype=torch.float32)
    y_pred = [x1, x2]

    y1 = torch.tensor(np.random.rand(N, 1))
    y_zeros = torch.zeros((N, 1))
    y_ones = torch.ones((N, 1))

    y_true = torch.where(y1 > 0, y_ones, y_zeros)
    y_true = torch.squeeze(y_true)

    loss = contrastive_loss(x1, x2, y_true)
    print(loss.shape)
    print(loss)

    sys.exit()


import os
import random
import datetime

db = {}
stats = {
    "read_response_times": [],
    "read_errors": 0,
    "read_count": 0,
    "create_response_times": [],
    "create_errors": 0,
    "create_count": 0,
    "update_response_times": [],
    "update_errors": 0,
    "update_count": 0,
    "delete_response_times": [],
    "delete_errors": 0,
    "delete_count": 0,
    "cache_hit": 0,
}
last_push = {
    "read": datetime.datetime.now(),
    "create": datetime.datetime.now(),
    "update": datetime.datetime.now(),
    "delete": datetime.datetime.now(),
}

def read(key):

    print(f"Reading...")

    if random.randint(0, 30) > 10:
        stats["cache_hit"] += 1

    stats["read_response_times"].append(random.uniform(0.5, 1.0))
    if random.choice([True, False]):
        stats["read_errors"] += 1
    stats["read_count"] += 1
    try_send("read")

def create(key, value):

    print(f"Writing...")

    db[key] = value
    stats["create_response_times"].append(random.uniform(0.5, 1.0))
    if random.choice([True, False]):
        stats["create_errors"] += 1
    stats["create_count"] += 1
    try_send("create")

def update(key, value):

    print(f"Updating...")

    db[key] = value
    stats["update_response_times"].append(random.uniform(0.5, 1.0))
    if random.choice([True, False]):
        stats["update_errors"] += 1
    stats["update_count"] += 1
    try_send("update")

def delete(key):

    print(f"Deleting...")

    db.pop(key, None)
    stats["delete_response_times"].append(random.uniform(0.5, 1.0))
    if random.choice([True, False]):
        stats["delete_errors"] += 1
    stats["delete_count"] += 1
    try_send("delete")

def try_send(type_):

    print("try_send")

def clear(type_):
    stats[f"{type_}_response_times"] = []
    stats[f"{type_}_errors"] = 0
    stats["cache_hit"] = 0
    stats[f"{type_}_count"] = 0
    last_push[type_] = datetime.datetime.now()


#remember the () when printing!! for print is really print() -- it's a command uwu

print ("Mary had a little lamb.")
print ("Its fleece was white as %s." % 'snow') #why is snow a character and not a string?
print ("And everywhere that Mary went...")
print ("." * 10) #this will repeat the string 10 times lol

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

#the comma there, that adds a space. without it, you'll get "SyntaxError: invalid syntax"
print (end1 + end2 + end3 + end4 + end5 + end6, end7 + end8 + end9 + end10 + end11 + end12)

#and yes, this is different from the book. The two print lines just separate the word.

#this was super unfunny.


#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Matplotlib and numpy configuration
"""

# Relative import regardless of file nesting depth
import os, sys
path = os.getcwd().split(os.sep)
while len(path) and path[-1]!='notebooks': path = path[:-1]
sys.path.append(os.sep.join(path[:-1]))
datadir = os.sep.join(path[:-2]+['example data'])+os.sep
datafiles = sorted([
    f for f in os.listdir(datadir)
    if f.startswith('r') and f.endswith('.mat')])
print('Available files:\n\t'+'\n\t'.join(datafiles))
fitdir = os.sep.join(path+['hyperparameter_fits',''])
print('Fitted models in fitdir =',fitdir)

import pickle
import numpy
from lgcp.data  import *
from lgcp.kern  import *
from lgcp.infer import *
from lgcp.plot  import *
from lgcp.post  import *
from lgcp.sg    import *
from lgcp.gridsearch  import *

# Fonts
SMALL  = 7
MEDIUM = 8
BIGGER = 9
LARGE  = BIGGER
def configure_pylab():
    mpl.rcParams['figure.figsize'] = (8,2.5)
    mpl.rcParams['figure.dpi']   = 240
    mpl.rcParams['image.origin'] = 'lower'
    mpl.rcParams['image.cmap']   = 'magma'
    mpl.rcParams['font.size'           ]=SMALL  # controls default text sizes
    mpl.rcParams['axes.titlesize'      ]=MEDIUM # fontsize of the axes title
    mpl.rcParams['axes.labelsize'      ]=MEDIUM # fontsize of the x and y labels
    mpl.rcParams['xtick.labelsize'     ]=SMALL  # fontsize of the tick labels
    mpl.rcParams['ytick.labelsize'     ]=SMALL  # fontsize of the tick labels
    mpl.rcParams['legend.fontsize'     ]=SMALL  # legend fontsize
    mpl.rcParams['figure.titlesize'    ]=BIGGER # fontsize of the figure title
    mpl.rcParams['lines.solid_capstyle']='round'
    mpl.rcParams['savefig.dpi'         ]=140
    mpl.rcParams['figure.dpi'          ]=140
    mpl.rcParams['figure.facecolor'    ]='w'
    lw = .7
    mpl.rcParams['axes.linewidth'] = lw
    mpl.rcParams['xtick.major.width'] = lw
    mpl.rcParams['xtick.minor.width'] = lw
    mpl.rcParams['ytick.major.width'] = lw
    mpl.rcParams['ytick.minor.width'] = lw
    tl = 3
    mpl.rcParams['xtick.major.size'] = tl
    mpl.rcParams['xtick.minor.size'] = tl
    mpl.rcParams['ytick.major.size'] = tl
    mpl.rcParams['ytick.minor.size'] = tl
    numpy.seterr(all='ignore')
    numpy.set_printoptions(precision=10)
    numpy.seterr(divide='ignore', invalid='ignore');
configure_pylab();

# Heading plot configuration
colorNSEW = float32([
    [0.08,0.40,1.0], # North color
    [0.92,0.60,0.0], # South color
    [0.10,0.85,0.3], # East  color
    [0.90,0.15,0.7]  # West  color
])
cN,cS,cE,cW = colorNSEW
hE = 0
hS = pi/2
hW = pi
hN = 3*pi/2
NSEW = [hN,hS,hE,hW]
ESWNmix = mpl.colors.LinearSegmentedColormap.from_list('ESNWmix',float32([
    [ 72, 160, 230, 234, 220, 203, 170, 101,  56,  31,  27,  72],
    [194, 175, 155, 132,  93,  72,  75,  98, 128, 159, 193, 194],
    [ 92,  42,  12,  51, 131, 180, 196, 222, 235, 200, 138,  92]]).T/255)
ESWNmix.set_bad((1,1,1,0))


class MyShape:
    def __init__(self, square_side=None, length=None, width=None, radius=None):
        self.square_side = square_side
        self.length = length
        self.width = width
        self.radius = radius

    def getSquareArea(self):
        if self.square_side is not None:
            return self.square_side ** 2
        else:
            return "請輸入邊長"

    def getRectangleArea(self):
        if self.length is not None and self.width is not None:
            return self.length * self.width
        else:
            return "請輸入長寬"

    def getCircleArea(self):
        if self.radius is not None:
            return 3.14 * (self.radius ** 2)
        else:
            return "請輸入半徑"

shape1 = MyShape(square_side=10)
print("Square Area:", shape1.getSquareArea())

shape2 = MyShape(length=9, width=7)
print("Rectangle Area:", shape2.getRectangleArea())

shape3 = MyShape(radius=6)
print("Circle Area:", shape3.getCircleArea())


import json

import pandas as pd
import matplotlib.pyplot as plt
import requests
from bs4 import BeautifulSoup

file = open("ingredient_list.json", "r")
item_list = []

class Data:
    def __init__(self):
        self.adjusted = True
        self.item_counts = json.load(file)
        self.graph = "not set"
        self.dumped = []

    def remove_keyword(self):
        pass

    def add_count(self, item):
        items = item.split("and") if item.find("and") > 0 else [item]
        for item in items:
            if item in self.item_counts:
                self.item_counts[item] += 1
            else:
                self.dumped.append(item)

    def sort_counts(self, reverse=False):
        self.item_counts = dict(sorted(self.item_counts.items(), key=lambda x: x[1], reverse=reverse))

    def setUp_graph(self, threshold):
        values = []
        names = []
        threshold -= 1
        other_count = 0
        x = 0
        for i in self.item_counts:
            if x < threshold:
                names.append(i)
                values.append(self.item_counts[i])
            else:
                other_count += self.item_counts[i]
            x = x + 1
        values.append(other_count)
        names.append("other")
        self.graph = pd.DataFrame({'count': values}, index=names)

    def print_pie_chart(self):
        self.graph.plot.pie(y='count', figsize=(50, 50), fontsize=30)
        plt.show()
        plt.close()


#create one function to partition an array in two halves and the further into two halves
#play on index so that original array can be passed and updated
#create another function which receives indexes and sorts them
#the advantage is that original array is updated.. so no need to manage different variables

class MergeSort:
    '''Performs Merge Sort'''
    def __init__(self, seq):
        self.seq = seq

    def __merge(self, sta, mid, end):
        #program to merge/sort and update

        point_a = sta
        point_b = mid+1
        t_a = []
        while point_a <= mid and point_b <= end:
            if self.seq[point_a] > self.seq[point_b]:
                while (point_a <= mid and point_b <= end) and (self.seq[point_a] > self.seq[point_b]) :
                    t_a.append(self.seq[point_b])
                    point_b+=1
            else:
                t_a.append(self.seq[point_a])
                point_a+=1
                # point_b+=1
        while point_a <=mid:
            t_a.append(self.seq[point_a])
            point_a+=1
        while point_b <= end:
            t_a.append(self.seq[point_b])
            point_b+=1

        self.seq[sta:end+1] = t_a.copy()

    def __partition(self, sta, end):
        #program to partition the sequence into two
        # print(sta, end)
        if sta < end:
            mid = (sta + end)//2

            self.__partition(sta, mid)
            self.__partition(mid+1, end)
            self.__merge(sta, mid, end)

    def sort(self):
        '''driver function'''
        self.__partition(0, len(self.seq) - 1)
        return self.seq

arr = [2,1,3,4,5,2,3,1,5,6,3,2,3,45,3,23,4,41,1,4,7]

ms = MergeSort(arr)

print(ms.sort())


import os

import cv2

from deepstar.filesystem.transform_file import TransformFile
from deepstar.filesystem.transform_set_sub_dir import TransformSetSubDir
from deepstar.models.transform_model import TransformModel
from deepstar.models.transform_set_model import TransformSetModel
from deepstar.util.debug import debug
from deepstar.util.cv import overlay_transparent_image

class OverlayImageTransformSetSelectMergePlugin:
    """
    This class implements the OverlayImageTransformSetSelectMergePlugin class.
    """

    name = 'overlay_image'

    def transform_set_select_merge(self, transform_set_ids, opts):
        """
        This method merges one transform set with one image. This is to say
        that one image is overlaid onto every transform in a transform set and
        at a specified position.

        :param list(int) transform_set_ids: The transform set IDs.
        :param dict opts: The dict of options.
        :raises: ValueError
        :rtype: int
        """

        if len(transform_set_ids) != 1:
            raise ValueError('Exactly one transform set ID must be supplied')

        image_path_1 = opts.get('image-path', None)
        x1 = int(opts['x1']) if ('x1' in opts) else None
        y1 = int(opts['y1']) if ('y1' in opts) else None

        if image_path_1 is None or x1 is None or y1 is None:
            raise ValueError(
                'The image-path, x1 and y1 options are required but were not '
                'supplied')

        if not os.path.isfile(image_path_1):
            raise ValueError(
                f'The image path {image_path_1} does not exist or is not a '
                f'file')

        transform_set_id = transform_set_ids[0]

        transform_model = TransformModel()

        transform_set_id_ = TransformSetModel().insert('overlay_image', None,
                                                       None)

        p1 = TransformSetSubDir.path(transform_set_id_)

        os.makedirs(p1)

        p2 = TransformSetSubDir.path(transform_set_id)
        length = int(os.environ.get('MODEL_LIST_LENGTH', '100'))
        offset = 0

        image_1 = cv2.imread(image_path_1, cv2.IMREAD_UNCHANGED)

        while True:
            transforms = transform_model.list(transform_set_id,
                                              length=length, offset=offset,
                                              rejected=False)

            if not transforms:
                break

            for transform in transforms:
                transform_id = transform_model.insert(transform_set_id_, None,
                                                      None, 0)

                image_path_2 = TransformFile.path(p2, transform[0], 'jpg')

                image_2 = cv2.imread(image_path_2)

                image_3 = overlay_transparent_image(image_2, image_1, x1, y1)

                image_path_3 = TransformFile.path(p1, transform_id, 'jpg')

                cv2.imwrite(image_path_3, image_3,
                            [cv2.IMWRITE_JPEG_QUALITY, 100])

                debug(f'{image_path_1} and transform with ID '
                      f'{transform[0]:08d} at {image_path_2} merged as ID '
                      f'{transform_id:08d} at {image_path_3}', 4)

            offset += length

        return transform_set_id_


# !/usr/bin/env python3
# -*- encoding utf-8 -*-
"""
--------------------------------------------------------------------------------
    _3.py    |    manipulate and represent word vectors with Numpy and Scipy
--------------------------------------------------------------------------------

Author   : Simone Santoni, simone.santoni.1@city.ac.uk

Synopsis : This tutorial pursues the following learning goals:

           1. charting the semantic relations involving sets of lexical items
           2. familiarizing with 'whatlies,' a dedicated libraries for the
              visualization of word embeddings

To do    : None

"""

# %% load libraries
from whatlies import EmbeddingSet
from whatlies.language import SpacyLanguage

# %% load a model of the language 'via' whatlies
lang = SpacyLanguage("en_core_web_lg")

# %% create a list of lexical items
"""
let's see how animals (actors) map onto qualities (attributes)
"""
# sample animals
animals = ["cat", "dog", "mouse"]
# sample qualities
qualities = ["responsive", "loyal"]
# set of lexical items
items = animals + qualities

# %% browse the loaded model of the language, retrieve the vectors
#    and create and initialize an embedding sets (a class specific
#    to the library whatlies)
emb = EmbeddingSet(*[lang[item] for item in items])
# the position of animals should be relative to the word vectors
#   for 'smart' and 'loyal'
emb.plot_interactive(x_axis=emb["responsive"], y_axis=emb["loyal"])


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

import logging

from collections import namedtuple

Swatch = namedtuple('Swatch', ['name', 'color'])

brainindex_2d = {
    'swatches': [
        {
            'name': 'pineal',
            'color': '61bb46',
        },
        {
            'name': 'lesion',
        },
        {
            'name': 'lesion',
            'title': 'Lesion Area',
            'color': '#fdb827',
        },
        {
            'name': 'hypothalamus',
            'title': 'Hypothalamus',
            'color': '#61bb46',
        },
        {
            'name': 'bone',
            'title': 'Bone Area',
            'color': '#3e3d97',
        },
        {
            'name': 'fat',
            'title': 'Fat Area',
            'color': '#ee1f98',
        },
        {
            'name': 'pineal',
            'title': 'Pineal Area',
            'color': '#3d7a97',
        },
        {
            'name': 'kidney',
            'title': 'Kidney Area',
            'color': '#2804cc',
        },
        {
            'name': 'psoas-muscle',
            'title': 'Psoas Muscle',
            'color': '#f5821f',
        },
        {
            'name': 'other-muscle',
            'title': 'Other Muscle',
            'color': '#04b8cf',
        },
        {
            'name': 'spleen',
            'title': 'Spleen',
            'color': '#e03a3a',
        },
        {
            'name': 'other-r-o-i',
            'title': 'Other-r-o-i',
            'color': '#c2cf04',
        },
        {
            'name': 'bowel',
            'title': 'Bowel',
            'color': '#963d97',
        },
    ],
}

abdoindex_2d = {
    'swatches': [
        Swatch('lesion','#fdb827'),
        Swatch('liver','#61bb46'),
        Swatch('bone','#3e3d97'),
        Swatch('fat','#ee1f98'),
        Swatch('lung','#3d7a97'),
        Swatch('kidney','#2804cc'),
        Swatch('psoas-muscle','#f5821f'),
        Swatch('other-muscle','#04b8cf'),
        Swatch('spleen','#e03a3a'),
        Swatch('other-r-o-i','#c2cf04'),
        Swatch('bowel','#963d97'),
    ],
}

brainindex_2d = {
    'swatches': [
        Swatch('pineal', '#61bb46'),
        Swatch('lesion', '#fdb827'),
        Swatch('medulla', '#f5821f'),
        Swatch('midbrain', '#04b8cf'),
        Swatch('cystinside', '#c2cf04'),
        Swatch('potentialinfarctingarea', '#2804cc'),
        Swatch('infarctedarea', '#e03a3a'),
        Swatch('leftthalamus', '#963d97'),
        Swatch('hippocampus', '#3d7a97'),
        Swatch('hematoma', '#3e3d97'),
        Swatch('righthypothalamus', '#ee1f98'),
    ]
}

freelabel_2d = {
    'swatches': [
        Swatch('a', '#61bb46'),
        Swatch('lesion', '#fdb827'),
        Swatch('b', '#f5821f'),
        Swatch('c', '#04b8cf'),
        Swatch('other-r-o-i', '#c2cf04'),
        Swatch('d', '#2804cc'),
        Swatch('j', '#e03a3a'),
        Swatch('h', '#963d97'),
        Swatch('e', '#3d7a97'),
        Swatch('f', '#3e3d97'),
        Swatch('i', '#ee1f98'),
    ]
}

headandneck_2d = {
    'swatches': [
        Swatch('thyroid', '#61bb46'),
        Swatch('lesion', '#fdb827'),
        Swatch('cystinside', '#5c4d61'),
        Swatch('muscle', '#f5821f'),
        Swatch('thymus', '#04b8cf'),
        Swatch('other-r-o-i', '#c2cf04'),
        Swatch('trachea', '#2804cc'),
        Swatch('left-parotid', '#e03a3a'),
        Swatch('right-parotid', '#963d97'),
        Swatch('lymph-node', '#3d7a97'),
        Swatch('bone', '#3e3d97'),
        Swatch('fat', '#ee1f98'),
    ]
}

mskidnex_2d = {
    'swatches': [
        Swatch('tendon', '#61bb46'),
        Swatch('lesion', '#fdb827'),
        Swatch('epiphysisofbone', '#f5821f'),
        Swatch('muscle-a-right', '#04b8cf'),
        Swatch('muscle-a-left', '#0e2124'),
        Swatch('muscle-b-right', '#100411'),
        Swatch('muscle-b-left', '#04cf7a'),
        Swatch('other-r-o-i', '#c2cf04'),
        Swatch('ligament', '#2804cc'),
        Swatch('cancellous-bone', '#e03a3a'),
        Swatch('cortical-bone', '#963d97'),
        Swatch('metaphysis', '#3d7a97'),
        Swatch('diaphysis', '#3e3d97'),
        Swatch('fat', '#ee1f98'),
    ]
}

thorax_2d = {
    'swatches': [
        Swatch('thymus', '#61bb46'),
        Swatch('lesion', '#fdb827'),
        Swatch('heart-muscle', '#f5821f'),
        Swatch('other-muscle', '#04b8cf'),
        Swatch('other-r-o-i', '#c2cf04'),
        Swatch('thyroid', '#2804cc'),
        Swatch('greatvessel', '#e03a3a'),
        Swatch('heart', '#963d97'),
        Swatch('lung', '#3d7a97'),
        Swatch('bone', '#3e3d97'),
        Swatch('fat', '#ee1f98'),
    ]
}

class Models:

    def for_page(self, page):
        logging.info('Requesting model for page: {}'.format(page))
        if page.endswith('/2dabdoindex.html'):
            return aboindex_2d
        if page.endswith('/2dbrainindex.html'):
            return brainindex_2d
        if page.endswith('/2dfreelabel.html'):
            return freelabel_2d
        if page.endswith('/2dheadandneckindex.html'):
            return headandneck_2d
        if page.endswith('/2dmskindex.html'):
            return mskidnex_2d
        if page.endswith('/2dthoraxindex.html'):
            return thorax_2d


# coding=utf-8

__author__ = 'brianoneill'

from .lcdict import LCDict
from .six import add_metaclass

from abc import ABCMeta, abstractmethod

__all__ = [
    'LCDictBuilderABC',
]

@add_metaclass(ABCMeta)
class LCDictBuilderABC():
    """
    .. include:: _global.rst

    A class for automating multi-package / multi-module logging configuration.
    ``LCDictBuilderABC`` is an abstract base class: its metaclass is ``ABCMeta``,
    defined in ``_collections_abc.py`` of the standard library. You can't
    directly instantiate this class: it has an `abstractmethod`
    ``add_to_lcdict(lcd: LCDict)``. Every package or module that
    wants a say in the configuration of logging should define its own
    (sub*)subclass of ``LCDictBuilderABC`` implementing ``add_to_lcdict``.

    Once (and once only), the application should call the classmethod
    ``LCDictBuilderABC.build_lcdict(...)``, which returns an ``LCDict``.
    The parameters of ``build_lcdict`` are the same as those of ``LCDict.__init__``.
    The ``build_lcdict`` method does the following:

        * creates a new ``LCDict``, ``lcd``, with the parameters provided;
        * calls ``subcls.add_to_lcdict(lcd)`` on every (imported!) subclass
          ``subcls`` that implements ``add_to_lcdict``, in a breadth-first way;
        * returns ``lcd``, the logging config dict built by the previous
          steps.

    Your program should then call ``config()`` on the returned logging config
    dict.

    For example, given the following inheritance tree (where "<" means
    "is a superclass of"):

    .. code::

        LCDictBuilderABC < MainBuilder < BuilderModuleA
                                       < BuilderModuleB
                                       < BuilderPackage < BuilderSubPackage

    Assuming that all classes shown implement ``add_to_lcdict``, that method
    will be called first on ``MainBuilder``; then on
    ``BuilderModuleA``, ``BuilderModuleB``, and
    ``BuilderPackage``, in some order; then on ``BuilderSubPackage``.

    See the test ``test_lcdict_builder.py`` for multi-module examples of these
    capabilities.
    |hr|
    """
    @classmethod
    @abstractmethod
    def add_to_lcdict(cls, lcdict):                         # pragma: no cover
        """(abstractmethod) Customize the passed ``LCDict``.

        :param lcdict: an ``LCDict``

        ``build_lcdict`` calls this method on every ``LCDictBuilderABC``
        subclass that implements it, **in breadth-first order**.
        All implementations are passed the same
        object ``lcdict``. Implementations should call ``LCDict``
        methods on ``lcdict`` to augment and customize it.

        **Note**: Implementations should *not* call ``super().add_to_lcdict`` —
        it has already been called on ancestors by ``build_lcdict``!

        """
        pass

    @classmethod
    def build_lcdict(cls,
                     root_level='WARNING',
                     log_path='',
                     locking=False,
                     attach_handlers_to_root=False,
                     disable_existing_loggers=False):
        """A single method which creates a new ``LCDict`` with the options provided,
        and returns it after calling all ``add_to_lcdict`` methods with that object.
        Your program should call this method once (only), and then call ``config()``
        on the returned logging config dict.

        Parameters are as for ``LCDict.__init__``.

        This method creates an ``LCDict``, ``lcdict``, and calls
        ``subcls.add_to_lcdict(lcd)`` on all subclasses ``subcls``
        of ``LCDictBuilderABC`` which implement the method, in breadth-first
        order, passing the same ``LCDict`` instance to each.

        :return: the built ``LCDict``

        .. note::
            ``build_lcdict()`` will call ``add_to_lcdict`` only on
            ``LCDictBuilderABC`` subclasses that have actually been imported
            at the time ``build_lcdict()`` is called.
            Thus, make sure that your program has imported all such subclasses
            before it calls this method. If the contributions of the ``add_to_lcdict``
            method of some such subclass have no effect — its handlers and/or
            loggers do nothing — it may be because the subclass wasn't imported
            when ``build_lcdict()`` was called.
        """
        lcdict = LCDict(root_level=root_level,
                        log_path=log_path,
                        locking=locking,
                        attach_handlers_to_root=attach_handlers_to_root,
                        disable_existing_loggers=disable_existing_loggers)
        derived_classes = LCDictBuilderABC.__subclasses__()

        while derived_classes:
            subcls = derived_classes.pop()
            if 'add_to_lcdict' in vars(subcls):    # i.e. in subcls.__dict__
                subcls.add_to_lcdict(lcdict)
            derived_classes.extend(subcls.__subclasses__())

        return lcdict


import sys
sys.setrecursionlimit(100500)
sys.stdin = open('connect.in')
sys.stdout = open('connect.out', 'w')

def dfs(v, c):
	global color
	color[v] = c

	for to in e[v]:
		if (not color[to]):
			dfs(to, c)

n = int(input())
e = [[] for i in range(n)]
color = [0] * n

for i in range(n):
	e[i] = list(map(lambda x : int(x) - 1, input().split()))[1:]

cur = 1
for i in range(n):
	if not color[i]:
		dfs(i, cur)
		cur += 1
print(cur - 1)
print(*color)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import tensorflow.contrib.slim as slim
import os
import vgg
import copy

import numpy as np
import misc.utils as utils

# The maximimum step during generation
MAX_STEPS = 30

class ShowTellModel():

    def initialize(self, sess):
        # Initialize the variables
        sess.run(tf.global_variables_initializer())
        # Initialize the saver
        self.saver = tf.train.Saver(tf.trainable_variables(), max_to_keep=1)
        # Load weights from the checkpoint
        if vars(self.opt).get('start_from', None):
            self.saver.restore(sess, self.opt.ckpt.model_checkpoint_path)
        # Initialize the summary writer
        self.summary_writer = tf.summary.FileWriter(self.opt.checkpoint_path, sess.graph)

    def __init__(self, opt):
        self.vocab_size = opt.vocab_size
        self.input_encoding_size = opt.input_encoding_size
        self.rnn_size = opt.rnn_size
        self.num_layers = opt.num_layers
        self.drop_prob_lm = opt.drop_prob_lm
        self.seq_length = opt.seq_length
        self.vocab_size = opt.vocab_size
        self.seq_per_img = opt.seq_per_img

        self.opt = opt

        # Variable indicating in training mode or evaluation mode
        self.training = tf.Variable(True, trainable = False, name = "training")

        # Input variables
        self.images = tf.placeholder(tf.float32, [None, 224, 224, 3], name = "images")
        self.labels = tf.placeholder(tf.int32, [None, self.seq_length + 2], name = "labels")
        self.masks = tf.placeholder(tf.float32, [None, self.seq_length + 2], name = "masks")

        # Build CNN
        if vars(self.opt).get('start_from', None):
            cnn_weight = None
        else:
            cnn_weight = vars(self.opt).get('cnn_weight', None)
        if self.opt.cnn_model == 'vgg16':
            self.cnn = vgg.Vgg16(cnn_weight)
        if self.opt.cnn_model == 'vgg19':
            self.cnn = vgg.Vgg19(cnn_weight)

        with tf.variable_scope("cnn"):
            self.cnn.build(self.images)
        self.fc7 = self.cnn.drop7
        self.cnn_training = self.cnn.training

        # Variable in language model
        with tf.variable_scope("rnnlm"):
            # Word Embedding table
            self.Wemb = tf.Variable(tf.random_uniform([self.vocab_size + 1, self.input_encoding_size], -0.1, 0.1), name='Wemb')

            # RNN cell
            if opt.rnn_type == 'rnn':
                self.cell_fn = cell_fn = tf.contrib.rnn.BasicRNNCell
            elif opt.rnn_type == 'gru':
                self.cell_fn = cell_fn = tf.contrib.rnn.GRUCell
            elif opt.rnn_type == 'lstm':
                self.cell_fn = cell_fn = tf.contrib.rnn.LSTMCell
            else:
                raise Exception("RNN type not supported: {}".format(opt.rnn_type))

            # keep_prob is a function of training flag
            self.keep_prob = tf.cond(self.training,
                                lambda : tf.constant(1 - self.drop_prob_lm),
                                lambda : tf.constant(1.0), name = 'keep_prob')

            # basic cell has dropout wrapper
            self.basic_cell = cell = tf.contrib.rnn.DropoutWrapper(cell_fn(self.rnn_size), 1.0, self.keep_prob)
            # cell is the final cell of each timestep
            self.cell = tf.contrib.rnn.MultiRNNCell([cell] * opt.num_layers)

    def build_model(self):
        with tf.name_scope("batch_size"):
            # Get batch_size from the first dimension of self.images
            self.batch_size = tf.shape(self.images)[0]

        with tf.variable_scope("cnn"):
            image_emb = slim.fully_connected(self.fc7, self.input_encoding_size, activation_fn=None, scope='encode_image')
        with tf.variable_scope("rnnlm"):
            # Replicate self.seq_per_img times for each image embedding
            image_emb = tf.reshape(tf.tile(tf.expand_dims(image_emb, 1), [1, self.seq_per_img, 1]), [self.batch_size * self.seq_per_img, self.input_encoding_size])

            # rnn_inputs is a list of input, each element is the input of rnn at each time step
            # time step 0 is the image embedding
            rnn_inputs = tf.split(axis=1, num_or_size_splits=self.seq_length + 1, value=tf.nn.embedding_lookup(self.Wemb, self.labels[:,:self.seq_length + 1]))
            rnn_inputs = [tf.squeeze(input_, [1]) for input_ in rnn_inputs]
            rnn_inputs = [image_emb] + rnn_inputs

            # The initial sate is zero
            initial_state = self.cell.zero_state(self.batch_size * self.seq_per_img, tf.float32)

            outputs, last_state = tf.contrib.legacy_seq2seq.rnn_decoder(rnn_inputs, initial_state, self.cell, loop_function=None)

            outputs = tf.concat(axis=0, values=outputs[1:])
            self.logits = slim.fully_connected(outputs, self.vocab_size + 1, activation_fn = None, scope = 'logit')
            self.logits = tf.split(axis=0, num_or_size_splits=len(rnn_inputs) - 1, value=self.logits)

        with tf.variable_scope("loss"):
            loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(self.logits,
                    [tf.squeeze(label, [1]) for label in tf.split(axis=1, num_or_size_splits=self.seq_length + 1, value=self.labels[:, 1:])], # self.labels[:,1:] is the target
                    [tf.squeeze(mask, [1]) for mask in tf.split(axis=1, num_or_size_splits=self.seq_length + 1, value=self.masks[:, 1:])])
            self.cost = tf.reduce_mean(loss)

        self.final_state = last_state
        self.lr = tf.Variable(0.0, trainable=False)
        self.cnn_lr = tf.Variable(0.0, trainable=False)

        # Collect the rnn variables, and create the optimizer of rnn
        tvars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='rnnlm')
        grads = utils.clip_by_value(tf.gradients(self.cost, tvars), -self.opt.grad_clip, self.opt.grad_clip)
        #grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars),
        #        self.opt.grad_clip)
        optimizer = utils.get_optimizer(self.opt, self.lr)
        self.train_op = optimizer.apply_gradients(zip(grads, tvars))

        # Collect the cnn variables, and create the optimizer of cnn
        cnn_tvars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='cnn')
        cnn_grads = utils.clip_by_value(tf.gradients(self.cost, cnn_tvars), -self.opt.grad_clip, self.opt.grad_clip)
        #cnn_grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, cnn_tvars),
        #        self.opt.grad_clip)
        cnn_optimizer = utils.get_cnn_optimizer(self.opt, self.cnn_lr)
        self.cnn_train_op = cnn_optimizer.apply_gradients(zip(cnn_grads, cnn_tvars))

        tf.summary.scalar('training loss', self.cost)
        tf.summary.scalar('learning rate', self.lr)
        tf.summary.scalar('cnn learning rate', self.cnn_lr)
        self.summaries = tf.summary.merge_all()

    def build_generator(self):
        """
        Generator for generating captions
        Support sample max or sample from distribution
        No Beam search here; beam search is in decoder
        """
        # Variables for the sample setting
        self.sample_max = tf.Variable(True, trainable = False, name = "sample_max")
        self.sample_temperature = tf.Variable(1.0, trainable = False, name = "temperature")

        self.generator = []
        with tf.variable_scope("cnn"):
            image_emb = slim.fully_connected(self.fc7, self.input_encoding_size, activation_fn=None, reuse=True, scope='encode_image')
        with tf.variable_scope("rnnlm") as rnnlm_scope:
            rnn_inputs = [image_emb] + [tf.nn.embedding_lookup(self.Wemb, tf.zeros([self.batch_size], tf.int32))] + [0] * (MAX_STEPS - 1)
            initial_state = self.cell.zero_state(self.batch_size, tf.float32)

            tf.get_variable_scope().reuse_variables()

            def loop(prev, i):
                if i == 1:
                    return rnn_inputs[1]
                with tf.variable_scope(rnnlm_scope):
                    prev = slim.fully_connected(prev, self.vocab_size + 1, activation_fn = None, scope = 'logit')
                    prev_symbol = tf.stop_gradient(tf.cond(self.sample_max,
                        lambda: tf.argmax(prev, 1), # pick the word with largest probability as the input of next time step
                        lambda: tf.squeeze(
                            tf.multinomial(tf.nn.log_softmax(prev) / self.sample_temperature, 1), 1))) # Sample from the distribution
                    self.generator.append(prev_symbol)
                    return tf.nn.embedding_lookup(self.Wemb, prev_symbol)

            outputs, last_state = tf.contrib.legacy_seq2seq.rnn_decoder(rnn_inputs, initial_state, self.cell, loop_function=loop)
            self.g_output = output = tf.reshape(tf.concat(axis=1, values=outputs[1:]), [-1, self.rnn_size]) # outputs[1:], because we don't calculate loss on time 0.
            self.g_logits = logits = slim.fully_connected(outputs, self.vocab_size + 1, activation_fn = None, scope = 'logit')
            self.g_probs = probs = tf.reshape(tf.nn.softmax(logits), [self.batch_size, MAX_STEPS, self.vocab_size + 1])

        self.generator = tf.transpose(tf.reshape(tf.concat(axis=0, values=self.generator), [MAX_STEPS - 1, -1]))

    # Decoders are used for beam search. Much complicated than sample max.
    # Decoder decodes the image one time step at a time
    def build_decoder_rnn(self, first_step):

        with tf.variable_scope("cnn"):
            image_emb = slim.fully_connected(self.fc7, self.input_encoding_size, reuse=True, activation_fn=None, scope='encode_image')
        with tf.variable_scope("rnnlm"):
            if first_step:
                rnn_input = image_emb # At the first step, the input is the embedded image
            else:
                # The input of later time step, is the embedding of the previous word
                # The previous word is a placeholder
                self.decoder_prev_word = tf.placeholder(tf.int32, [None])
                rnn_input = tf.nn.embedding_lookup(self.Wemb, self.decoder_prev_word)

            batch_size = tf.shape(rnn_input)[0]

            tf.get_variable_scope().reuse_variables()

            if not first_step:
                # If not first step, the states are also placeholders.
                self.decoder_initial_state = initial_state = utils.get_placeholder_state(self.cell.state_size)
                self.decoder_flattened_state = utils.flatten_state(initial_state)
            else:
                # The states for the first step are zero.
                initial_state = self.cell.zero_state(batch_size, tf.float32)

            outputs, state = tf.contrib.legacy_seq2seq.rnn_decoder([rnn_input], initial_state, self.cell)
            logits = slim.fully_connected(outputs[0], self.vocab_size + 1, activation_fn = None, scope = 'logit')
            decoder_probs = tf.reshape(tf.nn.softmax(logits), [batch_size, self.vocab_size + 1])
            decoder_state = utils.flatten_state(state)
        # output the current word distribution and states
        return [decoder_probs, decoder_state]

    def build_decoder(self):
        self.decoder_model_init = self.build_decoder_rnn(True)
        self.decoder_model_cont = self.build_decoder_rnn(False)

    def decode(self, img, beam_size, sess, max_steps=30):
        """Decode an image with a sentences."""

        # Initilize beam search variables
        # Candidate will be represented with a dictionary
        #   "indexes": a list with indexes denoted a sentence;
        #   "words": word in the decoded sentence without <bos>
        #   "score": log-likelihood of the sentence
        #   "state": RNN state when generating the last word of the candidate
        good_sentences = [] # store sentences already ended with <eos>
        cur_best_cand = [] # store current best candidates
        highest_score = 0.0 # hightest log-likelihodd in good sentences

        # Get the initial logit and state
        probs_init, state_init = self.get_probs_init(img, sess)
        cand = {'indexes': [0], 'score': 0, 'state': state_init}
        cur_best_cand.append(cand)

        # Expand the current best candidates until max_steps or no candidate
        for i in xrange(max_steps):
            # expand candidates
            cand_pool = []
            states = [np.vstack([cand['state'][i] for cand in cur_best_cand]) for i in xrange(len(cur_best_cand[0]['state']))]
            indexes = [cand['indexes'][-1] for cand in cur_best_cand]
            all_probs, all_states = self.get_probs_cont(states, indexes, sess)
            for ind_cand in range(len(cur_best_cand)):
                cand = cur_best_cand[ind_cand]
                probs = all_probs[ind_cand]
                state = [x[ind_cand] for x in all_states]

                probs = np.squeeze(probs)
                probs_order = np.argsort(-probs)
                for ind_b in xrange(beam_size):
                    cand_e = copy.deepcopy(cand)
                    cand_e['indexes'].append(probs_order[ind_b])
                    cand_e['score'] -= np.log(probs[probs_order[ind_b]])
                    cand_e['state'] = state
                    cand_pool.append(cand_e)
            # get final cand_pool
            cur_best_cand = sorted(cand_pool, key=lambda cand: cand['score'])
            cur_best_cand = utils.truncate_list(cur_best_cand, beam_size)

            # move candidates end with <eos> to good_sentences or remove it
            cand_left = []
            for cand in cur_best_cand:
                if len(good_sentences) > beam_size and cand['score'] > highest_score:
                    continue # No need to expand that candidate
                if cand['indexes'][-1] == 0: #end of sentence
                    good_sentences.append(cand)
                    highest_score = max(highest_score, cand['score'])
                else:
                    cand_left.append(cand)
            cur_best_cand = cand_left
            if not cur_best_cand:
                break

        # Add candidate left in cur_best_cand to good sentences
        for cand in cur_best_cand:
            if len(good_sentences) > beam_size and cand['score'] > highest_score:
                continue
            if cand['indexes'][-1] != 0:
                cand['indexes'].append(0)
            good_sentences.append(cand)
            highest_score = max(highest_score, cand['score'])

        # Sort good sentences and return the final list
        good_sentences = sorted(good_sentences, key=lambda cand: cand['score'])
        good_sentences = utils.truncate_list(good_sentences, beam_size)

        return [sent['indexes'][1:] for sent in good_sentences]

    def get_probs_init(self, img, sess):
        """Use the model to get initial logit"""
        m = self.decoder_model_init

        probs, state = sess.run(m, {self.images: img})

        return (probs, state)

    def get_probs_cont(self, prev_state, prev_word, sess):
        """Use the model to get continued logit"""
        m = self.decoder_model_cont
        prev_word = np.array(prev_word, dtype='int32')

        placeholders = [self.decoder_prev_word] + self.decoder_flattened_state
        feeded = [prev_word] + prev_state

        probs, state = sess.run(m, {placeholders[i]: feeded[i] for i in xrange(len(placeholders))})

        return (probs, state)


# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
from subprocess import check_call

import six

sys.path.insert(0, os.path.abspath("../.."))

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension model names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosectionlabel',
    'sphinx.ext.autosummary',
    'sphinx.ext.coverage',
    'sphinx.ext.doctest',
    'sphinx.ext.githubpages',
    'sphinx.ext.ifconfig',
    'sphinx.ext.intersphinx',
    'sphinx.ext.mathjax',
    'sphinx.ext.napoleon',
    'sphinx.ext.todo',
    'sphinx.ext.viewcode'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

pygments_style = 'sphinx'

# -- Project information -----------------------------------------------------

project = 'torecsys'
copyright = '2019, Jasper, Li Wai Yin'
author = 'Jasper, Li Wai Yin'

# The full version, including alpha/beta/rc tags
version = "dev-0.0.1"
release = "dev"

# The master toctree document.
master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# Disable docstring inheritance
autodoc_inherit_docstrings = True

# autosectionlabel throws warnings if section names are duplicated.
# The following tells autosectionlabel to not throw a warning for
# duplicated section names that are in different documents.
autosectionlabel_prefix_document = True

# Configuration of sphinx
add_function_parentheses = False
add_module_names = False
autoclass_content = "both"
autodoc_mock_imports = ["torch", "torchaudio", "torchvision", "torchtext"]

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'nature'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_title = "Torecsys Documentation - Torescys Master Documentation"
html_short_title = "torecsys documentation"
html_baseurl = "https://torecsys.readthedocs.io/"
html_static_path = ['_static']
html_logo = "_static/img/pytorch-logo-dark.svg"
html_favicon = "_static/img/pytorch-logo-flame.ico"

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
intersphinx_mapping = {
    'python': ('https://docs.python.org/3.9', None),
    'numpy': ('https://docs.scipy.org/doc/numpy/', None)
}

def on_init(app):  # pylint: disable=unused-argument
    """
    Run sphinx-apidoc after Sphinx initialization.
    Read the Docs won't run tox or custom shell commands, so we need this to
    avoid checking in the generated reStructuredText files.
    """
    docs_path = os.path.abspath(os.path.dirname(__file__))
    root_path = os.path.abspath(os.path.join(docs_path, '../..'))
    apidoc_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv
        # If we are, assemble the path manually
        bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin'))
        apidoc_path = os.path.join(bin_path, apidoc_path)
    check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, 'torecsys')])

def setup(app):
    """Sphinx extension: run sphinx-apidoc."""
    event = 'builder-inited' if six.PY3 else b'builder-inited'
    app.connect(event, on_init)


import copy

#? Checking the difference between copy & no copy

testlist = [1,2,3,4,5]

newtestlist = testlist
newtestlist[0] = 5
print(testlist) #? Assigning a list to another list doesn't make them separate - the values in testlist are changed when changing newtestlist
print(newtestlist)

testlist[-1] = 'fart'
print(newtestlist[-1])

#? Here's the version using the copy module

testlist = [1,2,3,4,5]
newtestlist = copy.copy(testlist)
testlist[0] = 'boofer'
print(newtestlist[0])


from MeiTuan_Spider.core.utils import Spider, Tool
from MeiTuan_Spider.settings import city_href_path
from lxml import etree
from collections import defaultdict

class CityLinks(object):
    # 城市链接
    def __init__(self):
        self.spider = Spider()
        self.file = Tool()
        self.data = defaultdict(dict)
        self.url = 'https://www.meituan.com/changecity/'

    def get_page(self):
        html = self.spider.crawl(url=self.url, plain='text')
        content = etree.HTML(html)
        divs = content.xpath('//*[@class="alphabet-city-area"]/div')
        if divs:
            for div in divs:
                city_label = div.xpath('./span[@class="city-label"]/text()')[0]
                cities = div.xpath('./span[@class="cities"]/a')
                for city in cities:
                    href = city.xpath('./@href')[0]
                    name = city.xpath('./text()')[0]
                    self.data[city_label].update({name: 'https:' + href})

        self.file.save_to_json(city_href_path, self.data)

if __name__ == '__main__':
    city = CityLinks()
    city.get_page()


import pandas as pd
from oandapyV20 import API
import oandapyV20.endpoints.instruments as instruments
from oandapyV20.types import DateTime
from datetime import datetime, timedelta

OANDA_ACCESS_TOKEN = ''
OANDA_ENVIRONMENT = "practice"
LIMIT_ROWS = 5000

def get_equity(
    since: str,
    until: str,
    instrument: str = 'USD_JPY',
    price: str = 'mid',
    interval: str = 'S5',
) -> pd.DataFrame:
    assert price in ['M', 'A', 'B'],\
        "'price' must be 'M' or 'A' or 'B'."
    cnt = 'mid' if price == 'M' \
        else 'ask' if price == 'A' \
        else 'bid' if price == 'B' \
        else 'mid'
    # interval: http://developer.oanda.com/rest-live-v20/instrument-df/#collapse_definition_1

    params = {
        "from": DateTime(since).value,
        "to": DateTime(until).value,
        "price": price,
        "granularity": interval
    }
    r = instruments.InstrumentsCandles(instrument=instrument, params=params)

    api = API(access_token=OANDA_ACCESS_TOKEN, environment=OANDA_ENVIRONMENT)
    api.request(r)
    raw_list = []
    for raw in r.response['candles']:
        raw_list.append(
            [
                raw['time'],
                raw[cnt]['o'],
                raw[cnt]
                ['h'],
                raw[cnt]['l'],
                raw[cnt]['c'],
                raw['volume']
            ]
        )
    raw_df = pd.DataFrame(
        raw_list,
        columns=[
            'Time',
            f'Open_{cnt}',
            f'High_{cnt}',
            f'Low_{cnt}',
            f'Close_{cnt}',
            'Volume'
        ])
    return raw_df

def add_equities(
    df: pd.DataFrame,
    since: str,
    until: str,
    instrument: str = 'USD_JPY',
    interval: str = 'S5',
) -> pd.DataFrame:
    print(f'since: {since}, until: {until}')
    raw_a = get_equity(
        since=since,
        until=until,
        instrument=instrument,
        price='A',
        interval=interval
    )
    raw_b = get_equity(
        since=since,
        until=until,
        instrument=instrument,
        price='B',
        interval=interval
    )
    raw_m = get_equity(
        since=since,
        until=until,
        instrument=instrument,
        price='M',
        interval=interval
    )

    raw = pd.merge(raw_a, raw_b)
    raw = pd.merge(raw, raw_m)
    raw = raw.set_index('Time')
    raw.index = pd.to_datetime(raw.index)

    df = pd.concat([df, raw])
    return df

def count_rows(
    period: timedelta,
    interval: str,
) -> int:
    unit_time = float(interval[1:]) if len(interval) > 1 else 1.0

    if period.days > 0:
        if 'S' in interval:
            rows_per_day = 24 * 3600 / unit_time
        if 'M' in interval:
            rows_per_day = 24 * 60 / unit_time
        if 'H' in interval:
            rows_per_day = 24 / unit_time
        if 'D' in interval:
            rows_per_day = unit_time
        if 'W' in interval:
            rows_per_day = unit_time / 7.0

        return period.days * rows_per_day

    # period が1日の範囲の場合
    if 'S' in interval:
        rows_per_sec = 1 / unit_time
    if 'M' in interval:
        rows_per_sec = 1 / (60 * unit_time)
    if 'H' in interval:
        rows_per_sec = 1 / (3600 * unit_time)

    return int(period.total_seconds() * rows_per_sec)

def get_candles(
    since: str,
    until: str,
    instrument: str = 'USD_JPY',
    interval: str = 'S5',
) -> pd.DataFrame:
    if type(since) == str:
        since = datetime.strptime(since, '%Y-%m-%d %H:%M:%S')
    if type(until) == str:
        until = datetime.strptime(until, '%Y-%m-%d %H:%M:%S')

    df = pd.DataFrame()

    if until > datetime.now():
        until = datetime.now()

    period = until - since
    n_rows = count_rows(
        period=period,
        interval=interval,
    )
    remain = n_rows
    unit_time = float(interval[1:]) if len(interval) > 1 else 1.0

    while True:
        delta = LIMIT_ROWS * unit_time if remain > LIMIT_ROWS \
            else remain * unit_time
        if 'S' in interval:
            until = since + timedelta(seconds=delta)
        if 'M' in interval:
            until = since + timedelta(minutes=delta)
        if 'H' in interval:
            until = since + timedelta(hours=delta)
        if 'D' in interval:
            until = since + timedelta(days=delta)
        if 'W' in interval:
            until = since + timedelta(weeks=delta)

        df = add_equities(
            df=df,
            since=since,
            until=until,
            instrument=instrument,
            interval=interval,
        )
        since = until
        remain -= LIMIT_ROWS
        if remain <= 0:
            break

    return df


# Author: Allen Anker
# Created by Allen Anker on 15/07/2018

"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
"""

class Solution:
    def convert(self, s, num_rows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if not s or num_rows == 1: return s
        rows = [''] * num_rows
        for i in range(len(s)):
            j = i % (2 * num_rows - 2)
            if j < num_rows:
                rows[j] += s[i]
            else:
                # num_rows - 1 - (j - num_rows) = 2 * num_rows - 1 - j
                rows[2 * num_rows - 2 - j] += s[i]

        return self.__compact_str_list(rows)

    @staticmethod
    def __compact_str_list(s):
        result = ''
        for item in s:
            result += item

        return result

solution = Solution()
s = 'PAYPALISHIRING'
print(solution.convert(s, 3))


from ast import arg
import os, sys

#retrieve current version
# with open('set_version.bat','r') as f: envs = f.readlines()
# envs = "".join(envs).replace('set ','').split()
# envs = {i.split('=')[0]:i.split('=')[1] for i in envs}
envVal = sys.argv[1] if len(sys.argv) > 1 else os.environ["DOM_API_APIVERSION"]
envs = {"DOM_API_APIVERSION": envVal}

output = ''
with open('.env','r') as f:
    dotenv = f.readlines()
    dotenv = "".join(dotenv).split()
    dotenv = {i.split('=')[0]:i.split('=')[1] for i in dotenv}
    for k in envs.keys():
        if k in dotenv: dotenv[k] = envs[k]
    output = "\n".join([f"{k}={dotenv[k]}" for k in dotenv.keys()])
    print(output)

with open('.env','w') as f:
    f.write(output)


from subprocess import *
import subprocess

outfile = open("out.txt", "a")

file_names = input('Enter C Program Names : ')

l = ["gcc","-g"]
l.extend(file_names.split())
status = subprocess.call(l)

if status != 0 :
	print("cannot compile and link", file_names)
	exit(1)

inp_files = input("Enter input as a text file:")
print()
inp_files = inp_files.split()
if len(inp_files) == 0:
	inp_files.append("")

# print(inp_files)

for inp in inp_files:
	p = Popen(['gdb', 'a.out'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines = True)
	if(inp == ""):
		p.stdin.write('r\n')
	else:
		print("For test case "+inp+":")
		p.stdin.write('r <'+inp+'\n')
	p.stdin.write('info locals\n')
	p.stdin.write('bt\n')
	out , errors = p.communicate()
	glob_list = out.split('\n')
	# print(glob_list)

	c = 0
	for i in glob_list:
		if i.startswith('(gdb)') and c == 0:
			c +=1
		elif i.startswith('(gdb)') and c == 1:
			print("\n")
			print(i[6:])
			c+=1
		elif i.startswith('(gdb)') and c == 2:
			print("\n")
			print(i[6:])
			c+=1
		elif i.startswith('(gdb)') and c == 3:	break
		elif c == 1:	print(i)
		elif c == 2:	print(i)
		elif c == 3:	print(i)
	print()

# out = a.communicate()

# command = "./a.out < in03.txt"

# result = run(command, universal_newlines=True,shell = True, text = True)
# print(result.returncode, result.stdout, result.stderr)

# command = "./a.out < in03.txt "
# subprocess.call([command],shell = True)


import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error

boston = datasets.load_boston()
inputs = boston.data
outputs = boston.target

X_train, X_test, y_train, y_test = train_test_split(inputs, outputs, test_size = 0.2)

scaler1 = MinMaxScaler()
X_train = scaler1.fit_transform(X_train)
X_test = scaler1.transform(X_test)

y_train = y_train.reshape(-1, 1)
y_test = y_test.reshape(-1, 1)
scaler2 = MinMaxScaler()
y_train = scaler2.fit_transform(y_train)
y_test = scaler2.transform(y_test)

network = MLPRegressor(max_iter=2000, verbose=True, hidden_layer_sizes=(7))
network.fit(X_train, y_train)

predictions = network.predict(X_test)
print('predictions',predictions)
print('y_test',y_test)

print('mean absolut error',mean_absolute_error(y_test, predictions))
print('mean squared error',np.sqrt(mean_squared_error(y_test, predictions)))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import anchor_generator
from util import cython_overlaps

BASE_NETS = ['vgg_16']
MODELS = ['faster_rcnn','ssd']

def get_target(model,base_net,image_size,gt_boxes):

    if model not in MODELS:
        raise ValueError('Unknown model.')
    if base_net not in BASE_NETS:
        raise ValueError('Unknown base net.')

    neg_max_iou = 0.3
    pos_min_iou = 0.7

    if model == 'ssd':
        neg_max_iou = 0.5
        pos_min_iou = 0.5

    height = image_size
    width = image_size

    all_anchors = anchor_generator.get_anchor(model = model,base_net = base_net,image_size = image_size)

    num_anchor = all_anchors.shape[0]
    num_box = gt_boxes.shape[0]

    _allowed_border = 100

    inds_inside = np.where(
        (all_anchors[:,0] >= -_allowed_border) &
        (all_anchors[:,1] >= -_allowed_border) &
        (all_anchors[:,2] < width + _allowed_border) &
        (all_anchors[:,3] < height + _allowed_border)
    )[0]

    anchors = all_anchors[inds_inside,:]

    labels = np.empty((len(inds_inside),),dtype = np.float32)
    labels.fill(-1)
    targets = np.empty((len(inds_inside),),dtype = np.float32)
    targets.fill(-1)

    overlaps = cython_overlaps.bbox_overlaps(
                    np.ascontiguousarray(anchors,dtype = np.float),
                    np.ascontiguousarray(gt_boxes,dtype = np.float))

    argmax_overlaps = overlaps.argmax(axis = 1)
    max_overlaps = overlaps[np.arange(len(inds_inside)),argmax_overlaps]
    gt_argmax_overlaps = overlaps.argmax(axis = 0)
    gt_max_overlaps = overlaps[gt_argmax_overlaps,
                            np.arange(overlaps.shape[1])]
    arg_gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]

    labels[max_overlaps < neg_max_iou] = 0
    labels[arg_gt_argmax_overlaps] = 1
    labels[max_overlaps >= pos_min_iou] = 1

    check = np.count_nonzero(labels) - len(labels)
    if check == 0:
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        return check

    ones = np.ones((len(labels)),dtype = np.float32)
    targets = np.where(labels == ones,argmax_overlaps,0)
    targets[gt_argmax_overlaps] = np.arange(num_box)

    labels = _unmap(labels,num_anchor,inds_inside,fill = -1)
    targets = _unmap(targets,num_anchor,inds_inside,fill = 0)
    return labels,targets

def _unmap(data,count,inds,fill = 0,dtype = np.float32):
    if len(data.shape) == 1:
        ret = np.empty((count,),dtype = dtype)
        ret.fill(fill)
        ret[inds] = data
    else:
        ret = np.empty((count,),dtype = dtype)
        ret.fill(fill)
        ret[inds,:] = data
    return ret


from models.basic_operators import *
from models.adapter_modules import *
from models.trihit_x import trihit_x

# the traditional adapeter architecture adopted in LWNet. Only the classification head is re-intialized and fine-tuned
class trihit_ft_adapter(trihit_x):
    def __init__(self,
                 in_chans=1,
                 num_classes=100,
                 depths=[2, 2, 4, 2],
                 dims=[64, 128, 320, 512],
                 arch=['conv', 'hit', 'hit', 'hit'],
                 head_dropout=0.0,
                 ):

        super().__init__(in_chans=in_chans, depths=depths, dims=dims, drop_path_rate=0.15, arch=arch, add_classifer=False)

        self.adapter_cls_norm = nn.LayerNorm(dims[-1])
        self.adapter_cls_head = MLP_head(dims[-1], num_classes, head_dropout=head_dropout)

    def forward(self, x):
        x = self.forward_features(x)
        x = self.adapter_cls_norm(x)
        out = self.adapter_cls_head(x)

        return out

def trihit_cth_ft(num_classes=100, dp_rate=0.0):
    model = trihit_ft_adapter(num_classes=num_classes, depths=[2, 2, 4, 2], dims=[32, 64, 128, 256], arch=['conv', 'hit', 'hit', 'hit'],)
    return model


# 격자판의 숫자 이어 붙이기
'''
문제 조건 이해하기
1. 만들 수 있는 서로 다른 7자리 수들의 개수 구하기
2. 4x4 격자 전체를 순회하기
3. 7자리 숫자를 만들기 위해 6번 이동
4. 범위 안에서 상, 하, 좌, 우를 이동 가능
5. DFS의 종료 조건은 n == 7
'''

# 4방향으로 가기 위해 si, sj 인자로 전달받기
def DFS(n, si, sj, num):
    if n == 7:
        sset.add(num)
        return

    for di, dj in zip([-1, 1, 0, 0], [0, 0, -1, 1]):
        ni, nj = si + di, sj + dj
        if 0 <= ni < 4 and 0 <= nj < 4:
            # 받은 숫자를 *10을 해줘서 10의 자리로 밀어주고 다음 더해 숫자열을 이어가기
            DFS(n + 1, ni, nj, num*10 + arr[ni][nj])

for t in range(1, int(input()) + 1):
    arr = [list(map(int, input().split())) for _ in range(4)]
    # 중복되지 않게 만들어진 수를 담을 set 변수 생성
    sset = set()
    for i in range(4):
        for j in range(4):
            DFS(0, i, j, 0)
    print(f'#{t} {len(sset)}')


import os
import wandb
import fastai
import joblib
from fastai.callbacks import CSVLogger
from fastai.vision import *
from bengaliai.config import *
from bengaliai.data import get_train
import click
from bengaliai.models import Loss_combine

print("Running Fast.AI version: ", fastai.__version__)

@click.command()
@click.argument()
def main():

    train_df, labels = get_train()

    fold = 0

    data = (
        ImageList.from_df(
            train_df,
            path=DATA_DIR,
            folder="train",
            suffix=".png",
            cols="image_id",
            convert_mode="L",
        )
        .split_by_idx(
            range(fold * len(train_df) // folds, (fold + 1) * len(train_df) // folds)
        )
        .label_from_df(cols=label_names)
        .transform(
            get_transforms(do_flip=False, max_warp=0.1), size=size, padding_mode="zeros"
        )
        .databunch(bs=batchsize)
    ).normalize(stats)

if __name__ == "__main__":
    # do stuff
    print("Wheee!")


import pybullet as p
import pybullet_data as pd
import math
import time

import random

class Terrain:
    def __init__(self, max_height=0.01, size=(25, 25), scale=(0.1, 0.1), clear_center=False):
        self.id = -1
        self.collision_shape = -1

        self.scale = scale
        self.rows = int(size[0] / scale[0])
        self.cols = int(size[1] / scale[1])
        self.heightfield_data = [0] * self.rows * self.cols
        self.clear_center_size = 2
        self.clear_center = clear_center

        self.randomize(max_height)

    def randomize(self, max_height):
        if max_height > 1:
            #hacky way to make different types of terrain just based on the max_height parameter
            max_height = max_height - 1
            for j in range(int(self.cols / 2)):
                for i in range(int(self.rows / 2)):
                    # create a quadratic shape with random height
                    height = random.uniform(0, max_height)
                    self.heightfield_data[2 * i + 2 * j * self.rows] = height
                    self.heightfield_data[2 * i + 1 + 2 * j * self.rows] = height
                    self.heightfield_data[2 * i + (2 * j + 1) * self.rows] = height
                    self.heightfield_data[2 * i + 1 + (2 * j + 1) * self.rows] = height
        else:
            for j in range(int(self.cols)):
                for i in range(int(self.rows)):
                    self.heightfield_data[i + j * self.rows] = random.uniform(0, max_height)

        if self.clear_center:
            # make sure the center is flat so the robot does not get stuck there on resetting
            for j in range(int(self.cols / 4) - self.clear_center_size, int(self.cols / 4) + self.clear_center_size):
                for i in range(int(self.rows / 4) - self.clear_center_size,
                               int(self.rows / 4) + self.clear_center_size):
                    self.heightfield_data[2 * i + 2 * j * self.rows] = 0
                    self.heightfield_data[2 * i + 1 + 2 * j * self.rows] = 0
                    self.heightfield_data[2 * i + (2 * j + 1) * self.rows] = 0
                    self.heightfield_data[2 * i + 1 + (2 * j + 1) * self.rows] = 0

        # first time we can't replace, also add some visuals
        if self.collision_shape == -1:
            self.collision_shape = p.createCollisionShape(
                shapeType=p.GEOM_HEIGHTFIELD,
                meshScale=[self.scale[0], self.scale[1], 1.0],
                heightfieldTextureScaling=(self.rows - 1) / 2,
                heightfieldData=self.heightfield_data,
                numHeightfieldRows=self.rows,
                numHeightfieldColumns=self.cols)
            self.id = p.createMultiBody(0, self.collision_shape)
            p.resetBasePositionAndOrientation(self.id, [0, 0, 0.0], [0, 0, 0, 1])
            p.changeVisualShape(self.id, -1, rgbaColor=[1, 1, 1, 1])
        else:
            p.createCollisionShape(
                shapeType=p.GEOM_HEIGHTFIELD,
                flags=p.GEOM_FORCE_CONCAVE_TRIMESH,
                meshScale=[self.scale[0], self.scale[1], 1.0],
                heightfieldTextureScaling=(self.rows - 1) / 2,
                heightfieldData=self.heightfield_data,
                numHeightfieldRows=self.rows,
                numHeightfieldColumns=self.cols,
                replaceHeightfieldIndex=self.collision_shape)


def displayBlock(processSize, segments):
    print()
    print("Process No. Process Size")
    for i in range(len(processSize)):
        print(i + 1, "         ", processSize[i],
              end="         ")
        if segments[i] != -1:
            print(segments[i] + 1)
        else:
            print("Not Allocated")

def firstFit(blockSize, processSize):
    segments = [-1] * len(processSize)
    for i in range(len(processSize)):
        for j in range(len(blockSize)):
            if blockSize[j] >= processSize[i]:
                segments[i] = j
                blockSize[j] -= processSize[j]
    displayBlock(processSize, segments)

def bestFit(blockSize, processSize):
    segments = [-1] * len(processSize)
    for i in range(len(processSize)):
        bestIndex = -1
        for j in range(len(blockSize)):
            if blockSize[j] >= processSize[i]:
                if bestIndex == -1:
                    bestIndex = j
                elif blockSize[bestIndex] > blockSize[j]:
                    bestIndex = j
        if bestIndex != -1:
            segments[i] = bestIndex
            blockSize[bestIndex] -= processSize[i]
    displayBlock(processSize, segments)

def worstFit(blockSize, processSize):
    segments = [-1] * len(processSize)
    for i in range(len(processSize)):
        worstIndex = -1
        for j in range(len(blockSize)):
            if blockSize[j] >= processSize[i]:
                if worstIndex == -1:
                    worstIndex = j
                elif blockSize[worstIndex] < blockSize[j]:
                    worstIndex = j
        if worstIndex != -1:
            segments[i] = worstIndex
            blockSize[worstIndex] -= processSize[i]
    displayBlock(processSize, segments)

def sizeBlock(blockSize, processSize):
    if (processSize >= 0):
        print(blockSize)
        blcSize = [0]*blockSize
        prcSize = [0]*processSize

        for i in range(blockSize):
            val = int(input(f"Enter block item for segment {i+1}: "))
            blcSize[i] = val

        for i in range(processSize):
            val = int(input(f"Enter process size for segment {i+1}: "))
            prcSize.append(val)
        print()
        print('----------------- BEST FIT -----------------')
        print()
        bestFit(blcSize, prcSize)
        print()
        print('----------------- FIRST FIT -----------------')
        print()
        firstFit(blcSize, prcSize)
        print()
        print('----------------- WORST FIT -----------------')
        print()
        worstFit(blcSize, prcSize)

    else:
        print("Not possible!")

if __name__ == "__main__":

    blockSize = int(input('Enter block size: '))
    processSize = int(input('Enter Number of Process: '))
    sizeBlock(blockSize, processSize)

Sequential File Allocation Algorithms/CT-19043-LAB05-BestFirstWorstFit.py


# Telegram: @ZumbiPy __   _ ___
#  /_  / __ ____ _  / /  (_) _ \__ __
#   / /_/ // /  ' \/ _ \/ / ___/ // /
#  /___/\_,_/_/_/_/_.__/_/_/   \_, /
# E-mail: zumbipy@gmail.com   /___/
"""
13 - Tendo como dados de entrada a altura e o sexo de uma pessoa,
construa um algoritmo que calcule seu peso ideal, utilizando as
seguintes fórmulas:
Para homens: (72.7*h) - 58
Para mulheres: (62.1*h) - 44.7 (h = altura)
Peça o peso da pessoa e informe se ela está dentro, acima ou abaixo do peso.
"""

altura = float(input("Digite sua altura em Cm: ")) / 100
sexo = input("Digite M (mulher) ou H (Homem): ").lower()
peso = float(input("Digite sua peso: "))
respota = None
peso_ideal = 0

if "homem".startswith(sexo):
    print("homem")
    peso_ideal = round(72.7 * altura - 58)
    if peso_ideal == peso:
        respota = """Sua altura é {}.
Seu peso é {:.0f}kg e Você esta (dentro) do seu peso
ideal que é {:.0f}kg""".format(altura, peso, peso_ideal)

    elif peso < peso_ideal:
        respota = """Sua altura é {}.
Seu peso é {:.0f}kg e Você esta (abaixo) do seu peso
ideal que é {:.0f}kg""".format(altura, peso, peso_ideal)

    else:
        respota = """Sua altura é {}.
Seu peso é {:.0f}kg e Você esta (acima) do seu peso
ideal que é  {:.0f}kg""".format(altura, peso, peso_ideal)

elif "mulher".startswith(sexo):
    print("mulher")
    peso_ideal = round(62.1 * altura - 44.7)
    if peso_ideal == peso:
        respota = """Sua altura é {}.
Seu peso é {:.0f}kg e Você esta (dentro) do seu peso
ideal que é {:.0f}kg""".format(altura, peso, peso_ideal)

    elif peso < peso_ideal:
        respota = """Sua altura é {}.
        Seu peso é {:.0f}kg e Você esta (abaixo) do seu peso
ideal que é {:.0f}kg""".format(altura, peso, peso_ideal)

    else:
        respota = """Sua altura é {}.
Seu peso é {:.0f}kg e Você esta (acima) do seu peso
ideal que é  {:.0f}kg""".format(altura, peso, peso_ideal)

print(respota)


from random import choice, randint
import pygame
pygame.init()
size = width, height = 75, 75
screen = pygame.display.set_mode(size, pygame.NOFRAME)

tiles = {0: [1, 1, 0, 0], 1: [0, 1, 1, 0], 2: [0, 0, 1, 1], 3: [1, 0, 0, 1]}
sides = {(-1, 0): 3, (1, 0): 1, (0, -1): 0, (0, 1): 2}

def find_lowest_entropy(grid: list) -> tuple:
    min = float("inf")
    for i, row in enumerate(grid):
        for j, cell in enumerate(row):
            if isinstance(cell, dict) and len(cell) < min:
                min = len(cell)
                pos = i, j
    if min == 4:
        pos = [randint(0, 4) for i in range(2)]
    return pos, min

def draw_tile(x: int, y: int, tile: int):
    pygame.draw.rect(screen, "0x303030", (x * 15, y * 15, 15, 15))
    if tile[0]:
        pygame.draw.rect(screen, "0xd0d010", (x * 15 + 5, y * 15 + 5, 5, 10))
    if tile[1]:
        pygame.draw.rect(screen, "0xd0d010", (x * 15 + 5, y * 15 + 5, 10, 5))
    if tile[2]:
        pygame.draw.rect(screen, "0xd0d010", (x * 15 + 5, y * 15, 5, 10))
    if tile[3]:
        pygame.draw.rect(screen, "0xd0d010", (x * 15, y * 15 + 5, 10, 5))

grid = [[tiles for i in range(5)] for j in range(5)]
screen.fill("0x303030")
pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # one iteration
            (y, x), minimum = find_lowest_entropy(grid)
            if isinstance(tile, dict):
                grid[y][x] = choice(grid[y][x])
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if not (i and j) and (i or j):
                            this = sides[(i, j)]
                            other = (this + 2) % 4
                            for variant in [_ for _ in grid[y + j][x + i]]:
                                if variant[other] != grid[y][x][this]:
                                    grid[y + j].remove(variant)

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                pygame.quit()
                quit()
    screen.fill("0x303030")
    for i, row in enumerate(grid):
        for j, tile in enumerate(row):
            if isinstance(tile, list):
                draw_tile(j, i, tile)
    pygame.display.update()


from detect import img2char
from syn_mod import Synthesizer
import cv2
from utils.audio import save_wav
import numpy as np

if __name__=="__main__":
  img = cv2.imread(r'C:\Users\김규림\pythonProject\tacotron2\test2.PNG')#이미지 루트
  texts = img2char(img) #텍스트
  load_path=r"C:\Users\김규림\pythonProject\tacotron2\checkpoint"#프리트레인 모델
  num_speakers =1
  checkpoint_step =None
  sample_path = r"C:\Users\김규림\pythonProject\tacotron2\sample"
  speaker_id = 0
  base_alignment_path = None
  is_korean = True
  audio = np.zeros(1)
  synthesizer.load(load_path,num_speakers,checkpoint_step,inference_prenet_dropout=False)
  synthesizer = Synthesizer()
  for text in texts:
      audio = np.append(audio,synthesizer.Synthesize(texts=[text],base_path=sample_path,speaker_ids=[speaker_id],
                                   attention_trim=True,base_alignment_path=base_alignment_path,isKorean=is_korean))
      audio = np.append(audio,np.zeros(5000))

  save_wav(audio,'/content/hi.wav',16000)