from personas import pasajero

class transporte:
    def __init__(self, patente, capacidad, consumo, vel_max, *args):
        self.__patente = patente#string
        self.__capacidad = capacidad#int
        self.__consumo = consumo#float
        self.__vel_max = vel_max#float
        self.__pasajeros = [*args]#obj

    @property
    def patente(self):
        return self.__patente

    @patente.setter
    def patente(self, patente):
        try:
            n_patente = str(patente)
        except ValueError or TypeError:
             "Coloque la patente como string"
        else:
            self.__patente = n_patente

    @property
    def capacidad(self):
        return self.__capacidad

    @capacidad.setter
    def capacidad(self, capacidad):
        try:
            n_capacidad = int(capacidad)
        except ValueError or TypeError:
             "Debe ser un numero sin coma"
        else:
            self.__capacidad = n_capacidad

    @property
    def consumo(self):
        return self.__consumo

    @consumo.setter
    def consumo(self, consumo):
        try:
            n_consumo = float(consumo)
        except ValueError or TypeError:
             "Se debe colocar un numero"
        else:
            self.__consumo = n_consumo

    @property
    def vel_max(self):
        return self.__vel_max

    @vel_max.setter
    def vel_max(self, vel_max):
        try:
            n_vel_max = float(vel_max)
        except ValueError or TypeError:
             "Se debe colocar un numero"
        else:
            self.__vel_max = n_vel_max

    @property
    def pasajeros(self):
        return self.__pasajeros

    #Agrgar-remover pasajeros
    def agregar_pasajero(self, pasajero):
        if self.__pasajeros.count(pasajero) == 1:
            return "Pasajero ya esta agregado"
        else:
            self.__pasajeros.append(pasajero)
            return "Pasajero agregado exitosamente"

    def remover_pasajero(self, pasajero):
        if self.__pasajeros.count(pasajero) == 1:
            self.__pasajeros.remove(pasajero)
            return "Pasajero Removido"
        else:
            return "Pasajero no figura en el transporte"

    #Transporte_detalles
    def dar_porcentaje_ocupacion(self):
        disponible = self.__capacidad-len(self.__pasajeros)
        print("Ocupado: ", len(self.__pasajeros))
        print("Disponible: ", disponible)
        return#float

    def dar_ingreso_viaje(self,recorrido):
        i = 0
        total = 0
        while i != len(self.pasajeros):
            total = self.pasajeros[i].dar_precio_pasaje(recorrido) + total
            i = i + 1
        return total

#t1 = transporte("abol4500",60,40,110)
#t2 = transporte("csrl7485",70,50,140)


import shelve
from SQLighter import SQLighter
from config import shelve_name, database_name
from random import shuffle
from telebot import types

def count_rows():
    # метод считает общее число строк в БД и сохраняет в хранилище.
    # Далее из него выбирается музыка
    db = SQLighter(database_name)
    rowsnum = db.count_rows()
    with shelve.open(shelve_name) as storage:
        storage['rows_counts'] = rowsnum

def get_rows_count():
    # Получаем из хранилища число строк в БД (:return: (int))
    with shelve.open(shelve_name) as storage:
        rowsnum = storage['rows_count']
    return rowsnum

def set_user_game(chat_id, estimated_answers):
    # записываем пользователя в игроки и запоминаем ответ
    with shelve.open(shelve_name) as storage:
        storage[str(chat_id)] = estimated_answers

def finish_user_game(chat_id):
    # заканчиваем игру
    with shelve.open(shelve_name) as storage:
        del storage[str(chat_id)]

def get_answer_for_user(chat_id):
    # получаем правильный ответ от пользователя
    with shelve.open(shelve_name) as storage:
        try:
            answer = storage[str(chat_id)]
            return answer

        except KeyError:
            return None

def generate_markup(right_answer, wrong_answers):
    markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
    all_answers = '{},{}'.format(right_answer, wrong_answers)
    list_items = []
    for item in all_answers.split(','):
        list_items.append(item)
    shuffle(list_items)
    for item in list_items:
        markup.add(item)
    return markup


import typing

from PySide6.QtGui import QDropEvent, QPixmap
from PySide6.QtWidgets import QComboBox, QTableWidgetItem

from foundry.game.gfx.objects.world_map.sprite import MAP_ITEM_SPRITES, MAP_OBJ_SPRITES
from foundry.game.level.LevelRef import LevelRef
from scribe.gui.commands import ChangeSpriteIndex, SetSpriteItem, SetSpriteType
from scribe.gui.tool_window.table_widget import (
    DialogDelegate,
    DropdownDelegate,
    TableWidget,
)
from smb3parse.constants import MAPITEM_NAMES, MAPOBJ_NAMES
from smb3parse.levels import FIRST_VALID_ROW

class SpriteList(TableWidget):
    def __init__(self, parent, level_ref: LevelRef):
        super(SpriteList, self).__init__(parent, level_ref)

        self.cellChanged.connect(self._save_sprite)

        self.set_headers(["Sprite Type", "Item Type", "Map Position"])

        self.setItemDelegateForColumn(
            0,
            DropdownDelegate(self, list(MAPOBJ_NAMES.values()), list(MAP_OBJ_SPRITES.values())),
        )
        self.setItemDelegateForColumn(
            1,
            DropdownDelegate(self, list(MAPITEM_NAMES.values()), list(MAP_ITEM_SPRITES.values())),
        )
        self.setItemDelegateForColumn(
            2,
            DialogDelegate(
                self,
                "No can do",
                "You can move sprites by dragging them around in the WorldView. "
                "Make sure they are shown in the View Menu.",
            ),
        )

        self.update_content()

    def dropEvent(self, event: QDropEvent) -> None:
        source_index = self.selectedIndexes()[0].row()
        target_index = self.indexAt(event.position().toPoint()).row()

        self.undo_stack.push(ChangeSpriteIndex(self.world, source_index, target_index))

        self.update_content()

    def _save_sprite(self, row: int, column: int):
        if column == 2:
            return

        sprite = self.world.sprites[row]

        widget = typing.cast(QComboBox, self.cellWidget(row, column))
        data = widget.currentText()

        if sprite.data.y < FIRST_VALID_ROW:
            sprite.data.y = FIRST_VALID_ROW

        if column == 0:
            self.undo_stack.push(SetSpriteType(sprite.data, list(MAPOBJ_NAMES.values()).index(data)))
        elif column == 1:
            self.undo_stack.push(SetSpriteItem(sprite.data, list(MAPITEM_NAMES.values()).index(data)))
        else:
            return

        self.world.data_changed.emit()

    def update_content(self):
        self.setRowCount(len(self.world.sprites))

        self.blockSignals(True)

        for index, sprite in enumerate(self.world.sprites):
            sprite_type = QTableWidgetItem(MAPOBJ_NAMES[sprite.data.type])
            sprite_type.setIcon(QPixmap(MAP_OBJ_SPRITES[sprite.data.type].scaled(self.iconSize())))

            item_type = QTableWidgetItem(MAPITEM_NAMES[sprite.data.item])
            item_type.setIcon(QPixmap(MAP_ITEM_SPRITES[sprite.data.item].scaled(self.iconSize())))
            pos = QTableWidgetItem(f"Screen {sprite.data.screen}: x={sprite.data.x}, y={sprite.data.y}")

            self._set_map_tile_as_icon(pos, sprite.get_position())

            self.setItem(index, 0, sprite_type)
            self.setItem(index, 1, item_type)
            self.setItem(index, 2, pos)

        self.blockSignals(False)


import argparse
import os
from typing import Iterable

import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.optim import create_optimizer
from timm.utils import NativeScaler, accuracy
from torch.nn.parallel import DistributedDataParallel as DDP
from torchvision import datasets, transforms

from config.linear.vit_base_linear import vit_base_linear
from config.linear.vit_small_linear import vit_small_linear
from config.linear.vit_tiny_linear import vit_tiny_linear
from module.vits import ViT
from utils import misc
from utils.logger import Logger, console_logger
from utils.misc import AverageMeter

def build_dataset(is_train, args):
    transform = build_transform(is_train, args)

    if args.dataset == 'cifar100':
        dataset = datasets.CIFAR100(
            args.data_root, train=is_train, transform=transform)
        nb_classes = 100
    elif args.dataset == 'cifar10':
        dataset = datasets.CIFAR10(
            args.data_root, train=is_train, transform=transform)
        nb_classes = 10
    elif args.dataset == 'imagenet1k':
        dataset = datasets.ImageFolder(
            root=os.path.join(args.data_root, 'train' if is_train else 'val'), transform=transform)
        nb_classes = 1000
    return dataset, nb_classes

