import argparse

import data_formatters.base
import expt_settings.configs

from Models.cslr import cslr
from Models.ml import ml_models

from bayes_opt.utils import write_results

ExperimentConfig = expt_settings.configs.ExperimentConfig

def main(
        expt_name,
        edcs_methods,
        use_ml,
        data_formatter
    ):
    """Trains cslr based on defined model params.

      Args:
        expt_name: Name of experiment.
        edcs_methods: List of EDCS solving approaches.
        use_ml: Whether to use state-of-the-art Machine Learning models.
        data_formatter: Dataset-specific data fromatter
    """

    if not isinstance(data_formatter, data_formatters.base.GenericDataFormatter):
        raise ValueError(
            "Data formatters should inherit from" +
            "AbstractDataFormatter! Type={}".format(type(data_formatter)))

    print("*** Training from defined parameters for {} ***".format(expt_name))

    ml_methods = ["tree", "xgboost", "logistic"]

    params = data_formatter.get_default_model_params()
    for k in params:
        print("{}: {}".format(k, params[k]))

    simulated_expt = ExperimentConfig.simulated_experiments
    writer = write_results(data_formatter)
    num_repeats = data_formatter.params["num_repeats"]

    # running the experiments
    for n in range(num_repeats):

        data_formatter.split_data()
        data_formatter.save_models(n, expt_name, simulated_expt)

        if data_formatter.params["validation"] == True:

            data_formatter.perform_validation(n)

            for split in range(data_formatter.n_splits):

                print("***Loading & splitting data***")
                train, test, valid = data_formatter.load_data(split)
                model = cslr(data_formatter, train, test, valid)

                # running edcs learning methods and printing the results
                for m in edcs_methods:
                    model.expt = m
                    train_scores, test_scores, val_scores = model.result()
                    writer.collect_results(n, m, train_scores, test_scores, val_scores)

                # running other machine learning methods and printing the results
                if use_ml == "yes":
                    ml_model = ml_models(data_formatter, train, test, valid)
                    for m in ml_methods:
                        ml_model.expt = m
                        train_scores, test_scores, val_scores = ml_model.result()
                        writer.collect_results(n, m, train_scores, test_scores, val_scores)

        else:
            print("***Loading & splitting data***")
            train, test, _ = data_formatter.load_data()
            model = cslr(data_formatter, train, test)

            # running edcs learning methods and printing the results
            for m in edcs_methods:
                model.expt = m
                train_scores, test_scores, _ = model.result()
                writer.collect_results(n, m, train_scores, test_scores)

            # running other machine learning methods and printing the results
            if use_ml == "yes":
                ml_model = ml_models(data_formatter, train, test)
                for m in ml_methods:
                    ml_model.expt = m
                    train_scores, test_scores, _ = ml_model.result()
                    writer.collect_results(n, m,train_scores, test_scores)

        writer.print_results()
        print("Printing average results.....")
        print(writer.average_results)
        #print(writer.mip_perf)

    #print(writer.train_df)
    print("Printing average results.....")
    print(writer.average_results)
    #print("Printing mip performance results.....")
    #print(writer.mip_avg_perf)

if __name__ == "__main__":

    def get_args():
        """Gets settings from command line."""

        datasets = ExperimentConfig.default_experiments
        parser = argparse.ArgumentParser(description = "Dataset and experiment configs")

        parser.add_argument(
            "expt_name",
            metavar="e",
            type=str,
            nargs="?",
            default="ex1",
            choices=datasets,
            help="Dataset Name. Default={}".format(",".join(datasets)))
        parser.add_argument(
            "cslr",
            metavar="c",
            type=str,
            nargs="?",
            choices=["yes", "no"],
            default="yes",
            help="Whether to use Cost Sensitive Logistic Learning")
        parser.add_argument(
            "mip_wi",
            metavar="w",
            type=str,
            nargs="?",
            choices=["yes", "no"],
            default="no",
            help="Whether to use MIP-WI")
        parser.add_argument(
            "mip",
            metavar="m",
            type=str,
            nargs="?",
            choices=["yes", "no"],
            default="no",
            help="Whether to use MIP")
        parser.add_argument(
            "ml",
            metavar="ml",
            type=str,
            nargs="?",
            choices=["yes", "no"],
            default="no",
            help="Whether to use ML algorithms")
        parser.add_argument(
            "hyperparam_opt",
            metavar="h",
            type=str,
            nargs="?",
            choices=["yes", "no"],
            default="no",
            help="Whether to use Hyperparam Opt on CSLR")
        parser.add_argument(
            "time_limit",
            metavar="tm",
            type=int,
            nargs="?",
            default=100,
            help="Time Limit")
        parser.add_argument(
            "output_folder",
            metavar="f",
            type=str,
            nargs="?",
            default=".",
            help="Path to folder for results and models")

        args = parser.parse_known_args()[0]

        folder = None if args.output_folder == "." else args.output_folder

        return (args.expt_name,
                args.cslr,
                args.mip_wi,
                args.mip,
                args.ml,
                args.hyperparam_opt,
                args.time_limit,
                folder
               )

    expt_name, use_cslr, mip_wi, mip, ml, hyperparam_opt, time_limit, folder = get_args()

    config = ExperimentConfig(expt_name, folder)
    formatter = config.make_data_formatter()

    formatter.expt_name = expt_name
    formatter.data_folder = config.data_folder
    formatter.model_folder = config.model_folder
    formatter.results_folder = config.results_folder
    formatter.time_limit = time_limit
    formatter.bayes = (True if hyperparam_opt == "yes" else False)

    edcs_methods = []
    if use_cslr == "yes":
        edcs_methods.append("cslr")
    if mip_wi == "yes":
        edcs_methods.append("mip_wi")
    if mip == "yes":
        edcs_methods.append("mip")

    # For new experiments customise inputs to main() .
    main(
        expt_name=expt_name,
        edcs_methods=edcs_methods,
        use_ml=ml,
        data_formatter=formatter
    )


#!/usr/bin/python
import sys
import os
import configparser
import pymongo
from pymongo import MongoClient

class NoSQLConnection:
    """Used to connect to a NoSQL database and send queries into it"""

    current_dir = os.path.dirname(__file__)
    config_rel_path = '../config/db.cfg'
    config_abs_path = os.path.join(current_dir, config_rel_path)

    section_name = 'NonRelational Database Details'

    def __init__(self):
        config = configparser.ConfigParser()
        config.read(self.config_abs_path)

        try:
            self.db_name = config[self.section_name]['db_name']
            self.monitoring_collection_name = \
                config[self.section_name]['monitoring_collection_name']
            self.migrations_collection_name = \
                config[self.section_name]['migrations_collection_name']
            self.viewercount_collection_name = \
                config[self.section_name]['viewercount_collection_name']
            self.hostname = config[self.section_name]['hostname']
            self.user = config[self.section_name]['user']
        except Exception as e:
            print('there was a problem accessing the db.cfg file and reading')
            print(str(e))
            sys.exit()

        self.client = MongoClient(self.hostname, 27017)
        self.db = self.client[self.db_name]
        self.monitoring_collection = self.db[self.monitoring_collection_name]
        self.migrations_collection = self.db[self.migrations_collection_name]
        self.migrations_collection.create_index([('from_stream', pymongo.ASCENDING),
                                                 ('to_stream', pymongo.ASCENDING)],
                                                unique=True)
        self.migrations_collection.create_index([('migrations.leave_time',
                                                  pymongo.DESCENDING)])
        self.migrations_collection.create_index([('migrations.join_time',
                                                  pymongo.DESCENDING)])
        self.viewercount_collection = self.db[self.viewercount_collection_name]

    def recreate_db(self):
        """
        drops the database and recreates it from scratch
        WARNING: all data will be lost
        """
        self.client.drop_database(self.db_name)
        self.db = self.client[self.db_name]
        self.monitoring_collection = self.db[self.monitoring_collection_name]
        self.migrations_collection = self.db[self.migrations_collection_name]
        self.migrations_collection.create_index([('from_stream', pymongo.ASCENDING),
                                                 ('to_stream', pymongo.ASCENDING)],
                                                unique=True)
        self.migrations_collection.create_index([('migrations.leave_time',
                                                  pymongo.DESCENDING)])
        self.migrations_collection.create_index([('migrations.join_time',
                                                  pymongo.DESCENDING)])
        self.viewercount_collection = self.db[self.viewercount_collection_name]


import pandas as pd

from numpy import inf
from matplotlib import pyplot as plt
import logging
import numpy as np

logger = logging.getLogger(__name__)

class MetricTracker:
    def __init__(self, *keys, writer=None):
        # self.writer = writer
        self._data = pd.DataFrame(index=keys, columns=['total', 'counts', 'average'])
        self.reset()

    def reset(self):
        for col in self._data.columns:
            self._data[col].values[:] = 0

    def update(self, key, value, n=1):
        self._data.total[key] += value * n
        self._data.counts[key] += n
        self._data.average[key] = self._data.total[key] * 1.0 / self._data.counts[key]

    def avg(self, key):
        return self._data.average[key]

    def result(self):
        return dict(self._data.average)

class MonitorEarlyStop:
    def __init__(self, monitor_spec, nb_earlystop):
        self.mnt_variable, self.mnt_mode = monitor_spec.split("_")
        assert self.mnt_variable in ['acc', 'loss'], f"{self.mnt_variable} not support"
        assert self.mnt_mode in ['min', 'max'], f"{self.mnt_mode} not support"
        self.mnt_best = inf if self.mnt_mode == "min" else -inf
        self.nb_earlystop = nb_earlystop
        self.nb_not_improve = 0

    def check_to_stop(self, mnt_result):
        step_result = mnt_result[self.mnt_variable]
        improved = (self.mnt_mode == 'min' and step_result < self.mnt_best) or \
                   (self.mnt_mode == 'max' and step_result > self.mnt_best)

        if not improved:
            self.nb_not_improve += 1
            logger.info(f"Model not improved {self.mnt_variable} in {self.nb_not_improve} epochs ")
        else:
            logger.info(f"{self.mnt_variable} improve from {self.mnt_best} to {step_result}")

            self.mnt_best = step_result
            self.nb_not_improve = 0

        need_stop = False
        if self.nb_not_improve >= self.nb_earlystop:
            logger.info("Stop training because EarlyStop")
            need_stop = True
        return improved, need_stop

def matplotlib_imshow(img, one_channel=False):
    if one_channel:
        img = img.mean(dim=0)
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    if one_channel:
        plt.imshow(npimg, cmap="Greys")
    else:
        plt.imshow(np.transpose(npimg, (1, 2, 0)))


trees = [[int(x) for x in line.strip()] for line in open("Input.txt", "r")]

scores = []

