from operator import itemgetter
import math

# Input file
file_name = input("Enter a filename: ")
with open(file_name) as file_name:
    text = file_name.read()

# Text indexing
text_count_game = text.split("\n")
index = [elem.strip().split("\t") for elem in text_count_game]
del index[-1]   # If you run test.py in terminal(not in VS-Code) -> use # before this line!!!
type_index = list(zip(*index))

# Report functions
def get_most_played(file_name):
    counter = 0
    played_float = []
    for i in type_index[1]:
        played_float.append(float(type_index[1][counter]))
        counter += 1
    played_million_index = max(enumerate(played_float), key=itemgetter(1))[0]
    return type_index[0][played_million_index]

def sum_sold(file_name):
    counter = 0
    played_float = []
    for i in type_index[1]:
        played_float.append(float(type_index[1][counter]))
        counter += 1
    return sum(played_float)

def get_selling_avg(file_name):
    counter = 0
    played_float = []
    for i in type_index[1]:
        played_float.append(float(type_index[1][counter]))
        counter += 1
    played_float_sum = sum(played_float)
    avg_sum = played_float_sum/len(type_index[1])
    return avg_sum

def count_longest_title(file_name):
    longest_title = 0
    for i in type_index[0]:
        if len(i) > longest_title:
            longest_title = len(i)
    return longest_title

def get_date_avg(file_name):
    date_avg = 0
    for i in type_index[2]:
        date_avg += int(i)
    return int(math.ceil((date_avg/(len(type_index[2]))/1.0))) * 1

def get_game(file_name, title):
    counter = 0
    for i in type_index[0]:
        if title == i:
            game = index[counter]
            game[1] = float(game[1])
            game[2] = int(game[2])
            return game
        counter += 1

def count_grouped_by_genre(file_name):
    genre_dict = {}
    for i in type_index[3]:
        if i not in genre_dict:
            genre_dict[i] = 1
        elif i in genre_dict:
            genre_dict[i] += 1
    return genre_dict

def get_date_ordered(file_name):
    name_date_dict = {}
    counter = 0
    for i in type_index[0]:
        name_date_dict[i] = type_index[2][counter]
        counter += 1
    name_date_dict_new = sorted(name_date_dict.items(), key=lambda t: t[0])
    name_date_dict_new_list = []
    for i in name_date_dict_new:
        name_date_dict_new_list.append(list(i))
    for i in range(len(name_date_dict_new_list)-1, 0, -1):
        for j in range(i):
            if name_date_dict_new_list[j][1] < name_date_dict_new_list[j+1][1]:
                temp = name_date_dict_new_list[j]
                name_date_dict_new_list[j] = name_date_dict_new_list[j+1]
                name_date_dict_new_list[j+1] = temp
    name_date_dict_end = []
    counter_new = 0
    for i in name_date_dict_new_list:
        name_date_dict_end.append(name_date_dict_new_list[counter_new][0])
        counter_new += 1
    return name_date_dict_end


from itertools import permutations

usr_input = input("word:")

permuted_list = [''.join(p) for p in permutations(str(usr_input))]
print (permuted_list)
count = 0
for elem in permuted_list:
    f = open("wordlist.txt")
    for line in f.readlines():
        if elem == line.strip("\n"):
            print (elem)
            count += 1

print (count)


import json
import os
from logic.classes.administrator import Administrator

PATH = os.getcwd()
DIR_DATA = PATH + '{0}data{0}'.format(os.sep)

class AdministratorController(object):

    def __init__(self):
        self.file = '{0}{1}'.format(DIR_DATA, 'administrator_storage.json')

    def add(self, administrator: Administrator = Administrator()) -> str:
        with open(self.file, 'r+') as f:
            data = json.load(f)
            data['administrator'].append(administrator.__str__())
            f.seek(0)
            json.dump(data, f)
        f.close()
        return administrator.__str__()

    def show(self):
        # Opening JSON file
        with open(self.file, 'r') as openfile:
            # Reading from json file
            json_object = json.load(openfile)
        return json_object


import argparse, os, shutil, time, warnings
from datetime import datetime
from pathlib import Path
import sys, os
import math
import collections
import gc

import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed

# import models
from fp16util import *

import resnet
import copy

import dataloader
import experimental_utils
import dist_utils
from logger import TensorboardLogger, FileLogger
from meter import AverageMeter, NetworkMeter, TimeMeter

def get_parser():
    parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
    parser.add_argument('data', metavar='DIR', help='path to dataset')
    parser.add_argument('--phases', type=str,
                    help='Specify epoch order of data resize and learning rate schedule: [{"ep":0,"sz":128,"bs":64},{"ep":5,"lr":1e-2}]')
    # parser.add_argument('--save-dir', type=str, default=Path.cwd(), help='Directory to save logs and models.')
    parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
                        help='number of data loading workers (default: 8)')
    parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                        help='manual epoch number (useful on restarts)')
    parser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum')
    parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
                        metavar='W', help='weight decay (default: 1e-4)')
    parser.add_argument('--init-bn0', action='store_true', help='Intialize running batch norm mean to 0')
    parser.add_argument('--print-freq', '-p', default=5, type=int,
                        metavar='N', help='log/print every this many steps (default: 5)')
    parser.add_argument('--no-bn-wd', action='store_true', help='Remove batch norm from weight decay')
    parser.add_argument('--resume', default='', type=str, metavar='PATH',
                        help='path to latest checkpoint (default: none)')
    parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
                        help='evaluate model on validation set')
    parser.add_argument('--fp16', action='store_true', help='Run model fp16 mode. Default True')
    parser.add_argument('--loss-scale', type=float, default=1024,
                        help='Loss scaling, positive power of 2 values can improve fp16 convergence.')
    parser.add_argument('--distributed', action='store_true', help='Run distributed training. Default True')
    parser.add_argument('--dist-url', default='env://', type=str,
                        help='url used to set up distributed training')
    parser.add_argument('--dist-backend', default='nccl', type=str, help='distributed backend')
    parser.add_argument('--local_rank', default=0, type=int,
                        help='Used for multi-process training. Can either be manually set ' +
                        'or automatically set by using \'python -m multiproc\'.')
    parser.add_argument('--logdir', default='', type=str,
                        help='where logs go')
    parser.add_argument('--skip-auto-shutdown', action='store_true',
                        help='Shutdown instance at the end of training or failure')
    parser.add_argument('--auto-shutdown-success-delay-mins', default=10, type=int,
                        help='how long to wait until shutting down on success')
    parser.add_argument('--auto-shutdown-failure-delay-mins', default=60, type=int,
                        help='how long to wait before shutting down on error')

    parser.add_argument('--short-epoch', action='store_true',
                        help='make epochs short (for debugging)')
    return parser

cudnn.benchmark = True
args = get_parser().parse_args()

# Only want master rank logging to tensorboard
is_master = (not args.distributed) or (dist_utils.env_rank()==0)
is_rank0 = args.local_rank == 0
tb = TensorboardLogger(args.logdir, is_master=is_master)
log = FileLogger(args.logdir, is_master=is_master, is_rank0=is_rank0)

def main():
    os.system('shutdown -c')  # cancel previous shutdown command
    log.console(args)
    tb.log('sizes/world', dist_utils.env_world_size())

    # need to index validation directory before we start counting the time
    dataloader.sort_ar(args.data+'/validation')

    if args.distributed:
        log.console('Distributed initializing process group')
        torch.cuda.set_device(args.local_rank)
        dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, world_size=dist_utils.env_world_size())
        assert(dist_utils.env_world_size() == dist.get_world_size())
        log.console("Distributed: success (%d/%d)"%(args.local_rank, dist.get_world_size()))

    log.console("Loading model")
    model = resnet.resnet50(bn0=args.init_bn0).cuda()
    if args.fp16: model = network_to_half(model)
    if args.distributed: model = dist_utils.DDP(model, device_ids=[args.local_rank], output_device=args.local_rank)
    best_top5 = 93 # only save models over 93%. Otherwise it stops to save every time

    global model_params, master_params
    if args.fp16: model_params, master_params = prep_param_lists(model)
    else: model_params = master_params = model.parameters()

    optim_params = experimental_utils.bnwd_optim_params(model, model_params, master_params) if args.no_bn_wd else master_params

    # define loss function (criterion) and optimizer
    criterion = nn.CrossEntropyLoss().cuda()
    optimizer = torch.optim.SGD(optim_params, 0, momentum=args.momentum, weight_decay=args.weight_decay) # start with 0 lr. Scheduler will change this later

    if args.resume:
        checkpoint = torch.load(args.resume, map_location = lambda storage, loc: storage.cuda(args.local_rank))
        model.load_state_dict(checkpoint['state_dict'])
        args.start_epoch = checkpoint['epoch']
        best_top5 = checkpoint['best_top5']
        optimizer.load_state_dict(checkpoint['optimizer'])

    # save script so we can reproduce from logs
    shutil.copy2(os.path.realpath(__file__), f'{args.logdir}')

    log.console("Creating data loaders (this could take up to 10 minutes if volume needs to be warmed up)")
    phases = eval(args.phases)
    dm = DataManager([copy.deepcopy(p) for p in phases if 'bs' in p])
    scheduler = Scheduler(optimizer, [copy.deepcopy(p) for p in phases if 'lr' in p])

    start_time = datetime.now() # Loading start to after everything is loaded
    if args.evaluate: return validate(dm.val_dl, model, criterion, 0, start_time)

    if args.distributed:
        log.console('Syncing machines before training')
        dist_utils.sum_tensor(torch.tensor([1.0]).float().cuda())

    log.event("~~epoch\thours\ttop1\ttop5\n")
    for epoch in range(args.start_epoch, scheduler.tot_epochs):
        dm.set_epoch(epoch)

        train(dm.trn_dl, model, criterion, optimizer, scheduler, epoch)
        top1, top5 = validate(dm.val_dl, model, criterion, epoch, start_time)

        time_diff = (datetime.now()-start_time).total_seconds()/3600.0
        log.event(f'~~{epoch}\t{time_diff:.5f}\t\t{top1:.3f}\t\t{top5:.3f}\n')

        is_best = top5 > best_top5
        best_top5 = max(top5, best_top5)
        if args.local_rank == 0:
            if is_best: save_checkpoint(epoch, model, best_top5, optimizer, is_best=True, filename='model_best.pth.tar')
            phase = dm.get_phase(epoch)
            if phase: save_checkpoint(epoch, model, best_top5, optimizer, filename=f'sz{phase["bs"]}_checkpoint.path.tar')

