import warnings

import theano

from .. import init
from .. import nonlinearities

from .base import Layer

from .conv import conv_output_length, BaseConvLayer
from ..utils import as_tuple

# check if Theano's new GPU backend is available and in use
try:
    from theano import gpuarray as gpu
except ImportError:
    from theano.sandbox import gpuarray as gpu
gpu_enabled = gpu.pygpu_activated
# if not, try to fall back to Theano's old GPU backend
if not gpu_enabled:
    try:
        from theano.sandbox import cuda as gpu
    except Exception:  # Theano 0.10+ raises nose.SkipTest
        gpu_enabled = False
    else:
        gpu_enabled = gpu.cuda_enabled
# if either of the backends is available, use it, otherwise bail out
if gpu_enabled:
    gpu_contiguous = gpu.basic_ops.gpu_contiguous
    GpuCorrMM = gpu.blas.GpuCorrMM
else:
    raise ImportError(
        "requires GPU support -- see http://lasagne.readthedocs.org/en/"
        "latest/user/installation.html#gpu-support")  # pragma: no cover

if theano.config.floatX == 'float64':
    warnings.warn("You are using a GPU layer with Theano configured for "
                  "double precision (floatX=float64). Depending on your "
                  "Theano version and GPU, this may be slow or unsupported. "
                  "We recommend to configure Theano for single precision "
                  "(floatX=float32); see http://lasagne.readthedocs.org/en/"
                  "latest/user/installation.html#gpu-support.")

__all__ = [
    "Conv2DMMLayer",
]

class Conv2DMMLayer(BaseConvLayer):
    """
    lasagne.layers.Conv2DMMLayer(incoming, num_filters, filter_size,
    stride=(1, 1), pad=0, untie_biases=False,
    W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),
    nonlinearity=lasagne.nonlinearities.rectify, flip_filters=False,
    **kwargs)

    2D convolutional layer

    Performs a 2D convolution on its input and optionally adds a bias and
    applies an elementwise nonlinearity.  This is an alternative implementation
    which uses ``theano.sandbox.cuda.blas.GpuCorrMM`` directly.

    Parameters
    ----------
    incoming : a :class:`Layer` instance or a tuple
        The layer feeding into this layer, or the expected input shape. The
        output of this layer should be a 4D tensor, with shape
        ``(batch_size, num_input_channels, input_rows, input_columns)``.

    num_filters : int
        The number of learnable convolutional filters this layer has.

    filter_size : int or iterable of int
        An integer or a 2-element tuple specifying the size of the filters.

    stride : int or iterable of int
        An integer or a 2-element tuple specifying the stride of the
        convolution operation.

    pad : int, iterable of int, 'full', 'same' or 'valid' (default: 0)
        By default, the convolution is only computed where the input and the
        filter fully overlap (a valid convolution). When ``stride=1``, this
        yields an output that is smaller than the input by ``filter_size - 1``.
        The `pad` argument allows you to implicitly pad the input with zeros,
        extending the output size.

        A single integer results in symmetric zero-padding of the given size on
        all borders, a tuple of two integers allows different symmetric padding
        per dimension.

        ``'full'`` pads with one less than the filter size on both sides. This
        is equivalent to computing the convolution wherever the input and the
        filter overlap by at least one position.

        ``'same'`` pads with half the filter size (rounded down) on both sides.
        When ``stride=1`` this results in an output size equal to the input
        size. Even filter size is not supported.

        ``'valid'`` is an alias for ``0`` (no padding / a valid convolution).

        Note that ``'full'`` and ``'same'`` can be faster than equivalent
        integer values due to optimizations by Theano.

    untie_biases : bool (default: False)
        If ``False``, the layer will have a bias parameter for each channel,
        which is shared across all positions in this channel. As a result, the
        `b` attribute will be a vector (1D).

        If True, the layer will have separate bias parameters for each
        position in each channel. As a result, the `b` attribute will be a
        3D tensor.

    W : Theano shared variable, expression, numpy array or callable
        Initial value, expression or initializer for the weights.
        These should be a 4D tensor with shape
        ``(num_filters, num_input_channels, filter_rows, filter_columns)``.
        See :func:`lasagne.utils.create_param` for more information.

    b : Theano shared variable, expression, numpy array, callable or ``None``
        Initial value, expression or initializer for the biases. If set to
        ``None``, the layer will have no biases. Otherwise, biases should be
        a 1D array with shape ``(num_filters,)`` if `untied_biases` is set to
        ``False``. If it is set to ``True``, its shape should be
        ``(num_filters, output_rows, output_columns)`` instead.
        See :func:`lasagne.utils.create_param` for more information.

    nonlinearity : callable or None
        The nonlinearity that is applied to the layer activations. If None
        is provided, the layer will be linear.

    flip_filters : bool (default: False)
        Whether to flip the filters and perform a convolution, or not to flip
        them and perform a correlation. Flipping adds a bit of overhead, so it
        is disabled by default. In most cases this does not make a difference
        anyway because the filters are learnt. However, ``flip_filters`` should
        be set to ``True`` if weights are loaded into it that were learnt using
        a regular :class:`lasagne.layers.Conv2DLayer`, for example.

    num_groups : int (default: 1)
        The number of groups to split the input channels and output channels
        into, such that data does not cross the group boundaries. Requires the
        number of channels to be divisible by the number of groups, and
        requires Theano 0.10 or later for more than one group.

    **kwargs
        Any additional keyword arguments are passed to the `Layer` superclass.

    Attributes
    ----------
    W : Theano shared variable
        Variable representing the filter weights.

    b : Theano shared variable
        Variable representing the biases.
    """
    def __init__(self, incoming, num_filters, filter_size, stride=(1, 1),
                 pad=0, untie_biases=False, W=init.GlorotUniform(),
                 b=init.Constant(0.), nonlinearity=nonlinearities.rectify,
                 flip_filters=False, num_groups=1, **kwargs):
        super(Conv2DMMLayer, self).__init__(incoming, num_filters, filter_size,
                                            stride, pad, untie_biases, W, b,
                                            nonlinearity, flip_filters,
                                            num_groups, n=2, **kwargs)
        border_mode = 'half' if self.pad == 'same' else self.pad
        extra_kwargs = {'num_groups': num_groups} if num_groups > 1 else {}
        self.corr_mm_op = GpuCorrMM(subsample=self.stride,
                                    border_mode=border_mode,
                                    **extra_kwargs)

    def convolve(self, input, **kwargs):
        filters = self.W
        if self.flip_filters:
            filters = filters[:, :, ::-1, ::-1]  # flip top-down, left-right

        contiguous_filters = gpu_contiguous(filters)
        contiguous_input = gpu_contiguous(input)
        conved = self.corr_mm_op(contiguous_input, contiguous_filters)
        return conved


# -*- coding: utf-8 -*-
"""
Welcome to NPark
"""
import PySimpleGUI as sg
import time
from pySerThread import SerComThread

def inner_window(exe_ope_list):
    inf_table = sg.Column([[sg.Text('倒计时:', font=('宋体', 40)),sg.T(' '  * 10), sg.Text('00 : 00', font=('宋体', 40), key='-Timer-')],
                            [sg.T(' '  * 1)],[sg.T(' '  * 1)],
                            [sg.T(' '  * 50),sg.Text('比分', font=('宋体', 40))],
                            [sg.T(' '  * 1)],
                            [sg.Text('A队:', font=('宋体', 40)),sg.T(' '  * 20), sg.Text(font=('宋体', 40), key='-TeamA-')],
                            [sg.T(' '  * 1)],
                            [sg.Text('B队:', font=('宋体', 40)),sg.T(' '  * 20), sg.Text(font=('宋体', 40), key='-TeamB-')]])
    oper_table = sg.Column([[sg.Listbox(values=exe_ope_list, font=('宋体', 16), size=(30, 16), key='-LIST-', enable_events=True)],
                            [sg.T(' '  * 1)],
                            [sg.T(' '  * 20), sg.Button('执行', size=(16, 3), font=('宋体', 12), key='-OPER-')], ])
    layout = [[sg.Text('当前时间:'), sg.Text(size=(20, 1), key='-TIME-')],
              [sg.T('   串口： '), sg.Button('开启', size=(10, 2), font=('宋体', 10), key='-Com-')],
              [sg.T(' '  * 1)],
              [sg.T(' '  * 1)],
              [sg.T(' '  * 1)],
              [sg.T(' '  * 50), inf_table, sg.T(' '  * 40), oper_table],
              [sg.T(' '  * 1)],
              [sg.T(' '  * 1)],
              [sg.T(' '  * 1)],
              [sg.T(' '  * 10), sg.Button('开始', size=(10, 2), font=('宋体', 10), key='start'),sg.T(' '  * 10), sg.Button('暂停', size=(10, 2), font=('宋体', 10), key='suspend'),sg.T(' '  * 10), sg.Button('继续', size=(10, 2), font=('宋体', 10), key='continue')],
              ]

    return sg.Window('Score Indicator', layout, no_titlebar=True, finalize=True, right_click_menu=[[''], ['Exit',]])

