# Self-supervised Spatiotemporal Learning via Video Clip Order Prediction
import torch
import numpy as np
import math
import itertools

def order_class_index(order):
    """Return the index of the order in its full permutation.

    Args:
        order (tensor): e.g. [0,1,2]
    """
    classes = list(itertools.permutations(list(range(len(order)))))
    return classes.index(tuple(order.tolist()))

def train(args, model, criterion, optimizer, device, train_dataloader, writer, epoch):
    torch.set_grad_enabled(True)
    model.train()

    running_loss = 0.0
    correct = 0
    if args.use_clip:
        tag = 'clip'
    elif args.use_front:
        tag = 'front'
    elif args.use_360:
        tag = '360'
    print("Start training...")

    target_list = []
    pred_list = []

    for i, data in enumerate(train_dataloader, 1):
        # get inputs
        if args.dataset == '360x':
            tuple_orders = data[tag]["order"]
        else:
            tuple_clips, tuple_orders = data

        # inputs = tuple_clips.to(device)
        targets = [order_class_index(order) for order in tuple_orders]
        targets = torch.tensor(targets).to(device)

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward and backward
        outputs = model(data) # return logits here
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()
        # compute loss and acc
        running_loss += loss.item()

        pts = torch.argmax(outputs, dim=1)
        correct += torch.sum(targets == pts).item()

        target_list.extend(targets.cpu().detach().numpy())
        pred_list.extend(pts.cpu().detach().numpy())

        # print statistics and write summary every N batch
        if i % args.pf == 0:
            avg_loss = running_loss / args.pf
            p = np.asarray(pred_list).flatten()

            print("pred_list:", pred_list)

            avg_acc = np.sum(target_list == p)/p.shape[0]
            target_list = []
            pred_list = []

            # avg_acc = # correct / (args.pf * args.bs)
            print('[TRAIN] epoch-{}, batch-{}, loss: {:.3f}, acc: {:.3f}'.format(epoch, i, avg_loss, avg_acc))
            step = (epoch -1 ) *len(train_dataloader) + i
            writer.add_scalar('train/CrossEntropyLoss', avg_loss, step)
            writer.add_scalar('train/Accuracy', avg_acc, step)
            running_loss = 0.0
            correct = 0

    # summary params and grads per eopch
    for name, param in model.named_parameters():
        try:
            writer.add_histogram('params/{}'.format(name), param, epoch)
            writer.add_histogram('grads/{}'.format(name), param.grad, epoch)
        except:
            pass

def validate(args, model, criterion, device, val_dataloader, writer, epoch):
    torch.set_grad_enabled(False)
    model.eval()

    total_loss = 0.0
    correct = 0
    if args.use_clip:
        tag = 'clip'
    elif args.use_front:
        tag = 'front'
    elif args.use_360:
        tag = '360'

    target_list = []
    pred_list = []
    for i, data in enumerate(val_dataloader):
        # get inputs
        if args.dataset == '360x':
            tuple_orders = data[tag]["order"]

        else:
            tuple_clips, tuple_orders = data

        # inputs = tuple_clips.to(device)
        targets = [order_class_index(order) for order in tuple_orders]
        targets = torch.tensor(targets).to(device)

        # forward
        outputs = model(data) # return logits here
        loss = criterion(outputs, targets)
        # compute loss and acc
        total_loss += loss.item()

        pts = torch.argmax(outputs, dim=1)
        correct += torch.sum(targets == pts).item()

        target_list.extend(targets.cpu().detach().numpy())
        pred_list.extend(pts.cpu().detach().numpy())
        # print('correct: {}, {}, {}'.format(correct, targets, pts))

    target_list = np.asarray(target_list).flatten()
    pred_list = np.asarray(pred_list).flatten()

    print("pred_list:", pred_list)

    avg_loss = total_loss / len(val_dataloader)

    avg_acc = np.sum(target_list == pred_list)/pred_list.shape[0] #correct / len(val_dataloader.dataset)

    writer.add_scalar('val/CrossEntropyLoss', avg_loss, epoch)
    writer.add_scalar('val/Accuracy', avg_acc, epoch)

    print('[VAL] loss: {:.3f}, acc: {:.3f}'.format(avg_loss, avg_acc))

    return avg_loss

def test(args, model, criterion, device, test_dataloader):
    torch.set_grad_enabled(False)
    model.eval()

    total_loss = 0.0
    correct = 0
    if args.use_clip:
        tag = 'clip'
    elif args.use_front:
        tag = 'front'
    elif args.use_360:
        tag = '360'

    for i, data in enumerate(test_dataloader, 1):
        # get inputs
        if args.dataset == '360x':
            tuple_clips = data[tag]["f"]
            tuple_orders = data[tag]["order"]
        else:
            tuple_clips, tuple_orders = data

        inputs = tuple_clips.to(device)
        targets = [order_class_index(order) for order in tuple_orders]
        targets = torch.tensor(targets).to(device)
        # forward
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        # compute loss and acc
        total_loss += loss.item()
        pts = torch.argmax(outputs, dim=1)
        correct += torch.sum(targets == pts).item()
        # print('correct: {}, {}, {}'.format(correct, targets, pts))
    avg_loss = total_loss / len(test_dataloader)
    avg_acc = correct / len(test_dataloader.dataset)
    print('[TEST] loss: {:.3f}, acc: {:.3f}'.format(avg_loss, avg_acc))
    return avg_loss


from sys import stdin

f = {}
def fib(n):
    global f
    if n in f: # if F(n) was computed before
        return f[n]

    # if F(n) was not computed before
    if n <= 1:
        f[n] = n
    else:
        f[n] = fib(n-1) + fib(n-2)
    return f[n]

def main():
    """Reads a user-specified non-negative integer n,
    and then prints the n-th Fibonacci number F(n)."""

    n = int(stdin.readline())
    print(f"F({n}) = {fib(n)}")

if __name__ == "__main__":
    print(main.__doc__)
    main()


#!/usr/bin/env python

from runtest import TestBase

class TestCase(TestBase):
    def __init__(self):
        TestBase.__init__(self, 'sort', """
# Function Call Graph for 'main' (session: 6085c5f021e501d0)
=============== BACKTRACE ===============
 backtrace #0: hit 1, time  10.321 ms
   [0] main (0x4004a0)

========== FUNCTION CALL GRAPH ==========
(1) main
 +-(2) foo
 | (6) loop
 |
 +-(1) bar
   (1) usleep

""", sort='graph')

    def prepare(self):
        self.subcmd = 'record'
        return self.runcmd()

    def setup(self):
        self.subcmd = 'graph'
        self.option = '-f none'
        self.exearg = 'main'


#!/usr/bin/python3
"""Unit test for the module Review"""

import unittest
from models.review import Review
from models import storage

class Test_Review(unittest.TestCase):
    """Test for the class Review"""
    instance = Review()
    instance.place_id = '2886'
    instance.user_id = "User Ana"
    instance.text = "The best hotel"

    data_base = storage.all()
    instance_name = 'Review.' + instance.id

    def test_reviewinit(self):
        """Test for the method __init__"""
        features = self.data_base.get(self.instance_name).to_dict()
        mb = "<class 'models.review.Review'>"
        d = "<class 'datetime.datetime'>"

        # Data types
        self.assertEqual(str(type(self.instance)), mb)
        self.assertEqual(str(type(self.instance.id)), "<class 'str'>")
        self.assertEqual(str(type(self.instance.created_at)), d)
        self.assertEqual(str(type(self.instance.updated_at)), d)

        # Basic features storage
        self.assertIn(self.instance_name, self.data_base.keys())
        self.assertIn('created_at', features.keys())
        self.assertIn('updated_at', features.keys())
        self.assertIn('id', features.keys())
        self.assertIn('place_id', features.keys())
        self.assertIn('user_id', features.keys())
        self.assertIn('text', features.keys())

        test_dict = {"id": "fy02d7e0-4254-43b3-b867-d9decb0dda13",
                     "created_at": "2021-06-28T17:47:38.773238",
                     "updated_at": "2021-06-28T17:47:38.773248",
                     "__class__": "Review",
                     "place_id": "Hotel Perrito",
                     "user_id": "Dalisaurio",
                     "text": "123456"}

        instance2 = Review(**test_dict)

        self.assertIsInstance(instance2, Review)
        self.assertEqual(instance2.id, "fy02d7e0-4254-43b3-b867-d9decb0dda13")
        self.assertEqual(instance2.place_id, "Hotel Perrito")
        self.assertEqual(instance2.user_id, "Dalisaurio")
        self.assertEqual(instance2.text, "123456")

    def test_reviewstr(self):
        """Test for the method __str__"""
        cs = '[Review] ({}) {}'.format(
            self.instance.id, self.instance.__dict__)
        my_string = self.instance.__str__()
        self.assertEqual(cs, my_string)

    def test_reviewsave(self):
        """Test for the method save"""
        dateofupdate = self.instance.updated_at
        self.instance.save()
        new_date = self.instance.updated_at
        self.assertNotEqual(dateofupdate, new_date)

    def test_reviewtodict(self):
        """Test for the method to_dict"""
        type_of_dict = str(type(self.instance.to_dict()))
        self.assertEqual(type_of_dict, "<class 'dict'>")
        self.assertIn(self.instance_name, self.data_base.keys())

if __name__ == '__main__':
    unittest.main()


"""Unit tests for utils.py"""

from unittest.mock import MagicMock

import numpy as np
import pytest

from utils import detect_horizon_line

class TestDetectHorizonLine():
    """Test detect_horizon_line"""

    @pytest.fixture(scope='class')
    def image_closed1(self):
        """image_closed1 object fixture

        This is used to test the final couple lines of code in
        `detect_horizon_line`, which finds the y-coordinates of the horizon
        line based off of the location of the max index holding a 0 value in
        the first / last column of the image (i.e. the first and last possible
        x-position). The image returned here should result in y-coordinates of
        (31, 15) being returned.
        """

        image_closed1 = np.ones((64, 48))
        image_closed1[:32, :] = 0
        image_closed1[16:, 47] = 1

        return image_closed1

    def test_detect_horizon_line(self, image_closed1, monkeypatch):
        """Test detect_horizon_line

        This tests two big things:
        - The flow of inputs / outputs through operations in
          `detect_horizon_line` is as expected (e.g. the output of the gaussian
          blur operation is passed to the threshold operation)
        - The returned (x1, x2, y1, y2) coordinates denoting the horizon are
          as expected

        :param image_closed1: image_closed1 object fixture
        :type image_closed1: np.ndarray
        """

        mock_blur = MagicMock()
        mock_blur.return_value = 'blur_return'
        monkeypatch.setattr('utils.cv2.GaussianBlur', mock_blur)

        mock_threshold = MagicMock()
        mock_threshold.return_value = (
            'threshold_return1', 3
        )
        monkeypatch.setattr('utils.cv2.threshold', mock_threshold)

        mock_morphology = MagicMock()
        mock_morphology.return_value = image_closed1
        monkeypatch.setattr('utils.cv2.morphologyEx', mock_morphology)

        image_grayscale = np.ones_like(image_closed1)
        horizon_x1, horizon_x2, horizon_y1, horizon_y2 = (
            detect_horizon_line(image_grayscale)
        )

        assert horizon_x1 == 0
        assert horizon_x2 == 47
        assert horizon_y1 == 31
        assert horizon_y2 == 15


import copy
import os

import pytorch_lightning as pl
from pytorch_lightning.strategies.ddp import DDPStrategy
from pytorch_lightning.loggers import TensorBoardLogger

from reinforce.config_reinforce import ex

from predictor.config_predictor import config as predictor_config
from predictor.config_predictor import _loss_names
from predictor.module import Predictor

from generator.config_generator import config as generator_config
from generator.datamodule import GeneratorDatamodule
from generator.module import Generator

from reinforce.module import Reinforce

