"""
NSynth classification using PyTorch

Authors: Japheth Adhavan, Jason St. George
Reference: Sasank Chilamkurthy <https://chsasank.github.io>
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import utils
import models
import data
import visualize
import time
import os
import argparse

import logging
logging.basicConfig(level=logging.INFO)

gpu_idx = utils.get_free_gpu()
device = torch.device("cuda:{}".format(gpu_idx))
logging.info("Using device cuda:{}".format(gpu_idx))

def train_model(model, dataloaders, criterion, optimizer, scheduler, network_type, num_epochs=10):
    """

    :param model:
    :param criterion:
    :param optimizer:
    :param scheduler:
    :param num_epochs:
    :return:
    """
    since = time.time()

    best_model_wts = model.state_dict()
    best_acc = 0.0
    dataset_sizes = {x: len(dataloaders[x].dataset) for x in ["train", "val"]}
    model_loss = {x: [0 for _ in range(num_epochs)] for x in ["train", "val"]}

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch + 1, num_epochs))
        print('-' * 10)

        for phase in ['train', 'val']:
            if phase == 'train':
                scheduler.step()
                model.train()
            else:
                model.eval()

            running_loss = 0.0
            running_corrects = 0

            # iterate over data
            for batch_idx, (samples, labels, targets) in enumerate(dataloaders[phase]):
                inputs = samples.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # aggregate statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

                if phase == 'train' and batch_idx % 50 == 0:
                    logging.info('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                        (epoch + 1),
                        (batch_idx + 1) * len(samples),
                        dataset_sizes[phase],
                        100. * (batch_idx + 1) / len(dataloaders[phase]),
                        loss.item()))

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            model_loss[phase][epoch] = epoch_loss

            logging.info('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase.capitalize(), epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = model.state_dict()
                torch.save(best_model_wts, "./models/{}Network.pt".format(network_type))

        print()

    time_elapsed = time.time() - since
    logging.info('Training completed in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    logging.info('Best overall val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model, model_loss

# def test(model, dataloader):
#     spreads = [[0 for y in range(10)] for x in range(10)]
#     test_c = [0 for x in range(10)]
#     test_t = [0 for x in range(10)]
#     c_done = [False for x in range(10)]
#     i_done = [False for x in range(10)]
#     c_samples, i_samples = 0, 0
#     y_test, y_pred = [], []
#
#     correct = (preds == labels).squeeze()
#     np_predicted = preds.cpu().numpy()  # Get vector of int class output labels
#     y_pred.extend(np_predicted)
#     y_test.extend(if_label.cpu().numpy())
#
#     if i_samples < 10 and c_samples < 10:
#         for i in range(len(outputs)):
#             label = str(labels[i])  # e.g. 'tensor(0)'
#             label = int(label[7])  # 0
#             test_c[label] += correct[i].item()
#             test_t[label] += 1
#
#             if np_predicted[i] != label:
#                 spreads[label][np_predicted[i]] += 1
#                 if i_samples < 10:
#                     i_samples += visualize.save_samples(inputs[i],
#                                                         np_predicted[i], label,
#                                                         i_done, False, CLASS_NAMES)
#             else:
#                 if c_samples < 10:
#                     c_samples += visualize.save_samples(inputs[i], None, label,
#                                                         c_done, True, CLASS_NAMES)

def test(model, test_loader, criterion, classes):
    model.eval()
    test_loss = 0
    correct = 0
    no_of_classes = len(classes)
    spread = [([0] * no_of_classes) for _ in range(no_of_classes)]
    examples = [{} for _ in range(no_of_classes)]
    y_test, y_pred = [], []

    with torch.no_grad():
        for data, labels, target in test_loader:
            data, labels = data.to(device), labels.to(device)
            output = model(data)
            test_loss += criterion(output, labels).item()  # sum up batch loss
            pred = output.max(1, keepdim=True)[1]  # get the index of the max log-probability
            actual = labels.view_as(pred)
            is_correct = pred.equal(actual)
            label_actual = int(labels) if int(labels) < 9 else 9
            label_pred = int(pred) if int(pred) < 9 else 9
            spread[label_actual][label_pred] += 1
            correct += 1 if is_correct else 0
            examples[label_actual][is_correct] = (data, label_pred)
            y_pred.append(label_pred)
            y_test.append(label_actual)

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

    return y_test, y_pred, spread, examples

def main(args):
    np.warnings.filterwarnings('ignore')

    os.makedirs("./graphs", exist_ok=True)
    os.makedirs("./models", exist_ok=True)

    model = {
        "Simple": models.SimpleNetwork,
        "Epic" : models.EpicNetwork,
        "Bonus" : models.BonusNetwork
    }[args.network]().to(device)

    classes = ['bass', 'brass', 'flute', 'guitar', 'keyboard',
                   'mallet', 'organ', 'reed', 'string', 'vocal']

    if args.network == "Bonus":
        classes = ['acoustic', 'electronic', 'synthetic']

    model.double()
    criterion = nn.CrossEntropyLoss()
    optimizer_conv = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
    exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=args.step, gamma=args.gamma)

    if not args.test:
        train_loader = data.get_data_loader("train", batch_size=args.batch_size,
                                            shuffle=True, num_workers=4, network=args.network)
        valid_loader = data.get_data_loader("valid", network=args.network)

        dataloaders = {
            "train": train_loader,
            "val": valid_loader
        }

        logging.info('Training...')
        model, model_loss = train_model(model, dataloaders,
                                        criterion, optimizer_conv,
                                        exp_lr_scheduler,
                                        args.network,
                                        num_epochs=args.epochs)

        visualize.plot_loss(model_loss, "{}Network".format(args.network))
    else:
        logging.info('Testing...')
        model.load_state_dict(torch.load("./models/{}Network.pt".format(args.network)))
        test_loader = data.get_data_loader("test", network=args.network)
        y_test, y_pred, spreads, examples = test(model, test_loader, criterion, classes)

        visualize.plot_histograms(classes, spreads, type=args.network)
        visualize.plot_confusion_matrix(y_test, y_pred, classes, type=args.network)
        visualize.save_samples(examples, classes)

    logging.info('Completed Successfully!')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='NSynth classifier')
    parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test', action='store_true', default=False,
                        help='disables training, loads model')
    parser.add_argument('--network', default='Epic', const='Epic', nargs="?", choices=['Simple', 'Epic', 'Bonus'],
                        help='Choose the type of network from Simple, Epic and Bonus (default: Epic)')
    parser.add_argument('--epochs', type=int, default=10, metavar='N',
                        help='number of epochs to train (default: 10)')
    parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
                        help='learning rate (default: 0.01)')
    parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
                        help='SGD momentum (default: 0.5)')
    parser.add_argument('--step', type=int, default=3, metavar='N',
                        help='number of epochs to decrease learn-rate (default: 3)')
    parser.add_argument('--gamma', type=float, default=0.1, metavar='N',
                        help='factor to decrease learn-rate (default: 0.1)')
    main(parser.parse_args())


# -*- coding: utf-8 -*-
"""
Created on Sat May  5 10:53:26 2018

