import collections.abc
import os
import warnings
from typing import Mapping, Union, Any

try:
    from typing import ForwardRef
except ImportError:
    from typing import _ForwardRef as ForwardRef

from depytg.errors import NotImplementedWarning
from depytg.types import *

_warned = False

def devel() -> bool:
    global _warned
    try:
        dbg = bool(os.environ.get('DEPYTG_DEVEL', False))
        if dbg and not _warned:
            _warned = True
            warnings.warn('DepyTG development mode enabled, uses more CPU. Unset DEPYTG_DEVEL for performance.')
        return dbg
    except Exception as e:
        warnings.warn(e)
        return False

def is_union(some_type: type(Union)) -> bool:
    """
    Apparently there's no way to know if some type is a Union other than checking
    the memory location of its type. Thanks Python <3
    :param some_type: The type you're checking
    :return: True if it is a Union
    """

    # Yeah. Thanks Python.
    return isinstance(some_type, type(Union)) or \
           id(type(some_type)) == id(type(Union)) or \
           str(type(some_type)) == "typing.Union"

def is_sequence(some_type) -> bool:
    if "__extra__" in dir(some_type):
        return some_type.__extra__ == collections.abc.Sequence
    return False

def is_mapping(some_type) -> bool:
    if "__extra__" in dir(some_type):
        return some_type.__extra__ == collections.abc.Mapping
    return False

def is_tobject(some_type: type) -> bool:
    return ((
                    type(some_type) == type and
                    issubclass(some_type, TelegramObjectBase)
            ) or isinstance(some_type, TelegramObjectBase))

def is_forwardref(some_type) -> bool:
    return isinstance(some_type, ForwardRef)

def depyfy(obj: Any, otype: type) -> Any:
    """
    Walks into a generic object 'obj' and converts it to a DepyTG typechecked
    object, if possible.
    Please note that only JSON-serializable objects are
    supported: other objects will be returned without conversion.
    Moreover, forward references are not supported and objects whose type
    specified as such will not be converted. To avoid passing unwanted forward references,
    please use 'typing.get_type_hints' instead of finding them manually.
    :param obj: The object to convert
    :param otype: The expected type for the object
    :return: The converted object
    """

    if not devel():
        return depyfy_fast(obj)

    if is_sequence(otype):
        return depyfy_sequence(obj, otype)
    elif is_mapping(otype):
        return depyfy_mapping(obj, otype)
    elif is_union(otype):
        return depyfy_union(obj, otype)
    elif is_tobject(otype):
        return depyfy_tobject(obj, otype)
    else:
        return obj

def depyfy_fast(obj: Any) -> Any:
    if isinstance(obj, TelegramObjectBase):
        return obj

    if isinstance(obj, tuple):
        obj = list(obj)

    if isinstance(obj, list):
        for i in range(len(obj)):
            obj[i] = depyfy_fast(obj[i])

        return obj

    if isinstance(obj, dict):
        new = TelegramObjectBase()

        for key, value in obj.items():
            new[key] = depyfy_fast(value)

        return new

    return obj

def depyfy_sequence(seq: Sequence, seq_type) -> Sequence:
    subtype = seq_type.__args__[0]
    newseq = []

    if isinstance(subtype, ForwardRef):
        warnings.warn("Not depyfying sequence whose argument is a forward reference", NotImplementedWarning)
        return seq
    elif is_sequence(subtype):
        for i in seq:
            newseq.append(depyfy_sequence(i, subtype))
    elif is_mapping(subtype):
        for i in seq:
            newseq.append(depyfy_mapping(i, subtype))
    elif is_tobject(subtype):
        for i in seq:
            newseq.append(depyfy_tobject(i, subtype))
    else:
        # Subtype is a regular Python object. This is not a typechecker, skip loop
        return seq

    # Cast back to original type
    return type(seq)(newseq)

def depyfy_mapping(mapp: Mapping, map_type) -> Mapping:
    keytype, valtype = map_type.__args__
    newmap = {}

    k_is_fref = is_forwardref(keytype)
    v_is_fref = is_forwardref(valtype)

    # Skip loop if everything is a forward reference
    if k_is_fref or v_is_fref:
        warnings.warn("Not depyfying mapping whose {} defined as ForwardRef"
                      .format(k_is_fref and not v_is_fref and "key is" or \
                              v_is_fref and not k_is_fref and "value is" or \
                              k_is_fref and v_is_fref and "key and value are"),
                      NotImplementedWarning)
        return mapp

    # Skip loop if both keys and values are regular Python objects
    if not is_tobject(keytype) or is_tobject(valtype):
        return mapp

    # Either key or value needs to be depyfied
    for k, v in mapp.items():
        newkey, newval = k, v

        if k_is_fref:
            pass
        elif is_sequence(keytype):
            newkey = depyfy_sequence(k, keytype)
        elif is_mapping(keytype):
            newkey = depyfy_mapping(k, keytype)
        elif is_tobject(keytype):
            newkey = depyfy_tobject(k, keytype)

        if v_is_fref:
            pass
        elif is_sequence(valtype):
            newval = depyfy_sequence(v, valtype)
        elif is_mapping(valtype):
            newval = depyfy_mapping(v, valtype)
        elif is_tobject(valtype):
            newval = depyfy_tobject(v, valtype)

        newmap[newkey] = newval

    # Cast back to original type
    return type(mapp)(newmap)

def depyfy_union(obj: Any, union) -> Any:
    given_t = type(obj)

    # If the object is a regular Python object and its type is specified
    # in the Union, it's good to go
    if given_t in union.__args__:
        return obj

    # Not a regular type, one first shot looking for TelegramObjectBase
    if given_t == dict and dict not in union.__args__:
        # Try to convert it to every TelegramObjectBase subclass specified
        # in the Union. Return the first one that succeeds
        for t in union.__args__:
            if not is_tobject(t):
                continue
            try:
                return depyfy_tobject(obj, t)
            except Exception:
                import traceback
                import traceback
                traceback.print_exc()

    # Maybe it's a GenericMeta. Check for Sequence and Mapping
    for t in union.__args__:
        try:
            if is_sequence(t):
                return depyfy_sequence(obj, t)
        except Exception:
            import traceback
            traceback.print_exc()

        try:
            if is_mapping(t):
                return depyfy_mapping(obj, t)
        except Exception:
            import traceback
            traceback.print_exc()

    # The object is nothing we can convert. Return it with a warning
    warnings.warn("Could not match object '{}' of type {} with anything in {}".format(obj, given_t, union))
    return obj

def depyfy_tobject(tobj: Union[TelegramObjectBase, dict, str], otype: type) -> TelegramObjectBase:
    if type(tobj) == otype:
        return tobj
    elif type(tobj) in (str, dict):
        return otype.from_json(tobj)
    return tobj

def depyfy_obj_hook(obj: dict) -> 'TelegramObjectBase':
    t = TelegramObjectBase()
    t.update(obj)
    return t


import subprocess

def un_hide_frequency() -> None:
    command: str = "powercfg -attributes SUB_PROCESSOR PROCFREQMAX -ATTRIB_HIDE"
    subprocess.run(command, shell=True)

def set_frequency(value: int) -> None:
    command: str = \
        f"powercfg /setacvalueindex SCHEME_CURRENT SUB_PROCESSOR PROCFREQMAX {value} && " \
        f"powercfg /setdcvalueindex SCHEME_CURRENT SUB_PROCESSOR PROCFREQMAX {value} && " \
        "powercfg /S SCHEME_CURRENT"
    subprocess.run(command, shell=True)

def get_frequency() -> int:
    try:
        return int(subprocess.run(
            'powercfg /query SCHEME_CURRENT SUB_PROCESSOR PROCFREQMAX',
            capture_output=True, shell=True).stdout[-12:-4], 16)
    except ValueError:
        un_hide_frequency()
        return get_frequency()


from dataclasses import dataclass
from typing import Optional

@dataclass
class EGRID:

    states: Optional[list] = None
    plant_fuel_types: Optional[dict] = None
    plant_fuel_type_agg_tags: Optional[dict] = None
    layout: Optional[list] = None

    def agg_fuel_types(self, df):

        df_agg = pd.DataFrame()

        unique_agg_fuel_types = _get_unique_agg_fuel_types()

        for agg_fuel_type in unique_agg_fuel_types:

            keep_fuel_types = list()

            for k, v in plant_fuel_type_agg_tags.items:

                if v == agg_fuel_type:

                    keep_columns.append(k)

            keep_columns = ([col for col in df.columns
                            if col.startswith("R") &
                            col.split("_")[1] in keep_fuel_types]
                            )

            df_filter = df[keep_columns]

            count_columns = [col for col in df_filter.columns if col.endswith("count")]
            mWh_columns = [col for col in df_filter.columns if col.endswith("mWh")]

            df_agg[f"R_{agg_fuel_type}_count"] = df_filter[count_columns].sum(axis=1)
            df_agg[f"R_{agg_fuel_type}_mWh"] = df_filter[mWh_columns].sum(axis=1)

        return df_agg

    def _get_unique_agg_fuel_types(self):

        unique_fuel_types = set()

        for k, v in self.plant_fuel_type:

            unique_agg_fuel_types.add(v)

        return list(unique_fuel_types)

    def get_states(self) -> list:
        states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
                  "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
                  "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
                  "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
                  "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]

        self.states = states

    def build_nerc(self) -> dict:

        self.layout = {"NERC": {
            "WECC": ["WA", "OR", "CA", "ID",
                     "NV", "AZ", "MT", "WY",
                     "UT", "CO", "NM"],
            "MRO": ["ND", "SD", "NE", "KS",
                    "OK", "IA", "MN", "WI"],
            "RF": ["MI", "IN", "OH", "PA",
                   "WV", "MD", "DE", "NJ",
                   "DC"],
            "SERC": ["MO", "AR", "LA", "IL", "KY", "VA", "TN", "NC",
                     "SC", "GA", "AL", "MS", "FL"],
            "NPCC": ["NY", "CT", "RI", "MA",
                     "VT", "NH", "ME"],
            "TEXAS": ["TX"],
            "ALASKA": ["AK"],
            "HAWAII": ["HI"],
        }
        }

    def get_plant_fuel_types(self) -> dict:

        self.plant_fuel_types = {
            "hydroelectric": "WAT",
            "bituminous coal": "BIT",
            "subbituminous coal": "SUB",
            "black liquour": "BLQ",
            "tire-derived fuels": "TDF",
            "petroleum coke": "PC",
            "synthetic coal": "SC",
            "biogenic municipal solid waste": "MSB",
            "Disolate Fue Oil": "DFO",
            "Other": "OTH",
            "landfill gas": "LFG",
            "gaseous propane": "PG",
            "waste/other coal": "WC",
            "waste/other oil": "WO",
            "other gas": "OG",
            "kerosene": "KER",
            "residual fuel oil": "RFO",
            "lignite coal": "LIG",
            "other biomass solids": "OBS",
            "jet fuel": "JF",
            "coal-derived synthetic gas": "SGC",
            "blast furnace gas": "BFG",
            "Wind": "WND",
            "Solar": "SUN",
            "Nuclear": "NUC",
            "agricultural by-products": "AB",
            "sludge waste": "SLW",
            "purchased steam": "PUR",
            "other biomass gas": "OBG",
            "subbituminous coal": "SUB",
            "geothermal": "GEO",
            "batteries or other electricity energy sources": "MWH",
            "waste heat": "WH", "non-biogenic municipal solid waste": "MSN",
            "wood/wood waste solids": "WDS",
            "municipal solid waste": "MSW",
            "Natural Gas": "NG",
            "biogenic municipal solid waste": "MSB",
            "refined coal": "RC",
        }

