#!/usr/bin/python
"""
Created on Thu Dec  1 15:41:13 2016

@author: pavla kratochvilova
"""
# Imports----------------------------------------------------------------------
from argparse import ArgumentParser
from time import sleep
import threading
import logging
import pika
# Custom imports --------------------------------------------------------------
import serverlib
import common
from common import send_message
from game import Game
# Setup Python logging --------------------------------------------------------
FORMAT = '%(asctime)-15s %(levelname)s %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.DEBUG)
# Constants -------------------------------------------------------------------
___NAME = 'Battleship Game Client'
___VER = '0.1.0.0'
___DESC = 'Battleship Game Client'
___BUILT = '2016-11-10'
# Classes ---------------------------------------------------------------------
class GameList(object):
    '''List of game sessions.
    '''
    def __init__(self, channel, server_args, clients):
        # Dict of running games
        self.games = {}

        # Communication
        self.server_args = server_args
        self.server_name = server_args.name
        self.clients = clients
        self.channel = channel
        self.games_queue = channel.queue_declare(exclusive=True).method.queue
        self.channel.queue_bind(exchange='direct_logs',
                                queue=self.games_queue,
                                routing_key=common.make_key_games(
                                    self.server_name))
        self.channel.basic_consume(self.reply_request,
                                   queue=self.games_queue,
                                   no_ack=True)

    def add_game(self, name, owner, width, height):
        '''Add game to the dict of games.
        @param name: name of game
        @param owner: owner of game
        @param width: width of field of game
        @param height: height of field of game
        '''
        # Create game in new thread
        game = Game(self, self.server_args, name, owner, width, height)
        self.games[name] = game
        game.start()

        # Send event about added game
        msg = serverlib.make_e_game_open(name)
        send_message(self.channel, msg,
                     common.make_key_game_advert(self.server_name))

        return game

    def remove_game(self, name):
        '''Remove game from the dict of games.
        @param name: name of game
        '''
        try:
            del self.games[name]
            # Send event about removed game
            msg = serverlib.make_e_game_end(name)
            send_message(self.channel, msg,
                         common.make_key_game_advert(self.server_name))
        except KeyError:
            pass

    def get_games(self, state=None):
        '''Get list of games, optionally filtering by state.
        @param state: state of game
        @return list: list of games
        '''
        if state is None:
            return self.games
        return [game for game in self.games.values() if game.state == state]

    def process_request(self, msg_parts, properties):
        '''Process request about list of games.
        @param msg_parts: parsed message
        @param properties: pika.spec.BasicProperties
        @return String, response
        '''
        # Get list of games request
        if msg_parts[0] == common.REQ_LIST_OPENED:
            game_names = [game.name for game in self.get_games('opened')]
            return serverlib.make_rsp_list_opened(game_names)
        if msg_parts[0] == common.REQ_LIST_CLOSED:
            game_names = [game.name for game in self.get_games('closed')]
            return serverlib.make_rsp_list_closed(game_names)

        # Create game request
        if msg_parts[0] == common.REQ_CREATE_GAME:
            if len(msg_parts) != 5 or msg_parts[1].strip() == '' or\
                msg_parts[3].strip() == '' or msg_parts[4].strip() == '':
                return serverlib.make_rsp_invalid_request()

            game_name = msg_parts[1]
            client_name = msg_parts[2]
            width = msg_parts[3]
            height = msg_parts[4]

            if game_name in self.games:
                return serverlib.make_rsp_name_exists()
            if client_name not in self.clients.client_set:
                return serverlib.make_rsp_permission_denied()

            game = self.add_game(game_name, client_name, width, height)
            game.wait_for_ready()
            game.client_queues[client_name] = properties.reply_to
            return serverlib.make_rsp_game_entered(game_name, 1)

        # Join game request
        if msg_parts[0] == common.REQ_JOIN_GAME:
            if len(msg_parts) != 3:
                return serverlib.make_rsp_invalid_request()

            game_name = msg_parts[1]
            client_name = msg_parts[2]

            if game_name not in self.games:
                return serverlib.make_rsp_name_doesnt_exist()
            if client_name not in self.clients.client_set:
                return serverlib.make_rsp_permission_denied()
            if client_name not in self.games[game_name].players and\
                self.games[game_name].state == 'closed':
                return serverlib.make_rsp_permission_denied()

            self.games[game_name].client_queues[client_name] =\
                properties.reply_to
            if client_name not in self.games[game_name].players:
                self.games[game_name].players.add(client_name)
                # Send event that new player was added
                msg = serverlib.make_e_new_player(client_name)
                send_message(self.channel, msg,
                             common.make_key_game_events(self.server_name,
                                                         game_name))

            return serverlib.make_rsp_game_entered(game_name, 0)

        # Spectating game request
        if msg_parts[0] == common.REQ_SPECTATE_GAME:
            if len(msg_parts) != 3:
                return serverlib.make_rsp_invalid_request()

            game_name = msg_parts[1]
            client_name = msg_parts[2]

            if game_name not in self.games:
                return serverlib.make_rsp_name_doesnt_exist()
            if client_name not in self.clients.client_set:
                return serverlib.make_rsp_permission_denied()
            if client_name in self.games[game_name].players:
                return serverlib.make_rsp_permission_denied()

            game = self.games[game_name]
            game.spectators.add(client_name)
            return serverlib.make_rsp_game_spectate(game_name, 0,
                                                    game.spectator_queue)

    def reply_request(self, ch, method, properties, body):
        '''Reply to request about list of games.
        @param ch: pika.BlockingChannel
        @param method: pika.spec.Basic.Deliver
        @param properties: pika.spec.BasicProperties
        @param body: str or unicode
        '''
        LOG.debug('Processing game list request.')
        LOG.debug('Received message: %s', body)
        msg_parts = body.split(common.SEP)
        response = self.process_request(msg_parts, properties)

        # Sending response
        ch.basic_publish(exchange='direct_logs',
                         routing_key=properties.reply_to,
                         body=response)
        LOG.debug('Sent response to client: %s', response)