def train(trn_loader, model, criterion, optimizer, scheduler, epoch):
    net_meter = NetworkMeter()
    timer = TimeMeter()
    losses = AverageMeter()
    top1 = AverageMeter()
    top5 = AverageMeter()

    # switch to train mode
    model.train()
    for i,(input,target) in enumerate(trn_loader):
        if args.short_epoch and (i > 10): break
        batch_num = i+1
        timer.batch_start()
        scheduler.update_lr(epoch, i+1, len(trn_loader))

        # compute output
        output = model(input)
        loss = criterion(output, target)

        # compute gradient and do SGD step
        if args.fp16:
            loss = loss*args.loss_scale
            model.zero_grad()
            loss.backward()
            model_grads_to_master_grads(model_params, master_params)
            for param in master_params: param.grad.data = param.grad.data/args.loss_scale
            optimizer.step()
            master_params_to_model_params(model_params, master_params)
            loss = loss/args.loss_scale
        else:
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        # Train batch done. Logging results
        timer.batch_end()
        corr1, corr5 = correct(output.data, target, topk=(1, 5))
        reduced_loss, batch_total = to_python_float(loss.data), to_python_float(input.size(0))
        if args.distributed: # Must keep track of global batch size, since not all machines are guaranteed equal batches at the end of an epoch
            metrics = torch.tensor([batch_total, reduced_loss, corr1, corr5]).float().cuda()
            batch_total, reduced_loss, corr1, corr5 = dist_utils.sum_tensor(metrics).cpu().numpy()
            reduced_loss = reduced_loss/dist_utils.env_world_size()
        top1acc = to_python_float(corr1)*(100.0/batch_total)
        top5acc = to_python_float(corr5)*(100.0/batch_total)

        losses.update(reduced_loss, batch_total)
        top1.update(top1acc, batch_total)
        top5.update(top5acc, batch_total)

        should_print = (batch_num%args.print_freq == 0) or (batch_num==len(trn_loader))
        if args.local_rank == 0 and should_print:
            tb.log_memory()
            tb.log_trn_times(timer.batch_time.val, timer.data_time.val, input.size(0))
            tb.log_trn_loss(losses.val, top1.val, top5.val)

            recv_gbit, transmit_gbit = net_meter.update_bandwidth()
            tb.log("sizes/batch_total", batch_total)
            tb.log('net/recv_gbit', recv_gbit)
            tb.log('net/transmit_gbit', transmit_gbit)

            output = (f'Epoch: [{epoch}][{batch_num}/{len(trn_loader)}]\t'
                      f'Time {timer.batch_time.val:.3f} ({timer.batch_time.avg:.3f})\t'
                      f'Loss {losses.val:.4f} ({losses.avg:.4f})\t'
                      f'Acc@1 {top1.val:.3f} ({top1.avg:.3f})\t'
                      f'Acc@5 {top5.val:.3f} ({top5.avg:.3f})\t'
                      f'Data {timer.data_time.val:.3f} ({timer.data_time.avg:.3f})\t'
                      f'BW {recv_gbit:.3f} {transmit_gbit:.3f}')
            log.verbose(output)

        tb.update_step_count(batch_total)

def validate(val_loader, model, criterion, epoch, start_time):
    timer = TimeMeter()
    losses = AverageMeter()
    top1 = AverageMeter()
    top5 = AverageMeter()

    model.eval()
    eval_start_time = time.time()

    for i,(input,target) in enumerate(val_loader):
        if args.short_epoch and (i > 10): break
        batch_num = i+1
        timer.batch_start()
        if args.distributed:
            top1acc, top5acc, loss, batch_total = distributed_predict(input, target, model, criterion)
        else:
            with torch.no_grad():
                output = model(input)
                loss = criterion(output, target).data
            batch_total = input.size(0)
            top1acc, top5acc = accuracy(output.data, target, topk=(1,5))

        # Eval batch done. Logging results
        timer.batch_end()
        losses.update(to_python_float(loss), to_python_float(batch_total))
        top1.update(to_python_float(top1acc), to_python_float(batch_total))
        top5.update(to_python_float(top5acc), to_python_float(batch_total))
        should_print = (batch_num%args.print_freq == 0) or (batch_num==len(val_loader))
        if args.local_rank == 0 and should_print:
            output = (f'Test:  [{epoch}][{batch_num}/{len(val_loader)}]\t'
                      f'Time {timer.batch_time.val:.3f} ({timer.batch_time.avg:.3f})\t'
                      f'Loss {losses.val:.4f} ({losses.avg:.4f})\t'
                      f'Acc@1 {top1.val:.3f} ({top1.avg:.3f})\t'
                      f'Acc@5 {top5.val:.3f} ({top5.avg:.3f})')
            log.verbose(output)

    tb.log_eval(top1.avg, top5.avg, time.time()-eval_start_time)
    tb.log('epoch', epoch)

    return top1.avg, top5.avg

def distributed_predict(input, target, model, criterion):
    # Allows distributed prediction on uneven batches. Test set isn't always large enough for every GPU to get a batch
    batch_size = input.size(0)
    output = loss = corr1 = corr5 = valid_batches = 0

    if batch_size:
        with torch.no_grad():
            output = model(input)
            loss = criterion(output, target).data
        # measure accuracy and record loss
        valid_batches = 1
        corr1, corr5 = correct(output.data, target, topk=(1, 5))

    metrics = torch.tensor([batch_size, valid_batches, loss, corr1, corr5]).float().cuda()
    batch_total, valid_batches, reduced_loss, corr1, corr5 = dist_utils.sum_tensor(metrics).cpu().numpy()
    reduced_loss = reduced_loss/valid_batches

    top1 = corr1*(100.0/batch_total)
    top5 = corr5*(100.0/batch_total)
    return top1, top5, reduced_loss, batch_total

class DataManager():
    def __init__(self, phases):
        self.phases = self.preload_phase_data(phases)
    def set_epoch(self, epoch):
        cur_phase = self.get_phase(epoch)
        if cur_phase: self.set_data(cur_phase)
        if hasattr(self.trn_smp, 'set_epoch'): self.trn_smp.set_epoch(epoch)
        if hasattr(self.val_smp, 'set_epoch'): self.val_smp.set_epoch(epoch)

    def get_phase(self, epoch):
        return next((p for p in self.phases if p['ep'] == epoch), None)

    def set_data(self, phase):
        """Initializes data loader."""
        if phase.get('keep_dl', False):
            log.event(f'Batch size changed: {phase["bs"]}')
            tb.log_size(phase['bs'])
            self.trn_dl.update_batch_size(phase['bs'])
            return

        log.event(f'Dataset changed.\nImage size: {phase["sz"]}\nBatch size: {phase["bs"]}\nTrain Directory: {phase["trndir"]}\nValidation Directory: {phase["valdir"]}')
        tb.log_size(phase['bs'], phase['sz'])

        self.trn_dl, self.val_dl, self.trn_smp, self.val_smp = phase['data']
        self.phases.remove(phase)

        # clear memory before we begin training
        gc.collect()

    def preload_phase_data(self, phases):
        for phase in phases:
            if not phase.get('keep_dl', False):
                self.expand_directories(phase)
                phase['data'] = self.preload_data(**phase)
        return phases

    def expand_directories(self, phase):
        trndir = phase.get('trndir', '')
        valdir = phase.get('valdir', trndir)
        phase['trndir'] = args.data+trndir+'/train'
        phase['valdir'] = args.data+valdir+'/validation'

    def preload_data(self, ep, sz, bs, trndir, valdir, **kwargs): # dummy ep var to prevent error
        if 'lr' in kwargs: del kwargs['lr'] # in case we mix schedule and data phases
        """Pre-initializes data-loaders. Use set_data to start using it."""
        if sz == 128: val_bs = max(bs, 512)
        elif sz == 224: val_bs = max(bs, 256)
        else: val_bs = max(bs, 128)
        return dataloader.get_loaders(trndir, valdir, bs=bs, val_bs=val_bs, sz=sz, workers=args.workers, distributed=args.distributed, **kwargs)

# ### Learning rate scheduler
class Scheduler():
    def __init__(self, optimizer, phases):
        self.optimizer = optimizer
        self.current_lr = None
        self.phases = [self.format_phase(p) for p in phases]
        self.tot_epochs = max([max(p['ep']) for p in self.phases])

    def format_phase(self, phase):
        phase['ep'] = listify(phase['ep'])
        phase['lr'] = listify(phase['lr'])
        if len(phase['lr']) == 2:
            assert (len(phase['ep']) == 2), 'Linear learning rates must contain end epoch'
        return phase

    def linear_phase_lr(self, phase, epoch, batch_curr, batch_tot):
        lr_start, lr_end = phase['lr']
        ep_start, ep_end = phase['ep']
        if 'epoch_step' in phase: batch_curr = 0 # Optionally change learning rate through epoch step
        ep_relative = epoch - ep_start
        ep_tot = ep_end - ep_start
        return self.calc_linear_lr(lr_start, lr_end, ep_relative, batch_curr, ep_tot, batch_tot)

    def calc_linear_lr(self, lr_start, lr_end, epoch_curr, batch_curr, epoch_tot, batch_tot):
        step_tot = epoch_tot * batch_tot
        step_curr = epoch_curr * batch_tot + batch_curr
        step_size = (lr_end - lr_start)/step_tot
        return lr_start + step_curr * step_size

    def get_current_phase(self, epoch):
        for phase in reversed(self.phases):
            if (epoch >= phase['ep'][0]): return phase
        raise Exception('Epoch out of range')

    def get_lr(self, epoch, batch_curr, batch_tot):
        phase = self.get_current_phase(epoch)
        if len(phase['lr']) == 1: return phase['lr'][0] # constant learning rate
        return self.linear_phase_lr(phase, epoch, batch_curr, batch_tot)

    def update_lr(self, epoch, batch_num, batch_tot):
        lr = self.get_lr(epoch, batch_num, batch_tot)
        if self.current_lr == lr: return
        if ((batch_num == 1) or (batch_num == batch_tot)):
            log.event(f'Changing LR from {self.current_lr} to {lr}')

        self.current_lr = lr
        for param_group in self.optimizer.param_groups:
            param_group['lr'] = lr

        tb.log("sizes/lr", lr)
        tb.log("sizes/momentum", args.momentum)

# item() is a recent addition, so this helps with backward compatibility.
def to_python_float(t):
    if isinstance(t, (float, int)): return t
    if hasattr(t, 'item'): return t.item()
    else: return t[0]

def save_checkpoint(epoch, model, best_top5, optimizer, is_best=False, filename='checkpoint.pth.tar'):
    state = {
        'epoch': epoch+1, 'state_dict': model.state_dict(),
        'best_top5': best_top5, 'optimizer' : optimizer.state_dict(),
    }
    torch.save(state, filename)
    if is_best: shutil.copyfile(filename, f'{args.logdir}/{filename}')

def accuracy(output, target, topk=(1,)):
    """Computes the accuracy@k for the specified values of k"""
    corrrect_ks = correct(output, target, topk)
    batch_size = target.size(0)
    return [correct_k.float().mul_(100.0 / batch_size) for correct_k in corrrect_ks]

def correct(output, target, topk=(1,)):
    """Computes the accuracy@k for the specified values of k"""
    maxk = max(topk)
    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    correct = pred.eq(target.view(1, -1).expand_as(pred))
    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).sum(0, keepdim=True)
        res.append(correct_k)
    return res

def listify(p=None, q=None):
    if p is None: p=[]
    elif not isinstance(p, collections.Iterable): p=[p]
    n = q if type(q)==int else 1 if q is None else len(q)
    if len(p)==1: p = p * n
    return p

if __name__ == '__main__':
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=UserWarning)
            main()
        if not args.skip_auto_shutdown: os.system(f'sudo shutdown -h -P +{args.auto_shutdown_success_delay_mins}')
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        import traceback
        traceback.print_tb(exc_traceback, file=sys.stdout)
        log.event(e)
        # in case of exception, wait 2 hours before shutting down
        if not args.skip_auto_shutdown: os.system(f'sudo shutdown -h -P +{args.auto_shutdown_failure_delay_mins}')
    tb.close()


class PaymentHistory:
    def __init__(
        self,
        product_id,
        payment_method,
        purchase_date,
        coupon,
        price,
        product_type,
        is_refund,
        is_recurrent,
    ):
        self.coupon = coupon
        self.product_id = product_id
        self.payment_method = payment_method
        self.purchase_date = purchase_date
        self.price = price
        self.product_type = product_type
        self.is_refund = is_refund
        self.is_recurrent = is_recurrent
        self.title = ""


from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404, render, redirect, reverse
from django.contrib import messages
from services.models import Item

def view_bag(request):
    """ A view that renders the bag contents page """

    return render(request, 'bag/bag.html')

def add_to_bag(request, item_id):
    """ A view to add item to the bag"""
    if request.method == "POST":
        item = get_object_or_404(Item, pk=item_id)
        quantity = int(request.POST.get('quantity'))
        redirect_url = request.POST.get('redirect_url')
        bag = request.session.get('bag', {})
    if item_id in list(bag.keys()):
        bag[item_id] += quantity
        messages.success(request,
                         f"Updated {item.name} \
                         quantity to {bag[item_id]}")
    else:
        bag[item_id] = quantity
        messages.success(request,
                         f"{item.name} \
                         has been added to your bag.")

    request.session['bag'] = bag
    return redirect(redirect_url)