for y in range(1, len(trees) - 1):
    for x in range(1, len(trees[y]) - 1):
        sights = [trees[y][: x][::-1], trees[y][x + 1 :], [line2[x] for line2 in trees[: y]][::-1], [line2[x] for line2 in trees[y + 1 :]]]

        total = 0
        for i, sight in enumerate(sights):
            for height in sight:
                if trees[y][x] > height:
                    total += 1

                else:
                    total += 1
                    break

            sights[i] = total
            total = 0

        total = 1
        for s in sights:
            total *= s

        scores.append(total)

print(max(scores))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019-12-17 10:27
# @Author  : liujin
# @Email   : 1045833538@QQ.com
# @File    : py.py
import threading
import requests
import datetime
import time
'''
@THREAD_NUM :线程数
@ONE_WORKER_NUM :每个线程循环数
'''

THREAD_NUM = 2000
ONE_WORKER_NUM = 1
SUMTIME = 0.00
SUCCESSCOUNT = 0
def getdatar(url):
    # url = 'http://wxbt.jcms.top:8080/hongbao'
    # url = 'http://10.168.5.120:8500'
    headers = {

    'Content-Type':'text/html;charset=utf-8',

    'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',

    }

    return requests.post(url, headers=headers)
def test(url):
    global a
    global SUMTIME
    global SUCCESSCOUNT
    global SUCCESSCOUNT
    response = getdatar(url)
    res_time = response.elapsed.microseconds/1000000
    c = response.status_code
    if c!=200:
        f=open("a.txt","a+")
        f.write(str(c))
    print(response.status_code)

    # print(datetime.datetime.now(),"—",response.text)
    print(1)
    SUMTIME = SUMTIME + res_time
    SUCCESSCOUNT = SUCCESSCOUNT + 1
url='http://10.168.5.164:8006/6A2255C958C2C155'
def working():
    global ONE_WORKER_NUM
    for i in range(0,ONE_WORKER_NUM):

        test(url)

def t():
    global THREAD_NUM
    Threads = []
    for i in range(THREAD_NUM):
        t = threading.Thread(target=working,name='T'+str(i))
        t.setDaemon(True)
        Threads.append(t)
    for t in Threads:
        t.start()
    for t in Threads:
        t.join()

if __name__ == '__main__':
    t()
    # print(a)
    print('并发数：' + str(THREAD_NUM * ONE_WORKER_NUM))
    print('成功数：' + str(SUCCESSCOUNT))
    print('成功率：' + str(SUCCESSCOUNT / (THREAD_NUM * ONE_WORKER_NUM) * 100) + '%')
    print('成功请求总响应时间：' + str(SUMTIME))
    (lambda x=SUMTIME, y=SUCCESSCOUNT: print('成功订单平均响应时间：' + str(x / y)) if y != 0 else print('成功数为0'))()
    (lambda x=SUMTIME, y=SUCCESSCOUNT: print('TPS：' + str(y / (x / y))) if x != 0 and y != 0 else print('成功数或响应时间为0'))()


class task:
    def __init__(self, title, description, status):
        self.title = title
        self.description = description
        self.status = status

mytasks = []

def strike(text):
    result = ''
    for c in text:
        result += + c + '\u0336'
    return result

def remove_strike(text):
    result = ''
    for char in text:
        if char != '\u0336':
            result += char
    return result

def addtask():

    while True:

        title = input("Enter the Task: ")
        desc = input("Enter the Description: ")

        if title=='' or title.isspace() or desc=='' or desc.isspace():
            print("\nEmpty Task. Please enter a valid task\n")
            continue
        else:
            mytasks.append(task(title,desc,"Pending"))
            break

def displaytask():
    # enumerate to iterate two variables in the list. One for the task and other for the number of the task
    for index,todo in enumerate(mytasks):
        print(index+1,") ",todo.title,sep='')
        print("  ",todo.description,"-",todo.status)

    if len(mytasks)==0:
        print("No Tasks. Add A New Task or Load From Files")
        return 0

def completetask():

    if len(mytasks)==0:
        return 0 #Using return here to stop the function if there are no existing tasks

    while True:
        try:
            index = int(input("\nEnter the task number which is complete: "))
        except ValueError:
            print("Invalid Input")
            continue
        break

    if index<=0 or index>len(mytasks):
        print("Invalid Index")

    else:
        index = index - 1 # mytasks index 0 will be the task number 1. So subtracting 1 from index
        mytasks[index].status = "Complete"
        mytasks[index].description = strike(mytasks[index].description)

def pendingtask():

    if len(mytasks)==0:
        return 0 #Using return here to stop the function if there are no existing tasks

    while True:
        try:
            index = int(input("\nEnter the task number which is pending: "))
        except ValueError:
            print("Invalid Input")
            continue
        break

    if index<=0 or index>len(mytasks):
        print("Invalid Index")

    else:
        index = index - 1 # mytasks index 0 will be the task number 1. So subtracting 1 from index
        mytasks[index].status = "Pending"
        mytasks[index].description = remove_strike(mytasks[index].description)

def deletetask():

    if len(mytasks)==0:
        return 0 #Using return here to stop the function if there are no existing tasks

    while True:
        try:
            index = int(input("\nEnter the task number to be deleted: "))
        except ValueError:
            print("Invalid Input")
            continue
        break

    if index<=0 or index>=len(mytasks):
        print("Invalid Index")

    else:
        index = index-1
        mytasks.pop(index)

def save():

    if len(mytasks)==0:
        print("No Tasks. Add A New Task or Load From Files")
        return 0 #Using return here to stop the function if there are no existing tasks

    with open("mytask.txt",'w') as myfile:
        for todo in mytasks:
            mystr = (todo.title,"|",todo.description,"|",todo.status,"|","\n") #tuple with all the values

            #adding | to separate title, desc etc, used later during loading from file

            mystr = "".join(mystr)
            # converted the tuple into a string with format "title | description status" and now we can write this to the file
            # and separate to multiple lines using \n

            myfile.write(mystr)

    print("Saved to File")

def load():
    with open("mytask.txt",'r') as myfile:
        for line in myfile:
            line = (line.split("|")) #splitting the line which was read, by | as it is stored in the txt file
            # ['chemistry', 'assingment', 'Pending', '\n'] returned line is in this format
            linetask = line[0]
            linedesc = line[1]
            linestatus = line[2]

            #adding to tasks array

            mytasks.append(task(linetask,linedesc,linestatus))

    print("Loaded From File")

while True:
    print("\nMenu")
    print("1. Add Task")
    print("2. Display All Tasks")
    print("3. Mark Task As Completed")
    print("4. Mark Task As Pending")
    print("5. Delete Task")
    print("6. Save")
    print("7. Load")
    print("8. Exit\n")

    choice = input("Enter the Choice: ")
    print()

    if choice == '1':
        addtask()
        continue

    elif choice == '2':
        displaytask()
        continue

    elif choice == '3':
        displaytask()
        completetask()
        continue

    elif choice == '4':
        displaytask()
        pendingtask()
        continue

    elif choice == '5':
        displaytask()
        deletetask()
        continue

    elif choice =='6':
        save()
        continue

    elif choice =='7':
        mytasks = []  #emptying the current tasks so we can replace it with the loaded tasks
        load()
        continue

    elif choice =='8':
        break

    else:
        print("Invalid Choice")
        continue


import numpy as np

a0 = 7
a1 = 1
a2 = 0
a3 = 8
plan_matrix = np.floor(20 * np.random.random((8, 3)))
Y = np.array([a0 + a1 * plan_matrix[i, 0] + a2 * plan_matrix[i, 1] + a3 * plan_matrix[i, 2] for i in range(len(plan_matrix))])
X0 = np.array([((np.max(plan_matrix[:, i]) + np.min(plan_matrix[:, i])) / 2) for i in range(len(plan_matrix[0]))])
Y_reference = a0 + a1 * X0[0] + a2 * X0[1] + a3 * X0[2]
interval_of_change = np.array([(np.max(plan_matrix[:, i]) - X0[i]) for i in range(len(plan_matrix[0]))])
X_norm = np.array([[round((plan_matrix[i, j] - X0[j]) / interval_of_change[j], 3) for j in range(len(plan_matrix[i]))] for i in
                   range(len(plan_matrix))])
diffs = sorted([i for i in sorted(Y) if i>Y_reference])[0]
evaluation_criterion = list(Y).index(diffs)
optionY = Y[evaluation_criterion]
optionX = plan_matrix[evaluation_criterion]
print("Матриця плану експерименту: \n", plan_matrix)
print("Значення функції відгуку: ", Y)
print("Значення нульових рівнів факторів: ", X0)
print("Эталонне значення Y: ", Y_reference)
print("Нормовані значення Х: \n", X_norm)
print("Середнє значення Y: ", np.mean(Y))
print("Значення функції відгуку, що задовольняє критерію оціновання: ", optionY)
print("Точка експерименту, що задавольняє критерію оцінювання: ", optionX)


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

# Stdlib imports

# Core Django imports
from django.contrib import admin
from django.utils.translation import ugettext as _

# Third-party app imports

# Realative imports of the 'app-name' package
from .models import Person, Contact

class ContactInline(admin.TabularInline):
    """
    Formulario de contatos em linha
    """
    model = Contact
    extra = 2

class PersonAdmin(admin.ModelAdmin):
    """
    Classe admin utilizada no django admin para oferecer as
    opcoes de CRUD da tabela pessoa
    """

    inlines = [ContactInline, ]

    # campos a serem exibidos na tabela
    list_display = (
        'name',
        'created'
    )

    date_hierarchy = 'created'

    # campos que utilizam buscas no model
    search_fields = ('name', 'created', )

    list_filter = ('created', )

    fieldsets = (
        (
            _(u'Dados da Pessoa'),
            {
                'fields': (
                    'name',
                ),
                'description': _(u'Dados'),
                'classes': [],
            }
        ),
    )

class ContactAdmin(admin.ModelAdmin):
    """
    Classe admin utilizada no django admin para oferecer as
    opcoes de CRUD da tabela de contatos
    """

    # campos a serem exibidos na tabela
    list_display = (
        'kind',
        'value',
        'created'
    )

    date_hierarchy = 'created'

    # campos que utilizam buscas no model
    search_fields = ('kind', 'value', 'created', )

    list_filter = ('created', )

    fieldsets = (
        (
            _(u'Dados de contatos'),
            {
                'fields': (
                    'kind',
                    'value'
                ),
                'description': _(u'Dados'),
                'classes': [],
            }
        ),
    )

admin.site.register(Person, PersonAdmin)
admin.site.register(Contact, ContactAdmin)


