from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import special_math_ops
from tensorflow.python.ops.distributions import distribution
from tensorflow.python.ops.distributions import util as distribution_util
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import tf_export

__all__ = [
    "DirichletMultinomial",
]

_dirichlet_multinomial_sample_note = """For each batch of counts,
`value = [n_0, ..., n_{K-1}]`, `P[value]` is the probability that after
sampling `self.total_count` draws from this Dirichlet-Multinomial distribution,
the number of draws falling in class `j` is `n_j`. Since this definition is
[exchangeable](https://en.wikipedia.org/wiki/Exchangeable_random_variables);
different sequences have the same counts so the probability includes a
combinatorial coefficient.

Note: `value` must be a non-negative tensor with dtype `self.dtype`, have no
fractional components, and such that
`tf.reduce_sum(value, -1) = self.total_count`. Its shape must be broadcastable
with `self.concentration` and `self.total_count`."""

@tf_export(v1=["distributions.DirichletMultinomial"])
class DirichletMultinomial(distribution.Distribution):
  """Dirichlet-Multinomial compound distribution.

  The Dirichlet-Multinomial distribution is parameterized by a (batch of)
  length-`K` `concentration` vectors (`K > 1`) and a `total_count` number of
  trials, i.e., the number of trials per draw from the DirichletMultinomial. It
  is defined over a (batch of) length-`K` vector `counts` such that
  `tf.reduce_sum(counts, -1) = total_count`. The Dirichlet-Multinomial is
  identically the Beta-Binomial distribution when `K = 2`.

  #### Mathematical Details

  The Dirichlet-Multinomial is a distribution over `K`-class counts, i.e., a
  length-`K` vector of non-negative integer `counts = n = [n_0, ..., n_{K-1}]`.

  The probability mass function (pmf) is,

  ```none
  pmf(n; alpha, N) = Beta(alpha + n) / (prod_j n_j!) / Z
  Z = Beta(alpha) / N!
  ```

  where:

  * `concentration = alpha = [alpha_0, ..., alpha_{K-1}]`, `alpha_j > 0`,
  * `total_count = N`, `N` a positive integer,
  * `N!` is `N` factorial, and,
  * `Beta(x) = prod_j Gamma(x_j) / Gamma(sum_j x_j)` is the
    [multivariate beta function](
    https://en.wikipedia.org/wiki/Beta_function#Multivariate_beta_function),
    and,
  * `Gamma` is the [gamma function](
    https://en.wikipedia.org/wiki/Gamma_function).

  Dirichlet-Multinomial is a [compound distribution](
  https://en.wikipedia.org/wiki/Compound_probability_distribution), i.e., its
  samples are generated as follows.

    1. Choose class probabilities:
       `probs = [p_0,...,p_{K-1}] ~ Dir(concentration)`
    2. Draw integers:
       `counts = [n_0,...,n_{K-1}] ~ Multinomial(total_count, probs)`

  The last `concentration` dimension parametrizes a single Dirichlet-Multinomial
  distribution. When calling distribution functions (e.g., `dist.prob(counts)`),
  `concentration`, `total_count` and `counts` are broadcast to the same shape.
  The last dimension of `counts` corresponds single Dirichlet-Multinomial
  distributions.

  Distribution parameters are automatically broadcast in all functions; see
  examples for details.

  #### Pitfalls

  The number of classes, `K`, must not exceed:
  - the largest integer representable by `self.dtype`, i.e.,
    `2**(mantissa_bits+1)` (IEE754),
  - the maximum `Tensor` index, i.e., `2**31-1`.

  In other words,

  ```python
  K <= min(2**31-1, {
    tf.float16: 2**11,
    tf.float32: 2**24,
    tf.float64: 2**53 }[param.dtype])
  ```

  Note: This condition is validated only when `self.validate_args = True`.

  #### Examples

  ```python
  alpha = [1., 2., 3.]
  n = 2.
  dist = DirichletMultinomial(n, alpha)
  ```

  Creates a 3-class distribution, with the 3rd class is most likely to be
  drawn.
  The distribution functions can be evaluated on counts.

  ```python
  # counts same shape as alpha.
  counts = [0., 0., 2.]
  dist.prob(counts)  # Shape []

  # alpha will be broadcast to [[1., 2., 3.], [1., 2., 3.]] to match counts.
  counts = [[1., 1., 0.], [1., 0., 1.]]
  dist.prob(counts)  # Shape [2]

  # alpha will be broadcast to shape [5, 7, 3] to match counts.
  counts = [[...]]  # Shape [5, 7, 3]
  dist.prob(counts)  # Shape [5, 7]
  ```

  Creates a 2-batch of 3-class distributions.

  ```python
  alpha = [[1., 2., 3.], [4., 5., 6.]]  # Shape [2, 3]
  n = [3., 3.]
  dist = DirichletMultinomial(n, alpha)

  # counts will be broadcast to [[2., 1., 0.], [2., 1., 0.]] to match alpha.
  counts = [2., 1., 0.]
  dist.prob(counts)  # Shape [2]
  ```

  """

  # TODO(b/27419586) Change docstring for dtype of concentration once int
  # allowed.
  @deprecation.deprecated(
      "2019-01-01",
      "The TensorFlow Distributions library has moved to "
      "TensorFlow Probability "
      "(https://github.com/tensorflow/probability). You "
      "should update all references to use `tfp.distributions` "
      "instead of `tf.distributions`.",
      warn_once=True)
  def __init__(self,
               total_count,
               concentration,
               validate_args=False,
               allow_nan_stats=True,
               name="DirichletMultinomial"):
    """Initialize a batch of DirichletMultinomial distributions.

    Args:
      total_count:  Non-negative floating point tensor, whose dtype is the same
        as `concentration`. The shape is broadcastable to `[N1,..., Nm]` with
        `m >= 0`. Defines this as a batch of `N1 x ... x Nm` different
        Dirichlet multinomial distributions. Its components should be equal to
        integer values.
      concentration: Positive floating point tensor, whose dtype is the
        same as `n` with shape broadcastable to `[N1,..., Nm, K]` `m >= 0`.
        Defines this as a batch of `N1 x ... x Nm` different `K` class Dirichlet
        multinomial distributions.
      validate_args: Python `bool`, default `False`. When `True` distribution
        parameters are checked for validity despite possibly degrading runtime
        performance. When `False` invalid inputs may silently render incorrect
        outputs.
      allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
        (e.g., mean, mode, variance) use the value "`NaN`" to indicate the
        result is undefined. When `False`, an exception is raised if one or
        more of the statistic's batch members are undefined.
      name: Python `str` name prefixed to Ops created by this class.
    """
    parameters = dict(locals())
    with ops.name_scope(name, values=[total_count, concentration]) as name:
      # Broadcasting works because:
      # * The broadcasting convention is to prepend dimensions of size [1], and
      #   we use the last dimension for the distribution, whereas
      #   the batch dimensions are the leading dimensions, which forces the
      #   distribution dimension to be defined explicitly (i.e. it cannot be
      #   created automatically by prepending). This forces enough explicitness.
      # * All calls involving `counts` eventually require a broadcast between
      #  `counts` and concentration.
      self._total_count = ops.convert_to_tensor(total_count, name="total_count")
      if validate_args:
        self._total_count = (
            distribution_util.embed_check_nonnegative_integer_form(
                self._total_count))
      self._concentration = self._maybe_assert_valid_concentration(
          ops.convert_to_tensor(concentration,
                                name="concentration"),
          validate_args)
      self._total_concentration = math_ops.reduce_sum(self._concentration, -1)
    super(DirichletMultinomial, self).__init__(
        dtype=self._concentration.dtype,
        validate_args=validate_args,
        allow_nan_stats=allow_nan_stats,
        reparameterization_type=distribution.NOT_REPARAMETERIZED,
        parameters=parameters,
        graph_parents=[self._total_count,
                       self._concentration],
        name=name)

  @property
  def total_count(self):
    """Number of trials used to construct a sample."""
    return self._total_count

  @property
  def concentration(self):
    """Concentration parameter; expected prior counts for that coordinate."""
    return self._concentration

  @property
  def total_concentration(self):
    """Sum of last dim of concentration parameter."""
    return self._total_concentration

  def _batch_shape_tensor(self):
    return array_ops.shape(self.total_concentration)

  def _batch_shape(self):
    return self.total_concentration.get_shape()

  def _event_shape_tensor(self):
    return array_ops.shape(self.concentration)[-1:]

  def _event_shape(self):
    # Event shape depends only on total_concentration, not "n".
    return self.concentration.get_shape().with_rank_at_least(1)[-1:]

  def _sample_n(self, n, seed=None):
    n_draws = math_ops.cast(self.total_count, dtype=dtypes.int32)
    k = self.event_shape_tensor()[0]
    unnormalized_logits = array_ops.reshape(
        math_ops.log(random_ops.random_gamma(
            shape=[n],
            alpha=self.concentration,
            dtype=self.dtype,
            seed=seed)),
        shape=[-1, k])
    draws = random_ops.multinomial(
        logits=unnormalized_logits,
        num_samples=n_draws,
        seed=distribution_util.gen_new_seed(seed, salt="dirichlet_multinomial"))
    x = math_ops.reduce_sum(array_ops.one_hot(draws, depth=k), -2)
    final_shape = array_ops.concat([[n], self.batch_shape_tensor(), [k]], 0)
    x = array_ops.reshape(x, final_shape)
    return math_ops.cast(x, self.dtype)

  @distribution_util.AppendDocstring(_dirichlet_multinomial_sample_note)
  def _log_prob(self, counts):
    counts = self._maybe_assert_valid_sample(counts)
    ordered_prob = (
        special_math_ops.lbeta(self.concentration + counts)
        - special_math_ops.lbeta(self.concentration))
    return ordered_prob + distribution_util.log_combinations(
        self.total_count, counts)

  @distribution_util.AppendDocstring(_dirichlet_multinomial_sample_note)
  def _prob(self, counts):
    return math_ops.exp(self._log_prob(counts))

  def _mean(self):
    return self.total_count * (self.concentration /
                               self.total_concentration[..., array_ops.newaxis])

  @distribution_util.AppendDocstring(
      """The covariance for each batch member is defined as the following:

      ```none
      Var(X_j) = n * alpha_j / alpha_0 * (1 - alpha_j / alpha_0) *
      (n + alpha_0) / (1 + alpha_0)
      ```

      where `concentration = alpha` and
      `total_concentration = alpha_0 = sum_j alpha_j`.

      The covariance between elements in a batch is defined as:

      ```none
      Cov(X_i, X_j) = -n * alpha_i * alpha_j / alpha_0 ** 2 *
      (n + alpha_0) / (1 + alpha_0)
      ```
      """)
  def _covariance(self):
    x = self._variance_scale_term() * self._mean()
    # pylint: disable=invalid-unary-operand-type
    return array_ops.matrix_set_diag(
        -math_ops.matmul(
            x[..., array_ops.newaxis],
            x[..., array_ops.newaxis, :]),  # outer prod
        self._variance())

  def _variance(self):
    scale = self._variance_scale_term()
    x = scale * self._mean()
    return x * (self.total_count * scale - x)

  def _variance_scale_term(self):
    """Helper to `_covariance` and `_variance` which computes a shared scale."""
    # We must take care to expand back the last dim whenever we use the
    # total_concentration.
    c0 = self.total_concentration[..., array_ops.newaxis]
    return math_ops.sqrt((1. + c0 / self.total_count) / (1. + c0))

  def _maybe_assert_valid_concentration(self, concentration, validate_args):
    """Checks the validity of the concentration parameter."""
    if not validate_args:
      return concentration
    concentration = distribution_util.embed_check_categorical_event_shape(
        concentration)
    return control_flow_ops.with_dependencies([
        check_ops.assert_positive(
            concentration,
            message="Concentration parameter must be positive."),
    ], concentration)

  def _maybe_assert_valid_sample(self, counts):
    """Check counts for proper shape, values, then return tensor version."""
    if not self.validate_args:
      return counts
    counts = distribution_util.embed_check_nonnegative_integer_form(counts)
    return control_flow_ops.with_dependencies([
        check_ops.assert_equal(
            self.total_count, math_ops.reduce_sum(counts, -1),
            message="counts last-dimension must sum to `self.total_count`"),
    ], counts)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 11:57:29 2021

