import pandas as pd
import numpy as np
import umap
import json
from loguru import logger

def convert_str_emb_to_float(emb_list):
    float_emb = []
    for str_emb in emb_list:
        emb = json.loads(str_emb)
        float_emb.append(np.array(emb))
    return float_emb

def reduce_embedding_dimension(
    data,
    dimension,
):

    float_emb = convert_str_emb_to_float(data)

    logger.info(f"reduction to {dimension} dimensions...")
    transformer = umap.UMAP(
        n_components=dimension,
        random_state=42,
        n_neighbors=10,
        transform_seed=42,
        verbose=False,
    ).fit(float_emb)
    emb_reduced = transformer.embedding_.astype(np.float32)
    return emb_reduced.tolist()


from vehicles.models import VehicleManufacturer, VehicleModel, Vehicle
import random

_manufacturer = 0
_vehicle_model = 0
_vehicle = 0

def create_manufacturer():
    global _manufacturer
    name = 'manufac' + str(_manufacturer) + 'v'
    manufacturer_dict = {
        'name': name
    }
    _manufacturer += 1
    manufacturer = VehicleManufacturer(**manufacturer_dict)
    manufacturer.save()
    return manufacturer

def create_vehicle_model():
    global _vehicle_model
    name = 'model' + str(_vehicle_model)
    dic = {
        'name': name,
        'manufacturer': create_manufacturer(),
        'motor': 1000,
        'vehicle_type': VehicleModel.TYPE_CAR
    }

    _vehicle_model += 1
    vehicleModel = VehicleModel(**dic)
    vehicleModel.save()
    return vehicleModel

def create_vehicle(**kwargs):
    global _vehicle
    years = [1999, 2010, 2015]
    colors = ['azul', 'prata', 'preto']

    _vehicle += 1

    dic = {
        'vehicle_model': create_vehicle_model(),
        'year': kwargs.get('year', random.choice(years)),
        'color': kwargs.get('color', random.choice(colors)),
        'mileage': kwargs.get('mileage', 100000)
    }

    vehicle = Vehicle(**dic)
    vehicle.save()
    return vehicle


import database
import databasebuilder
import idlparser
import logging.config
import os.path
import sys

_logger = logging.getLogger('fremontcutbuilder')

FEATURE_DISABLED = [
    'ENABLE_BATTERY_STATUS',
    'ENABLE_CSS3_CONDITIONAL_RULES',
    'ENABLE_CSS_DEVICE_ADAPTATION',
    'ENABLE_CUSTOM_SCHEME_HANDLER',
    'ENABLE_ENCRYPTED_MEDIA_V2',
    'ENABLE_MEDIA_CAPTURE', # Only enabled on Android.
    'ENABLE_ORIENTATION_EVENTS', # Only enabled on Android.
    'ENABLE_SPEECH_SYNTHESIS',
    'ENABLE_WEBVTT_REGIONS',
    'ENABLE_XHR_TIMEOUT',
]

FEATURE_DEFINES = [
    'ENABLE_CALENDAR_PICKER',
    'ENABLE_CANVAS_PROXY',
    'ENABLE_CSS_REGIONS',
    'ENABLE_CUSTOM_ELEMENTS',
    'ENABLE_DATALIST_ELEMENT',
    'ENABLE_DIALOG_ELEMENT',
    'ENABLE_ENCRYPTED_MEDIA',
    'ENABLE_FONT_LOAD_EVENTS',
    'ENABLE_GAMEPAD',
    'ENABLE_INPUT_SPEECH',
    'ENABLE_LEGACY_NOTIFICATIONS',
    'ENABLE_MEDIA_STREAM',
    'ENABLE_NAVIGATOR_CONTENT_UTILS',
    'ENABLE_NOTIFICATIONS',
    'ENABLE_PAGE_POPUP',
    'ENABLE_SHARED_WORKERS',
    'ENABLE_SVG',
    'ENABLE_SVG_FONTS',
    'ENABLE_VIDEO',
    'ENABLE_WEB_AUDIO',
    'ENABLE_WEBGL',
]

def build_database(idl_files, database_dir, feature_defines=None, parallel=False):
  """This code reconstructs the FremontCut IDL database from W3C,
  WebKit and Dart IDL files."""
  current_dir = os.path.dirname(__file__)
  logging.config.fileConfig(os.path.join(current_dir, "logging.conf"))

  db = database.Database(database_dir)

  # Delete all existing IDLs in the DB.
  db.Delete()

  builder = databasebuilder.DatabaseBuilder(db)

  # TODO(vsm): Move this to a README.
  # This is the Dart SVN revision.
  webkit_revision = '1060'

  # TODO(vsm): Reconcile what is exposed here and inside WebKit code
  # generation.  We need to recheck this periodically for now.
  webkit_defines = [ 'LANGUAGE_DART', 'LANGUAGE_JAVASCRIPT' ]

  if feature_defines is None:
    feature_defines = FEATURE_DEFINES

  webkit_options = databasebuilder.DatabaseBuilderOptions(
      idl_syntax=idlparser.WEBKIT_SYNTAX,
      # TODO(vsm): What else should we define as on when processing IDL?
      idl_defines=webkit_defines + feature_defines,
      source='WebKit',
      source_attributes={'revision': webkit_revision})

  # Import WebKit IDLs.
  builder.import_idl_files(idl_files, webkit_options, parallel)

  # Import Dart idl:
  dart_options = databasebuilder.DatabaseBuilderOptions(
    idl_syntax=idlparser.FREMONTCUT_SYNTAX,
    source='Dart',
    rename_operation_arguments_on_merge=True)

  builder.import_idl_files(
      [ os.path.join(current_dir, '..', 'idl', 'dart', 'dart.idl') ],
      dart_options,
      parallel)

  # Merging:
  builder.merge_imported_interfaces()

  builder.fetch_constructor_data(webkit_options)
  builder.fix_displacements('WebKit')

  # Cleanup:
  builder.normalize_annotations(['WebKit', 'Dart'])

  conditionals_met = set(
      'ENABLE_' + conditional for conditional in builder.conditionals_met)
  known_conditionals = set(FEATURE_DEFINES + FEATURE_DISABLED)

  unused_conditionals = known_conditionals - conditionals_met
  if unused_conditionals:
    _logger.warning('There are some unused conditionals %s' %
        sorted(unused_conditionals))

  unknown_conditionals = conditionals_met - known_conditionals
  if unknown_conditionals:
    _logger.warning('There are some unknown conditionals %s' %
        sorted(unknown_conditionals))

  db.Save()
  return db

def main(parallel=False):
  current_dir = os.path.dirname(__file__)

  idl_files = []

  webcore_dir = os.path.join(current_dir, '..', '..', '..', 'third_party',
                             'WebCore')
  if not os.path.exists(webcore_dir):
    raise RuntimeError('directory not found: %s' % webcore_dir)

  DIRS_TO_IGNORE = [
      'bindings', # Various test IDLs
      'testing', # IDLs to expose testing APIs
      'networkinfo', # Not yet used in Blink yet
      'vibration', # Not yet used in Blink yet
  ]

  def visitor(arg, dir_name, names):
    if os.path.basename(dir_name) in DIRS_TO_IGNORE:
      names[:] = [] # Do not go underneath
    for name in names:
      file_name = os.path.join(dir_name, name)
      (interface, ext) = os.path.splitext(file_name)
      if ext == '.idl':
        idl_files.append(file_name)

  os.path.walk(webcore_dir, visitor, webcore_dir)

  database_dir = os.path.join(current_dir, '..', 'database')
  return build_database(idl_files, database_dir, parallel=parallel)

if __name__ == '__main__':
  sys.exit(main())


#!/usr/bin/python
# coding:utf-8

"""
@author: yyhaker
@contact: 572176750@qq.com
@file: 19.报数.py
@time: 2019/8/4 16:02
"""
"""
leetcode38：报数(Count and Say)
"""
class Solution:
    def countAndSay(self, n: int) -> str:
        # 思路：统计字符串个数，然后拼接到一起
        res = "1"
        for i in range(n-1):
            prev = res[0]
            count = 1
            ans = ""
            for j in range(1, len(res)):
                cur = res[j]
                if prev != cur:
                    ans = ans + str(count) + str(prev)
                    prev = cur
                    count = 0
                count += 1
            res = ans + str(count) + str(prev)
        return res
# [38] 外观数列
#
# https://leetcode-cn.com/problems/count-and-say/description/
#
# algorithms
# Easy (56.98%)
# Likes:    653
# Dislikes: 0
# Total Accepted:    170.5K
# Total Submissions: 297.3K
# Testcase Example:  '1'
#
# 给定一个正整数 n ，输出外观数列的第 n 项。
#
# “外观数列”是一个整数序列，从数字 1 开始，序列中的每一项都是对前一项的描述。
#
# 你可以将其视作是由递归公式定义的数字字符串序列：
#
#
# countAndSay(1) = "1"
# countAndSay(n) 是对 countAndSay(n-1) 的描述，然后转换成另一个数字字符串。
#
#
# 前五项如下：
#
#
# 1.     1
# 2.     11
# 3.     21
# 4.     1211
# 5.     111221
# 第一项是数字 1
# 描述前一项，这个数是 1 即 “ 一 个 1 ”，记作 "11"
# 描述前一项，这个数是 11 即 “ 二 个 1 ” ，记作 "21"
# 描述前一项，这个数是 21 即 “ 一 个 2 + 一 个 1 ” ，记作 "1211"
# 描述前一项，这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ，记作 "111221"
#
#
# 要 描述 一个数字字符串，首先要将字符串分割为 最小 数量的组，每个组都由连续的最多 相同字符
# 组成。然后对于每个组，先描述字符的数量，然后描述字符，形成一个描述组。要将描述转换为数字字符串，先将每组中的字符数量用数字替换，再将所有描述组连接起来。
#
# 例如，数字字符串 "3322251" 的描述如下图：
#
#
#
#
#
#
# 示例 1：
#
#
# 输入：n = 1
# 输出："1"
# 解释：这是一个基本样例。
#
#
# 示例 2：
#
#
# 输入：n = 4
# 输出："1211"
# 解释：
# countAndSay(1) = "1"
# countAndSay(2) = 读 "1" = 一 个 1 = "11"
# countAndSay(3) = 读 "11" = 二 个 1 = "21"
# countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"
#
#
#
#
# 提示：
#
#
# 1
#
#


from hypothesis import given
from hypothesis.strategies import lists, builds

from cim.collection_validator import validate_collection_unordered
from cim.iec61968.common.test_document import document_kwargs, verify_document_constructor_default, verify_document_constructor_kwargs, \
    verify_document_constructor_args, document_args
from zepben.evolve import OperationalRestriction, Equipment

operational_restriction_kwargs = {
    **document_kwargs,
    "equipment": lists(builds(Equipment), max_size=2),
}