def productExceptSelf(nums):
	#first lets create the output array using mult from right
	out = [0]*len(nums)
	start = 1

	#accumulate the mult from right in out array
	for i in xrange(len(nums)-1,-1,-1):
		out[i] = start
		start *= nums[i]

	#now maintain leftMult variable and use it for every index in out array
	leftMult = 1
	for i in xrange(len(out)):
		out[i] *= leftMult
		leftMult*=nums[i]
	return out

nums = [1,2,3,4]
productExceptSelf(nums)


import logging
from typing import Any

from pandas import to_datetime

from core.enums.definition import ColumnDefinition, DefinitionType
from core.functions.definition.util import get_start_timestamp, get_column_definition
from core.functions.message.sender import send_streaming_prescription_request_to_all_plugins

# Enable logging
logger = logging.getLogger(__name__)

def prepare_prefix_and_send(project_id: int, model_names: dict[str, str], event_id: int,
                            columns_definition: dict[str, ColumnDefinition], case_attributes: list[str],
                            data: list[dict], additional_infos: dict[str, dict[str, Any]]) -> bool:
    # Prepare prefix and send to all plugins
    result = False

    try:
        # Rename columns
        data = rename_elements(data, columns_definition, case_attributes)

        # Get timestamp column
        timestamp_column = columns_definition[get_start_timestamp(columns_definition)]

        # Sort data's element by timestamp
        data.sort(key=lambda x: to_datetime(x[timestamp_column]))
        send_streaming_prescription_request_to_all_plugins(
            plugins=list(model_names.keys()),
            project_id=project_id,
            model_names=model_names,
            event_id=event_id,
            prefix=data,
            additional_infos=additional_infos
        )
        result = True
    except Exception as e:
        logger.error(f"Error while preparing prefix and sending to plugins: {e}", exc_info=True)

    return result

def rename_elements(data: list[dict], columns_definition: dict[str, ColumnDefinition],
                    case_attributes: list[str]) -> list[dict]:
    # Rename columns of elements in data list based on definition
    for element in data:
        for column in list(element):
            definition = get_column_definition(column, columns_definition)
            if definition in DefinitionType.SPECIAL:
                element[definition] = element.pop(column)
            elif definition == ColumnDefinition.CATEGORICAL:
                element[f"CATEGORICAL_{column}"] = element.pop(column)
            elif case_attributes and column in case_attributes:
                element[f"CASE_ATTRIBUTE_{definition}_{column}"] = element.pop(column)
            else:
                element[f"EVENT_ATTRIBUTE_{definition}_{column}"] = element.pop(column)
    return data


import argparse
import time
import sys

from kse.framework.library.file_util import load
from kse.kymera.kymera.generic.accmd import ACCMD_CMD_ID_MESSAGE_FROM_OPERATOR_REQ

START_TIME = 0                # Track the time for processing the simulation
ACCMD_CMD_ID_AANC_TRIGGER = 7 # Unsolicited message ID for AANC
PAYLOAD_OFFSET = 4            # Offset into the payload to start reading data
FF_FINE_GAIN_OFFSET = 3       # Offset into the data for FF fine gain
PREVIOUS_GAIN = 0             # Previous gain value

def cb_adaptive_gain(data):
    '''
    Callback to handle unsolicited messages.

    If the message comes from AANC print the time and gain value.

    Args:
        data (list[int]): accmd data received
    '''
    global PREVIOUS_GAIN
    cmd_id, _, payload = kymera._accmd.receive(data)

    if cmd_id == ACCMD_CMD_ID_MESSAGE_FROM_OPERATOR_REQ:
        if payload[1:3] == [0, ACCMD_CMD_ID_AANC_TRIGGER]:
            event_time = uut.timer_get_time() - START_TIME
            ff_fine_gain = payload[PAYLOAD_OFFSET + FF_FINE_GAIN_OFFSET]
            if ff_fine_gain != PREVIOUS_GAIN:
                print('%0.03f: Gain Update -> %d' % (event_time, ff_fine_gain))
                PREVIOUS_GAIN = ff_fine_gain

def run_graph(args):
    '''
    Run the AANC graph.

    Args:
        args (argparser.args): parsed command-line arguments
    '''
    global START_TIME
    print('downloading file %s' % (args.dkcs_file))

    id = hydra_cap_download.download(args.dkcs_file)
    print('Bundle downloaded. Id is %s' % (id))

    data = load(args.graph_file)
    graph.load(data)
    print('Graph loaded')

    kymera._accmd.register_receive_callback(cb_adaptive_gain)
    print('Callback registered')

    graph.create()
    print('Graph created')
    graph.config()
    print('Graph configured')
    graph.connect()
    print('Graph connected')

    graph.start()
    START_TIME = uut.timer_get_time()
    print('Graph started')

    while graph.check_active():
        time.sleep(0.5)

    print('Graph Finished!')

    graph.stop()
    graph.disconnect()
    graph.destroy()
    print('Graph destroyed')

    hydra_cap_download.remove(id)
    print('Bundle id %s removed' % (id))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='AANC capability startup kalsim shell script')
    parser.add_argument('dkcs_file', type=str, help='Input bundle file (dkcs file)')
    parser.add_argument('graph_file', type=str, help='Graph configuration file (cfg.json file)')
    args = parser.parse_args()
    run_graph(args)


from random import randint
from art import logo

def hint(guess, user_guess):
    if user_guess > guess:
        return "Too High\nGuess Again"
    elif user_guess < guess:
        return "Too low\nGuess Again"

def play(possible_attempts):
    while possible_attempts >= 0:
        user_guess = int(input(f"Remaing guess chance = {possible_attempts}.\nGuess a number between 1-100: "))
        if user_guess != guess:
            if possible_attempts == 0:
                print(f"Youve run out of guesses. You lose.The number is {guess}")
                break
            print(hint(guess,user_guess))
        else:
            print("You win")
            break
        possible_attempts -= 1

while input("Would you like to play a number guess game? Reply with 'y' or 'n': ").lower() == 'y':
    print(logo)
    print("Welcome to This Guess Game")
    Interested = True
    while Interested:
        guess = randint(1,100)
        user_choice = input("Choose Difficulty level. Reply with 'Easy' or 'Hard' or 'No': ").lower()
        if user_choice == 'easy':
            possible_attempts = 10
            play(possible_attempts)
        elif user_choice == 'hard':
            possible_attempts = 5
            play(possible_attempts)
        elif user_choice == 'no':
            break
        else:
            pass


import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

youtube_trending_url = "https://www.youtube.com/feed/trending"

def get_driver():
  chrome_options = Options()
  chrome_options.binary_location = '/opt/headless-chromium'
  chrome_options.add_argument('--headless')
  chrome_options.add_argument('--no-sandbox')
  chrome_options.add_argument('--single-process')
  chrome_options.add_argument('--disable-dev-shm-usage')
  driver = webdriver.Chrome(options=chrome_options)
  return driver

if __name__ == "__main__":

  print("Creating Driver")
  driver = get_driver()

  print("Fetching the Page")
  driver.get(youtube_trending_url)

  print("Get the Video's Div's")
  Video_Div_Class_Name = 'ytd-video-renderer'
  video_divs = driver.find_elements_by_class_name(Video_Div_Class_Name)

  print(f'Found {len(video_divs)} Videos')

# response = requests.get(youtube_trending_url)

# print('Status Code', response.status_code)

# with open ("trading.html", "w") as f:
#   f.write(response.text)

# doc = BeautifulSoup(response.text, "html.parser")

# print("Page Title:", doc.title)

# video_divs = doc.find_all('div', class_='ytd-video-renderer')

# print(f'Found {len(video_divs)} Videos')


import json

# Third party imports.
import aiofiles

# Local imports.
from .errors import MissingDeviceAuth
from typing import Optional, Union

class DeviceAuth:
    def __init__(self,
                 device_id: Optional[str] = None,
                 account_id: Optional[str] = None,
                 secret: Optional[str] = None,
                 **kwargs
                 ) -> None:
        self.device_id = device_id
        self.account_id = account_id
        self.secret = secret

class DeviceAuths:
    def __init__(self, filename: str) -> None:
        self.device_auth = None
        self.filename = filename

    async def load_device_auths(self) -> None:
        try:
            async with aiofiles.open(self.filename, mode='r') as fp:
                data = await fp.read()
                raw_device_auths = json.loads(data)
        except (json.decoder.JSONDecodeError, FileNotFoundError):
            raw_device_auths = {}

        if 'device_id' not in raw_device_auths or \
            'account_id' not in raw_device_auths or \
                'secret' not in raw_device_auths:
            raise MissingDeviceAuth('Missing required device auth key.')

        self.device_auth = DeviceAuth(
            device_id=raw_device_auths.get('device_id'),
            account_id=raw_device_auths.get('account_id'),
            secret=raw_device_auths.get('secret')
        )

    async def save_device_auths(self) -> None:
        async with aiofiles.open(self.filename, mode='w') as fp:
            await fp.write(json.dumps(
                {
                    "account_id": self.device_auth.account_id,
                    "device_id": self.device_auth.device_id,
                    "secret": self.device_auth.secret
                },
                sort_keys=False,
                indent=4
            ))

    def set_device_auth(self, **kwargs) -> None:
        self.device_auth = DeviceAuth(
            **kwargs
        )

    def get_device_auth(self) -> Union[DeviceAuth, None]:
        return self.device_auth


rawRestaurants=eval(input())
restaurants=[]
for rawRestaurant in rawRestaurants:
    tmp = []
    for s in rawRestaurant:
        tmp.append(int(s))
    restaurants.append(tmp)
veganFriendly=int(input())
maxPrice=int(input())
maxDistance=int(input())
dic = {}
for restaurant in restaurants:
    if veganFriendly == 0:
        if restaurant[3] <= maxPrice and restaurant[4] <= maxDistance:
            dic[restaurant[0]] = restaurant[1]
    else:
        if restaurant[3] <= maxPrice and restaurant[4] <= maxDistance and restaurant[2] == 1:
            dic[restaurant[0]] = restaurant[1]
res = []
# 按照 rating 从高到低排序。如果 rating 相同，那么按 id 从高到低排序。
dic = sorted(dic.items(), key=lambda x: [x[1], x[0]], reverse=True)
for i in dic:
    res.append(i[0])
print(res)


# import turtle module
import turtle

s = turtle.getscreen
turtle.title("Turtle Training Academy - You Gotta Train Your Turtle")
turtle.bgcolor("lavender")

# This variable name (t) is what we will call our turtle
t = turtle.Turtle()
# Appropriately shaped
t.shape("turtle")

t.pensize(5)
t.pencolor("white")
t.fillcolor("light blue")

# I turned certain things into functions to call upon later
# as opposed to deleting the code when not in use.
def myshape():
    t.right(90)
    t.forward(100)
    t.left(90)
    t.backward(100)

    t.goto(100, 100)
    t.home()

