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

"""
Created by Wang Han on 2018/5/28 22:46.
E-mail address is hanwang.0501@gmail.com.
Copyright © 2017 Wang Han. SCU. All Rights Reserved.
"""

import argparse
import ast
import os
from datetime import datetime

import numpy as np
import torch
from tensorboardX import SummaryWriter
from torch.backends import cudnn
from torch.optim import Adadelta

from dataset.cell_new import Cell
from models.patchwise_model import CellModel
from utils.gpu import set_gpu
from utils.log import Logger

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='DeepCell')
  parser.add_argument('--epochs', type=int, default=100,
                      help='number of training epochs. default=100')
  parser.add_argument('--lr', default=0.5, type=float, metavar='LR',
                      help='learning rate. default=0.5')
  parser.add_argument('--lr-decay-step', type=int, default=30,
                      help='number of training epochs. default=30')
  parser.add_argument('--lr-decay', default=0.1, type=float,
                      help='multiplicative factor of learning rate decay. default=0.1')
  parser.add_argument('--train-batch-size', type=int, default=4,
                      help='training batch size. default=4')
  parser.add_argument('--test-batch-size', type=int, default=1,
                      help='testing batch size. default=1')
  parser.add_argument('--workers', type=int, default=1,
                      help='number of data loading workers. default=1')
  parser.add_argument('--log-interval', type=int, default=100,
                      help='how many batches to wait before logging status. default=100')
  parser.add_argument('--use-cuda', type=ast.literal_eval, default=True,
                      help='ensable cuda training. default=True')
  parser.add_argument('--use-tensorboard', type=ast.literal_eval, default=True,
                      help='ensable tensorboard. default=True')
  parser.add_argument('--seed', type=int, default=22,
                      help='random seed for training. default=22')
  parser.add_argument('--gpu', default='all', type=str,
                      help='use gpu device. default: all')
  args = parser.parse_args()

  torch.manual_seed(args.seed)
  args.n_gpu = set_gpu(args.gpu)
  if args.use_cuda:
    print('Set random seed: {}'.format(args.seed))
    torch.cuda.manual_seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)

  model = CellModel()
  if args.use_cuda:
    print('Utilize GPUs for computation')
    print('Number of GPU available: {}'.format(torch.cuda.device_count()))
    model = model.cuda()
    cudnn.benchmark = True

    model = torch.nn.DataParallel(model)

  optimizer = Adadelta(model.parameters(), lr=args.lr)
  # lr_decay = lr_scheduler.MultiStepLR(
  #   optimizer, milestones=[30, 80], gamma=args.lr_decay)
  print("The model is: {}".format(model))

  # load dataset
  cell = Cell(train_batch_size=args.train_batch_size,
              test_batch_size=args.test_batch_size,
              num_workers=args.workers)

  # create saved model dir
  if not os.path.exists('saved_models'):
    os.mkdir('saved_models')

  run_timestamp = datetime.now().strftime("%Y%b%d-%H%M%S")
  saved_dir = os.path.join('saved_models', run_timestamp)

  if not os.path.exists(saved_dir):
    os.mkdir(saved_dir)
  logger = Logger(os.path.join(saved_dir, 'deepcell.log')).get_logger()

  # create summary dir
  if not os.path.exists('runs'):
    os.mkdir('runs')

  if args.use_tensorboard:
    runs_dir = os.path.join('runs', run_timestamp)
    if not os.path.exists(runs_dir):
      os.mkdir(runs_dir)
    write = SummaryWriter(runs_dir)

  logger.info(args)

  best_acc = 0
  best_epoch = 0
  for epoch in range(args.epochs):
    # lr_decay.step()
    # for param_group in optimizer.param_groups:
    # param_group['lr'] = max(param_group['lr'], 1e-4)
    # logger.info("Epoch {}'s LR is {}".format(epoch, param_group['lr']))

    train_loss = 0
    train_acc = 0
    model.train()
    for batch_id, (data, target, file) in enumerate(cell.train_loader):
      if args.use_cuda:
        data, target = data.cuda(), target.cuda()
      optimizer.zero_grad()
      _, logit, prob = model(data)
      loss = model.module.loss(logit, target)
      loss.backward()
      optimizer.step()
      train_loss += loss.data.item()
      acc = sum(
        np.argmax(prob.data.cpu().numpy(), 1) ==
        target.data.cpu().numpy()) / float(cell.train_loader.batch_size)
      train_acc += acc

      if batch_id % args.log_interval == 0:
        print(
          "Train Epoch: {} [{}/{} ({:.0f}%)] Loss: {:.6f} Accuracy: {:.6f}%".format(
            epoch, batch_id * len(data),
            len(cell.train_loader.dataset),
                   100. * batch_id / len(cell.train_loader),
            loss.data.item(),
                   100. * acc))

    train_acc = train_acc / len(cell.train_loader)
    train_loss = train_loss / len(cell.train_loader)
    if args.use_tensorboard:
      write.add_scalar('train/acc', train_acc, epoch)
      write.add_scalar('train/loss', train_loss, epoch)
    logger.info("[Train] Epoch:{}, Loss:{:.6f}, Accuracy:{:.6f}%".format(epoch, train_loss, 100. * train_acc))

    test_acc = 0
    model.eval()
    with torch.no_grad():
      for batch_id, (data, target, file) in enumerate(cell.test_loader):
        data = data.view(-1, 3, 512, 512)
        if args.use_cuda:
          data, target = data.cuda(), target.cuda()
        _, predict, prob = model(data)
        avg_prob = np.average(prob.cpu().numpy(), axis=0)
        acc = sum(np.argmax(avg_prob, 0) ==
                  target.cpu().numpy()) / float(args.test_batch_size)
        test_acc += acc

        if batch_id % args.log_interval == 0:
          print(
            "Test Epoch: {} [{}/{} ({:.0f}%)] Accuracy: {:.6f}%".format(
              epoch, batch_id * len(data),
              len(cell.test_loader.dataset),
                     100. * batch_id / len(cell.test_loader),
                     100. * acc))

      test_acc = test_acc / len(cell.test_loader)
      if args.use_tensorboard:
        write.add_scalar('test/acc', test_acc, epoch)
      logger.info("[Test] Epoch:{}, Accuracy:{:.6f}%".format(epoch, 100. * test_acc))

    # save best model
    if test_acc >= best_acc:
      best_acc = test_acc
      best_epoch = epoch
      torch.save({
        'epoch': best_epoch,
        'state_dict': model.module.state_dict(),
        'best_accuracy': best_acc,
      }, os.path.join(saved_dir, 'checkpoint.pth'))
      logger.info(
        'Best model has been saved at epoch {} with best accuracy {:.6f}%'.format(
          epoch, 100. * best_acc))

    logger.info("Best accuracy {:.6f}% at epoch {}".format(100. * best_acc, best_epoch))


import lib.save as save
from lib.interpreters.command import Command
from lib.interpreters.constants import Position

"""
Command Attributes;
attribute (default): description

aggro				(False)				: does it start combat?
canTarget			(False)				: can it take an automatic single target?
requireTarget		(False)				: does it require a target?
useInCombat			(False)				: can you use it in combat?
useWhileJustDied	(True)				: can you use it immediately after dying?
targetSelf			(True)				: can you target yourself?
Range				(Range.room)		: for skills that canTarget, what is the range of potential targets?
minPosition			(Position.standing)	: what is the minimum position as defined in constants.py?
"""

class Save(Command):
	def __init__(self, game):
		super(Save, self).__init__(game, 'save')
		self.minPosition = Position.sleeping

	def execute(self, args, config):
		sender = config['sender']

		dbd = save.databaseDaemon()

		sender.sendToClient('Initiating save.')

		import thread
		thread.start_new_thread(dbd.saveMobile, (sender,))
		sender.sendToClient('Save complete.')

class Quit(Command):
	def __init__(self, game):
		super(Quit, self).__init__(game, 'quit')
		self.minPosition = Position.sleeping

	def execute(self, args, config):
		sender = config['sender']

		# Only quit if they type 'quit confirm'
		if 'confirm' not in args:
			sender.sendToClient('You must type quit confirm to quit.')
			return

		# Send disconnect message
		sender.sendToClient('Alas, all good things must come to an end.')

		# Kill client connection
		if sender.client.getClientType() == 'websocket':
			sender.client.close()

		if 'nervous' in sender.affects:
			# If client is nervous, make them linkdead (and only decrement linkdead if not nervous)
			sender.goLinkdead()
		else:
			# Otherwise, quit the player
			sender.leaveGame()

		# Get rid of client
		sender.client = None

commandList = [Save, Quit]


""" Advent of code 2017	day 5/1	"""

from argparse import ArgumentParser

def read_data(input_data):
    return {key: int(value) for key, value in enumerate(input_data.split('\n'))}

class CPU(object):
    def jump(self):
        current_index = self.index
        self.index += self.data[current_index]
        self.data[current_index] += 1

    def __init__(self, data):
        self.data = data
        self.index = 0

def solution(input_data):
    """ Solution to the problem """
    data = read_data(input_data)
    array_length = len(data)
    cpu = CPU(data)
    step = 0
    while cpu.index < array_length and cpu.index >= 0:
        #print(step, cpu.data)
        cpu.jump()
        step += 1
    return step