def update_bag(request, item_id):
    """ A view to update quantity of the item to the specified amount"""

    if request.method == 'POST':
        item = get_object_or_404(Item, pk=item_id)
        quantity = int(request.POST.get('item_quantity'))
        bag = request.session.get('bag', {})

        if quantity > 0:
            bag[item_id] = quantity
            messages.success(request,
                             f"Updated {item.name} \
                             quantity to {bag[item_id]}.")
        else:
            bag.pop(item_id)
            messages.success(request,
                             f"Removed {item.name} \
                             from your bag.")
        request.session["bag"] = bag
        return redirect(reverse("view_bag"))

def remove_bag(request, item_id):
    """ A view to remove item from the shopping bag"""
    try:
        if request.method == 'POST':
            item = get_object_or_404(Item, pk=item_id)
            bag = request.session.get('bag', {})

            bag.pop(item_id)
            messages.success(request,
                             f"Removed {item.name} \
                             from your bag.")

            request.session["bag"] = bag
            return HttpResponse(status=200)
    except Exception as e:
        messages.error(request, f"Error removing item: {e}")
        return HttpResponse(status=500)


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as waitfr
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium. webdriver. common. keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

import time,random,os, csv
from csv import reader, writer
import djponline.workaround.NotifyObj as Notify
from workaround.captchSc import captchaAdjust

#! ERROR
from selenium.common.exceptions import ElementClickInterceptedException,NoSuchElementException,WebDriverException
from selenium.common.exceptions import JavascriptException

# ! GECKO
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

# profile.set_preference("pdfjs.disabled", False)

# profile.set_preference("general.useragent.override", useragent)
# options.add_argument('--headless')

# options = webdriver.ChromeOptions()
# downloaddir = f"{os.getcwd()}/downloads"
# prefs = {"download.default_directory" : f"{downloaddir}"}
from selenium.webdriver.firefox.options import Options
options = Options()

options.add_argument("--start-maximized")

options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.download.manager.showWhenStarting", False)
options.set_preference("browser.download.dir", "./downloads")
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")
# prefs = {"profile.default_content_settings.popups": 0,
#             "download.default_directory": r"C:\\Users\\Rustacean\Desktop\\eform0\\", # IMPORTANT - ENDING SLASH V IMPORTANT
#             "directory_upgrade": True}

driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe", options=options)

def obtainVerificationCode(email, nama):
    emailnesia = email[:-14]
    driver.get(f"http://mailnesia.com/mailbox/{emailnesia}")
    driver.switch_to.window(driver.window_handles[0])
    # wait until
    while True:
        try:
            time.sleep(3)
            driver.refresh()
            WebDriverWait(driver, 10).until(waitfr.presence_of_element_located((By.CLASS_NAME, "emailheader")))
        except NoSuchElementException:
            print('waiting for confirmation email!')
            continue
        except WebDriverException:
            print('(time out) waiting for aktivasi email!')
            continue
        break

    Textid = driver.find_elements_by_css_selector('.emailheader')[0].get_attribute('id')
    latestMail = driver.find_elements_by_css_selector('.emailheader td:nth-child(4)')[0]
    textTitle = latestMail.get_attribute("textContent")

    print('text Content :', textTitle)
    print('element id is', Textid)

    # test if lupa password
    a = textTitle.find('Verifikasi')

    if int(a) >= 0:
        print('obtaining kode verifikasi...')
        # click #emailbody_(id)
        driver.execute_script(f"document.getElementById({str(Textid)}).click()")
        time.sleep(1)
        driver.switch_to.window(driver.window_handles[0]) # in case ads pop up
        time.sleep(1)
        # get text content of verifikasi
        y = driver.find_elements_by_tag_name('strong')
        kode = y[2].get_attribute("textContent")
        print('kode verikasi :', kode)

        print(f'verification for {nama} is obtained!')
        driver.delete_all_cookies()
        return kode
    else:
        print('kode verifikasi not found!')

# with open('./src/app.csv') as belumLapor:
#     readCsv = csv.DictReader(belumLapor, delimiter=',')
#     for line in readCsv:
#         print(line)

import pandas as pd

# after manually making a column for index in the first column [0]
# use index_col=[0] as a parameter in pd.read_csv
# to prevent unnamed : 0 column from being created on loc function

# wp = pd.read_csv('./src/indexed.csv', delimiter=',', index_col=[0] )
# wpdict = wp.to_dict()
# print(wp)
# print(wp.columns)
# print(wp['NAMA_WP'])
# print(wp[['NAMA_WP', 'EMAIL']])
# specific column and row (r,c)
# print(wp.iloc[0,2])

# if the process is interrupted, u may skip iteration within following range
done = range(0,21)

wp = pd.read_csv('./src/indexed.csv', delimiter=',', index_col=[0] )
## scrape 'kode verifikasi' for each email and write it in app3.csv
for index, row in wp.iterrows():
    if index in done:
        continue
    bruh = obtainVerificationCode(row['EMAIL'], row['NAMA_WP'])
    print('bruh is :', bruh)
    if len(bruh) > 1:
        wp.loc[index,'aktivasi'] = bruh
        wp.to_csv('./src/app3 (continue).csv', index=False)
    time.sleep(1)


import torch
import torch.nn as nn
'''
        随着网络层数的增加，通过多层的计算后参数可能开始出现过大或过小的情况
        这样可能导致学习过程出现异常，模型收敛过慢
        因此添加规范化层进行数值的规范化，使其特征数值在合理范围内
'''

class LayerNorm(nn.Module):
    def __init__(self,features,eps=1e-6):
        '''

        :param features:  代表词嵌入的维度
        :param eps:
        '''
        super(LayerNorm, self).__init__()
        self.a2 = nn.Parameter(torch.ones(features))
        self.b2 = nn.Parameter(torch.zeros(features))
        # 防止分母为0
        self.eps = eps

    def forward(self,x):
        # 对输入变量x求其最后一个维度的均值，并保持输出维度与输入维度一致
        mean = x.mean(-1,keepdim=True)
        # 接着再求最后一个维度的标准差
        std = x.std(-1,keepdim=True)
        # 然后就是根据规范化公式，用x减去均值除以标准差获得规范化的结果
        # 最后对结果乘以我们的缩放参数，即a2，*号代表同型点乘，即对应位置进行乘法操作，加上位移参数
        return self.a2 * (x-mean) /(std + self.eps) + self.b2

if __name__ == '__main__':
    features = d_model = 512
    eps = 1e-6

    x = torch.randn(3,4,512)
    ln = LayerNorm(features,eps)

    ln_r = ln(x)
    print(ln_r)
    print(ln_r.shape)


from typing import Iterable, Optional

from ..annotations.range import Range
from .string_tokenizer import StringTokenizer

class LineSegmentTokenizer(StringTokenizer):
    def tokenize_as_ranges(self, data: str, data_range: Optional[Range[int]] = None) -> Iterable[Range[int]]:
        if data_range is None:
            data_range = Range.create(0, len(data))
        line_start = data_range.start
        i = data_range.start
        while i < data_range.end:
            if data[i] == "\n" or data[i] == "\r":
                yield Range.create(line_start, i)
                if data[i] == "\r" and i + 1 < data_range.end and data[i + 1] == "\n":
                    i += 1
                line_start = i + 1
            i += 1

        if line_start < data_range.end:
            yield Range.create(line_start, data_range.end)


from django.urls import path
from . import views
from .views import (post_like)
from my_site import views

app_name = 'my_site'

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('tag/<slug:tag_slug>/',
         views.post_list, name='post_list_by_tag'),
    path('<int:id>/', views.post_detail, name='post_detail'),
    path('like/', views.post_like, name='like'),
    path('<int:post_id>/share/', views.post_share, name='post_share'),
    path('<int:post_id>/comment/', views.post_comment, name='post_comment'),
    path('search/', views.search, name='search'),
    path('contact/', views.ContactView.as_view(), name='contact'),

]


from django.test import TestCase
from backend.models import Person
import datetime

class TestEmail(TestCase):
    def setUp(self):
        self.person = Person(cn="Ondřej", sn="Nový", email="ondrej@example.org")
        self.addrstr = "test@example.org"
        self.addrtuple = ("Enric♥ Zìní", "enrico@example.org")
        self.date = datetime.datetime(2017, 6, 5, 4, 3, 2)
        self.args = {
            "from_email": self.person,
            "to": self.addrstr,
            "cc": [self.person, self.addrstr, self.addrtuple],
            "subject": "♥ Debian ♥",
            "date": self.date,
            "body": "Debian ♥ Debian",
        }

    def test_python(self):
        from process.email import build_python_message
        msg = build_python_message(**self.args)
        lines = msg.as_string().splitlines()
        lines = sorted(lines[:-2]) + lines[-2:]

        self.assertEquals(lines, [
            'Cc: =?utf-8?b?T25kxZllaiBOb3bDvQ==?= <ondrej@example.org>, test@example.org, =?utf-8?b?RW5yaWPimaUgWsOsbsOt?= <enrico@example.org>',
            'Content-Transfer-Encoding: base64',
            'Content-Type: text/plain; charset="utf-8"',
            'Date: Mon, 05 Jun 2017 04:03:02 -0000',
            'From: =?utf-8?b?T25kxZllaiBOb3bDvQ==?= <ondrej@example.org>',
            'MIME-Version: 1.0',
            'Subject: =?utf-8?b?4pmlIERlYmlhbiDimaU=?=',
            'To: test@example.org',
            '',
            'RGViaWFuIOKZpSBEZWJpYW4=',
        ])

    def test_django(self):
        from process.email import build_django_message
        msg = build_django_message(**self.args)
        lines = msg.message().as_string().splitlines()
        # Message-ID is generated nondeterministically: skip it for now
        lines = sorted(line for line in lines[:-2] if not line.startswith("Message-ID")) + lines[-2:]

        self.assertEquals(lines, [
            ' <ondrej@example.org>, test@example.org, =?utf-8?b?RW5yaWPimaU=?=,',
            ' enrico@example.org',
            'Cc: =?utf-8?b?PT91dGYtOD9iP1QyNWt4WmxsYWlCT2IzYkR2UT09Pz0=?=',
            'Content-Transfer-Encoding: base64',
            'Content-Type: text/plain; charset="utf-8"',
            'From: =?utf-8?b?T25kxZllaiBOb3bDvQ==?= <ondrej@example.org>',
            'MIME-Version: 1.0',
            'Subject: =?utf-8?b?4pmlIERlYmlhbiDimaU=?=',
            'To: test@example.org',
            'date: Mon, 05 Jun 2017 04:03:02 -0000',
            '',
            'RGViaWFuIOKZpSBEZWJpYW4=',
        ])


from django.shortcuts import render,HttpResponse
from .models import Blog
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