oper_list = ['A队加一分','A队加二分','A队加三分','B队加一分'] #操作列表
win = inner_window(oper_list)
win.Maximize()
scom = SerComThread()

def get_countdown(cd): #计算倒计时时间 Output:  'min:sec'
    if cd <= 0:
        return '00:00'
    outp = ''
    m = int(cd/60)
    if m<10:
        outp += '0'
    outp += str(m)
    outp += ' : '
    s = int(cd-m*60)
    if s<10:
        outp += '0'
    outp += str(s)
    return outp

while True:
    scom.realtime_event()
    win['-TIME-'].update(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) #更新时间
    sco, ti, ck = scom.datapool() #获取数据池
    #更新数据
    win['-TeamA-'].update(str(sco[0]))
    win['-TeamB-'].update(str(sco[1]))

    if ti:
        if ck <= 60: #小于60s倒计时变红
            win['-Timer-'].update(get_countdown(ck), text_color='red')
        else:
            win['-Timer-'].update(get_countdown(ck))

    event, values = win.read(timeout=100)
    if event == '-Com-': #串口开启&关闭
        if scom.ser_state:
            scom.stop()
            if scom.com_close():
                sg.popup_error("串口关闭失败")
                continue
            win['-Com-'].update('开启')
        else:
            if scom.com_open():
                sg.popup_error("串口开启失败")
                continue
            scom.run()
            win['-Com-'].update('关闭')
        continue
    elif event in (sg.WIN_CLOSED, 'Exit', None):
        scom.stop()
        scom.com_close()
        break
    elif event == '-OPER-':
        try:
            scom.main(str(oper_list.index(values['-LIST-'][0])), met=0)
        except:
            continue
    elif event == 'start':
        scom.main('11', 0)
        continue
    elif event == 'continue':
        scom.main('12', 0)
        continue
    elif event == 'suspend':
        scom.main('10', 0)
        continue

win.close()


import numpy
import math
import matplotlib.pyplot as plt
from scipy import stats
speed = [32,111,138,28,59,77,97]
x=numpy.mean(speed)
print("The mean is ", x)
print("The median is " ,numpy.median(speed))

# #  let calculate the mode
# print("The mode is " , stats.mode(speed))

# let me calculate standard deviation
print("The standard deviation is ",numpy.std(speed))

# let me calculate variance
"""The variance means the std square root of the std """
# python has method to handle it
variance=numpy.var(speed)
print("The variance is ",variance)
print("The std using variance is ",math.sqrt(variance))

# let me find percentile
age=[90,20,20,30,45,6,1,2,3,3,45,67,78,67,78,90,91]
print("Percentile is ",numpy.percentile(age,100))

# let me generate the random numbers 500 between 0.0 and 5.0 by using Numpy module
randomNumbes=numpy.random.uniform(0.0,5.0,1000)
# let me present the generated numbers on the histogram
plt.pie(randomNumbes)
plt.show()

# let me generate the normal
y=numpy.random.normal(5.0,1.0,1000)
plt.hist(y,10)
plt.show()


# -*- coding:utf-8 -*-
'''
Created on 24 juin 2013

@author: ediemert
'''

import numpy as np

from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation
from sklearn.metrics import metrics
from sklearn.feature_extraction import FeatureHasher

def parse_header(line):
    attributes = line.strip().split(',')
    return attributes

def parse_line(line, attributes):
    features = [ int(_) for _ in line.strip().split(',') ]
    return dict(zip(attributes, features))

def stream_read(fn):
    fd = open(fn)
    attributes = None
    for line in fd:
        if not attributes:
            attributes = parse_header(line)
            continue
        yield parse_line(line, attributes)

def read_train(fn):
    X = []
    y = []
    for d in stream_read(fn):
        y.append(d['ACTION'])
        del d['ACTION']
        X.append(d)
    y = np.array(y)
    #X = FeatureHasher().fit_transform(X)
    X = np.array([np.array([xx for xx in x.itervalues()]) for x in X])
    return X, y

def evaluate(y_true, y_pred):
    y_pred = np.array(y_pred)
    y_true = np.array(y_true)
    fpr, tpr, _thresholds = metrics.roc_curve(y_true, y_pred, pos_label=1)
    return metrics.auc(fpr, tpr)

if __name__ == '__main__':

    X, y = read_train('train.csv')
    print("X:", X.shape, "y:",y.shape)
    cross_validation_iterator = cross_validation.StratifiedKFold(y, n_folds=5)
    y_pred = []
    y_true = []
    for train_index, test_index in cross_validation_iterator:
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        clf = RandomForestClassifier(n_estimators=30, n_jobs=4)
        clf.fit(X_train, y_train)
        y_true.extend(y_test)
        y_pred.extend(clf.predict(X_test))
        print("AUC: %.3f" % evaluate(y_true, y_pred))


def parse_subjects_list(filepath, datadir='', split=':', labelsf=None):
    """Parses a file with a list of: <subject_file>:<subject_class_label>.

    Parameters
    ----------
    filepath: str
    Path to file with a list of: <subject_file>:<subject_class_label>.
    Where ':' can be any split character

    datadir: str
    String to be path prefix of each line of the fname content,
    only in case the lines are relative file paths.

    split: str
    Split character for each line

    labelsf: str
    Path to file with a list of the labels if it is not included in
    fname. It will overwrite the labels from fname.

    Returns
    -------
    [labels, subjs] where labels is a list of labels and subjs a list of
    filepaths
    """
    labels = []
    subjs  = []

    if datadir:
        datadir += op.sep

    with open(filepath, 'r') as f:
        for s in f:
            line = s.strip().split(split)
            if len(line) == 2:
                labels.append(np.float(line[1]))
                subjf = line[0].strip()
            else:
                subjf = line.strip()

            if not op.isabs(subjf):
                subjs.append(datadir + subjf)
            else:
                subjs.append(subjf)

    if labelsf is not None:
        labels = np.loadtxt(labelsf)

    return [labels, subjs]


import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from dash_dict_callback import DashDictCallbackPlugin

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets, plugins=[DashDictCallbackPlugin])

app.layout = html.Div([
    dcc.Input(
        id='num-multi',
        type='number',
        value=5
    ),
    html.Table([
        html.Tr([html.Td(['x', html.Sup(2)]), html.Td(id='square')]),
        html.Tr([html.Td(['x', html.Sup(3)]), html.Td(id='cube')]),
        html.Tr([html.Td([2, html.Sup('x')]), html.Td(id='twos')]),
        html.Tr([html.Td([3, html.Sup('x')]), html.Td(id='threes')]),
        html.Tr([html.Td(['x', html.Sup('x')]), html.Td(id='x^x')]),
    ]),
])

@app.dict_callback(
    Output('square', 'children'),
    Output('cube', 'children'),
    Output('twos', 'children'),
    Output('threes', 'children'),
    Output('x^x', 'children'),
    Input('num-multi', 'value'))
def callback_a(inputs, states):
    x=inputs['num-multi.value']
    output={}
    output['square.children'] = x**2
    output['cube.children'] = x**3
    output['twos.children'] = 2**x
    output['threes.children'] = 3**x
    output['x^x.children'] = x**x
    return output

if __name__ == '__main__':
    app.run_server(debug=True)


from anki.exporting import Exporter, AnkiExporter
from anki.utils import ids2str
from aqt import mw
import os
from anki.storage import Collection

oldInit = Exporter.__init__
def __init__(self,*args, **kwargs):
    oldInit(self, *args, **kwargs)
    self.cids = None
Exporter.__init__ = __init__

def needSiblings(self):
    userOption = mw.addonManager.getConfig(__name__)
    siblings = userOption["siblings"]
    r=siblings.get(self.key)
    if r is None:
        r= siblings.get("default")
    if r is None:
        r = True
    return r
Exporter.needSiblings = needSiblings

def siblings(cids):
    siblings = mw.col.db.list(f"select id from cards where nid in (select nid from cards where id in {ids2str(cids)})")
    return siblings

oldCardIds= Exporter.cardIds
def cardIds(self):
    if self.cids is not None:
        cids= self.cids
        self.count = len(cids)
    else:
        cids=oldCardIds(self)
    if self.needSiblings():
        cids = siblings(cids)
    return cids
Exporter.cardIds = cardIds

