import argparse
import enum
import logging

# import pyqtgraph as pg
from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds, LogLevels
from brainflow.data_filter import DataFilter, FilterTypes, WindowOperations, DetrendOperations
from brainflow.ml_model import MLModel, BrainFlowMetrics, BrainFlowClassifiers, BrainFlowModelParams
# from pyqtgraph.Qt import QtGui, QtCore
import time
import numpy as np

def main():
    BoardShim.enable_dev_board_logger()
    DataFilter.enable_data_logger()
    MLModel.enable_ml_logger()
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port
    parser.add_argument('--timeout', type=int, help='timeout for device discovery or connection', required=False,
                        default=0)
    parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0)
    parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False,
                        default=0)
    parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='')
    parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='')
    parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='')
    parser.add_argument('--other-info', type=str, help='other info', required=False, default='')
    parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='')
    parser.add_argument('--serial-number', type=str, help='serial number', required=False, default='')
    parser.add_argument('--board-id', type=int, help='board id, check docs to get a list of supported boards',
                        required=False, default=BoardIds.SYNTHETIC_BOARD)
    parser.add_argument('--file', type=str, help='file', required=False, default='')
    parser.add_argument('--master-board', type=int, help='master board id for streaming and playback boards',
                        required=False, default=BoardIds.NO_BOARD)
    args = parser.parse_args()

    params = BrainFlowInputParams()
    params.timeout = 0
    params.ip_port = 0
    params.ip_protocol = 0
    params.ip_address = ''
    params.serial_port = ''
    params.mac_address = ''
    params.other_info = ''
    params.serial_number = ''
    params.file = ''
    params.master_board = BoardIds.NO_BOARD # Only useful if we are streaming in

    try:
        board_shim = BoardShim(38, params)
        board_shim.prepare_session()
        board_shim.start_stream(450000, '')
        master_board_id = board_shim.get_board_id()
        BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'start sleeping in the main thread')
        time.sleep(1)
        # Graph(board_shim)
        # prep ML model
        sampling_rate = BoardShim.get_sampling_rate(master_board_id)
        nfft = DataFilter.get_nearest_power_of_two(sampling_rate)

        data = board_shim.get_board_data()

        eeg_channels = BoardShim.get_eeg_channels(int(master_board_id))
        bands = DataFilter.get_avg_band_powers(data, eeg_channels, sampling_rate, True)
        feature_vector = bands[0]
        mindfulness_params = BrainFlowModelParams(BrainFlowMetrics.MINDFULNESS.value,
                                              BrainFlowClassifiers.DEFAULT_CLASSIFIER.value)
        mindfulness = MLModel(mindfulness_params)
        mindfulness.prepare()
        time.sleep(3)
        print('Mindfulness: %s' % str(mindfulness.predict(feature_vector)))

        while True:
            data = board_shim.get_current_board_data(sampling_rate)
            bands = DataFilter.get_avg_band_powers(data, eeg_channels, sampling_rate, True)

            feature_vector = bands[0]
            alphas = []
            betas = []

            for channelIDX in range(len(BoardShim.get_exg_channels(38))):
                # DataFilter.detrend(data[channelIDX], DetrendOperations.LINEAR.value)
                psd = DataFilter.get_psd_welch(data[channelIDX], nfft, nfft // 2, sampling_rate,
                                   WindowOperations.BLACKMAN_HARRIS.value)
                alphas.append(DataFilter.get_band_power(psd, 7.0, 13.0))
                betas.append(DataFilter.get_band_power(psd, 14.0, 20.0))

            alpha = np.mean(alphas)
            beta = np.mean(betas)
            # print(np.array(bands).shape)
            print(f'A:{alpha}, B:{beta} :::Mindfulness: {str(mindfulness.predict(feature_vector))}' )
            time.sleep(1)
        mindfulness.release()

    except BaseException:
        logging.warning('Exception', exc_info=True)
    finally:
        if board_shim.is_prepared():
            logging.info('Releasing session')
            board_shim.release_session()

if __name__ == '__main__':
    main()


from copy import deepcopy
from datetime import datetime, timedelta
from unittest import TestCase
from unittest.mock import patch, Mock

from pony.orm import db_session, rollback
from vk_api.bot_longpoll import VkBotEvent
from bot import Bot
import config
from ticket_generation import generate_ticket
from flights import FLIGHTS
from handlers import get_suggestion_dates

def isolate_db(test_func):
    """
    Изолирование базы данных для проведения теста
    :param test_func: функция теста
    """
    def wrapper(*args, **kwargs):
        with db_session:
            test_func(*args, **kwargs)
            rollback()
    return wrapper

class Test1(TestCase):
    RAW_EVENT = {
        'type': 'message_new',
        'object': {
            'message': {
                'date': 1624899179, 'from_id': 81687909, 'id': 77, 'out': 0, 'peer_id': 81687909, 'text': 'А',
                'conversation_message_id': 77, 'fwd_messages': [], 'important': False, 'random_id': 0,
                'attachments': [], 'is_hidden': False
            },
            'client_info': {
                'button_actions': [
                    'text', 'vkpay', 'open_app', 'location', 'open_link', 'callback', 'intent_subscribe',
                    'intent_unsubscribe'
                ],
                'keyboard': True, 'inline_keyboard': True, 'carousel': True, 'lang_id': 0
            }
        },
        'group_id': 202268874,
        'event_id': '253717ff7a6a586a068c5b54519b88baec82f49c'
    }

    def test_run(self):
        count = 5
        obj = {'a': 1}
        events = [obj] * count
        long_poller_mock = Mock(return_value=events)
        long_poller_listen_mock = Mock()
        long_poller_listen_mock.listen = long_poller_mock

        with patch('bot.vk_api.VkApi'):
            with patch('bot.VkBotLongPoll', return_value=long_poller_listen_mock):
                bot = Bot('', '')
                bot.on_event = Mock()
                bot.send_image = Mock()
                bot.run()

                bot.on_event.assert_called()
                bot.on_event.assert_any_call(obj)
                assert bot.on_event.call_count == count

    INPUTS = [
        'привет',
        '/ticket',
        FLIGHTS[0]['departure_city'],
        FLIGHTS[0]['destination_city'],
        datetime.strftime(datetime.now() + timedelta(days=50), '%d-%m-%Y'),
        '3',
        '7',
        '1',
        'Нужны билеты в первый класс',
        'да',
        '89037463761',
    ]

    SUGGESTION_DATES = get_suggestion_dates(INPUTS[2], INPUTS[3], datetime.strptime(INPUTS[4], '%d-%m-%Y'))

    EXPECTED_OUTPUTS = [
        config.DEFAULT_ANSWER,
        config.SCENARIOS['flight_search']['steps']['step1']['text'],
        config.SCENARIOS['flight_search']['steps']['step2']['text'],
        config.SCENARIOS['flight_search']['steps']['step3']['text'],
        config.SCENARIOS['flight_search']['steps']['step4']['text'].format(
            suggestion_dates_list_str='\n'.join(
                [f"{i + 1}. {datetime.strftime(date, '%H:%M  %d-%m-%Y')}" for i, date in enumerate(SUGGESTION_DATES)]
            )
        ),
        config.SCENARIOS['flight_search']['steps']['step5']['text'],
        config.SCENARIOS['flight_search']['steps']['step5']['failure_text'],
        config.SCENARIOS['flight_search']['steps']['step6']['text'],
        config.SCENARIOS['flight_search']['steps']['step7']['text'].format(
            departure_city=INPUTS[2],
            destination_city=INPUTS[3],
            selected_date=datetime.strftime(SUGGESTION_DATES[2], '%H:%M  %d-%m-%Y'),
            seats_number='1'
        ),
        config.SCENARIOS['flight_search']['steps']['step8']['text'],
        config.SCENARIOS['flight_search']['steps']['step9']['text'].format(phone_number='89037463761'),
    ]

    @isolate_db
    def test_run_ok(self):
        send_mock = Mock()
        api_mock = Mock()
        api_mock.messages.send = send_mock

        events = []
        for input_text in self.INPUTS:
            event = deepcopy(self.RAW_EVENT)
            event['object']['message']['text'] = input_text
            events.append(VkBotEvent(event))

        long_poller_mock = Mock()
        long_poller_mock.listen = Mock(return_value=events)
        with patch('bot.VkBotLongPoll', return_value=long_poller_mock):
            bot = Bot('', '')
            bot.api = api_mock
            bot.send_image = Mock()
            bot.run()

        assert send_mock.call_count == len(self.INPUTS)
        real_outputs = []
        for call in send_mock.call_args_list:
            args, kwargs = call
            real_outputs.append(kwargs['message'])
        assert real_outputs == self.EXPECTED_OUTPUTS

    def test_ticket_generation(self):
        with open('./files/test_avatar.svg', 'rb') as avatar_file:
            avatar_mock = Mock()
            avatar_mock.content = avatar_file.read()
        with patch('requests.get', return_value=avatar_mock):
            ticket_file = generate_ticket('Москва', 'Петербург', '10-12-2021', '89375647385')
        with open('./files/ticket_example.png', 'rb') as expected_file:
            expected_bytes = expected_file.read()
        assert ticket_file.read() == expected_bytes


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

import numpy as np
from evaluation.eval_ssl import evaluation
from utils.utils import get_config_from_json
import torch
import argparse
from optim.pretrain import *
import datetime
import random
from data.preprocessing import *
import os
import sys
sys.path.append('..')

def parse_option():
    parser = argparse.ArgumentParser('argument for training')
    parser.add_argument('--save_freq', type=int, default=200,
                        help='save frequency')
    parser.add_argument('--batch_size', type=int, default=128,
                        help='batch_size')
    # Bigger is better.
    parser.add_argument('--K', type=int, default=16,
                        help='Number of augmentation for each sample')

    parser.add_argument('--feature_size', type=int, default=64,
                        help='feature_size')
    parser.add_argument('--num_workers', type=int, default=16,
                        help='num of workers to use')
    parser.add_argument('--epochs', type=int, default=400,  # 400
                        help='number of training epochs')
    parser.add_argument('--patience', type=int, default=400,
                        help='training patience')
    parser.add_argument('--aug_type', type=str,
                        default='none', help='Augmentation type')
    parser.add_argument('--piece_size', type=float, default=0.2,
                        help='piece size for time series piece sampling')
    parser.add_argument('--class_type', type=str,
                        default='3C', help='Classification type')

    # optimization
    parser.add_argument('--learning_rate', type=float, default=0.01,
                        help='learning rate')
    # model dataset
    parser.add_argument('--dataset_name', type=str, default='CricketX',
                        help='dataset')
    parser.add_argument('--ucr_path', type=str, default='/dev_data/zzj/hzy/datasets/UCR',
                        help='Data root for dataset.')
    parser.add_argument('--ckpt_dir', type=str, default='./ckpt/',
                        help='Data path for checkpoint.')
    # method
    parser.add_argument('--backbone', type=str, default='SimConv4')
    parser.add_argument('--model_name', type=str, default='InterSample',
                        choices=['InterSample', 'IntraTemporal', 'SelfTime'], help='choose method')
    parser.add_argument('--config_dir', type=str,
                        default='./config', help='The Configuration Dir')
    parser.add_argument('--gpus', type=str, default='0', help='selected gpu')
    parser.add_argument('--random_seed', type=int,
                        default=42, help='for reproduction purpose')
    opt = parser.parse_args()
    return opt

