from urlparse import urlparse
from hamcrest import assert_that, is_, contains_string, is_not
from lxml import html
from pylons import url
from joj.services.model_run_service import ModelRunService
from joj.tests import TestController
from joj.utils.constants import *
from joj.model import session_scope, Session, ParameterValue

class TestModelRunOutput(TestController):
    def setUp(self):
        super(TestModelRunOutput, self).setUp()
        self.clean_database()
        self.user = self.login()
        self.valid_params = {
            'submit': u'Next',
            'ov_select_1': 1,
            'ov_yearly_1': 1,
            'ov_monthly_1': 1,
            'ov_select_2': 1,
            'ov_hourly_2': 1,
            'ov_daily_2': 1,
            'ov_select_3': 1,
            'ov_monthly_3': 1
        }
        self.model_run_service = ModelRunService()
        param_run_start = self.model_run_service.get_parameter_by_constant(JULES_PARAM_RUN_START)
        param_run_end = self.model_run_service.get_parameter_by_constant(JULES_PARAM_RUN_END)
        with session_scope(Session) as session:
            self.model_run = self.model_run_service._create_new_model_run(session, self.user)
            self.model_run.name = "MR1"

            pv_run_start = ParameterValue()
            pv_run_start.parameter_id = param_run_start.id
            pv_run_start.value = "'1901-01-01 00:00:00'"

            pv_run_end = ParameterValue()
            pv_run_end.parameter_id = param_run_end.id
            pv_run_end.value = "'1902-01-01 00:00:00'"

            self.model_run.parameter_values = [pv_run_start, pv_run_end]

            session.add(self.model_run)

    def test_GIVEN_no_model_being_created_WHEN_page_get_THEN_redirect_to_create_model_run(self):
        self.clean_database()
        self.user = self.login()
        response = self.app.get(
            url(controller='model_run', action='output'))
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path, is_(url(controller='model_run', action='create')), "url")

    def test_GIVEN_model_run_created_WHEN_page_get_THEN_page_loaded(self):
        response = self.app.get(
            url(controller='model_run', action='output'))
        assert_that(response.normal_body, contains_string("Select Output Variables"))
        self.assert_model_run_creation_action(self.user, 'output')

    def test_GIVEN_output_parameters_already_chosen_WHEN_page_get_THEN_parameters_rendered(self):
        self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        response = self.app.get(url(controller='model_run', action='output'))
        doc = html.fromstring(response.normal_body)

        # Check that the first output variable is displayed, selected and the yearly and monthly period boxes selected:
        output_row_1 = doc.xpath('//div[@id="output_row_1"]/@style')
        assert_that(output_row_1, is_not(contains_string('display:none')))
        ov_select_1 = doc.xpath('//input[@name="ov_select_1"]/@checked')
        ov_yearly_1 = doc.xpath('//input[@name="ov_yearly_1"]/@checked')
        ov_monthly_1 = doc.xpath('//input[@name="ov_monthly_1"]/@checked')
        ov_daily_1 = doc.xpath('//input[@name="ov_daily_1"]/@checked')
        ov_hourly_1 = doc.xpath('//input[@name="ov_hourly_1"]/@checked')
        assert_that(len(ov_select_1), is_(1))
        assert_that(len(ov_yearly_1), is_(1))
        assert_that(len(ov_monthly_1), is_(1))
        assert_that(len(ov_daily_1), is_(0))
        assert_that(len(ov_hourly_1), is_(0))

        # For the second we expect the same but with the hourly period box selected
        output_row_2 = doc.xpath('//div[@id="output_row_2"]/@style')
        assert_that(output_row_2, is_not(contains_string('display:none')))
        ov_select_2 = doc.xpath('//input[@name="ov_select_2"]/@checked')
        ov_yearly_2 = doc.xpath('//input[@name="ov_yearly_2"]/@checked')
        ov_monthly_2 = doc.xpath('//input[@name="ov_monthly_2"]/@checked')
        ov_daily_2 = doc.xpath('//input[@name="ov_daily_2"]/@checked')
        ov_hourly_2 = doc.xpath('//input[@name="ov_hourly_2"]/@checked')
        assert_that(len(ov_select_2), is_(1))
        assert_that(len(ov_yearly_2), is_(0))
        assert_that(len(ov_monthly_2), is_(0))
        assert_that(len(ov_daily_2), is_(1))
        assert_that(len(ov_hourly_2), is_(1))

        # For the third we expect the monthly box selected
        output_row_3 = doc.xpath('//div[@id="output_row_3"]/@style')
        assert_that(output_row_3, is_not(contains_string('display:none')))
        ov_select_3 = doc.xpath('//input[@name="ov_select_3"]/@checked')
        ov_yearly_3 = doc.xpath('//input[@name="ov_yearly_3"]/@checked')
        ov_monthly_3 = doc.xpath('//input[@name="ov_monthly_3"]/@checked')
        ov_daily_3 = doc.xpath('//input[@name="ov_daily_3"]/@checked')
        ov_hourly_3 = doc.xpath('//input[@name="ov_hourly_3"]/@checked')
        assert_that(len(ov_select_3), is_(1))
        assert_that(len(ov_yearly_3), is_(0))
        assert_that(len(ov_monthly_3), is_(1))
        assert_that(len(ov_daily_3), is_(0))
        assert_that(len(ov_hourly_3), is_(0))

        # Finally we check that no other output parameters are selected or visible
        ov_selects = doc.xpath('//input[contains(@name, "ov_select_") and not(@checked)]')
        n_output_params = len(self.model_run_service.get_output_variables(include_depends_on_nsmax=False))
        assert_that(len(ov_selects), is_(n_output_params - 3))

        invisible_rows = doc.xpath('//div[contains(@id, "output_row_") and contains(@style, "display:none")]')
        assert_that(len(invisible_rows), is_(n_output_params - 3))

    def test_GIVEN_selected_outputs_WHEN_post_THEN_redirected_to_next_page(self):
        response = self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='submit')), "url")

    def test_GIVEN_selected_outputs_and_user_over_quota_WHEN_post_THEN_redirected_to_catalogue(self):
        self.create_run_model(storage_in_mb=self.user.storage_quota_in_gb * 1024 + 1, name="big_run", user=self.user)
        response = self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='index')), "url")

    def test_GIVEN_selected_outputs_WHEN_post_THEN_params_stored_in_database(self):
        self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)

        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)

        # Check we have the right number of profiles
        n_expected = 5
        p_output_nprofiles = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NPROFILES)[0].get_value_as_python()
        assert_that(p_output_nprofiles, is_(n_expected))

        pv_var = model_run.get_parameter_values(JULES_PARAM_OUTPUT_VAR)
        pv_nvars = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NVARS)
        pv_profile_name = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PROFILE_NAME)
        pv_output_main_run = model_run.get_parameter_values(JULES_PARAM_OUTPUT_MAIN_RUN)
        pv_output_period = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PERIOD)
        pv_output_types = model_run.get_parameter_values(JULES_PARAM_OUTPUT_TYPE)

        # Check they are all 5
        assert_that(len(pv_var), is_(n_expected))
        assert_that(len(pv_nvars), is_(n_expected))
        assert_that(len(pv_profile_name), is_(n_expected))
        assert_that(len(pv_output_main_run), is_(n_expected))
        assert_that(len(pv_output_period), is_(n_expected))
        assert_that(len(pv_output_types), is_(n_expected))

        # Create list of values so we can check they are correct (easier than checking ParameterValue objects)
        var_vals = [pv.get_value_as_python() for pv in pv_var]
        nvars_vals = [pv.get_value_as_python() for pv in pv_nvars]
        profile_name_vals = [pv.get_value_as_python() for pv in pv_profile_name]
        output_main_run_vals = [pv.get_value_as_python() for pv in pv_output_main_run]
        output_period_vals = [pv.get_value_as_python() for pv in pv_output_period]
        output_types = [pv.get_value_as_python() for pv in pv_output_types]

        # Check that we got the correct values
        # The order is assured consistent by the sort in model_run.get_parameter_values()
        output_var_1 = self.model_run_service.get_output_variable_by_id(1)
        output_var_2 = self.model_run_service.get_output_variable_by_id(2)
        output_var_3 = self.model_run_service.get_output_variable_by_id(3)
        assert_that(var_vals, is_([output_var_1.name, output_var_1.name, output_var_2.name,
                                   output_var_2.name, output_var_3.name]))
        assert_that(nvars_vals, is_([1, 1, 1, 1, 1]))
        assert_that(profile_name_vals, is_([output_var_1.name + '_yearly', output_var_1.name + '_monthly',
                                            output_var_2.name + '_daily', output_var_2.name + '_hourly',
                                            output_var_3.name + '_monthly']))
        assert_that(output_main_run_vals, is_([True, True, True, True, True]))
        assert_that(output_period_vals, is_([-2, -1, JULES_DAILY_PERIOD, JULES_HOURLY_PERIOD, -1]))
        assert_that(output_types, is_(['M', 'M', 'M', 'M', 'M']))

    def test_GIVEN_selected_outputs_WHEN_go_back_THEN_previous_paged_rendered(self):
        params = self.valid_params
        params['submit'] = u'Back'
        response = self.app.post(
            url(controller='model_run', action='output'),
            params=params)
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='land_cover')), "url")

    def test_GIVEN_nsmax_set_zero_WHEN_page_get_THEN_nsmax_parameters_not_available_on_page(self):
        self.model_run_service.save_parameter(JULES_PARAM_NSMAX, 0, self.user)
        response = self.app.get(
            url(controller='model_run', action='output'))
        for output_name in DEPENDS_ON_NSMAX:
            assert_that(response.normal_body, is_not(contains_string(output_name)))

    def test_GIVEN_nsmax_set_three_WHEN_page_get_THEN_nsmax_parameters_shown_on_page(self):
        self.model_run_service.save_parameter(JULES_PARAM_NSMAX, 3, self.user)
        response = self.app.get(
            url(controller='model_run', action='output'))
        output_variables = self.model_run_service.get_output_variables(include_depends_on_nsmax=True)
        for output_variable in output_variables:
            if output_variable.depends_on_nsmax:
                assert_that(response.normal_body, contains_string(str(output_variable.name)))

    def test_GIVEN_page_already_run_once_WHEN_page_post_THEN_new_parameters_overwrite_old_parameters(self):
        self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        new_params = {
            'submit': u'Next',
            'ov_select_1': 1,
            'ov_hourly_1': 1,
            'ov_select_10': 1,
            'ov_yearly_10': 1,
            'ov_monthly_10': 1
        }
        self.app.post(
            url(controller='model_run', action='output'),
            params=new_params)

        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)

        # Check we have the right number of profiles
        n_expected = 3
        p_output_nprofiles = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NPROFILES)[0].get_value_as_python()
        assert_that(p_output_nprofiles, is_(n_expected))

        pv_var = model_run.get_parameter_values(JULES_PARAM_OUTPUT_VAR)
        pv_nvars = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NVARS)
        pv_profile_name = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PROFILE_NAME)
        pv_output_main_run = model_run.get_parameter_values(JULES_PARAM_OUTPUT_MAIN_RUN)
        pv_output_period = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PERIOD)
        pv_output_types = model_run.get_parameter_values(JULES_PARAM_OUTPUT_TYPE)

        # Check they are all 3 (not 4 anymore)
        assert_that(len(pv_var), is_(n_expected))
        assert_that(len(pv_nvars), is_(n_expected))
        assert_that(len(pv_profile_name), is_(n_expected))
        assert_that(len(pv_output_main_run), is_(n_expected))
        assert_that(len(pv_output_period), is_(n_expected))
        assert_that(len(pv_output_types), is_(n_expected))

        # Create list of values so we can check they are correct (easier than checking ParameterValue objects)
        var_vals = [pv.get_value_as_python() for pv in pv_var]
        nvars_vals = [pv.get_value_as_python() for pv in pv_nvars]
        profile_name_vals = [pv.get_value_as_python() for pv in pv_profile_name]
        output_main_run_vals = [pv.get_value_as_python() for pv in pv_output_main_run]
        output_period_vals = [pv.get_value_as_python() for pv in pv_output_period]
        output_types = [pv.get_value_as_python() for pv in pv_output_types]

        # Check that we got the correct values
        # The order is assured consistent by the sort in model_run.get_parameter_values()
        output_var_1 = self.model_run_service.get_output_variable_by_id(1)
        output_var_10 = self.model_run_service.get_output_variable_by_id(10)
        assert_that(var_vals, is_([output_var_1.name, output_var_10.name, output_var_10.name]))
        assert_that(nvars_vals, is_([1, 1, 1]))
        assert_that(profile_name_vals, is_([output_var_1.name + '_hourly', output_var_10.name + '_yearly',
                                            output_var_10.name + '_monthly']))
        assert_that(output_main_run_vals, is_([True, True, True]))
        assert_that(output_period_vals, is_([JULES_HOURLY_PERIOD, -2, -1]))
        assert_that(output_types, is_(['M', 'M', 'M']))