@author: ml
"""

from code.feature_extraction.hour import Hour
import numpy as np
import pandas as pd
import unittest

class HourTest(unittest.TestCase):

    def setUp(self):
        self.INPUT_COLUMN = "input"
        self.Hour_feature = Hour(self.INPUT_COLUMN)
        self.df = pd.DataFrame()
        self.df[self.INPUT_COLUMN] = ['01:37:00']

    def test_input_columns(self):
        """
        tests if the input column is the correct one

        Returns
        -------
        None.

        """
        self.assertEqual(self.Hour_feature._input_columns, [self.INPUT_COLUMN])

    def test_feature_name(self):
        """
        test if feature column is correctly named

        Returns
        -------
        None.

        """
        self.assertEqual(self.Hour_feature.get_feature_name(), ['HOUR OF DAY_0-2', 'HOUR OF DAY_3-5', 'HOUR OF DAY_6-8', 'HOUR OF DAY_9-11', 'HOUR OF DAY_12-14', 'HOUR OF DAY_15-17', 'HOUR OF DAY_18-20', 'HOUR OF DAY_21-23'])

    def test_ohe_hour_correct(self):
        """
        check if hour is correctly checked

        Returns
        -------
        None.

        """
        #arrange
        #CREATE THE ONE HOT ENCODING (OHE)
        #                    0      1     2     3    4      5     6     7
        #                   0-2    3-5  6-8  9-11 12-14 15-17 18-20 21-23
        ohe_hour=np.array([True,False,False,False,False,False,False,False])

        #act
        output=self.Hour_feature.fit_transform(self.df)

        for i in range(0,len(ohe_hour)):
            #assert
            self.assertEqual(output[0][i], ohe_hour[i])

if __name__ == '__main__':
    print("__[RUNNING: test.feature_extraction.test_hour]__")
    unittest.main()


# -*- encoding:utf-8 -*-
"""
模拟结果的可视化
plot_country: 绘制国家总SEIR-时间演化曲线
plot_all: 绘制各城市SEIR-时间演化曲线
animate: 制作国家演化视频
report: 生成csv格式的报告表，包含国家和各城市演化过程中的感染最大值及时刻、健康人数降至50%时刻信息
"""
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from simulation import SimCountry

def _plot(ax, time: "np.ndarray, shape=(N,)", itrack: "np.ndarray, shape=(N, 4)"):
    ax.plot(time, itrack[:, 0], lw=0.6, label='S')
    ax.plot(time, itrack[:, 1], lw=0.6, label='E')
    ax.plot(time, itrack[:, 2], lw=0.6, label='I')
    ax.plot(time, itrack[:, 3], lw=0.6, label='R')
    ax.legend()
    ax.set_xlabel("time / day")
    ax.set_ylabel("population / $10^{4}$")

def plot_country(country: "SimCountry") -> "fig, ax":
    fig, ax = plt.subplots(dpi=170)
    _plot(ax, country.time, country.track.sum(axis=(1, 2)))
    return fig, ax

def plot_all(country: "SimCountry", directory):
    if not os.path.exists(directory):
        os.makedirs(directory)

    fig, ax = plt.subplots(dpi=170)
    _plot(ax, country.time, country.track[:, 0, 0, :])
    for i in range(country.shape[0]):
        for j in range(country.shape[1]):
            ax.clear()
            _plot(ax, country.time, country.track[:, i, j, :])
            fig.savefig(f"{directory}/city{i}{j}.svg")

def animate(country: "SimCountry", interval=20, gap=10):
    r, c = country.shape
    I, J = np.mgrid[:r, :c]
    sizes = country.track[:, :, :, 2].reshape(country.track.shape[0], -1) / 490 * 5120

    fig, ax = plt.subplots(figsize=(5, 5))
    pc = ax.scatter(I.flatten(), J.flatten(), c='red', s=sizes[0], alpha=0.5)
    title = ax.set_title(rf"t = ${country.time[0]:.2f}$ days")

    def Animate(i):
        idx = int(i * gap)
        pc.set_sizes(sizes[idx])
        title.set_text(rf"t = ${country.time[idx]:.2f}$ days")
        return pc, title

    ani = animation.FuncAnimation(
        fig, Animate, frames=country.time.shape[0] // gap, interval=interval, blit=False, save_count=50)

    return ani

def report(country: "SimCountry", filename):
    index = ['country'] + [f'city_{i}{j}' for j in range(country.shape[1]) for i in range(country.shape[0])]
    df = pd.DataFrame(index=index, columns=['I_max_time', 'I_max', 'S_50_time'])

    # 处理全国的情况
    I = country.track[:, :, :, 2].sum(axis=(1, 2))
    Im_arg = I.argmax()
    Im_t = country.time[Im_arg]
    Im = I[Im_arg]
    S = country.track[:, :, :, 0].sum(axis=(1, 2))
    S_frac = S / S[0]
    S50_t = country.time[(S_frac > 0.5).sum() - 1]
    df.loc['country', :] = [Im_t, Im, S50_t]

    # 处理各城市
    I = country.track[:, :, :, 2].reshape(country.time.size, -1)
    Im_arg = I.argmax(axis=0)
    Im_t = country.time[Im_arg]
    Im = I[Im_arg, np.arange(I.shape[1])]
    S = country.track[:, :, :, 0].reshape(country.time.size, -1)
    S_frac = S / S[0, :].reshape(1, S.shape[1])
    S50_t = country.time[(S_frac > 0.5).sum(axis=0) - 1]
    df.iloc[1:, 0] = Im_t
    df.iloc[1:, 1] = Im
    df.iloc[1:, 2] = S50_t

    df.to_csv(filename)


# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import telebot
import pygame

#privet

print("Bot  WTP started")
bot = telebot.TeleBot('1777290579:AAGVarx5xRQ9QlPRx0L2LHyzgKMz-hDK284')

keyboard = telebot.types.ReplyKeyboardMarkup(True, True)
keyboard.row( 'I Want to play', 'Free court','Statistic')

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, '''Welcome to Want To Play service.
    We will help you to have those game that you want.
    Use the menu below.
    Tape "Want To Play" to begin from start page.  '''
                     , reply_markup=keyboard)

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == 'Free court':
        bot.send_message(message.chat.id, 'At the moment we have the following free courts')

        #bot.send_photo(message.chat.id, open('E:\logo.jpg', 'rb'));
    elif message.text.lower() == 'продукты':
        bot.send_message(message.chat.id, 'Уникальные светильники уже в продаже.')
    elif message.text.lower() == 'акции':
        bot.send_message(message.chat.id, 'Акционные товары всегд апользуються спросом.')
    elif message.text.lower() == 'я тебя люблю':
        bot.send_sticker(message.chat.id, 'CAADAgADZgkAAnlc4gmfCor5YbYYRAI')

bot.polling()


import sys
import os
import random
import hashlib
from shutil import copy2
from shutil import rmtree
import time

drive_loc = ""
copy_from_loc = ""
extensions = ['.jpg', '.png']
valid_args = ['-', 'c', 'd', 'r']
target_files = []

def usage():
    print("The program takes 1 mandatory argument")
    print("python wall.py -c|-d|-r")
    print("-c : copy files from temp")
    print("-d : find duplicate files")
    print("-r : rename files")

def find_rename(drive_loc):
    os.chdir(drive_loc)
    global target_files
    for file in os.listdir('.'):
        fname, ext = os.path.splitext(file)
        if ext.lower() in extensions:
            target_files.append(fname)
    try:
        target_files = [int(i) for i in target_files]
    except:
        print("Found a non numeric wallpaper name in the target directory...")
        new_count = complete_rename()
        return new_count
    else:
        target_files.sort()
        if len(target_files) == 0:
            print("no wallpaper in the directory")
            return 0
        if target_files[-1] == len(target_files):
            print('no need to rename')
            return target_files[-1]
        else:
            new_count = complete_rename()
            return new_count

def complete_rename():
    temp_name = str(random.randint(50000, sys.maxsize))
    print("starting renaming")
    try:
        os.mkdir(temp_name)
    except:
        print("Error during cretion of temp directory")
        exit(2)
    count = 1
    pass_count = fail_count = 0
    for i in os.listdir('.'):
        fname, ext = os.path.splitext(i)
        if ext.lower() in extensions:
            pass_count += 1
            newfname = str(count) + ext
            copy2(i, './' + temp_name + "/" + newfname)
            count += 1
        else:
            fail_count += 1

    for file in os.listdir('.'):
        fname, ext = os.path.splitext(file)
        if ext.lower() in extensions:
            os.remove(file)

    for file in os.listdir('./'+temp_name):
        copy2('./' + temp_name + '/' + file, '.')
    rmtree(temp_name)
    return count

def copy_wallpapers(temp_loc, drive_loc, new_count):
    os.chdir(temp_loc)
    for file in os.listdir('.'):
        fname, ext = os.path.splitext(file)
        if ext.lower() in extensions:
            newfname = str(new_count)+ext
            copy2(file, drive_loc + "/" + newfname)
            new_count += 1

def find_duplicates(drive_loc):
    os.chdir(drive_loc)
    hashes = {}
    count = 0
    for file in os.listdir('.'):
        fname, ext = os.path.splitext(file)
        if ext.lower() in extensions:
            with open(file, "rb") as f:
                bytes = f.read()
                pichash = hashlib.sha256(bytes).hexdigest()
                if pichash in hashes.keys():
                    print(str(file) + " is same as " + hashes[pichash])
                    count += 1
                else:
                    hashes[pichash] = file
    if count == 0:
        print("No duplicate files")
    else:
        print("""Advised to run the script with -r """
              """to rename the files after deleting the duplicates""")
        print("Process Complete")

def take_source_loc():
    global copy_from_loc
    copy_from_loc = input("Provide the source path: ")
    if not os.path.isdir(copy_from_loc):
        print("Not a valid source directory")
        exit(1)

def take_target_loc():
    global drive_loc
    drive_loc = input("Provide the wallpaper path: ")
    if not os.path.isdir(drive_loc):
        print("Not a valid source directory")
        exit(1)

if __name__ == '__main__':
    start = time.time()
    if len(sys.argv) == 1:
        usage()
    elif len(sys.argv) > 2:
        usage()
    else:
        count = 1
        args = list(sys.argv[1])
        for arg in args:
            if arg not in valid_args:
                print("invalid argument: " + arg +
                      " in " + ''.join(sys.argv[1]))
                usage()
                exit(1)
        if 'r' in args:
            print("Starting the renaming process")
            take_target_loc()
            count = find_rename(drive_loc)
            print("Renaming process complete")
            print()
        if 'c' in args and 'r' in args:
            print("starting the copy process to the above given location")
            take_source_loc()
            if drive_loc == copy_from_loc:
                print("Source and Target location is same... Exiting...")
                exit(1)
            copy_wallpapers(copy_from_loc, drive_loc, count+1)
            print("Copy process complete")
            print()
        if 'c' in args and 'r' not in args:
            take_source_loc()
            take_target_loc()
            if drive_loc == copy_from_loc:
                print("Source and Target location is same... Exiting...")
                exit(1)
            print("Starting the renaming process before copying")
            count = find_rename(drive_loc)
            print("Starting the copy process")
            copy_wallpapers(copy_from_loc, drive_loc, count+1)
            print("Copy process complete")
            print()
        if 'd' in args:
            print("Starting to find the duplicates")
            take_target_loc()
            find_duplicates(drive_loc)
            print()
    print("Program run time " + str(time.time() - start) + "s")


import supy
import math,collections,bisect,itertools

class Indices(supy.wrappedChain.calculable) :
    """
    This is a calculable to build the collection of jets that have
    some pt min and eta max. It can be used also for other
    collections, as long as they have a pt and eta.
    """
    def __init__(self, collection = None, ptMin = None, etaMax = None):
        self.moreName = "pt>%f;|eta|<%f" % (ptMin, etaMax)
        for item in ["ptMin", "etaMax" ] :
            setattr(self, item, eval(item))
        self.fixes = collection
        self.stash(["pt", "eta"])

    def update(self, _) :
        pts = self.source[self.pt]  # prefix, suffix
        etas = self.source[self.eta]
        self.value = []
        for i in range(pts.size()):
            if pts.at(i)<self.ptMin: continue #put a break if too slow and coll is sorted
            if abs(etas.at(i))>self.etaMax: continue
            self.value.append(i)

class P4(supy.wrappedChain.calculable) :
    """
    Calculable to build Lorentz vectors from the standard D3PD collections.
    """
    def __init__(self, collection = None,):
        self.fixes = collection
        self.stash(["pt", "eta", "phi", "m"])
    def update(self, _) :
        self.value = [supy.utils.root.LorentzV(pt, eta, phi, m) for pt,eta,phi,m in zip(self.source[self.pt],
                                                                                self.source[self.eta],
                                                                                self.source[self.phi],
                                                                                self.source[self.m])]

class M01(supy.wrappedChain.calculable) :
    """
    Calculable to compute the invariant mass of the first two objects
    in a collection.
    """
    def __init__(self, collection = None,):
        self.fixes = collection
        self.stash(["P4", "Indices"])
    def update(self, _) :
        P4 = self.source[self.P4]
        indices = self.source[self.Indices]
        jet0 = P4[indices[0]]
        jet1 = P4[indices[1]]
        self.value = (jet0+jet1).M()
        # self.value = sum([P4[indices[i]] for i in [0,1]]).M()


# 🚨 Don't change the code below 👇
row1 = ["⬜","⬜","⬜"]
row2 = ["⬜","⬜","⬜"]
row3 = ["⬜","⬜","⬜"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆

#Write your code below this row 👇
# Store the positional arguments in a variable
# Accounting for the index starting at 0
col_position = int(position[0]) -1
row_position = int(position[1]) -1

# Marking the spot with the 'X'
map[row_position][col_position] = 'X'

#Write your code above this row 👆

# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}")


def is_ok(people, partition):
    for i in range(len(people)):
        for j in range(i + 1, len(people)):
            if abs(people[i][0] - people[j][0]) + abs(people[i][1] - people[j][1]) <= 2: # too close
                if people[i][0] == people[j][0]: # vertical
                    if (people[i][0], (people[i][1] + people[j][1])/2) not in partition:
                        return 0
                elif people[i][1] == people[j][1]: # horizontal
                    if ((people[i][0] + people[j][0])/2, people[i][1]) not in partition:
                        return 0
                else: # cross
                    if (people[i][0]+1, people[i][1]) not in partition:
                        return 0
                    if people[i][1] > people[j][1]: # left side
                        if (people[i][0], people[i][1]-1) not in partition:
                            return 0
                    else: # right side
                        if (people[i][0], people[i][1]+1) not in partition:
                            return 0

            if people[i][0] - people[j][0] > 1: # no more close people
                break
    return 1

def solution(places):
    answer = []

    for place in places:
        people = []
        partition = []
        result = 1
        for i in range(len(place)):
            for j in range(len(place[i])):
                if place[i][j] == 'P':
                    people.append((i, j))
                elif place[i][j] == 'X':
                    partition.append((i, j))

        answer.append(is_ok(people, partition))

    return answer


from typing import *
import numpy as np
import pandas as pd

import time
from collections import namedtuple
import threading
import math
import warnings

from .spectral_clustering import spectral_clustering
from .flow_clustering import flow_clustering
from .GraphLocal import GraphLocal
from .triangleclusters import triangleclusters

def ncp_experiment(ncpdata,R,func,method_stats):
    if ncpdata.input_stats:
        input_stats = ncpdata.graph.set_scores(R)
        for F in ncpdata.set_funcs: # build the list of keys for set_funcs
            input_stats.update(F(ncpdata.graph, R))
        input_stats = {"input_" + str(key):value for key,value in input_stats.items() } # add input prefix
    else:
        input_stats = {}

    start = time.time()
    S = func(ncpdata.graph, R)
    dt = time.time() - start

    if len(S) > 0:
        output_stats = ncpdata.graph.set_scores(S)
        for F in ncpdata.set_funcs: # build the list of keys for set_funcs
            output_stats.update(F(ncpdata.graph, S))
        output_stats = {"output_" + str(key):value for key,value in output_stats.items() } # add output prefix

        method_stats['methodfunc']  = func
        method_stats['time'] = dt
        return [ncpdata.record(**input_stats, **output_stats, **method_stats)]
    else:
        return [] # nothing to return

def ncp_node_worker(ncpdata,sets,func,timeout_ncp,methodname):
    start = time.time()
    setno = 0
    for R in sets:
        #print("setno = %i"%(setno))
        setno += 1

        method_stats = {'input_set_type': 'node', 'input_set_params':R[0]}
        ncpdata.results.extend(ncp_experiment(ncpdata, R, func, method_stats))

        end = time.time()
        if end - start > timeout_ncp:
            break

# todo avoid code duplication
def ncp_neighborhood_worker(ncpdata,sets,func,timeout_ncp,methodname):
    start = time.time()
    setno = 0
    for R in sets:
        #print("setno = %i"%(setno))
        setno += 1

        R = R.copy() # duplicate so we don't keep extra weird data around
        node = R[0]
        R.extend(ncpdata.graph.neighbors(R[0]))
        method_stats = {'input_set_type': 'neighborhood', 'input_set_params':node}

        ncpdata.results.extend(ncp_experiment(ncpdata, R, func, method_stats))

        end = time.time()
        if end - start > timeout_ncp:
            break

# todo avoid code duplication
def ncp_set_worker(ncpdata,setnos,func,timeout_ncp,methodname):
    start = time.time()
    setno = 0
    for id in setnos:
        #print("setno = %i"%(setno))
        setno += 1
        R = ncpdata.sets[id]
        #R = R.copy() # duplicate so we don't keep extra weird data around
        method_stats = {'input_set_type': 'set', 'input_set_params':id}

        ncpdata.results.extend(ncp_experiment(ncpdata, R, func, method_stats))

        end = time.time()
        if end - start > timeout_ncp:
            break

class NCPData:
    def __init__(self, graph, setfuncs=[], input_stats=True, do_largest_component=True):
        if do_largest_component:
            self.graph = graph.largest_component()
        else:
            self.graph = graph

        # Todo - have "largest_component" return a graph for the largest component
        self.input_stats = input_stats
        self.set_funcs = setfuncs

        standard_fields = self.graph.set_scores([0])
        for F in self.set_funcs: # build the list of keys for set_funcs
            standard_fields.update(F(self.graph, [0]))
        if self.input_stats:
            result_fields = ["input_" + field for field in standard_fields.keys()]
        result_fields.extend(["output_" + str(field) for field in standard_fields.keys()])
        result_fields.extend(["methodfunc", "input_set_type", "input_set_params", "time"])
        self.record = namedtuple("NCPDataRecord", field_names=result_fields)
        self.neighborhood_cond = None
        self.reset_records()
        self.default_method = None
        self.method_names = {} # This stores human readable and usable names for methods

    def reset_records(self):
        self.results = []
        self.sets = []
        self.method_names = {}

    """ Generate nodes at random from the set of locally minimal seeds according
    to a vertex-based feature. By default, that feature is neighborhood conductance,
    following

        Vertex neighborhoods, low conductance cuts, and good seeds for local community methods
        DF Gleich and C Seshahdri, KDD 2012.

    But, by providing any vector of data for each node in the graph,
    this code can be extended. Note that the conductance of each vertex
    neighborhood in the graph is calculated the first time and cached,
    which could cause a long initialization.

    @param ratio The number of nodes to pick (if > 1.0) or the fraction
    of total nodes to pick (if <= 1.0) (no default)

    @param mindegree the minimum degree of a node to pick (default 5)

    @param feature The vector of data to use to produce the locally
    minimial seeds(default None, which means to use neighborhood conductance)

    @param strict (default True) if we use a strict minimum in the definition
    of a local minimum.
    """
    def random_localmin_nodes(self, ratio, mindegree=5, feature=None, strict=True):
        if feature is None:
            # then we use conductance
            if self.neighborhood_cond is None:
                self.neighborhood_cond = triangleclusters(self.graph)[0]
            feature = self.neighborhood_cond
        # find the set of minimal verts
        minverts = self.graph.local_extrema(feature, strict)[0]
        # filter by mindegree
        minverts = [v for v in minverts if self.graph.d[v] >= mindegree]

        if 0 < ratio <= 1:
            n_nodes = min(np.ceil(ratio*len(minverts)),len(minverts))
            n_nodes = int(n_nodes)
        elif ratio > 1.0: # this is a number of nodes
            n_nodes = min(int(ratio), len(minverts))
        else:
            raise(ValueError("the ratio parameter must be positive"))

        return np.random.choice(minverts, size=n_nodes, replace=False)

    def random_nodes(self, ratio):
        n = self.graph._num_vertices
        if 0 < ratio <= 1:
            n_nodes = min(np.ceil(ratio*n),n)
            n_nodes = int(n_nodes)
        elif ratio > 1.0: # this is a number of nodes
            n_nodes = int(ratio)
        else:
            raise(ValueError("the ratio parameter must be positive"))

        return np.random.choice(np.arange(0,n), size=n_nodes, replace=False)

    """ Decode and return the input set to a particular experiment. """
    def input_set(self, j):
        result = self.results[j] # todo check for validity
        if result.input_set_type=="node":
            return [result.input_set_params]
        elif result.input_set_type=="neighborhood":
            R = self.graph.neighbors(result.input_set_params)
            R.append(result.input_set_params)
            return R
        elif result.input_set_type=="set":
            return self.sets[result.input_set_params].copy()
        else:
            raise(ValueError("the input_set_type is unrecognized"))

    def output_set(self, j):
        result = self.results[j] # todo check for validity
        func = result.methodfunc
        R = self.input_set(j)
        return func(self.graph, R)

    def _check_method(self, method, name):
        if method == None:
            method = self.default_method
            if method == None:
                raise(ValueError("NCP call with method=None, but no default method specified"))
        if method in self.method_names:
            # in this case, we already have a name...
            if name is not None and name is not self.method_names[method]:
                warnings.warn("Duplicate name given to NCP method\n" +
                              "original name was: %s\n"%(self.method_names[method]) +
                              "new name attempted: %s\n"%(name), stacklevel=3)
        else:
            # we need to name the method
            if name is None:
                # need to figure out a name, let's use something boring.
                self.method_names[method] = "method-%i"%(len(self.method_names))
            else:
                self.method_names[method] = name

        return method

    def add_random_node_samples(self, ratio=0.3, timeout=1000, nthreads=4, method=None, methodname=None):
        method = self._check_method(method, methodname)
        nodes = self.random_nodes(ratio)

        threads = []
        threadnodes = np.array_split(nodes, nthreads)

        for i in range(nthreads):
            sets = [ [j] for j in threadnodes[i] ] # make a set of sets
            t = threading.Thread(target=ncp_node_worker,args=(self, sets, method, timeout, methodname))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()

    def add_random_neighborhood_samples(self, ratio=0.3, timeout=1000, nthreads=4, method=None, methodname=None):
        method = self._check_method(method, methodname)
        nodes = self.random_nodes(ratio)

        threads = []
        threadnodes = np.array_split(nodes, nthreads)

        for i in range(nthreads):
            sets = [ [j] for j in threadnodes[i] ] # make a set of sets
            t = threading.Thread(target=ncp_neighborhood_worker,args=(self, sets, method, timeout, methodname))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()

    """ Add expansions of all the locally minimal seeds.

    This routine follows ideas from:

        Vertex neighborhoods, low conductance cuts, and good seeds for local community methods
        DF Gleich and C Seshahdri, KDD 2012.

    which grow sets of out locally minimal seed vertices. These are
    vertices whose neighborhood conductance (in that paper) were better than all
    of the other neighbors. By default, this routine will use the same
    type of expansion.

    @param feature (default None, which means to use neighborhood conductance)
    @param strict, ratio, mindegree (see random_localmin_nodes)
    @param neighborhods this determinds if we seed based on the vertex (False)
    or the vertex neighborhood (True) (default True, following Gleich & Seshadhri)
    @param timeout, nthreads, method, methodname (see add_random_node samples)
    """
    def add_localmin_samples(self,
            feature=None, strict=True, ratio=1.0, mindegree=5, # localmin parameters
            neighborhoods=True, # use neighborhood expansion
            timeout=1000, nthreads=4, method=None, methodname=None):

        method = self._check_method(method, methodname)
        nodes = self.random_localmin_nodes(ratio,
            feature=feature, strict=strict, mindegree=mindegree)

        threads = []
        threadnodes = np.array_split(nodes, nthreads)

        for i in range(nthreads):
            sets = [ [j] for j in threadnodes[i] ] # make a set of sets
            if neighborhoods:
                t = threading.Thread(target=ncp_neighborhood_worker,args=(self, sets, method, timeout, methodname))
            else:
                t = threading.Thread(target=ncp_node_worker,args=(self, sets, method, timeout, methodname))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()

    def add_random_neighborhood_samples(self, ratio=0.3, timeout=1000, nthreads=4, method=None, methodname=None):
        method = self._check_method(method, methodname)
        nodes = self.random_nodes(ratio)

        threads = []
        threadnodes = np.array_split(nodes, nthreads)

        for i in range(nthreads):
            sets = [ [j] for j in threadnodes[i] ] # make a set of sets
            t = threading.Thread(target=ncp_neighborhood_worker,args=(self, sets, method, timeout, methodname))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()

    def add_set_samples(self, sets, nthreads=4, method=None, methodname=None, timeout=1000):
        method = self._check_method(method, methodname)
        threads = []
        startset = len(self.sets)
        self.sets.extend(sets)
        endset = len(self.sets)

        setnos = np.array_split(range(startset,endset), nthreads) # set numbers

        """
        results_id = len(self.results)
        self.results.append([])
        self.method_names.append(methodname)
        """

        #self.results[methodname] = []

        for i in range(nthreads):
            t = threading.Thread(target=ncp_set_worker,args=(self, setnos[i], method, timeout, methodname))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()

    def as_data_frame(self):
        """
        DF = pd.DataFrame.from_records([], columns=self.record._fields)
        for methodname in self.results.keys():
            df = pd.DataFrame.from_records(self.results[methodname], columns=self.record._fields)
            df.rename(columns={'method':'methodfunc'}, inplace=True)
            df["method"] = methodname
            DF = DF.append(df,ignore_index=True)
        return DF
        """
        df = pd.DataFrame.from_records(self.results, columns=self.record._fields)
        df.rename(columns={'method':'methodfunc'}, inplace=True)
        df["method"] = df["methodfunc"].map(self.method_names)
        return df

    def approxPageRank(self,
                       gamma: float = 0.01/0.99,
                       rholist: List[float] = [1.0e-10,1.0e-8,1.0e-7,1.0e-6,1.0e-5,1.0e-4],
                       ratio: float = 0.3,
                       nthreads: int = 4,
                       timeout: float = 1000):
        #self.reset_records("approxPageRank")
        alpha = 1.0-1.0/(1.0+gamma)
        funcs = {lambda G,R: spectral_clustering(G,R,alpha=alpha,rho=rho,method="acl")[0]:'acl;rho=%.0e'%(rho)
                    for rho in rholist}
        for func in funcs.keys():
            self.add_random_node_samples(method=func,methodname=funcs[func],ratio=ratio,nthreads=nthreads,timeout=timeout/len(funcs))

    def l1reg(self,
              gamma: float = 0.01/0.99,
              rholist: List[float] = [1.0e-10,1.0e-8,1.0e-7,1.0e-6,1.0e-5,1.0e-4],
              ratio: float = 0.3,
              nthreads: int = 4,
              timeout: float = 1000):
        #self.reset_records("l1reg")
        alpha = 1.0-1.0/(1.0+gamma)
        funcs = {lambda G,R: spectral_clustering(G,R,alpha=alpha,rho=rho,method="l1reg")[0]:'l1reg;rho=%.0e'%(rho)
                    for rho in rholist}
        for func in funcs.keys():
            self.add_random_node_samples(method=func,methodname=funcs[func],ratio=ratio,nthreads=nthreads,timeout=timeout/len(funcs))

    def crd(self,
            U: int = 3,
            h: int = 10,
            w: int = 2,
            ratio: float = 0.3,
            nthreads: int = 4,
            timeout: float = 1000):
        #self.reset_records("crd")
        func = lambda G,R: flow_clustering(G,R,w=w, U=U, h=h,method="crd")[0]
        self.add_random_neighborhood_samples(method=func,methodname="crd",
                ratio=ratio,nthreads=nthreads,timeout=timeout/2)
        self.add_random_node_samples(method=func,methodname="crd",
                ratio=ratio,nthreads=nthreads,timeout=timeout/2)
        return self

    def mqi(self,
            ratio: float = 0.3,
            nthreads: int = 4,
            timeout: float = 1000):
        #self.reset_records("mqi")
        func = lambda G,R: flow_clustering(G,R,method="mqi")[0]
        self.add_random_neighborhood_samples(ratio=ratio,nthreads=nthreads,timeout=timeout,
                method=func,methodname="mqi")


# General MIDI Level 1 PERCUSSION KEY MAP
# REF: https://www.midi.org/specifications-old/item/gm-level-1-sound-set
GM1_FULL_MAP = {
    "Acoustic_Bass_Drum": [35],
    "Bass_Drum_1": [36],
    "Side_Stick": [37],
    "Acoustic_Snare": [38],
    "Hand_Clap": [39],
    "Electric_Snare": [40],
    "Low_Floor_Tom": [41],
    "Closed_Hi_Hat": [42],
    "High_Floor_Tom": [43],
    "Pedal_Hi-Hat": [44],
    "Low_Tom": [45],
    "Open_Hi-Hat": [46],
    "Low-Mid_Tom": [47],
    "Hi-Mid_Tom": [48],
    "Crash_Cymbal_1": [49],
    "High_Tom": [50],
    "Ride_Cymbal_1": [51],
    "Chinese_Cymbal": [52],
    "Ride_Bell": [53],
    "Tambourine": [54],
    "Splash_Cymbal": [55],
    "Cowbell": [56],
    "Crash_Cymbal_2": [57],
    "Vibraslap": [58],
    "Ride_Cymbal_2": [59],
    "Hi_Bongo": [60],
    "Low_Bongo": [61],
    "Mute_Hi_Conga": [62],
    "Open_Hi_Conga": [63],
    "Low_Conga": [64],
    "High_Timbale": [65],
    "Low_Timbale": [66],
    "High_Agogo": [67],
    "Low_Agogo": [68],
    "Cabasa": [69],
    "Maracas": [70],
    "Short_Whistle": [71],
    "Long_Whistle": [72],
    "Short_Guiro": [73],
    "Long_Guiro": [74],
    "Claves": [75],
    "Hi_Wood_Block": [76],
    "Low_Wood_Block": [77],
    "Mute_Cuica": [78],
    "Open_Cuica": [79],
    "Mute_Triangle": [80],
    "Open_Triangle": [81]
}

# MAGENTA MAPPING
ROLAND_REDUCED_MAPPING = {
    "KICK": [36],
    "SNARE": [38, 37, 40],
    "HH_CLOSED": [42, 22, 44],
    "HH_OPEN": [46, 26],
    "TOM_3_LO": [43, 58],
    "TOM_2_MID": [47, 45],
    "TOM_1_HI": [50, 48],
    "CRASH": [49, 52, 55, 57],
    "RIDE":  [51, 53, 59]
}

# GrooveToolbox 5 Part Kit Mappings
Groove_Toolbox_5Part_keymap = {
    "kick": [36, 35],
    "snare": [38, 37, 40],
    "closed": [42, 22, 44, 51, 53, 59],     # Closed cymbals (hihat and ride)
    "open": [46, 26, 49, 52, 55, 57],       # Open cymbals (open hihat, crash)
    "Toms": [43, 58, 47, 45, 50, 48, 41]    # Toms (low mid and high)
}

# GrooveToolbox 3 Part Kit Mappings
Groove_Toolbox_3Part_keymap = {
    "low": [36, 35],                                        # Kick
    "mid": [38, 37, 40, 43, 58, 47, 45, 50, 48, 41],        # Snare and Tom
    "hi": [42, 22, 44, 51, 53, 59, 46, 26, 49, 52, 55, 57]  # Hats/Crashes/Rides
}

# GrooveToolbox General MIDI Mappings
Groove_Toolbox_GM_keymap = {
    "kick": [35, 36],
    "snare": [37, 38, 40],
    "closed hihat": [42, 44],
    "open hihat": [46],
    "ride": [51, 53, 59],
    "crash": [49, 57],
    "extra cymbal": [52, 55],
    "low tom": [41, 43, 45],
    "mid tom": [47, 48],
    "high tom": [50]
}

# https://bernhard.hensler.net/roland-td-11-setup-midi-mapping/
# REF: https://rolandus.zendesk.com/hc/en-us/articles/360005173411-TD-17-Default-Factory-MIDI-Note-Map
ROLAND_TD_17_Full_map = {
    "KICK": [36],
    "SNARE_HEAD": [38],
    "SNARE_RIM": [40],
    "SNARE_X_Stick": [37],
    "TOM_1": [48],
    "TOM_1_RIM": [50],
    "TOM_2": [45],
    "TOM_2_RIM": [47],
    "TOM_3_HEAD": [43],
    "TOM_3_RIM": [58],
    "HH_OPEN_BOW": [46],
    "HH_OPEN_EDGE": [26],
    "HH_CLOSED_BOW": [42],
    "HH_CLOSED_EDGE": [22],
    "HH_PEDAL": [44],
    "CRASH_1_BOW": [49],
    "CRASH_1_EDGE": [55],
    "CRASH_2_BOW": [57],
    "CRASH_2_EDGE": [52],
    "RIDE_BOW": [51],
    "RIDE_EDGE": [59],
    "RIDE_BELL": [53]
}

def get_drum_mapping_using_label(drum_map_label):
    """
    returns the mapping dictionary for a given drum map using a string label identifier

    :param drum_map_label: (string matching the variable names above

    :return: a dictionary of drum maps
    """
    assert drum_map_label in ["GM1_FULL_MAP", "ROLAND_REDUCED_MAPPING", "Groove_Toolbox_5Part_keymap",
                              "Groove_Toolbox_3Part_keymap", "Groove_Toolbox_GM_keymap", "ROLAND_TD_17_Full_map"
                              ], "DRUM MAP LABEL IS INCORRECT"

    if drum_map_label == "GM1_FULL_MAP":
        return GM1_FULL_MAP
    elif drum_map_label == "ROLAND_REDUCED_MAPPING":
        return ROLAND_REDUCED_MAPPING
    elif drum_map_label == "Groove_Toolbox_5Part_keymap":
        return Groove_Toolbox_5Part_keymap
    elif drum_map_label == "Groove_Toolbox_3Part_keymap":
        return Groove_Toolbox_3Part_keymap
    elif drum_map_label == "Groove_Toolbox_GM_keymap":
        return Groove_Toolbox_GM_keymap
    elif drum_map_label == "ROLAND_TD_17_Full_map":
        return ROLAND_TD_17_Full_map


"""Core serializers."""

from rest_framework import serializers

from core.markdown import MarkdownField

from .models import Document

class DocumentSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for documents."""

    content = MarkdownField()

    class Meta:  # noqa
        model = Document
        fields = ('title', 'slug', 'content', 'url')
        extra_kwargs = {
            'url': {
                'view_name': 'api:document-detail',
                'lookup_field': 'slug',
            },
        }


import sys

def check(number, e_buttons):
    number = str(number)
    for i in range(len(number)):
        if int(number[i]) in e_buttons:
            return False
    return True

def make_near_number(channel, e_buttons):
    # 눌리는 버튼 조합으로 가장 근접한 수를 잦는 것
    cnt = 0
    num = channel
    while True:
        # 쁠마
        min_c = channel - cnt
        max_c = channel + cnt

        # 이 수가 만들기 가능하다면
        if min_c >= 0:
            # 검사
            if check(min_c, e_buttons):
                num = min_c
                break

        if max_c >= 0:
            # 검사
            if check(max_c, e_buttons):
                num = max_c
                break

        cnt += 1

    return num

channel = int(sys.stdin.readline())
error_cnt = int(sys.stdin.readline())

if error_cnt == 0:
    print(min(abs(channel - 100), len(str(channel))))
else:
    e_buttons = list(map(int, sys.stdin.readline().split()))

    if channel == 100:
        print(0)
    elif len(e_buttons) >= 10:
        print(abs(channel - 100))
    else:
        tmp = make_near_number(channel, e_buttons)
        print(tmp)
        print(min((abs(tmp - channel) + len(str(tmp))), abs(channel - 100)))


import os
import re
import pickle
import random
import inspect
import argparse
import subprocess
import torch
from torch import optim
from logging import getLogger

from .logger import create_logger
from .loader import AVAILABLE_ATTR

FALSY_STRINGS = {'off', 'false', '0'}
TRUTHY_STRINGS = {'on', 'true', '1'}

MODELS_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'models')