if __name__ == "__main__":

    opt = parse_option()
    exp = 'linear_eval'

    os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    # set seed
    random.seed(opt.random_seed)
    np.random.seed(opt.random_seed)
    torch.manual_seed(opt.random_seed)
    torch.cuda.manual_seed(opt.random_seed)
    torch.cuda.manual_seed_all(opt.random_seed)
    aug1 = ['magnitude_warp']
    aug2 = ['time_warp']

    # use uwave config
    config_dict = get_config_from_json('{}/{}_config.json'.format(
        opt.config_dir, 'UWaveGestureLibraryAll'))

    opt.class_type = config_dict['class_type']
    opt.piece_size = config_dict['piece_size']

    if opt.model_name == 'InterSample':
        model_paras = 'none'
    else:
        model_paras = '{}_{}'.format(opt.piece_size, opt.class_type)

    if aug1 == aug2:
        opt.aug_type = [aug1]
    elif type(aug1) is list:
        opt.aug_type = aug1 + aug2
    else:
        opt.aug_type = [aug1, aug2]

    log_dir = './log/{}/{}/{}/{}/{}'.format(
        exp, opt.dataset_name, opt.model_name, '_'.join(opt.aug_type), model_paras)

    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    file2print_detail_train = open("{}/train_detail.log".format(log_dir), 'a+')
    print(datetime.datetime.now(), file=file2print_detail_train)
    print("Dataset\tTrain\tTest\tDimension\tClass\tSeed\tAcc_max\tEpoch_max",
          file=file2print_detail_train)
    file2print_detail_train.flush()

    sum_dataset, sum_target, nb_class = load_data(
        opt.ucr_path, opt.dataset_name)
    sum_dataset = np.expand_dims(sum_dataset, 2)
    train_datasets, train_targets, val_datasets, val_targets, test_datasets, test_targets = k_fold(
        sum_dataset, sum_target)

    accu = []
    if not os.path.exists(opt.ckpt_dir):
        os.makedirs(opt.ckpt_dir)

    print('[INFO] Running at:', opt.dataset_name)
    save_path = './ucr_result.csv'
    for i, x_train in enumerate(train_datasets):
        print('{} fold start training!'.format(i))
        y_train = train_targets[i]
        x_val = val_datasets[i]
        y_val = val_targets[i]
        x_test = test_datasets[i]
        y_test = test_targets[i]

        x_train, x_val, x_test = fill_nan_value(x_train, x_val, x_test)
        x_train, x_val, x_test = normalize_per_series(
            x_train), normalize_per_series(x_val), normalize_per_series(x_test)
        if opt.model_name == 'InterSample':
            acc_max, epoch_max = pretrain_InterSampleRel(x_train, y_train, opt)
        elif 'IntraTemporal' in opt.model_name:
            acc_max, epoch_max = pretrain_IntraSampleRel(x_train, y_train, opt)
        elif 'SelfTime' in opt.model_name:
            acc_max, epoch_max, model_state_dict = pretrain_SelfTime(
                x_train, y_train, opt)
            acc_test, epoch_max_point = evaluation(x_train, y_train, x_val, y_val, x_test, y_test,
                                                   nb_class=nb_class, ckpt=None, opt=opt, ckpt_tosave=None, my_state=model_state_dict)

        accu.append(acc_test)

    accu = np.array(accu)
    acc_mean = np.mean(accu)
    acc_std = np.std(accu)

    if os.path.exists(save_path):
        result_form = pd.read_csv(save_path)
    else:
        result_form = pd.DataFrame(columns=['target', 'accuracy', 'std'])

    result_form = result_form.append(
        {'target': opt.dataset_name, 'accuracy': '%.4f' % acc_mean, 'std': '%.4f' % acc_std}, ignore_index=True)
    result_form = result_form.iloc[:, -3:]
    result_form.to_csv(save_path)


import csv

def find_person():
    look_up = input("Enter a person's last name: ")
    for i in range(0, len(age)):
        if look_up == last_name[i]:
            print(f"Found it! The person you're looking for is {first_name[i]} {last_name[i]} {age[i]}")

first_name = []
last_name = []
age = []

with open("") as csvfile:
    file = csv.reader(csvfile)
    for row in file:
        first_name.append(row[0])
        last_name.append(row[1])
        age.append(row[2])

flag = -1
i=0

found_person = find_person()

while i<len(last_name) and found_person.lower()!=last_name[i].lower():
    i+=1

if i>=len(last_name):
    print("Record not found...")
else:
    print(f"{first_name} {last_name} {age}")


"""
Plugin for probing x11
"""

from owtf.dependency_management.dependency_resolver import ServiceLocator

DESCRIPTION = " x11 Probing "

def run(PluginInfo):
    resource = ServiceLocator.get_component("resource").get_resources('X11ProbeMethods')
    return ServiceLocator.get_component("plugin_helper").CommandDump('Test Command', 'Output',
                                                                     resource, PluginInfo, [])  # No previous output


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

"""
    Application controller
"""

__author__ = 'Mohamed Ouertani'

# Standard library imports
from builtins import input
# Local application imports
from gui import Interface
from cli import CLI
from model import Ensemble
from model import Person

class Controller():

    """Controller class in MVC model for application """

    def __init__(self):
        which_view = self.view_choice()
        if which_view == "1" :
            print("Vous avez choisi un GUI")
            self.view = Interface(self)
        elif which_view == "2":
            print("Vous avez choisi un CLI")
            self.view = CLI(self)
        self.model = Ensemble()

    @staticmethod
    def view_choice():
        """Choose between different views"""
        which_view = input("Tapez 1 pour un GUI ou 2 pour un CLI : ")
        while which_view not in ["1","2"]:
            which_view = input("Tapez 1 pour un GUI ou 2 pour un CLI : ")
        return which_view

    def start_view(self):
        """Launch the chosen view"""
        self.view.main()

    def search(self):
        """Control the search process between model and view"""
        nom = self.view.get_value("Nom")
        search_return = self.model.search_person(nom)
        self.view.search_result(search_return)

    def delete(self):
        """Control the deletion process between model and view"""
        family_name = self.view.get_value("Nom")
        if not family_name:
            message = "Veuillez insérer le nom d'une personne à supprimer"
            self.view.delete_result(message)
        else:
            search_return = self.model.search_person(family_name)
            if not search_return:
                message = "Pas de personnes à supprimer avec ce nom"
                self.view.delete_result(message)
            else:
                confirmation = self.view.delete_confirmation(search_return)
                if confirmation:
                    delete_return = self.model.delete_person(search_return)
                    self.view.delete_result(delete_return,True)

    def insert(self):
        """Control the insertion process between model and view"""
        first_name = self.view.get_value("Prenom")
        family_name = self.view.get_value("Nom")
        if not first_name or not family_name:
            message = "Veuillez insérer au moins un nom et un prénom"
            self.view.insert_result(message)
        else:
            person_to_add = self._create_person()
            insert_return = self.model.insert_person(person_to_add)
            self.view.insert_result(insert_return)

    def _create_person(self):
        """Create a person object from input"""
        person = Person(self.view.get_value("Nom"),
            self.view.get_value("Prenom"),
            self.view.get_value("Telephone"),
            self.view.get_value("Adresse"),
            self.view.get_value("Ville"))
        return person

    def command_handle(self, command_id):
        """Identify chosen function and apply appropriate method"""
        if command_id == "Chercher":
            self.search()
        elif command_id == "Effacer":
            self.delete()
        elif command_id == "Inserer":
            self.insert()

    def save(self):
        """Save data in model before exiting the application"""
        self.model.save_persons()

    def load(self):
        """Load data in model while launching the application"""
        self.model.load_persons()

if __name__ == "__main__":
    controller = Controller()
    controller.load()
    controller.start_view()
    controller.save()


'''
Things to notice:
    1. These are all function defintions, but there are no function calls.
       In other words, none of these functions will run unless they are
       invoked.
    2. Modules can import other modules. Note that this module is making use
       of the os module
'''

import os

def get_hypotenuse(side1, side2):
    return (side1 ** 2 + side2 ** 2) ** 0.5

def get_area(side1, side2):
    area = (side1 * side2) / 2
    return area

def get_perimeter(side1, side2):
    perimeter = 2 * side1 + 2 * side2
    return perimeter

def write_to_file(side1, side2, file_name='outfile.csv', delimiter=', ', print_header=False, mode='a'):
    # create a file to write to:
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_name = os.path.join(dir_path, file_name)
    out_file = open(file_name, mode)

    # print a header if the client requests one:
    if print_header:
        print(
            'side1',
            'side2',
            'hypotenuse',
            'area',
            'perimeter',
            sep=delimiter,
            file=out_file
        )
    # print the calculations to a file:
    print(
        side1,
        side2,
        get_hypotenuse(side1, side2),
        get_area(side1, side2),
        get_perimeter(side1, side2),
        sep=delimiter,
        file=out_file
    )


from collections import deque
"""
Definition for a point.
class Point:
    def __init__(self, a=0, b=0):
        self.x = a
        self.y = b
"""

class Solution:
    """
    @param grid: a chessboard included 0 (false) and 1 (true)
    @param source: a point
    @param destination: a point
    @return: the shortest path
    """
    def shortestPath(self, grid, source, destination):
        # write your code here
        if not grid or not grid[0]:
            return -1

        seen = set()
        queue = deque()
        queue.append(source)
        seen.add((source.x, source.y))
        steps = 0

        while queue:
            size = len(queue)
            for _ in range(size):
                point = queue.popleft()
                x, y = point.x, point.y
                if (x, y) == (destination.x, destination.y):
                    return steps
                for direction in [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,1]]:
                    newx = x + direction[0]
                    newy = y + direction[1]
                    if self.isvalid(newx, newy, grid, seen):
                        seen.add((newx, newy))
                        queue.append(Point(newx,newy))
            steps += 1
        return -1

    def isvalid(self, x, y, grid, seen):
        return 0 <= x <= len(grid) - 1 \
        and 0 <= y <= len(grid[0]) - 1 \
        and not grid[x][y] \
        and (x, y) not in seen


from ray import tune

from tableshift.models.compat import OPTIMIZER_ARGS

# Superset of https://arxiv.org/pdf/2106.11959.pdf, Table 15,
# in order to cover hparams for other searches that derive from this space.
_DEFAULT_NN_SEARCH_SPACE = {
    "d_hidden": tune.choice([64, 128, 256, 512, 1024]),
    "lr": tune.loguniform(1e-5, 1e-1),
    "n_epochs": tune.qrandint(5, 100, 5),
    "num_layers": tune.randint(1, 8),
    "dropouts": tune.uniform(0., 0.5),
    "weight_decay": tune.loguniform(1e-6, 1.)
}

_aldro_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    "eta_pi": tune.loguniform(1e-5, 1e-1),
    'r': tune.uniform(1e-5, 0.5),
    'clip_max': tune.loguniform(1e-1, 10),
    'eps': tune.loguniform(1e-4, 1e-1),
}

_dann_search_space = {
    **{k: v for k, v in _DEFAULT_NN_SEARCH_SPACE.items()
       if k not in OPTIMIZER_ARGS},
    # Below parameters all use the specified grid from DomainBed.
    # G (classifier) hyperparameters
    "lr_g": _DEFAULT_NN_SEARCH_SPACE["lr"],
    "weight_decay_g": _DEFAULT_NN_SEARCH_SPACE["weight_decay"],
    # D (discriminator) hyperparameters
    "lr_d": _DEFAULT_NN_SEARCH_SPACE["lr"],
    "weight_decay_d": _DEFAULT_NN_SEARCH_SPACE["weight_decay"],
    # Adversarial training parameters
    "d_steps_per_g_step": tune.loguniform(1, 2 ** 3, base=2),
    "grad_penalty": tune.loguniform(1e-2, 1e1),
    "loss_lambda": tune.loguniform(1e-2, 1e2),
}

_deepcoral_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    # Same range as DomainBed, see
    # https://github.com/facebookresearch/DomainBed/blob/main/domainbed
    # /hparams_registry.py#L72
    "mmd_gamma": tune.loguniform(1e-1, 1e1),
}

_dro_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    "geometry": tune.choice(["cvar", "chi-square"]),
    # Note: training is very slow for large values of uncertainty
    # set size (larger than ~0.5) for chi-square geometry, particularly
    # when the learning rate is small.
    "size": tune.loguniform(1e-4, 1.),

}