operational_restriction_args = [*document_args, [Equipment()]]

def test_operational_restriction_constructor_default():
    or_ = OperationalRestriction()

    verify_document_constructor_default(or_)
    assert not list(or_.equipment)

@given(**operational_restriction_kwargs)
def test_operational_restriction_constructor_kwargs(equipment, **kwargs):
    # noinspection PyArgumentList
    or_ = OperationalRestriction(
        equipment=equipment,
        **kwargs
    )

    verify_document_constructor_kwargs(or_, **kwargs)
    assert list(or_.equipment) == equipment

def test_operational_restriction_constructor_args():
    # noinspection PyArgumentList
    or_ = OperationalRestriction(*operational_restriction_args)

    verify_document_constructor_args(or_)
    assert list(or_.equipment) == operational_restriction_args[-1]

def test_equipment_collection():
    # noinspection PyArgumentList
    validate_collection_unordered(OperationalRestriction,
                                  lambda mrid, _: Equipment(mrid),
                                  OperationalRestriction.num_equipment,
                                  OperationalRestriction.get_equipment,
                                  OperationalRestriction.equipment,
                                  OperationalRestriction.add_equipment,
                                  OperationalRestriction.remove_equipment,
                                  OperationalRestriction.clear_equipment)


import cv2

fps = 24
size = (274,512)
videowriter = cv2.VideoWriter("result.avi",cv2.cv.FOURCC('M','J','P','G'),fps,size)

for i in range(1,150):
    img = cv2.imread('../results/result%d.png' % i)
    if i!=70:
    	videowriter.write(img)


# dndtester.py

import pygtk
pygtk.require("2.0")

import gtk
import gtk.glade

class DNDTester(object):
    def __init__(self):
        filename = 'dnd.glade'
        windowname = 'DNDTester'
        self.wTree = gtk.glade.XML(filename, windowname)
        self.log_buffer = gtk.TextBuffer()
        self.setupWidgets()

    def setupWidgets(self):
        HANDLERS_AND_METHODS = {
            "on_dndtester_destroy": self.destroy,
            "on_drag_data_received": self.on_log_drag_data_received
            }

        log = self.wTree.get_widget("log")
        log.set_buffer(self.log_buffer)
        self.wTree.signal_autoconnect(HANDLERS_AND_METHODS)

    def on_log_drag_data_received(self, data):
        self.log_buffer.insert_at_cursor(data+'\n', len(data))

    def destroy(self, data):
        gtk.mainquit()

if __name__ == "__main__":
    app = DNDTester()
    gtk.mainloop()


def uniquePaths(array_matrix): #Запускаем цикл, который идет по двумерному массиву
    for i in range(1, len(array_matrix)): #Запускаем цикл, который идет по элементам массива
        for j in range(1, len(array_matrix[i])):#Записываем в ячейку массива минимальное значение из соседних ячеек
            array_matrix[i][j] *= min(array_matrix[i - 1][j], array_matrix[i][j - 1], array_matrix[i - 1][j - 1]) + 1
    return sum(map(sum, array_matrix))#Возвращаем сумму всех единиц

print(uniquePaths([[0,1,1,1],[1,1,1,1],[0,1,1,1]]))
print(uniquePaths([[1,0,1],[1,1,0],[1,1,0]]))

"""Сложность O(n**2)"""


from __future__ import annotations

from typing import Callable, Type, TypeVar

T = TypeVar("T")
Instance = TypeVar("Instance")
MapValidateSub = TypeVar("MapValidateSub", bound = "MapValidate")

class MapValidate:
    """
    A data descriptor that will apply the provided mapper functions to its data to transform it and then validate it
    using the provided validator functions before completing assignment. If any of the validators return false, a
    ValueError is raised.
    The on_get and on_set functions are invoked when the data associated with the descriptor is accessed and set
    respectively
    """
    __slots__ = "p_name", "s_name", "mappers", "validators", "on_get", "on_set"

    def __init__(
        self,
        mappers: list[Callable[[MapValidateSub, Instance, T], T]] | None = None,
        validators: list[Callable[[MapValidateSub, Instance, T], tuple[bool, str]]] | None = None,
        on_get: list[Callable[[MapValidateSub, Instance], None]] | None = None,
        on_set: list[Callable[[MapValidateSub, Instance], None]] | None = None,
    ):
        """
        :param mappers: A list of functions that can mutate the value that is assigned to this property
        :param validators:
            A list of functions that can validate the value that is assigned to this property. A ValueError is raised if
            validation from any one of these functions fails
        :param on_get: A list of functions that are called when this property is accessed
        :param on_set: A list of functions that are called when this property is set
        """
        self.mappers = mappers or []
        self.validators = validators or []
        self.on_get = on_get or []
        self.on_set = on_set or []

    def __set_name__(self, owner: Type[Instance], name: str) -> None:
        self.p_name = name
        self.s_name = f"_{name}"

    def __get__(self, instance: Instance, owner: Type[Instance]) -> MapValidate | T:
        if instance is None:
            return self

        for func in self.on_get:
            func(self, instance)

        return getattr(instance, self.s_name)

    def __set__(self, instance: Instance, value: T) -> None:
        val = value
        for mapper in self.mappers:
            val = mapper(self, instance, val)

        for validator in self.validators:
            valid, msg = validator(self, instance, val)
            if not valid:
                raise ValueError(msg % repr(self.p_name))

        setattr(instance, self.s_name, val)
        for func in self.on_set:
            func(self, instance)


import torch
import torch.nn as nn
import torch.nn.functional as F

#TODO: focal loss index over error
class FocalLoss(nn.Module):
    def __init__(self, gamma=0, alpha=None, size_average=True):
        super(FocalLoss, self).__init__()
        self.gamma = gamma
        self.alpha = alpha
        if isinstance(alpha,(float,int)): self.alpha = torch.Tensor([alpha,1-alpha])
        if isinstance(alpha,list): self.alpha = torch.Tensor(alpha)
        self.size_average = size_average

    def forward(self, input, target):
        if input.dim()>2:
            input = input.view(input.size(0),input.size(1),-1)  # N,C,H,W => N,C,H*W
            input = input.transpose(1,2)    # N,C,H*W => N,H*W,C
            input = input.contiguous().view(-1,input.size(2))   # N,H*W,C => N*H*W,C
        target = target.view(-1,1)

        logpt = F.log_softmax(input)
        logpt = logpt.gather(1,target)
        logpt = logpt.view(-1)
        pt = logpt.data.exp()

        if self.alpha is not None:
            if self.alpha.type()!=input.data.type():
                self.alpha = self.alpha.type_as(input.data)
            at = self.alpha.gather(0,target.data.view(-1))
            logpt = logpt * at

        loss = -1 * (1-pt)**self.gamma * logpt
        if self.size_average:
            return loss.mean()
        else:
            return loss.sum()

def multi_focal_loss_fusion(d0, d1, d2, d3, d4, d5, d6, labels_v):
    focal_loss = FocalLoss(size_average=True)

    loss0 = focal_loss(d0, labels_v)
    loss1 = focal_loss(d1, labels_v)
    loss2 = focal_loss(d2, labels_v)
    loss3 = focal_loss(d3, labels_v)
    loss4 = focal_loss(d4, labels_v)
    loss5 = focal_loss(d5, labels_v)
    loss6 = focal_loss(d6, labels_v)
    loss = loss0 + loss1 + loss2 + loss3 + loss4 + loss5 + loss6

    #print("l0: %3f, l1: %3f, l2: %3f, l3: %3f, l4: %3f, l5: %3f, l6: %3f\n"%(loss0.data.item(),loss1.data.item(),loss2.data.item(),loss3.data.item(),loss4.data.item(),loss5.data.item(),loss6.data.item()))

    return loss0, loss

def multi_bce_loss_fusion(d0, d1, d2, d3, d4, d5, d6, labels_v):
    bce_loss = nn.BCELoss(size_average=True)

    loss0 = bce_loss(d0, labels_v)
    loss1 = bce_loss(d1, labels_v)
    loss2 = bce_loss(d2, labels_v)
    loss3 = bce_loss(d3, labels_v)
    loss4 = bce_loss(d4, labels_v)
    loss5 = bce_loss(d5, labels_v)
    loss6 = bce_loss(d6, labels_v)
    loss = loss0 + loss1 + loss2 + loss3 + loss4 + loss5 + loss6

    #print("l0: %3f, l1: %3f, l2: %3f, l3: %3f, l4: %3f, l5: %3f, l6: %3f\n"%(loss0.data.item(),loss1.data.item(),loss2.data.item(),loss3.data.item(),loss4.data.item(),loss5.data.item(),loss6.data.item()))

    return loss0, loss

# def CB_loss(labels, logits, samples_per_cls, no_of_classes, loss_type, beta, gamma):
#     """Compute the Class Balanced Loss between `logits` and the ground truth `labels`.
#     Class Balanced Loss: ((1-beta)/(1-beta^n))*Loss(labels, logits)
#     where Loss is one of the standard losses used for Neural Networks.
#     Args:
#       labels: A int tensor of size [batch].
#       logits: A float tensor of size [batch, no_of_classes].
#       samples_per_cls: A python list of size [no_of_classes].
#       no_of_classes: total number of classes. int
#       loss_type: string. One of "sigmoid", "focal", "softmax".
#       beta: float. Hyperparameter for Class balanced loss.
#       gamma: float. Hyperparameter for Focal loss.
#     Returns:
#       cb_loss: A float tensor representing class balanced loss
#     """
#     effective_num = 1.0 - np.power(beta, samples_per_cls)
#     weights = (1.0 - beta) / np.array(effective_num)
#     weights = weights / np.sum(weights) * no_of_classes
#
#     labels_one_hot = F.one_hot(labels, no_of_classes).float()
#
#     weights = torch.tensor(weights).float()
#     weights = weights.unsqueeze(0)
#     weights = weights.repeat(labels_one_hot.shape[0],1) * labels_one_hot
#     weights = weights.sum(1)
#     weights = weights.unsqueeze(1)
#     weights = weights.repeat(1,no_of_classes)
#
#     if loss_type == "focal":
#         cb_loss = focal_loss(labels_one_hot, logits, weights, gamma)
#     elif loss_type == "sigmoid":
#         cb_loss = F.binary_cross_entropy_with_logits(input = logits,target = labels_one_hot, weights = weights)
#     elif loss_type == "softmax":
#         pred = logits.softmax(dim = 1)
#         cb_loss = F.binary_cross_entropy(input = pred, target = labels_one_hot, weight = weights)
#     return cb_loss


import time
from pika import BlockingConnection, ConnectionParameters
from pika.adapters.blocking_connection import BlockingChannel

QUEUE_NAME = "basic_channel"

def send_message(channel: BlockingChannel, body: str):
    """
    Send a basic message to the given channel

    :param channel: The channel to send to.
    :param body: The body to send.
    """
    print(f"Sending message: {body}")
    channel.basic_publish(
        exchange="",
        routing_key=QUEUE_NAME,
        body=body
    )

