from zope.interface import implements
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.cachedescriptors.property import Lazy

import zc.resourcelibrary
from zc.table import table

from schooltool.common.inlinept import InlineViewPageTemplate
from schooltool.skin import flourish
from schooltool.table.interfaces import IFilterWidget
from schooltool.table.interfaces import IIndexedColumn
from schooltool.table.batch import TokenBatch
from schooltool.table.table import TableContent, FilterWidget
from schooltool.table.table import url_cell_formatter
from schooltool.table.table import SortUIHeaderMixin
from schooltool.table.table import HeaderFormatterMixin
from schooltool.table.table import StandaloneHeaderFormatterMixin
from schooltool.table.catalog import IndexedTableFormatter
from schooltool.table.catalog import IndexedFilterWidget
from schooltool.common import SchoolToolMessage as _

class AJAXSortHeaderMixin(SortUIHeaderMixin):

    html_id = None

    def _header_template(self, options):
        options = dict(options)
        options['containerID'] = self.html_id
        template = """

                %(header)s
        """
        return template % options

class AJAXFormSortFormatter(HeaderFormatterMixin,
                            AJAXSortHeaderMixin,
                            table.FormSortFormatter):
    script_name = 'ST.table.on_form_sort'

class AJAXStandaloneSortFormatter(StandaloneHeaderFormatterMixin,
                                  AJAXSortHeaderMixin,
                                  table.StandaloneSortFormatter):
    script_name = 'ST.table.on_standalone_sort'

class Table(flourish.ajax.CompositeAJAXPart, TableContent):

    no_default_url_cell_formatter = False

    container_wrapper = ViewPageTemplateFile('templates/f_ajax_table.pt')

    form_wrapper = InlineViewPageTemplate("""
      <form method="post" tal:attributes="action view/@@absolute_url;
                                          class view/form_class;
                                          id view/form_id">
        <tal:block replace="structure view/template" />
      </form>
    """)

    empty_message = u""
    form_class = None
    form_id = None

    table_formatter = AJAXFormSortFormatter

    inside_form = False # don't surround with <form> tag if inside_form

    @Lazy
    def html_id(self):
        return flourish.page.generic_viewlet_html_id(self, self.prefix)

    @Lazy
    def filter_widget(self):
        return self.get('filter')

    @Lazy
    def batch(self):
        return self.get('batch')

    def updateFormatter(self):
        if self._table_formatter is not None:
            return
        if self.no_default_url_cell_formatter:
            formatters = []
        else:
            formatters = [url_cell_formatter]
        self.setUp(formatters=formatters,
                   table_formatter=self.table_formatter,
                   batch_size=self.batch_size,
                   prefix=self.__name__,
                   css_classes={'table': 'data'})

    def update(self):
        self.updateFormatter()
        TableContent.update(self)
        flourish.ajax.CompositeAJAXPart.update(self)

    def makeFormatter(self):
        if self._table_formatter is None:
            return None
        formatter = self._table_formatter(
            self.source, self.request, self._items,
            visible_column_names=self.visible_column_names,
            columns=self._columns,
            batch_start=self.batch.start, batch_size=self.batch.size,
            sort_on=self._sort_on,
            prefix=self.prefix,
            ignore_request=self.ignoreRequest,
            group_by_column=self.group_by_column,
            )
        formatter.html_id = self.html_id
        formatter.view = self
        formatter.cssClasses.update(dict(self.css_classes))
        return formatter

    def renderTable(self):
        formatter = self.makeFormatter()
        return formatter() if formatter is not None else ''

    def render(self, *args, **kw):
        content = ''
        if self.inside_form:
            content = self.template(*args, **kw)
        else:
            content = self.form_wrapper(*args, **kw)

        if self.fromPublication:
            return content

        zc.resourcelibrary.need('schooltool.table')
        return self.container_wrapper(content=content)

class TableFilter(flourish.viewlet.Viewlet, FilterWidget):
    implements(IFilterWidget)

    before = ("batch", "table")

    template = ViewPageTemplateFile("templates/f_filter.pt")
    title = _("Search")
    legend = _("Search")

    @property
    def source(self):
        return self.manager.source

    @property
    def ignoreRequest(self):
        return self.manager.ignoreRequest

    def filter(self, list):
        if self.ignoreRequest:
            return list
        return FilterWidget.filter(self, list)

    @property
    def script(self):
        return "return ST.table.on_form_submit(${html_id}, this);"

class TableBatch(flourish.viewlet.Viewlet):

    before = ("table", )

    batch = None

    def __init__(self, context, request, view, manager):
        flourish.viewlet.Viewlet.__init__(
            self, context, request, view, manager)

    @property
    def html_id(self):
        return flourish.page.generic_viewlet_html_id(self)

    def __iter__(self):
        return iter(self.batch)

    def update(self):
        if self.manager.prefix:
            self.name = "." + self.manager.prefix
        else:
            self.name = ""
        if self.manager.ignoreRequest:
            start = 0
            size = self.manager.batch_size
        else:
            start = int(self.request.get(
                    'start' + self.name, 0))
            size = int(self.request.get(
                    'size' + self.name, self.manager.batch_size))
        items = self.manager._items
        self.batch = TokenBatch(
            items, size=size, start=start)

    @property
    def needsBatch(self):
        batch = self.batch
        return (batch.size < batch.full_size and batch.needsBatch)

    def extend_token(self, token, **kw):
        token = dict(token)
        script = "return ST.table.on_batch_link('%s', '%s', %d, %d);" % (
            self.manager.html_id,
            self.name, token['start'],
            token['size'])
        token['onclick'] = script
        token.update(kw)
        return token

    @property
    def start(self):
        return self.batch.start

    @property
    def size(self):
        return self.batch.size

    @property
    def length(self):
        return len(self.batch)

    @property
    def full_size(self):
        return self.batch.full_size

    @Lazy
    def previous(self):
        token = self.batch.previous()
        if token is None:
            return None
        return self.extend_token(token, css_class='previous')

    @Lazy
    def next(self):
        token = self.batch.next()
        if token is None:
            return None
        return self.extend_token(token, css_class='next')

    @Lazy
    def show_all(self):
        if self.batch.size >= self.batch.full_size:
            return None
        script = "return ST.table.on_batch_link('%s', '%s', %d, %d);" % (
            self.manager.html_id,
            self.name, 0, self.full_size)
        return {'start': 0,
                'size': self.full_size,
                'items': self.batch.items,
                'onclick': script,
                'css_class': 'all'}

    def tokens(self):
        tokens = []
        for token in self.batch.tokens():
            css_class = "batch_page"
            css_class += token['current'] and ' current' or ''
            token = self.extend_token(token, css_class=css_class)
            tokens.append(token)
        return tokens

class TableTable(flourish.viewlet.Viewlet):

    def render(self, *args, **kw):
        return self.manager.renderTable()

class IndexedTable(IndexedTableFormatter, Table):

    @Lazy
    def filter_widget(self):
        return self.get('filter')

    def makeFormatter(self):
        if self._table_formatter is None:
            return ''
        columns = [IIndexedColumn(c) for c in self._columns]
        formatter = self._table_formatter(
            self.source, self.request, self._items,
            columns=columns,
            batch_start=self.batch.start, batch_size=self.batch.size,
            sort_on=self._sort_on,
            prefix=self.prefix,
            group_by_column=self.group_by_column)
        formatter.html_id = self.html_id
        formatter.view = self
        formatter.cssClasses.update(dict(self.css_classes))
        return formatter

    renderTable = Table.renderTable

    def render(self, *args, **kw):
        return Table.render(self, *args, **kw)

class IndexedTableFilter(TableFilter, IndexedFilterWidget):

    def filter(self, list):
        if self.ignoreRequest:
            return list
        return IndexedFilterWidget.filter(self, list)


def isValidSubsequence(array, sequence):
    if array == sequence:
        return True

    check_list = []
    for i in sequence:
        for j in array:
            if j == i:
                check_list.append(True)
                break

    for boolean in check_list:
        if not boolean:
            return False
        return True

arr = [5,1,22,25,6,-1,8,10]
sub = [1,6,-1,10]

print(isValidSubsequence(arr, sub))


from typing import List

from celery import shared_task

from exareme2 import DATA_TABLE_PRIMARY_KEY
from exareme2.exceptions import DataModelUnavailable
from exareme2.exceptions import DatasetUnavailable
from exareme2.node import config as node_config
from exareme2.node.monetdb_interface import views
from exareme2.node.monetdb_interface.common_actions import create_table_name
from exareme2.node.monetdb_interface.common_actions import get_data_models
from exareme2.node.monetdb_interface.common_actions import (
    get_dataset_code_per_dataset_label,
)
from exareme2.node.node_logger import initialise_logger
from exareme2.node_tasks_DTOs import TableInfo
from exareme2.node_tasks_DTOs import TableType

MINIMUM_ROW_COUNT = node_config.privacy.minimum_row_count

@shared_task
@initialise_logger
def get_views(request_id: str, context_id: str) -> List[str]:
    """
    Parameters
    ----------
    request_id : str
        The identifier for the logging
    context_id : str
        The id of the experiment

    Returns
    ------
    List[str]
        A list of view names
    """
    return views.get_view_names(context_id)

@shared_task
@initialise_logger
def create_data_model_views(
    request_id: str,
    context_id: str,
    command_id: str,
    data_model: str,
    datasets: List[str],
    columns_per_view: List[List[str]],
    filters: dict = None,
    dropna: bool = True,
    check_min_rows: bool = True,
) -> List[str]:
    """
    Create a view on a provided data model with specific columns, filters and datasets to the DB.

    Parameters
    ----------
    request_id : str
        The identifier for the logging
    context_id : str
        The id of the experiment
    command_id : str
        The id of the command that the view
    data_model : str
        The data_model data table on which the view will be created
    datasets : List[str]
        The datasets that will be used in the view.
    columns_per_view : List[List[str]]
        One view will be created for each list of columns.
    filters : dict
        A Jquery filters object
    dropna : bool
        A flag that determines if the not null constraints about the columns should be included in the filters
    check_min_rows : bool
        A flag that determines if the min_rows_threshold should be checked.

    Returns
    ------
    List[str(TableInfo)]
        A list of TableInfo objects in a jsonified format
    """
    _validate_data_model_and_datasets_exist(data_model, datasets)
    if datasets:
        filters = _get_filters_with_datasets_constraints(
            filters=filters, datasets=datasets
        )

    # In each view, it's not null constraints should include the columns of ALL views
    if dropna:
        all_columns = [column for columns in columns_per_view for column in columns]
        filters = _get_filters_with_columns_not_null_constraints(
            filters=filters, columns=all_columns
        )

    return [
        create_data_model_view(
            context_id=context_id,
            command_id=command_id,
            result_id=str(count),
            data_model=data_model,
            columns=view_columns,
            filters=filters,
            check_min_rows=check_min_rows,
        ).json()
        for count, view_columns in enumerate(columns_per_view)
    ]

def create_data_model_view(
    context_id: str,
    command_id: str,
    result_id: str,
    data_model: str,
    columns: List[str],
    filters: dict = None,
    check_min_rows: bool = True,
) -> TableInfo:
    view_name = create_table_name(
        table_type=TableType.VIEW,
        node_id=node_config.identifier,
        context_id=context_id,
        command_id=command_id,
        result_id=result_id,
    )
    columns.insert(0, DATA_TABLE_PRIMARY_KEY)

    return views.create_view(
        view_name=view_name,
        table_name=f'"{data_model}"."primary_data"',
        columns=columns,
        filters=filters,
        minimum_row_count=MINIMUM_ROW_COUNT,
        check_min_rows=check_min_rows,
    )