def blog(request):
    blog_list = Blog.objects.filter(allowed=True)
    if len(blog_list) == 0:
        return HttpResponse('
This page is empty (no content is posted) at this moment. Please come back later.
')
    else:
        last = len(blog_list)-1
    banner_temp = blog_list[last]

    top3=[]
    latest = []

    for i in blog_list:
            if i == banner_temp:
                continue
            if i.top3:
                top3.append(i)
            else:
                latest.append(i)
    top3.reverse()

    latest.reverse()
    paged = Paginator(latest,5)
    page = request.GET.get('page', 1)
    try:
        latest = paged.get_page(page)
    except PageNotAnInteger:
        latest = paged.get_page(1)
    except EmptyPage:
        latest = paged.get_page(paged.num_pages)

    banner = {'linkkey': banner_temp.linkkey, 'title': banner_temp.title, 'image': banner_temp.image,
              'subtitle': banner_temp.subtitle, 'datetime': banner_temp.datetime,
              'writer': banner_temp.writer, 'type': banner_temp.type}
    if len(banner) == 0:
        banner={'title':'This section is empty at this moment.'}
    if len(latest) == 0:
        latest=['This section is empty at this moment.']
    if len(top3) == 0:
        top3=['This section is empty at this moment.']
    title = 'Blog'
    sidetitle = ' Blog'
    logolink = 'blog/'
    context = { 'title':title, 'sidetitle':sidetitle, 'logolink':logolink
               ,'redirect_to':'blog','top3flinks':top3,'flinks':latest,
               'banner':banner}
    return render(request, 'blog.html',context=context)

def blogView(request):
    goto = request.GET.get('to','')
    obj = Blog.objects.filter(linkkey=goto, allowed=True)
    try:
        out = {'title': obj[0].title, 'image':obj[0].image,
                  'subtitle': obj[0].subtitle, 'datetime': obj[0].datetime,
                  'writer': obj[0].writer, 'type': obj[0].type, 'text':obj[0].text,
                   'safe': obj[0].allow_html, 'linkkey': obj[0].linkkey}
        title = obj[0].title
    except:
        out = {'subtitle':'blog not found.'}
        title = '404 blog not found'

    genre = obj[0].type
    recommended = Blog.objects.filter(allowed=True, type=genre,)
    recommended_list = []
    count = 0
    for i in recommended:
        if count == 4:
            break
        if i.linkkey == obj[0].linkkey:
            continue
        recommended_list.append(i)
        count = count + 1
    recommended_list.reverse()
    sidetitle = ' Blog'
    logolink = 'blog/'
    context = {'blog':out, 'title':title, 'sidetitle':sidetitle, 'logolink':logolink,
               'flinks':recommended_list}
    return render(request,'blogview.html',context=context)


import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import plotly.express as px

st.title("Campus Recruitment Analysis")
st.sidebar.header("options")

@st.cache
def load_data():
    df = pd.read_csv('dataset/Placement_Data_Full_Class.csv')
    return df

genre = st.sidebar.radio("",('About Project', 'View Dataset', 'Graph Analysis'))

if genre == "About Project":
    st.info('''A college campus recruitment system that consists of a student login, company login and an admin login. The project is beneficial for college students, various companies visiting the campus for recruitment and even the college placement officer. The software system allows the students to create their profiles and upload all their details including their marks onto the system. The admin can check each student details and can remove faulty accounts. The system also consists of a company login where various companies visiting the college can view a list of students in that college and also their respective resumes. The software system allows students to view a list of companies who have posted for vacancy. The admin has overall rights over the system and can moderate and delete any details not pertaining to college placement rules. The system handles student as well as company data and efficiently displays all this data to respective sides.
    pass''')

if  genre == "View Dataset":
    df = load_data()
    st.dataframe(df)

if genre == "Graph Analysis":
    df = load_data()

    choice = st.sidebar.selectbox("Select any one",("Gender Ratio","Placed and Unplaced","Degree_T and salary","degree_t and status"))

    if choice == "Gender Ratio":
        gender_ratio = df["gender"].value_counts()
        fig = px.pie(df,values=gender_ratio,names=df["gender"].unique(),title="Gender Ratio:Male vs Female")
        st.plotly_chart(fig)

    if choice == "Placed and Unplaced":
        fig,ax = plt.subplots(figsize=(12,6))
        fig = px.bar(df, x="gender",color="status")
        st.plotly_chart(fig)

    if choice == "Degree_T and salary":
        fig,ax = plt.subplots(figsize=(12,6))
        df.plot.scatter(x='degree_t',y='salary',title='Degrre_T and salary',c='salary',cmap='rainbow',ax=ax)
        st.pyplot(fig)

    if choice == "degree_t and status":
        df_copy = df.copy()
        fig = px.box(df, y="ssc_p",x="status",color = "status")
        st.plotly_chart(fig)


import os
import re
import argparse
import ast

errors_dict = {"S001": "Too long",
               "S002": "Indentation is not a multiple of four",
               "S003": "Unnecessary semicolon",
               "S004": "At least two spaces required before inline comments",
               "S005": "TODO found",
               "S006": "More than two blank lines preceding a code line",
               "S007": "Too many spaces after 'class' or 'func'",
               "S008": "Class name 'X===X' should use CamelCase",
               "S009": "Function name 'X===X' should use snake_case",
               "S010": "Argument name 'X===X' should be written in snake_case",
               "S011": "Variable 'X===X' should be written in snake_case",
               "S012": "The default argument value is mutable"}

exclude_list = ["__init__.py", "tests.py"]

class BestAnalyzer:

    def __init__(self, file_name):
        self.file_name = file_name
        self.curr_file = ""
        self.prev_line = ""
        self.blankline_cnt = 0
        self.errornum = 0
        self.filescount = 0
        self.log_data = {}

    def add_error(self, fname, linenum, code, wrongplacename=""):
        if (linenum and code) != "":
            if code in errors_dict.keys():
                self.log_data[self.errornum] = [fname, linenum, code, wrongplacename]
        self.errornum += 1

    def checklen(self, line, linenum):
        if len(line) > 79:
            self.add_error(self.curr_file, linenum, "S001")  # comment

    def check_comment_spaces(self, line, linenum):
        template = r"\S\s{0,1}#"
        if line.count("#") == 1:
            re_obj = re.search(template, line)
            if re_obj:
                self.add_error(self.curr_file, linenum, "S004")

    def check_ident_spaces(self, line, linenum):
        template = r"\S{1}"
        re_obj = re.split(template, line, maxsplit=1)
        if not len(re_obj[0]) % 4 == 0 and re_obj[0] != "\n" and line[0] != "#":
            self.add_error(self.curr_file, linenum, "S002")

    def check_semicolor(self, line, linenum):
        template = r"(\);+$|; {1,2}#)"
        re_obj = re.search(template, line)
        if re_obj:
            self.add_error(self.curr_file, linenum, "S003")

    def check_todo(self, line, linenum):
        template = "#{1,2}.+todo"
        re_obj = re.search(template, line, flags=re.IGNORECASE)
        if re_obj:
            self.add_error(self.curr_file, linenum, "S005")

    def check_blanklines(self, line, linenum):
        if line == "\n":
            self.blankline_cnt += 1
        else:
            if self.blankline_cnt > 2:
                self.add_error(self.curr_file, linenum, "S006")
            self.blankline_cnt = 0

    def check_classspaces(self, line, linenum):
        template = r"^class\s{2,}\w"
        re_obj = re.search(template, line)
        if re_obj:
            self.add_error(self.curr_file, linenum, "S007")

    def check_defspaces(self, line, linenum):
        template = r"def\s{2,}\w"
        re_obj = re.search(template, line)
        if re_obj:
            self.add_error(self.curr_file, linenum, "S007")

    def check_classcamels(self, line, linenum):
        template = r"^class\s{1,}[^A-Z][a-z]+([A-Z]|)"
        re_obj = re.search(template, line)
        if re_obj:
            self.add_error(self.curr_file, linenum, "S008")

    def check_functsnake(self, line, linenum):
        template = r"def ([A-Z]|[a-z]+[A-Z])"
        re_obj = re.search(template, line)
        if re_obj:
            self.add_error(self.curr_file, linenum, "S009")

    def ast_funsnake(self, tree):
        """ S009 : Check if function snake_case """
        # print(ast.dump(tree))
        for item in ast.walk(tree):
            if isinstance(item, ast.FunctionDef) and item.name[0:2] != "__":
                template = r"_?[a-z]{1,}(_?[a-z]{1,}){0,}"
                re_obj = re.match(template, item.name)
                if not re_obj:
                    self.add_error(self.curr_file, item.lineno, "S009", item.name)

    def ast_argsnakecase(self, tree):
        """ S010 : Check if func arg is snake_case """
        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                for elem in node.args.args:
                    if not elem.arg.islower():
                        self.add_error(self.curr_file, elem.lineno, "S010", elem.arg)

    def ast_varsnakecase(self, tree):
        """ S011 : Check if var is snake_case """
        names_list = []
        for node in ast.walk(tree):
            if isinstance(node, ast.Name):
                if node.id not in names_list:
                    names_list.append(node.id)
                    if not node.id.islower():
                        self.add_error(self.curr_file, node.lineno, "S011", node.id)

    def ast_argmutable(self, tree):
        """ S012: Check default argument value is mutable """
        var_list = []

        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                for elem in node.args.args:
                    if elem.arg != "self":
                        var_list.append(elem.arg)
                for cnt, elem in enumerate(node.args.defaults):
                    if isinstance(elem, (ast.List, ast.Dict, ast.Set)):
                        self.add_error(self.curr_file, elem.lineno, "S012", var_list[cnt])
                var_list.clear()

    def check_code_classic(self, fp):  # check via RegExp
        linenum = 1
        for line in fp.readlines():
            self.checklen(line, linenum)
            self.check_comment_spaces(line, linenum)
            self.check_ident_spaces(line, linenum)
            self.check_semicolor(line, linenum)
            self.check_todo(line, linenum)
            self.check_blanklines(line, linenum)
            self.check_classspaces(line, linenum)
            self.check_defspaces(line, linenum)
            self.check_classcamels(line, linenum)
            linenum += 1

    def check_code_ast(self, tree):  # check via AST lib
        self.ast_funsnake(tree)
        self.ast_argsnakecase(tree)
        self.ast_argmutable(tree)
        self.ast_varsnakecase(tree)

    def checkcode(self):
        temp_flist = []
        if not os.path.exists(self.file_name):
            raise FileNotFoundError

        if os.path.isdir(self.file_name):
            temp_flist = [self.file_name + '\\' + fname for fname in os.listdir(self.file_name)
                          if fname.find(".py") > 1 and fname not in exclude_list]

        elif os.path.isfile(self.file_name):
            temp_flist = [self.file_name]

        for one_file in temp_flist:
            if os.path.getsize(one_file) > 0:
                self.curr_file = one_file.lower()
                self.filescount += 1
                # classic RegExp check
                with open(one_file) as fp:
                    self.check_code_classic(fp)

                # advanced AST check
                with open(one_file) as fp:
                    tree = ast.parse(fp.read())
                    self.check_code_ast(tree)

    def printallerrors(self):
        self.log_data = list(sorted(self.log_data.items(), key=lambda x: (x[1][0], x[1][1], x[1][2])))
        for elem in self.log_data:
            log_string = f"{elem[1][0]}: Line {elem[1][1]}: {elem[1][2]} {errors_dict[elem[1][2]]}"
            print(log_string.replace("X===X", elem[1][3]))

    def print_statistics(self):
        """Print statistic, error count and files count"""
        print("Total error count:", len(self.log_data), "in", self.filescount, "file(s)")

arg_pars = argparse.ArgumentParser("The simplest Python code analyzer ever")
arg_pars.add_argument('file_directory', help='File or directory name to check')
user_argums = arg_pars.parse_args()

my_analyzer = BestAnalyzer(user_argums.file_directory)
my_analyzer.checkcode()
my_analyzer.printallerrors()


import pandas as pd

from connect import service

def print_response(response):
    list = []
    # get report data
    for report in response.get('reports', []):
        # set column headers
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])

        for row in rows:
            # create dict for each row
            dict = {}
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])

            # fill dict with dimension header (key) and dimension value (value)
            for header, dimension in zip(dimensionHeaders, dimensions):
                dict[header] = dimension

            # fill dict with metric header (key) and metric value (value)
            for i, values in enumerate(dateRangeValues):
                for metric, value in zip(metricHeaders, values.get('values')):
                    # set int as int, float a float
                    if '.' in value or '.' in value:
                        dict[metric.get('name')] = float(value)
                    else:
                        dict[metric.get('name')] = int(value)

            list.append(dict)

        df = pd.DataFrame(list)
        return df