def run_distributer(connection):
    """
    Runs the distributer after we have established a connection.

    :param connection: The established connection.
    """
    channel = connection.channel()

    channel.queue_declare(queue=QUEUE_NAME)

    for counter in range(10000):
        send_message(channel, f"Message number: {counter}")

    connection.close()

if __name__ == "__main__":
    while True:
        try:
            time.sleep(1)
            connection = BlockingConnection(ConnectionParameters('rabbitmq'))
            break
        except Exception:
            print("Rabbitmq is down!")

    run_distributer(connection)


casenum = int(input())
case = [int(input()) for i in range(casenum)]

def Factorial(n) :
    if n == 0 :
        return 1
    elif n == 1 :
        return 1
    return n * Factorial(n-1)

for i in range(casenum) :
    print(f'#{i+1}')
    for j in range(0, case[i]) :
        for k in range(j+1) :
            print(Factorial(j) // (Factorial(j-k) * Factorial(k)), end=' ')
        print()


import math
import torch
import torch.nn as nn
import torch.nn.functional as F

class Downblock(nn.Module):
    def __init__(self, channels, kernel_size=3):
        super(Downblock, self).__init__()
        self.dwconv = nn.Conv2d(channels, channels, groups=channels, stride=2,
                                kernel_size=kernel_size, padding=1, bias=False)

        self.bn = nn.BatchNorm2d(channels)

    def forward(self, x):
        return self.bn(self.dwconv(x))

class GEBlock(nn.Module):
    def __init__(self, in_planes, out_planes, stride, spatial, extent=0, extra_params=True, mlp=True, dropRate=0.0):
        super(GEBlock, self).__init__()

        self.bnrelu = nn.Sequential(nn.BatchNorm2d(in_planes), nn.ReLU(inplace=True))

        self.conv = nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False),
                                  nn.BatchNorm2d(out_planes),
                                  nn.ReLU(inplace=True),
                                  nn.Dropout(p=dropRate),
                                  nn.Conv2d(out_planes, out_planes, kernel_size=3, padding=1, bias=False))

        self.equalInOut = (in_planes == out_planes)

        self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes,
            out_planes, kernel_size=1, stride=stride, bias=False) or None

        if extra_params:
            if extent: modules = [Downblock(out_planes)]
            for i in range((extent-1) // 2): modules.append(nn.Sequential(nn.ReLU(inplace=True), Downblock(out_planes)))
            self.downop = nn.Sequential(*modules) if extent else Downblock(out_planes, kernel_size=spatial)
        else:
            self.downop = nn.AdaptiveAvgPool2d(spatial // extent) if extent else nn.AdaptiveAvgPool2d(1)

        self.mlp = nn.Sequential(nn.Conv2d(out_planes, out_planes // 16, kernel_size=1, bias=False), nn.ReLU(inplace=True),
            nn.Conv2d(out_planes // 16, out_planes, kernel_size=1, bias=False)) if mlp else lambda x: x

    def forward(self, x):
        bnrelu = self.bnrelu(x)
        out = self.conv(bnrelu)
        map = self.mlp(self.downop(out))
        # Assuming squares because lazy.
        map = F.interpolate(map, out.shape[-1])
        if not self.equalInOut: x = self.convShortcut(bnrelu)
        return torch.add(x, out * torch.sigmoid(map))


import os, sys, time

if __name__ == '__main__':
    print("Je suis %d" % os.getpid())
    p = os.fork()
    if p == 0: # Fils
        print("fils %d de %d" % (os.getpid(), os.getppid()))
        time.sleep(5)
        sys.exit(12)
    # Suite du père
    print("père %d de %d" % (os.getpid(), p))
    pid, status = os.wait()
    if os.WIFEXITED(status):
        print("Code sortie fils: %d" % os.WEXITSTATUS(status))
    else:
        print("child {} terminated abnormally".format(pid))
    sys.exit(0)


# Local imports
import json
import os

# Paths
JLAB_ROOT = os.getcwd()
PACKAGE_JSON = os.path.join(JLAB_ROOT, "dev_mode", "package.json")
EXTERNAL_DEPENDENCIES = {
    "@jupyterlab-benchmarks/table-render": "0.1.1"
}

def main():
    with open(PACKAGE_JSON, "r") as fh:
        data = json.loads(fh.read())

    jlab_data = data["jupyterlab"]
    if "externalExtensions" in jlab_data:
        external_extensions = jlab_data["externalExtensions"]
    else:
        external_extensions = {}

    external_extensions.update(EXTERNAL_DEPENDENCIES)
    jlab_data["externalExtensions"] = external_extensions
    data["jupyterlab"] = jlab_data
    print(json.dumps(data, indent=4, sort_keys=True))

    with open(PACKAGE_JSON, "w") as fh:
        fh.write(json.dumps(data, indent=4, sort_keys=True))

if __name__ == "__main__":
    main()


'''
Created on Feb 27, 2014

@author: anshulchawla
'''

import re

# . (dot ) matches any character except new line one characher per dot.
# does left to right so takes the first one from the left
match = re.search('...n','Its a cool world anshulanshul')
if match:
  print(match.group())
# /w word char a-z 0-9 etc but no punctuation or special character or space
# /d digit
# /s white space
# /S is opposite or whit space, it means except white space
# + one or more
# * zero or more
# put * or + after the charater for appropriate match
# [] order inside bracket does not matter [\w.] is same as [.\w]
# () with saparate items in group as separate. ()+ doesnot mean multiple arrayitems
match= re.search('ansi', 'Its a cool worldanshul')
if match:
  print(match.group())
else:
  print('Not Found')

match= re.search('(\d+\s*)+','1 2 3')
if match:
  print(match.group())
else:
  print('not found')

match=re.search('([\w*\.]+)@(\w+)\.(\w+)','ansjdhsj asf%anshul.ankush@yahoo.com%s anshulankush@gmail.com')
if match:
  print(match.group(0))
else:
  print('not found')

match=re.findall('([\w*\.]+)@(\w+)\.(\w+)','ansjdhsj asf%anshul.ankush@yahoo.com%s anshulankush@gmail.com')
if match:
  print(match)
else:
  print('not found')

import shutil


#
#
#
##------------------------MAIN SELECTION INTRO------------------------------

from operator import itemgetter
import os.path

def main():
    global storelist
    global incomelist
    storelist = ['store1', 'store2', 'store3', 'store4', 'store5']
    incomelist = [0.0, 0.0, 0.0, 0.0, 0.0]
    usr_sel = 0
    while (usr_sel != 11):
        print("------------------- \n")
        print("""\n\n  Hello, this is a sale report manager.
        Please select an option: \n
        1- Print the sales
        2- Sort/Print sales High to Low
        3- Sort/Print sales Low to High
        4- Print Highest and Lowest only
        5- Print Total Sales
        6- Print Avg Sales
        7- Enter sales data
        8- Rename Store
        9- Save Sales Data
        10- Load Sales Data
        11- Quit Program
        """)

        usr_sel = int(input("> "))

        if usr_sel ==1:
            print_sales()
        elif usr_sel==2:
            sort_HL()
        elif usr_sel==3:
            sort_LH()
        elif usr_sel==4:
            HL_only()
        elif usr_sel==5:
            total_sales()
        elif usr_sel==6:
            avg_sales()
        elif usr_sel==7:
            input_sales()
        elif usr_sel==8:
            rename_shop()
        elif usr_sel==9:
            save_data()
        elif usr_sel==10:
            temp_store, temp_income = load_data()
            storelist.clear()
            incomelist.clear()
            storelist=temp_store
            incomelist= temp_income

##--------------------------INPUT SALES DATA--------------------------

def input_sales():
    print(" Which shop would you like to input sales data for? \n")

    for i in range(len(storelist)):
        print(f" {i} - {storelist[i]}  ")
   # print(f"2- {storelist[1]}  ")
   # print(f"3- {storelist[2]}  ")
   # print(f"4- {storelist[3]}  ")
   # print(f"5- {storelist[4]}  ")

    print(f"99- New Store  ")

    shop_num = int(input("> "))

    if shop_num == 99:
        shop_num = addshop()
        #shop_num += 1

    shop_num -=1
    print(f"Please input the sales data for {storelist[shop_num]} in dollars.")
    sales_amt = float(input("$ "))

    incomelist[shop_num] = sales_amt

##---------------------------ADDING SHOP----------------------------

def addshop():
    print("------------------- \n")
    i_num = len(storelist)
    #act_num = i_num +1
    storelist.append('Store' + str(i_num+1))
    incomelist.append(0.0)
    return (len(storelist))

##---------------------------RENAME SHOP----------------------------

def rename_shop():
    print("------------------- \n")
    print("What shop would you like to rename?")
    for i, name in enumerate(storelist):
        print(f" {i+1}. {storelist[i]} ")

    s_sel = int(input("> "))
    s_sel -= 1
    new_name= input("New Storename: ")
    storelist[s_sel] = new_name

##--------------------------PRINTING SALES------------------------

def print_sales():
    print("------------------- \n")
    for i in range(len(storelist)):
        print(f" {storelist[i]}      \t ${incomelist[i]} ")

##--------------------------PRINTING High to Low------------------

def sort_HL():
    print("------------------- \n")
    templist=(sorted(zip(storelist, incomelist), key=itemgetter(1), reverse=True))
    for i, entry in enumerate(templist):
        print(f"{i+1}. {templist[i]}")

##--------------------------PRINTING Low to High------------------

def sort_LH():
    print("------------------- \n")
    templist=sorted(zip(storelist, incomelist), key=itemgetter(1))
    for i, entry in enumerate(templist):
        print(f"{i+1}. {templist[i]}")

##--------------------------PRINTING High and Low Only-----------

def HL_only():
    print("------------------- \n")
    templist=sorted(zip(storelist, incomelist), key=itemgetter(1))
    low_store=templist[0]
    high_store=templist[(len(templist)-1)]
    print(f"Lowest Sales: {low_store} \nHighest Sales:{high_store}")

##--------------------------PRINTING Total Sales----------------

def total_sales():
    print("------------------- \n")
    sum_sales=0.0
    for i in range(len(incomelist)):
        sum_sales = sum_sales + incomelist[i]
    print(f"Total Sales Revenue: {sum_sales}")

##--------------------------Average Sales----------------------

def avg_sales():
    print("------------------- \n")
    avg_sales=0.0
    for i in range(len(incomelist)):
        avg_sales = avg_sales + incomelist[i]
    avg_sales = avg_sales / (len(storelist))
    print(f"Average Sales Revenue: {avg_sales}")

##--------------------------Save Data-------------------------

def save_data():
    print("------------------- \n")
    print("What would you like to name the data file?")
    name_sel = input("> ")

    name_sel = (name_sel + ".txt")
    print(name_sel)

    data_src= open(name_sel, 'w')

    t_storelist =[]
    t_incomelist =[]
    t2_incomelist =[]

    t_storelist = ','.join(storelist)
    t_storelist = t_storelist + '\n'

    for i in range(len(incomelist)):
        t_incomelist.append(str(incomelist[i]))

    t2_incomelist = ','.join(t_incomelist)
    t2_incomelist = t2_incomelist + '\n'

    data_src.write(t_storelist)
    data_src.write(t2_incomelist)

    data_src.close()

##--------------------------Load Data-------------------------

def load_data():
    print("------------------- \n")
    file_list = os.listdir()
    for item in file_list:
        print(item)    #list of everything in current directory

    print("What is the name the data file?")
    name_sel = input("> ")
    if os.path.isfile(name_sel): #test to see if file exists
        data_src = open(name_sel, 'r')
    else:
        return

    t_storelist = data_src.readline()
    t_storelist = t_storelist.rstrip()
    storelist = t_storelist.split(",")

    t_incomelist = data_src.readline()
    t_incomelist = t_incomelist.rstrip()
    incomelist = t_incomelist.split(",")

    data_src.close()

    return(storelist, incomelist)

##--------------------------Gen Body-------------------------
# error code

main()


# Name: John Kelly
# ID: C00176932

from flask import Flask, render_template, request, session
from operator import itemgetter
from collections import Counter
import pickle
import random
import time
import os.path
import parse_words

app = Flask(__name__)

@app.route('/')
def start_app():
    if os.path.isfile('pickle/source_words.pickle'):
        with open('pickle/source_words.pickle', 'rb') as ph:
            source_words = pickle.load(ph)
    else:
        parse_words.create_selected_word_dictionary()
    session.setdefault('selected_word', '')
    session.setdefault('current_user', {})
    session['selected_word'] = random.choice(source_words)
    session['current_user']['start_time'] = time.time() * 1000
    return render_template('entries.html',
                                    title=session['selected_word'] + ' | Word Game')

@app.route('/checkscore', methods=['POST'])
def process_the_data():
    session['current_user']['end_time'] = time.time() * 1000
    session.setdefault('user_input', {})
    session['user_input'] = request.form.to_dict()
    valid_word = validate_input_duplicates(session['user_input'])

    if valid_word:
        valid_word, session['user_input'] = validate_input(session['user_input'], session['selected_word'])

    if valid_word is False:
        return render_template('wrong_results.html',
                                        sourceWord=session['selected_word'],
                                        words=session['user_input'])

    session['current_user']['total_time'] = session['current_user']['end_time'] -session['current_user']['start_time']
    return render_template('right_answer.html')

@app.route('/topscorerslist', methods=['POST'])
def join_the_scoreboard():
    user_input = request.form.to_dict()
    if os.path.isfile('pickle/top_scorers_list.pickle'):
        with open('pickle/top_scorers_list.pickle', 'rb') as ph:
            top_scorers_list = pickle.load(ph)
    else:
        top_scorers_list = []
    session['current_user']['name'] = user_input['name']
    session['current_user']['display_time'] = calculate_display_time(session['current_user']['total_time'])
    top_scorers_list.append(session['current_user'])
    with open('pickle/top_scorers_list.pickle', 'wb') as ph:
        pickle.dump(top_scorers_list, ph)
    sorted_list = sorted(top_scorers_list, key=itemgetter('total_time', 'start_time'), reverse=False)

    return render_template('top_ten.html',
                                    words=session['user_input'],
                                    selected_word=session['selected_word'],
                                    top_ten_scorers=sorted_list[:10],
                                    position=sorted_list.index(session['current_user']) + 1)

def validate_input(user_input, selected_word):
    valid_word = True
    for user_input_key, user_input_value in user_input.items():
        if validate_input_length(user_input_value) and validate_input_characters(user_input_value.lower(), selected_word) and validate_input_in_dictionary(user_input_value) and user_input_value != selected_word:
            user_input[user_input_key] = {
                'word': user_input_value,
                'color': 'green'
            }
        else:
            if ' ' in user_input_value:
                user_input[user_input_key] = {
                    'word': "Spaces aren't allowed",
                    'color': 'orange'
                }
            else:
                user_input[user_input_key] = {
                    'word': user_input_value,
                    'color': 'red'
                }
            valid_word = False

    return valid_word, user_input

def validate_input_length(word):
    return len(word) > 2

def validate_input_characters(word, selected_word):
    valid_word = True
    s = Counter(selected_word)
    w = Counter(word)
    for letter in word:
        if letter not in selected_word or w[letter] > s[letter]:
            valid_word = False
    return valid_word

def validate_input_duplicates(all_values):
    return len(set(all_values)) == 7

def validate_input_in_dictionary(word):
    if os.path.isfile('pickle/dictionary.pickle'):
        with open('pickle/dictionary.pickle', 'rb') as ph:
            dictionary = pickle.load(ph)
    else:
        parse_words.create_dictionary()
    return word in dictionary

def calculate_display_time(milliseconds):
    seconds = int((session['current_user']['total_time'] / 1000) % 60)
    minutes = int((session['current_user']['total_time'] / (1000*60)) % 60)
    hours   = int((session['current_user']['total_time'] / (1000*60*60)) % 24)
    return str(hours) + ':' + str(minutes) + ':' + str(seconds)

if __name__ == '__main__':
    app.config['SECRET_KEY'] = 'THISISMYSECRETKEY'
    app.run(debug=True)


import json
import logging
import os
import re
import sys
import time

import requests

def get_logger(name):
    log_file = os.getenv('DISKU_LOG_FILE')
    if log_file:
        log_handler = logging.FileHandler(log_file)
    else:
        log_handler = logging.StreamHandler(sys.stdout)

    log_handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
        '%Y-%m-%d %H:%M:%S %Z'
    ))

    logger = logging.getLogger(name)
    logger.setLevel(os.getenv('DISKU_LOG_LEVEL', 'ERROR'))
    logger.addHandler(log_handler)
    return logger

logger = get_logger(__name__)
logger.debug('DISKU module loaded')

class CaseInsensitiveDict(dict):
    def __repr__(self):
        return 'CaseInsensitiveDict(%r)' % super().__repr__()

    def _find_key(self, key):
        # XXX: iterate over self.keys() is slow
        lkey = key.lower()

        for k in self.keys():
            if k.lower() == lkey:
                return k

        return key

    def __lower_keys__(self):
        # FIXME: handle collisions
        return [k.lower() for k in self.keys()]

    def __contains__(self, key):
        # XXX: performance issue
        return self._find_key(key) in self.__lower_keys__()

    def __getitem__(self, key):
        return super().__getitem__(self._find_key(key))

    def __setitem__(self, key, val):
        return super().__setitem__(self._find_key(key), val)

    def __delitem__(self, key):
        return super().__delitem__(self._find_key(key))

    def get(self, key, defval=None):
        return super().get(self._find_key(key), defval)

class ConfigProxy:
    # TODO: it's read-only, what about set() and __setitem__?
    # consider implement full MutableMapping iter
    def __init__(self, src, namespace):
        # XXX: namespace will become case-insensitive too
        self.src = CaseInsensitiveDict(src)
        self.namespace = namespace

    def key(self, k):
        return '%s.%s' % (self.namespace, k)

    def __contains__(self, key):
        return self.key(k) in self.src

    def __getitem__(self, key):
        return self.src[self.key(key)]

    def get(self, key, defval=None):
        return self.src.get(self.key(key), defval)

def _find_subclass(parent, name):
    name = (name + parent.__name__).lower()

    for klass in parent.__subclasses__():
        if klass.__name__.lower() == name:
            return klass
        raise KeyError('Can not find subclass of %s (name: %s)' % (parent.__name__, name))

class BinaryOperator:
    def __init__(self, op):
        self.op = op
        # FIXME: potential code injection vulnerability
        # should we make a whitelist of allowed operators?
        # *current usage is not vulnerable
        self.f = eval('lambda l, r: l %s r' % op)

    def __call__(self, l, r):
        return self.f(l, r)

    def __repr__(self):
        return 'BinaryOperator(%r)' % self.op

def parse_size_string(s, suffixes='KMGTPEZY'):
    suffix_idx = suffixes.find(s[-1].upper())
    if suffix_idx == -1:
        return int(s)

    return int(s[:-1]) * (1024 ** (suffix_idx + 1))

def parse_time_interval(s):
    suffixes = {
        's': 1,
        'm': 60,
        'h': 60*60,
        'd': 60*60*24,
    }

    try:
        return int(s)
    except ValueError:
        pass

    re_obj = r'(?P<val>[1-9]\d*)(?P<unit>[smhd])'

    if not re.fullmatch('(?:(?:{})+|\s)+'.format(re_obj), s):
        raise ValueError('Invalid time value', s)

    t = 0
    for m in re.finditer(re_obj, s):
        val, unit = m.groups()
        t += int(val) * suffixes[unit]

    return t

class AlertCheck:
    def __init__(self, conditions):
        self.conditions = []
        if not self.parse(conditions):
            raise ValueError('Invalid condition(s): %r' % conditions)

    def parse(self, conditions):
        def parse_val(v):
            if v[-1] == '%':
                return int(v[:-1]) / 100.0
            return parse_size_string(v)

        re_cmp = re.compile(
            r'(?P<var>\w+)'       # variable name
            r'\s*'                # spaces are allowed
            r'(?P<op>[<>]=?|==)'  # compare operator
            r'\s*'                # spaces are allowed
            r'(?P<val>'           # begin value group
            r'100%|0%|[1-9]\d?%|' # percentage
            r'[1-9]\d*[KMGTP]?'   # size
            r')'                  # end value group
            )

        for cond in re.split(r'\s*,\s*', conditions):
            m = re.fullmatch(re_cmp, cond)
            if not m:
                logger.error('Can not parse condition: %s', cond)
                return False

            raw = m.group(0)
            var, op, val = m.groups()
            self.conditions.append((var, BinaryOperator(op), parse_val(val), raw))
            logger.debug('Parsed condition: %s %s %s', var, op, val)

        return True

    @staticmethod
    def validate_params(disk_usage):
        return 'used' in disk_usage and \
               'free' in disk_usage and \
               'total' in disk_usage

    def __call__(self, disk_usage):
        du = CaseInsensitiveDict(disk_usage)
        if not self.validate_params(du):
            raise ValueError('Invalid disk usage status object')
        du['used_p'] = du['used'] / du['total']
        du['free_p'] = du['free'] / du['total']

        for var, op, val, raw in self.conditions:
            if isinstance(val, float):
                var += '_p'

            if op(du.get(var), val):
                return raw

        return False

class AlertChannel:
    '''
    Abstraction class for alert channels
    '''
    _channel_cache = {}

    @classmethod
    def load(cls, config):
        name = config['disku.alert_channel']
        cached = cls._channel_cache.get(name)
        if cached:
            return cached
        try:
            klass = _find_subclass(cls, name)
        except KeyError:
            logger.error('Can not find AlertChannel sublcass: %s', name)
            raise

        instance = klass(ConfigProxy(config, name.lower()))
        instance.prepare()
        return cls._channel_cache.setdefault(name, instance)

    def __init__(self, config):
        self.config = config

    def prepare(self):
        pass

    def fire(self, message):
        raise NotImplemented()

class WebhookAlertChannel(AlertChannel):
    '''
    Webhook alert channel provider, it's made for Slack/Mattermost compatible
    webhook interface
    '''

    def prepare(self):
        try:
            self.mixin = json.loads(self.config.get('mixin', '{}'))
            logger.info('mixin: %r', self.mixin)
        except json.decoder.JSONDecodeError:
            self.mixin = {}

    def fire(self, message):
        data = dict(self.mixin)
        data.update({'text': message})
        logger.debug('webhook sent message: %r', data)

        try:
            resp = requests.post(self.config['url'], json=data)
            logger.debug('response: %r', resp)
            return resp.status_code == 200
        except Exception as e:
            logger.exception('Error during sending http request: %r', e)
            return False

class AlertBuffer:
    def __init__(self, interval, fire):
        self.interval = interval
        self.next_time = 0
        self.buffer = {}
        self.fire = fire

    def push(self, identifier, data):
        self.buffer[identifier] = data

        if time.time() >= self.next_time:
            logger.info('Flushing buffer')
            self.fire(self.buffer)
            self.buffer = {}
            self.next_time = time.time() + self.interval

def test():
    try:
        checker = AlertCheck('FREE == 100G, FREE   <\t 5G, USED     >10G, USED>95%')
        logger.info('Success!')
    except ValueError as e:
        logger.exception('Can not parse condition, error: %r', e)

    for c in checker.conditions:
        logger.info(c)

    GB = 2 ** 30

    logger.info(checker({ 'total': 100 * GB, 'used': 96 * GB, 'free': 4 * GB }))
    logger.info(checker({ 'total': 100 * GB, 'used': 90 * GB, 'free': 10 * GB }))
    logger.info(checker({ 'total': 100 * GB, 'used': 9 * GB, 'free': 91 * GB }))
    logger.info(checker({ 'total': 100 * GB, 'used': 0 * GB, 'free': 100 * GB }))

    for t in '5 10s 10m 2h 1d 24h9d 1s1m1h 1s2m3h4d'.split():
        logger.info('%-10s %d', t, parse_time_interval(t))

if __name__ == '__main__':
    test()


import argparse
import time
import absim.world as world

from absim.bayesian_agent import BayesianAgent
from absim.prob_agent import ProbAgent
from absim.prox_agent import ProxAgent
from absim.prob_prox_agent import ProbProxAgent
from absim.salesman_agent import SalesmanAgent

agent_lookup = {
    "prob" : ProbAgent,
    "prox" : ProxAgent,
    "prob_prox" : ProbProxAgent,
    "salesman" : SalesmanAgent,
    "bayes" : BayesianAgent
}

def parse_world(fname):
    """Parses a scavenger hunt world from a datfile.

    Parameters
    ----------
    fname : str
        source file name

    Returns
    -------
    world.World
        finalized scavenger hunt world
    list of str
        scavenger hunt
    str
        start location name
    """
    src = open(fname, "r")
    sec = None
    start_loc = None
    conns = []  # 3-tuples (from, to, cost)
    nodes = {}  # User-specified loc names -> integer IDs
    node_count = 0
    distrs = []
    hunt = []

    for line in src.readlines():
        # Blank lines and comments
        line = line.strip()
        if len(line) == 0 or line[0] == '#':
            continue

        # Section header line
        if line[0] == '[':
            sec = line[1:line.find(']')]
            continue

        # Map section
        if sec == "map":
            args = line.split()
            assert len(args) == 3
            n_from, n_to = args[0], args[1]

            # Parse for starting location
            if '*' in n_from:
                n_from = n_from.replace('*', '')
                if start_loc is None:
                    start_loc = n_from
            elif '*' in n_to:
                n_to = n_to.replace('*', '')
                if start_loc is None:
                    start_loc = n_to

            cost = float(args[2])
            if n_from not in nodes:
                nodes[n_from] = node_count
                node_count += 1
            if n_to not in nodes:
                nodes[n_to] = node_count
                node_count += 1
            conns.append((n_from, n_to, cost))
        # Distribution section
        elif sec == "distr":
            args = line.split()
            assert len(args) > 2
            obj = args[0]
            events = []
            ind = 1

            if obj not in hunt:
                hunt.append(obj)

            while ind < len(args):
                locs = []
                prob_ind = ind
                while args[prob_ind] in nodes:
                    locs.append(nodes[args[prob_ind]])
                    prob_ind += 1
                prob_arg = args[prob_ind]
                if '/' in prob_arg:
                    frac = prob_arg.split('/')
                    prob = float(frac[0]) / float(frac[1])
                else:
                    prob = float(prob_arg)
                events.append(world.Event(obj, locs, prob))
                ind = prob_ind + 1

            distrs.append(world.Distribution(events))
        else:
            assert False

    src.close()

    # Build graph
    g = world.Graph(node_count)
    for conn in conns:
        id_from, id_to, cost = nodes[conn[0]], nodes[conn[1]], conn[2]
        g.connect(id_from, id_to, cost)
        g.name_ids[conn[0]] = id_from
        g.name_ids[conn[1]] = id_to
    g.finalize()

    # Build world
    w = world.World(g, distrs)
    w.finalize()

    return w, hunt, start_loc

def simulate(world, hunt, start_loc, args):
    """Runs one or more scavenger hunts.

    Parameters
    ----------
    world : world.World
        scavenger hunt world
    hunt : list of str
        objects to find
    start_loc : str
        starting node name
    args : Namespace
        cmdline args parsed by argparse

    Returns
    -------
    float
        average distance traveled across all trials
    """
    total_distance = 0
    total_runtime = 0
    trials = args.trials
    agent = agent_lookup[args.agent](world, hunt, world.node_id(start_loc))
    agent.epoch()

    if not args.suppress:
        print(">>> Running %s trials of %s" % \
            (trials, agent.__class__.__name__))

    for i in range(trials):
        t_start, t_end = None, None
        world.populate()
        agent.setup()
        t_start = time.time()
        while not agent.done():
            agent.objs_at_loc = world.objs_at(agent.loc)
            agent.run()
        t_end = time.time()
        total_distance += agent.travel_distance
        total_runtime += t_end - t_start
        if not args.suppress:
            print("Progress: {:2.1%}".format(i / trials), end="\r")

    avg_distance = total_distance / trials
    avg_runtime = total_runtime / trials
    if not args.suppress:
        print("Average distance: %s" % avg_distance)
        if args.runtime:
            print("Average runtime: %ss" % avg_runtime)

    return avg_distance

if __name__ == "__main__":
    # Parse cmdline args
    ap = argparse.ArgumentParser()
    ap.add_argument("datfile", help="scavenger hunt world file", type=str)
    ap.add_argument("agent", help="algorithm to run", type=str)
    ap.add_argument("-t", "--trials", help="number of trials to run", type=int,
        default=1)
    ap.add_argument("-s", "--suppress", help="silence output",
        action='store_true')
    ap.add_argument("-r", "--runtime", help="show average runtime",
        action='store_true')
    args = ap.parse_args()

    # Generate scavenger hunt problem and simulate
    world, hunt, start_loc = parse_world(args.datfile)
    simulate(world, hunt, start_loc, args)


from app.control import modes as robotControl
from app.test.fake.bot import motorPairFake

class TestControlBasic:

    def test_initialization(self):
        wheels = motorPairFake.MotorPair()
        self.control = robotControl.RobotControl(wheels)
        assert(self.control is not None)


import cv2
import matplotlib.pyplot as plt
import os
from glob import glob
import numpy as np
import argparse

parser = argparse.ArgumentParser()
parser.add_argument( "--root",   type=str,   default="./atten_bear_visualization/",  help="down or middle or up" )
parser.add_argument( "--num_sample", type=int,   default=3,  help="number of samples generated in the ldm model" )
parser.add_argument( "--num_level", type=int,   default=4,  help="(8, 16, 32, 64)" )
parser.add_argument( "--num_att_comp", type=int,   default=3,  help="down, up, down&up =3" )
parser.add_argument( "--num_att_maps", type=int,   default=10,  help="number of attnetion maps generated in the model." )
parser.add_argument( "--token_idx", type=int,   default=1,  help="number of samples generated in the ldm model" )
args = parser.parse_args()

root = args.root
num_sample = args.num_sample
num_level = args.num_level    # (8, 16, 32, 64)
num_att_comp = args.num_att_comp #level= 00,22,02
num_att_maps = args.num_att_maps

imgs = sorted(glob( os.path.join(root, "*.png") ))#os.listdir(root)

attmap_list = []
bundle_list = []

""" 1. bundle image 읽어오는 과정 """
cur_idx = num_sample*num_att_maps #i*num_att_maps + k +1
for m in range(cur_idx, cur_idx+num_att_maps):
    if m == cur_idx:
        h,w,c = cv2.imread(imgs[m]).shape
        white_img = np.ones((h, h*num_sample, 3))*255

    bundle_list.append( cv2.resize(cv2.imread(imgs[m]), (h*num_sample,h)) ) # (516, 1548, 3)

""" 2. attention map 읽어오는 과정 """
for i in range(num_sample): # num_sample
    for k in range(num_att_maps): # num attention maps in each sample
            attmap_list.append(  cv2.resize(cv2.imread(imgs[i*num_att_maps + k]), (h,h))  )

""" 3. make bundle composition """
last_bundle = None
for mm in range(num_level):
    if mm==0:
        init_bundle = np.concatenate( ( bundle_list[mm], white_img, white_img), axis=1 )
    else:
        cur_idx = mm*num_att_comp-(num_sample-1)
        cur_bundle = np.concatenate( bundle_list[ cur_idx : cur_idx+num_att_comp ], axis=0 ) # down, downup, up
        if last_bundle is None:
            last_bundle = cur_bundle
        else:
            last_bundle = np.concatenate( (last_bundle, cur_bundle), axis=1 )
last_bundle = np.concatenate( (init_bundle, last_bundle), axis=0 )
cv2.imwrite( os.path.join(root, "./last_bundle_imgs_idx:{0}.png".format(args.token_idx)  ), last_bundle)

""" 4. make attenmap composition
0: 0 10 20
1: 1 11 21/ 2 12 22 /3 13 23
2: 4 14 24 /5 15 25 /6 16 26
....
"""
last_bundle = None
for r in range(num_level): # 4
    cur_att_map_list = []
    if r ==0:
        for i in range(num_sample): # 3
            cur_attmap = attmap_list[i*num_att_maps]
            cur_att_map_list.append(cur_attmap)
        cur_att_map_list = np.concatenate(cur_att_map_list, axis=1)

        white_img = np.ones((h, h*num_sample*2, 3))*255
        init_bundle = np.concatenate( (cur_att_map_list, white_img), axis=1 )
    else:
        cur_idx = r*(num_level-1)-(num_sample-1) #-2
        for i in range(num_sample): # 3
            cur_subatt_map_list = []
            for j in range(num_sample):
                cur_attmap  = attmap_list[i+cur_idx + j*num_att_maps]
                cur_subatt_map_list.append(cur_attmap)
            cur_att_map_list.append( np.concatenate(cur_subatt_map_list, axis=1) )

        cur_bundle = np.concatenate( cur_att_map_list, axis=0 )#.reshape(h*num_sample, h*num_sample, 3)

        if last_bundle is None:
            last_bundle = cur_bundle
        else:
            last_bundle = np.concatenate( (last_bundle, cur_bundle), axis=1 )
last_bundle = np.concatenate( (init_bundle, last_bundle), axis=0 )
cv2.imwrite( os.path.join(root, "./last_bundle_attnmaps_idx:{0}.png".format(args.token_idx)), last_bundle)


import numpy             as np
import mediapipe         as mp
import matplotlib.pyplot as plt

from utils import (
    poseDetector, poseUtils
)

def main():

    fileName = 'data/Question 19 - 8AE44065-F2F5-4D85-9A96-F69471837F7A.jpeg'
    image    = poseUtils.getImage(fileName)

    pDetector      = poseDetector.PoseDetector()
    results        = pDetector.getResults( image )
    annotatedImage = poseUtils.generateAnnotatedImage( image, results )

    print(results.segmentation_mask)
    print(results.segmentation_mask.shape)

    plt.figure()
    plt.imshow(image)

    plt.figure()
    plt.imshow(annotatedImage)
    plt.savefig('results/temp.png')

    return

if __name__ == '__main__':
    main()


totalentrevistado = cont_maior_18 = cont_M = cont_mulher_20 = 0
while True:
    idade = int(input('Idade: '))
    sexo = ' '
    while sexo not in 'MF':
        sexo = str(input('Sexo: [M/F] ')).upper()
    totalentrevistado += 1
    if idade > 18:
        cont_maior_18 += 1
    if sexo == 'M':
        cont_M += 1
    if idade < 20 and sexo == 'F':
        cont_mulher_20 += 1

    pergunta = str(input('Deseja continuar? [S/N] ')).upper()
    if pergunta == 'N':
        break
print(f'Total de pessoas entrevistadas: {totalentrevistado}')
print(f'Total de pessoas com mais de 18 anos: {cont_maior_18}')
print(f'Total de homens cadastrados: {cont_M}')
print(f'Total de mulheres com menos de 20 anos: {cont_mulher_20}')


from struct import pack, unpack
import logging

from handleclient import common
from handleclient import utils
from handleclient import message
from handleclient import handlevalue

from handleclient.handlevalue import HandleValue
from handleclient.message import Message, Envelope, Header, Body, Credential

logger = logging.getLogger(__name__)
logger.setLevel(common.LOG_LEVEL)
logger.addHandler(common.ch)

class ErrorResponseBody(Body):
    def __init__(self):
        self.errMsg = ""

    @classmethod
    def parse(self, body):
        assert isinstance(body, bytes)
        self.errMsg = utils.uba(body)
        assert 4 + len(self.errMsg) == len(body)

    def __str__(self):
        res = ""
        res += f"{self.errMsg}"
        return res

class ReferralResponseBody(Body):
    """https://tools.ietf.org/html/rfc3652#section-3.4
    """
    def __init__(self):
        self.valueList = []

    @classmethod
    def parse(self, body):
        assert isinstance(body, bytes)
        logger.debug(body[:])

        offset = 0
        self.valueCnt = utils.u32(body[offset:])
        offset += 4
        for _i in range(self.valueCnt):
            pass

    # def __str__(self):
    #     res = ""
    #     res += f"{self.errMsg}\n"
    #     return res

class SomeResponseBody(Body):
    def __init__(self):
        pass

    @classmethod
    def parse(self, body):
        assert isinstance(body, bytes)
        logger.warning("todo")

    def __str__(self):
        res = ""
        res += "unimplemented"
        return res


# Title: 우수 마을
# Link: https://www.acmicpc.net/problem/1949

import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)

read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))