"This script is used to run obj_int_extract and output the result to a file."

import optparse
import subprocess
import sys

parser = optparse.OptionParser()
parser.description = __doc__
parser.add_option('-e', '--executable', help='path to obj_int_extract.')
parser.add_option('-f', '--format', help='binary format (gas or rvds).')
parser.add_option('-b', '--binary', help='path to binary to parse.')
parser.add_option('-o', '--output', help='path to write extracted output to.')

options, args = parser.parse_args()
if (not options.executable or not options.format or not options.binary or
    not options.output):
  parser.error('Must specify all four arguments.')
  sys.exit(1)

with open(options.output, 'w') as fh:
  subprocess.check_call([options.executable, options.format, options.binary],
                        stdout=fh)

sys.exit(0)


seiscut=nparray[350,:,:]

#cut amp value
max_v=2000
maxcondition=(seiscut>=max_v)
a=np.where(maxcondition)

min_v=-2000
mincondition=(seiscut<=min_v)
b=np.where(mincondition)

seiscut[a]=max_v
seiscut[b]=min_v

data=np.interp(seiscut, (seiscut.min(), seiscut.max()), (0, 565))
data=data.astype(dtype='int64')
bb=uni_clr[data.transpose()]

fig = plt.figure(figsize=(15,15))
p1 = plt.subplot(1, 1,1)
seisline0 = bb[:,:,:3]
p1.imshow(seisline0)


"""ChessWarrior runner"""

import argparse
import os
import logging

from chesswarrior.config import Config
from chesswarrior.data import DataReader
from chesswarrior.train import Trainer
from chesswarrior.play import Player

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console = logging.StreamHandler()
console.setFormatter(fmt)
handler = logging.FileHandler('log.txt')
handler.setFormatter(fmt)
logger.addHandler(handler)
logger.addHandler(console)

config = Config()
parser = argparse.ArgumentParser()
parser.add_argument('-mode', type=str, help="which mode", choices=config.CMD)
parser.add_argument('--no-cuda', action='store_false', help="Running without cuda")
parser.add_argument('-epoch', type=int, help="training epoches",default=config.training.epoches)
parser.add_argument('-lr', type=float, help="learning rate",default=config.training.learning_rate)
parser.add_argument('-batch_size', type=int, help="batch size",default=config.training.batch_size)
parser.add_argument('-l2_reg', type=float, help="l2_regulation",default=config.model.l2_regularizer)
parser.add_argument('-ch', type=int, help="choise for white or black",default=0)

args = parser.parse_args()

config.cuda_avaliable = args.no_cuda
if not config.cuda_avaliable:

    logger.info('CPU is running')
    os.environ["CUDA_VISIBLE_DEVICES"] = ""
else:
    logger.info('GPU is running')

config.training.epoches = args.epoch
config.training.learning_rate = args.lr
config.training.batch_size = args.batch_size
config.training.l2_reg = args.l2_reg

if args.mode == 'data':
    logger.info('Initializing DataReader')
    datareader = DataReader(config)
    datareader.start()
elif args.mode == 'train':
    logger.info('Initializing Trainer')
    trainer = Trainer(config)
    trainer.start()
elif args.mode == 'play':
    logger.info('Initializing Player')
    player = Player(config)
    player.start(args.ch)
else:
    raise RuntimeError("Mode %s is undefined." % args.mode)


import nltk
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import SmoothingFunction

nltk.download('punkt')
nltk.download('stopwords')

def compute_code_bleu(reference_code, candidate_code):
    """
    Compute the CodeBLEU score.

    :param candidate_code: The generated code as a list of tokens.
    :param reference_code: The reference code as a list of tokens.
    :return: The CodeBLEU score.
    """
    # We use the smoothing function to avoid division by zero
    candidate_code = candidate_code.split()
    reference_code = reference_code.split()
    smoothing = SmoothingFunction().method1

    return sentence_bleu([reference_code], candidate_code, smoothing_function=smoothing)

if __name__ == '__main__':
    # Use the function
    candidate_code = 'LaptopParts::Keyboard hasA\nValue layout: String = \"QWERTY\",\nValue backlight: Boolean = true,\nValue language: String = \"English-US\".'.split()
    reference_code = 'LaptopParts::Keyboard hasA\nValue layout: String = \"QWERTY\",\nValue backlight: Boolean = true,\nValue language: String = \"English-US\".'.split()

    score = compute_code_bleu(candidate_code, reference_code)
    print(f"CodeBLEU score: {score}")


from torchvision import transforms
import random
import os
import numpy as np
import torch
import Utils.config_stomach as CONFIG
import itertools
from matplotlib import pyplot as plt
import scipy
from sklearn.metrics import roc_curve, roc_auc_score
import math

def seed_torch(seed=0):
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True

class Random90Rotation():
    def __init__(self, degrees=[0, 90, 180, 270]):
        self.degrees = degrees

    def __call__(self, im):
        degree = random.sample(self.degrees, k=1)[0]
        return im.rotate(degree)

transform_train = transforms.Compose([
    transforms.Resize(256),
    transforms.RandomCrop(224),
    Random90Rotation(),
    transforms.RandomVerticalFlip(),
    transforms.RandomHorizontalFlip(),
    transforms.RandomApply([transforms.ColorJitter(brightness=0.8)], p=0.8),
    transforms.RandomApply([transforms.ColorJitter(contrast=0.8)], p=0.8),
    transforms.RandomApply([transforms.ColorJitter(saturation=0.8, hue=0.2)], p=0.8),

    transforms.ToTensor(),
    transforms.Normalize(
        mean=CONFIG.Vahadane_stomach_10x_Mean, std=CONFIG.Vahadane_stomach_10x_Std
    ),
])

transform_valid = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=CONFIG.Vahadane_stomach_10x_Mean, std=CONFIG.Vahadane_stomach_10x_Std
    ),
])

transform_test = transforms.Compose([
    transforms.Resize(224),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=CONFIG.Vahadane_stomach_10x_Mean, std=CONFIG.Vahadane_stomach_10x_Std
    ),
])

def plot_confusion_matrix(cm, classes,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    # https://blog.csdn.net/qq_32425195/article/details/101537049
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    fig = plt.figure(figsize=(12, 6))
    plt.title(title)
    for plot_index in range(2):
        if plot_index == 1:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

        plt.subplot(1, 2, plot_index + 1)
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes, rotation=15);
        plt.yticks(tick_marks, classes)

        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i,
                     cm[i, j] if plot_index == 0 else "{:.2f}%".format(cm[i, j] * 100),
                     horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")

        plt.ylabel('True label');
        plt.xlabel('Predicted label')
        plt.tight_layout()
    return fig

def print_conf_matrix(confusion_matrix, classes):
    first_line = [' ']
    first_line.extend(classes)
    first_line = map(lambda s: s.ljust(20), first_line)

    print(''.join(first_line))
    all_acc = 0
    i = 0
    for row, _class in zip(confusion_matrix, classes):
        row_pretty = [_class]
        row_pretty.extend(
            ['{:>5.2f}%({:>5.0f}/{:<5.0f})'.format(number * 100 / sum(row), number, sum(row)) for number in row])
        row_pretty = map(lambda s: s.ljust(20), row_pretty)
        all_acc += (row[i] / sum(row))
        i += 1
        print(''.join(row_pretty))
    return all_acc / len(classes)

def make_weights_for_balanced_classes(label_list, nclasses):
    count = [0] * nclasses
    for item in label_list:
        count[item] += 1
    weight_per_class = [0.] * nclasses
    N = float(sum(count))
    print(N)

    for i in range(nclasses):
        print(i)
        weight_per_class[i] = N / float(count[i])
    print(count)
    print(weight_per_class)
    weight = [0] * len(label_list)
    for idx, val in enumerate(label_list):
        weight[idx] = weight_per_class[val]
    return weight, weight_per_class

def eer_threshold(all_labels, all_values):
    fpr, tpr, threshold = roc_curve(all_labels, all_values, pos_label=1)
    min_val = 999
    min_i = 0
    for i in range(len(fpr)):
        val = abs(fpr[i] + tpr[i] - 1)
        if val < min_val:
            min_val = val
            min_i = i
    print(threshold[min_i], fpr[min_i], tpr[min_i])
    return threshold[min_i]

def bootstrap_auc(all_labels, all_values, n_bootstraps=1000):
    rng_seed = 1  # control reproducibility
    bootstrapped_scores = []

    rng = np.random.RandomState(rng_seed)
    for i in range(n_bootstraps):
        # bootstrap by sampling with replacement on the prediction indices
        indices = rng.randint(0, len(all_values), len(all_values))
        if len(np.unique(all_labels[indices])) < 2:
            # We need at least one positive and one negative sample for ROC AUC
            # to be defined: reject the sample
            continue
        score = roc_auc_score(all_labels[indices], all_values[indices])
        bootstrapped_scores.append(score)