def exportInto(self, path: str) -> None:
    # sched info+v2 scheduler not compatible w/ older clients
    self._v2sched = self.col.schedVer() != 1 and self.includeSched

    # create a new collection at the target
    try:
        os.unlink(path)
    except (IOError, OSError):
        pass
    self.dst = Collection(path)
    self.src = self.col
    # find cards
    cids = self.cardIds()
    # copy cards, noting used nids
    nids = {}
    data = []
    for row in self.src.db.execute(
        "select * from cards where id in " + ids2str(cids)
    ):
        nids[row[1]] = True
        data.append(row)
        # clear flags
        row = list(row)
        row[-2] = 0
    self.dst.db.executemany(
        "insert into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", data
    )
    # notes
    strnids = ids2str(list(nids.keys()))
    notedata = []
    for row in self.src.db.all("select * from notes where id in " + strnids):
        # remove system tags if not exporting scheduling info
        if not self.includeSched:
            row = list(row)
            row[5] = self.removeSystemTags(row[5])
        notedata.append(row)
    self.dst.db.executemany(
        "insert into notes values (?,?,?,?,?,?,?,?,?,?,?)", notedata
    )
    # models used by the notes
    mids = self.dst.db.list("select distinct mid from notes where id in " + strnids)
    # card history and revlog
    if self.includeSched:
        data = self.src.db.all("select * from revlog where cid in " + ids2str(cids))
        self.dst.db.executemany(
            "insert into revlog values (?,?,?,?,?,?,?,?,?)", data
        )
    else:
        # need to reset card state
        self.dst.sched.resetCards(cids)
    # models - start with zero
    self.dst.models.models = {}
    for m in self.src.models.all():
        if int(m["id"]) in mids:
            self.dst.models.update(m)
    # decks
    dids = self.deckIds()
    print(f"dids is {dids}")
    dconfs = {}
    for d in self.src.decks.all():
        if str(d["id"]) == "1":
            continue
        if dids and d["id"] not in dids:
            continue
        if not d["dyn"] and d["conf"] != 1:
            if self.includeSched:
                dconfs[d["conf"]] = True
        if not self.includeSched:
            # scheduling not included, so reset deck settings to default
            d = dict(d)
            d["conf"] = 1
        self.dst.decks.update(d)
    # copy used deck confs
    for dc in self.src.decks.allConf():
        if dc["id"] in dconfs:
            self.dst.decks.updateConf(dc)
    # find used media
    media = {}
    self.mediaDir = self.src.media.dir()
    if self.includeMedia:
        for row in notedata:
            flds = row[6]
            mid = row[2]
            for file in self.src.media.filesInStr(mid, flds):
                # skip files in subdirs
                if file != os.path.basename(file):
                    continue
                media[file] = True
        if self.mediaDir:
            for fname in os.listdir(self.mediaDir):
                path = os.path.join(self.mediaDir, fname)
                if os.path.isdir(path):
                    continue
                if fname.startswith("_"):
                    # Scan all models in mids for reference to fname
                    for m in self.src.models.all():
                        if int(m["id"]) in mids:
                            if self._modelHasMedia(m, fname):
                                media[fname] = True
                                break
    self.mediaFiles = list(media.keys())
    self.dst.crt = self.src.crt
    # todo: tags?
    self.count = self.dst.cardCount()
    self.dst.setMod()
    self.postExport()
    self.dst.close()

def deckIds(self):
    dids: List[int]
    if self.did:
        return [self.did] + [x[1] for x in self.src.decks.children(self.did)]
    elif self.cids:
        return self.col.db.list(f"SELECT did FROM cards where id in {ids2str(self.cids)}")
    else:
        return []

AnkiExporter.deckIds = deckIds
AnkiExporter.exportInto = exportInto


import sys
input = sys.stdin.readline

N = int(input())

li = []
for _ in range(N):
    li.append(int(input()))

dp = [0] * N

dp[0] = li[0]
if N == 1:
    print(dp[0])
else:
    dp[1] = dp[0] + li[1]
    if N == 2:
        print(dp[1])
    else:
        dp[2] = max(li[0] + li[2], li[1] + li[2])
        if N == 3:
            print(dp[2])
        if N >= 4:
            for i in range(3, N):
                dp[i] = max(dp[i-2], dp[i-3]+li[i-1]) + li[i]

            print(dp[N-1])

# c++ 에서의 return 0 처럼 sys.exit(0)으로 조건문에서 프로그램 중단 가능
# -> 불필요한 조건 제거 가능


import json
import pickle
import traceback
from multiprocessing import Pool
from pathlib import Path
from typing import Iterable, NamedTuple

import numpy as np
import xmltodict
from skimage import img_as_float
from skimage.io import imread

from budynki import Building, fetch_buildings
from config import CACHE_DIR, CPU_COUNT, DATASET_DIR, IMAGES_DIR
from db_grid import random_grid
from processor import ProcessPolygonResult, process_image, process_polygon
from tuned_model import TunedModel
from utils import print_run_time, save_image

class DatasetEntry(NamedTuple):
    id: str
    label: int
    image: np.ndarray

def _tag_to_label(tag: dict) -> int | None:
    if tag['@source'] != 'manual':
        print(f'[DATASET] тЪая╕П Unknown source: {tag["@source"]!r}')
        return None

    if tag['@label'] in {'good'}:
        return 1
    elif tag['@label'] in {'bad', 'fundament'}:
        return 0
    elif tag['@label'] in {'unknown'}:
        return None

    raise ValueError(f'Unknown tag label: {tag["@label"]!r}')

def _iter_dataset_identifier(identifier: str, raw_path: Path, annotation: dict) -> DatasetEntry | None:
    cache_path = CACHE_DIR / f'DatasetEntry_{identifier}.pkl'
    if cache_path.is_file():
        return pickle.loads(cache_path.read_bytes())

    if len(annotation['tag']) != 1:
        print(f'[DATASET] тЪая╕П Unexpected tag count {len(annotation["tag"])} for {identifier!r}')
        return None

    label = _tag_to_label(annotation['tag'][0])

    if label is None:
        return None

    raw_name = raw_path.name
    raw_name_safe = raw_name.replace('.', '_')
    related_files_dir = raw_path.parent / 'related_images' / raw_name_safe

    mask_path = related_files_dir / 'mask.png'

    image = imread(raw_path)
    image = img_as_float(image)

    mask = imread(mask_path)
    mask = img_as_float(mask)

    # backwards compatibility with RGB masks
    if len(mask.shape) == 3:
        mask = mask[:, :, 0]

    entry = DatasetEntry(identifier, label, process_image(image, mask))
    cache_path.write_bytes(pickle.dumps(entry, protocol=pickle.HIGHEST_PROTOCOL))
    return entry

def iter_dataset() -> Iterable[DatasetEntry]:
    cvat_annotation_paths = tuple(sorted(DATASET_DIR.rglob('annotations.xml')))
    done = set()

    for i, p in enumerate(cvat_annotation_paths, 1):
        dir_progress = f'{i}/{len(cvat_annotation_paths)}'
        cvat_dir = p.parent
        print(f'[DATASET][{dir_progress}] ЁЯУБ Iterating: {cvat_dir!r}')

        cvat_annotations = xmltodict.parse(p.read_text(), force_list=('image', 'tag', 'attribute'))
        cvat_annotations = cvat_annotations['annotations']['image']

        for j, annotation in enumerate(cvat_annotations, 1):
            file_progress = f'{j}/{len(cvat_annotations)}'
            raw_path = cvat_dir / Path(annotation['@name'])
            identifier = raw_path.stem
            if identifier in done:
                continue

            # print(f'[DATASET][{dir_progress}][{file_progress}] ЁЯУД Iterating: {identifier!r}')

            entry = _iter_dataset_identifier(identifier, raw_path, annotation)
            if entry is None:
                continue

            done.add(identifier)
            yield entry

def _process_building(building: Building) -> tuple[Building, np.ndarray | None, ProcessPolygonResult | None]:
    with print_run_time('Process building'):
        try:
            polygon_result = process_polygon(building.polygon)
            return building, process_image(polygon_result.image, polygon_result.mask), polygon_result
        except:
            traceback.print_exc()
            return building, None, None

def create_dataset(size: int) -> None:
    cvat_annotations = {
        'annotations': {
            'version': '1.1',
            'image': []
        }
    }

    cvat_image_annotations: list[dict] = cvat_annotations['annotations']['image']

    with print_run_time('Loading model'):
        model = TunedModel()

    with Pool(CPU_COUNT) as pool:
        for cell in random_grid():
            print(f'[CELL] тЪЩя╕П Processing {cell!r}')

            with print_run_time('Fetch buildings'):
                buildings = fetch_buildings(cell)[:(size - len(cvat_image_annotations))]

            if not buildings:
                print('[CELL] тПня╕П Nothing to do')
                continue

            if CPU_COUNT == 1:
                iterator = map(_process_building, buildings)
            else:
                iterator = pool.imap_unordered(_process_building, buildings, chunksize=4)

            for building, model_input, polygon_result in iterator:
                if model_input is None:
                    continue

                unique_id = building.polygon.unique_id_hash()

                is_valid, proba = model.predict_single(model_input, threshold=0.5)
                label = 'good' if is_valid else 'bad'

                raw_path = save_image(polygon_result.image, f'CVAT/images/{unique_id}', force=True)
                raw_name = raw_path.name
                raw_name_safe = raw_name.replace('.', '_')

                save_image(polygon_result.mask, f'CVAT/images/related_images/{raw_name_safe}/mask', force=True)
                save_image(polygon_result.overlay, f'CVAT/images/related_images/{raw_name_safe}/overlay', force=True)

                with open(IMAGES_DIR / f'CVAT/images/related_images/{raw_name_safe}/polygon.json', 'w') as f:
                    json.dump(building.polygon, f)

                annotation = {
                    '@name': f'images/{raw_name}',
                    '@height': polygon_result.image.shape[0],
                    '@width': polygon_result.image.shape[1],
                    'tag': [{
                        '@label': label,
                        '@source': 'auto',
                        'attribute': [{
                            '@name': 'proba',
                            '#text': f'{proba:.3f}'
                        }]
                    }]
                }

                cvat_image_annotations.append(annotation)

            if len(cvat_image_annotations) >= size:
                break

    # sort in lexical order
    cvat_image_annotations.sort(key=lambda x: x['@name'])

    # add numerical ids
    for i, annotation in enumerate(cvat_image_annotations):
        annotation['@id'] = i

    with open(IMAGES_DIR / 'CVAT/annotations.xml', 'w') as f:
        xmltodict.unparse(cvat_annotations, output=f, pretty=True)