def get_max(vil: int, select: int, dp: list, edges: defaultdict, popls: list, p_node: int):
    if dp[vil][select] != -1:
        return dp[vil][select]

    ans = popls[vil] if select else 0

    for child in edges[vil]:
        if child == p_node:
            continue
        if select:
            ans += get_max(child, 0, dp, edges, popls, vil)
        else:
            ans += max(get_max(child, 0, dp, edges, popls, vil), get_max(child, 1, dp, edges, popls, vil))

    dp[vil][select] = ans
    return ans

def solution(n: int, popls: list, edges: defaultdict):
    dp = [[-1 for _ in range(2)] for _ in range(n+1)]
    return max(get_max(1, 0, dp, edges, popls, 0), get_max(1, 1, dp, edges, popls, 0))

def main():
    n = read_single_int()
    popls = [0] + read_list_int()
    edges = defaultdict(lambda: [])
    for _ in range(n-1):
        a, b = read_list_int()
        edges[a].append(b)
        edges[b].append(a)
    print(solution(n, popls, edges))

if __name__ == '__main__':
    main()


import ply.lex as lex
from ply.lex import TOKEN

class Lexer:
    tokens = (
        "WORD",
        "APOSTROPH",
        "NEWLINE",
        "OTHERS",
    )

    large_alpha = "[ΑἈἌᾌἊᾊἎᾎᾈἉἍᾍἋᾋᾋἏᾉΆᾺᾼ]"
    large_epsilon = "[ΕἘἜἚἙἝἛΈῈ]"
    large_eta = "[ΗἨἬᾜἪᾚἮᾞᾘἩἭᾝἫᾛᾛἯᾙΉῊῌ]"
    large_iota = "[ΙἸἼἺἾἹἽἻἿΊῚΪ]"
    large_omicron = "[ΟὈὌὊὉὍὋΌῸ]"
    large_upsilon = "[ΥὙὝὛὟΎῪΫ]"
    large_omega = "[ΩὨὬᾬὪᾪὮᾮᾨὩὭᾭὫᾫᾫὯᾩΏῺῼ]"
    large_rho = "[ΡῬ]"
    large_consonant = "[ΒΓΔΖΘΚΛΜΝΞΠΣΤΦΧΨ]"

    small_alpha = "[αἀἄᾄἂᾂἆᾆᾀἁἅᾅἃᾃᾃἇᾁάᾴὰᾲᾶᾷᾳ]"
    small_epsilon = "[εἐἔἒἑἕἓέὲ]"
    small_eta = "[ηἠἤᾔἢᾒἦᾖᾐἡἥᾕἣᾓᾓἧᾑήῄὴῂῆῇῃ]"
    small_iota = "[ιἰἴἲἶἱἵἳἷίὶῖϊΐῒῗ]"
    small_omicron = "[οὀὄὂὁὅὃόὸ]"
    small_upsilon = "[υὐὔὒὖὑὕὓὗύὺῦϋΰῢῧ]"
    small_omega = "[ωὠὤᾤὢᾢὦᾦᾠὡὥᾥὣᾣᾣὧᾡώῴὼῲῶῷῳ]"
    small_rho = "[ρῤῥ]"
    small_consonant = "[βγδζθκλμνξπσςτφχψ]"

    alphabet = "(" + large_alpha + \
                "|" + large_epsilon + \
                "|" + large_eta + \
                "|" + large_iota + \
                "|" + large_omicron + \
                "|" + large_upsilon + \
                "|" + large_omega + \
                "|" + large_rho + \
                "|" + large_consonant + \
                "|" + small_alpha + \
                "|" + small_epsilon + \
                "|" + small_eta + \
                "|" + small_iota + \
                "|" + small_omicron + \
                "|" + small_upsilon + \
                "|" + small_omega + \
                "|" + small_rho + \
                "|" + small_consonant + ")"

    apostroph = "'"

    word = alphabet + "+" \
            + "(" + apostroph + alphabet + "*" + ")?"

    @TOKEN(word)
    def t_WORD(self, t):
        return t

    def t_NEWLINE(self, t):
        "\\r?\\n"
        pass

    def t_OTHERS(self, t):
        "."
        pass

    def t_error(self, t):
        pass

    def __init__(self):
        self.lexer = None

    def build(self, **kwargs):
        self.lexer = lex.lex(module=self, **kwargs)

    def test(self, data):
        self.lexer.input(data)
        while True:
             tok = self.lexer.token()
             if not tok:
                 break
             print(tok)