logger = getLogger()

def initialize_exp(params):
    """
    Experiment initialization.
    """
    # dump parameters
    params.dump_path = get_dump_path(params)
    pickle.dump(params, open(os.path.join(params.dump_path, 'params.pkl'), 'wb'))

    # create a logger
    logger = create_logger(os.path.join(params.dump_path, 'train.log'))
    logger.info('============ Initialized logger ============')
    logger.info('\n'.join('%s: %s' % (k, str(v)) for k, v
                          in sorted(dict(vars(params)).items())))
    return logger

def bool_flag(s):
    """
    Parse boolean arguments from the command line.
    """
    if s.lower() in FALSY_STRINGS:
        return False
    elif s.lower() in TRUTHY_STRINGS:
        return True
    else:
        raise argparse.ArgumentTypeError("invalid value for a boolean flag. use 0 or 1")

def attr_flag(s):
    """
    Parse attributes parameters.
    """
    if s == "*":
        return s
    attr = s.split(',')
    assert len(attr) == len(set(attr))
    attributes = []
    for x in attr:
        if '.' not in x:
            attributes.append((x, 2))
        else:
            split = x.split('.')
            assert len(split) == 2 and len(split[0]) > 0
            assert split[1].isdigit() and int(split[1]) >= 2
            attributes.append((split[0], int(split[1])))
    return sorted(attributes, key=lambda x: (x[1], x[0]))