def build_transform(is_train, args):
    if is_train:
        return transforms.Compose([
            transforms.RandomResizedCrop(args.input_size, interpolation=3),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)])
    else:
        return transforms.Compose([
            transforms.Resize(
                int(args.input_size / 224 * 256), interpolation=3),
            transforms.CenterCrop(args.input_size),
            transforms.ToTensor(),
            transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)])

def get_model_from_frame(checkpoint, args):
    encoder = args.encoder
    state_dict = checkpoint['state_dict']
    encoder = ('module.' if 'module' in list(
        state_dict.keys())[0] else '') + encoder
    for k in list(state_dict.keys()):
        if k.startswith(encoder) and not k.startswith(encoder + '.head'):
            state_dict[k[len(encoder + "."):]] = state_dict[k]
        del state_dict[k]
    return state_dict

def sanity_check(state_dict, pretrained_weights, args):
    """
    Linear classifier should not change any weights other than the linear layer.
    This sanity check asserts nothing wrong happens (e.g., BN stats updated).
    """
    encoder = args.encoder
    print("=> loading '{}' for sanity check".format(pretrained_weights))
    checkpoint = torch.load(pretrained_weights, map_location="cpu")
    state_dict_pre = checkpoint['state_dict']
    module_kw = 'module.' if 'module' in list(state_dict_pre.keys())[0] else ''
    for k in list(state_dict.keys()):
        if 'head.weight' in k or 'head.bias' in k:
            continue
        pre_k = module_kw + encoder + '.' + (k[len('module.'):] if 'module' in k else k)
        assert ((state_dict[k].cpu() == state_dict_pre[pre_k]).all()), \
            '{} is changed in linear classifier training.'.format(k)

    print("=> sanity check passed.")

def train_one_epoch(model: torch.nn.Module, criterion,
                    train_loader: Iterable, optimizer: torch.optim.Optimizer,
                    epoch: int, loss_scaler, loggers, args, max_norm: float = 0,
                    ):
    model.eval()
    logger_tb, logger_console = loggers

    losses = AverageMeter('Loss', ':.4e')

    num_iter = len(train_loader)
    niter_global = epoch * num_iter

    for i, (images, targets) in enumerate(train_loader):
        images = images.to(args.rank, non_blocking=True)
        targets = targets.to(args.rank, non_blocking=True)

        with torch.cuda.amp.autocast():
            outputs = model(images)
            loss = criterion(outputs, targets)

        losses.update(loss.item(), images.size(0))

        optimizer.zero_grad()
        is_second_order = hasattr(
            optimizer, 'is_second_order') and optimizer.is_second_order
        loss_scaler(loss, optimizer, clip_grad=max_norm,
                    parameters=model.parameters(), create_graph=is_second_order)

        torch.cuda.synchronize()

        niter_global += 1
        if args.rank == 0:
            logger_tb.add_scalar('Finetune/Iter/loss',
                                 losses.val, niter_global)

        if (i + 1) % args.print_freq == 0 and logger_console is not None and args.rank == 0:
            lr = optimizer.param_groups[0]['lr']
            logger_console.info(f'Epoch [{epoch}][{i + 1}/{num_iter}] - '
                                f'lr: {lr:.5f},     '
                                f'loss: {losses.avg:.3f}')
    if args.pretrained_weights and epoch == args.start_epoch and args.rank == 0:
        sanity_check(model.state_dict(), args.pretrained_weights, args)
    if args.distributed:
        losses.synchronize_between_processes()

    return losses.avg

@torch.no_grad()
def evaluate(data_loader, model, args):
    accs1 = AverageMeter('Acc@1', ':6.2f')
    accs5 = AverageMeter('Acc@5', ':6.2f')

    model.eval()

    for i, (images, target) in enumerate(data_loader):
        images = images.to(args.rank, non_blocking=True)
        target = target.to(args.rank, non_blocking=True, dtype=torch.long)

        with torch.cuda.amp.autocast():
            output = model(images)

        acc1, acc5 = accuracy(output, target, topk=(1, 5))

        batch_size = images.shape[0]
        accs1.update(acc1.item(), batch_size)
        accs5.update(acc5.item(), batch_size)
    if args.distributed:
        accs1.synchronize_between_processes()
        accs5.synchronize_between_processes()

    return accs1.avg, accs5.avg

def main_ddp(args):
    if args.distributed:
        ngpus_per_node = torch.cuda.device_count()
        args.world_size = args.world_size * ngpus_per_node
        mp.spawn(main, args=(args,), nprocs=args.world_size)
    else:
        main(args.rank, args)

def main(rank, args):
    args.rank = rank
    if args.distributed:
        dist.init_process_group(
            backend="nccl",
            init_method=args.dist_url,
            world_size=args.world_size,
            rank=args.rank,
        )

    misc.fix_random_seeds(args.seed)

    cudnn.benchmark = True
    if not args.evaluate:
        if args.rank == 0:
            for k, v in sorted(vars(args).items()):
                print(k, '=', v)
            name = str(args.arch) + "_" + str(args.dataset) + \
                   "_epochs_" + str(args.epochs) + "_lr_" + str(args.lr)
            logger_tb = Logger(args.output_dir, name)
            logger_console = console_logger(logger_tb.log_dir, 'console_eval')
            dst_dir = os.path.join(logger_tb.log_dir, 'code/')
        else:
            logger_tb, logger_console = None, None
        if args.rank == 0:
            path_save = os.path.join(args.output_dir, logger_tb.log_name)

    dataset_train, num_class = build_dataset(is_train=True, args=args)
    dataset_val, _ = build_dataset(is_train=False, args=args)

    if args.distributed:
        num_tasks = args.world_size
        global_rank = args.rank
        sampler_train = torch.utils.data.DistributedSampler(
            dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True
        )
        sampler_val = torch.utils.data.SequentialSampler(dataset_val)
        args.num_workers = int((args.num_workers + 1) / args.world_size)
    else:
        sampler_train = torch.utils.data.RandomSampler(dataset_train)
        sampler_val = torch.utils.data.SequentialSampler(dataset_val)

    if args.arch == 'vit-tiny':
        model = ViT(patch_size=args.patch_size, img_size=args.input_size,
                    embed_dim=192, depth=12, num_heads=3, mlp_ratio=4)
    elif args.arch == 'vit-small':
        model = ViT(patch_size=args.patch_size, img_size=args.input_size,
                    embed_dim=384, depth=12, num_heads=12, mlp_ratio=4)

    elif args.arch == 'vit-base':
        model = ViT(patch_size=args.patch_size, img_size=args.input_size,
                    embed_dim=768, depth=12, num_heads=12, mlp_ratio=4)

    if args.pretrained_weights:
        if os.path.isfile(args.pretrained_weights):
            print("=> loading checkpoint '{}'".format(args.pretrained_weights))
            checkpoint = torch.load(
                args.pretrained_weights, map_location=torch.device(args.rank))

            state_dict = get_model_from_frame(checkpoint, args)

            args.start_epoch = 0
            msg = model.load_state_dict(state_dict, strict=False)
            print(msg.missing_keys)
            assert set(msg.missing_keys) == {"head.weight", "head.bias"}

            print("=> loaded pre-trained model '{}'".format(args.pretrained_weights))
        else:
            print("=> no checkpoint found at '{}'".format(
                args.pretrained_weights))

    model.head = nn.Linear(model.head.in_features, num_class)

    for name, param in model.named_parameters():
        if name not in ['head.weight', 'head.bias']:
            param.requires_grad = False
    model.cuda(args.rank)

    model_without_ddp = model
    if args.distributed:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[args.rank])
        torch.cuda.set_device(args.rank)
        model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
        args.batch_size = int(args.batch_size / args.world_size)
        model_without_ddp = model.module

    if args.distributed:
        args.lr = args.lr * args.batch_size * args.world_size / 256
    else:
        args.lr = args.lr * args.batch_size / 256

    optimizer = create_optimizer(args, model_without_ddp)
    lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, args.epochs, eta_min=0)

    loss_scaler = NativeScaler()
    criterion = torch.nn.CrossEntropyLoss()

    data_loader_train = torch.utils.data.DataLoader(
        dataset_train, sampler=sampler_train,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        pin_memory=args.pin_memory,
        prefetch_factor=args.prefetch_factor,
        drop_last=True,
    )

    data_loader_val = torch.utils.data.DataLoader(
        dataset_val, sampler=sampler_val,
        batch_size=int(1.5 * args.batch_size),
        num_workers=args.num_workers,
        pin_memory=args.pin_memory,
        prefetch_factor=args.prefetch_factor,
        drop_last=False
    )

    acc_best = 0.0
    if args.resume:
        if os.path.isfile(args.resume):
            print("=> loading checkpoint '{}'".format(args.resume))
            if args.gpu is None:
                checkpoint = torch.load(args.resume)
            else:
                loc = 'cuda:{}'.format(args.gpu)
                checkpoint = torch.load(args.resume, map_location=loc)
            args.start_epoch = checkpoint['epoch']
            acc_best = checkpoint['acc_best']
            if args.gpu is not None:
                acc_best = acc_best.to(args.gpu)
            if isinstance(model, DDP):
                model.module.load_state_dict(checkpoint['state_dict'])
            else:
                model.load_state_dict(checkpoint['state_dict'])
            optimizer.load_state_dict(checkpoint['optimizer'])
            loss_scaler.load_state_dict(checkpoint['scaler'])
            print("=> loaded checkpoint '{}' (epoch {})"
                  .format(args.resume, checkpoint['epoch']))
        else:
            print("=> no checkpoint found at '{}'".format(args.resume))

    if args.evaluate:
        if os.path.isfile(args.evaluate):
            print("=> loading checkpoint '{}'".format(args.evaluate))
            model = torch.load(
                args.evaluate, map_location=torch.device(args.rank))
            print("=> loaded pre-trained model '{}'".format(args.evaluate))
        else:
            print("=> no checkpoint found at '{}'".format(args.evaluate))
        acc1, acc5 = evaluate(data_loader_val, model, args)
        print('Acc1 :' + str(acc1) + '\tAcc5 :' + str(acc5))
        return

    print(f"Start training for {args.epochs} epochs")
    for epoch in range(args.start_epoch, args.epochs):
        if args.distributed:
            data_loader_train.sampler.set_epoch(epoch)
        loss = train_one_epoch(
            model, criterion, data_loader_train,
            optimizer, epoch, loss_scaler, (logger_tb, logger_console), args,
            args.clip_grad
        )
        if args.rank == 0:
            logger_tb.add_scalar('Finetune/Epoch/loss', loss, epoch)

        state_dict = model.module.state_dict() if isinstance(model, DDP) else model.state_dict()
        if epoch % args.save_freq == 0 and args.rank == 0:
            torch.save(
                {
                    'epoch': epoch + 1,
                    'arch': args.arch,
                    'state_dict': state_dict,
                    'acc_best': acc_best,
                    'optimizer': optimizer.state_dict(),
                    'scaler': loss_scaler.state_dict(),
                },
                f'{path_save}/{epoch:0>4d}.pth'
            )

        lr_scheduler.step(epoch)
        acc1, acc5 = evaluate(data_loader_val, model, args)
        if args.rank == 0:
            logger_tb.add_scalar('Finetune/Epoch/Accuracy', acc1, epoch)
            logger_console.info(
                f'Epoch: {epoch}\t'
                f'Acc1: {round(acc1, 3)}\t'
                f'Acc5: {round(acc5, 3)}'
            )

        if acc1 > acc_best:
            acc_best = acc1
            epoch_best = epoch
            if args.rank == 0:
                torch.save(
                    model_without_ddp,
                    f'{path_save}/best.pth'
                )

        if args.rank == 0:
            logger_console.info(
                f'Epoch: {epoch_best}, '
                f'Best Acc1: {round(acc_best, 3)}'
            )

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--arch", type=str, default='vit-small',
                        choices=['vit-tiny', 'vit-small', 'vit-base'])
    parser.add_argument("--pretrained-weights", type=str,
                        default='')
    parser.add_argument("--evaluate", type=str, default=None)
    return parser