if __name__ == "__main__":
    import sys
    lexer = Lexer()
    lexer.build()
    lexer.test(sys.argv[1])


# 1293. Shortest Path in a Grid with Obstacles Elimination

# https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
# https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/451787/Python-O(m*n*k)-BFS-Solution-with-Explanation

class Solution:
    def shortestPath(self, grid: List[List[int]], k: int) -> int:
        # Store all the state
        m, n = len(grid), len(grid[0])
        queue = deque([(0, 0, k, 0)])
        visited = set([(0, 0, k)])

        if k >= (m + n - 2 - 1):
            return m + n - 2

        while queue:
            x, y, kk, steps = queue.popleft()
            for i, j in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                xx, yy = x + i, y + j
                if not (0 <= xx < m and 0 <= yy < n):
                    continue
                if grid[xx][yy] and kk > 0 and (xx, yy, kk - 1) not in visited:
                    visited.add((xx, yy, kk - 1))
                    queue.append((xx, yy, kk - 1, steps + 1))
                if not grid[xx][yy] and (xx, yy, kk) not in visited:
                    if xx == m - 1 and yy ==  n - 1:
                        return steps + 1
                    visited.add((xx, yy, kk))
                    queue.append((xx, yy, kk, steps + 1))
        return - 1

        # My method, it should be correct, but TLE
        def dfs(x, y, k, steps):
            nonlocal m, n, result, min_pos
            if result == min_pos:
                return
            if (not (0 <= x < m and 0 <= y < n)) or visited[x][y] or k < 0:
                return
            if grid[x][y]:
                if k == 0:
                    return
                k -= 1
            if x == m - 1 and y ==  n - 1:
                result = min(result, steps)
                return
            visited[x][y] = True
            for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                dfs(x + i, y + j, k, steps + 1)
            visited[x][y] = False
        m, n = len(grid), len(grid[0])
        min_pos = m + n - 2
        result = 10000
        visited = [[False] * n for _ in range(m)]

        dfs(0, 0, k, 0)
        return result if result <= 10000 else -1


