#!/usr/bin/env python3
'''Equivariant pentago networks

Let G = Z_4 be the group of global rotations.  (For now we are ignoring rotations,
as they're harder to deal with.)  Ignoring batch dimension, our interior activations
will have shape [4,width], corresponding to one width-dimension vector per quadrant.
If b is a board, h(b) is some internal layer of the network, and f(b) is the final
logits (shape [3]), we will enforce

1. g h(b) = h(gb)  # equivariance
2. f(b) = f(gb)    # invariance

where g ∈ G acts on internal activations of shape [4,width] by cyclic rotation.
'''

from functools import partial
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np

class Embed(hk.Module):
  """Embed [batch,4,9]-shaped boards equivariantly into [batch,4,width] activations

  We embed each quadrant by summing together embeddings at each position, using
  an embedding tensor of shape [9,3,width].  This tensor is rotated when applying
  it to the non-lower-left quadrants (or rather, those quadrants and rotated) so
  that equivariance holds after embedding.

  We also embed the total stone count, in particular to tell the network whose turn it is.

  Args:
    boards: A [batch,4,9]-shaped integer tensor with values in 0,1,2 (empty, black, white)
    width: Inner embedding dimension

  Returns:
    [batch,4,width]-shaped tensor
  """
  def __init__(self, width):
    super().__init__()
    self._width = width

  def __call__(self, boards):
    batch = boards.shape[0]
    width = self._width
    assert boards.shape == (batch, 4, 9)
    q0, q1, q2, q3 = boards.swapaxes(0,1)
    q1 = q1.reshape(batch, 3, 3).swapaxes(1,2)[:,::-1,:].reshape(batch, 9)
    q2 = q2.reshape(batch, 3, 3)[:,::-1,:].swapaxes(1,2).reshape(batch, 9)
    q3 = q3[:, ::-1]
    rotated = jnp.stack([q0, q2, q3, q1], axis=1)  # Put quads in counterclockwise order
    count = (rotated.reshape(batch, 4*9) != 0).astype(np.int32).sum(axis=-1)
    init = hk.initializers.RandomNormal(1 / np.sqrt(9+1))
    w_quads = hk.get_parameter('w_quads', shape=(9*3, width), init=init)
    w_count = hk.get_parameter('w_count', shape=(19, width), init=init)
    x = jax.nn.one_hot(rotated, 3).reshape(batch, 4, 9*3) @ w_quads
    x += (jax.nn.one_hot(count, 19) @ w_count)[:,None,:]
    assert x.shape == (batch, 4, width)
    return x

def fourier(s, *, axis, scale=0.5):
  """Size 4 Fourier transform"""
  assert s.dtype == np.float32
  s0, s1, s2, s3 = scale * jnp.moveaxis(s, axis, 0)
  s02 = s0 + s2
  s13 = s1 + s3
  t0 = s02 + s13
  t1 = jax.lax.complex(s0 - s2, s3 - s1)
  t2 = s02 - s13
  return t0, t1, t2

def unfourier(t, *, axis, scale=0.5):
  """Size 4 inverse Fourier transform"""
  t0, t1, t2 = t
  t0 = scale * t0
  t2 = scale * t2
  t1 = 2 * scale * t1
  s02 = t0 + t2
  s13 = t0 - t2
  s0 = s02 + t1.real
  s2 = s02 - t1.real
  s1 = s13 - t1.imag
  s3 = s13 + t1.imag
  return jnp.stack([s0, s1, s2, s3], axis=axis)

def convolve(x, y, *, axis, mul=jnp.matmul):
  """Convolve tensors of shape [a,4,b], [b,4,c] → shape [a,4,c]"""
  x = fourier(x, axis=axis, scale=1)
  y = fourier(y, axis=axis, scale=1)
  z = jax.tree_multimap(mul, x, y)
  return unfourier(z, axis=axis, scale=0.25)

def sws_standardize(w, *, gain, eps=1e-4, scale=1):
  """Scaled weight standardize a matrix, with optional scalar gain

  See Brock et al., https://arxiv.org/abs/2101.08692 for details.
  Code modified from https://github.com/deepmind/deepmind-research/blob/master/nfnets/base.py#L121.
  """
  n_in, n_out = w.shape
  w = w - jnp.mean(w, axis=0, keepdims=True)
  sum_sqr = jnp.square(w).sum(axis=0, keepdims=True)
  scale *= jax.lax.rsqrt(jnp.maximum(sum_sqr, eps))  # 1 / sqrt(n_in * var)
  if gain:
    scale *= hk.get_parameter('gain', shape=(n_out,), dtype=w.dtype, init=jnp.ones)
  return scale * w

class SwsLinear(hk.Module):
  """SWS linear layer"""
  def __init__(self, size, *, gain=True):
    super().__init__()
    self._size = size
    self._gain = gain

  def __call__(self, x):
    n_in = x.shape[-1]
    n_out = self._size
    w = hk.get_parameter('w', shape=(n_in, n_out), dtype=x.dtype,
                         init=hk.initializers.VarianceScaling(1, 'fan_in', 'normal'))
    bias = hk.get_parameter('bias', shape=(n_out,), dtype=x.dtype, init=jnp.zeros)
    w = sws_standardize(w, gain=self._gain)
    return x @ w + bias

class SwsConv(hk.Module):
  """SWS convolutional layer"""
  def __init__(self, size, *, gain=True, scale=1):
    super().__init__()
    self._size = size
    self._gain = gain
    self._scale = scale

  def __call__(self, x):
    batch, _, n_in = x.shape
    n_out = self._size
    assert x.shape == (batch, 4, n_in)
    w = hk.get_parameter('w', shape=(4*n_in, n_out), dtype=x.dtype,
                         init=hk.initializers.VarianceScaling(1, 'fan_in', 'normal'))
    bias = hk.get_parameter('bias', shape=(n_out,), dtype=x.dtype, init=jnp.zeros)
    w = sws_standardize(w, gain=self._gain, scale=self._scale)
    w = w.reshape(n_in, 4, n_out)
    y = convolve(x, w, axis=1) + bias
    assert y.shape == (batch, 4, n_out)
    return y

class EquivariantLinear:
  """An equivariant linear layer"""
  def __init__(self, size):
    self._size = size

  def __call__(self, x):
    batch, _, width = x.shape
    assert x.shape == (batch, 4, width)
    # Make a [batch,4,4*width]-shape tensor by rolling x 4 ways
    rolls = jnp.stack([jnp.roll(x, -k, axis=1) for k in range(4)], axis=1)
    rolls = rolls.reshape(batch, 4, 4*width)
    x = hk.Linear(self._size)(rolls)
    assert x.shape == (batch, 4, self._size)
    return x

class EquivariantBlock(hk.Module):
  """An equivariant resnet block: x → x + linear(gelu(ev_linear(norm(x))))"""

  def __init__(self, *, mid):
    super().__init__()
    self._mid = mid

  def __call__(self, x):
    mid = self._mid
    batch, _, width = x.shape
    assert x.shape == (batch, 4, width)
    y = hk.LayerNorm(axis=-1, create_scale=True, create_offset=True)(x)
    y = EquivariantLinear(self._mid)(y)
    y = jax.nn.gelu(y)
    y = hk.Linear(width)(y)
    return x + y

class NFBlock(hk.Module):
  """Normalizer-free resnet block

  See Brock et al., https://arxiv.org/abs/2101.08692 for details.
  """
  def __init__(self, mid):
    super().__init__()
    self._mid = mid

  def __call__(self, x, *, in_scale, out_scale):
    batch, _, width = x.shape
    assert x.shape == (batch, 4, width)
    gamma = np.sqrt(2 / (1 - 1/np.pi))
    y = SwsConv(self._mid, scale=gamma / in_scale)(x)
    y = jax.nn.relu(y)
    y = SwsConv(width, scale=out_scale)(y)
    return x + y

class InvariantLogits:
  def __call__(self, x, *, classes=3):
    """Invariant final logit layer

    Returns [batch,3]-shaped outcome logits on the value of the positions, with indices
    0,1,2 corresponding to outcomes -1,0,1 representing value for the player to move.
    """
    batch, _, width = x.shape
    assert x.shape == (batch, 4, width)
    x = hk.LayerNorm(axis=-1, create_scale=False, create_offset=False)(x)
    x = jnp.mean(x, axis=1)
    logits = hk.Linear(classes)(x)
    return logits

def invariant_net(boards, *, layers, width, mid):
  """A simple equivariant pentago reset"""
  x = Embed(width)(boards)
  for layer in range(layers):
    x = EquivariantBlock(mid=mid)(x)
  logits = InvariantLogits()(x)
  metrics = {}
  return logits, metrics

def nf_net_scale(layer, *, layer_scale):
  return jnp.sqrt(1 + layer*jnp.square(layer_scale))

def nf_net(boards, *, layers, width, mid, layer_scale, classes=3):
  """A normalizer-free equivariant pentago resnet"""
  scale = partial(nf_net_scale, layer_scale=layer_scale)
  means, stds = [], []
  def stat(x):
    means.append(jnp.mean(x))
    stds.append(jnp.std(x))
  x = Embed(width)(boards)
  stat(x)
  for layer in range(layers):
    x = NFBlock(mid)(x, in_scale=scale(layer), out_scale=layer_scale)
    stat(x)
  x = 0.25 / scale(layers) * x.sum(axis=1)
  logits = hk.Linear(classes)(x)
  metrics = dict(means=jnp.asarray(means),
                 stds=jnp.asarray(stds))
  return logits, metrics


from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil

authorize = extensions.soft_extension_authorizer('compute', 'image_size')

def make_image(elem):
    elem.set('{%s}size' % Image_size.namespace, '%s:size' % Image_size.alias)

class ImagesSizeTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('images')
        elem = xmlutil.SubTemplateElement(root, 'image', selector='images')
        make_image(elem)
        return xmlutil.SlaveTemplate(root, 1, nsmap={
            Image_size.alias: Image_size.namespace})

class ImageSizeTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('image', selector='image')
        make_image(root)
        return xmlutil.SlaveTemplate(root, 1, nsmap={
            Image_size.alias: Image_size.namespace})

class ImageSizeController(wsgi.Controller):

    def _extend_image(self, image, image_cache):
        key = "%s:size" % Image_size.alias
        image[key] = image_cache['size']

    @wsgi.extends
    def show(self, req, resp_obj, id):
        context = req.environ["nova.context"]
        if authorize(context):
            # Attach our slave template to the response object
            resp_obj.attach(xml=ImageSizeTemplate())
            image_resp = resp_obj.obj['image']
            # image guaranteed to be in the cache due to the core API adding
            # it in its 'show' method
            image_cached = req.get_db_item('images', image_resp['id'])
            self._extend_image(image_resp, image_cached)

    @wsgi.extends
    def detail(self, req, resp_obj):
        context = req.environ['nova.context']
        if authorize(context):
            # Attach our slave template to the response object
            resp_obj.attach(xml=ImagesSizeTemplate())
            images_resp = list(resp_obj.obj['images'])
            # images guaranteed to be in the cache due to the core API adding
            # it in its 'detail' method
            for image in images_resp:
                image_cached = req.get_db_item('images', image['id'])
                self._extend_image(image, image_cached)

class Image_size(extensions.ExtensionDescriptor):
    """Adds image size to image listings."""

    name = "ImageSize"
    alias = "OS-EXT-IMG-SIZE"
    namespace = ("http://docs.openstack.org/compute/ext/"
                 "image_size/api/v1.1")
    updated = "2013-02-19T00:00:00+00:00"

    def get_controller_extensions(self):
        controller = ImageSizeController()
        extension = extensions.ControllerExtension(self, 'images', controller)
        return [extension]


"""

Explanation
Test Case 1:

After first round, the numbering is [1, 0, 1, 2].

Test Case 2:

After first round, the numbering is [2, 1, 0, 1, 2, 3].

After second round, the numbering is [3, 2, 1, 1, 2, 3].

"""

def get_max_num(n, m, positions):
    max_num = 0
    for i in range(n):
        max_num = max(max_num, get_num(i, positions))
    return max_num

