import json
import sys

NUMBER_OF_REQUESTS = 2559

def printLine(str):
	sys.stdout.write(str + '\n')
	sys.stdout.flush()

def appendToFile(objects, file, sep='', end=''):
	enc = file.encoding
	if enc == 'UTF-8':
		print(*objects, sep=sep, end=end, file=file)
	else:
		f = lambda obj: str(obj).encode(enc, errors='backslashreplace').decode(enc)
		print(*map(f, objects), sep=sep, end=end, file=file)

printLine('Splitting responses...\n')

with open('responses/allResponses.txt', 'r') as responsesFile:
    responses = responsesFile.read()

tag = responses[:18];
i = 1
while True:
	title = 'response' + str(i)
	resultsTagPosition1 = responses.find(tag)
	resultsTagPosition2 = responses.find(tag, resultsTagPosition1 + 1)
	if resultsTagPosition2 == -1:
		response = responses[resultsTagPosition1:].rstrip()
		responseFile = open('responses/eachResponse/' + title + '.txt', 'w')
		appendToFile(response, responseFile)
		printLine('File created : ' + title)
		break
	else:
		response = responses[resultsTagPosition1:resultsTagPosition2].rstrip()
		responseFile = open('responses/eachResponse/' + title + '.txt', 'w')
		appendToFile(response, responseFile)
		printLine('File created : ' + title)
		responses = responses[resultsTagPosition2:]
	i += 1

printLine('Done, ' + str(i) + 'files created')


import argparse
import uuid
import hashlib
import itertools
import pathlib
import json
import random
import copy
import requests
import traceback
import xml
import xml.etree.ElementTree as ET
import collections
from folioclient.FolioClient import FolioClient
from faker import Faker
from datetime import datetime, timedelta

class Worker:
    """Class that is responsible for the acutal work"""

    def __init__(self, folio_client, args):
        """Init, setup"""
        self.folio_client = folio_client
        self.faker = Faker()
        self.items = set()
        self.loan_policies = {}
        self.create_requests = args.create_requests
        self.create_page_requests = args.create_page_requests
        print(
            f"Init. Interacting with tenant {args.tenant_id} as {args.username}  at {args.okapi_url}",
            flush=True,
        )
        self.patron_groups = folio_client.get_all_ids("/groups")
        print(f"Fetched {len(self.patron_groups)} patron groups")

        self.item_loan_types = folio_client.get_all_ids("/loan-types")
        print(f"Fetched {len(self.item_loan_types)} item loan types")

        self.item_material_types = folio_client.get_all_ids("/material-types")
        print(f"Fetched {len(self.item_material_types)} item material types")

        self.service_points = folio_client.get_all_ids(
            "/service-points", "?query=(pickupLocation==true)"
        )
        print(f"Fetched {len(self.service_points)} Service points")

        self.locations = folio_client.get_all_ids("/locations")
        print(f"Fetched {len(self.locations)} locations")

        self.item_seeds = list(
            itertools.product(
                self.item_material_types, self.item_loan_types, self.locations
            )
        )
        # Shuffle the list of combinations so that you can run multiple instances at the same time
        random.shuffle(self.item_seeds)
        print(
            f"Created randomized list of {len(self.item_seeds)} possible combinations"
        )
        print("Init done.")

    def work(self):
        print("Starting....")
        # Iterate over every combination
        for seed in self.item_seeds:
            material_type_id = seed[0]
            loan_type_id = seed[1]
            location_id = seed[2]
            i_query = f'?query=(materialTypeId="{material_type_id}" and permanentLoanTypeId="{loan_type_id}" and effectiveLocationId="{location_id}" and status.name=="Available")'
            # iterate over every patron group
            for patron_group_id in self.patron_groups:

                # get random Items from FOLIO based on the combination of parameters
                items = self.folio_client.get_random_objects(
                    "/item-storage/items", 10, query=i_query
                )

                # Get patrons from the current patron group
                p_query = f'query=(patronGroup=="{patron_group_id}" and active==true)'
                patrons = self.folio_client.get_random_objects("/users", 10, p_query)

                # tie a patron to an item
                item_patrons = zip(items, patrons)

                for item_patron in item_patrons:

                    # make sure we have barcodes
                    if "barcode" in item_patron[1] and "barcode" in item_patron[0]:

                        # pick a random service point
                        service_point_id = random.choice(self.service_points)

                        # 5 out of 6 items are checked out if argument -p was given
                        if random.randint(0, 5) > 0 or not self.create_page_requests:
                            # check out the item
                            loan = self.folio_client.check_out_by_barcode(
                                item_patron[0]["barcode"],
                                item_patron[1]["barcode"],
                                datetime.now(),
                                service_point_id,
                            )

                            # "extend" the loan date backwards in time in a randomized matter
                            if loan[0]:
                                extension_date = self.faker.date_time_between(
                                    start_date="-1y", end_date="now"
                                )
                                self.folio_client.extend_open_loan(
                                    loan[1], extension_date
                                )

                        # 1 out of 6 items are paged if argument -p was given
                        else:
                            print("create page request", flush=True)
                            self.folio_client.create_request(
                                "Page",
                                item_patron[1],
                                item_patron[0],
                                service_point_id,
                            )

                        # TODO: speed up this thingy. Fetching users is slow
                        # Create requests for the loan or page. If -r was given
                        if self.create_requests:
                            for b in random.sample(range(30), random.randint(1, 4)):
                                # pick random patron
                                new_patron = next(
                                    iter(
                                        self.folio_client.get_random_objects(
                                            "/users", 1, p_query
                                        )
                                    )
                                )
                                # request the item
                                self.folio_client.create_request(
                                    random.choice(["Hold", "Recall"]),
                                    new_patron,
                                    item_patron[0],
                                    service_point_id,
                                )