def _get_filters_with_datasets_constraints(filters, datasets):
    """
    This function will return the given filters which will also include the dataset's constraints.
    """
    rules = [
        {
            "id": "dataset",
            "field": "dataset",
            "type": "string",
            "input": "text",
            "operator": "in",
            "value": datasets,
        }
    ]

    if filters:
        rules.append(filters)

    return {
        "condition": "AND",
        "rules": rules,
        "valid": True,
    }

def _get_filters_with_columns_not_null_constraints(filters, columns):
    """
    This function will return the given filters which will also include the columns' not null constraints.
    """
    rules = [
        {
            "condition": "AND",
            "rules": [
                {
                    "id": variable,
                    "type": "string",
                    "operator": "is_not_null",
                    "value": None,
                }
                for variable in columns
            ],
        }
    ]

    if filters:
        rules.append(filters)

    return {
        "condition": "AND",
        "rules": rules,
        "valid": True,
    }

def _validate_data_model_and_datasets_exist(data_model: str, datasets: List[str]):
    if data_model not in get_data_models():
        raise DataModelUnavailable(node_config.identifier, data_model)

    available_datasets = get_dataset_code_per_dataset_label(data_model)
    for dataset in datasets:
        if dataset not in available_datasets:
            raise DatasetUnavailable(node_config.identifier, dataset)

@shared_task
@initialise_logger
def create_view(
    request_id: str,
    context_id: str,
    command_id: str,
    table_name: str,
    columns: List[str],
    filters: dict,
) -> str:
    """
    Creates a view of a table with specific columns and filters to the DB.

    Parameters
    ----------
    request_id : str
        The identifier for the logging
    context_id : str
        The id of the experiment
    command_id : str
        The id of the command that the view
    table_name : str
        The name of the table
    columns : List[str]
        A list of column names
    filters : dict
        A Jquery filters in a dict

    Returns
    ------
    str(TableInfo)
        A TableInfo object in a jsonified format
    """
    view_name = create_table_name(
        TableType.VIEW,
        node_config.identifier,
        context_id,
        command_id,
    )
    return views.create_view(
        view_name=view_name,
        table_name=table_name,
        columns=columns,
        filters=filters,
        minimum_row_count=MINIMUM_ROW_COUNT,
    ).json()


# ############################################################################ #
#                                                                              #
#                                                         :::      ::::::::    #
#    align.py                                           :+:      :+:    :+:    #
#                                                     +:+ +:+         +:+      #
#    By: cacharle <me@cacharle.xyz>                 +#+  +:+       +#+         #
#                                                 +#+#+#+#+#+   +#+            #
#    Created: 2020/10/04 09:56:31 by cacharle          #+#    #+#              #
#    Updated: 2021/02/11 20:13:11 by charles          ###   ########.fr        #
#                                                                              #
# ############################################################################ #

from __future__ import annotations

import re
import typing

if typing.TYPE_CHECKING:
    from typing import Literal

from c_formatter_42.formatters import helper

TYPEDECL_OPEN_REGEX = re.compile(
    r"""^(?P<prefix>\s*(typedef\s+)?   # Maybe a typedef
        (struct|enum|union))           # Followed by a struct, enum or union
        \s*(?P<suffix>[a-zA-Z_]\w+)?$  # Name of the type declaration
    """,
    re.X,
)
TYPEDECL_CLOSE_REGEX = re.compile(
    r"""^(?P<prefix>\})\s*             # Closing } followed by any amount of spaces
        (?P<suffix>([a-zA-Z_]\w+)?;)$  # Name of the type (if typedef used)
    """,
    re.X,
)