if __name__ == '__main__':
    parser = parse_args()
    _args = parser.parse_args()

    if _args.arch == 'vit-tiny':
        args = vit_tiny_linear()
    elif _args.arch == 'vit-small':
        args = vit_small_linear()
    elif _args.arch == 'vit-base':
        args = vit_base_linear()
    args.pretrained_weights = _args.pretrained_weights
    args.evaluate = _args.evaluate
    main_ddp(args)


import requests
from bs4 import BeautifulSoup

from movexplo.constants import TOFIND, URL
from movexplo.utils import (duration_to_int, get_logger, remove_special_characters)

logger = get_logger("scrapper")

def get_soup_from_url(url):
    result = requests.get(url)
    soup = BeautifulSoup(result.text, 'html.parser')
    return soup

def get_link_from_file(file_info):
    url = URL.format(remove_special_characters(file_info["file_name"].replace(" ", "%20").lower()))
    logger.info("Searching {}".format(url))
    soup = get_soup_from_url(url)
    try:
        return get_link_from_soup(soup)
    except (IndexError, AttributeError) as e:
        logger.warning("Search failed for {} at url {}".format(file_info["file_name"], url))
        return TOFIND

def get_link_from_soup(soup):
    item = soup.find("div", "ProductListItem__TextContainer-sc-1ci68b-8 kKuZab")
    links = item.find_all("a", href=True)
    for link in links:
        if link["href"] is not None:
            return link["href"]

def get_image_from_soup(soup):
    item = soup.find("img", "pvi-hero-poster")
    return item["src"]

def get_director_from_soup(soup):
    item = soup.find("span", itemprop="name")
    return item.text

def get_date_from_soup(soup):
    item = soup.find("time")
    if item:
        return item["datetime"]

def get_genres_from_soup(soup):
    items = soup.find_all("span", itemprop="genre")
    return [item.text for item in items]

def get_duration_from_soup(soup):
    items = soup.find_all("li", "pvi-productDetails-item")
    for item in items:
        if item.find("meta", itemprop="duration"):
            return duration_to_int(item.text.replace("\n", "").replace("\t", ""))

def get_name_from_soup(soup):
    item = soup.find("h1", "pvi-product-title")
    return item["title"]

def get_original_name_from_soup(soup):
    item = soup.find("h2", "pvi-product-originaltitle")
    if item:
        return item.text

FIELD_TO_METHOD = {
    "image": get_image_from_soup,
    "director": get_director_from_soup,
    "date": get_date_from_soup,
    "genres": get_genres_from_soup,
    "duration": get_duration_from_soup,
    "name": get_name_from_soup,
    "original_name": get_original_name_from_soup,
}


from keras.utils import plot_model
from keras.models import Sequential, Model, model_from_json