def rectangle():
    t.fd(200)
    t.rt(90)
    t.fd(100)
    t.rt(90)
    t.fd(200)
    t.rt(90)
    t.fd(100)

def pick_pen_up():
    t.penup()
    t.right(90)
    t.forward(100)
    t.left(90)
    t.pendown()
    t.forward(125)

def circles_w_clone():
    t.begin_fill()
    t.circle(90)
    t.end_fill()

    # Our second turtle
    c = t.clone()
    c.circle(50)

def six_circles():
    n = 10
    while n <= 60:
        t.circle(n)
        n = n + 10

x = input("Would you like me to draw you a shape? [y]es or [n]o: ")
if x == "y":
    circles_w_clone()
elif x == "n":
    print("Well, okay then.")
else:
    print("Hm? Invalid reply. Terminating program.")


"""
Number of Palindromic Substrings

We try every possible center for our palindromes, expanding as much as possible. This works because the center part of a palindrome is a palindrome as well:

tacocat
acoca
coc
o
"""
class Solution:
    def solve(self, s):
        def expand(i,j):
            ans=0
            while i>=0 and j<len(s) and s[i] == s[j]:
                i-=1
                j+=1
                ans+=1
            return ans
        return sum(expand(i,i)+expand(i,i+1) for i in range(len(s)))


from geoClients.GeoClient import GeoClient, GeoClientException, Location

class HEREGeoClient(GeoClient):

	def __init__(self, APP_ID, APP_CODE):

		self.APP_ID=APP_ID
		self.APP_CODE=APP_CODE

	def queryAddress(self,address,max_results=10):
		self.max_results=max_results
		url='https://geocoder.cit.api.here.com/6.2/geocode.json?app_id={}&app_code={}&searchtext={}'.format(self.APP_ID,self.APP_CODE,address)
		data=GeoClient.queryService(self,url)

		return self.parseData(data)

	def parseData(self,data):

		if 'Response' not in data:
			raise GeoClientException("Bad Results")
			return None

		if 'View' not in data['Response']:
			raise GeoClientException("Bad Results")
			return None

		if len(data['Response']['View'])==0:
			raise GeoClientException("No Results")
			return None

		results=[]

		results_n=0

		for result in data['Response']['View'][0]['Result']:

			if results_n == self.max_results: break

			label_address=result['Location']['Address']['Label']
			loc=result['Location']['DisplayPosition']

			results.append(Location(label_address,loc['Latitude'],loc['Longitude']))

			results_n+=1

		return results


result=''
n= int(input())
while(n!=0):
    a=n%26
    if a==0:
        a=26
    result = chr(65 + a - 1) + result
    if n!=26:
        n=int(n/26)
    else:
        break

print(result)


# This file is part of the Printrun suite.
#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Printrun.  If not, see <http://www.gnu.org/licenses/>.

from queue import Queue
from collections import deque
import numpy
import wx
import time
from . import gcoder
from .injectgcode import injector, injector_edit
from printrun.gui.viz import BaseViz
from .gui.widgets import get_space

from .utils import imagefile, install_locale, get_home_pos
install_locale('pronterface')