import math
with open("bai23.out","w",encoding="utf-8") as fo:
    try:
        #đọc file input
        with open("bai23.inp","r") as fi:
                option=float(fi.readline().rstrip("\n"))
                if option==1:
                    #lựa chọn 1 giải phương trình bậc nhất
                    a,b=map(float,fi.readline().rstrip("\n").split())
                    if a==0:
                        if b==0:
                            fo.write("phương trình có vô số nghiệm")
                        else:
                            fo.write("phương trình vô nghiệm")
                    else:
                        x=-b/a
                        fo.write(f"phương trình có nghiệm duy nhất x={x}")
                elif option==2:
                    #lựa chọn 2 giải phương trình bậc hai
                    a,b,c=map(float,fi.readline().rstrip("\n").split())
                    delta=b*b-4*a*c
                    if delta<0:
                        fo.write("phương trình vô nghiệm")
                    elif delta==0:
                        x=-b/(2*a)
                        fo.write(f"phương trình có nghiệm kép x1=x2={x}")
                    else:
                        fo.write("phương trình có 2 nghiệm phân biệt \n")
                        x1=(-b-math.sqrt(delta))/(2*a)
                        x2=(-b+math.sqrt(delta))/(2*a)
                        fo.write(f"  x1={x1}")
                        fo.write(f"\n  x2={x2}")
                else:
                    #nếu nằm ngoài lựa chọn 1 2 thì mời chọn lại
                    fo.write("Vui long chon mot trong hai chuc nang:\n")
                    fo.write("  1. Giai phuong trinh bac nhat\n")
                    fo.write("  2. Giai phuong trinh bac hai\n")
        fi.close()
    #Thông báo lỗi
    except FileNotFoundError:
            fo.write("Khong tim thay file input!")
    except:
            fo.write("EROR DATA INPUT")
fo.close()


#터미널 > pip install bs4

from bs4 import BeautifulSoup
from urllib.request import urlopen

#네이버 웹툰 > 신의 탑 제목 가져오자

if __name__ == '__main__':
    # data = urlopen("https://comic.naver.com/webtoon/list.nhn?titleId=183559&weekday=mon")
    # data = urlopen("https://comic.naver.com/webtoon/list.nhn?titleId=651673&weekday=wed")
    # soup = BeautifulSoup(data,"lxml")
    with urlopen("https://comic.naver.com/webtoon/list.nhn?titleId=183559&weekday=mon") as response:
        response_byte = response.read()
    cartoon_titles = soup.find_all("td", attrs={'class':'title'})   #
    html = "<meta charset='utf-8'>"
    print(html)
    for title in cartoon_titles:
        t = title.find('a').text     #제목 가져오자
        link = title.find("a").get("href")  #link 가져오자
        link="http://comic.naver.com/"+link
        # print(t)
        # print(link)
        # print(""+t+"")
        html+=""+t+"
"
    html==""
    outputSoup = BeautifulSoup(html, "lxml")    #htmlstring -> BeaurifulSoup 객체
    prettyHtml = str(outputSoup.prettify())     #html 줄 예쁘게
    with open("유미의세포들.html","w",encoding="utf-8") as f:
        f.write(html)

    #다음 웹툰 > 어쩌다 발견한 7월
    # data = urlopen("http://webtoon.daum.net/webtoon/view/findjuly")
    # soup = BeautifulSoup(data,"lxml")
    # print(data)
    # cartoon_titles = soup.find_all("string", attrs={'class':'tit_wt'})
    # for title in cartoon_titles:
    #     print(t)


# Реализуйте RLE алгоритм: реализуйте модуль сжатия и восстановления данных.

task = str()

path = '/Users/alina/Desktop/Seminar PY/HW_PY_5/data_task4.txt'
data = open(path, 'r')
for line in data:
    task = line
data.close()

result = str()
count = 1

if len(task) == 1:
    result += task[0] + str(len(task))
elif len(task) != 0:
    temp = task[0]
    for i in range(1, len(task)):
        if task[i] == temp:
            count +=1
        else:
            result += task[i-1] + str(count)
            temp = task[i]
            count = 1
    result += task[i] + str(count)

with open('/Users/alina/Desktop/Seminar PY/HW_PY_5/result_task4.txt', 'w') as data:
    data.write(result)

# Модуль восстановления
task = str()

path = '/Users/alina/Desktop/Seminar PY/HW_PY_5/result_task4.txt'
data = open(path, 'r')
for line in data:
    task = line
data.close()

task += ' '
item = str()
num = str()
result = str()

for i in task:
    if not i.isdigit():
        if len(num) != 0 or i == ' ':
            result += int(num) * item
            item = i
            num = str()
        else: item = i
    else:
        num += i

with open('/Users/alina/Desktop/Seminar PY/HW_PY_5/recovery_task4.txt', 'w') as data:
    data.write(result)


import numpy as np
import os
import json
import urllib
import tensorflow as tf
from keras.preprocessing.sequence import pad_sequences

from rotary.models.nlp.bert import BERT
from rotary.models.nlp.lstm import LSTMNet
from rotary.models.nlp.bi_lstm import BiLSTM

import rotary.reader.udtb_reader as udtb_reader
import rotary.reader.lmrd_reader as lmrd_reader