#         print("Bootstrap #{} ROC area: {:0.3f}".format(i + 1, score))
    return bootstrapped_scores

def clopper_pearson(x, n, alpha=0.05):
    """Estimate the confidence interval for a sampled Bernoulli random
    variable.
    `x` is the number of successes and `n` is the number trials (x <=
    n). `alpha` is the confidence level (i.e., the true probability is
    inside the confidence interval with probability 1-alpha). The
    function returns a `(low, high)` pair of numbers indicating the
    interval on the probability.
    """
    b = scipy.stats.beta.ppf
    lo = b(alpha / 2, x, n - x + 1)
    hi = b(1 - alpha / 2, x + 1, n - x)
    return 0.0 if math.isnan(lo) else lo, 1.0 if math.isnan(hi) else hi

def print_result(all_labels, all_values, all_predicts):
    all_auc = bootstrap_auc(all_labels, all_values)
    auc_95_ci = scipy.stats.norm.interval(0.95, np.mean(all_auc), np.std(all_auc))
    print("AUC 95% CI:")
    print("(%.4f, %.4f)" % auc_95_ci)
    TP = ((all_predicts == 1) & (all_labels == 1)).sum()
    TN = ((all_predicts == 0) & (all_labels == 0)).sum()
    FN = ((all_predicts == 0) & (all_labels == 1)).sum()
    FP = ((all_predicts == 1) & (all_labels == 0)).sum()
    sensi_95 = []
    lo, hi = clopper_pearson(TP, TP + FN)
    sensi_95.append(lo)
    sensi_95.append(hi)
    print('Sensitivity 95% confidence interval: ({:.2f}, {:.2f})'.format(lo, hi))
    speci_95 = []
    lo, hi = clopper_pearson(TN, FP + TN)
    speci_95.append(lo)
    speci_95.append(hi)
    print('Specificity 95% confidence interval: ({:.2f}, {:.2f})'.format(lo, hi))
    return auc_95_ci, sensi_95, speci_95


"""
    GIT: @drafonsopena
    + The objective of this project is to create a Madlibs Generator App using Python.
    | Group:
    +-+---------------- 1 ----------------
    | Prerequisites:
    | Install Tkinter (pip3 install tk)
    +---------------- 2 ----------------
    | Project File Structure:
    | Import all the needed libraries/modules
    | Create display window
    | Create functions and input variables
    +---------------- 3 ----------------
    | All necessary libraries to form the alarm clock:
    | From tkinter import *
    +------------------------------------
"""

# import module
from tkinter import *
# create a display window
# set the size of the window
root = Tk ()
root.geometry ('300x300')
root.title ('Mad Libs Generator')

Label (root, text='Mad Libs Generator \n For Fun Time',
       font='arial 20 bold').pack ()

Label (root, text='Click Any One: ',
       font='arial 15 bold').place (x=40, y=80)

# madlibs_One function was created for the first story "The Photograph."
# and some user input variables
def madlib_One ():
    animals = input ("Enter an animal name: ")
    profession = input ("Enter a profession name: ")
    cloth = input ("Enter a cloth name: ")
    objects = input ("Enter an object name: ")
    name = input ("Enter a name: ")
    place = input ("Enter a place name: ")
    verb = input ("Enter a verb in 'ing' form: ")
    food = input ("Enter a food name: ")

    print ('Say ' + food + ', the photographer said as the camera flashed! '
           + name + ' and I had gone to ' + place + ' to get our photos taken on my birthday. The first photo we really wanted was a picture of us dressed as '
           + animals + ' pretending to be a ' + profession + '. when we saw the second photo, it was exactly what I wanted. We both looked like '
           + objects + ' wearing ' + cloth + ' and ' + verb + ' --exactly what I had in mind')

# madlibs_Two function was created for the second story "The Butterfly."
# and some user input variables
def madlib_Two ():
    adjective = input ("Enter an adjective: ")
    color = input ("Enter a color name: ")
    objects = input ("Enter an object name: ")
    place = input ("Enter a place name: ")
    person = input ("Enter a person's'name: ")
    adjective1 = input ("Enter an adjective: ")
    insect = input ("Enter an insect name: ")
    food = input ("Enter a food name: ")
    verb = input ("Enter a verb: ")

    print ('Last night I dreamed I was a ' + adjective + ' butterfly with ' + color + ' splotches that looked like '
           + objects + ' .I flew to ' + place + ' with my best-friend and ' + person + ' who was a '
           + adjective1 + ' ' + insect + ' . We ate some ' + food + ' when we got there and then decided to '
           + verb + ' and the dream ended when I said-- lets ' + verb + '.')

# madlibs_Three function was created for the first story "Apples and Apples"
# and some user input variables
def madlib_Three ():
    person = input ("Enter a person's' name: ")
    color = input ("Enter color: ")
    foods = input ("Enter a food name: ")
    adjective = input ("Enter an adjective name: ")
    objects = input ("Enter an object name: ")
    place = input ("Enter a place name: ")
    verb = input ("Enter a verb: ")
    adverb = input ("Enter an adverb: ")
    food = input ("Enter a food name: ")
    objects1 = input ("Enter another object name: ")

    print ('Today we picked apple from ' + person + "'s Orchard. I had no idea there were so many different varieties of apples. I ate "
           + color + ' apples straight off the tree that tested like ' + foods + '. Then there was a ' + adjective + ' apple that looked like a '
           + objects + '.When our bag were full, we went on a free hay ride to ' + place + ' and back. It ended at a hay pile where we got to '
           + verb + ' ' + adverb + '. I can hardly wait to get home and cook with the apples. We are going to make apple ' + food + ' and '
           + objects1 + ' pies!.')
# creation of the buttons used to select the stories
Button (root, text='The Photographer',
        font='arial 15', command=madlib_One,
        bg='ghost white').place (x=60, y=120)

Button (root, text='The Butterfly',
        font='arial 15', command=madlib_Two,
        bg='ghost white').place (x=70, y=180)

Button (root, text='Apple and Apples',
        font='arial 15', command=madlib_Three,
        bg='ghost white').place (x=70, y=240)
# run the program
root.mainloop ()


import turtle, math

def main():
    n = 10
    size = 100

    t = turtle.Turtle()
    t.speed(0)
    #t.hideturtle()
    t.setheading(180)
    t.penup()
    t.backward(450)
    t.pendown()
    angle = 90

    getString = sierpLSys("A")
    for i in xrange(n):
        sizeToDraw = size/(math.pow(3, i-1))
        drawFrom(getString, t, sizeToDraw)

        getString = sierpLSys(getString)

        #print i, sizeToDraw
        t.penup()
        t.setheading(t.heading() + angle)
        t.forward(10)
        t.setheading(t.heading() + angle)
        t.pendown()

        angle = -1*angle

    t.getscreen()._root.mainloop()

def sierpLSys(begin):
    newString = []
    for char in begin:
        if char == "A":
            newString.append("ABA")
        elif char == "B":
            newString.append("BBB")
    return "".join(newString)

def drawFrom(drawS, t, size):
    for char in drawS:
        if char == "A":
            t.forward(size)
        elif char == "B":
            t.penup()
            t.forward(size)
            t.pendown()

main()


import os
import gym
import numpy as np
import torch
import matplotlib.pyplot as plt
import argparse
from copy import  deepcopy
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
from OppModeling.atari_wrappers import make_ftg_ram, make_ftg_ram_nonstation
from OppModeling.SAC import MLPActorCritic

def test_proc(global_ac, env, args, device):
    scores, wins, m_score, win_rate = [], [], 0, 0
    o, ep_ret, ep_len = env.reset(), 0, 0
    discard = False
    local_t = 0
    local_e = 0
    while local_e < args.test_episode:
        with torch.no_grad():
            a = global_ac.get_action(o, greedy=True, device=device)
        # Step the env
        o2, r, d, info = env.step(a)
        if info.get('no_data_receive', False):
            discard = True
        ep_ret += r
        ep_len += 1
        d = False if (ep_len == args.max_ep_len) or discard else d
        o = o2
        local_t += 1
        # End of trajectory handling
        if d or (ep_len == args.max_ep_len) or discard:
            # logger.store(EpRet=ep_ret, EpLen=ep_len)
            local_e += 1
            if info.get('win', False):
                wins.append(1)
            else:
                wins.append(0)
            scores.append(ep_ret)
            o, ep_ret, ep_len = env.reset(), 0, 0
            discard = False
    m_score = np.mean(scores)
    win_rate = np.mean(wins)
    return m_score, win_rate, local_t

def test_summary(p2, steps, m_score, win_rate, writer, args, e):
    print("\n" + "=" * 20 + "TEST SUMMARY" + "=" * 20)
    summary = "opponent:\t{}\n# test episode:\t{}\n# total steps:\t{}\nmean score:\t{:.1f}\nwin_rate:\t{}".format(
        p2, args.test_episode, steps, m_score, win_rate)
    print(summary)
    print("=" * 20 + "TEST SUMMARY" + "=" * 20 + "\n")
    writer.add_scalar("Test/mean_score", m_score.item(), e)
    writer.add_scalar("Test/win_rate", win_rate.item(), e)
    writer.add_scalar("Test/total_step", steps, e)