import json
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    age = Column(Integer)
    income = Column(Integer)
    physiological_need = Column(String)
    safety_need = Column(String)
    love_and_belonging_need = Column(String)
    esteem_need = Column(String)
    self_actualization_need = Column(String)

def create_user(db_file: str, age: int, income: int, physiological_need: str, safety_need: str, love_and_belonging_need: str, esteem_need: str, self_actualization_need: str):
    engine = create_engine(f'sqlite:///{db_file}')
    Base.metadata.create_all(engine)

    Session = sessionmaker(bind=engine)
    session = Session()

    new_user = User(age=age,
                    income=income,
                    physiological_need=physiological_need,
                    safety_need=safety_need,
                    love_and_belonging_need=love_and_belonging_need,
                    esteem_need=esteem_need,
                    self_actualization_need=self_actualization_need)

    session.add(new_user)
    session.commit()

    return new_user.id

def update_user(db_file="user.db", user_id="username", age=None, income=None, physiological_need=None, safety_need=None, love_and_belonging_need=None, esteem_need=None, self_actualization_need=None):
    engine = create_engine(f'sqlite:///{db_file}')
    Session = sessionmaker(bind=engine)
    session = Session()

    user = session.query(User).filter_by(id=user_id).first()
    if user is None:
        return "FAILURE"

    if age is not None:
        user.age = age
    if income is not None:
        user.income = income
    if physiological_need is not None:
        user.physiological_need = physiological_need
    if safety_need is not None:
        user.safety_need = safety_need
    if love_and_belonging_need is not None:
        user.love_and_belonging_need = love_and_belonging_need
    if esteem_need is not None:
        user.esteem_need = esteem_need
    if self_actualization_need is not None:
        user.self_actualization_need = self_actualization_need

    session.commit()

    return "SUCCESS"