def get_report(analytics, start_date, end_date, view_id, metrics, dimensions, filter):
    return analytics.reports().batchGet(
        body={
            'reportRequests': [
                {
                    'viewId': view_id,
                    'dateRanges': [{'startDate': start_date, 'endDate': end_date}],
                    'metrics': metrics,
                    'dimensions': dimensions,
                    'pageSize': 10000,
                    'filtersExpression': filter
                }]
        }
    ).execute()

def return_ga_data(start_date, end_date, view_id, metrics, dimensions, filter):
    return print_response(get_report(service, start_date, end_date, view_id, metrics, dimensions, filter))

def get_report_df(view_ids, metrics, dimensions, filter):
    df = []

    for account_id, account_name in view_ids:
        tmp_df = return_ga_data(
            start_date='yesterday',
            end_date='today',
            view_id=account_id,
            metrics=metrics,
            dimensions=dimensions,
            filter=filter
        )

        tmp_df['account'] = account_name
        df.append(tmp_df)

    report = pd.concat(df, ignore_index=True)
    report.columns = map(str.lower, list(report.columns.str.replace('ga:', '')))

    return report


#!/usr/bin/env python3
"""
Author : Emmanuel Gonzalez
Date   : 2021-09-13
Purpose: Download gantry data
"""

import argparse
import os
import sys
import subprocess as sp
import re
from datetime import datetime