@ex.automain
def main(_config):
    pl.seed_everything(_config["seed"])
    # 1. load predictor
    predictors = []
    for i in range(len(_config["predictor_load_path"])):
        pred_config = predictor_config()
        pred_config["test_only"] = True
        pred_config["loss_names"] = _loss_names({"regression": 1})
        pred_config["load_path"] = _config["predictor_load_path"][i]
        pred_config["mean"] = _config["mean"][i]
        pred_config["std"] = _config["std"][i]

        predictor = Predictor(pred_config)
        predictor.eval()
        predictors.append(predictor)

    # 2. load generator
    gen_config = generator_config()
    gen_config["load_path"] = _config["generator_load_path"]
    gen_config["batch_size"] = _config["batch_size"]
    gen_config["dataset_dir"] = _config["dataset_dir"]

    generator = Generator(gen_config)
    dm = GeneratorDatamodule(gen_config)

    # 3. set reinforce
    _config = copy.deepcopy(_config)
    pl.seed_everything(_config["seed"])

    model = Reinforce(generator, predictors, _config)

    exp_name = f"{_config['exp_name']}"
    os.makedirs(_config["log_dir"], exist_ok=True)
    checkpoint_callback = pl.callbacks.ModelCheckpoint(
        save_top_k=-1,
        verbose=True,
        monitor="val/total_reward",
        mode="max",
        save_last=True,
    )

    logger = pl.loggers.TensorBoardLogger(
        _config["log_dir"],
        name=f'{exp_name}_seed{_config["seed"]}_from_{_config["load_path"].split("/")[-1][:-5]}',
    )
    lr_callback = pl.callbacks.LearningRateMonitor(logging_interval="step")
    callbacks = [checkpoint_callback, lr_callback]

    trainer = pl.Trainer(
        accelerator="gpu",
        devices=_config["devices"],
        num_nodes=_config["num_nodes"],
        precision=_config["precision"],
        deterministic=True,
        strategy=DDPStrategy(find_unused_parameters=True),
        max_epochs=_config["max_epochs"],
        callbacks=callbacks,
        logger=logger,
        accumulate_grad_batches=_config["accumulate_grad_batches"],
        log_every_n_steps=10,
        resume_from_checkpoint=_config["resume_from"],
        limit_train_batches=_config["limit_train_batches"],
        limit_val_batches=_config["limit_val_batches"],
        num_sanity_val_steps=_config["limit_val_batches"],
        val_check_interval=_config["val_check_interval"],
        gradient_clip_val=_config["gradient_clip_val"],
    )

    if not _config["test_only"]:
        trainer.fit(model, datamodule=dm)
        # trainer.test(model, datamodule=dm)
    else:
        trainer.test(model, datamodule=dm)


with open("day10.txt") as f:
    data = [x.strip() for x in f.readlines()]

points = {")": 3, "]": 57, "}": 1197, ">": 25137}
opening = ["(", "[", "{", "<"]
closing = [")", "]", "}", ">"]
pairs = {"(": ")", "[": "]", "{": "}", "<": ">"}

incomplete_lines = list()

score = 0

for i in data:
    instruction = list()
    for j in i:
        if j in opening:
            instruction.append(j)
        elif j in closing:
            if j == ")" and instruction[-1] == "(":
                instruction.pop()
            elif j == "]" and instruction[-1] == "[":
                instruction.pop()
            elif j == "}" and instruction[-1] == "{":
                instruction.pop()
            elif j == ">" and instruction[-1] == "<":
                instruction.pop()
            else:
                score += points[j]
                break
    incomplete_lines.append(instruction)

print("Part 1:", score)

points = {"(": 1, "[": 2, "{": 3, "<": 4}

scores = list()
for i in incomplete_lines:
    score = 0
    for j in i[::-1]:
        score *= 5
        score += points[j]
    scores.append(score)