def parse_args():
    """Parse CLI Arguments"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "okapi_url",
        help=(
            "url of your FOLIO OKAPI endpoint."
            "See settings->software version in FOLIO"
        ),
    )
    parser.add_argument(
        "tenant_id",
        help=("id of the FOLIO tenant. " "See settings->software version in FOLIO"),
    )
    parser.add_argument("username", help=("the api user"))
    parser.add_argument("password", help=("the api users password"))
    parser.add_argument(
        "-create_requests",
        "-r",
        help=("Add requests to created loan or page"),
        action="store_true",
    )
    parser.add_argument(
        "-create_page_requests",
        "-p",
        help=("Create page requests as well as loans"),
        action="store_true",
    )
    args = parser.parse_args()
    return args

def main():
    """Main Method. Used for bootstrapping. """
    # Parse CLI Arguments
    args = parse_args()

    # Connect to a FOLIO tenant
    folio_client = FolioClient(
        args.okapi_url, args.tenant_id, args.username, args.password
    )

    # Iniiate Worker
    worker = Worker(folio_client, args)

    # Do work
    worker.work()

if __name__ == "__main__":
    """This is the Starting point for the script"""
    main()


from __future__ import division
from collections import defaultdict
from functools import partial

import abc
from tqdm import tqdm
import numpy as np
import sklearn.base
from sklearn.base import BaseEstimator
import torch
from auto_LiRPA import BoundedModule, BoundedTensor, PerturbationLpNorm

from .utils import compute_coverage, default_loss

class RegressionErrFunc(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self):
        super(RegressionErrFunc, self).__init__()

    @abc.abstractmethod
    def apply(self, prediction, y):
        pass

    @abc.abstractmethod
    def apply_inverse(self, nc, significance):
        pass

class AbsErrorErrFunc(RegressionErrFunc):
    def __init__(self):
        super(AbsErrorErrFunc, self).__init__()

    def apply(self, prediction, y):
        err = np.abs(prediction - y)
        if err.ndim > 1:
            err = np.linalg.norm(err, ord=np.inf, axis=1)
        return err

    def apply_inverse(self, nc, significance):
        nc = np.sort(nc)[::-1]
        border = int(np.floor(significance * (nc.size + 1))) - 1
        border = min(max(border, 0), nc.size - 1)
        return np.vstack([nc[border], nc[border]])

class BaseScorer(sklearn.base.BaseEstimator):
    __metaclass__ = abc.ABCMeta

    def __init__(self):
        super(BaseScorer, self).__init__()

    @abc.abstractmethod
    def fit(self, x, y):
        pass

    @abc.abstractmethod
    def score(self, x, y=None):
        pass

    @abc.abstractmethod
    def score_batch(self, dataloader):
        pass

class BaseModelNc(BaseScorer):
    def __init__(self, model, err_func, normalizer=None, beta=1e-6):
        super(BaseModelNc, self).__init__()
        self.err_func = err_func
        self.model = model
        self.normalizer = normalizer
        self.beta = beta

        if (self.normalizer is not None and hasattr(self.normalizer, 'base_model')):
            self.normalizer.base_model = self.model

        self.last_x, self.last_y = None, None
        self.last_prediction = None
        self.clean = False

    def fit(self, x, y):
        self.model.fit(x, y)
        if self.normalizer is not None:
            self.normalizer.fit(x, y)
        self.clean = False

    def score(self, x, y=None):
        n_test = x.shape[0]
        prediction = self.model.predict(x)
        if self.normalizer is not None:
            norm = self.normalizer.score(x) + self.beta
        else:
            norm = np.ones(n_test)

        if prediction.ndim > 1:
            ret_val = self.err_func.apply(prediction, y)
        else:
            ret_val = self.err_func.apply(prediction, y) / norm

        return ret_val

    def score_batch(self, dataloader):
        ret_val = []
        for x, _, y in tqdm(dataloader):
            prediction = self.model.predict(x)
            if self.normalizer is not None:
                norm = self.normalizer.score(x) + self.beta
            else:
                norm = np.ones(len(x))

            if prediction.ndim > 1:
                batch_ret_val = self.err_func.apply(prediction, y.detach().cpu().numpy())
            else:
                batch_ret_val = self.err_func.apply(prediction, y.detach().cpu().numpy()) / norm
            ret_val.append(batch_ret_val)
        ret_val = np.concatenate(ret_val, axis=0)
        return ret_val

class RegressorNc(BaseModelNc):
    def __init__(self, model, err_func=AbsErrorErrFunc(), normalizer=None, beta=1e-6):
        super(RegressorNc, self).__init__(model, err_func, normalizer, beta)

    def predict(self, x, nc, significance=None):
        n_test = x.shape[0]
        prediction = self.model.predict(x)
        if self.normalizer is not None:
            norm = self.normalizer.score(x) + self.beta
        else:
            norm = np.ones(n_test)

        if significance:
            intervals = np.zeros((x.shape[0], self.model.model.out_shape, 2))
            err_dist = self.err_func.apply_inverse(nc, significance)  # (2, y_dim)
            err_dist = np.stack([err_dist] * n_test)  # (B, 2, y_dim)
            if prediction.ndim > 1:  # CQR
                intervals[..., 0] = prediction - err_dist[:, 0]
                intervals[..., 1] = prediction + err_dist[:, 1]
            else:  # regular conformal prediction
                err_dist *= norm[:, None, None]
                intervals[..., 0] = prediction[:, None] - err_dist[:, 0]
                intervals[..., 1] = prediction[:, None] + err_dist[:, 1]

            return intervals
        else:  # Not tested for CQR
            significance = np.arange(0.01, 1.0, 0.01)
            intervals = np.zeros((x.shape[0], 2, significance.size))

            for i, s in enumerate(significance):
                err_dist = self.err_func.apply_inverse(nc, s)
                err_dist = np.hstack([err_dist] * n_test)
                err_dist *= norm

                intervals[:, 0, i] = prediction - err_dist[0, :]
                intervals[:, 1, i] = prediction + err_dist[0, :]

            return intervals

class FeatErrorErrFunc(RegressionErrFunc):
    def __init__(self, feat_norm):
        super(FeatErrorErrFunc, self).__init__()
        self.feat_norm = feat_norm

    def apply(self, prediction, z):
        ret = (prediction - z).norm(p=self.feat_norm, dim=1)
        return ret

    def apply_inverse(self, nc, significance):
        nc = np.sort(nc)[::-1]
        border = int(np.floor(significance * (nc.size + 1))) - 1
        border = min(max(border, 0), nc.size - 1)
        return np.vstack([nc[border], nc[border]])

class FeatRegressorNc(BaseModelNc):
    def __init__(self, model,
                 # err_func=FeatErrorErrFunc(),
                 inv_lr, inv_step, criterion=default_loss, feat_norm=np.inf, certification_method=0, cert_optimizer='sgd',
                 normalizer=None, beta=1e-6, g_out_process=None):
        if feat_norm in ["inf", np.inf, float('inf')]:
            self.feat_norm = np.inf
        elif (type(feat_norm) == int or float):
            self.feat_norm = feat_norm
        else:
            raise NotImplementedError
        err_func = FeatErrorErrFunc(feat_norm=self.feat_norm)

        super(FeatRegressorNc, self).__init__(model, err_func, normalizer, beta)
        self.criterion = criterion
        self.inv_lr = inv_lr
        self.inv_step = inv_step
        self.certification_method = certification_method
        self.cmethod = ['IBP', 'IBP+backward', 'backward', 'CROWN-Optimized'][self.certification_method]
        print(f"Use {self.cmethod} method for certification")

        self.cert_optimizer = cert_optimizer
        # the function to post process the output of g, because FCN needs interpolate and reshape
        self.g_out_process = g_out_process

    def inv_g(self, z0, y, step=None, record_each_step=False):
        z = z0.detach().clone()
        z = z.detach()
        z.requires_grad_()
        if self.cert_optimizer == "sgd":
            optimizer = torch.optim.SGD([z], lr=self.inv_lr)
        elif self.cert_optimizer == "adam":
            optimizer = torch.optim.Adam([z], lr=self.inv_lr)

        self.model.model.eval()
        each_step_z = []
        for _ in range(step):
            pred = self.model.model.g(z)
            if self.g_out_process is not None:
                pred = self.g_out_process(pred)

            loss = self.criterion(pred.squeeze(), y)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if record_each_step:
                each_step_z.append(z.detach().cpu().clone())

        if record_each_step:
            return each_step_z
        else:
            return z.detach().cpu()

    def get_each_step_err_dist(self, x, y, z_pred, steps):
        each_step_z_true = self.inv_g(z_pred, y, step=steps, record_each_step=True)

        if self.normalizer is not None:
            raise NotImplementedError
        else:
            norm = np.ones(len(x))

        err_dist_list = []
        for i, step_z_true in enumerate(each_step_z_true):
            err_dist = self.err_func.apply(z_pred.detach().cpu(), step_z_true.detach().cpu()).numpy() / norm
            err_dist_list.append(err_dist)
        return err_dist_list

    def coverage_loose(self, x, y, z_pred, steps, val_significance):
        z_pred_detach = z_pred.detach().clone()

        idx = torch.randperm(len(z_pred_detach))
        n_val = int(np.floor(len(z_pred_detach) / 5))
        val_idx, cal_idx = idx[:n_val], idx[n_val:]

        cal_x, val_x = x[cal_idx], x[val_idx]
        cal_y, val_y = y[cal_idx], y[val_idx]
        cal_z_pred, val_z_pred = z_pred_detach[cal_idx], z_pred_detach[val_idx]

        cal_score_list = self.get_each_step_err_dist(cal_x, cal_y, cal_z_pred, steps=steps)

        val_coverage_list = []
        for i, step_cal_score in enumerate(cal_score_list):
            val_predictions = self.predict(x=val_x.detach().cpu().numpy(), nc=step_cal_score,
                                           significance=val_significance)
            val_y_lower, val_y_upper = val_predictions[..., 0], val_predictions[..., 1]
            val_coverage, _ = compute_coverage(val_y.detach().cpu().numpy(), val_y_lower, val_y_upper, val_significance,
                                               name="{}-th step's validation".format(i), verbose=False)
            val_coverage_list.append(val_coverage)
        return val_coverage_list, len(val_x)

    def coverage_tight(self, x, y, z_pred,  steps, val_significance):
        z_pred_detach = z_pred.detach().clone()

        idx = torch.randperm(len(z_pred_detach))
        n_val = int(np.floor(len(z_pred_detach) / 5))
        val_idx, cal_idx = idx[:n_val], idx[n_val:]

        cal_x, val_x = x[cal_idx], x[val_idx]
        cal_y, val_y = y[cal_idx], y[val_idx]
        cal_z_pred, val_z_pred = z_pred_detach[cal_idx], z_pred_detach[val_idx]

        cal_score_list = self.get_each_step_err_dist(cal_x, cal_y, cal_z_pred, steps=steps)
        val_score_list = self.get_each_step_err_dist(val_x, val_y, val_z_pred, steps=steps)

        val_coverage_list = []
        for i, (cal_score, val_score) in enumerate(zip(cal_score_list, val_score_list)):
            err_dist_threshold = self.err_func.apply_inverse(nc=cal_score, significance=val_significance)[0][0]
            val_coverage = np.sum(val_score < err_dist_threshold) * 100 / len(val_score)
            val_coverage_list.append(val_coverage)
        return val_coverage_list, len(val_x)

    def find_best_step_num(self, x, y, z_pred):
        max_inv_steps = 200
        val_significance = 0.1

        each_step_val_coverage, val_num = self.coverage_loose(x, y, z_pred, steps=max_inv_steps, val_significance=val_significance)
        # each_step_val_coverage, val_num = self.coverage_tight(x, y, z_pred, steps=max_inv_steps, val_significance=val_significance)

        tolerance = 1
        count = 0
        final_coverage, best_step = None, None
        for i, val_coverage in enumerate(each_step_val_coverage):
            # print("{}-th step's validation coverage is {}".format(i, val_coverage))
            if val_coverage > (1 - val_significance) * 100 and final_coverage is None:
                count += 1
                if count == tolerance:
                    final_coverage = val_coverage
                    best_step = i
            elif val_coverage <= (1 - val_significance) * 100 and count > 0:
                count = 0

        if final_coverage is None or best_step is None:
            raise ValueError(
                "does not find a good step to make the coverage higher than {}".format(1 - val_significance))
        print("The best inv_step is {}, which gets {} coverage on val set".format(best_step + 1, final_coverage))
        return best_step + 1

    def find_best_step_num_batch(self, dataloader):
        max_inv_steps = 200
        val_significance = 0.1

        accumulate_val_coverage = np.zeros(max_inv_steps)
        accumulate_val_num = 0
        print("begin to find the best step number")
        for x, _, y in tqdm(dataloader):
            x, y = x.to(self.model.device), y.to(self.model.device)
            z_pred = self.model.model.encoder(x)
            # batch_each_step_val_coverage, val_num = self.coverage_loose(x, y, z_pred, steps=max_inv_steps, val_significance=val_significance)  # length: max_inv_steps
            batch_each_step_val_coverage, val_num = self.coverage_tight(x, y, z_pred, steps=max_inv_steps, val_significance=val_significance)  # length: max_inv_steps
            accumulate_val_coverage += np.array(batch_each_step_val_coverage) * val_num
            accumulate_val_num += val_num

        each_step_val_coverage = accumulate_val_coverage / accumulate_val_num

        tolerance = 3
        count = 0
        final_coverage, best_step = None, None
        for i, val_coverage in enumerate(each_step_val_coverage):
            # print("{}-th step's validation tight coverage is {}".format(i, val_coverage))
            if val_coverage > (1 - val_significance) * 100 and final_coverage is None:
                count += 1
                if count == tolerance:
                    final_coverage = val_coverage
                    best_step = i
            elif val_coverage <= (1 - val_significance) * 100 and count > 0:
                count = 0

        if final_coverage is None or best_step is None:
            raise ValueError(
                "does not find a good step to make the coverage higher than {}".format(1 - val_significance))
        print("The best inv_step is {}, which gets {} coverage on val set".format(best_step + 1, final_coverage))
        return best_step + 1

    def score(self, x, y=None):  # overwrite BaseModelNc.score()
        self.model.model.eval()
        n_test = x.shape[0]
        x, y = torch.from_numpy(x).to(self.model.device), torch.from_numpy(y).to(self.model.device)
        z_pred = self.model.model.encoder(x)

        if self.inv_step is None:
            self.inv_step = self.find_best_step_num(x, y, z_pred)

        z_true = self.inv_g(z_pred, y, step=self.inv_step)

        if self.normalizer is not None:
            raise NotImplementedError
        else:
            norm = np.ones(n_test)

        ret_val = self.err_func.apply(z_pred.detach().cpu(), z_true.detach().cpu())  # || z_pred - z_true ||
        ret_val = ret_val.numpy() / norm
        return ret_val

    def score_batch(self, dataloader):
        self.model.model.eval()
        if self.inv_step is None:
            self.inv_step = self.find_best_step_num_batch(dataloader)

        print('calculating score:')
        ret_val = []
        for x, _, y in tqdm(dataloader):
            x, y = x.to(self.model.device), y.to(self.model.device)

            if self.normalizer is not None:
                raise NotImplementedError
            else:
                norm = np.ones(len(x))

            z_pred = self.model.model.encoder(x)
            z_true = self.inv_g(z_pred, y, step=self.inv_step)
            batch_ret_val = self.err_func.apply(z_pred.detach().cpu(), z_true.detach().cpu())
            batch_ret_val = batch_ret_val.detach().cpu().numpy() / norm
            ret_val.append(batch_ret_val)
        ret_val = np.concatenate(ret_val, axis=0)
        return ret_val

    def predict(self, x, nc, significance=None):
        n_test = x.shape[0]
        prediction = self.model.predict(x)

        if self.normalizer is not None:
            norm = self.normalizer.score(x) + self.beta
        else:
            norm = np.ones(n_test)

        if significance:
            intervals = np.zeros((x.shape[0], self.model.model.out_shape, 2))
            feat_err_dist = self.err_func.apply_inverse(nc, significance)

            if prediction.ndim > 1:
                if isinstance(x, torch.Tensor):
                    x = x.to(self.model.device)
                else:
                    x = torch.from_numpy(x).to(self.model.device)
                z = self.model.model.encoder(x).detach()

                lirpa_model = BoundedModule(self.model.model.g, torch.empty_like(z))
                ptb = PerturbationLpNorm(norm=self.feat_norm, eps=feat_err_dist[0][0])
                my_input = BoundedTensor(z, ptb)

                if 'Optimized' in self.cmethod:
                    lirpa_model.set_bound_opts(
                        {'optimize_bound_args': {'ob_iteration': 20, 'ob_lr': 0.1, 'ob_verbose': 0}})
                lb, ub = lirpa_model.compute_bounds(x=(my_input,), method=self.cmethod)
                if self.g_out_process is not None:
                    lb = self.g_out_process(lb)
                    ub = self.g_out_process(ub)
                lb, ub = lb.detach().cpu().numpy(), ub.detach().cpu().numpy()

                intervals[..., 0] = lb
                intervals[..., 1] = ub
            else:
                if not isinstance(x, torch.Tensor):
                    x = torch.from_numpy(x).to(self.model.device)
                z = self.model.model.encoder(x).detach()

                lirpa_model = BoundedModule(self.model.model.g, torch.empty_like(z))
                ptb = PerturbationLpNorm(norm=self.feat_norm, eps=feat_err_dist[0][0])  # feat_err_dist=[[0.122, 0.122]]
                my_input = BoundedTensor(z, ptb)

                if 'Optimized' in self.cmethod:
                    lirpa_model.set_bound_opts({'optimize_bound_args': {'ob_iteration': 20, 'ob_lr': 0.1, 'ob_verbose': 0}})
                lb, ub = lirpa_model.compute_bounds(x=(my_input,), method=self.cmethod)  # (bs, 1), (bs, 1)
                if self.g_out_process is not None:
                    lb = self.g_out_process(lb)
                    ub = self.g_out_process(ub)
                lb, ub = lb.detach().cpu().numpy(), ub.detach().cpu().numpy()

                intervals[..., 0] = lb
                intervals[..., 1] = ub

            return intervals

        else:
            raise NotImplementedError

class BaseIcp(BaseEstimator):
    def __init__(self, nc_function, condition=None):
        self.cal_x, self.cal_y = None, None
        self.nc_function = nc_function

        default_condition = lambda x: 0
        is_default = (callable(condition) and
                      (condition.__code__.co_code ==
                       default_condition.__code__.co_code))

        if is_default:
            self.condition = condition
            self.conditional = False
        elif callable(condition):
            self.condition = condition
            self.conditional = True
        else:
            self.condition = lambda x: 0
            self.conditional = False

    @classmethod
    def get_problem_type(cls):
        return 'regression'

    def fit(self, x, y):
        self.nc_function.fit(x, y)

    def calibrate(self, x, y, increment=False):
        self._calibrate_hook(x, y, increment)
        self._update_calibration_set(x, y, increment)

        if self.conditional:
            category_map = np.array([self.condition((x[i, :], y[i])) for i in range(y.size)])
            self.categories = np.unique(category_map)
            self.cal_scores = defaultdict(partial(np.ndarray, 0))

            for cond in self.categories:
                idx = category_map == cond
                cal_scores = self.nc_function.score(self.cal_x[idx, :], self.cal_y[idx])
                self.cal_scores[cond] = np.sort(cal_scores, 0)[::-1]
        else:
            self.categories = np.array([0])
            cal_scores = self.nc_function.score(self.cal_x, self.cal_y)
            self.cal_scores = {0: np.sort(cal_scores, 0)[::-1]}

    def calibrate_batch(self, dataloader):
        if self.conditional:
            raise NotImplementedError

        else:
            self.categories = np.array([0])
            cal_scores = self.nc_function.score_batch(dataloader)
            self.cal_scores = {0: np.sort(cal_scores, 0)[::-1]}

    def _calibrate_hook(self, x, y, increment):
        pass

    def _update_calibration_set(self, x, y, increment):
        if increment and self.cal_x is not None and self.cal_y is not None:
            self.cal_x = np.vstack([self.cal_x, x])
            self.cal_y = np.hstack([self.cal_y, y])
        else:
            self.cal_x, self.cal_y = x, y

class IcpRegressor(BaseIcp):
    def __init__(self, nc_function, condition=None):
        super(IcpRegressor, self).__init__(nc_function, condition)

    def predict(self, x, significance=None):
        self.nc_function.model.model.eval()

        n_significance = (99 if significance is None
                          else np.array(significance).size)

        if n_significance > 1:
            prediction = np.zeros((x.shape[0], self.nc_function.model.model.out_shape, 2, n_significance))
        else:
            prediction = np.zeros((x.shape[0], self.nc_function.model.model.out_shape, 2))

        condition_map = np.array([self.condition((x[i, :], None))
                                  for i in range(x.shape[0])])

        for condition in self.categories:
            idx = condition_map == condition
            if np.sum(idx) > 0:
                p = self.nc_function.predict(x[idx, :], self.cal_scores[condition], significance)
                if n_significance > 1:
                    prediction[idx, :, :] = p
                else:
                    prediction[idx, :] = p

        return prediction

    def if_in_coverage(self, x, y, significance):
        self.nc_function.model.model.eval()
        condition_map = np.array([self.condition((x[i, :], None))
                                  for i in range(x.shape[0])])
        result_array = np.zeros(len(x)).astype(bool)
        for condition in self.categories:
            idx = condition_map == condition
            if np.sum(idx) > 0:
                err_dist = self.nc_function.score(x[idx, :], y[idx])
                err_dist_threshold = self.nc_function.err_func.apply_inverse(self.cal_scores[condition], significance)[0][0]
                result_array[idx] = (err_dist < err_dist_threshold)
        return result_array

    def if_in_coverage_batch(self, dataloader, significance):
        self.nc_function.model.model.eval()
        err_dist = self.nc_function.score_batch(dataloader)
        err_dist_threshold = self.nc_function.err_func.apply_inverse(self.cal_scores[0], significance)[0][0]
        result_array = (err_dist < err_dist_threshold)
        return result_array

def calc_p(ncal, ngt, neq, smoothing=False):
    if smoothing:
        return (ngt + (neq + 1) * np.random.uniform(0, 1)) / (ncal + 1)
    else:
        return (ngt + neq + 1) / (ncal + 1)


# Choose your own path
N = int(input())
tree = {} # this is a dictionary, key is the node, values are the children
for i in range(N):
  vals = input().split()
  # the first value is Mi, the number of the children
  # others are the children
  if int(vals[0]) > 0:  # make sure this is greater than 0
    tree[i+1] = [int(val) for index, val in enumerate(vals) if index > 0]

# we need 2 answer, 1 is whether all pages are included, 2 is short level
minLevel = 20000  # we will put min level in this minLevel
# using BFS (guarantee to get the shortest path)
queue = [(1, 1)]  # we use tuple as element of the queue
# first one is the page number, second one is the level
visited = {1} # visited is a set, containing all visited pages
while queue:
  page, level = queue.pop(0)  # BFS, always pops the top one
  if page not in tree:  # end
    if level < minLevel:  # compare your level with minLevel
      minLevel = level
  else:
    for nextPage in tree[page]:
      if nextPage not in visited:
        queue.append((nextPage, level+1))
        visited.add(nextPage)

if len(visited) < N:
  print("N")
else:
  print("Y")
print(minLevel)


from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.aggregates import Max
from django.middleware.csrf import _sanitize_token
from django.utils.crypto import constant_time_compare
from django.utils.http import same_origin
from tastypie import fields
from tastypie.authentication import BasicAuthentication, Authentication
from tastypie.authorization import DjangoAuthorization
from tastypie.authorization import Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.resources import ModelResource

from models import QandaUser, Question, Answer, Reply

class SessionAuthentication(Authentication):
	"""
	An authentication mechanism that piggy-backs on Django sessions.

	This is useful when the API is talking to Javascript on the same site.
	Relies on the user being logged in through the standard Django login
	setup.

	Requires a valid CSRF token.
	"""
	def is_authenticated(self, request, **kwargs):
		"""
		Checks to make sure the user is logged in & has a Django session.
		"""
		# Cargo-culted from Django 1.3/1.4's ``django/middleware/csrf.py``.
		# We can't just use what's there, since the return values will be
		# wrong.
		# We also can't risk accessing ``request.POST``, which will break with
		# the serialized bodies.
		if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
			return request.user.is_authenticated()

		if getattr(request, '_dont_enforce_csrf_checks', False):
			return request.user.is_authenticated()

		csrf_token = _sanitize_token(request.COOKIES.get(settings.CSRF_COOKIE_NAME, ''))

		if request.is_secure():
			referer = request.META.get('HTTP_REFERER')

			if referer is None:
				return False

			good_referer = 'https://%s/' % request.get_host()

			if not same_origin(referer, good_referer):
				return False

		request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')

		if not constant_time_compare(request_csrf_token, csrf_token):
			return False

		return request.user.is_authenticated()

	def get_identifier(self, request):
		"""
		Provides a unique string identifier for the requestor.

		This implementation returns the user's username.
		"""
		return request.user.username

class UserAuthorization(DjangoAuthorization):
	def is_authorized(self, request, object=None):
		return super(UserAuthorization, self).is_authorized(request,object)

	def apply_limits(self,request,object_list):
		return object_list

class UserResource(ModelResource):
	class Meta:
		queryset = User.objects.all()
		resource_name = 'user'
		authentication=SessionAuthentication()
		authorization = UserAuthorization()
		fields = ['username']
		list_allowed_methods = ['get']
		detail_allowed_methods = ['get','put','patch']
		filtering = {
			'username': ALL ,
		}

	def determine_format(self, request):
		return "application/json"

	def dehydrate(self, bundle):
		userInstance=bundle.obj

		#if self.get_resource_uri(bundle) == bundle.request.path:
			#"Detail"
		if bundle.request.user.pk == bundle.obj.pk:
			bundle.data['first-name']=userInstance.first_name
			bundle.data['last-name']=userInstance.last_name
			bundle.data['email']=userInstance.email
		return bundle

	def apply_authorization_limits(self, request, object_list):
		if request.method in ["PUT","PATCH"]:
			return object_list.filter(pk=request.user.pk)
		else:
			return object_list

class QandaUserResource(ModelResource):
	djangoUser = fields.ForeignKey(UserResource, 'djangoUser')
	class Meta:
		queryset = QandaUser.objects.all()
		resource_name = 'qandauser'
		list_allowed_methods = ['get']
		detail_allowed_methods = ['get','put','patch']
		authentication = SessionAuthentication()
		authorization = UserAuthorization()
		always_return_data=True
		filtering = {
			'djangoUser': ALL_WITH_RELATIONS ,
		}
	def determine_format(self, request):
		return "application/json"

class QuestionResource(ModelResource):
	author = fields.ForeignKey(QandaUserResource, 'author')
	class Meta:
		queryset = Question.objects.all()
		resource_name = 'question'
		list_allowed_methods = ['get']
		detail_allowed_methods = ['get','put','patch']
		authentication = SessionAuthentication()
		authorization = UserAuthorization()
		always_return_data=True
		filtering = {
			'djangoUser': ALL_WITH_RELATIONS ,
		}
	def determine_format(self, request):
		return "application/json"

class AnswerResource(ModelResource):
	author = fields.ForeignKey(QandaUserResource, 'author')
	question = fields.ForeignKey(QuestionResource, 'question')
	class Meta:
		queryset = Answer.objects.all()
		resource_name = 'answer'
		list_allowed_methods = ['get']
		detail_allowed_methods = ['get','put','patch']
		authentication = SessionAuthentication()
		authorization = UserAuthorization()
		always_return_data=True
		filtering = {
			'djangoUser': ALL_WITH_RELATIONS ,
		}
	def determine_format(self, request):
		return "application/json"

class ReplyResource(ModelResource):
	author = fields.ForeignKey(QandaUserResource, 'author')
	answer = fields.ForeignKey(AnswerResource, 'answer')
	class Meta:
		queryset = Reply.objects.all()
		resource_name = 'reply'
		list_allowed_methods = ['get']
		detail_allowed_methods = ['get','put','patch']
		authentication = SessionAuthentication()
		authorization = UserAuthorization()
		always_return_data=True
		filtering = {
			'djangoUser': ALL_WITH_RELATIONS ,
		}
	def determine_format(self, request):
		return "application/json"


class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

class Queue:
    def __init__(self):
        self.front = self.back = Node()

    def isEmpty(self):
        return self.front == self.back

    def EnQueue(self, val):
        emptyNode = Node()
        self.back.data = val
        self.back.next = emptyNode
        if self.front.data == None:
            self.front = self.back
        self.back = emptyNode

    def DeQueue(self):
        if self.isEmpty():
            return False
        frontVal = self.front.data
        self.front = self.front.next
        return frontVal

    def traverse(self, startNode, endNode):
        while startNode != None:
            print(startNode.data)
            if startNode == endNode:
                return "Traverse Completed"
            startNode = startNode.next
        return "Traverse Completed"

    def __str__(self):
        return self.traverse(self.front, self.back)

queue = Queue()
queue.EnQueue(12)
queue.EnQueue(15)
queue.EnQueue(34)
queue.DeQueue()
print(queue)

linked lists/queues with linked lists.py


import re

def transfer_underline(name):
    """驼峰转下划线"""
    pattern = re.compile(r'([A-Z]{1})')
    res = re.sub(pattern, '_' + r'\1', name).lower()
    while res.startswith('_'):
        res = res[1:]
    while res.endswith('_'):
        res = res[-1:]
    return res

def transfer_hump(name, ignore_first=True):
    """下划线转驼峰"""
    res = []
    for index, n in enumerate(name.split('_')):
        if ignore_first and index == 0:
            res.append(n)
        else:
            res.append(f'{n[0].upper()}{n[1:]:}')
    return ''.join(res)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 16:38:37 2017

@author: nuria
"""