# --------------------------------------------------
def get_args():
    """Get command-line arguments"""

    parser = argparse.ArgumentParser(
        description='iRODS data downloader',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('-sea',
                        '--season',
                        help='Season to download. Choices are 10, 11, or 12.',
                        metavar='str',
                        type=str,
                        required=True,
                        choices=['10', '11', '12', '13', '14', '15'])

    parser.add_argument('-sen',
                        '--sensor',
                        help='Sensor to download. Choices are FLIR, PS2, RGB, or 3D.',
                        metavar='str',
                        type=str,
                        required=True,
                        choices=['FLIR', 'PS2', 'RGB', '3D'])

    parser.add_argument('-lev',
                        '--level',
                        help='Data level to download. Choices are 0, 1, 2, 3, or 4.',
                        metavar='str',
                        type=str,
                        required=True,
                        choices=['0', '1', '2', '3', '4'])

    parser.add_argument('-seq',
                        '--sequence',
                        help='Sequence to grep. For example "_ortho.tif".',
                        metavar='str',
                        type=str,
                        required=True)

    parser.add_argument('-out',
                        '--outdir',
                        help='Output directory.',
                        metavar='str',
                        type=str,
                        default='irods_data')

    parser.add_argument('-c',
                        '--crop',
                        help='Crop name.',
                        metavar='str',
                        type=str,
                        default=None)

    return parser.parse_args()

# --------------------------------------------------
def get_dict():

    irods_dict = {
        'server_path': '/iplant/home/shared/phytooracle/',

        'season': {
            '10': 'season_10_lettuce_yr_2020',
            '11': 'season_11_sorghum_yr_2020',
            '12': 'season_12_sorghum_soybean_sunflower_tepary_yr_2021',
            '13': 'season_13_lettuce_yr_2022',
            '14': 'season_14_sorghum_yr_2022',
            '15': 'season_15_lettuce_yr_2022',
            '16': 'season_16_sorghum_yr_2023'
        },

        'level': {
            '0': 'level_0',
            '1': 'level_1',
            '2': 'level_2',
            '3': 'level_3',
            '4': 'level_4'
        },

        'sensor': {
            'FLIR': 'flirIrCamera',
            'PS2': 'ps2Top',
            'RGB': 'stereoTop',
            '3D': 'scanner3DTop'
        }
    }

    return irods_dict

# --------------------------------------------------
def get_file_list(data_path, sequence):

    result = sp.run(f'ilocate {os.path.join(data_path, "%", f"{sequence}")}', stdout=sp.PIPE, shell=True)
    files = result.stdout.decode('utf-8').split('\n')

    return files

# --------------------------------------------------
def download_files(item, out_path):

    # for item in files:

    os.chdir(out_path)

    if not 'deprecated' in item:

        try:
            item = os.path.normpath(item)

            try:

                match_str = re.search(r'\d{4}-\d{2}-\d{2}__\d{2}-\d{2}-\d{2}-\d{3}', item)
                date = match_str.group()
                # date = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
            except:
                match_str = re.search(r'\d{4}-\d{2}-\d{2}', item)
                date = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
                date = str(date)

            print(f"Found item {item}.")

            if not os.path.isdir(date):
                print(f"Making directory {date}.")
                os.makedirs(date)

            if '.tar.gz' in item:
                print(f"Downloading {item}.")
                sp.call(f'iget -KPVT {item}', shell=True)

                print(f"Extracting {item}.")
                ret = sp.call(f'tar -xzvf {os.path.basename(item)} -C {date}', shell=True)

                if ret != 0:
                    print(f"Reattempting to extract {item}.")
                    sp.call(f'tar -xvf {os.path.basename(item)} -C {date}', shell=True)

                sp.call(f'rm {os.path.basename(item)}', shell=True)

            elif '.tar' in item:
                print(f"Downloading {item}.")
                sp.call(f'iget -KPVT {item}', shell=True)

                print(f"Extracting {item}.")
                sp.call(f'tar -xvf {os.path.basename(item)} -C {date}', shell=True)
                sp.call(f'rm {os.path.basename(item)}', shell=True)

            else:
                os.chdir(date)
                sp.call(f'iget -KPVT {item}', shell=True)

        except:
            pass

# --------------------------------------------------
def main():
    """Download data here"""
    args = get_args()
    cwd = os.getcwd()

    # Get dictionary to pull path components.
    irods_dict = get_dict()

    # Create iRODS path from components.
    data_path = os.path.join(irods_dict['server_path'], irods_dict['season'][args.season], irods_dict['level'][args.level], irods_dict['sensor'][args.sensor])
    if args.crop:
        data_path = os.path.join(irods_dict['server_path'], irods_dict['season'][args.season], irods_dict['level'][args.level], irods_dict['sensor'][args.sensor], args.crop)
    # Get list of all files that match a character sequence.
    print(f'Searching for files matching "{os.path.join(data_path, args.sequence)}". Note: This process may take a few minutes.')
    files = get_file_list(data_path, args.sequence)
    print('Matches obtained.')

    # Prepare to download data.
    out_path = os.path.join(args.outdir, irods_dict['season'][args.season], irods_dict['sensor'][args.sensor])
    if not os.path.isdir(out_path):
        os.makedirs(out_path)

    os.chdir(out_path)

    # Download files.
    for item in files:
        # print(f'Downloading {item}.')
        download_files(item=item, out_path=os.path.join(cwd, out_path))

# --------------------------------------------------
if __name__ == '__main__':
    main()


import json

output = open("output.py", "w")
nations = open("country_data.json", "r")

data = json.load(nations)
x = 0

for country in data:
    y = x + 1
    output.write(
        f'R{y} = ttk.Radiobutton(second_frame, text="{country}", variable=var, value="{country}", command=sel)\n'
    )
    output.write(f"R{y}.pack(anchor=tk.W)\n")
    x = x + 1

"""
R1 = ttk.Radiobutton(root, text="Andorra", variable=var, value="Andorra", command=sel)
R1.pack(anchor=tk.W)
"""


# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 20:49:21 2021

@author: pon01
"""

# capitals = {'France': 'Paris', 'Italy': 'Rome', 'Japan':'Kyoto'}

# x = input('The capital of ' )

# if x in capitals.keys(): #x가 capitals의 key값중 하나라면
#     print('is ', capitals[x]) #capitals의 key x에 해당하는 value를 출력
# else:
#     print("")

# number_to_word = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 10: 'ten'}
# word_to_number = {w: d for d, w in number_to_word.items()}
# word_to_number = {w: d for d, w in number_to_word.items() if d < 10}

gen_code_keys = (lambda book, plain_text:({c: str(book.find(c)) for c in plain_text}))
encoder = (lambda code_keys, plain_text: ''.join(['*' + code_keys[c] for c in plain_text])[1:])
encrypt = (lambda book, plain_text:encoder(gen_code_keys(book, plain_text), plain_text))

decoder = (lambda decode_keys, cipher_text: ''.join([decode_keys[i] for i in cipher_text.split('*')]))
gen_decode_keys = (lambda book, cipher_text: {s: book[int(s)] for s in cipher_text.split('*')})

book = 'In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing.jqxz'

plain_text = 'no is no'
code_keys = gen_code_keys(book, plain_text)
encoding = encoder(code_keys, plain_text)
encoding2 = encrypt(book, plain_text)
cipher_text = '22*13*33*137*59*11*23*11*1*57*6*13*1*2*6*57*2*6*1*22*13*33*137*59*11*23*11*1*57*6*173*7*11'
decode_keys = gen_decode_keys(book, cipher_text)
decoding = decoder(decode_keys, cipher_text)

x = []
for i in cipher_text.split('*'):
    x.append(decode_keys[i])
x="".join(x)


from eval import eval, MovingAverage
from config import FLAGS, COMET_EXPERIMENT
from model_factory import create_model

from pprint import pprint
import time
import torch

def train(train_data, val_data, saver):
    train_data.init_node_feats(FLAGS.init_type, FLAGS.device)
    val_data.init_node_feats(FLAGS.init_type, FLAGS.device)
    model = create_model(train_data)
    model = model.to(FLAGS.device)
    pytorch_total_params = sum(p.numel() for p in model.parameters())
    print("Number params: ", pytorch_total_params)
    moving_avg = MovingAverage(FLAGS.validation_window_size, FLAGS.validation_metric != 'loss')
    pyg_graph = train_data.get_pyg_graph(FLAGS.device)
    optimizer = torch.optim.Adam(model.parameters(), lr=FLAGS.lr, )

    for epoch in range(FLAGS.num_epochs):
        t = time.time()
        model.train()
        model.zero_grad()
        loss, preds_train = model(pyg_graph, train_data)
        loss.backward()
        optimizer.step()
        loss = loss.item()
        if COMET_EXPERIMENT:
            COMET_EXPERIMENT.log_metric("loss", loss, epoch + 1)
        with torch.no_grad():
            val_loss, preds_val = model(pyg_graph, val_data)
            val_loss = val_loss.item()
            eval_res_val = eval(preds_val, val_data)
            print("Epoch: {:04d}, Train Loss: {:.5f}, Time: {:.5f}".format(epoch, loss, time.time() - t))
            print("Val Loss: {:.5f}".format(val_loss))
            print("Val Results: ...")
            pprint(eval_res_val)
            eval_res_val["loss"] = val_loss
            if COMET_EXPERIMENT:
                COMET_EXPERIMENT.log_metrics(eval_res_val, prefix="validation", step=epoch+1)

            if len(moving_avg.results) == 0 or moving_avg.best_result(eval_res_val[FLAGS.validation_metric]):
                saver.save_trained_model(model, epoch + 1)
            moving_avg.add_to_moving_avg(eval_res_val[FLAGS.validation_metric])
            if moving_avg.stop():
                break
    best_model = saver.load_trained_model(train_data)
    return best_model, model


from typing import List

from ..classes.WarCraft3CollisionShape import WarCraft3CollisionShape
from . import binary_reader
from .parse_node import parse_node
from ..classes.WarCraft3Model import WarCraft3Model
from ..classes.WarCraft3Node import WarCraft3Node

def parse_collision_shapes(data: bytes):
    data_size = len(data)
    r = binary_reader.Reader(data)

    nodes: List[WarCraft3Node] = []
    while r.offset < data_size:

        collision_shape = WarCraft3CollisionShape()
        parse_node(r, collision_shape)
        collision_type = r.getf('<I')[0]

        if collision_type == 0:
            vertices_count = 2
        elif collision_type == 2:
            vertices_count = 1
        else:
            raise Exception('UNSUPPORTED COLLISION SHAPE TYPE:', collision_type)

        for _ in range(vertices_count):
            position = r.getf('<3f')

        if collision_type == 2:
            bounds_radius = r.getf('<f')[0]

        nodes.append(collision_shape)
    return nodes


from multiprocessing import Pool, Manager
import numpy as np
import numpy.linalg as la
import cvxpy as cp
from pdb import set_trace
from sympy import expand, symbols
import tqdm
from sympy.utilities.iterables import multiset_permutations

def parse(coeffdict):
  res = []
  coeff0 = None

  for key in coeffdict:
    if key[0] == '1':
      coeff0 = coeffdict[key]
    else:
      strlen = len(key)
      i = 0
      resinner = []
      # walk through key
      while(i < strlen):
        # check if new monomial
        if key[i] == 'x':
          i += 1
          num = ''
          exponent = ''
          # extract index
          while(i < strlen and key[i] != '*'):
            num += key[i]
            i += 1
          # check if reached the end of key
          if i == strlen:
            exponent = '1'
            pass
          # check next character
          elif key[i] == '*':
            i += 1
            # check next character. if true, then there is an exponent.
            if key[i] == '*':
              i += 1
              # extract exponent
              while(i < strlen and key[i] != '*'):
                exponent += key[i]
                i += 1
              i += 1
            # if there was no exponent
            else:
              exponent = '1'
        resinner.append((num, exponent, key))
      res.append(resinner)
  return res, coeff0

def worker_allpass(inputs):
  E, H1all, H2all, params, ind = inputs
  Mr,Mb,Nu,Mu,sigma1, sigma2, Plist = params
  nsamp, nP = ind
  Pt = Pr =  Plist[nP]
  sumrate_trials = []
  H1 = H1all[nsamp]
  H2_original = H2all[nsamp]

  for ntrial in range(10):
    Pi = np.eye(Nu)[np.random.permutation(Nu)]
    H2 = Pi@H2_original
    Qeq, Geq = la.qr((H2@H1).T.conj(), 'complete')

    Qeq = Qeq.T.conj()
    Geq = Geq.T.conj()

    Geq_diag = np.abs(np.diag(Geq))**2
    # A = Qeq@(H1.T.conj())
    A = H1@(Qeq.T.conj())
    AHAdiag = np.array([np.linalg.norm(aa)**2 for aa in A.T])

    h = np.array([np.linalg.norm(hi2)**2*sigma1**2 for hi2 in H2])

    p = cp.Variable(Mu, pos=True)
    gs = cp.Variable(pos=True)
    # set_trace()
    C1 = [gs*AHAdiag@p + Mr*sigma1**2*gs <= Pr]
    C2 = [cp.sum(p) <= Pt]

    a  = h[:Mu]
    x = symbols('x')
    exp = 1
    for aa in a:
      exp = exp * (aa + sigma2**2*x)
    expanded = expand(exp)
    coeffdictsym = expanded.as_coefficients_dict()
    coeffdict = {}
    for i in coeffdictsym:
      coeffdict[str(i)] = coeffdictsym[i]
    res, coeff0 = parse(coeffdict)

    if coeff0 is not None:
      x = coeff0
    else:
      x = 0
    # set_trace()
    for r in res:
      term = 1
      for rr in r:
        # set_trace()
        # term *= (coeffdict[rr[2]])**(1/len(r))*cp.power(k[int(rr[0])],-int(rr[1]))
        term *= cp.power(gs,-int(rr[1]))
      x += term * coeffdict[rr[2]]

    # coeffs = np.array([float(coeffdict[1])] + [float(coeffdict[x**k]) for k in range(1, len(a)+1)])
    # set_trace()
    # x = coeffs[0]
    # for i in range(1, len(coeffs)):
    #   x += coeffs[i]*cp.power(gs,-i)

    obj = x*cp.prod(cp.inv_pos(p))*np.prod(1/Geq_diag[:Mu])
    constraints = C1+C2
    prob = cp.Problem(cp.Minimize(obj), constraints)
    prob.solve(gp=True, solver='ECOS')
    gs_opt = gs.value
    p_opt = p.value
    d_opt = Geq_diag * gs_opt
    v_opt = gs_opt*h[:Mu] + sigma2**2

    sumrate = 0.5 * np.sum([np.log2(1+di*pi/vi) for di,pi,vi in zip(d_opt,p_opt,v_opt)])
    # print(sumrate)

    W = gs_opt*np.eye(Mr)
    F = Qeq.T.conj() @ np.diag(np.sqrt(p_opt))
    for i in range(Mu):
      indexes = list(range(Mu))
      indexes.pop(i)
      interference = sum([np.abs(H2[i].T.conj()@W@H1@F[:,l])**2 for l in indexes])
      v_opt[i] += interference

    sumrate = 0.5 * np.sum([np.log2(1+di*pi/vi) for di,pi,vi in zip(d_opt,p_opt,v_opt)])
    # print(sumrate)
    # set_trace()

    sumrate_trials.append(sumrate)

  sumrate_max = np.max(sumrate_trials)

  E.append({'ind':ind, 'sumrate':sumrate_max})
  # print(len(E))

def worker_svd(inputs):
  E, H1all, H2all, params, ind = inputs
  Mr,Mb,Nu,Mu,sigma1, sigma2, Plist = params
  nsamp, nP = ind
  Pt = Pr =  Plist[nP]
  sumrate_trials = []
  H1 = H1all[nsamp]
  H2_original = H2all[nsamp]

  # Q = cp.Variable(shape=(H1.shape[1],H1.shape[1]), PSD=True)
  # obj = cp.log_det(np.eye(H1.shape[0]) + (1/sigma1**2)*H1@Q@(H1.T.conj()))
  # constraints = [cp.trace(Q) <= Pt]
  # prob = cp.Problem(cp.Maximize(obj), constraints)
  # prob.solve()
  # upperbound = prob.value

  w,v = la.eig(H1.T.conj()@H1)
  q = np.zeros(w.shape[0])
  mu = [0,1000]
  while(mu[1]-mu[0]>1e-2):
    q = np.clip(np.mean(mu) - 1/w, 0, None)
    if sum(q) > Pt:
      mu[1] = np.mean(mu)
    else:
      mu[0] = np.mean(mu)
    # print(mu)
  upperbound = np.log2(la.det(np.eye(H1.shape[0]) + (1/sigma1**2)*H1@np.diag(q)@(H1.T.conj()))).real/2
  # print(upperbound/2)
  # print(sum(np.clip(np.log2(mu[0]*w), 0, None)).real/2)
  # set_trace()

  # set_trace()

  for ntrial in range(10):
  # for perm in multiset_permutations(np.arange(Nu)):
    Pi = np.eye(Nu)[np.random.permutation(Nu)]
    H2 = Pi@H2_original
    # Pi = np.eye(Nu)[perm]
    Q2, G2 = la.qr(H2.T.conj())
    Q2 = Q2.T.conj()
    G2 = G2.T.conj()

    G2_diag = np.abs(np.diag(G2))**2

    U, S, Vh = la.svd(H1)
    # A = Qeq@(H1.T.conj())
    # A = H1@(Qeq.T.conj())
    # AHAdiag = np.array([np.linalg.norm(aa)**2 for aa in A.T])

    # h = np.array([np.linalg.norm(hi2)**2*sigma1**2 for hi2 in H2])

    p = cp.Variable(Mu, pos=True)
    k = cp.Variable(Mu, pos=True)

    C1 = [k @ (cp.multiply(S,p) + sigma1**2) <= Pr]
    C2 = [cp.sum(p) <= Pt]
    # set_trace()
    nuG = 1/(S**2*G2_diag[:Mu])
    # b = nuG * sigma2**2
    x = symbols('x:'+str(Mu))
    exp = 1
    for i in range(Mu):
      expsum = 0
      for j in range(i+1):
        expsum += np.abs(G2[i,j])**2 * sigma1**2 + x[j] * sigma2**2
      exp = exp * expsum

    expanded = expand(exp)
    coeffdictsym = expanded.as_coefficients_dict()
    coeffdict = {}
    for i in coeffdictsym:
      coeffdict[str(i)] = coeffdictsym[i]
    # coeffs = np.array([float(coeffdict[1])] + [float(coeffdict[x**k]) for k in range(1, len(a)+1)])

    res, coeff0 = parse(coeffdict)

    if coeff0 is not None:
      x = coeff0
    else:
      x = 0

    for r in res:
      term = 1
      for rr in r:
        # set_trace()
        # term *= (coeffdict[rr[2]])**(1/len(r))*cp.power(k[int(rr[0])],-int(rr[1]))
        term *= cp.power(k[int(rr[0])],-int(rr[1]))
      x += term * coeffdict[rr[2]]
      # set_trace()
      # print(term)
      # print(coeffdict[rr[2]])
      # else:
      #   set_trace()
      #   x += coeffs[r[2]]*cp.power(k[int(r[0])],-int(r[1]))
    # print('x',x)
    obj = x*cp.prod(cp.inv_pos(p)) * np.prod(1/(S*G2_diag[:Mu]))
    # print(obj.is_dgp())
    # set_trace()
    constraints = C1+C2
    prob = cp.Problem(cp.Minimize(obj), constraints)
    prob.solve(gp=True, solver='ECOS')
    # set_trace()
    k_opt = k.value
    p_opt = p.value
    d_opt = G2_diag[:Mu] * k_opt * S
    v_opt = []
    for i in range(Mu):
      v_opt.append(sum([np.abs(G2[i,j])**2 * k_opt[j] * sigma1**2 for j in range(i+1)]) + sigma2**2)

    # set_trace()
    sumrate = 0.5 * np.sum([np.log2(1+di*pi/vi) for di,pi,vi in zip(d_opt,p_opt,v_opt)])
    # print(sumrate)

    # set_trace()
    W = Q2.T.conj()[:,:Mu] @ np.diag(k_opt) @ (U.T.conj()[:Mu])
    F = Vh.T.conj() @ np.diag(np.sqrt(p_opt))
    v_opt = np.zeros(Mu)
    for i in range(Mu):
      indexes = list(range(Mu))
      indexes.pop(i)
      interference = sum([np.abs(H2[i].T.conj()@W@H1@F[:,l])**2 for l in indexes])
      v_opt[i] += interference
      v_opt[i] += np.linalg.norm(H2[i].T.conj()@W)**2 * sigma1**2 + sigma2**2
    sumrate = 0.5 * np.sum([np.log2(1+di*pi/vi) for di,pi,vi in zip(d_opt,p_opt,v_opt)])

    # print(sumrate)
    # set_trace()

    sumrate_trials.append(sumrate)

  sumrate_max = np.max(sumrate_trials)

  E.append({'ind':ind, 'sumrate':sumrate_max, 'upperbound':upperbound})
  # print(sumrate_max)

def run(Mr, Mb, Nu, method, single):
  # if M is not None:
  #   Mr = Mb = M
  # else:
  #   Mr = 3 # number of relay antennas
  #   Mb = 2 # number of BS antennas

  # Nu = 5 # number of users
  Mu = np.min([Nu,Mb,Mr])
  sigma1 = sigma2 = 1

  numP = 6
  Nsamp = 100

  Plist = np.logspace(0.5,3,numP)

  # numP = 1
  # Plist = [10**2]
  params = (Mr,Mb,Nu,Mu,sigma1,sigma2,Plist)

  H1all = (np.random.randn(Nsamp, Mr, Mb) + 1j*np.random.randn(Nsamp, Mr, Mb))/np.sqrt(2)
  H2all = (np.random.randn(Nsamp, Nu, Mr) + 1j*np.random.randn(Nsamp, Nu, Mr))/np.sqrt(2)

  H1mp = []
  H2mp = []

  ind = []
  for i in range(Nsamp):
    for j in range(numP):
      ind.append((i,j))
      H1mp.append(H1all[i])
      H2mp.append(H2all[i])

  manager = Manager()
  E = manager.list()
  inputs = list(zip([E]*Nsamp*numP, [H1all]*Nsamp*numP, [H2all]*Nsamp*numP, [params]*Nsamp*numP, ind))

  if single == True:
    worker_svd(inputs[-1])
    worker_allpass(inputs[-1])
    return

  with Pool() as pool:
    if method == 'svd':
      for _ in tqdm.tqdm(pool.imap_unordered(worker_svd, inputs), total=len(inputs)):
        pass
    elif method == 'allpass':
      for _ in tqdm.tqdm(pool.imap_unordered(worker_allpass, inputs), total=len(inputs)):
        pass

  results = np.empty((numP, Nsamp))
  upperbound = np.empty((numP, Nsamp))
  for e in E:
    nsamp, nP = e['ind']
    results[nP, nsamp] = e['sumrate']
    if method == 'svd':
      upperbound[nP,nsamp] = e['upperbound']

  print(method, np.mean(results, axis=1))
  if method == 'svd':
    print('upper bound', np.mean(upperbound, axis=1))

  return np.mean(results, axis=1)

if __name__ == '__main__':
  # run('single')
  res = []

  # M = None
  Nu = 5
  for method in ['svd','allpass']:
  # for method in ['svd']:
    # for M in [2,3,4,5]:
    # for Nu in [2,5,10,15,20]:
      print('Nu =', Nu)
      res.append(run(Mr=3, Mb=2, Nu=Nu, method=method, single=False))
  print(method)
  print(res)


import numpy as np
import matplotlib.pyplot as plt

def calculate_ocv(soc):
    """
    Calculate the open circuit voltage (ocv) based on state of charge (soc) and given coefficients (c).

    Parameters:
    soc (numpy.ndarray or float): The state of charge. This can be a single float value or a numpy array.
    c (numpy.ndarray): The array of coefficients for the polynomial.

    Returns:
    numpy.ndarray or float: The open circuit voltage (ocv). This will be a numpy array if soc is a numpy array,
    otherwise a single float value.
    """
    c = np.array([-1.2918e+00, 9.6896e+00, -2.1023e+01, 1.9749e+01, -8.0028e+00, 1.6362e+00, 3.4722e+00])
    return sum(coefficient * soc ** power for power, coefficient in enumerate(c[::-1]))

# Coefficients for the polynomial
# c = np.array([-1.2918e+00, 9.6896e+00, -2.1023e+01, 1.9749e+01, -8.0028e+00, 1.6362e+00, 3.4722e+00])

# Create an array of soc values
soc_values = np.linspace(-0.1, 1.1, 200)

# Calculate ocv values for the array of soc values
ocv_values = calculate_ocv(soc_values)

# Uncomment below lines to plot soc_values vs ocv_values
# plt.plot(soc_values, ocv_values)
# plt.show()

# Calculate ocv for a single soc value
soc = 0.7
ocv = calculate_ocv(soc)
print(ocv)

# import numpy as np
# import matplotlib.pyplot as plt

# c = np.array([-1.2918e+00,
#                 9.6896e+00,
#                 -2.1023e+01,
#                 1.9749e+01,
#                 -8.0028e+00,
#                 1.6362e+00,
#                 3.4722e+00])

# soc = np.linspace(-0.1, 1.1, 200)
# ocv = c[0] * soc ** 6 + \
#         c[1] * soc ** 5 + \
#         c[2] * soc ** 4 + \
#         c[3] * soc ** 3 + \
#         c[4] * soc ** 2 + \
#         c[5] * soc ** 1 + \
#         c[6] * soc ** 0
# # plt.plot(soc, ocv)
# # plt.show()

# soc = 0.7
# ocv = c[0] * soc ** 6 + \
#         c[1] * soc ** 5 + \
#         c[2] * soc ** 4 + \
#         c[3] * soc ** 3 + \
#         c[4] * soc ** 2 + \
#         c[5] * soc ** 1 + \
#         c[6] * soc ** 0
# print(ocv)


#coerente > 10
food_list10 = ['water', 'mellon', 'apple', 'pizza', 'chips', 'meat', 'chicken', 'potato', 'milk', 'chocolate']
#coerente > 50
food_list50 = ['water', 'mellon', 'apple', 'pizza', 'chips', 'meat', 'chicken', 'potato', 'milk', 'chocolate',
               'seafood','nuts', 'rice', 'beans', 'legume', 'tofu', 'yogurt', 'cheese', 'bread', 'pasta',
               'cake', 'noodles', 'beef', 'beer', 'vegetables', 'pie', 'tomato', 'mushroom', 'kebab', 'pork',
                'orange', 'lemon', 'banana', 'butter', 'oil', 'olive', 'grapes', 'plum', 'onion', 'hamburger',
               'bacon', 'steak', 'porridge', 'fish', 'chips', 'lobster', 'chips', 'candy','cream', 'soup']
#coerente > 2
electronics_list2 = ['phone', 'computer']

#non coerente > 5
mix5 = ['chocolate', 'phone', 'politician', 'new jersey', 'show']

#non coerente > 20
mix20 = ['baker', 'mechanician', 'worker', 'clerk', 'politician', 'pilot', 'school', 'university', 'academy', 'exam',
         'teacher', 'student', 'master', 'rejection', 'sadness', 'disappointment', 'anger', 'take',  'table',  'every',
         'time', 'watch', 'tablet', 'camera', 'console', 'exam', 'pizza', 'chips', 'tofu', 'yogurt', 'cheese', 'bread',
         'room', 'one', 'vegas', 'water', 'mellon', 'apple', 'sunshine', 'sun', 'moon', 'heart', 'earth']
#astratta coerente > 9
sentiment_list9 = ['love', 'friendship', 'sadness', 'disappointment', 'anger', 'consolation', 'deception', 'betrayal',
                  'fraternity']
#astratta non coerente > 5
abstract = ['love', 'immeasurable', 'power', 'straight', 'hystory']
#solo termine
solo = ['table']
#family coerente > 10
family = ['sister', 'mother', 'father', 'son', 'daughter', 'uncle', 'aunt', 'brother', 'grandmother', 'grandfather']
#semi coerente > 10 - c'e' solo un elemento estraneo nella lista
food_with_outsider10 = ['mellon', 'apple', 'pizza', 'chips', 'meat', 'chicken','potato', 'milk', 'camera']
#semi coerente > 3
food_with_outsider3 = ['mellon', 'apple', 'exam']
jobs_list = ['baker', 'mechanician', 'worker', 'clerk', 'politician', 'pilot']
school_list = ['school', 'university', 'academy', 'exam', 'teacher', 'student', 'master', 'rejection']
mix = ['water', 'mellon', 'apple', 'school', 'university', 'academy', 'exam', 'pizza', 'chips', 'meat', 'chicken',
       'potato', 'milk', 'chocolate', 'phone', 'computer', 'watch', 'tablet', 'camera', 'console']
example_list = ['developer', 'web', 'software', 'politician', 'diiner', 'chinese', 'new jersey']
a = ['take',  'table',  'every', 'time', 'show', 'room', 'one', 'vegas', 'place', 'bar']
topic_exemple = ['love', 'enjoyed',  'perfect', 'hotel', 'dont' 'one', 'place view']


from sys import stdin, stdout

read = stdin.readline
write = stdout.write

xs, ys = list(map(int, read().rsplit(' ')))
xe, ye, dx, dy = list(map(int, read().rsplit(' ')))

min = 100000000

x = xe
y = ye

if dx == 0:
    while True:
        dis = ((xs-xe)**2 + (ys-y)**2)**0.5
        if dis <= min:
            min = dis
        else:
            y -= 1
            break
        y += 1
else:
    a = dy/dx
    b = ye - a*xe
    while True:
        y = int(a*x + b)
        dis = ((xs-x)**2 + (ys-y)**2)**0.5
        if dis <= min:
            min = dis
        else:
            x -= 1
            y = int(a*x + b)
            break
        x += 1

write(f'{x} {y}')

백준/Silver/1393. 음하철도 구구팔/음하철도 구구팔.py


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 14:37:20 2020

@author: Alex

code for windows
"""
from typing import List
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        pre = []
        cur = []
        ans = 0
        count = 0
        m = len(grid)
        n = len(grid[0])
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 2:
                    pre.append((i, j))
                elif grid[i][j] == 1:
                    count += 1
        if count == 0:
            return ans
        while pre:
            pre_i, pre_j = pre.pop()
            for di, dj in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                cur_i, cur_j = pre_i + di, pre_j + dj
                if cur_i >= 0 and cur_j >= 0 and cur_i < m and cur_j < n and grid[cur_i][cur_j] == 1:
                    grid[cur_i][cur_j] = 2
                    count -= 1
                    cur.append((cur_i, cur_j))
            if not pre:
                pre = cur
                cur = []
                ans += 1
        return ans - 1 if count == 0 else -1

if __name__ == "__main__":
    s = Solution()
    a1 = [[2,1,1],[1,1,0],[0,1,1]]
    #a2 =
    print(s.orangesRotting(a1))


from smbus2 import SMBus
from time import sleep

class MP3Trigger(object):

    COMMAND_STOP = 0x00
    COMMAND_PLAY_TRACK = 0x01
    COMMAND_PLAY_FILENUMBER = 0x02
    COMMAND_PAUSE = 0x03
    COMMAND_PLAY_NEXT = 0x04
    COMMAND_PLAY_PREVIOUS = 0x05
    COMMAND_SET_EQ = 0x06
    COMMAND_SET_VOLUME = 0x07
    COMMAND_GET_SONG_COUNT = 0x08
    COMMAND_GET_SONG_NAME = 0x09
    COMMAND_GET_PLAY_STATUS = 0x0A
    COMMAND_GET_CARD_STATUS = 0x0B
    COMMAND_GET_VERSION = 0x0C
    COMMAND_CLEAR_INTERRUPTS = 0x0D
    COMMAND_GET_VOLUME = 0x0E
    COMMAND_GET_EQ = 0x0F
    COMMAND_GET_ID = 0x10
    COMMAND_SET_ADDRESS = 0xC7

    EQ_NORMAL = 0
    EQ_POP = 1
    EQ_ROCK = 2
    EQ_JAZZ = 3
    EQ_CLASSICAL = 4
    EQ_BASS = 5

    def __init__(self, bus_number, device_address):
        self.bus = SMBus(bus_number)
        self.device_address = device_address

    def __del__(self):
        self.bus.close()

    def stop(self):
        """
        Stops any currently playing track
        """
        self.bus.write_byte(self.device_address, self.COMMAND_STOP)
        sleep(0.05)

    def play_track(self, track_number):
        """
        Play a given track number (like on a CD).
        For example, 0x0A will play the 10th MP3 file in the root directory.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_PLAY_TRACK, track_number)
        sleep(0.05)

    def play_file(self, file_number):
        """
        Play a file # from the root directory. For example, 0x03 will play F003.mp3.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_PLAY_FILENUMBER, file_number)
        sleep(0.05)

    def pause(self):
        """
        Pause if playing, or starting playing if paused
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_PAUSE)
        sleep(0.05)

    def play_next(self):
        """
        Play the next file (next track) located in the root directory
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_PLAY_NEXT)
        sleep(0.05)

    def play_previous(self):
        """
        Play the previous file (previous track) located in the root directory
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_PLAY_PREVIOUS)
        sleep(0.05)

    def set_eq(self, eq):
        """
        Set the equalization level to one of 6 settings.
        Setting is stored to NVM and is loaded at each power-on.
        """
        if eq not in [self.EQ_NORMAL, self.EQ_POP, self.EQ_ROCK, self.EQ_JAZZ, self.EQ_CLASSICAL, self.EQ_BASS]:
            raise ValueError('Invalid EQ setting')
        self.bus.write_byte_data(self.device_address, self.COMMAND_SET_EQ, eq)
        sleep(0.05)

    def get_eq(self):
        """
        Returns byte that represents the EQ setting.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_ID)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def set_volume(self, volume_level):
        """
        Set volume level to one of 32 settings: 0 = Off, 31 = Max volume.
        Setting is stored to NVM and is loaded at each power-on.
        """
        if volume_level < 0 or volume_level > 31:
            raise ValueError('Invalid volume level')
        self.bus.write_byte_data(self.device_address, self.COMMAND_SET_VOLUME, volume_level)
        sleep(0.05)

    def get_volume(self):
        """
        Returns byte that represents the volume level
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_VOLUME)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def get_song_count(self):
        """
        Returns one byte representing the number of MP3s found on the microSD card. 255 max.
        Note: Song count is established at power-on. After loading files on the SD card via USB
        be sure to power-cycle the board to update this value. Note: This causes song to stop playing.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_SONG_COUNT)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def get_song_name(self):
        """
        Returns the first 8 characters of the file currently being played. Once the command is issued,
        the MP3 Trigger must be given 50ms to acquire the song name before it can be queried with an I2C read.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_SONG_NAME)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def get_id(self):
        """
        Returns 0x39. Useful for testing if a device at a given I2C address is indeed an MP3 Trigger.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_ID)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def get_card_status(self):
        """
        Returns a byte indicating card status. 0 = OK, 5 = SD Error. Once the command is issued,
        the MP3 Trigger must be given 50ms to acquire the card status before it can be queried with an I2C read.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_CARD_STATUS)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def get_version(self):
        """
        Returns two bytes indicating Major and Minor firmware version.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_GET_VERSION)
        sleep(0.05)
        result = self.bus.read_byte_data(self.device_address, 0)
        sleep(0.05)
        return result

    def clear_interrupts(self):
        """
        Clears the interrupt bit.
        """
        self.bus.write_byte_data(self.device_address, self.COMMAND_CLEAR_INTERRUPTS)
        sleep(0.05)

    def get_play_status(self):
        """
        Returns a byte indicating MP3 player status. 0 = OK, 1 = Fail, 2 = No such file, 5 = SD Error.
        """
        result = self.bus.read_byte_data(self.device_address, self.COMMAND_GET_PLAY_STATUS)
        sleep(0.05)
        return result

    def set_address(self, address):
        """
        Sets the I2C address of Qwiic MP3 Trigger. For example, 0x6E 0xC7 0x21 will change the MP3 Trigger at I2C address
        0x37 to address 0x21. In this example 0x6E is device address 0x37 with write bit set to 1. Valid addresses
        are 0x08 to 0x77 inclusive. Setting is stored to NVM and is loaded at each power-on.
        """
        if address < 0x07 or address > 0x78:
            raise ValueError('Invalid I2C address')
        self.bus.write_byte_data(self.device_address, self.COMMAND_CHANGE_ADDRESS, address)
        sleep(0.05)