class NLPProfiler:
    def __init__(self,
                 model_name,
                 batch_size,
                 optimizer,
                 learning_rate,
                 epoch,
                 profile_metric,
                 output_dir,
                 *args, **kwargs):

        self.model_name = model_name
        self.batch_size = batch_size
        self.optimizer = optimizer
        self.learning_rate = learning_rate
        self.epoch = epoch
        self.profile_metric = profile_metric
        self.output_dir = output_dir

        if model_name == 'bert':
            self.max_seq_length = kwargs['model_max_seq_len']
            self.hidden_layer = kwargs['model_hidden_layer']
            self.hidden_size = kwargs['model_hidden_size']
            if self.max_seq_length is None:
                raise ValueError('Max sequence length for BERT is missing')
            elif self.hidden_layer is None:
                raise ValueError('hidden layer for BERT is missing')
            elif self.hidden_size is None:
                raise ValueError('hidden size for BERT is missing')
            else:
                pass

    def run(self):
        ###################################
        # prepare the model
        ###################################

        if self.model_name == 'bert':
            # Params for bert model and tokenization
            bert_path = "https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1"

            train_df, test_df = lmrd_reader.download_and_load_datasets()

            # Create datasets (Only take up to max_seq_length words for memory)
            train_text = train_df["sentence"].tolist()
            train_text = [" ".join(t.split()[0:self.max_seq_length]) for t in train_text]
            train_text = np.array(train_text, dtype=object)[:, np.newaxis]
            train_label = train_df["polarity"].tolist()

            test_text = test_df["sentence"].tolist()
            test_text = [" ".join(t.split()[0:self.max_seq_length]) for t in test_text]
            test_text = np.array(test_text, dtype=object)[:, np.newaxis]
            test_label = test_df["polarity"].tolist()

            with tf.Session() as sess:
                # Instantiate tokenizer
                tokenizer = lmrd_reader.create_tokenizer_from_hub_module(bert_path, sess)

                # Convert data to InputExample format
                train_examples = lmrd_reader.convert_text_to_examples(train_text, train_label)
                test_examples = lmrd_reader.convert_text_to_examples(test_text, test_label)

                # Convert to features
                (
                    train_input_ids,
                    train_input_masks,
                    train_segment_ids,
                    train_labels,
                ) = lmrd_reader.convert_examples_to_features(tokenizer, train_examples, self.max_seq_length)

                (
                    test_input_ids,
                    test_input_masks,
                    test_segment_ids,
                    test_labels,
                ) = lmrd_reader.convert_examples_to_features(tokenizer, test_examples, self.max_seq_length)

                model = BERT(max_length=self.max_seq_length,
                             hidden_size=self.hidden_size,
                             num_hidden_layers=self.hidden_layer,
                             learn_rate=self.learning_rate,
                             optimizer=self.optimizer)

                logit, trainable_parameters = model.build()

                # Instantiate variables
                sess.run(tf.local_variables_initializer())
                sess.run(tf.global_variables_initializer())
                sess.run(tf.tables_initializer())
                tf.keras.backend.set_session(sess)

                hist = logit.fit([train_input_ids, train_input_masks, train_segment_ids],
                                 train_labels,
                                 epochs=self.epoch,
                                 batch_size=self.batch_size,
                                 verbose=0)

                acc_record_list = hist.history['acc']
                acc_record_list = [float(item) for item in acc_record_list]

                # scores = logit.evaluate([test_input_ids, test_input_masks, test_segment_ids], test_labels)
                # scores = logit.evaluate([train_input_ids, train_input_masks, train_segment_ids], train_labels)
                # print('{}: {}'.format(logit.metrics_names[1], scores[1]))

        elif self.model_name == 'bilstm' or self.model_name == 'lstm':

            ####################################################
            # Download and load the dataset
            ####################################################

            UD_ENGLISH_TRAIN = './datasets/ud_treebank/en_partut-ud-train.conllu'
            UD_ENGLISH_DEV = './datasets/ud_treebank/en_partut-ud-dev.conllu'
            UD_ENGLISH_TEST = './datasets/ud_treebank/en_partut-ud-test.conllu'

            if not os.path.exists(UD_ENGLISH_TRAIN):
                urllib.request.urlretrieve('http://archive.aueb.gr:8085/files/en_partut-ud-train.conllu',
                                           UD_ENGLISH_TRAIN)
            if not os.path.exists(UD_ENGLISH_DEV):
                urllib.request.urlretrieve('http://archive.aueb.gr:8085/files/en_partut-ud-dev.conllu',
                                           UD_ENGLISH_DEV)
            if not os.path.exists(UD_ENGLISH_TEST):
                urllib.request.urlretrieve('http://archive.aueb.gr:8085/files/en_partut-ud-test.conllu',
                                           UD_ENGLISH_TEST)

            train_sentences = udtb_reader.read_conllu(UD_ENGLISH_TRAIN)
            val_sentences = udtb_reader.read_conllu(UD_ENGLISH_DEV)
            test_sentences = udtb_reader.read_conllu(UD_ENGLISH_TEST)

            ####################################################
            # Preprocessing
            ####################################################

            train_text = udtb_reader.text_sequence(train_sentences)
            test_text = udtb_reader.text_sequence(test_sentences)
            # val_text = udtb_reader.text_sequence(val_sentences)

            train_label = udtb_reader.tag_sequence(train_sentences)
            test_label = udtb_reader.tag_sequence(test_sentences)
            # val_label = udtb_reader.tag_sequence(val_sentences)

            ####################################################
            # Build dictionary with tag vocabulary
            ####################################################

            words, tags = set([]), set([])

            for s in train_text:
                for w in s:
                    words.add(w.lower())

            for ts in train_label:
                for t in ts:
                    tags.add(t)

            word2index = {w: i + 2 for i, w in enumerate(list(words))}
            # The special value used for padding
            word2index['-PAD-'] = 0
            # The special value used for OOVs
            word2index['-OOV-'] = 1

            tag2index = {t: i + 1 for i, t in enumerate(list(tags))}
            # The special value used to padding
            tag2index['-PAD-'] = 0

            train_sentences_X, test_sentences_X, train_tags_y, test_tags_y = [], [], [], []

            for s in train_text:
                s_int = []
                for w in s:
                    try:
                        s_int.append(word2index[w.lower()])
                    except KeyError:
                        s_int.append(word2index['-OOV-'])

                train_sentences_X.append(s_int)

            for s in test_text:
                s_int = []
                for w in s:
                    try:
                        s_int.append(word2index[w.lower()])
                    except KeyError:
                        s_int.append(word2index['-OOV-'])

                test_sentences_X.append(s_int)

            for s in train_label:
                train_tags_y.append([tag2index[t] for t in s])

            for s in test_label:
                test_tags_y.append([tag2index[t] for t in s])

            MAX_LENGTH = len(max(train_sentences_X, key=len))

            train_sentences_X = pad_sequences(train_sentences_X, maxlen=MAX_LENGTH, padding='post')
            test_sentences_X = pad_sequences(test_sentences_X, maxlen=MAX_LENGTH, padding='post')
            train_tags_y = pad_sequences(train_tags_y, maxlen=MAX_LENGTH, padding='post')
            test_tags_y = pad_sequences(test_tags_y, maxlen=MAX_LENGTH, padding='post')

            if self.model_name == 'bilstm':
                model = BiLSTM(max_length=MAX_LENGTH,
                               learn_rate=self.learning_rate,
                               optimizer=self.optimizer)

            else:
                model = LSTMNet(max_length=MAX_LENGTH,
                                learn_rate=self.learning_rate,
                                optimizer=self.optimizer)

            logit, trainable_parameters = model.build(word2index, tag2index)

            hist = logit.fit(train_sentences_X,
                             udtb_reader.to_categorical(train_tags_y, len(tag2index)),
                             batch_size=self.batch_size,
                             epochs=self.epoch)

            acc_record_list = hist.history['acc']
            acc_record_list = [float(item) for item in acc_record_list]

        else:
            raise ValueError('model is not supported')

        results_path = self.output_dir + '/' + self.model_name + '_' + self.profile_metric

        if os.path.exists(results_path):
            with open(results_path) as f:
                model_json_list = json.load(f)
        else:
            model_json_list = list()

        # create a dict for the conf
        model_perf_dict = dict()

        model_perf_dict['model_name'] = self.model_name
        model_perf_dict['num_parameters'] = trainable_parameters
        model_perf_dict['batch_size'] = self.batch_size
        model_perf_dict['opt'] = self.optimizer
        model_perf_dict['learn_rate'] = self.learning_rate

        if self.model_name == 'bert':
            model_perf_dict['training_data'] = 'stanford-lmrd'
            model_perf_dict['classes'] = 2
        else:
            model_perf_dict['training_data'] = 'udtreebank'
            model_perf_dict['classes'] = 17

        model_perf_dict['accuracy'] = acc_record_list

        model_json_list.append(model_perf_dict)

        with open(results_path, 'w+') as f:
            json.dump(model_json_list, f)


#!/bin/env python
import os
import sys
length = len(sys.argv)
if length != 3:
  print("\n\nUsage: python main.py <file_name> <number_of_characters>")
else:
  file_name = sys.argv[1]
  try: int(sys.argv[2])
  except ValueError or TypeError:
    print('\n\nEnter a valid number for the number of characters needed.')
    exit()
  num_of_char = int(sys.argv[2])
  if os.path.exists(file_name):
    with open(file_name, 'r') as file:
      for line in file:
        line0 = line.strip('\n')
        if len(line0) == num_of_char:
          with open('output.txt','a') as f:
            f.write(line)
          word = f'{line0}',str(len(line0))
          print('\n',word)
  else:
    print('Enter a valid path, file does not exist.')
    exit()
  print(f'''
\n\n Le nouveau fichier "output.txt" a ete cree et est a \n\n {os.path.abspath("output.txt")}
Supprimer output.txt avant de relancer le code en ecrivant :  \n\n\t\t
sudo rm -f {os.path.abspath("output.txt")} ou \n\n echo '' > {os.path.abspath("output.txt")}
''')


import json
import os

import discord

SLASH_GUILD_IDS = None
if os.environ.get("SLASH_GUILD_IDS"):
    SLASH_GUILD_IDS = json.loads(os.environ.get("SLASH_GUILD_IDS"))
TITLE_JOIN_REQUEST = "Join request"
TITLE_MOVE_REQUEST = "Move request"
TEXT_ACCEPT_ANYONE = "anyone ^-^"
TEXT_ACCEPT_ANYONE_CHANNEL = "Anyone in channel "
EMOJI_TICK = "✅"
EMPTY_EMBED = dict.fromkeys(("name", "value"), "\u200b")

def get_member_voice_channel(member: discord.Member, match_channel_id=None):
    voice_state = member.voice
    if not voice_state:
        return None
    voice_state_channel = voice_state.channel
    if match_channel_id is not None and voice_state_channel.id != match_channel_id:
        return None
    return voice_state_channel

def format_member_list(*_, ids=None, members=None):
    if ids is None and members is None:
        return None
    if members and not ids:
        ids = [m.id for m in members]
    return " ".join(f"<@{id_}>" for id_ in ids)


#%% [markdown]
# You are given an array of integers.
# Return the largest product that can be made by multiplying any 3 integers in the array.
#
# Example
# ```
# Input: [-4, -4, 2, 8]
# Output: 128
# ```

#%%
def maximum_product_of_three(lst):
    maxprod = lst[0] * lst[1] * lst[2]
    for i, x1 in enumerate(lst[:-2]):
        for j, x2 in enumerate(lst[i+1:-1]):
            for x3 in lst[i+j+2:]:
                maxprod = max(x1*x2*x3, maxprod)
    return maxprod