def check_attr(params):
    """
    Check attributes validy.
    """
    if params.attr == '*':
        params.attr = attr_flag(','.join(AVAILABLE_ATTR))
    else:
        assert all(name in AVAILABLE_ATTR and n_cat >= 2 for name, n_cat in params.attr)
    params.n_attr = sum([n_cat for _, n_cat in params.attr])

def get_optimizer(model, s):
    """
    Parse optimizer parameters.
    Input should be of the form:
        - "sgd,lr=0.01"
        - "adagrad,lr=0.1,lr_decay=0.05"
    """
    if "," in s:
        method = s[:s.find(',')]
        optim_params = {}
        for x in s[s.find(',') + 1:].split(','):
            split = x.split('=')
            assert len(split) == 2
            assert re.match("^[+-]?(\d+(\.\d*)?|\.\d+)$", split[1]) is not None
            optim_params[split[0]] = float(split[1])
    else:
        method = s
        optim_params = {}

    if method == 'adadelta':
        optim_fn = optim.Adadelta
    elif method == 'adagrad':
        optim_fn = optim.Adagrad
    elif method == 'adam':
        optim_fn = optim.Adam
        optim_params['betas'] = (optim_params.get('beta1', 0.5), optim_params.get('beta2', 0.999))
        optim_params.pop('beta1', None)
        optim_params.pop('beta2', None)
    elif method == 'adamax':
        optim_fn = optim.Adamax
    elif method == 'asgd':
        optim_fn = optim.ASGD
    elif method == 'rmsprop':
        optim_fn = optim.RMSprop
    elif method == 'rprop':
        optim_fn = optim.Rprop
    elif method == 'sgd':
        optim_fn = optim.SGD
        assert 'lr' in optim_params
    else:
        raise Exception('Unknown optimization method: "%s"' % method)

    # check that we give good parameters to the optimizer
    expected_args = inspect.getargspec(optim_fn.__init__)[0]
    assert expected_args[:2] == ['self', 'params']
    if not all(k in expected_args[2:] for k in optim_params.keys()):
        raise Exception('Unexpected parameters: expected "%s", got "%s"' % (
            str(expected_args[2:]), str(optim_params.keys())))

    return optim_fn(model.parameters(), **optim_params)