def test_func(global_ac, rank, e, p2, args, device, tensorboard_dir, ):
    torch.manual_seed(args.seed + rank)
    np.random.seed(args.seed + rank)
    print("set up Test process env")
    temp_dir = os.path.join(tensorboard_dir, "test_{}".format(p2))
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)
    writer = SummaryWriter(log_dir=temp_dir)

    # Main loop: collect experience in env and update/log each epoch
    if args.exp_name == "test":
        env = gym.make("CartPole-v0")
    elif p2 == "Non-station":
        env = make_ftg_ram_nonstation(args.env, p2_list=args.list, total_episode=args.test_episode,stable=args.stable)
    else:
        env = make_ftg_ram(args.env, p2=p2)
    print("TESTING process {} start to test, opp: {}".format(rank, p2))
    m_score, win_rate, steps = test_proc(global_ac, env, args, device)
    test_summary(p2, steps, m_score, win_rate, writer, args, e)
    env.close()
    del env
    print("TESTING process {} finished, opp: {}".format(rank, p2))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    # running setting
    parser.add_argument('--cuda', default=False, action='store_true')
    parser.add_argument('--seed', '-s', type=int, default=0)
    parser.add_argument('--n_process', type=int, default=1)
    # basic env setting
    parser.add_argument('--env', type=str, default="FightingiceDataFrameskip-v0")
    parser.add_argument('--p2', type=str, default="Toothless")
    # non station agent settings
    parser.add_argument('--non_station', default=False, action='store_true')
    parser.add_argument('--stable', default=False, action='store_true')
    parser.add_argument('--station_rounds', type=int, default=1000)
    parser.add_argument('--list', nargs='+')
    # training setting
    parser.add_argument('--hid', type=int, default=256)
    parser.add_argument('--l', type=int, default=2, help="layers")
    parser.add_argument('--test_episode', type=int, default=10)
    parser.add_argument('--max_ep_len', type=int, default=1000)
    # CPC setting
    parser.add_argument('--cpc', default=False, action="store_true")
    parser.add_argument('--z_dim', type=int, default=64)
    parser.add_argument('--c_dim', type=int, default=32)
    parser.add_argument('--timestep', type=int, default=10)
    # Saving settings
    parser.add_argument('--exp_name', type=str, default='test')
    parser.add_argument('--save-dir', type=str, default="./experiments")
    parser.add_argument('--traj_dir', type=str, default="./experiments")
    parser.add_argument('--model_para', type=str, default="test_sac.torch")
    parser.add_argument('--cpc_para', type=str, default="test_cpc.torch")
    parser.add_argument('--numpy_para', type=str, default="test.numpy")
    parser.add_argument('--train_indicator', type=str, default="test.data")
    args = parser.parse_args()

    mp.set_start_method("forkserver")
    os.environ['OMP_NUM_THREADS'] = '1'
    os.environ['MKL_NUM_THREADS'] = '1'
    experiment_dir = os.path.join(args.save_dir, args.exp_name)
    tensorboard_dir = os.path.join(experiment_dir, "evaluation")
    if not os.path.exists(tensorboard_dir):
        os.makedirs(tensorboard_dir)
    file_list = os.listdir(experiment_dir)
    print()
    model_para = [i for i in file_list if "model_torch" in i]
    model_para = ["model_torch_{}".format(i*100) for i in range(len(model_para)) if "model_torch_{}".format(i*100) in model_para ]
    obs_dim = 143
    act_dim = 56
    ac_kwargs = dict(hidden_sizes=[args.hid] * args.l)
    p2_list = ["Non-station"] + args.list
    global_ac = MLPActorCritic(obs_dim, act_dim, **ac_kwargs)

    scores, win_rates,rounds = [[], [], [], [],], [[], [], [], []], [[], [], [], []]
    for e in range(2):
        global_ac.load_state_dict(torch.load(os.path.join(experiment_dir, model_para[e])))
        global_ac.share_memory()
        for index, p2 in enumerate(p2_list):
            if args.exp_name == "test":
                env = gym.make("CartPole-v0")
            elif p2 == "Non-station":
                env = make_ftg_ram_nonstation(args.env, p2_list=args.list, total_episode=args.test_episode,
                                              stable=args.stable)
            else:
                env = make_ftg_ram(args.env, p2=p2)
            m_score, win_rate, steps = test_proc(global_ac, env, args, torch.device("cpu"))
            scores[index].append(m_score)
            win_rates[index].append(win_rate)
            rounds[index].append(e*100)
            env.close()
            del env
        print("First Round finished")
        torch.save((scores, win_rates, rounds,), os.path.join(tensorboard_dir, "test_data_{}".format(e*100)))

    for index in range(len(scores)):
        plt.plot(rounds[index], scores[index], label=p2_list[index])
    plt.legend(title='Opponent')
    plt.savefig(os.path.join(tensorboard_dir, "evaluation_plot"))


import random

def minesweeper(width: int, height: int, totalMines: int) -> list:

    if totalMines > (width * height - 16):
        raise Exception("FATAL - Too many mines for board size")
    if (width < 4) or (height < 4) or (width == 4 and height == 4):
        raise Exception("FATAL - Board too small")

    output = [0 for i in range(width * height)]

    for i in range(totalMines):
        loop = 0
        while True:
            if loop > 100:
                raise Exception("FATAL - Failed to generate valid mine location")
            loop += 1

            #sudoLocation = 0
            sudoLocation = random.randrange(0, width * height - 16 - i)

            location = sudoLocation + 2

            while output[location] == -1:
                location += 1
            if location >= width - 4 + 2:
                location += 4

            while output[location] == -1:
                location += 1
            if location >= 2 * width - 2:
                location += 2

            while output[location] == -1:
                location += 1
            if location >= width * height - 2 * width - 6 + 6:
                location += 2

            while output[location] == -1:
                location += 1
            if location >= width * height - width - 8 + 6:
                location += 4

            while output[location] == -1:
                location += 1
            if output[location] != -1 and location < width * height - 2:
                break

        output[location] = -1

    for index, value in enumerate(output):
        if value == 0:
            checks = ["" for i in range(8)]
            if index - width >= 0 and index % width != 0:
                checks[0] = index - width - 1
            if index - width >= 0:
                checks[1] = index - width
            if index - width >= 0 and (index + 1) % width != 0:
                checks[2] = index - width + 1
            if index % width != 0:
                checks[3] = index - 1
            if (index + 1) % width != 0:
                checks[4] = index + 1
            if index + width < width * height and index % width != 0:
                checks[5] = index + width - 1
            if index + width < width * height:
                checks[6] = index + width
            if index + width < width * height and (index + 1) % width != 0:
                checks[7] = index + width + 1

            mines = 0
            for i in checks:
                if i != "":
                    if output[i] == -1:
                        mines += 1

            output[index] = mines

    return output


# Program potrzebuje następujących bibliotek:
# pygame, numpy, matplotlib, keras

# import gry Pong
from PongGame import PongGame  # import The Pong Game
from PongGenome import PongGenome
#
import random
import matplotlib.pyplot as plt
import operator

MAX_EVALUATE_FRAMES = 500
MAXEPOCHS = 31

def GetFuzzyValues(BallX, BallY, PlayerY, BDirection):
    """ Metoda zwraca "z-fuzz-owane ;D" przybliżone wartości dla:
    - dystans
    - wysokość
    - kierunek wznoszenia (~Kąt toru lotu)

    Nie są one idealne - wymagają dopracowania
    ToDo - Poprawić otrzymywane wartości """

    DString = 'Null'  # Dystans
    HString = 'Same'  # Wysokość
    DirString = 'Null'  # Kierunek wznoszenia

    """
        Wyliczanie dystansu piłki:
        Far  - Daleko
        Med  ~ W połowie
        Near - Bardzo blisko
    """
    if (BallX >= 175):
        DString = 'Far'
    if ((BallX < 175) and (BallX >= 50)):
        DString = 'Med'
    if (BallX < 50):
        DString = 'Near'

    """
           Wyliczanie wysokości piłki:
           Aboce - Ponad
           Same  - Ten sam poziom
           Below - Poniżej
    """
    DeltaY = (PlayerY + 30) - (BallY + 5)

    if (DeltaY >= 15):
        HString = 'Below'
    if (DeltaY < -15):
        HString = 'Above'

    """
        Wyliczanie wznoszenia/opadania piłki:
    """
    if (BDirection < 0):
        DirString = 'Left'
    else:
        DirString = 'Right'

    return DString, HString, DirString

def CopyGenome(OriginalGenome):
    NewGenome = PongGenome()
    NewGenome.DistanceValues = OriginalGenome.DistanceValues
    NewGenome.HeightValues = OriginalGenome.HeightValues
    NewGenome.BallDirection = OriginalGenome.BallDirection
    NewGenome.LengthGenome = OriginalGenome.LengthGenome
    NewGenome.score = -1
    NewGenome.PongGN = list(OriginalGenome.PongGN)
    return NewGenome

"""
   Główna metoda Fuzzy Logic
"""
def EvaluateGenome(TheGenome):
    FrameTime = 0

    #  Tworzenie instancji gry Pong
    TheGame = PongGame()
    #  Inicjalizacja gry
    TheGame.InitialDisplay()

    #  Inicjalizacja kolejnych akcji:
    #  0:pozostań
    #  1:w górę
    #  2:w dół
    AppliedAction = 'S'
    PMissed = False
    GameQuit = False

    #  Główna pętla całej gry
    while ((FrameTime < MAX_EVALUATE_FRAMES) and (not PMissed) and (not GameQuit)):

        # Aktualny stan gry
        [PlayerYPos, BallXPos, BallYPos, BallXDirection, BallYDirection] = TheGame.ReturnCurrentState()
        DValue, HValue, DirValue = GetFuzzyValues(BallXPos, BallYPos, PlayerYPos, BallXDirection)

        AppliedAction = 'S'

        #  Przesuń w górę, swoją "paletką", jeśli piłka jest wyżej, niż "paletka" przeciwnika
        if (PlayerYPos + 30 > BallYPos + 5):
            BestAction = 'U'
        #  Przesuń w dół, swoją "paletką", jeśli piłka jest niżej, niż "paletka" przeciwnika
        if (PlayerYPos + 30 < BallYPos + 5):
            BestAction = 'D'

        #  Użyj FuzzyLogic, aby wybrać odpowiednią akcję
        AppliedAction = TheGenome.RtnAction(HValue, DValue, DirValue)

        #  Zastosuj najbardziej odpowiednią akcję w grze
        FrameCount, PMissed, GameQuit = TheGame.PlayNextMove(AppliedAction)

        #  Przejdź do kolejnej klatki
        FrameTime = FrameTime + 1

    TheGenome.SetScore(FrameTime)

    return GameQuit