_irm_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    # Same tuning space as  for IRM parameters as DomainBed; see
    # https://github.com/facebookresearch/DomainBed/blob
    # /2ed9edf781fe4b336c2fb6ffe7ca8a7c6f994422/domainbed/hparams_registry.py
    # #L61
    "irm_lambda": tune.loguniform(1e-1, 1e5),
    "irm_penalty_anneal_iters": tune.loguniform(1, 1e4)
}

# Similar to XGBoost search space; however, note that LightGBM is not
# use in the study from which the XGBoost space is derived.
_lightgbm_search_space = {
    "learning_rate": tune.loguniform(1e-5, 1.),
    "min_child_samples": tune.choice([1, 2, 4, 8, 16, 32, 64]),
    "min_child_weight": tune.loguniform(1e-8, 1e5),
    "subsample": tune.uniform(0.5, 1),
    "max_depth": tune.choice([-1] + list(range(1, 31))),
    "colsample_bytree": tune.uniform(0.5, 1),
    "colsample_bylevel": tune.uniform(0.5, 1),
    "reg_alpha": tune.loguniform(1e-8, 1e2),
    "reg_lambda": tune.loguniform(1e-8, 1e2),
}

_mixup_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    # Same range as DomainBed, see
    # https://github.com/facebookresearch/DomainBed/blob
    # /2ed9edf781fe4b336c2fb6ffe7ca8a7c6f994422/domainbed/hparams_registry.py
    # #L66
    "mixup_alpha": tune.uniform(10 ** -1, 10 ** 1)
}

_mmd_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    # Same range as DomainBed, see
    # https://github.com/facebookresearch/DomainBed/blob/main/domainbed
    # /hparams_registry.py#L72
    "mmd_gamma": tune.loguniform(1e-1, 1e1),
}

_wcs_search_space = {
    "C_domain": tune.choice([0.001, 0.01, 0.1, 1., 10., 100., 1000.]),
    "C_discrim": tune.choice([0.001, 0.01, 0.1, 1., 10., 100., 1000.]),

}
# Matches https://arxiv.org/pdf/2106.11959.pdf; see Table 16
_xgb_search_space = {
    "learning_rate": tune.loguniform(1e-5, 1.),
    "max_depth": tune.randint(3, 10),
    "min_child_weight": tune.loguniform(1e-8, 1e5),
    "subsample": tune.uniform(0.5, 1),
    "colsample_bytree": tune.uniform(0.5, 1),
    "colsample_bylevel": tune.uniform(0.5, 1),
    "gamma": tune.loguniform(1e-8, 1e2),
    "lambda": tune.loguniform(1e-8, 1e2),
    "alpha": tune.loguniform(1e-8, 1e2),
    "max_bin": tune.choice([128, 256, 512])
}

_expgrad_search_space = {
    **_xgb_search_space,
    "eps": tune.loguniform(1e-4, 1e0),
    "eta0": tune.choice([0.1, 0.2, 1.0, 2.0]),
}

_group_dro_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    "group_weights_step_size": tune.loguniform(1e-4, 1e0),
}

# Superset of https://arxiv.org/pdf/2106.11959.pdf, Table 14.
_resnet_search_space = {
    # Drop the key for d_hidden;
    **{k: v for k, v in _DEFAULT_NN_SEARCH_SPACE.items() if k != "d_hidden"},
    "n_blocks": tune.randint(1, 16),
    "d_main": tune.randint(64, 1024),
    "hidden_factor": tune.randint(1, 4),
    "dropout_first": tune.uniform(0., 0.5),  # after first linear layer
    "dropout_second": tune.uniform(0., 0.5),  # after second/hidden linear layer
}

# Superset of https://arxiv.org/pdf/2106.11959.pdf, Table 13
_ft_transformer_search_space = {
    # Drop the key for d_hidden;
    **{k: v for k, v in _DEFAULT_NN_SEARCH_SPACE.items() if k != "d_hidden"},
    "n_blocks": tune.randint(1, 4),
    "residual_dropout": tune.uniform(0, 0.2),
    "attention_dropout": tune.uniform(0, 0.5),
    "ffn_dropout": tune.uniform(0, 0.5),
    "ffn_factor": tune.uniform(2 / 3, 8 / 3),
    # This is feature embedding size in Table 13 above. Note that Table 13
    # reports this as a uniform (64, 512) parameter, but d_token *must* be a
    # multiple of n_heads, which is fixed at 8, so we use this
    # simpler/equivalent range instead.
    "d_token": tune.choice([64, 128, 256, 512])
}

_vrex_search_space = {
    **_DEFAULT_NN_SEARCH_SPACE,
    "vrex_lambda": tune.loguniform(1e-1, 1e5),
    "vrex_penalty_anneal_iters": tune.loguniform(1, 1e4),
}

_node_search_space = {
    **{k: v for k, v in _DEFAULT_NN_SEARCH_SPACE.items() if
       k in ("lr", "weight_decay")},
    # NODE uses much smaller batch size (256x smaller: 4096 vs. 16), so we also
    # train for fewer epochs to keep the number of gradient updates more closely
    # matched to other methods.
    "n_epochs": tune.qrandint(1, 5, 1),
    # Below is identical search space to NODE paper (Appendix A.2.3). Note
    # that they use a fixed learning rate of 10e-3, but we tune learning
    # rate, and they use "the maximal batch size that fits in GPU memory" but
    # we instead keep the batch size consistent at a size that fits in memory
    # regardless of model (and tune LR) instead of manually tuning the batch
    # size.
    "num_layers": tune.choice([2, 4, 8]),
    "total_tree_count": tune.choice([1024, 2048]),
    "depth": tune.choice([6, 8]),  # "tree depth" in A.2.3
    "tree_dim": tune.choice([2, 3])  # "tree output dim" in A.2.3
}

_saint_search_space = {
    **{k: v for k, v in _DEFAULT_NN_SEARCH_SPACE.items() if
       k in ("lr", "weight_decay")},
    # SAINT uses much smaller batch size (256x smaller: 4096 vs. 16) than
    # other models in our suite, so we also train for fewer epochs to keep
    # the number of gradient updates more closely matched to other methods.
    "n_epochs": tune.qrandint(1, 5, 1),
    "dim": tune.choice([4, 8, 12, 16, 32]),

    # NOTE: this parameter is ignored when attentiontype is set to 'row' or
    # 'colrow', as in original SAINT paper/code we use depth==1 for those
    # attention types. See utils.get_estimator().
    "depth": tune.choice([4, 6]),
    "ff_dropout": tune.uniform(0.1, 0.8),
    "heads": tune.choice([4, 8]),
    "attentiontype": tune.choice(['row', 'col', 'colrow']),
}

_tabtransformer_search_space = {
    **{k: v for k, v in _DEFAULT_NN_SEARCH_SPACE.items() if
       k in ("lr", "n_epochs", "weight_decay")},
    "ff_dropout": tune.uniform(0., 0.5),
    "attn_dropout": tune.uniform(0., 0.5, ),
    "dim": tune.choice([32, 64, 128, 256]),
    "depth": tune.choice([3, 4, 5, 6]),
    "heads": tune.choice([2, 4, 8]),
}

search_space = {
    "aldro": _aldro_search_space,
    "dann": _dann_search_space,
    "deepcoral": _deepcoral_search_space,
    "dro": _dro_search_space,
    "expgrad": _expgrad_search_space,
    "ft_transformer": _ft_transformer_search_space,
    "group_dro": _group_dro_search_space,
    "irm": _irm_search_space,
    "label_group_dro": _group_dro_search_space,
    "lightgbm": _lightgbm_search_space,
    "mixup": _mixup_search_space,
    "mlp": _DEFAULT_NN_SEARCH_SPACE,
    "mmd": _mmd_search_space,
    "node": _node_search_space,
    "resnet": _resnet_search_space,
    "saint": _saint_search_space,
    "tabtransformer": _tabtransformer_search_space,
    "vrex": _vrex_search_space,
    "wcs": _wcs_search_space,
    "xgb": _xgb_search_space,
}


# create a list containing all of even numbers up to 20
evens = []

for n in range(20):
    # loop through these numbers
    # check if they're even
    # if they are, add it to our list
    if n % 2 == 0:
        evens.append(n)
print(evens)

# let's use a list comprehension to do the same thing
evens = [n for n in range(20)if n % 2 == 0]

print(evens)

# steps for creating a list comprehension
# 1. write out how you'd do the same logic with a normal for loop
# 2. Take the for loop you wrote and "translate" it into list comprehension

squares = []

# populate a list with all of the squares up to 20
for n in range(20):
    squares.append(n*n)
print(squares)

squares2 = [n*n for n in range(20)]

print(squares2)


"""
https://open.kattis.com/problems/softpasswords
Author: https://github.com/smh997/
"""
s = input()
p = input()
res = ''
for a in p:
    res += a if a.isdigit() else a.upper() if a.islower() else a.lower()
if s == p or (len(p)+1 == len(s) and ((p == s[:len(s)-1] and s[len(s)-1].isdigit()) or (p == s[1:] and s[0].isdigit()))) or res == s:
    print('Yes')
else:
    print('No')


import csv
import json
import os.path
import shutil
from pathlib import Path
from tempfile import NamedTemporaryFile

from schema import And, Schema, Use

from src.service.sellers import SellersService
from src.utils.date_validation import date_validation

"""Static class for actions between the sales and the database"""

class SalesService:
    _schema = Schema(
        {
            "seller": And(
                SellersService.validate_seller,
                error=f"Seller name not found. "
                f"Avaliable sellers are: {SellersService.avaliable_sellers()}",
            ),
            "customer": And(Use(str), error="Customer name must be a string"),
            "date": And(date_validation, error="Date must be in yyyy-mm-dd format"),
            "value": And(Use(float), error="Sale value must be a float"),
            "item": And(Use(str), error="Item name must be a string"),
        }
    )
    _csv_path = (Path(__file__).parent / "../data/rank.csv").resolve()
    _sales_path = (Path(__file__).parent / "../data/sales.json").resolve()
    _ordered_ranking = list()

    """Validates the provided dict with user data upon the pre-defined schema"""

    @classmethod
    def validate_schema(cls, data: dict) -> dict:

        data = {k: v for k, v in data.items() if v is not None}

        return cls._schema.validate(data)

    """After validation, data can be inserted both in json as in the csv file"""

    @classmethod
    def insert_data(cls, data: dict) -> None:
        tempfile = NamedTemporaryFile(mode="w", delete=False)
        file_exists = os.path.exists(cls._sales_path)

        # If the user is appending data, we recover the existing json,
        # otherwise we create a new one
        if file_exists:
            with open(cls._sales_path, "r", encoding="utf-8") as current_file, tempfile:
                current_json = json.load(current_file)
                current_json.append(data)
                json.dump(current_json, tempfile)
            shutil.move(tempfile.name, cls._sales_path)
        else:
            with open(cls._sales_path, "w", encoding="utf-8") as current_file:
                new_json = [data]
                json.dump(new_json, current_file)

        tempfile.close()
        tempfile = NamedTemporaryFile(mode="w", delete=False)

        # CSV was chosen due to it low complexity,
        # since we just want to store the relation between each seller
        # and their rank
        with open(
            cls._csv_path, "r", encoding="utf-8", newline=""
        ) as rank_file, tempfile:
            csv_reader = csv.DictReader(
                rank_file, delimiter=",", fieldnames=["seller", "value"]
            )
            csv_writer = csv.DictWriter(
                tempfile, delimiter=",", fieldnames=["seller", "value"]
            )
            for row in csv_reader:
                if row["seller"] == data["seller"]:
                    row["value"] = float(row["value"]) + data["value"]
                csv_writer.writerow(row)
        shutil.move(tempfile.name, cls._csv_path)
        tempfile.close()

    """Outputs a json object for each record of a sale,
    ordered by sellers performances"""

    @classmethod
    def print_sale_list(cls) -> None:
        with open(cls._csv_path, "r", encoding="utf-8") as rank_csv:
            csv_reader = csv.DictReader(rank_csv, fieldnames=["seller", "value"])
            for row in csv_reader:
                index = 0
                for rank in cls._ordered_ranking:
                    if rank[1] > row["value"]:
                        index = index + 1
                        continue
                cls._ordered_ranking.insert(index, tuple([row["seller"], row["value"]]))

        with open(cls._sales_path, "r", encoding="utf-8") as sales_list:
            sales_list = json.load(sales_list)

        for seller in cls._ordered_ranking:
            for sale in sales_list:
                if seller[0] == sale["seller"]:
                    print(json.dumps(sale))