def clip_grad_norm(parameters, max_norm, norm_type=2):
    """Clips gradient norm of an iterable of parameters.
    The norm is computed over all gradients together, as if they were
    concatenated into a single vector. Gradients are modified in-place.
    Arguments:
        parameters (Iterable[Variable]): an iterable of Variables that will have
            gradients normalized
        max_norm (float or int): max norm of the gradients
        norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm.
    """
    parameters = list(parameters)
    max_norm = float(max_norm)
    norm_type = float(norm_type)
    if norm_type == float('inf'):
        total_norm = max(p.grad.data.abs().max() for p in parameters)
    else:
        total_norm = 0
        for p in parameters:
            param_norm = p.grad.data.norm(norm_type)
            total_norm += param_norm ** norm_type
        total_norm = total_norm ** (1. / norm_type)
    clip_coef = max_norm / (total_norm + 1e-6)
    if clip_coef >= 1:
        return
    for p in parameters:
        p.grad.data.mul_(clip_coef)

def get_dump_path(params):
    """
    Create a directory to store the experiment.
    """
    assert os.path.isdir(MODELS_PATH)

    # create the sweep path if it does not exist
    sweep_path = os.path.join(MODELS_PATH, params.name)
    if not os.path.exists(sweep_path):
        subprocess.Popen("mkdir %s" % sweep_path, shell=True).wait()

    # create a random name for the experiment
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    while True:
        exp_id = ''.join(random.choice(chars) for _ in range(10))
        dump_path = os.path.join(MODELS_PATH, params.name, exp_id)
        if not os.path.isdir(dump_path):
            break

    # create the dump folder
    if not os.path.isdir(dump_path):
        subprocess.Popen("mkdir %s" % dump_path, shell=True).wait()
    return dump_path

def reload_model(model, to_reload, attributes=None):
    """
    Reload a previously trained model.
    """
    # reload the model
    assert os.path.isfile(to_reload)
    to_reload = torch.load(to_reload)

    # check parameters sizes
    model_params = set(model.state_dict().keys())
    to_reload_params = set(to_reload.state_dict().keys())
    assert model_params == to_reload_params, (model_params - to_reload_params,
                                              to_reload_params - model_params)

    # check attributes
    attributes = [] if attributes is None else attributes
    for k in attributes:
        if getattr(model, k, None) is None:
            raise Exception('Attribute "%s" not found in the current model' % k)
        if getattr(to_reload, k, None) is None:
            raise Exception('Attribute "%s" not found in the model to reload' % k)
        if getattr(model, k) != getattr(to_reload, k):
            raise Exception('Attribute "%s" differs between the current model (%s) '
                            'and the one to reload (%s)'
                            % (k, str(getattr(model, k)), str(getattr(to_reload, k))))

    # copy saved parameters
    for k in model.state_dict().keys():
        if model.state_dict()[k].size() != to_reload.state_dict()[k].size():
            raise Exception("Expected tensor {} of size {}, but got {}".format(
                k, model.state_dict()[k].size(),
                to_reload.state_dict()[k].size()
            ))
        model.state_dict()[k].copy_(to_reload.state_dict()[k])