@author: lenovo
"""

import numpy as np
from scipy.optimize import leastsq

def fun(p,x):
    """定义想要拟合的函数"""
    k,b = p
    return k*x+b
def err(p,x,y):
    """定义误差函数"""
    return fun(p,x)-y

x = [1,2,3,4]
y = [6,5,7,10]

p0 = [1,1]
x1 = np.array(x)
y1 = np.array(y)
xishu = leastsq(err,p0,args=(x1,y1))
print(xishu[0])


#! /usr/bin/env python
from sensor_msgs.msg import CompressedImage
from cv_bridge import CvBridge, CvBridgeError
import cv2
import rospy
import subprocess
#from PIL import Image # PIL

from __init__ import *
from rgiro_spco2_slam.srv import spco_data_image,spco_data_imageResponse
import spco2_placescnn as places365

class ImageFeatureServer():

    def image_server(self, req):

        if len(self.frame) == 0:
             return spco_data_imageResponse(False)
        #cv2.imshow("image", self.frame)

        # forward pass
        convert_img = places365.Image.fromarray(self.frame)#convert into PIL
        input_img = places365.V(self.tf(convert_img).unsqueeze(0))
        logit = self.model.forward(input_img)
        h_x = places365.F.softmax(logit, 1).data.squeeze()

        # save image feature
        fp = open(self.DATA_FOLDER + '/img/ft' + str(req.count) + '.csv','a')
        h_x_numpy = h_x.to('cpu').detach().numpy().copy()
        fp.write(','.join(map(str, h_x_numpy)))
        fp.write('\n')
        fp.close()
        rospy.loginfo("[Service] save new feature")

        # save image
        if self.image_save:
            if req.mode == "new":
                p = subprocess.Popen("mkdir " + self.DATA_FOLDER + "/image/", shell=True)
                rospy.sleep(0.5)
            image_name = self.DATA_FOLDER + "/image/" + str(req.count) + ".jpg"

            cv2.imwrite(image_name, self.frame)
            rospy.loginfo("[Service spco_data/image] save new image as %s", image_name)

        # save and publish activation image
        #print "h_x",h_x
        probs, idx = h_x.sort(0, True)
        probs = probs.numpy()
        idx = idx.numpy()
        # generate class activation mapping
        #print('Class activation map is saved as cam.jpg')
        #CAMs = places365.returnCAM(features_blobs[0], weight_softmax, [idx[0]])

        # render the CAM and output
        #img = cv2.imread('test.jpg')
        '''
        height, width, _ = self.frame.shape#  img.shape
        heatmap = cv2.applyColorMap(cv2.resize(CAMs[0],(width, height)), cv2.COLORMAP_JET)
        result = heatmap * 0.4 + img * 0.5
        image_name = self.DATA_FOLDER + "/image/" + str(req.count) + "_activation.jpg"
        cv2.imwrite(image_name, result)
        '''
        return spco_data_imageResponse(True)

    def image_callback(self, image):

        try:
            self.frame = CvBridge().compressed_imgmsg_to_cv2(image)
        except CvBrideError as e:
            print (e)

    def load_network_model(self):
        # load the labels
        self.classes, self.labels_IO, self.labels_attribute, self.W_attribute = places365.load_labels()

        # load the model
        self.model = places365.load_model()

        # load the transformer
        self.tf = places365.returnTF() # image transformer

        # get the softmax weight
        self.params = list(self.model.parameters())
        self.weight_softmax = self.params[-2].data.numpy()
        self.weight_softmax[self.weight_softmax<0] = 0

        return (True)

    def __init__(self):

        TRIALNAME = "test"#rospy.get_param('~trial_name')#test
        IMAGE_TOPIC = '/hsrb/head_rgbd_sensor/rgb/image_rect_color/compressed' #"/hsrb/head_rgbd_sensor/rgb/image_raw"#rospy.get_param('~image_topic')#/camera/rgb/image_raw
        self.image_save = True #rospy.get_param('~image_save')#true

        # subscrib image
        rospy.Subscriber(IMAGE_TOPIC, CompressedImage, self.image_callback, queue_size=1)
        if self.load_network_model()==False:
            print ("error")

        self.DATA_FOLDER = datafolder + TRIALNAME
        self.frame = []

        s = rospy.Service('rgiro_spco2_slam/image', spco_data_image, self.image_server)
        rospy.loginfo("[Service spco_data/image] Ready")

if __name__ == "__main__":
    rospy.init_node('spco2_image_features',anonymous=False)
    srv = ImageFeatureServer()
    rospy.spin()


"""
Tests for voting 31/01/2023.
"""

from scripts.vote_2023_01_31 import start_vote

from brownie import chain, accounts
from brownie.network.transaction import TransactionReceipt

from eth_abi.abi import encode_single

from utils.config import network_name
from utils.test.tx_tracing_helpers import *
from utils.test.event_validators.easy_track import (
    validate_evmscript_factory_added_event,
    EVMScriptFactoryAdded,
    validate_evmscript_factory_removed_event,
)
from utils.easy_track import create_permissions
from utils.agent import agent_forward
from utils.voting import create_vote, bake_vote_items

eth = "0x0000000000000000000000000000000000000000"

def test_vote(
    helpers,
    accounts,
    vote_id_from_env,
    bypass_events_decoding,
    unknown_person,
    interface,
    ldo_holder,
):

    dai_token = interface.ERC20("0x6B175474E89094C44Da98b954EedeAC495271d0F")

    allowed_recipients = [
        accounts.at("0xaf8aE6955d07776aB690e565Ba6Fbc79B8dE3a5d", {"force": True}),
        accounts.at("0x558247e365be655f9144e1a0140D793984372Ef3", {"force": True}),
        accounts.at("0x53773E034d9784153471813dacAFF53dBBB78E8c", {"force": True}),
        accounts.at("0xC976903918A0AF01366B31d97234C524130fc8B1", {"force": True}),
        accounts.at("0x9e2b6378ee8ad2A4A95Fe481d63CAba8FB0EBBF9", {"force": True}),
        accounts.at("0x82AF9d2Ea81810582657f6DC04B1d7d0D573F616", {"force": True}),
        accounts.at("0x586b9b2F8010b284A0197f392156f1A7Eb5e86e9", {"force": True}),
        accounts.at("0x883f91D6F3090EA26E96211423905F160A9CA01d", {"force": True}),
        accounts.at("0x351806B55e93A8Bcb47Be3ACAF71584deDEaB324", {"force": True}),
        accounts.at("0xf6502Ea7E9B341702609730583F2BcAB3c1dC041", {"force": True}),
        accounts.at("0xDB2364dD1b1A733A690Bf6fA44d7Dd48ad6707Cd", {"force": True}),
        accounts.at("0xF930EBBd05eF8b25B1797b9b2109DDC9B0d43063", {"force": True}),
        accounts.at("0x6DC9657C2D90D57cADfFB64239242d06e6103E43", {"force": True}),
        accounts.at("0x13C6eF8d45aFBCcF15ec0701567cC9fAD2b63CE8", {"force": True}),
    ]

    finance = interface.Finance("0xB9E5CBB9CA5b0d659238807E84D0176930753d86")
    dao_voting = interface.Voting("0x2e59A20f205bB85a89C53f1936454680651E618e")
    easy_track = interface.EasyTrack("0xF0211b7660680B49De1A7E9f25C65660F0a13Fea")

    referral_dai_registry = interface.AllowedRecipientRegistry("0xa295C212B44a48D07746d70d32Aa6Ca9b09Fb846")
    referral_dai_topup_factory = interface.TopUpAllowedRecipients("0x009ffa22ce4388d2F5De128Ca8E6fD229A312450")
    referral_dai_add_recipient_factory = interface.AddAllowedRecipient("0x8F06a7f244F6Bb4B68Cd6dB05213042bFc0d7151")
    referral_dai_remove_recipient_factory = interface.RemoveAllowedRecipient("0xd8f9B72Cd97388f23814ECF429cd18815F6352c1")
    referral_program_multisig = accounts.at("0xe2A682A9722354D825d1BbDF372cC86B2ea82c8C", {"force": True})

    rewards_topup_factory_old = interface.IEVMScriptFactory("0x77781A93C4824d2299a38AC8bBB11eb3cd6Bc3B7")
    rewards_add_factory_old = interface.IEVMScriptFactory("0x9D15032b91d01d5c1D940eb919461426AB0dD4e3")
    rewards_remove_factory_old = interface.IEVMScriptFactory("0xc21e5e72Ffc223f02fC410aAedE3084a63963932")

    old_factories_list = easy_track.getEVMScriptFactories()

    assert len(old_factories_list) == 15

    assert referral_dai_topup_factory not in old_factories_list
    assert referral_dai_add_recipient_factory not in old_factories_list
    assert referral_dai_remove_recipient_factory not in old_factories_list

    assert rewards_topup_factory_old in old_factories_list
    assert rewards_add_factory_old in old_factories_list
    assert rewards_remove_factory_old in old_factories_list

    ##
    ## START VOTE
    ##

    vote_id = vote_id_from_env or start_vote({"from": ldo_holder}, silent=True)[0]

    tx: TransactionReceipt = helpers.execute_vote(
        vote_id=vote_id, accounts=accounts, dao_voting=dao_voting, skip_time=3 * 60 * 60 * 24
    )

    updated_factories_list = easy_track.getEVMScriptFactories()
    assert len(updated_factories_list) == 15

    # 1. Add Referral program DAI top up EVM script factory 0x009ffa22ce4388d2F5De128Ca8E6fD229A312450 to Easy Track
    assert referral_dai_topup_factory in updated_factories_list
    create_and_enact_payment_motion(
        easy_track,
        referral_program_multisig,
        referral_dai_topup_factory,
        dai_token,
        allowed_recipients,
        [10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18, 10 * 10**18,10 * 10**18, 10 * 10**18],
        unknown_person,
    )
    check_add_and_remove_recipient_with_voting(referral_dai_registry, helpers, ldo_holder, dao_voting)

    # 2. Add Referral program DAI add recipient EVM script factory 0x8F06a7f244F6Bb4B68Cd6dB05213042bFc0d7151 to Easy Track
    assert referral_dai_add_recipient_factory in updated_factories_list
    create_and_enact_add_recipient_motion(
        easy_track,
        referral_program_multisig,
        referral_dai_registry,
        referral_dai_add_recipient_factory,
        unknown_person,
        "",
        ldo_holder,
    )

    # 3. Add Referral program DAI remove recipient EVM script factory 0xd8f9B72Cd97388f23814ECF429cd18815F6352c1 to Easy Track
    assert referral_dai_remove_recipient_factory in updated_factories_list
    create_and_enact_remove_recipient_motion(
        easy_track,
        referral_program_multisig,
        referral_dai_registry,
        referral_dai_remove_recipient_factory,
        unknown_person,
        ldo_holder,
    )

    # 4. Remove reWARDS top up EVM script factory (old ver) 0x77781A93C4824d2299a38AC8bBB11eb3cd6Bc3B7 from Easy Track
    assert rewards_topup_factory_old not in updated_factories_list

    # 5. Remove reWARDS add recipient EVM script factory (old ver) 0x9D15032b91d01d5c1D940eb919461426AB0dD4e3 from Easy Track
    assert rewards_add_factory_old not in updated_factories_list

    # 6. Remove reWARDS remove recipient EVM script factory (old ver) 0xc21e5e72Ffc223f02fC410aAedE3084a63963932 from Easy Track
    assert rewards_remove_factory_old not in updated_factories_list

    # validate vote events
    assert count_vote_items_by_events(tx, dao_voting) == 6, "Incorrect voting items count"

    display_voting_events(tx)

    if bypass_events_decoding or network_name() in ("goerli", "goerli-fork"):
        return

    evs = group_voting_events(tx)

    validate_evmscript_factory_added_event(
        evs[0],
        EVMScriptFactoryAdded(
            factory_addr=referral_dai_topup_factory,
            permissions=create_permissions(finance, "newImmediatePayment")
            + create_permissions(referral_dai_registry, "updateSpentAmount")[2:],
        ),
    )
    validate_evmscript_factory_added_event(
        evs[1],
        EVMScriptFactoryAdded(
            factory_addr=referral_dai_add_recipient_factory,
            permissions=create_permissions(referral_dai_registry, "addRecipient"),
        ),
    )
    validate_evmscript_factory_added_event(
        evs[2],
        EVMScriptFactoryAdded(
            factory_addr=referral_dai_remove_recipient_factory,
            permissions=create_permissions(referral_dai_registry, "removeRecipient"),
        ),
    )
    validate_evmscript_factory_removed_event(evs[3], rewards_topup_factory_old)
    validate_evmscript_factory_removed_event(evs[4], rewards_add_factory_old)
    validate_evmscript_factory_removed_event(evs[5], rewards_remove_factory_old)

def _encode_calldata(signature, values):
    return "0x" + encode_single(signature, values).hex()

def create_and_enact_payment_motion(
    easy_track,
    trusted_caller,
    factory,
    token,
    recievers,
    transfer_amounts,
    stranger,
):
    agent = accounts.at("0x3e40D73EB977Dc6a537aF587D48316feE66E9C8c", {"force": True})
    agent_balance_before = balance_of(agent, token)
    recievers_balance_before = [balance_of(reciever, token) for reciever in recievers]
    motions_before = easy_track.getMotions()

    recievers_addresses = [reciever.address for reciever in recievers]

    calldata = _encode_calldata("(address[],uint256[])", [recievers_addresses, transfer_amounts])

    tx = easy_track.createMotion(factory, calldata, {"from": trusted_caller})

    motions = easy_track.getMotions()
    assert len(motions) == len(motions_before) + 1

    chain.sleep(60 * 60 * 24 * 3)
    chain.mine()

    easy_track.enactMotion(
        motions[-1][0],
        tx.events["MotionCreated"]["_evmScriptCallData"],
        {"from": stranger},
    )

    recievers_balance_after = [balance_of(reciever, token)for reciever in recievers]
    for i in range(len(recievers)):
        assert recievers_balance_after[i] == recievers_balance_before[i] + transfer_amounts[i]

    agent_balance_after = balance_of(agent, token)

    assert agent_balance_after == agent_balance_before - sum(transfer_amounts)

def balance_of(address, token):
    if token == eth:
        return address.balance()
    else:
        return token.balanceOf(address)

def create_and_enact_add_recipient_motion(
    easy_track,
    trusted_caller,
    registry,
    factory,
    recipient,
    title,
    stranger,
):
    recipients_count = len(registry.getAllowedRecipients())
    assert not registry.isRecipientAllowed(recipient)
    motions_before = easy_track.getMotions()

    calldata = _encode_calldata("(address,string)", [recipient.address, title])

    tx = easy_track.createMotion(factory, calldata, {"from": trusted_caller})

    motions = easy_track.getMotions()
    assert len(motions) == len(motions_before) + 1

    chain.sleep(60 * 60 * 24 * 3)
    chain.mine()

    easy_track.enactMotion(
        motions[-1][0],
        tx.events["MotionCreated"]["_evmScriptCallData"],
        {"from": stranger},
    )

    assert len(registry.getAllowedRecipients()) == recipients_count + 1
    assert registry.isRecipientAllowed(recipient)

def create_and_enact_remove_recipient_motion(
    easy_track,
    trusted_caller,
    registry,
    factory,
    recipient,
    stranger,
):
    recipients_count = len(registry.getAllowedRecipients())
    assert registry.isRecipientAllowed(recipient)
    motions_before = easy_track.getMotions()

    calldata = _encode_calldata("(address)", [recipient.address])

    tx = easy_track.createMotion(factory, calldata, {"from": trusted_caller})

    motions = easy_track.getMotions()
    assert len(motions) == len(motions_before) + 1

    chain.sleep(60 * 60 * 24 * 3)
    chain.mine()

    easy_track.enactMotion(
        motions[-1][0],
        tx.events["MotionCreated"]["_evmScriptCallData"],
        {"from": stranger},
    )

    assert len(registry.getAllowedRecipients()) == recipients_count - 1
    assert not registry.isRecipientAllowed(recipient)

def check_add_and_remove_recipient_with_voting(registry, helpers, ldo_holder, dao_voting):
    recipient_candidate = accounts[0]
    title = ""
    recipients_length_before = len(registry.getAllowedRecipients())

    assert not registry.isRecipientAllowed(recipient_candidate)

    call_script_items = [
        agent_forward(
            [
                (
                    registry.address,
                    registry.addRecipient.encode_input(recipient_candidate, title),
                )
            ]
        )
    ]
    vote_desc_items = ["Add recipient"]
    vote_items = bake_vote_items(vote_desc_items, call_script_items)

    vote_id = create_vote(vote_items, {"from": ldo_holder})[0]

    helpers.execute_vote(
        vote_id=vote_id,
        accounts=accounts,
        dao_voting=dao_voting,
        skip_time=3 * 60 * 60 * 24,
    )

    assert registry.isRecipientAllowed(recipient_candidate)
    assert len(registry.getAllowedRecipients()) == recipients_length_before + 1, 'Wrong whitelist length'

    call_script_items = [
        agent_forward(
            [
                (
                    registry.address,
                    registry.removeRecipient.encode_input(recipient_candidate),
                )
            ]
        )
    ]
    vote_desc_items = ["Remove recipient"]
    vote_items = bake_vote_items(vote_desc_items, call_script_items)

    vote_id = create_vote(vote_items, {"from": ldo_holder})[0]

    helpers.execute_vote(
        vote_id=vote_id,
        accounts=accounts,
        dao_voting=dao_voting,
        skip_time=3 * 60 * 60 * 24,
    )

    assert not registry.isRecipientAllowed(recipient_candidate)
    assert len(registry.getAllowedRecipients()) == recipients_length_before, 'Wrong whitelist length'


import pygame

pygame.init()

__screen_info = pygame.display.Info()
__height = __screen_info.current_h

# Screen constants
SCREEN_SIZE = (__height / 7 * 6, __height - 64)
ICON_SIZE = (64, 64)
LEFT_BOUND = 0
RIGHT_BOUND = SCREEN_SIZE[0] - ICON_SIZE[0]
TOP_BOUND = 0
BOTTOM_BOUND = SCREEN_SIZE[1]
ALIEN_INVASION_BOUND = SCREEN_SIZE[1] / 6 * 5 - ICON_SIZE[1]

# Player constants
INITIAL_PLAYER_COORDINATES = (SCREEN_SIZE[0] / 2 - ICON_SIZE[0] / 2,
                              SCREEN_SIZE[1] / 6 * 5)
PLAYER_BODY_LEFT_PAD = 6
PLAYER_BODY_TOP_PAD = 17
PLAYER_WIDTH = 52
PLAYER_HEIGHT = 31
# Num pixels the player moves left or right with each key pressed
PLAYER_SPEED = SCREEN_SIZE[0] * 9 / 800

# PlayerBullet constants
PLAYER_BULLET_SPEED = SCREEN_SIZE[1] / 100 * 3
PLAYER_BULLET_BODY_LEFT_PAD = 30
PLAYER_BULLET_BODY_TOP_PAD = 0
PLAYER_BULLET_WIDTH = 4
PLAYER_BULLET_HEIGHT = 17

# Alien constants
INITIAL_ALIEN_COORDINATES = (ICON_SIZE[0], SCREEN_SIZE[1] / 10 + ICON_SIZE[1])
ALIEN_BODY_LEFT_PAD = 2
ALIEN_BODY_TOP_PAD = 7
ALIEN_WIDTH = 60
ALIEN_HEIGHT = 48
NUM_ALIENS_PER_ROW = 8
BASE_NUM_ALIEN_ROWS = 3
MAX_NUM_ALIEN_ROWS = 5
ALIEN_HORIZONTAL_GAP = (
    SCREEN_SIZE[0] - 2 * INITIAL_ALIEN_COORDINATES[0] - ICON_SIZE[0]) / (NUM_ALIENS_PER_ROW - 1)
ALIEN_VERTICAL_GAP = SCREEN_SIZE[1] / 15
BASE_ALIEN_MOVES_PER_SECOND = 0.4
# Num pixels alien traverses each time it moves
ALIEN_SPEED = SCREEN_SIZE[0] / 80

# Alien bullet constants
BASE_ALIEN_BULLET_SPEED = SCREEN_SIZE[1] / 100
BASE_ALIEN_CHANCE_TO_FIRE = 1 / 1_000
ALIEN_BULLET_BODY_LEFT_PAD = 26
ALIEN_BULLET_BODY_TOP_PAD = 36
ALIEN_BULLET_WIDTH = 12
ALIEN_BULLET_HEIGHT = 28

# UFO constants
INITIAL_UFO_COORDINATES = (0, 0)
BASE_UFO_SPEED = SCREEN_SIZE[0] / 160
UFO_WIDTH = 80
UFO_HEIGHT = 24
UFO_CHANCE_TO_APPEAR = 1 / 400
UFO_LEFT_PAD = 0
UFO_TOP_PAD = 16
UFO_WIDTH = 64
UFO_HEIGHT = 32

# Scales for the constants as the level progresses
ALIEN_LEVEL_BEATEN_MOVES_PER_SECOND_SCALE = 1.15
ALIEN_DROP_ROW_MOVES_PER_SECOND_SCALE = 1.25
ALIEN_CHANCE_TO_FIRE_SCALE = 1.065
UFO_SPEED_SCALE = 1.05

# Hud constants
FONT_SIZE = int(ICON_SIZE[0] / 1.7)
SCORE_TEXT_COORDINATES = (SCREEN_SIZE[0] / 5 - FONT_SIZE * 5 / 2,
                          SCREEN_SIZE[1] / 100)
SCORE_VALUE_COORDINATES = (
    SCORE_TEXT_COORDINATES[0], FONT_SIZE + SCREEN_SIZE[1] / 50)
LEVEL_TEXT_COORDINATES = (SCREEN_SIZE[0] / 2 - FONT_SIZE * 5 / 2,
                          SCREEN_SIZE[1] / 100)
LEVEL_VALUE_COORDINATES = (
    LEVEL_TEXT_COORDINATES[0], FONT_SIZE + SCREEN_SIZE[1] / 50)
NUM_LIVES_TEXT_COORDINATES = (SCREEN_SIZE[0] / 5 * 4 - FONT_SIZE * 5 / 2,
                              SCREEN_SIZE[1] / 100)
NUM_LIVES_VALUE_COORDINATES = (
    NUM_LIVES_TEXT_COORDINATES[0], FONT_SIZE + SCREEN_SIZE[1] / 50)
NUM_POINTS_FOR_ALIEN_KILL = 10

# Game over screen constants
GAME_OVER_TEXT_COORDINATES = (SCREEN_SIZE[0] / 2 - FONT_SIZE * (9 / 2),
                              SCREEN_SIZE[1] / 2 - FONT_SIZE / 2 - FONT_SIZE * 3)
GAME_OVER_SCORE_TEXT_Y_COORDINATE = GAME_OVER_TEXT_COORDINATES[1] + FONT_SIZE * 2
HIGH_SCORE_TEXT_Y_COORDINATE = GAME_OVER_SCORE_TEXT_Y_COORDINATE + FONT_SIZE * 2
RESTART_TEXT_COORDINATES = (SCREEN_SIZE[0] / 2 - FONT_SIZE * (12 / 2),
                            HIGH_SCORE_TEXT_Y_COORDINATE + FONT_SIZE * 2)

# Other
NUM_LEVELS_TILL_NEW_ALIEN_ROW = 3
BASE_POINTS_PER_KILL = 10
BASE_POINTS_PER_UFO_KILL = 100
FPS = 30  # Used to maintain smooth movement


"""The URL configuration of the application
When the particular URL is hit it feeds the request to the corresponding view.
"""
from django.urls import path
from django.views.generic import RedirectView

from .views import base, add_to_registry, validate_url, issue_registry, dashboard

urlpatterns = [
    path('base/', base),
    path('add/', add_to_registry),
    path('api/validate_url', validate_url),
    path('issue_registry/', issue_registry),
    path('dashboard/', dashboard, name='dashboard'),
    path('', RedirectView.as_view(pattern_name='dashboard', permanent=False)),
]


import csv

from django.db.models import Q
from django.http import HttpResponse

from data.models import (
    List,
    Pairing,
    AOS,
    BCP,
)

def raw_list(request, list_id):
    list = List.objects.get(id=list_id)
    return HttpResponse(list.raw_list.replace("\n", "<br>"))

def export_pairings_as_csv(request, game_type: int = AOS):
    pairings = Pairing.objects.filter(
        Q(event__start_date__range=["2023-07-01", "2023-12-31"])
        & Q(event__rounds__in=[3, 5, 8])
        & Q(event__game_type=game_type)
        & Q(event__source=BCP)
    ).order_by("event__name", "-event__start_date", "round", "id")

    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="pairings.csv"'

    writer = csv.writer(
        response,
        quoting=csv.QUOTE_NONNUMERIC,
    )
    writer.writerow(
        [
            "pairing_id",
            "round",
            "player1_name",
            "player2_name",
            "player1_result",
            "player2_result",
            "player1_score",
            "player2_score",
            "event_name",
            "event_date",
            "event_end_date",
            "event_country",
            "event_online",
            "season",
            "player1_faction",
            "player1_subfaction",
            "player2_faction",
            "player2_subfaction",
            "player1_list_url",
            "player2_list_url",
            "source",
        ]
    )

    for pairing in pairings:
        if pairing.event.source == BCP:
            player1_name = (
                f"{pairing.player1.player.source_json['firstName']} {pairing.player1.player.source_json['lastName']}"
                if pairing.player1
                else ""
            )
            player2_name = (
                f"{pairing.player2.player.source_json['firstName']} {pairing.player2.player.source_json['lastName']}"
                if pairing.player2
                else ""
            )
        else:
            player1_name = (
                pairing.player1.player.source_json["playerName"]
                if pairing.player1
                else ""
            )
            player2_name = (
                pairing.player2.player.source_json["playerName"]
                if pairing.player2
                else ""
            )
        event_country = (
            pairing.event.source_json["country"] if pairing.event.source_json else ""
        )
        if "isOnlineEvent" in pairing.event.source_json:
            event_online = pairing.event.source_json["isOnlineEvent"]
        else:
            event_online = False
        player1_list_faction = (
            pairing.player1_list.faction if pairing.player1_list else ""
        )
        player1_list_subfaction = (
            pairing.player1_list.subfaction if pairing.player1_list else ""
        )
        player2_list_faction = (
            pairing.player2_list.faction if pairing.player2_list else ""
        )
        player2_list_subfaction = (
            pairing.player2_list.subfaction if pairing.player2_list else ""
        )

        if pairing.player1_list and len(pairing.player1_list.raw_list) > 10000:
            pairing.player1_list.raw_list = "List too long"
        if pairing.player2_list and len(pairing.player2_list.raw_list) > 10000:
            pairing.player2_list.raw_list = "List too long"

        writer.writerow(
            [
                pairing.id,
                pairing.round,
                player1_name,
                player2_name,
                pairing.player1_result,
                pairing.player2_result,
                pairing.player1_score,
                pairing.player2_score,
                pairing.event.name,
                pairing.event.start_date,
                pairing.event.end_date,
                event_country,
                event_online,
                "2023",
                player1_list_faction,
                player1_list_subfaction,
                player2_list_faction,
                player2_list_subfaction,
                pairing.player1_list.raw_list if pairing.player1_list else "",
                pairing.player2_list.raw_list if pairing.player2_list else "",
                "bcp" if pairing.event.source == BCP else "snl",
            ]
        )

    return response


from aiogram.types import (
    ReplyKeyboardMarkup,
    InlineKeyboardMarkup,
    InlineKeyboardButton,
)

main_buttons = {
    "ask": "Спросить 🤖",
}

class Keyboard:
    def __init__(self):
        self.main = self.make_main_buttons()

    def make_main_buttons(self):
        _keyboard_main = ReplyKeyboardMarkup(resize_keyboard=True)
        for button_label in main_buttons.values():
            _keyboard_main.add(button_label)
        return _keyboard_main

    @property
    def translate(self):
        inline_keyboard = InlineKeyboardMarkup(row_width=2)
        true_button = InlineKeyboardButton(text="Да", callback_data=f"translate_1")
        false_button = InlineKeyboardButton(text="Нет", callback_data=f"translate_0")
        inline_keyboard.row(true_button, false_button)
        return inline_keyboard

kb = Keyboard()


import logging
from datetime import datetime
from typing import Generic, Text, Type, TypeVar
from uuid import UUID, uuid4

from injector import (
    Injector,
    UnknownProvider,
    UnsatisfiedRequirement,
    inject,
    singleton,
)
from pydantic import BaseModel, Field

log = logging.getLogger(__name__)

class Command(BaseModel):
    id: UUID = Field(default_factory=uuid4)
    timestamp: datetime = Field(default_factory=datetime.utcnow)

    class Config:
        allow_mutation = False

    def __str__(self) -> Text:
        std_str = super().__str__()
        return f"<Command:{self.__class__.__name__} {std_str}>"

class Event(BaseModel):
    command_id: UUID
    id: UUID = Field(default_factory=uuid4)
    timestamp: datetime = Field(default_factory=datetime.utcnow)

    class Config:
        allow_mutation = False

    def __str__(self) -> Text:
        std_str = super().__str__()
        return f"<Event:{self.__class__.__name__} {std_str}>"

TCommand = TypeVar("TCommand")

class Handler(Generic[TCommand]):
    def __call__(self, command: TCommand) -> None:
        raise NotImplementedError

@inject
@singleton
class CommandBus:
    def __init__(self, container: Injector) -> None:
        self._get = container.get

    def handle(self, command: Command) -> None:
        log.debug(command)
        command_cls: Type[Command] = type(command)
        handler = self._get(Handler[command_cls])
        handler(command)

TEvent = TypeVar("TEvent")

class Listener(Generic[TEvent]):
    def __call__(self, event: TEvent) -> None:
        raise NotImplementedError

@inject
@singleton
class EventBus:
    def __init__(self, container: Injector) -> None:
        self._get = container.get

    def emit(self, event: TEvent) -> None:
        log.debug(event)
        event_cls: Type[TEvent] = type(event)
        try:
            listeners = self._get(list[Listener[event_cls]])
        except (UnsatisfiedRequirement, UnknownProvider):
            listeners = []

        for listener in listeners:
            listener(event)

__all__ = ["Command", "CommandBus", "Event", "EventBus", "Handler", "Listener"]


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# PYTHON_ARGCOMPLETE_OK
# Pass --help flag for help on command-line interface

import sympy as sp
import numpy as np

from pyneqsys.symbolic import SymbolicSys

def solve(guess_a, guess_b, power, solver='scipy'):
    """ Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. """
    # The problem is 2 dimensional so we need 2 symbols
    x = sp.symbols('x:2', real=True)
    # There is a user specified parameter ``p`` in this problem:
    p = sp.Symbol('p', real=True, negative=False, integer=True)
    # Our system consists of 2-non-linear equations:
    f = [x[0] + (x[0] - x[1])**p/2 - 1,
         (x[1] - x[0])**p/2 + x[1]]
    # We construct our ``SymbolicSys`` instance by passing variables, equations and parameters:
    neqsys = SymbolicSys(x, f, [p])  # (this will derive the Jacobian symbolically)

    # Finally we solve the system using user-specified ``solver`` choice:
    return neqsys.solve([guess_a, guess_b], [power], solver=solver)

def main(guess_a=1., guess_b=0., power=3, savetxt='None', verbose=False):
    """
    Example demonstrating how to solve a system of non-linear equations defined as SymPy expressions.

    The example shows how a non-linear problem can be given a command-line interface which may be
    preferred by end-users who are not familiar with Python.
    """
    x, sol = solve(guess_a, guess_b, power)  # see function definition above
    assert sol.success
    if savetxt != 'None':
        np.savetxt(x, savetxt)
    else:
        if verbose:
            print(sol)
        else:
            print(x)

if __name__ == '__main__':  # are we running from the command line (or are we being imported from)?
    try:
        import argh
        argh.dispatch_command(main, output_file=None)
    except ImportError:
        import sys
        if len(sys.argv) > 1:
            import warnings
            warnings.warn("Ignoring parameters run "
                          "'pip install --user argh' to fix.")
        main()


import os
#os.environ['GLOG_minloglevel'] = '2'
from tqdm import trange
import caffe
import argparse
import pandas as pd

def main(solver_proto, out_dir):
    caffe.set_mode_gpu()
    solver = caffe.SGDSolver(solver_proto)
    train_loss, test_loss = [], []
    test_loss.append(solver.test_nets[0].blobs['loss'].data.copy())
    for ix in trange(solver.param.max_iter, desc='overall progress'): #):
        for jx in trange(solver.param.test_interval, desc='until next test'):
            solver.step(1)
            train_loss.append(solver.net.blobs['loss'].data.ravel()[0])
        test_loss.append(solver.test_nets[0].blobs['loss'].data.ravel()[0])
        if ix % 1 == 0:
            solver.snapshot()
            pd.DataFrame(train_loss, columns=['train_loss']).to_csv(os.path.join(out_dir, 'train_loss.csv'))
            pd.DataFrame(test_loss, columns=['test_loss']).to_csv(os.path.join(out_dir, 'test_loss.csv'))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--solver', required=True, type=str)
    parser.add_argument('--out_dir', default='.')
    args = parser.parse_args()

    main(args.solver, args.out_dir)


"""
WRITE ME