if __name__ == "__main__":
    PARSER = ArgumentParser()
    PARSER.add_argument("--input", dest='input', action='store_true')
    PARSER.add_argument("--test")
    ARGS = PARSER.parse_args()
    if ARGS.input:
        with(open('input.txt', 'r')) as input_file:
            print(solution(input_file.read()))
    elif ARGS.test:
        print(solution(str(ARGS.test)))
    else:
        DEBUG = "0\n3\n0\n1\n-3"
        print(solution(DEBUG))


#!/usr/bin/env python3
"""Test the class_oid module."""

import sys
import unittest
import os

# Try to create a working PYTHONPATH
EXEC_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(
    os.path.abspath(os.path.join(
            os.path.abspath(os.path.join(
                os.path.abspath(os.path.join(
                        EXEC_DIR,
                        os.pardir)), os.pardir)), os.pardir)), os.pardir))
_EXPECTED = ('''\
{0}pattoo-agents{0}tests{0}test_pattoo_agents{0}modbus{0}tcp'''.format(os.sep))
if EXEC_DIR.endswith(_EXPECTED) is True:
    # We need to prepend the path in case PattooShared has been installed
    # elsewhere on the system using PIP. This could corrupt expected results
    sys.path.insert(0, ROOT_DIR)
else:
    print('''This script is not installed in the "{0}" directory. Please fix.\
'''.format(_EXPECTED))
    sys.exit(2)

# Pattoo imports
from pattoo_agents.modbus.tcp import configuration
from pattoo_agents.modbus.variables import (
    InputRegisterVariable, HoldingRegisterVariable, RegisterVariable,
    TargetRegisterVariables)
from tests.libraries.configuration import UnittestConfig

class TestConfigModbusTCP(unittest.TestCase):
    """Checks all ConfigModbusTCP methods."""

    ##########################################################################
    # Initialize variable class
    ##########################################################################
    config = configuration.ConfigModbusTCP()

    def test___init__(self):
        """Testing function __init__."""
        pass

    def test_polling_interval(self):
        """Test pattoo_shared.Config inherited method polling_interval."""
        # Initialize key values
        expected = 457

        # Test
        result = self.config.polling_interval()
        self.assertEqual(result, expected)

    def test_registervariables(self):
        """Testing method / function registervariables."""
        # Initialize variables
        expected_ip_target = 'unittest.modbus.tcp.target.net'
        register_variables = []

        # Test
        result = self.config.registervariables()
        self.assertTrue(isinstance(result, list))
        self.assertEqual(len(result), 2)
        for drv in result:
            self.assertTrue(isinstance(drv, TargetRegisterVariables))
            self.assertTrue(drv.valid)
            self.assertEqual(drv.target, expected_ip_target)
            for _rv in drv.data:
                self.assertTrue(isinstance(_rv, RegisterVariable))
                self.assertTrue(_rv.valid)
            register_variables.extend(drv.data)

        # Evaluate each RegisterVariable
        self.assertEqual(len(register_variables), 3)
        for index, _rv in enumerate(register_variables):
            if index == 0:
                self.assertEqual(_rv.address, 387)
                self.assertEqual(_rv.count, 2)
                self.assertEqual(_rv.multiplier, 7)
                self.assertEqual(_rv.unit, 3)
                self.assertTrue(isinstance(_rv, InputRegisterVariable))
            elif index == 1:
                self.assertEqual(_rv.address, 123)
                self.assertEqual(_rv.count, 1)
                self.assertEqual(_rv.multiplier, 9)
                self.assertEqual(_rv.unit, 3)
                self.assertTrue(isinstance(_rv, HoldingRegisterVariable))
            else:
                self.assertEqual(_rv.address, 456)
                self.assertEqual(_rv.count, 1)
                self.assertEqual(_rv.multiplier, 9)
                self.assertEqual(_rv.unit, 3)
                self.assertTrue(isinstance(_rv, HoldingRegisterVariable))

    def test_language(self):
        """Test pattoo_shared.Config inherited method language."""
        # Initialize key values
        expected = 'abc'

        # Test
        result = self.config.language()
        self.assertEqual(result, expected)

    def test_agent_api_ip_address(self):
        """Test pattoo_shared.Config inherited method agent_api_ip_address."""
        # Initialize key values
        expected = '127.0.0.11'

        # Test
        result = self.config.agent_api_ip_address()
        self.assertEqual(result, expected)

    def test_agent_api_ip_bind_port(self):
        """Test pattoo_shared.Config inherited method agent_api_ip_bind_port."""
        # Initialize key values
        expected = 50001

        # Test
        result = self.config.agent_api_ip_bind_port()
        self.assertEqual(result, expected)

    def test_agent_api_uri(self):
        """Test pattoo_shared.Config inherited method api_uri."""
        # Initialize key values
        expected = '/pattoo/api/v1/agent/receive'

        # Test
        result = self.config.agent_api_uri()
        self.assertEqual(result, expected)

    def test_agent_api_server_url(self):
        """Test pattoo_shared.Config inherited method agent_api_server_url."""
        # Initialize key values
        expected = 'http://127.0.0.11:50001/pattoo/api/v1/agent/receive/123'
        agent_id = 123

        # Test
        result = self.config.agent_api_server_url(agent_id)
        self.assertEqual(result, expected)

    def test_web_api_ip_address(self):
        """Testing method / function web_api_ip_address."""
        # Test
        result = self.config.web_api_ip_address()
        self.assertEqual(result, '127.0.0.12')

    def test_web_api_ip_bind_port(self):
        """Testing method / function web_api_ip_bind_port."""
        # Test
        result = self.config.web_api_ip_bind_port()
        self.assertEqual(result, 50002)

    def test_web_api_server_url(self):
        """Testing method / function web_api_server_url."""
        # Test
        result = self.config.web_api_server_url()
        self.assertEqual(
            result, 'http://127.0.0.12:50002/pattoo/api/v1/web/graphql')

    def test_daemon_directory(self):
        """Test pattoo_shared.Config inherited method daemon_directory."""
        # Nothing should happen. Directory exists in testing.
        _ = self.config.daemon_directory()

    def test_log_directory(self):
        """Test pattoo_shared.Config inherited method log_directory."""
        # Nothing should happen. Directory exists in testing.
        _ = self.config.log_directory()

    def test_log_file(self):
        """Test pattoo_shared.Config inherited method log_file."""
        # Initialize key values
        expected = '{1}{0}pattoo.log'.format(
            os.sep, self.config.log_directory())

        # Test
        result = self.config.log_file()
        self.assertEqual(result, expected)

    def test_log_file_api(self):
        """Test pattoo_shared.Config inherited method log_file_api."""
        # Initialize key values
        expected = '{1}{0}pattoo-api.log'.format(
            os.sep, self.config.log_directory())

        # Test
        result = self.config.log_file_api()
        self.assertEqual(result, expected)

    def test_log_level(self):
        """Test pattoo_shared.Config inherited method log_level."""
        # Initialize key values
        expected = 'debug'

        # Test
        result = self.config.log_level()
        self.assertEqual(result, expected)

    def test_log_file_daemon(self):
        """Test pattoo_shared.Config inherited method log_file_daemon."""
        # Initialize key values
        expected = '{1}{0}pattoo-daemon.log'.format(
            os.sep, self.config.log_directory())

        # Test
        result = self.config.log_file_daemon()
        self.assertEqual(result, expected)

    def test_cache_directory(self):
        """Test pattoo_shared.Config inherited method cache_directory."""
        # Nothing should happen. Directory exists in testing.
        _ = self.config.cache_directory()

    def test_agent_cache_directory(self):
        """Test pattoo_shared.Config inherited method agent_cache_directory."""
        # Initialize key values
        agent_id = 123
        expected = '{1}{0}{2}'.format(
            os.sep, self.config.cache_directory(), agent_id)

        # Test
        result = self.config.agent_cache_directory(agent_id)
        self.assertEqual(result, expected)

class TestBasicFunctions(unittest.TestCase):
    """Checks all ConfigSNMP methods."""

    ##########################################################################
    # Initialize variable class
    ##########################################################################

    def test__create_drv(self):
        """Testing method / function _create_drv."""
        # Tested by test_registervariables
        pass

if __name__ == '__main__':
    # Make sure the environment is OK to run unittests
    UnittestConfig().create()

    # Do the unit test
    unittest.main()


import os
import json
import matplotlib.pyplot as plt

from MatchHistory import MatchHistory
from FileStorage import FileStorage