def get_plant_fuel_type_agg_tags(self) -> dict:

        self.plant_fuel_type_agg_tags = {
            "WAT": "Hydroelectric",
            "BIT": "Coal",
            "SUB": "Coal",
            "WC": "Coal",
            "LIG": "Coal",
            "SC": "Coal",
            "SGC": "Coal",
            "SUB": "Coal",
            "RC": "Coal",
            "MSB": "Biomass",
            "OBS": "Biomass",
            "LFG": "Biomass",
            "AB": "Biomass",
            "SLW": "Biomass",
            "OBG": "Biomass",
            "WDS": "Biomass",
            "MSB": "Biomass",
            "BLQ": "Biomass",

            "PG": "Oil Gas",
            "WO": "Oil Gas",
            "OG": "Oil Gas",
            "KER": "Oil Gas",
            "RFO": "Oil Gas",
            "JF": "Oil Gas",
            "BFG": "Oil Gas",
            "TDF": "Oil Gas",
            "PC": "Oil Gas",
            "DFO": "Oil Gas",

            "WND": "Wind",
            "SUN": "Solar",
            "NUC": "Nuclear",
            "NG": "Natural Gas",

            "GEO": "Geothermal",
            "MWH": "batteries or other use of electricity as an energy source",

            "MSN": "Municipal Waste",
            "MSW": "Municipal Waste",

            "OTH": "Other",
            "PUR": "Other",
            "WH": "Other",

        }


class Solution:
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        return self.findPemutation(n, k)

    def findPemutation(self, n, k):

        nummap = { 1: 0, 2: 1, 3: 2, 4: 6, 5: 24, 6: 120, 7: 720, 8: 5040, 9: 40320}
        nums = list(map(str,list(range(1,n+1))))
        res = ""
        while k:
            if n == 1:
                return res + nums.pop()
            mod = k % nummap[n]
            quotient = k // nummap[n]
            if mod == 0:
                res += nums.pop(quotient-1)
                return res + "".join(sorted(nums,reverse=True))
            elif mod == 1:
                res += nums.pop(quotient)
                return res + "".join(sorted(nums))
            else:
                res += nums.pop(quotient)
                k = mod
                n = n-1


import shotgun_api3
import nuke
import os
import re

def get_shotgun_module():
    # connect
    sgl = sg_connect()
    sg = sgl.script_auth(script_name="Toolkit", api_key="")
    return sg

sg = get_shotgun_module()

def check_plate():
    try:
        # get plate version data from shotgun
        filters = [
                      ['project.Project.name', 'is', os.environ.get('SHOW')],
                      ['code', 'is', '{0}_{1}'.format(
                        os.environ.get('SEQ'), os.environ.get('SHOT'))
                      ]
        ]
        plate_data = sg.find_one('Shot',
                                 filters=filters,
                                 fields=['code', 'sg_shot_type', 'sg_plate_ver'])
    except:
        return

    # return if couldn't find any field values
    if not plate_data:
        return

    # convert version integers to regular-expression pattern
    if not plate_data['sg_shot_type'] or not plate_data['sg_plate_ver']:
        return

    plate_data['type'] = change_int_to_pattern(plate_data['sg_shot_type'])
    plate_data['ver'] = change_int_to_pattern(plate_data['sg_plate_ver'])

    # mapping latest plate version and pattern
    plate_pattern = '{code}_{type}_{ver}'.format(**plate_data)
    plate_ver = '{code}_{sg_shot_type}_{sg_plate_ver}'.format(**plate_data)

    # check all read nodes
    old_read = []
    for node in nuke.allNodes('Read'):
        file_path = node['file'].value()
        file_path_ver = os.path.basename(file_path)

        # only running in plate directory
        if '/plate/' not in file_path:
            continue

        matched_pattern = re.search(plate_pattern, file_path_ver)
        if matched_pattern and not file_path_ver.startswith(plate_ver):
            old_read.append('[%s] %s' % (node.name(), file_path_ver.split('.')[0]))
        if matched_pattern and plate_ver.split('_')[-2] != file_path_ver.split('_')[-2]:
            old_read.append('[%s] %s' % (node.name(), file_path_ver.split('.')[0]))

    # finally, show up the alert
    if old_read:
        comment = 'The following plate version is not up-to-date:\n\n%s' % '\n'.join(sorted(old_read))
        comment += '\n\n\nLatest version: '
        comment += '\n%s' % plate_ver
        nuke.message(comment)

def check_cutIO():
    try:
        # get plate version data from shotgun
        filters = [
                      ['project.Project.name', 'is', os.environ.get('SHOW')],
                      ['code', 'is', '{0}_{1}'.format(
                        os.environ.get('SEQ'), os.environ.get('SHOT'))
                      ]
        ]
        plate_data = sg.find_one('Shot',
                                 filters=filters,
                                 fields=['code', 'sg_cut_in', 'sg_cut_out'])
    except:
        return

    # return if couldn't find any field values
    if not plate_data:
        return

    # convert version integers to regular-expression pattern
    if not plate_data['sg_cut_in'] or not plate_data['sg_cut_out']:
        return

    comment_before = []
    comment_after = []
    if plate_data['sg_cut_in'] and plate_data['sg_cut_out']:
        root_cut_in = nuke.root().firstFrame()
        root_cut_out = nuke.root().lastFrame()
        if root_cut_in != int(plate_data['sg_cut_in']):
            comment_before.append('[Cut In] %s' % root_cut_in)
            comment_after.append('[Cut In] %s' % int(plate_data['sg_cut_in']))
        if root_cut_out != int(plate_data['sg_cut_out']):
            comment_before.append('[Cut Out] %s' % root_cut_out)
            comment_after.append('[Cut Out] %s' % int(plate_data['sg_cut_out']))

    if comment_before:
        comment = 'Please check the shotgrid information.\n'
        comment += '(Sync Frame Range with Shotgun)\n\n'
        comment += 'current setting:\n%s' % ' / '.join(comment_before)
        comment += '\n\nLatest info:'
        comment += '\n%s' % ' / '.join(comment_after)
        nuke.message(comment)

def check_MetaData():
    try:
        # get plate version data from shotgun
        filters = [
                      ['project.Project.name', 'is', os.environ.get('SHOW')],
                      ['code', 'is', '{0}_{1}'.format(
                        os.environ.get('SEQ'), os.environ.get('SHOT'))
                      ]
        ]
        plate_data = sg.find_one('Shot',
                                 filters=filters,
                                 fields=['code', 'sg_shot_type', 'sg_plate_ver', 'sg_cut_in', 'sg_cut_out'])
    except:
        return

    # return if couldn't find any field values
    if not plate_data:
        return

    # convert version integers to regular-expression pattern
    if not plate_data['sg_shot_type'] or not plate_data['sg_plate_ver']:
        return
    if not plate_data['sg_cut_in'] or not plate_data['sg_cut_out']:
        return

    if nuke.toNode('MetadataCopy'):
        Metadata = nuke.toNode('MetadataCopy')
        plate_type = plate_data['sg_shot_type']
        plate_code = '%s_%s_%s' % (plate_data['code'], plate_type, plate_data['sg_plate_ver'])
        plate_path = '%s/plate/%s/%s/%s.%s' % (os.environ.get('SHOTDIR'), plate_type, plate_code, plate_code, '%04d.exr')
        Metadata['org_path'].setValue(plate_path)
        Metadata['first'].setValue(int(plate_data['sg_cut_in']))
        Metadata['last'].setValue(int(plate_data['sg_cut_out']))

def change_int_to_pattern(text):
    """return a regular-expression pattern from given text"""
    digit = [n for n in text if n.isdigit()]
    pattern = text.replace(''.join(digit), '[0-9]{%s}' % len(digit) if digit else '')
    return pattern


from algoliasearch import algoliasearch

def search_all(query):
    client = algoliasearch.Client("1SS7XPOA8X",
                                  '9375902912f6f82964c8ec269234b3c2')
    index = client.init_index('nprorg')
    res = index.search(query,
                       {'hitsPerPage': 10}
                       )
    # for audio-only search, add 'hasAudio:true', to filters above.
    # storyIDs = [i['objectID'] for i in res['hits']]
    try:
        return res['hits']
    except:
        return res

def search_podcasts(query):
    for res in search_all(query):
        try:
            yield {"summary": res["teaser"],
                   "episodes": res.get("episodes", []),
                   "podcast": res["podcast"],
                   "date": res["displayDate"]["longDate"],
                   "type": res["type"],
                   "title": res["title"],
                   "url": res["url"]
                   }
        except:
            # not a podcast
            pass

if __name__ == "__main__":
    from pprint import pprint

    pprint(search_all("science")[0])


import unittest
import utils
import numpy as np

class PerceptionTest(unittest.TestCase):

    def test_shortDistanceToBox(self):
        # Distance from the point to the box
        bbox = np.array([[0,0], [1,0], [1,1], [0,1], [0, 0]])
        point = np.array([0.5, 0.5])
        d = utils.shortDistanceToBox(bbox, point)
        self.assertTrue(d, 0.5)

        point = np.array([0.5, 0])
        d = utils.shortDistanceToBox(bbox, point)
        self.assertLess(d, np.finfo(float).tiny)

        point = np.array([0, 0.5])
        d = utils.shortDistanceToBox(bbox, point)
        self.assertLess(d, np.finfo(float).tiny)

    def test_getRectFit(self):
        # Rectangle fit to the points with min area fitting
        bbox = np.array([[0,0], [1,0], [1,1], [0,1]])
        bp, center, size, orientation = utils.getRectFit(bbox, minAreaFit=True)
        self.assertListEqual(center, [0.5, 0.5])
        self.assertListEqual(size, [1, 1])
        self.assertEqual(orientation, 90.0)

        # Rectangle fit to the points without min area fitting
        bp, center, size, orientation = utils.getRectFit(bbox, minAreaFit=False)
        self.assertListEqual(center, [0.5, 0.5])
        self.assertListEqual(size, [1, 1])
        self.assertEqual(orientation, 0)

        # Size of the bounding rectangle if it contains only one point
        bbox = np.array([[1.2, 2.1]])
        bp, center, size, orientation = utils.getRectFit(bbox, minAreaFit=True)
        self.assertIsNone(np.testing.assert_array_equal(center, bbox.squeeze()))
        self.assertListEqual(size, [0., 0.])

    def test_filterPoints(self):
        # Checking size of filtered points
        bbox = np.array([[0,0], [1,0], [1,1], [0,1], [0, 0]])
        point = np.array([[0.1, 0.5]])
        filtered_points = utils.filterPoints(bbox, point)
        self.assertTupleEqual(filtered_points.shape, (0,2))

        point = np.array([[0.5, 0.5]])
        filtered_points = utils.filterPoints(bbox, point)
        self.assertTupleEqual(filtered_points.shape, (1,2))

    def test_boundsWithMinArea(self):
        width, height = 15, 10
        maxlevel = 5
        angles = list(range(0,100,10))
        L1 = [10,10.154,10.642,8,6.57,7.779,10,15.962,15.231,15]
        L2 = [15,15.231,15.963,10,7.779,7.779,11.547,10.642,10.154,10]
        dataset = utils.getDataset(L1, L2, angles, width, height)
        bpoints, *_ = utils.getRectFit(dataset, minAreaFit=True)
        filtered_dataset = utils.filterPoints(bpoints, dataset)
        _, center, size, orientation = utils.getRectFit(filtered_dataset, minAreaFit=True)
        self.assertListEqual(center, [6.85344765625, 5.53761875])
        self.assertListEqual(size, [1.83545078125, 6.077576171875])
        self.assertEqual(orientation, 80.82377624511719)

    def test_boundsWithoutMinArea(self):
        width, height = 15, 10
        maxlevel = 5
        angles = list(range(0,100,10))
        L1 = [10,10.154,10.642,8,6.57,7.779,10,15.962,15.231,15]
        L2 = [15,15.231,15.963,10,7.779,7.779,11.547,10.642,10.154,10]
        dataset = utils.getDataset(L1, L2, angles, width, height)
        bpoints, *_ = utils.getRectFit(dataset, minAreaFit=True)
        filtered_dataset = utils.filterPoints(bpoints, dataset)
        _, center, size, orientation = utils.getRectFit(filtered_dataset, minAreaFit=False)
        self.assertListEqual(center, [6.999877592124205, 5.964101615137754])
        self.assertListEqual(size, [5.999755184248411, 1.9282032302755105])
        self.assertEqual(orientation, 0.0)

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