import operator
import os

class Word:
    def __init__(self, word):
        self.word = word
        self.cased = {} # word before .lower()
        self.count = 1
        self.previous_word = {} # dictionary of words that appeared one spot before word
        self.previous_word2 = {} # .................................two spots...........
        self.previous_word3 = {} # ...............................three spots...........
        self.next_word = {}  # dictionary of words that appeared one spot after word
        self.next_word2 = {} # ..................................two spots..........
        self.next_word3 = {} # ................................three spots..........
        self.endOfSentence = 0 # count of how many times word was last word in sentence
        self.startOfSentence = 0 # ..............................first word............

    # increments count + 1
    def setCount(self):
        self.count += 1

    # returns count
    def getCount(self):
        return self.count

    # adds cased version of word to dictionary
    def addCase(self, cased):
        self.cased.setdefault(cased, 0)
        self.cased[cased] += 1

    # return cased dictionary
    def getCase(self):
        return self.cased

    # sets previous 3 words except for those that are None
    def setPreviousWords(self, prev1, prev2, prev3):
        if prev1 != None:
            self.previous_word.setdefault(prev1, 0)
            self.previous_word[prev1] += 1
        if prev2 != None:
            self.previous_word2.setdefault(prev2, 0)
            self.previous_word2[prev2] += 1
        if prev3 != None:
            self.previous_word3.setdefault(prev3, 0)
            self.previous_word3[prev3] += 1

    # sets next 3 words, except for those that are None
    def setNextWords(self, next1, next2, next3):
        if next1 != None:
            self.next_word.setdefault(next1, 0)
            self.next_word[next1] += 1
        if next2 != None:
            self.next_word2.setdefault(next2, 0)
            self.next_word2[next2] += 1
        if next3 != None:
            self.next_word3.setdefault(next3, 0)
            self.next_word3[next3] += 1

    # return first previous word
    def getPreviousWord(self):
        return self.previous_word

    # return second previous word
    def getPreviousWord2(self):
        return self.previous_word2

    # return third previous word
    def getPreviousWord3(self):
        return self.previous_word3

    # return first next word
    def getNextWord(self):
        return self.next_word

    # return second next word
    def getNextWord2(self):
        return self.next_word2

    # return third next word
    def getNextWord3(self):
        return self.next_word3

    # increment endOfSentence
    def endIncrement(self):
        self.endOfSentence += 1

    # increment startOfSentence
    def startIncrement(self):
        self.startOfSentence += 1

    # return endOfSentence
    def getEnd(self):
        return self.endOfSentence

    # return startOfSentence
    def getStart(self):
        return self.startOfSentence