def load_model(path_model, path_weights):
    # load json and create model
    json_file = open(path_model, 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights(path_weights)
    print("Loaded model from disk")
    return loaded_model

if __name__ == "__main__":
    model = load_model("/var/lib/arhuaco/data/models/model.json",
                       "/var/lib/arhuaco/data/models/weights_file_network")
    plot_model(model, to_file='/var/lib/arhuaco/data/models/model_network.png')


from asgiref.sync import async_to_sync
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.generic.websocket import WebsocketConsumer
import json
from .models import *

state_reference = {"ready": "https://media.giphy.com/media/26BkNrGhy4DKnbD9u/giphy.gif",
                   "preparing": "https://media.giphy.com/media/9g1h1BQx9a55m/giphy.gif", "": "", None: ""}

class RoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name
        self.user = self.scope["user"]
        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        usernow = self.user
        room_id = self.room_group_name[5:]
        codeUser = CodingUser.objects.get(user=usernow)
        room_instance = Room.objects.get(id=room_id)
        room_owner = room_instance.room_owner
        user1 = room_instance.user1
        user2 = room_instance.user2
        user3 = room_instance.user3
        user4 = room_instance.user4
        if room_instance != None:
            if user2 == None:
                url2 = ""
                state2 = ""
            else:
                url2 = user2.picture.url
                state2 = room_instance.user2_state
            if user3 == None:
                url3 = ""
                state3 = ""
            else:
                url3 = user3.picture.url
                state3 = room_instance.user3_state
            if user4 == None:
                url4 = ""
                state4 = ""
            else:
                url4 = user4.picture.url
                state4 = room_instance.user4_state
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'disconnection_update': "true",
                    'user1_url': user1.picture.url,
                    'user2_url': url2,
                    'user3_url': url3,
                    'user4_url': url4,
                    'user1_status': room_instance.user1_state,
                    'user2_status': state2,
                    'user3_status': state3,
                    'user4_status': state4
                }
            )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        if text_data_json.get("userstatus"):
            usernow = self.user
            room_id = text_data_json['room_id']
            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            position = ""
            new_status = ""
            gamestart = "no"
            if room_instance.user4 == codeUser:
                position = 'user4'
                if room_instance.user4_state == 'preparing':
                    room_instance.user4_state = 'ready'
                    new_status = 'ready'
                else:
                    room_instance.user4_state = 'preparing'
                    new_status = 'preparing'
            if room_instance.user3 == codeUser:
                position = 'user3'
                if room_instance.user3_state == 'preparing':
                    room_instance.user3_state = 'ready'
                    new_status = 'ready'
                else:
                    room_instance.user3_state = 'preparing'
                    new_status = 'preparing'
            if room_instance.user2 == codeUser:
                position = 'user2'
                if room_instance.user2_state == 'preparing':
                    room_instance.user2_state = 'ready'
                    new_status = 'ready'
                else:
                    room_instance.user2_state = 'preparing'
                    new_status = 'preparing'
            if room_instance.user1 == codeUser:
                position = 'user1'
                if room_instance.user1_state == 'preparing':
                    room_instance.user1_state = 'ready'
                    new_status = 'ready'
                    gamestart = 'yes'
                else:
                    room_instance.user1_state = 'preparing'
                    new_status = 'preparing'
            room_instance.save()
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'position': position,
                    'new_status': new_status,
                    'gamestart': gamestart,
                    'room_id': room_id
                }
            )

        if text_data_json.get("newarrival"):
            usernow = self.user
            room_id = text_data_json['room_id']
            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            position = ""
            user_url = "/codewar" + codeUser.picture.url
            user_status = 'preparing'
            if room_instance.user1 == codeUser:
                position = 'user1'
            if room_instance.user2 == codeUser:
                position = 'user2'
            if room_instance.user3 == codeUser:
                position = 'user3'
            if room_instance.user4 == codeUser:
                position = 'user4'
                # Send message to room group

            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'position': position,
                    'url': user_url,
                    'status': user_status,
                    'newarrival': 'newarrival'
                }
            )
        if text_data_json.get("change"):
            change = text_data_json['change']
            room_id = text_data_json['room_id']

            usernow = self.user

            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            message = 'nochange'
            initial = ''

            if change == "user2":
                if room_instance.user2 != None:
                    message = "nochange"
                elif room_instance.user3 == codeUser:
                    if room_instance.user3_state == "preparing":
                        message = 'change'
                        initial = 'user3'
                elif room_instance.user4 == codeUser:
                    if room_instance.user4_state == "preparing":
                        message = 'change'
                        initial = 'user4'
            if change == "user3":
                if room_instance.user3 != None:
                    message = "nochange"
                elif room_instance.user2 == codeUser:
                    if room_instance.user2_state == "preparing":
                        message = 'change'
                        initial = 'user2'
                elif room_instance.user4 == codeUser:
                    if room_instance.user4_state == "preparing":
                        message = 'change'
                        initial = 'user4'
            if change == "user4":
                if room_instance.user4 != None:
                    message = "nochange"
                elif room_instance.user3 == codeUser:
                    if room_instance.user3_state == "preparing":
                        message = 'change'
                        initial = 'user3'
                elif room_instance.user2 == codeUser:
                    if room_instance.user2_state == "preparing":
                        message = 'change'
                        initial = 'user2'
            # Send message to room group
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message,
                    'initial': initial,
                    'modify': change,
                    'room_id': room_id
                }
            )
        if text_data_json.get("exit"):
            usernow = self.user
            room_id = text_data_json['room_id']
            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            room_owner = room_instance.room_owner
            user_url = codeUser.picture.url
            exit_user = ""
            adjusted_user = ""
            if room_owner == codeUser:
                if room_instance.user2 != None:
                    exit_user = "user1"
                    adjusted_user = "user2"
                elif room_instance.user3 != None:
                    third_user = room_instance.user3
                    room_instance.room_owner = third_user
                    room_instance.user1 = third_user
                    room_instance.user1_state = room_instance.user3_state
                    room_instance.user3 = None
                    room_instance.user3_state = None
                    room_instance.save()
                    exit_user = "user1"
                    adjusted_user = "user3"
                elif room_instance.user4 != None:
                    fourth_user = room_instance.user4
                    room_instance.room_owner = fourth_user
                    room_instance.user1 = fourth_user
                    room_instance.user1_state = room_instance.user4_state
                    room_instance.user4 = None
                    room_instance.user4_state = None
                    room_instance.save()
                    exit_user = "user1"
                    adjusted_user = "user4"
                else:
                    room_instance.delete()
                    # Send message to room group
            if room_instance.user2 == codeUser:
                room_instance.user2 = None
                room_instance.user2_state = ""
                exit_user = "user2"
                adjusted_user = "nouser"
            if room_instance.user3 == codeUser:
                room_instance.user3 = None
                room_instance.user3_state = ""
                exit_user = "user3"
                adjusted_user = "nouser"
            if room_instance.user4 == codeUser:
                room_instance.user4 = None
                room_instance.user4_state = ""
                exit_user = "user4"
                adjusted_user = "nouser"

            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'exit_user': exit_user,
                    'adjusted_user': adjusted_user

                }
            )
        if text_data_json.get("room_acces_symbol"):
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'room_acces_symbol': text_data_json.get("room_acces_symbol")
                }
            )

    # Receive message from room group
    async def chat_message(self, event):
        if event.get('new_status') != None:
            position = event['position']
            new_status = event['new_status']
            room_id = event["room_id"]
            room_instance = Room.objects.get(id=room_id)
            user1_name = room_instance.user1.user.username
            user2_name = ""
            user3_name = ""
            user4_name = ""
            if room_instance.user2:
                user2_name = room_instance.user2.user.username
            if room_instance.user3:
                user3_name = room_instance.user3.user.username
            if room_instance.user4:
                user4_name = room_instance.user4.user.username
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'position': position,
                'new_status': new_status,
                "new_status_url": state_reference[new_status],
                'gamestart': event['gamestart'],
                "user1_username": user1_name,
                "user2_username": user2_name,
                "user3_username": user3_name,
                "user4_username": user4_name
            }))
        elif event.get('message') != None:
            message = event['message']
            if message == 'nochange':
                pass
            else:
                room_id = event['room_id']
                room_instance = Room.objects.get(id=room_id)
                initial = event['initial']
                modify = event['modify']
                if modify == "user2":
                    if room_instance.user2 != None:
                        message = 'nochange'
                if modify == "user3":
                    if room_instance.user3 != None:
                        message = 'nochange'
                if modify == "user4":
                    if room_instance.user4 != None:
                        message = 'nochange'
                # Send message to WebSocket
                await self.send(text_data=json.dumps({

                    'type': 'chat_message',
                    'message': message,
                    'initial': initial,
                    'modify': modify

                }))
        elif event.get('newarrival') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'position': event['position'],
                'url': event['url'],
                'status': event['status'],
                'status_url': state_reference[event['status']],
                'newarrival': 'newarrival'
            }))
        elif event.get('exit_user') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'exit_user': event['exit_user'],
                'adjusted_user': event['adjusted_user']
            }))
        elif event.get('disconnection_update') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'disconnection_update': event['disconnection_update'],
                'user1_url': event['user1_url'],
                'user1_status': event['user1_status'],
                'user1_status_url': state_reference[event['user1_status']],
                'user2_url': event['user2_url'],
                'user2_status': event['user2_status'],
                'user2_status_url': state_reference[event['user2_status']],
                'user3_url': event['user3_url'],
                'user3_status': event['user3_status'],
                'user3_status_url': state_reference[event['user3_status']],
                'user4_url': event['user4_url'],
                'user4_status': event['user4_status'],
                'user4_status_url': state_reference[event['user4_status']]
            }))
        elif event.get('room_acces_symbol') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'room_acces_symbol': event['room_acces_symbol']
            }))

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        print("disconnect")
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))


"""
VELM6070 Module
THIS IS NOT THREAD SAFE SO WATCH OUT !
"""
import i2c

"""  VEML6070 I2C adresses  """
VEML6070_ADDR_L = 0x38
VEML6070_ADDR_H = 0x39

class VEML6070:
    def __init__(self, port):
        self.port = port
        #Set port address to the VEML6070 control register/low data
        self.port.set_addr(VEML6070_ADDR_L)
        #init the sensor
        self.port.write([0x06])

    def getUV(self):
        #Set port to the high uv data address
        self.port.set_addr(VEML6070_ADDR_H)
        #Read one byte from the register
        uvH = self.port.read(1)
        #Set port to the low uv data / control register
        self.port.set_addr(VEML6070_ADDR_L)
        #Read one byte from the register
        uvL = self.port.read(1)

        ret = uvL[0] | uvH[0] << 8

        return ret