import sys
sys.stdin = open("C:\\Users\\82103\\pythonprogramming\\baekjoon\\input.txt","rt")

T = int(input())
dp = [[0]*30 for _ in range(30)]
for i in range(30):
    for j in range(30):
        if i == 1:
            dp[i][j] = j
        else:
            if i == j:
                dp[i][j] = 1
            elif i < j:
                dp[i][j] = dp[i-1][j-1] + dp[i][j-1]

for _ in range(T):
    n, m = map(int, input().split())
    print(dp[n][m])


from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.http import Http404, HttpResponse
from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _
from social_auth.utils import setting

def username_available(request):
    if request.method == "GET":
        p = request.GET.copy()
        if p.has_key('username'):
            name = p['username']
            if User.objects.filter(username__iexact = name):
                return HttpResponse(False)
            else:
                return HttpResponse(True)
    return Http404

class UsernameForm(forms.Form):
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
    }
    username = forms.RegexField(label=_("Username"), max_length=30,
        regex=r'^[\w.-]+$',
        help_text = _("30 characters or fewer. Letters, digits and "
                      "./-/_ only."),
        error_messages = {
            'invalid': _("This value may contain only letters, numbers and "
                         "./-/_ characters.")})

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

def username_form(request):
    if request.method == 'POST':
        form = UsernameForm(request.POST)
        if form.is_valid():
            name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline')
            request.session['saved_username'] = form.cleaned_data['username']
            backend = request.session[name]['backend']
            return redirect('socialauth_complete', backend=backend)
    else:
        form = UsernameForm()
    name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline')
    backend = request.session[name]['backend']
    details = request.session[name]['kwargs']['details']
    try:
        orig_username = details['username']
        if not orig_username: orig_username = details['email']
        if not orig_username: orig_username = details['first_name']
    except KeyError:
        pass
    return render(request, 'username_form.html', {'backend': backend, 'username': orig_username, 'form': form})


try:
    from urllib import quote_plus  # python 2
except:
    pass

try:
    from urllib.parse import quote_plus  # python 3
except:
    pass

from django.contrib import messages
from django.contrib.auth.decorators import login_required

from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render, get_object_or_404

from .forms import CommentForm
from .models import Comment

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.utils import timezone

from rest_framework import generics
from rest_framework.mixins import DestroyModelMixin, UpdateModelMixin
from posts.pagination import PostLimitOffsetPagination, \
    PostPageNumberPagination
from rest_framework.filters import SearchFilter, OrderingFilter
from posts.permissions import IsOwnerOrReadOnly
from rest_framework.permissions import (AllowAny, IsAuthenticated, IsAdminUser,
                                        IsAuthenticatedOrReadOnly)
from .serializers import (CommentListSerializer, CommentDetailSerializer)

@login_required  # (login_url='/login/') #LOGIN_URL = '/login/'
def comment_delete(request, id):
    # obj = get_object_or_404(Comment, id=id)
    # obj = CommentFormmment.objects.get(id=id)
    try:
        obj = Comment.objects.get(id=id)
    except:
        raise Http404

    if obj.user != request.user:
        # messages.success(request, "You do not have permission to view this.")
        # raise Http404
        reponse = HttpResponse("You do not have permission to do this.")
        reponse.status_code = 403
        return reponse
        # return render(request, "confirm_delete.html", context, status_code=403)

    if request.method == "POST":
        parent_obj_url = obj.content_object.get_absolute_url()
        obj.delete()
        messages.success(request, "This has been deleted.")
        return HttpResponseRedirect(parent_obj_url)
    context = {
        "object": obj
    }
    return render(request, "confirm_delete.html", context)

def comment_thread(request, id):
    # obj = Comment.objects.get(id=id)
    try:
        obj = Comment.objects.get(id=id)
    except:
        raise Http404

    if not obj.is_parent:
        obj = obj.parent

    content_object = obj.content_object  # Post that the comment is on
    content_id = obj.content_object.id

    initial_data = {
        "content_type": obj.content_type,
        "object_id": obj.object_id
    }
    form = CommentForm(request.POST or None, initial=initial_data)
    if form.is_valid() and request.user.is_authenticated():
        c_type = form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = form.cleaned_data.get('object_id')
        content_data = form.cleaned_data.get("content")
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()

        new_comment, created = Comment.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=obj_id,
            content=content_data,
            parent=parent_obj,
        )
        return HttpResponseRedirect(
            new_comment.content_object.get_absolute_url())

    context = {
        "comment": obj,
        "form": form,
    }
    return render(request, "comment_thread.html", context)

class CommentListAPIView(generics.ListAPIView):
    serializer_class = CommentListSerializer
    queryset = Comment.objects.all()
    # filter_backends = [SearchFilter, OrderingFilter]
    # search_fields = ['title', 'content', 'user__first_name']
    # pagination_class = PostPageNumberPagination  # PageNumberPagination
    #
    # def get_queryset(self, *args, **kwargs):
    #     queryset_list = Post.objects.all()
    #     query = self.request.GET.get("q")
    #     if query:
    #         queryset_list = queryset_list.filter(
    #             Q(title__icontains=query) |
    #             Q(content__icontains=query) |
    #             Q(user__first_name__icontains=query) |
    #             Q(user__last_name__icontains=query)
    #         ).distinct()
    #     return queryset_list

class CommentDetailAPIView(DestroyModelMixin, UpdateModelMixin,
                           generics.RetrieveAPIView):
    queryset = Comment.objects.filter(id__gte=0)
    serializer_class = CommentDetailSerializer
    permission_classes = [IsOwnerOrReadOnly]
    lookup_field = 'id'

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

# class PostDeleteAPIView(generics.DestroyAPIView):
#     queryset = Post.objects.all()
#     serializer_class = PostDetailSerializer
#     permission_classes = [IsAuthenticated]
#     lookup_field = 'slug'


import glob
import os.path
import shutil
import subprocess
import time
import argparse
import json

SUBDIRS=["BlindW-RW-Cheng-2000txns-8oppertxn-threads24-I0-D0-R50-U50-RANGEE0-SI2-2022-09-13-14-04-10",
         "BlindW-RW-Cheng-5000txns-8oppertxn-threads24-I0-D0-R50-U50-RANGEE0-SI2-2022-09-12-13-05-17"]

SIZES=["2k", "5k"]
EXAMPLES=["G1c", "G-SIb", "long_fork"]

TIMEOUT = 60

def call_with_timeout(cmd, log_dir, algo):
    print(f"Executing {' '.join(cmd)}")
    try:
        subprocess.run(cmd, stderr=subprocess.STDOUT, timeout=TIMEOUT)
    except subprocess.TimeoutExpired as e:
        print(f"{log_dir} using {algo} timeouts")
        print(e)

def elle(log_folder, output_file, elle_path):
    perf_rs = {}
    for i, exp_dir in enumerate(SUBDIRS):  # 10s-20220518T161953.000Z
        for anomaly in EXAMPLES:
            exp_name = f"Elle_{SIZES[i]}_{anomaly}"
            log_path = os.path.join(log_folder, anomaly, exp_dir, "jepsen", "history.edn")
            print(f"log_folder={log_folder}, exp_dir={exp_dir}, log_path={log_path}")
            cmd = ["java", "-jar", elle_path, "--model", "rw-register", "-f", "edn",
                   log_path, "-c", "snapshot-isolation"]
            t1 = time.time()
            call_with_timeout(cmd, exp_dir, "elle")
            t2 = time.time()
            dur = t2 - t1
            print(f"elle {log_path} consumes {dur}s")
            perf_rs[exp_name] = dur
    with open(output_file, "a") as f:
        result_str = json.dumps(perf_rs)
        f.write(result_str + "\n")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--log_folder", type=str)
    parser.add_argument("--perf_file", type=str,
                        help="which file to store the performance results in for later figure plotting")
    parser.add_argument("--elle", type=str, help="the path of the elle-cli jar")
    args = parser.parse_args()
    elle(args.log_folder, args.perf_file, args.elle)


#!/usr/bin/env python3.5
"""Model of a multi-lane road controler"""
# -*- coding: utf-8 -*-

#import classes.Vehicle
import random
import classes.Vehicle as Vehicle