class MatchStats:
    """Class to go through the games in the match history and get indepth stats from it"""

    def __init__(self, summonerName, server = "na1", champion = "", queue = ""):
        self.summonerName = summonerName
        self.champion = champion
        self.queue = queue
        self.server = server

        self.fileStorage = FileStorage()
        self.matchHistory = MatchHistory(self.summonerName, self.server, self.champion, self.queue)

        # file handling
        self.queueFile = self.queue.title()
        self.championFile = self.champion.replace(" ", "") #no spaces

        self.specificGameIdFile = f"{self.fileStorage.dataStoragePath}/{self.server}/{self.summonerName}/{self.championFile}{self.queueFile}GameIds.json"

        self.detailedMatchesFolder = f"{self.fileStorage.dataStoragePath}/{self.server}/{self.summonerName}/matches"
        # plot files
        self.figureFilename = f"{self.fileStorage.dataStoragePath}/{self.server}/{self.summonerName}"

    def getParticpantId(self, matchData):
        """stats are sorted by participant ID in the match files, will need to get that everytime"""
        try:
            participants = matchData["participantIdentities"]
        except KeyError:
            pass
        for participant in participants:
            if participant['player']['summonerName'] == self.summonerName:
                participantId = participant['participantId']

        return participantId

    def getCsValues(self):
        """get the values for the cs per minute the player in the list of game Ids"""

        gameIdFile = self.specificGameIdFile

        # get the game ids
        with open(gameIdFile) as f:
            gameIds = json.load(f)

        csdList = []

        # loop through all the games in gameIds, getting the csd values for the player
        for game in gameIds:
            try:
                with open(f"{self.detailedMatchesFolder}/{game}.json") as matchFile:
                    # get the participant Id
                    matchData = json.load(matchFile)
                    participantId = self.getParticpantId(matchData)

                    # go into the participants list, if its the correct participant then get the values for CSD (or all stats?)

                    participants = matchData["participants"]

                    for participant in participants:
                        if participant["participantId"] == participantId:
                            try:
                                csd = participant["timeline"]["creepsPerMinDeltas"]["0-10"]
                                csdList.append(csd)
                            except KeyError:
                                pass
            except FileNotFoundError:
                pass

        return csdList

    def plotCsValues(self):
        """Make a plot of the differences in CS"""
        csValues = self.getCsValues()
        numGames = len(csValues)
        figureFilename = f"{self.figureFilename}/CsDifferences.png"

        plt.style.use('dark_background')
        fig, ax = plt.subplots()
        ax.plot(range(numGames), csValues)
        plt.xlabel('Game Number')
        plt.ylabel('CS Per Minute at 10')
        plt.title('CS Per Minute by 10 minutes')
        ax.tick_params(axis='x', which='major', rotation=90)
        plt.savefig(figureFilename,bbox_inches='tight')

        return ax

    def displayPlots(self):
        """display the plots"""
        plotCsDifferences = self.plotCsValues()

        plt.show()


from xai.brain.wordbase.adjectives._thirsty import _THIRSTY

#calss header
class _THIRSTIER(_THIRSTY, ):
	def __init__(self,):
		_THIRSTY.__init__(self)
		self.name = "THIRSTIER"
		self.specie = 'adjectives'
		self.basic = "thirsty"
		self.jsondata = {}


import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torchvision
import os
import argparse
import torch.backends.cudnn as cudnn
import math
import pickle
#import torch.mul as mul
from utils import progress_bar

best_acc = 0
batch_size = 64
epoch_time = 0
#mnist : 28 * 28
input_size = 28
time_step = 28
hidden_size = 64

is_resume = False
train_loss_record = []
test_loss_record = []

parser = argparse.ArgumentParser(description='PyTorch LSTM Training on MNIST dataset')
#default learing rate = 0.1
parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--resume', '-r', help='resume from checkpoint')
parser.add_argument('--dropout', default=0.2, type=float, help='dropout')
parser.add_argument('--epoch', default=20, type=int, help='training epoch')
args = parser.parse_args()

print('learning rate',args.lr)
print('dropout',args.dropout)

device = 'cuda' if torch.cuda.is_available() else 'cpu'

train_data = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_data = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, shuffle=True)

print('batch size', batch_size)
print('size of training dataset', len(train_loader))

epoch_time = args.epoch
model_weights_name = 'lstm_mnist'

class LSTM_self(nn.Module):
	def __init__(self, input_size, hidden_size, bias=True, dropout=0.0):
		super(LSTM_self, self).__init__()
		self.input_size = input_size
		self.hidden_size = hidden_size
		self.bias = bias
		self.dropout = dropout
		#there are four parts(i, f, o, c), each part size is hidden_size
		#input to hidden: in_channel = input_size*timestep(28*28)
		self.i2h = nn.Linear(input_size*time_step, 4 * hidden_size, bias=bias)
		#hidden to hidden : hidden_size
		self.h2h = nn.Linear(hidden_size, 4 * hidden_size, bias=bias)
		self.outlayer = nn.Linear(hidden_size, 10)
		#self.reset_parameters()
		#====prevent value error of dropout or not====#

		#=============================================#
	def reset_parameters(self):
		std = 1.0 / math.sqrt(self.hidden_size)
		for w in self.parameters():
			print(w)
			w.data.uniform_(-std, std)
	def forward(self, x, hidden):
		#do_dropout = self.training and self.dropout > 0.0
		#initial state of hidden layer and cell
		h, c = hidden

		#reshape h,c,x
		#reserve the dimension 0, and the rest of dimension do multiplication
		#h = h.view(h.size(0),-1)
		#c = c.view(c.size(0),-1)
		#x shape : from (64,28,28) to (64,28*28)
		x = x.view(x.size(0),-1)
		#h shape: (batch size, hidden size) (64,64)
		#c shape: (batch size, hidden size) (64,64)

		# Linear mappings
		#preact shape : (64,256) (four parts, 64*4=256)
		preact = self.i2h(x) + self.h2h(h)

		#print('preact.shape',preact.shape)

		# activations
		'''
		math:
		equation 1:
		i_t = sigmoid(w_x_i*xt+w_h_i*h(t-1)+bi)
		f_t = sigmoid(w_x_f*xt+w_h_f*h(t-1)+bf)
		o_t = sigmoid(w_x_o*xt+w_h_o*h(t-1)+bo)

		equation 2: input transform with cell state(c_in(t)=current input)
		c_in(t) = tanh(w_x_c*xt + w_h_c*h(t-1) + bc)

		equation 3:
		c(t) = f(t)*c(t-1) + i(t)*c_in(t)
		h(t) = o(t)*tanh(c(t))

		'''

		#equation 1, from 0 to 3*hidden_size(i,f,o)
		gates = preact[:, :3 * self.hidden_size].sigmoid()
		#equation 2, from 3*hidden_size to end(c)
		g_t = preact[:, 3 * self.hidden_size:].tanh()
		#i_t : input gate at time t. f_t : forget gate. o_t : output_gate
		i_t = gates[:, :self.hidden_size]
		f_t = gates[:, self.hidden_size:2 * self.hidden_size]
		o_t = gates[:, 2 * self.hidden_size: 3 * self.hidden_size]

		#equation 3 + dropout
		if self.dropout != 0.0:
			g_t = F.dropout(g_t,p=self.dropout)
		c_t = torch.mul(c, f_t) + torch.mul(i_t, g_t)
		if self.dropout != 0.0:
			c_t = F.dropout(c_t,p=self.dropout)
		h_t = torch.mul(o_t, c_t.tanh())
		if self.dropout != 0.0:
			h_t = F.dropout(h_t,p=self.dropout)

		#reshape: from (16,64) to (1,16,64)
		h_t = h_t.view(1, h_t.size(0), -1)
		c_t = c_t.view(1, c_t.size(0), -1)

		#return h_t, (h_t, c_t)
		#previously reshape is for return (16,64)
		#position -1 means returning the latest value of h_t(though it may just have one value)
		output = self.outlayer(h_t[-1,:,:])
		return output

lstm = LSTM_self(input_size,hidden_size,dropout=0.2)
print(lstm)
lstm = lstm.to(device)
if device == 'cuda':
	lstm = torch.nn.DataParallel(lstm)
	cudnn.benchmark = True
# Load checkpoint.
if args.resume:
	print('==> Resuming from checkpoint..')
	assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'
	checkpoint = torch.load('./checkpoint/'+model_weights_name+'.t7')
	lstm.load_state_dict(checkpoint['lstm'])
	best_acc = checkpoint['acc']
	start_epoch = checkpoint['epoch']
	is_resume = True

optimizer = torch.optim.Adam(lstm.parameters(), lr=args.lr)
loss_func = nn.CrossEntropyLoss()