scores.sort()
score = scores[(len(scores)) // 2]

print("Part 2:", score)


import json
from typing import Generator, List, Optional

import arrow
import attr
import deserialize

from fractal_python.api_client import (
    ApiClient,
    _arrow_or_none,
    _call_api,
    _get_paged_response,
)
from fractal_python.banking.api import BANKING_ENDPOINT

banks_endpoint = BANKING_ENDPOINT + "/banks"
consents = "consents"

@attr.s(auto_attribs=True)
@deserialize.auto_snake()
class Bank:
    r"""Bank.

    :attr id: unique id of the bank
    :attr name: name of the bank
    :attr logo: bank logo
    :attr logo_url: url to logo
    """
    id: int
    name: str
    logo: Optional[str]
    logo_url: Optional[str]

def new_bank(
    bank_id: int,
    name: str,
    logo: str = None,
    logo_url: str = None,
) -> Bank:
    r"""Make a new Bank object.

    :param bank_id: unique id of the bank
    :type bank_id: int
    :param name: name of the bank
    :type name: str
    :param logo: logo
    :type logo: str
    :param logo_url: url to the logo
    :type logo_url: str
    :return: new Bank object
    :rtype: Bank
    """
    return Bank(bank_id, name, logo, logo_url)

def retrieve_banks(client: ApiClient) -> Generator[List[Bank], None, None]:
    r"""Retrieve all banks.

    :param client: the client to use for the api call
    :type client: ApiClient
    :yield: Page of Banks
    :rtype: Generator[List[Bank], None, None]

    Usage::

      >>> banks =[x for y in banking.retrieve_banks(client) for x in y]
    """
    yield from _get_paged_response(
        client=client, url=banks_endpoint, cls=Bank, param_keys=None, company_id=None
    )

@attr.s(auto_attribs=True)
@deserialize.auto_snake()
class CreateBankConsentResponse:
    r"""Response for a CreateBankConsent call.

    :attr signin_url: URL user will sign in to bank at
    :attr consent_id: unique id of the consent
    :attr bank_id: unique id of the bank
    :attr type: type of consent
    :attr permission: permissions available
    """
    signin_url: str
    consent_id: str
    bank_id: int
    type: str
    permission: str

def create_bank_consent(
    client: ApiClient, bank_id: int, redirect: str, company_id: str
) -> CreateBankConsentResponse:
    r"""Create a bank consent.

    This is the first step in connecting an account.

    :param client: the client to use for the api call
    :type client: ApiClient
    :param bank_id: the unique id of the bank
    :type bank_id: int
    :param redirect: the urk to redirect the account owner to
    :type redirect: str
    :param company_id: the unique id of the company
    :type company_id: str
    :return: response from the bank
    :rtype: CreateBankConsentResponse
    """
    response = _call_api(
        client=client,
        url=f"{banks_endpoint}/{bank_id}/{consents}",
        method="POST",
        company_id=company_id,
        data=json.dumps(dict(redirect=redirect)),
    )
    json_response = json.loads(response.text)
    bank_consent_response = deserialize.deserialize(
        CreateBankConsentResponse, json_response
    )
    return bank_consent_response

@attr.s(auto_attribs=True)
@deserialize.auto_snake()
@deserialize.parser("expiry_date", _arrow_or_none)
@deserialize.parser("date_created", _arrow_or_none)
@deserialize.parser("authorised_date", _arrow_or_none)
class BankConsent:
    r"""Bank Consent for company.

    :attr company_id: unique identifier for the company
    :attr permission: permissions given by account owner
    :attr expiry_date: consent may expire
    :attr consent_id: unique id for this consent
    :attr bank_id: unique id of the bank
    :attr date_created: when this consent was created
    :attr authorised_date: when the consent was last authorised
    :attr consent_type: type of consent
    :attr status: status of consent
    """
    company_id: str
    permission: str
    expiry_date: Optional[arrow.Arrow]
    consent_id: str
    bank_id: int
    date_created: arrow.Arrow
    authorised_date: Optional[arrow.Arrow]
    consent_type: str
    status: str

def retrieve_bank_consents(
    client: ApiClient, bank_id: int, company_id: Optional[str] = None
) -> Generator[List[BankConsent], None, None]:
    r"""Retrieve consents by bank id and company id.

    :param client: the client to use for the api call
    :type client: ApiClient
    :param bank_id: the id of the bank to filter on
    :type bank_id: int
    :param company_id: the id of the company to filter on, defaults to None
    :type company_id: str, optional
    :yield: Page of Bank Consents
    :rtype: Generator[List[BankConsent], None, None]
    """
    url = f"{banks_endpoint}/{bank_id}/{consents}"
    yield from _get_paged_response(
        client=client, url=url, cls=BankConsent, param_keys=[], company_id=company_id
    )

def put_bank_consent(
    client: ApiClient,
    code: str,
    id_token: str,
    state: str,
    bank_id: int,
    consent_id: str,
    company_id: str,
):
    r"""Put a Bank Consent for a Company.

    Call this after user has been redirected back from the bank.

    :param client: the client to use for the api call
    :type client: ApiClient
    :param code: to be exchanged for access token with the bank
    :type code: str
    :param id_token: base64 encoded JSON for verifying
    :type id_token: str
    :param state: base64b encoded JSON to persist the state
    :type state: str
    :param bank_id: the id of the bank to filter on
    :type bank_id: int
    :param consent_id: id returned from create_bank_consent
    :type consent_id: str
    :param company_id:  the id of the company
    :type company_id: str
    :raises AssertionError: When response code not 204
    """
    payload = {"code": code, "id_token": id_token, "state": state}
    response = _call_api(
        client,
        f"{banks_endpoint}/{bank_id}/{consents}/{consent_id}",
        "PUT",
        company_id=company_id,
        data=json.dumps(payload),
    )
    if response.status_code != 204:
        raise AssertionError(f"status_code:{response.status_code} {response.text}")

def delete_bank_consent(
    client: ApiClient,
    bank_id: int,
    consent_id: str,
    company_id: str,
):
    r"""Delete a bank consent.

    Use this when a bank account owner wants to disconnect their account.

    :param client: the client to use for the api call
    :type client: ApiClient
    :param bank_id: the id of the bank to filter on
    :type bank_id: int
    :param consent_id: id returned from create_bank_consent
    :type consent_id: str
    :param company_id:  the id of the company
    :type company_id: str
    :raises AssertionError: When response code not 202
    """
    response = _call_api(
        client,
        f"{banks_endpoint}/{bank_id}/{consents}/{consent_id}",
        "DELETE",
        company_id=company_id,
    )
    if response.status_code != 202:
        raise AssertionError(f"status_code:{response.status_code} {response.text}")


import matplotlib.pyplot as plt
import src.features.helpers_vis as hp_vis
import src.features.helpers as hp
import logging
import pickle
from pathlib import Path
import numpy as np
import click

hp_vis.set_layout(15)

ROOT = Path(__file__).resolve().parents[3]

SOUND_FILES = ROOT / 'data/raw/sound_samples/'
# create a list of the sound files
SOUND_FILES = list(SOUND_FILES.glob('**/*.wav'))

# Parameters
@click.command()
@click.option('--save_figs', type=click.BOOL, default=False, help='Save figures')
@click.option('--save_type', default='svg', help='Define the format figures are saved.')
@click.option('--model_name', default='parameter_sweep', help='Defines the model name.')
@click.option('--exp_name', default='default', help='Defines the experiment name')
@click.option('--azimuth', default=12, help='Azimuth for which localization is done. Default is 12')
@click.option('--snr', default=0.2, help='Signal to noise ration to use. Default is 0.2')
@click.option('--freq_bands', default=128, help='Amount of frequency bands to use. Default is 128')
@click.option('--max_freq', default=20000, help='Max frequency to use. Default is 20000')
@click.option('--elevations', default=25, help='Number of elevations to use 0-n. Default is 25 which equals 0-90 deg')
@click.option('--mean_subtracted_map', default=True, help='Should the learned map be mean subtracted. Default is True')
@click.option('--ear', default='contra', help='Which ear should be used, contra or ipsi. Default is contra')
@click.option('--normalization_type', default='sum_1', help='Which normalization type should be used sum_1, l1, l2. Default is sum_1')
@click.option('--clean', is_flag=True)
def main(save_figs=False, save_type='svg', model_name='parameter_sweep', exp_name='default', azimuth=12, snr=0.2, freq_bands=128, max_freq=20000, elevations=25, mean_subtracted_map=True, ear='ipsi', normalization_type='sum_1', clean=False):

    logger = logging.getLogger(__name__)
    logger.info('Showing parameter sweep results')

    ########################################################################
    ######################## Set parameters ################################
    ########################################################################

    # make sure save type is given
    if not save_type or len(save_type) == 0:
        save_type = 'svg'

    normalize = False
    time_window = 0.1  # time window in sec

    elevations = np.arange(0, elevations, 1)

    ########################################################################
    ########################################################################

    # create unique experiment name
    exp_name_str = hp.create_exp_name([exp_name, normalization_type, mean_subtracted_map, time_window, int(
        snr * 100), freq_bands, max_freq, (azimuth - 12) * 10, normalize, len(elevations), ear])

    exp_path = ROOT / 'models' / model_name
    exp_file = exp_path / exp_name_str
    # check if model results exist already and load
    if exp_path.exists() and exp_file.is_file():
        # try to load the model files
        with open(exp_file.as_posix(), 'rb') as f:
            logger.info('Reading model data from file')
            [scores,sigma_smoothing_vals,sigma_gauss_norm_vals] = pickle.load(f)

        fig = plt.figure(figsize=(20, 5))
        axes = fig.subplots(1,3,sharex=True,sharey=True)
        ax = axes[0]
        p = ax.pcolormesh(sigma_smoothing_vals, sigma_gauss_norm_vals, np.squeeze(scores[:, :, 0]),linewidth=0,rasterized=True)
        p.set_edgecolor('face')
        ax.set_xlabel(r'Gauss Normalization $\sigma$')
        ax.set_ylabel(r'Smoothing $\sigma$')
        # ax.set_title('Gain')
        cbar = plt.colorbar(p,ax=ax)
        cbar.set_label('Gain', rotation=270)
        cbar.ax.get_yaxis().labelpad = 15

        ax = axes[1]
        p = ax.pcolormesh(sigma_smoothing_vals, sigma_gauss_norm_vals, np.squeeze(scores[:, :, 1]),linewidth=0,rasterized=True)
        p.set_edgecolor('face')
        ax.set_xlabel(r'Gauss Normalization $\sigma$')
        # ax.set_ylabel('Smoothing Sigma')
        # ax.set_title('Bias')
        cbar = plt.colorbar(p,ax=ax)
        cbar.set_label('Bias', rotation=270)
        cbar.ax.get_yaxis().labelpad = 15

        ax = axes[2]
        p = ax.pcolormesh(sigma_smoothing_vals, sigma_gauss_norm_vals, np.squeeze(scores[:, :, 2]),linewidth=0,rasterized=True)
        p.set_edgecolor('face')
        ax.set_xlabel(r'Gauss Normalization $\sigma$')
        # ax.set_ylabel('Smoothing Sigma')
        # ax.set_title('Score')
        cbar = plt.colorbar(p,ax=ax)
        cbar.set_label('Score', rotation=270)
        cbar.ax.get_yaxis().labelpad = 15

        plt.tight_layout()

        if save_figs:
            exp_name_str = hp.create_exp_name([exp_name, normalization_type, 0, 1, mean_subtracted_map, time_window, int(
            snr * 100), freq_bands, max_freq, (azimuth - 12) * 10, normalize, len(elevations), ear])
            fig_save_path = ROOT / 'reports' / 'figures' / exp_name_str / model_name
            if not fig_save_path.exists():
                fig_save_path.mkdir(parents=True, exist_ok=True)
            logger.info('Saving figures to ' + fig_save_path.as_posix())
            plt.savefig((fig_save_path / (model_name + '_' + exp_name + '_sweep.' + save_type)).as_posix(), dpi=300)
        else:
            plt.show()
    else:
        logger.error('No data set found. Run model first!')
        logger.error(exp_file)

if __name__ == '__main__':
    log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(level=logging.INFO, format=log_fmt)

    main()


from flask import render_template, redirect, request
from flask_app import app
from flask_app.models.orders import Order

@app.route('/cookies')
def r_cookies():
    orders = Order.get_all_orders()
    return render_template('cookies.html', orders=orders)

@app.route('/cookies/new')
def r_cookies_new():
    return render_template('new_order.html')

@app.route('/cookies/placeorder', methods=['POST'])
def f_cookies_new():
    inbound = request.form
    data = {
        'name': inbound['order_name'],
        'cookie_type': inbound['cookie_type'],
        'number_of_boxes': inbound['number_of_boxes']
    }

    if not Order.validate_order(inbound):
        return redirect('/cookies/new')

    Order.add_new_order(data)
    return redirect('/cookies')

@app.route('/cookies/edit/<int:id>')
def r_cookies_edit(id):
    data = {
        'id' : id
    }
    order = Order.get_one_order(data)
    return render_template('edit_order.html', order=order)

@app.route('/cookies/editorder', methods=['POST'])
def f_cookies_edit():
    inbound = request.form
    stored_id = inbound['id']
    data = {
        'id' : stored_id,
        'name' : inbound['order_name'],
        'cookie_type': inbound['cookie_type'],
        'number_of_boxes': inbound['number_of_boxes']
    }
    if not Order.validate_order(inbound):
        return redirect(f'/cookies/edit/{stored_id}')

    Order.update_order(data)
    return redirect('/cookies')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 19 12:15:08 2023

@author: aaa
"""

import os
import numpy as np
import shutil
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib.gridspec import GridSpec
plt.rcParams.update({'figure.max_open_warning': 0})
from PIL import Image as im
from scipy.optimize import curve_fit as fit
import warnings
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)

w_ps=8.002

a1=1/5**0.5
a2=2*a1
a21=2
def exp_w1p(x,x0):
    return alpha*((1/(1+a21*np.exp(-1j*(w_ps*(x-x0)))))).real

def fit_cos(x,A,B,C,D):
    return A+B*np.cos(C*x-D)

def I_px_co(beta, chi, C, alpha, gamma):
    d=((alpha+beta)**2+gamma**2)**0.5
    e=(beta**2+gamma**2)**0.5
    return C*((a1*np.cos(d/2))**2+(a2*np.cos(e/2))**2+2*a1*a2*np.cos(d/2)*np.cos(e/2)*np.cos(chi))/4

def I_px_in(beta, chi, eta, alpha, gamma):
    d=((alpha+beta)**2+gamma**2)**0.5
    e=(beta**2+gamma**2)**0.5
    return eta*(np.cos(d/2)**2+(a2/a1)**2*np.cos(e/2)**2)/4

def I_mx_co(beta, chi, C, alpha, gamma):
    d=((alpha+beta)**2+gamma**2)**0.5
    e=(beta**2+gamma**2)**0.5
    r=np.arctan(gamma/beta)
    p=np.arctan(gamma/(beta+gamma))
    return C*((a1*np.sin(d/2))**2+(a2*np.sin(e/2))**2+2*a1*a2*np.sin(d/2)*np.sin(e/2)*np.cos(chi+r-p))/4

def I_mx_in(beta, chi, eta, alpha, gamma):
    d=((alpha+beta)**2+gamma**2)**0.5
    e=(beta**2+gamma**2)**0.5
    return eta*(np.sin(d/2)**2+(a2/a1)**2*np.sin(e/2)**2)/4
beta=0
g=np.linspace(-np.pi/2,np.pi/2,100)
c=np.linspace(-2*np.pi,2*np.pi,25)
alpha=np.pi/2

def I_px(x, gamma0, chi0, C, eta):
    gamma=g-gamma0
    chi=c-chi0
    gamma, chi = np.meshgrid(gamma, chi)
    fit_I_px=I_px_co(beta, chi, C, alpha, gamma) #+ I_px_in(0, chi, eta, alpha, gamma)
    return fit_I_px

def I_mx(x, gamma0, chi0, C, eta):
    gamma=g-gamma0
    chi=c-chi0
    gamma, chi = np.meshgrid(gamma, chi)
    fit_I_mx=I_mx_co(beta, chi, C, alpha, gamma) #+ I_mx_in(0, chi, eta, alpha, gamma)
    return fit_I_mx

p=[0,0,1,0]
# beta = exp_w1p(c[i], 0)
Z= I_px(0,*p)
# Z0= I_px(0,0,0,1,0)
# Z2p= I_px(0,2*np.pi,0,1,0.2)
# Z= (I_px(0,*p)-I_mx(0,*p))/(I_px(0,*p)+I_mx(0,*p))

# fig = plt.figure(figsize=(10,10))
# ax = plt.axes(projection='3d')
# x, y = np.meshgrid(g, c)
# ax.contour3D(x, y, Z, 30, cmap='plasma')#cmap='Blues')
# ax.set_xlabel('$\\gamma$')
# ax.set_ylabel('$\chi$')
# ax.set_zlabel('z')
# ax.view_init(40, 45)
wg=np.zeros((len(c)))
for i in range(len(c)):
    fig = plt.figure(figsize=(5,5))
    ax = fig.add_subplot(111)
    ax.set_title(str(c[i]))
    ax.plot(g,Z[0])
    ax.vlines(0,0,np.amax(Z[0]))
    ax.plot(g,Z[i])
    # ax.set_ylim([0,0.05])
    # ax.set_xlim([2.5,5])
    # ax.plot(g,g*0+1)
#     wg[i]=Z2p[i,0]-Z0[i,0]

# fig = plt.figure(figsize=(5,5))
# ax = fig.add_subplot(111)
# ax.plot(c,g)
plt.show()

Grenoble 1st round/Scripts/Imperfect interferometer sim.py


import os
import argparse
import glob
from pathlib import Path
import pickle
import random
import statistics

import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics

import misc
import copy

# ——————————————————————————————————————————————————————————————————————

def get_label_from_filename(x):
  if x.startswith(('BM_spin', 'ext_benign')):
    return 'benign'
  elif x.startswith(('MM_sarc', 'boston_meso')):
    return 'tumor'

label_to_value = {'benign': 0.,
                  'tumor': 1.}

def get_value_from_filename(x):
  label = get_label_from_filename(x)
  return label_to_value[label]

def np_to_str(x):
  return np.array_str(x)[1:-1]

def print_run_separator(idx):
  print('\n===============================================================')
  print('RUN {}'.format(idx))

def print_predictions(preds, labels, cases):
  print('\nTest predictions:')
  for i in range(len(preds)):
    print('{}:\t{:.03}\t({})'.format(cases[i], preds[i], int(labels[i])) )

def plot_roc_curve_test(preds, labels, folder=None, test_set=None):
  preds = preds.flatten()
  labels = labels.flatten()
  labels.astype('int')
  fpr, tpr, _ = metrics.roc_curve(labels, preds)
  plt.title('Receiver Operating Characteristic')
  plt.plot(fpr, tpr,)
  plt.xlim([-0.01, 1.])
  plt.ylim([0, 1.01])
  plt.ylabel('True Positive Rate')
  plt.xlabel('False Positive Rate')
  if folder:
    save_path=os.path.join(folder, test_set + '.png')
    plt.savefig(save_path)
    print('saved AUC curve as:', save_path)

def plot_roc_curve_crossval(preds, labels, folder=None):
  plt.title('Receiver Operating Characteristic')
  for i,_ in enumerate(preds):
    run_preds = preds[i].flatten()
    run_labels = labels[i].flatten()
    run_labels.astype('int')
    fpr, tpr, _ = metrics.roc_curve(run_labels, run_preds)
    plt.plot(fpr, tpr, label='Cross-val run {}'.format(i+1))
  plt.legend(loc = 'lower right')
  plt.xlim([-0.01, 1.])
  plt.ylim([0, 1.01])
  plt.ylabel('True Positive Rate')
  plt.xlabel('False Positive Rate')
  if folder:
    save_path=os.path.join(folder, 'crossval.png')
    plt.savefig(save_path)
    print('saved AUC curve as:', save_path)

# ——————————————————————————————————————————————————————————————————————

class EvaluatePredictions():
  def __init__(self, preds, labels, threshold=0.99, print_output=True,
               n_iter=1000):
    if type(preds) is np.ndarray:
      self.preds = preds.flatten().tolist()
    else:
      self.preds = preds
    if type(labels) is np.ndarray:
      self.labels = labels.flatten().tolist()
    else:
      self.labels = labels
    self.threshold = threshold
    self.print_output = print_output
    self.n_iter = n_iter
    self.size = len(preds)

  def sample(self, list_):
    # Following three rules:
    #    1. Sampling with replacement
    #    2. Equal probability for all samples
    #    3. Same size as original list
    if type(list_) is np.ndarray:
      sample_ = np.random.choice(list_, size=self.size, replace=True)
    else:
      sample_ = random.choices(list_, k=self.size)
    return sample_

  def binarize_predictions(self, preds):
    x = copy.deepcopy(preds)
    x[x > self.threshold] = 1.
    x[x <= self.threshold] = 0.
    return x

  def specificity(self, labels, preds):
    cm = metrics.confusion_matrix(labels, preds)
    return cm[0,0]/(cm[0,0]+cm[0,1])

  def run(self):
    dict_ = {x: [] for x in ['auc', 'acc', 'sensitivity', 'specificity']}
    data = list(zip(self.preds, self.labels))

    for idx in range(self.n_iter):
      if idx == 0:
        preds, labels = zip(*data)
      else:
        sample_ = self.sample(data)
        preds, labels = zip(*sample_)
      dict_['auc'].append(metrics.roc_auc_score(labels, preds))
      binary = self.binarize_predictions(np.array(preds))
      dict_['acc'].append(metrics.accuracy_score(labels, binary))
      dict_['sensitivity'].append(metrics.recall_score(labels, binary)) # sens
      dict_['specificity'].append(self.specificity(labels, binary)) # sens

    if self.print_output:
      print('\n\nMETRICS:')
      for key, value in dict_.items():
        print('{}: {:.03} ({:.03}-{:.03})'.format(key, value[0],
              np.percentile(value, 5), np.percentile(value, 95)))

def threshold_search(preds, labels):
  threshold_values = [0.5, 0.80, 0.90, 0.95, 0.98, 0.99, 0.99, 0.999, 0.9999,
                      0.99999]
  best_acc = 0
  best_threshold = 0
  for threshold in threshold_values:
    binary = binarize_predictions(preds, threshold)
    acc = metrics.accuracy_score(labels, binary)
    precision = metrics.precision_score(labels, binary) # PPV
    recall = metrics.recall_score(labels, binary) # sensitivity
    f1 = metrics.f1_score(labels, binary)
    print('\n{} - acc: {:.03}, precision {:.03}, recall {:.03}, '
          'f1 {:.03}'.format(threshold, acc, precision, recall, f1),
          flush=True)
    if acc > best_acc:
      best_acc = acc
      best_threshold = threshold

  print('\nBEST THRESHOLD: {}'.format(best_threshold))
  return threshold

def save_histogram(data, title, save_dir):
  n, bins, patches = plt.hist(data, bins=100)
  plt.title(title)
  plt.ylabel('N tiles')
  plt.xlabel('value')
  plt.savefig(os.path.join(save_dir, title + '.jpg'))
  plt.clf()

# ——————————————————————————————————————————————————————————————————————

class SlidePrediction():
  def __init__(self, subdir, preds_dir, case_split, save_histograms=True,
               test_set='val'):
    self.subdir = subdir
    self.predictions_dir = preds_dir
    self.save_histograms = save_histograms
    self.test_set = test_set
    if save_histograms:
      dirs = os.path.split(subdir)
      self.histogram_dir = os.path.join(dirs[0], 'histograms', dirs[1])
      Path(self.histogram_dir).mkdir(parents=True, exist_ok=True)
    self.case_split = case_split
    self.fv_len = 512
    self.verbose = False
    self.modes = list(case_split.keys())
    # make dictionary mapping case to mode
    self.case_to_mode = dict( (v,k) for k in self.case_split
                              for v in self.case_split[k] )
    self.load_tile_predictions()

  def load_tile_predictions(self):
    self.output_dict = {x: {} for x in self.modes}
    pkl_list = [x for x in os.listdir(self.predictions_dir)
                if x.endswith('pkl')]
    for pkl_file in pkl_list:
      try:
        pred =  misc.load_pkl(os.path.join(self.predictions_dir, pkl_file))
        case_id = os.path.splitext(pkl_file)[0]
        try:
          mode = self.case_to_mode[case_id]
          self.output_dict[mode][case_id] = pred
        except KeyError:
          print('case {} not found in case split'.format(pkl_file))
      except pickle.UnpicklingError as e:
        print('unable to load {} due to:'.format(pkl_file), e)
    n_preds = {mode: len(self.output_dict[mode]) for mode in self.modes}
    print('loaded predictions:', n_preds )

  def avg_pool_prediction(self, topN=0.005, min_imgs=10, output='softmax'):
    """ Average pooling prediction using the tiles that are most likely
    to be tumor.

    # Args:
      topN: proportion of tiles to use (ie sort in descending order and
            then use topN * num_tiles)
      output: type of output data from network to use (ie softmax or fc)
    """
    predictions_dict = {}
    labels_dict = {}
    cases_dict = {}
    for mode in self.modes:
      preds = np.empty(0)
      labels = np.empty(0)
      cases = []
      if self.save_histograms:
        set_ = self.test_set if mode=='test' else 'train'
        histogram_subdir = os.path.join(self.histogram_dir, set_)
        Path(histogram_subdir).mkdir(parents=True, exist_ok=True)
      case_list = list( self.output_dict[mode].keys() )
      for case in case_list:
        try:
          output_data = self.output_dict[mode][case][output][:,1]
          if self.save_histograms:
            save_histogram(output_data, case, histogram_subdir)
          output_data = np.sort(output_data)[::-1]
          if isinstance(topN, int):
            n_imgs = topN
          else:
            n_imgs = int(np.max((len(output_data) * topN, min_imgs)))
          if self.verbose:
            print(case, n_imgs)
          pred = np.mean(output_data[:n_imgs]).reshape(1)
          preds = np.concatenate((preds, pred))
          label = np.array(get_value_from_filename(case)).reshape(1)
          labels = np.concatenate((labels, label))
          cases.append(case)
        except KeyError as e:
          print(case, e)
      predictions_dict[mode] = preds
      labels_dict[mode] = labels
      cases_dict[mode] = cases
    return predictions_dict, labels_dict, cases_dict

# ——————————————————————————————————————————————————————————————————————

def evaluate_run(subdir, case_split, prediction_method, threshold,
                 fv_type='pred_features', print_predictions=False):
  """ Evaluate the performance from a single cross validation run
  """
  preds_dir = os.path.join(subdir, 'predictions_cv/case')
  predictor = SlidePrediction(subdir, preds_dir, case_split)

  modes = list(case_split.keys())

  test_metrics = {}
  preds, labels, cases = predictor.avg_pool_prediction()

  for mode in modes:
    if mode in ['val', 'test']:
      if print_predictions:
        print_predictions(preds[mode], labels[mode], cases[mode])
      if FLAGS.threshold_search and mode=='val':
        threshold = threshold_search(preds[mode], labels[mode])
      metrics = EvaluatePredictions(preds[mode], labels[mode], threshold).run()
      test_metrics = metrics
  return test_metrics, preds, labels

def evaluate_cross_val_runs(run_dir, case_split, threshold, prediction_method,
                            print_predictions=False, **kwargs):
  run_subdirs = glob.glob(os.path.join(run_dir, 'run_*'))
  full_metrics = {}
  cv_preds, cv_labels = [], []
  # loop over all CV runs and save metrics to dict
  for idx in range(1, len(run_subdirs)+1):
    print_run_separator(idx)
    subdir = run_subdirs[idx-1]
    split = {'train': case_split[str(idx)]['train'],
             'val': case_split[str(idx)]['test']}
    full_metrics[idx], preds, labels = evaluate_run(subdir, split,
                                       prediction_method, threshold,
                                       print_predictions=print_predictions)
    cv_preds.append(preds['val'])
    cv_labels.append(labels['val'])

  EvaluatePredictions(np.concatenate(cv_preds), np.concatenate(cv_labels),
                      threshold).run()
  plot_roc_curve_crossval(cv_preds, cv_labels)

def test_set_prediction(run_id, test_list, test_pred_dir, prediction_method,
                        threshold=0.99, test_set='val', print_predictions=False,
                        **kwargs):
  """ Evaluate test set by averaging predictions from models trained
  in multi-fold cross validation runs
  """
  case_split = {'test': misc.load_txt_file_lines(test_list)}
  run_dir = os.path.join(FLAGS.runs_main, run_id)
  run_subdirs = glob.glob(os.path.join(run_dir, 'run_*'))
  for idx in range(1, len(run_subdirs)+1):
    print_run_separator(idx)
    subdir = os.path.join(run_dir, 'run_{}'.format(idx))

    preds_dir = os.path.join(subdir, test_pred_dir, 'case')
    predictor = SlidePrediction(subdir, preds_dir, case_split,
                                test_set=test_set)

    preds, labels, cases = predictor.avg_pool_prediction()
    preds = preds['test'].reshape((-1, 1))
    labels = labels['test'].reshape((-1, 1))
    try:
      full_preds = np.concatenate((full_preds, preds), 1)
      full_labels = np.concatenate((full_labels, labels), 1)
    except NameError:
      full_preds = preds
      full_labels = labels

  avg_preds = np.mean(full_preds, 1)
  if print_predictions:
    print_predictions(avg_preds, labels, cases['test'])
  EvaluatePredictions(avg_preds, labels, threshold, n_iter=1000).run()
  plot_roc_curve_test(avg_preds, labels)

# ——————————————————————————————————————————————————————————————————————

def main(FLAGS):
  run_dir = os.path.join(FLAGS.runs_main, FLAGS.run_id)
  # load slide split
  case_split = misc.load_pkl(os.path.join(run_dir, 'case_split.pkl'))

  # path to csv summary file
  handle = (FLAGS.run_id[:-2] if FLAGS.run_id.endswith('_', -3, -1)
            else FLAGS.run_id)
  csv_file = os.path.join(FLAGS.runs_main,
                              'run_summaries/{}.csv'.format(handle))

  from folder_config import folder_config
  folders = folder_config.get(FLAGS.test_set, folder_config['val'])

  config = {'run_id': FLAGS.run_id,
            'run_dir': run_dir,
            'case_split': case_split,
            'csv_file': csv_file,
            'cv_idx': FLAGS.cv_idx,
            'threshold': FLAGS.threshold,
            'prediction_method': FLAGS.prediction_method,
            'reset_csv': FLAGS.reset_csv,
            'plot_histograms': FLAGS.plot_histograms,
            'test_list': folders['list'],
            'test_pred_dir': folders['output_dir'],
            'test_set': FLAGS.test_set,
            'print_predictions': FLAGS.print_predictions,
            }

  if FLAGS.test_set in ['external', 'referrals']:
    test_set_prediction(**config)
  else:
    evaluate_cross_val_runs(**config)

# ——————————————————————————————————————————————————————————————————————

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  # locate run folder
  parser.add_argument('--runs_main',
      default='/path/to/dir/results')
  parser.add_argument('--run_id', default=None,
      help="Saved model to use for generating predictions")
  parser.add_argument('--cv_idx', default=None, type=int)

  # options for predictions
  parser.add_argument('--new_fv', action='store_true')
  parser.add_argument('--prediction_method', default='avg_pool')
  parser.add_argument('--threshold_search', action='store_true',
    help='search through values to determine best threshold for considering'
         'a case malignant')
  parser.add_argument('--threshold', default=0.999, type=float,
    help='threshold to consider a case malignant (i.e. for getting accuracy')

  parser.add_argument('--reset_csv', action='store_true',
      help='clear any existing data in csv summary file')
  parser.add_argument('--plot_histograms', action='store_true')
  parser.add_argument('--print_predictions', action='store_true')

  # testing
  parser.add_argument('--test_set', default=None,
      choices=['external', 'referrals', 'val'])

  FLAGS = parser.parse_args()

  main(FLAGS)


from pygame import mouse
from pygame.display import update
import Sakuya
import pygame
import sys
import random
import math
import copy
from Sakuya.math import *
from Sakuya.object import Object
from Sakuya.replay import Frame
from assets import *

WINDOW_SIZE = Vector(480, 640)
BUTTONS = {
    "up": pygame.K_UP,
    "left": pygame.K_LEFT,
    "down": pygame.K_DOWN,
    "right": pygame.K_RIGHT,
    "shoot": pygame.K_z,
    "use": pygame.K_x,
    "select": pygame.K_a,
    "start": pygame.K_s
}
MAX_PROJECTILES = 1000
BOSSBAR_UPDATE_SPEED = to_pixels(0.2)
PLAYER_SHOOTING_COOLDOWN = 100

pygame.init()
Sakuya.init()
pg_flags = pygame.SCALED
screen = pygame.display.set_mode(size=(WINDOW_SIZE.x, WINDOW_SIZE.y), flags = pg_flags)
pygame.display.set_caption("Endless Sim (PRE-ALPHA)")
clock = pygame.time.Clock()
sak_time = Sakuya.Time()
delta_time = 0
current_scene = None
mouse_pos = Vector(0, 0)
angle_attack = 0
game_state = "Main" # Main, Game, Pause, Dead
score = 0

# Main world setup
world = Sakuya.World()
world.gravity = Vector(0, 0)

def spread_attack(speed: float, projectile_count: int, delay_per_bullet: int, rng_range: float, damage: float, mid, min, max):
    projectiles = []
    dist = (max - min) / projectile_count
    for p in range(projectile_count):
        projectiles.append(dist*p + mid + min)

    return {"projectiles": projectiles, "speed": speed, "dpb": delay_per_bullet, "rng_range": rng_range, "damage": damage}

def spiral_attack(speed: float, projectile_count: int, delay_per_bullet: int, rng_range: float, damage: float):
    projectiles = []
    dist = 1 / projectile_count
    for p in range(projectile_count):
        projectiles.append(dist * 360 * p)

    return {"projectiles": projectiles, "speed": speed, "dpb": delay_per_bullet, "rng_range": rng_range, "damage": damage}

def target_attack(speed: float, projectile_count: int, delay_per_bullet: int, rng_range: float, damage: float, mid):
    projectiles = []
    dist = 1 / projectile_count
    for p in range(projectile_count):
        projectiles.append(mid + angle_attack)

    return {"projectiles": projectiles, "speed": speed, "dpb": delay_per_bullet, "rng_range": rng_range, "damage": damage}

def attack(shooter: Sakuya.Entity, projectile_data, start_angle: float):
    bullet_time_offset = 0
    for atk in projectile_data["projectiles"]:
        def time_stuff(o, p, a, s):
            global score
            p = shooter.shoot(o, p, a+start_angle, s)
            p.on_destroy(2000)
            world.objects.append(p)
            score += 10

        t = Sakuya.Event(
            bullet_time_offset, time_stuff,
            [Vector(0, 0), CHUNAMI_PROJECTILE, math.radians(atk) + random.uniform(-projectile_data["rng_range"], projectile_data["rng_range"]), projectile_data["speed"]]
        )
        sak_time.wait(t)
        bullet_time_offset += projectile_data["dpb"]

# Player Setup
PLAYER = Sakuya.Entity(
    Vector(to_units(WINDOW_SIZE.x/2), 40),
    Sakuya.Unit(0.5),
    pygame.Surface([10, 10]),
    name = "PLAYER"
)
PLAYER.speed = 0.03
is_moving_left = False
is_moving_right = False
is_moving_down = False
is_moving_up = False
is_shooting = False
can_shoot = True
player_damage = 10

# Projectile Setup
CHUNAMI_PROJECTILE = Sakuya.Entity(
    Vector(0, 0),
    Sakuya.Unit(1),
    pygame.Surface([2, 2]),
    name = "CHUNAMI PROJECTILE"
)

PLAYER_PROJECTILE = Sakuya.Entity(
    Vector(0, 0),
    Sakuya.Unit(1),
    pygame.Surface([2, 2]),
    name = "PLAYER PROJECTILE"
)

# Chunami setup
CHUNAMI = Sakuya.Entity(
    Vector(to_units(WINDOW_SIZE.x/2), 10),
    Sakuya.Unit(5),
    pygame.Surface([10, 10]),
    name = "CHUNAMI"
)
CHUNAMI.MAX_HEALTH = 1000
CHUNAMI.current_health = CHUNAMI.MAX_HEALTH
CHUNAMI.speed = 0.3
chunami_bossbar = Sakuya.BossBar(CHUNAMI.MAX_HEALTH, BOSSBAR_UPDATE_SPEED)

def chu_move0():
    CHUNAMI.target_position = Vector(random.randint(5, to_units(WINDOW_SIZE.x)-5), random.randint(5, int(to_units(WINDOW_SIZE.y * (1/3)))-5))

def chu_atk1(): attack(CHUNAMI, target_attack(10, 3, 50, 0, 10, 180), 0)
def chu_atk2(): attack(CHUNAMI, spread_attack(10, 10, 50, 0.008, 10, 90, -50, 50), 0)
def chu_atk3(): attack(CHUNAMI, spiral_attack(10, 10, 0, 0, 10), 0)

chunami_ai = Sakuya.AI(
    [
        Sakuya.Decision(chu_move0, 0.001),
        Sakuya.Decision(chu_atk1, 0.5),
        Sakuya.Decision(chu_atk2, 0.3),
        Sakuya.Decision(chu_atk3, 0.4)
    ], 10, max_decisions=2
)

world.objects.append(PLAYER)
world.objects.append(CHUNAMI)

def input():
    global is_moving_up
    global is_moving_down
    global is_moving_left
    global is_moving_right
    global is_shooting

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == BUTTONS["up"] and game_state == "Game":
                is_moving_up = True
            if event.key == BUTTONS["down"] and game_state == "Game":
                is_moving_down = True
            if event.key == BUTTONS["left"] and game_state == "Game":
                is_moving_left = True
            if event.key == BUTTONS["right"] and game_state == "Game":
                is_moving_right = True
            if event.key == BUTTONS["shoot"] and game_state == "Game":
                is_shooting = True
        if event.type == pygame.KEYUP:
            if event.key == BUTTONS["up"] and game_state == "Game":
                is_moving_up = False
            if event.key == BUTTONS["down"] and game_state == "Game":
                is_moving_down = False
            if event.key == BUTTONS["left"] and game_state == "Game":
                is_moving_left = False
            if event.key == BUTTONS["right"] and game_state == "Game":
                is_moving_right = False
            if event.key == BUTTONS["shoot"] and game_state == "Game":
                is_shooting = False

def main_menu():
    global delta_time
    global current_scene
    global game_state
    global score

    game_state = "Main"
    buttons = []
    input()

    # Draws background
    screen.fill((0,0,0))
    tLOGO1 = pygame.transform.scale(LOGO1, (LOGO1.get_width()*3, LOGO1.get_height()*3))
    screen.blit(tLOGO1, (WINDOW_SIZE.x/2-tLOGO1.get_width()/2, WINDOW_SIZE.y*(1/4)-tLOGO1.get_height()/2))

    # Buttons
    ## Play Button
    def play_button_f():
        global current_scene
        current_scene = game_scene
    play_text = Sakuya.text("Play", to_pixels(4), "Arial", (0,0,0))
    play_rect = play_text.get_rect()
    play_rect.x = WINDOW_SIZE.x/2 - play_rect.width/2
    play_rect.y = WINDOW_SIZE.y * (3/5) - play_rect.height/2
    play_button = Sakuya.Button(play_rect, [play_button_f], key=BUTTONS["start"])
    pygame.draw.rect(screen, (255,0,0), play_button.rect)
    screen.blit(play_text, (play_button.rect.x, play_button.rect.y))
    buttons.append(play_button)

    # Update values
    world.advance_frame(delta_time)
    sak_time.update()
    pygame.display.update()
    for b in buttons: b.update()
    delta_time = 1 / clock.tick(60)

def game_scene():
    global is_moving_up
    global is_moving_down
    global is_moving_left
    global is_moving_right
    global is_shooting
    global delta_time
    global current_scene
    global mouse_pos
    global angle_attack
    global shooting_cooldown
    global can_shoot
    global game_state
    global score

    game_state = "Game"
    mouse_pos = to_vector(pygame.mouse.get_pos())
    angle_attack = math.degrees(get_angle(PLAYER.position, CHUNAMI.position))
    input()

    # Adds player movement
    movement = Vector(0, 0)
    if is_moving_up: movement.y = -to_pixels(PLAYER.speed)
    if is_moving_down: movement.y = to_pixels(PLAYER.speed)
    if is_moving_right: movement.x = to_pixels(PLAYER.speed)
    if is_moving_left: movement.x = -to_pixels(PLAYER.speed)
    PLAYER.position += movement

    # Test for collisions
    try:
        collided = world.test_collisions(PLAYER)
        for c in collided:
            if c.name == "CHUNAMI PROJECTILE":
                current_scene = dead_scene
                world.objects.remove(c)

        collided = world.test_collisions(CHUNAMI)
        for c in collided:
            if c.name == "PLAYER PROJECTILE":
                if CHUNAMI.current_health >= 0:
                    CHUNAMI.current_health -= player_damage
                world.objects.remove(c)
    except ObjectNotInWorld:
        pass

    # Draws background
    screen.fill((0,0,0))

    # Draws debug hitboxes
    for o in world.objects:
        pygame.draw.circle(screen, (255,255,255), o.hitbox.position.to_list(), o.hitbox.radius)

    # Player shooting
    if is_shooting and can_shoot:
        def can_shoot_func():
            global can_shoot
            can_shoot = True

        player_shooting_event = Sakuya.Event(PLAYER_SHOOTING_COOLDOWN, can_shoot_func)
        p = PLAYER.shoot(Vector(0,-2), PLAYER_PROJECTILE, math.radians(-90), 30)
        p.on_destroy(3000)
        world.objects.append(p)
        can_shoot = False
        sak_time.wait(player_shooting_event)

    # Draws debug values
    pixel_offset = to_pixels(2)
    fps = Sakuya.text(f"fps: {int(clock.get_fps())}", 20, "Arial", (0, 255, 0))
    objects_loaded = Sakuya.text(f"loaded objects: {len(world.objects)}", 20, "Arial", (0, 255, 0))
    score_text = Sakuya.text(f"score: {score}", 20, "Arial", (0, 255, 0))
    screen.blit(fps, (0,pixel_offset))
    screen.blit(objects_loaded, (0,20 + pixel_offset))
    screen.blit(score_text, (0,40 + pixel_offset))

    # Chunami's Boss Bar & AI
    chunami_bossbar.current_health = CHUNAMI.current_health
    bossbar_percentage = chunami_bossbar.display_health / chunami_bossbar.max_health
    pygame.draw.rect(screen, (255,0,0), pygame.Rect(0,0,to_pixels(30), to_pixels(2)))
    pygame.draw.rect(screen, (0,255,0), pygame.Rect(0,0,to_pixels(bossbar_percentage * 30), to_pixels(2)))

    chunami_ai.update_decisions(world.ticks_elapsed)

    # Update values
    world.advance_frame(delta_time)
    sak_time.update()
    chunami_bossbar.update()
    pygame.display.update()
    delta_time = 1 / clock.tick(60)

def dead_scene():
    global game_state
    global score

    game_state = "Dead"
    buttons = []
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # Draws background
    screen.fill((0,0,0))

    # Draws game over message
    game_over_text = Sakuya.text("game over", 20, "Arial", (0, 255, 0))
    screen.blit(game_over_text, (WINDOW_SIZE.x/2 - game_over_text.get_rect().width/2,WINDOW_SIZE.y * (1/3) - game_over_text.get_rect().height/2))

    # Buttons
    ## Try Again Button
    def try_again_button_f():
        global current_scene
        global score
        global is_moving_down
        global is_moving_left
        global is_moving_right
        global is_moving_up
        global is_shooting
        global CHUNAMI

        world.objects = []
        is_moving_up = False
        is_moving_down = False
        is_moving_right = False
        is_moving_left = False
        is_shooting = False
        CHUNAMI.current_health = CHUNAMI.MAX_HEALTH
        world.objects.append(PLAYER)
        world.objects.append(CHUNAMI)
        current_scene = main_menu
        score = 0

    try_again_text = Sakuya.text("Try Again?", to_pixels(4), "Arial", (0,0,0))
    try_again_rect = try_again_text.get_rect()
    try_again_rect.x = WINDOW_SIZE.x/2 - try_again_rect.width/2
    try_again_rect.y = WINDOW_SIZE.y * (3/5) - try_again_rect.height/2
    try_again_button = Sakuya.Button(try_again_rect, [try_again_button_f], key=BUTTONS["start"])
    pygame.draw.rect(screen, (255,0,0), try_again_button.rect)
    screen.blit(try_again_text, (try_again_button.rect.x, try_again_button.rect.y))
    buttons.append(try_again_button)

    # Draws debug values
    fps = Sakuya.text(f"fps: {int(clock.get_fps())}", 20, "Arial", (0, 255, 0))
    objects_loaded = Sakuya.text(f"loaded objects: {len(world.objects)}", 20, "Arial", (0, 255, 0))
    score_text = Sakuya.text(f"score: {score}", 20, "Arial", (0, 255, 0))
    screen.blit(fps, (0,0))
    screen.blit(objects_loaded, (0,20))
    screen.blit(score_text, (0,40))

    # loop
    pygame.display.update()
    sak_time.update()
    for b in buttons: b.update()
    delta_time = 1 / clock.tick(60)

current_scene = main_menu
if __name__ == "__main__":
    while(True):
        current_scene()


class Solution(object):
    def binarysearch(self, source, target):
        if not source :
            return -1

        leftindex, rightindex = 0, len(source) - 1

        while leftindex < rightindex:
            middle = (leftindex + rightindex) >> 1
            if source[middle] == target:
                leftindex = middle
                return leftindex
            elif source[middle] < target:
                leftindex = middle
            else :
                rightindex = middle

        if source[leftindex] == target :
            return leftindex
        if source[rightindex] == target :
            return rightindex
        return -1

if __name__ == "__main__":
    source = [1,2,3,4,5,6,7,8,9,10]
    target = 2
    result = Solution().binarysearch(source, target)
    print(result)


import re

#### The BS stands for 'Binary Search'

with open("/Users/DominikKloepfer/Documents/workspace/Personal_Projects/Advent of Code 2018/Day 23/day23_input1.txt") as input:
    data = [line.strip() for line in input]

nanobots = []

for l in data:
    bot = re.split('<|,|>|r=', l)
    bot = [int(bot[6]), int(bot[1]), int(bot[2]), int(bot[3])]
    nanobots.append(bot)

# This isn't working for every input but only if the nanobot cubes are is sufficiently overlapping
# The algorithm counts the number of bots in range of increasingly fine-grained test points and
# restricts itself to the cube around the test point with the most bots in range.
# This assumes that the cube around the test point with the most bots in range also contains the
# correct global maximum, which is more likely if the range cubes around each bot heavily overlap.
# For my input this gives the correct answer, if we want to be more certain we can do a ternary
# subdivision instead of a binary one or zoom into the two (not one) test point cubes
# with the most bots in range.

xs = [x[1] for x in nanobots] + [0]
ys = [x[2] for x in nanobots] + [0]
zs = [x[3] for x in nanobots] + [0]
size = 1
while size < max(xs) - min(xs):
    size *= 2
while True:
    print(size)
    target_count = 0
    best_point = None
    best_val = None
    for x in range(min(xs), max(xs) + 1, size):
        for y in range(min(ys), max(ys) + 1, size):
            for z in range(min(zs), max(zs) + 1, size):
                count = 0
                for radius, bx, by, bz in nanobots:
                    if size == 1:
                        calc = abs(x - bx) + abs(y - by) + abs(z - bz)
                        if calc <= radius:
                            count += 1
                    else:
                        calc = abs(x // size - bx // size) + abs(y // size - by // size) + abs(z // size - bz // size)
                        if calc - 1 <= radius // size:
                            count += 1
                if count > target_count:
                    target_count = count
                    best_val = abs(x) + abs(y) + abs(z)
                    best_point = (x, y, z)
                elif count == target_count:
                    if best_val is None or abs(x) + abs(y) + abs(z) < best_val:
                        best_val = abs(x) + abs(y) + abs(z)
                        best_point = (x, y, z)
    if size == 1:
        print("The max count I found was: " + str(target_count))
        print(best_val)
        break
    else:
        xs = [best_point[0] - size, best_point[0] + size]
        ys = [best_point[1] - size, best_point[1] + size]
        zs = [best_point[2] - size, best_point[2] + size]
        size = size // 2


from Task import Task
from TodoList import TodoList

def task_test():
    print("Task testing: \n")
    todo_list = set()

    print("creating set from tasks: 'do hw', 'drink coffee', 'go jogging' and 'do hw'")

    todo_list.add(Task('do hw'))
    todo_list.add(Task('drink coffee'))
    todo_list.add(Task('go jogging'))
    todo_list.add(Task('do hw'))

    print("this set contains:\n")
    for item in todo_list:
        print(item)

    print("creating list of tasks with 'do hw', '', 'sleep', ''")

    todo_list = []

    todo_list.append(Task('do hw'))
    todo_list.append(Task(''))
    todo_list.append(Task('sleep'))
    todo_list.append(Task(''))

    print("list of non-empty tasks contains:")

    non_empty_tasks = [item for item in todo_list if item]
    print(non_empty_tasks)

def todo_test():
    print("\nTodoList testing:")
    todo_list = TodoList(2)
    todo_list[0] = Task("do hw")
    todo_list[1] = Task("drink coffee")
    print("after creating todo list with 'do hw' and 'drink coffee' task printing it with next()")
    print(next(todo_list))
    print(next(todo_list))
    print("and printing it with for loop")
    for item in todo_list:
        print(item)

def main():
    task_test()
    todo_test()

if __name__ == "__main__":
    main()


"""Component 5 - statement formatter v1
Written by Katelyn Gee
Created 15/05/2022
"""

# Creating formatted statement
symbol = "*"
text = "Hello world"
sides = symbol * 3

formatted_text = f"{sides} {text} {sides}"
top_bottom = symbol * len(formatted_text)

# Printing formatted statement
print(top_bottom)
print(formatted_text)
print(top_bottom)


from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from .models import organisation, product
from taggit.models import Tag
from django.db.models import Count

@login_required(login_url='/login')
def products_request(request, tag_slug=None):
    products_list = product.objects.all()
    tag = None

    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        products_list = products_list.filter(product_tags__in=[tag])

    return render(request, 'organisations/productsList.html', {"products": products_list,
                                                               "tag": tag})

@login_required(login_url='/login')
def product_request(request, publish, prod):
    print(prod)
    product_item = get_object_or_404(product, product_name=prod,
                                     publish__year=publish.split('.')[2],
                                     publish__month=publish.split('.')[1],
                                     publish__day=publish.split('.')[0])
    product_tags_ids = product_item.product_tags.values_list('id', flat=True)
    similar_products = product.objects.filter(product_tags__in=product_tags_ids).exclude(id_product=product_item.id_product)
    print('Похожее:', similar_products)
    similar_products = similar_products.annotate(same_tags=Count('product_tags')).order_by('-same_tags', '-publish')[:4]

    return render(request, 'organisations/product.html', context={'product_item': product_item,
                                                                  'similar_products': similar_products})

@login_required(login_url='/login')
def update_product(request):
    if request.method == 'POST':
        name = request.POST['product']
        new_product_name = request.POST['newproductname']
        new_product_description = request.POST['newproductdescription']
        username = str(request.user)

        if ("/" in new_product_name):
            return JsonResponse({}, status=405)

        try:
            if (new_product_name != name): # если название отличное от текущего
                existing_product = product.objects.get(
                        product_name=new_product_name)
                if (existing_product): # если такой продукт уже есть
                    return JsonResponse({}, status=402)
        except BaseException:
            pass

        try:
            product_to_update = product.objects.get(product_name=name)
            product_to_update.product_name = new_product_name
            product_to_update.product_description = new_product_description
            product_to_update.save()
            return JsonResponse({}, status=200)
        except BaseException:
            print('error')
            return JsonResponse({}, status=400)
    return JsonResponse({}, status=400)

def organisation_request(request, inn):
    org_item = get_object_or_404(organisation, organisation_inn=inn)
    return render(request, 'organisations/organisation.html', context={'organisation_item': org_item})

@login_required(login_url='/login')
def organisations_request(request):
    organisations_list = organisation.objects.all()
    return render(request, 'organisations/organisationsList.html', {"organisations": organisations_list})

@login_required(login_url='/login')
def employee_json(request):
    employees = organisation.objects.all()
    data = [employee.get_data() for employee in employees]
    response = {'data': data}
    return JsonResponse(response)


import streamlit as st
import joblib
import pandas as pd
from streamlit_option_menu import option_menu
from PIL import Image
import seaborn as sns
import base64
import pickle
import numpy as np

with st.sidebar:
    selected=option_menu(
    menu_title="Main Menu",
        options=['Home','Depression Prediction'],
        icons=['house','book'],
        styles={
            "container":{"background-color":"#c6be9a"},
            "nav-link":{
                "font-size":"21px",
                "--hover-color":"#ad8b32",
                "color":"317202A"
            },
            "nav-link-selected":{
                "background-color":"#937460"
            },
            "icon":{
                "font-size":"20px"
            },
        },
    )

if selected == 'Home':
    st.markdown("""

    """, unsafe_allow_html=True)

    st.markdown('
 WELCOME TO THE DEPRESSION PREDICTION SYSTEM
',unsafe_allow_html=True)
    st.markdown('
 Depression is known as a mood disorder. It is described as feelings of sadness, loss, or anger that interfere with a person’s everyday activities. People experience depression in different ways. It may interfere with your daily work, resulting in lost time and lower productivity. It can also influence relationships and some chronic health conditions.
',
    unsafe_allow_html=True)
    file_=open("depression2.png","rb")
    contents=file_.read()
    data_url=base64.b64encode(contents).decode("utf-8")
    file_.close()

    st.markdown(
        f'',
        unsafe_allow_html=True, )

if selected=='Depression Prediction':
    file_=open("depression-sad.gif","rb")
    contents=file_.read()
    data_url=base64.b64encode(contents).decode("utf-8")
    file_.close()

    st.markdown(
        f'',
        unsafe_allow_html=True, )

    st.markdown("""

    """,unsafe_allow_html=True)
    loaded_model=pickle.load(open('depression.sav','rb'))

    def depression_prediction(input_data):

        # changing the input_data to numpy array
        input_data_as_numpy_array = np.asarray(input_data)

        # reshape the array as we are predicting for one instance
        input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)

        prediction = loaded_model.predict(input_data_reshaped)
        print(prediction)

        if (prediction[0] == 0):
            return 'Person is Not Depressed'
        else:
            return 'Person is Depressed'
    def main():

        st.markdown("
DEPRESSION PREDICTION SYSTEM
", unsafe_allow_html=True)
        #getting the input data from the user
        co1,col2,=st.columns(2)

        with co1:
            Cant_Work=st.selectbox('Are you Not Able to Work  No:0 Yes:1',(0,1),index=0)
            Memory_Problems=st.selectbox('Do you Have Memory Problems No:0 Yes:1',(0,1),index=0)

        with col2:
            Limited_Work=st.selectbox('Do you Have Limited Work No:0 Yes:1',(0,1),index=0)
            Trouble_Sleeping_History=st.selectbox('Are You Facing Trouble To Sleep No:0 Yes:1',(0,1),index=0)
            Health_Problem_Back_Or_Neck=st.selectbox('Do you Have Health Problem of Back Or Neck No:0 Yes:1',(0,1),index=0)

        #code for the prediction
        diagnosis=''
        #creating a button for prediction
        if st.button('Depression Prediction Result'):
            diagnosis = depression_prediction([Cant_Work,Memory_Problems,Limited_Work,Trouble_Sleeping_History,Health_Problem_Back_Or_Neck])
            st.success(diagnosis)

    if __name__ =='__main__':
        main()


#!/usr/bin/env python3
""" proof of concept"""

import argparse
import os

from GenomicsDBData.Manhattan.gwas_track import GWASTrack
from GenomicsDBData.Util.utils import warning, create_dir, execute_cmd

def fetch_data(trackId):
    if not args.annotateOnly:
        track.fetch_track_data()
        track.fetch_title()
        track.get_data().to_csv(os.path.join(args.outputPath, trackId + "-track.txt"), sep="\t")

    track.fetch_gene_data()
    track.get_gene_annotation().to_csv(os.path.join(args.outputPath, trackId + "-annotation.txt"), sep="\t")

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--tracks', help='track key/may be comma separated list', required=True)
    parser.add_argument('--generatePlots', help='generate plots', action='store_true')
    parser.add_argument('-p', '--plotType', help='plot type', default='all', choices=["all", "plotly", "png"])
    parser.add_argument('-l', '--limit', help='limit number of rows to return for test')
    parser.add_argument('-o', '--outputPath', help='outputPath', required=True)
    parser.add_argument('-c', '--cap', default=50, help='-log 10 pvalue cap (recommend 50)', type=int)
    parser.add_argument('--annotateOnly',  help='annotateOnly?', action='store_true')
    parser.add_argument('--fetchData',  help='fetch data? use --annotateOnly flag to only fetch annotation', action='store_true')

    args = parser.parse_args()

    create_dir(args.outputPath)

    tracks = args.tracks.split(',')
    for trackName in tracks:
        track = GWASTrack(trackName)
        track.connect(None)
        if args.limit:
            track.set_limit(args.limit)
        if args.cap:
            track.set_cap(args.cap)

        if args.fetchData:
            fetch_data(trackName)

        if args.generatePlots:
            create_dir(os.path.join(args.outputPath, "png"))
            create_dir(os.path.join(args.outputPath, "pdf"))
            cmd = ["generateManhattanPlots.R", trackName, args.outputPath, str(args.cap), args.plotType]
            execute_cmd(cmd, verbose=True)


from bandetl.utils.band_utils import from_val_to_acc_address
from bandetl.utils.string_utils import to_int

def map_transaction(block, tx):
    address = get_sender_from_transaction(tx)

    return {
        'type': 'transaction',
        'transaction_type': tx.get('tx', EMPTY_OBJECT).get('type'),
        'txhash': tx.get('txhash'),
        'block_height': block.get('block_height'),
        'block_timestamp': block.get('block_timestamp'),
        'block_timestamp_truncated': block.get('block_timestamp_truncated'),
        'gas_wanted': tx.get('gas_wanted'),
        'gas_used': tx.get('gas_used'),
        'sender': address,
        'fee': get_fee(tx),
        'memo': tx.get('tx', EMPTY_OBJECT).get('value', EMPTY_OBJECT).get('memo')
    }

def get_fee(tx):
    fee = tx.get('tx', EMPTY_OBJECT).get('value', EMPTY_OBJECT).get('fee', EMPTY_OBJECT)
    amount_list = [map_amount(amt) for amt in fee.get('amount', EMPTY_LIST)]
    return {
        'amount': amount_list,
        'gas': to_int(fee.get('gas'))
    }

def map_amount(amount):
    return {
        'denom': amount.get('denom'),
        'amount': to_int(amount.get('amount'))
    }

def get_sender_from_transaction(tx):
    msgs = tx.get('tx', EMPTY_OBJECT).get('value', EMPTY_OBJECT).get('msg', EMPTY_LIST)
    if len(msgs) == 0:
        return None

    first_msg = msgs[0]
    return get_sender_from_message(first_msg)

def get_sender_from_message(msg):
    msg_type = msg.get('type')
    msg_value = msg.get('value')

    if msg_type == 'oracle/Activate':
        return from_val_to_acc_address(msg_value.get('validator'))
    if msg_type == 'oracle/AddReporter':
        return from_val_to_acc_address(msg_value.get('validator'))
    if msg_type == 'oracle/CreateDataSource':
        return msg_value.get('sender')
    if msg_type == 'oracle/CreateOracleScript':
        return msg_value.get('sender')
    if msg_type == 'oracle/EditDataSource':
        return msg_value.get('sender')
    if msg_type == 'oracle/EditOracleScript':
        return msg_value.get('sender')
    if msg_type == 'oracle/Report':
        return msg_value.get('reporter')
    if msg_type == 'oracle/Request':
        return msg_value.get('sender')
    if msg_type == 'oracle/RemoveReporter':
        return from_val_to_acc_address(msg_value.get('validator'))

    if msg_type == 'cosmos-sdk/MsgDelegate':
        return msg_value.get('delegator_address')
    if msg_type == 'cosmos-sdk/MsgEditValidator':
        return from_val_to_acc_address(msg_value.get('address'))
    if msg_type == 'cosmos-sdk/MsgMultiSend':
        inputs = msg_value.get('inputs')
        if inputs:
            return inputs[0].get('address')
    if msg_type == 'cosmos-sdk/MsgSend':
        return msg_value.get('from_address')
    if msg_type == 'cosmos-sdk/MsgBeginRedelegate':
        return msg_value.get('delegator_address')
    if msg_type == 'cosmos-sdk/MsgCreateValidator':
        return msg_value.get('delegator_address')
    if msg_type == 'cosmos-sdk/MsgDeposit':
        return msg_value.get('depositor')
    if msg_type == 'cosmos-sdk/MsgFundCommunityPool':
        return msg_value.get('depositor')
    if msg_type == 'cosmos-sdk/MsgModifyWithdrawAddress':
        return msg_value.get('delegator_address')
    if msg_type == 'cosmos-sdk/MsgSubmitEvidence':
        return msg_value.get('submitter')
    if msg_type == 'cosmos-sdk/MsgSubmitProposal':
        return msg_value.get('proposer')
    if msg_type == 'cosmos-sdk/MsgUndelegate':
        return msg_value.get('delegator_address')
    if msg_type == 'cosmos-sdk/MsgUnjail':
        return from_val_to_acc_address(msg_value.get('address'))
    if msg_type == 'cosmos-sdk/MsgVerifyInvariant':
        return msg_value.get('sender')
    if msg_type == 'cosmos-sdk/MsgVote':
        return msg_value.get('voter')
    if msg_type == 'cosmos-sdk/MsgWithdrawDelegationReward':
        return msg_value.get('delegator_address')
    if msg_type == 'cosmos-sdk/MsgWithdrawValidatorCommission':
        return from_val_to_acc_address(msg_value.get('validator_address'))
    return None

EMPTY_OBJECT = {}
EMPTY_LIST = []


"""File with different utils classes and methods for DRF API."""
import re

from rest_framework_xml.parsers import XMLParser

class DocuSignXMLParser(XMLParser):
    """Custom XML parser for DocuSign.

    It defines specific for DocuSign xml `media_type` and performs some data
    cleaning after parsing.

    """
    media_type = 'text/xml; charset=utf-8'

    def parse(self, stream, media_type=None, parser_context=None):
        """Overridden original method to perform data cleaning after parsing.

        DocuSign XML file contains its related API link in all parsed keys.

        """
        data = super().parse(stream, media_type, parser_context)
        cleaned_data = self.clean_data({}, data)
        return cleaned_data

    def clean_data(self, cleaned: dict, original: dict):
        """Recursion to perform dict keys cleaning from HTML links."""
        for key, value in original.items():
            clean_key = re.sub(r'\{http[s]?://\S+\}', '', key)
            if isinstance(value, dict):
                cleaned[clean_key] = self.clean_data(
                    cleaned.get(key, {}),
                    value
                )
            else:
                cleaned[clean_key] = value
        return cleaned


from utils import Student

def get_lines(fn):
    f = open(file_name, encoding="utf-8")
    lines = f.readlines()
    f.close()
    return lines

def get_objects(lines):
    objs = []
    for line in lines:
        id, name, group = tuple(line.split("|"))
        st = Student(id, name, group)  # объект студента
        objs.append(st)
    return objs

file_name = "students.csv"
lines = get_lines(file_name)
students = get_objects(lines[1:])
for student in students:
    print(student)


import torch
import numpy as np
import onnx
import onnxruntime
import cv2
import yy
'''
用于临时测试输出的网络

'''
ONNXPath='./output/论文testnet.onnx'
# ONNXPath='C:/Users/yuanying/Desktop/outputONNX（movi res101 ）.onnx'
# ONNXPath='C:/Users/yuanying/Desktop/outputONNX（movi res101 ）.onnx'
mode=1 #1 从测试集获取数据 2 从自己照片获取数据

if mode ==1:
    testVideo, testJoint=yy.dataProcess.loadYYDataToNumpy(fileName='MoViData_Subj_87_Re_Tr_Ct_PG[1]_Inte_3.npy',dataPath='D:/1Datasets/MoVi/yyData')
    # testVideo, testJoint=yy.dataProcess.loadYYDataToNumpy(fileName='HM36_[11]_Inte_50.npy',dataPath='D:/1Datasets/Human3.6M/yyData')
    sess = onnxruntime.InferenceSession(ONNXPath)
    inputs = sess.get_inputs()
    while True:
        index=np.random.randint(0,testVideo.shape[0])
        print(index)
        img = testVideo[index,...].astype(np.float32)/255.0
        #模型
        out= sess.run(None,{
            inputs[0].name:img[np.newaxis,...],
        })
        yy.tools.showMotionAndVideo(markerlocation=yy.tools.changeCoord(out[0]),parent=yy.MoViConst.getAmass20()[1],fps=1,video=img[np.newaxis,...],azim=-60,elev=-160,normlization=0)
        # yy.tools.showMotionAndVideo(markerlocation=yy.tools.changeCoord(out[0]),parent=yy.dataProcess.HM36Const.getParent(),fps=1,video=img[np.newaxis,...],azim=-90,elev=-179,normlization=0)

elif mode ==2 :
    for i in range(15):
        picturePath='./testImages/test/test'+str(i)+'.png'
        img=cv2.imread(picturePath)
        img=cv2.resize(img,(448,448))
        img=img[...,[2,1,0]]
        img=img.swapaxes(0,2).swapaxes(1,2)
        #4:3转1:1
        # img=np.concatenate((np.random.randint(size=(3,50,400),high=256,low=0,dtype='uint8'),img,np.random.randint(size=(3,50,400),high=256,low=0,dtype='uint8')),axis=1)

        img = img.astype(np.float32)/255.0
        print('输入',img.shape,type(img))
        img = img[np.newaxis,...]
        #模型
        sess = onnxruntime.InferenceSession(ONNXPath)
        inputs = sess.get_inputs()
        out= sess.run(None,{
            inputs[0].name:img,
        })
        print('输出',out[0].shape)
        # exit()
        yy.tools.showMotionAndVideo(markerlocation=yy.tools.changeCoord(out[0]),parent=yy.MoViConst.getAmass20()[1],fps=1,video=img,azim=-90,elev=-179,normlization=0)


def init(self):
        """Create Session by desiredCapabilities

        Support:
            Android iOS Web(WebView)

        Returns:
            WebDriver Object.
        """
        resp = self._execute(Command.NEW_SESSION, {
            'desiredCapabilities': self.desired_capabilities
        }, False)
        resp.raise_for_status()
        self.session_id = str(resp.session_id)
        self.capabilities = resp.value


import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

import os
import json
import argparse
from scenario import gazebo as scenario
from gym_ignition.utils.scenario import init_gazebo_sim
from adherent.data_processing.utils import iCub
from adherent.trajectory_generation.utils import SphereURDF
from adherent.trajectory_generation.utils import Shape
from adherent.trajectory_generation.utils import visualize_generated_motion

# ==================
# USER CONFIGURATION
# ==================

parser = argparse.ArgumentParser()

parser.add_argument("--storage_path", help="Path where the generated trajectory is stored. Relative path from script folder.",
                    type=str, default="../datasets/inference/")
parser.add_argument("--deactivate_blending_coeffs_plot", help="Deactivate plot of the blending coefficients.", action="store_true")

args = parser.parse_args()

storage_path = args.storage_path
plot_blending_coeffs = not args.deactivate_blending_coeffs_plot

# ===============================
# LOAD TRAJECTORY GENERATION DATA
# ===============================

# Define the paths for the generated postural, footsteps, joystick inputs and blending coefficients
script_directory = os.path.dirname(os.path.abspath(__file__))
storage_path = os.path.join(script_directory, storage_path)
postural_path = storage_path + "postural.txt"
footsteps_path = storage_path + "footsteps.txt"
joystick_input_path = storage_path + "joystick_input.txt"
blending_coeffs_path = storage_path + "blending_coefficients.txt"

# Load generated posturals
with open(postural_path, 'r') as openfile:
    posturals = json.load(openfile)

# Load generated footsteps
with open(footsteps_path, 'r') as openfile:
    footsteps = json.load(openfile)
    l_footsteps = footsteps["l_foot"]
    r_footsteps = footsteps["r_foot"]

# Load joystick inputs (motion and facing directions) associated to the generated trajectory
with open(joystick_input_path, 'r') as openfile:
    joystick_input = json.load(openfile)
    raw_data = joystick_input["raw_data"]

# Load blending coefficients associated to the generated trajectory (if available)
if not os.path.exists(blending_coeffs_path):
    plot_blending_coeffs = False
if plot_blending_coeffs:
    with open(blending_coeffs_path, 'r') as openfile:
        blending_coeffs = json.load(openfile)
else:
    blending_coeffs = {}

# ===============
# MODEL INSERTION
# ===============

# Set scenario verbosity
scenario.set_verbosity(scenario.Verbosity_warning)

# Get the default simulator and the default empty world
gazebo, world = init_gazebo_sim()

# Retrieve the robot urdf model
icub_urdf = os.path.join(script_directory, "../src/adherent/model/iCubGazeboSimpleCollisionsV2_5_xsens/iCubGazeboSimpleCollisionsV2_5_xsens.urdf")

# Insert the robot in the empty world
icub = iCub(world=world, urdf=icub_urdf)

# Get the controlled joints
controlled_joints = icub.joint_names()

# Show the GUI
gazebo.gui()
gazebo.run(paused=True)

# ===================
# VISUALIZE FOOTSTEPS
# ===================

# Retrieve left and right footsteps
ground_l_footsteps = []
for element in l_footsteps:
    ground_l_footsteps.append(element["2D_pos"])
ground_r_footsteps = []
for element in r_footsteps:
    ground_r_footsteps.append(element["2D_pos"])

# Insert a blue sphere for each left contact
blue = (0, 0, 1, 1)
for ground_l_footstep in ground_l_footsteps:
    sphere_position = [ground_l_footstep[0], ground_l_footstep[1], 0.0]
    sphere = Shape(world=world,
                   model_string=SphereURDF(radius=0.025, color=blue).urdf(),
                   position=sphere_position)

# Insert a red sphere for each right contact
red = (1, 0, 0, 1)
for ground_r_footstep in ground_r_footsteps:
    sphere_position = [ground_r_footstep[0], ground_r_footstep[1], 0.0]
    sphere = Shape(world=world,
                   model_string=SphereURDF(radius=0.025, color=red).urdf(),
                   position=sphere_position)

# ==========================
# VISUALIZE GENERATED MOTION
# ==========================

input("Press Enter to start the visualization of the generated trajectory.")
visualize_generated_motion(icub=icub, gazebo=gazebo, posturals=posturals,
                           raw_data=raw_data, blending_coeffs=blending_coeffs,
                           plot_blending_coeffs=plot_blending_coeffs)


#!./Python/python.exe
"""
make_pretty.py

Take a 'human readable' mess and make it into something
easier to tackle programmatically, strip line padding if
working with a delimited file, otherwise we'll see what
it comes back with.

input will (generally) be a string., ideally launching
from a file, and landing with a file. will prepend "pretty"
to the filename.

I'm running through some troubleshooting to make better use of the
utility.
"""

import os;
import os.path;
import sys;
import string;
import shutil; # might add functionality to archive the old files.

pattern = None;

def make_pretty(filename, new_name = "pretty_"):
        """
        general form of the make_pretty function. doesn't need to be executed from
        within the class.
        """
        filename = os.path.realpath(filename);
        pretty_data = "";
        try:
            with open(filename,"r") as delt:
                for a in delt.readlines():
                    ctr=0;
                    for b in a:
                        if b not in string.whitespace:
                            ctr =1;
                            break; # escape the inner loop, save clock time.
                    if ctr>0:
                        pretty_data+=a; # I could break it at the first non- whitespace character
                        continue;  # escape the inner loop
            filename_2 = prepend_filename(filename,new_name);
            with open(filename_2,'w') as fi:
                fi.write(pretty_data)
        except Exception as ex:
            input("%s\nDo you understand? "%(str(ex)));
        print("completed operation on: %s"%(filename))
        return;

def prepend_filename(filename, prepend_data=""):
    """
    Python function to prepend data to a file – you could try any arbitrary data that
    Can be represented as a string (if you’re feeling ambitious/bored, look up datetime module)
    """
    filename_ = os.path.realpath(filename)
    path__,filename__ = os.path.split(filename_)
    filename__ = "%s%s"%(prepend_data,filename__)
    return "%s%s%s"%(path__,os.sep,filename__)# littered with typos

class ugly_file:
    """
    *** DON'T USE ME - INCOMPLETE ***
    ugly_files are the type of input we're expecting.
    attributes will be "ugly","pretty","stripped"
    might eventually add extensions for encryption.

    Encoding might not matter at this point, I'll leave it in for now.
    """
    __slots__ = [
    'encoding',   # choose an encoding (default will be ascii)
    'ugly',       # representation of the initial file state
    'pretty',     # representation of the cleaned file state
    'stripped',   # representation of the stripped down (sans whitespace) file
    'path',       # representation of the file path (ideally full-path)
    'name'        # filename (part 2 of os.path.split(filename))
    ]
    def __init__(self, filename = None, path = None, encoding = None):
        """
        this will work by passing a relative path in to filename - I'll need
        to handle the case where it is only a relpath.
        """
        self.encoding = encoding or 'ascii'
        self.name = os.path.basename(filename); # immediately assume that this will be none
        # I'll simply add a mechanism to generate the fullpath from the filename -
        # if it doesn't exist, we might run into an error...
        #if os.path.isabs(filename): self.path = os.path.split(filename)[0];
        try:
            self.path = os.path.realpath(filename)
            self.filename = os.path.realpath(filename)
        except Exception as Echo:
            print(Echo); # that should handle things for the most part.
            self.path = None;

    def filename_prepend(self, prepend_data="",filename = None):
        """
        prepend 'prepend_data' to 'filename'
        will default to the filename supplied with the file.
        """
        pass;
        # this will need to split the filename and then write the prepended data
        filename_ = os.path.realpath(filename)
        path__, filename__ = os.path.split(filename)
        filename__ = "%s%s"%(prepend_data,filename__);
        return "%s%s%s"%(path__,os.sep,filename__)

    def make_pretty(self,filename = None):
        """
        function will work by passing in a path, then removing extraneous characters and lines.
        will remove each line that is only Null or whitespace.
        """
        filename = filename or self.name; # allow the input to override the instance variable
        pretty_data = "";
        try:
            with open(filename,"r") as delt:
                for a in delt.readlines():
                    ctr=0;
                    for b in a:
                        if b not in string.whitespace:
                            ctr =1;
                            break; # escape the inner loop, save clock time.
                    if ctr>0:
                        pretty_data+=a; # I could break it at the first non- whitespace character
                        continue;  # escape the inner loop
            filename = os.path.realpath(filename)
            path = os.path.split(filename)[0]
            filename_2 = os.path.split(filename)[-1]
            filename_2 = "pretty_%s"%(filename_2)
            filename_2 = path+os.sep+filename_2;
            with open(filename_2,'w') as fi:
                fi.write(pretty_data)
        except Exception as ex:
            input("%s\nDo you understand? "%(str(ex)));

def pretty_path(path,pattern=None):
    targs = []
    for a in os.listdir(path):
        if pattern:
            if pattern in a: targs.append(a);
        else: targs.append(a)
    for a in targs:
        print(a)
        make_pretty(a)
    return;

def argv_():
    for a in sys.argv[1:]:
        if "=" in a: pattern = a.split("=")[-1] # get the pattern
        if os.path.isdir(a):
            if pattern: pretty_path(a,pattern);
            else: pretty_path(a);
        elif os.path.isfile(a): make_pretty(a);
        else: print("Not sure what to do with '%s'"%(a))

def interact_(val,pat = None):
    rt_ = None;
    if os.path.isdir(val):
        if pat:
            pretty_path(val,pat)
        else:
            pretty_path(val);
        rt_ = True;
    elif os.path.isfile(val):
        make_pretty(val);
        rt_ = True;
    elif "=" in val:
        pattern = val.split("=")[-1]
        rt_ = True; # return for input.
    else:
        print("Not sure what to do with '%s'"%(val))
        rt_ = False;
    return rt_;

def main_():
    """
    main loop - iterate through a set of files and make them pretty if they match a pattern.
    """
    pattern = "txt"; # by default i'm going to let it look for patterns with text.
    pass
    if len(sys.argv)>1: # handle the cmdline args
        pass
    else:
        print("Ctrl+c to quit (or pass a non-file/non-directory item)")
        print("Enter a pattern to match as pattern='val' will look for pattern in filename.")
        fn = input("Enter a path to make pretty(directory will run against everything): ")
        while fn:
            if type(fn) != str:
                fn = input("Enter a path to make pretty(directory will run against everything): ")
            try:
                if not (os.path.isfile(fn) or os.path.isdir(fn)) and "=" in fn:
                    pattern = fn.split("=")[-1];
                    fn = True;
                    continue;
                if pattern: fn = interact_(fn,pattern)
                else: fn = interact_(fn)
            except Exception as e:
                print(e);
                fn = False;

if __name__=="__main__": main_();
else: print("imported make_pretty.py");