class Controller:
    """Model of a multi-lane road controler"""

    def __init__(self, setup):
        self.__setup = setup
        self.__vehicles = []
        self.__vehicle_archive = []

        setup_line = setup.get('lanes')
        self.__n_lanes = setup_line.get('n_lanes')
        self.__lane_length = setup_line.get('lane_length')
        self.__lane_v = setup_line.get('lane_v')

    def act(self, timestep):
        """ determines how the vehicles act and follow the plan  """
        print("Calculate decision of each vehicle at timestep " + str(timestep))
        for vehicle in self.__vehicles:
            vehicle.decide(timestep)

    def plan(self, timestep):
        """ models the global control strategy for the road """
        print("Calculate new targets for vehicles at timestep " + str(timestep))

        for vehicle in reversed(self.__vehicles):
            print(str(vehicle))
            vehicle.set_desired_lane(vehicle.get_lane())
            vehicle.set_desired_velocity(self.__lane_v[vehicle.get_lane()])

    def update(self, timestep):
        """ models the transition between the vehicle's state at timestep i and i+1  """
        print("Calculate new state of system at timestep " + str(timestep))

        for vehicle in self.__vehicles:
            vehicle.update(timestep)
            print(str(vehicle))

        # sort vehicles by their position
        self.__vehicles = sorted(
            self.__vehicles, key=lambda vehicle: vehicle.get_position())

        # remove vehicles, which left the system
        while self.__vehicles and self.__vehicles[-1].get_position() >= self.__lane_length:
            vehicle = self.__vehicles.pop()
            # move archived vehicles to lane n_lane to mark thar vehicle is not in system anymore
            vehicle.position_archive[timestep + 1:, 1] = self.__n_lanes
            vehicle.position_archive[timestep + 1:, 0] = self.__lane_length
            self.__vehicle_archive.append(vehicle)

        # update predecessors and add new vehicles
        last = [None] * self.__n_lanes
        new_vehicles = [None] * self.__n_lanes
        for vpos, vehicle in enumerate(self.__vehicles):
            lastVehicle = last[vehicle.get_lane()]

            if lastVehicle:
                # if lastVehicle and vehicle are closer than horizon lastVehicle knows about vehicle
                assert vehicle.get_position() - lastVehicle.get_position() > lastVehicle.safety_distance()

                if abs(vehicle.get_position() - lastVehicle.get_position() < lastVehicle.get_horizon()):
                    lastVehicle.set_predecessor(vehicle)
            else:
                # a new vehicle is created when the distance between the new vehicle and vehicle close to the horizon
                if self.__setup.get('cars').get('horizon') * self.__setup.get('lanes').get('spawn_parameter') < vehicle.get_position():
                    lane = vehicle.get_lane()
                    new_vehicles[lane] = self.create_vehicle(lane, timestep)

            last[vehicle.get_lane()] = vehicle
            vehicle.set_predecessor(None)

        # Add new cars into list
        for lane in range(self.__n_lanes):
            if new_vehicles[lane]:
                print("creating new vehicle")
                self.__vehicles.insert(0, new_vehicles[lane])

    def create_vehicle(self, lane, timestep):
        return Vehicle.Vehicle(
            "v_" + str(lane) + "_" + str(timestep), lane, self.__lane_v[lane], timestep, self.__setup)

    def init(self):
        for lane in range(self.__n_lanes):
            print(lane)
            self.__vehicles.insert(0, self.create_vehicle(lane, 0))

    def get_vehicles(self):
        return self.__vehicle_archive + self.__vehicles


# regression baybay
import pandas as pd
import statsmodels.api as sm

def suit_fit(dataframe, y_col, x_cols):
    """
    Performs linear regression on the given data.

    Parameters:
    - dataframe (pd.DataFrame): The data to perform regression on.
    - y_col (str): The dependent variable column.
    - x_cols (list): The independent variable(s) column(s).

    Returns:
    - regression_result (statsmodels.regression.linear_model.RegressionResultsWrapper): The regression results.
    """

    # Define the dependent and independent variables
    Y = dataframe[y_col]
    X = dataframe[x_cols]

    # Add a constant to the independent variable(s) for the intercept
    X = sm.add_constant(X)

    # Create a model
    model = sm.OLS(Y, X)

    # Fit the model
    regression_result = model.fit()

    # Print the summary of the regression
    print(regression_result.summary())

    return regression_result

# regression formula
def get_tailor(regression_result, y_col, x_cols):
    """
    Generates the linear formula from the regression result.

    Parameters:
    - regression_result (statsmodels.regression.linear_model.RegressionResultsWrapper): The regression results.
    - y_col (str): The dependent variable column name.
    - x_cols (list): The independent variable(s) column(s) names.

    Returns:
    - formula (str): The linear formula.
    """

    # Extracting coefficients and the intercept
    coefficients = regression_result.params
    formula_terms = [f"{y_col} = {coefficients[0]:.4f} (Intercept)"]

    for idx, col in enumerate(x_cols, 1):
        formula_terms.append(f"{coefficients[idx]:+.4f}*{col}")

    formula = " + ".join(formula_terms)
    return formula


def compute_probs(neg,pos):
  p0 = neg/(neg+pos)
  p1 = pos/(neg+pos)
  return [p0,p1]

def test_it():
  return 'loaded'

def cond_prob(table, evidence, evidence_value, target, target_value):
  t_subset = up_table_subset(table, target, 'equals', target_value)
  e_list = up_get_column(t_subset, evidence)
  p_b_a = sum([1 if v==evidence_value else 0 for v in e_list])/len(e_list)
  return p_b_a + .01

def cond_probs_product(table, evidence_values, target_column, target_val):
  table_columns = up_list_column_names(table)
  evidence_columns = table_columns [:-1]
  evidence_complete = up_zip_lists (evidence_columns, evidence_values)
  cond_prob_list = []
  for evidence_column, evidence_val in evidence_complete:
    cond_prob_value = cond_prob (table, evidence_column, evidence_val, target_column, target_val)
    cond_prob_list += [cond_prob_value]
  partial_numerator = up_product (cond_prob_list)
  return partial_numerator

def prior_prob (table, target, target_value):
  t_list = up_get_column(table, target)
  p_a = sum([1 if v==target_value else 0 for v in t_list])/len(t_list)
  return p_a

def naive_bayes(table, evidence_row, target):
  target_value = 0
  result1 = cond_probs_product(table, evidence_row, target, target_value)* prior_prob(table, target, target_value)
  target_value = 1
  result2 = cond_probs_product(table, evidence_row, target, target_value)* prior_prob(table, target, target_value)
  neg, pos = compute_probs(result1, result2)
  return [neg, pos]

def metrics (zipped_list):
  assert isinstance(zipped_list, list), f'parameter must be a list'
  assert all([isinstance(item, list) for item in zipped_list]), f'parameter must be a list of lists'
  assert all([len(item)==2 for item in zipped_list]), f'parameter must be a zipped list'
  assert all([isinstance(a, (int, float)) and isinstance(b, (int, float)) for a,b in zipped_list]), f'each value must be an int or a float'
  assert all(a >=0 and b>=0 for a,b in zipped_list), f'each value must be >= 0'
  tn = sum([1 if pair==[0,0] else 0 for pair in zipped_list])
  tp = sum([1 if pair==[1,1] else 0 for pair in zipped_list])
  fp = sum([1 if pair==[1,0] else 0 for pair in zipped_list])
  fn = sum([1 if pair==[0,1] else 0 for pair in zipped_list])
  precision = tp/(tp + fp) if tp + fp > 0 else 0
  recall = tp/(tp + fn) if tp + fn > 0 else 0
  f1 = (2* precision * recall) / (precision + recall) if precision + recall > 0 else 0
  accuracy = (tp + tn) / (tn+tp+fn+fp) if (tn+tp+fn+fp) >0 else 0
  return {'Precision': precision, 'Recall': recall, 'F1': f1, 'Accuracy': accuracy}

from sklearn.ensemble import RandomForestClassifier  #make sure this makes it into your library
def run_random_forest(train, test, target, n):
  X = up_drop_column(train, target)
  y = up_get_column(train,target)
  k_feature_table = up_drop_column(test, target)
  k_actuals = up_get_column(test, target)
  clf = RandomForestClassifier(n_estimators=n, max_depth=2, random_state=0)
  clf.fit(X, y)  #builds the trees as specified above
  probs = clf.predict_proba(k_feature_table)
  pos_probs = [p for n,p in probs]  #probs is list of [neg,pos] like we are used to seeing.
  pos_probs[:5]
  all_mets = []
  for t in thresholds:
    all_predictions = [1 if pos>t else 0 for pos in pos_probs]
    pred_act_list = up_zip_lists(all_predictions, k_actuals)
    mets = metrics(pred_act_list)
    mets['Threshold'] = t
    all_mets = all_mets + [mets]
  all_mets[:2]
  metrics_table = up_metrics_table(all_mets)
  metrics_table
  print(metrics_table)  #output we really want - to see the table
  return None

def try_archs(full_table, target, architectures, thresholds):
  train_table, test_table = up_train_test_split(full_table, target, .4)
  for arch in all_architectures:
    all_results = up_neural_net(train_table, test_table, arch, target)
  all_mets = []
  for t in thresholds:
    all_predictions = [1 if pos>=t else 0 for neg,pos in all_results]
    pred_act_list = up_zip_lists(all_predictions, up_get_column(test_table, target))
    mets = metrics(pred_act_list)
    mets['Threshold'] = t
    all_mets += [mets]
    all_mets[:2]
  print(f'Architecture: {arch}')
  print(up_metrics_table(all_mets))
  return None
  print(up_metrics_table(all_mets))


import random
import math
import numpy as np
import matplotlib.pyplot as plt

class Node:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.parent = None
        self.cost = 0