#for training
def train():
	#should be added?
	lstm.train()
	# gives batch data
	train_loss = 0
	correct = 0
	total = 0

	for batch_idx, (inputs, targets) in enumerate(train_loader):
		current_batch = len(inputs)
		inputs, targets = inputs.to(device), targets.to(device)
		# reshape x to (batch, time_step, input_size)
		#change shape to (64,28,28), no batch
		input_reshape = inputs.view(-1, 28, 28)

		#initial state of hidden and cell
		h = torch.zeros(current_batch,hidden_size,dtype=torch.float32)
		c = torch.zeros(current_batch,hidden_size,dtype=torch.float32)
		h, c = h.to(device), c.to(device)

		outputs = lstm(input_reshape,(h,c))
		# cross entropy loss
		loss = loss_func(outputs, targets)
		optimizer.zero_grad()
		loss.backward()
		optimizer.step()
		#===============================compute loss========================#
		train_loss += loss.item()
		_, predicted = outputs.max(1)
		total += targets.size(0)
		#correct target
		correct += predicted.eq(targets).sum().item()
		#(computing loss so far) / (processing batch so far)
		progress_bar(batch_idx, len(train_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
			% (train_loss/(batch_idx+1), 100.*correct/total, correct, total))

		#===================================================================#
	train_loss_record.append((train_loss/(batch_idx+1)))
#for testing
def test(epoch):
	global best_acc
	#do testing
	lstm.eval()
	test_loss = 0
	correct = 0
	total = 0
	#do not calculate gradient
	with torch.no_grad():
		for batch_idx, (inputs, targets) in enumerate(test_loader):

			current_batch = len(inputs)
			inputs, targets = inputs.to(device), targets.to(device)
			#initial state of hidden and cell
			h = torch.zeros(current_batch,hidden_size,dtype=torch.float32)
			c = torch.zeros(current_batch,hidden_size,dtype=torch.float32)
			h, c = h.to(device), c.to(device)

			outputs = lstm(inputs,(h,c))
			loss = loss_func(outputs, targets)

			#tensor.max(1) : the first value: the maximum value in tensor. the second value: the idx of the first value (return type:tensor)

			#compute testing loss
			test_loss += loss.item()
			max_acc, max_idx = outputs.max(1)

			#total will be added batch by batch
			total += targets.size(0)
			#use sum() to sum up all the value, but the return type is still tensor
			#so use item() to extract the value
			correct += max_idx.eq(targets).sum().item()

			progress_bar(batch_idx, len(test_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
				% (test_loss/(batch_idx+1), 100.*correct/total, correct, total))

	test_loss_record.append((test_loss/(batch_idx+1)))
	# Save checkpoint.
	if is_resume != True:
		acc = 100.*correct/total
		if acc > best_acc:
			print('Saving..')
			state = {
				'lstm': lstm.state_dict(),
				'acc': acc,
				'epoch': epoch,
			}
			if not os.path.isdir('checkpoint'):
				os.mkdir('checkpoint')
			torch.save(state, './checkpoint/'+model_weights_name+'.t7')
			best_acc = acc

if __name__ == '__main__':
	for epoch_num in range(epoch_time):
		if is_resume == True:
			test(epoch_num)
			break
		else:
			print('epoch',epoch_num)
			train()
			test(epoch_num)
	if is_resume != True:
		with open(model_weights_name+'_train_loss','wb') as fp:
			pickle.dump(train_loss_record,fp)
		with open(model_weights_name+'_test_loss','wb') as fp:
			pickle.dump(test_loss_record,fp)


import re;

def preprocess_subinsts(input_lines, output_lines, savelines, debug):
    """
    # Add #SUBINST comment w/name of subinstance.

    #####################################################
    # Example (SUBINST added):
    #
    # #SUBINST tst2dut_cfg_ifc
    #    <SubInstanceItem>
    #      <BaseModuleName>cfg_ifc</BaseModuleName>
    #      ...
    #      <InstanceName>tst2dut_cfg_ifc</InstanceName>
    #      ...
    #    </SubInstanceItem>
    #####################################################
    """
    #print "hello i am preprocess_subinsts";

    #while (@input_lines) {
    #   my $line = shift @input_lines;

    while (input_lines):
        line = input_lines[0];

        # Not interested unless we find a "SubInstanceItem" block.

        #if (! ($line =~ /^\W*<SubInstanceItem>\W*$/)) {
        #    savelines($line); # Save lines in "output_lines" block for next pass.
        #    next;
        #}

        if (not (re.search("^\W*<SubInstanceItem>\W*$", line))) :
            savelines(line);    # Save lines in "output_lines" block for next pass.
            input_lines.pop(0); # (pop(0) == shift);
            continue;

	#<SubInstanceItem> alone on a line: start looking for InstanceName.

	#my @saveblock = ("#$line");
        #saveblock = ["#" + line];  # Save lines until parm block is completely processed
        saveblock = [];

#	while (my $subline = shift(@input_lines)) {
#

        while (input_lines):
            subline = input_lines[0];
            input_lines.pop(0); # (pop(0) == shift);

            #push @saveblock, $subline;  # Save lines in buffer until find InstanceName
            saveblock.append(subline);

            match_iname = re.search("^\s*<InstanceName>([^<]+)</InstanceName>" , subline);

            if re.search(subline, "^\W*<SubInstanceItem>\W*$"):
                printdie("ERROR: no InstanceName before SubInstanceItem");

            elif re.search(subline, "^\W*</SubInstanceItem>\W*$"):
                printdie("ERROR: no InstanceName in SubInstanceItem block");

            #elsif ($subline =~ /^\s*<InstanceName>([^<]+)<\/InstanceName>/) {
            elif match_iname:

                #savelines("#SUBINST $1\n");
                #savelines(@saveblock);
                #last; # We done (with SubInstanceItem block).

                # Found InstanceName; write it out, along with saved lines.
                savelines("#SUBINST %s\n" % match_iname.group(1));
                for tmp in saveblock : savelines(tmp);
                break;                                   # perl: last

    # END while (input_lines)
# END def preprocess_subinsts

#def savelines(line):
#    if (print_savelines): print line,
#    output_lines.append(line);
#
#


N, K = map( int, input().split())
A = list( map( int, input().split()))
RA = sorted(A)
RA = RA[::-1]
s = 0
ans = 0
for i in range(N):
    a = RA[i]
    if s+a < K:
        s += a
        ans += 1
    else:
        ans = 0
print(ans)
#反例
#5 12
#6 4 3 2 1
#通るらしいけどなんでかわからない
#https://beta.atcoder.jp/contests/abc056/submissions/2203497
    # Aのうち要素が大きいものから見ていったとき、
    # その要素を入れても総和がK未満のものだけ加えていく
    # 最後に連続して加えた要素の個数が解となる
    # (それら以外の要素の組み合わせでK以上にでき、かつ、
    #  それらの総和がK未満になるため)


from __future__ import print_function
from mitsuba.core import *
import mitsuba
from mitsuba.render import Scene
import multiprocessing
from mitsuba.render import *
from MitsubaShape import *

#My imports
from Material import *
from Integrator import *
from Sampler import *
from Sensor import *
from Film import *

sensorProps = None

scheduler = Scheduler.getInstance()

import time

# Start up the scheduling system with one worker per local core
for i in range(0, multiprocessing.cpu_count()):
    w = LocalWorker(i, "wkr%i" % i)
    scheduler.registerWorker(w)

scheduler.start()
queue = RenderQueue()

image_width = 304
image_height = 228
# image_width = 320
# image_height = 240
num_samples = 64

mesh_file = 'data/car_000000027.ply'
#mesh_file = '/home/adrian/model/Medieval_City.obj'

def register_scene_config(scene, pmgr, scene_config):

        scene_node = pmgr.create(scene_config)
        scene.addChild(scene_node)
        scene.configure()

        scene.initialize()
        sceneResID = scheduler.registerResource(scene)
        return sceneResID

def init_scene():

    pmgr = PluginManager.getInstance()

    camera_pos = Vector(0, 0.0, -12)
    model_pos = Vector(0.5, -0.5, -2.0)

    #camera_pos = Vector(4, 44.0, -7.0)
    #model_pos = Vector(0.0, 0.0, 0.0)

    #camera_matrix = Transform(Matrix4x4([[0.1,0.017,-1.0,0.0],[0.0,1.0,0.0,0.1],[1.0,0.0,0.1,0.0],[4.3,-6.0,-7.0,1.0]]))

    cube_pos = Vector(-0.5, 0.0, -1.0)

    a = MitsubaShape(shape_type=MitsubaShape.PLY_TYPE, to_world=Transform.translate(model_pos), filename=mesh_file)
    b = MitsubaShape(shape_type=MitsubaShape.CUBE, to_world=Transform.translate(cube_pos))

    #integrator = create_integrator(RenderTargetType.AO, hide_emitters=False)
    integrator = create_integrator(RenderTargetType.DIRECT, hide_emitters=True)
    depth_integrator = create_integrator(RenderTargetType.INDEX, hide_emitters=True)

    sampler = Sampler(SamplerType.HALTON, num_samples=num_samples)
    film = Film(FilmType.LDR, image_width, image_height)
    sensor = Sensor(SensorType.PERSPECTIVE, sampler=sampler, film=film, to_world=Transform.translate(camera_pos))

    scene_config = {
        'type' : 'scene',
        'a': a.config,
        # 'b':b.config,
        # 'envmap' : {
        #      'type' : 'sunsky',
        #      'hour' : 12.0,
        #      'albedo' : Spectrum(1.0),
        #      'samplingWeight' : 1.0,
        # },
        # 'envmap' : {
        #      'type' : 'sunsky',
        #      #'hour' : 10.0,
        #      'radiance': Spectrum(1.0),
        #      'samplingWeight': 1.0
        # },
        'sensor' : sensor.config
    }

    # scene_config['cube'] = create_object('cube', Transform.translate(model_pos), bsdf=create_bsdf())

    yangles = range(0,1)
    xangles = range(0,1)
    num_views = len(xangles) * len(yangles)
    #step_size = 360/(num_views)
    step_size = 1

    #List containing the integrators to use in Multi-Pass rendering
    passes = [integrator, depth_integrator]

    start = time.time()
    render_count = 0
    num_scale = 1
    offset = num_scale/2
    print ("Size:", (num_views*num_scale))

    for x in xangles:
        for y in yangles:
            original_Z = camera_pos[2]
            for s in range(num_scale):

                #for y in range(yangles):
                    #Set the correct destination file
                new_camera = camera_pos
                z = (s - offset)
                print ("Z:", z)
                print(new_camera[2])
                new_camera[2] = original_Z + z
                print(new_camera[2])

                for p in passes:

                    i = render_count
                    scene = Scene()
                    pass_config = scene_config

                    destination = 'results/%03i' % i
                    if p.type == RenderTargetType.DEPTH:
                        destination += "_d"
                    elif p.type == RenderTargetType.NORMAL:
                        destination += "_n"

                    #Set the pass integrator
                    pass_config['integrator'] = p.config
                    sceneResID = register_scene_config(scene, pmgr, scene_config)

                    # Create a shallow copy of the scene so that the queue can tell apart the two
                    # rendering processes. This takes almost no extra memory
                    newScene = mitsuba.render.Scene(scene)
                    pmgr = PluginManager.getInstance()
                    newSensor = pmgr.createObject(scene.getSensor().getProperties())

                    #Calculate the rotations
                    yrotation = Transform.rotate(Vector(1, 0, 0), y)
                    xrotation = Transform.rotate(Vector(0, 1, 0), x)
                    rotationCur = xrotation * yrotation

                    #Set the new camera position, applying the rotations
                    new_pos = rotationCur*new_camera
                    new_transform = Transform.lookAt(Point(new_pos), Point(0, 0, 0), Vector(0, 1, 0))
                    newSensor.setWorldTransform(new_transform)

                    newFilm = pmgr.createObject(scene.getFilm().getProperties())
                    newFilm.configure()
                    newSensor.addChild(newFilm)
                    newSensor.configure()
                    newScene.addSensor(newSensor)
                    newScene.setSensor(newSensor)
                    newScene.setSampler(scene.getSampler())
                    newScene.setDestinationFile(destination)

                    # Create a render job and insert it into the queue. Note how the resource
                    # ID of the original scene is provided to avoid sending the full scene
                    # contents over the network multiple times.
                    j = RenderJob('myRenderJob' + str(i), newScene, queue, sceneResID)
                    j.start()

                render_count += 1

    # Wait for all jobs to finish and release resources
    queue.waitLeft(0)

    finish = time.time()
    print("Run Time:", finish-start)

def main():
    # Encodes parameters on how to instantiate the 'perspective' plugin
    init_scene()

if __name__ == "__main__":
    main()


# coding=UTF-8+-
'''
Created on 2016年10月24日

@author: dmnnaxxi
Detecting and tracking faces
We need a classifier model that can be used to
detect the faces in an image. OpenCV provides
an xml file that can be used for this purpose.
We use the function CascadeClassifier to load
the xml file. Once we start capturing the input
frames from the webcam, we convert it to grayscale
and use the function detectMultiScale to get the
bounding boxes for all the faces in the current
image. The second argument in this function
specifies the jump in the scaling factor.
As in, if we don’t find an image in the current
scale, the next size to check will be, in our case,
1.3 times bigger than the current size. The last
parameter is a threshold that specifies the number
of adjacent rectangles needed to keep the current
rectangle. It can be used to increase the robustness
of the face detector.
'''
import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('../../haarcascades/haarcascade_frontalface_alt.xml')

cap = cv2.VideoCapture(0)
scalling_factor = 0.5

while True:
    ret,frame = cap.read()
    frame = cv2.resize(frame,None,fx=scalling_factor,fy=scalling_factor,interpolation=cv2.INTER_AREA)
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    face_rects = face_cascade.detectMultiScale(gray,1.3,5)
    for (x,y,w,h) in face_rects:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)

    cv2.imshow('Face Detector',frame)

    c = cv2.waitKey(1)
    if c == 27:
        break

cap.release()
cv2.destroyAllWindows()


class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i = int(a, 2)
        j = int(b, 2)
        val = i + j
        val = str(bin(val))
        return val[2::]

sol = Solution()

print(sol.addBinary(11, 1))


import datetime
import json
import math
import os
import re
import shutil
import sys

import htcondor

pjoin = os.path.join

def chunkify(items, nchunk):
    '''Split list of items into nchunk ~equal sized chunks'''
    chunks = [[] for _ in range(nchunk)]
    for i in range(len(items)):
        chunks[i % nchunk].append(items[i])
    return chunks

def ismc(dataset):
    return True

def setup_dirs(datasets, tag):

    # Copy gridpack
    owd = os.getcwd()
    os.chdir(pjoin(os.environ['CMSSW_BASE'],'..'))
    os.system('tar -zvcf CMSSW_11_2_1_%s.tgz CMSSW_11_2_1 --exclude="*.root" --exclude="*.pdf" --exclude="*.pyc" --exclude=tmp --exclude="*.tgz" --exclude-vcs --exclude-caches-all --exclude="*err*" --exclude=*out_* --exclude=*txt --exclude=*jdl'%tag)
    print("tar complete")
    os.chdir(owd)

    for year in datasets:

        # Overall working directory for this tag
        wdir = os.path.abspath("./wdir/%s/%s/"%(tag,year))
        try:
            os.makedirs(wdir)
        except: # FileExistsError:
            pass

        gp_original = pjoin(os.environ['CMSSW_BASE'],'..','CMSSW_11_2_1_%s.tgz'%tag)
        gp = pjoin(wdir, os.path.basename(gp_original))
        shutil.copyfile(gp_original, gp)

        # Loop over datasets
        for item in datasets[year]:
            shortname = item['dataset']
            print('Submitting sample %s'%shortname)
            outdir = "/store/user/lpcbacon/drankin/nanopost_process/%s/%s/%s"%(tag, year, shortname)

            os.system("eos root://cmseos.fnal.gov/ mkdir -p %s"%outdir)
            # Working directory for this dataset
            subdir = pjoin(wdir, shortname)
            try:
                os.makedirs(subdir)
            except: #FileExistsError:
                UserWarning ('overwriting files!')

            # Submission date identifier
            subdate = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
            # Read list of files
            with open(str(item['filelist'])) as f:
                files = [x.strip() for x in f.readlines()]
            cut='(1==1)' #cut = '(FatJet_msoftdrop[0]>30.)&&(FatJet_pt[0]>450.)'
            #if 'JetHT' in shortname: cut += '&&(event%10==0)'
            print('Preparing %i jobs with %i files per job'%(int(math.ceil(len(files) / item['mergefactor'])), item['mergefactor']))
            for ichunk, chunk in enumerate( chunkify(files, int(math.ceil(len(files) / item['mergefactor'])))):
                input_files = [
                    gp,
                    #os.path.abspath('./input/nano_from_edm_cfg.py')
                ]
                arguments = [
                    tag,
                    item['dataset'],
                    shortname,
                    year,
                    ismc(item['dataset']),
                    ichunk,
                    'nocrab_' + subdate,
                    0,# if item['convert'] else 0,
                    outdir,
                    cut,
                ] + chunk

                # Dfine submission settings
                submission_settings = {
                    "Initialdir" : subdir,
                    "executable": os.path.abspath("./input/skim.sh"),
                    "should_transfer_files" : "YES",
                    "transfer_input_files" : ", ".join(input_files),
                    "arguments": " ".join([str(x) for x in arguments]),
                    "Output" : "out_%s_%s_%i.txt"% ( tag, shortname, ichunk ),
                    "Error" : "err_%s_%s_%i.txt" % ( tag, shortname, ichunk ),
                    "log" : "log_%s_%s_%i.txt"   % ( tag, shortname, ichunk ),
                    "WhenToTransferOutput" : "ON_EXIT_OR_EVICT",
                    "universe" : "vanilla",
                    "request_cpus" : 1,
                    "request_memory" : 2000,
                    #"+MaxRuntime" : "{60*60*8}",
                    "on_exit_remove" : "((ExitBySignal == False) && (ExitCode == 0)) || (NumJobStarts >= 2)",
                    }

                # Write JDL file
                jobfile = pjoin(subdir, "skim_%s_%s_%i.jdl"% (tag, shortname, ichunk) )
                sub = htcondor.Submit(submission_settings)
                with open(jobfile,"w") as f:
                    f.write(str(sub))
                    f.write("\nqueue 1\n")

                #if ('boostedTau' not in item['dataset'] or ichunk%5==0):
                os.system('condor_submit %s'%jobfile)

def main():
    tag = 'Sep14'
    skiplist = ['boostedTau','HTauTau','HToWW','WJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8','JetHT']
    whitelist = []
    datasets_dict = {}
    with open("input/fileset_2017.json","r") as f:
        datasets_dict['2017'] = json.loads(f.read())
    with open("input/fileset_2018.json","r") as f:
        datasets_dict['2018'] = json.loads(f.read())
    datasets = {}
    for y in ['2017', '2018']:
        datasets[y] = []
        for d in datasets_dict[y]:
            if any(d['dataset'].startswith(s) for s in skiplist): continue
            if len(whitelist)>0:
                if (not any(w in d['dataset'] for w in whitelist)): continue
            print(d['dataset'])
            datasets[y].append(d)

    setup_dirs(datasets, tag)

if __name__ == "__main__":
    main()


from __future__ import print_function
import math

treefmt = "I6,I3,F6.0,I1,A3,F5.1,F3.1,F3.0,F3.0,F4.1,I1,6I2,I1,I1,I2,I3,I3,I1,I1,F4.0"
treefmt = treefmt.split(",")

valid_types = "IFA"

def linepos(treefmt):
    line = 0
    for fmt in treefmt:
        mult = 1
        ftype, num = fmt[0], fmt[1:]
        if ftype not in valid_types:
            # assume it's a number
            mult = int(ftype)
            ftype, num = num[0], num[1:]
        num = int(math.floor(float(num)))
        for x in range(mult):
            line += num
            yield line

if __name__ == '__main__':
    print(list(linepos(treefmt)))


import re
import operator

from datetime import datetime
from tinydb import TinyDB, Query
from functools import reduce

def is_phone(value: str) -> bool:
    """
    Функция проверяет, является ли переданная строка номером телефона.
    Формат номера телефона, по условию тестового задания: +7 xxx xxx xx xx
    """
    pattern = re.compile("^\+7\s\d{3}\s\d{3}\s\d{2}\s\d{2}$")
    return bool(pattern.match(value))

def is_email(value: str) -> bool:
    """
    Функция проверяет, является ли переданная строка email адресом.
    """
    pattern = re.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
    return bool(pattern.match(value))

def is_date(value: str) -> bool:
    """
    Функция проверяет, является ли переданная строка датой по своему формату.
    Формат даты, по условию тестового задания, может быть DD.MM.YYYY или YYYY-MM-DD.
    """

    ddmmyyyy = re.compile("^\d{2}.\d{2}.\d{4}$")  # DD.MM.YYYY
    yyyymmdd = re.compile("^\d{4}-\d{2}-\d{2}$")  # YYYY-MM-DD

    try:
        if ddmmyyyy.match(value):
            datetime.strptime(value, '%d.%m.%Y')
        elif yyyymmdd.match(value):
            datetime.strptime(value, '%Y-%m-%d')
        else:
            raise ValueError()
    except:
        # Неправильный формат даты.
        return False
    else:
        return True

def get_field_type_by_field_value(value: str) -> str:
    """
    Функция возвращает тип поля формы исходя из его значения.
    Всего поддерживается четыре типа полей: date, phone, email, text.
    Тип поля формы 'text' является запасным, когда значение поля формы не совпадает ни с одним из вышеописанных типов.
    """
    if is_date(value):
        return 'date'
    elif is_phone(value):
        return 'phone'
    elif is_email(value):
        return 'email'
    else:
        return 'text'

def search_form_template_name_by_post_parameters(search_params: dict):
    """
    Функция поиска имени шаблона формы.
    Совпавшими считаются поля, у которых совпали имя и тип значения.
    """
    db = TinyDB('db.json')
    q = Query()

    # Первым действием необходиом получить все шаблоны форм,
    # поля которого совпали, хотябы один раз, с полями присланной формы
    query_conditions = [q[field_name] == field_type for field_name, field_type in search_params.items()]
    query = reduce(operator.or_, query_conditions)
    search_result = db.search(query)

    if len(search_result) == 0:
        # Если ни одного шаблона формы не найдено
        return None

    elif len(search_result) == 1:
        # Если был найдет один шаблон формы,
        # значит один или более полей формы совпали,
        # в этом случае возвращаем имя шаблона формы
        return search_result[0]['ftname']

    else:
        # Если найдено больше одного шаблона формы, сравниваем каждый найденый шаблон формы
        # с  полями присланой формы, считаем количество совпавших полей и записываем в словарь.
        # {id шаблона формы: кол-во совпавших полей, ...}
        result = {item.eid: len(set(item.items() & search_params.items())) for item in search_result}

        # Получаем id шаблона формы с максимальным кол-вом совпавших полей ...
        eid = max(result, key=result.get)

        # ... находим его в бд и получаем имя
        return db.get(eid=eid)['ftname']


#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os

vallist = 'vallist.txt'
testlist = 'testlist.txt'
sampling_times = 10
cropping_times = 3

fl = open(vallist).readlines()
fl = [line.strip() for line in fl if line.strip() != '']
f_test = open(testlist, 'w')

for i in range(len(fl)):
    line = fl[i].split(' ')
    fn = line[0]
    label = line[1]
    for j in range(sampling_times):
        for k in range(cropping_times):
            test_item = fn + ' ' + str(i) + ' ' + str(j) + ' ' + str(k) + '\n'
            f_test.write(test_item)

f_test.close()


''' World Class
This class is the launching point for the game.
This is the file that needs to run to start the game,
and this class creates all the pieces of the game.
'''
import direct.directbase.DirectStart
from direct.filter.CommonFilters import CommonFilters

from TrackClass_00 import Track
from CycleClass_00 import Cycle
from InputManagerClass_00 import InputManager
from MenuClass_01 import Menu

class World:
	def __init__(self):
		base.disableMouse()
		# Turns off the default mouse-camera controls in Panda3D.

		base.setBackgroundColor(0, 0, 0)
		# Sets the background to black.

		self.inputManager = InputManager()
		# Creates an InputManager to handle all of the user input in the game.

		self.track = Track()
		# Creates the track the cycles will race on.

		self.cycle1 = Cycle(self.inputManager, self.track, 1, "Bert", ai = True)
		self.cycle2 = Cycle(self.inputManager, self.track, 2, "Ernie", ai = True)
		self.cycle3 = Cycle(self.inputManager, self.track, 3, "William", ai = True)
		self.cycle4 = Cycle(self.inputManager, self.track, 4, "Patrick", ai = True)
		# Creates one uncontrolled cycle, and one player controlled cycle.

		taskMgr.doMethodLater(10, self.debugTask, "Debug Task")
		# Tells the debugTask to run once every ten seconds. The debug task is a good
		# place to put various data print outs about the game to help with debugging.

		self.filters = CommonFilters(base.win, base.cam)
		filterok = self.filters.setBloom(blend=(0,0,0,1),
			desat=-0.5, intensity=3.0, size=2)

		render.setShaderAuto()
		# Turns on Panda3D's automatic shader generation.

		self.menuGraphics = loader.loadModel(
			"../Models/MenuGraphics.egg")
		self.fonts = {
			"silver" : loader.loadFont("../Fonts/LuconSilver.egg"),
			"blue" : loader.loadFont("../Fonts/LuconBlue.egg"),
			"orange" : loader.loadFont("../Fonts/LuconOrange.egg")}

		menu = Menu(self.menuGraphics, self.fonts, self.inputManager)

		menu.initMenu([0,None,
			["New Game","Quit Game"],
			[[self.printTest],[self.printTest]],
			[[0],[1]]])

	def printTest(self,arg):
		print(arg)

	def debugTask(self, task):
		print(taskMgr)
		# prints all of the tasks in the task manager.
		return task.again
# debugTask: Runs once every ten seconds to print out reports on the games status.
w = World()
run()


#%%
import json
from pathlib import Path

results_files = [
    Path("sebastian/results/linear_search_results.json"),
    Path("sebastian/results/linear_search_results_8_10.json"),
]
with open(results_files[0], "r") as f:
    results = json.load(f)

with open(results_files[1], "r") as f:
    results_2 = json.load(f)
    results["best_s"] = results_2["best_s"]
    results["best_acc"] = results_2["best_acc"]

    results["performances"] += results_2["performances"]

#%% binary case
import matplotlib.pyplot as plt

def extract_data(class_mode: str, total_set_size):
    parameter_values = []
    accuracies = []
    recall = []
    precision = []
    unmatched_total = []
    unmatched_e = []
    unmatched_non_e = []
    for result in results["performances"]:
        parameter_values += [result[0]]

        binary = result[2][class_mode]

        accuracies += [binary["accuracy"] * 100]
        try:
            recall += [binary["recall"] * 100]
            precision += [binary["precision"] * 100]

            unmatched_e += [binary["unmatched"]["enzyme"] / total_set_size * 100]
            unmatched_non_e += [
                binary["unmatched"]["non-enzyme"] / total_set_size * 100
            ]

            unmatched_total += [unmatched_non_e[-1] + unmatched_e[-1]]
        except KeyError:
            pass

    return (
        parameter_values,
        accuracies,
        recall,
        precision,
        unmatched_total,
        unmatched_e,
        unmatched_non_e,
    )

#%%
def plot_metric(metric_list, y_axis_description: str):
    try:
        plt.plot(parameter_values, metric_list, label=y_axis_description)
        plt.xlabel("sensitivityof 'mmseq -s'")
        plt.ylabel("value in %")
    except ValueError as e:
        print(e)

def plot_binary_metrics(title: str):
    plot_metric(accuracies, "accuracy in %")
    plot_metric(recall, "recall in %")
    plot_metric(precision, "precision in %")
    plt.ylim(ymin=0, ymax=100)
    plt.legend()
    plt.title(title)
    plt.show()
    plt.close()

def plot_unmatched(title: str):
    plot_metric(unmatched_e, "unmatched in %")
    plot_metric(unmatched_non_e, "unmatched non enzymes in %")
    plot_metric(unmatched_total, "unmatched total in %")
    plt.ylim(ymin=0, ymax=100)
    plt.legend()
    plt.title(title)
    plt.show()
    plt.close()

#%%
parameter_values, accuracies, recall, precision, unmatched_total, unmatched_e, unmatched_non_e, = extract_data(
    "binary", total_set_size=500.0
)

plot_binary_metrics("Binary Metrics")
plot_unmatched("Binary Unmatched")

# %%
parameter_values, accuracies, recall, precision, unmatched_total, unmatched_e, unmatched_non_e, = extract_data(
    "multiclass", total_set_size=500.0
)

plot_binary_metrics("Multiclass Metrics")
plot_unmatched("Multiclass Unmatched")


from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.http import HttpResponseForbidden
from .forms import ReviewForm
from product.models import Product

# Create your views here.
def add_a_review(request):
    if not request.user.is_authenticated:
        return HttpResponseForbidden()

    product_id = int(request.POST['product'])
    product = get_object_or_404(Product, pk=product_id)

    form = ReviewForm(request.POST)
    if form.is_valid():
        review = form.save(commit=False)
        review.reviewer = request.user
        review.product = product
        review.save()

    return redirect(reverse('product_detail', args=(product_id,)))


import numpy as np
import torch as T
from agent import MARL

PATH = 'Tennis_Linux/Tennis.x86_64'

args = {'obs_space': 24,  # length of state vector
        'action_space': 2,  # number of actions
        'n_agents': 2,  # number of agents
        'n_hidden_actor': (128, 256, 128),  # number of hidden neurons per layer
        'n_hidden_critic': (512, 256),
        'bs': 128,  # number of samples per batch
        'lr_actor': 1e-4,  # learning rate for actor network
        'lr_critic': 1e-3,  # learning rate for critic network
        'device': 'cuda:0',  # device to use for computations
        'gamma': .99,  # discount factor
        'noise_factor': 0.5,  # noise factor for action noise
        'noise_decay': 0.999,  # decay of noise factor applied after every update
        'noise_minimum': 0.03,  # minimum of noise factor
        'buffer_size': 100_000,  # buffer size/length of experience buffer
        'episodes': 10000,  # maximum of episodes to train for
        'buffer_threshold': .10,  # buffer threshold before starting training
        'train_every_n': 1,  # train on one batch every n steps of the env
        'model_update_every_n': 2,  # soft update of target models every n steps
        'train_n_epochs': 2, # train n times/epochs
        'tau': 0.01,  # value for soft updating the target networks tau*local+(1-tau)*target
        'clip_grad': 1.,  # clipping value for gradients
        'exploration_steps': 10_000  # number of random explorations steps before using network predictions
        }

maddpg = MARL(PATH, kwargs=args)

for episode in range(args['episodes']):

    done = False
    states = maddpg.env.reset()
    while not done:
        maddpg.exp_cache.append([T.Tensor(state) for state in states])

        # begin with explorations steps and sample from uniform distribution
        if maddpg.steps < args['exploration_steps']:
            action_one = np.random.uniform(-1, 1, size=(args['action_space']))
            action_two = np.random.uniform(-1, 1, size=(args['action_space']))
            actions = [action_one, action_two]
        else:
            # get actions from MARL
            action_one, action_two = maddpg.step(states)

            # add noise to network actions
            noise_one = np.random.randn(args['action_space']) * max(args['noise_factor'], args['noise_minimum'])
            noise_two = np.random.randn(args['action_space']) * max(args['noise_factor'], args['noise_minimum'])
            actions = [np.clip(action_one + noise_one, -1., 1.), np.clip(action_two + noise_two, -1., 1.)]

        maddpg.exp_cache.append([T.Tensor(action) for action in actions])

        # take step in the environment
        next_states, rewards, done_flags, _ = maddpg.env.step(actions)

        maddpg.stats['rewards'] += (max(rewards))

        maddpg.steps += 1

        # store transitions
        maddpg.exp_cache.append([T.Tensor([reward]) for reward in rewards])
        maddpg.exp_cache.append([T.Tensor([flag]) for flag in done_flags])
        maddpg.exp_cache.append([T.Tensor(next_state) for next_state in next_states])

        maddpg.add_exp()

        if np.any(done_flags):
            done = True

        states = next_states.copy()

        # only train the network every n steps AND when threshold is reached
        if (maddpg.steps % maddpg.train_every_n == 0) and maddpg.buffer.threshold:

            for n in range(maddpg.train_every_n):
                maddpg.learn()

            # update the noise factor with decay
            if maddpg.steps % 3 == 0:
                args['noise_factor'] *= args['noise_decay']

        # do a soft update of the target networks every n steps with value tau
        if maddpg.steps % maddpg.model_update_every_n == 0:
            maddpg.soft_update()

    # append the episode rewards
    maddpg.rewards.append(maddpg.stats['rewards'])

    print(f'episode {episode}:')
    print(f'rewards: {maddpg.stats["rewards"]:.2f}')
    print(f'actor loss: {maddpg.stats["actor_loss"]:.3f}')
    print(f'critic loss: {maddpg.stats["critic_loss"]:.3f}')
    print(f'noise factor: {max(args["noise_factor"], args["noise_minimum"]):.4f}')
    print(f'buffer size: {len(maddpg.buffer)}\n')

    maddpg.reset_stats()
    # # save models every 100 episodes
    if episode % 500 == 0:
        for n in range(maddpg.n_agents):
            T.save(maddpg.agents[n].state_dict(), f'actor_{n}_eps_{episode}_rew_{maddpg.stats["rewards"]:.3f}.h5')
            T.save(maddpg.critics[n].state_dict(), f'critic_{n}_eps_{episode}_rew_{maddpg.stats["rewards"]:.2f}.h5')

    # env is considered solved after mean rewards of +30, save models
    if np.mean(np.array(maddpg.rewards[-100:])) > 0.5:
        print(f'SOLVED ENV AFTER {episode} EPISODES')
        for n in range(maddpg.n_agents):
            T.save(maddpg.agents[n].state_dict(), f'solved_actor_{n}_eps_{episode}_rew_{maddpg.stats["rewards"]:.2f}.h5')
            T.save(maddpg.critics[n].state_dict(), f'solved_critic_{n}_one_eps_{episode}_rew_{maddpg.stats["rewards"]:.2f}.h5')

        break


from mxnet import image
from mxnet.gluon import utils as gutils
from fig_config import *
import os

def _download_pikachu(data_dir):
    root_url = ('https://apache-mxnet.s3-accelerate.amazonaws.com/'
                'gluon/dataset/pikachu/')
    dataset = {'train.rec': 'e6bcb6ffba1ac04ff8a9b1115e650af56ee969c8',
               'train.idx': 'dcf7318b2602c06428b9988470c731621716c393',
               'val.rec': 'd6c33f799b4d058e82f2cb5bd9a976f69d72d520'}

    for k, v in dataset.items():
        gutils.download(root_url + k, os.path.join(data_dir, k), sha1_hash=v)

def load_data_pikachu(batch_size, edge_size=256):  # edge_size：输出图像的宽和高
    data_dir = '../data/pikachu'
    _download_pikachu(data_dir)
    train_iter = image.ImageDetIter(
        path_imgrec=os.path.join(data_dir, 'train.rec'),
        path_imgidx=os.path.join(data_dir, 'train.idx'),  ##提供图像索引文件，以随机读取小批量
        batch_size=batch_size,
        data_shape=(3, edge_size, edge_size),
        shuffle=True,  ##以随机顺序读取训练数据集
        rand_crop=1,  ##进行随机裁剪
        min_object_covered=0.95,  ##裁剪出的图像至少覆盖每个目标95%的区域
        max_attempts=200)  ##最多尝试200次随机裁剪
    val_iter = image.ImageDetIter(  # 不随机裁剪测试数据集中的图像
        path_imgrec=os.path.join(data_dir, 'val.rec'),
        batch_size=batch_size,
        data_shape=(3, edge_size, edge_size),
        shuffle=False)  ##无须按随机顺序读取测试数据集
    return train_iter, val_iter

def bbox_to_rect(bbox, color):
    # 将边界框(左上x, 左上y, 右下x, 右下y)格式转换成matplotlib格式：
    # ((左上x, 左上y), 宽, 高)
    return plt.Rectangle(
        xy=(bbox[0], bbox[1]), width=bbox[2] - bbox[0], height=bbox[3] - bbox[1],
        fill=False, edgecolor=color, linewidth=2)

def show_bboxes(axes, bboxes, labels=None, colors=None):
    def _make_list(obj, default_values=None):  ##使obj为list或者tuple类型
        if obj is None:
            obj = default_values
        elif not isinstance(obj, (list, tuple)):
            obj = [obj]
        return obj

    labels = _make_list(labels)
    colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])
    for i, bbox in enumerate(bboxes):
        color = colors[i % len(colors)]
        rect = bbox_to_rect(bbox.asnumpy(), color)  ##为什么要变换成numpy类型？？
        axes.add_patch(rect)
        if labels and len(labels) > i:  ##输出方框的标签
            text_color = 'k' if color == 'w' else 'w'
            axes.text(rect.xy[0], rect.xy[1], labels[i],
                      va='center', ha='center', fontsize=9, color=text_color,
                      bbox=dict(facecolor=color, lw=0))