class Clients(object):
    '''Process client connections.
    '''
    def __init__(self, channel, server_name):
        '''Set a set of client usernames, communication channel, and consuming.
        @param channel: pika connection channel
        @param server_name: name of server
        '''
        # Set of client usernames
        self.client_set = set()

        self.server_name = server_name

        # Communication
        self.channel = channel
        self.connect_queue = channel.queue_declare(exclusive=True).method.queue
        self.channel.queue_bind(exchange='direct_logs',
                                queue=self.connect_queue,
                                routing_key=self.server_name)
        self.channel.basic_consume(self.process_client,
                                   queue=self.connect_queue,
                                   no_ack=True)

    def process_client(self, ch, method, properties, body):
        '''Process client's connection request.
        @param ch: pika.BlockingChannel
        @param method: pika.spec.Basic.Deliver
        @param properties: pika.spec.BasicProperties
        @param body: str or unicode
        '''
        LOG.debug('Processing connection request.')
        LOG.debug('Received message: %s', body)
        msg_parts = body.split(common.SEP)
        response = None

        # Connect request
        if msg_parts[0] == common.REQ_CONNECT:
            if len(msg_parts) != 2:
                response = serverlib.make_rsp_invalid_request()
            else:
                client_name = msg_parts[1].strip()
                if client_name in self.client_set:
                    response = serverlib.make_rsp_username_taken()
                else:
                    self.client_set.add(msg_parts[1].strip())
                    response = serverlib.make_rsp_connected(self.server_name,
                                                            client_name)

        # Disconnect request
        elif msg_parts[0] == common.REQ_DISCONNECT:
            try:
                self.client_set.remove(msg_parts[1])
            except KeyError:
                pass
            response = serverlib.make_rsp_disconnected()

        # Sending response
        ch.basic_publish(exchange='direct_logs',
                         routing_key=properties.reply_to,
                         body=response)
        LOG.debug('Sent response to client: %s', response)

# Functions -------------------------------------------------------------------
def __info():
    return '%s version %s (%s)' % (___NAME, ___VER, ___BUILT)

def publish_server_advertisements(server_on, channel, server_name, interval=2):
    '''Publishes server adverts periodically.
    @param server_on: indicate server running
    @param channel: pika.BlockingChannel
    @param server_name: name of server
    @param interval: interval for publishing
    '''
    while server_on[0]:
        channel.basic_publish(exchange='direct_logs',
                              routing_key=common.make_key_server_advert(),
                              body=server_name)
        sleep(interval)

def stop_server(channel, server_name):
    '''Publishes server advert about stopping server.
    @param channel: pika.BlockingChannel
    @param server_name: name of server
    '''
    channel.basic_publish(exchange='direct_logs',
                          routing_key=common.make_key_server_stop(),
                          body=server_name)

# Main function ---------------------------------------------------------------
if __name__ == '__main__':
    # Parsing arguments
    parser = ArgumentParser()
    parser.add_argument(
        '-H', '--host',
        help='Address of the RabbitMQ server, defaults to %s' %
        common.DEFAULT_SERVER_INET_ADDR,
        default=common.DEFAULT_SERVER_INET_ADDR
    )
    parser.add_argument(
        '-p', '--port',
        help='Port of the RabbitMQ server, defaults to %d' %
        common.DEFAULT_SERVER_PORT,
        default=common.DEFAULT_SERVER_PORT
    )
    parser.add_argument('-n', '--name',
                        help='Server name.',
                        required=True)
    args = parser.parse_args()

    # Connection
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=args.host, port=args.port)
    )
    channel = connection.channel()
    channel.exchange_declare(exchange='direct_logs', type='direct')

    # Client connections
    clients = Clients(channel, args.name)

    # Server advertisements
    server_on = [True]
    t = threading.Thread(target=publish_server_advertisements,
                         args=(server_on, channel, args.name))
    t.setDaemon(True)
    t.start()
    LOG.debug('Started server advertising.')

    # Dict of games
    game_list = GameList(channel, args, clients)

    try:
        while True:
            channel.start_consuming()
    except KeyboardInterrupt as e:
        LOG.debug('Crtrl+C issued ...')
        LOG.info('Terminating server ...')

    server_on[0] = False
    stop_server(channel, args.name)
    LOG.debug('Stopped advertising.')

    # Send message to all games control queues to stop consuming.
    for game in game_list.games.values():
        channel.basic_publish(exchange='direct_logs',
                              routing_key=game.control_queue,
                              body='')


import scrapy

from food.items import FoodItem

class RussianFoodSpider(scrapy.Spider):
    dict_products = {
        '2' : 'Первые блюда',
        '3' : 'Вторые блюда',
        '4' : 'Рецепты напитков',
        '5' : 'Рецепты изделий из теста',
        '6' : 'Рецепты закусок',
        '7' : 'Рецепты сладостей',
        '8' : 'Рецепты заготовок',
        '9' : 'Рецепты соусов',
        '69' : 'Рецепты приправ',
        '1535' : 'Рецепты маринада',
    }

    name = 'gastronom'
    allowed_domains = ['www.gastronom.ru']
    start_urls = ['https://www.gastronom.ru/catalog']

    def parse(self, response):
        all_categories = response.xpath("//a[@class='col-catalog__link_cloud']/@href").extract()
        for link in all_categories:
            yield response.follow(link, callback=self.parse_categories)
        print(1)

    def parse_categories(self, response):
        link_recipes = response.xpath("//a[@class='material-anons__title']/@href").extract()
        next_page = response.xpath("//a[@class='pagination__arrow-next  ']/@href").extract()
        print(1)
        for link in link_recipes:
            yield response.follow(link, callback=self.parse_recipes)
        if next_page:
            if len(next_page[0]) > 2:
                yield response.follow(next_page[0], callback=self.parse_categories)

    def parse_recipes(self, response):
        print(1)
        name = response.xpath("//h1[@class='recipe__title']/text()").extract_first()
        time = response.xpath("//div[@class='recipe__summary-list-des recipe__summary-list-des_big']/text()").extract_first()
        ingradient = response.xpath("//li[@class='recipe__ingredient']/text()").extract()
        step_rpeparation = response.xpath("//div[@class='recipe__step-text']/text()").extract()
        img = response.xpath("//div[@class='main-slider__image-wrap']/img/@src").extract_first()
        if img:
            img = self.allowed_domains[0]+img
            # img = img
        else:
            img = 'Фото нету'
        if len(ingradient) >= 1:
            yield FoodItem(name=name, time=time, ingradient=ingradient,step_rpeparation=step_rpeparation,img=img )


"""
Implementation of torch modules for generative flows. Most of the codebase was adapted
from Ilya Kostrikov's implementation at github.com/ikostrikov/pytorch-flows
"""

import math
import torch
import torch.nn as nn