from itertools import product
#lista =[]
#A = [1, 2]
#B = [3, 4]
#lista.append(A)
#lista.append(B)
#print(list(product(*lista)))

def calcular(a,b):
	lista = []
	lista.append(a)
	lista.append(b)
	r = " ".join(map(str,list(product(*lista))))
	return r

if __name__ == '__main__':
	dato1 = input().split()
	dato2 = input().split()
	lista1=[]
	lista2=[]
	for i in range(len(dato1)):
		a=int(dato1[i])
		#b=int(dato1[1])
		lista1.append(a)

	for j in range(len(dato2)):
		a=int(dato2[j])
		#b=int(dato2[1])
		lista2.append(a)

	result = calcular(lista1,lista2)
	print(result)


print("Mario Pyramid in Python!")

# Prints mario pyramid given a size
def mario_pyramid(size):

	row = "#"

	# Prints row of blocks
	for block in range(size):
		print(row)
		row+="#"

mario_pyramid(10)

# Prints mario pyramid in reverse
def mario_reverse_pyramid(size):

	row = "#"

	# Prints row of Blocks
	for block in range(size):
		# Prints spaces
		spaces = ""
		for space in range(size - len(row)):
			spaces += " "

		print(spaces+row);
		row += "#"

mario_reverse_pyramid(10)


# -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 18:24:49 2021

@author: G-GRE-GRE050402
"""
# Bfield(0.8)

continuous_acquisition()
continuous_acquisition_ch2()

mwgen.off()
rampVG3(-848.7)
rampVG4(-830.7)
VG5now=VG5()
VG2now=VG2()
VG6now=VG6()
VG1now=VG1()
# 1089_0.899T_MWon10dB_5GHz_G3vsG4COMP_G1-1672.3mV_G2-1377.1969mV_G3-845.0mV_G4-834.0mV_G5-1471.0487mV_G6-1593.2417mV2
# VG6onmin_phD(VG6now-20,VG6now+20,801,1)
VG5onmin_phD(VG5now-5,VG5now+5,401,1)

# VG1onmin_phS(VG1now-20,VG1now+20,801,1)
VG2onmin_phS(VG2now-5,VG2now+5,401,1)

name=str(Bfield())+'T_G3vsG4COMP_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c,d=sweep2D(VG3,-847.3,-846,41,0.05,VG4,-831,-831.6,41,0.02,ph1,ph2)
# a,dataid,c,d=sweep2D(VG3comp,-850,-845,51,0.05,VG4comp,-829,-834,51,0.012,ph1,ph2)
plot_by_id(dataid)
save2plots(name,dataid)
plt.close()
plot_by_id(dataid)

plot2d_diff(dataid)

#########################################################################

continuous_acquisition()
continuous_acquisition_ch2()

detuningPoint1 = [-847.7,-830.5]  #TPC #G3,G4
detuningPoint2 = [-847.2,-831.7]
VG3comp(detuningPoint1[0])
VG4comp(detuningPoint1[1])
DeltaG4G3=(detuningPoint1[0]-detuningPoint2[0])/(detuningPoint1[1]-detuningPoint2[1])

G4detuning=  SpecialParameters.DetuningG4(VG4,VG3,DeltaG4G3)
# G4detuning=  SpecialParameters.CompensateG4(VG4comp,VG3comp,DeltaG4G3)

mwgen.off()
#test detuning
name=str(Bfield())+'T_detuningscan_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c=sweep1D(G4detuning,-830.5,-832.5,101,0.012,ph1,ph2)
plot_by_id(dataid)
saveplot(name,dataid)
plt.show()
#################################

#testrf
mwgen.on()
mwgen.power(3)

name=str(Bfield())+'T_freq_scan_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c=sweep1D(mwgen.frequency,3e9,20e9,501,0.012,ph2)
plot_by_id(dataid)
saveplot(name,dataid)
#calibrate rf power
mwgen.on()
mwgen.power(10)
mwgen.frequency(12e9)
name=str(Bfield())+'T_power_scan_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c=sweep1D(mwgen.power,-10,30,401,0.012,ph1)
plot_by_id(dataid)
saveplot(name,dataid)
#calibrate rf power

mwgen.on()
mwgen.power(20)
name=str(Bfield())+'T_freqvsdetuning_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
mwgen.on()
a,dataid,c,d=sweep2D(G4detuning,-832.5,-831,51,0.05,mwgen.frequency,9e9,19e9,1000,0.01,ph2,ph1)
plot_by_id(dataid)
saveplot(name,dataid)

save2plots(name,dataid)

############
# VG3comp(-846.85)
# VG4comp(-832.8)
Bfield(0.2)
mwgen.on()
mwgen.power(-10)
name=str(Bfield())+'T_freqvsdetuning_power-10dBm_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
mwgen.on()
a,dataid,c,d=sweep2D(mwgen.frequency,3e9,10e9,700,0.01,G4detuning,-830.5,-831.7,81,0.01,ph1,ph2)
plot_by_id(dataid)
save2plots(name,dataid)

##########################

VG3comp(-850)
VG4comp(-829)
VG5onmin_phD(VG5now-5,VG5now+5,401,1)
VG2onmin_phS(VG2now-5,VG2now+5,401,1)
mwgen.on()
name=str(Bfield())+'T_freqvspower_offICT_pulseonG4__45dBatt_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c,d=sweep2D(mwgen.frequency,3e9,20e9,341,0.01,mwgen.power,30,-10,81,0.05,ph2,ph1)
plot_by_id(dataid)
save2plots(name,dataid)
# save4plots(name,dataid)

# data_set,data_get,parameters_name=Extract_data(a)

the_data = load_by_id(dataid)
data_list = the_data.get_parameter_data()
P = the_data.parameters
p = P.split(',')
Y= data_list[p[2]][p[0]]#freq
X = data_list[p[2]][p[1]]#gate
x = np.unique(X)
y = np.unique(Y)
z1 = data_list[p[2]][p[2]]#phS
Z1 = z1.reshape((np.size(np.unique(Y)),np.size(np.unique(X))))
X,Y = np.meshgrid(x,y)

Z1 = z1.reshape((np.size(np.unique(Y)),np.size(np.unique(X))))
par=x
far=y
threshold=-4.1
calib=[]
for i in range(0,len(y)):
    previousmin=10
    for j in range(0,len(x)):
     # Z1[i]=scipy.signal.savgol_filter(Z1[i], 11, 3)
         if np.abs(Z1[i][j]-threshold)<previousmin:
             previousmin= np.abs(Z1[i][j]-threshold)
             argmin=j
    calib.append(x[argmin])

mwfreq_calib=SpecialParameters.Calibrated_Fmw(mwgen.frequency,mwgen.power,calib,far,-5)

np.savetxt(folder2+'\\'+dayFolder+'\\'+str(dataid)+'calibfile.txt',calib)

VG3comp(-846.75)
VG4comp(-831.25)

G4detuning(-831)

mwgen.on()
mwgen.power(16)
name=str(Bfield())+'T_fvsdet_P'+str(mwgen.power()-65)+'dBG1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c,d=sweep2D(mwgen.frequency,10e9,15e9,5001,0.01,G4detuning,-831,-832,81,0.01,ph1,ph2)
plot_by_id(dataid)
save2plots(name,dataid)

VG3comp(-846.75)
VG4comp(-831.25)
G4detuning(-831.75)

Bfield(0.4)
mwgen.on()
mwgen.power(10)
ziUhf.daq.setInt('/dev2010/awgs/0/enable', 1)
ampliAWG(0.1)

name=str(Bfield())+'T_fvsdet_pulsing_P'+str(mwgen.power()-65)+'dBG1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c,d=sweep2D(Bfield_Hon,0.7,0.8,21,1,mwgen.frequency,12e9,18e9,3000,0.005,ph1,ph2)
plot_by_id(dataid)
save2plots(name,dataid)

Bfield(0.4)
mwgen.on()
mwgen.power(10)
ziUhf.daq.setInt('/dev2010/awgs/0/enable', 1)
ampliAWG(0.1)
name=str(Bfield())+'T_freq_scan_pulsing_G1'+str(VG1())+'mV_G2'+str(VG2())+'mV_G3'+str(VG3())+'mV_G4'+str(VG4())+'mV_G5'+str(VG5())+'mV_G6'+str(VG6())+'mV'
a,dataid,c=sweep1D(mwgen.frequency,6.5e9,9e9,25001,0.012,ph2,ph1)
plot_by_id(dataid)
saveplot(name,dataid)
# P0=0
# calib=np.subtract(calib,P0)
# val=3e9
# initF=mwgen.frequency()
# initP=mwgen.power()
# p = np.argmin(np.abs(far-val))
# Power = float(calib[p])
# mwgen.frequency(val)
# mwgen.power(Power+P0)


import json

# status, stations, started, nextrun, train_nr, finished, date
# arrival, departure, station_id, delay, delay_cause, scraped

def print_station(s):
    name = stations[str(s["station_id"])]["name"].ljust(24)
    dep = "     "
    arr = "     "
    if "departure" in s:
        h = s['departure']//60
        m = s['departure']%60
        dep = f"{h:02}:{m:02}"
    if "arrival" in s:
        h = s['arrival']//60
        m = s['arrival']%60
        arr = f"{h:02}:{m:02}"
    delay = ""
    cause = ""
    if "delay" in s:
        delay = s["delay"]
    if "delay_cause" in s:
        cause = s["delay_cause"]
    print("-", name, arr, dep, delay, cause)

def print_train(t):
    print("")
    print(t['train_nr'], t['status'])
    print(t['date'], t['started'], t['finished'], t['nextrun'])
    for s in t['stations']:
        print_station(s)

with open('data/zugfinder_example_stations.json') as myfile:
    stations = json.load(myfile)

with open('data/zugfinder_example_trains.json') as myfile:
    trains = json.load(myfile)
    for i in trains:
        print_train(trains[i])


"""
    Read CSV data from GPUz