def TrainPopulation():
    print()
    print("Creating Player Population set")

    EpochCount = 0
    HighestScore = 0
    TrainQuit = False

    GameHistory = []

    # Tworzenie najlepszego w historii genomy do zachowania
    BestEverScore = 0
    BestEverGenome = PongGenome()

    # Tworzenie początkowej populacji 14 genomów
    PlayerPopulation = []
    for ix in range(14):
        PlayerPopulation.append(PongGenome())

    print("Wyświetl początkową populację: ")
    for AGenome in PlayerPopulation:
        AGenome.DisplayFlat()

    print("*** Teraz uruchom oceny epoki  *** ")
    # Teraz trenuj całą populację przez MAXEPOCHS
    while ((EpochCount < MAXEPOCHS) and (not TrainQuit)):

        # Do oceny każdego z genomów w populacji
        for AGenome in PlayerPopulation:
            TrainQuit = EvaluateGenome(AGenome)
            if (TrainQuit):
                break

        # Dzielenie populacji na jalepsze wyniki
        PlayerPopulation.sort(key=operator.attrgetter('score'), reverse=True)

        HighestScore = PlayerPopulation[0].score
        # Sprawdź najlepszy w historii genom
        if (HighestScore > BestEverScore):
            BestEverScore = HighestScore
            BestEverGenome = CopyGenome(PlayerPopulation[0])
            BestEverGenome.SetScore(BestEverScore)

        if EpochCount % 5 == 0:
            # Wyświetlanie najlepszego genomu
            print()
            print("Nalepszy obecnie genom: ")
            BestEverGenome.DisplayGenome()
            for AGenome in PlayerPopulation:
                AGenome.DisplayFlat()
            print()

        PlayerPopulation[0] = CopyGenome(BestEverGenome)
        PlayerPopulation[0].SetScore(HighestScore)

        PlayerPopulation[2] = CopyGenome(PlayerPopulation[0])
        PlayerPopulation[2].Mutate()
        PlayerPopulation[3] = CopyGenome(PlayerPopulation[0])
        PlayerPopulation[3].Mutate()
        PlayerPopulation[4] = CopyGenome(PlayerPopulation[0])
        PlayerPopulation[4].Mutate()

        PlayerPopulation[5] = CopyGenome(PlayerPopulation[1])
        PlayerPopulation[5].Mutate()
        PlayerPopulation[6] = CopyGenome(PlayerPopulation[1])
        PlayerPopulation[6].Mutate()
        PlayerPopulation[7] = CopyGenome(PlayerPopulation[1])
        PlayerPopulation[7].Mutate()

        PlayerPopulation[8] = PongGenome()
        PlayerPopulation[8].InheritFromParents(PlayerPopulation[0], PlayerPopulation[1])
        PlayerPopulation[9] = PongGenome()
        PlayerPopulation[9].InheritFromParents(PlayerPopulation[0], PlayerPopulation[1])
        PlayerPopulation[10] = PongGenome()
        PlayerPopulation[10].InheritFromParents(PlayerPopulation[0], PlayerPopulation[1])
        PlayerPopulation[11] = PongGenome()
        PlayerPopulation[11].InheritFromParents(PlayerPopulation[0], PlayerPopulation[1])

        PlayerPopulation[12] = PongGenome()
        PlayerPopulation[13] = PongGenome()

        EpochCount = EpochCount + 1

        print("Epoka: ", EpochCount, "  Najlepszy wynik: ", HighestScore)
        GameHistory.append((EpochCount, HighestScore))

    print("*** Koniec epok testowych*** ")

    #  Narysuj Wynik vs Epoki
    x_val = [x[0] for x in GameHistory]
    y_val = [x[1] for x in GameHistory]

    plt.plot(x_val, y_val)
    plt.xlabel("Epoka ")
    plt.ylabel("Najlepszy wynik")
    plt.show()

    print()
    print("Najlepszy genom: ")
    PlayerPopulation[0].DisplayFlat()
    print()
    PlayerPopulation[0].DisplayGenome()

    print(" *** Rozgrywka najlepszego genomu *** ")
    TrainQuit = EvaluateGenome(PlayerPopulation[0])

    print("******** Koniec ********* ")
    print()

def main():
    # Główna metoda
    TrainPopulation()

if __name__ == "__main__":
    main()


import logging