class BatchNormFlow(nn.Module):
    """ An implementation of a batch normalization layer from
    Density estimation using Real NVP
    (https://arxiv.org/abs/1605.08803).
    """

    def __init__(self, num_inputs, momentum=0.0, eps=1e-5):
        super(BatchNormFlow, self).__init__()

        self.log_gamma = nn.Parameter(torch.zeros(num_inputs))
        self.beta = nn.Parameter(torch.zeros(num_inputs))
        self.momentum = momentum
        self.eps = eps

        self.register_buffer('running_mean', torch.zeros(num_inputs))
        self.register_buffer('running_var', torch.ones(num_inputs))

    def forward(self, inputs, cond_inputs=None, mode='direct'):
        if mode == 'direct':
            if self.training:
                self.batch_mean = inputs.mean(0)
                self.batch_var = (
                    inputs - self.batch_mean).pow(2).mean(0) + self.eps

                self.running_mean.mul_(self.momentum)
                self.running_var.mul_(self.momentum)

                self.running_mean.add_(self.batch_mean.data *
                                       (1 - self.momentum))
                self.running_var.add_(self.batch_var.data *
                                      (1 - self.momentum))

                mean = self.batch_mean
                var = self.batch_var
            else:
                mean = self.running_mean
                var = self.running_var

            x_hat = (inputs - mean) / var.sqrt()
            y = torch.exp(self.log_gamma) * x_hat + self.beta
            return y, (self.log_gamma - 0.5 * torch.log(var)).sum(
                -1, keepdim=True)
        else:
            if self.training:
                mean = self.batch_mean
                var = self.batch_var
            else:
                mean = self.running_mean
                var = self.running_var

            x_hat = (inputs - self.beta) / torch.exp(self.log_gamma)

            y = x_hat * var.sqrt() + mean

            return y, (-self.log_gamma + 0.5 * torch.log(var)).sum(
                -1, keepdim=True)

class CouplingLayer(nn.Module):
    """ An implementation of a coupling layer
    from RealNVP (https://arxiv.org/abs/1605.08803).
    """

    def __init__(self,
                 num_inputs,
                 num_hidden,
                 mask,
                 num_cond_inputs=None,
                 s_act='tanh',
                 t_act='relu',
                 shared=False,
                 pre_mlp=False,
                 pre_mlp_units=64):
        super(CouplingLayer, self).__init__()

        self.num_inputs = num_inputs
        self.mask = mask
        self.shared = shared
        self.pre_mlp = pre_mlp
        self.pre_mlp_units = pre_mlp_units

        activations = {'relu': nn.ReLU, 'sigmoid': nn.Sigmoid, 'tanh': nn.Tanh}
        s_act_func = activations[s_act]
        t_act_func = activations[t_act]

        if num_cond_inputs is not None:
            total_inputs = num_inputs + (num_cond_inputs if not self.pre_mlp else self.pre_mlp_units)
            if self.pre_mlp:
                self.mlp = nn.Sequential(
                    nn.Linear(num_cond_inputs, self.pre_mlp_units), t_act_func(),
                    nn.Linear(self.pre_mlp_units, self.pre_mlp_units), t_act_func(),
                    nn.Linear(self.pre_mlp_units, self.pre_mlp_units)
                    )
        else:
            total_inputs = num_inputs

        if self.shared:
            self.shared_net = nn.Sequential(
                nn.Linear(total_inputs, num_hidden), t_act_func(),
                nn.Linear(num_hidden, num_hidden), t_act_func())
            self.scale_net = nn.Sequential(nn.Linear(num_hidden, num_inputs))
            self.translate_net = nn.Sequential(nn.Linear(num_hidden, num_inputs))
        else:
            self.scale_net = nn.Sequential(
                nn.Linear(total_inputs, num_hidden), s_act_func(),
                nn.Linear(num_hidden, num_hidden), s_act_func(),
                nn.Linear(num_hidden, num_inputs))
            self.translate_net = nn.Sequential(
                nn.Linear(total_inputs, num_hidden), t_act_func(),
                nn.Linear(num_hidden, num_hidden), t_act_func(),
                nn.Linear(num_hidden, num_inputs))

    def forward(self, inputs, cond_inputs=None, mode='direct'):
        mask = self.mask
        masked_inputs = inputs * mask
        if cond_inputs is not None:
            cond_inputs = cond_inputs if not self.pre_mlp else self.mlp(cond_inputs)
            masked_inputs = torch.cat([masked_inputs, cond_inputs], -1)

        if mode == 'direct':
            if self.shared:
                masked_inputs = self.shared_net(masked_inputs)
            log_s = self.scale_net(masked_inputs) * (1 - mask)
            t = self.translate_net(masked_inputs) * (1 - mask)
            s = torch.exp(log_s)
            return inputs * s + t, log_s.sum(-1, keepdim=True)
        else:
            if self.shared:
                masked_inputs = self.shared_net(masked_inputs)
            log_s = self.scale_net(masked_inputs) * (1 - mask)
            t = self.translate_net(masked_inputs) * (1 - mask)
            s = torch.exp(-log_s)
            return (inputs - t) * s, -log_s.sum(-1, keepdim=True)