import pygame     #sound
import tkinter as tkr #gui
import os # change directry,to give path
import time #for all time relater function
import threading #multiple programming
import speech_recognition as sr #convert speech to text
from mutagen.mp3 import MP3  #handle mp3 file, load ,play,total time

player=tkr.Tk()
player.title("MP3 Player")
player.geometry('480x620+450+40')

os.chdir("./Music")
songlist=os.listdir() #like a ls command

for i in songlist:
    if not i.endswith(".mp3"):
        songlist.remove(i)

curlist = songlist

scrollbar=tkr.Scrollbar(player)
scrollbar.pack(side=tkr.RIGHT,fill=tkr.Y)

playlist=tkr.Listbox(player,width=500,height=300,highlightcolor="blue",selectmode=tkr.SINGLE,yscrollcommand=scrollbar.set) #cointainer
#to select one at the time
pos=0
for song in songlist:
    playlist.insert(pos, song)
    pos=pos+1

try:
    F = open(".fav", "r+") #w+ ka nai: original file wala data udun jato
except FileNotFoundError:
    F = open(".fav", "w+")
finally:
    favlist = [s[:-1] for s in F.readlines()] #/n nai paije

songlength=tkr.Label(player,text="Total Time= _ _ : _ _")
currenttime=tkr.Label(player,text="Current Time= _ _ : _ _")