class RRTStar:
    def __init__(self, start, goal, circle_obstacle_list, poly_obstacle_list, rand_area, max_iter=1000, expand_dist=0.2, goal_sample_rate=5, max_distance=1.0):
        self.start = Node(start[0], start[1])
        self.goal = Node(goal[0], goal[1])
        self.min_rand_x = rand_area[0]
        self.max_rand_x = rand_area[1]
        self.min_rand_y = rand_area[2]
        self.max_rand_y = rand_area[3]

        self.circle_obstacle_list = circle_obstacle_list
        self.poly_obstacle_list = poly_obstacle_list
        self.obstacle_list = circle_obstacle_list
        self.max_iter = max_iter
        self.expand_dist = expand_dist
        self.goal_sample_rate = goal_sample_rate
        self.max_distance = max_distance

    def plan(self):
        self.node_list = [self.start]
        for i in range(self.max_iter):
            rnd = self.get_random_node()                                # Get a random node
            nearest_index = self.get_nearest_node_index(rnd)            # Find the nearest node index
            nearest_node = self.node_list[nearest_index]                # Get the nearest node

            new_node = self.steer(nearest_node, rnd)                    # Steer from the random node based on the nearest node

            if self.check_collision(new_node, self.circle_obstacle_list, self.poly_obstacle_list):          # Check if the new node collides with an obstacle
                near_indices = self.find_near_nodes(new_node)                                               # Find the near nodes in a radius of max_distance
                node_with_min_cost = self.choose_parent(new_node, near_indices)                             # Choose the parent node with the lowest cost
                self.node_list.append(new_node)                                                             # Add the new node to the node list
                self.rewire(node_with_min_cost, new_node, near_indices)                                     # Rewire the tree if a better path is found

            # if i % 20 == 0:
            #     self.draw_graph(rnd)                                                                        # Draw the graph every 5 iterations

        last_index = self.get_best_last_index()                                                             # Get the index of the node with the lowest cost
        if last_index is None:
            return None

        path = self.generate_final_course(last_index)                                                       # Generate the final path
        return path

    # Returns a random node within the specified bounds.
    def get_random_node(self):
        if random.randint(0, 100) > self.goal_sample_rate:
            rnd = Node(random.uniform(self.min_rand_x, self.max_rand_x),
                       random.uniform(self.min_rand_y, self.max_rand_y))
        else:
            rnd = Node(self.goal.x, self.goal.y)

        return rnd

    # Connect two nodes with a line segment and calculate the cost
    def steer(self, from_node, to_node):
        new_node = Node(from_node.x, from_node.y)
        d = math.sqrt((to_node.x - new_node.x) ** 2 + (to_node.y - new_node.y) ** 2)
        theta = math.atan2(to_node.y - new_node.y, to_node.x - new_node.x)
        new_node.x += self.expand_dist * math.cos(theta)
        new_node.y += self.expand_dist * math.sin(theta)
        new_node.parent = from_node
        new_node.cost = from_node.cost + d
        return new_node

    # Chooses the parent node that results in the minimum cost for a given node.
    def choose_parent(self, new_node, near_indices):
        if len(near_indices) == 0:
            return None

        costs = []
        for i in near_indices:
            near_node = self.node_list[i]
            if self.check_collision(new_node, self.obstacle_list, self.poly_obstacle_list):
                d = math.sqrt((near_node.x - new_node.x) ** 2 + (near_node.y - new_node.y) ** 2)
                cost = near_node.cost + d
                costs.append(cost)
            else:
                costs.append(float("inf"))

        min_cost = min(costs)
        if min_cost == float("inf"):
            return None

        min_index = near_indices[costs.index(min_cost)]
        new_node.cost = min_cost
        new_node.parent = self.node_list[min_index]
        return self.node_list[min_index]

    # Rewires the tree by updating the parent and cost of nearby nodes if a better path is found.
    def rewire(self, node_with_min_cost, new_node, near_indices):
        for i in near_indices:
            near_node = self.node_list[i]
            d = math.sqrt((near_node.x - new_node.x) ** 2 + (near_node.y - new_node.y) ** 2)
            scost = new_node.cost + d
            if near_node.cost > scost and self.check_collision(new_node, self.circle_obstacle_list, self.poly_obstacle_list):
                near_node.parent = new_node
                near_node.cost = scost
                self.propagate_cost_to_leaves(near_node)

    # Propagates the cost of a node to all of its descendants.
    def propagate_cost_to_leaves(self, parent_node):
        for node in self.node_list:
            if node.parent == parent_node:
                d = self.node_distance(node, parent_node)
                node.cost = parent_node.cost + d
                self.propagate_cost_to_leaves(node)

    # Returns the indices of nodes that are within a certain distance of a given node.
    def find_near_nodes(self, new_node):
        n = len(self.node_list) + 1
        r = self.max_distance * math.sqrt((math.log(n) / n))
        indices = []
        for i, node in enumerate(self.node_list):
            if self.node_distance(node, new_node) <= r:
                indices.append(i)
        return indices

    # Find the index of the node in the tree that is closest to a given node
    def get_nearest_node_index(self, node):
        dlist = [(n.x - node.x) ** 2 + (n.y - node.y) ** 2 for n in self.node_list]
        min_index = dlist.index(min(dlist))

        return min_index

    # Check if a node collides with any obstacle in the obstacle list
    def check_collision(self, node, circle_obstacle_list, poly_obstacle_list):
        for i, obstacle in enumerate(poly_obstacle_list):
            x, y = node.x, node.y
            n = len(obstacle)
            p1x, p1y = obstacle[0]
            if_Safe_poly = True
            for i in range(n + 1):
                p2x, p2y = obstacle[i % n]
                if y > min(p1y, p2y):
                    if y <= max(p1y, p2y):
                        if x <= max(p1x, p2x):
                            if p1y != p2y:
                                x_inters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
                            if p1x == p2x or x <= x_inters:
                                if_Safe_poly = not if_Safe_poly
                p1x, p1y = p2x, p2y
            if if_Safe_poly == False:
                break

        for (ox, oy, size) in circle_obstacle_list:
            IF_Safe_circle = True
            dx = ox - node.x
            dy = oy - node.y
            d = math.sqrt(dx ** 2 + dy ** 2)
            if d <= size:
                IF_Safe_circle = False  # collision
                break

        IF_Safe = IF_Safe_circle and if_Safe_poly
        return IF_Safe

    def get_best_last_index(self):
        goal_node = Node(self.goal.x, self.goal.y)
        n = len(self.node_list)
        r = self.max_distance * math.sqrt((math.log(n) / n))
        near_goal_indices = []
        for i, node in enumerate(self.node_list):
            if self.node_distance(node, goal_node) <= r:
                near_goal_indices.append(i)

        if len(near_goal_indices) == 0:
            return None

        min_cost = min([self.node_list[i].cost for i in near_goal_indices])
        for i in near_goal_indices:
            if self.node_list[i].cost == min_cost:
                return i
        return None

    # Generate the final path from the start to the goal
    def generate_final_course(self, goal_index):
        path = [[self.goal.x, self.goal.y]]
        node = self.node_list[goal_index]
        while node.parent is not None:
            path.append([node.x, node.y])
            node = node.parent
        path.append([self.start.x, self.start.y])
        return path

    # Distance between points and nodes
    def distance(self, n1, n2):
        return math.sqrt((n1.x - n2[0]) ** 2 + (n1.y - n2[1]) ** 2)

    # Distance between two nodes
    def node_distance(self, n1, n2):
        return math.sqrt((n1.x - n2.x) ** 2 + (n1.y - n2.y) ** 2)

    # Draw the RRT tree
    def draw_graph(self, rnd=None):
        plt.clf()
        if rnd is not None:
            plt.plot(rnd.x, rnd.y, "^k")

        for node in self.node_list:
            if node.parent:
                plt.plot([node.x, node.parent.x], [node.y, node.parent.y], "-g", linewidth=0.2)

        for (ox, oy, size) in self.circle_obstacle_list:
            self.plot_circle(ox, oy, size)

        for i, obstacle in enumerate(self.poly_obstacle_list):
            self.plot_polygon(obstacle, 'darkgray')

        plt.plot(self.start.x, self.start.y, "xr")
        plt.plot(self.goal.x, self.goal.y, "xr")
        plt.axis([self.min_rand_x, self.max_rand_x, self.min_rand_y, self.max_rand_y])
        plt.grid(True)
        plt.pause(0.01)

    # Plot a circle obstacle
    def plot_circle(self, x, y, size):
        deg = list(range(0, 360, 5))
        deg.append(0)
        xl = [x + size * math.cos(math.radians(d)) for d in deg]
        yl = [y + size * math.sin(math.radians(d)) for d in deg]
        plt.plot(xl, yl)

    # Define functions to plot obstacles
    def plot_polygon(self, polygon, color):
        x, y = zip(*polygon)
        plt.fill(x, y, color=color)

def main():
    start = (-2, -2)
    goal = (8, 6)
    circle_obstacle_list = [(2, 2, 1), (3, 3, 1), (4, 4, 1)]

    # Define the area
    rand_area = [-5, 15, -5, 15]
    static_obstacles = [
                        [(2, 2), (2, 8), (3, 8), (3, 3), (8, 3), (8, 2)],
                        [(6, 6), (7, 6), (7, 7), (6, 7)]
                        ]
    rrt_star = RRTStar(start, goal, circle_obstacle_list, static_obstacles, rand_area)
    path = rrt_star.plan()
    if path is None:
        print("Cannot find path")
    else:
        print("Found path")
        print(path)
        rrt_star.draw_graph()
        plt.plot([x for (x, y) in path], [y for (x, y) in path], color='blue', linewidth=3)
        plt.show()

if __name__ == '__main__':
    main()


import pandas as pd
import requests
from bs4 import BeautifulSoup

ds = pd.read_excel("WKTlength_test.xlsx")  # 讀取excel檔

for URL in ds['Concat']:  # 批次讀取網址
    response = requests.get(URL[5:])  # 爬蟲
    soup = BeautifulSoup(response.text, "html.parser")  # 設定原始碼條件"div", ...
    div_web = soup.find_all("div", class_="mapdata") and soup.find_all("div", id="map_google3_1")
    div_str = "".join(map(str, div_web))  # 轉換為string

    if ',"pos":[{' in div_str and div_str.count(',"pos":[{') == 1:  # 標示為Linestring
        # print(URL[:5] + ": is Linestring.")
        L_startsplit = div_str.split(',"pos":')  # 去除非坐標訊息
        for L_1 in L_startsplit:
            if L_1.startswith('[{"lat":'):
                L_2 = L_1.split(',"polygons":')
                for L_3 in L_2:
                    if L_3.startswith('[{"lat":') and L_3.endswith('}]'):
                        L_str = L_3.replace('[', '').replace('{"lat":', '') \
                            .replace(',"lon":', ',').replace('},', '; ').replace('}]}]', '')
                        Lturn_1 = L_str.split('; ')
                        my_Linestring = ''
                        for Lturn_2 in Lturn_1:  # 經緯度交換
                            Lturn_3 = Lturn_2.split(',')
                            Lturn_4 = Lturn_3[1] + ' ' + Lturn_3[0]
                            my_Linestring += str(Lturn_4 + ", ")  # 整合WKT格式
                        result_2 = (URL[:5] + ":LINESTRING (" + my_Linestring[:-2] + ")")

                        if len(result_2) >= 32762:  # WKT文字太長標記
                            print(URL[:5] + ": Too long. " + str(len(result_2)))

                        elif len(result_2) < 32762:
                            print(result_2)

    elif ',"pos":[{' in div_str and div_str.count(',"pos":[{') > 1:  # 標示為Multilinestring
        # print(URL[:5] + ": is Multilinestring.")
        M_step1 = div_str.split(',"pos":')  # 去除前段非坐標訊息
        Mmid_final = ''  # 整合最後一段以外的Linestring預留
        Mend_list = ''  # 為了加入最後一段的Linestring預留
        for M_step2 in M_step1:
            if M_step2.startswith('[{"lat":'):
                if M_step2.endswith(',"strokeWeight":"2"'):  # 去除中段非坐標訊息
                    M_step3_mid = M_step2.split(',{"text":')
                    for M_step4_mid in M_step3_mid:
                        if M_step4_mid.startswith('[{"lat":'):
                            # print(M_step4_mid)
                            M_str_mid = M_step4_mid.replace('[', '').replace('{"lat":', '') \
                                .replace(',"lon":', ',').replace('},', '; ').replace('}]}', '')
                            M_turn1_mid = M_str_mid.split('; ')
                            my_Mmid = ''
                            for M_turn2_mid in M_turn1_mid:  # 經緯度交換
                                M_turn3_mid = M_turn2_mid.split(',')
                                M_turn4_mid = M_turn3_mid[1] + ' ' + M_turn3_mid[0]
                                my_Mmid += str(M_turn4_mid + ", ")
                            Mmid_list = "(" + my_Mmid[:-2] + "), "  # 整合WKT格式
                            # print(Mmid_list)
                            for concat in Mmid_list:  # 最後一段以外的Linestring整併
                                Mmid_final += concat

                elif M_step2.endswith('</div>'):  # 去除後段非坐標訊息
                    M_step3_end = M_step2.split('],"polygons":')
                    for M_step4_end in M_step3_end:
                        if M_step4_end.startswith('[{"lat":'):
                            # print(M_step4_end)
                            M_str_end = M_step4_end.replace('[', '').replace('{"lat":', '') \
                                .replace(',"lon":', ',').replace('},', '; ').replace('}]}', '')
                            M_turn1_end = M_str_end.split('; ')
                            my_Mend = ''
                            for M_turn2_end in M_turn1_end:  # 經緯度交換
                                M_turn3_end = M_turn2_end.split(',')
                                M_turn4_end = M_turn3_end[1] + ' ' + M_turn3_end[0]
                                my_Mend += str(M_turn4_end + ", ")
                            Mend_list = ("(" + my_Mend[:-2] + "))")  # 整合WKT格式
                            # print(Mend_list)

        result_3 = (URL[:5] + ":MULTILINESTRING (" + Mmid_final + Mend_list)  # 加最後一段Linestring

        if len(result_3) >= 32762:  # WKT文字太長標記
            print(URL[:5] + ": Too long. " + str(len(result_3)))

        elif len(result_3) < 32762:
            print(result_3)

print("Finish!")

Web Crawler WKT and check string length.py