import pandas as pd
import sklearn.cluster as cl

from sklearn import preprocessing
from sklearn.neighbors import kneighbors_graph

import general as general

#CASO DE ESTUDIO 1: Queremos controlar el riesgo de la Barcelona a la hora de salida del colegio
#o dela salida del trabajo del turno de mañanas (1-4) en Barcelona

#Definición del subcaso
def define_subset():
    accidentes = pd.read_csv('accidentes_2013.csv')

    #Seleccionamos aquellos accidentes que hayan tenido lugar en la provincia de Barcelona
    subset = accidentes.loc[accidentes['PROVINCIA'].str.contains("Barcelona")]
    #Seleccionamos aquellos accidentes que hayan tenido lugar en la franjahoraria [13-16]
    subset = subset.loc[(subset['HORA'] >= 13) & (subset['HORA'] <= 16)]

    #subset = accidentes[accidentes['TIPO_ACCIDENTE'].str.contains("Colisión de vehículos")]
    #subset = subset.sample(1000, random_state=123456)

    #Seleccionamos aquellos atributos que queramos estudiar.
    usadas = ['TOT_MUERTOS', 'TOT_HERIDOS_GRAVES', 'TOT_HERIDOS_LEVES', 'TOT_VEHICULOS_IMPLICADOS']
    X = subset[usadas]

    return X