import threading
import socket
import docker
import time
import random
from backend.logger import Logger

socket.setdefaulttimeout(3)
logger = Logger(__name__, log_file="auth.log")

def socket_port(ip, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = s.connect_ex((ip, port))
        if result == 0:
            return True
        return False
    except:
        return True

class Sandbox:
    def __init__(self) -> None:
        port = random.randint(9000, 10000)
        while socket_port("localhost", port):
            port += 1
        self.port = port
        self.time = time.time()
        self.client = docker.from_env()
        self.container = self.client.containers.run(
            "xdeviation/sandbox:latest", detach=True, ports={"7681/tcp": self.port}
        )

    def __del__(self) -> None:
        try:
            self.container.stop()
        except Exception as e:
            logger.exception(e)

    def stop(self) -> None:
        try:
            self.container.stop()
        except Exception as e:
            logger.exception(e)

from contextlib import contextmanager
from typing import Generator

class ChPoolError(Exception):
    """A generic exception that may be raised by ChPool"""

class TooManyConnections(ChPoolError):
    """Raised when attempting to use more than connections_max clients."""

class ChPool:
    # pylint: disable=too-many-instance-attributes
    def __init__(self, **kwargs):
        self.connections_min = kwargs.pop("connections_min", 1)
        self.connections_max = kwargs.pop("connections_max", 20)

        self.connection_args = {"host": kwargs.pop("host", "localhost"), **kwargs}
        self.closed = False
        self._pool = []
        self._used = {}

        # similar to psycopg2 pools, _rused is used for mapping instances of conn
        # to their respective keys in _used
        self._rused = {}
        self._keys = 0
        self._lock = threading.Lock()

        for _ in range(self.connections_min):
            self._connect()

    def _connect(self, key: str = None) -> Sandbox:
        sandbox = Sandbox()
        if key is not None:
            self._used[key] = sandbox
            self._rused[id(sandbox)] = key
        else:
            self._pool.append(sandbox)
        return sandbox

    def _get_key(self):
        self._keys += 1
        return self._keys

    def pull(self, key: str = None) -> Sandbox:
        self._lock.acquire()
        try:
            if self.closed:
                raise ChPoolError("pool closed")

            if key is None:
                key = self._get_key()

            if key in self._used:
                return self._used[key]

            if self._pool:
                self._used[key] = sandbox = self._pool.pop()
                self._rused[id(sandbox)] = key
                return sandbox

            if len(self._used) >= self.connections_max:
                raise TooManyConnections("too many connections")
            return self._connect(key)
        finally:
            self._lock.release()

    def push(self, sandbox: Sandbox = None, key: str = None, close: bool = False):
        self._lock.acquire()
        try:
            if self.closed:
                raise ChPoolError("pool closed")
            if key is None:
                key = self._rused.get(id(sandbox))
                if key is None:
                    raise ChPoolError("trying to put unkeyed client")
            if len(self._pool) < self.connections_min and not close:
                # TODO: verify connection still valid
                if time.time() - sandbox.time < 3600:
                    self._pool.append(sandbox)
            else:
                sandbox.stop()

            # ensure thread doesn't put connection back once the pool is closed
            if not self.closed or key in self._used:
                del self._used[key]
                del self._rused[id(sandbox)]
        finally:
            self._lock.release()

    def cleanup(self):
        self._lock.acquire()
        try:
            if self.closed:
                raise ChPoolError("pool closed")
            for sandbox in self._pool + list(self._used.values()):
                try:
                    sandbox.stop()
                # TODO: handle problems with stop
                except Exception:
                    pass
            self.closed = True
        finally:
            self._lock.release()

    @contextmanager
    def get_sandbox(self, key: str = None) -> Generator[Sandbox, None, None]:
        """A clean way to grab a client via a contextmanager.
        Args:
            key: If known, the key of the client to grab.
        Yields:
            Client: a clickhouse-driver client
        """
        sandbox = self.pull(key)
        try:
            yield sandbox
        finally:
            self.push(sandbox=sandbox)


import logging
import threading

from flask import request, url_for
from flask.ext.api import FlaskAPI, status, exceptions

FORMAT = '%(asctime)-15s %(name)s %(threadName)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
log = logging.getLogger()

app = FlaskAPI(__name__)

if __name__ == "__main__":
    log.info('start')
    rest_service_thread = threading.Thread(name='reset_service', target=app.run, kwargs=dict(debug=False))
    rest_service_thread.start()
    log.info('main thread is mine!')
    import time
    while True:
        print('this is main thread' + time.ctime())
        time.sleep(1)
    rest_service_thread.join()


#Q1.

p1 = input("Choose from rock, paper or scissors: ")
p2 = input("Choose from rock, paper or scissors: ")
r = "rock"
p = "paper"
s = "scissors"
q = "quit"
if p1 == r and p2 == p:
    print("Congratulations! Player 2 has won!")
elif p1 == r and p2 == s:
    print("Congratulations! Player 1 has won!")
elif p1 == p and p2 == r:
    print("Congratulations! Player 1 has won!")
elif p1 == p and p2 == s:
    print("Congratulations! Player 2 has won!")
elif p1 == s and p2 == r:
    print("Congratulations! Player 2 has won!")
elif p1 == s and p2 == p:
    print("Congratulations! Player 1 has won!")
elif p1 == p2:
    print("It's a draw! Try Again")
    p1 = input("Choose from rock, paper or scissors: ")
    p2 = input("Choose from rock, paper or scissors: ")
elif p1 == q or p2 == q:
    print("Game ended")
else:
    print("Play again")
    p1 = input("Choose from rock, paper or scissors: ")
    p2 = input("Choose from rock, paper or scissors: ")

#---------------------------------------------------------------------

#Q2.

a = int(input("Enter the input in seconds: "))
d = a//86400
h = (a%86400)//3600
m = ((a%86400)%3600)//60
s = (((a%86400)%3600)%60)
print("The days, hours, minutes and seconds(d:h:m:s) are as follows:")
print(f"{d}:{h}:{m}:{s}")

#---------------------------------------------------------------------


from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.db.models import Q
from django.db.models.functions import Lower
from .models import Product, Category
from .forms import ProductForm
import cloudinary.uploader
from django.contrib.auth.decorators import user_passes_test

def all_products(request):
    """ A view that displays all products."""

    products = Product.objects.all()
    available_items = Product.objects.all().values('in_stock')
    query = None
    categories = None
    sort = None
    direction = None

    if request.GET:
        if 'sort' in request.GET:
            sortkey = request.GET['sort']
            sort = sortkey
            if sortkey == 'name':
                sortkey = 'lower_name'
                products = products.annotate(lower_name=Lower('name'))

            if sortkey == 'category':
                sortkey = 'category__name'

            if 'direction' in request.GET:
                direction = request.GET['direction']
                if direction == 'desc':
                    sortkey = f'-{sortkey}'
            products = products.order_by(sortkey)

        if 'category' in request.GET:
            categories = request.GET['category'].split(',')
            products = products.filter(category__name__in=categories)
            categories = Category.objects.filter(name__in=categories)

        if 'q' in request.GET:
            query = request.GET['q']
            if not query:
                messages.error(
                    request, "Please type what you are looking for...")
                return redirect(reverse('products'))

            queries = Q(
                name__icontains=query) | Q(description__icontains=query)
            products = products.filter(
                queries)

    current_sorting = f'{sort}_{direction}'
    available_items = Product.objects.filter(in_stock=True)

    context = {
        'products': products,
        'search_term': query,
        'current_categories': categories,
        'current_sorting': current_sorting,
        'available_items': available_items,
    }
    return render(request, 'products/products.html', context)

def product_detail(request, product_id):
    """ A view to return an individual product detail page """

    product = get_object_or_404(Product, pk=product_id)

    context = {
        'product': product,
    }

    return render(request, 'products/product_detail.html', context)

@user_passes_test(lambda u: u.is_superuser)
def add_product(request):
    """ Add a product to the store """
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data['image']
            image_data = cloudinary.uploader.upload(image)['secure_url']

            product = form.save(commit=False)
            product.image = image_data
            product.image_url = image_data
            product.save()

            messages.success(request, 'Successfully added product!',)
            return redirect(reverse('product_detail', args=[product.id]))
        else:
            messages.error(
                request,
                """
                Failed to add product.
                Please ensure the form is valid.
                """)
    else:
        form = ProductForm()

    template = 'products/add_product.html'
    context = {
        'form': form,
    }

    return render(request, template, context)

@user_passes_test(lambda u: u.is_superuser)
def edit_product(request, product_id):
    """ Edit a product in the store """
    product = get_object_or_404(Product, pk=product_id)
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES, instance=product)
        if form.is_valid():
            if 'image' in request.FILES:
                image = form.cleaned_data['image']
                image_data = cloudinary.uploader.upload(
                    image)['secure_url']
            else:
                image_data = product.image

            product = form.save(commit=False)
            product.image = image_data
            product.save()

            messages.success(request, 'Successfully updated product!')
            return redirect(reverse('product_detail', args=[product.id]))
        else:
            messages.error(
                request, 'Failed to update product. Please submit valid form.')
    else:
        form = ProductForm(instance=product)
        messages.info(request, f'You are editing {product.name}')

    template = 'products/edit_product.html'
    context = {
        'form': form,
        'product': product,
    }

    return render(request, template, context)

@user_passes_test(lambda u: u.is_superuser)
def delete_product(request, product_id):
    """ Delete a product from the store """
    product = get_object_or_404(Product, pk=product_id)
    basket = request.session.get('basket', {})
    if basket:
        messages.error(request, """There are items in you basket!
                                Please remove all basket items before
                                editing the product inventory.""")
    else:
        product.delete()
        messages.success(request, 'Product deleted!')
    return redirect(reverse('products'))


import os
import sys

cwd = os.getcwd()
sys.path.append(cwd)
from Task5.src.server import server

# buffer= 1024
buffer = 10
host = "localhost"
port = 50007

mural = server(buffer=buffer, host=host, port=port)
mural.mtd_server_start()


import string

def main():
    word = input("Enter a word: ")
    shortened_word = shorten(word)
    print("Shortened word:", shortened_word)

def shorten(word):
    vowels = set(['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'])
    punctuation = set(string.punctuation)
    result = ''.join(char for char in word if char not in vowels and char not in punctuation)
    return result

if __name__ == "__main__":
    main()


n, m = [int(i) for i in input().split(' ')]
if n >= m:
    print(n-m)
else:
    count = 0
    while m > n:
        if m % 2 == 0:
            m //= 2
            count += 1
        else:
            m += 1
            count += 1
    print(count + (n-m))


from matplotlib import pyplot as plt
import torch
from data.data import ForceData
from model.trans_forcer import TransForcer