logging.basicConfig(format="%(asctime)s - %(name)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)

from telegram import Update
from telegram.ext import (
    Application,
    CommandHandler,
    ContextTypes,
)

TOKEN = "TOKEN"

async def quadratic(update: Update, context: ContextTypes) -> None:
    # Проверить сообщение ли это
    if not update.message:
        return
    # Это нужно пототму что в update.message.text лежит команда и аргументы типа
    # {text: "/quadratic 1 2 3"}
    text = update.message.text.replace("/quadratic", "").split()
    a, b, c = text
    d = int(b) ** 2 - 4 * int(a) * int(c)

    if d < 0:
        await update.message.reply_text("Дискриминант меньше нуля, корней нет")
    elif d == 0:
        x = -int(b) / (2 * int(a))
        await update.message.reply_text(
            f"Дискриминант равен нулю, корень один\n\nD = {d}\nx = {x}"
        )
    else:
        x1 = (-int(b) + d**0.5) / (2 * int(a))
        x2 = (-int(b) - d**0.5) / (2 * int(a))
        await update.message.reply_text(
            f"Дискриминант больше нуля, корней два\n\nD = {d}\nx1 = {x1}\nx2 = {x2}"
        )

def main() -> None:
    application = Application.builder().token(TOKEN).build()

    application.add_handler(CommandHandler("quadratic", quadratic))
    application.run_polling()

if __name__ == "__main__":
    main()


import math

import numpy

class TriangleError(Exception):
    pass

class Triangle(object):
    def __init__(self, x1, y1, x2, y2, x3, y3):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.x3 = x3
        self.y3 = y3

    def get_ab(self):
        return math.sqrt((self.x1 - self.x2) ** 2 + (self.y1 - self.y2) ** 2)

    def get_bc(self):
        return math.sqrt((self.x2 - self.x3) ** 2 + (self.y2 - self.y3) ** 2)

    def get_ca(self):
        return math.sqrt((self.x3 - +self.x1) ** 2 + (self.y3 - self.y1) ** 2)

    def is_triangle(self):
        if (self.x2 - self.x1) * (self.y3 - self.y1) == (self.x3 - self.x1) * (self.y2 - self.y1):
            return False
        return True

    def get_area(self):  # площадь
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        return 0.5 * abs((self.x2 - self.x1) * (self.y3 - self.y1) -
                         (self.x3 - self.x1) * (self.y2 - self.y1))

    def get_perimeter(self):  # периметр
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        return self.get_ab() + self.get_bc() + self.get_ca()

    def get_circumcircle_radius(self):  # описаннaя окружность
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        return self.get_ab() * self.get_bc() * self.get_ca() / (4 * Triangle.get_area(self))

    def get_circumcircle_center(self):
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        k1 = ((self.x2 ** 2 + self.y2 ** 2) - (self.x3 ** 2 + self.y3 ** 2)) / (
                2 * ((self.x2 - self.x3) * (self.y1 - self.y2) - (self.x1 - self.x2) * (self.y2 - self.y3)))
        k2 = ((self.x1 ** 2 + self.y1 ** 2) - (self.x2 ** 2 + self.y2 ** 2)) / (
                2 * ((self.x2 - self.x3) * (self.y1 - self.y2) - (self.x1 - self.x2) * (self.y2 - self.y3)))
        return [k1 * (self.y1 - self.y2) - k2 * (self.y2 - self.y3),
                -k1 * (self.x1 - self.x2) + k2 * (self.x2 - self.x3)]

    def get_incircle_radius(self):  # вписанная окружность
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        return 2 * Triangle.get_area(self) / Triangle.get_perimeter(self)

    def get_incircle_center(self):
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        a1 = (self.get_ca() * (self.y2 - self.y1) + self.get_ab() * (self.y3 - self.y1)) / (
                self.get_ca() * (self.x2 - self.x1) + self.get_ab() * (self.x3 - self.x1))
        a2 = (self.get_bc() * (self.y1 - self.y2) + self.get_ab() * (self.y3 - self.y2)) / (
                self.get_bc() * (self.x1 - self.x2) + self.get_ab() * (self.x3 - self.x2))
        m1 = numpy.array([[a1, -1.0],
                          [a2, -1.0]])
        v1 = numpy.array(
            [-self.y1 + self.x1 * a1,
             -self.y2 + self.x2 * a2])
        return list(numpy.linalg.solve(m1, v1))

    def get_triangle_type_by_sides(self):
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        if (abs(self.get_ab() - self.get_bc()) < 1e-10 and
            abs(self.get_ab() - self.get_ca()) > 1e-10) or (
                abs(self.get_bc() - self.get_ca()) < 1e-10 and
                abs(self.get_ab() - self.get_ca()) > 1e-10) or (
                abs(self.get_ab() - self.get_ca()) < 1e-10 and
                abs(self.get_ab() - self.get_bc()) > 1e-10):
            return "isosceles"  # равнобедренный
        elif abs(self.get_ab() - self.get_bc()) < 1e-10 and abs(self.get_bc() - self.get_ca()) < 1e-10:
            return "equilateral"  # равносторонний
        return "various"  # разносторонний

    def get_triangle_type_by_angles(self):
        if not self.is_triangle():
            raise TriangleError('This triangle is invalid! Check it!')
        if (abs(self.get_ab() ** 2 + self.get_bc() ** 2 - self.get_ca() ** 2) < 1e-10) or (
                abs(self.get_ab() ** 2 + self.get_ca() ** 2 - self.get_bc() ** 2) < 1e-10) or (
                abs(self.get_ca() ** 2 + self.get_bc() ** 2 - self.get_ab() ** 2) < 1e-10):
            return "right"  # прямоугольный
        elif (self.get_ab() ** 2 + self.get_bc() ** 2 - self.get_ca() ** 2 > 1e-10) and (
                self.get_ab() ** 2 + self.get_ca() ** 2 - self.get_bc() ** 2 > 1e-10) and (
                self.get_ca() ** 2 + self.get_bc() ** 2 - self.get_ab() ** 2 > 1e-10):
            return "acute"  # остроугольный
        return "obtuse"  # тупоугольный


# 문자를 받은 승현이

import sys
input = sys.stdin.readline

def check(a,b,r,c):
    if 0<=a<=r-1 and 0<=b<=c-1 and msg1[a][b] != -1:
        return True
    return False

def change(x):
    y = 0
    for i in range(5):
        y += int(x[i])*(2**(4-i))
    if y==0:
        y = -32
    return chr(y+64)

t = int(input())
dx = [0,1,0,-1]
dy = [1,0,-1,0]
for _ in range(t):
    r,c,msg = map(str,input().split())
    r,c = map(int,[r,c])
    msg1 = [[0 for _ in range(c)] for _ in range(r)]
    cnt = 0
    for i in range(r):
        for j in range(c):
            msg1[i][j] = msg[cnt]
            cnt += 1

    cnt = 1
    tmp = ''
    result = []
    x,y = 0,0
    d = 0
    while cnt <= len(msg):
        tmp += msg1[x][y]
        msg1[x][y] = -1
        if len(tmp) == 5:
            result.append(tmp)
            tmp = ''
        a = x+dx[d]
        b = y+dy[d]
        if check(a,b,r,c):  # 다음 좌표
            x = a
            y = b
        else:
            d = (d+1)%4
            x += dx[d]
            y += dy[d]
        cnt += 1

    ans = ''
    for alphabet in result:
        ans += change(alphabet)
    print(ans.rstrip())

2714 문자를받은승현이.py

2714 문자를받은승현이.py


# -*- coding: utf-8 -*-
"""stochastic_evolutionary.py: Module containing functionalities to optimize
a given Latin Hypercube Design using an implementation of the Enhanced
Stochastic Evolutionary Algorithm proposed by Jin, Chen, and Sudjianto (1).
Details can be found in (1) for the enhanced version and (2) for the original
version.

**References**

 (1) R. Jin, W. Chen, and A. Sudjianto, "An Efficient Algorithm for Constructing
     Optimal Design of Computer Experiments," Proceedings of DETC'03, ASME 2003
     Design Engineering Technical Conferences and Computers and Information in
     Engineering Conference, Chicago, Illinois, Sept. 2-6, 2003.
 (2) Y.G. Saab and V.B. Rao, "Combinatorial Optimization by Stochastic
     Evolution," IEEE Transactions on Computer-Aided Design, vol. 10(4), 1981.
"""
import types
import math
import numpy as np
from . import objective_functions

__author__ = "Damar Wicaksono"

def pick_obj_function(obj_function: str) -> types.FunctionType:
    """Function to select by name the objective function to optimize

    :param obj_function: the name of the objective function
    :return: the objective function (FunctionType data type)
    """
    if obj_function == "w2_discrepancy":
        return objective_functions.w2_discrepancy_fast
    else:
        raise TypeError("Unsupported objective function")

def init_threshold(dm: np.ndarray,
                   obj_func: types.FunctionType,
                   multiplier: float = 0.005) -> float:
    """Calculate the initial threshold as recommended in the article

    The initial threshold is obtained by multiplying the objective function of
    the initial design by a very small multiplier to get a small threshold.

    :param dm: the initial design matrix
    :param obj_func: the objective function (FunctionType data type)
    :param multiplier: the multiplier to have a very small value of threshold
        based on the initial design's objective function (default = 0.005)
    :return: the initial threshold
    """
    return multiplier*obj_func(dm)

def calc_num_candidate(n: int) -> int:
    """Calculate the number of candidates from perturbing the current design

    Recommended in the article is the maximum number of pair combination from a
    given column divided by a factor of 5.

    It is also recommended that the number of candidates to be evaluated does
    not exceed 50

    :param n: the number of elements to be permuted
    :return: the number of candidates from perturbing the current design
        column-wise
    """
    pairs = math.factorial(n) / math.factorial(n-2) / math.factorial(2)
    fac = 5 # The factor recommended in the article

    return min(int(pairs/fac), 50)

def calc_max_inner(n: int, k: int) -> int:
    """Calculate the maximum number of inner iterations

    :math:`\frac{2 \times n_e \times k}{J}`
    It is recommended that the number of inner iterations does not exceed 100

    :param n: the number of samples in the design
    :param k: the number of design dimension
    :return: the maximum number of inner iterations/loop
    """
    pairs = math.factorial(n) / math.factorial(n-2) / math.factorial(2)

    return min(int(2*pairs*k/calc_num_candidate(n)), 100)

def perturb(dm: np.ndarray,
            num_dimension: int,
            num_exchanges: int,
            obj_func: types.FunctionType) -> np.ndarray:
    """Create new configuration of a design matrix according to ESE algorithm

    According to the algorithm, a distinct `num_candidate` designs have to be
    generated from the current design by carrying out a column-wise perturbation
    on a given column `num_dimension`. The best design according to the select
    `obj_function` will be selected as the "perturbed" design

    :param dm: the current design matrix
    :param num_dimension: the column of design matrix to be perturbed
    :param num_exchanges: the number of distinct candidates to be generated
    :param obj_func: the select objective function
    :return: the perturbed state of the current design
    """
    import itertools

    # Create pairs of all possible combination
    num_samples = dm.shape[0]
    pairs = list(itertools.combinations([_ for _ in range(num_samples)], 2))
    # Create random choices for the pair of perturbation, w/o replacement
    rand_choices = np.random.choice(len(pairs), num_exchanges, replace=False)
    # Initialize the search
    obj_func_current = np.inf
    dm_current = dm.copy()
    for i in rand_choices:
        dm_try = dm.copy() # Always perturb from the design passed in argument
        # Do column-wise operation in a given column 'num_dimension'
        dm_try[pairs[i][0], num_dimension] = dm[pairs[i][1], num_dimension]
        dm_try[pairs[i][1], num_dimension] = dm[pairs[i][0], num_dimension]
        obj_func_try = obj_func(dm_try)
        if obj_func_try < obj_func_current:
            # Select the best trial from all the perturbation trials
            obj_func_current = obj_func_try
            dm_current = dm_try.copy()

    return dm_current

def adjust_threshold(threshold: float,
                     flag_imp: bool,
                     flag_explore: bool,
                     n_accepted: int,
                     n_improved: int,
                     num_exchanges: int,
                     improving_params: list,
                     exploring_params: list) -> tuple:
    """Calculate the new threshold based on the results of previous iteration

    :param threshold: the current threshold
    :param flag_imp: the flag indicating whether new best solution was found
    :param flag_explore: the flag indicating whether in exploration mode
    :param n_accepted: the number of accepted solution in the previous iteration
    :param n_improved: the number of new best solution found in previous iter.
    :param num_exchanges: the number of candidates considered from curr. design
    :param improving_params: The 2 parameters used in improving process phase
        (1) the cut-off value to decrease the threshold
        (2) the multiplier to decrease or increase the threshold
    :param exploring_params: The 4 parameters used in exploring process phase
        (1) the cut-off value of acceptance to start increasing the threshold
        (2) the cut-off value of acceptance to start decreasing the threshold
        (3) the cooling multiplier for the threshold
        (4) the warming multiplier for the threshold
    :return: tuple of the update flag_explore (whether still in explore mode)
        and the adjusted threshold
    """
    # Improve vs. Explore Phase and Threshold Update
    if flag_imp:    # Improve
        # New best solution found, carry out improvement process
        if (float(n_accepted/num_exchanges) > improving_params[0]) & \
                (n_accepted > n_improved):
            # Lots acceptance but not all of them is improvement,
            # reduce threshold, make it harder to accept a trial
            threshold *= improving_params[1]
        else:
            # Few acceptance or all trials are improvement, increase threshold
            # make it easier to accept a trial
            threshold /= improving_params[1]

    else:           # Explore, No new best solution found during last iteration
        # Exploring process, warming up vs. cooling down
        if n_accepted < exploring_params[0] * num_exchanges:
            # Reach below limit, increase threshold ("warming up")
            flag_explore = True
        elif n_accepted > exploring_params[1] * num_exchanges:
            # Reach above limit, decrease threshold ("cooling down")
            flag_explore = False

        if flag_explore:
            # Ramp up exploration and below upper limit, increase threshold
            threshold /= exploring_params[3]
        elif not flag_explore:
            # Slow down exploration and above lower limit, decrease threshold
            threshold *= exploring_params[2]

    return flag_explore, threshold

def optimize(dm_init: np.ndarray,
             obj_func_name: str,
             threshold_init: float,
             num_exchanges: int,
             max_inner: int,
             max_outer: int,
             improving_params: list,
             exploring_params: list):
    """Optimize a given design using Enhanced Evolutionary Algorithm

    :param dm_init: the initial design matrix
    :param obj_func_name: the objective function used in the optimization
    :param threshold_init: the initial threshold, if equal or less than zero,
        then calculate from the recommended value
    :param num_exchanges: the number of candidates obtained by perturbing current design,
        0 or less means calculate from the recommended value
    :param max_inner: the maximum number of inner iterations, 0 or less means calculate
        from the recommended value
    :param max_outer: the maximum number of outer iterations, served as the
        stopping criterion for the optimization algorithm
    :param improving_params: The 2 parameters used in improving process phase
        (1) the cut-off value to decrease the threshold
        (2) the multiplier to decrease or increase the threshold
    :param exploring_params: The 4 parameters used in exploring process phase
        (1) the cut-off value of acceptance to start increasing the threshold
        (2) the cut-off value of acceptance to start decreasing the threshold
        (3) the cooling multiplier for the threshold
        (4) the warming multiplier for the threshold
    :return: a collection of obj_function evolution and best design
    """
    import collections

    # Initialize output structure
    OptSolution = collections.namedtuple("OptSolution",
                                         "dm_init dm_best best_evol try_evol")

    # Initialization of Outer Iteration
    n = dm_init.shape[0]     # number of samples
    k = dm_init.shape[1]     # number of dimension
    obj_function = pick_obj_function(obj_func_name)  # Choose objective function
    if threshold_init <= 0.0:
        threshold = init_threshold(dm_init, obj_function)   # Initial threshold
    else:
        threshold = threshold_init
    if num_exchanges <= 0:                  # number of exchanges
        num_exchanges = calc_num_candidate(n)
    if max_inner <= 0:                      # maximum number of inner iterations
        max_inner = calc_max_inner(n, k)

    dm = dm_init.copy()                     # the current design
    obj_func_best = obj_function(dm)        # the best value of obj.func. so far
    obj_func_best_old = obj_function(dm)    # the old value of obj.func.
    flag_explore = False                    # improved flag

    best_evol = []                      # Keep track the best solution
    try_evol = []                       # Keep track the accepted trial solution

    # Begin Outer Iteration
    for outer in range(max_outer):
        # Initialization of Inner Iteration
        n_accepted = 0              # number of accepted trial
        n_improved = 0              # number of improved trial

        # Begin Inner Iteration
        for inner in range(max_inner):
            obj_func = obj_function(dm)
            # Perturb current design
            dm_try = perturb(dm, inner % k, num_exchanges, obj_function)
            obj_func_try = obj_function(dm_try)
            # Check whether solution is acceptable
            if (obj_func_try - obj_func) <= threshold * np.random.rand():
                # Accept solution
                dm = dm_try.copy()
                n_accepted += 1
                try_evol.append(obj_func_try)
                if obj_func_try < obj_func_best:
                    # Best solution found
                    dm_best = dm.copy()
                    obj_func_best = obj_func_try
                    best_evol.append(obj_func_best)
                    n_improved += 1

        # Accept/Reject as Best Solution for convergence checking
        if ((obj_func_best_old - obj_func_best)/obj_func_best) > 1e-6:
            # Improvement found
            obj_func_best_old = obj_func_best
            flag_explore = False  # Reset the explore flag after new best found
            flag_imp = True
        else:
            # Improvement not found
            flag_imp = False

        # Improve vs. Explore Phase and Threshold Update
        flag_explore, threshold = adjust_threshold(threshold, flag_imp,
                                                   flag_explore, n_accepted,
                                                   n_improved,
                                                   num_exchanges,
                                                   improving_params,
                                                   exploring_params)

    output = OptSolution(dm_init = dm_init, dm_best = dm_best,
                         best_evol = best_evol, try_evol = try_evol)

    return output


from pydantic import BaseModel, Field
from beartype import beartype
from kubernetes.client.rest import ApiException

class InputSchema(BaseModel):
    k8s_cli_string: str = Field(
        title='Kubectl Command',
        description='kubectl command '
                    'eg "kubectl get pods --all-namespaces"'
    )
    deployment: str = Field(
        title='Deployment Name',
        description='Deployment Name'
    )
    namespace: str = Field(
        title='Namespace',
        description='Namespace'
    )

@beartype
def k8s_kubectl_rollout_deployment_printer(data: str):
    if data is None:
        print("Error while executing command")
        return

    print (data)

@beartype
def k8s_kubectl_rollout_deployment(
    handle,
    k8s_cli_string: str,
    deployment: str,
    namespace: str
    ) -> str:
    k8s_cli_string = k8s_cli_string.format(deployment=deployment, namespace=namespace)
    result = handle.run_native_cmd(k8s_cli_string)

    if result is None:
        print(
            f"Error while executing command ({k8s_cli_string}) (empty response)")
        return ""

    if result.stderr:
        raise ApiException(
            f"Error occurred while executing command {k8s_cli_string} {result.stderr}")

    return result.stdout

## Duplicate code?


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 18 10:28:32 2018

@author: User
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
from deap import creator, tools, base, gp
import operator

def preprocessData():
    #Importing the dataset
    dataset = pd.read_csv('train.csv')
    X = dataset[['Pclass','Age', 'Sex','SibSp','Parch','Fare']].values
    Y = dataset.iloc[:, 1].values

    #Dealing with encoding the labels
    from sklearn.preprocessing import LabelEncoder#, OneHotEncoder
    labelencoder_X = LabelEncoder()
    X[:,2] = labelencoder_X.fit_transform(X[:,2])

    #Dealing with missing datas
    from sklearn.preprocessing import Imputer
    imputer = Imputer()
    imputer=Imputer(missing_values='NaN',
                    strategy='mean', axis=0)
    imputer=imputer.fit(X[:,1:2])
    X[:,1:2]=imputer.transform(X[:,1:2])
    return X, Y

#Number of attribute param
IND_SIZE = 6

#Creating the individuals
#lists of floats with a minimizing objectives fitness
creator.create("FitnessMin", base.Fitness, weights = (1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness = creator.FitnessMin)

#initialize a primitive set and add all the primitives our trees can use
pset = gp.PrimitiveSet("MAIN", 6, "IN")
pset.addPrimitive(np.add, arity=2)
pset.addPrimitive(np.subtract, arity=2)
pset.addPrimitive(np.multiply, arity=2)
pset.addPrimitive(np.negative, arity=1)
#Addional primitives? ========================================================
pset.addPrimitive(np.absolute, arity=1)
pset.addPrimitive(np.log, arity=1)
pset.renameArguments(ARG0='x')
pset.renameArguments(ARG1='y')
pset.addTerminal(0)
pset.addTerminal(1)

toolbox = base.Toolbox()
#Returns a primitive tree based on a primitive set and a minimum and maximum tree depth
#Maybe change the size of the tree?
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=5)

toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("compile", gp.compile, pset=pset)

inputs, outputs = preprocessData()

def evaluateInd(individual, pset):
    func = gp.compile(expr=individual, pset=pset)
    #sqerrors = (func(X) - Y)**2
    #print(inputs, outputs)
    #print(individual)
    #print([func(*in_>0) for in_ in inputs])
    #print([out for out in outputs])
    #result = np.array([func(*in_>0) for in_ in inputs]) & np.array([out for out in outputs])
    #return np.sum(result)
    return sum((func(*in_)>0) == out for in_, out in zip(inputs, outputs)),
    '''
    for i in range(len(X)):
        #sqerrors += ((func([1,2]) - Y[i]))**2
        print("=========", func(X[i]))
        sqerrors += ((func(X[i]) - Y[i]))**2
    return (np.sqrt(sqerrors) / len(X),)
    '''
    #return (np.sqrt(sqerrors) / len(X),)

toolbox.register("evaluate", evaluateInd, pset = pset)

'''
CHANGE THE THINGS HERE!!!!!!
==============================================================================
'''
#Change the params here for mating, mutating, and selecting
#toolbox.register("mate", tools.cxBlend, alpha = 0.5)
toolbox.register("mate", gp.cxOnePoint)
#there is a variety of mutation operators in the deap.tools module
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
#https://github.com/DEAP/deap/blob/master/deap/gp.py <-- more mutator methods
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)
toolbox.register("select", tools.selTournament, tournsize=3)