#Definimos los algoritmos a utilizar
def definition_clusters(subset):
    #Importante -> normalizar el conjunto de datos que utilizamos
    normalized_set = preprocessing.normalize(subset, norm='l2')

    print("-------- Definiendo los clusteres...")

    k_means = cl.KMeans(init='k-means++', n_clusters=5, n_init=100)

    two_means = cl.MiniBatchKMeans(n_clusters=5,  init='k-means++')

    # estimate bandwidth for mean shift
    bandwidth = cl.estimate_bandwidth(normalized_set, quantile=0.3)
    ms = cl.MeanShift(bandwidth=bandwidth)

    # connectivity matrix for structured Ward
    #connectivity = kneighbors_graph(normalized_set, n_neighbors=10, include_self=False)
    # make connectivity symmetric
    #connectivity = 0.5 * (connectivity + connectivity.T)
    ward = cl.AgglomerativeClustering(n_clusters=100, linkage='ward')

    average = cl.AgglomerativeClustering(n_clusters=100, linkage='average')

    #Utilizarlo para casos de estudio pequeños
    #n_jobs = -1 para q vaya en paralelo
    #spectral = cl.SpectralClustering(n_clusters=3, affinity="nearest_neighbors",n_jobs=-1, n_neighbors = 3)

    #dbscan = cl.DBSCAN(eps=0.3)

    #Los añadimos a una lista
    clustering_algorithms = (
        ('K-Means', k_means),
        ('MeanShift', ms),
        ('MiniBatchMeans',two_means),
        ('AgglomerativeWard', ward),
        ('AgglomerativeAverage', average)
    )

    return clustering_algorithms

#Definimos el subset
subset1 = define_subset()
print("Tamaño del caso de estudio:" + str(len(subset1)))

#Definimos los algoritmos que vamos a utilizar
algorithms1 = definition_clusters(subset1)
predictions1 = general.get_predictions(algorithms1, subset1)

#Calculamos medidas de error
medidas1 = general.calculoMedidas(subset1, predictions1)

#Calculamos numero de clústeres para aquellos métodos a los que no se le especifique
n_clusters_meanshift = general.numero_clusters(predictions1[1])
print("El número de clústeres para MeanShift es {:.0f} ".format(n_clusters_meanshift))

########################## CONFIGURACIÓN DE PARAMETROS ##############################

############ kmeans

def configuraciones_kmeans():
    #normalized_set = preprocessing.normalize(subset, norm='l2')

    k_means_10 = cl.KMeans(init='k-means++', n_clusters=10, n_init=100)
    k_means_20 = cl.KMeans(init='k-means++', n_clusters=20, n_init=100)
    k_means_30 = cl.KMeans(init='k-means++', n_clusters=30, n_init=100)
    k_means_40 = cl.KMeans(init='k-means++', n_clusters=40, n_init=100)
    k_means_50 = cl.KMeans(init='k-means++', n_clusters=50, n_init=100)

    #Los añadimos a una lista
    clustering_algorithms = (
        ('K-Means-10', k_means_10),
        ('K-Means-20', k_means_20),
        ('K-Means-30', k_means_30),
        ('K-Means-40', k_means_40),
        ('K-Means-50', k_means_50)

    )

    return clustering_algorithms

config_kmeans = configuraciones_kmeans()
predictions_kmeans = general.get_predictions(config_kmeans, subset1)
medidas_kmeans = general.calculoMedidas(subset1, predictions_kmeans)

############ jerarquico

#Preprocesado -> eliminación de outliers

def delete_outliers(prediction, subset):
    X = subset
    k = general.numero_clusters(prediction)
    #se convierte la asignación de clusters a DataFrame
    clusters = pd.DataFrame(prediction[1],index=X.index,columns=['cluster'])
    #y se añade como columna a X
    X_cluster = pd.concat([X, clusters], axis=1)

    #Filtro quitando los elementos (outliers) que caen en clusters muy pequeños en el jerárquico
    min_size = 2
    X_filtrado = X_cluster[X_cluster.groupby('cluster').cluster.transform(len) > min_size]
    k_filtrado = len(set(X_filtrado['cluster']))
    print('''De los {:.0f} clusters hay {:.0f} con más de {:.0f} elementos.
          Del total de {:.0f} elementos, se seleccionan {:.0f}'''.format(k,k_filtrado,min_size,len(X),len(X_filtrado)))
    X_filtrado = X_filtrado.drop('cluster', 1)

    #X_filtrado_normal = preprocessing.normalize(X_filtrado, norm='l2')

    return X_filtrado

new_subset = delete_outliers(predictions1[3], subset1)