class CNNCouplingLayer(CouplingLayer):
    """ An implementation of a coupling layer
    from RealNVP (https://arxiv.org/abs/1605.08803) conditioned on images.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.pre_mlp:
            self.mlp = nn.Sequential(
                nn.Conv2d(3, 16, 3, 1), nn.ReLU(), nn.MaxPool2d(2),
                nn.Conv2d(16, 16, 3, 1), nn.ReLU(), nn.MaxPool2d(2),
                nn.Conv2d(16, 16, 3, 1), nn.ReLU(), nn.Flatten(),
                nn.Linear(2304, 1024), nn.ReLU(),
                nn.Linear(1024, 512), nn.ReLU(),
                nn.Linear(512, kwargs['pre_mlp_units']))

class FlowSequential(nn.Sequential):
    """ A sequential container for flows.
    In addition to a forward pass it implements a backward pass and
    computes log jacobians.
    """

    def forward(self, inputs, cond_inputs=None, mode='direct', logdets=None):
        """ Performs a forward or backward pass for flow modules.
        Args:
            inputs: a tuple of inputs and logdets
            mode: to run direct computation or inverse
        """
        self.num_inputs = inputs.size(-1)

        if logdets is None:
            logdets = torch.zeros(inputs.size(0), 1, device=inputs.device)

        assert mode in ['direct', 'inverse']
        if mode == 'direct':
            for module in self._modules.values():
                inputs, logdet = module(inputs, cond_inputs, mode)
                logdets += logdet
        else:
            for module in reversed(self._modules.values()):
                inputs, logdet = module(inputs, cond_inputs, mode)
                logdets += logdet

        return inputs, logdets

    def log_probs(self, inputs, cond_inputs = None):
        u, log_jacob = self(inputs, cond_inputs)
        log_probs = (-0.5 * u.pow(2) - 0.5 * math.log(2 * math.pi)).sum(
            -1, keepdim=True)
        return (log_probs + log_jacob).sum(-1, keepdim=True)

    def sample(self, num_samples=None, noise=None, cond_inputs=None):
        if noise is None:
            noise = torch.Tensor(num_samples, self.num_inputs).normal_()
        device = next(self.parameters()).device
        noise = noise.to(device)
        if cond_inputs is not None:
            cond_inputs = cond_inputs.to(device)
        samples = self.forward(noise, cond_inputs, mode='inverse')[0]
        return samples

class Deterministic(nn.Module):
    """ Simple MLP that learns deterministic mappings instead of conditional distributions. """
    def __init__(self, num_inputs, num_hidden, num_outputs):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(num_inputs, num_hidden), nn.ReLU(),
            nn.Linear(num_hidden, num_hidden), nn.ReLU(),
            nn.Linear(num_hidden, num_outputs), nn.Tanh()
        )

    def forward(self, x):
        return self.net(x)

    def sample(self, num_samples=None, noise=None, cond_inputs=None):
        device = next(self.parameters()).device
        cond_inputs = cond_inputs.to(device)
        return self.forward(cond_inputs)

class Gaussian(nn.Module):
    """ Simple MLP that learns deterministic mappings instead of conditional distributions. """
    def __init__(self, num_inputs, num_hidden, num_outputs):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(num_inputs, num_hidden), nn.ReLU(),
            nn.Linear(num_hidden, num_hidden), nn.ReLU()
        )
        self.mu_net = nn.Linear(num_hidden, num_outputs)
        self.log_std_net = nn.Linear(num_hidden, num_outputs)

    def forward(self, x):
        feat = self.net(x)
        return self.mu_net(feat), self.log_std_net(feat)

    def sample(self, num_samples=None, noise=None, cond_inputs=None):
        device = next(self.parameters()).device
        cond_inputs = cond_inputs.to(device)
        return self.forward(cond_inputs)


import json
import logging
import os
from io import BytesIO
from pathlib import Path

import numpy as np
import requests
from PIL import Image
from memgen.stages.embedder import Embedder
from memgen.stages.matcher import Matcher

class ISearcher:
    DUMP_FOLDER = Path('embeddings')
    EMBEDDING_DUMP = DUMP_FOLDER / 'embeddings.npy'
    MAPPING_DUMP = DUMP_FOLDER / 'mapping.txt'
    EMBEDDING_SIZE = 2048

    def __init__(self, path: str):
        self.path = path
        self.logger = logging.getLogger(self.__class__.__name__)
        embeddings, mapping = self._build_index()
        self.index_to_id = mapping
        self.matcher = Matcher(embeddings)

    def search_img(self, img, top_k: int = 1):
        results = [self.index_to_id[str(idx)] for idx in self.matcher.match(img, top_k)]
        self.logger.info(f'Search results: {results}')
        return results

    def search(self, url: str, top_k: int = 1):
        self.logger.info(f'Searching for {url}')
        response = requests.get(url)
        img = Image.open(BytesIO(response.content))
        return self.search_img(img, top_k)

    def _load_images(self):
        for file_name in os.listdir(self.path):
            image_id = file_name
            image_data = Image.open(os.path.join(self.path, file_name))
            yield (image_id, image_data)

    def _build_index(self):
        if not self.DUMP_FOLDER.exists():
            self.DUMP_FOLDER.mkdir()

        if self.EMBEDDING_DUMP.exists():
            embeddings = np.load(str(self.EMBEDDING_DUMP))

            with self.MAPPING_DUMP.open('r') as f:
                mapping = json.load(f)
        else:
            embedder = Embedder()
            images = list(self._load_images())
            embeddings = np.zeros((len(images), self.EMBEDDING_SIZE))
            mapping = {}

            for index, (image_id, img) in enumerate(images):
                mapping[index] = image_id
                embeddings[index] = embedder.embed(img)

            np.save(str(self.EMBEDDING_DUMP), embeddings)
            with self.MAPPING_DUMP.open('w') as f:
                json.dump(mapping, f)

        return embeddings, mapping


import array
import textwrap

from pynodegl_utils.misc import SceneCfg, scene
from pynodegl_utils.tests.cmp_cuepoints import test_cuepoints
from pynodegl_utils.tests.cmp_fingerprint import test_fingerprint
from pynodegl_utils.tests.data import (
    ANIM_DURATION,
    LAYOUTS,
    gen_floats,
    gen_ints,
    get_data_debug_positions,
    get_field_scene,
    match_fields,
)
from pynodegl_utils.tests.debug import get_debug_points
from pynodegl_utils.toolbox.colors import COLORS

import pynodegl as ngl

def _get_data_spec(layout, i_count=6, f_count=7, v2_count=5, v3_count=9, v4_count=2, mat_count=3):
    f_list = gen_floats(f_count)
    v2_list = gen_floats(v2_count * 2)
    v3_list = gen_floats(v3_count * 3)
    v4_list = gen_floats(v4_count * 4)
    i_list = gen_ints(i_count)
    iv2_list = [int(x * 256) for x in v2_list]
    iv3_list = [int(x * 256) for x in v3_list]
    iv4_list = [int(x * 256) for x in v4_list]
    mat4_list = gen_floats(mat_count * 4 * 4)
    one_f = gen_floats(1)[0]
    one_v2 = gen_floats(2)
    one_v3 = gen_floats(3)
    one_v4 = gen_floats(4)
    one_i = gen_ints(1)[0]
    one_b = True
    one_iv2 = gen_ints(2)
    one_iv3 = gen_ints(3)
    one_iv4 = gen_ints(4)
    one_u = gen_ints(1)[0]
    one_uv2 = gen_ints(2)
    one_uv3 = gen_ints(3)
    one_uv4 = gen_ints(4)
    one_mat4 = gen_floats(4 * 4)
    one_quat = one_v4

    f_array = array.array("f", f_list)
    v2_array = array.array("f", v2_list)
    v3_array = array.array("f", v3_list)
    v4_array = array.array("f", v4_list)
    i_array = array.array("i", i_list)
    iv2_array = array.array("i", iv2_list)
    iv3_array = array.array("i", iv3_list)
    iv4_array = array.array("i", iv4_list)
    mat4_array = array.array("f", mat4_list)

    spec = []

    # fmt: off
    spec += [dict(name=f"b_{i}",    type="bool",      category="single", data=one_b)    for i in range(i_count)]
    spec += [dict(name=f"f_{i}",    type="float",     category="single", data=one_f)    for i in range(f_count)]
    spec += [dict(name=f"v2_{i}",   type="vec2",      category="single", data=one_v2)   for i in range(v2_count)]
    spec += [dict(name=f"v3_{i}",   type="vec3",      category="single", data=one_v3)   for i in range(v3_count)]
    spec += [dict(name=f"v4_{i}",   type="vec4",      category="single", data=one_v4)   for i in range(v4_count)]
    spec += [dict(name=f"i_{i}",    type="int",       category="single", data=one_i)    for i in range(i_count)]
    spec += [dict(name=f"iv2_{i}",  type="ivec2",     category="single", data=one_iv2)  for i in range(v2_count)]
    spec += [dict(name=f"iv3_{i}",  type="ivec3",     category="single", data=one_iv3)  for i in range(v3_count)]
    spec += [dict(name=f"iv4_{i}",  type="ivec4",     category="single", data=one_iv4)  for i in range(v4_count)]
    spec += [dict(name=f"u_{i}",    type="uint",      category="single", data=one_u)    for i in range(i_count)]
    spec += [dict(name=f"uiv2_{i}", type="uvec2",     category="single", data=one_uv2)  for i in range(v2_count)]
    spec += [dict(name=f"uiv3_{i}", type="uvec3",     category="single", data=one_uv3)  for i in range(v3_count)]
    spec += [dict(name=f"uiv4_{i}", type="uvec4",     category="single", data=one_uv4)  for i in range(v4_count)]
    spec += [dict(name=f"m4_{i}",   type="mat4",      category="single", data=one_mat4) for i in range(mat_count)]
    spec += [dict(name=f"qm_{i}",   type="quat_mat4", category="single", data=one_quat) for i in range(mat_count)]
    spec += [dict(name=f"qv_{i}",   type="quat_vec4", category="single", data=one_quat) for i in range(v4_count)]
    spec += [
        dict(name="t_f",   type="float",     category="array",    data=f_array,    len=f_count),
        dict(name="t_v2",  type="vec2",      category="array",    data=v2_array,   len=v2_count),
        dict(name="t_v3",  type="vec3",      category="array",    data=v3_array,   len=v3_count),
        dict(name="t_v4",  type="vec4",      category="array",    data=v4_array,   len=v4_count),
        dict(name="a_qm4", type="quat_mat4", category="animated", data=one_quat),
        dict(name="a_qv4", type="quat_vec4", category="animated", data=one_quat),
        dict(name="a_f",   type="float",     category="animated", data=None),
        dict(name="a_v2",  type="vec2",      category="animated", data=one_v2),
        dict(name="a_v3",  type="vec3",      category="animated", data=one_v3),
        dict(name="a_v4",  type="vec4",      category="animated", data=one_v4),
    ]

    if layout != "uniform":
        spec += [
            dict(name="t_i",    type="int",        category="array",           data=i_array,    len=i_count),
            dict(name="t_iv2",  type="ivec2",      category="array",           data=iv2_array,  len=v2_count),
            dict(name="t_iv3",  type="ivec3",      category="array",           data=iv3_array,  len=v3_count),
            dict(name="t_iv4",  type="ivec4",      category="array",           data=iv4_array,  len=v4_count),
            dict(name="t_mat4", type="mat4",       category="array",           data=mat4_array, len=mat_count),
            dict(name="ab_f",   type="float",      category="animated_buffer", data=f_array,    len=f_count),
            dict(name="ab_v2",  type="vec2",       category="animated_buffer", data=v2_array,   len=v2_count),
            dict(name="ab_v3",  type="vec3",       category="animated_buffer", data=v3_array,   len=v3_count),
            dict(name="ab_v4",  type="vec4",       category="animated_buffer", data=v4_array,   len=v4_count),
        ]
    # fmt: on

    return spec

def _get_data_function(spec, category, field_type, layout):
    nb_keyframes = 5 if "animated" in category else 1
    fields = match_fields(spec, category, field_type)

    @test_cuepoints(
        points=get_data_debug_positions(fields),
        nb_keyframes=nb_keyframes,
        tolerance=1,
        debug_positions=False,
    )
    @scene(seed=scene.Range(range=[0, 100]), debug_positions=scene.Bool(), color_tint=scene.Bool())
    def scene_func(cfg: SceneCfg, seed=0, debug_positions=True, color_tint=False):
        cfg.duration = ANIM_DURATION
        return get_field_scene(cfg, spec, category, field_type, seed, debug_positions, layout, color_tint)

    return scene_func

for layout in LAYOUTS:
    spec = _get_data_spec(layout)
    test_fields = set((f["category"], f["type"]) for f in spec)
    for category, field_type in test_fields:
        globals()[f"data_{category}_{field_type}_{layout}"] = _get_data_function(spec, category, field_type, layout)

_RENDER_STREAMEDBUFFER_VERT = """
void main()
{
    ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
    var_uvcoord = ngl_uvcoord;
}
"""

_RENDER_STREAMEDBUFFER_FRAG = """
void main()
{
    uint x = uint(var_uvcoord.x * %(size)d.0);
    uint y = uint(var_uvcoord.y * %(size)d.0);
    uint i = clamp(x + y * %(size)dU, 0U, %(data_size)dU - 1U);
    ngl_out_color = vec4(streamed.data[i]);
}
"""

def _get_data_streamed_buffer_cuepoints(size):
    f = float(size)
    off = 1 / (2 * f)
    c = lambda i: (i / f + off) * 2.0 - 1.0
    return {f"{x}{y}": (c(x), c(y)) for y in range(size) for x in range(size)}

def _get_data_streamed_buffer_vec4_scene(cfg: SceneCfg, size, nb_keyframes, scale, single, show_dbg_points):
    cfg.duration = nb_keyframes * scale
    cfg.aspect_ratio = (1, 1)
    data_size = size * size
    assert not single or size == 2

    time_anim = None
    if scale != 1:
        kfs = [
            ngl.AnimKeyFrameFloat(0, 0),
            ngl.AnimKeyFrameFloat(cfg.duration, nb_keyframes),
        ]
        time_anim = ngl.AnimatedTime(kfs)

    pts_data = array.array("q")
    assert pts_data.itemsize == 8

    for i in range(nb_keyframes):
        offset = 10000 if i == 0 else 0
        pts_data.extend([i * 1000000 + offset])

    vec4_data = array.array("f")
    for i in range(nb_keyframes):
        for j in range(data_size):
            v = i / float(nb_keyframes) + j / float(data_size * nb_keyframes)
            if single:
                vec4_data.extend([v])
            else:
                vec4_data.extend([v, v, v, v])

    pts_buffer = ngl.BufferInt64(data=pts_data)
    vec4_buffer = ngl.BufferVec4(data=vec4_data)

    if single:
        streamed_buffer = ngl.StreamedVec4(pts_buffer, vec4_buffer, time_anim=time_anim, label="data")
    else:
        streamed_buffer = ngl.StreamedBufferVec4(data_size, pts_buffer, vec4_buffer, time_anim=time_anim, label="data")
    streamed_block = ngl.Block(layout="std140", label="streamed_block", fields=(streamed_buffer,))

    shader_params = dict(data_size=data_size, size=size)

    quad = ngl.Quad((-1, -1, 0), (2, 0, 0), (0, 2, 0))
    program = ngl.Program(
        vertex=_RENDER_STREAMEDBUFFER_VERT,
        fragment=_RENDER_STREAMEDBUFFER_FRAG % shader_params,
    )
    program.update_vert_out_vars(var_uvcoord=ngl.IOVec2())
    render = ngl.Render(quad, program)
    render.update_frag_resources(streamed=streamed_block)

    group = ngl.Group(children=(render,))
    if show_dbg_points:
        cuepoints = _get_data_streamed_buffer_cuepoints(size)
        group.add_children(get_debug_points(cfg, cuepoints))
    return group

def _get_data_streamed_buffer_function(scale, single):
    size = 2 if single else 4
    nb_keyframes = 4

    @test_cuepoints(points=_get_data_streamed_buffer_cuepoints(size), nb_keyframes=nb_keyframes, tolerance=1)
    @scene(show_dbg_points=scene.Bool())
    def scene_func(cfg: SceneCfg, show_dbg_points=False):
        return _get_data_streamed_buffer_vec4_scene(cfg, size, nb_keyframes, scale, single, show_dbg_points)

    return scene_func

data_streamed_vec4 = _get_data_streamed_buffer_function(1, True)
data_streamed_vec4_time_anim = _get_data_streamed_buffer_function(2, True)
data_streamed_buffer_vec4 = _get_data_streamed_buffer_function(1, False)
data_streamed_buffer_vec4_time_anim = _get_data_streamed_buffer_function(2, False)

@test_cuepoints(points={"c": (0, 0)}, tolerance=1)
@scene()
def data_integer_iovars(cfg: SceneCfg):
    cfg.aspect_ratio = (1, 1)
    vert = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
            var_color_u32 = color_u32;
        }
        """
    )
    frag = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_color = vec4(var_color_u32) / 255.;
        }
        """
    )
    program = ngl.Program(vertex=vert, fragment=frag)
    program.update_vert_out_vars(var_color_u32=ngl.IOIVec4())
    geometry = ngl.Quad(corner=(-1, -1, 0), width=(2, 0, 0), height=(0, 2, 0))
    render = ngl.Render(geometry, program)
    render.update_vert_resources(color_u32=ngl.UniformIVec4(value=(0x50, 0x80, 0xA0, 0xFF)))
    return render

@test_cuepoints(points={"c": (0, 0)}, tolerance=1)
@scene()
def data_mat_iovars(cfg: SceneCfg):
    cfg.aspect_ratio = (1, 1)
    vert = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
            var_mat3 = mat3(1.0);
            var_mat4 = mat4(1.0);
            var_vec4 = vec4(1.0, 0.5, 0.0, 1.0);
        }
        """
    )
    frag = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_color = mat4(var_mat3) * var_mat4 * var_vec4;
        }
        """
    )
    program = ngl.Program(vertex=vert, fragment=frag)
    program.update_vert_out_vars(
        var_mat3=ngl.IOMat3(),
        var_mat4=ngl.IOMat4(),
        var_vec4=ngl.IOVec4(),
    )
    geometry = ngl.Quad(corner=(-1, -1, 0), width=(2, 0, 0), height=(0, 2, 0))
    render = ngl.Render(geometry, program)
    return render

@test_fingerprint(nb_keyframes=10, tolerance=1)
@scene()
def data_noise_time(cfg: SceneCfg):
    cfg.aspect_ratio = (1, 1)
    cfg.duration = 2
    vert = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
            ngl_out_pos += vec4(t - 1., signal, 0.0, 0.0);
        }
        """
    )
    frag = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_color = vec4(color, 1.0);
        }
        """
    )

    geometry = ngl.Circle(radius=0.25, npoints=6)
    program = ngl.Program(vertex=vert, fragment=frag)
    render = ngl.Render(geometry, program)
    render.update_vert_resources(t=ngl.Time(), signal=ngl.NoiseFloat(octaves=8))
    render.update_frag_resources(color=ngl.UniformVec3(value=COLORS.white))
    return render

@test_fingerprint(nb_keyframes=30, tolerance=1)
@scene()
def data_noise_wiggle(cfg: SceneCfg):
    cfg.aspect_ratio = (1, 1)
    cfg.duration = 3
    vert = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
            ngl_out_pos += vec4(wiggle, 0.0, 0.0);
        }
        """
    )
    frag = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_color = vec4(color, 1.0);
        }
        """
    )

    geometry = ngl.Circle(radius=0.25, npoints=6)
    program = ngl.Program(vertex=vert, fragment=frag)
    render = ngl.Render(geometry, program)
    render.update_vert_resources(wiggle=ngl.NoiseVec2(octaves=8))
    render.update_frag_resources(color=ngl.UniformVec3(value=COLORS.white))
    return render

@test_cuepoints(points={"c": (0, 0)}, nb_keyframes=10, tolerance=1)
@scene()
def data_eval(cfg: SceneCfg):
    cfg.aspect_ratio = (1, 1)

    # Entangled dependencies between evals
    t = ngl.Time()
    a = ngl.UniformFloat(0.7)
    b = ngl.UniformFloat(0.3)
    x = ngl.EvalFloat("sin(a - b + t*4)")
    x.update_resources(t=t, a=a, b=b)
    color = ngl.EvalVec4(
        expr0="sat(sin(x + t*4)/2 + wiggle/3)",
        expr1="abs(fract(sin(t + a)))",
        expr2=None,  # re-use expr1
        expr3="1",
    )
    color.update_resources(wiggle=ngl.NoiseFloat(), t=t, a=a, x=x)

    vert = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
        }
        """
    )
    frag = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_color = color;
        }
        """
    )
    program = ngl.Program(vertex=vert, fragment=frag)
    geometry = ngl.Quad(corner=(-1, -1, 0), width=(2, 0, 0), height=(0, 2, 0))
    render = ngl.Render(geometry, program)
    render.update_frag_resources(color=color)

    return render

def _data_vertex_and_fragment_blocks(cfg: SceneCfg, layout):
    """
    This test ensures that the block bindings are properly set by pgcraft
    when UBOs or SSBOs are bound to different stages.
    """
    cfg.aspect_ratio = (1, 1)

    src = ngl.Block(
        fields=[
            ngl.UniformVec3(value=COLORS.red, label="color"),
            ngl.UniformFloat(value=0.5, label="opacity"),
        ],
        layout="std140",
    )
    dst = ngl.Block(
        fields=[
            ngl.UniformVec3(value=COLORS.white, label="color"),
        ],
        layout=layout,
    )
    vert = textwrap.dedent(
        """\
        void main()
        {
            ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
            var_src = vec4(src.color, 1.0) * src.opacity;
        }
        """
    )
    frag = textwrap.dedent(
        """\
        void main()
        {
            vec3 color = var_src.rgb + (1.0 - var_src.a) * dst.color;
            ngl_out_color = vec4(color, 1.0);
        }
        """
    )

    program = ngl.Program(vertex=vert, fragment=frag)
    program.update_vert_out_vars(
        var_src=ngl.IOVec4(),
    )
    geometry = ngl.Quad(corner=(-1, -1, 0), width=(2, 0, 0), height=(0, 2, 0))
    render = ngl.Render(geometry, program)
    render.update_vert_resources(src=src)
    render.update_frag_resources(dst=dst)

    return render

@test_cuepoints(points={"c": (0, 0)}, nb_keyframes=1, tolerance=1)
@scene()
def data_vertex_and_fragment_blocks(cfg: SceneCfg):
    return _data_vertex_and_fragment_blocks(cfg, "std140")

@test_cuepoints(points={"c": (0, 0)}, nb_keyframes=1, tolerance=1)
@scene()
def data_vertex_and_fragment_blocks_std430(cfg: SceneCfg):
    return _data_vertex_and_fragment_blocks(cfg, "std430")


import pygame
import random
import os

pygame.mixer.init()
pygame.mixer.music.load('32.mp3')
pygame.mixer.music.play()

pygame.init()

# Specifying Colors
white = (255, 255, 255)
red = (255, 0, 0)
blue = (200, 203, 255)
black = (0, 0, 0)
unknown = (154,207,229)

# Setting Window
screen_width = 900
screen_height = 600
gameWindow = pygame.display.set_mode((screen_width, screen_height))

## Background Image
# bg = pygame.image.load('bg.jpg')
# bg = pygame.transform.scale(bg, (screen_width, screen_height)).convert_alpha()
# bg2 = pygame.image.load('bg2.jpg')
# bg2 = pygame.transform.scale(bg2, (screen_width, screen_height)).convert_alpha()

exit_Game = False
game_Over = False
clock = pygame.time.Clock()

# Game Title
pygame.display.set_caption("SnakesWithAwan")
pygame.display.update()
font = pygame.font.SysFont(None, 55)

def score_screen(text, color, x, y):
    text_screen = font.render(text, True, color)
    gameWindow.blit(text_screen, [x,y])

def plot_snake(gameWindow, color, snk_list, snake_size):
    for x, y in snk_list:
        pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])

def welcome():
    exit_Game = False
    while not exit_Game:
        gameWindow.fill(blue)
        score_screen("Welcome to the Snake Game!", white, 180, 250)
        score_screen("Press Space Bar to Play", white, 230, 290)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_Game = True
                # exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    gmeloop()
        # gameWindow.blit(bg, (0, 0))

        pygame.display.update()
        clock.tick(60)

# Game Loop
def gmeloop():

    # Game Variables
    snake_x = 45
    snake_y = 55
    snake_size = 15
    food_size = 11
    exit_Game = False
    game_Over = False
    clock = pygame.time.Clock()
    fps = 60
    velocity_x = 0
    velocity_y = 0
    vel = 4
    food_x = random.randint(20, screen_width/2)
    food_y = random.randint(20, screen_height/2)
    score = 0
    snk_list = []
    snk_len = 1
    if(not os.path.exists("highscore.txt")):
        with open('highscore.txt', 'w') as f:
            f.write("0")
    with open('highscore.txt', 'r') as f:
        hscore = f.read()

    while not exit_Game:
        if game_Over:
            score_screen("Game Over, Enter to start over!", red, 200, 250)
            with open('highscore.txt', 'w') as f:
                f.write(str(hscore))
            for event in pygame.event.get():
                    exit_Game = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    welcome()

        else:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit_Game = True

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        velocity_x = vel
                        velocity_y = 0

                    if event.key == pygame.K_LEFT:
                        velocity_x = -vel
                        velocity_y = 0

                    if event.key == pygame.K_DOWN:
                        velocity_y = vel
                        velocity_x = 0

                    if event.key == pygame.K_UP:
                        velocity_y = -vel
                        velocity_x = 0

                    if event.key == pygame.K_q:
                        score += 10

            snake_x += velocity_x
            snake_y += velocity_y

            if abs(snake_x - food_x)<8 and abs(snake_y - food_y)<8:
                score += 10
                food_x = random.randint(20, screen_width/2)
                food_y = random.randint(20, screen_height/2)
                vel += 0.05
                snk_len += 3
                if score > int(hscore):
                    hscore = score

            gameWindow.fill(unknown)
            # gameWindow.blit(bg2, (0, 0))
            score_screen("Score: " + str(score) + "  Highscore: " + str(hscore), red, 5, 5)

            plot_snake(gameWindow, black, snk_list, snake_size)
            pygame.draw.rect(gameWindow, red, [food_x, food_y, food_size, food_size])

            head = []
            head.append(snake_x)
            head.append(snake_y)
            snk_list.append(head)

            if len(snk_list)>snk_len:
                del snk_list[0]

            if head in snk_list[:-1]:
                game_Over = True

            if snake_x<0 or snake_x>screen_width or snake_y<0 or snake_y>screen_height:
                game_Over = True

        pygame.display.update()
        clock.tick(fps)

    pygame.quit()
    quit()

welcome()


TC = int(input())
for tc in range(1, TC + 1):
    N = int(input())
    cards = input().split()
    deck = []

    idx = 1

    if N % 2 == 0:
        for i in range(N):
            if i < N // 2:
                deck.append(cards[i])
            else:
                deck.insert(idx, cards[i])
                idx += 2
    if N % 2 == 1:
        for j in range(N):
            if j < N // 2 + 1:
                deck.append(cards[j])
            else:
                deck.insert(idx, cards[j])
                idx += 2

    print('#{} {}'.format(tc, ' '.join(map(str, deck))))


from config import q, D
from src.file_io.utils import get_data_file_path
from src.coding.encode import encode_bit_string
from src.ofdm.modulate import modulate_sequence
import numpy as np

def gen_known_data_chunk(N, K):
    """Generates the standard block"""
    known_file = get_data_file_path("random_bits.txt")

    file_obj = open(known_file, mode="r")
    bit_string = file_obj.read()
    bit_string = bit_string[0 : (N//2 -1)*q] # just sufficient for first symbol
    file_obj.close()

    # map to QPSK
    symbol_sequence = encode_bit_string(bit_string)
    # convert to time-domain
    known_block = modulate_sequence(symbol_sequence, N=N, K=K, Q1=1, Q2=N//2)

    # check just one block long
    P = N + K
    assert len(known_block) == P

    # repeat D times
    known_block_repeated = np.tile(known_block, D)
    return known_block_repeated


import requests

def weather_by_city(city_name):
    weather_url = "http://api.worldweatheronline.com/premium/v1/weather.ashx"
    params = {
        "key": "API_KEY",
        "q": city_name,
        "format": "json",
        "num_of_days": 1,
        "lang": "ru"
    }
    try:
        result = requests.get(weather_url, params=params)
        result.raise_for_status()
        return result.json()

    except(requests.RequestException, ValueError):
        return False


#!/usr/bin/env python

import sys, os
import matplotlib
import matplotlib.pyplot as plt

from demo_utils.log_pkt_parser import LogPktParser
from demo_utils.flow_stats import FlowStats
from demo_utils.scapy_patch import rdpcap_raw

RATE_AVG_INTERVAL = 100000 # ns
EGRESS_LINK_RATE = 5

MAX_FLOW_ID = 512

def print_fcts(input_log_pkts):
    start_time = input_log_pkts[0].time
    flow_stats = FlowStats(input_log_pkts, start_time)
    flow_stats.calc_fcts()

def parse_log_pkts(pcap_file):
    try:
        log_pkts = []
        for (pkt, _) in rdpcap_raw(pcap_file):
            if pkt is not None:
                log_pkts.append(pkt)
    except IOError as e:
        print >> sys.stderr, "ERROR: failed to read pcap file: {}".format(pcap_file)
        sys.exit(1)
    except:
        print >> sys.stderr, "ERROR: empty pcap file? {}".format(pcap_file)
        sys.exit(1)

    # Parse the logged pkts
    pkt_parser = LogPktParser()
    log_pkts = pkt_parser.parse_pkts(log_pkts, MAX_FLOW_ID)
    return log_pkts

def main():
    # parse the logged pcap files
    input_log_pkts = parse_log_pkts('fct_logs/eth2.pcap')

    # plot input / output rates
    print_fcts(input_log_pkts)

if __name__ == '__main__':
    main()


# Shaggy has an array A consisting of N elements. We call a pair of distinct indices in that array a special if elements at those indices in the array are equal.
# Shaggy wants you to find a special pair such that the distance between that pair is minimum. Distance between two indices is defined as |i-j|. If there is no special pair in the array, then return -1.

# TC: O(N)
# SC: O(N)

def solve(A):

    idx = {}
    n = len(A)

    for i in A:
        print(i)
        idx[i] = -1
        print(idx)

    res = 10^9
    for i in range(n):
        if idx[A[i]] != -1:
            res = min(res, i - idx[A[i]])
            print('res ', res)
            print(res)
        idx[A[i]] = i

  #  if res == 10^9:
  #      return -1
    return res

# Driver Code
A = [7, 1, 3, 4, 1, 7]
print(solve(A))


#Problem: 	2520 is the smallest number divisible by 1,2,3,...10.
#			What is the smallest number divisible by 1-20 (more generally, 1-n)?

import math

def greatestLesserPower(x,y):
	#findsthe greatest power of x less than or equal to y
	if x > y:
		return 0
	product = 1
	while product <= y:
		product *= x
	return product/x

def isPrime(x):
	if (x == 2 or x == 3 or x ==5 or x == 7):
		return 1
	test = 1
	for i in range(2, int(math.ceil(math.sqrt(x))+1)):
		if not(x%i):
			test = 0
			break
	return test

def lowerPrimes(x):
	#generates the list of all primes less than or equal to x
	plist = []
	for i in range(2,x+1):
		if isPrime(i):
			plist.append(i)
	return plist

def main():
	#strategy: find the product of the greatest powers less than num of each prime number less than num

	'''print(isPrime(27), isPrime(31), isPrime(3), isPrime(4), isPrime(11))
	print(lowerPrimes(25), lowerPrimes(31))
	print(greatestLesserPower(5,7), greatestLesserPower(2,40))'''

	num = 20
	plist = lowerPrimes(num)
	product = 1
	for i in plist:
		product *= greatestLesserPower(i, num)
	print(product)

main()


T = int(input())
for test_case in range(1, T+1):
    k = int(input())
    sentence = input()
    s_list = []
    s_len = len(sentence)

    if k <= s_len:

        for i in range(s_len):
            s_list.append(sentence[i:])
        s_list = sorted(s_list)
        result = s_list[k-1]
    else:
        result = None
    print("#{} {}".format(test_case, result))


from django.test import TestCase
from users.models import Profile
from django.contrib.auth.models import User
from image_recognition.models import Image, ImageAttentionDescription
from django.urls import reverse

class ImageTestCase(TestCase):
    def setUp(self):
        User.objects.create(username="UnittestTestUser1")
        self.user1 = User.objects.filter(username="UnittestTestUser1").first()

    def test_deleting_image_deletes_its_description(self):
        Image.objects.create(author=self.user1, original_image="TEST_IMAGE.jpg", user_description="Test description 2")
        image = Image.objects.filter(author=self.user1, user_description="Test description 2").first()
        ImageAttentionDescription.objects.create(image_id = image.id, attention_image="TEST_IMAGE.jpg", attention_word="some_word")
        image.delete()
        self.assertTrue(len(ImageAttentionDescription.objects.filter(image_id = image.id, attention_image="TEST_IMAGE.jpg", attention_word="some_word").all()) == 0)

    def test_anonymous_cant_see_pictures(self):
        response = self.client.get(reverse('user-images'))
        self.assertRedirects(response, "/login/?next=/user-images/")

    def test_anonymous_cant_see_picture_detail(self):
        response = self.client.get(reverse('image-detail', kwargs={'pk': '1'}))
        self.assertRedirects(response, "/login/?next=/image/1/")

    def test_deleting_user_delets_his_images(self):
        user1_id = self.user1
        Image.objects.create(author=self.user1, original_image="TEST_IMAGE.jpg", user_description="Test description 3")
        self.user1.delete()
        self.assertTrue(len(Image.objects.filter(author=user1_id).all()) == 0)


'''
Problem Solving Baekjoon 1918_2
Author: Injun Son
Date: September 3, 2020
'''
from collections import deque
import sys
str = sys.stdin.readline().strip()
stack = []
prior = {"*":2, "/":2, "+":1, "-":1, "(":0}
post_list = []
for ch in '('+str+')':
    #알파벳이면
    if ch.isupper():
        post_list.append(ch)
    elif ch=='(':
        stack.append(ch)
    elif ch==')':
        while True:
            x = stack.pop()
            if x=='(':
                break
            post_list.append(x)
    #연산자면
    else:
        while stack[-1] !='(' and prior[ch] <= prior[stack[-1]]:
            post_list.append(stack.pop())
        stack.append(ch)

print(''.join(post_list))

'''
연산자 우선순위 지정
후위 표현식으로 만들어져 반환될 리스트 생성
중위 표현식을 왼쪽부터 한 글짜씩 읽음
피연산자면 리스트에 append
'('이면 스택에 PUSH, ')'이면 '('가 나올때까지 스택에서 POP, 리스트에 append
연산자면 스택에서 이보다 높은 우선순위들 POP, 리스트에 append
그리고 이 연산자를 스택에 PUSH
스택에 남아있는 연산자는 모두 POP, 리스트에 append
'''