def vis_forcemap(rgb, inf, targets, mask, force_maps):
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(3,3,1)
    ax.imshow(rgb.squeeze().cpu().detach().numpy().transpose(1,2,0))
    ax.set_title("rgb")

    ax = fig.add_subplot(3,3,2)
    ax.imshow(inf.squeeze().cpu().detach().numpy().transpose(1,2,0))
    ax.set_title("inf")

    ax = fig.add_subplot(3,3,3)
    ax.imshow(mask.cpu().detach().numpy().transpose(1,2,0)*255)
    ax.set_title("mask")

    ax = fig.add_subplot(3,3,4)
    ax.imshow(targets[0].cpu().detach().numpy().transpose(1,2,0) * 255, cmap='jet', vmin=0, vmax=255)
    ax.set_title("x_origin")

    ax = fig.add_subplot(3,3,5)
    ax.imshow(targets[1].cpu().detach().numpy().transpose(1,2,0) * 255, cmap='jet', vmin=0, vmax=255)
    ax.set_title("y_origin")

    ax = fig.add_subplot(3,3,6)
    ax.imshow(targets[2].cpu().detach().numpy().transpose(1,2,0) * 255, cmap='jet', vmin=0, vmax=255)
    ax.set_title("z_origin")

    ax = fig.add_subplot(3,3,7)
    ax.imshow(force_maps[0].squeeze(0).cpu().detach().numpy().transpose(1,2,0) * 255, cmap='jet', vmin=0, vmax=255)
    ax.set_title("x_predict")

    ax = fig.add_subplot(3,3,8)
    ax.imshow(force_maps[1].squeeze(0).cpu().detach().numpy().transpose(1,2,0) * 255, cmap='jet', vmin=0, vmax=255)
    ax.set_title("y_predict")

    ax = fig.add_subplot(3,3,9)
    ax.imshow(force_maps[2].squeeze(0).cpu().detach().numpy().transpose(1,2,0) * 255, cmap='jet', vmin=0, vmax=255)
    ax.set_title("z_predict")

    fig.savefig("result480.png")

if __name__ == "__main__":
    data_path = "src/data2"
    checkout_path = "stats_10_5/best.pth"
    checkpoint = torch.load(checkout_path)

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    img_shape = (256, 256)
    decoder_params = {"depth": 4, "hidden_dim": 96, "norm_type": dict(type="BN"), "act_type": dict(type="LeakyReLU")}
    net = TransForcer(in_channels=6, window_size=8, input_shape=img_shape, checkout_path=checkout_path, use_checkout=False, **decoder_params)
    net.load_state_dict(checkpoint)
    net.eval()
    net.to(device)

    dataset = ForceData(data_path)
    rgb, inf, targets, mask = dataset[480]

    rgb = rgb.unsqueeze(0)
    rgb = rgb.to(device)
    inf = inf.unsqueeze(0)
    inf = inf.to(device)
    mask = mask.to(device)
    for target in targets:
        target.to(device)

    force_maps = net(rgb, inf)

    vis_forcemap(rgb, inf, targets, mask, force_maps)


import urllib.request
import json
import csv

input_file = 'D:/Projects/Pycharm/SIR/Data/55/4167944869092927/uid'
output_file = 'D:/Projects/Pycharm/SIR/Data/55/4167944869092927/uid_loc'

#设置代理IP
proxy_addr="122.241.72.191:808"
proxy_addr_1 = "113.121.255.0:808"

#定义页面打开函数
def use_proxy(url,proxy_addr):
    req = urllib.request.Request(url)
    req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0")
    proxy = urllib.request.ProxyHandler({'http': proxy_addr})
    opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
    urllib.request.install_opener(opener)
    data = urllib.request.urlopen(req).read().decode('utf-8', 'ignore')
    return data

#发帖数，粉丝数，性别，关注数
def get_userInfo(id):
    judge = 1
    url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value='+id
    while judge == 1:
        try:
            data = use_proxy(url,proxy_addr)
            judge = 0
        except Exception as e:
            print(1)
    try:
        content = json.loads(data)
    except Exception as e:
        print(2)
        filewriter = [id, e]
        return filewriter
    statuses_count = content.get('data').get('userInfo').get('statuses_count')
    fensi = content.get('data').get('userInfo').get('followers_count')
    gender = content.get('data').get('userInfo').get('gender')
    guanzhu = content.get('data').get('userInfo').get('follow_count')
    #城市另外一个数据包
    # 获取微博主页的containerid，爬取城市需要,存在两种不一样的数据表
    try:
        containerid = content.get('data').get('tabsInfo').get('tabs')[0].get('containerid')
    except Exception as e:
        print(3)
        filewriter = [id,e]
        return filewriter
    url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + str(id) + '&containerid=' + str(containerid)
    #print(containerid)
    judge = 1
    while judge == 1:
        try:
            data = use_proxy(url, proxy_addr_1)
            judge = 0
        except Exception as e:
            print(4)
    content = json.loads(data)
    #print(content)
    cards = content.get('data').get('cards')
    #print(cards)
    location = cards[0].get('card_group')[0].get('item_content')
    #print(statuses_count,fensi,gender,guanzhu,location)
    filewriter = [id, statuses_count, fensi, gender, guanzhu, location]
    return filewriter

if __name__ == '__main__':
    csvfile_r = open(input_file, "r", encoding='gbk')#输入
    read = csv.reader(csvfile_r)
    csvfile_w = open(output_file, "w", newline='')#输出
    writer = csv.writer(csvfile_w)
    fileHeader = ["UID", "发帖数", "粉丝数", "性别", "关注数", "城市"]
    writer.writerow(fileHeader)
    i = 1
    for uid in read:
        j = 0
        while j < 3:
            try:
                term = get_userInfo(uid[0])
                j = 5
            except Exception as e:
                j = j + 1
                print(e)
        if j == 3:
            term = [id]
        writer.writerow(term)
        i = i+1
        if i % 200 == 0:
            print(i)
    csvfile_r.close()
    csvfile_w.close()


def test(s, name):
    s = s.replace(" ", "").lower()
    for letter in name.lower():
        flag = 0
        for i in range(len(s.replace(" ", ""))):
            if letter == s.replace(" ", "").lower()[i]:
                s = s[i+1:]
                name = name[1:]
                flag = 1
                break
        if len(name) == 0:
            return True
        if flag == 0:
            return False

print(test("ppipip","Pippi"))


from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from ..models import Contato
from ..serializers import ContatoSerializer