#Ejecutamos estos nuevos algoritmos.
pred_new_subset = general.get_predictions(algorithms1[3:5], new_subset)
medidas_new_subset = general.calculoMedidas(new_subset, pred_new_subset)

#Definimos algoritmo jerárquico con 100 clústeres:
ward_1000 = cl.AgglomerativeClustering(n_clusters=35, linkage='ward')

ward_1000_alg = (
        ('Ward-1000', ward_1000)
    )

pred_ward_1000 =  ('Ward-1000', ward_1000.fit_predict(new_subset))

new_subset_2 = delete_outliers(pred_ward_1000, pd.core.frame.DataFrame(new_subset))

#Ejecutamos estos nuevos algoritmos.

def configuraciones_jerarquicos():
    ward_5 = cl.AgglomerativeClustering(n_clusters=5, linkage='ward')
    average_5 = cl.AgglomerativeClustering(n_clusters=5, linkage='average')

    ward_10 = cl.AgglomerativeClustering(n_clusters=10, linkage='ward')
    average_10 = cl.AgglomerativeClustering(n_clusters=10, linkage='average')

    ward_15 = cl.AgglomerativeClustering(n_clusters=15, linkage='ward')
    average_15 = cl.AgglomerativeClustering(n_clusters=15, linkage='average')

    ward_20 = cl.AgglomerativeClustering(n_clusters=20, linkage='ward')
    average_20 = cl.AgglomerativeClustering(n_clusters=20, linkage='average')

    ward_25 = cl.AgglomerativeClustering(n_clusters=25, linkage='ward')
    average_25 = cl.AgglomerativeClustering(n_clusters=25, linkage='average')

    ward_30 = cl.AgglomerativeClustering(n_clusters=30, linkage='ward')
    average_30 = cl.AgglomerativeClustering(n_clusters=30, linkage='average')

    #Los añadimos a una lista
    clustering_algorithms = (
        ('Ward-5', ward_5),
        ('Average-5', average_5),
        ('Ward-10', ward_10),
        ('Average-10', average_10),
        ('Ward-15', ward_15),
        ('Average-15', average_15),
        ('Ward-20', ward_20),
        ('Average-20', average_20),
        ('Ward-25', ward_25),
        ('Average-25', average_25),
        ('Ward-30', ward_30),
        ('Average-30', average_30)

    )

    return clustering_algorithms

new_algoritmos = configuraciones_jerarquicos()

pred_new_subset_2 = general.get_predictions(new_algoritmos, new_subset_2)
medidas_new_subset_2 = general.calculoMedidas(new_subset_2, pred_new_subset_2)

##################################### scatter-matrix
general.scatter_matrix(predictions1[0], subset1)

subset_dataframe = pd.core.frame.DataFrame(new_subset_2, columns=['TOT_MUERTOS', 'TOT_HERIDOS_GRAVES', 'TOT_HERIDOS_LEVES', 'TOT_VEHICULOS_IMPLICADOS'])
general.scatter_matrix(pred_new_subset_2[0], subset_dataframe)

################################# dendograma
dendograma = new_subset_2.sample(500, random_state=123456)
dendograma_subset = preprocessing.normalize(dendograma, norm='l2')
dendograma_subsetDF = pd.DataFrame(dendograma_subset,index=dendograma.index,columns=['TOT_MUERTOS', 'TOT_HERIDOS_GRAVES', 'TOT_HERIDOS_LEVES', 'TOT_VEHICULOS_IMPLICADOS'])
sns.clustermap(dendograma_subsetDF, method='ward', col_cluster=False, figsize=(20,10), cmap="YlGnBu", yticklabels=False)


class pieza():
    def __init__ (self):

        self.NPieza : int #Numero de pieza
        self.Capacidad : int #Capacidad de la pieza
        self.Valorxdia : int #Valor de la pieza x dia
        self.Estado : str #Estado de la pieza 'S' o 'N'

class reserva ():
    def __init__(self):
        self.npieza : int #Numero Pieza
        self.npasajero : str #Nombre pasajero
        self.fingreso : float #Fecha de ingreso
        self.consumo : float #Consumo de cosas extras

arreglohotel = [pieza() for i in range(20)]
with open('Pieza.txt','rt') as f:
    infopiezas = f.readlines()
    f.close

for i in range (len(arreglohotel)):
    piezaaux = infopiezas.split(';')
    arreglohotel[i].NPieza = piezaaux[0]
    arreglohotel[i].Capacidad = piezaaux[1]
    arreglohotel[i].Valorxdia = piezaaux[2]
    arreglohotel[i].Estado = piezaaux[3]


from classes.strategy import Strategy

def binary_search(array, target, strategy=Strategy.Iteration, validate_sorted=False):
  '''
  The prototypical binary search algorithm implemented at a high level with the ability
  to toggle between iterative or recursive strategy

  Time and Space Complexity by Strategy:
   * Iterative: O(log(n)) time | O(1) space
   * Recursive: O(log(n)) time | O(log(n)) space
  '''
  if validate_sorted:
    if not _array_is_sorted(array):
      raise Exception('Input <array> is not in sorted order')

  # Small shortcut if the target is completely out of the array's range, or the
  # array itself is completely empty. NOTE: We return -1 if the array is empty
  # to match Python's built-in `in` operator behavior where `1 in []` returns
  # the not found value, but doesn't raise an exception
  if not len(array) or target < array[0] or array[-1] < target:
    return -1

  if strategy == Strategy.Iteration:
    return _binary_search_iterative(array, target)
  elif strategy == Strategy.Recursion:
    return _binary_search_recursive(array, target, 0, len(array)-1)

  raise KeyError(f'Invalid strategy: {strategy}')

def _binary_search_iterative(array, target):
  # Create a window from the start index of the array to the last index,
  # keep searching windows of halving size until we find the array or
  # our window becomes smaller than size 1
  left, right = 0, len(array)-1
  while left <= right:

    mid = (left + right) // 2
    midVal = array[mid]

    # If the midpoint is exaclty our target, we're done
    if midVal == target:
      return mid

    # Since the array is sorted we can simply check the left half if the
    # target is less than our midpoint value. Do this by moving the right
    # pointer to just left of the mid pointer
    elif target < midVal:
      right = mid - 1

    # If the target value is greater than our midpoint value, search the
    # right half by moving the left pointer to just after the mid pointer
    #
    # NOTE: We don't need a strict else, since the target can only be equal,
    # smaller, or greater than our mid value (so this is effectively an else
    # with better readability)
    elif midVal < target:
      left = mid + 1

  # The standard 'not found' indicator value is -1 since -1 is not a valid index
  return -1

def _binary_search_recursive(array, target, left, right):
  if left > right:
    return -1

  mid = (left + right) // 2
  midVal = array[mid]
  if midVal == target:
    return mid
  elif target < midVal:
    return _binary_search_recursive(array, target, left, mid-1)
  elif midVal < target:
    return _binary_search_recursive(array, target, mid+1, right)

def _array_is_sorted(array):
  '''
  An O(n) scan across the array to check if the array is sorted
  '''
  return all(map(lambda i: array[i-1] <= array[i], range(1,len(array))))

for strategy in Strategy:
  assert binary_search([1,2,3,4,5,6,7], 3, strategy) == 2
  assert binary_search([1,2,3,4,5,6,7], 8, strategy) == -1
  assert binary_search([99, 100, 110, 130, 133], 133, strategy) == 4
  assert binary_search([99, 100, 110, 130, 133], 134, strategy) == -1
  assert binary_search([64, 81, 144, 256, 512], 81, strategy) == 1
  assert binary_search([64, 81, 144, 256, 512], 420, strategy) == -1


#!/usr/bin/python
# -- coding: utf-8 --
import socket;
if "__main__" == __name__:
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); #定义socket类型，网络通信，TCP
        print("create socket succ!");
        sock.bind(('192.168.177.111', 6666)); #套接字绑定的IP与端口
        print("bind socket succ!");
        sock.listen(5);
        print("listen succ!");
    except:
        print("init socket err!");
    while True:
        print("listen for client...");
        conn, addr = sock.accept(); #接受TCP连接，并返回新的套接字与IP地址
        print("get client");
        print(addr);
        conn.settimeout(5);
        szBuf = conn.recv(1024); #把接收的数据实例化
        print("recv:" + str(szBuf));
        if "0" == szBuf:
            conn.sendall('exit');
        else:
            conn.sendall('welcome client!');
        conn.close();
        print("end of sevice");


def smallest(n):
    strN = str(n)
    minNumber = min(strN)
    minIndex = strN.index(minNumber)
    result = []

    # print('minimum', minNumber, 'minimum index', minIndex)

    for i in range(len(strN)):
        index = i
        item = int(strN[i])
        # print('index', index, 'item', item)

        if item == int(minNumber):
            print(item, minNumber)
            # print(strN)
            strN = strN.replace(minNumber, '', 1)
            # print(strN)
            strN = minNumber + strN
            # print(strN)

            # print(type(strN), type(minNumber), type(minIndex))

            result = [strN] + [str(minIndex)] + [0]
            # print('result', result)
            break

    return result

print(smallest(261235))     #[126235, 2, 0]
# print(smallest(209917))     #[29917, 0, 1]
print(smallest(285365))     #[238565, 3, 1]
# print(smallest(269045))     #[26945, 3, 0]
# print(smallest(296837))     #[239687, 4, 1]


import threading

from hdwallet import HDWallet
from hdwallet.symbols import BTC as SYMBOL
from hexer import mHash
from rich.console import Console
from colorama import Fore, Style, Back
from hexer import mHash

mmdrza = '''
         - - - - - - - - - - - - - - - - - - - - - ---***--- - - - - - - - - - - - - - - - - - - - -
        ███╗███╗   ███╗███╗   ███╗██████╗ ██████╗ ███████╗ █████╗     ██████╗ ██████╗ ███╗   ███╗███╗
        ██╔╝████╗ ████║████╗ ████║██╔══██╗██╔══██╗╚══███╔╝██╔══██╗   ██╔════╝██╔═══██╗████╗ ████║╚██║
        ██║ ██╔████╔██║██╔████╔██║██║  ██║██████╔╝  ███╔╝ ███████║   ██║     ██║   ██║██╔████╔██║ ██║
        ██║ ██║╚██╔╝██║██║╚██╔╝██║██║  ██║██╔══██╗ ███╔╝  ██╔══██║   ██║     ██║   ██║██║╚██╔╝██║ ██║
        ███╗██║ ╚═╝ ██║██║ ╚═╝ ██║██████╔╝██║  ██║███████╗██║  ██║██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║███║
        ╚══╝╚═╝     ╚═╝╚═╝     ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝     ╚═╝╚══╝
        '''