from modules.agents import REGISTRY as agent_REGISTRY
from modules.comm import REGISTRY as comm_REGISTRY
from components.action_selectors import REGISTRY as action_REGISTRY
import math
import torch as th
import torch.distributions as D
import torch.nn.functional as F
import numpy as np
import random

# This multi-agent controller shares parameters between agents
class TarCommMAC:
	def __init__(self, scheme, groups, args):
		self.n_agents = args.n_agents
		self.args = args
		self.comm_embed_dim = args.comm_embed_dim
		input_shape_for_comm = 0
		if args.comm:
			input_shape, input_shape_for_comm = self._get_input_shape(scheme)
		else:
			input_shape = self._get_input_shape(scheme)

		self._build_agents(input_shape)
		self.agent_output_type = args.agent_output_type

		self.action_selector = action_REGISTRY[args.action_selector](args)

		self.hidden_states = None

		if args.comm:
			self.comm = comm_REGISTRY[self.args.comm_method](input_shape_for_comm, args)

		self.is_print_once = False

		if self.args.env_args['print_rew']:
			self.c_step = 0
			self.cut_mean_num_list = []

	def select_actions(self, ep_batch, t_ep, t_env, bs=slice(None), test_mode=False, thres=0., prob=0.):
		# Only select actions for the selected batch elements in bs
		avail_actions = ep_batch["avail_actions"][:, t_ep]
		# if self.args.comm:
		#     agent_outputs, (_, _), _, _ = self.forward(ep_batch, t_ep, test_mode=test_mode)
		# else:
		agent_outputs = self.forward(ep_batch, t_ep, test_mode=test_mode, thres=thres, prob=prob)
		chosen_actions = self.action_selector.select_action(agent_outputs[bs], avail_actions[bs], t_env,
		                                                    test_mode=test_mode)
		return chosen_actions

	def forward(self, ep_batch, t, test_mode=False, thres=0., prob=0.):
		agent_inputs = self._build_inputs(ep_batch, t)

		if self.args.comm:
			(_, _), messages, _ = self._communicate(ep_batch.batch_size, agent_inputs,
			                                        self.hidden_states.detach(), test_mode,
			                                        thres=thres, prob=prob)
			agent_inputs = th.cat([agent_inputs, messages], dim=1)

		avail_actions = ep_batch["avail_actions"][:, t]
		agent_outs, self.hidden_states = self.agent(agent_inputs, self.hidden_states)

		# Softmax the agent outputs if they're policy logits
		# is not used in qmix
		if self.agent_output_type == "pi_logits":

			if getattr(self.args, "mask_before_softmax", True):
				# Make the logits for unavailable actions very negative to minimise their affect on the softmax
				reshaped_avail_actions = avail_actions.reshape(ep_batch.batch_size * self.n_agents, -1)
				agent_outs[reshaped_avail_actions == 0] = -1e10

			agent_outs = th.nn.functional.softmax(agent_outs, dim=-1)
			if not test_mode:
				# Epsilon floor
				epsilon_action_num = agent_outs.size(-1)
				if getattr(self.args, "mask_before_softmax", True):
					# With probability epsilon, we will pick an available action uniformly
					epsilon_action_num = reshaped_avail_actions.sum(dim=1, keepdim=True).float()

				agent_outs = ((1 - self.action_selector.epsilon) * agent_outs
				              + th.ones_like(agent_outs) * self.action_selector.epsilon / epsilon_action_num)

				if getattr(self.args, "mask_before_softmax", True):
					# Zero out the unavailable actions
					agent_outs[reshaped_avail_actions == 0] = 0.0

		# shape = (bs, self.n_agents, -1)
		return agent_outs.view(ep_batch.batch_size, self.n_agents, -1)

	def init_hidden(self, batch_size):
		self.hidden_states = self.agent.init_hidden().unsqueeze(0).expand(batch_size, self.n_agents, -1)  # bav

	def parameters(self):
		return list(self.agent.parameters()) + list(self.comm.parameters())

	def load_state(self, other_mac):
		self.agent.load_state_dict(other_mac.agent.state_dict())
		self.comm.load_state_dict(other_mac.comm.state_dict())

	def cuda(self):
		self.agent.cuda()
		self.comm.cuda()

	def save_models(self, path):
		th.save(self.agent.state_dict(), "{}/agent.th".format(path))
		th.save(self.comm.state_dict(), "{}/comm.th".format(path))

	def load_models(self, path):
		self.agent.load_state_dict(th.load("{}/agent.th".format(path), map_location=lambda storage, loc: storage))
		self.comm.load_state_dict(th.load("{}/comm.th".format(path), map_location=lambda storage, loc: storage))

	def _build_agents(self, input_shape):
		self.agent = agent_REGISTRY[self.args.agent](input_shape, self.args)

	def _build_inputs(self, batch, t):
		# Assumes homogenous agents with flat observations.
		# Other MACs might want to e.g. delegate building inputs to each agent
		# shape = (bs * self.n_agents, -1)
		bs = batch.batch_size
		inputs = []
		inputs.append(batch["obs"][:, t])  # b1av
		if self.args.obs_last_action:
			if t == 0:
				inputs.append(th.zeros_like(batch["actions_onehot"][:, t]))
			else:
				inputs.append(batch["actions_onehot"][:, t - 1])
		if self.args.obs_agent_id:
			inputs.append(th.eye(self.n_agents, device=batch.device).unsqueeze(0).expand(bs, -1, -1))

		inputs = th.cat([x.reshape(bs * self.n_agents, -1) for x in inputs], dim=1)
		return inputs

	def _get_input_shape(self, scheme):
		# shape = (bs * self.n_agents, -1 + self.comm_embed_dim * self.n_agents)
		input_shape = scheme["obs"]["vshape"]
		ms_shape = 0
		if self.args.obs_last_action:
			input_shape += scheme["actions_onehot"]["vshape"][0]
		if self.args.obs_agent_id:
			input_shape += self.n_agents
		if self.args.comm:
			ms_shape = self.comm_embed_dim

		if self.args.comm:
			return input_shape + ms_shape, input_shape
		else:
			return input_shape

	def _cut_alpha(self, attn, thres=0., prob=0.):
		if self.args.is_cur_mu:
			s_num = 0
			attn = attn.detach().cpu()
			attn_2 = attn.detach().numpy()
			for i in range(self.n_agents):
				for j in range(self.n_agents):
					if i != j:
						if attn_2[0, i, j] <= thres or random.random() < prob:
							attn[0, i, j] = 0.
							s_num += 1
			attn = attn.cuda()
			self.c_step += 1
			self.cut_mean_num_list.append(1. * s_num / (self.n_agents * (self.n_agents - 1) + 1e-3))
			if self.c_step >= self.args.env_args['print_steps'] and not self.is_print_once:
				print('cut num ratio:', np.mean(self.cut_mean_num_list))
				self.c_step = 0
				self.is_print_once = True
		elif thres > 0:
			attn = attn.detach().cpu()
			index = np.argsort(abs(attn).reshape(-1))
			rank = np.zeros_like(index)
			for i, item in enumerate(index):
				rank[item] = i
			rank = 100. * rank / rank.size
			rank = th.Tensor(rank.reshape(attn.shape))
			attn[rank < thres] = 0.
			attn = attn.cuda()
		return attn

	def _communicate(self, bs, inputs, hidden_states, test_mode, thres=0., prob=0.):
		# shape = (bs * self.n_agents, -1)
		inputs = th.cat([inputs, hidden_states.view(bs * self.n_agents, -1)], dim=1).detach()
		message, signature, query = self.comm(inputs)

		message = message.view(bs, self.n_agents, -1)
		signature = signature.view(bs, self.n_agents, -1)
		query = query.view(bs, self.n_agents, -1)

		# Concatenate and weighting message

		if test_mode:
			all_m = message.clone()
			scores = th.matmul(query, signature.transpose(-2, -1)) / math.sqrt(self.args.comm_embed_dim)
			attn = F.softmax(scores, dim=-1)
			attn = self._cut_alpha(attn, thres=thres, prob=prob)
			comm = th.matmul(attn, all_m)
			comm = comm.reshape(bs * self.n_agents, -1)
			return (None, None), comm, None
		else:
			all_m = message.clone()
			scores = th.matmul(query, signature.transpose(-2, -1)) / math.sqrt(self.args.comm_embed_dim)
			attn = F.softmax(scores, dim=-1)
			comm = th.matmul(attn, all_m)
			comm = comm.reshape(bs * self.n_agents, -1)
			return (None, None), comm, None

	def clean(self):
		if self.args.env_args['print_rew']:
			self.c_step = 0
			self.cut_mean_num_list = []
			self.is_print_once = False


# encoding: utf-8
from __future__ import absolute_import
import types
import requests
import sys
import pdef
import pdef.descriptors
from pdef.invoke import Invocation
from pdefc.lang import TypeEnum

try:
    # Python 2.7
    import httplib as http_codes
except ImportError:
    # Python 3
    import http.client as http_codes

GET = 'GET'
POST = 'POST'
UTF8 = 'utf-8'
APPLICATION_JSON_CONTENT_TYPE = 'application/json; charset=utf-8'
FORM_URLENCODED_MIME_TYPE = 'application/x-www-form-urlencoded'
TEXT_PLAIN_CONTENT_TYPE = 'text/plain; charset=utf-8'

def rpc_client(interface, url, session=None):
    '''Create an RPC client.'''
    return RpcClient(interface, url, session=session)

def rpc_handler(interface, service):
    '''Create an RPC handler.'''
    return RpcHandler(interface, service)

def wsgi_app(handler):
    '''Create a WSGI RPC server.'''
    return WsgiRpcApp(handler)

class RpcException(Exception):
    def __init__(self, status, message=None):
        super(RpcException, self).__init__(message)
        self.message = message
        self.status = status

class RpcRequest(object):
    def __init__(self, method=GET, path='', query=None, post=None):
        self.method = method
        self.path = path
        self.query = dict(query) if query else {}
        self.post = dict(post) if post else {}

    def __str__(self):
        return '%s %s' % (self.method, self.path)

    def __repr__(self):
        return '<RpcRequest %s %s>' % (self.method, self.path)

    @property
    def is_post(self):
        return self.method == POST