def print_accuracies(values):
    """
    Pretty plot of accuracies.
    """
    assert all(len(x) == 2 for x in values)
    for name, value in values:
        logger.info('{:<20}: {:>6}'.format(name, '%.3f%%' % (100 * value)))
    logger.info('')

def get_lambda(l, params):
    """
    Compute discriminators' lambdas.
    """
    s = params.lambda_schedule
    if s == 0:
        return l
    else:
        return l * float(min(params.n_total_iter, s)) / s


from torch import nn

class LigthSpeechLoss(nn.Module):
    """ LigthSpeech Loss """

    def __init__(self):
        super(LigthSpeechLoss, self).__init__()

    def forward(self, mel,
                padd_predicted, cemb_out,
                mel_tac2_target,
                D, cemb):
        mel_loss = nn.MSELoss()(mel, mel_tac2_target)

        # similarity_loss = nn.MSELoss()(cemb_out, cemb)
        similarity_loss = nn.L1Loss()(cemb_out, cemb)

        duration_loss = nn.L1Loss()(padd_predicted, D.float())

        return mel_loss, similarity_loss, duration_loss


# -*- coding: utf-8 -*-
from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals,
)
from builtins import *
import json
import pytest
import pytz
import requests
import requests_mock
import uuid
from copy import deepcopy
from datetime import datetime
from pkg_resources import resource_filename

from scriptabit import (
    Task,
    Difficulty,
    CharacterAttribute,
    ChecklistItem,
    SyncStatus,
    TaskService,
    TaskMap)

class MockTask(Task):
    def __init__(
            self,
            _id,
            name='',
            description='',
            completed=False,
            difficulty=Difficulty.easy,
            attribute=CharacterAttribute.strength,
            status=SyncStatus.new,
            due_date=None,
            last_modified=None):
        super().__init__()
        self.__id = _id
        self.name = name
        self.description = description
        self.completed = completed
        self.difficulty = difficulty
        self.attribute = attribute
        self.status = status
        self.due_date = due_date
        self.__last_modified = last_modified or datetime.now(tz=pytz.utc)
        self.__checklist = []

    @property
    def id(self):
        """ Task id """
        return self.__id

    @property
    def name(self):
        """ Task name """
        return self.__name

    @name.setter
    def name(self, name):
        """ Task name """
        self.__name = name

    @property
    def description(self):
        """ Task description """
        return self.__description

    @description.setter
    def description(self, description):
        """ Task description """
        self.__description = description

    @property
    def completed(self):
        """ Task completed """
        return self.__completed

    @completed.setter
    def completed(self, completed):
        """ Task completed """
        self.__completed = completed

    @property
    def difficulty(self):
        """ Task difficulty """
        return self.__difficulty

    @difficulty.setter
    def difficulty(self, difficulty):
        """ Task difficulty """
        if not isinstance(difficulty, Difficulty):
            raise TypeError
        self.__difficulty = difficulty

    @property
    def attribute(self):
        """ Task character attribute """
        return self.__attribute

    @attribute.setter
    def attribute(self, attribute):
        """ Task character attribute """
        if not isinstance(attribute, CharacterAttribute):
            raise TypeError
        self.__attribute = attribute

    @property
    def due_date(self):
        """ The due date if there is one, or None. """
        return self.__due_date

    @due_date.setter
    def due_date(self, due_date):
        """ Sets or clears the due date. """
        if due_date and not isinstance(due_date, datetime):
            raise TypeError
        self.__due_date = due_date

    @property
    def last_modified(self):
        """ The last modified timestamp in UTC. """
        return self.__last_modified

    @property
    def checklist(self):
        """ The checklist, or None if there is no checklist."""
        return self.__checklist

    @checklist.setter
    def checklist(self, checklist):
        """ Sets, or clears the checklist. """
        self.__checklist = checklist

class MockTaskService(TaskService):
    def __init__(self, tasks):
        super().__init__()
        self.tasks = tasks
        self.persisted_tasks = []

    def get_all_tasks(self):
        """ Get all tasks """
        return self.tasks

    def get_task(self, _id):
        """ Gets a task by id """
        # Quick and nasty sequential search, good enough for testing
        for t in self.tasks:
            if t.id == _id:
                return t
        return None

    def persist_tasks(self, tasks):
        self.persisted_tasks = tasks

    def _create_task(self, src=None):
        return MockTask(_id=uuid.uuid4())


"""

Miska Pajukangas
Opiskelijanumero: 150281685

Ohjelma kysyy käyttäjältä kirjain-syötettä, kunnes vastaus on y tai Y, jolloin
silmukka päättyy. Jos syöte taas ei ole n taikka N, ohjelma kertoo syötteen
olevan virheellinen, n ja N syötteillä kysytään vain kysymystä uudelleen.

"""

def main():
    kysymys = True
    while kysymys:
        vastaus = input("Bored? (y/n) ")
        if vastaus == "y" or vastaus == "Y":
            print("Well, let's stop this, then.")
            kysymys = False
        elif vastaus != "n" and vastaus != "N":
            print("Incorrect entry.")

if __name__ == "__main__":
    main()


#!/usr/bin/python3
import time
import datetime
from gpiozero import InputDevice, LED
import subprocess
import requests

# RPI enumeration is:
# pin 5 & 6 are used for the button (3 & ground)
# pin 7 & 9 are used for the LED (4 & ground)

button_pin = 3
led_pin = 4

button = InputDevice(button_pin, pull_up=True)
last_active = False
last_press = None

led = LED(led_pin)
led.on()

def button_hold(now, seconds):
    if seconds > 3:
        print('button hold')
        led.blink(.05, .5)
        requests.get('http://localhost:8080/home')
        time.sleep(2)
        subprocess.call(['shutdown', '-h', 'now'], shell=False)

def button_release(now, seconds):
    print('button release')
    requests.get('http://localhost:8080/button')

while True:
    cur_active = button.is_active
    now = datetime.datetime.now()
    if cur_active and not last_active:
        last_press = now
    if cur_active:
        duration = now - last_press
        button_hold(now, duration.total_seconds())
    if not cur_active and last_active:
        duration = now - last_press
        button_release(now, duration.total_seconds())
    last_active = cur_active
    time.sleep(1/60)


from cvzone.FaceDetectionModule import FaceDetector
from model.resnet import resnet_face18
from torch.nn import DataParallel
from sklearn.metrics.pairwise import cosine_similarity
import cv2, math, json, torch, os
import numpy as np

def load_model():
    model = resnet_face18(use_se=False)
    model = DataParallel(model)
    model_pretrained = torch.load("model/resnet18_110.pth", map_location="cpu")
    model.load_state_dict(model_pretrained)
    model.to(torch.device("cpu"))
    return model

def crop_face (image):
    img_ori = image.copy()
    img, bboxs = detector.findFaces(image)
    # print(bboxs[0]['bbox'])
    x, y, w, h = bboxs[0]['bbox']
    crop = img_ori[y:y+h, x:x+w]
    crop = cv2.resize(crop,(120, 120))
    return crop