filename = input('[*]Enter File Name With Type Format: ')
console = Console()
console.clear()

with open(filename) as f:
	add = f.read().split()
add = set(add)
print('\n\n\n\n\n\n\n\n\n\n\n\n', Fore.RED, str(mmdrza), Style.RESET_ALL, '\n')

def mmdrza_t():
	w = 0
	z = 0
	print(Fore.YELLOW + '[*] Programmer Mmdrza.Com    ' + Fore.YELLOW + '\n[*] Telegram Channel: @mPython3   ' + Fore.YELLOW + '\n[*] Telegram iD @PyMmdrza\n' + Fore.YELLOW + '[*] All Address Type Generated Type:' + Fore.GREEN + '\n[*] P2PKH - P2SH - P2wSH - P2wPKH - Bech32\n')
	while True:
		ihex = mHash()
		PrivHex = str(ihex)
		hd: HDWallet = HDWallet(symbol=SYMBOL)
		hd.from_private_key(private_key=PrivHex)
		priv = hd.private_key()
		addr1 = hd.p2pkh_address()
		addr2 = hd.p2wpkh_address()
		addr3 = hd.p2wsh_address()
		addr4 = hd.p2sh_address()
		addr5 = hd.p2wsh_in_p2sh_address()
		addr6 = hd.p2wpkh_in_p2sh_address()
		if addr1 in add:
			print('New Find Detail BTC Wallet ... Saved On Text File .', str(addr1), str(priv))
			f = open("BTC_Winner_DETAIL.txt", "a")
			f.write('\nAddr:       ' + str(addr1))
			f.write('\nPrivateKey: ' + str(priv))
			f.write('\n================[ MMDRZA.COM ]==================\n')
			f.close()
			w += 1
			z += 1

		elif addr2 in add:
			print('New Find Detail BTC Wallet ... Saved On Text File .', str(addr2), str(priv))
			f = open("BTC_Winner_DETAIL.txt", "a")
			f.write('\nAddr:       ' + str(addr2))
			f.write('\nPrivateKey: ' + str(priv))
			f.write('\n================[ MMDRZA.COM ]==================\n')
			f.close()
			w += 1
			z += 1

		elif addr3 in add:
			print('New Find Detail BTC Wallet ... Saved On Text File .', str(addr3), str(priv))
			f = open("BTC_Winner_DETAIL.txt", "a")
			f.write('\nAddr:       ' + str(addr3))
			f.write('\nPrivateKey: ' + str(priv))
			f.write('\n================[ MMDRZA.COM ]==================\n')
			f.close()
			w += 1
			z += 1

		elif addr4 in add:
			print('New Find Detail BTC Wallet ... Saved On Text File .', str(addr4), str(priv))
			f = open("BTC_Winner_DETAIL.txt", "a")
			f.write('\nAddr:       ' + str(addr4))
			f.write('\nPrivateKey: ' + str(priv))
			f.write('\n================[ MMDRZA.COM ]==================\n')
			f.close()
			w += 1
			z += 1

		elif addr5 in add:
			print('New Find Detail BTC Wallet ... Saved On Text File .', str(addr5), str(priv))
			f = open("BTC_Winner_DETAIL.txt", "a")
			f.write('\nAddr:       ' + str(addr5))
			f.write('\nPrivateKey: ' + str(priv))
			f.write('\n================[ MMDRZA.COM ]==================\n')
			f.close()
			w += 1
			z += 1

		elif addr6 in add:
			print('New Find Detail BTC Wallet ... Saved On Text File .', str(addr6), str(priv))
			f = open("BTC_Winner_DETAIL.txt", "a")
			f.write('\nAddr:       ' + str(addr6))
			f.write('\nPrivateKey: ' + str(priv))
			f.write('\n================[ MMDRZA.COM ]==================\n')
			f.close()
			w += 1
			z += 1

		else:
			print(Fore.RED, '[+] TOTAL:', Fore.WHITE, str(z), Fore.YELLOW, '- Win:', Fore.CYAN, str(w), Fore.WHITE, Back.RED, str(priv), Style.RESET_ALL, end='\r')
			z += 1
mmdrza_t()

t_Core = threading.Thread(target=mmdrza_t)
t_Core.start()
t_Core.join()


#
# @lc app=leetcode id=86 lang=python3
#
# [86] Partition List
#

# @lc code=start
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution():
    def partition(self, head, x):
        new_list1 = []
        new_list2 = []
        while head is not None:
            # print(head.val)
            if head.val < x:
                new_list1.append(head.val)
            else:
                new_list2.append(head.val)
            head = head.next
        new_list1 = new_list1 + new_list2
        print(new_list1)

        new_node = ListNode()
        r_node = new_node
        for i in new_list1:
            temp = ListNode(i)
            r_node.next, temp.next = temp, None
            r_node = r_node.next

        return new_node.next

if __name__ == "__main__":
    n1 = ListNode(1, None)
    n2 = ListNode(4, None)
    n3 = ListNode(3, None)
    n4 = ListNode(2, None)
    n5 = ListNode(5, None)
    n6 = ListNode(2, None)
    n1.next = n2
    n2.next = n3
    n3.next = n4
    n4.next = n5
    n5.next = n6

    s = Solution()
    s.partition(n1, 3)

# @lc code=end


from sortedcontainers import SortedList
nums = [5,3,2,10,15,7,9]
x = 2
# nums = [68,68]
# x = 1

def minAbsoulteDifference(nums,x):
    n = len(nums)
    mn = float('inf')
    sl = SortedList(nums[x-1:])
    for i in range(n-x):
        sl.discard(nums[i+x-1])
        j = sl.bisect_left(nums[i])
        if j==0:
            mn = min(mn, abs(nums[i]-sl[0]))
        elif j==len(sl):
            mn = min(mn, abs(nums[i]-sl[-1]))
        else:
            mn = min(mn, abs(nums[i]-sl[j-1]), abs(nums[i]-sl[j]))
        # for j in range(i+x,n):
        #     mn = min(mn,abs(nums[i]-nums[j]))
    return mn

print(minAbsoulteDifference(nums,x))


__author__ = 'Sean Lip'

import copy
import os

from core.domain import obj_services
from core.domain import rule_domain
import feconf
import jinja_utils
import schema_utils
import utils

# Indicates that the learner view of the interaction should be displayed in the
# context of the conversation.
DISPLAY_MODE_INLINE = 'inline'
# Indicates that the learner view of the interaction should be displayed as a
# separate object from the conversation.
DISPLAY_MODE_SUPPLEMENTAL = 'supplemental'

ALLOWED_DISPLAY_MODES = [DISPLAY_MODE_SUPPLEMENTAL, DISPLAY_MODE_INLINE]

class AnswerHandler(object):
    """Value object for an answer event stream (e.g. submit, click, drag)."""

    def __init__(self, name, obj_type):
        self.name = name
        self.obj_type = obj_type
        self.obj_class = obj_services.Registry.get_object_class_by_type(
            obj_type)

    @property
    def rules(self):
        return rule_domain.get_rules_for_obj_type(self.obj_type)

    def to_dict(self):
        return {
            'name': self.name,
            'obj_type': self.obj_type,
        }

class CustomizationArgSpec(object):
    """Value object for a customization arg specification."""

    def __init__(self, name, description, schema, default_value):
        self.name = name
        self.description = description
        self.schema = schema
        self.default_value = default_value

class BaseInteraction(object):
    """Base interaction definition class.

    This class is not meant to be user-editable. The only methods on it should
    be get()-type methods.
    """

    # The human-readable name of the interaction. Overridden in subclasses.
    name = ''
    # The category the interaction falls under in the repository. Overridden in
    # subclasses; a value of '' means that this should be displayed as a
    # top-level interaction.
    category = ''
    # A description of the interaction. Overridden in subclasses.
    description = ''
    # Describes how the interaction should be displayed -- either within the
    # conversation ('inline'), or as a separate object ('supplemental'). In the
    # latter case, the interaction instance is reused if two adjacent states
    # have the same interaction id.
    display_mode = ''
    # Whether this interaction should be considered terminal, i.e. it ends
    # the exploration. Defaults to False.
    is_terminal = False
    # Additional JS library dependencies that should be loaded in pages
    # containing this interaction. These should correspond to names of files in
    # feconf.DEPENDENCIES_TEMPLATES_DIR. Overridden in subclasses.
    _dependency_ids = []
    # Actions that the learner can perform on this interaction which trigger a
    # feedback response, and the associated input types. Each interaction must
    # have at least one of these. Overridden in subclasses.
    _handlers = []
    # Customization arg specifications for the component, including their
    # descriptions, schemas and default values. Overridden in subclasses.
    _customization_arg_specs = []

    @property
    def id(self):
        return self.__class__.__name__

    @property
    def customization_arg_specs(self):
        return [
            CustomizationArgSpec(**cas)
            for cas in self._customization_arg_specs]

    @property
    def handlers(self):
        return [AnswerHandler(**ah) for ah in self._handlers]

    @property
    def dependency_ids(self):
        return copy.deepcopy(self._dependency_ids)

    def normalize_answer(self, answer, handler_name):
        """Normalizes a learner's input to this interaction."""
        for handler in self.handlers:
            if handler.name == handler_name:
                return handler.obj_class.normalize(answer)

        raise Exception(
            'Could not find handler in interaction %s with name %s' %
            (self.name, handler_name))

    def validate_customization_arg_values(self, customization_args):
        """Validates customization arg values. The input is a dict whose
        keys are the names of the customization args.
        """
        for ca_spec in self.customization_arg_specs:
            schema_utils.normalize_against_schema(
                customization_args[ca_spec.name]['value'],
                ca_spec.schema)

    @property
    def _stats_log_template(self):
        """The template for reader responses in the stats log."""
        try:
            return utils.get_file_contents(os.path.join(
                feconf.INTERACTIONS_DIR, self.id, 'stats_response.html'))
        except IOError:
            return '{{answer}}'

    @property
    def html_body(self):
        """The HTML code containing directives and templates for the
        interaction. This contains everything needed to display the interaction
        once the necessary attributes are supplied.

        Each interaction has two directive/template pairs, one for the
        interaction itself and the other for displaying the learner's response
        in a read-only view after it has been submitted.
        """
        js_directives = utils.get_file_contents(os.path.join(
            feconf.INTERACTIONS_DIR, self.id, '%s.js' % self.id))
        html_templates = utils.get_file_contents(os.path.join(
            feconf.INTERACTIONS_DIR, self.id, '%s.html' % self.id))
        return '<script>%s</script>\n%s' % (js_directives, html_templates)

    @property
    def validator_html(self):
        """The HTML code containing validators for the interaction's
        customization_args and handlers.
        """
        return (
            '<script>%s</script>\n' %
            utils.get_file_contents(os.path.join(
                feconf.INTERACTIONS_DIR, self.id, 'validator.js')))

    def to_dict(self):
        """Gets a dict representing this interaction. Only default values are
        provided.
        """
        result = {
            'id': self.id,
            'name': self.name,
            'category': self.category,
            'description': self.description,
            'display_mode': self.display_mode,
            'is_terminal': self.is_terminal,
            'customization_arg_specs': [{
                'name': ca_spec.name,
                'description': ca_spec.description,
                'default_value': ca_spec.default_value,
                'schema': ca_spec.schema,
            } for ca_spec in self.customization_arg_specs],
        }

        # Add information about the handlers.
        result['handler_specs'] = [h.to_dict() for h in self.handlers]
        for idx, handler in enumerate(self.handlers):
            result['handler_specs'][idx]['rules'] = dict((
                rule_cls.description,
                {'classifier': rule_cls.__name__}
            ) for rule_cls in handler.rules)

        return result

    def get_handler_by_name(self, handler_name):
        """Get the handler for an interaction, given the handler's name."""
        try:
            return next(h for h in self.handlers if h.name == handler_name)
        except StopIteration:
            raise Exception(
                'Could not find handler with name %s' % handler_name)

    def get_rule_by_name(self, handler_name, rule_name):
        """Gets a rule, given its name and ancestors."""
        handler = self.get_handler_by_name(handler_name)
        try:
            return next(
                r for r in handler.rules if r.__name__ == rule_name)
        except StopIteration:
            raise Exception(
                'Could not find rule with name %s for handler %s'
                % (rule_name, handler_name))

    def get_stats_log_html(self, state_customization_args, answer):
        """Gets the HTML for recording a learner's response in the stats log.

        Returns an HTML string.
        """
        customization_args = {
            ca_spec.name: (
                state_customization_args[ca_spec.name]['value']
                if ca_spec.name in state_customization_args
                else ca_spec.default_value
            ) for ca_spec in self.customization_arg_specs
        }
        customization_args['answer'] = answer

        return jinja_utils.parse_string(
            self._stats_log_template, customization_args, autoescape=False)