class RpcProtocol(object):
    def __init__(self, jsonformat=None):
        self.jsonformat = jsonformat or pdef.jsonformat

    def get_request(self, invocation):
        if not invocation:
            raise ValueError('Invocation required')

        method = invocation.method
        if not method.is_terminal:
            raise ValueError('Last invocation method must be terminal')

        request = RpcRequest()
        request.method = POST if method.is_post else GET
        for inv in invocation.to_chain():
            self._write_invocation(request, inv)

        return request

    def _write_invocation(self, request, invocation):
        method = invocation.method
        kwargs = invocation.kwargs

        post = request.post
        query = request.query
        path = '/' + method.name

        for argd in method.args:
            name = argd.name
            kwarg = kwargs.get(name)
            value = self._to_json(kwarg, argd.type)

            if argd.is_post:
                post[name] = value
            elif argd.is_query:
                query[name] = value
            else:
                path += '/' + urlencode(value)

        request.path += path

    def _to_json(self, kwarg, descriptor):
        '''Serialize a kwarg to json, strip quotes.'''
        s = self.jsonformat.write(kwarg, descriptor)
        return s.strip('"')

    def get_invocation(self, request, interface_descriptor):
        '''Parse an invocation from an rpc request using an interface descriptor.'''
        if not request:
            raise ValueError('Request required')
        if not interface_descriptor:
            raise ValueError('Interface descriptor required')

        invocation = None
        parts = request.path.strip('/').split('/')

        while parts:
            part = parts.pop(0)

            # Find a method by a name.
            method = interface_descriptor.find_method(part)
            if not method:
                raise RpcException(http_codes.BAD_REQUEST, 'Method not found')

            # Check the required HTTP method.
            if method.is_post and not request.is_post:
                raise RpcException(http_codes.METHOD_NOT_ALLOWED, 'Method not allowed, POST required')

            # Parse keyword arguments.
            kwargs = self._read_kwargs(method, parts, request.query, request.post)

            # Create a root invocation,
            # or a next invocation in a chain.
            invocation = invocation.next(method, **kwargs) \
                if invocation else Invocation(method, kwargs=kwargs)

            if method.is_terminal:
                break

            # It's an interface method.
            # Get the next interface descriptor and proceed parsing the parts.
            interface_descriptor = method.result

        if parts:
            # No more interface descriptors in a chain, but the parts are still present.
            raise RpcException(http_codes.BAD_REQUEST, 'Failed to parse an invocation chain')

        if not invocation:
            raise RpcException(http_codes.BAD_REQUEST, 'Methods required')

        if not invocation.method.is_terminal:
            raise RpcException(http_codes.BAD_REQUEST, 'The last method must be a terminal one. '
                                                       'It must return a data type or be void.')

        return invocation

    def _read_kwargs(self, method, parts, query, post):
        kwargs = {}

        for argd in method.args:
            name = argd.name

            if argd.is_post:
                value = post.get(name)
            elif argd.is_query:
                value = query.get(name)
            elif not parts:
                raise RpcException(http_codes.NOT_FOUND, 'Wrong number of method args: "%s"'
                                                      % method.name)
            else:
                value = urldecode(parts.pop(0))

            arg = self._from_json(value, argd.type)
            kwargs[name] = arg

        return kwargs

    def _from_json(self, s, descriptor):
        if s is None:
            return None

        type0 = descriptor.type
        if type0 in (TypeEnum.STRING, TypeEnum.DATETIME, TypeEnum.ENUM):
            if not (s.startswith('"') and s.endswith('"')):
                # Return the quotes to get a valid json string.
                s = '"' + s + '"'

        return self.jsonformat.read(s, descriptor)

class RpcClient(object):
    def __init__(self, interface, url, session=None, protocol=None):
        if not interface:
            raise ValueError('Interface required')
        if not url:
            raise ValueError('Url required')

        self.interface = interface
        self.interface_descriptor = interface.descriptor

        self.url = url
        self.session = session or requests.session()
        self.protocol = protocol or RpcProtocol()

    def proxy(self):
        return pdef.proxy(self.interface, self)

    def __call__(self, invocation):
        if not invocation:
            raise ValueError('Invocation required')

        rpc_request = self.protocol.get_request(invocation)

        method = invocation.method
        resultd = method.result
        excd = self.interface_descriptor.exc

        request = self._build_request(rpc_request)
        return self._send(request, resultd, excd)

    def _build_request(self, rpc_request):
        url = self._build_url(rpc_request.path)
        return requests.Request(method=rpc_request.method,
                                url=url,
                                data=rpc_request.post,
                                params=rpc_request.query)

    def _build_url(self, path):
        return self.url + path

    def _send(self, request, resultd, excd=None):
        session = self.session
        prepared = request.prepare()
        response = session.send(prepared)
        return self._parse_response(response, resultd, excd)

    def _parse_response(self, response, resultd, excd=None):
        code = response.status_code

        if code not in (http_codes.OK, http_codes.UNPROCESSABLE_ENTITY):
            # It's an HTTP error.
            return self._parse_error(response)

        # It's a successful rpc result.
        text = response.text

        # Create a generic rpc result class.
        result_class = rpc_result_class(resultd, excd)
        result = result_class.from_json(text)

        if code == http_codes.OK:
            return result.data
        else:
            exc = result.error or RpcException(code, 'Unsupported application exception')
            raise exc

    def _parse_error(self, response):
        try:
            text = response.text
        except Exception as e:
            text = 'Failed to get the response text, e=%s' % e

        # Limit the text to use in as an exception description.
        text = text if len(text) < 255 else text[:255]
        raise RpcException(response.status_code, text)

class RpcHandler(object):
    def __init__(self, interface, service, protocol=None):
        if not interface:
            raise ValueError('Interface required')
        if not service:
            raise ValueError('Service required')
        self.interface = interface
        self.interface_descriptor = interface.descriptor
        self.service = service
        self.protocol = protocol or RpcProtocol()

    def __call__(self, rpc_request):
        return self.handle(rpc_request)

    def handle(self, rpc_request):
        '''Handle an rpc request and return a tuple (is_successful, rpc_result).'''
        if not rpc_request:
            raise ValueError('Rpc request required')

        invocation = self.protocol.get_invocation(rpc_request, self.interface_descriptor)

        method = invocation.method
        datad = method.result
        excd = self.interface_descriptor.exc
        result_class = rpc_result_class(datad, excd)

        try:
            data = invocation.invoke(self.service)
            return True, result_class(data)
        except Exception as e:
            if excd and isinstance(e, excd.pyclass):
                # It's an expected application exception.
                return False, result_class(data=None, error=e)

            # Not an application exception, reraise it.
            raise

class WsgiRpcApp(object):
    '''WSGI RPC application.'''
    def __init__(self, handler):
        if not handler:
            raise ValueError('Handler required')
        self.handler = handler

    def __call__(self, environ, start_response):
        return self.handle(environ, start_response)

    def handle(self, environ, start_response):
        request = self._parse_request(environ)
        try:
            success, result = self.handler(request)
        except RpcException as e:
            status = e.status or http_codes.INTERNAL_SERVER_ERROR
            content = e.message or 'Internal server error'
            return self._response(start_response, status, content)

        status_code = http_codes.OK if success else http_codes.UNPROCESSABLE_ENTITY
        content = result.to_json(indent=True)
        return self._response(start_response, status_code, content,
                              content_type=APPLICATION_JSON_CONTENT_TYPE)

    def _parse_request(self, env):
        '''Create an http server request from a wsgi request.'''
        method = env['REQUEST_METHOD']
        path = env['PATH_INFO']
        query = self._read_wsgi_query(env)
        post = self._read_wsgi_post(env)

        return RpcRequest(method, path=path, query=query, post=post)

    def _read_wsgi_query(self, env):
        if 'QUERY_STRING' not in env:
            return {}
        s = env['QUERY_STRING']
        return self._parse_query(s)

    def _read_wsgi_post(self, env):
        ctype = env.get('CONTENT_TYPE', '')
        clength = self._read_wsgi_clength(env)

        body = None
        if clength > 0 and ctype.lower().startswith(FORM_URLENCODED_MIME_TYPE):
            body = env['wsgi.input'].read(clength)

        if not body:
            return {}

        if sys.version > '3':
            body = body.decode(UTF8)

        return self._parse_query(body)

    def _read_wsgi_clength(self, env):
        clength = env.get('CONTENT_LENGTH') or 0
        try:
            return int(clength)
        except (ValueError, TypeError):
            return 0

    def _parse_query(self, s):
        d = parse_query(s)
        result = {}
        for key, values in d.items():
            result[key] = values[0] if values else ''
        return result

    def _response(self, start_response, status_code, unicode_content, content_type=None):
        reason = http_codes.responses.get(status_code)
        status = '%s %s' % (status_code,  reason)

        content = unicode_content.encode(UTF8)
        content_type = content_type or TEXT_PLAIN_CONTENT_TYPE
        headers = [('Content-Type', content_type),
                   ('Content-Length', str(len(content)))]

        start_response(status, headers)
        return [content]

def rpc_result_class(datad, excd=None):
    '''Create a generic RpcResult class with a given data and exception descriptors.'''
    class RpcResult(pdef.Message):
        data = pdef.descriptors.field('data', datad)
        error = pdef.descriptors.field('error', excd or pdef.descriptors.string0)
        descriptor = pdef.descriptors.message(lambda: RpcResult, fields=[data, error])

        has_data = data.has_property
        has_error = error.has_property

        def __init__(self, data=None, error=None):
            self.data = data
            self.error = error

    return RpcResult

try:
    # Python 2.7
    import urllib
    import urlparse

    def urlencode(s, safe='[]{},.-"'):
        if isinstance(s, types.UnicodeType):
            s = s.encode(UTF8)

        if isinstance(safe, types.UnicodeType):
            safe = safe.encode(UTF8)

        result = urllib.quote_plus(s, safe)
        return result.decode(UTF8)

    def urldecode(s):
        if isinstance(s, types.UnicodeType):
            s = s.encode(UTF8)

        result = urllib.unquote_plus(s)
        return result.decode(UTF8)

    def parse_query(s):
        if isinstance(s, types.UnicodeType):
            s = s.encode(UTF8)

        q = urlparse.parse_qs(s)

        # Decode the result to unicode.
        result = {}
        for key, values in q.items():
            k = key.decode(UTF8)
            vv = [v.decode(UTF8) for v in values] if values else []
            result[k] = vv

        return result

except ImportError:
    # Python 3
    import urllib.parse

    def urlencode(s, safe='[]{},.-"'):
        return urllib.parse.quote_plus(s, safe, encoding=UTF8)

    def urldecode(s):
        return urllib.parse.unquote_plus(s, encoding=UTF8)

    def parse_query(s):
        return urllib.parse.parse_qs(s)


import json
import requests

URL = "http://127.0.0.1:8000/student/create"

data = {
    'name': 'Sameen',
    'roll': 123,
    'city': ''
}

json_data = json.dumps(data)
r = requests.post(url=URL, data=json_data)

data = r.json()
print(data)


# x i y spr. większości
# i odpowiedni komunikat

x = int(input("X:"))
y = int(input("Y:"))

if x-y>0:
    print("X>Y",x)

if x>y:
    print("x>y",x)

if y>x:
    print("y>x",y)

if x == y:
    print("równe")


import sys
from collections import deque

input = sys.stdin.readline
N = int(input())
blocks=[list(map(int,input().split())) for _ in range(N)] # t, x, y,
# t=1 1x1,   t=2 (x,y)(x,y+1),    t=3 (x,y)(x+1,y)

green=deque([[0,0,0,0] for _ in range(6)])
blue=deque([[0,0,0,0] for _ in range(6)])
score=0

def pb():
    for i in range(3,-1,-1):
        for j in range(6):
            print(blue[j][i], end=" ")
        print()
    print()

def pg():
    for a in green:
        print(a)
    print()

def move(type,board,t,x,y):
    x=0
    if t == 1:
        while x<6 and board[x][y] == 0 :
            x+=1
        board[x-1][y]=1

    elif t == 2:
        if type =='g':  #green
            while x < 6 and board[x][y] == 0 and board[x][y + 1] == 0:
                x+=1
            board[x - 1][y] = 1
            board[x - 1][y + 1] = 1
        else:           #blue
            while x < 5 and board[x][y] == 0 and board[x+1][y] == 0:
                x+=1
            board[x-1][y] = 1
            board[x][y] = 1

    elif t == 3:
        if type =='g':  #green
            while x < 5 and board[x][y] == 0 and board[x+1][y] == 0 :
                x+=1
            board[x - 1][y] = 1
            board[x][y] = 1
        else:           #blue
            x+=1
            while x < 6 and board[x][y] == 0 and board[x][y-1] == 0:
                x+=1
            board[x-1][y-1] = 1
            board[x-1][y] = 1