def get_num(i, positions):
    num = 0
    for pos in positions:
        if i <= pos:
            num += 1
        else:
            num -= 1
    return num

if __name__ == "__main__":
    t = int(input())
    for i in range(t):
        n, m = map(int, input().split())
        positions = list(map(int, input().split()))
        print(get_max_num(n, m, positions))


import os
import errno
import logging
import numbers
import warnings
from inspect import cleandoc
from collections import OrderedDict

import numpy as np
import h5py
from atom.api import Str, Enum, Value, Bool, Dict, Int, Typed, List, set_default

from exopy.tasks.api import SimpleTask, RootTask, validators
from exopy.tasks.tasks.logic.loop_task import LoopTask
from exopy.utils.atom_util import ordered_dict_from_pref, ordered_dict_to_pref
from exopy.utils.traceback import format_exc

logger = logging.getLogger(__name__)

class SmartSaveTask(SimpleTask):
    """Save the specified data in a HDF5 file.

    Try to detect if it is placed inside of nested loops and reshape
    the data accordingly.

    """
    #: Folder in which to save the data.
    folder = Str('{default_path}').tag(pref=True, fmt=True)

    #: Name of the file in which to write the data.
    filename = Str().tag(pref=True, fmt=True)

    #: Currently opened file object. (File mode)
    file_object = Value()

    #: Header to write at the top of the file.
    header = Str().tag(pref=True, fmt=True)

    #: Values to save as an ordered dictionary.
    saved_values = Typed(OrderedDict, ()).tag(pref=(ordered_dict_to_pref,
                                                    ordered_dict_from_pref))

    #: Parameters to save
    saved_parameters = Typed(OrderedDict, ()).tag(pref=(ordered_dict_to_pref,
                                                        ordered_dict_from_pref))

    #: Data type (float16, float32, etc.)
    datatype = Enum('float16', 'float32', 'float64').tag(pref=True)

    #: Flag indicating whether or not initialisation has been performed.
    initialized = Bool(False)

    database_entries = set_default({'file': None})

    wait = set_default({'activated': True})  # Wait on all pools by default.

    def perform(self):
        """ Collect all data and write them to file.

        """
        # Initialisation.
        if not self.initialized:
            for name, path in self._loop_paths.items():
                self._dims.append(self.database.get_value(path, f"{name}_point_number"))
            self._dims.reverse()

            self._formatted_labels = []

            full_folder_path = self.format_string(self.folder)
            filename = self.format_string(self.filename)
            full_path = os.path.join(full_folder_path, filename)
            try:
                self.file_object = h5py.File(full_path, 'w', libver='latest')
            except IOError:
                log = logging.getLogger()
                msg = "In {}, failed to open the specified file."
                log.exception(msg.format(self.name))
                self.root.should_stop.set()

            self.root.resources['files'][full_path] = self.file_object

            f = self.file_object

            parameters_group = f.create_group("parameters")
            for l, v in self.saved_parameters.items():
                label = self.format_string(l)
                value = self.format_and_eval_string(v)
                parameters_group.create_dataset(label, data=value)

            data_group = f.create_group("data")
            for l, v in self.saved_values.items():
                label = self.format_string(l)
                self._formatted_labels.append(label)
                value = self.format_and_eval_string(v)
                if isinstance(value, np.ndarray):
                    names = value.dtype.names
                    if names:
                        for m in names:
                            data_shape = tuple(self._dims) + value[m].shape
                            data_group.create_dataset(label + '_' + m,
                                             data_shape,
                                             self.datatype)
                    else:
                        data_shape = tuple(self._dims) + value.shape
                        data_group.create_dataset(label,
                                         data_shape,
                                         self.datatype)
                else:
                    data_shape = tuple(self._dims)
                    data_group.create_dataset(label, data_shape,
                                     self.datatype)
            f.attrs['header'] = self.format_string(self.header)
            f.attrs['count_calls'] = 0
            f.swmr_mode = True

            self.initialized = True

        f = self.file_object
        count_calls = f.attrs['count_calls']

        labels = self._formatted_labels
        for i, v in enumerate(self.saved_values.values()):
            value = self.format_and_eval_string(v)
            index = np.unravel_index(count_calls, self._dims)
            if isinstance(value, np.ndarray) and value.dtype.names:
                for m in value.dtype.names:
                    f['data'][labels[i] + '_' + m][index] = value[m]
            else:
                expected_size = f['data'][labels[i]][index].size
                if isinstance(value, np.ndarray) and value.size != expected_size:
                    logger.warning("Incorrect data size. Attempting to resize the data")
                    value = np.copy(value)
                    value.resize(f['data'][labels[i]][index].shape)
                f['data'][labels[i]][index] = value

        f.attrs['count_calls'] = count_calls + 1
        f.flush()

    def check(self, *args, **kwargs):
        """Check that all the parameters are correct.

        """
        self.detect_loops(update_names=False)

        err_path = self.get_error_path()
        test, traceback = super(SmartSaveTask, self).check(*args, **kwargs)
        try:
            full_folder_path = self.format_string(self.folder)
            filename = self.format_string(self.filename)
        except Exception:
            return test, traceback

        full_path = os.path.join(full_folder_path, filename)

        overwrite = False
        if os.path.isfile(full_path):
            overwrite = True
            traceback[err_path + '-file'] = \
                cleandoc('''File already exists, running the measure will
                override it.''')

        try:
            f = open(full_path, 'ab')
            f.close()
            if not overwrite:
                os.remove(full_path)
        except Exception as e:
            mess = 'Failed to open the specified file : {}'.format(e)
            traceback[err_path] = mess.format(e)
            return False, traceback

        labels = set()
        for i, (l, v) in enumerate(self.saved_values.items()):
            try:
                labels.add(self.format_string(l))
            except Exception:
                traceback[err_path + '-label_' + str(i)] = \
                    'Failed to evaluate label {}:\n{}'.format(l, format_exc())
                test = False
            try:
                self.format_and_eval_string(v)
            except Exception:
                traceback[err_path + '-entry_' + str(i)] = \
                    'Failed to evaluate entry {}:\n{}'.format(v, format_exc())
                test = False

        if len(labels) != len(self.saved_values):
            traceback[err_path] = "All labels must be different."
            return False, traceback

        labels = set()
        for i, (l, v) in enumerate(self.saved_parameters.items()):
            try:
                labels.add(self.format_string(l))
            except Exception:
                traceback[err_path + '-label_' + str(i)] = \
                    'Failed to evaluate label {}:\n{}'.format(l, format_exc())
                test = False
            try:
                self.format_and_eval_string(v)
            except Exception:
                traceback[err_path + '-entry_' + str(i)] = \
                    'Failed to evaluate entry {}:\n{}'.format(v, format_exc())
                test = False

        if not test:
            return test, traceback

        if len(labels) != len(self.saved_parameters):
            traceback[err_path] = "All labels must be different."
            return False, traceback

        return test, traceback

    def detect_loops(self, update_names=True):
        n = self.parent
        tmp_names = []
        tmp_paths = OrderedDict()
        while not isinstance(n, RootTask):
            if isinstance(n, LoopTask):
                if n.name not in self.saved_parameters:
                    tmp_names.append((n.name, f"{{{n.name}_loop_values}}"))
                else:
                    tmp_names.append((n.name, self.saved_parameters[n.name]))
                tmp_paths[n.name] = n.path
            n = n.parent
        # Only refresh the names if the number of nested loops has changed
        if update_names and len(tmp_names) != len(self.saved_parameters):
            self.saved_parameters = OrderedDict(tmp_names)
        self._loop_paths = OrderedDict(tmp_paths)

    #: List of the formatted names of the entries.
    _formatted_labels = List()

    #: List of the paths of the loops
    _loop_paths = Typed(OrderedDict, ())

    #: Data dimensions:
    _dims = List()


#encoding:utf-8
import random
import re
import time
import unittest

import requests
import urllib3

from interface import common_function