#Optional, limits tree size
toolbox.decorate("mate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17))
toolbox.decorate("mutate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17))
'''
==============================================================================
'''

def main():
    gen = range(50)
    avg_list = []
    max_list = []
    min_list = []

    pop = toolbox.population(n=10)

    # Evaluate the entire population
    fitnesses = list(map(toolbox.evaluate, pop))
    for ind, fit in zip(pop, fitnesses):
        ind.fitness.values = fit

    # Begin the evolution
    for g in gen:
        print("-- Generation %i --" % g)

        # Select the next generation individuals
        offspring = toolbox.select(pop, len(pop))
        # Clone the selected individuals
        offspring = list(map(toolbox.clone, offspring))

        # Apply crossover and mutation on the offspring
        for child1, child2 in zip(offspring[::2], offspring[1::2]):
            if random.random() < 0.5:
                toolbox.mate(child1, child2)
                del child1.fitness.values
                del child2.fitness.values

        for mutant in offspring:
            if random.random() < 0.2:
                toolbox.mutate(mutant)
                del mutant.fitness.values

        # Evaluate the individuals with an invalid fitness
        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            print(ind)
            ind.fitness.values = fit

        # Replace population
        pop[:] = offspring

        # Gather all the fitnesses in one list and print the stats
        fits = [ind.fitness.values[0] for ind in pop]

        length = len(pop)
        mean = sum(fits) / length
        sum2 = sum(x*x for x in fits)
        std = abs(sum2 / length - mean**2)**0.5
        g_max = max(fits)
        g_min = min(fits)

        avg_list.append(mean)
        max_list.append(g_max)
        min_list.append(g_min)

        print("  Min %s" % g_min)
        print("  Max %s" % g_max)
        print("  Avg %s" % mean)
        print("  Std %s" % std)

    print("-- End of (successful) evolution --")

    best_ind = tools.selBest(pop, 1)[0]
    print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))

    plt.plot(gen, avg_list, label="average")
    plt.plot(gen, min_list, label="minimum")
    plt.plot(gen, max_list, label="maximum")
    plt.xlabel("Generation")
    plt.ylabel("Fitness")
    plt.legend(loc="upper right")
    plt.show()

main()


# 간단한 소인수분해
t = int(input())
primes = [2, 3, 5, 7, 11]
for tc in range(1, t+1):
    result = []
    num = int(input())
    for prime in primes:
        quot, mod = divmod(num, prime)
        count = 0 # 소인수 개수 카운트
        while not mod: # 나머지 0 일 동안
            count += 1
            num = quot
            quot, mod = divmod(num, prime)
        result.append(str(count))
    print('#{} {}'.format(tc, ' '.join(result)))


import sdl2
import sdlboy_console_component
import sdlboy_time
import hw_video as vid
import ctypes
import math

class Color:
    def __init__(self, r, g, b, a=255):
        self.r = r
        self.g = g
        self.b = b
        self.a = a
        self.c_argb = (ctypes.c_uint)((a<<24)|(r<<16)|(g<<8)|b)

class Tileview(sdlboy_console_component.ConsoleComponent):
    pixels = None
    tiles_texture = None
    tiles_texture_rect = None
    tiles_color_map = None
    tiles_num_rows = 0
    tiles_num_cols = 0
    tiles_scale = 0
    tiles_spacing = 0
    last_render_time = 0
    def on_init(self):
        self.tiles_color_map = [None]*4
        self.tiles_color_map[3] = Color(0x00, 0x00, 0x00)
        self.tiles_color_map[2] = Color(0x55, 0x55, 0x55)
        self.tiles_color_map[1] = Color(0xAA, 0xAA, 0xAA)
        self.tiles_color_map[0] = Color(0xFF, 0xFF, 0xFF)
    def on_visible(self):
        if(self.tiles_texture == None):
            self.tiles_texture_rect = sdl2.SDL_Rect(0,0,0,0)
            self.tiles_texture_dst_rect = sdl2.SDL_Rect(0,0,0,0)
    def on_update(self):
        if(sdlboy_time.since_start - self.last_render_time > 0.25):
            self.set_render_required()
    def on_render(self):
        self.last_render_time = sdlboy_time.since_start
        pixels = self.pixels
        color_map = self.tiles_color_map
        pattern_ptr = 0
        pixel_index = 0
        col_counter = 0
        for i in range(0, 512):
            # draw tile row by row
            for j in range(0, 8):
                byte_1 = vid.videoram[pattern_ptr]
                byte_2 = vid.videoram[pattern_ptr+1]
                pixels[pixel_index+0] = color_map[((byte_2>>6)&0x2)|((byte_1>>7)&0x1)].c_argba
                pixels[pixel_index+1] = color_map[((byte_2>>5)&0x2)|((byte_1>>6)&0x1)].c_argba
                pixels[pixel_index+2] = color_map[((byte_2>>4)&0x2)|((byte_1>>5)&0x1)].c_argba
                pixels[pixel_index+3] = color_map[((byte_2>>3)&0x2)|((byte_1>>4)&0x1)].c_argba
                pixels[pixel_index+4] = color_map[((byte_2>>2)&0x2)|((byte_1>>3)&0x1)].c_argba
                pixels[pixel_index+5] = color_map[((byte_2>>1)&0x2)|((byte_1>>2)&0x1)].c_argba
                pixels[pixel_index+6] = color_map[((byte_2>>0)&0x2)|((byte_1>>1)&0x1)].c_argba
                pixels[pixel_index+7] = color_map[((byte_2<<1)&0x2)|((byte_1>>0)&0x1)].c_argba
                # point to next pair of bytes
                pattern_ptr += 2
                # point to next row
                pixel_index += self.tiles_texture_rect.w
            col_counter += 1
            if(col_counter == self.tiles_num_cols):
                col_counter = 0
                pixel_index += self.tiles_texture_rect.w*(self.tiles_spacing-1)
                pixel_index += 8
            else:
                pixel_index -= self.tiles_texture_rect.w*8
                pixel_index += (8+self.tiles_spacing)
        sdl2.SDL_UpdateTexture(
            self.tiles_texture,
            self.tiles_texture_rect,
            pixels,
            self.tiles_texture_rect.w*4
        )
        sdl2.SDL_RenderCopy(
            self.renderer,
            self.tiles_texture,
            self.tiles_texture_rect,
            self.tiles_texture_dst_rect
        )
    def on_resize(self):
        pass
    def set_tiles_dimensions(self, num_rows, num_cols, scale, spacing):
        if(num_rows == self.tiles_num_rows
           and num_cols == self.tiles_num_cols
           and scale == self.tiles_scale
           and spacing == self.tiles_spacing
        ):
            return
        self.tiles_num_rows = num_rows
        self.tiles_num_cols = num_cols
        self.tiles_scale = scale
        self.tiles_spacing = spacing
        pixels_inital = [0]*(0x8000)
        self.pixels = ((ctypes.c_uint)*(256*256))(*pixels_inital)
        self.tiles_texture_rect.w = self.tiles_num_cols*(8+self.tiles_spacing)-self.tiles_spacing
        self.tiles_texture_rect.h = self.tiles_num_rows*(8+self.tiles_spacing)-self.tiles_spacing
        self.tiles_texture_dst_rect.w = self.tiles_texture_rect.w*self.tiles_scale
        self.tiles_texture_dst_rect.h = self.tiles_texture_rect.h*self.tiles_scale
        if(self.tiles_texture):
            sdl2.SDL_DestroyTexture(self.tiles_texture)
        self.tiles_texture = sdl2.SDL_CreateTexture(
            self.renderer,
            sdl2.SDL_PIXELFORMAT_ARGB8888,
            sdl2.SDL_TEXTUREACCESS_TARGET,
            self.tiles_texture_rect.w,
            self.tiles_texture_rect.h
        )
        self.preferred_h = self.tiles_texture_dst_rect.h
    def on_present_width(self, w):
        spacing = 1
        scale = 2
        tile_width = (8+spacing)*scale
        try:
            cols = math.floor(w/tile_width)
            cols = cols - (cols%8) # make cols multiple of 8 (round down)
            rows = math.ceil(512/cols)
        except Exception as e:
            cols = 64
            rows = 8
            print(e)
        self.set_tiles_dimensions(rows, cols, scale, spacing)