from PyQt5.QtWidgets import QDialog
from PyQt5 import uic
global file_path
file_path = os.path.dirname(os.path.abspath(__file__)) + "/"
class FilterSupport(QDialog):
	def __init__(self):
		super().__init__()

		#load template
		uic.loadUi(file_path+"templates/FilterSyntaxSupport.ui", self)

		self.show()

# if __name__ == "__main__":
# 	app = QApplication(sys.argv)
# 	mainWindow = IpsWindow("192.168.1.1",[])
# 	sys.exit(app.exec_())


"""
.. module:: _grids
"""

from __future__ import absolute_import, division, print_function, unicode_literals

import logging
from dune.grid.grid_generator import getDimgrid
from dune.mmesh import _grid2d, _grid3d

# Need to import _interfacegrid modules to ensure Python type is registered.
#pylint: disable=unused-import
from dune.mmesh import _interfacegrid2d, _interfacegrid3d
#pylint: enable=unused-import

logger = logging.getLogger(__name__)

def mmesh(constructor, dimgrid=None, **_parameters):
  """Create an MMesh grid.

  Args:
    constructor: Grid constructor, e.g. (dune.grid.reader.gmsh, 'grid.msh') or dune.grid.cartesianDomain([0,0],[1,1],[10,10]).
    dimgrid (int, optional): The world dimension (must be 2 or 3). Might be guessed by constructor.
    **parameters: Additional parameters.

  Returns:
    An MMesh grid instance.

  Examples:

    Creating simple structured grid::

      from dune.grid import cartesianDomain
      from dune.mmesh import mmesh
      grid = mmesh(cartesianDomain([0,0], [1,1], [10,10]))

    Using a .msh file::

      from dune.grid import reader
      from dune.mmesh import mmesh
      grid = mmesh((reader.gmsh, "grid.msh"), 2)
      igrid = grid.hierarchicalGrid.interfaceGrid

    where grid.msh can be generated by `gmsh <https://pypi.org/project/gmsh/>`_ [GR09]_. For instance::

      name = "grid.msh"
      h = 0.1
      hf = 0.01

      import gmsh
      gmsh.initialize()
      gmsh.option.setNumber("Mesh.MshFileVersion", 2.2)

      gmsh.model.add("name")

      geo = gmsh.model.geo

      p1 = geo.addPoint(0, 0, 0, h, 1)
      p2 = geo.addPoint(1, 0, 0, h, 2)
      p3 = geo.addPoint(1, 1, 0, h, 3)
      p4 = geo.addPoint(0, 1, 0, h, 4)

      l1 = geo.addLine(p1, p2, 1)
      l2 = geo.addLine(p2, p3, 2)
      l3 = geo.addLine(p3, p4, 3)
      l4 = geo.addLine(p4, p1, 4)

      p5 = geo.addPoint(0.25, 0.5, 0, hf, 5)
      p6 = geo.addPoint(0.75, 0.5, 0, hf, 6)
      lf = geo.addLine(p5, p6, 10)

      geo.addCurveLoop([l1, l2, l3, l4], 1)
      geo.addPlaneSurface([1], 0)

      geo.synchronize()

      gmsh.model.mesh.embed(1, [lf], 2, 0)
      gmsh.model.mesh.generate(dim=2)
      gmsh.write(name)
      gmsh.finalize()

    .. [GR09] C. Geuzaine and J.-F. Remacle. Gmsh: a three-dimensional finite element mesh generator with built-in pre- and post-processing facilities.
    International Journal for Numerical Methods in Engineering 79(11), pp. 1309-1331, 2009.

  """

  if not dimgrid:
    dimgrid = getDimgrid(constructor)

  if not dimgrid in [2,3]:
    raise KeyError("Parameter error in MMesh with dimgrid=" + str(dimgrid) + ": dimgrid has to be either 2 or 3")

  if dimgrid == 2:
    gridModule = _grid2d

  elif dimgrid == 3:
    gridModule = _grid3d

  gridView = gridModule.LeafGrid(gridModule.reader(constructor))

  # in case of a cartesian domain store if old or new boundary ids was used
  # this can be removed in later version - it is only used in dune-fem
  # to give a warning that the boundary ids for the cartesian domains have changed
  try:
    #pylint: disable=protected-access
    gridView.hierarchicalGrid._cartesianConstructionWithIds = constructor.boundaryWasSet
    #pylint: enable=protected-access
  except AttributeError:
    pass

  def interfaceGrid(self):
    return self.interfaceHierarchicalGrid.leafView

  gridModule.HierarchicalGrid.interfaceGrid = property(interfaceGrid)

  return gridView

grid_registry = {
  "MMesh" : mmesh
}

if __name__ == "__main__":
  import doctest
  doctest.testmod(optionflags=doctest.ELLIPSIS)


class Solution:
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        # Exception: division by zero:
        try:
            diff = (coordinates[1][1]-coordinates[0][1])/(coordinates[1][0]-coordinates[0][0])
            for i, coord in enumerate(coordinates[1:], 1):
                if (coord[1]-coordinates[i-1][1])/(coord[0]-coordinates[i-1][0])!=diff:
                    return False
            return True
        except:
            x_axis = coordinates[0][0]
            for coord in coordinates[1:]:
                if x_axis!=coord[0]:
                    return False
            return True


#!/usr/bin/env python3

import scipy.special as spfunc
import os
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import re

def plot_data_dict(main_dict, spatial_freqs, power_setting):
	data = []

	ordered_images = sorted([image for image in main_dict])

	for image in ordered_images:
		modulations = main_dict[image]

		y = [modulation[0] for modulation in modulations]
		y_err = [modulation[1] for modulation in modulations]

		a,cov = fit(spatial_freqs, y, y_err,model)
		data.append([image,[a,cov[0][0]]])

	voltages = [point[0] for point in data]
	a = [point[1][0] for point in data]
	a_err = [point[1][1] for point in data]

	# Print the focal spot data onto a textfile.
	data_file = open("/home/lucas/Documents/Code/microCTImageAnalyser/docs/focalspots_at_{}W.txt".format(power_setting),"w")
	for i in range(len(a)-1):
		data_file.write("{}\t{}\t{}\n".format(voltages[i],float(a[i]),float(a_err[i])))
	data_file.close()

	plt.figure()
	plt.xlabel("Voltages")
	plt.ylabel("Focal spotsize (µm)")
	plt.title("Focal spotsizes at {}W".format(power_setting))
	plt.errorbar(voltages,a,yerr = a_err, fmt='ro')
	plt.show()

def get_voltage(image):
	print(image)
	result = re.search('r"(?i)\d\dkV',str(image))
	return int(result.group(0))

def plot_modulation_transfer(image, modulations, spatial_freqs):
	# Make the figure and set all the text for the axis and title.
	plt.figure()
	plt.xlabel("Spatial Frequency")
	plt.ylabel("Modulation")
	plt.title("Modulation transfer function"\
	" of image: {}".format(os.path.basename(image)))

	# Create the y data and its errorbars given in modulations.
	y = [modulation[0] for modulation in modulations]
	y_err = [modulation[1] for modulation in modulations]

	# Create fitted function points.
	special_freqs = np.arange(0,spatial_freqs[len(spatial_freqs)-1],0.1)
	a,cov = fit(spatial_freqs,y,y_err,model)
	fit_data = [model(x,a) for x in special_freqs]

	# Plot and show.
	plt.plot(spatial_freqs, y,'co',special_freqs,fit_data)
	plt.text(1,1, 'Focal spotsize = {}'.format(round(float(a), 3)))
	plt.show()

def fit(x,y,y_err,model):
	"""
	This function uses a scipy method to fit the parameters to the given x,y data.
	"""
	fitted_output = curve_fit(model,x,y,sigma=y_err)
	a = fitted_output[0]
	covariance = fitted_output[1]
	return a,covariance

def model(x,a):

	m = 67.45
	return 2*spfunc.jn(1,np.pi*x*a*((m-1)/m))/(np.pi*x*a*((m-1)/m))