print(maximum_product_of_three([-4, -4, 2, 8]))


# vim: set tabstop=4 expandtab :
###############################################################################
#   Copyright (c) 2019-2021 ams AG
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
###############################################################################

# Authors:
# - Thomas Winkler, ams AG, thomas.winkler@ams.com

import binascii
import math
import struct
from enum import Enum
from typing import Union, Dict

from dottmi.dottexceptions import DottException
from dottmi.utils import log

ALIGN_DEFAULT = 4  # default alignment for memory allocation is 4 bytes

class TargetMemModel(Enum):
    """
    Enum for the different on-target memory allocation models supported by DOTT.
    """
    NOALLOC  = 0x0  # Don't use any of the built-in on-target memory allocation models.
    TESTHOOK = 0x1  # DOTT test-hook based memory allocation
    PRESTACK = 0x2  # memory allocation prior to stack memory ('stack stealing')

    @classmethod
    def get_keys(cls):
        return list(map(lambda c: c.name, cls))

# -------------------------------------------------------------------------------------------------
class TypedPtr:
    def __init__(self, target: 'Target', addr: int, var_type: str = None) -> None:
        """
        Constructor.

        Args:
            target: Target instance.
            addr: Address represented by the pointer.
            var_type: Type of the variable the pointer is pointing to.
        """
        self._target: 'Target' = target
        self._addr: int = addr
        self._var_type: str = var_type
        if self._var_type is None:
            self._var_type = 'void'

    @property
    def type(self) -> str:
        """
        This function returns the they of the variable the pointer is pointing to.

        Returns:
            Returns the type of the variable the pointer is pointing to.
        """
        return self._var_type

    @property
    def addr(self) -> int:
        """
        This function returns the raw address.

        Returns:
            Returns raw address as integer.
        """
        return self._addr

    @property
    def val(self) -> Union[int, float, bool, str, None]:
        """
        This function dereferences the pointer and returns the value. This might not be possible for all data types
        (e.g., composite types).

        Returns:
            Dereferences the pointer and returns the value.
        """
        return self._target.eval(f'*({self.__str__()})')

    def __getitem__(self, key) -> Union[int, float, bool, str, None]:
        """
        Allows access to items pointed to by TypedPtr in index notation. Example:
        p = dott().target.mem.alloc_type('uint32_t', cnt=16)
        p[8] = 0xdeadbeef
        print('0x%x' % p[8])

        Important: The implementation does not perform array index checking.

        Args:
            key: Index used for accessing the array data pointed to by the TypedPtr instance.

        Returns: The value at index key.
        """
        return self._target.eval(f'{self.__str__()}[{key}]')

    def __setitem__(self, key, value) -> None:
        """
        Allows access to items pointed to by TypedPtr in index notation. Example:
        p = dott().target.mem.alloc_type('uint32_t', cnt=16)
        p[8] = 0xdeadbeef
        print('0x%x' % p[8])

        Important: The implementation does not perform array index checking.

        Args:
            key: Index used for accessing the array data pointed to by the TypedPtr instance.

        Returns: The value at index key.
        """
        self._target.eval(f'{self.__str__()}[{key}] = {value}')

    def __str__(self) -> str:
        """
        This function returns a string containing address in hex (pre-fixed with 0x) together with the type of
        the pointer as a prefix. E.g., (uint32_t*)0x20000000

        Returns:
            Returns string representation of the pointer in hex format together with type prefix.
        """
        return f'(({self._var_type}*)0x{self._addr:x})'

# -------------------------------------------------------------------------------------------------
class TargetMem(object):
    def __init__(self, target: 'Target', target_mem_start_addr: int, target_mem_num_bytes: int, zero_mem: bool = True):
        """
        Constructor.

        Args:
            target: The target instance.
            target_mem_start_addr: The memory address where DOTT's on-target scratchpad memory starts.
            target_mem_num_bytes: The size in bytes of DOTT's on-target scratchpad memory.
            zero_mem: Zero out the on-target scratchpad memory when calling reset (default: True).
        """
        self._target: 'Target' = target
        self._sz_types: Dict = {}  # dict with target sizes (cache used by sizeof)
        self._heap_next_free_addr: int = target_mem_start_addr
        self._target_mem_base_addr: int = target_mem_start_addr
        self._target_mem_num_bytes: int = target_mem_num_bytes
        self._zero_mem = zero_mem
        self.reset()

    def _bytes_needed(self, n):
        if n == 0:
            return 1
        return int(math.log(n, 256)) + 1

    def _write_raw(self, dst_addr: Union[int, str, TypedPtr], values: bytes) -> None:
        content = binascii.hexlify(struct.pack('<%dB' % len(values), *values)).decode('utf8')
        self._target.exec(f'-data-write-memory-bytes {dst_addr} "{content}"')

    def sizeof(self, target_type: str) -> int:
        """
        This function returns the size in bytes of the given target data type.

        Args:
            target_type: Name of the target data type.

        Returns:
            The size in bytes of the data type on target.
        """
        if target_type not in self._sz_types.keys():
            try:
                sz = int(self._target.eval('sizeof(%s)' % target_type))
                self._sz_types[target_type] = sz
            except:
                log.error('Unable to determine size for target type %s' % target_type)

        return self._sz_types[target_type]

    def write(self, dst_addr: Union[int, str, TypedPtr], val: Union[int, bytes, str], cnt: int = 1) -> None:
        """
        This function writes the provided data to target memory at destination address. If cnt is other than one,
        the provided data is replicated cnt times.

        Args:
            dst_addr: The target's destination memory address to write to.
            val: Content to be written to the target.
            cnt: The number of times val shall be repeated when writing to the target.
        """
        if isinstance(val, int):
            # note: int.to_bytes raises exception if type_sz != val size
            bval = val.to_bytes(self._bytes_needed(val), byteorder=self._target.byte_order)
            self._write_raw(dst_addr, bval * cnt)
        elif isinstance(val, bytes):
            self._write_raw(dst_addr, val * cnt)
        elif isinstance(val, str):
            bval = bytes(val, encoding='ascii')
            self._write_raw(dst_addr, bval * cnt)
        else:
            raise ValueError('Only int, bytes or str (ascii) are supported as val types')

    def read(self, src_addr: Union[int, str, TypedPtr], num_bytes: int) -> bytes:
        """
        This function reads the requested number of bytes from the specified source address.

        Args:
            src_addr: The target's source memory address to read from.
            num_bytes: The number of bytes to read from target memory.

        Returns:
            Returns the bytes read from the target.
        """
        num_remaining: int = num_bytes
        if isinstance(src_addr, int):
            addr_to_read = src_addr
        elif isinstance(src_addr, str):
            addr_to_read = int(src_addr, 10)
        elif isinstance(src_addr, TypedPtr):
            addr_to_read = src_addr.addr
        else:
            raise ValueError('Illegal type for src_addr')
        content = ''

        while num_remaining > 0:
            bytes_to_read = 1024
            if num_remaining < 1024:
                bytes_to_read = num_remaining

            data = self._target.exec(f'-data-read-memory-bytes -o 0 {addr_to_read} {bytes_to_read}')
            buf = data['payload']['memory'][0]['contents']
            buf_len = len(buf) / 2
            content += buf

            num_remaining -= buf_len
            addr_to_read += buf_len

        return binascii.unhexlify(content)

    def reset(self) -> None:
        """
        This function resets the on-target memory. It sets the next_element pointer back to the first element and it
        zeros out the on-target memory region used for memory allocation.
        """
        self._heap_next_free_addr = self._target_mem_base_addr
        if self._zero_mem:
            # note: bytes(sz) creates zero-filled bytes object of length sz
            self.write(self._target_mem_base_addr, bytes(self._target_mem_num_bytes))

    def alloc(self, req_num_bytes: int, var_name: str = None, align: int = ALIGN_DEFAULT) -> TypedPtr:
        """
        This function allocates the requested number of bytes on the target device. The allocated memory is guaranteed
        to be word (32bit aligned). Optionally, a GDB convenience variable with the provided variable name is created
        which can be optionally used to reference the allocated memory in GDB commands.

        Args:
            req_num_bytes: Requested number of bytes.
            var_name: Optional GDB variable name used for the newly allocated memory.
            align: Alignment for allocated memory. Default is 4 bytes.

        Returns:
            Returns the address of the allocated on-target memory as a TypedPtr.
        """
        align_delta: int = 0
        if self._heap_next_free_addr % align != 0:
            align_delta = align - (self._heap_next_free_addr % align)

        # number of bytes still available on target for memory allocation
        avail_bytes: int = (self._target_mem_base_addr + self._target_mem_num_bytes) - (self._heap_next_free_addr + align_delta)

        assert(req_num_bytes <= avail_bytes), 'unable to allocate %d bytes of on-target memory' % req_num_bytes

        addr: int = self._heap_next_free_addr + align_delta
        self._heap_next_free_addr += align_delta + req_num_bytes

        if var_name is not None:
            self._target.cli_exec(f'set var {var_name} = (void*){addr}')

        return TypedPtr(self._target, addr, 'void')

    def alloc_type(self, var_type: str, val: Union[int, bytes, str] = None, cnt: int = 1, var_name: str = None, align: int = ALIGN_DEFAULT) -> TypedPtr:
        """
        This function allocates on-target memory for cnt number of variables of the specified type. The start of the
        allocated memory is guaranteed to be word (32bit aligned). If the memory is allocated for, e.g., for an array
        holding elements of a composite type with size not being a multiple of words, this function does not guarantee
        word alignment from the second array element onwards. In other word, this function simply allocates memory
        of size = sizeof(var_type) * cnt.
        Optionally, the allocate memory can be initialized with the provided value.
        Optionally, a GDB convenience variable with the provided variable name is created which can be used to reference
        the allocated memory in GDB commands.

        Args:
            var_type: Type of variable to be allocated on-target.
            val: Value for the newly assigned variable. Note that if cnt > 1 this value is set for all the elements.
            cnt: Number of elements to be allocated.
            var_name: Optional GDB variable name used for the newly allocated memory.
            align: Alignment for allocated memory. Default is 4 bytes.

        Returns:
            Returns the address of the allocated on-target memory as a TypedPtr.
        """
        type_sz: int = self.sizeof(var_type)
        p_var: TypedPtr = self.alloc(type_sz * cnt, var_name, align)
        if val is not None:
            self.write(p_var, val, cnt)

        # optionally create a gdb convenience variable and cast to concrete type as specified by var_type
        if var_name is not None:
            self._target.cli_exec('set var %s = (%s*)%s' % (var_name, var_type, var_name))
        return TypedPtr(self._target, p_var.addr, var_type)

    def get_num_alloc_bytes(self) -> int:
        """
        Returns: Number of bytes allocated since last call to TargetMem::reset.
        """
        return self._heap_next_free_addr - self._target_mem_base_addr