host = "https://dev.yizhibo.tv"
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class Test(unittest.TestCase):

    def setUp(self):
        print("start")
    def tearDown(self):
        time.sleep(1)
        print("the end")

    def test_freelive_watcher(self):
        #登录
        login_perf=requests.post(host +"/dev/appgw/userlogin?", data=common_function.login_data("e10adc3949ba59abbe56e057f20f883e", 13399887766), verify=False)
        #验证返回内容中是否有“ok”字样
        self.assertIn("ok",login_perf.text)
        #提取主播的易播号name
        perf_name=str(re.findall(r"name(.+?)nickname",login_perf.text))[5:-5]
        print("perf_name:",perf_name)
        #获取sessionid
        sessionid_perf=str(re.findall(r"sessionid(.+?)auth",login_perf.text))[5:-5]
        print("performer sessionid:",sessionid_perf)
        #获取主播饭团数
        get_riceroll0=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",get_riceroll0.text)
        riceroll0=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll0.text))[4:-4])
        print("riceroll0",riceroll0)

        #观众登录
        login_watcher=requests.post(host +"/dev/appgw/userlogin?", data=common_function.login_data("e10adc3949ba59abbe56e057f20f883e", 13399778866), verify=False)
        #验证返回内容中是否有“ok”字样
        self.assertIn("ok",login_watcher.text)
        #获取sessionid
        sessionid_watcher=str(re.findall(r"sessionid(.+?)auth",login_watcher.text))[5:-5]
        print("watcher sessionid:",sessionid_watcher)

        #准备直播，获取vid
        prepare=requests.get(host+"/dev/appgw/liveprepare?switch=false&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",prepare.text)
        #提取返回内容中的vid
        vid=str(re.findall(r"vid(.+?)live_url",prepare.text))[5:-5]
        print("vid:",vid)
        #开启直播
        livestart=requests.get(host+"/dev/appgw/livestart?vid="+vid+"&quality=normal&permission=0&thumb=0&sessionid="+sessionid_perf+"&title=performer%E5%B8%A6%E4%BD%A0%E8%BA%AB%E4%B8%B4%E5%85%B6%E5%A2%83%EF%BC%8C%E4%B8%8D%E5%AE%B9%E9%94%99%E8%BF%87&gps_latitude=30.542094&mode=0&gps=1&accompany=0&nettype=wifi&gps_longitude=104.061429&cp=V0_P1_S0_E1_R1_B0_A0_CN_M0",verify=False)
        self.assertIn("ok",livestart.text)

        #赠送礼物：么么哒*1
        send_Agift01=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(1, perf_name, vid, 332, sessionid_watcher), verify=False)
        self.assertIn("ok",send_Agift01.text)
        #获取饭团数
        get_riceroll1=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll1=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll1.text))[4:-4])
        self.assertTrue(riceroll1>riceroll0)

        #赠送幸运礼物：幸运1黑丝*1
        send_Bgift01=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(1, perf_name, vid, 309, sessionid_watcher), verify=False)
        self.assertIn("ok",send_Bgift01.text)
        #获取饭团数
        get_riceroll2=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll2=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll2.text))[4:-4])
        self.assertTrue(riceroll2>riceroll1)

        #赠送钻石礼物:10钻石礼物*1
        send_Cgift01=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(1, perf_name, vid, 308, sessionid_watcher), verify=False)
        self.assertIn("ok",send_Cgift01.text)
        #获取饭团数
        get_riceroll3=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll3=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll3.text))[4:-4])
        self.assertTrue(riceroll3>riceroll2)

        #赠送普通礼物*2
        send_Agift02=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(2, perf_name, vid, 332, sessionid_watcher), verify=False)
        self.assertIn("ok",send_Agift02.text)
        #获取饭团数
        get_riceroll4=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll4=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll4.text))[4:-4])
        self.assertTrue(riceroll4>riceroll3)

        #赠送幸运礼物：幸运1黑丝*520
        send_Bgift02=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(520, perf_name, vid, 309, sessionid_watcher), verify=False)
        self.assertIn("ok",send_Bgift02.text)
        #获取饭团数
        get_riceroll5=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll5=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll5.text))[4:-4])
        self.assertTrue(riceroll5>riceroll4)

        #赠送钻石礼物:10钻石礼物*9
        send_Cgift02=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(9, perf_name, vid, 308, sessionid_watcher), verify=False)
        self.assertIn("ok",send_Cgift02.text)
        #获取饭团数
        get_riceroll6=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll6=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll6.text))[4:-4])
        self.assertTrue(riceroll6>riceroll5)

        #随机赠送任意数量、任一礼物*3次
        for i in range(0,2):
            gifts=["308","309","332","307","311","334"]
            gift_data={
                "number":random.randint(1,20),
                "name":perf_name,
                "vid":vid,
                "goodsid":int(random.choice(gifts)),
                "sessionid":sessionid_watcher
            }
            send_gift=requests.post(host+"/dev/appgw/pay/buy?",data=gift_data,verify=False)
            self.assertIn("ok",send_gift.text)
            #获取饭团数
            get_riceroll7=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
            riceroll7=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll7.text))[4:-4])
            self.assertTrue(riceroll7>riceroll6)
            print("这是第",i+1,"次")

        #获取贵族信息
        get_noble=requests.post(host +"/dev/appgw/getnobleinfo?", data=common_function.headers(sessionid_watcher), verify=False)
        noble1=re.findall(r'"noble_list":(.+?)}}',get_noble.text)
        print("get_nolble:",noble1)
        #截取noble_level
        noble_level=re.findall(r":(.+?),",str(re.findall(r"noble_level(.+?)name",str(noble1))))
        print("noble_level:",noble_level)
        #截取开通贵族价值易币
        noble_ecoin=re.findall(r":(.+?),",str(re.findall(r"ecoin(.+?)rebate_ecoin",str(noble1))))
        print("noble_ecoin: ",noble_ecoin)
        #截取返回易币
        retbate_coin=re.findall(r":(.+?),",str(re.findall(r"rebate_ecoin(.+?)image_id",str(noble1))))
        print("retbate_coin:",retbate_coin)

        #开通贵族
        level=random.randint(0,len(noble_level)-1)
        buy_noble=requests.post(host +"/dev/appgw/buynoble?", data=common_function.buynoble(noble_level[level], noble_ecoin[level], retbate_coin[level], 0, vid, sessionid_watcher), verify=False)
        self.assertIn("ok",buy_noble.text)
        #贵族续费
        noble_continue=requests.post(host +"/dev/appgw/buynoble?", data=common_function.buynoble(noble_level[level], noble_ecoin[level], retbate_coin[level], 0, vid, sessionid_watcher), verify=False)
        self.assertIn("ok",noble_continue.text)
        #贵族自动续费
        noble_auto_continue=requests.post(host +"/dev/appgw/buynoble?", data=common_function.buynoble(noble_level[level], noble_ecoin[level], retbate_coin[level], 1, vid, sessionid_watcher), verify=False)
        self.assertIn("ok",noble_auto_continue.text)
        #获取专属礼物
        getparamnew=requests.get(host+"/dev/appgw/getparamnew?devtype=android&sessionid="+sessionid_watcher,verify=False)
        #获取第一个位置的专属礼物id和对应等级(备用)
        #noblegift= common_function.get_noblegift_id(getparamnew)
        #print("noblegift_id",noblegift,int(noblegift[1]))
        #gift_position=int(noblegift[1])-1
        #print("position",gift_position)
        #获取第一个位置的专属礼物id和对应等级
        noblegift= common_function.get_noblegift_id(getparamnew)
        print("noblegift_id",noblegift[0],int(str(noblegift[1])[:-10]))
        gift_position=noble_level.index(str(noblegift[1])[:-10])
        print("position",gift_position)
        #购买第一个贵族专属礼物对应的等级
        #开通贵族
        buy_noble=requests.post(host +"/dev/appgw/buynoble?", data=common_function.buynoble(noble_level[gift_position], noble_ecoin[gift_position], retbate_coin[gift_position], 0, vid, sessionid_watcher), verify=False)
        self.assertIn("ok",buy_noble.text)
        #赠送贵族专属礼物
        print(common_function.gift_data(1, perf_name, vid, noblegift[0], sessionid_watcher))
        noble_gift=requests.post(host +"/dev/appgw/pay/buy?", data=common_function.gift_data(1, perf_name, vid, noblegift[0], sessionid_watcher), verify=False)
        self.assertIn("ok",noble_gift.text)
        #获取饭团数
        get_riceroll8=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        riceroll8=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll8.text))[4:-4])
        self.assertTrue(riceroll8>riceroll7)

        ###商城###

        #获取商城电子券列表
        get_e_coupon_list=requests.get(host+"/wgl/shop/goodslist?sessionid="+sessionid_watcher+"&type=2&number_type=1&goods_type=2,5&start=0&count=6",verify=False)
        self.assertIn("ok",get_e_coupon_list.text)
        #用正则筛选各类信息
        e_coupon_info= common_function.get_goodsinfo(get_e_coupon_list)
        #商品数量
        e_coupon__num=e_coupon_info[-1]
        #购买电子券商品，2代表电子券
        #获取商品数量最多的
        max_num=str(max(map(int,e_coupon__num)))
        if int(max_num)>0:
            #判断数量最多的位置
            e_coupon__position=e_coupon__num.index(max_num)
            #购买电子券
            e_shopping=requests.post(host +"/wgl/shop/goodsbuy", data=common_function.shopping(sessionid_watcher, 2, e_coupon_info[0][e_coupon__position], e_coupon_info[3][e_coupon__position], e_coupon_info[2][e_coupon__position], e_coupon_info[4][e_coupon__position], e_coupon_info[1][e_coupon__position], 1), verify=False)
            #判断返回接口内容
            self.assertIn("ok",e_shopping.text)
            print(e_shopping.content.decode("unicode_escape"))
        else:
            print(r"商城没有可购买的电子券")

        #购买认证
        #获取认证商品列表
        get_authen_list=requests.get(host+"/wgl/shop/goodslist?sessionid="+sessionid_watcher+"&type=2&number_type=1&goods_type=3&start=0&count=6",verify=False)
        print(get_authen_list.text)
        authen_info= common_function.get_goodsinfo(get_authen_list)
        authen_num=authen_info[-1]
        print(len(authen_info),authen_info)
        #获取商品数量最多的
        max_num1=str(max(map(int,authen_num)))
        print(max_num1)
        if int(max_num1)>0:
            #最大值的位置
            authen_position=authen_num.index(max_num1)
            #购买认证
            authen_shopping=requests.post(host +"/wgl/shop/goodsbuy", data=common_function.shopping(sessionid_watcher, 2, authen_info[0][authen_position], authen_info[3][authen_position], authen_info[2][authen_position], authen_info[4][authen_position], authen_info[1][authen_position], 1), verify=False)
            #判断返回内容
            self.assertIn("ok",authen_shopping.text)
            #打印返回后的内容
            print(authen_shopping.content.decode("unicode_escape"))
        else:
            print(r"商城没有可购买的认证")

        #购买座驾
        #获取座驾靓号商品列表
        seat_list=requests.get(host+"/wgl/shop/goodslist?sessionid="+sessionid_watcher+"&type=2&number_type=2&goods_type=4&start=0&count=6",verify=False)
        print(seat_list.text)
        seat_info= common_function.get_goodsinfo(seat_list)
        seat_num=seat_info[-1]
        print(len(seat_info),seat_num)
        #获取商品数量最多的
        max_num4=str(max(map(int,seat_num)))
        print(max_num4)
        if int(max_num4)>0:
            #最大值的位置
            seat_position=seat_num.index(max_num4)
            #购买生日靓号
            seat_shopping=requests.post(host +"/wgl/shop/goodsbuy", data=common_function.shopping(sessionid_watcher, 2, authen_info[0][seat_position], authen_info[3][seat_position], authen_info[2][seat_position], authen_info[4][seat_position], authen_info[1][seat_position], 1), verify=False)
            #判断返回内容
            self.assertIn("ok",seat_shopping.text)
            #打印返回后的内容
            print(r"座驾购买：",seat_shopping.content.decode("unicode_escape"))
        else:
            print(r"商城没有可购买的座驾")

        #购买8位靓号
        #获取8位靓号的礼物信息
        get_eightnumber_list=requests.get(host+"/wgl/shop/goodslist?sessionid="+sessionid_watcher+"&type=1&number_type=1&goods_type=0&start=0&count=6",verify=False)
        self.assertIn("ok",get_eightnumber_list.text)
        #提取id和type
        eightnumber_info= common_function.get_number(get_eightnumber_list)
        #购买8位靓号
        buy_eightnumber=requests.post(host +"/wgl/shop/goodsbuy", data=common_function.buy_number(sessionid_watcher, eightnumber_info[1][0][:-1], eightnumber_info[0][0]), verify=False)
        self.assertIn("ok",buy_eightnumber.text)

        #购买生日靓号
        #获取生日靓号信息
        get_birth_list=requests.get(host+"/wgl/shop/goodslist?sessionid="+sessionid_watcher+"&type=1&number_type=2&goods_type=0&start=0&count=6",verify=False)
        print(get_birth_list.text)
        #提取id和type
        birth_info= common_function.get_number(get_birth_list)
        #购买生日靓号
        buy_eightnumber=requests.post(host +"/wgl/shop/goodsbuy", data=common_function.buy_number(sessionid_watcher, birth_info[1][0][:-1], birth_info[0][0]), verify=False)
        self.assertIn("ok",buy_eightnumber.text)

        #结束直播
        livestop=requests.get(host+"/dev/appgw/livestop?vid="+vid+"&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",livestop.text)

    def test_freelive_shopping(self):
        #登录
        login_perf=requests.post(host +"/dev/appgw/userlogin?", data=common_function.login_data("e10adc3949ba59abbe56e057f20f883e", 13399887766), verify=False)
        #验证返回内容中是否有“ok”字样
        self.assertIn("ok",login_perf.text)
        #提取主播的易播号name
        perf_name=str(re.findall(r"name(.+?)nickname",login_perf.text))[5:-5]
        print("perf_name:",perf_name)
        #获取sessionid
        sessionid_perf=str(re.findall(r"sessionid(.+?)auth",login_perf.text))[5:-5]
        print("performer sessionid:",sessionid_perf)
        #获取主播饭团数
        get_riceroll0=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",get_riceroll0.text)
        riceroll0=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll0.text))[4:-4])
        print("riceroll0",riceroll0)

        #观众登录
        login_watcher=requests.post(host +"/dev/appgw/userlogin?", data=common_function.login_data("e10adc3949ba59abbe56e057f20f883e", 13399778866), verify=False)
        #验证返回内容中是否有“ok”字样
        self.assertIn("ok",login_watcher.text)
        #提取观看端的易播号name
        watcher_name=str(re.findall(r"name(.+?)nickname",login_watcher.text))[5:-5]
        print("watcher_name:",watcher_name)
        #获取sessionid
        sessionid_watcher=str(re.findall(r"sessionid(.+?)auth",login_watcher.text))[5:-5]
        print("watcher sessionid:",sessionid_watcher)

        #准备直播，获取vid
        prepare=requests.get(host+"/dev/appgw/liveprepare?switch=false&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",prepare.text)
        #提取返回内容中的vid
        vid=str(re.findall(r"vid(.+?)live_url",prepare.text))[5:-5]
        print("vid:",vid)
        #开启直播
        livestart=requests.get(host+"/dev/appgw/livestart?vid="+vid+"&quality=normal&permission=0&thumb=0&sessionid="+sessionid_perf+"&title=performer%E5%B8%A6%E4%BD%A0%E8%BA%AB%E4%B8%B4%E5%85%B6%E5%A2%83%EF%BC%8C%E4%B8%8D%E5%AE%B9%E9%94%99%E8%BF%87&gps_latitude=30.542094&mode=0&gps=1&accompany=0&nettype=wifi&gps_longitude=104.061429&cp=V0_P1_S0_E1_R1_B0_A0_CN_M0",verify=False)
        self.assertIn("ok",livestart.text)

        #普通单抽
        #普通十连抽

        #高级单抽
        get_high_one=requests.get(host+"/dev/agservice/admin/superlottery?vid="+vid+"&sessionid="+sessionid_watcher+"&number=1",verify=False)
        self.assertIn("ok",get_high_one.text)
        #高级十连抽
        get_high_ten=requests.get(host+"/dev/agservice/admin/superlottery?vid="+vid+"&sessionid="+sessionid_watcher+"&number=10",verify=False)
        self.assertIn("ok",get_high_ten.text)
        #高级百连抽
        get_high_ten=requests.get(host+"/dev/agservice/admin/superlottery?vid="+vid+"&sessionid="+sessionid_watcher+"&number=100",verify=False)
        self.assertIn("ok",get_high_ten.text)
        #送背包礼物（考虑观影券问题）
        #获取背包礼物信息
        get_package_info=requests.get(host+"/dev/appgw/userpackagetools?&start=0&count=100000&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",get_package_info.text)
        #获取礼物名称
        package_list=get_package_info.content.decode("unicode_escape")
        print(package_list)
        #获取背包道具的type和tool_id
        packagegoods_info= common_function.get_packagegoods_info(get_package_info)
        #判断是否存在可赠送礼物type为1
        if '1' in packagegoods_info[0]:
            print("背包存在可赠送礼物")
            bag_position=packagegoods_info[0].index('1')
            print("bag_position",bag_position)
            tool_id=packagegoods_info[1][bag_position]
            #赠送背包道具
            send_pag_gift=requests.get(host+"/dev/appgw/usepackagetool?&number=1&touser="+perf_name+"&vid="+vid+"&usetype=1&toolid="+tool_id+"&sessionid="+sessionid_watcher,verify=False)
            print(send_pag_gift.content.decode("unicode_escape"))
            self.assertIn("ok",send_pag_gift.text)
            #获取饭团数
            get_riceroll1=requests.get(host+"/dev/appgw/pay/asset?sessionid="+sessionid_perf,verify=False)
            riceroll1=int(str(re.findall(r"riceroll(.+?)limitcash",get_riceroll1.text))[4:-4])
            self.assertTrue(riceroll1>riceroll0)
        else:
            print("背包没有可赠送礼物")

        #转赠礼物
        gift_giving=requests.get(host+"/dev/appgw/usepackagetool?&toolid="+packagegoods_info[1][0]+"&usetype=2&vid="+vid+"&number=1&touser="+perf_name+"&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",gift_giving.text)

        #购买/续费默默守护
        buy_momo=requests.get(host+"/dev/appgw/pay/buyguardian?vid="+vid+"&guardianid=1&to_user="+perf_name+"&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",buy_momo.text)
        #购买/续费一生守护
        buy_alive=requests.get(host+"/dev/appgw/pay/buyguardian?vid="+vid+"&guardianid=2&to_user="+perf_name+"&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",buy_alive.text)
        #购买/续费珍爱守护
        buy_love=requests.get(host+"/dev/appgw/pay/buyguardian?vid="+vid+"&guardianid=3&to_user="+perf_name+"&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",buy_love.text)

        #抢座
        grab_seat=requests.get(host+"/dev/appgw/grabseat?name="+perf_name+"&vid="+vid+"&sessionid="+sessionid_watcher+"&level=1&ecoin=100",verify=False)
        self.assertIn("ok",grab_seat.text)
        #弹幕
        bulletscreen=requests.get(host+"/dev/appgw/bulletscreen?content="+"asd"+"&vid="+vid+"&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",bulletscreen.text)

        #主播开启秘聊接单
        anchorstartsolo=requests.get(host+"/dev/appgw/anchorstartsolo?type=2&price=10&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",anchorstartsolo.text)
        print("anchorstartsolo:",anchorstartsolo.text)
        solo_id=str(re.findall(r"solo_id(.+?)channel_id",anchorstartsolo.text))[4:-4]
        #主播端心跳
        anchorsoloheartbt=requests.get(host+"/dev/appgw/anchorsoloheartbt?sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",anchorsoloheartbt.text)
        #客户端发起秘聊申请
        usercallsolo=requests.get(host+"/dev/appgw/usercallsolo?solo_id="+solo_id+"&sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",usercallsolo.text)
        print("usercallsolo:",usercallsolo.text)
        #客户端心跳
        usersoloheartbt=requests.get(host+"/dev/appgw/usersoloheartbt?sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",usersoloheartbt.text)
        #主播端结束直播
        livestop=requests.get(host+"/dev/appgw/livestop?vid="+vid+"&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",livestop.text)
        #主播端接受秘聊
        anchoracceptsolo=requests.get(host+"/dev/appgw/anchoracceptsolo?accept=1&username="+watcher_name+"&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",anchoracceptsolo.text)
        print("anchoracceptsolo:",anchoracceptsolo.text)
        #主播端心跳
        anchorsoloheartbt=requests.get(host+"/dev/appgw/anchorsoloheartbt?sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",anchorsoloheartbt.text)
        #客户端心跳
        usersoloheartbt=requests.get(host+"/dev/appgw/usersoloheartbt?sessionid="+sessionid_watcher,verify=False)
        self.assertIn("ok",usersoloheartbt.text)
        #客户端退出秘聊
        stopsolo=requests.get(host+"/dev/appgw/stopsolo?sessionid="+sessionid_watcher,verify=False)
        #self.assertIn("ok",stopsolo.text)
        print("stopsolo:",stopsolo.text)

    def test_freelive_performer(self):
        #登录
        login_perf=requests.post(host +"/dev/appgw/userlogin?", data=common_function.login_data("e10adc3949ba59abbe56e057f20f883e", 13399887766), verify=False)
        #验证返回内容中是否有“ok”字样
        self.assertIn("ok",login_perf.text)
        #提取主播的易播号name
        perf_name=str(re.findall(r"name(.+?)nickname",login_perf.text))[5:-5]
        print("perf_name:",perf_name)
        #获取sessionid
        sessionid_perf=str(re.findall(r"sessionid(.+?)auth",login_perf.text))[5:-5]
        print("performer sessionid:",sessionid_perf)

        #观众登录
        login_watcher=requests.post(host +"/dev/appgw/userlogin?", data=common_function.login_data("e10adc3949ba59abbe56e057f20f883e", 13399778866), verify=False)
        #验证返回内容中是否有“ok”字样
        self.assertIn("ok",login_watcher.text)
        #提取观看端的易播号name
        watcher_name=str(re.findall(r"name(.+?)nickname",login_watcher.text))[5:-5]
        print("watcher_name:",watcher_name)
        #获取sessionid
        sessionid_watcher=str(re.findall(r"sessionid(.+?)auth",login_watcher.text))[5:-5]
        print("watcher sessionid:",sessionid_watcher)

        #准备直播，获取vid
        prepare=requests.get(host+"/dev/appgw/liveprepare?switch=false&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",prepare.text)
        #提取返回内容中的vid
        vid=str(re.findall(r"vid(.+?)live_url",prepare.text))[5:-5]
        print("vid:",vid)
        #开启直播
        livestart=requests.get(host+"/dev/appgw/livestart?vid="+vid+"&quality=normal&permission=0&thumb=0&sessionid="+sessionid_perf+"&title=performer%E5%B8%A6%E4%BD%A0%E8%BA%AB%E4%B8%B4%E5%85%B6%E5%A2%83%EF%BC%8C%E4%B8%8D%E5%AE%B9%E9%94%99%E8%BF%87&gps_latitude=30.542094&mode=0&gps=1&accompany=0&nettype=wifi&gps_longitude=104.061429&cp=V0_P1_S0_E1_R1_B0_A0_CN_M0",verify=False)
        self.assertIn("ok",livestart.text)

        #主播发红包
        createredpack=requests.get(host+"/dev/appgw/pay/createredpack?count=10&vid="+vid+"&sessionid="+sessionid_perf+"&title=%E6%81%AD%E5%96%9C%E5%8F%91%E8%B4%A2%EF%BC%8C%E5%A4%A7%E5%90%89%E5%A4%A7%E5%88%A9%EF%BC%81&ecoin=20",verify=False)
        self.assertIn("ok",createredpack.text)
        print(createredpack.text)
        #从系统消息中找到红包消息
        #get_redpack_info=requests.get("http://123.57.240.208:3100/getstatus?gid=0&vid="+vid+"&sid=rDg2T6VDLQMjTrUgjbHVEJlLjReNxKuk&hid=475&lt=1561357084&cid=0&aid=37&cnt=0")
        #print(get_redpack_info.text)
        #pack_code=str(re.findall(r'hb(.+?)hnm',get_redpack_info.text))
        #print("pack_code",pack_code)
        #客户端打开红包
        #redpack=requests.get(host+"/dev/appgw/pay/redpack?vid="+vid+"&code=dqssmvmg"+pack_code+"esox0040xmty10&sessionid="+sessionid_watcher,verify=False)
        #print(redpack.text)

        #主播发送弹幕
        perf_bulletscreen=requests.get(host+"/dev/appgw/bulletscreen?content="+"asd"+"&vid="+vid+"&sessionid="+sessionid_perf,verify=False)
        self.assertIn("ok",perf_bulletscreen.text)

        #抽奖单抽
        #抽奖十连抽

        #


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