global paused
paused=False

pygame.init()     #graphics initialization
pygame.mixer.init() #speaker initialize

def showdetails():
    audio=MP3(playlist.get(tkr.ACTIVE)) #je mouse ni select kela
    total_length=audio.info.length
    mins,secs=divmod(total_length,60)
    mins=round(mins)
    secs=round(secs)
    timeformat="{:02d}:{:02d}".format(mins,secs) #round off upto two decimal point
    songlength["text"]="Total Length= "+timeformat
    thread1=threading.Thread(target=start_count,args=(total_length,))
    thread1.start()

def start_count(t):
    t1=0
    while t1!=t and pygame.mixer.music.get_busy():  #check if music stream is playing or not
        if paused:
            continue
        else:
            mins, secs = divmod(t1, 60)
            mins = round(mins)
            secs = round(secs)
            timeformat = "{:02d}:{:02d}".format(mins, secs)
            currenttime["text"] = "Current time= " + timeformat
            time.sleep(1)
            t1 += 1

def play():
    global paused
    if pygame.mixer.music.get_busy():
        stop()
        time.sleep(1)
    paused=False
    pygame.mixer.music.load(playlist.get(tkr.ACTIVE))
    var.set(playlist.get(tkr.ACTIVE))    #song name to put on window
    pygame.mixer.music.set_volume(volumeLevel.get()/100)     #volume 0 to 1 madhe asto
    pygame.mixer.music.play()
    showdetails()