# -------------------------------------------------------------------------------------------------
class TargetMemTestHook(TargetMem):
    """
    This class implements a variation of the TargetMem class which is intended to be used if the DOTT_test_hook is
    used for on-target memory allocation. In addition to setting the correct memory address (in stack from of the
    test hook) this class also checks that allocation is only performed if the target is halted in the context of the
    test hook.
    """
    def __init__(self, target: 'Target'):
        start_addr = target.eval('dbg_mem_u32')
        num_bytes = int(target.eval('dbg_mem_u32_sz'))
        super().__init__(target, start_addr, num_bytes)

    def alloc(self, req_num_bytes: int, var_name: str = None, align: int = ALIGN_DEFAULT):
        try:
            self._target.eval('dbg_mem_u32')  # raises exception if symbol is not accessible in current context
        except:
            raise DottException('Test-hook based memory allocation is only possible '
                                'if program is halted in the test hook!') from None
        return super().alloc(req_num_bytes, var_name, align)

    def alloc_type(self, var_type: str, val: Union[int, bytes, str] = None, cnt: int = 1, var_name: str = None, align: int = ALIGN_DEFAULT):
        try:
            self._target.eval('dbg_mem_u32')  # raises exception if symbol is not accessible in current context
        except Exception:
           raise DottException('Test-hook based memory allocation is only possible '
                               'if program is halted in the test hook!') from None

        return super().alloc_type(var_type, val, cnt, var_name, align)

# -------------------------------------------------------------------------------------------------
class TargetMemNoAlloc(TargetMem):
    """
    This class implements a variation of the TargetMem class which actually does not allow on-target memory allocation.
    Target memory bulk read and write still are supported.
    """
    def __init__(self, target: 'Target'):
        start_addr = 0xffffffff
        num_bytes = 0
        super().__init__(target, start_addr, num_bytes)

    def alloc(self, req_num_bytes: int, var_name: str = None, align: int = ALIGN_DEFAULT) -> TypedPtr:
        raise Exception('On-target memory allocation not supported in by this memory model!')

    def alloc_type(self, var_type: str, val: Union[int, bytes, str] = None, cnt: int = 1, var_name: str = None, align: int = ALIGN_DEFAULT) -> TypedPtr:
        raise Exception('On-target memory allocation not supported in by this memory model!')

    def reset(self) -> None:
        return

# -------------------------------------------------------------------------------------------------
class TargetMemScoped(object):
    """
    This class implements a form of on-target, on-stack memory allocation with a limited scope. In contrast to the
    test hook approach, this allocation technique can be used at every location the program can be halted. At this
    halt location, it enables users to grab a chunk of memory which is located on the current stack as indicated by
    SP. If this is MSP or PSP is not checked.
    It returns a TargetMem instance which can be used to allocate memory blocks within this on-target memory chunk.
    These allocated memory regions can then be populated and used as arguments in on-target function calls using
    'eval(...)'. At the end of the 'with ... as' statement, the chunk of on target memory is 'returned' to the target
    by re-adjusting the stack pointer accordingly.

    Example:
        # - grab a chunk of 128 bytes of on-target (stack) memory
        # - within this chunk, allocate an array with 5 uint16_t variables
        # - fill the array, use it as function call parameter
        # - note: outside the scope of the 'with ... as', the m.alloc functions are unavailable as the chunk of
        #   on-target stack is already returned to the target system.

        with TargetMemScoped(dott().target, 128) as m:
            elements = [0, 1, 2, 65535, 99]
            addr = m.alloc_type('uint16_t', cnt=len(elements), val=0x0)
            for i in range(len(elements)):
                dott().target.eval(f'{addr}[{i}] = {elements[i]}')
            res = dott().target.eval(f'example_SumElements({addr}, {len(elements)})')
            assert (sum(elements) == res), f'expected: {sum(elements)}, is: {res}'
    """
    def __init__(self, target: 'Target', num_bytes: int, suppress_warnings: bool = False):
        """
        Constructor.

        Args:
            target: The target instance on which the memory shall be allocated.
            num_bytes: The number of bytes the chunk of memory shall be able to hold. Note: This value is internally
                     increased to the next value where num_bytes % 8 == 0 to ensure double-world alignment of the stack.
            suppress_warnings: Suppress warnings which would be issued if the SP and PC are not having the expected
                     values when leaving the 'with ... as' block.
        """
        self._target: 'Target' = target
        self._pc_init: int = 0x0  # the program counter upon entering the 'with' block
        self._sp_init: int = 0x0  # the stack pointer upon entering the 'with' block
        self._sp_init_dec: int = 0x0  # the decremented _sp_init
        self._mem: TargetMem = None
        # ensure that the requested number of bytes is a multiple of 8 (double-word alignment of stack; cp.
        # "Procedure Call Standard for the Arm® Architecture").
        if num_bytes % 8 != 0:
            num_bytes += 8 - (num_bytes % 8)
        self._num_bytes: int = num_bytes  # the size in bytes of the on-target memory chunk
        self._suppress_warnings: bool = suppress_warnings

    def __enter__(self) -> TargetMem:
        if self._target.is_running():
            raise DottException('Target must be halted when initializing scoped on-target memory.')

        # save current stack pointer and program counter
        self._sp_init = self._target.eval('$sp')
        self._pc_init = self._target.eval('$pc')

        # (1) set decremented SP equal to current SP
        self._sp_init_dec = self._sp_init

        # (2) check if SP is double-word aligned. if not, do so.
        if self._sp_init_dec % 8 != 0:
            # Arm 'Procedure Call Standard for the Arm Architecture' requires double-word alignment on
            # 'public interface' (i.e., when calling functions).
            log.warn('Current SP is not double-word aligned! Correcting alignment for allocated memory.')
            self._sp_init_dec += 8 - (self._sp_init_dec % 8)

        # (3) decrement SP
        # Note: Stack is "full-descending" (see 'Procedure Call Standard for the Arm Architecture').
        #       That means the SP points to the last used (full)  entry and the stack grows down (descends).
        self._sp_init_dec -= self._num_bytes  # decrement (descend) SP

        # Finally, adjust the SP to reserve the requested chunk of the stack. Create and return a memory manager for it.
        self._target.eval(f'$sp = {self._sp_init_dec}')
        self._mem = TargetMem(self._target, self._sp_init_dec, self._num_bytes)
        return self._mem

    def __reset_sp(self):
        pc_curr = self._target.eval('$pc')
        sp_curr = self._target.eval('$sp')

        sp_pc_ok: bool = True

        # check if SP and PC are as expected
        if sp_curr != self._sp_init_dec:
            sp_pc_ok = False
            if not self._suppress_warnings:
                log.warn(f'Stack pointer is not as expected (expected: 0x{self._sp_init_dec:x}, act: 0x{sp_curr:x}). '
                         f'You should not alter execution flow within "with" block os scoped memory by using DOTT '
                         f'functions such as "cont", "ret", "step", and "step_inst" etc.!')
        if pc_curr != self._pc_init:
            sp_pc_ok = False
            if not self._suppress_warnings:
                log.warn(f'Program counter is not as expected (expected: 0x{self._pc_init:x}, actual: 0x{pc_curr:x}). '
                         f'You should not alter execution flow within "with" block os scoped memory by using DOTT '
                         f'functions such as "cont", "ret", "step", and "step_inst" etc.!')

        if sp_pc_ok:
            self._target.eval(f'$sp = {self._sp_init}')
        else:
            if not self._suppress_warnings:
                log.warn('Not undoing stack memory allocation at end of "with" statement!')

    @staticmethod
    def __func_unavailable(*args) -> None:
        log.warn("The functions 'alloc', 'alloc_type', and 'reset' are no longer available after the 'with ... as' "
                 "block of TargetMemScoped!")

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Note: We are not checking if there was an exception. We are always undoing (rolling back)
        # the on-stack memory allocation.

        if self._target.is_running():
            raise DottException('Target must be halted when leaving "with" block of scoped on-target memory.')

        # reset the internal state of the TargetMem instance with respect to the memory it managed.
        self._mem.reset()
        # reset the SP to the state it had before the 'with' block
        self.__reset_sp()
        # make alloc/reset functions of the TargetMem instance unusable after the 'with' block.
        self._mem.alloc = self.__func_unavailable
        self._mem.alloc_type = self.__func_unavailable
        self._mem.reset = self.__func_unavailable