def load_image(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = np.dstack((image, np.fliplr(image)))
    image = image.transpose((2, 0, 1))
    image = image[:, np.newaxis, :, :]
    image = image.astype(np.float32, copy=False)
    image -= 127.5
    image /= 127.5
    return image

def FR_inference(processed_image):
    with torch.no_grad():
        data = torch.from_numpy(processed_image)
        data = data.to(torch.device("cpu"))
        output = model(data)
        output = output.data.cpu().numpy()
        fe_1 = output[::2]
        fe_2 = output[1::2]
        feature = np.hstack((fe_1,fe_2))
    return feature

def calculate_angle(emb1, emb2):
    cos_sim = cosine_similarity(emb1, emb2)
    angle = math.acos(cos_sim[0][0])
    angle = math.degrees(angle)
    return angle

if __name__ == "__main__":
    #load model
    model = load_model()
    model.eval()
    detector = FaceDetector()
    img = cv2.imread('guntur.jpg')
    img_crop = crop_face(img)
    img_crop = load_image(img_crop)
    feature = FR_inference(img_crop)

    print("Masukkan Nama:")
    nama = input()
    print (nama, feature)

    f = open('result2.json')
    data = json.load(f)
    f.close()

    data[nama] = feature.tolist()

    with open('result2.json',"w") as outfile:
        json.dump(data, outfile)


import numpy as np
from prettytable import PrettyTable

def manual_input(n, m):
    Q = []
    print("Введите значения таблицы Q построчно:")
    for i in range(n):
        row = []
        for j in range(m):
            value = int(input(f"Введите значение для строки {i + 1}, столбца {j + 1}: "))
            row.append(value)
        Q.append(row)
    return Q

def random_input(n, m):
    return np.random.randint(1, 20, size=(n, m))

def default_input(n, m):
    return np.array([
        [6, 7, 8, 10],
        [4, 5, 6, 13],
        [10, 6, 5, 11],
        [8, 9, 7, 9],
        [1, 2, 1, 2],
        [2, 1, 2, 4],
        [3, 3, 2, 2],
        [4, 1, 3, 3]
    ])

def wald_function(Q):
    # Критерий Вальда
    wald_values = []
    for i in range(n):
        wald = min(Q[i])
        wald_values.append(wald)

    # Создание таблицы PrettyTable для Критерия Вальда
    table_w = PrettyTable()
    table_w.field_names = ["Проект"] + ["Критерий Вальда"]

    # Добавление строк в таблицу table_w
    for i in range(n):
        table_w.add_row([i + 1] + [wald_values[i]])

    # Вывод таблицы Критерия Вальда
    print("\nТаблица Критерия Вальда:")
    print(table_w)

    # Нахождение проекта с минимальным Критерием Вальда
    optimal_project = np.argmax(wald_values) + 1
    best_wald_value = max(wald_values)

    return optimal_project, best_wald_value

def savage_function(Q):
    # Находим максимумы для каждого столбца исходной матрицы Q
    max_values = np.max(Q, axis=0)

    # Создаем таблицу PrettyTable для максимумов столбцов
    table_max_values = PrettyTable()
    table_max_values.field_names = [f"Состояние {i + 1}" for i in range(len(max_values))]
    table_max_values.add_row(max_values)

    print("\nМаксимумы для каждого состояния:")
    print(table_max_values)

    # Создаем матрицу рисков
    risk_matrix = max_values - Q

    # Создаем таблицу PrettyTable для матрицы рисков
    table_risk_matrix = PrettyTable()
    table_risk_matrix.field_names = ["Проект"] + [f"Состояние {j + 1}" for j in range(Q.shape[1])]

    # Добавляем строки в таблицу матрицы рисков
    for i in range(risk_matrix.shape[0]):
        table_risk_matrix.add_row([i + 1] + list(risk_matrix[i]))

    print("\nМатрица рисков:")
    print(table_risk_matrix)

    # Находим максимумы для каждой строки матрицы рисков
    max_values_rows = np.max(risk_matrix, axis=1)

    # Создаем таблицу PrettyTable для максимумов строк
    table_max_values_rows = PrettyTable()
    table_max_values_rows.field_names = ["Проект"] + ["Максимум строки"]

    # Добавляем строки в таблицу максимумов строк
    for i in range(len(max_values_rows)):
        table_max_values_rows.add_row([i + 1, max_values_rows[i]])

    print("\nМаксимумы для каждой строки матрицы рисков:")
    print(table_max_values_rows)

    # Находим минимальное значение максимума для строки
    min_max_row = np.min(max_values_rows)

    # Находим индекс строки с минимальным значением максимума
    optimal_project = np.argmin(max_values_rows) + 1
    return optimal_project, min_max_row

def gurwitz_function(Q, alpha=0.6):

    min_values = np.min(Q, axis=1)
    max_values = np.max(Q, axis=1)

    # Рассчитываем среднее взвешенное значение для каждой строки
    c_values = alpha * min_values + (1 - alpha) * max_values

    # Создаем таблицу PrettyTable
    table_gurwitz = PrettyTable()
    table_gurwitz.field_names = ["Проект", "min", "max", "с"]

    # Добавляем строки в таблицу
    for i in range(n):
        table_gurwitz.add_row([i + 1, min_values[i], max_values[i], c_values[i]])

    print("\nСтолбцы: проект, min, max, с")
    print(table_gurwitz)

    max_c = np.max(c_values)

    # Находим индекс строки с максималььным значением среднего взвешенного
    optimal_project = np.argmax(c_values)

    return optimal_project + 1, max_c

def laplas_function(Q):
    laplas_values = []
    for i in range(n):
        laplas = sum(Q[i]) / m
        laplas_values.append(laplas)

    # Создание таблицы PrettyTable для Критерия Лапласа
    table_l = PrettyTable()
    table_l.field_names = ["Проект"] + ["Критерий Лапласа"]

    # Добавление строк в таблицу table_l
    for i in range(n):
        table_l.add_row([i + 1] + [laplas_values[i]])

    # Вывод таблицы Критерия Лапласа
    print("\nТаблица Критерия Лапласа:")
    print(table_l)

    max_l = np.max(laplas_values)

    # Находим индекс строки с максималььным значением среднего взвешенного
    optimal_project = np.argmax(laplas_values)

    return optimal_project + 1, max_l

def bayes_function(Q, vector=[0.1, 0.4, 0.4, 0.1]):
    # Рассчитываем сумму для каждой строки с учетом весовых коэффициентов
    bayes_values = np.dot(Q, vector)

    # Находим максимум из значений критерия Байеса
    max_bayes_value = np.max(bayes_values)

    # Находим индекс строки с максимальным значением критерия Байеса
    optimal_project = np.argmax(bayes_values) + 1

    # Создаем таблицу PrettyTable
    table_b = PrettyTable()
    table_b.field_names = ["Проект"] + ["Критерий Байеса"]

    # Добавляем строки в таблицу
    for i in range(Q.shape[0]):
        table_b.add_row([i + 1] + [bayes_values[i]])

    print("\nТаблица Критерия Байеса:")
    print(table_b)

    return optimal_project, max_bayes_value

# Ввод способа заполнения таблицы
print("Выберите способ заполнения таблицы Q:\n \
      1. Ручной ввод \n \
      2. Случайные значения \n \
      3. Значения по умолчанию")

choice = int(input("Введите номер способа (1/2/3): "))

if choice == 1:
    # Ввод количества проектов (n) и состояний (m)
    n = int(input("Введите количество проектов (n): "))
    m = int(input("Введите количество состояний (m): "))
    Q = manual_input(n, m)
elif choice == 2:
    # Ввод количества проектов (n) и состояний (m)
    n = int(input("Введите количество проектов (n): "))
    m = int(input("Введите количество состояний (m): "))
    Q = random_input(n, m)
elif choice == 3:
    n, m = 8, 4
    Q = default_input(n, m)
else:
    print("Неверный выбор способа заполнения.")
    exit()

# Преобразование списка в массив NumPy
Q = np.array(Q)

# Создание таблицы PrettyTable для Q
table = PrettyTable()
table.field_names = ["Проект"] + [f"Состояние {j + 1}" for j in range(m)]

# Добавление строк в таблицу
for i in range(n):
    table.add_row([i + 1] + list(Q[i]))

# Вывод исходной таблицы Q
print("\nТаблица Q:")
print(table)

# Критерий Вальда
voice_w , value_w = wald_function(Q)
print(f"Оптимальный проект: Проект {voice_w} с Критерием Вальда = {value_w}")

print("\n\nТаблица Q:")
print(table)
voice_s, value_s = savage_function(Q)
print(f"Оптимальный проект: Проект {voice_s} с Критерием Сэвиджа = {value_s}")

print("\n\nТаблица Q:")
print(table)
# a = float(input('\nВведите весовой коэффициент: '))
voice_g, value_g = gurwitz_function(Q) #, a)
print(f"Оптимальный проект: Проект {voice_g} с Критерием Гурвица = {round(value_g, 2)}")

print("\n\nТаблица Q:")
print(table)
voice_l, value_l = laplas_function(Q)
print(f"Оптимальный проект: Проект {voice_l} с Критерием Лапласа = {value_l}")

print("\n\nТаблица Q:")
print(table)
# v = [float(input('\nВведите весовой коэффициент: ')) for _ in range(m)]
voice_b, value_b = bayes_function(Q) #, v)
print(f"Оптимальный проект: Проект {voice_l} с Критерием Байеса = {voice_l}")

# Создание таблицы PrettyTable для Q
table = PrettyTable()
table.field_names = ["Критерий"] + ["Голос"]

# Добавление строк в таблицу
table.add_row(["Критерий Вальда"] + [voice_w])
table.add_row(["Критерий Сэвиджа"] + [voice_s])
table.add_row(["Критерий Гурвица"] + [voice_g])
table.add_row(["Критерий Лапласа"] + [voice_l])
table.add_row(["Критерий Байеса"] + [voice_b])

# Создаем словарь для хранения голосов критериев

criteria_votes = {
    "Критерий Вальда": voice_w,
    "Критерий Сэвиджа": voice_s,
    "Критерий Гурвица": voice_g,
    "Критерий Лапласа": voice_l,
    "Критерий Байеса": voice_b
}

# Создаем векторы голосов
vectors = {criterion: [] for criterion in criteria_votes}

# Заполняем векторы голосов
for criterion, votes in criteria_votes.items():
    vector = [1 if i + 1 == votes else 0 for i in range(n)]
    vectors[criterion] = vector

# Преобразуем векторы голосов в матрицу
voting_matrix = np.array([vectors[criterion] for criterion in criteria_votes])

# Транспонируем матрицу
voting_matrix_transposed = voting_matrix.T

print("\n\nМатрица голосования:")
# Создаем таблицу PrettyTable
voting_table = PrettyTable()
voting_table.field_names = ["Номер проекта"] + list(criteria_votes.keys()) + ["Сумма голосов"]

# Выводим транспонированную матрицу голосов
for i, row in enumerate(voting_matrix_transposed):
    project_name = f"x_{i+1}"
    row_str = [project_name] + list(map(str, row)) + [sum(row)]
    voting_table.add_row(row_str)

# Выводим таблицу
print(voting_table)

# Находим номер проекта с максимальной суммой голосов
max_sum_project = voting_matrix_transposed.sum(axis=1).argmax() + 1
max_sum = max(voting_matrix_transposed.sum(axis=1))

# Выводим номер проекта и сумму голосов
print(f"Проект с максимальной суммой голосов: x_{max_sum_project} (Сумма голосов: {max_sum})")


from ...core.message import (
    MessageType,
    MessageRequest,
    MessageResponse,
    MessageBody
)

class MessageB0Base(MessageRequest):
    def __init__(self,  protocol_version, message_type, body_type):
        super().__init__(
            device_type=0xB0,
            protocol_version=protocol_version,
            message_type=message_type,
            body_type=body_type
        )

    @property
    def _body(self):
        raise NotImplementedError

class MessageQuery00(MessageB0Base):
    def __init__(self, protocol_version):
        super().__init__(
            protocol_version=protocol_version,
            message_type=MessageType.query,
            body_type=0x00)

    @property
    def _body(self):
        return bytearray([])

class MessageQuery01(MessageB0Base):
    def __init__(self, protocol_version):
        super().__init__(
            protocol_version=protocol_version,
            message_type=MessageType.query,
            body_type=0x01)

    @property
    def _body(self):
        return bytearray([])

class B0MessageBody(MessageBody):
    def __init__(self, body):
        super().__init__(body)
        if len(body) > 15:
            self.door = (body[0] & 0x80) > 0
            self.status = body[0] & 0x7F
            self.time_remaining = body[2] * 60 + body[3]
            self.error_code = body[5]

class B0Message01Body(MessageBody):
    def __init__(self, body):
        super().__init__(body)
        if len(body) > 15:
            self.door = (body[32] & 0x02) > 0
            self.status = body[31]
            self.time_remaining = (0 if body[22] == 0xFF else body[22]) * 3600 + \
                                  (0 if body[23] == 0xFF else body[23]) * 60 + \
                                  (0 if body[24] == 0xFF else body[24])
            self.current_temperature = (body[25] << 8) + (body[26])
            if self.current_temperature == 0:
                self.current_temperature = (body[27] << 8) + body[28]
            self.tank_ejected = (body[32] & 0x04) > 0
            self.water_shortage = (body[32] & 0x08) > 0
            self.water_change_reminder = (body[32] & 0x10) > 0

class MessageB0Response(MessageResponse):
    def __init__(self, message):
        super().__init__(message)
        if self.message_type in [MessageType.notify1, MessageType.query]:
            if self.body_type == 0x01:
                self.set_body(B0Message01Body(super().body))
            elif self.body_type == 0x04:
                pass
            else:
                self.set_body(B0MessageBody(super().body))
        self.set_attr()


def pytest_collection_modifyitems(
    session, config, items
) -> None:
    """
    搜集全部用例
    :param session:
    :param config:
    :param items:所有用例的列表
    :return:
    """
    cases = []
    # 测试用例参数的编码格式改写
    for item in items:
        # items 就是一条用例对象
        # 修改每一条用例对象的 name 和 _nodeid 两个属性的编码
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')


import asyncio
from engine.codec.proto_importer import PlayerLoginRequest,CreateRoleRequest, SpeakOnWorldRequest
from engine.codec.Codec import CodecMgr
from engine.utils.Utils import uint_from_bytes, uint32_to_bytes
from engine.utils.Singleton import Singleton
import uuid

class ClientMessage:
    __slots__ = ["msg_id", "data_len", "data"]

    def __init__(self):
        self.msg_id = 0
        self.data_len = 0
        self.data = bytearray()

    def __str__(self):
        return f"msg_id:{self.msg_id}, self.data_len:{self.data_len}, data:{self.data}"

class ClientMsgPack(Singleton):
    def __init__(self):
        pass

    def pack(self, mess:ClientMessage):
        data = bytearray()
        data += uint32_to_bytes(mess.msg_id)
        data += uint32_to_bytes(len(mess.data))
        data += mess.data
        return data

    def unpack(self, data, index):
        mess = ClientMessage()
        mess.msg_id = uint_from_bytes(data[index:index+4])
        mess.data_len = uint_from_bytes(data[index+4:index+8])
        mess.data = data[index+8:index+8+mess.data_len]
        index+8+mess.data_len
        return mess, index

class EchoClientProtocol(asyncio.Protocol):
    def __init__(self):
        self.transport = None

    def connection_made(self, transport):
        print(f'connection_made: {transport}')

    def data_received(self, data):
        mess, index = ClientMsgPack().unpack(data, 0)
        cmd = CodecMgr().get_proto_name(mess.msg_id)
        obj = CodecMgr().decode(cmd, mess.data)
        print(f"receive:{cmd}, data:{obj}")

    def connection_lost(self, exc):
        print('The server closed the connection')

def send_pack(transport, pck):
    msg_id = CodecMgr().get_proto_id(pck.DESCRIPTOR.name)
    mess = ClientMessage()
    mess.msg_id = msg_id
    mess.data = CodecMgr().encode(pck)
    data = ClientMsgPack().pack(mess)
    transport.write(data)

def send_player_login(player_id, transport):
    req = PlayerLoginRequest()
    req.player_id = player_id
    send_pack(transport, req)
    print(f"player:{player_id} send login")

def send_create_role(player_id, transport):
    req = CreateRoleRequest()
    req.player_id = player_id
    req.role_id = 1010
    send_pack(transport, req)
    print(f"player:{player_id} send create role:{req.role_id}")

def send_speak_world(player_id, name, transport):
    req = SpeakOnWorldRequest()
    req.player_id = player_id
    req.name = name
    req.content = "hello, i'm wind!"
    send_pack(transport, req)
    print(f"player:{player_id} speak world:{req.content}")

async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()
    transport, protocol = await loop.create_connection(
        lambda: EchoClientProtocol(),
        '127.0.0.1', 50100)

    await asyncio.sleep(3)
    player_id = uuid.uuid4().hex
    name = "name_"+player_id[-4:]
    send_player_login(player_id, transport)
    await asyncio.sleep(1)

    send_create_role(player_id, transport)
    await asyncio.sleep(1)

    while True:
        send_speak_world(player_id, name, transport)
        await asyncio.sleep(2)

asyncio.run(main())


import pandas as pd
import numpy as np
import re
import os
import pickle
import sys

from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.cluster import KMeans
from yellowbrick.cluster import KElbowVisualizer
from sklearn.feature_extraction.text import TfidfVectorizer

from cluster_utils import get_options, read_object, save_object , save_txt
from cluster_utils import clear_log, load_log
from cluster_utils import create_log_tag,create_sub_files,create_view,create_view_test

from collections import Counter
from collections import defaultdict

def tfidf_feature(documents, maxx, minn,documents_test):

    vectorizer = CountVectorizer(max_df=maxx, min_df=minn)
    transformer = TfidfTransformer()
    tf = vectorizer.fit_transform(documents)
    tf_test=vectorizer.transform(documents_test)
    tfidf_vectors_test = transformer.fit_transform(tf_test)
    tfidf_vectors = transformer.fit_transform(tf)
    words = vectorizer.get_feature_names()  # Get all the words in the word bag model
    weight = tfidf_vectors.toarray()
    save_txt("words", words)
    print("preprocessing finished......")

    #printing the shape of tfidf_vectors feature vector for test and train
    print(tfidf_vectors.shape,tfidf_vectors_test.shape)

    return tfidf_vectors,tfidf_vectors_test

#Calculate the distance between two vectors

def distance(a, b):
    sum = 0
    for i, j in zip(a, b):
        sum += (abs(i - j) ** 2)

    return sum ** 0.5

from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt

def kmeans_cluster(data,data_test,n_clusters):
    kmeans = KMeans(init="k-means++", n_clusters=n_clusters,
                    n_jobs=-1, random_state=0).fit(data)
    labels = kmeans.labels_
    centers = kmeans.cluster_centers_

    labels_test=kmeans.predict(data_test)
    return labels,labels_test

def k_elbow(data,k_min,k_max,locate_elbow=True):
    model = KMeans(init="k-means++",n_jobs=-1)
    visualizer = KElbowVisualizer(model, k=(k_min,k_max), locate_elbow=True)
    visualizer.fit(data)        # Fit the data to the visualizer
    visualizer.poof()        # Draw/show/poof the data

def main():

    # data = load_log(filename)
    # kmeans_cluster(data)
    if not os.path.exists("{}_{}_cache".format(filename, clusters)):
        os.mkdir("{}_{}_cache".format(filename, clusters))

    filename_test='logs/private_test_set.txt'   #the filename of the test set on which prediction is to be done.

    documents = load_log(filename,chars)
    documents_test=load_log(filename_test,chars)

    tfidf_vectors,tfidf_vectors_test = tfidf_feature(documents,maxx, minn,documents_test)
    labels,labels_test = kmeans_cluster(tfidf_vectors,tfidf_vectors_test,clusters)

    # Instantiate the clustering model and visualizer to find the optimal number of clusters.
    data=tfidf_vectors    #train data
    k_elbow(data,2,20,locate_elbow=True)

    database, labels_info = create_log_tag(labels, filename)
    database_test,labels_info_test=create_log_tag(labels_test,filename_test)

    create_view(labels_info, database)
    create_view_test(labels_info_test, database_test)

if __name__ == '__main__':

    option_dict = get_options()
    filename = option_dict['filename']
    clusters = option_dict['clusters']
    maxx = option_dict['max']
    minn = option_dict['min']
    chars = option_dict['chars']

    main()


from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants
import time
from custom_templates.custom_funcs import get_box

class Game_2(Page):
    form_model = 'player'
    form_fields = ['counting_box']
    def time_remaining(self):
        return self.participant.vars['expiry'] - time.time()
    def is_displayed(self):
        self.participant.vars['game_2_score'] = self.player.get_score()
        return self.time_remaining() > 0
    def get_timeout_seconds(self):
        remaining_time = self.time_remaining()
        return remaining_time
    def app_after_this_page(self, upcoming_apps):
        if self.time_remaining() <= 0:
            self.participant.vars['game_2_score'] = self.player.get_score()
            return upcoming_apps[0]
    def vars_for_template(self):
        img, num_zeros = get_box()
        round_values = ''
        for i in self.session.config['round_values']:
            round_values = round_values + '$' + i + ', '
        round_values = round_values[:len(round_values)-2]
        return {
            "img": img,
            "answer": num_zeros,
            'participant_vars': self.participant.vars,
            "score": self.player.get_score(),
            "round": self.player.round_number-1,
            'time_limit': self.session.config['seconds_for_counting_task'],
            'round_values': round_values
        }

page_sequence = [Game_2]


#!/usr/bin/python3
''' module for the class: Square '''
from .rectangle import Rectangle

class Square(Rectangle):
    ''' a Square class '''
    def __init__(self, size, x=0, y=0, id=None):
        ''' initializes a square '''
        super().__init__(size, size, x, y, id)

    def __str__(self):
        ''' gets the string drawing of the square '''
        return '[Square] ({}) {}/{} - {}'.format(
            self.id, self.x, self.y, self.height)

    @property
    def size(self):
        ''' size getter '''
        return self.width

    @size.setter
    def size(self, val):
        ''' size setter '''
        self.width = val
        self.height = val

    def update(self, *args, **kwargs):
        ''' updates the square '''
        sz = len(args)
        if sz:
            if sz:
                self.id = args[0]
            if sz > 1:
                self.size = args[1]
            if sz > 2:
                self.x = args[2]
            if sz > 3:
                self.y = args[3]
        else:
            self.id = kwargs.get('id', self.id)
            self.size = kwargs.get('size', self.size)
            self.x = kwargs.get('x', self.x)
            self.y = kwargs.get('y', self.y)

    def to_dictionary(self):
        ''' gets a dictionary representation of the square '''
        return {'id': self.id, 'size': self.size,
                'x': self.x, 'y': self.y}


#!/usr/bin/env python3

from argparse import ArgumentParser
from time import localtime, mktime, strftime, struct_time

import shelve
import shutil
import sys

argparser = ArgumentParser(description='''
Extracts a time range from db/tweets and stores it in db/slice.
''')

defaulttime = 'xxxx0101000000'
def parse_time(s):
  if len(s) < 4:
    raise ValueError('Please specify at least the year.')
  t = s + defaulttime[len(s):]
  try:
    return mktime(struct_time((
      int(t[0:4]),
      int(t[4:6]),
      int(t[6:8]),
      int(t[8:10]),
      int(t[10:12]),
      int(t[12:14]),
      0,0,-1)))
  except Exception as e:
    raise ValueError(e)

def today():
  return parse_time(strftime('%Y%02m%02d', localtime()))

argparser.add_argument('-o', action='store_true',
  help='at the end, replace db/tweets by db/slice')
argparser.add_argument('-v', '--verbose', action='store_true',
  help='say what it does')
argparser.add_argument('starttime', nargs='?', type=parse_time,
  help='e.g., 201704021130, or 201704 = 201704010000')
argparser.add_argument('stoptime', nargs='?', type=parse_time,
  help='e.g., 201704021130, or 201704 = 201704010000')

def main():
  args = argparser.parse_args()
  if args.starttime is None:
    args.starttime = today()
  if args.stoptime is None:
    args.stoptime = args.starttime + 60 * 60 * 24
  in_count = out_count = 0
  with shelve.open('db/tweets') as tweets:
    with shelve.open('db/slice','n') as slice:
      for i, t in tweets.items():
        in_count += 1
        if not (args.starttime <= t.time < args.stoptime):
          continue
        out_count += 1
        slice[i] = t
  if args.verbose:
    sys.stdout.write('kept {} out of {} tweets\n'.format(out_count, in_count))
  if args.o:
    shutil.move('db/tweets', 'db/tweets.bck')
    shutil.move('db/slice', 'db/tweets')
    if args.verbose:
      sys.stdout.write('old database saved in db/tweets.bck\n')

if __name__ == '__main__':
  main()


import math

v0 = 0
v = 0.00000000000000000001
m = 1
g = 9.8
dt = 0.001
t = 0
A = 2.4
B = 5.12
C  = -0.124
beta = 0.100
sum= 0

def phi(t):
    return (A + B*t+ C*t**3)*math.e**(-beta*t)

def angvel(t):
    return (phi(t+dt) - phi(t))/dt

while(angvel(t) > 0):
    t += dt
    sum += 0.5*(angvel(t)+angvel(t+dt))*dt

print("angvel is 0 at",t)
print(sum)


import sseclient, requests
from urllib.parse import urlparse, parse_qs
from ermez.connect.abstract_consumer import AbstractConsumer

class Consumer(AbstractConsumer):
    def __init__(self, uri: str, credential):
        self.uri_parsed = urlparse(uri)

        headers = {
            "Accept": "text/event-stream",
            "Authorization": str.encode("Bearer " + credential),
        }

        query = parse_qs(self.uri_parsed.query)

        response = requests.get(
            self.uri_parsed.scheme
            + "://"
            + self.uri_parsed.netloc
            + self.uri_parsed.path,
            stream=True,
            headers=headers,
            params={"topic": [query["topic"][0]]},
        )
        self.client = sseclient.SSEClient(response)

    def get_message(self):
        for event in self.client.events():
            yield event.data