Tests for the R operator / L operator

For the list of op with r op defined, with or without missing test
see this file: doc/library/tensor/basic.txt

For function to automatically test your Rop implementation, look at
the docstring of the functions: check_mat_rop_lop, check_rop_lop,
check_nondiff_rop,
"""
from __future__ import absolute_import, print_function, division
import unittest
from theano.tests import unittest_tools as utt
from theano import function
import theano
from theano import tensor
import itertools
import numpy as np
from theano.gof import Op, Apply
from theano.gradient import grad_undefined
from theano.tests.unittest_tools import SkipTest
from theano.tensor.signal.pool import Pool
from theano.tensor.nnet import conv, conv2d

'''
Special Op created to test what happens when you have one op that is not
differentiable in the computational graph
'''

class BreakRop(Op):
    """
    @note: Non-differentiable.
    """
    __props__ = ()

    def make_node(self, x):
        return Apply(self, [x], [x.type()])

    def perform(self, node, inp, out_):
        x, = inp
        out, = out_
        out[0] = x

    def grad(self, inp, grads):
        return [grad_undefined(self, 0, inp[0])]

    def R_op(self, inputs, eval_points):
        return [None]

break_op = BreakRop()

class RopLop_checker(unittest.TestCase):
    """
    Don't peform any test, but provide the function to test the
    Rop to class that inherit from it.
    """
    def setUp(self):
        utt.seed_rng()
        # Using vectors make things a lot simpler for generating the same
        # computations using scan
        self.x = tensor.vector('x')
        self.v = tensor.vector('v')
        self.rng = np.random.RandomState(utt.fetch_seed())
        self.in_shape = (5 + self.rng.randint(3),)
        self.mx = tensor.matrix('mx')
        self.mv = tensor.matrix('mv')
        self.mat_in_shape = (5 + self.rng.randint(3),
                             5 + self.rng.randint(3))

    def check_nondiff_rop(self, y):
        """
        If your op is not differentiable(so you can't define Rop)
        test that an error is raised.
        """
        raised = False
        try:
            tensor.Rop(y, self.x, self.v)
        except ValueError:
            raised = True
        if not raised:
            self.fail((
                'Op did not raise an error even though the function'
                ' is not differentiable'))

    def check_mat_rop_lop(self, y, out_shape):
        """
        Test the Rop/Lop when input is a matrix and the output is a vector

        :param y: the output variable of the op applied to self.mx
        :param out_shape: Used to generate a random tensor
                          corresponding to the evaluation point of the Rop
                          (i.e. the tensor with which you multiply the
                          Jacobian). It should be a tuple of ints.

        If the Op has more than 1 input, one of them must be mx, while
        others must be shared variables / constants. We will test only
        against the input self.mx, so you must call
        check_mat_rop_lop/check_rop_lop for the other inputs.

        We expect all inputs/outputs have dtype floatX.

        If you want to test an Op with an output matrix, add a sum
        after the Op you want to test.
        """
        vx = np.asarray(self.rng.uniform(size=self.mat_in_shape),
                        theano.config.floatX)
        vv = np.asarray(self.rng.uniform(size=self.mat_in_shape),
                        theano.config.floatX)
        yv = tensor.Rop(y, self.mx, self.mv)
        rop_f = function([self.mx, self.mv], yv, on_unused_input='ignore')
        sy, _ = theano.scan(lambda i, y, x, v:
                            (tensor.grad(y[i], x) * v).sum(),
                            sequences=tensor.arange(y.shape[0]),
                            non_sequences=[y, self.mx, self.mv])
        scan_f = function([self.mx, self.mv], sy, on_unused_input='ignore')

        v1 = rop_f(vx, vv)
        v2 = scan_f(vx, vv)

        assert np.allclose(v1, v2), ('ROP mismatch: %s %s' % (v1, v2))

        self.check_nondiff_rop(theano.clone(y, replace={self.mx: break_op(self.mx)}))

        vv = np.asarray(self.rng.uniform(size=out_shape), theano.config.floatX)
        yv = tensor.Lop(y, self.mx, self.v)
        lop_f = function([self.mx, self.v], yv)

        sy = tensor.grad((self.v * y).sum(), self.mx)
        scan_f = function([self.mx, self.v], sy)

        v1 = lop_f(vx, vv)
        v2 = scan_f(vx, vv)
        assert np.allclose(v1, v2), ('LOP mismatch: %s %s' % (v1, v2))

    def check_rop_lop(self, y, out_shape):
        """
        As check_mat_rop_lop, except the input is self.x which is a
        vector. The output is still a vector.
        """
        # TEST ROP
        vx = np.asarray(self.rng.uniform(size=self.in_shape),
                        theano.config.floatX)
        vv = np.asarray(self.rng.uniform(size=self.in_shape),
                        theano.config.floatX)

        yv = tensor.Rop(y, self.x, self.v)
        rop_f = function([self.x, self.v], yv, on_unused_input='ignore')
        J, _ = theano.scan(lambda i, y, x: tensor.grad(y[i], x),
                           sequences=tensor.arange(y.shape[0]),
                           non_sequences=[y, self.x])
        sy = tensor.dot(J, self.v)

        scan_f = function([self.x, self.v], sy, on_unused_input='ignore')

        v1 = rop_f(vx, vv)
        v2 = scan_f(vx, vv)
        assert np.allclose(v1, v2), ('ROP mismatch: %s %s' % (v1, v2))
        known_fail = False
        try:
            self.check_nondiff_rop(theano.clone(y, replace={self.x: break_op(self.x)}))
        except AssertionError:
            known_fail = True

        # TEST LOP

        vx = np.asarray(self.rng.uniform(size=self.in_shape),
                        theano.config.floatX)
        vv = np.asarray(self.rng.uniform(size=out_shape),
                        theano.config.floatX)

        yv = tensor.Lop(y, self.x, self.v)
        lop_f = function([self.x, self.v], yv, on_unused_input='ignore')
        J, _ = theano.scan(lambda i, y, x: tensor.grad(y[i], x),
                           sequences=tensor.arange(y.shape[0]),
                           non_sequences=[y, self.x])
        sy = tensor.dot(self.v, J)

        scan_f = function([self.x, self.v], sy)

        v1 = lop_f(vx, vv)
        v2 = scan_f(vx, vv)
        assert np.allclose(v1, v2), ('LOP mismatch: %s %s' % (v1, v2))

        if known_fail:
            raise SkipTest('Rop does not handle non-differentiable inputs '
                           'correctly. Bug exposed by fixing Add.grad method.')

class test_RopLop(RopLop_checker):
    def test_shape(self):
        self.check_nondiff_rop(self.x.shape[0])

    def test_specifyshape(self):
        self.check_rop_lop(tensor.specify_shape(self.x, self.in_shape),
                           self.in_shape)

    def test_max(self):
        # If we call max directly, we will return an CAReduce object
        # which doesn't have R_op implemented!
        # self.check_mat_rop_lop(tensor.max(self.mx, axis=[0,1])[0], ())
        self.check_mat_rop_lop(tensor.max(self.mx, axis=0),
                               (self.mat_in_shape[1],))
        self.check_mat_rop_lop(tensor.max(self.mx, axis=1),
                               (self.mat_in_shape[0],))

    def test_argmax(self):
        self.check_nondiff_rop(tensor.argmax(self.mx, axis=1))

    def test_subtensor(self):
        self.check_rop_lop(self.x[:4], (4,))

    def test_incsubtensor1(self):
        tv = np.asarray(self.rng.uniform(size=(3,)),
                        theano.config.floatX)
        t = theano.shared(tv)
        out = tensor.inc_subtensor(self.x[:3], t)
        self.check_rop_lop(out, self.in_shape)

    def test_incsubtensor2(self):
        tv = np.asarray(self.rng.uniform(size=(10,)),
                        theano.config.floatX)
        t = theano.shared(tv)
        out = tensor.inc_subtensor(t[:4], self.x[:4])
        self.check_rop_lop(out, (10,))

    def test_setsubtensor1(self):
        tv = np.asarray(self.rng.uniform(size=(3,)),
                        theano.config.floatX)
        t = theano.shared(tv)
        out = tensor.set_subtensor(self.x[:3], t)
        self.check_rop_lop(out, self.in_shape)

    def test_print(self):
        out = theano.printing.Print('x', attrs=('shape',))(self.x)
        self.check_rop_lop(out, self.in_shape)

    def test_setsubtensor2(self):
        tv = np.asarray(self.rng.uniform(size=(10,)),
                        theano.config.floatX)
        t = theano.shared(tv)
        out = tensor.set_subtensor(t[:4], self.x[:4])
        self.check_rop_lop(out, (10,))

    def test_dimshuffle(self):
        # I need the sum, because the setup expects the output to be a
        # vector
        self.check_rop_lop(self.x[:4].dimshuffle('x', 0).sum(axis=0),
                           (4,))

    def test_rebroadcast(self):
        # I need the sum, because the setup expects the output to be a
        # vector
        self.check_rop_lop(tensor.unbroadcast(
            self.x[:4].dimshuffle('x', 0), 0).sum(axis=1),
            (1,))

    def test_downsample(self):
        rng = np.random.RandomState(utt.fetch_seed())
        # ws, shp
        examples = (
            ((2,), (16,)),
            ((2,), (4, 16,)),
            ((2,), (4, 2, 16,)),
            ((1, 1), (4, 2, 16, 16)),
            ((2, 2), (4, 2, 16, 16)),
            ((3, 3), (4, 2, 16, 16)),
            ((3, 2), (4, 2, 16, 16)),
            ((3, 2, 2), (3, 2, 16, 16, 16)),
            ((2, 3, 2), (3, 2, 16, 16, 16)),
            ((2, 2, 3), (3, 2, 16, 16, 16)),
            ((2, 2, 3, 2), (3, 2, 6, 6, 6, 5)),
        )

        for example, ignore_border in itertools.product(examples, [True, False]):
            (ws, shp) = example
            vx = rng.rand(*shp)
            vex = rng.rand(*shp)

            x = theano.shared(vx)
            ex = theano.shared(vex)

            maxpool_op = Pool(ignore_border, ndim=len(ws))
            a_pooled = maxpool_op(x, ws).flatten()
            yv = tensor.Rop(a_pooled, x, ex)
            mode = None
            if theano.config.mode == "FAST_COMPILE":
                mode = "FAST_RUN"
            rop_f = function([], yv, on_unused_input='ignore', mode=mode)
            sy, _ = theano.scan(lambda i, y, x, v:
                                (tensor.grad(y[i], x) * v).sum(),
                                sequences=tensor.arange(a_pooled.shape[0]),
                                non_sequences=[a_pooled, x, ex],
                                mode=mode)
            scan_f = function([], sy, on_unused_input='ignore', mode=mode)
            v1 = rop_f()
            v2 = scan_f()
            assert np.allclose(v1, v2), ("Rop mismatch: %s %s" % (v1, v2))

    def test_conv(self):
        for conv_op in [conv.conv2d, conv2d]:
            for border_mode in ['valid', 'full']:
                image_shape = (2, 2, 4, 5)
                filter_shape = (2, 2, 2, 3)
                image_dim = len(image_shape)
                filter_dim = len(filter_shape)
                input = tensor.TensorType(
                    theano.config.floatX,
                    [False] * image_dim)(name='input')
                filters = tensor.TensorType(
                    theano.config.floatX,
                    [False] * filter_dim)(name='filter')
                ev_input = tensor.TensorType(
                    theano.config.floatX,
                    [False] * image_dim)(name='ev_input')
                ev_filters = tensor.TensorType(
                    theano.config.floatX,
                    [False] * filter_dim)(name='ev_filters')

                def sym_conv2d(input, filters):
                    return conv_op(input, filters, border_mode=border_mode)
                output = sym_conv2d(input, filters).flatten()
                yv = tensor.Rop(output, [input, filters], [ev_input, ev_filters])
                mode = None
                if theano.config.mode == "FAST_COMPILE":
                    mode = "FAST_RUN"
                rop_f = function([input, filters, ev_input, ev_filters],
                                 yv, on_unused_input='ignore', mode=mode)
                sy, _ = theano.scan(lambda i, y, x1, x2, v1, v2:
                                    (tensor.grad(y[i], x1) * v1).sum() +
                                    (tensor.grad(y[i], x2) * v2).sum(),
                                    sequences=tensor.arange(output.shape[0]),
                                    non_sequences=[output, input, filters,
                                                   ev_input, ev_filters],
                                    mode=mode)
                scan_f = function([input, filters, ev_input, ev_filters], sy,
                                  on_unused_input='ignore', mode=mode)
                dtype = theano.config.floatX
                image_data = np.random.random(image_shape).astype(dtype)
                filter_data = np.random.random(filter_shape).astype(dtype)
                ev_image_data = np.random.random(image_shape).astype(dtype)
                ev_filter_data = np.random.random(filter_shape).astype(dtype)
                v1 = rop_f(image_data, filter_data, ev_image_data, ev_filter_data)
                v2 = scan_f(image_data, filter_data, ev_image_data, ev_filter_data)
                assert np.allclose(v1, v2), ("Rop mismatch: %s %s" % (v1, v2))

    def test_join(self):
        tv = np.asarray(self.rng.uniform(size=(10,)),
                        theano.config.floatX)
        t = theano.shared(tv)
        out = tensor.join(0, self.x, t)
        self.check_rop_lop(out, (self.in_shape[0] + 10,))

    def test_dot(self):
        insh = self.in_shape[0]
        vW = np.asarray(self.rng.uniform(size=(insh, insh)),
                        theano.config.floatX)
        W = theano.shared(vW)
        self.check_rop_lop(tensor.dot(self.x, W), self.in_shape)

    def test_elemwise0(self):
        self.check_rop_lop((self.x + 1) ** 2, self.in_shape)

    def test_elemwise1(self):
        self.check_rop_lop(self.x + tensor.cast(self.x, 'int32'),
                           self.in_shape)

    def test_reshape(self):
        new_shape = tensor.constant(np.asarray([
            self.mat_in_shape[0] * self.mat_in_shape[1]],
            dtype='int64'))

        self.check_mat_rop_lop(self.mx.reshape(new_shape),
                               (self.mat_in_shape[0] * self.mat_in_shape[1],))

    def test_flatten(self):
        self.check_mat_rop_lop(self.mx.flatten(),
                               (self.mat_in_shape[0] * self.mat_in_shape[1],))

    def test_sum(self):
        self.check_mat_rop_lop(self.mx.sum(axis=1), (self.mat_in_shape[0],))

    def test_softmax(self):
        # Softmax adds an extra dimnesion !
        self.check_rop_lop(tensor.nnet.softmax(self.x)[0], self.in_shape[0])

    def test_alloc(self):
        # Alloc of the sum of x into a vector
        out1d = tensor.alloc(self.x.sum(), self.in_shape[0])
        self.check_rop_lop(out1d, self.in_shape[0])

        # Alloc of x into a 3-D tensor, flattened
        out3d = tensor.alloc(self.x, self.mat_in_shape[0], self.mat_in_shape[1], self.in_shape[0])
        self.check_rop_lop(out3d.flatten(), self.mat_in_shape[0] * self.mat_in_shape[1] * self.in_shape[0])

    def test_invalid_input(self):
        success = False

        try:
            tensor.Rop(0., [tensor.matrix()], [tensor.vector()])
            success = True
        except ValueError:
            pass

        assert not success

    def test_multiple_outputs(self):
        m = tensor.matrix('m')
        v = tensor.vector('v')
        m_ = tensor.matrix('m_')
        v_ = tensor.vector('v_')

        mval = self.rng.uniform(size=(3, 7)).astype(theano.config.floatX)
        vval = self.rng.uniform(size=(7,)).astype(theano.config.floatX)
        m_val = self.rng.uniform(size=(3, 7)).astype(theano.config.floatX)
        v_val = self.rng.uniform(size=(7,)).astype(theano.config.floatX)

        rop_out1 = tensor.Rop([m, v, m + v], [m, v], [m_, v_])
        assert isinstance(rop_out1, list)
        assert len(rop_out1) == 3
        rop_out2 = tensor.Rop((m, v, m + v), [m, v], [m_, v_])
        assert isinstance(rop_out2, tuple)
        assert len(rop_out2) == 3

        all_outs = []
        for o in rop_out1, rop_out2:
            all_outs.extend(o)
        f = theano.function([m, v, m_, v_], all_outs)
        f(mval, vval, m_val, v_val)

    def test_Rop_dot_bug_18Oct2013_Jeremiah(self):
        # This test refers to a bug reported by Jeremiah Lowin on 18th Oct
        # 2013. The bug consists when through a dot operation there is only
        # one differentiable path (i.e. there is no gradient wrt to one of
        # the inputs).
        x = tensor.arange(20.0).reshape([1, 20])
        v = theano.shared(np.ones([20]))
        d = tensor.dot(x, v).sum()
        tensor.Rop(tensor.grad(d, v), v, v)


import pygame, sys, time, random
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()

lives = 3
lives2 = 3

width = 800
height = 600
windowSurface = pygame.display.set_mode((width, height), 0, 32)

pygame.display.set_caption('Star Wars!')

movementSpeed = 10
projectileSpeed = 30
scrollSpeed = 6
iambecomespeed = 200

shotFrameCounter = 0
targetFrameCounter = 0
collisionFrameCounter = 0

shots = []
shots2 = []
targets = []
lifeblocks = []
nopain = []
death = []

maxLives = 3
score = 0

maxTargets = 5
lifes = 4
maxShots = 3
Finvincible = 1
iambecome = 1

moveLeft = False
moveLeft2 = False
moveRight = False
moveRight2 = False

black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)

x = 48
y = 48
t = 40

player = pygame.Rect(273, 20, x, t)
player2 = pygame.Rect(273, 530, x, t)

bg = pygame.Rect(0, -100, 10, 10)
shoot = False
shoot2 = False

background = pygame.image.load('Resources/Images/StarsPattern.png')
Da_Ship = pygame.image.load('Resources/Images/marrio.jpeg')
SS_Falcon = pygame.image.load('Resources/Images/SS Falcon.png').convert()
Rover = pygame.image.load('Resources/Images/World.png').convert()
The_World = pygame.image.load('Resources/Images/tuskc.png').convert()
pew = pygame.mixer.Sound('Resources/Audio/Gun+1.wav')
pew2 = pygame.mixer.Sound('Resources/Audio/Gun+Shot2.wav')
boom = pygame.mixer.Sound('Resources/Audio/Explosion+1.wav')
boom7 = pygame.mixer.Sound('Resources/Audio/boom7.wav')
space = pygame.mixer.music.load('Resources/Audio/Space Fighter Loop.mp3')

DASHIP = pygame.transform.scale(Da_Ship, (x, y))
FALCON = pygame.transform.scale(SS_Falcon, (x ,y))
ROVER = pygame.transform.scale(Rover, (x,y))
THE_WORLD = pygame.transform.scale(The_World, (x,y))

mcounter = 1
mouset = True
yellowrect = pygame.draw.rect(windowSurface, yellow, (400, 550, 30, 30))
greenRect = pygame.draw.rect(windowSurface, green, (250, 10, 500, 300))
titleFont = pygame.font.SysFont("none", 60)
myText = "Welcome to Space War! Here are the rules:"
text = titleFont.render(myText, True, black)

def end(lives,lives2):
    while True:
        windowSurface.fill(black)
        windowSurface.blit(background, bg)
        bg.left -= scrollSpeed
        if bg.left < -800:
            bg.left = 0
        pygame.display.update()
        if lives <= 0:
            font = pygame.font.SysFont("none", 24)
            scoreText = ("Player 2 WINS!")
            text2 = font.render(scoreText, True, white)
            windowSurface.blit(text2, (10, 10))
            thatRect = pygame.draw.rect(windowSurface, green, (50, 300, 390, 100))
            myText = "End Game?"

            thisRect = pygame.draw.rect(windowSurface, green, (50, 450, 390, 100))
            myText2 = "New Game?"

            text = titleFont.render(myText, True, black)
            textRect = text.get_rect()
            textRect.centerx = thatRect.centerx
            textRect.centery = thatRect.centery
            windowSurface.blit(text, textRect)

            text2 = titleFont.render(myText2, True, black)
            textRect2 = text.get_rect()
            textRect2.centerx = thisRect.centerx
            textRect2.centery = thisRect.centery
            windowSurface.blit(text2, textRect2)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == MOUSEBUTTONDOWN:
                    if event.pos[0] >= thatRect.left and event.pos[0] <= thatRect.right and event.pos[
                        1] >= thatRect.top and \
                            event.pos[1] <= thatRect.bottom:
                        print("endgame selected!")
                        pygame.quit()
                        sys.exit()

                if event.type == MOUSEBUTTONDOWN:
                    if event.pos[0] >= thisRect.left and event.pos[0] <= thisRect.right and event.pos[
                        1] >= thisRect.top and \
                            event.pos[1] <= thisRect.bottom:
                        pygame.mixer.music.unpause()
                        print("newgame selected")
                        startgame()
                        chooseship()

                if event.type == QUIT:
                    print("quit selected!")
                    pygame.quit()
                    sys.exit()

        if lives2 <= 0:
            font = pygame.font.SysFont("none", 24)
            scoreText = ("Player 1 WINS!")
            text2 = font.render(scoreText, True, white)
            windowSurface.blit(text2, (10, 10))
            thatRect = pygame.draw.rect(windowSurface, green, (50, 300, 390, 100))
            myText = "End Game?"

            thisRect = pygame.draw.rect(windowSurface, green, (50, 450, 390, 100))
            myText2 = "New Game?"

            text = titleFont.render(myText, True, black)
            textRect = text.get_rect()
            textRect.centerx = thatRect.centerx
            textRect.centery = thatRect.centery
            windowSurface.blit(text, textRect)

            text2 = titleFont.render(myText2, True, black)
            textRect2 = text.get_rect()
            textRect2.centerx = thisRect.centerx
            textRect2.centery = thisRect.centery
            windowSurface.blit(text2, textRect2)

            pygame.display.update()
            for event in pygame.event.get():
                if event.type == MOUSEBUTTONDOWN:
                    if event.pos[0] >= thatRect.left and event.pos[0] <= thatRect.right and event.pos[
                        1] >= thatRect.top and \
                            event.pos[1] <= thatRect.bottom:
                        print("endgame selected!")
                        pygame.quit()
                        sys.exit()

                if event.type == MOUSEBUTTONDOWN:
                    if event.pos[0] >= thisRect.left and event.pos[0] <= thisRect.right and event.pos[
                        1] >= thisRect.top and \
                            event.pos[1] <= thisRect.bottom:
                        pygame.mixer.music.unpause()
                        print("newgame selected")
                        startgame()
                        chooseship()

                if event.type == QUIT:
                    print("quit selected!")
                    pygame.quit()
                    sys.exit()
                pygame.display.update()

def chooseship():
    shotFrameCounter = 0
    targetFrameCounter = 0
    collisionFrameCounter = 0

    shots = []
    shots2 = []
    targets = []
    lifeblocks = []
    nopain = []
    death = []

    maxLives = 3
    score = 0

    maxTargets = 5
    lifes = 4
    maxShots = 3
    Finvincible = 1
    iambecome = 1

    moveLeft = False
    moveLeft2 = False
    moveRight = False
    moveRight2 = False

    x = 48
    y = 54

    player = pygame.Rect(273, 20, x, y)
    player2 = pygame.Rect(273, 530, x, y)

    bg = pygame.Rect(0, -100, 10, 10)
    shoot = False
    shoot2 = False

    lives = 3
    lives2 = 3

    mcounter = 1
    safe = 0
    safe2 = 0
    mouset = True
    while mouset:
        windowSurface.fill(black)
        windowSurface.blit(background, bg)
        bg.left -= scrollSpeed
        if bg.left < -800:
            bg.left = 0
        blueRect = pygame.draw.rect(windowSurface, blue, (200, 100, 60, 60))
        redRect = pygame.draw.rect(windowSurface, red, (200, 300, 60, 60))
        greenRect = pygame.draw.rect(windowSurface, green, (400, 100, 60, 60))
        whiteRect = pygame.draw.rect(windowSurface, white, (400, 300, 60, 60))
        firstship = "The World"
        secondship = "Rover"
        thirdship = "Inevitability"
        fourthship = "Falcon"
        daFont = pygame.font.SysFont("none", 20)
        hrship = daFont.render(firstship, True, blue)
        windowSurface.blit(hrship, (200, 170))
        rhship = daFont.render(secondship, True, red)
        windowSurface.blit(rhship, (200, 370))
        ssship = daFont.render(thirdship, True, green)
        windowSurface.blit(ssship, (400, 170))
        tship = daFont.render(fourthship, True, white)
        windowSurface.blit(tship, (400, 370))

        windowSurface.blit(THE_WORLD, blueRect)
        windowSurface.blit(ROVER, redRect)
        windowSurface.blit(DASHIP, greenRect)
        windowSurface.blit(FALCON, whiteRect)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                if event.pos[0] >= greenRect.left and event.pos[0] <= greenRect.right and event.pos[
                    1] >= greenRect.top and event.pos[1] <= greenRect.bottom:
                    if mcounter == 2:
                        ship2 = DASHIP
                        shipname = ("daship")
                        mouset = False
                if event.pos[0] >= blueRect.left and event.pos[0] <= blueRect.right and event.pos[1] >= blueRect.top and \
                        event.pos[1] <= blueRect.bottom:
                    if mcounter == 2:
                        ship2 = THE_WORLD
                        shipname = ("world")
                        mouset = False
                if event.pos[0] >= redRect.left and event.pos[0] <= redRect.right and event.pos[1] >= redRect.top and \
                        event.pos[1] <= redRect.bottom:
                    if mcounter == 2:
                        ship2 = ROVER
                        shipname = ("Rover")
                        mouset = False
                if event.pos[0] >= whiteRect.left and event.pos[0] <= whiteRect.right and event.pos[
                    1] >= whiteRect.top and \
                        event.pos[1] <= whiteRect.bottom:
                    if mcounter == 2:
                        ship2 = FALCON
                        shipname = ("Falcon")
                        mouset = False
            if event.type == MOUSEBUTTONDOWN:
                if event.pos[0] >= greenRect.left and event.pos[0] <= greenRect.right and event.pos[
                    1] >= greenRect.top and event.pos[1] <= greenRect.bottom:
                    if mcounter == 1:
                        ship1 = DASHIP
                        shipname = ("daship")
                        mcounter = 2
                if event.pos[0] >= blueRect.left and event.pos[0] <= blueRect.right and event.pos[1] >= blueRect.top and \
                        event.pos[1] <= blueRect.bottom:
                    if mcounter == 1:
                        ship1 = THE_WORLD
                        shipname = ("mworld")
                        mcounter = 2
                if event.pos[0] >= redRect.left and event.pos[0] <= redRect.right and event.pos[1] >= redRect.top and \
                        event.pos[1] <= redRect.bottom:
                    if mcounter == 1:
                        ship1 = ROVER
                        shipname = ("Rover")
                        mcounter = 2
                if event.pos[0] >= whiteRect.left and event.pos[0] <= whiteRect.right and event.pos[
                    1] >= whiteRect.top and \
                        event.pos[1] <= whiteRect.bottom:
                    if mcounter == 1:
                        ship1 = FALCON
                        shipname = ("Falcon")
                        mcounter = 2

    ship1 = pygame.transform.rotate(ship1, 180)

    great = True
    while great:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_LEFT:
                    moveLeft = True
                if event.key == K_RIGHT:
                    moveRight = True
                if event.key == K_p:
                    shoot = True
                    pew2.play()
                if event.key == K_a:
                    moveLeft2 = True
                if event.key == K_d:
                    moveRight2 = True
                if event.key == K_SPACE:
                    shoot2 = True
                    pew.play()
            if event.type == KEYUP:
                if event.key == K_LEFT:
                    moveLeft = False
                if event.key == K_RIGHT:
                    moveRight = False
                if event.key == K_p:
                    shoot = False
                if event.key == K_a:
                    moveLeft2 = False
                if event.key == K_d:
                    moveRight2 = False
                if event.key == K_SPACE:
                    shoot2 = False
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()

        if moveLeft2 == True:
            if player2.left > 0:
                player2.left -= movementSpeed
        if moveRight2 == True:
            if player2.right < width:
                player2.right += movementSpeed
        if moveLeft == True:
            if player.left > 0:
                player.left -= movementSpeed
        if moveRight == True:
            if player.right < width:
                player.right += movementSpeed
        windowSurface.fill(black)
        windowSurface.blit(background, bg)
        bg.left -= scrollSpeed
        if bg.left < -800:
            bg.left = 0
        windowSurface.blit(ship1, player)
        windowSurface.blit(ship2, player2)
        for target in targets[:]:
            if target.left < - 20:
                targets.remove(target)
        for life in lifeblocks[:]:
            if life.left < - 20:
                lifeblocks.remove(life)
        for invincible in nopain[:]:
            if invincible.left < - 20:
                nopain.remove(invincible)
        for dead in death[:]:
            if dead.left < -20:
                death.remove(dead)

        if shoot == True and (len(shots) < maxShots):
            shots.append(pygame.Rect(player.centerx - 3, player.centery - 3, 6, 6))
        for i in range(len(shots)):
            pygame.draw.rect(windowSurface, green, shots[i])
            shots[i].bottom += projectileSpeed
            if shots[i].colliderect(player2):
                lives2 -= 1
                shots[i].top = 600
                boom7.play()
            for target in targets[:]:
                if shots[i].colliderect(target):
                    targets.remove(target)
                    lives -= 1
                    shots[i].top = 600
                    boom.play()
            for life in lifeblocks[:]:
                if shots[i].colliderect(life):
                    lifeblocks.remove(life)
                    lives += 1
                    shots[i].top = 600
                    boom.play()
            for invincible in nopain[:]:
                if shots[i].colliderect(invincible):
                    nopain.remove(invincible)
                    if safe == 0:
                        safe = 30
                        maxLives -= 1
            for dead in death[:]:
                if shots[i].colliderect(dead):
                    lives2 = 1
                    shots[i].top = 600
                    boom.play()
            if safe > 0:
                if safe % 3 == 0:
                    boom.play()
                    ship1.set_alpha(255)
                    safe -= 1
                else:
                    ship1.set_alpha(0)
            else:
                ship1.set_alpha(255)

        if shoot2 == True and (len(shots2) < maxShots):
            shots2.append(pygame.Rect(player2.centerx - 3, player2.centery - 3, 6, 6))
        for i in range(len(shots2)):
            pygame.draw.rect(windowSurface, red, shots2[i])
            shots2[i].bottom -= projectileSpeed
            if shots2[i].colliderect(player):
                lives -= 1
                boom7.play()
            for target in targets[:]:
                if shots2[i].colliderect(target):
                    targets.remove(target)
                    lives2 -= 1
                    shots2[i].bottom = 0
            for life in lifeblocks[:]:
                if shots2[i].colliderect(life):
                    lifeblocks.remove(life)
                    lives2 += 1
                    shots2[i].bottom = 0
            for invincible in nopain[:]:
                if shots2[i].colliderect(invincible):
                    invincible.left = -10
                    if safe2 == 0:
                        safe2 = 30
            for dead in death[:]:
                if shots2[i].colliderect(dead):
                    lives = 1
                    shots2[i].bottom = 0
            if safe2 > 0:
                if safe2 % 3 == 0:
                    boom.play()
                    ship2.set_alpha(255)
                    safe2 -= 1
                else:
                    ship2.set_alpha(0)
            else:
                ship2.set_alpha(255)

        for shot in shots[:]:
            if shot.top > 620:
                shots.remove(shot)
        for shot in shots[:]:
            if shot.colliderect(player2):
                shot.top = 600

        for shot2 in shots2[:]:
            if shot2.bottom < 0:
                shots2.remove(shot2)
        for shot2 in shots2[:]:
            if shot2.colliderect(player):
                shot2.bottom = 0

        z = random.randint(0, 23)
        if z == 4:
            if len(targets) < maxTargets:
                targets.append(pygame.Rect(width + 20, random.randint(100, height - 100), 40, 20))
        if z == 13:
            if len(lifeblocks) < lifes:
                lifeblocks.append(pygame.Rect(width + 20, random.randint(100, height - 100), 40, 20))
        if z == 5:
            if len(nopain) < Finvincible:
                nopain.append(pygame.Rect(width + 20, random.randint(100, height - 100), 40, 20))
        if z == 1:
            if len(death) < iambecome:
                death.append(pygame.Rect(width + 20, random.randint(100, height - 100), 40, 20))

        for i in range(len(targets)):
            pygame.draw.rect(windowSurface, red, targets[i])
            targets[i].left -= movementSpeed
        for i in range(len(lifeblocks)):
            pygame.draw.rect(windowSurface, blue, lifeblocks[i])
            lifeblocks[i].left -= movementSpeed
        for i in range(len(nopain)):
            pygame.draw.rect(windowSurface, black, nopain[i])
            nopain[i].left -= movementSpeed
        for i in range(len(death)):
            pygame.draw.rect(windowSurface, white, death[i])
            death[i].left -= iambecomespeed

        font = pygame.font.SysFont("none", 20)
        scoreText = "Lives: " + str(lives)
        text2 = font.render(scoreText, True, green)
        windowSurface.blit(text2, (10, 10))

        font = pygame.font.SysFont("none", 20)
        scoreText = "Lives: " + str(lives2)
        text3 = font.render(scoreText, True, red)
        windowSurface.blit(text3, (750, 560))

        pygame.display.update()
        mainClock.tick(60)
        if safe > 0:
            safe -= 1
        if safe2 > 0:
            safe2 -= 1
        if lives <= 0 or lives2 <= 0:
            end(lives,lives2)
def playmusic():
    v = .1
    pygame.mixer.music.load('Resources/Audio/Space Fighter Loop.mp3')
    pygame.mixer.music.play(-1, 0)
    pygame.mixer.music.set_volume(v)

def startgame():
    game = True
    realgame = False
    while game:
        windowSurface.fill(black)
        windowSurface.blit(background, bg)
        bg.left -= scrollSpeed
        if bg.left < -800:
            bg.left = 0
        greenRect = pygame.draw.rect(windowSurface, green, (200, 250, 390, 100))
        titleFont = pygame.font.SysFont("none", 90)
        myText = "Start game?"
        text = titleFont.render(myText, True, black)
        textRect = text.get_rect()
        textRect.centerx = windowSurface.get_rect().centerx
        textRect.centery = windowSurface.get_rect().centery
        windowSurface.blit(text, textRect)
        bigFont = pygame.font.SysFont("none", 100)
        Spacewar = "SPACE WAR"
        text3 = bigFont.render(Spacewar, True, red)
        windowSurface.blit(text3, (200, 100))
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                if event.pos[0] >= greenRect.left and event.pos[0] <= greenRect.right and event.pos[1] >= greenRect.top and event.pos[1] <= greenRect.bottom:
                    playmusic()
                tules = True
                while tules:
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            pygame.quit()
                            sys.exit()
                        if event.type == MOUSEBUTTONDOWN:
                            if event.pos[0] >= yellowrect.left and event.pos[0] <= yellowrect.right and event.pos[
                                1] >= yellowrect.top and \
                                    event.pos[1] <= yellowrect.bottom:
                                chooseship()
                        pygame.display.update()
                    windowSurface.fill(black)
                    windowSurface.blit(background, bg)
                    bg.left -= scrollSpeed
                    if bg.left < -800:
                        bg.left = 0
                    yellowrect = pygame.draw.rect(windowSurface, yellow, (400, 550, 30, 30))
                    greenRect = pygame.draw.rect(windowSurface, green, (30, 10, 720, 40))
                    redrect = pygame.draw.rect(windowSurface, red, (60, 150, 70, 40))
                    bluerect = pygame.draw.rect(windowSurface, blue, (60, 220, 70, 40))
                    blackrect = pygame.draw.rect(windowSurface, black, (60, 290, 70, 40))
                    whiterect = pygame.draw.rect(windowSurface, white, (60, 360, 70, 40))
                    rulered = "if you hit the red rectangle, you lose a life"
                    ruleblue = "if you hit the blue rectangle, you get a life"
                    ruleblack = "if you hit the black rectangle, you are invisible (but it itself is basically invisible) until you shoot"
                    rulewhite = " if you hit the white rectangle, the other character gets their lives reduced to one life(you can try to hit it, anyway.)"
                    titleFont = pygame.font.SysFont("none", 50)
                    myText = "Welcome to Space War! Here are the rules:"
                    text = titleFont.render(myText, True, black)
                    Start = "READY? PRESS THE YELLOW BUTTON!"
                    text3 = titleFont.render(Start, True, blue)
                    windowSurface.blit(text3, (75, 500))
                    windowSurface.blit(text, greenRect)
                    littleFont = pygame.font.SysFont("none", 20)
                    tusk = pygame.font.SysFont("none", 18)
                    text4 = littleFont.render(rulered, True, red)
                    windowSurface.blit(text4, (160, 150))
                    text5 = littleFont.render(ruleblue, True, blue)
                    windowSurface.blit(text5, (160, 220))
                    text6 = littleFont.render(ruleblack, True, white)
                    windowSurface.blit(text6, (160, 290))
                    text7 = tusk.render(rulewhite, True, white)
                    windowSurface.blit(text7, (160, 360))
                    pygame.display.update()
        pygame.display.update()
startgame()


from PySide2.QtCore import QUrl, QObject, Slot

from PySide2.QtGui import QGuiApplication

from PySide2.QtQuick import QQuickView

class MyClass(QObject):

    @Slot(int, result=str)  # 声明为槽，输入参数为int类型，返回值为str类型
    def returnValue(self, value):
        return str(value + 10)

if __name__ == '__main__':
    path = 'src/demo1.qml'

    app = QGuiApplication([])

    view = QQuickView()

    con = MyClass()

    context = view.rootContext()

    context.setContextProperty("con", con)

    view.engine().quit.connect(app.quit)

    view.setSource(QUrl(path))

    view.show()

    app.exec_()


from django.shortcuts import render

product_price = {"라면":980,"홈런볼":1500,"칙촉":2300, "식빵":1800}

# Create your views here.
def price(request, thing, cnt):
    if thing in product_price:
        y_n = 'y'
        price = product_price[thing]
    else:
        y_n = 'n'
        price = 0
    context = {
        'y_n' : y_n,
        'price' : price,
        'thing' : thing,
        'cnt' : cnt,
        'total' : price * cnt
    }
    return render(request, 'prices/price.html', context)


"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import (
    include,
    url,
)
from django.contrib import admin

from classifier.views import CreateClassification
from healthcheck.views import HealthCheck
from report.views import CreateReport
from secret.views import Secret

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^auth/', include('djoser.urls')),
    url(r'^auth/', include('djoser.urls.authtoken')),
    url(
        r'^classify-image',
        CreateClassification.as_view(),
        name='classify-image',
    ),
    url(r'^health', HealthCheck.as_view(), name='healthcheck'),
    url(r'^report', CreateReport.as_view(), name='report'),
    url(r'^secret', Secret.as_view(), name='secret'),
]


from __future__ import print_function, division

import os
import logging
import math
import numpy as np
import pandas as pd

import torch
from torch.utils.tensorboard import SummaryWriter

IS_ON_SERVER = False if os.getcwd().startswith('/home/SENSETIME/yuanjing1') else True

axis_name2np_dim = {
    "x": 2,
    "y": 1,
    "z": 0,
}

# --------
# data normalization
def mean_std_norm(array):
    return (array - array.mean()) / (array.std() + 1e-10)

def rescale01(arr):
    return (arr - arr.min()) / (arr.max() - arr.min())

def window_rescale(arr, a_min=None, a_max=None):
    arr = np.clip(arr, a_min=a_min, a_max=a_max)
    return (arr - a_min) / (a_max - a_min)

def auto_window(arr):
    return window_rescale(arr, a_min=np.percentile(arr, 1), a_max=np.percentile(arr, 99))

# --------
# pad & crop
def get_pad_border(origin_shape, target_shape):
    assert len(origin_shape) == len(target_shape), 'Dimension mismatch.'
    borders = []
    for i in range(len(origin_shape)):
        tmp = target_shape[i] - origin_shape[i]
        borders.extend((tmp // 2, tmp - tmp // 2))
    return tuple(zip(borders[::2], borders[1::2]))

def pad_zyx_constant(nda, target_shape, pad_value=0, strict=False):
    assert nda.ndim == len(target_shape), 'Dimension mismatch.'
    if strict:
        assert np.all(np.array(target_shape) >= np.array(nda.shape)), 'Target shape must be larger than input shape.'
    else:
        target_shape = np.maximum(nda.shape, target_shape)
    borders = get_pad_border(nda.shape, target_shape)
    nda = np.pad(nda, borders, mode='constant', constant_values=pad_value)
    return nda

def center_crop_zyx(nda, target_shape):
    starts = np.asarray((np.asarray(nda.shape) - np.asarray(target_shape)) // 2)
    slice_fn = tuple(map(slice, starts, np.asarray(starts) + np.asarray(target_shape)))
    return nda[slice_fn]

def constant_pad_crop(nda, target_shape, pad_value=0, strict=False):
    assert nda.ndim == len(target_shape), 'Dimension mismatch.'
    nda = pad_zyx_constant(nda, target_shape, pad_value, strict)
    return center_crop_zyx(nda, target_shape)

# --------
# logger
def log_init(log_dir):
    logger = logging.getLogger()
    logger.setLevel(level=logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(lineno)d - %(module)s - %(message)s')
    # handle for txt file
    f_handler = logging.FileHandler(os.path.join(log_dir, 'log.txt'))
    f_handler.setLevel(logging.INFO)
    f_handler.setFormatter(formatter)
    # handle for screen
    c_handler = logging.StreamHandler()
    c_handler.setLevel(logging.INFO)
    c_handler.setFormatter(formatter)
    logger.addHandler(f_handler)
    logger.addHandler(c_handler)

    writer = SummaryWriter(log_dir=os.path.join(log_dir, 'tb'))
    return logger, writer

# --------
def get_bbox(np_lbl):
    lbl_indices = np.nonzero(np_lbl)
    bbox = np.array([[i.min(), i.max()] for i in lbl_indices])
    return bbox

def hist_match(source, template):
    oldshape = source.shape
    source = source.ravel()
    template = template.ravel()
    # get the set of unique pixel values and their corresponding indices and counts
    s_values, bin_idx, s_counts = np.unique(source, return_inverse=True, return_counts=True)
    t_values, t_counts = np.unique(template, return_counts=True)
    s_quantiles = np.cumsum(s_counts).astype(np.float64)
    s_quantiles /= s_quantiles[-1]
    t_quantiles = np.cumsum(t_counts).astype(np.float64)
    t_quantiles /= t_quantiles[-1]
    interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)
    return interp_t_values[bin_idx].reshape(oldshape)

def make_one_hot(labels, num_classes):
    r"""
    Convert int labels to one-hot encoding labels
    :param labels: N x H x W or N x D x H x W shape torch.LongTensor
    :param num_classes: class number control output channel C
    :return: N x C x H x W or N x C x D x H x W
    """
    labels = torch.unsqueeze(labels, dim=1)
    one_hot_shape = list(labels.size())
    one_hot_shape[1] = num_classes
    one_hot = torch.zeros(one_hot_shape).long().to(labels.device)
    return one_hot.scatter_(dim=1, index=labels, value=1)

def save_csv(cfg, file_list, file_name):
    df = pd.DataFrame(np.array(file_list), columns=['file names'])
    df.to_csv(os.path.join(cfg.save_dir, file_name), index=False)

def train_val_test_split(data_list, train_control, val_control, data_stratify=None, random_seed=None):

    def _split_one_group(data_list, train_num, val_num, random_seed=None):
        data_length = len(data_list)
        if random_seed is not None:
            np.random.seed(random_seed)
        ids_seq = np.random.permutation(data_length)
        return data_list[ids_seq[0:train_num]], \
               data_list[ids_seq[train_num:train_num + val_num]], \
               data_list[ids_seq[train_num + val_num:]]

    data_length = len(data_list)
    if type(data_list) != np.ndarray:
        data_list = np.array(data_list)

    train_num = int(math.ceil(train_control * data_length)) if isinstance(train_control, float) else train_control
    val_num = int(math.floor(val_control * data_length)) if isinstance(val_control, float) else val_control

    if data_stratify is None:
        train_list, val_list, test_list = _split_one_group(data_list, train_num, val_num, random_seed)
    else:
        if type(data_stratify) != np.ndarray:
            data_stratify = np.array(data_stratify)
        classes, classes_counts = np.unique(data_stratify, return_counts=True)
        train_ratio = train_control if isinstance(train_control, float) else train_num / data_length
        val_ratio = val_control if isinstance(val_control, float) else val_num / data_length

        train_nums = []
        val_nums = []

        for i in range(len(classes)):
            if i != len(classes) - 1:
                train_nums.append(int(math.ceil(train_ratio * classes_counts[i])))
                val_nums.append(int(math.floor(val_ratio * classes_counts[i])))
            else:
                train_nums.append(train_num - np.asarray(train_nums).sum())
                val_nums.append(val_num - np.asarray(val_nums).sum())

        train_list = np.array([])
        val_list = np.array([])
        test_list = np.array([])
        for i, (t, v) in enumerate(zip(train_nums, val_nums)):

            tmp_train_list, tmp_val_list, tmp_test_list = \
                _split_one_group(data_list[data_stratify == classes[i]], t, v,
                                 random_seed + i * 10 if random_seed is not None else random_seed)
            train_list = np.concatenate((train_list, tmp_train_list))
            val_list = np.concatenate((val_list, tmp_val_list))
            test_list = np.concatenate((test_list, tmp_test_list))

    return train_list.tolist(), val_list.tolist(), test_list.tolist()


"""
Script for labeling purposes

Usage :
    python label_processing.py -d [PATH TO IMAGES FOLDER] [PARAMS]

Parameters:
    -d : Path to the folder where the images is stored
    -l : Lower all labels in xml files.
    -c : Count each label of all the xml files
    -s : Find images with specific label
    -lm : Create label_map.pbtxt
    -ar : Remove xml piles without images

RangRang - Machine Learning - 2021
"""

import os, argparse, glob
import xml.etree.ElementTree as ET

def auto_remove(path):
    """ Menghapus file xml tanpa gambar """
    images = [os.path.splitext(x) for x in os.listdir(path)]
    images = [x for x, y in images]
    for x in set(images):
        if images.count(x) < 2:
            os.remove(os.path.join(path, x + '.xml'))

def make_labelmap(path, export_dir):
    """ Membuat label_map.pbtxt """
    labels = []
    for xml_file in glob.glob(path + '/*.xml'):
        root = ET.parse(xml_file).getroot()
        for member in root.findall('object'):
            if member[0].text not in labels:
                labels.append(member[0].text)

    with open(os.path.join(export_dir, 'label_map.pbtxt'), 'w') as w:
        for i, label in enumerate(labels):
            w.writelines('item {\n    id: ' + str(i + 1) +  "\n    name: '" + label + "'\n}\n\n")
    print(f'[INFO] label_map.pbtxt exported to {export_dir}')

def counter(path):
    """ Menghitung jumlah masing - masing label dari setiap xml file """
    count = {}
    for xml_file in glob.glob(path + '/*.xml'):
        root = ET.parse(xml_file).getroot()
        for member in root.findall('object'):
            if member[0].text in count:
                count[member[0].text] += 1
            else:
                count[member[0].text] = 1

    print('[INFO] Label Counter')
    for i, (key, value) in enumerate(count.items()):
        print(f'  {i + 1}. {key} : {value}')

def search(path, indexs):
    """ Mencari image yang memiliki label tertentu """
    images = {}
    for xml_file in glob.glob(path + '/*.xml'):
        images[os.path.basename(xml_file)] = []
        root = ET.parse(xml_file).getroot()
        for member in root.findall('object'):
            images[os.path.basename(xml_file)].append(member[0].text)

    print('[INFO] Label Finder')
    for label in indexs.split(','):
        print(f' {label} '.center(20, '#'))
        for img in [x for x, y in images.items() if label in y]:
            print(f' - {img}')
        print()

def lower(path):
    """ lowering all label in the xml files """
    for xml_file in glob.glob(path + '/*.xml'):
        root = ET.parse(xml_file).getroot()
        for member in root.findall('object'):
            member[0].text = member[0].text.lower()
        element = ET.tostring(root)

        with open(xml_file, "wb") as w:
            w.write(element)

def UA(path):
    """ lowering all label in the xml files """
    for xml_file in glob.glob(path + '/*.xml'):
        root = ET.parse(xml_file).getroot()
        img_file = list(os.path.splitext(os.path.basename(root.find('filename').text)))
        xml_file_ = list(os.path.splitext(os.path.basename(xml_file)))
        if img_file[0] != xml_file_[0]:
            img_file[0] = xml_file_[0]
            if os.path.isfile(os.path.join(path, img_file[0] + '.jpg')):
                img_file[1] = '.jpg'
            else:
                img_file[1] = '.jpeg'
            img_file = img_file[0] + img_file[1]
            root.find('filename').text = img_file

            print(f'[INFO] Writing {xml_file}')
            element = ET.tostring(root)
            with open(xml_file, "wb") as w:
                w.write(element)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Labeling helper script")
    parser.add_argument("-d",
                        "--img_dir",
                        help="Path to the folder where the images is stored.",
                        type=str)
    parser.add_argument("-l",
                        "--to_lower",
                        help="Lower all labels in xml files.",
                        action='store_true')
    parser.add_argument("-c",
                        "--counter",
                        help="Count each label of all the xml files",
                        action='store_true')
    parser.add_argument("-s",
                        "--search",
                        help="Find images with specific label",
                        type=str)
    parser.add_argument("-lm",
                        "--label_map",
                        help="Create label_map.pbtxt",
                        type=str)
    parser.add_argument("-ar",
                        "--auto_remove",
                        help="Delete xlm files without img",
                        action='store_true')
    parser.add_argument("-ua",
                        "--update_annotation",
                        help="Update annotation",
                        action='store_true')

    args = parser.parse_args()

    if args.img_dir is None:
        raise KeyError('Harus menyertakan -d argument atau folder dimana images disimpan')

    if args.to_lower:
        lower(args.img_dir)

    if args.counter:
        counter(args.img_dir)

    if args.search:
        search(args.img_dir, args.search)

    if args.label_map:
        make_labelmap(args.img_dir, args.label_map)

    if args.auto_remove:
        auto_remove(args.img_dir)

    if args.update_annotation:
        UA(args.img_dir)


from django.contrib import auth
from django.core.exceptions import ObjectDoesNotExist

from .models import Member

class EcosystemActivityMiddleware:
    EXTENSIONS_EXCLUDED = ['js', 'map', 'css']
    PATHS_EXCLUDED = ['/api/graphql-jwt']

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

    def __call__(self, request):
        user = self._get_user(request)
        if user.is_authenticated and \
                request.method in ['POST', 'PUT', 'DELETE']:

            try:
                member = Member.objects.get(user=user)
                member.update_activity()
            except ObjectDoesNotExist:
                pass

        return self.get_response(request)

    def _get_user(self, request):
        if not hasattr(request, '_cached_user'):
            request._cached_user = auth.get_user(request)
        return request._cached_user


#
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#

# @lc code=start
# Definition for singly-linked list.
from typing import Optional

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

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        while head and head.next:
            left = head
            right = head.next
            pre.next = right
            left.next = right.next
            right.next = left
            pre = left
            head = pre.next
        if head:
            pre.next = head

        return dummy.next

# @lc code=end


from flask import Flask, render_template, request, redirect
import datetime

app=Flask(__name__)

messages=[]

@app.route('/')
def index():
    return render_template("index.html.jinja2", messages=messages)

@app.route('/post/add/', methods=['POST'])
def add_message():
    text = request.form.get('message')
    timestamp = datetime.datetime.now()
    messages.append({'text': text, 'timestamp': timestamp})
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)