def stop():
    pygame.mixer.music.stop()
    currenttime["text"] = "Current Time= _ _ : _ _"
    songlength["text"]="Total time= _ _ : _ _"

def pause():
    global paused
    paused=True
    pygame.mixer.music.pause()

def resume():
    global paused
    paused=False
    pygame.mixer.music.unpause()

def setvol(val):
    volume=int(val)/100
    pygame.mixer.music.set_volume(volume)

def search_song():
    global playlist, ent_bx, curlist
    findsong = ent_bx.get()      #search madhe taklay te get
    playlist.delete(0, 'end')
    p = 0
    if findsong != "":
        for cursong in curlist:
            if str(findsong).lower() in str(cursong).lower():
                playlist.insert(p, cursong)
                p += 1
    else:
        for cursong in curlist:
            playlist.insert(p, cursong)
            p += 1

def refresh_songs():
    playlist.delete(0, 'end')
    p = 0
    for i in songlist:
        playlist.insert(p, i)
        p += 1

def show_all_songs():
    global curlist, songlist
    songlist = curlist
    refresh_songs()

def show_favorites():
    global songlist, favlist, playlist
    songlist = favlist
    refresh_songs()

def add_to_fav():
    global playlist, F
    songtoadd = playlist.get(tkr.ACTIVE)
    if songtoadd not in favlist:
        F.write("%s\n" %songtoadd)
        favlist.append(songtoadd)
        refresh_songs()