#
# SPDX-License-Identifier: GPL-3.0
#
# GNU Radio Python Flow Graph
# Title: AM Modulation (SSB)
# GNU Radio version: 3.10.3.0

from packaging.version import Version as StrictVersion

if __name__ == '__main__':
    import ctypes
    import sys
    if sys.platform.startswith('linux'):
        try:
            x11 = ctypes.cdll.LoadLibrary('libX11.so')
            x11.XInitThreads()
        except:
            print("Warning: failed to XInitThreads()")

from PyQt5 import Qt
from gnuradio import qtgui
from gnuradio.filter import firdes
import sip
from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import filter
from gnuradio import gr
from gnuradio.fft import window
import sys
import signal
from argparse import ArgumentParser
from gnuradio.eng_arg import eng_float, intx
from gnuradio import eng_notation
from gnuradio import zeromq
from gnuradio.qtgui import Range, RangeWidget
from PyQt5 import QtCore

from gnuradio import qtgui

class ssb_transmitter(gr.top_block, Qt.QWidget):

    def __init__(self):
        gr.top_block.__init__(self, "AM Modulation (SSB)", catch_exceptions=True)
        Qt.QWidget.__init__(self)
        self.setWindowTitle("AM Modulation (SSB)")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "ssb_transmitter")

        try:
            if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
                self.restoreGeometry(self.settings.value("geometry").toByteArray())
            else:
                self.restoreGeometry(self.settings.value("geometry"))
        except:
            pass

        ##################################################
        # Variables
        ##################################################
        self.volume = volume = 10
        self.samp_rate = samp_rate = 192000
        self.interp = interp = 4
        self.carrier_freq = carrier_freq = 16000
        self.audio_rate = audio_rate = 48000

        ##################################################
        # Blocks
        ##################################################
        self._volume_range = Range(0, 20, 0.1, 10, 200)
        self._volume_win = RangeWidget(self._volume_range, self.set_volume, "Audio Gain", "counter_slider", float, QtCore.Qt.Horizontal)
        self.top_layout.addWidget(self._volume_win)
        self.zeromq_push_sink_0 = zeromq.push_sink(gr.sizeof_gr_complex, 1, 'tcp://127.0.0.1:50301', 100, False, (-1))
        self.qtgui_freq_sink_x_0 = qtgui.freq_sink_c(
            2048, #size
            window.WIN_BLACKMAN_hARRIS, #wintype
            0, #fc
            samp_rate, #bw
            "", #name
            1,
            None # parent
        )
        self.qtgui_freq_sink_x_0.set_update_time(0.10)
        self.qtgui_freq_sink_x_0.set_y_axis((-140), 10)
        self.qtgui_freq_sink_x_0.set_y_label('Relative Gain', 'dB')
        self.qtgui_freq_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, 0.0, 0, "")
        self.qtgui_freq_sink_x_0.enable_autoscale(False)
        self.qtgui_freq_sink_x_0.enable_grid(False)
        self.qtgui_freq_sink_x_0.set_fft_average(1.0)
        self.qtgui_freq_sink_x_0.enable_axis_labels(True)
        self.qtgui_freq_sink_x_0.enable_control_panel(False)
        self.qtgui_freq_sink_x_0.set_fft_window_normalized(False)

        labels = ['', '', '', '', '',
            '', '', '', '', '']
        widths = [1, 1, 1, 1, 1,
            1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
            "magenta", "yellow", "dark red", "dark green", "dark blue"]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
            1.0, 1.0, 1.0, 1.0, 1.0]

        for i in range(1):
            if len(labels[i]) == 0:
                self.qtgui_freq_sink_x_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_freq_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_freq_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_freq_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_freq_sink_x_0.set_line_alpha(i, alphas[i])

        self._qtgui_freq_sink_x_0_win = sip.wrapinstance(self.qtgui_freq_sink_x_0.qwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_freq_sink_x_0_win)
        self.blocks_repeat_0 = blocks.repeat(gr.sizeof_float*1, interp)
        self.blocks_multiply_xx_0 = blocks.multiply_vcc(1)
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_ff(volume)
        self.blocks_float_to_complex_0 = blocks.float_to_complex(1)
        self.band_pass_filter_0 = filter.fir_filter_ccf(
            1,
            firdes.band_pass(
                1,
                samp_rate,
                16300,
                19000,
                200,
                window.WIN_HAMMING,
                6.76))
        self.audio_source_0 = audio.source(48000, '', True)
        self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_SIN_WAVE, carrier_freq, 1, 0, 0)
        self.analog_const_source_x_0 = analog.sig_source_f(0, analog.GR_CONST_WAVE, 0, 0, 0)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_const_source_x_0, 0), (self.blocks_float_to_complex_0, 0))
        self.connect((self.analog_sig_source_x_0, 0), (self.blocks_multiply_xx_0, 0))
        self.connect((self.audio_source_0, 0), (self.blocks_multiply_const_vxx_0, 0))
        self.connect((self.band_pass_filter_0, 0), (self.qtgui_freq_sink_x_0, 0))
        self.connect((self.band_pass_filter_0, 0), (self.zeromq_push_sink_0, 0))
        self.connect((self.blocks_float_to_complex_0, 0), (self.blocks_multiply_xx_0, 1))
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_repeat_0, 0))
        self.connect((self.blocks_multiply_xx_0, 0), (self.band_pass_filter_0, 0))
        self.connect((self.blocks_repeat_0, 0), (self.blocks_float_to_complex_0, 1))

    def closeEvent(self, event):
        self.settings = Qt.QSettings("GNU Radio", "ssb_transmitter")
        self.settings.setValue("geometry", self.saveGeometry())
        self.stop()
        self.wait()

        event.accept()

    def get_volume(self):
        return self.volume

    def set_volume(self, volume):
        self.volume = volume
        self.blocks_multiply_const_vxx_0.set_k(self.volume)

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
        self.band_pass_filter_0.set_taps(firdes.band_pass(1, self.samp_rate, 16300, 19000, 200, window.WIN_HAMMING, 6.76))
        self.qtgui_freq_sink_x_0.set_frequency_range(0, self.samp_rate)

    def get_interp(self):
        return self.interp

    def set_interp(self, interp):
        self.interp = interp
        self.blocks_repeat_0.set_interpolation(self.interp)

    def get_carrier_freq(self):
        return self.carrier_freq

    def set_carrier_freq(self, carrier_freq):
        self.carrier_freq = carrier_freq
        self.analog_sig_source_x_0.set_frequency(self.carrier_freq)

    def get_audio_rate(self):
        return self.audio_rate

    def set_audio_rate(self, audio_rate):
        self.audio_rate = audio_rate