import os

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from common.utils import compute_std_of_mean

SAVE_ROOT = '../../figs_sigcomm22'

plt.style.use('seaborn-deep')
plt.rcParams['font.family'] = 'Arial'
# plt.rcParams['font.size'] = 42
# plt.rcParams['axes.labelsize'] = 42
# plt.rcParams['legend.fontsize'] = 42
# plt.rcParams['figure.figsize'] = (11, 9)
plt.rcParams['svg.fonttype'] = 'none'

HATCHES = ['/', '\\', 'x', 'o', '.', 'O', '-', '*', '+']
WIDTH = 0.3

bbr_reward, bbr_tput, bbr_tail_lat, bbr_loss = 192.81, 32.94, 368.93, 0.03
copa_reward, copa_tput, copa_tail_lat, copa_loss = 183.89, 25.70, 265.02, 0.01
cubic_reward, cubic_tput, cubic_tail_lat, cubic_loss = -19.16, 33.99, 802.69, 0.02
vivace_reward, vivace_tput, vivace_tail_lat, vivace_loss = -547.01, 21.71, 947.25, 0.13
vivace_latency_reward, vivace_latency_tput, vivace_latency_tail_lat, vivace_latency_loss = -548.64, 21.84, 1010.43, 0.13
vivace_loss_reward, vivace_loss_tput, vivace_loss_tail_lat, vivace_loss_loss = -825.15, 28.89, 1125.94, 0.26

genet_reward = 223.88
genet_reward_err = 8.05
genet_tput, genet_tail_lat, genet_loss = 31.77, 183.75, 0.02
udr1_reward = 136.81
udr1_reward_err = 23.61
udr1_tput, udr1_tail_lat, udr1_loss = 23.16, 204.23, 0.03
udr2_reward = 158.48
udr2_reward_err = 17.71
udr2_tput, udr2_tail_lat, udr2_loss = 23.09, 185.58, 0.02
udr3_reward = 159.34
udr3_reward_err = 22.83
udr3_tput, udr3_tail_lat, udr3_loss = 22.72, 179.06, 0.02
real_reward = 191.61
real_reward_err = 3.88      # 26.39   250.47  0.02
cl1_reward = 143.86
cl1_reward_err = 7.64      # 22.53   206.07  0.02
cl2_reward = 177.97
cl2_reward_err = 4.55      # 23.17   204.86  0.01

udr3_real_5percent_ethernet_rewards = [177.2, 209.8, 95.2]
udr3_real_10percent_ethernet_rewards = [139, 175, 173]
udr3_real_20percent_ethernet_rewards = [133, 125, 151]
udr3_real_50percent_ethernet_rewards = [162, 124, 78]

column_wid = 0.7
capsize_wid = 8
eline_wid = 2

def generalization_test_ethernet():
    plt.rcParams['font.size'] = 36
    plt.rcParams['axes.labelsize'] = 36
    plt.rcParams['axes.titlesize'] = 36
    plt.rcParams['legend.fontsize'] = 36
    fig, ax = plt.subplots(figsize=(9, 5))
    # plt.bar([1, 2], [bbr_reward, cubic_reward], hatch=HATCHES[:2])
    bars = ax.bar([1, 2, 3, 4],
           [udr1_reward, udr2_reward, udr3_reward, real_reward],
           yerr=[udr1_reward_err, udr2_reward_err, udr3_reward_err,
                 real_reward_err], color='C0', width=column_wid,
           error_kw=dict( lw=eline_wid, capsize=capsize_wid))
    # bars = ax.bar([1, 2, 3, 4],
    #         [udr1_reward, udr2_reward, udr3_reward, real_reward],
    #         color=None, edgecolor='white')
    for bar, pat in zip(bars, HATCHES):
        bar.set_hatch(pat)

    ax.bar([5], [genet_reward], yerr=[genet_reward_err], capsize=8, width=column_wid,
           color='C2', error_kw=dict( lw=eline_wid, capsize=capsize_wid))
    # plt.title('Ethernet')
    ax.set_xticks([1, 2, 3, 4, 5])
    ax.set_xticklabels(['RL1', 'RL2', 'RL3', 'RL-real', 'Genet'], rotation=20)
    ax.set_ylabel('Test reward')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False)         # ticks along the top edge are off
    # plt.tight_layout()
    svg_file = os.path.join(SAVE_ROOT, 'evaluation_generalization_test_ethernet.svg')
    pdf_file = os.path.join(SAVE_ROOT, 'evaluation_generalization_test_ethernet.pdf')
    fig.savefig(svg_file,  bbox_inches='tight')
    os.system("inkscape {} --export-pdf={}".format(svg_file, pdf_file))
    os.system("pdfcrop --margins 1 {} {}".format(pdf_file, pdf_file))

def asymptotic_real():
    plt.rcParams['font.size'] = 34
    plt.rcParams['axes.labelsize'] = 34
    plt.rcParams['axes.titlesize'] = 34
    plt.rcParams['legend.fontsize'] = 34
    fig, ax = plt.subplots(figsize=(9.5, 5))
    bbr_reward = 192.81 #32.94   368.93  0.03
    udr_real_synthetic_reward =  171.16 #    23.67   194.00  0.02
    udr_real_synthetic_reward_err =  24.22
    genet_real_synthetic_reward = 239.39   # 30.93   208.04  0.02
    genet_real_synthetic_reward_err = 7.34
    cubic_reward = 97.16 #  33.99   802.69  0.02

    # plt.bar([1, 2], [bbr_reward, cubic_reward])
    # plt.bar([3.5, 4.5,],
    ax.bar([1, 2.2, 3.4, 4.6, 5.8],
            [udr_real_synthetic_reward, # 1%
             np.mean(udr3_real_10percent_ethernet_rewards),
             np.mean(udr3_real_20percent_ethernet_rewards),
             np.mean(udr3_real_50percent_ethernet_rewards),
             real_reward],
            yerr=[udr_real_synthetic_reward_err,
              compute_std_of_mean(udr3_real_10percent_ethernet_rewards),
              compute_std_of_mean(udr3_real_20percent_ethernet_rewards),
              compute_std_of_mean(udr3_real_50percent_ethernet_rewards),

                  real_reward_err], hatch=HATCHES[:5], capsize=8)

    ax.bar([7.3], [genet_real_synthetic_reward],
           yerr=[genet_real_synthetic_reward_err], capsize=8, color='C2')

    ax.set_xticks([1, 2.2, 3.4, 4.6, 5.8, 7.3])
    ax.set_xticklabels(['5%', '10%',
                        '20%', '50%',
                        '100%', 'Genet\n(synthetic+real)'],)
                        # rotation=30, ha='right', rotation_mode='anchor')
    ax.annotate("RL (synthetic + real)", (0.9, 209))
    ax.set_ylabel('Test reward')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False)         # ticks along the top edge are off
    # plt.tight_layout()

    svg_file = os.path.join(SAVE_ROOT, 'evaluation_asymptotic_real_new.svg')
    pdf_file = os.path.join(SAVE_ROOT, 'evaluation_asymptotic_real_new.pdf')
    fig.savefig(svg_file,  bbox_inches='tight')
    os.system("inkscape {} --export-pdf={}".format(svg_file, pdf_file))
    os.system("pdfcrop --margins 1 {} {}".format(pdf_file, pdf_file))

def cc_scatter():
    plt.rcParams['font.size'] = 32
    plt.rcParams['axes.labelsize'] = 32
    plt.rcParams['axes.titlesize'] = 32
    plt.rcParams['legend.fontsize'] = 32
    fig, ax = plt.subplots(figsize=(9, 5))
    msize = 200
    ax.scatter([bbr_tail_lat], [bbr_tput], marker='d', s=msize, color='C0',
               label='BBR')
    ax.annotate('BBR', (bbr_tail_lat+70, bbr_tput-2))
    ax.scatter([copa_tail_lat], [copa_tput], marker='>', s=msize, color='C1',
               label='Copa')
    ax.annotate('Copa', (copa_tail_lat+110, copa_tput+0.8))
    ax.scatter([cubic_tail_lat], [cubic_tput], marker='v',
               s=msize, color='darkorange', label='Cubic')
    ax.annotate('Cubic', (cubic_tail_lat+80, cubic_tput - 2))
    ax.scatter([vivace_latency_tail_lat], [vivace_latency_tput], marker='^',
               s=msize, color='C3', label='Vivace')
    ax.annotate('Vivace', (vivace_latency_tail_lat, vivace_latency_tput))
    ax.scatter([udr1_tail_lat], [udr1_tput], marker='<', s=msize, color='C4',
               label='RL1')
    ax.annotate('RL1', (udr1_tail_lat+115, udr1_tput))
    ax.scatter([udr2_tail_lat], [udr2_tput], marker='p', s=msize, color='C5',
               label='RL2')
    ax.annotate('RL2', (udr2_tail_lat+20, udr2_tput+0.5))
    ax.scatter([udr3_tail_lat], [udr3_tput], marker='s', s=msize, color='indigo', label='RL3')
    ax.annotate('RL3', (udr3_tail_lat+120, udr3_tput-1.2))
    ax.scatter([genet_tail_lat], [genet_tput], s=msize, color='C2',
               label='Genet')
    ax.annotate('Genet', (genet_tail_lat+80, genet_tput-1.5))
    ax.set_ylabel('Throughput (Mbps)')
    ax.set_xlabel('90th percentile latency (ms)')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.invert_xaxis()
    # fig.legend(bbox_to_anchor=(0, 1.02, 1, 0.14), ncol=4, loc="upper center",
    #            borderaxespad=0, borderpad=0.2, columnspacing=0.01,
    #            handletextpad=0.001)

    svg_file = os.path.join(SAVE_ROOT, 'evaluation_cc_scatter.svg')
    pdf_file = os.path.join(SAVE_ROOT, 'evaluation_cc_scatter.pdf')
    fig.savefig(svg_file,  bbox_inches='tight')
    os.system("inkscape {} --export-pdf={}".format(svg_file, pdf_file))
    os.system("pdfcrop --margins 1 {} {}".format(pdf_file, pdf_file))

if __name__ == '__main__':
    # generalization_test_ethernet()
    asymptotic_real()
    # cc_scatter()