def check(board):
    global score
    for i in range(2,6):
        if 0 not in board[i]:
            del board[i]
            board.appendleft([0,0,0,0])
            score+=1

    for i in range(0,2):
        if 1 in board[i]:
            board.pop()
            board.appendleft([0,0,0,0])

def solve(t,x,y):
    move('g',green,t,x,y)
    move("b",blue, t,y,3-x)
    check(green)
    check(blue)

def count():
    cnt=0
    for i in range(2,6):
        for j in range(4):
            cnt+=blue[i][j]
            cnt+=green[i][j]
    return cnt
for t,x,y in blocks:

    solve(t,x,y)
print(score)
print(count())


from scipy.linalg import sqrtm
import random
from Pauli import *
from metrics.density_runner import apply_channel, run_by_matrices, ops
import math
from typing import List, Iterable, Any, Dict, Optional

def trace_norm(m1: np.ndarray, m2: np.ndarray) -> float:
    diff = complex(1, 0) * (m1 - m2)
    return np.trace(sqrtm(diff @ diff.transpose().conjugate())).real / 2

def random_state(dim: int) -> np.ndarray:
    # might want to put a different distribution on this, idk
    c = np.array([complex(random.random() - 0.5, random.random() - 0.5) for _ in range(dim)])
    squared_modulus = c @ c.conjugate()
    return c / (squared_modulus ** 0.5)

def pure_density_from_state(state: np.ndarray) -> np.ndarray:
    return np.outer(state.conjugate(), state)

def random_densities(dim: int, n_trials: int) -> List[np.ndarray]:
    return [sum([r * pure_density_from_state(random_state(dim)) for r in np.random.dirichlet(np.ones(dim), size=1)[0]])
            for _ in range(n_trials)]

def monte_carlo_f_algorithm(channel1: Iterable[np.ndarray], channel2: Iterable[np.ndarray], n_trials: int) -> float:
    # channels: a list of numpy arrays (Kraus matrices)
    dim = channel1[0].shape[0]
    max_norm = max([trace_norm(apply_channel(channel1, xi), apply_channel(channel2, xi)) for xi in
                    random_densities(dim, n_trials)])
    for k in range(int(math.log(dim, 2))):
        channel1 = [np.kron(e, np.eye(2)) for e in channel1]
        channel2 = [np.kron(e, np.eye(2)) for e in channel2]
        with_ancilla = max([trace_norm(apply_channel(channel1, xi), apply_channel(channel2, xi)) for xi in
                            random_densities(2 ** (k + 1) * dim, n_trials)])
        max_norm = max(max_norm, with_ancilla)
    return max_norm

def monte_carlo_from_circuit(circuit_string: Iterable[Any], unitary: np.ndarray, n_trials: int,
                             noise_channels: Optional[Iterable] = None,
                             circuit_key: Dict[Any, np.ndarray] = None) -> float:
    if circuit_key is None:
        circuit_key = ops
    dim = unitary.shape[0]
    max_norm = max([trace_norm(run_by_matrices(circuit_string, xi, noise_channels, circuit_key), apply_channel([unitary], xi))
                    for xi in random_densities(dim, n_trials)])
    for k in range(int(math.log(dim, 2))):
        circuit_key = {i: np.kron(v, np.eye(2)) for i, v in circuit_key.items()}
        unitary = np.kron(unitary, np.eye(2))
        noise_channels = [[np.kron(e, np.eye(2)) for e in c] for c in noise_channels]
        with_ancilla = max([trace_norm(run_by_matrices(circuit_string, xi, noise_channels, circuit_key),
                            apply_channel([unitary], xi)) for xi in random_densities(2 ** (k + 1) * dim, n_trials)])
        max_norm = max(max_norm, with_ancilla)
    return max_norm

def effect_of_noise(circuit_description: Iterable[Any], noise_channels: Iterable,  n_qubits: int = 1,
                    circuit_key: Optional[Dict[Any, np.ndarray]] = None) -> float:
    d = 2 ** n_qubits
    unitary = np.eye(d)
    for s in circuit_description[::-1]:
        unitary = circuit_key[s] @ unitary
    return monte_carlo_from_circuit(circuit_description, unitary, 100, noise_channels, circuit_key=circuit_key)


""" Copied from  """

import torch

class L2Normalization(torch.nn.Module):
    def __init__(self, alpha=1.0):
        super(L2Normalization, self).__init__()
        self.alpha = alpha

    def forward(self, v):
        # v_ = v / norm * alpha
        # norm = sqrt(norm_sq)
        # norm_sq = sum(v ** 2)
        v_sq= torch.pow(v, 2)

        norm_sq = torch.sum(v_sq, dim=1).add(1e-5)
        norm = torch.sqrt(norm_sq).view(-1,1).expand_as(v)

        v_ = v.div(norm).mul(self.alpha)

        return v_


from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.datasets import load_files
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Task 1.3
#load the BBC text data into a training set
path = input("Enter the path to the directory of the dataset you would like to analyze: (Ex: \'BBC\')\n")
try:
    bbc_train = load_files(path,encoding='latin1')
except:
    print("File path was not valid.")
    exit(0)
# Task 1.2
n, bins, patches = plt.hist(bbc_train.target, color='blue', edgecolor='black')
plt.title('Distribution of Instances in Each Class')
xticks = [0] * len(bbc_train.target_names)
for i in range(len(xticks)):
    xticks[i] = i
plt.xticks(xticks, labels=bbc_train.target_names)
plt.savefig('BBC-distribution.pdf')

# Task 1.4
#initialize a count vectorizer for the data
count_vect = CountVectorizer()

# Task 1.5 Split dataset into 80% training and 20% test
X_train, X_test, y_train, y_test = train_test_split(bbc_train.data, bbc_train.target, test_size=0.2, train_size=0.8, random_state=None)
X_train_counts = count_vect.fit_transform(X_train)

# Task 1.6 Train a multinomial Naive Bayes Classifier on the training set
text_clf = Pipeline([
    ('vect', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('clf', MultinomialNB()),
])
text_clf.fit(X_train, y_train)
y_pred = text_clf.predict(X_test)

# The following section is used to help answer questions 1.7.e, 1.7.f, 1.7.i, 1.7.j, 1.7.k
vocab_size = len(count_vect.get_feature_names())
# Get tokens in entire corpus (train and test set)
num_tokens = sum(sum(X_train_counts.toarray())) + sum(sum(count_vect.fit_transform(X_test).toarray()))
print(num_tokens)
class_sums = [0] * len(bbc_train.target_names)
class_zeros = [0] * len(bbc_train.target_names)
class_docs = [0, 0, 0, 0, 0]
for x in y_train:
    class_docs[x] += 1
print(len(y_train))
priors = list(zip(bbc_train.target_names, [x/len(y_train) for x in class_docs]))

# The indices of each of the inner lists corresponds to the indices of the list count_vect.get_feature_names()
class_frequencies = [
    [0] * vocab_size,
    [0] * vocab_size,
    [0] * vocab_size,
    [0] * vocab_size,
    [0] * vocab_size
]
corpus_frequencies = [0] * vocab_size
i = 0
# Add up the frequencies for each word based on class and whole corpus
print('Processing lots of data, this may take a while...')
for row, category in zip(X_train_counts.toarray(), y_train):
    for index, word_freq in enumerate(row):
        class_frequencies[category][index] += word_freq
        corpus_frequencies[index] += word_freq
    class_sums[category] += row.sum()
class_sums = list(zip(bbc_train.target_names, class_sums))

num_ones =  sum([1 for freq in corpus_frequencies if freq == 1])
freq_one = (num_ones, num_ones/num_tokens)

# Writes different statistics about the model to a file
def add_to_file(title, file, y_test, y_pred):
    file.write(f'(a) ******************************** {title} ********************************\n')
    file.write('\n(b) Confusion Matrix:\n')
    file.write(str(confusion_matrix(y_test, y_pred)))
    file.write('\n\n(c)(d) Classification Report:\n')
    file.write(str(classification_report(y_test, y_pred, target_names=bbc_train.target_names)))
    file.write('\n(e) Prior Probability:\n')
    for name, prob in priors:
        file.write(f'{name}: {prob}\n')
    file.write(f'\n(f) Size of vocabulary: {vocab_size} different words')
    file.write('\n\n(g) Number of word tokens in each class:\n')
    for name, num in class_sums:
        file.write(f'{name}: {num}\n')
    file.write(f'\n(h) Number of word tokens in total: {num_tokens}\n')
    file.write('\n(i) Number of words with frequency 0 in each class:\n')
    i = 0
    for name, num in class_sums:
        file.write(f'{name}:\n')
        num_zeros =  sum([1 for freq in class_frequencies[i] if freq == 0])
        freq_zeros = (num_zeros, num_zeros/num)
        file.write(f'words: {freq_zeros[0]} percentage: {freq_zeros[1]}\n')
        i += 1
    file.write('\n(j) Number of words with frequency 1 in the corpus:\n')
    file.write(f'words: {freq_one[0]} percentage: {freq_one[1]}\n')
    file.write(f'\n(k) Log Prob of the word \'programme\':\n')
    logProb = np.log(corpus_frequencies[count_vect.get_feature_names().index('programme')]/num_tokens)/np.log(2)
    file.write(f'{str(logProb)}')
    file.write(f'\nLog Prob of the word \'laptops\':\n')
    logProb = np.log(corpus_frequencies[count_vect.get_feature_names().index('laptops')]/num_tokens)/np.log(2)
    file.write(f'{str(logProb)}\n\n\n')

# Open bbc-performance.txt to write to
with open('bbc-performance.txt', 'w') as file:
    # Task 1.7
    title = "MultinomialNB default values, try 1"
    print(f'Writing to file, {title}')
    add_to_file(title, file, y_test, y_pred)

    # Task 1.8
    text_clf = Pipeline([
        ('vect', CountVectorizer()),
        ('tfidf', TfidfTransformer()),
        ('clf', MultinomialNB()),
    ])
    text_clf.fit(X_train, y_train)
    y_pred = text_clf.predict(X_test)
    title = "MultinomialNB default values, try 2"
    print(f'Writing to file, {title}')
    add_to_file(title, file, y_test, y_pred)

    # Task 1.9
    text_clf = Pipeline([
        ('vect', CountVectorizer()),
        ('tfidf', TfidfTransformer()),
        ('clf', MultinomialNB(alpha=0.0001)),
    ])
    text_clf.fit(X_train, y_train)
    y_pred = text_clf.predict(X_test)
    title = "MultinomialNB default values, try 3"
    print(f'Writing to file, {title}')
    add_to_file(title, file, y_test, y_pred)

    # Task 1.10
    text_clf = Pipeline([
        ('vect', CountVectorizer()),
        ('tfidf', TfidfTransformer()),
        ('clf', MultinomialNB(alpha=0.9)),
    ])
    text_clf.fit(X_train, y_train)
    y_pred = text_clf.predict(X_test)
    title = "MultinomialNB default values, try 4"
    print(f'Writing to file, {title}')
    add_to_file(title, file, y_test, y_pred)
    print('Finished!')