def get_user(db_file: str, user_id: int):
    engine = create_engine(f'sqlite:///{db_file}')
    Session = sessionmaker(bind=engine)
    session = Session()

    user = session.query(User).filter_by(id=user_id).first()

    # Convert user object to dictionary
    user_dict = {column.name: getattr(user, column.name) for column in user.__table__.columns}

    return user_dict


"""
Utilities for testing
"""
from collections import namedtuple

import numpy as np

from .callbacks import ConvergenceCallback
from .cpd import GaussianCPD
from .irt import BayesNetLearner
from .node import Node

EPSILON = 1e-3
NUM_TRIALS = 3

NUM_ITEMS = 50
NUM_INSTR_ITEMS = 0
NUM_LATENT = 1
NUM_CHOICES = 2
NUM_RESPONSES = 500
NUM_STUDENTS = 20
PROB_CORRECT = 0.5

THETA_MU = 0.0
THETA_SIGMA = 1.0

NONOFFSET_COEFF_SHAPE_GEN = 100.0
NONOFFSET_COEFF_SCALE_GEN = 0.01

NONOFFSET_COEFF_SHAPE = 2.0
NONOFFSET_COEFF_SCALE = 0.5

OFFSET_COEFF_MU = 0.0
OFFSET_COEFF_SIGMA = 1.0

INSTR_COEFF_MU = 0.05
INSTR_COEFF_SIGMA = 0.025

THETA_OFFSETS_SIGMA = 0.05

ResponseData = namedtuple('ResponseData', ['correct', 'student_idx', 'item_idx'])

def log_norm_pdf(x, mu=0.0, var=1.0):
    """ Evaluate the log normal pdf.
    :param np.ndarray|float x: point at which to evaluate the log norm pdf
    :param np.ndarray|float mu: mean of the normal distribution
    :param np.ndarray|float var: variance of the normal distribution.
    """
    return -0.5 * np.log(2. * np.pi * var) - 0.5 / var * (x - mu) ** 2

FINITE_DIFF_EPSILON = 1e-6
ALMOST_EQUAL_EPSILON = 1e-4

def finite_diff_grad(x, func, epsilon=FINITE_DIFF_EPSILON):
    """ Approximate the derivative of a function using finite difference.
     :param np.ndarray x: point at which to evaluate derivative
     :param function func: function with which to take finite differences.
     """
    fwd_x = np.copy(x)
    bwd_x = np.copy(x)
    fwd_xx = fwd_x.ravel()
    bwd_xx = bwd_x.ravel()
    y = np.zeros(x.shape)
    yy = y.ravel()
    for i in xrange(x.size):
        fwd_xx[i] += epsilon
        bwd_xx[i] -= epsilon
        yy[i] = (func(fwd_x) - func(bwd_x)) / 2.0 / epsilon
        fwd_xx[i] -= epsilon
        bwd_xx[i] += epsilon
    return y

def finite_diff_hessian(x, grad, epsilon=FINITE_DIFF_EPSILON):
    """ Approximate the Hessian of a function using finite difference in the partial gradient.
    :param np.ndarray x: point at which to evaluate derivative
    :param function grad: function that returns the gradient
    """
    fwd_x = np.copy(x)
    bwd_x = np.copy(x)
    fwd_xx = fwd_x.ravel()
    bwd_xx = bwd_x.ravel()
    y = np.zeros((x.size, x.size))
    for i in xrange(x.size):
        for j in xrange(x.size):
            fwd_xx[i] += epsilon
            bwd_xx[i] -= epsilon
            y[i, j] = (grad(fwd_x).ravel()[j] - grad(bwd_x).ravel()[j]) / 2.0 / epsilon
            fwd_xx[i] -= epsilon
            bwd_xx[i] += epsilon
    return y

def finite_diff_hessian_diag(x, grad, epsilon=FINITE_DIFF_EPSILON):
    """ Approximate the diagonal of the Hessian of a function using finite difference in the
    partial gradient.
    :param np.ndarray x: point at which to evaluate derivative
    :param function grad: function that returns the gradient
    """
    fwd_x = np.copy(x)
    bwd_x = np.copy(x)
    fwd_xx = fwd_x.ravel()
    bwd_xx = bwd_x.ravel()
    y = np.zeros(x.shape)
    yy = y.ravel()
    for i in xrange(x.size):
        fwd_xx[i] += epsilon
        bwd_xx[i] -= epsilon
        yy[i] = (grad(fwd_x).ravel()[i] - grad(bwd_x).ravel()[i]) / 2.0 / epsilon
        fwd_xx[i] -= epsilon
        bwd_xx[i] += epsilon
    return y

def generate_data(num_students=NUM_STUDENTS,
                  num_items=NUM_ITEMS,
                  num_responses=NUM_RESPONSES,
                  prob_correct=PROB_CORRECT):
    """ Simulate student response data (independently of any parameters).

    :param int num_students: Number of unique student ids.
    :param int num_items: number of assessment items
    :param int num_responses: number of responses to generate
    :param float prob_correct: probability of correct (probability of choosing first choice when
                               num_choices > 1; probability of other choices are all equal)
    :return: the response data
    :rtype: ResponseData
    """
    correct = np.random.rand(num_responses) < prob_correct
    num_responses_per_student, remainder = divmod(num_responses, num_students)
    unique_student_ids = range(num_students)
    student_idx = [reg_id for reg_id in unique_student_ids for _ in
                   range(num_responses_per_student)]
    # If num_responses can't be perfectly divided into students, add the remaining responses
    # to the last student id:
    student_idx.extend([unique_student_ids[-1]] * remainder)
    student_idx = np.array(student_idx)

    item_idx = np.random.random_integers(low=0, high=num_items-1, size=num_responses)
    np.random.shuffle(student_idx)

    return ResponseData(correct, student_idx, item_idx)

class MockNode(Node):
    """
    A test node class that stores the evidence terms passed into it and does nothing with them,
    and whose update method returns a dictionary with param node names
    """

    def __init__(self, *args, **kwargs):
        super(MockNode, self).__init__(*args, **kwargs)
        self.obtained_evidence_terms = {}

    def update(self, evidence_terms=None):
        """ An update function that stores all the evidence infos passed to it, and sets its
        log_prob to a random Gaussian value

        :param list evidence_terms: evidence information passed into the node
        :return: the names of all param nodes
        :rtype: dict[Node, str]
        """
        if evidence_terms is not None:
            self.obtained_evidence_terms.update(evidence_terms)
        self.log_prob = np.random.randn()
        return {v: v.name for k, v in self.param_nodes.iteritems()}

class MockLearner(BayesNetLearner):
    """
    A learner with the following graph of TestNodes (directed edges pointing down):

       A
       |
       B
      / \
     C  D
     \ / \
     E   F
    """

    def __init__(self):
        cpd = GaussianCPD(dim=1)
        node_a = MockNode(name='A', data=None, cpd=cpd)
        node_b = MockNode(name='B', data=None, cpd=cpd, param_nodes={'mean': node_a})
        node_c = MockNode(name='C', data=None, cpd=cpd, param_nodes={'mean': node_b})
        node_d = MockNode(name='D', data=None, cpd=cpd, param_nodes={'mean': node_b})
        node_e = MockNode(name='E', data=None, cpd=cpd, param_nodes={'mean': node_c,
                                                                     'precision': node_d})
        node_f = MockNode(name='F', data=None, cpd=cpd, param_nodes={'mean': node_d})
        super(MockLearner, self).__init__(nodes=[node_a, node_b, node_c, node_d, node_e, node_f],
                                          max_iterations=1, callback=ConvergenceCallback())


from typing import List

# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

class Solution:
    def findRoot(self, tree: List['Node']) -> 'Node':
        if len(tree) == 0:
            return None
        all_children = set()
        vals = {}
        for node in tree:
            vals[node.val] = node
            for child in node.children:
                all_children.add(child.val)
        for v, n in vals.items():
            if v not in all_children:
                return n
        return None


import time

import gql
from gql.transport.aiohttp import AIOHTTPTransport
from gql.transport.exceptions import TransportError

class MidosHouse:
    def __init__(self):
        self.client = gql.Client(transport=AIOHTTPTransport(url='https://midos.house/api/v1/graphql'))
        self.cache = None
        self.cache_expires_at = time.monotonic()

    async def handles_custom_goal(self, goal_name):
        if time.monotonic() >= self.cache_expires_at:
            try:
                query = gql.gql("""
                    query {
                        goalNames
                    }
                """)
                response = await self.client.execute_async(query)
                self.cache_expires_at = time.monotonic() + 60 * 60 * 24
                self.cache = response['goalNames']
            except TransportError: # if anything goes wrong, assume Mido's House is down and we should handle the room
                self.cache_expires_at = time.monotonic() + 60
                self.cache = None
        if self.cache is None:
            return False
        return goal_name in self.cache


class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums_len = len(nums)
        nums[:] = nums[nums_len - k:] + nums[: nums_len - k]

        print (nums)
if __name__ == "__main__":
    nums = [1, 2, 3, 4, 5, 6, 7]
    k = 3
    solution = Solution()
    solution.rotate(nums, k)