"""

# IMPORTS #
import csv

# CLASSES #
class Config:
    default_file_name = r"GPU-Z Sensor Log.txt"
    default_file_encoding = 'cp1250'

class Data:
    def __init__(self,
                 filename,  # Name of the file
                 ):

        # Instnance variables #

        # Raw data from a file
        self.raw_data = str()

        # All data categorized
        self.data = list()

        # Unig mapping dictionary
        self.unit_mapping = dict()

        # Reading a file
        try:
            with open(filename, 'r', encoding=Config.default_file_encoding) as csv_file:
                csv_file_content = csv.DictReader(csv_file)
                for csv_line in csv_file_content:
                    trimmed_line = {
                        key.strip(): value for key, value in csv_line.items()
                    }
                    self.data.append(trimmed_line)

                    # Extract units and create unit_mapping
                    if not self.unit_mapping:
                        self.unit_mapping = {
                            key.strip().split('[')[0].strip(): key.split('[')[-1].rstrip(']')
                            for key in trimmed_line.keys()
                        }

        except FileNotFoundError as e_file_not_found:
            print(f"A file {filename} couldn't be found.")

        self.get_data()

    def get_data(self, column_name=None):
        for line in self.data:
            for key in line.keys():
                stripped_key = key.strip()
                if stripped_key in self.unit_mapping:
                    unit = self.unit_mapping[stripped_key]
                elif stripped_key:
                    if '[' in stripped_key:
                        stripped_key = stripped_key[:stripped_key.index('[')].strip()
                    print(stripped_key)

# RUNTIME #
def main():
    data = Data(Config.default_file_name)

if __name__ == "__main__":
    main()


from rest_framework import viewsets
from wesPool.models import Ride,Requests
from .serializers import UserSerializer,RideSerializer,RequestsSerializer

from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated, BasePermission, SAFE_METHODS, DjangoModelPermissionsOrAnonReadOnly
from django.contrib.auth.models import User
from rest_framework import filters
from rest_framework.permissions import AllowAny
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, OAuth2Authentication
from oauth2_provider.models import AccessToken
from rest_framework.decorators import action
from django.db.models import Q
from functools import reduce
from rest_framework import status
from rest_framework.response import Response
from wesPool.models import Ride, Requests

# Create your views here.
class PostReviewWritePermission(BasePermission):
    message = "Editing posts is restricted to the author only"

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        try:
            user = AccessToken.objects.get(token=request.data['access_token'])
            return True
        except:
            print('not logged in')
            return False
        return obj.host == user.user

class RideViewSet(viewsets.ModelViewSet):
    # queryset = Ride.objects.all()
    serializer_class = RideSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_fields = (
        'src',
        'dst',
        'date_time'
    )

    # def list(self, request):
    #     serializer = ItemSerializer(self.queryset, many=True)
    #     return Response(serializer.data)

    # def perform_create(self, serializer,request):
    #     # here you will send `created_by` in the `validated_data`
    #     user = AccessToken.objects.get(token=request.data['access_token'])
    #     serializer.save(
    #         date_time=self.request.data.date,
    #         src=self.request.data.src,
    #         dst=self.request.data.dst,
    #         seats=self.request.data.seats,
    #         price=self.request.data.price,
    #         uber=self.request.data.uber,
    #         host=user,
    #         group=self.request.data.group
    #     )
    def create(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        del request.data['host']
        del request.data['group']
        request.data['host'] = user.id
        request.data['group'] = [user.id]
        print(request.data['date_time'],'HI AGAIN')
        return super().create(request)

    def get_queryset(self, *args, **kwargs):
        print('hello?',self.request.query_params)
        user = AccessToken.objects.get(token=self.request.META['HTTP_AUTHORIZATION'][7:]).user
        if len(self.request.query_params)==0:
            data = Ride.objects.all()
            return data
        res = []
        res2 = []
        for key in self.request.query_params:
            try:
                if key == "host":
                    res = Ride.objects.filter(host=user)
                if key == "group":
                    res2 = Ride.objects.filter(group__in=[user.id]).exclude(host=user)
            except:
                print('oops')
        final = res | res2
        return final.distinct()

    def get(self, *args, **kwargs):
        print('wa')

    def update(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        ride = Ride.objects.get(id=self.request.data['id'])
        if len(self.request.data)==2:
            print('helllllllooooo')
            user = User.objects.get(id=self.request.data['req_by'])

            # new_lst = []
            for user_d in ride.group.all():
                if user==user_d:
                    return Response({},status.HTTP_204_NO_CONTENT)
            # new_lst.append(user)
            ride.group.add(user)
            # ride.save(update_fields=['group'])
            print(ride.get_fields())
            return Response({}, status.HTTP_204_NO_CONTENT)

        host = ride.host
        old_ride = ride.get_fields()
        if user == old_ride['host']:
            for key in old_ride:
                if key=='id' or key=='host':
                    continue
                if key=='group':
                    if old_ride['group']!=self.request.data['group']:
                        print('hi',old_ride['group'],self.request.data['group'])
                if self.request.data[key]!=old_ride[key]:
                    if key=="src":
                        ride.src = self.request.data[key]
                    elif key=="dst":
                        ride.dst = self.request.data[key]
                    elif key =="uber":
                        ride.uber = self.request.data[key]
                    elif key=="group":
                        ride.group = self.request.data[key]
                    elif key=="seats":
                        ride.seats = self.request.data[key]
                    elif key=="price":
                        ride.price = self.request.data[key]
                    elif key == 'date_time':
                        ride.date_time = self.request.data[key]
                    ride.save(update_fields=[key])
        else:
            print('NOOOO')

        return Response({}, status.HTTP_204_NO_CONTENT)

    def destroy(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        print(self.request.data,"????")
        ride = Ride.objects.get(id=self.request.data['id'])
        old_ride = ride.get_fields()
        if user == old_ride['host']:
            ride.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = User.objects.all()
    serializer_class = UserSerializer

class RequestsViewSet(viewsets.ModelViewSet, PostReviewWritePermission):
    # queryset = Requests.objects.all()
    serializer_class = RequestsSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_fields = (
        'req_by',
        'req_to'
    )

    def create(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        ride = Ride.objects.get(id=request.data['req_to'])
        del request.data['req_by']
        del request.data['req_to']
        request.data['req_by'] = user.id
        request.data['req_to'] = ride.id
        return super().create(request)

    def get_queryset(self, *args, **kwargs):
        # print('hello?',self.request)
        if len(self.request.query_params)==1:
            ride = Ride.objects.get(id=self.request.query_params['req_to'])
            print(Requests.objects.filter(req_to=ride))
            return Requests.objects.filter(req_to=ride)
        user = AccessToken.objects.get(token=self.request.META['HTTP_AUTHORIZATION'][7:]).user
        req = Requests.objects.filter(req_by=user.id)
        return req

    def destroy(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        print(self.request.data,"????")
        req = Requests.objects.get(id=self.request.data['id'])
        req.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


from pool_table import PoolTable
import util

pool_tables = []

for x in range(12):
    pool_tables.append(PoolTable(x+1))

while True:
    util.clear_screen()
    util.display_table_statuses(pool_tables)
    util.display_commands()
    choice = input("Select a choice: ")
    print('')

    try:
        # check into table
        if choice == "1":
            table_number = util.get_pool_table_number_input(
                "Which table is getting checked out?", len(pool_tables))
            pool_tables[table_number].check_out()
        # check out of table
        elif choice == "2":
            table_number = util.get_pool_table_number_input(
                "Which table is getting checked in?", len(pool_tables))
            pool_tables[table_number].check_in()
        # detailed status of table
        elif choice == "3":
            table_number = util.get_pool_table_number_input(
                "Get details from which table?", len(pool_tables))
            pool_tables[table_number].display_details()

        # entry log of table
        elif choice == "4":
            table_number = util.get_pool_table_number_input(
                "Get details from which table?", len(pool_tables))
            pool_tables[table_number].display_entries()

        # entry log of all tables
        elif choice == "5":
            cost = 0.00
            for pool_table in pool_tables:
                pool_table.display_entries(True)
                table_cost = pool_table.get_entries_cost()
                cost += table_cost

            print("===========================")
            print(f"Total Cost: ${cost:.2f}\n")
            input('Press any key to continue...')

        elif choice.lower() == 'q':
            break

        else:
            raise IndexError

    except IndexError:
        util.display_error("Invalid Option")

    except ValueError:
        util.display_error("A number must be entered")


#! /usr/bin/python3

from string import ascii_lowercase
from itertools import combinations
from math import factorial
from functools import lru_cache

letters = [x for x in ascii_lowercase]

@lru_cache(maxsize=None)
def binomial(x, y):
	return int(factorial(x)/(factorial(y)*factorial(x-y)))

#for length in range(3,26):
#	print( length, len( list( combinations( letters, length))))

#check now if all 1 height words can be generated with neighbour transpotions and rotations on the ordered words

#def is1Height( word):
#	vals = list(map(ord, word))
#	flagged = False
#	for i in range( len( vals)-1):
#		if vals[i+1] < vals[i]:
#			if not flagged:
#				flagged = True
#			else:
#				return False #at least two heights
#	return flagged
#
#
#letters = [x for x in "abcd"]
#from itertools import permutations
#for p in permutations( letters):
#	word = "".join( p)
#	if is1Height( word):
#		print( word)

def p(n):
	p = 0
	for l1 in range(1,n):
		l2 = n - l1
		for w1 in combinations(letters, l1):
			complement = [l for l in letters if l not in w1]
			#second loop could be replaced by some smart counting
			#for w2 in combinations(complement, l2):
			#	if w1[-1] > w2[0]:
			#		p += 1
			for index, l in enumerate(complement):#[:-l2+1]):
				if w1[-1] > l and len(complement) - 1 - index >= l2 - 1:
					p += binomial( len(complement) - 1 - index, l2-1)
	return p

for n in range(15,20):
	print( n, p(n))

#solve by splitting with combinations part1 (length 1) + part2 (length 2) with height between part1 and part2


from django.db import models
from django.contrib.auth.models import AbstractUser
from apps.users.validators import validate_file_extension

# Create your models here.

class User(AbstractUser):
    profile_image = models.FileField(
        upload_to='profile_image/',
        validators=[validate_file_extension]
    )
    GENDERS = (
        ('Мужчина', 'Мужчина'),
        ('Женщина', 'Женщина'),
        ('Другое', 'Другое'),
    )
    gender = models.CharField(
        choices=GENDERS,
        default='Другое',
        max_length=20
    )
    phone_number = models.CharField(
        max_length=25
    )
    live_in = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )
    from_in = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )
    status = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = "Пользователь"
        verbose_name_plural = "Пользователи"

class Followers(models.Model):
    to_user = models.ForeignKey(
        User,
        related_name='followers',
        on_delete=models.CASCADE
    )
    from_user = models.ForeignKey(
        User,
        related_name='followings',
        on_delete=models.CASCADE
    )


#!/usr/bin/env python

from TreeNode import TreeNode
import string
import pdb

"""
the reader takes a tree in Newick format,
builds all the nodes and edges and
returns the root node
format: "(A:0.1,B:0.2,(C:0.3,D:0.4):0.5);"
"""

#return root node of the tree
def parse(string):
	node2 = TreeNode(False)
	return build(string, node2, 0, len(string), 1)

#IdCounter = 0

def build(string, parentNode, start, stop, index):
	if(not string[start] == "("):
		id = string[start:stop]
		parentNode.setID(id)
		return parentNode

	b = 0 #bracket counter
	c = 0 #colon counter
	x = start #position marker

	for i in range(start, stop):
		char = string[i]
		if(not char == ";"):
			if(char == "("):
				b = b+1
			elif(char == ")"):
				b = b-1
			elif(char == ':'):
				c = i

			if(b == 0 or b == 1 and char == ","):
				if string[c-1] == "@":
					parentNode.addChildren(build(string, TreeNode(True,parentNode,string[c+1:i],"ancient"), x+1, c-1, index))
				else:
					parentNode.addChildren(build(string, TreeNode(False,parentNode,string[c+1:i],""), x+1, c, index))
				x = i

	return parentNode

def annotateInternalNodes(tree):
	IDCounter = 0
	for j in tree.iternodes(order="postorder"):

		if j.getID() == "" or j.getID() == None:
			j.setID(str(IDCounter))
			IDCounter = IDCounter + 1
	return tree

# testree = "(A:0.1,B:0.2,(C:0.3,D:0.4):0.5);"
# test = parse(testree)
# tree = annotateInternalNodes(test)
# print test.getLeafNames()
# print test.getNewickString(True)
# for j in tree.iternodes(order="postorder"):
#  		if len(j.getChildren()) == 0:
#  			print j.getID()
#  		else:
#  			print j.getID()

# test2 = "((((One:0.2,Two:0.3):0.3,(Three:0.5,Four:0.3):0.2):0.3,Five:0.7):0.0);"
# test = parse(test2)
# print test.getLeafNames()
# print test.getNewickString(True)


# -*- coding: utf-8 -*-
"""
Created on Thu Dec  8 00:07:14 2022