def union_team(parent, a, b):
    a = find_parent(parent, a)
    b = find_parent(parent, b)
    if a < b:
        parent[b] = a
    else:
        parent[a] = b

    return

def find_parent(parent, a):
    if a != parent[a]:
        parent[a] = find_parent(parent, parent[a])
    return parent[a]

def is_cycle(parent, a, b):
    if find_parent(parent, a) == find_parent(parent, b):
        return True
    else:
        return False

N, M = map(int, stdin.readline().split())
parent = [0] * (N + 1)
queue = []
result = 0

for i in range(N + 1):
    parent[i] = i

for i in range(M):
    A, B, C = map(int, stdin.readline().split())
    queue.append((C, A, B))

last = 0
queue.sort()
for item in queue:
    C, A, B = item
    if is_cycle(parent, A, B):
        continue
    else:
        union_team(parent, A, B)
        result += C
        if last < C:
            last = C

print(result - last)

문제유형/그래프이론/커리큘럼.py


from xivo_dao.alchemy import QueueMember
from xivo_dao.resources.agent import dao as agent_dao
from xivo_dao.resources.queue import dao as queue_dao

from .resource import QueueMemberAgentSchema

class QueueMemberMiddleWare:
    def __init__(self, service):
        self._service = service

        self._schema = QueueMemberAgentSchema()

    def _find_or_create_member(self, queue, agent):
        member = self._service.find_member_agent(queue, agent)
        if not member:
            member = QueueMember(agent=agent)
        return member

    def associate(self, body, queue_id, agent_id, tenant_uuids):
        queue = queue_dao.get(queue_id, tenant_uuids=tenant_uuids)
        agent = agent_dao.get(agent_id, tenant_uuids=tenant_uuids)
        member = self._find_or_create_member(queue, agent)
        form = self._schema.load(body)
        member.penalty = form['penalty']
        member.priority = form['priority']
        self._service.associate_member_agent(queue, member)

    def dissociate(self, queue_id, agent_id, tenant_uuids):
        queue = queue_dao.get(queue_id, tenant_uuids=tenant_uuids)
        agent = agent_dao.get(agent_id, tenant_uuids=tenant_uuids)
        member = self._find_or_create_member(queue, agent)
        self._service.dissociate_member_agent(queue, member)


# --- imports
import discord
import aiosqlite
from datetime import datetime
from discord.ext import commands

class Achievements:
    # --- attributs

    # --- methods
    # constructor
    def __init__(self, bot):
        self.bot = bot

    # achievement(): async
    @commands.group()
    async def achievement(self, ctx):
        """manage NorthgardBattle Achievements"""
        if ctx.invoked_subcommand is None:
            await ctx.send("No param...")

    # list_achievements(): async
    @achievement.command(name="list")
    async def list_achievements(self, ctx, page: int = 1):
        """list all Achievements"""
        async with aiosqlite.connect('./ext/Northgard/battle/data/battle-db.sqlite') as db:
            async with db.execute("SELECT * FROM achievements LIMIT ?, 15;", ((page-1) * 15, )) as cursor:
                achievements = ""
                async for result in cursor:
                    achievements += f"`#{result[0]:>2}` `{result[1]}` {result[2]}\n"
        # generate embed
        embed = discord.Embed(title="__Achievement List__",
                              description=f"List of all registered Achievements in Northgard Battle\n \nPage: {page}",
                              colour=6809006,
                              timestamp = datetime.now())
        embed.set_footer(text='--- List: sorted by AchievementID --- ||')
        if not achievements:
            embed.add_field(name='Achievements', value="no Achievements listed here.", inline=True)
        else:
            embed.add_field(name='Achievements', value=achievements, inline=True)
        await ctx.send(content=f"used Feature: NorthgardBattle `{ctx.message.content}`", embed=embed)

    # add_achievement(): async
    @achievement.command(name="add")
    @commands.is_owner()
    async def add_achievement(self, ctx, icon: str, *, title: str):
        """add an Achievement"""
        async with aiosqlite.connect('./ext/Northgard/battle/data/battle-db.sqlite') as db:
            await db.execute("INSERT INTO achievements (Icon, Name) VALUES (?, ?);", (icon, title))
            await db.commit()
        await ctx.send(f"Achievement '{title}' (Icon: {icon}) got sucessfully added.")

    # grant_achievement(): async
    @achievement.command(name="assign")
    async def assign_achievement(self, ctx, id: int, *, target: str):
        """assign an Achievement to a Player"""
        async with aiosqlite.connect('./ext/Northgard/battle/data/battle-db.sqlite') as db:
            cursor = await db.execute("""
                SELECT AchievementID, Name
                FROM achievements
                WHERE AchievementID = ?;""", (id,))
            achievement = await cursor.fetchone()
            await cursor.close()
            if achievement is not None:
                cursor = await db.execute("""
                    SELECT player.PlayerID, discord.InternalID
                    FROM player
                    LEFT JOIN discord ON discord.ReferenceID = player.PlayerID
                    WHERE discord.Reference = 'Player' AND player.Name = ?;""", (target,))
                player = await cursor.fetchone()
                await cursor.close()
                if player is not None:
                    cursor = await db.execute("""
                        SELECT playerachievements.Value
                        FROM playerachievements
                        LEFT JOIN player ON player.PlayerID = playerachievements.PlayerID
                        WHERE player.PlayerID = ? AND playerachievements.AchievementID = ?;""", (player[0],achievement[0]))
                    result = await cursor.fetchone()
                    await cursor.close()
                    # Achievement already exists?
                    if result is not None:
                        await db.execute("""
                            UPDATE playerachievements
                            SET Value = ?
                            WHERE PlayerID = ? AND AchievementID = ?;""", (result[0] + 1,player[0],achievement[0]))
                    else:
                        await db.execute("""
                            INSERT INTO playerachievements (PlayerID, AchievementID)
                            VALUES (?,?)""", (player[0], achievement[0]))
                    await db.commit()
                    await ctx.send(f"Achievement '{achievement[1]}' got sucessfully assigned to Player '{target}'.")
                    await self.bot.get_guild(self.bot.northgardbattle).get_member(player[1]).send(
                        f"Congratulations! You have got a new Achievement on Northgard Battle:\n`{achievement[1]}`")
                else:
                    return await ctx.send(f"Player not found (Name: {target})")
            else:
                return await ctx.send(f"Achievement not found (ID: {id})")

    # delete_achievement(): async
    @achievement.command(name="delete", hidden=True)
    async def delete_achievement(self, ctx):
        """delete an Achievement"""
        print("Here: !achievement delete")

    # set_achievement_data(): async
    @achievement.command(name="set", hidden=True)
    async def set_achievement_data(self, ctx, subject: str, *, data: str):
        """set Data for your achievement profile"""
        args = ["icon", "title"]
        if subject.lower() in args:
            async with aiosqlite.connect('./ext/Northgard/battle/data/battle-db.sqlite') as db:
                if subject.lower() == "icon":
                    if data.startswith("https://steamcommunity.com/"):
                        await db.execute("UPDATE achievement SET Steam = ? WHERE Name = ?;", (data, ctx.author.name))
                elif subject.lower() == "title":
                    await db.execute('UPDATE achievement SET Description = ? WHERE Name = ?;', (data, ctx.author.name))
                await db.commit()
            await ctx.send(f"Your Achievement-Data '{subject}' got set to `{data}`")

# --- routine: setup/assign cog
def setup(bot):
    bot.add_cog(Achievements(bot))


import FWCore.ParameterSet.Config as cms

NonTauPairTrackCollectionProducer = cms.EDProducer(
	"NonTauPairTrackCollectionProducer",
	CandsTag = cms.InputTag("packedPFCandidates"),
	TauPairTag = cms.InputTag("slimmedTaus"),
	PVTag = cms.InputTag("offlineSlimmedPrimaryVertices"),
	deltaRThreshold = cms.double(0.001),
	deltaPtThreshold = cms.double(0.001)
)


###
#   File name  : 5_11_p52.py
#   Author     : Hyunjin Kim
#   Date       : Jun 19, 2019
#   Email      : firadazer@gmail.com
#   Purpose    : Write a program that takes as input a permutation, and returns the next permutation
#                under dictionary ordering. If the permutation is the last permutation, return the empty array.
#
#   Example    : input: [1, 0, 3, 2], output: [1, 2, 0, 3]
#                input: [3, 2, 1, 0], output: []
#                input: [3, 1, 0, 2, 4], output: [3, 1, 0, 4, 2]
#                input: [2, 0, 1, 3, 4, 5], output: [2, 0, 1, 3, 5, 4]
#                input: [0, 4, 2, 1, 3, 7, 6, 5], output: [0, 4, 2, 1, 5, 3, 6, 7]
#                input: [1, 5, 4, 3, 2, 0], output: [2, 0, 1, 3, 4, 5]
#
#   Instruction
#               1. import 5_11_p52.py
#               2. Run the function 5_11_p52.start()
#               3. The results will be generated in the console
###

### import modules
import timeit

### a function starting this script
def start():
    print("5_11_p52.py")

    start_time = timeit.default_timer()
    print("next_perm([1, 0, 3, 2]) = ", next_perm([1, 0, 3, 2]))
    print("next_perm([3, 2, 1, 0]) = ", next_perm([3, 2, 1, 0]))
    print("next_perm([3, 1, 0, 2, 4]) = ", next_perm([3, 1, 0, 2, 4]))
    print("next_perm([2, 0, 1, 3, 4, 5]) = ", next_perm([2, 0, 1, 3, 4, 5]))
    print("next_perm([0, 4, 2, 1, 3, 7, 6, 5]) = ", next_perm([0, 4, 2, 1, 3, 7, 6, 5]))
    print("next_perm([1, 5, 4, 3, 2, 0]) = ", next_perm([1, 5, 4, 3, 2, 0]))
    print("Execution Time: ", timeit.default_timer() - start_time)

### from the end, find the lower value than the end
### if found, swap it with the end and swap the next right with the swapped one again
### time complexity: O(n), space complexity: O(1)
def next_perm(P):
    stop_idx = -1
    for i in reversed(range(len(P)-1)):
        if P[i] < P[len(P)-1]:
            stop_idx = i
            break

    if stop_idx is -1:
        return []
    elif len(P) - stop_idx is 2:
        P[stop_idx], P[len(P) - 1] = P[len(P) - 1], P[stop_idx]
        return P
    else:
        P[stop_idx], P[stop_idx + 1], P[len(P) - 1] = P[len(P) - 1], P[stop_idx], P[stop_idx + 1]
        return P

start()