def align_scope(content: str, scope: Literal["local", "global"]) -> str:
    """Align content
    scope can be either local or global
      local:  for variable declarations in function
      global: for function prototypes
    """

    lines = content.split("\n")
    # select regex according to scope
    if scope == "local":
        align_regex = "^\t" r"(?P<prefix>{type})\s+" r"(?P<suffix>\**{decl};)$"
    elif scope == "global":
        align_regex = (
            r"^(?P<prefix>{type})\s+"
            r"(?P<suffix>({name}\(.*\)?;?)|({decl}(;|(\s+=\s+.*))))$"
        )
    align_regex = align_regex.format(
        type=helper.REGEX_TYPE, name=helper.REGEX_NAME, decl=helper.REGEX_DECL_NAME
    )
    lines_to_be_aligned = [re.match(align_regex, line) for line in lines]
    aligned = [
        (i, match.group("prefix"), match.group("suffix"))
        for i, match in enumerate(lines_to_be_aligned)
        if match is not None
        and match.group("prefix") not in ["struct", "union", "enum"]
    ]

    # Global type declaration (struct/union/enum)
    if scope == "global":
        in_type_scope = False
        for i, line in enumerate(lines):
            m = TYPEDECL_OPEN_REGEX.match(line)
            if m is not None:
                in_type_scope = True
                if m.group("suffix") is not None and "typedef" not in m.group("prefix"):
                    aligned.append((i, m.group("prefix"), m.group("suffix")))
                continue
            m = TYPEDECL_CLOSE_REGEX.match(line)
            if m is not None:
                in_type_scope = False
                if line != "};":
                    aligned.append((i, m.group("prefix"), m.group("suffix")))
                continue
            if in_type_scope:
                m = re.match(
                    r"^(?P<prefix>\s+{type})\s+"
                    r"(?P<suffix>\**{decl};)$".format(
                        type=helper.REGEX_TYPE, decl=helper.REGEX_DECL_NAME
                    ),
                    line,
                )
                if m is not None:
                    aligned.append((i, m.group("prefix"), m.group("suffix")))

    # Minimum alignment required for each line
    min_alignment = max(
        (len(prefix.expandtabs(4)) // 4 + 1 for _, prefix, _ in aligned), default=1
    )
    for i, prefix, suffix in aligned:
        alignment = len(prefix.expandtabs(4)) // 4
        lines[i] = prefix + "\t" * (min_alignment - alignment) + suffix
        if scope == "local":
            lines[i] = (
                "\t" + lines[i]
            )  # Adding one more indent for inside the type declaration
    return "\n".join(lines)

@helper.locally_scoped
def align_local(content: str) -> str:
    """Wrapper for align_scope to use local_scope decorator"""
    return align_scope(content, scope="local")

def align(content: str) -> str:
    """Align the content in global and local scopes"""
    content = align_scope(content, scope="global")
    content = align_local(content)
    return content


import Terminal_assets as assets
import Bank

while (True):
    opc = assets.Menu.openMainMenu()

    if opc == 0:
        assets.showExitMsg()
        break

    elif opc == 1:
        values = assets.Menu.openRegisterElderlyMenu()
        Bank.Elderly.insert(name=values['name'], cpf=values['cpf'], birth=values['birth'])

    elif opc == 2:
        assets.Menu.openListerElderly(Bank.Elderly.list())


import re
import traceback
from random import choices
from string import ascii_lowercase, digits
from subprocess import PIPE, STDOUT, run
from sys import byteorder
from xml.dom import ValidationErr

import base58
import near_api
from django.forms import ValidationError
from numpy import uint8

from lastwill.consts import (CONTRACT_PRICE_USDT, NET_DECIMALS, VERIFICATION_PRICE_USDT, WHITELABEL_PRICE_USDT)
from lastwill.contracts.submodels.common import *
from lastwill.contracts.submodels.ico import AbstractContractDetailsToken
"""
ИНТЕГРАЦИЯ NEAR БЛОКЧЕЙНА

Как выглядит флоу:
 - create contract class
 - contract calls details
 - new_account()
 - deploy() (with compile() inside)
 - initialized() (with burn_keys() and check_contract() to be 100% sure)
"""

def init_account(network: str, account_id: str, private_key: str):
    """
    init_account - функция инициализации аккаунта в near-api-py
    (получает информацию о существующем аккаунте и импортирует его в соответствующий класс)

    Returns:
        near_api.account.Account : класс аккаунта из модуля
    """
    provider = near_api.providers.JsonProvider(network)
    signer = near_api.signer.Signer(account_id, near_api.signer.KeyPair(private_key))
    near_account = near_api.account.Account(provider, signer, account_id)
    return near_account

def generate_account_name():
    """
    generate_account_name - функция для генерации имени аккаунта.
    Дополнительно проводится проверка по регулярке с официального сайта
    Генерируется имя длиной 64 символа со строкой 'mywish' в начале

    Returns:
        str: строка с именем аккаунта
    """
    # регулярка для валидации имени аккаунта
    # https://docs.near.org/docs/concepts/account#account-id-rules
    ACCOUNT_NAME_REGEX = '^(([a-z\d]+[\-_])*[a-z\d]+\.)*([a-z\d]+[\-_])*[a-z\d]+$'
    regex = re.compile(ACCOUNT_NAME_REGEX)
    result = f"mywish{''.join(choices(ascii_lowercase+digits+'-_', k=58))}"
    while not regex.match(result):
        result = f"mywish{''.join(choices(ascii_lowercase+digits+'-_', k=58))}"
    return result

class NearContract(EthContract):
    pass

@contract_details('Near Token contract')
class ContractDetailsNearToken(CommonDetails):
    # адрес владельца контракта
    admin_address = models.CharField(max_length=64)
    # адрес аккаунта контракта
    deploy_address = models.CharField(max_length=64)
    token_name = models.CharField(max_length=512)
    token_short_name = models.CharField(max_length=64)
    decimals = models.IntegerField()
    maximum_supply = models.BigIntegerField()
    token_type = models.CharField(max_length=32, default='NEP-141')
    future_minting = models.BooleanField(default=True)
    near_contract = models.ForeignKey(NearContract, null=True, default=None, on_delete=models.SET_NULL)

    @classmethod
    def min_cost(cls):
        network = Network.objects.get(name='NEAR_MAINNET')
        cost = cls.calc_cost({}, network)
        return cost

    @staticmethod
    def calc_cost(kwargs, network):
        if NETWORKS[network.name]['is_free']:
            return 0
        price = CONTRACT_PRICE_USDT['NEAR_TOKEN']
        if 'verification' in kwargs and kwargs['verification']:
            price += VERIFICATION_PRICE_USDT
        if 'white_label' in kwargs and kwargs['white_label']:
            price += WHITELABEL_PRICE_USDT
        return price * NET_DECIMALS['USDT']

    @postponable
    @blocking
    def new_account(self, NEAR_NETWORK_TYPE: str):
        """
        new_account - создает implicit аккаунт для пользователя,
        на который будет задеплоен контракт

        создание аккаунта будет проводиться через near-cli
        https://docs.near.org/docs/roles/integrator/implicit-accounts

        ключи аккаунта хранятся в ~/.near-credentials/{network-type}/{self.admin_address}.json
        """
        try:
            account_name = generate_account_name()
            public_key = run(['near', 'generate-key', f'{account_name}'], stdout=PIPE, stderr=STDOUT, check=True)
            print(f'Public key: {public_key}', flush=True)
        except Exception:
            print('Error generating key for Near Account', flush=True)
            traceback.print_exc()
        else:
            try:
                public_key = public_key.stdout.decode('utf-8').split()[4].split(':')[1]
            except IndexError:
                # срабатывает когда ключ уже сгенерирован
                public_key = public_key.stdout.decode('utf-8').split()[3].split(':')[1]
        implicit_account_name = base58.b58decode(public_key).hex()
        try:
            run(f'mv ~/.near-credentials/{NEAR_NETWORK_TYPE}/{account_name}.json ~/.near-credentials/{NEAR_NETWORK_TYPE}/{implicit_account_name}.json',
                stdout=PIPE,
                stderr=STDOUT,
                check=True,
                shell=True)
        except Exception:
            print('Error moving keys to Near Account')
            traceback.print_exc()
        print(f'Near user address {implicit_account_name}', flush=True)
        self.deploy_address = implicit_account_name
        self.save()

    def compile(self):
        dest = path.join(CONTRACTS_DIR, 'lastwill/near-contract/')
        if not 'MAINNET' in self.contract.network.name:
            with open(path.join(dest, 'near.token.wasm'), 'rb') as f:
                # код контракта представляет из себя побайтовый массив uint8
                bytecode = []
                while True:
                    char = f.read(1)
                    if not char:
                        break
                    bytecode.append(uint8(int.from_bytes(char, byteorder)))
        else:
            # заглушка для контракта в мейннете,
            # т.к. нынешний контракт отмечен "только для тестнета"
            bytecode = []
        near_contract = NearContract()
        near_contract.bytecode = bytecode
        near_contract.contract = self.contract
        near_contract.original_contract = self.contract
        near_contract.save()
        self.near_contract = near_contract
        self.save()

    @blocking
    @postponable
    def deploy(self):
        """
        deploy - функция создания аккаунта и деплоя контракта

        для создания аккаунта нужен трансфер на 182 * 10**19 монет
        для создания, деплоя и инициализации нужно 222281 * 10 ** 19 монет
        для удаления ключей нужно 40601225 * 10**12 ~ 5 * 10**19 монет
        буду отправлять 24 * 10**23, чтобы гарантированно хватило

        Raises:
            Exception:
                - если не получилось создать аккаунт с помощью transfer()
                - если завалится парсинг ключа из json файла
                - если завалится деплой контракта на аккаунт
        """
        if self.contract.state not in ('CREATED', 'WAITING_FOR_DEPLOYMENT'):
            print('launch message ignored because already deployed', flush=True)
            take_off_blocking(self.contract.network.name)
            return

        if not 'MAINNET' in self.contract.network.name:
            NEAR_NETWORK_TYPE = 'testnet'
            NEAR_NETWORK_URL = NETWORKS[self.contract.network.name]['node_url']
            NEAR_ADDRESS = NETWORKS[self.contract.network.name]['address']
        else:
            NEAR_NETWORK_TYPE = 'mainnet'
            NEAR_NETWORK_URL = NETWORKS[self.contract.network.name]['node_url']
            NEAR_ADDRESS = NETWORKS[self.contract.network.name]['address']

        try:
            private_key = run(f'cat ~/.near-credentials/{NEAR_NETWORK_TYPE}/{NEAR_ADDRESS}.json',
                              stdout=PIPE,
                              stderr=STDOUT,
                              check=True,
                              shell=True)
        except Exception:
            print(f'Error getting private key from Near Account json {NEAR_ADDRESS}')
            traceback.print_exc()
        else:
            private_key = private_key.stdout.decode('utf-8').split('"')[11].split(':')[1]
            if len(private_key) != 88:
                raise Exception(f"Wrong private key provided for account {NEAR_ADDRESS}")

        mywish_account = init_account(NEAR_NETWORK_URL, NEAR_ADDRESS, private_key)

        # sending await transfer to new user account
        self.new_account(NEAR_NETWORK_TYPE)
        try:
            tx_account_hash = mywish_account.send_money(self.deploy_address, 24 * 10**23)
            print(f'account creation:\n{tx_account_hash}\n', flush=True)
        except Exception:
            traceback.print_exc()

        try:
            private_key = run(f'cat ~/.near-credentials/{NEAR_NETWORK_TYPE}/{self.deploy_address}.json',
                              stdout=PIPE,
                              stderr=STDOUT,
                              check=True,
                              shell=True)
        except Exception:
            print(f'Error getting private key from Near Account json {self.deploy_address}')
            traceback.print_exc()
        else:
            private_key = private_key.stdout.decode('utf-8').split('"')[11].split(':')[1]
            if len(private_key) != 88:
                raise Exception(f"Wrong private key provided for account {self.deploy_address}")
        near_account = init_account(NEAR_NETWORK_URL, self.deploy_address, private_key)

        self.compile()
        args = {
            "owner_id": self.admin_address,
            "total_supply": str(self.maximum_supply),
            "metadata": {
                "spec": "ft-1.0.0",
                "name": self.token_name,
                "symbol": self.token_short_name,
                "decimals": self.decimals
            }
        }
        print(args, flush=True)

        try:
            tx_deploy_hash = near_account.deploy_and_init_contract(contract_code=self.near_contract.bytecode,
                                                                   args=args,
                                                                   gas=near_api.account.DEFAULT_ATTACHED_GAS,
                                                                   init_method_name="new")
        except Exception:
            traceback.print_exc()
        else:
            tx_deploy_hash = tx_deploy_hash['transaction_outcome']['id']
        print(f'tx_hash: {tx_deploy_hash}', flush=True)
        self.near_contract.tx_hash = tx_deploy_hash
        self.near_contract.save()
        self.contract.state = 'WAITING_ACTIVATION'
        self.contract.save()

    def burn_keys(self, NEAR_NETWORK_TYPE: str, NEAR_NETWORK_URL: str):
        """
        burn_keys - функция для сжигания ключей после деплоя контракта

        Raises:
            ValidationError: завалился парсинг ключа из json файла
            ValidationError: не получилось сжечь ключи
        """
        try:
            keys = run(f'cat ~/.near-credentials/{NEAR_NETWORK_TYPE}/{self.deploy_address}.json',
                       stdout=PIPE,
                       stderr=STDOUT,
                       check=True,
                       shell=True)
        except Exception:
            print('Error getting keys from Near Account json')
            traceback.print_exc()
        else:
            private_key = keys.stdout.decode('utf-8').split('"')[11].split(':')[1]
            public_key = keys.stdout.decode('utf-8').split('"')[7].split(':')[1]
            if len(private_key) != 88:
                raise ValidationError(f"Wrong private key provided for account {self.deploy_address}")
            if len(public_key) != 44:
                raise ValidationError(f"Wrong public key provided for account {self.deploy_address}")

        near_account = init_account(NEAR_NETWORK_URL, self.deploy_address, private_key)

        try:
            near_account.delete_access_key(public_key=near_account.signer.public_key)
        except Exception:
            traceback.print_exc()

    def check_contract(self, NEAR_NETWORK_TYPE: str, NEAR_NETWORK_URL: str):
        """
        check_contract - функция проверки валидность контракта
        и успешность транзакции сжигания ключей

        Raises:
            ValidationError: получен неверный ключ
            ValidationError: контракт не совпадает
            ValidationError: ключи не сожглись
        """
        try:
            keys = run(f'cat ~/.near-credentials/{NEAR_NETWORK_TYPE}/{self.deploy_address}.json',
                       stdout=PIPE,
                       stderr=STDOUT,
                       check=True,
                       shell=True)
        except Exception:
            print('Error getting keys from Near Account json')
            traceback.print_exc()
        else:
            private_key = keys.stdout.decode('utf-8').split('"')[11].split(':')[1]
            if len(private_key) != 88:
                raise ValidationError(f"Wrong private key provided for account {self.deploy_address}")

        near_account = init_account(NEAR_NETWORK_URL, self.deploy_address, private_key)

        try:
            result = near_account.function_call(contract_id=self.deploy_address,
                                                method_name='ft_metadata',
                                                args={},
                                                gas=near_api.account.DEFAULT_ATTACHED_GAS)
        except Exception:
            print(f'Error function call ft_metadata() for {near_account.account_id}')
            traceback.print_exc()
        else:
            if not (result['name'] == self.token_name and result['symbol'] == self.token_short_name and
                    result['decimals'] == self.decimals):
                raise ValidationError(f"Contract metadata is corrupted on account {self.deploy_address}")

        print(f'Contract {self.deploy_address} checked successfully', flush=True)

    @postponable
    @blocking
    def initialized(self):
        """
        initialized - финальная функция,
        которая сжигает ключи и
        проверяет, что контракт был успешно задеплоен

        затем отправляет сообщение пользователю и боту
        об успешности операции
        """
        if self.contract.state not in ('WAITING_ACTIVATION'):
            take_off_blocking(self.contract.network.name)
            return

        if not 'MAINNET' in self.contract.network.name:
            NEAR_NETWORK_TYPE = 'testnet'
            NEAR_NETWORK_URL = NETWORKS[self.contract.network.name]['node_url']
        else:
            NEAR_NETWORK_TYPE = 'mainnet'
            NEAR_NETWORK_URL = NETWORKS[self.contract.network.name]['node_url']

        self.burn_keys(NEAR_NETWORK_TYPE, NEAR_NETWORK_URL)
        self.check_contract(NEAR_NETWORK_TYPE, NEAR_NETWORK_URL)

        self.contract.state = 'ACTIVE' if self.future_minting else 'DONE'
        self.contract.deployed_at = datetime.datetime.now()
        self.contract.save()
        if self.contract.user.email:
            send_mail(common_subject, near_token_text.format(addr=self.deploy_address, network=NEAR_NETWORK_TYPE),
                      DEFAULT_FROM_EMAIL, [self.contract.user.email])
            if not 'MAINNET' in self.contract.network.name:
                send_testnet_gift_emails.delay(self.contract.user.profile.id)
            else:
                send_promo_mainnet.delay(self.contract.user.email)

        msg = self.bot_message
        transaction.on_commit(lambda: send_message_to_subs.delay(msg, True))

    @postponable
    def msg_deployed(self, message):
        # deprecated
        return


"""Update all "de.po" dictionaries from the JSON file.

Use this script only for global changes of existing descriptions.

Copyright (c) 2023 Peter Triesberger
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
import os
from translations import Translations

START_DIR = os.getcwd()
ROOT = '../../'

with os.scandir(ROOT) as prjPaths:
    for prjPath in prjPaths:
        if os.path.isdir(prjPath):
            poFile = f'{prjPath.path}/i18n/de.po'
            if os.path.isfile(poFile):
                print(poFile)
                os.chdir(f'{prjPath.path}/i18n')
                translations = Translations('de')
                translations.read_pot()
                translations.read_po()
                translations.read_json()
                translations.write_po()
os.chdir(START_DIR)


import click
import pandas as pd
import numpy as np
import urllib
import json
import os
import things

@click.group("import_project")
def import_project():
    pass

@import_project.command('import_asana')
@click.argument('path_to_csv', type=click.Path(exists=True))
@click.option('--name', type=str, default=None)
def import_asana(path_to_csv: str, name: str = None):
    name = name if name is not None else path_to_csv.strip(".csv")

    # check if project exists
    for project in things.projects():
        if project["title"] == name:
            print(f'Project {name} already exists. Delete it first —-- this function will overwrite existing projects.')
            # return

    print(f'Importing project {name} from {path_to_csv}...')
    project = pd.read_csv(path_to_csv)
    project["completion-date"] = pd.to_datetime(project["Completed At"]).dt.strftime('%Y-%m-%dT%H:%M:%SZ')
    items = []
    headings = {}
    for i, reminder in project.iterrows():
        attributes = {
            "title": reminder["Name"],
            "completed": not pd.isna(reminder["Completed At"])
        }
        if not pd.isna(reminder["Completed At"]):
            attributes["completion-date"] = reminder["completion-date"]
        if not pd.isna(reminder["Notes"]):
            attributes["notes"] = reminder["Notes"]
        if not pd.isna(reminder["Due Date"]):
            attributes["when"] = reminder["Due Date"]
            attributes["deadline"] = reminder["Due Date"]
        if not (reminder["Section/Column"] == "(no section)" or pd.isna(reminder["Section/Column"])):
            attributes["heading"] = reminder["Section/Column"]
            if reminder["Section/Column"] not in headings.keys():
                headings[reminder["Section/Column"]] = {
                    "type": "heading",
                    "attributes": {
                        "title": reminder["Section/Column"]
                    }
                }
        items.append({
            "type": "to-do",
            "attributes": attributes
        })

    print(headings)
    print(items[-1])

    # test post
    post_to_things([
        {
            "type": "project",
            "attributes": {
                "title": name,
                "items": list(headings.values()) + items
            }
        }
    ])

def post_to_things(data):
    url = "things:///json?data="
    token = json.load(open('token.json'))['token']
    print(json.dumps(data))
    uri = url + urllib.parse.quote(json.dumps(data))
    os.system(f"open {uri}")

if __name__ == "__main__":
    import_project()


# -*- coding: utf-8 -*-
from sympy import isprime, prime, factorial

def euclid(a, b):
    """ Euclidean Algorithm."""
    a, b = b, a%b
    return a if not b else euclid(a, b)

def lcm(a, b):
    """ Least common multiple."""
    return (a * b) / (euclid(a, b))

def inverse(a, b, both = False):
    """ Multiplicative inverse of 'a' in mod 'b'.
        both = True gives the coefficients 'A' and 'B' of
        the equation A*x + B*y = gcd(x,y)"""
    x = [1, 0]
    y = [0, 1]
    q = a / b
    a, b = b, a % a
    while r[1]:
        x[0], x[1] = x[1], x[0] - q * x[1]
        y[0], y[1] = y[1], y[0] - q * y[1]
        q = a / b
        a, b = b, a % a
    if both:
        return (x[-1], y[-1])
    else:
        return x[-1] % b if a == 1 else None

def primefact(number):
    """ Prime factorization of 'number'.
        Returns a list of 2-tuples in which the first
        element is the prime factor and the second is the
        number of times that prime appears.  For example,
        [(2,1), (5,3)] corresponds to  2^1 * 5^3 = 250
        ( 2**1 * 5**3 in Python syntax )."""

    if isprime(number) or number == 1:
        return [(number, 1)]
    else:
        factors = []
        counts = []
        for primenum in (prime(n) for n in xrange(1, number)):
            if number == 1:
                break
            if not number % primenum:
                factors.append(primenum)
                counts.append(1)
                number = number // primenum
                while not (number % primenum):
                    counts[-1] += 1
                    number = number // primenum
        return zip(factors, counts)

def encrypt_general(message, encrypter, modulo = 26):
    return

def encrypt(message, a, b):
    """ Encrypts a message with formula y = a * x + b.
        Input may be either a string message or a list of indices 0-25."""
    alpha = [chr(char) for char in range(ord('a'), ord('z'))]
    if isinstance(message, str):
        offset = 65 if ord(message[0]) <=90 else 97
        encrypted = [(a * (ord(char) - offset) + b) % 26 for char in message]
    else:
        encrypted = [(a * char + b) % 26 for char in message]
    return "".join([chr(char + 65) for char in encrypted]), encrypted

def decrypt(message, a, b):
    """ Decrypts a message encrypted with formula y = a * x + b.
        Input may be either a string message or a list of indices 0-25."""

    if isinstance(message, str):
        offset = 65 if ord(message[0]) <=90 else 97
        message = [(ord(char) - offset) % 26 for char in message]
    a = inverse(a, 26)
    b = 26 - b
    decrypted = [(a * (char + b)) % 26 for char in message]
    return "".join([chr(char+65) for char in decrypted]), decrypted

def cartesian(*sets):
    """ Returns the cartesian product of the argument sets.  This can get very big."""
    def product(s1, s2):
        return set([(el1, el2) for el1 in s1 for el2 in s2])
    def merge(s1, s2):
        return set(tuple(list(el1) + [el2]) for el1 in s1 for el2 in s2)
    master = product(sets[0], sets[1])
    for s in sets[2:]:
        master = merge(master, s)
    return master

def powerset(s):
    """ Returns the powerset of a set.  Subsets will be instances of
        the 'frozenset' type.

        May also call as 'pset(s)'.

        This is the optimal option as it is far faster than the others
        for larger sets and correctly computes powersets of powersets.
        (ie: it handles sets containing sets correctly.)

        NOTE:  This will hog up your RAM if you use it to compute
               the power set of the power set of a set larger than 4 elements.
               I used all 32 gigs of ram trying pset(pset({1,2,3,4,5})).
               Thats 4294967296 elements, and each element eats up a lot of
               memory!

        This implementation is recursive."""
    def iterate(s, newSet = None):
        if newSet is None:
            newSet = set()
            s = {item for item in s}
        thisItem = frozenset([s.pop()])
        newSet.add(thisItem)
        for item in set(newSet):
            newSet.add(frozenset.union(thisItem, item))
        if s:
            return iterate(s, newSet)
        else:
            newSet.add(frozenset())
            return newSet

    return iterate(s)
pset = powerset

def subsets(s, cardinality):
    """ Returns a set of subsets with the specified cardinality.
        The subsets will be selected from input set 's'.

        Implemented poorly at the moment, but it works."""
    return {item for item in pset(s) if (len(item) == cardinality )}

def totient(num):
    """ Returns the totient of num."""
    if isprime(num):
        return num - 1
    else:
        return sum((1 for n in xrange(1, num) if euclid(num, n) == 1))

def powerset_old(s):
    """ Returns the powerset of a set.  Subsets will be instances of
        the 'frozenset' type. Broken for sets containing sets. ¯\_(ツ)_/¯"""
    sets = set([frozenset([item]) for item in s])
    lengthstart = 0
    while len(sets) != lengthstart:
        lengthstart = len(sets)
        sets = set.union(sets, set([frozenset.union(s1, s2)
                                    for s1 in sets for s2 in sets]))
    return set([frozenset(subset) for subset in sets] + [frozenset()])

def powerset_alt(s):
    """ Much slower way of getting the powerset."""
    tuples = cartesian(*[s for _ in range(len(s))])
    return set([frozenset(item) for item in tuples] + [frozenset()])

def breakRSA(e, n, message = None):
    """ Breaks a 'nice' RSA encryption with public key '(e, n)'."""
    (p, _), (q, _)  = primefact(n)
    tot = (p - 1) * (q - 1)
    d = inverse(e, tot, both = False)
    if message:
        return [num ** d % n for num in message]
    else:
        return d

def permute(n, r):
    """ Permutations of 'r' subitems in a set of 'n' items.
        May also call as 'permutations(n, r)'"""
    return factorial(n)/factorial(n - r)
permutations = permute

def choose(n, r):
    """ Combinations of 'r' subitems in a set of 'n' items.
        May also call as 'combinations(n, r)'"""
    return permute(n, r) / factorial(r)
combinations = choose

def recursive_choose(n, r):
    """ Recursive implementation of choose.  For fun."""
    if n == r:
        return 1
    elif r == 1 or n - r == 1:
        return n
    else:
        return choose_recursive(n-1, r) + choose_recursive(n-1, r - 1)

def binom(num, xcoeff = 1, ycoeff = 1):
    """ Coefficients of the resultant expansion of (xcoeff * x + ycoeff * y)^(num)."""
    return [choose(num, n) * xcoeff ** (num - n) * ycoeff**n for n in range(num+1)]

def pascal(row, index = None, allRows = False):
    """ Returns the requested row of pascals triangle.
        index:      Returns only the item at position 'index' within the row.
        allRows:    Call with 'allRows = True' to show every row up to and including
                    the requested row.  Priority given to 'index' over 'allRows'. """

    if index is not None:
        return choose(row, index)
    elif allRows:
        return [choose(row, n) for n in range(row+1)]
    else:
        return binom(row)

def pigeon(bins, pigeons):
    """ Pigeon hole principle with 'n' boxes needing
        'pigeons' items to fill them.  Gives the 'smallest maximum'
        that a bin/box must hold no matter how the 'pigeons' are arranged."""
    return pigeons // bins + bool(pigeons % bins)

def ballbins(balls, bins, withholding= False, minimum = 0):
    """ Returns the number of possible ways to arrange a given number of 'balls'
        into a given number of 'bins'.

        withholding: set this to true if some number of balls may be withheld
                     from the bins.
        minimum:     the minimum number of balls that must be contained within
                     each bin."""
    if withholding:
        if balls > bins:
            return sum([choose(bins + n - 1 - minimum * bins, balls - minimum * bins)
                        for n in range(balls+1)])
        else:
            return sum([choose(bins + n - 1, bins - 1)
                        for n in range(balls+1)])
    else:
        if balls > bins:
            return choose(bins + balls - 1 - minimum * bins, balls - minimum * bins)
        else:
            return choose(bins + balls - 1, bins - 1 )

def organize(seq):
    f = factorial(sum(seq))
    return f/(reduce(lambda x, y: x * y, [factorial(n) for n in seq]))

if __name__ == "__main__":
    pass


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

import argparse
import os
import time
import json
import random

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

def parse_args():
    p = argparse.ArgumentParser(description="deepracer submit")
    p.add_argument("-t", "--target", default="", help="target", required=True)
    p.add_argument("-m", "--model", default="", help="model")
    p.add_argument("-d", "--debug", default="False", help="debug")
    return p.parse_args()

def open_browser(args):
    if args.debug == "True":
        return None

    options = Options()
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")
    # options.add_argument("--no-sandbox")
    # options.add_argument("--single-process")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument(
        "user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
    )

    browser = webdriver.Chrome(options=options)

    # browser = webdriver.Chrome("/usr/local/bin/chromedriver")

    browser.set_window_size(1600, 1700)

    return browser

def close_browser(browser, args):
    if args.debug == "True":
        return

    try:
        browser.close()
    except Exception as ex:
        print("Error", ex)

def login_aws(doc, args, browser):
    print("+ login_aws", doc["username"])

    url = "https://{}.signin.aws.amazon.com/console".format(doc["userno"])

    if args.debug == "True":
        print("url: ", url)
        return

    # screenshot = "config/login-{}.png".format(doc["userno"])
    # screenshot = "{}/config/login-{}.png".format(os.path.dirname(os.path.realpath(__file__)), doc["userno"])

    browser.get(url)

    time.sleep(5)

    # browser.save_screenshot(screenshot)

    browser.find_element(By.ID, "username").send_keys(doc["username"])
    browser.find_element(By.ID, "password").send_keys(doc["password"])

    browser.find_element(By.ID, "signin_button").click()

    time.sleep(5)

    # browser.save_screenshot(screenshot)

def submit_model(doc, args, browser):
    print("+ submit_model", args.target)

    arn = ""
    model = ""

    for attrs in doc["races"]:
        if attrs["name"] == args.target:
            arn = attrs["arn"]
            models = attrs["models"]

            if args.model != "":
                model = args.model
            elif len(models) > 0:
                model = random.choice(models)

            break

    if arn == "":
        print("Not found arn.")
        return

    if model == "":
        print("Empty model.")
        return

    # #league/arn%3Aaws%3Adeepracer%3A%3A%3Aleaderboard%2F9f6ca6de-ecfa-467a-a7d9-c899a811a206/submitModel
    # #league/arn%3Aaws%3Adeepracer%3A%3A%3Aleaderboard%2F55234c74-2c48-466d-9e66-242ddf05e04d/submitModel
    # #competition/arn%3Aaws%3Adeepracer%3A%3A082867736673%3Aleaderboard%2Fe9fbfc93-ed99-494c-8b61-ac13a2274859/submitModel

    url = "https://console.aws.amazon.com/deepracer/home?region=us-east-1#{}/submitModel".format(
        arn
    )

    # screenshot = "config/submit-{}.png".format(args.target)
    screenshot = "{}/config/submit-{}.png".format(
        os.path.dirname(os.path.realpath(__file__)), args.target
    )

    if args.debug == "True":
        print("arn: ", arn)
        print("model: ", model)
        print("url: ", url)
        return

    try:
        browser.get(url)

        time.sleep(5)

        try:
            browser.find_element(By.XPATH, "//body").click()

            # # PLCHLDR__new_car_reward_modal
            # browser.find_element(
            #     By.XPATH, '//div[@id="PLCHLDR__new_car_reward_modal"]'
            # ).click()

            # # awsui_dismiss-control_1d2i7_1qdlw_312 awsui_button_vjswe_1asap_101 awsui_variant-modal-dismiss_vjswe_1asap_162
            # browser.find_element(
            #     By.CSS_SELECTOR, "button[class*='awsui_variant-modal']"
            # ).click()
        except Exception as ex:
            print("Error", ex)
            browser.save_screenshot(screenshot)
            post_slack(doc, "{} : {}".format(args.target, ex), screenshot)

        time.sleep(3)

        # awsui_button-trigger_18eso_5wauj_97 awsui_has-caret_18eso_5wauj_135
        browser.find_element(
            By.CSS_SELECTOR, "button[class^='awsui_button-trigger']"
        ).click()

        path = '//*[@title="{}"]'.format(model)
        browser.find_element(By.XPATH, path).click()

        # awsui_button_vjswe_1asap_101 awsui_variant-primary_vjswe_1asap_206
        browser.find_element(
            By.CSS_SELECTOR, "button[class*='awsui_variant-primary']"
        ).click()

        time.sleep(10)

        browser.save_screenshot(screenshot)
        post_slack(doc, "{} : {}".format(args.target, model), screenshot)
    except Exception as ex:
        print("Error", ex)
        browser.save_screenshot(screenshot)
        post_slack(doc, "{} : {}".format(args.target, ex), screenshot)

def post_slack(doc, text, screenshot=""):
    if doc["slack"]["token"] == "":
        return

    token = doc["slack"]["token"]
    channel = doc["slack"]["channel"]

    print("+ post_slack", channel)

    # filepath = "{}/{}".format(os.path.dirname(os.path.realpath(__file__)), screenshot)

    client = WebClient(token)

    try:
        if screenshot == "":
            client.chat_postMessage(channel=channel, text=text)
        else:
            client.files_upload(channels=channel, file=screenshot, text=text)
    except SlackApiError as e:
        print("Error", e.response["error"])

def main():
    args = parse_args()

    if args.target == "":
        print("Empty target.")
        return

    filepath = "{}/config/deepracer.json".format(
        os.path.dirname(os.path.realpath(__file__))
    )

    if os.path.exists(filepath):
        if args.debug == "True":
            print("filepath : {}".format(filepath))

        doc = None

        with open(filepath, "r") as file:
            doc = json.load(file)

            if doc["userno"] == "":
                print("Empty userno.")
                return

            browser = open_browser(args)

            login_aws(doc, args, browser)

            submit_model(doc, args, browser)

            close_browser(browser, args)

if __name__ == "__main__":
    main()


from ctypes import *

import array
import itertools

libseastar = CDLL("./seastar/libseastar.so")
libseastar.init_astar.argtypes = [c_long, c_long]
libseastar.astar.argtypes = [POINTER(c_long), c_long, POINTER(c_long), c_long,
    POINTER(c_long), c_long, c_long]
libseastar.astar.restype = POINTER(c_long)
libseastar.reset_obstacles.argtype = [POINTER(c_long), c_long, c_long]
libseastar.reset_obstacles.restype = c_void_p
libseastar.set_layer_distance.argtype = [c_long, c_long]
libseastar.set_layer_distance.restype = c_void_p
libseastar.reset_layer_distance.argtype = [c_long]
libseastar.reset_layer_distance.restype = c_void_p

def xytuples_to_clist(lst):
    """
    Given a list of tuples, this function converts it to the flat c_type
    int array used by the c based astar
    """
    clength = len(lst) * 2
    cltype = c_long * clength
    outlst = []
    for (x,y) in lst:
        outlst.append(x)
        outlst.append(y)
    return cltype(*outlst)

def clist_to_xytuples(lst, length=None):
    """
    Given a flat c_type int array of points, convert it to a list of tuples
    with the method based on if you know how long the array is.
    """
    if length != None:
        # Apply the length to the clist, which may or may not already have a
        # size:
        resize(lst,length * sizeof(c_long))
        lstpy = itertools.imap(int, lst)
    else:
        # We don't know what the length of the list is. We have to expand
        # The list and then search through the memory, wee!
        lstpy = itertools.takewhile(lambda x: x != -1, itertools.imap(lambda y: int(lst[y]), itertools.count()))
    return itertools.izip(lstpy,lstpy)

class Seastar(object):
    """
    Python code to interface with my C based A*
    """
    def __init__(self, map_width, map_height):
        """
        Calls the libseastar's init astar function that prepares the adjacency
        table. You can call it a bunch of times, but it just wastes CPU.

        Also initializes the blocking and obstacles to some default settings.
        """
        libseastar.init_astar(c_long(map_width), c_long(map_height))
        self.map_width = map_width
        self.map_height = map_height

        # Init: no obstacles
        self.obstacles = array.array('l',[ 0 for _ in range(map_width * map_height) ])

        # Init: Everything blocks a path.
        self.set_blocking(0xffffffff) # Block on any obstacle

    def xy(self,x,y):
        return  y * self.map_width + x

    def set_blocking(self,blk):
        """
        Changes the blocking mask that will be used in the next pathing.
        """
        self.blocking = blk
        self.c_blocking = c_long(blk)

    def reset_obstacles(self,layer=0xffffffff):
        """
        Given a layer mask, remove all the obstacles from that layer.
        """
        addr, count = self.obstacles.buffer_info()
        c_obstacles = cast(addr, POINTER(c_long))
        c_obstacles_c = c_long(count)
        c_layer = c_long(layer)
        libseastar.reset_obstacles(c_obstacles, c_obstacles_c, c_layer)

    def remove_obstacle(self, pt, layer):
        index = self.xy(pt)
        self.obstacles[index] &= ~layer

    def add_obstacle(self, pt, layer):
        index = self.xy(pt)
        self.obstacles[index] |= layer

    def add_obstacles(self, lst, layer):
        """
        Given a list of x,y tuples and a layer mask, add obstacles to those
        layers.
        """
        for (x,y) in lst:
            index = self.xy(x,y)
            self.obstacles[index] |= layer

    def load_obstacles(self, iterable):
        self.obstacles = array.array('l')
        self.obstacles.extend(iterable)

    def set_layer_distance(self, layer, distance):
        libseastar.set_layer_distance(c_long(layer), c_long(distance))

    def reset_layer_distance(layer):
        libseastar.reset_layer_distance(c_long(layer))

    def get_path(self, starts, ends):
        """
        Tries to find a path between one of the starts and ends. Returns the
        shortest path between one of the starts and one of the ends. Returns
        an empty list if no path is found. Otherwise, returns a list of x,y
        tuples which are the path.

        C function args:
        -list of start points
        -count of start points
        -list of end points
        -count of end pints
        -list of obstacles
        -count of obstacles
        -blocking mask.
        """
        for start in starts:
            if start in ends:
                return [start]
        c_starts = xytuples_to_clist(starts)
        c_starts_c = c_long(len(starts)*2)
        c_ends = xytuples_to_clist(ends)
        c_ends_c = c_long(len(ends)*2)
        addr, count = self.obstacles.buffer_info()
        c_obstacles = cast(addr, POINTER(c_long))
        c_obstacles_c = c_long(count)
        rslt = libseastar.astar(c_starts, c_starts_c, c_ends, c_ends_c,
            c_obstacles, c_obstacles_c, self.c_blocking)
        if not rslt:
            return []
        return clist_to_xytuples(rslt)


#!/usr/bin/python3
combsi =[]
for x in [1, 2, 3]:
    for y in [3, 1, 4]:
        if x != y:
            combsi.append((x, y))

print(combsi)
combs =[]
combs = [y for r in combsi for y in r]
print(combs)
i = len(combs) - 1
while i > 1:
    j = 0
    while j < i:
        print("\nIs {} > {}".format(combs[j], combs[j + 1]))
        if combs[j] > combs[j + 1]:
            print("Switch")
            temp = combs[j]
            combs[j] = combs[j + 1]
            combs[j + 1] = temp
        else:
            print("Don't Switch")

        j += 1

        for k in combs:
            print(k, end="")
        print()

    print("END OF ROUND")
    i -= 1

for k in combs:
    print(k, end=", ")

print()


from PIL import Image, ImageFont, ImageDraw
text = u
font = ImageFont.truetype("msyh.ttf",18)
lines = []
line =''
for word in text.split():
    print(word)
    if font.getsize(line+word)[0] >= 300:
        lines.append(line)
        line = u''
        line += word
        print('size=',font.getsize(line+word)[0])
    else:
        line = line + word
line_height = font.getsize(text)[1]
img_height = line_height*(len(lines)+1)
print('len=',len(lines))
print('lines=',lines)


# -*- coding: utf-8 -*-
"""
Created on Mon Sep  9 07:22:01 2019

@author: creddersen
"""

def first_non_repeating_letter(string):
        list = [i.lower() for i in string]
        for i in range(len(list)):
            if list.count(list[i]) == 1:
                return string[i]
            return ""


# python3
import random
def max_pairwise_product(A):
	n = len(A)
	index1 = 0
	for i in range(1,n):
		if A[i]>A[index1]:
			index1 = i

	if index1 == 0 :
		index2 = 1
	else:
		index2 = 0

	for i in range(0,n):
		if i!=index1 and A[i]>A[index2]:
			index2= i
	return A[index1]*A[index2]

def max_pairwise_product_naive(A):
	product = 0
	for i in range(len(A)):
		for j in range(i + 1, len(A)):
			product = max(product, A[i] * A[j])
	return product

def stress_test(N,M):

	while True:
		n = random.randint(2,N)
		print("n:",n)
		A = []
		for i in range(n):
			randm = random.randint(1,M)
			A.append(randm)
		print(A)

		result_1 = max_pairwise_product_naive(A)
		result_2 = max_pairwise_product(A)

		if result_1 == result_2:
			print("-ok-")
		else:
			print("Wrong answer:",result_1," ",result_2)
			return

if __name__ == '__main__':
	input_n = int(input())
	input_numbers = [int(x) for x in input().split()]
	print(max_pairwise_product(input_numbers))


import xbmc
import xbmcgui
import xbmcaddon
import json

##############################################################
#                                                            #
#                                                            #
#			from script.module.drmhelper                     #
#				ausieaddons                                  #
# 					by glennguy                              #
#                                                            #
##############################################################

def get_addon(wtyk="inputstream.rtmp"):
    """
    Check if inputstream is installed, attempt to install if not.
    Enable inpustream addon.
    """
    addon = None

    try:
        enabled_json = ('{"jsonrpc":"2.0","id":1,"method":'
                        '"Addons.GetAddonDetails","params":'
                        '{"addonid":"%s", '
                        '"properties": ["enabled"]}}'%wtyk)
        result = json.loads(xbmc.executeJSONRPC(enabled_json))
    except RuntimeError:
        return False

    if 'error' in result:  # not installed
        try:  # see if there's an installed repo that has it
            xbmc.executebuiltin('InstallAddon(%s)'%wtyk, True)
            addon = xbmcaddon.Addon('%s'%wtyk)
            return addon
        except RuntimeError:
            xbmcgui.Dialog().ok('%s not installed'%wtyk,
                                '%s not installed. This '
                                'addon now comes supplied with newer builds '
                                'of Kodi 18 for Windows/Mac/LibreELEC/OSMC, '%wtyk)
        return False

    else:  # installed but not enabled. let's enable it.
        if result['result']['addon'].get('enabled') is False:
            json_string = ('{"jsonrpc":"2.0","id":1,"method":'
                           '"Addons.SetAddonEnabled","params":'
                           '{"addonid":"%s",'
                           '"enabled":true}}'%wtyk)
            try:
                xbmc.executeJSONRPC(json_string)
            except RuntimeError:
                xbmcgui.Dialog().ok('Unable to enable %s'%wtyk,
                                    'Unable to enable %s, '
                                    'please try to enable manually '
                                    'and try again'%wtyk)
                return False
        addon = xbmcaddon.Addon('%s'%wtyk)

    return addon

def disable_addon(wtyk="inputstream.rtmp"):
	addon=None
	json_string = ('{"jsonrpc":"2.0","id":1,"method":'
				'"Addons.SetAddonEnabled","params":'
				'{"addonid":"%s",'
				'"enabled":false}}'%wtyk)
	try:
		xbmc.executeJSONRPC(json_string)
		#xbmcgui.Dialog().ok('Disabled','%s is disabled'%wtyk)
	except RuntimeError:
		xbmcgui.Dialog().ok('Unable to disable %s'%wtyk,
							'Unable to disable %s, '
							'please try to disable manually '
							'and try again'%wtyk)
		return False

	return addon


import random

from tqdm import tqdm
import lightning.pytorch as pl
from torch.utils.data import DataLoader

from mm import *
from mm.mmdataset import build_yolo_dataset, IterableSimpleNamespace
from mm.mmdataloader import build_dataloader, build_mm_dataloader
from mm.mmchecks import check_det_dataset

class ModelManager(object):
    """Model manager."""

    def __init__(self):
        self.model_list = {}
        self.trainer_list = {}

    def create_model(self, model_cls, model_weight_path=None):
        """Create an new pretrained model.

        Args:
            model_cls (str): Model class name.
            model_weight_path (str): Model weight path.

        Returns:
            int: model ID.
        """
        model = build_network(model_cls, model_weight_path=model_weight_path)
        trainer = pl.Trainer(log_every_n_steps=5, max_epochs=model.args['epochs'])
        model_id = self._generate_model_id()
        self.model_list[model_id] = model
        self.trainer_list[model_id] = trainer
        return model_id

    def _generate_model_id(self):
        """Generate a random model ID.

        Returns:
            int: Model ID.
        """
        model_id = random.randint(0, 2**32)
        while model_id in self.model_list:
            model_id = random.randint(0, 2**32)
        return model_id

    def train_model(self, model_id):
        """Train a model.

        Args:
            model_id (int): Model ID.

        Returns:
            bool: True if success, otherwise False.

        Raises:
            ValueError: If model_id is invalid.
        """
        if "yolo" in self.model_list[model_id].model_name:
            print("Start training model {}.".format(model_id))
            current_file = os.path.realpath(__file__)
            current_directory = os.path.dirname(current_file)
            config_file = os.path.join(current_directory, "mm/configs", "coco.yaml")
            gs = max(int(self.model_list[model_id].model.stride.max() if self.model_list[model_id] else 0), 32)
            model_cfg = self.model_list[model_id].model.args.copy()
            for k, v in model_cfg.items():
                if isinstance(v, str) and v.lower() == 'none':
                    model_cfg[k] = None
            model_cfg = IterableSimpleNamespace(**model_cfg)
            data_cfg = check_det_dataset(config_file)
            dataset = build_yolo_dataset(model_cfg, f"./cache/{self.model_list[model_id].model_type}/images",
                                        self.model_list[model_id].args['batch'], data_cfg,
                                        mode='train', rect=False, stride=gs)
            dataloader = build_dataloader(dataset, self.model_list[model_id].args['batch'],
                                        self.model_list[model_id].args['workers'],
                                        self.model_list[model_id].args['shuffle'])
            self.trainer_list[model_id].fit(self.model_list[model_id], dataloader)
        elif "fast" or "sdd" or "detr" in self.model_list[model_id].model_name:
            print("Start training model {}.".format(model_id))
            dataloader = build_mm_dataloader(self.model_list[model_id].model_size)
            self.model_list[model_id].train()
            self.trainer_list[model_id].fit(self.model_list[model_id], dataloader)

        return True

    def delete_model(self, model_id):
        """Delete a model.

        Args:
            model_id (int): Model ID.

        Returns:
            bool: True if success, otherwise False.

        Raises:
            ValueError: If model_id is invalid.
        """
        del self.model_list[model_id]
        del self.trainer_list[model_id]
        return True

    def deploy_model(self, model_id, device):
        """Deploy a model on a device.

        Args:
            model_id (int): Model ID.
            device (str): Device name.

        Returns:
            bool: True if success, otherwise False.

        Raises:
            ValueError: If model_id or device is invalid.
        """
        self.model_list[model_id].model.to(device)
        return True

    def inference(self, model_id, *args, **kargs):
        """Model inference.

        Args:
            model_id (int): Model ID.
            *args: Model input.
            **kargs: Model input.

        Returns:
            Model output.

        Raises:
            ValueError: If model_id is invalid.
        """
        image = args[0]
        model = self.model_list[model_id]
        if not isinstance(image, list): image = [image]
        return model.predict_step(image)

if __name__ == "__main__":
    import cv2
    mmclass = ModelManager()
    model_id = mmclass.create_model("ssd_s_detect")
    device = "cuda:0"
    flag = mmclass.deploy_model(model_id, device)
    if not flag:
        print("Deploy model failed.")

    image = cv2.imread("demo.jpg")
    results = mmclass.inference(model_id, image)

    flag = mmclass.train_model(model_id)
    assert flag, "Train model failed."

    device = "cuda:1"
    mmclass.deploy_model(model_id, device)
    image = cv2.imread("demo.jpg")
    results = mmclass.inference(model_id, image)

    # delete model and trainer
    flag = mmclass.delete_model(model_id)
    assert flag, "Delete model failed."


import pandas as pd

def intersection(lst1, lst2, total_num):
    lst3 = [value for value in lst1 if value in lst2]
    if (len(lst3) == 1):
        return 4
    elif (len(lst3) > 1):
        return 5
    elif (len(lst3) == 0):
        return 0

def user_profile_restaurant(cuisine_input, user_id):
    allRestaurants = pd.read_csv(r'E:\\1.Study Stuff\College\\4th year\GP\TravelRecommeder_Flask\Restaurants\Cairo_FInal_Clean_Updated.csv' ,encoding='latin-1')

    cuisine_types = {1: 'Mediterranean', 2: 'Egyptian', 3: 'Italian', 4:'Seafood', 5:'Middle Eastern',6:'European',
                 7:'American',8:'Vegetarian Friendly', 9:'Lebanese', 10:'Barbecue', 11:'Japanese',12:'Healthy',13:'Steakhouse',
                 14:'French', 15:'International'}

    preferred_cuisine_types = []
    user_input = ''
    total_num = len(cuisine_input)
    for i in cuisine_input:
        preferred_cuisine_types.append(cuisine_types[i])

    # while user_input != 0:
    #     user_input = int(input("Please choose numbers of your favorite cuisine_types (type '0' to exit): "))
    #     if user_input!=0:
    #         print(cuisine_types[user_input])
    #         preferred_cuisine_types.append(cuisine_types[user_input])
    #         total_num = total_num + 1

    # user_id = 1
    user_rating_df = []
    print(preferred_cuisine_types)
    for ind, row in allRestaurants.iterrows():

       if (pd.isna(row[7])):
            continue
       cuisine_types = row[7]
       row_cuisine_types = cuisine_types.split(",")

       interValue = intersection(row_cuisine_types, preferred_cuisine_types,total_num)
       if (interValue > 3):
           user_rating_df.append(
               {
                   'userID': user_id,
                   'restID': row[0],
                   'ratings': interValue,
                   'flag': 'F',
                   'city': row[2]

               }
           )

    print(pd.DataFrame(user_rating_df))
    pd.DataFrame(user_rating_df).to_csv('user_profiling_rest.csv', index = False, mode='a',header=False)
# user_profile()


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

import collections
import contextlib
import importlib
import inspect
import logging
import os
import pkgutil
import socket
import sys
from datetime import datetime

import aiohttp
import discord
import humanize
import psutil
from discord.ext import commands

from . import commands as inspector

from utils import db
from utils.scheduler import DatabaseScheduler
from utils.transformdict import CaseInsensitiveDict
from utils.time import duration_units

logger = logging.getLogger(__name__)
command_logger = logging.getLogger('commands')

# permission calculations for bot invitations
def _define_permissions(*perms):
    permissions = discord.Permissions.none()
    permissions.update(**dict.fromkeys(perms, True))
    return permissions

_PERMISSIONS = [
    'send_messages',
    'embed_links',
    'add_reactions',
    'attach_files',
    'use_external_emojis',
    'create_instant_invite',
    'manage_messages',
    'read_message_history',
]

# Let's make actual permissions out of that stuff.
_PERMISSIONS = _define_permissions(*_PERMISSIONS)
del _define_permissions

VersionInfo = collections.namedtuple('VersionInfo', 'major minor micro releaselevel serial')

class CodeInspector(commands.AutoShardedBot):
    __version__ = '1.0.0'
    version_info = VersionInfo(1, 0, 0, 'final', 0)

    def __init__(self, config: dict):
        super().__init__(
            command_prefix=commands.when_mentioned_or(*config['prefix']),
            description=config['description'],
            case_insensitive=True,
            fetch_offline_members=False,
        )

        self.app_info = None
        self.creator = None

        self.cogs = CaseInsensitiveDict()
        self.categories = collections.defaultdict(list)
        self.owners = config['owners']

        self.command_counter = collections.Counter()
        self.session = aiohttp.ClientSession(
            connector=aiohttp.TCPConnector(resolver=aiohttp.AsyncResolver(), family=socket.AF_INET),
            loop=self.loop
        )
        self.start_time = datetime.utcnow()
        self.pool = self.loop.run_until_complete(db.create_pool(config['pg_credentials']))
        self.process = psutil.Process(os.getpid())
        self.token = config['token']
        self.webhook_url = config['webhook_url']

        self.db_scheduler = DatabaseScheduler(self.pool, timefunc=datetime.utcnow)
        self.db_scheduler.add_callback(self._dispatch_from_scheduler)

        # add our error handler
        self.load_extension('core.error_handler')

        # load any extensions from the cogs directory
        for name in os.listdir('cogs'):
            if name.startswith('__'):
                continue

            self.load_extension(f'cogs.{name}')

    def _dispatch_from_scheduler(self, entry):
        self.dispatch(entry.event, entry)

    async def is_owner(self, user):
        if self.owners:
            return user.id in self.owners

        return await super().is_owner(user)

    def run(self):
        super().run(self.token, reconnect=True)

    async def ci_stats(self):
        await self.wait_until_ready()

        async with self.pool.acquire() as db:
            with self.process.oneshot():
                memory = self.process.memory_full_info()

                print(
                    '================ CI Stats ================\n'
                    '----------- System information -----------\n'
                    f'Running on {sys.platform} with Python {sys.version}.\n'
                    f'Using {humanize.naturalsize(memory.rss)} physical memory'
                    f' and {humanize.naturalsize(memory.vms)} virtual memory,'
                    f' of which {humanize.naturalsize(memory.uss)} unique to this process.\n'
                    f'PostgreSQL version: {".".join(map(str, db.get_server_version()[:3]))}\n'
                    '------------- Bot statistics -------------\n'
                    f'Version: {self.__version__}\n'
                    f'Online for: {self.uptime}\n'
                    f'Guilds: {len(self.guilds)}\n'
                    f'Users: {len(self.users)}\n'
                    f'Voice channels: {len(self.voice_clients)}\n'
                    f'Shards: {len(self.shards)}\n'
                    f'discord.py version: {discord.__version__}\n'
                    '=========================================='
                )

    async def logout(self):
        await self.session.close()
        self.db_scheduler.close()
        await super().logout()

    @staticmethod
    def search_extensions(name):
        spec = importlib.util.find_spec(name)
        if not spec:
            raise ModuleNotFoundError(f'No module called {name!r}')

        path = spec.submodule_search_locations
        if not path:
            return None

        return (name for info, name, is_pkg in pkgutil.iter_modules(path, spec.name + '.')
                if not is_pkg)

    def _add_extension(self, name):
        ext = importlib.import_module(name)
        if hasattr(ext, 'setup'):
            ext.setup(self)
            self.extensions[name] = ext
        else:
            for _, m in inspect.getmembers(ext):
                if inspect.isclass(m) and isinstance(m, inspector.MetaCog):
                    try:
                        m(self)
                    except Exception as e:
                        logger.error(e)

                    if name not in self.extensions:
                        self.extensions[name] = ext
                else:
                    continue

        if name not in self.extensions:
            del ext
            del sys.modules[name]
            raise discord.ClientException('extension does not have a setup function')

    def load_extension(self, name):
        modules = self.search_extensions(name)
        if not modules:
            return self._add_extension(name)

        for module in modules:
            try:
                self._add_extension(module)
            except discord.ClientException as e:
                if 'extension does not have a setup function' not in str(e):
                    raise

    def unload_extension(self, name):
        super().unload_extension(name)

        for module_name in self.extensions.keys():
            if name == module_name or module_name.startswith(name + '.'):
                self.remove_cog(module_name)
                del self.extensions[module_name]

    @contextlib.contextmanager
    def temp_listener(self, func, name=None):
        """Context manager for temporary listeners."""

        self.add_listener(func, name)
        try:
            yield
        finally:
            self.remove_listener(func)

    async def process_commands(self, message):
        ctx = await self.get_context(message, cls=inspector.Context)

        if ctx.command is None:
            return

        async with ctx.acquire():
            await self.invoke(ctx)

    async def on_ready(self):
        logger.info(f'\n================\nLogged in as:\n{self.user.name}\n{self.user.id}\n================\n')
        self.db_scheduler.run()

        if self.app_info is None:
            self.app_info = await self.application_info()

        if self.creator is None:
            self.creator = await self.get_user_info(self.app_info.owner.id)

        if not hasattr(self, 'start_time'):
            self.start_time = datetime.utcnow()

        await self.change_presence(
            activity=discord.Activity(name='your shitcode', type=discord.ActivityType.watching),
            status=discord.Status.dnd
        )

    async def on_message(self, message):
        if message.author.bot:
            return

        await self.process_commands(message)

    async def on_command(self, ctx):
        self.command_counter['total'] += 1
        if isinstance(ctx.channel, discord.abc.PrivateChannel):
            self.command_counter['in DMs'] += 1
        elif isinstance(ctx.channel, discord.abc.GuildChannel):
            self.command_counter[str(ctx.guild.id)] += 1

        # DM channels don't have a guild attribute
        if not ctx.guild:
            ctx.guild = 'DM channel'
            ctx.guild.id = 'no ID provided'

        fmt = ('Command executed in {0.channel} ({0.channel.id}) from {0.guild} ({0.guild.id})'
               ' by {0.author} ({0.author.id}) with content: {0.message.content}')
        command_logger.info(fmt.format(ctx))

    async def on_command_error(self, ctx, error):
        if not (
                isinstance(error, commands.CheckFailure)
                and not isinstance(error, commands.BotMissingPermissions)
                and await self.is_owner(ctx.author)
        ):
            return

        try:
            await ctx.release()
            async with ctx.acquire():
                await ctx.reinvoke()

        except Exception as e:
            await ctx.command.dispatch_error(ctx, e)

    @property
    def webhook(self):
        webhook_url = self.webhook_url
        if webhook_url:
            return discord.Webhook.from_url(webhook_url, adapter=discord.AsyncWebhookAdapter(self.session))

        return None

    @property
    def source(self):
        return 'https://github.com/itsVale/code-inspector'

    @property
    def uptime(self):
        return duration_units((datetime.utcnow() - self.start_time).total_seconds())

    @discord.utils.cached_property
    def invite_url(self):
        return discord.utils.oauth_url(self.user.id, _PERMISSIONS)


def power(a,b):
    if b==0:
        return 1
    if b==1:
        return a
    ans=power(a,int(b/2))
    if b%2==0:
        return ans*ans
    else:
        return a*ans*ans
if __name__=="__main__":
    a=int(input())
    b=int(input())
    ans=power(a,b)
    print(ans)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 13:54:30 2021

Read .xls output from bettersizer

@author: tobias
"""
import pandas as pd

def read_metadata(path, header_row=2, n_rows=6):
    xls_metadata = pd.read_excel(path, header=header_row).iloc[:n_rows]

    # drop empty columns
    for col in xls_metadata.columns:
        if all(xls_metadata.loc[:, col].isna()):
            xls_metadata = xls_metadata.drop(col, axis=1)

    metadata = dict()
    for row in xls_metadata.iterrows():
        for cell in row[1]:
            key, value = cell.split(':', maxsplit=1)
            metadata[key.strip()] = value.strip()
    return metadata

def read_analysis_data(path, first_row=8, last_row=10):
    xls_analysis_data = pd.read_excel(path).iloc[first_row: last_row]

    # drop empty columns
    for col in xls_analysis_data.columns:
        if all(xls_analysis_data.loc[:, col].isna()):
            xls_analysis_data = xls_analysis_data.drop(col, axis=1)

    analysis_data = dict()
    for row in xls_analysis_data.iterrows():
        for cell in row[1]:
            key, value = cell.split(':', maxsplit=1)
            analysis_data[key.strip()] = value.strip()
    return analysis_data

def read_sd_data(path, data_categories=['Diam um', 'Diff%', 'Cum%']):
    """
    Read the size distribution data from an xls sheet generated by the Bettersizer software.

    Parameters
    ----------
    path : str
        Path to the .xls file.

    Returns
    -------
    pd.DataFrame
        Contains the size distribution data from the xls sheet.

    """
    def get_data_header_row_idx(df):
        """Get the row index of data header"""
        for idx, row in df.iterrows():
            if any(row.astype('str').str.contains('(Diam um)')):
                return idx

    def get_data_category_columns(header_row, data_category):
        """Get a list of excel column names belonging to a data category"""
        return list(header_row[header_row.astype(str).str.contains(data_category)].index)

    def concat_columns(df, xls_header_row_idx, xls_category_column_names):
        """Concatenate columns which belong to the same category"""
        s = pd.Series(dtype=float)

        for col_name in xls_category_column_names:
            ss = df.loc[xls_header_row_idx + 1:, col_name]  # subseries

            # delete cells after first entry which contains NaN
            fist_nan_idx = ss[ss.isna()].index.min()
            indices_after_first_nan_idx = ss.loc[fist_nan_idx:].index
            ss = ss.drop(indices_after_first_nan_idx)

            s = s.append(ss, ignore_index=True)
        return s

    xls_df = pd.read_excel(path)
    xls_header_row_idx = get_data_header_row_idx(xls_df)

    data = pd.DataFrame()
    for data_category in data_categories:
        xls_category_column_names = get_data_category_columns(xls_df.loc[xls_header_row_idx], data_category)
        data[data_category] = concat_columns(xls_df, xls_header_row_idx, xls_category_column_names)

    return data

def read_system_status(path):
    """Reads the cell with system status information and splits the alphabetical keys"""
    import re

    def find_string_coordinates_in_df(df, string):
        for col in df.columns:
            if any(df[col].astype(str).str.contains(string)):
                idx = df[col][df[col].astype(str).str.contains(string)].index
                return (idx, col)

    xls_df = pd.read_excel(path)
    cell_coords = find_string_coordinates_in_df(xls_df, 'System Status')
    xls_sys_status = xls_df.loc[cell_coords[0], cell_coords[1]].item()

    sys_status = dict()
    separated_entries = re.split(r'\s+', xls_sys_status)
    for entry in separated_entries:
        if ':' in entry:
            key, value = entry.split(':')
            sys_status[key] = value
        else:
            continue

    return sys_status


import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib

class Scope:
    def __init__(self, ax, maxt=2, dt=0.02):
        self.ax = ax
        self.dt = dt
        self.maxt = maxt
        self.tdata = [0]
        self.ydata = [0]
        self.line = Line2D(self.tdata, self.ydata)
        self.ax.add_line(self.line)
        self.ax.set_ylim(-.1, 1.1)
        self.ax.set_xlim(0, self.maxt)

    def update(self, y):
        lastt = self.tdata[-1]
        if lastt > self.tdata[0] + self.maxt:  # reset the arrays
            self.tdata = [self.tdata[-1]]
            self.ydata = [self.ydata[-1]]
            self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
            self.ax.figure.canvas.draw()

        t = self.tdata[-1] + self.dt
        self.tdata.append(t)
        self.ydata.append(y)
        self.line.set_data(self.tdata, self.ydata)
        return self.line,

def emitter(p=0.1):
    """Return a random value in [0, 1) with probability p, else 0."""
    while True:
        v = np.random.rand(1)
        if v > p:
            yield 0.
        else:
            yield np.random.rand(1)

if __name__ == '__main__':
    # перебираем возможные backend
    gui_env = ['Qt5Agg', 'GTKAgg', 'TKAgg', 'WXAgg']
    for gui in gui_env:
        try:
            print("testing", gui)
            matplotlib.use(gui, force=True)
            from matplotlib import pyplot as plt

            break
        except:
            continue
        else:
            print("Not found backend for GUI. Terminate program ")
            exit(1)
    print("Using:", matplotlib.get_backend())

    # Fixing random state for reproducibility
    np.random.seed(19680801 // 10)

    fig, ax = plt.subplots()
    scope = Scope(ax)

    # pass a generator in "emitter" to produce data for the update func
    ani = animation.FuncAnimation(fig, scope.update, emitter, interval=50, blit=True)

    plt.show()


from django.contrib import admin
from .models import TypeInfo,GoodsInfo
from django.utils.safestring import mark_safe
class TypeInfoAdmin(admin.ModelAdmin):
    list_display = ['id','ttitle']

class GoodsInfoAdmin(admin.ModelAdmin):
    fields = ['gtitle','gpic','image_data','goriginal_price',\
    'gdiscount_price','gsynopsis','ginventory','gpostage',\
    'gcontext','isDelete','gadvertis','gtype']
    list_per_page = 10
    list_display = ['id','image_data','gtitle','gdiscount_price','gtype']
    readonly_fields = ('image_data',)  #必须加这行 否则访问编辑页面会报错
    def image_data(self, obj):
        return mark_safe('<img src="http://127.0.0.1:8000/static/%s" width="60px" />' % obj.gpic.url)
    image_data.short_description = '主图图片'

admin.site.register(TypeInfo,TypeInfoAdmin)
admin.site.register(GoodsInfo,GoodsInfoAdmin)


import json
import pandas as pd

with open('data/routes.json') as f:
    sample_data = json.loads(f.read())
#print(sample_data)
## Remove an element from JSON data
#import json
#
#with open('data.json', 'r') as data_file:
#    data = json.load(data_file)
#
#for element in data:
#    element.pop('hours', None)
#
#with open('data.json', 'w') as data_file:
#    data = json.dump(data, data_file)

def is_empty(any_structure): #d = {} # Empty dictionary, l = [] # Empty list, ms = set() # Empty set, s = '' # Empty string, t = () # Empty tuple
    if any_structure: #print('Structure is not empty.')
        return False
    else: #print('Structure is empty.')
        return True
def get_coordinates(data):
    clean_data = []
    for element in sample_data:
        element.pop('data', None)
        element.pop('msgid', None)
        element.pop('status', None)
        element.pop('submsgid', None)
        element.pop('svid', None)
        element.pop('type', None)
        element.pop('time', None)
        if not(is_empty(element)):
            clean_data.append(element)
    return clean_data

#print(data_sample)
clean_data = get_coordinates(sample_data)

#print(clean_data)
data_dict = json.loads(json.dumps(sample_data))
#type(data_dict)
#print(data_dict[0]['lat']) #print(data[<keyFromTheJsonFile>])

df = pd.DataFrame.from_dict(clean_data)
json.dumps(clean_data)
#print(df)
lon = df['lon']
lat = df['lat']


alt = {
    "A1": "!B!",
    "B1": "B`",
    "B`1": "T",
    "B`2": "B`+T",
    "T1": "T`",
    "T`1": "M",
    "T`2": "T`*M",
    "M1": "a",
    "M2": "b",
    "M3": "(B)",
}
L = {}
R = {}
for x in alt.keys():
    st = x[: len(x) - 1]
    L[st] = []
    R[st] = []
for x in L.keys():
    tmp = x + "1"
    while alt.get(tmp) != None:
        val = alt.get(tmp)
        l_tmp = L.get(x)
        if len(val) > 1:
            if val[1] == "`":
                if (val[0] + val[1]) in l_tmp:
                    pass
                else:
                    l_tmp.append(val[0] + val[1])
            else:
                if (val[0]) in l_tmp:
                    pass
                else:
                    l_tmp.append(val[0])
        else:
            if (val[0]) in l_tmp:
                pass
            else:
                l_tmp.append(val[0])
        L[x] = l_tmp
        r_tmp = R.get(x)
        if val[len(val) - 1] == "`":
            if (val[len(val) - 2] + val[len(val) - 1]) in r_tmp:
                pass
            else:
                r_tmp.append(val[len(val) - 2] + val[len(val) - 1])
        else:
            if (val[len(val) - 1]) in r_tmp:
                pass
            else:
                r_tmp.append(val[len(val) - 1])
        R[x] = r_tmp
        tmp = tmp[: len(tmp) - 1] + chr(ord(tmp[len(tmp) - 1]) + 1)
l_keys = list(L.keys())
for i in range(1, len(l_keys) - 1):
    append_l = L.get(l_keys[i])
    for j in range(i + 1, len(l_keys)):
        tmp_l = L.get(l_keys[j])
        for x in tmp_l:
            if x in append_l:
                pass
            else:
                append_l.append(x)
    L[l_keys[i]] = append_l
r_keys = list(R.keys())
for i in range(1, len(r_keys) - 1):
    append_r = R.get(r_keys[i])
    for j in range(i + 1, len(r_keys)):
        tmp_r = R.get(r_keys[j])
        for x in tmp_r:
            if x in append_r:
                pass
            else:
                append_r.append(x)
    R[r_keys[i]] = append_r
mp_idx = []
for x in alt.keys():
    tmp = alt.get(x)
    tmp_list = []
    for y in tmp:
        if y != "`":
            tmp_list.append(str(y))
        else:
            tmp_list[len(tmp_list) - 1] = tmp_list[len(tmp_list) - 1] + "`"
    for y in tmp_list:
        if y in mp_idx:
            pass
        else:
            mp_idx.append(y)
mp = []
for i in mp_idx:
    mp_str = []
    for j in mp_idx:
        mp_str.append("")
    mp.append(mp_str)
for x in alt.keys():
    tmp = alt.get(x)
    tmp_list = []
    for y in tmp:
        if y != "`":
            tmp_list.append(str(y))
        else:
            tmp_list[len(tmp_list) - 1] = tmp_list[len(tmp_list) - 1] + "`"
    if len(tmp_list) > 1:
        for i in range(0, len(tmp_list) - 1):
            v = mp_idx.index(tmp_list[i])
            g = mp_idx.index(tmp_list[i + 1])
            mp[v][g] = "=."
T = ["!", "(", "*", "+", ")"]
NT = ["B", "B`", "T", "T`", "M"]
for x in alt.keys():
    tmp = alt.get(x)
    tmp_list = []
    for y in tmp:
        if y != "`":
            tmp_list.append(str(y))
        else:
            tmp_list[len(tmp_list) - 1] = tmp_list[len(tmp_list) - 1] + "`"
    if len(tmp_list) > 1:
        for i in range(0, len(tmp_list) - 1):
            if (tmp_list[i] in T) and (tmp_list[i + 1] in NT):
                v = mp_idx.index(tmp_list[i])
                tmp_l = L.get(tmp_list[i + 1])
                for j in tmp_l:
                    g = mp_idx.index(j)
                    mp[v][g] = "<."
for x in alt.keys():
    tmp = alt.get(x)
    tmp_list = []
    for y in tmp:
        if y != "`":
            tmp_list.append(str(y))
        else:
            tmp_list[len(tmp_list) - 1] = tmp_list[len(tmp_list) - 1] + "`"
    if len(tmp_list) > 1:
        for i in range(0, len(tmp_list) - 1):
            if (tmp_list[i] in NT) and (tmp_list[i + 1] in T):
                g = mp_idx.index(tmp_list[i + 1])
                tmp_r = R.get(tmp_list[i])
                for j in tmp_r:
                    v = mp_idx.index(j)
                    mp[v][g] = ".>"
in_str = str(input("Enter string ="))
print("L=")
for x in L:
    print(x, "\t", L.get(x))
print("\nR=")
for x in R:
    print(x, "\t", R.get(x))
res = ""
for x in mp_idx:
    res += "\t" + x
print(res)
for x in range(len(mp_idx)):
    res = ""
    for y in mp[x]:
        res += y + "\t"
    print(mp_idx[x], "\t", res)
idx_alt = {
    "A1": "1",
    "B1": "2",
    "B`1": "3",
    "B`2": "4",
    "T1": "5",
    "T`1": "6",
    "T`2": "7",
    "M1": "8",
    "M2": "9",
    "M3": "10",
}
res = ""
stack1 = []
stack1.append(in_str[0])
in_str = in_str[1:]
while stack1[0] != "A":
    if len(in_str) == 0:
        svertka = []
        svertka = [stack1.pop()] + svertka
        while (
            len(stack1) > 0
            and mp[mp_idx.index(stack1[len(stack1) - 1])][mp_idx.index(svertka[0])]
            != "<."
        ):
            svertka = [stack1.pop()] + svertka
        st_svertka = ""
        for x in svertka:
            st_svertka += x
        flag = True
        for x in alt.keys():
            if alt.get(x) == st_svertka:
                res += idx_alt.get(x) + " "
                flag = False
                stack1.append(x[: len(x) - 1])
                break
        if flag:
            res = "Can't represent this string"
            break
        continue

    if (mp[mp_idx.index(stack1[len(stack1) - 1])][mp_idx.index(in_str[0])] == "<.") or (
        mp[mp_idx.index(stack1[len(stack1) - 1])][mp_idx.index(in_str[0])] == "=."
    ):
        stack1.append(in_str[0])
        in_str = in_str[1:]
        continue
    if mp[mp_idx.index(stack1[len(stack1) - 1])][mp_idx.index(in_str[0])] == ".>":
        svertka = []
        svertka = [stack1.pop()] + svertka
        while (
            len(stack1) > 0
            and mp[mp_idx.index(stack1[len(stack1) - 1])][mp_idx.index(svertka[0])]
            != "<."
        ):
            svertka = [stack1.pop()] + svertka
        st_svertka = ""
        for x in svertka:
            st_svertka += x
        flag = True
        for x in alt.keys():
            if alt.get(x) == st_svertka:
                res += idx_alt.get(x) + " "
                flag = False
                stack1.append(x[: len(x) - 1])
                break
        if flag:
            res = "Can't represent this string"
            break
        continue
    res = "Can't represent this string"
    break
print(res)


import pygame
import sys

# 初始化

pygame.init()

# 创建游戏窗口
"""
- resolution 指定屏幕的 宽 和 高，默认创建的窗口大小和屏幕大小一致
- flags 参数指定屏幕的附加选项，例如是否全屏等等，默认不需要传递
- depth 参数表示颜色的位数，默认自动匹配
"""
size = width, height = 480, 700

screen = pygame.display.set_mode(size)

# 绘制背景图像

# 加载图像
bg = pygame.image.load("./images/background.png")

# 1> 加载图像
hero = pygame.image.load("./images/me1.png")

# 定义英雄初始化位置
hero_rect = hero.get_rect()
hero_rect.x = 100
hero_rect.y = 500
print(hero_rect.width, hero_rect.height)
print(hero_rect.x, hero_rect.y)
speed = [0, -6]

# 获取时钟
clock = pygame.time.Clock()

while 1:
    # 设置刷新频率
    clock.tick(120)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("退出游戏。。。")
            pygame.quit()
            sys.exit()

    hero_rect = hero_rect.move(speed)

    if hero_rect.y < - 126:
        hero_rect.y = 700

    # 绘制在屏幕
    screen.blit(bg, (0, 0))
    # 2> 绘制在屏幕
    screen.blit(hero, hero_rect)

    pygame.display.update()


temp = input()
temp = temp.split()
n, k = int(temp[0]), int(temp[1])
coin_arr = [0 for _ in range(n)]
d_arr = [0 for _ in range(k + 1)]

for i in range(n):
    coin_arr[i] = int(input())

d_arr[0] = 1

for i in range(n) :
    for j in range(k + 1):
        if j - coin_arr[i] >= 0:
            d_arr[j] = d_arr[j] + d_arr[j - coin_arr[i]]

print(d_arr[-1])