def main(top_block_cls=ssb_transmitter, options=None):

    if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
        Qt.QApplication.setGraphicsSystem(style)
    qapp = Qt.QApplication(sys.argv)

    tb = top_block_cls()

    tb.start()

    tb.show()

    def sig_handler(sig=None, frame=None):
        tb.stop()
        tb.wait()

        Qt.QApplication.quit()

    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGTERM, sig_handler)

    timer = Qt.QTimer()
    timer.start(500)
    timer.timeout.connect(lambda: None)

    qapp.exec_()

if __name__ == '__main__':
    main()


import os
import re
import glob
import uuid
import sys
import time

try:
    import pip
except ImportError:
    pip = None

from . import fs_tracker
from .util import shquote

class Experiment(object):
    """Experiment information."""

    def __init__(self, key, filename, args, pythonenv,
                 project=None,
                 artifacts=None,
                 status='waiting',
                 resources_needed=None,
                 time_added=None,
                 time_started=None,
                 time_last_checkpoint=None,
                 time_finished=None,
                 info={},
                 git=None,
                 metric=None,
                 pythonver=None,
                 max_duration=None):

        self.key = key
        self.args = []
        self.filename = filename

        if filename and '::' in filename:
            self.filename = '-m'
            module_name = filename.replace('::', '.')
            if module_name.startswith('.'):
                module_name = module_name[1:]

            self.args.append(module_name)

        if args:
            self.args += args

        self.args = [shquote(a) for a in self.args]

        self.pythonenv = pythonenv
        self.project = project
        self.pythonver = pythonver if pythonver else sys.version_info[0]

        workspace_path = os.path.abspath('.')
        try:
            model_dir = fs_tracker.get_model_directory(key)
        except BaseException:
            model_dir = None

        self.artifacts = {
            'workspace': {
                'local': workspace_path,
                'mutable': False,
                'unpack': True
            },
            'modeldir': {
                'local': model_dir,
                'mutable': True,
                'unpack': True
            },
            'output': {
                'local': fs_tracker.get_artifact_cache('output', key),
                'mutable': True,
                'unpack': True
            },
            'tb': {
                'local': fs_tracker.get_tensorboard_dir(key),
                'mutable': True,
                'unpack': True
            },
            '_metrics': {
                'local': fs_tracker.get_artifact_cache('_metrics', key),
                'mutable': True,
                'unpack': True
            }
        }
        if artifacts is not None:
            self.artifacts.update(artifacts)

        self.resources_needed = resources_needed
        self.status = status
        self.time_added = time_added
        self.time_started = time_started
        self.time_last_checkpoint = time_last_checkpoint
        self.time_finished = time_finished
        self.info = info
        self.git = git
        self.metric = metric
        self.max_duration = max_duration

    def get_model(self, db):
        modeldir = db.get_artifact(self.artifacts['modeldir'])
        hdf5_files = [
            (p, os.path.getmtime(p))
            for p in
            glob.glob(modeldir + '/*.hdf*') +
            glob.glob(modeldir + '/*.h5')]
        if any(hdf5_files):
            # experiment type - keras
            import keras
            last_checkpoint = max(hdf5_files, key=lambda t: t[1])[0]
            return keras.models.load_model(last_checkpoint)

        if self.info.get('type') == 'tensorflow':
            raise NotImplementedError

        raise ValueError("Experiment type is unknown!")

def create_experiment(
        filename,
        args,
        experiment_name=None,
        project=None,
        artifacts={},
        resources_needed=None,
        metric=None,
        max_duration=None):
    key = experiment_name if experiment_name else \
        str(int(time.time())) + "_" + str(uuid.uuid4())

    packages = []
    for pkg in pip.operations.freeze.freeze():

        if pkg.startswith('-e git+'):
            # git package
            packages.append(pkg)
        elif '==' in pkg:
            # pypi package
            pkey = re.search(r'^.*?(?=\=\=)', pkg).group(0)
            pversion = re.search(r'(?<=\=\=).*\Z', pkg).group(0)

            if resources_needed is not None and \
                    int(resources_needed.get('gpus')) > 0:
                if (pkey == 'tensorflow' or key == 'tf-nightly'):
                    pkey = pkey + '-gpu'

            # TODO add installation logic for torch
            packages.append(pkey + '==' + pversion)

    return Experiment(
        key=key,
        filename=filename,
        args=args,
        pythonenv=[p for p in packages],
        project=project,
        artifacts=artifacts,
        resources_needed=resources_needed,
        metric=metric,
        max_duration=max_duration)

def experiment_from_dict(data, info={}):
    try:
        return Experiment(
            key=data['key'],
            filename=data['filename'],
            args=data.get('args'),
            pythonenv=data['pythonenv'],
            project=data.get('project'),
            status=data['status'],
            artifacts=data.get('artifacts'),
            resources_needed=data.get('resources_needed'),
            time_added=data['time_added'],
            time_started=data.get('time_started'),
            time_last_checkpoint=data.get('time_last_checkpoint'),
            time_finished=data.get('time_finished'),
            info=info if any(info) else data.get('info'),
            git=data.get('git'),
            metric=data.get('metric'),
            pythonver=data.get('pythonver'),
            max_duration=data.get('max_duration')
        )
    except KeyError as e:
        self.logger.error(data)
        raise e


#!/usr/bin/env python3

from eth_abi import encode_abi
from eth_account import Account
from eth_utils import (
    encode_hex,
    function_abi_to_4byte_selector,
)
import time, json
#from web3 import Web3
from web3.auto.infura import w3
import argparse
import math
import lzstring
from eth_account import Account