# FBV
@api_view(http_method_names=['get', 'post'])
def agenda_api_list_v1(request):
    if request.method == 'GET':
        contatos = Contato.objects.all()
        serializer = ContatoSerializer(
            instance=contatos,
            many=True,
            context={'request': request},
        )
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ContatoSerializer(
            data=request.data,
            context={'request': request},
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(['get', 'pathc', 'delete'])
def agenda_api_detail_v1(request, pk):
    contato = get_object_or_404(
        Contato.objects.filter(),
        pk=pk,
    )
    if request.method == 'GET':
        serializer = ContatoSerializer(
            instance=contato,
            many=False,
            context={'request': request},
        )
        return Response(serializer.data)
    elif request.method == 'PATCH':
        serializer = ContatoSerializer(
            instance=contato,
            data=request.data,
            many=False,
            partial=True,
            context={'request': request},
        )
        return Response(serializer.data)
    elif request.method == 'DELETE':
        contato.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


import unittest
import os

from pythia.journal.diagnostics import (info, debug, warning, error, firewall)
from pythia.pyre.applications.Script import Script

class TestFacilities(unittest.TestCase):

    def test_console(self):
        app = JournalApp()
        args = [
            "--journal.debug.debug_on=1",
            "--journal.debug.debug_off=0",
        ]
        app.run(argv=["journalapp"] + args)

    def test_colorconsole(self):
        app = JournalApp()
        args = [
            "--journal.debug.debug_on=1",
            "--journal.debug.debug_off=0",
            "--journal.device=color-console",
        ]
        app.run(argv=["journalapp"] + args)

    def test_file(self):
        filename = "journalapp.log"

        app = JournalApp()
        args = [
            "--journal.debug.debug_on=1",
            "--journal.debug.debug_off=0",
            "--journal.device=file",
            "--journal.device.name={}".format(filename),
        ]
        app.run(argv=["journalapp"] + args)

        with open(filename, "r") as log:
            logLines = log.readlines()
            self.assertEqual(4, len(logLines))
            iLine = 2
            self.assertEqual("-- debug_on(debug)", logLines[iLine].strip())
            iLine += 1
            self.assertEqual("-- This journal should be on.", logLines[iLine].strip())
        os.remove(filename)

class JournalApp(Script):

    def __init__(self, name="journalapp"):
        Script.__init__(self, name)

    def main(self, *args, **kwds):
        debugOn = debug("debug_on")
        debugOn.activate()
        debugOn.log("This journal should be on.")
        debugOn.deactivate()
        debugOn.log("This journal should be off.")

        debugOff = debug("debug_off")
        debugOff.log("This journal should be off.")

def test_classes():
    return [TestFacilities]

if __name__ == "__main__":
    suite = unittest.TestSuite()
    for cls in test_classes():
        suite.addTest(unittest.makeSuite(cls))
    unittest.TextTestRunner(verbosity=2).run(suite)

# End of file


import random, sys
from math import *

import ogre.renderer.OGRE as Ogre
from ogre.io import OIS
from ogre.physics import bullet
from ogre.physics import OgreBulletC, OgreBulletD

from config import FrameListener
from ragdoll.character import Character

BOX_NUM = 1000
BOX_SCALE = 0.02
BOX_MASS = 20.0

TIME_SCALE = 0.1

class RagdollFrameListener(FrameListener):
    """Frame updater"""

    id = 0

    def __init__(self, renderWindow, camera, app):
        FrameListener.__init__(self, renderWindow, camera)

        self.app = app
        self.boxes = []
        # create test boxes if neccessary
        #self.create_boxes()
        self.character = Character(self.app)
        self.shot_cooldown = 0

    def create_boxes(self):
        """Create couple of boxes"""

        _scale_factor = 0.1
        for _i in xrange(BOX_NUM):
            _scale = (random.random() * 0.5 + 0.1) * _scale_factor
            _position = Ogre.Vector3((random.random() - 0.5) * 800.0,
                (random.random()) * 500.0,
                (random.random() - 0.5) * 800.0
            )
            _quat = Ogre.Quaternion(0, 0, 0, 1)
            self.boxes.append(
                self.create_box(str(_i), "Cube",
                    _position, _quat, _scale, bodyMass=100
                )
            )

    def create_box(self, id, instanceName, pos, quat, scale,
        mesh = "cube.mesh", material = "Examples/BumpyMetal",
        bodyRestitution=0.3, bodyFriction=0.3, bodyMass=10.0):
        """Create one box element"""

        _entity = self.app.sceneManager.createEntity(
            instanceName + id, mesh
        )
        _entity.setQueryFlags(1<<2)
        _entity.setCastShadows(True)
        _entity.setMaterialName(material)

        _boundingB = _entity.getBoundingBox()
        _size = _boundingB.getSize()
        _size /= 2.0 # only the half needed
        #_size *= 0.95 # Bullet margin is a bit bigger so we need a smaller size
        #_size *= scale

        _cube_shape = OgreBulletC.BoxCollisionShape(_size)
        _ph_body = OgreBulletD.RigidBody(
            instanceName + "Body" + id, self.app.world
        )

        _node = self.app.sceneManager.getRootSceneNode().createChildSceneNode()
        #_node.scale(scale, scale, scale)
        _ph_body.setShape(_node, _cube_shape,
            bodyRestitution, bodyFriction, bodyMass,
            pos, quat
        )
        _node.attachObject(_entity)
        return (_node, _entity, _cube_shape, _ph_body)

    def frameStarted(self, evt):
        if self.shot_cooldown > 0:
            self.shot_cooldown -= evt.timeSinceLastFrame

        _time = evt.timeSinceLastFrame * TIME_SCALE

        self.character.update_pre_physics(_time)
        self.app.world.stepSimulation(_time)
        self.character.update_post_physics(_time)

        return FrameListener.frameStarted(self, evt)

    def frameEnded(self, evt):
        return FrameListener.frameEnded(self, evt)

    def _processUnbufferedKeyInput(self, evt):
        if self.Keyboard.isKeyDown(OIS.KC_SPACE) and self.shot_cooldown <= 0:
            # starting position of the box
            _position = (self.app.camera.getDerivedPosition() \
                + self.app.camera.getDerivedDirection().normalisedCopy() * 10)
            # create an ordinary, Ogre mesh with texture
            _entity = self.app.sceneManager.createEntity(
               "Box" + str(self.id), "cube.mesh")
            _entity.setCastShadows(True)
            # we need the bounding box of the box to be able to set the size of the Bullet-box
            _boundingB = _entity.getBoundingBox()
            _size = _boundingB.getSize()
            _size /= 2.0 # only the half needed
            _size *= 0.96   # Bullet margin is a bit bigger so we need a smaller size
                              # (Bullet 2.76 Physics SDK Manual page 18)
            _entity.setMaterialName("Examples/BumpyMetal")
            _node = self.app.sceneManager.getRootSceneNode().createChildSceneNode()
            _node.attachObject(_entity)
            _node.scale(BOX_SCALE, BOX_SCALE, BOX_SCALE)
            _size *= BOX_SCALE                  # don't forget to scale down the Bullet-box too
            # after that create the Bullet shape with the calculated size
            _sceneBoxShape = OgreBulletC.BoxCollisionShape(_size)
            # and the Bullet rigid body
            _defaultBody = OgreBulletD.RigidBody(
               "defaultBoxRigid" + str(self.id), self.app.world
            )
            _defaultBody.setShape(
                _node, _sceneBoxShape,
                0.6, 0.6, BOX_MASS,
                _position, Ogre.Quaternion(0, 0, 0, 1)
            )
            _defaultBody.setLinearVelocity(
                  self.app.camera.getDerivedDirection().normalisedCopy() * 70.0
            )
            # push the created objects to the deques
            self.boxes.append((_entity, _node, _sceneBoxShape, _defaultBody))
            self.id += 1
            self.shot_cooldown = 2

        return FrameListener._processUnbufferedKeyInput(self, evt)


from datetime import date

class CalDate:

    def __init__(self):
        self.year=2017
        self.month=10
        self.days=29

    def deltaDate(self,year1,month1,days1,year2,month2,days2):
        d0=date(year1,month1,days1)
        d1=date(year2,month2,days2)
        result=d1-d0
        return abs(result)

##s=CalDate()
##n=s.deltaDate(2017,8,23,2017,9,24)
##print n.days
##print type(n.days)


# Для Связанного списка(LinkedList) реализуйте метод reverse() - меняющий значения всех нод(узлов) на противоположное.
# Значение первой ноды становится значением последней, значение второй, значением предпоследней.
# Примечание: при реализации не используйте список(list).
class Node:
    """Класс для узла списка. Хранит значение и указатель на следующий узел."""

    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

    def __str__(self):
        return f'Node: {self.value}'

class LinkedList:
    def __init__(self, *args):
        self.first = None
        self.last = None
        self.elem_index = 0
        if args:
            for arg in args:
                self.__add__(arg)
        self.length = None
        self.length = self.__len__()

    def __str__(self):
        if self.first is not None:
            current = self.first
            out = 'LinkedList [' + str(current.value) + ','
            while current.next is not None:
                current = current.next
                out += str(current.value) + ','
            return out[:-1] + ']'
        return 'LinkedList []'

    def __add__(self, other):
        self.add(other)

    def __iter__(self):
        self.elem_index = 0
        return self

    def __next__(self):
        node = self.__getitem__(self.elem_index)
        self.elem_index += 1
        if self.elem_index > self.__len__():
            raise StopIteration
        return node

    def __getitem__(self, index):
        i = 0
        if index > len(self):
            raise IndexError
        node = self.first
        while i != index:
            node = node.next
            i += 1
        return node

    def __setitem__(self, key, value):
        item = self.__getitem__(key)
        item.value = value

    def __len__(self):
        return self.len()

    def __reversed__(self):
        return self.reverse()

    def clear(self):
        """Очищаем список"""
        self.first = None
        self.last = None
        self.length = 0

    def add(self, value):
        """Добавляем новое значение value в конец списка"""
        self.length = None
        new_node = Node(value, None)  # Создаем новый узел
        if self.first is None:  # Если список был пуст
            self.last = new_node
            self.first = new_node
        else:
            self.last.next = new_node
            self.last = new_node
        self.length = self.__len__()

    def push(self, value):
        """Добавляет элемент со значением value в начало списка"""
        self.length = 0
        if self.first is None:  # Если список был пуст
            # self.first и self.last будут указывать на один и тотже узел
            self.last = self.first = Node(value, None)
        else:
            new_node = Node(value, self.first)
            self.first = new_node
        self.length = self.__len__()

    def insert(self, value, index):
        """Вставляет узел со значением value на позицию index"""
        item = self.__getitem__(index)
        item.value = value

    def find(self, value):
        """
        Ищет элемент со зачением value
        :param value: значение искомого элемента
        :return: индекс искомого элемента, или ???, если элемент не найден
        """
        i = 0
        node = self.first
        while i != self.__len__():
            if node.value == value:
                return i
            node = node.next
            i += 1
        raise AttributeError

    def len(self):
        if self.length:
            return self.length
        length = 0
        if self.first is not None:
            current = self.first
            while current.next is not None:
                current = current.next
                length += 1
        else:
            return 0
        return length + 1  # +1 для учета self.first

    def reverse(self):
        for i in range(self.__len__() // 2):
            self[i].value, self[self.__len__() - i - 1].value = self[self.__len__() - i - 1].value, self[i].value
        return self

if __name__ == "__main__":
    L = LinkedList(2, 4, 6, -12, 8)
    print(L)
    # print(len(L))

    print('reverse()')
    L.reverse()
    print(L)
    print(reversed(L))
    L.add(100)
    print(reversed(L))
    print(L.first)
    print(L.last)


def computegrade(score):
    if (score >= 0.9 and score <= 1.0):
        grade = "Sobresaliente"
    elif (score >=  0.8 and score < 0.9):
        grade = "Notable"
    elif (score >=  0.7 and score < 0.8):
        grade = "Bien"
    elif (score >=  0.6  and score < 0.7):
        grade = "Suficiente"
    elif (score >= 0 and grade < 0.6):
        grade = "Insuficiente"
    else:
        grade = "Error calificacion no valida"
    return grade

try:
    score = float(input("Ingrese la calificacion (0.1-1.0): "))
    grade = computegrade(score)
    print("El grado de su calificacion es:" , grade)
except:
    print("Error! Debe ingresar un valor numerico")


from django.db import models
from django.core.validators import MaxValueValidator
from ckeditor.fields import RichTextField
from colorful.fields import RGBColorField

class initmes(models.Model):
	descript = RichTextField('Mensagem de Início')

	def __str__(self):
		return self.descript

	class Meta:
		verbose_name = '1 - Mensagem Inicial'
		verbose_name_plural = '1 - Mensagens Iniciais'

class mission(models.Model):

	title = models.CharField('Título', max_length=200,)
	text = RichTextField('Texto',)

	def __str__(self):
		return self.title

	class Meta:
		verbose_name = '3 - Andamento da Missão: Texto'
		verbose_name_plural = '3 - Andamento da Missão: Texto'

class valore(models.Model):
	item = models.CharField('Missões',max_length=50,)
	valor = models.CharField('Valor', max_length=100,)

	def __str__(self):
		return self.item

	class Meta:
		verbose_name = '2 - Conquista da Empresa'
		verbose_name_plural = '2 - Conquistas da Empresa'

class astronauta(models.Model):
	APPROVAL_CHOICES = (
    ('apollo', 'Apollo'),
    ('gemini', 'Gemini'),
    ('mercury', 'Mercury'),
	)

	name = models.CharField('Nome', max_length=100,)
	texto = RichTextField()
	tipo = models.CharField(max_length=9, choices=APPROVAL_CHOICES, default='apollo',)
	photo = models.ImageField(upload_to='sitio/images/astronautas', verbose_name='Foto',)

	def __str__(self):
		return self.name

	class Meta:
		verbose_name = '5 - Astronauta'
		verbose_name_plural = '5 - Astronautas'

class portfc(models.Model):
	descript = RichTextField('Nome & Descrição da Empresa',)
	logo = models.ImageField(upload_to='sitio/images/portifolio', verbose_name='Logo',)

	def __str__(self):
		return self.descript

	class Meta:
		verbose_name = '6 - Portifólio - Em Construção'
		verbose_name_plural = '6 - Portifólio - Em Construção'

class portfl(models.Model):
	descript = RichTextField('Nome & Descrição da Empresa',)
	logo = models.ImageField(upload_to='sitio/images/portifolio', verbose_name='Logo',)

	def __str__(self):
		return self.descript

	class Meta:
		verbose_name = '7 - Portifólio - Lançado'
		verbose_name_plural = '7 - Portifólio - Lançados'

class indicador(models.Model):

	name = models.CharField('Nome', max_length=100,)
	percent = models.PositiveIntegerField(primary_key=True, validators=[MaxValueValidator(100)])
	##color = models.CharField(max_length=1, default='1')
	color= RGBColorField()

	def __str__(self):
		return self.name

	class Meta:
		verbose_name = '4 - Andamento da Missão: Indicador'
		verbose_name_plural = '4 - Andamento da Missão: Indicadores'

class choicesportf(models.Model):
	APPROVAL_CHOICES = (
    ('Em Construção', 'Em Construção'),
    ('Lançadas', 'Lançadas'),
	)

	approval = models.CharField(max_length=20, choices=APPROVAL_CHOICES, default='blank',)

	def __str__(self):
		return self.approval

	class Meta:
		verbose_name = 'Classe de empresa'
		verbose_name_plural = 'Classes de empresas'
		ordering=['approval']

class portfcl(models.Model):
	APPROVAL_CHOICES = (
    ('Em Construção', 'Em Construção'),
    ('Lançadas', 'Lançadas'),
	)

	descript = RichTextField('Nome & Descrição da Empresa',)
	logo = models.ImageField(upload_to='sitio/images/portifolio', verbose_name='Logo',)
	andament = models.CharField(max_length=20, choices=APPROVAL_CHOICES, default='Em Construção',)

	def __str__(self):
		return self.descript

	class Meta:
		verbose_name = '8 - Portifólio (Em Desenvolvimento)'
		verbose_name_plural = '8 - Portifólio (Em Desenvolvimento)'
		ordering=['descript']


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from GAN.cGANGenerator import EncoderLayer
import os

config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
tf.compat.v1.enable_eager_execution(config=config)
layers = tf.keras.layers

"""
The Discriminator is a PatchGAN.
"""

class Discriminator(tf.keras.Model):
    def __init__(self):
        super(Discriminator, self).__init__()
        initializer = tf.random_normal_initializer(0., 0.02)
        # downsample
        self.encoder_layer_1 = EncoderLayer(filters=64, kernel_size=4, apply_batchnorm=False)
        self.encoder_layer_2 = EncoderLayer(filters=128, kernel_size=4)
        self.encoder_layer_3 = EncoderLayer(filters=128, kernel_size=4)

        # conv block1
        self.zero_pad1 = layers.ZeroPadding2D()
        self.conv = tf.keras.layers.Conv2D(512, 4, strides=1, kernel_initializer=initializer, use_bias=False)
        self.bn1 = layers.BatchNormalization()
        self.ac = layers.LeakyReLU()

        # block2
        self.zero_pad2 = tf.keras.layers.ZeroPadding2D()
        self.last = tf.keras.layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)

    def call(self, y):
        """inputs can be generated image. """
        target = y
        x = target
        x = self.encoder_layer_1(x)
        x = self.encoder_layer_2(x)
        x = self.encoder_layer_3(x)

        x = self.zero_pad1(x)
        x = self.conv(x)
        x = self.bn1(x)
        x = self.ac(x)

        x = self.zero_pad2(x)
        x = self.last(x)
        return x


from tkinter import *
from tkinter.ttk import *
import random
import math
import os
import pickle
import time
import sys

class baseGame:
    def __init__(self,lowangle=False):
        self.author = "Aikko"
        self.width = 500
        self.height = 400
        self.boardwidth = 60
        self.rodheight = 60
        self.angle = -1
        self.pos= self.width/2
        self.lowangle = lowangle
        self.initAngle()
        self.save_Flag = False
        self.failedTime = 0
        self.successTime = 0
        self.maxSuccessTime = 50
        self.maxFailedTime = 50
        #=====
        self._keyDown=False
        self._keyCode=0
    def initAngle(self):
        if self.lowangle:
            _randA=random.randint(1,45)
            _randB=random.randint(135,179)
            self.angle = random.choice([_randA,_randB])
        else:
            self.angle = random.randint(1,179)

    def start(self):
        self.createCanvas()

    def createCanvas(self):
        self.root = Tk()
        self.root.title("QLearning Practice Project")
        self.root.geometry(str(self.width+1)+ "x" + str(self.height+1))
        self.root.resizable(False, False)

        self.canvas = Canvas(self.root, width=self.width, height=self.height, bg="black")
        self.canvas.pack()

        self.root.bind("<KeyPress>", self.keyPress)
        self.root.bind("<KeyRelease>", self.keyRelease)
        self.root.bind('<Destroy>', self._on_destroy)
        self.visionUpdate()
        self.root.after(10,self.actionMove)
        self.root.mainloop()

    def actionMove(self):
        if self._keyCode == 37 and self.pos > self.boardwidth*0.5:
            self.pos -= 1
            self.angleCompensate(-1,0.25)
        elif self._keyCode == 39 and self.pos < self.width-self.boardwidth*0.5:
            self.pos += 1
            self.angleCompensate(1,0.25)
        self.angleChange()
        if self.angle==0 or self.angle==180:
            self.failedTime+=1
        elif int(round(self.angle,1))==90:
            self.successTime+=1
        if self.failedTime>self.maxFailedTime:
            self.failedTime=0
            print('failed')
            self.restartGame()
        elif self.successTime>self.maxSuccessTime:
            self.successTime=0
            print('success')
            self.restartGame()
        self.visionUpdate()

        self.root.after(10,self.actionMove)

    def loseCheck(self):
        if self.angle==0 or self.angle==180:
            return True

    def winCheck(self):
        if self.angle==90:
            return True
        else:
            return False

    def checkwall(self,forwards):
        if forwards<0:
            if self.pos <= self.boardwidth*0.5:
                return False
            else:
                return True
        elif forwards>0:
            if self.pos >= self.width-self.boardwidth*0.5:
                return False
            else:
                return True
        else:
            return True

    def angleChange(self,weight=0.01):
        self.angle += (self.angle - 90) * weight
        if self.angle>180:
            self.angle=180
        if self.angle<0:
            self.angle=0

    def angleCompensate(self,forwards,rate):
        if forwards>0:
            _angleDifference=int(abs(self.angle-90)) if int(abs(self.angle-90))>1 else 1
            _attenuation=math.pow(1/_angleDifference,rate)
            self.angle += 3*_attenuation
        else:
            _angleDifference=int(abs(self.angle-90)) if int(abs(self.angle-90))>1 else 1
            _attenuation=math.pow(1/_angleDifference,rate)
            self.angle -= 3*_attenuation
        if self.angle>180:
            self.angle=180
        if self.angle<0:
            self.angle=0

    def visionUpdate(self):
        _board_y = self.height - 50
        self.canvas.delete("all")
        self.canvas.create_line(self.pos-self.boardwidth/2, _board_y, self.pos+self.boardwidth/2, _board_y, fill="white")
        self.rod_x = self.pos + self.boardwidth/2 * math.cos(math.radians(self.angle))
        self.rod_y = _board_y - self.boardwidth/2 * math.sin(math.radians(self.angle))
        self.canvas.create_line(self.pos, _board_y, self.rod_x, self.rod_y, fill="gold")
        self.root.update()

    def keyPress(self,event):
        self._keyDown=True
        self._keyCode=event.keycode

    def keyRelease(self,event):
        self._keyDown=False
        self._keyCode=0

    def restartGame(self):
        self.pos= self.width/2
        self.initAngle()
        self.visionUpdate()
        self.root.update()

    def saveDat(self):
        pass

    def _on_destroy(self, event):
        if self.save_Flag:
            self.saveDat()
        self.root.quit()

    def _Bot_keyPress(self,key):
        if key==-1:
            self._keyDown=True
            self._keyCode=37
        elif key==1:
            self._keyDown=True
            self._keyCode=39
        elif key==0:
            self._keyDown=False
            self._keyCode=0

    def _Bot_See(self):
        return int(round(self.angle,1))

class botGame(baseGame):
    def __init__(self,lowangle):
        super().__init__(lowangle)
        self.ACTIONS = ['left','stop','right'] #可用的动作
        self.action_code = {"left":-1,"stop":0,"right":1}
        self.EPSILON = 0.9 #贪婪度
        self.ALPHA = 0.1 #学习率
        self.GAMMA = 0.9 #奖励递减值
        self.save_Flag = True
        self.operatTime = 0
        self.buildingQtable()

    def createCanvas(self):
        self.root = Tk()
        self.root.title("QLearning Practice Project")
        self.root.geometry(str(self.width+301)+ "x" + str(self.height+1))
        self.root.resizable(False, False)

        self._Frame_Canvas = Frame(self.root, width=self.width, height=self.height)
        self._Frame_Canvas.place(anchor=CENTER,relx=0.5,rely=0.5,x=-151,y=0)

        self.canvas = Canvas(self._Frame_Canvas, width=self.width, height=self.height, bg="black")
        self.canvas.pack()

        self._Frame_Control = LabelFrame(self.root, width=290, height=self.height-5,text="Control")
        self._Frame_Control.place(anchor=E,relx=0.99,rely=0.5,x=2,y=0)

        self._Label_EPSILON = Label(self._Frame_Control, text="EPSILON: "+str(self.EPSILON))
        self._Label_EPSILON.place(anchor=CENTER,relx=0.5,rely=0.1,x=0,y=0)

        self._Label_ALPHA = Label(self._Frame_Control, text="ALPHA: "+str(self.ALPHA))
        self._Label_ALPHA.place(anchor=CENTER,relx=0.5,rely=0.3,x=0,y=0)

        self._Label_GAMMA = Label(self._Frame_Control, text="GAMMA: "+str(self.GAMMA))
        self._Label_GAMMA.place(anchor=CENTER,relx=0.5,rely=0.5,x=0,y=0)

        self._Scale_EPSILON = Scale(self._Frame_Control, from_=0, to=1, orient=HORIZONTAL,length=250,command=self.EPSILON_Change)
        self._Scale_EPSILON.set(self.EPSILON)
        self._Scale_EPSILON.place(anchor=CENTER,relx=0.5,rely=0.2,x=0,y=0)

        self._Scale_ALPHA = Scale(self._Frame_Control, from_=0, to=1, orient=HORIZONTAL,length=250,command=self.ALPHA_Change)
        self._Scale_ALPHA.set(self.ALPHA)
        self._Scale_ALPHA.place(anchor=CENTER,relx=0.5,rely=0.4,x=0,y=0)

        self._Scale_GAMMA = Scale(self._Frame_Control, from_=0, to=1, orient=HORIZONTAL,length=250,command=self.GAMMA_Change)
        self._Scale_GAMMA.set(self.GAMMA)
        self._Scale_GAMMA.place(anchor=CENTER,relx=0.5,rely=0.6,x=0,y=0)

        self._Button_Save = Button(self._Frame_Control, text="Save",width=25, command=self.saveDat)
        self._Button_Save.place(anchor=CENTER,relx=0.5,rely=0.8,x=0,y=0)

        self.root.bind("<KeyPress>", self.keyPress)
        self.root.bind("<KeyRelease>", self.keyRelease)
        self.root.bind('<Destroy>', self._on_destroy)
        self.visionUpdate()
        self.root.after(10,self.actionMove)
        self.root.mainloop()

    def EPSILON_Change(self,event):
        self.EPSILON = round(self._Scale_EPSILON.get(),3)
        self._Label_EPSILON.config(text="EPSILON: "+str(self.EPSILON))

    def ALPHA_Change(self,event):
        self.ALPHA = round(self._Scale_ALPHA.get(),3)
        self._Label_ALPHA.config(text="ALPHA: "+str(self.ALPHA))

    def GAMMA_Change(self,event):
        self.GAMMA = round(self._Scale_GAMMA.get(),3)
        self._Label_GAMMA.config(text="GAMMA: "+str(self.GAMMA))

    def buildingQtable(self):
        self.QTable={}
        if os.path.exists('learning_data.dat'):
            with open('learning_data.dat','rb') as f:
                _dat = pickle.loads(f.read())
                self.EPSILON,self.ALPHA,self.GAMMA,self.QTable=_dat
    def saveDat(self,*event):
        with open('learning_data.dat','wb') as f:
            _dat = pickle.dumps([self.EPSILON,self.ALPHA,self.GAMMA,self.QTable])
            f.write(_dat)
    def GetRandom(self):
        random.seed()
        return random.random()
    def GetRandomChoice(self,_act):
        random.seed()
        return random.choice(_act)
    def stateExist(self,state):
        if state in self.QTable.keys():
            return True
        else:
            return False
    def createState(self,state):
        self.QTable[state]={'left':0,'stop':0,'right':0}

    def getValue(self,state,action):
        return self.QTable[state][action]

    def getMaxAction(self,state):
        if self.stateExist(state):
            _maxAction = max(self.QTable[state],key=self.QTable[state].get)
            return _maxAction
        else:
            raise Exception('state not exist')

    def getMaxValue(self,state):
        if self.stateExist(state):
            _maxValue = self.QTable[state][self.getMaxAction(state)]
            return _maxValue
        else:
            raise Exception('state not exist')

    def action(self,_act):
        if _act=='left':
            self._Bot_keyPress(1)
        elif _act=='right':
            self._Bot_keyPress(-1)
        elif _act=='stop':
            self._Bot_keyPress(0)
    def choiceAction(self,state):
        usefulActions = []
        for action in range(len(self.ACTIONS)-1):
            if self.checkwall(action):
                usefulActions.append(self.ACTIONS[action])
        if (self.GetRandom() > self.EPSILON) or (not self.stateExist(state)):  #非贪婪 or 或者这个 state 还没有探索过
            if not self.stateExist(state):
                self.createState(state)
            action_name = self.GetRandomChoice(usefulActions)
        else:
            if not self.stateExist(state):
                self.createState(state)
            action_name = self.getMaxAction(state)    # 贪婪模式
        return action_name
    def doAction(self,action):
        self._Bot_keyPress(self.action_code[action])

    def timeReward(self):
        _div=self.operatTime
        if _div==0:
            _div=1
        return 500/_div

    def feedback(self):
        _angle=self._Bot_See()
        _timePunish = self.timeReward()
        if _angle==90:
            return 50 + _timePunish
        elif _angle==180 or _angle==0:
            return -20

        return round((math.pow(1/abs(_angle-90),0.25)-1.1)*10/3,2)

    def actionMove(self):
        S=self._Bot_See()               # 观察状态
        A=self.choiceAction(S)           # 选择行为
        q_predict = self.getValue(S,A)  # 预期值,当前选择的动作对应的分值
        self.doAction(A)                 # 执行动作
        S_=self._Bot_See()              # 观察执行动作后的状态
        q_actual = self.getMaxValue(S_)   #实际值,执行动作后的最大分值
        if self._keyCode == 37 and self.pos > self.boardwidth*0.5:
            self.pos -= 1
            self.angleCompensate(-1,0.25)   #位移时角度补偿
        elif self._keyCode == 39 and self.pos < self.width-self.boardwidth*0.5:
            self.pos += 1
            self.angleCompensate(1,0.25)    #位移时角度补偿
        self.angleChange()              #角度变化

        if S_!=90:
            self.operatTime+=1

        R = self.feedback()             # 获取奖励
        self.visionUpdate()             # 更新视觉

        if S_==0 or S_==180:
            self.failedTime+=1
        elif S_==90:
            self.successTime+=1
            self.operatTime-=1
        if self.failedTime>self.maxFailedTime:
            self.failedTime=0
            self.operatTime=0
            print('failed')
            self.restartGame()
        elif self.successTime>self.maxSuccessTime:
            self.successTime=0
            self.operatTime=0
            print('success')
            self.restartGame()
        q_target = R + self.GAMMA * q_actual
        # 更新QTable
        self.QTable[S][A] += self.ALPHA * (q_target - q_predict)  # 更新
        self.root.after(10,self.actionMove)

class botGame_WithoutUI(baseGame):
    def __init__(self,lowangle=False):
        super().__init__(lowangle)
        self.ACTIONS = ['left','stop','right'] #可用的动作
        self.action_code = {"left":-1,"stop":0,"right":1}
        self.EPSILON = 0.9 #贪婪度
        self.ALPHA = 0.1 #学习率
        self.GAMMA = 0.9 #奖励递减值
        self.save_Flag = True
        self.NiceTrainTime = 0
        self.operatTime = 0
        self.buildingQtable()

        self.averageOperatTime = 0

    def buildingQtable(self):
        self.QTable={}
        if os.path.exists('learning_data.dat'):
            with open('learning_data.dat','rb') as f:
                _dat = pickle.loads(f.read())
                self.EPSILON,self.ALPHA,self.GAMMA,self.QTable=_dat
    def saveDat(self,*event):
        with open('learning_data.dat','wb') as f:
            _dat = pickle.dumps([self.EPSILON,self.ALPHA,self.GAMMA,self.QTable])
            f.write(_dat)
        return
    def GetRandom(self):
        random.seed()
        return random.random()
    def GetRandomChoice(self,_act):
        random.seed()
        return random.choice(_act)
    def stateExist(self,state):
        if state in self.QTable.keys():
            return True
        else:
            return False
    def createState(self,state):
        self.QTable[state]={'left':0,'stop':0,'right':0}

    def getValue(self,state,action):
        return self.QTable[state][action]

    def getMaxAction(self,state):
        if self.stateExist(state):
            _maxAction = max(self.QTable[state],key=self.QTable[state].get)
            return _maxAction
        else:
            raise Exception('state not exist')

    def getMaxValue(self,state):
        if self.stateExist(state):
            _maxValue = self.QTable[state][self.getMaxAction(state)]
            return _maxValue
        else:
            raise Exception('state not exist')

    def action(self,_act):
        if _act=='left':
            self._Bot_keyPress(1)
        elif _act=='right':
            self._Bot_keyPress(-1)
        elif _act=='stop':
            self._Bot_keyPress(0)
    def choiceAction(self,state):
        usefulActions = []
        for action in range(len(self.ACTIONS)-1):
            if self.checkwall(action):
                usefulActions.append(self.ACTIONS[action])
        if (self.GetRandom() > self.EPSILON) or (not self.stateExist(state)):  #非贪婪 or 或者这个 state 还没有探索过
            if not self.stateExist(state):
                self.createState(state)
            action_name = self.GetRandomChoice(usefulActions)
        else:
            if not self.stateExist(state):
                self.createState(state)
            action_name = self.getMaxAction(state)    # 贪婪模式
        return action_name
    def doAction(self,action):
        self._Bot_keyPress(self.action_code[action])

    def timeReward(self):
        _div=self.operatTime
        if _div==0:
            _div=1
        return 500/_div

    def feedback(self):
        _angle=self._Bot_See()
        _timePunish = self.timeReward()
        if _angle==90:
            return 50 + _timePunish
        elif _angle==180 or _angle==0:
            return -20

        return round((math.pow(1/abs(_angle-90),0.25)-1.1)*10/3,2)

    def start(self):
        print('Learning start...')
        _count=0
        startTime=time.time()
        while True:
            self.actionMove()
            if _count==500000:
                _count=0
                _useTime=time.time()-startTime
                print('500000 times Learning use: %.2f s'%(_useTime))
                print('average operat time: %.2f'%(self.averageOperatTime))
                print('Saving QTable...')
                self.saveDat()
                print('Save Finished')
                startTime=time.time()
            _count+=1
            if self.NiceTrainTime>=10:
                self.saveDat()
                print('Training Finished!')
                break

    def restartGame(self):
        self.pos= self.width/2
        self.initAngle()

    def actionMove(self):
        S=self._Bot_See()               # 观察状态
        A=self.choiceAction(S)           # 选择行为
        q_predict = self.getValue(S,A)  # 预期值,当前选择的动作对应的分值
        self.doAction(A)                 # 执行动作
        S_=self._Bot_See()              # 观察执行动作后的状态
        q_actual = self.getMaxValue(S_)   #实际值,执行动作后的最大分值
        if self._keyCode == 37 and self.pos > self.boardwidth*0.5:
            self.pos -= 1
            self.angleCompensate(-1,0.25)   #位移时角度补偿
        elif self._keyCode == 39 and self.pos < self.width-self.boardwidth*0.5:
            self.pos += 1
            self.angleCompensate(1,0.25)    #位移时角度补偿
        self.angleChange()                  #角度变化
        if S_!=90:
            self.operatTime+=1

        R = self.feedback()                 # 获取奖励

        if S_==0 or S_==180:
            self.failedTime+=1
        elif S_==90:
            self.successTime+=1
        if S_!=90 and self.successTime>0:
            self.successTime=0
        if self.failedTime>self.maxFailedTime:
            self.failedTime=0
            self.NiceTrainTime=0
            self.averageOperatTime=(self.averageOperatTime + self.operatTime)/2
            self.operatTime=0
            self.restartGame()
        elif self.successTime>self.maxSuccessTime:
            self.successTime=0
            self.NiceTrainTime+=1
            print('Success!')
            self.averageOperatTime=(self.averageOperatTime + self.operatTime)/2
            self.operatTime=0
            self.restartGame()
        q_target = R + self.GAMMA * q_actual
        # 更新QTable
        self.QTable[S][A] += self.ALPHA * (q_target - q_predict)

def buildingQtable():
    QTable={}
    if os.path.exists('learning_data.dat'):
        with open('learning_data.dat','rb') as f:
            _dat = pickle.loads(f.read())
            _,_,_,QTable=_dat
    for angle in QTable:
        print('angle=>'+str(angle)+' Left:'+str(QTable[angle]['left'])+' Stop:'+str(QTable[angle]['stop'])+' Right:'+str(QTable[angle]['right']))

if __name__ == "__main__":
    lowangle=False
    mode='GUI'  # GUI , Train , Manual , ShowQTable
    _help=False
    args = sys.argv[1:]
    for arg in args:
        if arg[:2]!='--':
            print('参数错误,请使用 --help 查看帮助')
            exit()
        if arg[2:]=='lowangle':
            lowangle=True
        if arg[2:7]=='mode-':
            if arg[7:].lower() in ['gui','train','manual']:
                mode=arg[7:]
            else:
                print('参数错误,请使用 --help 查看帮助')
                exit()
        if arg[2:]=='help':
            _help=True
            print('args:')
            print('--lowangle: 低角度模式,默认为False,随机角度为1-45°或者135-179°')
            print('--mode-GUI: GUI模式,默认为GUI模式')
            print('--mode-Train: 训练模式,无GUI,用于快速训练')
            print('--mode-Manual: 手动模式,不进行训练,用于手动控制游玩,左右方向键控制板子移动')
            print('--mode-ShowQTable: 显示QTable,用于查看QTable')

    if not _help:
        if mode.lower()=='train':
            Game=botGame_WithoutUI(lowangle).start()
        elif mode.lower()=='manual':
            Game=baseGame(lowangle).start()
        elif mode.lower()=='showqtable':
            buildingQtable()
        else:
            Game=botGame(lowangle).start()


import evaluate
from formulas import jaccard, ochiai, tarantula, ample, wong1, wong2, wong3, op1, op2, gp_list, gpif, gpasgn, gpcall, gpseq
import math
import sys

def compare_formula(spectra_list, f1, f2):
    f1_list = list(map(lambda sp : f1(sp[0], sp[1], sp[2], sp[3]), spectra_list))
    f2_list = list(map(lambda sp : f2(sp[0], sp[1], sp[2], sp[3]), spectra_list))
    f1_sorted = sorted(f1_list, reverse = True)
    f2_sorted = sorted(f2_list, reverse = True)
    f1_rank = list(map(lambda x : f1_sorted.index(x), f1_list))
    f2_rank = list(map(lambda x : f2_sorted.index(x), f2_list))
    return measure_similarity(f1_rank, f2_rank)

def measure_similarity(order1, order2):
    res = 0
    for (i1, i2) in zip(order1, order2):
        res += abs(i1 - i2)
    return res

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    if b == 0:
        return 1
    else:
        return a / b

def sqrt(a):
    return math.sqrt(abs(a))

def parse_formula(fun_str):
    return lambda ep, ef, np, nf : eval(fun_str)

def read_formulas(file_path):
    formula_list = []
    with open(file_path, 'r') as file:
        while True:
            line = file.readline()
            if '"' not in line:
                continue
            if not line:
                break
            fun_str = line.split('"')[1]
            formula_list.append(parse_formula(fun_str))
    return formula_list

def file_test(formula_path, data_path, write_path):
    formula_path = sys.argv[1]
    formula_list = read_formulas(formula_path)
    data_path = sys.argv[2]
    write_path = sys.argv[3]
    human_list = [("jaccard", jaccard), ("ochiai", ochiai), ("tarantula", tarantula),
                    ("ample", ample), ("wong1", wong1), ("wong2", wong2), ("wong3", wong3), ("op1", op1), ("op2", op2)]
    spectra_list = evaluate.spectra_list([data_path])[0]["spectra_list"]
    with open(write_path, 'w') as out:
        for i in range(1, 31):
            eval_formula = gp_list[i - 1]
            formula_name = "gp" + str(i)
            sim_list = list(map(lambda f : str(compare_formula(spectra_list, f, eval_formula)), formula_list))
            out.write(formula_name + "," + ','.join(sim_list) + '\n')
        for name, eval_formula in human_list:
            sim_list = list(map(lambda f : str(compare_formula(spectra_list, f, eval_formula)), formula_list))
            out.write(name + "," + ','.join(sim_list) + '\n')

def form_test(data_path, write_path):
    formula_list = [gpif, gpasgn, gpcall, gpseq]
    human_list = [("jaccard", jaccard), ("ochiai", ochiai), ("tarantula", tarantula),
                    ("ample", ample), ("wong1", wong1), ("wong2", wong2), ("wong3", wong3), ("op1", op1), ("op2", op2)]
    spectra_list = evaluate.spectra_list([data_path])[0]["spectra_list"]
    with open(write_path, 'w') as out:
        for i in range(1, 31):
            eval_formula = gp_list[i - 1]
            formula_name = "gp" + str(i)
            sim_list = list(map(lambda f : str(compare_formula(spectra_list, f, eval_formula)), formula_list))
            out.write(formula_name + "," + ','.join(sim_list) + '\n')
        for name, eval_formula in human_list:
            sim_list = list(map(lambda f : str(compare_formula(spectra_list, f, eval_formula)), formula_list))
            out.write(name + "," + ','.join(sim_list) + '\n')

if __name__ == "__main__":
    if len(sys.argv) == 4:
        file_test(sys.argv[1], sys.argv[2], sys.argv[3])
    else:
        form_test(sys.argv[1], sys.argv[2])