import sys
import os
import glob
import argparse
#from ..common.bounding_box import BoundingBox
import subprocess
import json
from rh_logger.api import logger
import rh_logger
import logging
import multiprocessing as mp
import numpy as np

def add_transformation(in_file, out_file, transform, deltas):
    # load the current json file
    try:
        with open(in_file, 'r') as f:
            data = json.load(f)
    except:
        logger.report_event("Error when reading {} - Exiting".format(in_file), log_level=logging.ERROR)
        raise

    if deltas[0] != 0.0 and deltas[1] != 0.0:
        for tile in data:
            # Update the transformation
            if "transforms" not in tile.keys():
                tile["transforms"] = []
            tile["transforms"].append(transform)

            # Update the bbox
            if "bbox" in tile.keys():
                bbox = tile["bbox"]
                bbox_new = [bbox[0] - deltas[0], bbox[1] - deltas[0], bbox[2] - deltas[1], bbox[3] - deltas[1]]
                tile["bbox"] = bbox_new

    with open(out_file, 'w') as f:
        json.dump(data, f, indent=4)

def read_minxy_grep(tiles_spec_fname):
    cmd = "grep -A 5 \"bbox\" {}".format(tiles_spec_fname)
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Output will be of the following format:
    """
        "bbox": [
            13262.416015625,
            16390.580476722345,
            10470.920522462373,
            13195.109375
        ],
--
        "bbox": [
            16273.984836771779,
            19402.12109375,
            10470.3515625,
            13194.508027928736
        ],
--
...
    """

    # Parse all bounding boxes in the given json file
    lines = p.stdout.readlines()
    min_x = np.min([float(line.decode('utf-8').strip(' ,\n')) for line in lines[1::7]])
    #max_x = np.max([float(line.decode('utf-8').strip(' ,\n')) for line in lines[2::7]])
    min_y = np.min([float(line.decode('utf-8').strip(' ,\n')) for line in lines[3::7]])
    #max_y = np.max([float(line.decode('utf-8').strip(' ,\n')) for line in lines[4::7]])
    #return np.array([min_x, max_x, min_y, max_y])
    return [min_x, min_y]

#     ret_val = None
#     cur_bbox_lines = []
#     for line in iter(p.stdout.readline, ''):
#         if line.startswith("--"):
#             cur_bbox = BoundingBox.fromStr(BoundingBox.parse_bbox_lines(cur_bbox_lines))
#             if ret_val is None:
#                 ret_val = cur_bbox
#             else:
#                 ret_val.extend(cur_bbox)
#             cur_bbox_lines = []
#         else:
#             cur_bbox_lines.append(line.strip(' \n'))
#     if len(cur_bbox_lines) > 0:
#         cur_bbox = BoundingBox.fromStr(BoundingBox.parse_bbox_lines(cur_bbox_lines))
#         if ret_val is None:
#             ret_val = cur_bbox
#         else:
#             ret_val.extend(cur_bbox)
#     return ret_val

def normalize_coordinates(tile_fnames_or_dir, output_dir, pool):
    # Get all the files that need to be normalized
    all_files = []

    logger.report_event("Reading {}".format(tile_fnames_or_dir), log_level=logging.INFO)
    for file_or_dir in tile_fnames_or_dir:
        if not os.path.exists(file_or_dir):
            logger.report_event("{0} does not exist (file/directory), skipping".format(file_or_dir), log_level=logging.WARN)
            continue

        if os.path.isdir(file_or_dir):
            actual_dir_files = glob.glob(os.path.join(file_or_dir, '*.json'))
            all_files.extend(actual_dir_files)
        else:
            all_files.append(file_or_dir)

    if len(all_files) == 0:
        logger.report_event("No files for normalization found.", log_level=logging.ERROR)
        raise Exception("No files for normalization found.")

    logger.report_event("Normalizing coordinates of {} files".format(len(all_files)), log_level=logging.INFO)

    # Retrieve the bounding box of these files
    entire_image_bbox = None

    # merge the bounding boxes to a single bbox
    if len(all_files) > 0:
        sections_min_xys = np.array(pool.map(read_minxy_grep, all_files))
#         entire_image_bbox = np.array([
#                                 np.min(sections_bboxes[:, 0]), np.max(sections_bboxes[:, 1]),
#                                 np.min(sections_bboxes[:, 2]), np.max(sections_bboxes[:, 3])
#                             ])

    # Set the translation transformation
    #deltaX = entire_image_bbox[0]
    #deltaY = entire_image_bbox[2]
    deltaX = np.min(sections_min_xys[:, 0])
    deltaY = np.min(sections_min_xys[:, 1])

    logger.report_event("Entire 3D image min x,y: {}, {}".format(deltaX, deltaY), log_level=logging.INFO)

    # TODO - use models to create the transformation
    transform = {
            "className" : "mpicbg.trakem2.transform.TranslationModel2D",
            "dataString" : "{0} {1}".format(-deltaX, -deltaY)
        }

    # Add the transformation to each tile in each tilespec
#     out_files = [os.path.join(output_dir, os.path.basename(in_file)) for in_file in all_files]
#     pool.map(lambda in_f, out_f: add_transformation(in_f, out_f, transform, [deltaX, deltaY]), zip(all_files, out_files))
    pool_results = []
    for in_file in all_files:
        out_file = os.path.join(output_dir, os.path.basename(in_file))
        res = pool.apply_async(add_transformation, (in_file, out_file, transform, [deltaX, deltaY]))
        pool_results.append(res)

    for res in pool_results:
        res.get()

if __name__ == '__main__':
    # Command line parser
    parser = argparse.ArgumentParser(description='Given a list of tilespec file names, normalizes all the tilepecs to a single coordinate system starting from (0,0).')
    parser.add_argument('tile_files_or_dirs', metavar='tile_files_or_dirs', type=str, nargs='+',
                        help='a list of json files that need to be normalized or a directories of json files')
    parser.add_argument('-o', '--output_dir', type=str,
                        help='an output directory (default: ./after_norm)',
                        default='./after_norm')
    parser.add_argument('-p', '--processes_num', type=int,
                        help='number of processes (default: 1)',
                        default=1)

    args = parser.parse_args()

    logger.start_process('normalize_coordinates', 'normalize_coordinates.py', [args.tile_files_or_dirs, args.output_dir])
    pool = mp.Pool(processes=args.processes_num)

    normalize_coordinates(args.tile_files_or_dirs, args.output_dir, pool)

    pool.close()
    pool.join()

    logger.end_process('normalize_coordinates', rh_logger.ExitCode(0))


'''
2) (пользовательский ввод можно заменить на рандомный)
Пользователь вводит  размер массива – N
и элементы массива (целые числа).
нужно посчитать сколько повторений у каждого числа
посчитанные числа можно посчитать повторно в паре с другими числами

Ввод:			Вывод:
1 2 3 2 3 2			4
Пример решения на Python:

import random

n = int(input("Введите размер массива: "))
arr = []
for i in range(n):
    arr.append(random.randint(1, 10)) # генерируем случайные числа от 1 до 10

count_dict = {}
for num in arr:
    if num not in count_dict:
        count_dict[num] = arr.count(num)

total_count = 0
for count in count_dict.values():
    total_count += count * (count - 1) // 2 # формула для подсчета количества пар

print("Количество пар чисел с повторениями:", total_count)

'''
from random import randint

n = randint(5, 10)
list1 = [randint(1, 10) for num in range(n)]
print(list1)

count = 0

for i in range(len(list1)):
    for j in range(i + 1, len(list1)):
        if list1[i] == list1[j]:
            count += list1.count(+1)
print(count)