class GvizBaseFrame(wx.Frame):

    def create_base_ui(self):
        self.CreateStatusBar(1)
        self.SetStatusText(_("Layer number and Z position show here when you scroll"))

        panel = wx.Panel(self, -1)
        v_sizer = wx.BoxSizer(wx.VERTICAL)
        h_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.toolbar = wx.ToolBar(panel, -1, style = wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_HORZ_TEXT)
        self.build_toolbar()
        self.toolbar.Realize()
        v_sizer.Add(self.toolbar, 0, wx.EXPAND)
        v_sizer.Add(h_sizer, 1, wx.EXPAND)

        self.layerslider = wx.Slider(panel, style = wx.SL_VERTICAL | wx.SL_AUTOTICKS | wx.SL_LEFT | wx.SL_INVERSE)
        self.layerslider.Bind(wx.EVT_SCROLL, self.process_slider)
        panel.SetSizer(v_sizer)

        return panel, h_sizer

    def build_toolbar(self):
        self.toolbar.SetMargins(get_space('minor'), get_space('mini'))
        self.toolbar.SetToolPacking(get_space('minor'))
        self.toolbar.AddTool(1, '', wx.Image(imagefile('zoom_out.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _("Zoom Out [-]"))
        self.toolbar.AddTool(2, '', wx.Image(imagefile('zoom_in.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _("Zoom In [+]"),)
        self.toolbar.AddTool(3, _("Reset View"), wx.Image(imagefile('fit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
                             shortHelp = _("Reset View"))
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(4, '', wx.Image(imagefile('arrow_down.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _("Move Down a Layer [D]"))
        self.toolbar.AddTool(5, '', wx.Image(imagefile('arrow_up.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _("Move Up a Layer [U]"))
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(6, 'Inject', wx.Image(imagefile('inject.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
                             wx.NullBitmap, shortHelp = _("Inject G-Code"), longHelp = _("Insert code at the beginning of this layer"))
        self.toolbar.AddTool(7, 'Edit', wx.Image(imagefile('edit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
                             wx.NullBitmap, shortHelp = _("Edit Layer"), longHelp = _("Edit the G-Code of this layer"))
        self.toolbar.AddStretchableSpace()
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(9, _('Close'), wx.Image(imagefile('fit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
                             shortHelp = _("Close Window"))

    def setlayercb(self, layer):
        self.layerslider.SetValue(layer)

    def process_slider(self, event):
        raise NotImplementedError

ID_ABOUT = 101
ID_EXIT = 110
class GvizWindow(GvizBaseFrame):
    def __init__(self, f = None, size = (550, 550), build_dimensions = [200, 200, 100, 0, 0, 0], grid = (10, 50), extrusion_width = 0.5, bgcolor = "#000000"):
        super().__init__(None, title = _("G-Code Viewer"), size = size, style = wx.DEFAULT_FRAME_STYLE)

        panel, h_sizer = self.create_base_ui()

        self.p = Gviz(panel, size = size, build_dimensions = build_dimensions, grid = grid, extrusion_width = extrusion_width, bgcolor = bgcolor, realparent = self)
        h_sizer.Add(self.p, 1, wx.EXPAND)
        h_sizer.Add(self.layerslider, 0, wx.EXPAND | wx.ALL, get_space('minor'))
        self.p.SetToolTip("Left-click to move the view, scroll to zoom and shift + scroll to change the layer.")

        self.Layout()
        size = (size[0] + self.layerslider.GetEffectiveMinSize().width,
                size[1] + self.toolbar.GetEffectiveMinSize().height)
        minsize = self.toolbar.GetEffectiveMinSize().width
        self.SetMinClientSize((minsize, minsize))
        self.SetClientSize(size)

        self.Bind(wx.EVT_TOOL, lambda x: self.p.zoom(-1, -1, 1 / 1.2), id = 1)
        self.Bind(wx.EVT_TOOL, lambda x: self.p.zoom(-1, -1, 1.2), id = 2)
        self.Bind(wx.EVT_TOOL, self.reset_view, id = 3)
        self.Bind(wx.EVT_TOOL, lambda x: self.p.layerdown(), id = 4)
        self.Bind(wx.EVT_TOOL, lambda x: self.p.layerup(), id = 5)
        self.Bind(wx.EVT_TOOL, lambda x: self.p.inject(), id = 6)
        self.Bind(wx.EVT_TOOL, lambda x: self.p.editlayer(), id = 7)
        self.Bind(wx.EVT_TOOL, self.reset_selection, id = 8)
        self.Bind(wx.EVT_TOOL, lambda x: self.Close(), id = 9)

        self.initpos = None
        self.p.Bind(wx.EVT_KEY_DOWN, self.key)
        self.Bind(wx.EVT_KEY_DOWN, self.key)
        self.p.Bind(wx.EVT_MOUSEWHEEL, self.zoom)
        self.Bind(wx.EVT_MOUSEWHEEL, self.zoom)
        self.p.Bind(wx.EVT_MOUSE_EVENTS, self.mouse)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.mouse)

        if f:
            gcode = gcoder.GCode(f, get_home_pos(self.p.build_dimensions))
            self.p.addfile(gcode)

        self.CenterOnParent()

    def set_current_gline(self, gline):
        return

    def process_slider(self, event):
        self.p.layerindex = self.layerslider.GetValue()
        z = self.p.get_currentz()
        wx.CallAfter(self.SetStatusText, _("Layer %d: Z = %.03f mm") % (self.p.layerindex + 1, z), 0)
        self.p.dirty = True
        wx.CallAfter(self.p.Refresh)

    def reset_view(self, event):
        self.p.translate = [0.0, 0.0]
        self.p.scale = self.p.basescale
        self.p.zoom(0, 0, 1.0)

    def reset_selection(self, event):
        self.parent.rectangles = []
        wx.CallAfter(self.p.Refresh)

    def mouse(self, event):
        if event.ButtonUp(wx.MOUSE_BTN_LEFT) or event.ButtonUp(wx.MOUSE_BTN_RIGHT):
            if self.initpos is not None:
                self.initpos = None
        elif event.Dragging():
            e = event.GetPosition()
            if self.initpos is None:
                self.initpos = e
                self.basetrans = self.p.translate
            self.p.translate = [self.basetrans[0] + (e[0] - self.initpos[0]),
                                self.basetrans[1] + (e[1] - self.initpos[1])]
            self.p.dirty = True
            wx.CallAfter(self.p.Refresh)
        else:
            event.Skip()

    def key(self, event):
        #  Keycode definitions
        kup = [85, 315]               # Up keys
        kdo = [68, 317]               # Down Keys
        kzi = [388, 316, 61]        # Zoom In Keys
        kzo = [390, 314, 45]       # Zoom Out Keys
        x = event.GetKeyCode()
        cx, cy = self.p.translate
        if x in kup:
            self.p.layerup()
        if x in kdo:
            self.p.layerdown()
        if x in kzi:
            self.p.zoom(cx, cy, 1.2)
        if x in kzo:
            self.p.zoom(cx, cy, 1 / 1.2)

    def zoom(self, event):
        z = event.GetWheelRotation()
        if event.ShiftDown():
            if z > 0:
                self.p.layerdown()
            elif z < 0:
                self.p.layerup()
        else:
            if z > 0:
                self.p.zoom(event.GetX(), event.GetY(), 1.2)
            elif z < 0:
                self.p.zoom(event.GetX(), event.GetY(), 1 / 1.2)

class Gviz(wx.Panel, BaseViz):

    # Mark canvas as dirty when setting showall
    _showall = 0

    def _get_showall(self):
        return self._showall

    def _set_showall(self, showall):
        if showall != self._showall:
            self.dirty = True
            self._showall = showall
    showall = property(_get_showall, _set_showall)

    def __init__(self, parent, size = (200, 200), build_dimensions = [200, 200, 100, 0, 0, 0], grid = (10, 50), extrusion_width = 0.5, bgcolor = "#000000", realparent = None):
        wx.Panel.__init__(self, parent, -1)
        self.widget = self
        size = [max(1.0, x) for x in size]
        ratio = size[0] / size[1]
        self.SetMinSize((150, 150 / ratio))
        self.parent = realparent if realparent else parent
        self.size = size
        self.build_dimensions = build_dimensions
        self.grid = grid
        self.Bind(wx.EVT_PAINT, self.paint)
        self.Bind(wx.EVT_SIZE, self.resize)
        self.hilight = deque()
        self.hilightarcs = deque()
        self.hilightqueue = Queue(0)
        self.hilightarcsqueue = Queue(0)
        self.clear()
        self.filament_width = extrusion_width  # set it to 0 to disable scaling lines with zoom
        self.update_basescale()
        self.scale = self.basescale
        penwidth = max(1, int(self.filament_width * ((self.scale[0] + self.scale[1]) / 2.0)))
        self.translate = [0.0, 0.0]
        self.mainpen = wx.Pen(wx.Colour(0, 0, 0), penwidth)
        self.arcpen = wx.Pen(wx.Colour(255, 0, 0), penwidth)
        self.travelpen = wx.Pen(wx.Colour(10, 80, 80), penwidth)
        self.hlpen = wx.Pen(wx.Colour(200, 50, 50), penwidth)
        self.fades = [wx.Pen(wx.Colour(int(250 - 0.6 ** i * 100), int(250 - 0.6 ** i * 100), int(200 - 0.4 ** i * 50)), penwidth) for i in range(6)]
        self.penslist = [self.mainpen, self.arcpen, self.travelpen, self.hlpen] + self.fades
        self.bgcolor = wx.Colour()
        self.bgcolor.Set(bgcolor)
        self.blitmap = wx.Bitmap(self.GetClientSize()[0], self.GetClientSize()[1], -1)
        self.paint_overlay = None

    def inject(self):
        layer = self.layers[self.layerindex]
        injector(self.gcode, self.layerindex, layer)

    def editlayer(self):
        layer = self.layers[self.layerindex]
        injector_edit(self.gcode, self.layerindex, layer)

    def clearhilights(self):
        self.hilight.clear()
        self.hilightarcs.clear()
        while not self.hilightqueue.empty():
            self.hilightqueue.get_nowait()
        while not self.hilightarcsqueue.empty():
            self.hilightarcsqueue.get_nowait()

    def clear(self):
        self.gcode = None
        self.lastpos = [0, 0, 0, 0, 0, 0, 0]
        self.hilightpos = self.lastpos[:]
        self.lines = {}
        self.pens = {}
        self.arcs = {}
        self.arcpens = {}
        self.layers = {}
        self.layersz = []
        self.clearhilights()
        self.layerindex = 0
        self.showall = 0
        self.dirty = True
        self.partial = False
        self.painted_layers = set()
        wx.CallAfter(self.Refresh)

    def get_currentz(self):
        z = self.layersz[self.layerindex]
        z = 0. if z is None else z
        return z

    def layerup(self):
        if self.layerindex + 1 < len(self.layers):
            self.layerindex += 1
            z = self.get_currentz()
            wx.CallAfter(self.parent.SetStatusText, _("Layer %d: Z = %.03f mm") % (self.layerindex + 1, z), 0)
            self.dirty = True
            self.parent.setlayercb(self.layerindex)
            wx.CallAfter(self.Refresh)

    def layerdown(self):
        if self.layerindex > 0:
            self.layerindex -= 1
            z = self.get_currentz()
            wx.CallAfter(self.parent.SetStatusText, _("Layer %d: Z = %.03f mm") % (self.layerindex + 1, z), 0)
            self.dirty = True
            self.parent.setlayercb(self.layerindex)
            wx.CallAfter(self.Refresh)

    def setlayer(self, layer):
        if layer in self.layers:
            self.clearhilights()
            self.layerindex = self.layers[layer]
            self.dirty = True
            self.showall = 0
            wx.CallAfter(self.Refresh)

    def update_basescale(self):
        self.basescale = 2 * [min(float(self.size[0] - 1) / self.build_dimensions[0],
                                  float(self.size[1] - 1) / self.build_dimensions[1])]

    def resize(self, event):
        old_basescale = self.basescale
        width, height = self.GetClientSize()
        if width < 1 or height < 1:
            return
        self.size = (width, height)
        self.update_basescale()
        zoomratio = float(self.basescale[0]) / old_basescale[0]
        wx.CallLater(200, self.zoom, 0, 0, zoomratio)

    def zoom(self, x, y, factor):
        if x == -1 and y == -1:
            side = min(self.size)
            x = y = side / 2
        self.scale = [s * factor for s in self.scale]

        self.translate = [x - (x - self.translate[0]) * factor,
                          y - (y - self.translate[1]) * factor]
        penwidth = max(1, int(self.filament_width * ((self.scale[0] + self.scale[1]) / 2.0)))
        for pen in self.penslist:
            pen.SetWidth(penwidth)
        self.dirty = True
        wx.CallAfter(self.Refresh)

    def _line_scaler(self, x):
        return (int(self.scale[0] * x[0]),
                int(self.scale[1] * x[1]),
                int(self.scale[0] * x[2]),
                int(self.scale[1] * x[3]),)

    def _arc_scaler(self, x):
        return (self.scale[0] * x[0],
                self.scale[1] * x[1],
                self.scale[0] * x[2],
                self.scale[1] * x[3],
                self.scale[0] * x[4],
                self.scale[1] * x[5],)

    def _drawlines(self, dc, lines, pens):
        scaled_lines = [self._line_scaler(l) for l in lines]
        dc.DrawLineList(scaled_lines, pens)

    def _drawarcs(self, dc, arcs, pens):
        scaled_arcs = [self._arc_scaler(a) for a in arcs]
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        for i, arc in enumerate(scaled_arcs):
            dc.SetPen(pens[i] if isinstance(pens, numpy.ndarray) else pens)
            dc.DrawArc(*arc)

    def repaint_everything(self):
        width = self.scale[0] * self.build_dimensions[0]
        height = self.scale[1] * self.build_dimensions[1]
        self.blitmap = wx.Bitmap(int(width) + 1, int(height) + 1, -1)
        dc = wx.MemoryDC()
        dc.SelectObject(self.blitmap)
        dc.SetBackground(wx.Brush((250, 250, 200)))
        dc.Clear()
        dc.SetPen(wx.Pen(wx.Colour(180, 180, 150)))
        for grid_unit in self.grid:
            if grid_unit > 0:
                for x in range(int(self.build_dimensions[0] / grid_unit) + 1):
                    draw_x = self.scale[0] * x * grid_unit
                    dc.DrawLine(int(draw_x), 0, int(draw_x), int(height))
                for y in range(int(self.build_dimensions[1] / grid_unit) + 1):
                    draw_y = self.scale[1] * (self.build_dimensions[1] - y * grid_unit)
                    dc.DrawLine(0, int(draw_y), int(width), int(draw_y))
            dc.SetPen(wx.Pen(wx.Colour(0, 0, 0)))

        if not self.showall:
            # Draw layer gauge
            dc.SetBrush(wx.Brush((43, 144, 255)))
            dc.DrawRectangle(int(width) - 15, 0, 15, int(height))
            dc.SetBrush(wx.Brush((0, 255, 0)))
            if self.layers:
                dc.DrawRectangle(int(width) - 14, int((1.0 - (1.0 * (self.layerindex + 1)) / len(self.layers)) * height), 13, int(height) - 1)

        if self.showall:
            for i in range(len(self.layersz)):
                self.painted_layers.add(i)
                self._drawlines(dc, self.lines[i], self.pens[i])
                self._drawarcs(dc, self.arcs[i], self.arcpens[i])
            dc.SelectObject(wx.NullBitmap)
            return

        if self.layerindex < len(self.layers) and self.layerindex in self.lines:
            for layer_i in range(max(0, self.layerindex - 6), self.layerindex):
                self._drawlines(dc, self.lines[layer_i], self.fades[self.layerindex - layer_i - 1])
                self._drawarcs(dc, self.arcs[layer_i], self.fades[self.layerindex - layer_i - 1])
            self._drawlines(dc, self.lines[self.layerindex], self.pens[self.layerindex])
            self._drawarcs(dc, self.arcs[self.layerindex], self.arcpens[self.layerindex])

        self._drawlines(dc, self.hilight, self.hlpen)
        self._drawarcs(dc, self.hilightarcs, self.hlpen)

        self.paint_hilights(dc)

        dc.SelectObject(wx.NullBitmap)

    def repaint_partial(self):
        if self.showall:
            dc = wx.MemoryDC()
            dc.SelectObject(self.blitmap)
            for i in set(range(len(self.layersz))).difference(self.painted_layers):
                self.painted_layers.add(i)
                self._drawlines(dc, self.lines[i], self.pens[i])
                self._drawarcs(dc, self.arcs[i], self.arcpens[i])
            dc.SelectObject(wx.NullBitmap)

    def paint_hilights(self, dc = None):
        if self.hilightqueue.empty() and self.hilightarcsqueue.empty():
            return
        hl = []
        if not dc:
            dc = wx.MemoryDC()
            dc.SelectObject(self.blitmap)
        while not self.hilightqueue.empty():
            hl.append(self.hilightqueue.get_nowait())
        self._drawlines(dc, hl, self.hlpen)
        hlarcs = []
        while not self.hilightarcsqueue.empty():
            hlarcs.append(self.hilightarcsqueue.get_nowait())
        self._drawarcs(dc, hlarcs, self.hlpen)
        dc.SelectObject(wx.NullBitmap)

    def paint(self, event):
        if self.dirty:
            self.dirty = False
            self.partial = False
            self.repaint_everything()
        elif self.partial:
            self.partial = False
            self.repaint_partial()
        self.paint_hilights()
        dc = wx.PaintDC(self)
        dc.SetBackground(wx.Brush(self.bgcolor))
        dc.Clear()
        dc.DrawBitmap(self.blitmap, int(self.translate[0]), int(self.translate[1]))
        if self.paint_overlay:
            self.paint_overlay(dc)

    def addfile_perlayer(self, gcode, showall = False):
        self.clear()
        self.gcode = gcode
        self.showall = showall
        generator = self.add_parsed_gcodes(gcode)
        generator_output = next(generator)
        while generator_output is not None:
            yield generator_output
            generator_output = next(generator)
        max_layers = len(self.layers)
        if hasattr(self.parent, "layerslider"):
            self.parent.layerslider.SetRange(0, max_layers - 1)
            self.parent.layerslider.SetValue(0)
        yield None

    def addfile(self, gcode = None, showall = False):
        generator = self.addfile_perlayer(gcode, showall)
        while next(generator) is not None:
            continue

    def _get_movement(self, start_pos, gline):
        """Takes a start position and a gcode, and returns a 3-uple containing
        (final position, line, arc), with line and arc being None if not
        used"""
        target = start_pos[:]
        target[5] = 0.0
        target[6] = 0.0
        if gline.current_x is not None:
            target[0] = gline.current_x
        if gline.current_y is not None:
            target[1] = gline.current_y
        if gline.current_z is not None:
            target[2] = gline.current_z
        if gline.e is not None:
            if gline.relative_e:
                target[3] += gline.e
            else:
                target[3] = gline.e
        if gline.f is not None:
            target[4] = gline.f
        if gline.i is not None:
            target[5] = gline.i
        if gline.j is not None:
            target[6] = gline.j

        if gline.command in ["G2", "G3"]:
            # startpos, endpos, arc center
            arc = [self._x(start_pos[0]), self._y(start_pos[1]),
                   self._x(target[0]), self._y(target[1]),
                   self._x(start_pos[0] + target[5]), self._y(start_pos[1] + target[6])]
            if gline.command == "G2":  # clockwise, reverse endpoints
                arc[0], arc[1], arc[2], arc[3] = arc[2], arc[3], arc[0], arc[1]
            return target, None, arc

        # ["G0", "G1"]:
        line = [self._x(start_pos[0]),
                self._y(start_pos[1]),
                self._x(target[0]),
                self._y(target[1])]
        return target, line, None

    def _y(self, y):
        return self.build_dimensions[1] - (y - self.build_dimensions[4])

    def _x(self, x):
        return x - self.build_dimensions[3]

    def add_parsed_gcodes(self, gcode):
        start_time = time.time()

        layer_idx = 0
        while layer_idx < len(gcode.all_layers):
            layer = gcode.all_layers[layer_idx]
            has_move = False
            for gline in layer:
                if gline.is_move:
                    has_move = True
                    break
            if not has_move:
                yield layer_idx
                layer_idx += 1
                continue
            viz_layer = len(self.layers)
            self.lines[viz_layer] = []
            self.pens[viz_layer] = []
            self.arcs[viz_layer] = []
            self.arcpens[viz_layer] = []
            for gline in layer:
                if not gline.is_move:
                    continue

                target, line, arc = self._get_movement(self.lastpos[:], gline)

                if line is not None:
                    self.lines[viz_layer].append(line)
                    self.pens[viz_layer].append(self.mainpen if target[3] != self.lastpos[3] or gline.extruding else self.travelpen)
                elif arc is not None:
                    self.arcs[viz_layer].append(arc)
                    self.arcpens[viz_layer].append(self.arcpen)

                self.lastpos = target
            # Transform into a numpy array for memory efficiency
            self.lines[viz_layer] = numpy.asarray(self.lines[viz_layer], dtype = numpy.float32)
            self.pens[viz_layer] = numpy.asarray(self.pens[viz_layer])
            self.arcs[viz_layer] = numpy.asarray(self.arcs[viz_layer], dtype = numpy.float32)
            self.arcpens[viz_layer] = numpy.asarray(self.arcpens[viz_layer])
            # Only add layer to self.layers now to prevent the display of an
            # unfinished layer
            self.layers[layer_idx] = viz_layer
            self.layersz.append(layer.z)

            # Refresh display if more than 0.2s have passed
            if time.time() - start_time > 0.2:
                start_time = time.time()
                self.partial = True
                wx.CallAfter(self.Refresh)

            yield layer_idx
            layer_idx += 1

        self.dirty = True
        wx.CallAfter(self.Refresh)
        yield None

    def addgcodehighlight(self, gline):
        if gline.command not in ["G0", "G1", "G2", "G3"]:
            return

        target, line, arc = self._get_movement(self.hilightpos[:], gline)

        if line is not None:
            self.hilight.append(line)
            self.hilightqueue.put_nowait(line)
        elif arc is not None:
            self.hilightarcs.append(arc)
            self.hilightarcsqueue.put_nowait(arc)

        self.hilightpos = target
        wx.CallAfter(self.Refresh)

if __name__ == '__main__':
    import sys
    app = wx.App(False)
    with open(sys.argv[1], "r") as arg:
        main = GvizWindow(arg)
    main.Show()
    app.MainLoop()


from glob import glob
from os.path import join,splitext,basename
from natsort import natsorted
import random
import tifffile
import numpy as np
import matplotlib.pyplot as plt

def read_vaihingen(path_dataset):
  """Read images and labels paths of the
      Vaihingen dataset

  Args:
      path_dataset (string): Path to the folder
      with the Vaihingen dataset

  Returns:
      tuple: two list with the path of the
      images and labels
  """
  path_top = join(path_dataset,"top")
  path_gts = join(path_dataset,"gts")

  # List with all TIF images in each folder
  list_top = glob(join(path_top,"*.tif"))
  list_top = natsorted(list_top, key=lambda y: y.lower())

  list_gts = glob(join(path_gts,"*.tif"))
  list_gts = natsorted(list_gts, key=lambda y: y.lower())

  return list_top, list_gts

def train_val_test_vaihingen(list_top,
                             list_gts,
                             val_size=0.25,
                             seed=42):
  """Function to generate the train, validation and test
  sets of the Vaihingen dataset

  Args:
      list_top (list): list with the paths of the images
      list_gts (list): list with the paths of the labels
      val_size (float, optional): Proportion to be used
        for validation. Defaults to 0.25.
      seed (int, optional): Seed to shuffle train samples
        before split. Defaults to 42.

  Returns:
      splits : dictionary with the paths of the images and
        labels for train, validation, and test
  """
  # Based on the benckmark rules,
  # these are the areas for train and test
  train_ids = [1,3,5,7,11,13,15,17,21,23,26,28,30,32,34,37]
  test_ids = [2,4,6,8,10,12,14,16,20,22,24,27,29,31,33,35,38]

  # Initialization of train, val and test sets
  list_top_train, list_top_val, list_top_test = ([] for i in range(3))
  list_gts_train, list_gts_val, list_gts_test = ([] for i in range(3))

  for top,gts in zip(list_top,list_gts):
    # Get the area ID from the filename
    # Example: ISPRS_semantic_labeling_Vaihingen/top/top_mosaic_09cm_area1.tif
    area_id = int(splitext(basename(top))[0].split("area")[-1])
    # Train set
    if area_id in train_ids:
      list_top_train.append(top)
      list_gts_train.append(gts)
    # Test set
    elif area_id in test_ids:
      list_top_test.append(top)
      list_gts_test.append(gts)

  # shuffle train lists
  temp = list(zip(list_top_train,list_gts_train))
  random.seed(seed)
  random.shuffle(temp)
  list_top_train,list_gts_train = zip(*temp)

  # take val_size as validation set
  n_val = int(val_size*len(list_top_train))

  list_top_val = list_top_train[:n_val]
  list_top_train = list_top_train[n_val:]

  list_gts_val = list_gts_train[:n_val]
  list_gts_train = list_gts_train[n_val:]

  splits = dict()
  splits["top_train"] = list_top_train
  splits["gts_train"] = list_gts_train
  splits["top_val"] = list_top_val
  splits["gts_val"] = list_gts_val
  splits["top_test"] = list_top_test
  splits["gts_test"] = list_gts_test

  return splits

def print_info(list_top, list_gts):
  """Function to print information of the Vaihingen dataset
   about number of classes

  Args:
      list_top (list): list with the paths of the true orthophotos
      list_gts (list): list with the paths of the laels
  """
  for top,gts in zip(list_top,list_gts):
    gt_temp = tifffile.imread(gts)
    n_classes = len(np.unique(gt_temp.reshape(-1,3), axis=0))
    print("TOP:{} , GT:{} , N:{}".format(basename(top),
                                          basename(gts),
                                          n_classes))

def show_batch(img, label, colormap):
  """Function to show the content in a batch

  Args:
      img (np.array): array with image data from
        a batch
      label (np.array): array with label data from
        a batch
      colormap (dict): dictionary with the colormap
        and labels for visualization
  """
  for x_i,y_i in zip(img,label):
    # For visualization: [0,1] => [0,255]
    x_i = x_i*255
    # Apply argmax to convert from one hot to integers
    y_i = np.argmax(y_i, axis=-1)
    # Convert each class to a color given a colormap
    y_i_rgb = np.zeros((y_i.shape[0],
                        y_i.shape[1],
                        3),
                       dtype=np.uint8)
    for key,value in colormap.items():
      y_i_rgb[y_i==value] = key
    # Visualization of RGB image and its ground truth or reference
    plt.figure(figsize=(5,5))
    plt.subplot(1,2,1)
    plt.imshow(x_i.astype("uint8"))
    plt.title("RGB Image")
    plt.axis("off")

    plt.subplot(1,2,2)
    plt.imshow(y_i_rgb, cmap="jet")
    plt.title("Ground Truth")
    plt.axis("off")
    plt.show()

Machine Learning Intermedio/4. Semantic Segmentation/utils.py


#-*- coding: utf-8 -*-
'''
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
'''

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        #这种多的Sum的问题，通常需要降维至2Sum问题来解决。
        nums.sort()
        sum = nums[0]+nums[1]+nums[2]
        l = len(nums)
        if l < 3:
            return -1
        for i in range(l-2):
            tem = self.twoSumClosest(nums[i+1:],target-nums[i])
            if abs(tem+nums[i]-target) < abs(sum-target):
                sum = tem + nums[i]
        return sum

    def twoSumClosest(self,nums,target):
        l,r = 0,len(nums)-1
        sum = nums[0] + nums[-1]
        while l<r:
            tem = nums[l] + nums[r]
            if tem == target:
                return tem
            elif tem > target:
                r -= 1
            else:
                l += 1
            if abs(tem-target) < abs(sum-target):
                sum = tem
        return sum


#Andrew Hull
#Monday, Oct 2
#Discrete state ex.
import gym
from gym import spaces
import numpy as np
import matplotlib.pyplot as plt

class SimpleDroneEnv(gym.Env):
    def __init__(self):
        super(SimpleDroneEnv, self).__init__()

        # Define action space: 4 discrete actions (up, down, left, right)
        self.action_space = spaces.Discrete(4)

        # Define observation space: drone position (x, y), battery level
        self.observation_space = spaces.Box(low=np.array([0, 0, 0]), high=np.array([10, 10, 100]), dtype=np.float32)

        # Initial state
        self.state = np.array([5, 5, 100])  # drone starts at position (5, 5) with full battery

    def step(self, action):
        # Apply action (update drone's position)
        if action == 0:   # up
            self.state[1] += 1
        elif action == 1: # down
            self.state[1] -= 1
        elif action == 2: # left
            self.state[0] -= 1
        elif action == 3: # right
            self.state[0] += 1

        # Decrease battery level
        self.state[2] -= 1

        # Calculate reward (simplified for this example)
        reward = self.state[2]

        # Check if episode is done (battery is empty or drone is out of bounds)
        done = self.state[2] <= 0 or \
               self.state[0] < 0 or self.state[0] > 10 or \
               self.state[1] < 0 or self.state[1] > 10

        return self.state, reward, done, {}

    def reset(self):
        # Reset state to initial condition for new episode
        self.state = np.array([5, 5, 100])
        return self.state

    def render(self, mode='human'):
        plt.clf()  # clear the current figure
        plt.xlim(0, 10)  # set the x-limits of the current axes
        plt.ylim(0, 10)  # set the y-limits of the current axes
        plt.plot(self.state[0], self.state[1], 'bo')  # plot the drone's position as a blue dot
        plt.pause(0.1)  # pause for a short duration before the next render


from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg \
    import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from utils import utils

class Statistics(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        vbox = QVBoxLayout()
        self.setLayout(vbox)
        self.setWindowTitle('Click-Click Training')
        self.setWindowIcon(QIcon('pictures/заставка.png'))

        self.figure = Figure()
        self.figure.subplots_adjust(hspace=0.5)

        self.canvas = FigureCanvas(self.figure)
        hide_button = QPushButton('Скрыть статистику')
        hide_button.clicked.connect(lambda: self.setVisible(False))

        self.setFixedSize(1200, 600)

        data = utils.readFromJson("utils/statistics.json")
        x, y_count_characters, y_count_words, y_print_speed = [], [], [], []
        x_training_dynamics, y_training_dynamics = [], []

        x_training_dynamics.extend([int(i) for i in data['training_dynamics'] if i != "current_date"])
        y_training_dynamics.extend([data['training_dynamics'][i] for i in data['training_dynamics'] if i != "current_date"])

        x.extend([i for i in range(len(data['count_characters_entered']))])
        for count_characters, count_words, print_speed in zip(data['count_characters_entered'],
                                                              data['count_words_entered'],
                                                              data['print_speed']):
            y_count_characters.append(count_characters)
            y_count_words.append(count_words)
            y_print_speed.append(print_speed)

        plt.xticks(range(0, len(x), 1))

        ax1 = self.figure.add_subplot(2, 2, 1, title="Количество попыток")
        ax2 = self.figure.add_subplot(2, 2, 2, title="Количество набранных текстов")
        ax3 = self.figure.add_subplot(2, 2, 3, title="Скорость набора")
        ax4 = self.figure.add_subplot(2, 2, 4, title="Динамика тренировок")

        ax1.plot(x, y_count_characters)
        ax2.plot(x, y_count_words)
        ax3.plot(x, y_print_speed)
        ax4.plot(x_training_dynamics, y_training_dynamics)

        vbox.addWidget(self.canvas)
        vbox.addWidget(hide_button)

        self.canvas.draw()

def initialize_days_in_month(date):
    data = utils.readFromJson("utils/statistics.json")
    if len(data["training_dynamics"]) != 0:
        if data['training_dynamics']['current_date'] == date.toString():
            return
    data['training_dynamics']['current_date'] = date.toString()
    numbers_days = [str(day) for day in range(1, date.daysInMonth() + 1)]
    for number_day in numbers_days:
        data['training_dynamics'][number_day] = 0
    utils.writeToJson("utils/statistics.json", data)


import yaml
from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.drawing.image import Image
from openpyxl.styles import PatternFill
from enum import IntEnum

import combine_data_for_checklist

import excel_styles_and_validation as mas_styles

""" Tool for exporting the MASVS requirements as a checklist including MASTG coverage.

    By Carlos Holguera

    Copyright (c) 2023 OWASP Foundation

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

"""

# TODO parametrize & create a function
# TODO read sheet, col ids and cell styles (centered, left, colored, character if true, etc) from yaml

MASVS_GROUPS = None

MASVS = None
MASTGVERSION = ""
MASTGCOMMIT = ""
MASVSVERSION = ""
MASVSCOMMIT = ""

MAS_WEBSITE_ROOT = "https://mas.owasp.org/"

class Position(IntEnum):
    START = 1
    ID = 2
    PLATFORM = 3
    TEXT = 4
    L1 = 5
    L2 = 6
    R = 7
    PADDING = 8
    STATUS = 9
    EMPTY = 10

WS_BASE_CONFIG = {
    "start_row": 7,
    "columns": [
        {"col": "A", "position": Position.START, "name": "", "width": 10, "style": "gray_header"},
        {"col": "B", "position": Position.ID, "name": "MASVS-ID", "width": 25, "style": "gray_header"},
        {"col": "C", "position": Position.PLATFORM, "name": "Platform", "width": 15, "style": "gray_header"},
        {"col": "D", "position": Position.TEXT, "name": "Description",  "width": 80, "style": "gray_header"},
        {"col": "E", "position": Position.L1, "name": "L1", "width": 5, "style": "gray_header"},
        {"col": "F", "position": Position.L2, "name": "L2", "width": 5, "style": "gray_header"},
        {"col": "G", "position": Position.R, "name": "R", "width": 5, "style": "gray_header"},
        {"col": "H", "position": Position.PADDING, "name": "", "width": 5, "style": "gray_header"},
        {"col": "I", "position": Position.STATUS, "name": "Status", "width": 10, "style": "gray_header"},
        {"col": "J", "position": Position.EMPTY, "name": "", "width": 15, "style": "gray_header"},
    ]
}

def write_header(ws, category_title, background_color="ffffff", font_color="000000"):

    ws.row_dimensions[2].height = 65

    img = Image("Document/Images/logo_circle.png")
    img.height = 165
    img.width = 165
    ws.add_image(img, "B2")

    img = Image("Document/Images/OWASP_logo_white.png")
    img.height = img.height * 0.15
    img.width = img.width * 0.15
    ws.add_image(img, "F2")

    ws["C2"].value = "Mobile Application Security Checklist"
    ws["C2"].style = "big_title"

    ws["C3"].value = category_title
    ws["C3"].style = "medium_title"

    ws["C5"].value = f'OWASP MASTG {MASTGVERSION} (commit: {MASTGCOMMIT})' + "    " + f'OWASP MASVS {MASVSVERSION} (commit: {MASVSCOMMIT})'
    ws["C5"].font = Font(name=mas_styles.FONT, color="ffffff")
    ws["C5"].style = "versions_white"

    # MAS logo
    ws.merge_cells(start_row=2, end_row=4, start_column=2, end_column=2)
    # OWASP logo
    ws.merge_cells(start_row=2, end_row=2, start_column=5, end_column=7)
    # Checklist Title
    ws.merge_cells(start_row=2, end_row=2, start_column=3, end_column=4)
    # Sheet title
    ws.merge_cells(start_row=3, end_row=3, start_column=3, end_column=4)
    # Version Info
    ws.merge_cells(start_row=5, end_row=5, start_column=3, end_column=4)

    # Set background color
    for col in WS_BASE_CONFIG.get("columns"):
        for row in range(1, 7):
            ws.cell(row=row, column=col.get("position")).fill = PatternFill(start_color=background_color, fill_type="solid")

def set_columns_width(ws):
    for col in WS_BASE_CONFIG.get("columns"):
        ws.column_dimensions[col.get("col")].width = col.get("width")

def set_table_headers(row, ws):
    for col in WS_BASE_CONFIG["columns"]:
        ws.cell(row=row, column=col.get("position")).value = col.get("name")
        ws.cell(row=row, column=col.get("position")).style = col.get("style")

def write_title(ws, row, start_column, end_column, title, masvs_font_style="underline"):
    cell = ws.cell(row=row, column=start_column)
    cell.value = title
    cell.style = masvs_font_style
    cell.alignment = mas_styles.align_left

    ws.merge_cells(start_row=row, end_row=row, start_column=start_column, end_column=end_column)

    ws.row_dimensions[row].height = 25  # points

def create_security_requirements_sheet(wb):
    first_sheet = wb.active

    for group_id, elements in MASVS.items():
        ws = wb.create_sheet(group_id)

        ws.title = group_id
        ws.sheet_view.showGridLines = False
        category_title = f"{group_id}: {MASVS_GROUPS[group_id]['title']}"

        write_header(ws, category_title, mas_styles.MASVS_COLORS[group_id])
        set_columns_width(ws)

        status_cells = 'I11:I400'
        ws.conditional_formatting.add(status_cells, mas_styles.rule_fail)
        ws.conditional_formatting.add(status_cells, mas_styles.rule_pass)
        ws.conditional_formatting.add(status_cells, mas_styles.rule_na)

        row = WS_BASE_CONFIG["start_row"]

        row = row + 1

        # category_title = f"{group_id}: {MASVS_GROUPS[group_id]['title']}"
        # write_title(ws, row, Position.ID, Position.STATUS, category_title, masvs_font_style=group_id)
        # row = row + 2

        set_table_headers(row, ws)
        row = row + 1

        ws.add_data_validation(mas_styles.status_validation)
        row = row + 1

        # End header

        for element in elements:
            # MASVS control
            if element.get("MASVS-ID") != "":

                row = row + 1

                ws.cell(row=row, column=Position.ID).value = f'=HYPERLINK("{MAS_WEBSITE_ROOT}{element["path"]}", "{element["MASVS-ID"]}")'
                ws.cell(row=row, column=Position.ID).style = "text_bold"

                ws.cell(row=row, column=Position.TEXT).value = element["Control / MASTG Test"]
                ws.cell(row=row, column=Position.TEXT).style = "text_bold"

                status_cell = ws.cell(row=row, column=Position.STATUS).coordinate
                mas_styles.status_validation.add(status_cell)

                row = row + 2
            # MASTG test
            elif element.get("Platform") != "":

                ws.cell(row=row, column=Position.PLATFORM).value = element["Platform"]
                ws.cell(row=row, column=Position.PLATFORM).style = "gray_text"

                ws.cell(row=row, column=Position.TEXT).value = f'=HYPERLINK("{MAS_WEBSITE_ROOT}{element["path"]}", "{element["Control / MASTG Test"]}")'
                ws.cell(row=row, column=Position.TEXT).style = "text"

                if element["L1"]:
                    ws.cell(row=row, column=Position.L1).style = "blue"
                if element["L2"]:
                    ws.cell(row=row, column=Position.L2).style = "green"
                if element["R"]:
                    ws.cell(row=row, column=Position.R).style = "orange"

                ws.row_dimensions[row].height = 55  # points

                status_cell = ws.cell(row=row, column=Position.STATUS).coordinate
                mas_styles.status_validation.add(status_cell)

                row = row + 1

        row = row + 1
        ws.cell(row=row, column=1).value = ""

    del wb[first_sheet.title]

def create_about_sheet(wb):
    ws = wb.create_sheet("About")
    ws.sheet_view.showGridLines = False
    write_header(ws, "About", background_color=mas_styles.MAS_BLUE)
    set_columns_width(ws)

    row = WS_BASE_CONFIG["start_row"]
    first_col = WS_BASE_CONFIG["columns"][1].get("position")
    last_col = WS_BASE_CONFIG["columns"][-2].get("position")

    row = row + 2

    write_title(ws, row, first_col, last_col, "About the Project")

    row = row + 2

    ws.cell(row=row, column=first_col).value = "The OWASP Mobile Application Security (MAS) flagship project led by Carlos Holguera and Sven Schleier \ndefines the industry standard for mobile application security."
    ws.merge_cells(start_row=row, end_row=row, start_column=first_col, end_column=last_col)
    ws.cell(row=row, column=first_col).style = "text"

    row = row + 2
    url = MAS_WEBSITE_ROOT
    ws.cell(row=row, column=first_col).value = f'=HYPERLINK("{url}", "{url}")'

    row = row + 2

    ws.cell(row=row, column=first_col).value = "The OWASP MASVS (Mobile Application Security Verification Standard) is a standard that establishes the \nsecurity requirements for mobile app security."
    ws.merge_cells(start_row=row, end_row=row, start_column=first_col, end_column=last_col)
    ws.cell(row=row, column=first_col).style = "text"

    row = row + 2
    url = "https://mas.owasp.org/MASVS/"
    ws.cell(row=row, column=first_col).value = f'=HYPERLINK("{url}", "{url}")'

    ws.cell(row=row, column=first_col+2).value = f'=HYPERLINK("https://github.com/OWASP/owasp-masvs/releases/tag/{MASVSVERSION}", "OWASP MASVS {MASVSVERSION} (commit: {MASVSCOMMIT})")'
    ws.cell(row=row, column=first_col+2).style = "text"

    row = row + 2

    ws.cell(row=row, column=first_col).value = "The OWASP MASTG (Mobile Application Security Testing Guide) is a comprehensive manual for mobile app security testing \nand reverse engineering. It describes technical processes for verifying the controls listed in the MASVS."
    ws.merge_cells(start_row=row, end_row=row, start_column=first_col, end_column=last_col)
    ws.cell(row=row, column=first_col).style = "text"

    row = row + 2
    url = "https://mas.owasp.org/MASTG/"
    ws.cell(row=row, column=first_col).value = f'=HYPERLINK("{url}", "{url}")'

    ws.cell(row=row, column=first_col+2).value = f'=HYPERLINK("https://github.com/OWASP/owasp-mastg/releases/tag/{MASTGVERSION}", "OWASP MASTG {MASTGVERSION} (commit: {MASTGCOMMIT})")'
    ws.cell(row=row, column=first_col+2).style = "text"

    row = row + 2

    write_title(ws, row, first_col, last_col, "Feedback")

    row = row + 2

    ws.cell(row=row, column=first_col).value = "If you have any comments or suggestions, please post them on our GitHub Discussions."
    ws.merge_cells(start_row=row, end_row=row, start_column=first_col, end_column=last_col)
    ws.cell(row=row, column=first_col).style = "text"

    row = row + 2
    url = "https://github.com/OWASP/owasp-mastg/discussions/categories/ideas"
    ws.cell(row=row, column=first_col).value = f'=HYPERLINK("{url}", "{url}")'

    row = row + 2

    write_title(ws, row, first_col, last_col, "Licence")

    row = row + 2

    ws.cell(row=row, column=first_col).value = "Copyright © 2023 The OWASP Foundation. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. \nFor any reuse or distribution, you must make clear to others the license terms of this work."
    ws.merge_cells(start_row=row, end_row=row, start_column=first_col, end_column=last_col)
    ws.cell(row=row, column=first_col).style = "text"

    row = row + 2
    url = "https://github.com/OWASP/owasp-mastg/blob/master/License.md"
    ws.cell(row=row, column=first_col).value = f'=HYPERLINK("{url}", "{url}")'

    # padding
    row = row + 1
    ws.cell(row=row, column=first_col).value = ""
    row = row + 1
    ws.cell(row=row, column=first_col).value = ""

def generate_spreadsheet(output_file):

    wb = Workbook()
    mas_styles.load_styles(wb)

    create_security_requirements_sheet(wb)
    create_about_sheet(wb)

    wb.save(filename=output_file)

def main():
    global MASVS, MASVS_GROUPS, MASTGVERSION, MASTGCOMMIT, MASVSVERSION, MASVSCOMMIT
    import argparse

    parser = argparse.ArgumentParser(description="Export the MAS checklist as Excel.")
    parser.add_argument("-o", "--outputfile", required=False, default="OWASP_MAS_Checklist.xlsx")
    parser.add_argument("-v1", "--mastgversion", required=False, default="x.x.x")
    parser.add_argument("-c1", "--mastgcommit", required=False, default="xxxxxx")
    parser.add_argument("-v2", "--masvsversion", required=False, default="y.y.y")
    parser.add_argument("-c2", "--masvscommit", required=False, default="yyyyyy")

    args = parser.parse_args()

    # set global vars
    MASVS = combine_data_for_checklist.get_checklist_dict()
    MASVS_GROUPS = combine_data_for_checklist.get_masvs_groups()
    MASTGVERSION = args.mastgversion
    MASTGCOMMIT = args.mastgcommit
    MASVSVERSION = args.masvsversion
    MASVSCOMMIT = args.masvscommit

    print(f"Generating Checklist for MASTG {MASTGVERSION} ({MASTGCOMMIT}) and MASVS {MASVSVERSION} ({MASVSCOMMIT})")

    generate_spreadsheet(args.outputfile)

if __name__ == "__main__":
    main()


# n, lost, reserve = 5, [2, 4], [1, 3, 5] # 5
# n, lost, reserve = 5, [2, 4], [3] # 4
# n, lost, reserve = 3, [3], [1] # 2
# n, lost, reserve = 10, [4,6], [3,5] # 10
n, lost, reserve = 10, [4,6], [5,3] # 10 # 정렬 안하는 경우 return 9

def solution(n, lost, reserve):
    # 여벌옷이 있는데 도난을 당한 학생은 아예 제외하고 시작합니다.
    # 교집합을 제거하는 방식으로 구현했습니다.
    intersection = list(set(lost) & set(reserve))
    for ele in intersection:
        reserve.remove(ele)
        lost.remove(ele)

    # 각 배열을 정렬해줍니다. (정렬하는 이유는 맨 밑 회고에 있습니다.)
    lost.sort()
    reserve.sort()

    # 학생들의 체육복 유무를 나타내는 변수입니다.
    clothes = [1] * n

    # 도난당한 학생들에 대해 체육복 소지 여부를 0으로 업데이트 합니다.
    for i in lost:
        clothes[i-1] = 0

    # 빌려줄 수 있는 학생들을 순회하면서
    for i in reserve:
        # 앞 학생의 인덱스가 유효하고 체육복이 없다면
        # 앞 학생의 체육복 소지 여부를 1로 바꿔줍니다.
        # 체육복을 빌려줬다면 더이상의 조건은 확인하지 않고
        # 다음 학생으로 넘어갑니다.
        if i-2 >= 0 and clothes[i-2] == 0:
            clothes[i-2] = 1
            continue

        # 뒤 학생의 인덱스가 유효하고 체육복이 없다면
        # 뒤 학생의 체육복 소지 여부를 1로 바꿔줍니다.
        elif i < n and clothes[i] == 0:
            clothes[i] = 1

    # 옷을 가진 (1) 학생 수를 세서 반환합니다.
    return clothes.count(1)

print(solution(n, lost, reserve))

"""
<회고>
- 처음 짠 코드에서는 첫번째 if문에서 부등호 실수를 해서 테스트케이스 11, 13-16을 통과하지 못했다. (부등호 '>' 에서 '>=' 로 바꿈)
배열의 인덱스 자체는 0 <= idx < n 인데 여기서 i-2를 가지고 생각하느라 잠시 헷갈렸던 것 같다.

- 저걸 해결하고 나서는 아무리 해도 테케 18, 20이 해결되지 않았다.
검색 끝에 lost와 reserve 배열을 정렬해줘야 한다는 것을 알았고, 그 이유는 다음과 같다.
이 문제는 '최대한' 많은 학생이 체육수업을 들을 수 있도록 해야하는데 정렬하지 않으면 다음과 같은 문제가 발생한다.

(아래 글 출처: https://ongveloper.tistory.com/90)
만약 4번 학생과 6번 학생이 체육복을 잃어버렸고,
3번 학생과 5번 학생이 여벌의 체육복을 가지고 있다고 하자.
4번 학생이 5번 학생에게 체육복을 빌린다면 6번 학생은 체육복을 입지 못하고,
4번 학생이 3번 학생에게 체육복을 빌린다면 6번 학생은 5번 학생에게 체육복을 빌릴 수 있다.
따라서 lost와 reserve를 정렬하고, 앞에서부터 짝을 지어준다.
"""


import random
listnumber = [] #empty list

for i in range(10):
  listnumber.append(random.randint(1, 10))
print(listnumber)

findNum = int(input('Enter your number: '))
found = 0 #0 is false
for i in range(10):
  if listnumber[i] == findNum:
    found = 1
    print('Found: ', findNum, ' at ', i)
    break
if found == 0:
  print('Cannot find your number')


from mixer.backend.django import mixer
from django.urls import reverse
from rest_framework.test import APITransactionTestCase, APIClient
from rest_framework.views import status
from ..models import JobListing
from ..api.serializers import JobListingSerializer
from apps.company.models import Company
from apps.common.models import (
    LocationStateCode,
    LocationCountryCode
)

class JobListingViewTest(APITransactionTestCase):
    client = APIClient()
    reset_sequences = True

    def setUp(self):
        country = mixer.blend(LocationCountryCode)
        state = mixer.blend(LocationStateCode, country_id=country.id)
        company = mixer.blend(Company, state_id=state.id,
                              country_id=country.id)

        mixer.cycle(2).blend(
            JobListing,
            company=company,
            country=country,
            state=state,
        )

class GetJobListingTests(JobListingViewTest):

    def test_get_job_listing_by_id(self):
        """
        This test asserts that a specific JobListing record added during
        setUp will be retrieved and serialized when making a GET request
        to the job-listings/{id} endpoint.
        """

        response = self.client.get(
            reverse("job-listing", kwargs={'id': 2})
        )

        expected = JobListing.objects.get(id=2)
        serialised = JobListingSerializer(expected)

        self.assertEqual(response.data, serialised.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)