# reads file, removes trash characters, parse text, and return dictionary
def read_file(book):

    wordDict = {} # empty dictionary for words
    listed = [] # empty list for sentences

    # reading entire text file into string, cleaning it up, and separating into list of sentences
    with open(book, encoding='utf-8') as file:
        entire_book = file.read().replace('\n', ' ').replace('!', '.').replace('?', '.').replace('"', '')
        sentences = entire_book.split(". ")
        for sentence in sentences:
            listed.append(sentence)

    trashChars = '''()[]{};:,'"\,<>/@#$%^&*_~“”''' # characters to be removed from sentences
    for sentence in listed:
        sentence = sentence.replace('...', '').replace("’s", '') # other stuff being removed from sentence
        for ele in sentence:
            if ele in trashChars:
                sentence = sentence.replace(ele, '') # removing trashChars
        words = sentence.split(' ') # splitting sentence into words
        index = 0
        prev1 = None
        prev2 = None
        prev3 = None
        for word in words:
            for ele in word:
                if '.' in ele:
                    word = word.replace('.', '') # removing periods from words

            cased = word # original casing
            word = word.lower()

            if word not in wordDict:
                wordDict[word] = Word(word)
                wordDict[word].setPreviousWords(prev1, prev2, prev3)
                wordDict[word].addCase(cased)
            else:
                wordDict[word].setCount()
                wordDict[word].setPreviousWords(prev1, prev2, prev3)

            if index == 0:
                wordDict[word].startIncrement()

            if len(words) >= index + 4:
                next1 = words[index + 1]
                next2 = words[index + 2]
                next3 = words[index + 3]
            elif len(words) == index + 3:
                next1 = words[index + 1]
                next2 = words[index + 2]
                next3 = None
            elif len(words) == index + 2:
                next1 = words[index + 1]
                next2 = None
                next3 = None
            else:
                next1 = None
                next2 = None
                next3 = None
                wordDict[word].endIncrement()

            index += 1
            prev3 = prev2
            prev2 = prev1
            prev1 = word

    del wordDict['']
    return wordDict

'''wordDict = read_file('book.txt')

sortedPrevWord = sorted(wordDict['drow'].getPreviousWord().items(), key=operator.itemgetter(1), reverse=True)
for x, y in sortedPrevWord:
    print(x + ' appeared before DROW ' + str(y) + ' times.')'''

'''if __name__ == '__main__':
    import sys
    for arg in sys.argv[1:]:
        read_file(arg)
'''


import unittest
import gdb

def get_n(n_str):
    return int(n_str.split("=")[1].strip())

class HeapMemoryTest(unittest.TestCase):

    def setUp(self):
        gdb.execute('set pagination on')
        gdb.execute("file test/sample_heap_test.o")
        gdb.execute("source heap_print_script.py")
        gdb.execute("delete")
        gdb.execute("watch_heap")

    def check_memory(self, n, array_ptr_str, offset=1):
        """
        It is used to test what we got from 'print_ptr' is what we expect.
        Sample test program allocates array of n int's using malloc and then
        assigns 1 to n values to that array. So checking that malloc_ptr_str
        is 1 to n, following big endian size and size of int as 32 bits

        Parameters
        ----------
        n : int
            array length
        array_ptr_str : str
            whole output from print_ptr command including memory content
        offset : int
            checking memory content starts from offset value. By default it is 1
        """

        data = array_ptr_str.split("\n")[3]
        bytes_from_heap = data.split(" ")
        actual_start = offset
        for i in range(0, n * 4, 4):
            hex_str = bytes_from_heap[i+3][2:]
            hex_str += bytes_from_heap[i+2][2:]
            hex_str += bytes_from_heap[i+1][2:]
            hex_str += bytes_from_heap[i][2:]
            int_of_hex = int(hex_str, 16)
            self.assertEqual(actual_start, int_of_hex)
            actual_start += 1

    def test_malloc(self):
        print("malloc test")
        gdb.execute("b 20")
        gdb.execute("r")
        n_str = gdb.execute("print n", to_string=True)
        n = get_n(n_str)
        malloc_ptr_array_str = gdb.execute(
            "print_ptr malloc_ptr", to_string=True)
        print(malloc_ptr_array_str)
        self.check_memory(n, malloc_ptr_array_str)
        self.assertTrue(True)

    def test_realloc(self):
        print("realloc test")
        gdb.execute("b 27")
        gdb.execute("r")
        new_n = gdb.execute("print new_n", to_string=True)
        n = get_n(new_n)
        malloc_ptr_str = gdb.execute("print_ptr malloc_ptr", to_string=True)
        print(malloc_ptr_str)
        self.check_memory(n, malloc_ptr_str)

    def test_offset(self):
        """
        Testcase to test raw_pointers that are offset
        """

        print("offset test. we have array of 20 (80 bytes) and \
                we offset it by 3, so new length should be 68")
        offset = 3
        gdb.execute("b 27")
        gdb.execute("r")
        new_n = gdb.execute("print new_n", to_string=True)
        n = get_n(new_n)
        malloc_ptr_str = gdb.execute(
            "print_ptr malloc_ptr + {}".format(offset), to_string=True)
        print(malloc_ptr_str)
        self.check_memory(n - offset, malloc_ptr_str, offset+1)

    def test_free(self):
        print("free test")
        gdb.execute("b 28")
        gdb.execute("r")
        malloc_ptr_str = gdb.execute("print_ptr malloc_ptr", to_string=True)
        data = malloc_ptr_str.split("\n")[2].strip()
        self.assertEqual(data, "No address mapping found!")

    def test_new(self):
        print("operator new[] test")
        gdb.execute("b 41")
        gdb.execute("r")
        n_str = gdb.execute("print n", to_string=True)
        n = get_n(n_str)
        new_ptr_array_str = gdb.execute("print_ptr new_ptr", to_string=True)
        self.check_memory(n, new_ptr_array_str)

    def test_delete(self):
        print("operator delete[]")
        gdb.execute("b 42")
        gdb.execute("r")
        new_ptr_array_str = gdb.execute("print_ptr new_ptr", to_string=True)
        data = new_ptr_array_str.split("\n")[2].strip()
        self.assertEqual(data, "No address mapping found!")

if __name__ == '__main__':
    unittest.main()