#!/usr/bin/env python
import argparse
from termcolor import colored
from app import App
from constants import ERROR_COLOR, KEY_COLOR, INFO_COLOR
from utils import did_you_mean

def run():
    parser = argparse.ArgumentParser(description='Command line key-value store.',
                                     add_help=False, )
    parser.add_argument('action', metavar='action', nargs='*', help='action')
    args = parser.parse_args()
    # command = args or 'help'
    if not args.action:
        command = 'help'
    else:
        command = args.action[0]
    application = App()

    if not hasattr(application, command):
        print (colored('Command `', ERROR_COLOR) +
               colored(command, INFO_COLOR) +
               colored('`not found, Did you mean `', ERROR_COLOR) +
               colored(did_you_mean(command, App.SUPPORTED_COMMANDS), KEY_COLOR) +
               colored('`', ERROR_COLOR))
    else:
        sub_commands = args.action[1:] if args.action else None
        if sub_commands:
            application.call(command, *sub_commands)
        else:
            application.call(command)

if __name__ == "__main__":
    run()


def is_lucky_ticket(ticket_number):
    ticket_str = str(ticket_number)

    # Проверяем, что номер билета состоит из шести цифр
    if len(ticket_str) != 6:
        return False

    # Вычисляем сумму первых трех цифр и последних трех цифр
    sum_first_half = sum(int(digit) for digit in ticket_str[:3])
    sum_second_half = sum(int(digit) for digit in ticket_str[3:])

    # Проверяем условие счастливого билета
    if sum_first_half == sum_second_half:
        return True
    else:
        return False

# Пример использования функции
ticket_number = input("Введите номер билета: ")
if is_lucky_ticket(ticket_number):
    print("У вас счастливый билет!")
else:
    print("У вас не счастливый билет.")


import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import *
from transformers.modeling_roberta import RobertaLMHead
from transformers.modeling_bert import BertOnlyMLMHead

class BertMLM(BertPreTrainedModel):
    """BERT model with the masked language modeling head.
    """
    def __init__(self, config):
        super(BertMLM, self).__init__(config)
        self.bert = BertModel(config)
        self.cls = BertOnlyMLMHead(config)
        self.init_weights()
        self.tie_weights()

    def get_trainable_parameters(self):
        # this is useful when freezing the encoder parameters
        return list(self.bert.embeddings.word_embeddings.parameters()) + [self.cls.predictions.bias]

    def tie_weights(self):
        self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.weight

    def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):
        outputs = self.bert(input_ids, token_type_ids, attention_mask)
        sequence_output = outputs[0]
        pred_mask = masked_lm_labels.ne(-1)
        pred_vect = sequence_output[pred_mask]  # (bs, slen, dim)
        y = torch.masked_select(masked_lm_labels, pred_mask)
        prediction_scores = self.cls(pred_vect)
        masked_lm_loss = F.cross_entropy(prediction_scores, y)
        return masked_lm_loss

class RobertaMLM(BertPreTrainedModel):
    """RoBERTa model with the masked language modeling head.
    """
    def __init__(self, config):
        super(RobertaMLM, self).__init__(config)
        self.roberta = RobertaModel(config)
        self.lm_head = RobertaLMHead(config)
        self.init_weights()
        self.tie_weights()

    def get_trainable_parameters(self):
        return list(self.roberta.embeddings.word_embeddings.parameters()) + [self.lm_head.bias]

    def tie_weights(self):
        self.lm_head.decoder.weight = self.roberta.embeddings.word_embeddings.weight

    def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):
        outputs = self.roberta(input_ids, token_type_ids, attention_mask)
        sequence_output = outputs[0]
        pred_mask = masked_lm_labels.ne(-1)
        pred_vect = sequence_output[pred_mask]  # (bs, slen, dim)
        y = torch.masked_select(masked_lm_labels, pred_mask)
        prediction_scores = self.lm_head(pred_vect)
        masked_lm_loss = F.cross_entropy(prediction_scores, y)
        return masked_lm_loss

class BertAdaptor(nn.Module):
    """
    A class for adapting English BERT to other languages
    """
    def __init__(self, src_model, tgt_model):
        """
        src_model: (BertForMaskedLM) of English
        tgt_model: (BertForMaskedLM) of Foreign
        """
        super(BertAdaptor, self).__init__()
        self.src_model = src_model
        self.tgt_model = tgt_model

        # force sharing params
        self.tgt_model.bert.encoder = self.src_model.bert.encoder
        self.tgt_model.bert.pooler = self.src_model.bert.pooler
        # share embedding params
        self.tgt_model.bert.embeddings.position_embeddings = self.src_model.bert.embeddings.position_embeddings
        self.tgt_model.bert.embeddings.token_type_embeddings = self.src_model.bert.embeddings.token_type_embeddings
        self.tgt_model.bert.embeddings.LayerNorm = self.src_model.bert.embeddings.LayerNorm
        # share output layers
        self.tgt_model.cls.predictions.transform = self.src_model.cls.predictions.transform

    def forward(self, lang, input_ids, token_type_ids=None,
                attention_mask=None, masked_lm_labels=None):
        model = self.src_model if lang == 'en' else self.tgt_model
        return model(input_ids, token_type_ids, attention_mask=attention_mask,
                     masked_lm_labels=masked_lm_labels)

class RobertaAdaptor(nn.Module):
    """
    A class for adapting English BERT to other languages
    """
    def __init__(self, src_model, tgt_model):
        """
        src_model: (BertForMaskedLM) of English
        tgt_model: (Roberta) of Foreign
        """
        super(RobertaAdaptor, self).__init__()
        self.src_model = src_model
        self.tgt_model = tgt_model

        # force sharing params
        self.tgt_model.roberta.encoder = self.src_model.roberta.encoder
        self.tgt_model.roberta.pooler = self.src_model.roberta.pooler
        # share embedding params
        self.tgt_model.roberta.embeddings.position_embeddings = self.src_model.roberta.embeddings.position_embeddings
        self.tgt_model.roberta.embeddings.token_type_embeddings = self.src_model.roberta.embeddings.token_type_embeddings
        self.tgt_model.roberta.embeddings.LayerNorm = self.src_model.roberta.embeddings.LayerNorm
        # share output layers
        self.tgt_model.lm_head.dense = self.src_model.lm_head.dense
        self.tgt_model.lm_head.layer_norm = self.src_model.lm_head.layer_norm

    def forward(self, lang, input_ids, token_type_ids=None,
                attention_mask=None, masked_lm_labels=None):
        model = self.src_model if lang == 'en' else self.tgt_model
        return model(input_ids, token_type_ids, attention_mask=attention_mask,
                     masked_lm_labels=masked_lm_labels)


import numpy as np
import cv2 as cv

img = cv.imread("Resources/test.png")
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow("Gray", gray)
lap = cv.Laplacian(gray,cv.CV_64F)
lap = np.uint8(np.absolute(lap))
cv.imshow("Laplacian", lap)

cv.waitKey(0)


def shift_symbols():
    temp = word[shift:len(word)] + word[0:shift]
    return temp

def caesar():
    encrypted_message = [alfabet[alfabet.index(letter) - len(alfabet) + 51]
                         if letter in alfabet else letter for letter in my_word]
    return encrypted_message

word = 'vujgvmCfb tj ufscfu ouib z/vhm '
alfabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
my_words_list = []
for shift in range(len(word)):
    my_words_list.append(shift_symbols())
count = 0
for my_word in my_words_list:
    print(count)
    print(my_word, '===================', ''.join(caesar()))
    count += 1


from zepben.evolve import ConductingEquipmentStepTracker, ConductingEquipmentStep, Junction

def test_visited_step_is_reported_as_visited():
    # noinspection PyArgumentList
    step = ConductingEquipmentStep(Junction())
    tracker = ConductingEquipmentStepTracker()

    # pylint: disable=protected-access
    print()
    print(step.conducting_equipment)
    print("----------------")
    assert not tracker.has_visited(step), "has_visited returns false for unvisited equipment"
    print(tracker._minimum_steps)
    print("----------------")
    assert tracker.visit(step), "Visiting unvisited equipment returns true"
    print(tracker._minimum_steps)
    print("----------------")
    assert tracker.has_visited(step), "has_visited returns true for visited equipment"
    print(tracker._minimum_steps)
    print("----------------")
    assert not tracker.visit(step), "Revisiting visited equipment returns false"
    print(tracker._minimum_steps)
    print("----------------")
    # pylint: enable=protected-access

def test_smaller_step_for_same_equipment_is_reported_as_unvisited():
    ce = Junction()
    # noinspection PyArgumentList
    step1 = ConductingEquipmentStep(ce, 1)
    # noinspection PyArgumentList
    step2 = ConductingEquipmentStep(ce)

    tracker = ConductingEquipmentStepTracker()
    tracker.visit(step1)

    assert not tracker.has_visited(step2), "has_visited returns false for smaller step of visited"
    assert tracker.visit(step2), "Visiting smaller step of visited returns true"

def test_larger_step_for_same_equipment_is_reported_as_visited():
    ce = Junction()
    # noinspection PyArgumentList
    step1 = ConductingEquipmentStep(ce)
    # noinspection PyArgumentList
    step2 = ConductingEquipmentStep(ce, 1)

    tracker = ConductingEquipmentStepTracker()
    tracker.visit(step1)

    assert tracker.has_visited(step2), "has_visited returns true for larger step of visited"
    assert not tracker.visit(step2), "Visiting larger step of visited returns false"

def test_steps_of_different_equipment_are_tracked_separately():
    # noinspection PyArgumentList
    step1 = ConductingEquipmentStep(Junction())
    # noinspection PyArgumentList
    step2 = ConductingEquipmentStep(Junction())

    tracker = ConductingEquipmentStepTracker()
    tracker.visit(step1)

    assert not tracker.has_visited(step2), "has_visited returns false for same step on different equipment"
    assert tracker.visit(step2), "Visiting same step on different equipment returns true"

def test_clear():
    # noinspection PyArgumentList
    step = ConductingEquipmentStep(Junction())

    tracker = ConductingEquipmentStepTracker()
    tracker.visit(step)
    tracker.clear()

    assert not tracker.has_visited(step), "clear un-visits all steps"

def test_copy():
    # noinspection PyArgumentList
    step1 = ConductingEquipmentStep(Junction())
    # noinspection PyArgumentList
    step2 = ConductingEquipmentStep(Junction())

    tracker = ConductingEquipmentStepTracker()
    # noinspection PyArgumentList
    tracker.visit(step1)

    tracker_copy = tracker.copy()
    assert tracker is not tracker_copy, "Tracker copy is not a reference to the original tracker"
    assert tracker_copy.has_visited(step1), "Tracker copy reports has_visited as True for steps original tracker visited"

    tracker_copy.visit(step2)
    assert not tracker.has_visited(step2), "Tracker copy maintains separate tracking records"