def remove_song():
    global playlist, F
    songtorem = playlist.get(tkr.ACTIVE)
    try:
        favlist.remove(songtorem)
    except:
        return
    F.close()
    F = open(".fav", "w+")          #try catch GUI warun song remove hota , actual file madhun ya code ni hota
    for i in favlist:             #fav list parat lihili , madhlich line kadhu nai shakat mhanun purn fav list parat lihili
        F.write("%s\n" %i)
    refresh_songs()

def listencommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:  #microphone object return karta
        r.adjust_for_ambient_noise(source, duration=3)         #
        r.energy_threshold = 4000
        r.dynamic_energy_threshold = True
        print("Say command:")
        audio = r.listen(source)
    try:
        cmd = r.recognize_google(audio)   #net nasel tr erroe yeil mg except block
        cmd = str(cmd).lower()
    except sr.UnknownValueError:
        voicecommand()
    return cmd

def voicecommand():
    while True:
        time.sleep(3)
        vcmd = listencommand()
        print(vcmd)

        if 'play' in vcmd:
            indexplaylist = 0
            foundsong = False
            vcmd = str(vcmd).partition(' ',)[2]      #play kadhun taka
            playlistsize = playlist.size()
            while indexplaylist != playlistsize:
                playlistsong = playlist.get(indexplaylist)
                if vcmd in str(playlistsong).lower():
                    print("found song", playlist.get(indexplaylist))
                    playlist.activate(indexplaylist)
                    #tkr.ACTIVE = indexplaylist
                    foundsong = True
                    break
                indexplaylist = indexplaylist + 1
            if foundsong == True:
                play()
            else:
                print("Song not found ", indexplaylist)

        elif 'stop' in vcmd:
            stop()
        elif 'pause' in vcmd:
            pause()
        elif 'resume' in vcmd:
            resume()
        else:
            print ("Unrecognized Command")

f = tkr.Frame(player, background = "#EEE", height = 60)
s_label = tkr.Label(f, text = "search")
ent_bx = tkr.Entry(f)
search_button = tkr.Button(f, text = "go!", command = search_song, background = "#55F")  #a=11f=15
s_label.grid(row = 0, column = 0, padx = 10)
ent_bx.grid(row = 0, column = 1, padx = 10, pady = 10)
search_button.grid(row = 0, column = 2, padx = 10)
f.pack()

volumeLevel=tkr.Scale(player,from_=0,to_=100,orient=tkr.HORIZONTAL,resolution=1,command=setvol)
volumeLevel.set(7)
Button1=tkr.Button(player,width=5,height=3,text="PLAY",command=play)
Button2=tkr.Button(player,width=5,height=3,text="STOP",command=stop)
Button3=tkr.Button(player,width=5,height=3,text="PAUSE",command=pause)
Button4=tkr.Button(player,width=5,height=3,text="RESUME",command=resume)

f2 = tkr.Frame(player)
allsongbtn = tkr.Button(f2, text = "All Songs\n", command = show_all_songs, background = "black", foreground = "white")
addfav = tkr.Button(f2, text = "Add to \nFavorites", command = add_to_fav, background = "#F66", foreground = "white")
favbtn = tkr.Button(f2, text = "Favorites\n", command = show_favorites, background = "#E55")
allsongbtn.grid(row = 0, column = 0, padx = 10)
favbtn.grid(row = 0, column = 1, padx = 10)
remfromfav = tkr.Button(f2, text = "Remove from\nFavorites", command = remove_song, background = "black", foreground = "red")
addfav.grid(row = 0, column = 2, padx = 10)
remfromfav.grid(row = 0, column = 3, padx = 10)

var=tkr.StringVar()
songtitle=tkr.Label(player,textvariable=var)

Button1.pack(fill="x")
Button2.pack(fill="x")
Button3.pack(fill="x")
Button4.pack(fill="x")
songtitle.pack(fill="x")
songlength.pack(fill="x")
currenttime.pack(fill="x")
volumeLevel.pack(fill="x",pady = 5)
f2.pack(pady = 3)

playlist.pack() #nusta create kela ki disat nai pack karav lagta
scrollbar.config(command=playlist.yview) #sagla mplayer nai only songs khaliwr

class listener(threading.Thread):        #thread pasun inherit kela class
    def __init__(self):        #method create karaychi asel tr ,init is constructor
        super(listener, self).__init__()
        self.setDaemon(True)

    def run(self):
        voicecommand()

objlistener = listener()
objlistener.start()

player.mainloop()
pygame.mixer.music.stop()
F.close()