@author: Shahir, Faraz, Pratyush
Modified from: https://github.com/MCG-NJU/VideoMAE
"""

import os
import json

import numpy as np

from torch.utils.data import Dataset

import decord
from PIL import Image

class TinyVIRAT(Dataset):
    def __init__(
            self,
            root_dir,
            train=True,
            num_segments=1,
            new_length=1,
            new_step=1,
            temporal_jitter=False,
            verbose=False):

        super().__init__()

        self.root_dir = root_dir
        self.train = train
        self.num_segments = num_segments
        self.new_length = new_length
        self.new_step = new_step
        self.temporal_jitter = temporal_jitter
        self.verbose = verbose

        self.skip_length = self.new_length * self.new_step

        self.settings_fname = os.path.join(self.root_dir, "tiny_train.json" if train else "tiny_test.json")
        self.data_dir = os.path.join(self.root_dir, "videos", "train" if self.train else "test")

        self.clips, self.label_index_to_class_name = self._make_dataset()
        self.num_channels = 3

        self.rng = np.random.default_rng()

    def __getitem__(self, index):
        video_fname, label = self.clips[index]

        video_reader = decord.VideoReader(video_fname, num_threads=1)
        duration = len(video_reader)

        segment_indices, skip_offsets = self._sample_train_indices(duration)

        # t, PIL image (h, w, c)
        if self.verbose:
            print("Decoding", video_fname, duration, segment_indices, skip_offsets)
        try:
            images_per_frame = self._video_tsn_decord_batch_loader(
                video_reader, duration, segment_indices, skip_offsets)
        except:
            if self.verbose:
                print("Failed to decode", video_fname, duration, segment_indices, skip_offsets)
            raise

        return images_per_frame, label

    def __len__(self):
        return len(self.clips)

    def _make_dataset(self):
        with open(os.path.join(self.root_dir, "tiny_train.json")) as f:
            self.train_settings = json.load(f)
        with open(os.path.join(self.root_dir, "tiny_test.json")) as f:
            self.test_settings = json.load(f)

        all_tubes = self.train_settings["tubes"] + self.test_settings["tubes"]
        selected_set_tubes = self.train_settings["tubes"] if self.train else self.test_settings["tubes"]

        class_names = set()
        class_name_to_label_index = {}
        label_index_to_class_name = {}

        for tube in all_tubes:
            label = tube["label"]
            if label[0] not in class_names:
                class_names.add(label[0])
        class_names = sorted(class_names)

        counter = 0
        for label in class_names:
            class_name_to_label_index[label] = counter
            label_index_to_class_name[counter] = label
            counter = counter + 1
        clips = []
        for tube in selected_set_tubes:
            clip_path = os.path.join(self.data_dir, tube["path"])
            label = tube["label"][0]
            label = class_name_to_label_index[label]
            item = (clip_path, label)
            clips.append(item)

        return clips, label_index_to_class_name

    def _sample_train_indices(self, num_frames):
        average_duration = (
            num_frames - self.skip_length + 1) // self.num_segments
        if average_duration > 0:
            offsets = np.multiply(
                list(range(self.num_segments)), average_duration)
            offsets = offsets + \
                self.rng.integers(average_duration, size=self.num_segments)
        elif num_frames > max(self.num_segments, self.skip_length):
            offsets = np.sort(self.rng.integers(
                num_frames - self.skip_length + 1, size=self.num_segments))
        else:
            offsets = np.zeros((self.num_segments,))

        if self.temporal_jitter:
            skip_offsets = self.rng.integers(
                self.new_step, size=self.skip_length // self.new_step)
        else:
            skip_offsets = np.zeros(self.skip_length // self.new_step)

        return (offsets + 1).astype(int), skip_offsets.astype(int)

    def _video_tsn_decord_batch_loader(
            self,
            video_reader,
            duration,
            segment_indices,
            skip_offsets):

        frame_ids = []

        for segment_index in segment_indices:
            offset = int(segment_index)
            for i, _ in enumerate(range(0, self.skip_length, self.new_step)):
                if offset + skip_offsets[i] <= duration:
                    frame_id = offset + skip_offsets[i] - 1
                else:
                    frame_id = offset - 1
                frame_ids.append(frame_id)
                if offset + self.new_step < duration:
                    offset += self.new_step

        video_data = video_reader.get_batch(frame_ids).asnumpy()
        sampled_images = [Image.fromarray(video_data[i]).convert('RGB') for i in range(len(frame_ids))]

        return sampled_images


import numpy as np

def wkmean(k, data, weights=None, metric='Euclidian',
           MAX_ITERATIONS=1000, method='k++'):
    """
    Weighted k-means algorithm with relative weighted population count
    for each cluster. Returns the best centroids in the form
    positions, relative weighted populations and fit errror.
    If no weights are provided all data points are assumed to be equal.
    If no metric is provided, the standard Euclidian metric is used.
    Possible methods are:
        'k++_pdf' for kmeans++ initialization with PDF distributed choice
        'k++_max' for kmeans++ initialization with farthest point choice
        'uniform' for uniform [-0.5, 0.5] initialization
    """

    def euclidian_metric(coords):
        return (coords**2).sum(axis=1)

    def kmeans_plus_plus_initialization(X, k, pdf_method=True):
        '''Initialize one point at random. Loop for k - 1 iterations:
        Next, calculate for each point the distance of the point from its
        nearest center. Sample a point with a probability proportional to
        the square of the distance of the point from its nearest center.'''
        def distance_to_centroids(data, centers):
            distance = np.sum((np.array(centers) - data[:, None, :])**2,
                              axis=2)
            return distance

        centers = []
        X = np.array(X)

        # Sample the first point
        initial_index = np.random.choice(range(X.shape[0]), )
        centers.append(X[initial_index, :].tolist())

        # Loop and select the remaining points
        for i in range(k - 1):
            distance = distance_to_centroids(X, np.array(centers))

            if i == 0:
                pdf = distance/np.sum(distance)
                centroid_new = X[np.random.choice(range(X.shape[0]),
                                                  replace=False,
                                                  p=pdf.flatten())]
            else:
                # Calculate the distance of each point to its nearest centroid
                dist_min = np.min(distance, axis=1)
                if pdf_method is True:
                    pdf = dist_min/np.sum(dist_min)
                    # Sample one point from the given distribution
                    centroid_new = X[np.random.choice(range(X.shape[0]),
                                                      replace=False,
                                                      p=pdf)]
                else:
                    index_max = np.argmax(dist_min, axis=0)
                    centroid_new = X[index_max, :]
            centers.append(centroid_new.tolist())

        return np.array(centers)

    # Uniform random initialization
    def random_coord_initialization(data, k):
        dim = np.array(data[1]).shape[0]
        centroids = [np.random.rand(dim) - 0.5 for _ in range(k)]
        return np.array(centroids)

    # Stop criteria for k-means update
    def should_stop(oldCentroids, centroids, iterations):
        if iterations > MAX_ITERATIONS:
            return True
        return (oldCentroids == centroids).all()

    # Returns array of indexes of closest centroid for each point
    def assign_centroids(data, centroids):
        distances = [0 for _ in range(k)]
        for ii in range(k):
            diff = data - centroids[ii]
            distances[ii] = metric(diff)
        distances = np.array(distances)
        closest_centroid = distances.argmin(axis=0)
        return closest_centroid

    # New centroid positions, their relative weighted population and error
    def update_centroids(data, weights, labels):
        neighborhood = np.array([labels == jj for jj in range(k)])
        neighborhood = neighborhood * weights
        # Sets unnormalized cumulative centroid
        centroids = neighborhood.dot(data)

        populations = np.array([0 for _ in range(k)]).astype(float)
        error = 0
        for jj in range(k):
            s = sum(neighborhood[jj])
            if s != 0:
                centroids[jj] = centroids[jj] / s
                diff = data - centroids[jj]
                distances = metric(diff)
                error += distances.dot(neighborhood[jj])
                populations[jj] = s
        return np.array(centroids), populations, error

    # Make the initial preparations
    data = np.array(data)
    if weights is None:
        weights = np.array([1 for _ in data])
    else:
        weights = np.array(weights)
        weights = weights / sum(weights)
    if metric == 'Euclidian':
        metric = euclidian_metric
    if method == 'uniform':
        def initialize_centroids(data, k):
            return random_coord_initialization(data, k)
    elif method == 'k++_max':
        def initialize_centroids(data, k):
            return kmeans_plus_plus_initialization(data, k, pdf_method=False)
    elif method == 'k++_pdf':
        def initialize_centroids(data, k):
            return kmeans_plus_plus_initialization(data, k, pdf_method=True)
    else:
        raise NotImplementedError()

    # Initialize clusters
    centroids = initialize_centroids(data, k)
    populations = [0 for _ in range(k)]
    error = 10**15

    # Initialize book keeping vars
    iterations = 0
    oldCentroids = None

    # Repeat until centroids converge to a local minima
    while not should_stop(oldCentroids, centroids, iterations):
        oldCentroids = centroids
        iterations += 1

        # Find the closest centroid for each point
        labels = assign_centroids(data, centroids)

        # Update centroid positions
        centroids, populations, error = update_centroids(data,
                                                         weights, labels)

    return np.array(centroids), np.array(populations), error


from collections import deque

# it's basically a double ended queue
# so you can append and pop from both sides

d = deque()

d.append(1)
d.append(2)
d.appendleft(0)

print(d[0])


import sympy as sp

def calculator():
    print("Calculadora Matemática")
    print("Ingrese una expresión matemática:")
    expression = input()

    try:
        # Parseamos la expresión matemática
        expr = sp.sympify(expression)

        # Resolvemos la expresión
        result = sp.solve(expr)

        # Mostramos la solución
        print("Solución:", result)

        # Mostramos el procedimiento paso a paso
        steps = sp.solve(expr, dict=True)
        print("\nProcedimiento:")
        for step in steps:
            for variable, value in step.items():
                print(f"{variable} = {value}")

    except Exception as e:
        print("Error al resolver la expresión:", e)

if __name__ == "__main__":
    calculator()


import nltk

def load_and_tag_words(filename):
    words = []
    with open(filename, 'r') as words_file:
        for line in words_file:
            words.append(line.strip())

    tags = []
    for word in words:
        text = nltk.word_tokenize(word)
        a = nltk.pos_tag(text)
        for item in a:
            tags.append(f'1    {item[1]} {item[0]}')

    tags.sort()
    return tags

if __name__ == "__main__":
    tags = load_and_tag_words('allowed_words.txt')
    with open('G_Vocab.gr', 'w') as vocab_file:
        for tag in tags:
            vocab_file.write(f'{tag}\n')