def _get_args():
    '''
    Internal function. Creates an argparser for the main method to use.

    :return: parser: argparse object for parsing program arguments.
    '''
    parser = argparse.ArgumentParser(
        description=
        "Tool to upload/store files to the Ethereum blockchain",
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument(
        '-r',
        '--rpc-url',
        required=False,
        type=str,
        default="http://127.0.0.1:8545",
        help="The HTTP RPC Endpoint URL you wish to use.")
    parser.add_argument(
        'key',
        type=str,
        help="The Ethereum raw private key for the address that you wish to use to store with."
             " This address must have enough money to store with.")
    parser.add_argument(
        '--gas-price',
        required=False,
        type=int,
        default=(int(6e9) + 5),  # start gas price (1gwei + epsilon)
        help="Gas price to pay.")
    parser.add_argument(
        '--start-gas',
        required=False,
        type=int,
        default=999000,  # start gas price (1gwei + epsilon)
        help="Amount of Gas to pay in Wei.")

    return parser.parse_args()

def main():
    '''
    Main method. Runs the program if it is used standalone (rather than as an exported library).
    '''

    parser = _get_args()
    #prov = Web3.HTTPProvider(parser.rpc_url) # not necessary if using infura
    #w3 = Web3(prov)

    with open('./compiles/Registry.abi','r') as f:
        abi = json.loads(f.read())
    with open('./compiles/Registry.bin', 'r') as f:
        content = f.read()

    acct = Account.privateKeyToAccount(parser.key)
    pool_addr = acct.address

    tx = {
       'from': pool_addr,
       'gasPrice': 3000000000,
       'gas': 2000000,
       'value': 0,
       'data': content
    }
    tx['nonce'] = w3.eth.getTransactionCount(tx['from'])

    signed_tx = w3.eth.account.signTransaction(tx, parser.key)
    sent = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
    receipt = w3.eth.waitForTransactionReceipt(sent)
    print(receipt)

if __name__ == "__main__":
    main()


from django import template
register = template.Library()

@register.assignment_tag(takes_context=True)
def get_attachment(context, comment_id):

    if str(comment_id) in context['attachments']:
        return context['attachments'][str(comment_id)]
    else:
        return False


import paho.mqtt.client as mqtt
import random
import time

# MQTT settings
mqtt_broker_address = "0.0.0.0"
mqtt_topic = "random_data_topic"
geo_topic = "geo_topic"

# create a client instance
client = mqtt.Client()

# connect callback
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(mqtt_topic)

# publish random data
def publish_random_data():
    with open("sample_geo_data.json") as fileobj:
        geodata = fileobj.read()
    while True:
        random_value = random.randint(0, 100)
        client.publish(mqtt_topic, str(random_value))
        client.publish(geo_topic, geodata)
        print(f"Published {random_value} to {mqtt_topic}")
        time.sleep(2)

client.on_connect = on_connect
client.connect(mqtt_broker_address, 1883, 60)
client.loop_start()
publish_random_data()


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'timeConversion' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#

def timeConversion(s):
    # Write your code here
    listS = s.split(":")
    if listS[2].__contains__("PM") and int(listS[0]) < 12:
        listS[0] = str(int(listS[0]) + 12)
        listS[2] = listS[2][0:2]
    elif listS[2].__contains__("AM") and listS[0] == "12":
        listS[0] == "00"
        listS[2] = listS[2][0:2]
    else:
        listS[2] = listS[2][0:2]
    strS = ""
    for i in range(0, 3):
        strS += ":".join(listS[i])
    # print(type(strS))
    return strS

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = timeConversion(s)

    fptr.write(result + '\n')

    fptr.close()


class ListNode(object):
  def __init__(self, val=0,next=None):
    self.val = val
    self.next = next

class Soltuion:
  def remove_k_node_from_list(self, head: ListNode, n: int) -> ListNode:
      """
      type head: ListNode
      :type n: int
      :rtype: ListNode
      """
      # init dummy to use
      dummy = ListNode(0,head)
      # point left pointer at dummy
      left = dummy
      # point right pointer at the head
      right = head
      # we are going to decrement n as we increase right until no n is left
      while n > 0 and right:
        # increment right to the next node value
        right = right.next
        # decrement n by 1
        n -= 1

      # while right is not null.
      # update left point to the left next node
      # update right pointer to the right next node
      while right:
        #these two pointers will now travel together
        # they are spaced out by n due to first while loop
        left = left.next
        right = right.next

      # when left stops it is at the node we want to remove
      # simply reassign this left node next value to skip the node we want to remove
      left.next = left.next.next

      # after all is complete the dummy node is on None and pointing to head.
      # if we right its .next value it will remove itself from start of list
      return dummy.next


import numpy as np
import os
import cv2
import predict

recs = []

th = 45
minSize = 15

def setT(t):
    th = t

class Rect:
    def __init__(self, x, y, w, h):
        self.x1, self.y1, self.w, self.h = x, y, w, h
        self.x2 = self.x1 + self.w
        self.y2 = self.y1 + self.h

    def area(self):
        return self.w*self.h

def calDist(rect1, rect2):

    cx1 = rect1.x1 + rect1.w // 2
    cy1 = rect1.y1 + rect1.h // 2
    cx2 = rect2.x1 + rect2.w// 2
    cy2 = rect2.y1 + rect2.h // 2

    dist = ((cx1 - cx2)** 2 + (cy1 - cy2)** 2)** 0.5

    return dist

def recs_or(rect1, rect2):  # 并集
    x1 = min(rect1.x1, rect2.x1)
    x2 = max(rect1.x2, rect2.x2)
    y1 = min(rect1.y1, rect2.y1)
    y2 = max(rect1.y2, rect2.y2)
    return Rect(x1, y1, x2 - x1, y2 - y1)

def recs_and(rect1, rect2): # 交集
    x1 = max(rect1.x1, rect2.x1)
    y1 = max(rect1.y1, rect2.y1)
    x2 = min(rect1.x2, rect2.x2)
    y2 = min(rect1.y2, rect2.y2)

    if x1 > x2 or y1 > y2:
        return 0
    else:
        return Rect(x1, y1, x2 - x1, y2 - y1)

def isInside(rect1, rect2):
    # 若两矩形相交的比例超过任意一个矩形的50%，则认为inside
    res = recs_and(rect1, rect2)
    if res == 0:
        return False
    else:
        if res.area() > 0.5 * rect1.area() or res.area() > 0.5 * rect2.area():
            return True
    return False

def update(rect):
    if len(recs) == 0:
        recs.append(rect)
        return

    for i in range(len(recs)):
        if calDist(recs[i], rect) < th:
            newRect = recs_or(recs[i], rect)
            del recs[i]
            recs.append(newRect)
            return

    recs.append(rect)
    return

def merge():
    for i in range(len(recs)):
        for j in range(i + 1, len(recs), 1):
            if isInside(recs[i], recs[j]):
                recs[i] = recs_or(recs[i], recs[j])
                del recs[j]
                return False
    return True

def getSobel(ROI):
    if len(ROI.shape) == 3:
        ROI = cv2.cvtColor(ROI, cv2.COLOR_BGR2GRAY)
    xgrad = cv2.Sobel(ROI, cv2.CV_8UC1, 1, 0, 3)
    ygrad = cv2.Sobel(ROI, cv2.CV_8UC1, 0, 1, 3)
    res = cv2.addWeighted(xgrad, 0.5, ygrad, 0.5, 0)
    return res

def getLapliacian(ROI):
    if len(ROI.shape) == 3:
        ROI = cv2.cvtColor(ROI, cv2.COLOR_BGR2GRAY)
    res = cv2.Laplacian(ROI, cv2.CV_8UC1, ksize = 3)
    return res

def calG_C(ROI, sobel, feature):
    if len(ROI.shape) == 3:
        ROI = cv2.cvtColor(ROI, cv2.COLOR_BGR2GRAY)
    sobel[feature==0] = 0

    totalG = 0
    totalN = 0
    totalColor = 0
    colorN = 0

    for i in range(ROI.shape[1]):
        for j in range(ROI.shape[0]):
            if sobel[j][i] != 0:
                totalG += sobel[j][i]
            if ROI[j][i] != 255:
                totalColor += ROI[j][i]
                colorN += 1

    if colorN == 0:
        return 0
    aveColor = totalColor / colorN
    return totalG / aveColor

def locate(img, ori, border, faceBorder, harris, t, sobel):

    final_recs = []

    recs.clear()
    setT(t)

    ori = cv2.cvtColor(ori, cv2.COLOR_GRAY2BGR)

    clone = ori.copy()

    border = border.reshape((border.shape[0], -1))
    faceBorder = faceBorder.reshape((faceBorder.shape[0], -1))

    img[border == 0] = 0
    img[faceBorder == 0] = 0

    img = cv2.addWeighted(img, 1, harris, 1, 0)

    feature = img.copy()

    contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

    ori2 = ori.copy()
    cv2.drawContours(ori2, contours, -1, (0, 0, 255), 3)

    for ct in contours:
        x, y, w, h = cv2.boundingRect(ct)
        update(Rect(x, y, w, h))

    c = merge()

    while c == False:
        c = merge()

    count = 0
    font = cv2.FONT_HERSHEY_SIMPLEX
    for i in range(len(recs)):
        if recs[i].area() > minSize:

            block_feature = img[recs[i].y1:recs[i].y2+1, recs[i].x1:recs[i].x2+1]
            block_sobel = sobel[recs[i].y1:recs[i].y2+1, recs[i].x1:recs[i].x2+1]

            block = clone[recs[i].y1:recs[i].y2+1, recs[i].x1:recs[i].x2+1]

            aveT = calG_C(block, block_sobel, block_feature)

            #if aveT > 10:
            count += 1
            cv2.rectangle(ori, (recs[i].x1, recs[i].y1), (recs[i].x2, recs[i].y2), (0, 255, 0), 1)
            cv2.putText(ori, str(count), (recs[i].x1, recs[i].y1), font, 0.8, (0, 0, 255), 1)
            final_recs.append(recs[i])

    return ori, ori2, final_recs, feature


#!/usr/bin/env python2
from __future__ import print_function

import argparse
import gfal2

from random import sample
from os.path import basename, dirname, realpath
from time import time

class Dump:
    def __init__(self, path):
        self.path = path
        self.nlines = None

    def _count_lines(self):
        with open(self.path) as fd:
            for idx, line in enumerate(fd):
                pass
        self.nlines = idx

    @property
    def ready(self):
        return self.nlines is not None

    def prepare(self):
        self._count_lines()

    def random_lines(self, line_count):
        if not self.ready:
            self.prepare()

        if line_count > self.nlines:
            raise ValueError("Requested more {0} lines, while there is only {1} in {2}".format(line_count, self.nlines, self.path))

        selected = sample(range(self.nlines), line_count)

        res = []
        with open(self.path) as fd:
            for idx, line in enumerate(fd):
                if idx in selected:
                   res.append(line)
        return res

def run_stats(dump, count, output_dir='.', check_type='stat'):
    do_stat = lambda ctx, url: ctx.stat(url)
    do_cksum = lambda ctx, url: ctx.getxattr(url, 'xroot.cksum')

    if check_type == 'stat':
        check_func = do_stat
    elif check_type == 'csum':
        check_func = do_cksum
    elif check_type == 'both':
        check_func = lambda ctx,url: (do_stat(ctx, url), do_cksum(ctx, url))
    else:
        raise ValueError("Wrong check type: shoud be either 'stat', 'csum' or 'both'.")

    output_urls = "{0}/urls_{1}.csv".format(realpath(output_dir), basename(dump.path))
    output_chunks = "{0}/chunks_{1}.csv".format(realpath(output_dir), basename(dump.path))
    URLs = dump.random_lines(count)
    ctx = gfal2.creat_context()
    url_times = []
    chunk_res = 0
    print("Starting stats for {0} at {1}".format(dump.path, time()))
    chunk_start = time()
    for idx, url in enumerate(URLs):
        url = url.strip()
        url_start = time()
        try:
            test_res = check_func(ctx, url)
        except gfal2.GError as e:
            print("Exception while stat {0}: {1}".format(url, e))
            res = 1
        else:
            res = 0
        finally:
            url_end = time()
            url_times.append( (url_start, url_end-url_start, res) )
            chunk_res = max(chunk_res, res)
        if (idx+1) % 50 == 0:
            print("{0} urls processed".format(idx+1))
    chunk_time = url_end - chunk_start
    print("Chunk processed in {0}".format(chunk_time))

    for fname, res in ( (output_urls, url_times), (output_chunks, [(chunk_start, chunk_time, chunk_res)]) ):
        with open(fname, 'a') as fd:
            for tup in res:
                print("{0},{1},{2}".format(tup[0],tup[1],tup[2]), file=fd)

def run_dirac_checks(dump, prefix, count, se, output_dir='.'):
    output_file = "{0}/chunks_{1}.csv".format(realpath(output_dir), basename(dump.path))
    URLs = [u.replace(prefix, '', 1) for u in  dump.random_lines(count)]
    replicas = {}
    for url in URLs:
        replicas[url] = [se]

    from LHCbDIRAC.DataManagementSystem.Client.DataIntegrityClient import DataIntegrityClient
    client = DataIntegrityClient()

    print("Starting stats for {0} at {1}".format(dump.path, time()))
    chunk_start = time()
    res = client.checkPhysicalFiles(replicas=replicas, catalogMetadata={})
    exec_time = time() - chunk_start

    print("Execution took {0}".format(exec_time))

    with open(output_file, 'a') as fd:
        print( "{0},{1},{2}".format(chunk_start, exec_time, 0 if res['OK'] else 1) , file=fd)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--count", help="Number of files to stat. Must not be less then number of lines in a dump", type=int)
    parser.add_argument("-d", "--dumps", help="Comma-separated list of files with URLs for stats. No commas in filenames, please")
    parser.add_argument("-o", "--output_dir", help="Dir where results should be stored")
    parser.add_argument("-t", "--check_type", help="Check type. Either 'stat' (e.g. do only stats), 'cksum' (only cksums) or 'both' (both of the above). Default is 'stat'.", default='stat')
    parser.add_argument("-D", "--DIRAC", help="Run DIRAC-specific checks", action='store_true')
    parser.add_argument("-S", "--SE", help="Dirac SE. Required only for DIRAC-specific tests", default=None)
    parser.add_argument("-p", "--prefix", help="Prefix to remove from PFN to get LFN. Required only for DIRAC-Specific tests", default=None)
    args = parser.parse_args()
    if args.DIRAC and (args.SE is None or args.prefix is None):
        raise ValueError("For DIRAC-specific tests SE and prefix must be given.")
    elif not args.DIRAC and (args.SE is not None or args.prefix is not None):
        raise ValueError("For non DIRAC-specific tests SE and prefix must not be given.")
    return args

if __name__ == '__main__':
    args = parse_args()
    Dumps = []
    for fname in args.dumps.split(','):
        Dumps.append(Dump(fname))

    for dump in Dumps:
        if args.DIRAC:
            run_dirac_checks(dump, args.prefix, args.count, args.SE)
        else:
            run_stats(dump, args.count, output_dir=args.output_dir, check_type=args.check_type)


from .base import FunctionalTest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class NewVisitorTest(FunctionalTest):

    def test_can_start_a_list_for_one_user(self):
        # User searches out new to-do app via its homepage
        self.browser.get(self.live_server_url)

        # User notices page title and header mention to-do lists
        self.browser.quit()
        self.browser = webdriver.Firefox()
        self.browser.get(self.live_server_url)
        self.assertIn('To-Do', self.browser.title)
        header_text = self.browser.find_element_by_tag_name('h1').text
        self.assertIn('To-Do', header_text)

        # User is invited to enter a to-do list item immediately
        inputbox = self.get_item_input_box()
        self.assertEqual(
            inputbox.get_attribute('placeholder'),
            'Enter a to-do item'
        )

        # User types "Buy guitar strings" into a text box
        # When user hits enter, page updates, now page lists
        # "1: Buy guitar strings" as an item in a to-do list
        self.add_list_item('Buy guitar strings')

        # There is still a text box inviting her to add another item.
        # User enters "Re-string guitar"
        self.add_list_item('Re-string guitar')

        # The page updates again - both items are now on the list
        self.wait_for_row_in_list_table('1: Buy guitar strings')
        self.wait_for_row_in_list_table('2: Re-string guitar')

        # Site has generated unique URL for user -- there is text explaining this
        # self.fail('Finish the test!')

        # User visits that URL - their to-do list is still there

        # Satisfied, they go on about their day

    def test_multiple_users_can_start_lists_at_different_urls(self):
        # Edith starts a new to-do list
        self.browser.get(self.live_server_url)
        inputbox = self.get_item_input_box()
        self.add_list_item('Buy guitar strings')

        # Edith noticed that their list has a unique URL
        edith_list_url = self.browser.current_url
        self.assertRegex(edith_list_url, '/lists/.+')

        ## We use a new browser session to make sure that no info
        ## of Edith's is coming through from cookies, etc.
        self.browser.quit()
        self.browser = webdriver.Firefox()

        # Francis visits the home page. Cannot see Edith's list
        self.browser.get(self.live_server_url)
        page_text = self.browser.find_element_by_tag_name('body').text
        self.assertNotIn('Buy guitar strings', page_text)
        self.assertNotIn('Re-string guitar', page_text)

        # Francis starts a new list by entering a new item.
        inputbox = self.get_item_input_box()
        self.add_list_item('Buy milk')

        # Francis gets own unique URL
        francis_list_url = self.browser.current_url
        self.assertRegex(francis_list_url, '/lists/.+')
        self.assertNotEqual(francis_list_url, edith_list_url)

        # Again, no sign of Edith's list
        page_text = self.browser.find_element_by_tag_name('body').text
        self.assertNotIn('Buy guitar strings', page_text)
        self.assertIn('Buy milk', page_text)

        # Both satisfied - days carry on.


import numpy as np
import matplotlib.pyplot as plt

inp_signal = input('Enter binary bit: ')

time = np.array(list())
amplitude = np.array(list())
step = 0
Low_amplitude = 1
High_amplitude = 3

def getSignal(A,time):
    frequency = 2
    phase = 0
    return A*np.sin(2*np.pi*frequency*time+phase)

for i in inp_signal:
    temp_time = np.arange(step,step+2,0.001)
    time = np.append(time,temp_time)
    if i == '0':
        amplitude = np.append(amplitude,getSignal(Low_amplitude,temp_time))
    else:
        amplitude = np.append(amplitude,getSignal(High_amplitude,temp_time))
    step = step + 2

plt.title('ASK Representation of : '+inp_signal)

plt.plot(time,amplitude,color='red')
plt.grid(True)
plt.show()


import argparse
import os
import pandas as pd

def splitBedpe(bedpe,tmp1="tmp1.bed",tmp2="tmp2.bed",header=False,verbose=False):
	""" Function that splits up bedpe files into 2 temp files """
	if header:
		inputBedpe = pd.read_csv(bedpe,sep="\t")
	else:
		inputBedpe = pd.read_csv(bedpe,sep="\t",header=None)
	num_cols = len(inputBedpe.columns)
	id_col = num_cols
	inputBedpe[id_col] = inputBedpe.index
	inputBedpe.iloc[:,[0,1,2,id_col]].to_csv("tmp1.bed", sep="\t", header = False, index = False)
	inputBedpe.iloc[:,[3,4,5,id_col]].to_csv("tmp2.bed", sep="\t", header = False, index = False)
	if num_cols > 6:
		extra_data = inputBedpe.iloc[:,list(range(6,num_cols))].copy()
		return extra_data
	else:
		return None

def doliftOver(liftOver,chain,infile,verbose=False):
	""" Function that implements liftOver """
	cmd = " ".join([liftOver,infile,chain,infile + ".success",infile + ".failure"])
	if verbose:
		print(cmd)
	os.system(cmd)

def mergeliftOver(f1,f2,extra_data,outputfile,verbose=False):
	""" Function that merges liftOver """
	sideA = pd.read_csv(f1, header = None, sep="\t", index_col = 3)
	sideB = pd.read_csv(f2, header = None, sep="\t", index_col = 3)
	merged = sideA.merge(sideB,left_index=True,right_index=True,validate ="one_to_one")
	if extra_data is not None:
		merged = sideA.merge(extra_data,left_index=True,right_index=True,validate ="one_to_one")
	merged.to_csv(outputfile, sep="\t", header = False, index = False)

if __name__ == "__main__":

	parser = argparse.ArgumentParser(description='wrapper for liftOver to accomodate bedpe files')

	parser.add_argument("-i",'--input', dest='infile', action='store', required=True,
                    help='input file name')
	parser.add_argument("-o",'--output', dest='outfile', action='store', required=True,
						help='ouput file name')
	parser.add_argument("-v",'--verbose', dest='verbose', action='store_true', default=False, required=False,
						help='Verbose')
	parser.add_argument("-t",'--header', dest='header', action='store_true', default=False, required=False,
						help='If file has a 1-line header')
	parser.add_argument("-l",'--lift', dest='liftOver', action='store', required=True,
                    help='path to liftOver')
	parser.add_argument("-c",'--chain', dest='chain', action='store', required=True,
						help='path to chain file')

	# parse arguments
	args = parser.parse_args()

	# read in args
	LO       = args.liftOver
	chain    = args.chain
	bedpeIN  = args.infile
	bedpeOUT = args.outfile
	tmp1     = "tmp1.bed"
	tmp2     = "tmp2.bed"
	header	 = args.header
	verbose	 = args.verbose

	# break up the files
	extra_data = splitBedpe(bedpeIN,tmp1,tmp2,header,verbose)

	# perform liftOver
	doliftOver(LO,chain,tmp1,verbose)
	doliftOver(LO,chain,tmp2,verbose)

	# merge liftOvered files
	mergeliftOver(tmp1+".success",tmp2+".success",extra_data,bedpeOUT,verbose)

	# remove tmp files
	os.remove(tmp1)
	os.remove(tmp2)
	os.remove(tmp1+".success")
	os.remove(tmp1+".failure")
	os.remove(tmp2+".success")
	os.remove(tmp2+".failure")


# -*- coding: utf-8 -*-
import threading
import multiprocessing as mp
import sys, pyaudio, os
import speech_recognition as sr
from playsound import playsound
from gtts import gTTS
from datetime import datetime
from respostas_datetime import data, horas
from agenda import agenda

reload(sys)
sys.setdefaultencoding('utf-8')

# TODO: adicionar a thread do calendário para ocorrer de maneira paralela às threads
agora = datetime.now()
frase = []
mara = False
lembrete = False

def processa_funcao(audio):
    global mara
    global agora
    global lembrete
    # mostrando a string de audio que foi criada quando você falou
    tts = gTTS(audio,lang='pt-br')

    print("MARA chegou no processo: ", mara)
    #Da play ao audio
    if("bom dia" in audio.lower()):
        playsound('audios/bom_dia.mp3')
    if("que horas são" in audio.lower()):
        horas(agora)
        playsound('audios/horario.mp3')
    if("que dia é hoje" in audio.lower()):
        data(agora)
        playsound('audios/data_hoje.mp3')
    if ("conte uma piada" in audio.lower()):
        playsound ('audios/piada.mp3')
    if (audio == "ativar contato de emergência"):
        playsound ('audios/emergencia.mp3')
        #enviar_sms()
    if ("quem é você" in audio.lower()):
        playsound ('audios/mara.mp3')
    if ("como você está" in audio.lower()):
        playsound ('audios/estou_bem.mp3')
    if ("criar um lembrete" in audio.lower()):
        lembrete = True
        print("NOVO VALOR DE LEMBRETE:", lembrete)

    mara = False
    print("MARA terminou de processar: ", mara)
    main_task()

def frases(lock):
    global frase
    global mara
    lock.acquire()
    print("MARA(frases): ", mara)
    while(True):
        print("Estou te ouvindo")
        microfone = sr.Recognizer()
        with sr.Microphone() as source:
            #Chama um algoritmo de reducao de ruidos no som
            microfone.adjust_for_ambient_noise(source)
            #Armazena o que foi dito numa variavel
            audio = microfone.listen(source)
        try:
            #Passa a variavel para o algoritmo reconhecedor de padroes
            frase = microfone.recognize_google(audio,language='pt-BR')
            print(frase)
            if "Mara" in frase:
                mara = True
                print("MARA foi encontrada: ", mara)
                break
            if(mara is True):
                print("MARA sendo processada: ", mara)
                processa_funcao(frase)
                break
        except sr.UnknownValueError:
            if(mara is True):
                playsound ('audios/nao_entendi.mp3')
                mara = False
                print("MARA sendo processada(com error): ", mara)

            else:
                print("...")

    lock.release()

def lembrete_func(lock):
    global lembrete
    lock.acquire()
    print("Executando função para criar um lembrete")
    # chama a função agenda para salvar o novo áudio falando os lembretes do dia
    agenda()
    # Executa o áudio com o nome X, criado em agenda
    lembrete = False
    lock.release()

def main_task():
    global mara
    global lembrete
    lock = threading.Lock()

    escutando = threading.Thread(target=frases, args=(lock,)) # procurar "Mara"
    funcao = threading.Thread(target=frases, args=(lock,)) # ouvir a função
    lembrando = threading.Thread(target=lembrete_func, args=(lock,)) # função de agenda ativada

    print("______Lembrete",lembrete)
    if(lembrete is True):
        playsound('audios/lembrete_passo1.mp3')
        lembrando.start()
        lembrando.join()

    if(mara is False):
        print("modo escuta")
        escutando.start()
        escutando.join()
    if(mara is True):
        print("iniciando a funcao")
        playsound('audios/chamou.mp3')
        funcao.start()
        funcao.join()

if __name__ == "__main__":
    main_task()


def solution(sequence, k):
    answer = []
    start = 0
    end = 0
    num = sequence[0] #sequence의 첫 값 저장
    min_len = 99999999999 #임의의 큰 값 저장

    while start <= end and end < len(sequence):
        if num == k:
            if min_len > end - start + 1:
                min_len = end - start + 1
                answer = [start, end]
            num -= sequence[start]
            start += 1

        elif num > k:
            num -= sequence[start]
            start += 1

        elif num < k:
            end+=1
            if end < len(sequence):
                num += sequence[end]

    return answer


import subprocess

import sublime
import sublime_plugin

from . import utils

go_tools = {
    "gocode": "github.com/nsf/gocode",
    "guru": "golang.org/x/tools/cmd/guru",
    "goimports": "golang.org/x/tools/cmd/goimports",
    "godef": "github.com/rogpeppe/godef",
    "gometalinter": "github.com/alecthomas/gometalinter",
    "gorename": "golang.org/x/tools/cmd/gorename",
}

class GoliteInstallCommand(sublime_plugin.ApplicationCommand):
    """GoliteInstallCommand

    Install dependencies

    Extends:
        sublime_plugin.ApplicationCommand
    """

    def run(self):
        sublime.set_timeout_async(self.install_sublime_linter, 0)
        sublime.set_timeout_async(self.install_go_tools, 0)

    def install_sublime_linter(self):
        from package_control.package_manager import PackageManager
        manager = PackageManager()
        manager.install_package("SublimeLinter")

    def install_go_tools(self):
        settings = sublime.load_settings("Golite.sublime-settings")
        update_tools = settings.get("install_cmd_update_go_tools", False)

        print("[golite] start installing go tools: [%s]" %
              ','.join(go_tools.keys()))
        try:
            for tool in go_tools:
                args = ["go", "get", go_tools[tool]]
                if update_tools:
                    args.insert(2, "-u")
                self.run_cmd(args, timeout=60)

                if tool == "gometalinter":
                    args = ["gometalinter", "--install"]
                    if update_tools:
                        args.append("--update")
                    self.run_cmd(args, timeout=300)
        except Exception as e:
            utils.prompt(
                "Golite\n\n"
                "Failed to install go tools, please view the console for more "
                "details.")
            raise e
        print("[golite] go tools installed")

    def run_cmd(self, args, timeout=60):
        print("[golite] running '%s'" % ' '.join(args))
        subprocess.check_call(args, timeout=timeout, env=utils.get_env())

class GoliteDoctorCommand(sublime_plugin.ApplicationCommand):
    """GoliteDoctorCommand

    Audit installation for common issues

    Extends:
        sublime_plugin.ApplicationCommand
    """

    def run(self):
        self.doctor()

    def doctor(self):
        msg_tmpl = ("[%s] Golang installed\n"
                    "[%s] Go tools installed\n"
                    "[%s] Sublimelinter installed")

        # check golang
        go_installed = True
        try:
            utils.which("go")
        except EnvironmentError:
            go_installed = False

        # check go tools
        go_tools_installed = True
        for tool in go_tools.keys():
            try:
                utils.which(tool)
            except EnvironmentError:
                go_tools_installed = False
                break

        # check sublimelinter
        sublime_linter_installed = True
        try:
            import SublimeLinter.lint
        except ImportError:
            sublime_linter_installed = False

        msg = msg_tmpl % tuple([
            "√" if b else "×"
            for b in
            [go_installed, go_tools_installed, sublime_linter_installed]
        ])
        utils.prompt(msg)


# -*- coding: utf-8 -*-
"""Working with Path-like objects."""
from pathlib import Path

def full_path_glob(path):
    """Recursive glob, including directories with regex."""
    resolved = Path(path.absolute().parts[0])
    glob_parts = []
    to_path = True
    for part in path.parts[1:]:
        if to_path and ("*" in part):
            to_path = False
        if to_path:
            resolved /= part
        else:
            glob_parts.append(part)
    gen = resolved.rglob(path.anchor.join(glob_parts))
    return gen

def lsdir(path):
    """List all files and directories in the given path, sorted."""
    return sorted(path.iterdir())

class DisplayablePath:
    """
    Tree-like representation of a path.

    Usage:
    ------
    >>> paths = DisplayablePath.make_tree(Path("foo"))
    >>> for path in paths:
            print(path.displayable())

    """

    display_filename_prefix_middle = "├──"
    display_filename_prefix_last = "└──"
    display_parent_prefix_middle = "    "
    display_parent_prefix_last = "│   "

    def __init__(self, path, parent_path, is_last):
        """Initialise DisplayablePath."""
        self.path = Path(str(path))
        self.parent = parent_path
        self.is_last = is_last
        if self.parent:
            self.depth = self.parent.depth + 1
        else:
            self.depth = 0

    @classmethod
    def make_tree(cls, root, parent=None, is_last=False, criteria=None):
        """Make a path tree from the given top-level path."""
        root = Path(str(root))
        criteria = criteria or cls._default_criteria

        displayable_root = cls(root, parent, is_last)
        yield displayable_root

        children = sorted(
            (path for path in root.iterdir() if criteria(path)),
            key=lambda s: str(s).lower(),
        )
        count = 1
        for path in children:
            is_last = count == len(children)
            if path.is_dir():
                yield from cls.make_tree(
                    path, parent=displayable_root, is_last=is_last, criteria=criteria
                )
            else:
                yield cls(path, displayable_root, is_last)
            count += 1

    @classmethod
    def _default_criteria(cls, path):
        return True

    @property
    def displayname(self):  # noqa
        if self.path.is_dir():
            return self.path.name + "/"
        return self.path.name

    def displayable(self):  # noqa
        if self.parent is None:
            return self.displayname

        _filename_prefix = (
            self.display_filename_prefix_last
            if self.is_last
            else self.display_filename_prefix_middle
        )

        parts = ["{!s} {!s}".format(_filename_prefix, self.displayname)]

        parent = self.parent
        while parent and parent.parent is not None:
            parts.append(
                self.display_parent_prefix_middle
                if parent.is_last
                else self.display_parent_prefix_last
            )
            parent = parent.parent

        return "".join(reversed(parts))


import primes

import time

start_time = time.time()

# Create a vector of integers
# vec = primes.IntVector([1, 2, 3, 4, 5])

hi = primes.find_primes(10000)

for h in hi:
    print(h)

# # Iterate over the vector
# for x in vec:
#     print(x)

end_time = time.time()

time_taken = end_time - start_time

print("Time taken:", time_taken, "seconds")


'''
Coder: Jacky Shew
Description: Returns maximum congestion level of a graph from some vertex u,v.
			 Congestion is defined as number of edge-disjoint paths meaning
			 no usage of edges as other paths, however nodes may be reused.
Input: First Line: Total number of nodes. Following Lines: Adjacency list of the nodes.
	   Repeat until 0.
Input example:
8
4 5 7
5 6
6 7
7
0 7
0 1
1 2 7
0 2 3 4 6
4
1 2
0 2
3 0 1
2
0
'''

import time
import operator
import networkx as nx
from networkx.algorithms.flow import edmonds_karp

def instantiate_graph(nodes):
	degree_pair_list = []
	G = nx.DiGraph()
	#G.add_nodes_from(list(range(nodes))) #can also add_nodes_from(another_graph) #augment
	for i in range(nodes):
		nodes_edge = input().split() #Returns list of nodes to connect to by node[n]
		for j in range(len(nodes_edge)): #Loops for length of elements in 'nodes to connect to'
			current_edge = int(nodes_edge[j])
			if current_edge > i: #Optimise by keeping already connected edges
				G.add_edge(i,current_edge, capacity=1)
				G.add_edge(current_edge, i, capacity=1)
				degree_pair_list += [(i,G.degree(i))]
	#print(degree_pair_list)
	#print(G.edges)
	#print(G.nodes)
	start_time = time.time()
	while_counter = 0
	counter = 0
	congestion = 0
	visited_list = {}
	x = sorted(degree_pair_list, key=lambda x:x[1])
	while while_counter != nodes:
		i = x.pop()
		highest_degree_i = i[0]
		#print(highest_degree_i)
		if highest_degree_i > congestion:
			if highest_degree_i not in visited_list:
				visited_list[highest_degree_i] = []
			for j in range(nodes): #highest_degree_i node source, j node sink
				if j not in visited_list:
						visited_list[j] = []
				if highest_degree_i!=j and G.degree(highest_degree_i)//2 > congestion and G.degree(j)//2 > congestion and j not in visited_list[highest_degree_i]:
					#print("congestion:", congestion, 'G.degree(j):', G.degree(j))
					flow_value = nx.maximum_flow_value(G,highest_degree_i,j)
					congestion = max(congestion, flow_value)
					visited_list[j].append(highest_degree_i)
					counter += 1
					#print(highest_degree_i, j, "congestion:", congestion)
		while_counter += 1
	print(congestion)
	#print("Counter:", counter)
	#print("--- %s seconds ---" % (time.time() - start_time))

nodes = int(input()) #Start
while nodes != 0: #Optimise for duplicated graphs
	if nodes != 1:
		instantiate_graph(nodes)
	else:
		input()
		print(1)
	nodes = int(input())

'''import networkx as nx
from networkx.algorithms.flow import edmonds_karp
from networkx.algorithms import approximation as approx

G = nx.DiGraph()
G.add_edge('x','a', capacity=3.0)
G.add_edge('x','b', capacity=1.0)
G.add_edge('a','c', capacity=3.0)
G.add_edge('b','c', capacity=5.0)
G.add_edge('b','d', capacity=4.0)
G.add_edge('d','e', capacity=2.0)
G.add_edge('c','y', capacity=2.0)
G.add_edge('e','y', capacity=3.0)
R = edmonds_karp(G, 'x', 'y')
flow_value = nx.maximum_flow_value(G, 'x', 'y')
print(flow_value)
flow_value == R.graph['flow_value']
'''


"""Perform Kmeans"""
import numpy as np

MAX_ITERATIONS = 100

class Kmeans:

    def __init__(self, k, data):
        """Initialize the KMeans algorithm for k clusters. The k centers are initialized with
        values from the given data.

        :param k: the number of clusters
        :param data: a numpy array of values to partition
        """
        self.number_of_clusters = k
        self.data = data

    def process(self):
        """Apply the KMeans algorithm to our data.

        The initial K centers are randomly chosen from the dataset. All values in the dataset are assigned
        to the closest center. For each of the k centers, a new center is calculated depending on the
        values that were assigned to it. These steps of assigning items and recalculating the center
        are repeated for a fixed number of iterations.

        :return: a numpy array of class indexes, each item corresponds to the data point at the same index,
                    i.e. result[i] = class of data[i]
        """
        centers = self._randomize_centers()
        assert centers.shape[0] == self.number_of_clusters
        assigned_centers = np.zeros(self.data.shape)

        for _ in range(MAX_ITERATIONS):
            assigned_centers = self._assign_items_to_closest_center(centers)
            centers = self._recalculate_centers(assigned_centers)

        return assigned_centers

    def _randomize_centers(self):
        """Return a list of k random values from the dataset"""
        return np.random.choice(self.data, self.number_of_clusters, replace=False)

    def _assign_items_to_closest_center(self, centers):
        """For each item in self.data, find the center that's closest.
        Proximity is defined as the absolute difference between two integer values.

        :param centers: a list of k values
        :return: a numpy array of center indexes
        """
        diff_data_center = np.zeros((self.number_of_clusters, self.data.shape[0]))
        for i in range(self.number_of_clusters):
            diff_data_center[i] = np.abs(self.data - centers[i])
        return np.argmin(diff_data_center, axis=0)

    def _recalculate_centers(self, assigned_centers):
        """Compute the new centers by calculating the mean of the points that were
        assigned to them.

        :param assigned_centers: a numpy array of center indexes, i.e. assigned_centers[i] = class of data[i]
        :return: a numpy array of k new centers
        """
        new_centers = np.zeros((self.number_of_clusters,))

        for i in range(self.number_of_clusters):
            if self.data[assigned_centers == i].shape[0] != 0:
                new_centers[i] = self.data[assigned_centers == i].mean()
            else:
                new_centers[i] = -255

        return new_centers


import sqlite3
from flask_restful import Resource,reqparse
from flask_jwt import jwt_required
from models.item import ItemModel
class Item(Resource):
	parser = reqparse.RequestParser()
	parser.add_argument(
			'price',
			type=float,
			required=True,
			help='Truong nay khong the bo trong'
	)
	parser.add_argument(
			'store_id',
			type=int,
			required=True,
			help='Truong store id nay khong the bo trong'
	)
	@jwt_required()
	def get(self,name):
		item = ItemModel.find_by_name(name)
		if item:
			return item.json()
		return {"Mess":"Khong tim thay item"},404

	def post(self,name):
		if ItemModel.find_by_name(name):
			return {'mess': "mot item ten la '{}'".format(name)},404
		data = Item.parser.parse_args()
		item = ItemModel(name ,data['price'],data['store_id'])

		try:
			item.save_to_db()
		except:
			return {"Mess":"khong insert dc item"},500
		return item.json(),201

	def delete(self,name):
		item = ItemModel.find_by_name(name)
		if item is None:
			return {'mess': "ko co item"},404
		item.delete_from_db()
		return {'Mess': 'item deleted'}

	def put(self,name):
		data = Item.parser.parse_args()
		item = ItemModel.find_by_name(name)
		if item is None:
			item = ItemModel(name,data['price'],data['store_id'])
		else:
			item.price = data['price']
		item.save_to_db()
		return item.json()

class ItemList(Resource):
	def get(self):
		return {'lists':list(map(lambda x: x.json(),ItemModel.query.all()))}