import os
from pathlib import Path
from loguru import logger

import cv2
import numpy as np
from pycocotools.coco import COCO

from torch.utils.data.dataset import Dataset
from torchvision.io import read_image
# 用 cv2 是因为需要插值 resize....

class CocoDataset(Dataset):
    """
    COCO dataset class.
    """

    def __init__(
        self,
        data_dir = '',
        json_file="instances_train2017.json",
        imgs_dirname="train2017",
        preproc=None,
        coco = None
    ):
        """
        COCO dataset initialization. Annotation data are read into memory by COCO API.
        Args:
            data_dir (str): dataset root directory
            json_file (str): COCO json file name
            imgs_dirname (str): COCO data imgs_dir (e.g. 'train2017' or 'val2017')
            img_size (int): target image size after pre-processing
            preproc: data augmentation strategy
        """
        super().__init__()
        self.data_dir = data_dir
        if coco is not None:
            self.coco = coco
        elif len(json_file) > 0:
            self.json_file = json_file
            self.coco = COCO(self.json_file)
        else:
            raise RuntimeError('where is the data?')
            return

        self._remove_useless_info(self.coco)
        self.ids = self.coco.getImgIds()
        # category
        self.class_ids = sorted(self.coco.getCatIds())
        self.cats = self.coco.loadCats(self.coco.getCatIds())
        self.classes = tuple([c["name"] for c in self.cats]) #
        # self.imgs = None # 没这么大的内存去将数据集放RAM中....
        self.imgs_dirname = imgs_dirname
        self.preproc = preproc
        # list of (list of [x1,y1,x2,y2,category_id], img_info, resized_info, file_name)
        self.annotations = self._load_coco_annotations()

    def _remove_useless_info(self,coco):
        """
        Remove useless info in coco dataset. COCO object is modified inplace.
        This function is mainly used for saving memory (save about 30% mem).
        """
        if isinstance(coco, COCO):
            dataset = coco.dataset
            dataset.pop("info", None)
            dataset.pop("licenses", None)
            for img in dataset["images"]:
                img.pop("license", None)
                img.pop("coco_url", None)
                img.pop("date_captured", None)
                img.pop("flickr_url", None)
            if "annotations" in coco.dataset:
                for anno in coco.dataset["annotations"]:
                    anno.pop("segmentation", None)

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

    def _load_coco_annotations(self):
        # 每张图片都有一个 tuple 的 annotation
        return [self.load_anno_from_ids(_ids) for _ids in self.ids]

    def load_anno_from_ids(self, id_):
        # 相比原来去掉了 resized_info ，标签缩放与图片缩放都在 _resize_img_and_labels
        im_ann = self.coco.loadImgs(id_)[0]
        width = im_ann["width"]
        height = im_ann["height"]
        anno_ids = self.coco.getAnnIds(imgIds=[int(id_)], iscrowd=False)
        annotations = self.coco.loadAnns(anno_ids)
        objs = []

        # 读取标签，得到 box 的左上角点与右下角点(原json文件是[xmin,ymin,w,h]格式)
        for obj in annotations:
            x1 = np.max((0, obj["bbox"][0]))
            y1 = np.max((0, obj["bbox"][1]))
            x2 = np.min((width, x1 + np.max((0, obj["bbox"][2]))))
            y2 = np.min((height, y1 + np.max((0, obj["bbox"][3]))))
            if obj["area"] > 0 and x2 >= x1 and y2 >= y1:
                obj["clean_bbox"] = [x1, y1, x2, y2]
                objs.append(obj)

        num_objs = len(objs)

        labels = np.zeros((num_objs, 5))

        for ix, obj in enumerate(objs):
            cls = self.class_ids.index(obj["category_id"])
            labels[ix, 0:4] = obj["clean_bbox"]
            labels[ix, 4] = cls
        img_hw = (height, width)
        file_name =  im_ann["file_name"] if "file_name" in im_ann else "{:012}".format(id_) + ".jpg"

        return (labels,img_hw,file_name)

    def load_anno(self, index):

        return self.annotations[index][0]

    def load_image(self, file_name):
        '''
        读取图片
        默认使用 opencv 的 imread 读取，颜色 BGR，shape[H,W,3]
        '''
        img_file_path = os.path.join(self.data_dir, self.imgs_dirname, file_name)
        img = cv2.imread(img_file_path)
        assert img is not None, f"file named {img_file_path} not found"

        # # Tensor[image_channels, image_height, image_width] uint8
        # img = read_image(img_file_path)
        return img

    def __getitem__(self, index):
        """
        通过给定 index 获取 图片与标签即图片COCO的id

        """
        if index > len(self) - 1:
            raise IndexError("index {} is out of range".format(index))
        img_id = np.array([self.ids[index]]) # 获取图片的 id ndarray([id])

        labels,img_hw, file_name = self.annotations[index]

        file_names = file_name.split('/')
        file_name = file_names[-2] + '/' + file_names[-1]
        logger.info('[{}][{}][{}]',labels,img_hw, file_name)
        img = self.load_image(file_name)

        # 图片缩放放至 preproc 中
        # img,labels = _resize_img_and_labels(img,labels)

        if self.preproc is not None:
            img, labels = self.preproc(img, labels)
        return img, labels, np.array(img_hw),img_id

def test_coco():
    data_dir ='D:/Liyi/Datasets/DETRAC'
    jsonfile = "coco_anno.json"
    coco = COCO(os.path.join(data_dir, "annotations", jsonfile))

    ids = coco.getImgIds()
    print('ids',len(ids),' ',ids[0])
    class_ids = sorted(coco.getCatIds())
    print('class_ids',len(class_ids),' ',class_ids[0])
    cats = coco.loadCats(coco.getCatIds())
    print('cats',len(cats),cats[0])
    classes = tuple([c["name"] for c in cats])
    print(classes[cats[0]['id']-1])

    test_id = ids[0]
    im_ann = coco.loadImgs(test_id) #dict
    print('im_ann',len(im_ann),' ',im_ann[0])
    im_ann = im_ann[0]
    width = im_ann["width"]
    height = im_ann["height"]
    # 一张图片对应多个标签
    anno_ids = coco.getAnnIds(imgIds=[int(test_id)], iscrowd=False)
    print('anno_ids',anno_ids)
    annotations = coco.loadAnns(anno_ids)
    print('annotations',len(annotations),annotations[2])
    print('dataset',len(coco.dataset['annotations']),coco.dataset['annotations'][0]['category_id'])

    print('-----------------------------------------------------------------------')

def test():
    from torchvision.utils import make_grid
    from data_transform import TrainTransform

    print(__file__)
    data_dir = 'D:/Liyi/Datasets/DETRAC'
    jsonfile = 'test.json'# "D:/Liyi/Datasets/DETRAC/DETRAC-Train-Annotations-XML/coco_anno.json"
    cocoDataset = CocoDataset(data_dir,jsonfile,"Insight-MVT_Annotation_Train")

    # print(cocoDataset.cats)
    preproc = TrainTransform(need_size=(640,640),
                        max_labels=120,
                        flip_prob=0.5,
                        hsv_prob=0.5)

    import sys
    import copy
    sys.path.append(str(Path(__file__).parent.parent).replace('/','\\'))
    from utils.functions import show_box_on_img,cxcywh2xyxy

    for idx in np.random.randint(low=0,high=len(cocoDataset),size=(10,)):
        orig_img,orig_targets,img_hw,_ = cocoDataset[idx]

        img, targets = preproc(copy.deepcopy(orig_img), copy.deepcopy(orig_targets))
        logger.info(orig_img.shape)
        logger.info(img.shape)
        logger.info(orig_targets)
        img_file_name = cocoDataset.annotations[idx][2]
        logger.info(img_file_name)
        # print(cocoDataset.annotations[idx][0])
        # show_box_on_img(img.astype(np.uint8),targets,cocoDataset.classes,mode='xyxy')
        # 数据增强后变为了 cxcywh
        # print(targets)
        logger.info('cxcywh\n {}',targets[targets.sum(1)>0])

        img = img.numpy().astype(np.uint8).transpose(1,2,0)

        # 这之前应该是没问题的
        show_box_on_img(img,targets,cocoDataset.classes,mode='cxcywh')
        # target:[x1,y1,x2,y2,category]

        # 缩放逆运算
        logger.info('xyxy\n {}',targets[targets.sum(1)>0])
        # opencv img : [h,w,3]

        scale = min(
                img.shape[1] / float(img_hw[0]), img.shape[2] / float(img_hw[1])
            )
        start_x = int((img.shape[2] - int(img_hw[1]*scale)) / 2)
        start_y = int((img.shape[1] - int(img_hw[0]*scale)) / 2)
        logger.info('{},{},{}',start_x,start_y,scale)
        logger.info('scale orig xyxy\n {}',orig_targets*scale)
        # 这一步仅缩放时图片靠左靠上才行，居中不行
        targets[targets.sum(1)>0,0:4:2] -=  start_x
        targets[targets.sum(1)>0,1:4:2] -=  start_y
        targets[:,:4] /= scale
        logger.info(targets[targets.sum(1)>0])
        # show_box_on_img(orig_img,targets,cocoDataset.classes,mode='xyxy')
        logger.info('-'*42)

if __name__ == "__main__":
    test()


import logging

_logger = logging.getLogger(__name__)

import pytz
from datetime import datetime

from odoo import osv
from odoo import models, fields, api, _

from odoo.addons.Weladee_Attendances.models.sync.weladee_base import renew_connection, sync_loginfo, sync_logerror, sync_logdebug, sync_logwarn, sync_stop, sync_has_error
from odoo.addons.Weladee_Attendances_timesheet.models.sync.weladee_customer import sync_customer
from odoo.addons.Weladee_Attendances_timesheet.models.sync.weladee_project import sync_project
from odoo.addons.Weladee_Attendances_timesheet.models.sync.weladee_task import sync_task
from odoo.addons.Weladee_Attendances_timesheet.models.sync.weladee_worktype import sync_work_type
from odoo.addons.Weladee_Attendances_timesheet.models.sync.weladee_timesheet import sync_timesheet

class weladee_attendance_timesheet(models.TransientModel):
    _inherit="weladee_attendance.synchronous"

    def init_param(self):
        r = super(weladee_attendance_timesheet, self).init_param()

        # for timesheet
        r.customer_obj = False
        r.customer_odoo_weladee_ids = {}
        ''' map customer, key: weladee customer id,value: customer odoo id'''

        r.project_obj = False
        r.project_odoo_weladee_ids = {}
        ''' map project, key: weladee project id,value: project odoo id'''

        r.task_obj = False
        r.task_odoo_weladee_ids = {}
        ''' map task, key: weladee task id,value: task odoo id'''

        r.user_odoo_weladee_ids = {}
        ''' map user, key: weladee employee id,value: user odoo id'''

        r.work_type_obj = False
        r.work_type_odoo_weladee_ids = {}
        ''' map work type, key: weladee work type id,value: work type odoo id'''

        r.timesheet_obj = False

        return r

    def do_sync_options(self, req):
        super(weladee_attendance_timesheet, self).do_sync_options(req)

        if req.config.sync_timesheet and not sync_has_error(req.context_sync):

            if not req.config.timehsheet_account_analytic_id:
               sync_stop(req.context_sync)
               sync_logerror(req.context_sync,'Please setup Account Analytic at Weladee settings -> Timesheet')
               return

            sync_logdebug(req.context_sync,"Start sync...Customer")
            req.customer_obj = self.env['res.partner']
            sync_customer(req)

            sync_logdebug(req.context_sync,"Start sync...Project")
            req.project_obj = self.env['project.project']
            req.task_obj = self.env['project.task']
            req.timesheet_obj= self.env['account.analytic.line']
            sync_project(req)

            sync_logdebug(req.context_sync,"Start sync...Task")
            sync_task(req)

            sync_logdebug(req.context_sync,"Start sync...Work type")
            req.work_type_obj = self.env['mail.activity.type']
            sync_work_type(req)

            sync_logdebug(req.context_sync,"Start sync...Timesheet")
            sync_timesheet(req)


from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
import random
import save_manager

def get_stats(driver):
    return driver.find_element_by_id("cookies").text

def _list_numerated_elements_by_id(driver, name, attempts=10):
    elements = []
    ind = 0
    for _ in range(attempts):
        try:
            elements.append(driver.find_element_by_id('{0}{1}'.format(name, ind)))
            ind += 1
        except Exception:
            break
    return elements

def try_click_list(clickable_list):
    for ind in range(len(clickable_list) - 1, -1, -1):
        try:
            clickable_list[ind].click()
        except Exception:
            clickable_list.pop(ind)
            continue

def click_ups(driver, update_attempts=5):
    upgrades = _list_numerated_elements_by_id(driver, 'upgrade')
    products = _list_numerated_elements_by_id(driver, 'product')

    for _ in range(update_attempts):
        if random.random() < 0.5:
            try_click_list(upgrades)
        else:
            try_click_list(products)

def _print_border():
    print('-' * 20)

def refresh_info(driver):
    _print_border()
    print('Stats before upgrades:\n', get_stats(driver))
    click_ups(driver)
    print('Stats after upgrades:\n', get_stats(driver))
    _print_border()

def get_cookie(driver, attempts=10):
    for _ in range(attempts):
        try:
            big_cookie = WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.ID, 'bigCookie')))
            big_cookie.click()
            return big_cookie
        except Exception:
            pass
    assert False, "Big Cookie "

def farm(driver, farm_time):
    big_cookie = get_cookie(driver)

    time_end = time.time() + farm_time
    next_refresh = 100
    next_save = 50000
    while time.time() < time_end:
        driver.execute_script('arguments[0].click();', big_cookie)
        next_refresh -= 1
        next_save -= 1
        if next_refresh <= 0:
            refresh_info(driver)
            next_refresh = random.randint(10, 30) * 1000
            print("Next refresh in {0} clicks".format(next_refresh))
        if next_save <= 0:
            save_manager.download_save_file(driver)
            next_save = 50000


# -*- encoding: utf8 -*-

import json

import asyncio
import ormar

import pandas as pd

from db import MentalModel

async def build_model(model_info:dict):

    try:
        model = await MentalModel.objects.get(title=model_info['title'])
    except ormar.exceptions.NoMatch:
        model = MentalModel(
            title = model_info['title']
        )
        await model.save()

    model.summary = model_info['summary']
    model.tags = model_info['tags']
    model.chatpan_assistant_uuid = model_info['chatpan_assistant_uuid']

    await model.save()

async def get_all_models(model_json_file:str = 'models/models.json'):

    return json.loads(open(model_json_file, 'r').read())

async def write_all_models(file_path:str, to_file:str):

    df = pd.read_excel(file_path, sheet_name="models")

    model_data_list = []
    id_idx = 0
    for index, row in df.iterrows():
        id_idx = id_idx + 1

        model_data_list.append({
            "id": id_idx,
            "title": row['title'].strip(),
            "summary" : row['summary'].strip(),
            # "tags" : row['tags'],
            "chatpan_assistant_uuid": row['chatpan_assistant_uuid'].strip(),
            "chatpan_room_uuid": row['chatpan_room_uuid'].strip()
        })

    # for model_info in model_data_list:
    #     # build_model(model_info)
    #     print(model_info)

    open(to_file, 'w').write(json.dumps(model_data_list, indent=2))

    return model_data_list

if __name__ == '__main__':

    asyncio.run(write_all_models('models/models.xlsx', 'models/models.json'))


import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
import cv2
from scipy.misc import imsave
import scipy.io
from scipy.misc import toimage
#reading input data
data_path = os.getcwd() + "/data"
save_path = os.getcwd() + "/checkpoint/vcegan2.ckpt"
filename_list = []
for path,dirs,files in os.walk(data_path):
  for file in files:
    filename_list.append(os.path.join(data_path,file))

filename_queue = tf.train.string_input_producer(filename_list)

image_reader = tf.WholeFileReader()

_, image_file = image_reader.read(filename_queue)

img = tf.expand_dims(tf.image.resize_image_with_crop_or_pad(tf.image.decode_jpeg(image_file),28,28),axis=0)

# print(img)

X = tf.cast(tf.train.shuffle_batch([img], 65, 100, 90, enqueue_many=True, shapes=[28,28,3],num_threads=1),tf.float32)

X1 = tf.image.resize_images(X,[14,14])

#initializing capsule parameters
caps1_n_maps = 32
caps1_n_caps = caps1_n_maps * 6 * 6  # 1152 primary capsules
caps1_n_dims = 8

conv1_params = {
    "filters": 256,
    "kernel_size": 9,
    "strides": 1,
    "padding": "valid",
    "activation": tf.nn.relu,
}

conv2_params = {
    "filters": caps1_n_maps * caps1_n_dims, # 256 convolutional filters
    "kernel_size": 9,
    "strides": 1,
    "padding": "same",
    "activation": tf.nn.relu
}

#primary caps layer
conv1 = tf.layers.conv2d(X1, name="enc_conv1", **conv1_params)
conv2 = tf.layers.conv2d(conv1, name="enc_conv2", **conv2_params)

caps1_raw = tf.reshape(conv2, [-1, caps1_n_caps, caps1_n_dims],
                       name="enc_caps1_raw")

def squash(s, axis=-1, epsilon=1e-7, name=None):
    with tf.name_scope(name, default_name="squash"):
        squared_norm = tf.reduce_sum(tf.square(s), axis=axis,
                                     keep_dims=True)
        safe_norm = tf.sqrt(squared_norm + epsilon)
        squash_factor = squared_norm / (1. + squared_norm)
        unit_vector = s / safe_norm
        return squash_factor * unit_vector

caps1_output = squash(caps1_raw, name="enc_caps1_output")

caps2_n_caps = 10
caps2_n_dims = 25

init_sigma = 0.1

# part to whole relationship mapping using W_init

W_init = tf.random_normal(
    shape=(1, caps1_n_caps, caps2_n_caps, caps2_n_dims, caps1_n_dims),
    stddev=init_sigma, dtype=tf.float32, name="enc_W_init")
W = tf.Variable(W_init, name="enc_W")

batch_size = tf.shape(X)[0]

#final weight
W_tiled = tf.tile(W, [batch_size, 1, 1, 1, 1], name="enc_W_tiled")

caps1_output_expanded = tf.expand_dims(caps1_output, -1,
                                       name="caps1_output_expanded")
caps1_output_tile = tf.expand_dims(caps1_output_expanded, 2,
                                   name="caps1_output_tile")

#final primary caps output
caps1_output_tiled = tf.tile(caps1_output_tile, [1, 1, caps2_n_caps, 1, 1],
                             name="enc_caps1_output_tiled")

#final predictions for second caps
caps2_predicted = tf.matmul(W_tiled, caps1_output_tiled,
                            name="enc_caps2_predicted")

#bij matrix
raw_weights = tf.zeros([batch_size, caps1_n_caps, caps2_n_caps, 1, 1],
                       dtype=np.float32, name="enc_raw_weights")

# Round 1

routing_weights = tf.nn.softmax(raw_weights, dim=2, name="enc_routing_weights")

weighted_predictions = tf.multiply(routing_weights, caps2_predicted,
                                   name="weighted_predictions")
weighted_sum = tf.reduce_sum(weighted_predictions, axis=1, keep_dims=True,
                             name="weighted_sum")

caps2_output_round_1 = squash(weighted_sum, axis=-2,
                              name="caps2_output_round_1")

# Round 2

caps2_output_round_1_tiled = tf.tile(
    caps2_output_round_1, [1, caps1_n_caps, 1, 1, 1],
    name="caps2_output_round_1_tiled")

agreement = tf.matmul(caps2_predicted, caps2_output_round_1_tiled,
                      transpose_a=True, name="agreement")

raw_weights_round_2 = tf.add(raw_weights, agreement,
                             name="raw_weights_round_2")

routing_weights_round_2 = tf.nn.softmax(raw_weights_round_2,
                                        dim=2,
                                        name="routing_weights_round_2")
weighted_predictions_round_2 = tf.multiply(routing_weights_round_2,
                                           caps2_predicted,
                                           name="weighted_predictions_round_2")
weighted_sum_round_2 = tf.reduce_sum(weighted_predictions_round_2,
                                     axis=1, keep_dims=True,
                                     name="weighted_sum_round_2")
caps2_output_round_2 = squash(weighted_sum_round_2,
                              axis=-2,
                              name="caps2_output_round_2")

flat_caps2 = tf.layers.flatten(caps2_output_round_2)

fc1 = tf.nn.relu(tf.layers.dense(flat_caps2, 250, name="enc_fc1"))

# print(fc1)
# print(tf.squeeze(caps2_output_round_2))

def generator(inpu, reuse=False):
	with tf.variable_scope("generate") as scope:

		if reuse:
			scope.reuse_variables()

		fulc = tf.nn.relu(tf.layers.dense(inpu, 490))
		reshp = tf.reshape(fulc,[-1,7,7,10])
		hidden1 = tf.nn.relu(tf.layers.conv2d_transpose(reshp, 128, [5,5], strides=(1,1), padding="VALID",name="hidden1"))
		hidden2 = tf.nn.relu(tf.layers.conv2d_transpose(hidden1, 64, [5,5], strides=(1,1),padding="VALID",name="hidden2"))
		hidden3 = tf.nn.relu(tf.layers.conv2d_transpose(hidden2, 32, [5,5], strides=(1,1),padding="VALID",name="hidden3"))
		hidden4 = tf.nn.relu(tf.layers.conv2d_transpose(hidden3, 16, [5,5], strides=(1,1),padding="VALID",name="hidden4"))
		hidden5 = tf.nn.relu(tf.layers.conv2d_transpose(hidden4, 8, [4,4], strides=(1,1),padding="VALID",name="hidden5"))
		gen_output = tf.layers.conv2d_transpose(hidden5,3,[3,3], strides=(1,1), padding="VALID",name="gen_output")

		return tf.nn.tanh(gen_output)

def discriminator(inpu):
	with tf.variable_scope("discriminator", reuse=tf.AUTO_REUSE) as scope:

		dconv1 = tf.nn.relu(tf.layers.conv2d(inpu,name="dconv1",filters=64,kernel_size=3,strides=2,padding="VALID"))
		dconv2 = tf.nn.relu(tf.layers.conv2d(dconv1,name="dconv2",filters=256,kernel_size=3,strides=1,padding="VALID"))
		dconv3 = tf.nn.relu(tf.layers.conv2d(dconv2,name="dconv3",filters=512,kernel_size=3,strides=1,padding="VALID"))
		dconv4 = tf.layers.conv2d(dconv3,name="dconv4",filters=512,kernel_size=3,strides=1,padding="VALID")

		dconv5 = tf.nn.relu(tf.layers.conv2d(dconv4,name="dconv5",filters=256,kernel_size=3,strides=1,padding="VALID"))
		dconv6 = tf.layers.flatten(tf.nn.relu(tf.layers.conv2d(dconv5,name="dconv6",filters=128,kernel_size=3,strides=1,padding="VALID")))

		dfc = tf.nn.relu(tf.layers.dense(dconv6,256))

		disc_output = tf.nn.sigmoid(tf.layers.dense(dfc,1))

		return disc_output

def NLLNormal(pred, target):
	c = -0.5 * tf.log(2 * np.pi)
	multiplier = 1.0 / (2.0 * 1)
	tmp = tf.square(pred - target)
	tmp *= -multiplier
	tmp += c
	return tmp

x_tilde = generator(fc1, reuse=False)

real = discriminator(X)

print(real)

fake = discriminator(x_tilde)

print(fake)

# kl_loss = -0.5 * tf.reduce_sum(1 + z_sigma - tf.pow(z_mean, 2) - tf.exp(z_sigma))

D_loss = -tf.reduce_mean(tf.log(real + 1e-12) + tf.log((1. - fake) + 1e-12))

generation_loss = tf.reduce_mean(tf.square(X - x_tilde))

# latent_loss = - 0.5 * tf.reduce_sum(1 + z_sigma - tf.square(z_mean) - tf.square(tf.exp(z_sigma)))

G_loss = -tf.reduce_mean(tf.log(fake + 1e-12))

total_loss = generation_loss

t_variables = tf.trainable_variables()

# encoder_variables = [var for var in t_variables if 'enc_' in var.name]
generator_variables = [var for var in t_variables if 'generate' or 'enc_' in var.name]
discriminator_variables = [var for var in t_variables if 'discri' in var.name]

# global_step = tf.Variable(0, trainable=False)
# add_global = global_step.assign_add(1)
# new_learning_rate = tf.train.exponential_decay(0.0003, global_step=global_step, decay_steps=10000,
#                                                    decay_rate=0.98)

d_solver = tf.train.GradientDescentOptimizer(learning_rate = 1e-4).minimize(D_loss,var_list=discriminator_variables)

e_solver = tf.train.AdamOptimizer(learning_rate = 1e-4).minimize(total_loss,var_list=generator_variables)

g_solver = tf.train.AdamOptimizer(learning_rate = 1e-4).minimize(G_loss,var_list=generator_variables)

init = tf.global_variables_initializer()

saver = tf.train.Saver()

restore_check = False

with tf.Session() as sess:

	if restore_check and tf.train.checkpoint_exists(save_path):
		saver.restore(sess,save_path)
	else:
		sess.run(init)

	coord = tf.train.Coordinator()
	threads = tf.train.start_queue_runners(coord=coord)

	for iterations in range(10000*3000):

		if(iterations<10000):
			_,tlloss,recon, I = sess.run([e_solver, total_loss, x_tilde, X])
			if(iterations%30 == 0):
				print("patches: {}  tloss: {:.5f}".format(iterations, tlloss))
				imsave(os.getcwd()+"/recon.jpg",recon[0])
				imsave(os.getcwd()+"/og.jpg",I[0])
				continue

		_,tlloss = sess.run([e_solver, total_loss])
		_,d_loss = sess.run([d_solver, D_loss])
		_, g_loss, recon, I = sess.run([g_solver, G_loss, x_tilde, X])

		# new_learn_rate = sess.run(new_learning_rate)

		# if new_learn_rate > 0.00005:
		# 	sess.run(add_global)

		if(iterations%30 == 0):
			print("\rPatches: {}  gLoss: {:.5f} dLoss: {:.5f}".format(
                    iterations,
                    g_loss,
                    d_loss))
			save = saver.save(sess,save_path)
			imsave(os.getcwd()+"/recon.jpg",recon[0])
			imsave(os.getcwd()+"/og.jpg",I[0])

	coord.request_stop()
	coord.join(threads)


"""hackovid URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url

from purchase import views

urlpatterns = [
    url(r'^list/$', views.list, name='purchase_list'),
    url(r'^shop/(?P<id>[0-9A-Za-z_\-]+)/(?P<time_str>[0-:_\-]+)/$', views.info, name='go_shop'),
    url(r'^user_list/$', views.userList, name='user_list'),
    url(r'^info/(?P<id>[0-9A-Za-z_\-]+)/$', views.infoUserPurchase, name='purchase'),
    url(r'^qr_accept_purchase/(?P<id>[0-9A-Za-z_\-]+)/$', views.qrreaded, name='qr_read'),
]


import os
from typing import Union
from typing import Dict

from flexmock import flexmock
import pytest
from pathlib import Path
import json
import yaml

from thoth.adviser.boot import Boot
from thoth.adviser.enums import DecisionType
from thoth.adviser.enums import RecommendationType
from thoth.adviser.pipeline_builder import PipelineBuilder
from thoth.adviser.pipeline_builder import PipelineBuilderContext
from thoth.adviser.pseudonym import Pseudonym
from thoth.adviser.sieve import Sieve
from thoth.adviser.step import Step
from thoth.adviser.stride import Stride
from thoth.adviser.unit import Unit
from thoth.adviser.wrap import Wrap
from thoth.adviser.exceptions import PipelineConfigurationError
from thoth.adviser.exceptions import UnknownPipelineUnitError
from thoth.python import Project

import tests.units as units

from .base import AdviserTestCase
from .helpers import use_test_units

@pytest.fixture
def builder_context() -> PipelineBuilderContext:
    """Fixture for a builder context."""
    builder_context = PipelineBuilderContext(
        graph=None,
        project=None,
        library_usage=None,
        labels={},
        decision_type=DecisionType.RANDOM,
        recommendation_type=None,
    )
    builder_context.add_unit(units.boots.Boot1())
    builder_context.add_unit(units.pseudonyms.Pseudonym1())
    builder_context.add_unit(units.sieves.Sieve1())
    builder_context.add_unit(units.steps.Step1())
    builder_context.add_unit(units.strides.Stride1())
    builder_context.add_unit(units.wraps.Wrap1())
    return builder_context

class TestPipelineBuilderContext(AdviserTestCase):
    """Test context carried within pipeline builder."""

    def test_is_included(self, builder_context: PipelineBuilderContext) -> None:
        """Test check if the given pipeline unit is included."""
        assert builder_context.is_included(units.boots.Boot1)
        assert not builder_context.is_included(units.boots.Boot2)
        assert builder_context.is_included(units.pseudonyms.Pseudonym1)
        assert not builder_context.is_included(units.pseudonyms.Pseudonym2)
        assert builder_context.is_included(units.sieves.Sieve1)
        assert not builder_context.is_included(units.sieves.Sieve2)
        assert builder_context.is_included(units.steps.Step1)
        assert not builder_context.is_included(units.steps.Step2)
        assert builder_context.is_included(units.strides.Stride1)
        assert not builder_context.is_included(units.strides.Stride2)
        assert builder_context.is_included(units.wraps.Wrap1)
        assert not builder_context.is_included(units.wraps.Wrap2)

    def test_is_adviser_pipeline(self) -> None:
        """Test check for an adviser build context."""
        builder_context = PipelineBuilderContext(
            graph=None,
            project=None,
            library_usage=None,
            decision_type=None,
            recommendation_type=RecommendationType.LATEST,
        )
        assert builder_context.is_adviser_pipeline()
        assert not builder_context.is_dependency_monkey_pipeline()

    def test_is_dependency_monkey_pipeline(self) -> None:
        """Test check for a dependency monkey build context."""
        builder_context = PipelineBuilderContext(
            graph=None,
            project=None,
            library_usage=None,
            decision_type=DecisionType.RANDOM,
            recommendation_type=None,
        )
        assert builder_context.is_dependency_monkey_pipeline()
        assert not builder_context.is_adviser_pipeline()

    def test_invalid_pipeline_builder_context(self) -> None:
        """Test check an invalid build context."""
        # Exactly one from decision type/recommendation type has to be specified.
        with pytest.raises(ValueError):
            PipelineBuilderContext(
                graph=None,
                project=None,
                library_usage=None,
                decision_type=None,
                recommendation_type=None,
            )

        with pytest.raises(ValueError):
            PipelineBuilderContext(
                graph=None,
                project=None,
                library_usage=None,
                decision_type=DecisionType.ALL,
                recommendation_type=RecommendationType.LATEST,
            )

    @pytest.mark.parametrize(
        "unit_class,builder_context_attr",
        [
            (units.boots.Boot2, "boots"),
            (units.pseudonyms.Pseudonym2, "pseudonyms"),
            (units.sieves.Sieve2, "sieves"),
            (units.steps.Step2, "steps"),
            (units.strides.Stride2, "strides"),
            (units.wraps.Wrap2, "wraps"),
        ],
    )
    def test_add_unit(
        self,
        builder_context: PipelineBuilderContext,
        unit_class: Unit,
        builder_context_attr: str,
    ) -> None:
        """Test addition of a unit."""
        assert not builder_context.is_included(unit_class)
        unit = unit_class()
        builder_context.add_unit(unit)
        assert builder_context.is_included(unit_class)
        assert getattr(builder_context, builder_context_attr)[-1] is unit

    def test_get_included_boots(self) -> None:
        """Test get included boots of the provided boot class."""
        builder_context = PipelineBuilderContext(decision_type=DecisionType.RANDOM)
        assert list(builder_context.get_included_boots(units.boots.Boot1)) == []
        assert list(builder_context.get_included_boot_names()) == []
        unit = units.boots.Boot1()
        builder_context.add_unit(unit)
        assert list(builder_context.get_included_boots(units.boots.Boot1)) == [unit]
        assert list(builder_context.get_included_boot_names()) == ["Boot1"]

    def test_get_included_pseudonyms(self) -> None:
        """Test get included pseudonyms of the provided pseudonym class."""
        builder_context = PipelineBuilderContext(decision_type=DecisionType.RANDOM)
        assert list(builder_context.get_included_pseudonyms(units.pseudonyms.Pseudonym1)) == []
        assert list(builder_context.get_included_pseudonym_names()) == []
        unit = units.pseudonyms.Pseudonym1()
        builder_context.add_unit(unit)
        assert list(builder_context.get_included_pseudonyms(units.pseudonyms.Pseudonym1)) == [unit]
        assert list(builder_context.get_included_pseudonym_names()) == ["Pseudonym1"]

    def test_get_included_sieves(self) -> None:
        """Get included sieves of the provided sieve class."""
        builder_context = PipelineBuilderContext(decision_type=DecisionType.RANDOM)
        assert list(builder_context.get_included_sieves(units.sieves.Sieve1)) == []
        assert list(builder_context.get_included_sieve_names()) == []
        unit = units.sieves.Sieve1()
        builder_context.add_unit(unit)
        assert list(builder_context.get_included_sieves(units.sieves.Sieve1)) == [unit]
        assert list(builder_context.get_included_sieve_names()) == ["Sieve1"]

    def test_get_included_steps(self) -> None:
        """Get included steps of the provided step class."""
        builder_context = PipelineBuilderContext(decision_type=DecisionType.RANDOM)
        assert list(builder_context.get_included_steps(units.steps.Step1)) == []
        assert list(builder_context.get_included_step_names()) == []
        unit = units.steps.Step1()
        builder_context.add_unit(unit)
        assert list(builder_context.get_included_steps(units.steps.Step1)) == [unit]
        assert list(builder_context.get_included_step_names()) == ["Step1"]

    def test_get_included_strides(self) -> None:
        """Get included strides of the provided stride class."""
        builder_context = PipelineBuilderContext(decision_type=DecisionType.RANDOM)
        assert list(builder_context.get_included_strides(units.strides.Stride1)) == []
        assert list(builder_context.get_included_stride_names()) == []
        unit = units.strides.Stride1()
        builder_context.add_unit(unit)
        assert list(builder_context.get_included_strides(units.strides.Stride1)) == [unit]
        assert list(builder_context.get_included_stride_names()) == ["Stride1"]

    def test_get_included_wraps(self) -> None:
        """Get included wraps of the provided wrap class."""
        builder_context = PipelineBuilderContext(decision_type=DecisionType.RANDOM)
        assert list(builder_context.get_included_wraps(units.wraps.Wrap1)) == []
        assert list(builder_context.get_included_wrap_names()) == []
        unit = units.wraps.Wrap1()
        builder_context.add_unit(unit)
        assert list(builder_context.get_included_wraps(units.wraps.Wrap1)) == [unit]
        assert list(builder_context.get_included_wrap_names()) == ["Wrap1"]

class TestPipelineBuilder(AdviserTestCase):
    """Tests related to pipeline builder."""

    @use_test_units
    @pytest.mark.parametrize(
        "pipeline_config_method,kwargs",
        [
            (
                "get_adviser_pipeline_config",
                {"recommendation_type": RecommendationType.LATEST},
            ),
            (
                "get_dependency_monkey_pipeline_config",
                {"decision_type": DecisionType.RANDOM},
            ),
        ],
    )
    def test_build_configuration(
        self,
        pipeline_config_method: str,
        kwargs: Dict[str, Union[RecommendationType, DecisionType]],
    ) -> None:
        """Test building configuration."""
        # All test units do not register themselves - let's cherry-pick ones that should be present.
        # There are done 3 iterations in total during pipeline configuration creation.
        flexmock(units.boots.Boot1).should_receive("should_include").and_yield(
            {"some_parameter": 1.0}
        ).and_yield().and_yield().times(3)
        flexmock(units.pseudonyms.Pseudonym2).should_receive("should_include").and_yield(
            {}
        ).and_yield().and_yield().times(3)
        flexmock(units.sieves.Sieve2).should_receive("should_include").and_yield(
            {"foo": "bar"}
        ).and_yield().and_yield().times(3)
        flexmock(units.steps.Step1).should_receive("should_include").and_yield({}).and_yield().and_yield().times(3)
        flexmock(units.strides.Stride2).should_receive("should_include").and_yield({}).and_yield().and_yield().times(3)
        flexmock(units.strides.Stride1).should_receive("should_include").and_yield().and_yield(
            {"linus": "torvalds"}
        ).and_yield().times(3)
        flexmock(units.wraps.Wrap2).should_receive("should_include").and_yield({}).and_yield().and_yield().times(3)

        # It is not relevant if adviser/dependency monkey is called in this case.
        pipeline = getattr(PipelineBuilder, pipeline_config_method)(
            graph=None,
            project=None,
            library_usage=None,
            labels={},
            prescription=None,
            cli_parameters=None,
            **kwargs,
        )

        assert pipeline.to_dict() == {
            "boots": [
                {"name": "Boot1", "configuration": {"some_parameter": 1.0, "package_name": "flask"}, "unit_run": False}
            ],
            "sieves": [
                {
                    "name": "Sieve2",
                    "configuration": {"date": "2015-09-15", "foo": "bar", "package_name": "selinon"},
                    "unit_run": False,
                }
            ],
            "pseudonyms": [{"name": "Pseudonym2", "configuration": {"package_name": "flask"}, "unit_run": False}],
            "steps": [
                {
                    "name": "Step1",
                    "configuration": {
                        "guido_retirement": 2019,
                        "package_name": "tensorflow",
                        "multi_package_resolution": False,
                    },
                    "unit_run": False,
                }
            ],
            "strides": [
                {"name": "Stride2", "configuration": {"foo": None, "package_name": "thamos"}, "unit_run": False},
                {
                    "name": "Stride1",
                    "configuration": {
                        "linus": "torvalds",
                        "package_name": None,
                    },
                    "unit_run": False,
                },
            ],
            "wraps": [{"name": "Wrap2", "configuration": {"package_name": "hexsticker"}, "unit_run": False}],
        }

    @use_test_units
    def test_blocked_units(self, project: Project) -> None:
        """Test preventing a pipeline unit from being added to pipeline configuration."""
        flexmock(units.boots.Boot1).should_receive("should_include").and_yield({}).and_yield().times(2)
        flexmock(units.steps.Step1).should_receive("should_include").and_yield({}).and_yield().times(2)

        pipeline = PipelineBuilder.get_adviser_pipeline_config(
            recommendation_type=RecommendationType.LATEST,
            graph=None,
            project=project,
            labels={},
            library_usage=None,
            prescription=None,
            cli_parameters=None,
        )

        assert len(pipeline.boots) == 1
        assert pipeline.boots[0].__class__ is units.boots.Boot1

        assert len(pipeline.steps) == 1
        assert pipeline.steps[0].__class__ is units.steps.Step1

        assert "THOTH_ADVISER_BLOCKED_UNITS" not in os.environ

        try:
            os.environ["THOTH_ADVISER_BLOCKED_UNITS"] = f"{units.boots.Boot1.__name__},{units.steps.Step1.__name__}"

            flexmock(units.boots.Boot1).should_receive("should_include").times(0)
            flexmock(units.steps.Step1).should_receive("should_include").times(0)

            pipeline = PipelineBuilder.get_adviser_pipeline_config(
                recommendation_type=RecommendationType.LATEST,
                graph=None,
                project=None,
                labels={},
                library_usage=None,
                prescription=None,
                cli_parameters=None,
            )
            assert len(pipeline.boots) == 0
            assert len(pipeline.steps) == 0
        finally:
            os.environ.pop("THOTH_ADVISER_BLOCKED_UNITS")

    @use_test_units
    def test_from_dict(self) -> None:
        """Test instantiation of a pipeline from a dictionary."""
        dict_ = {
            "boots": [
                {"name": "Boot1", "configuration": {"some_parameter": 1.0, "package_name": "flask"}, "unit_run": False}
            ],
            "pseudonyms": [{"name": "Pseudonym2", "configuration": {"package_name": "tensorflow"}, "unit_run": False}],
            "sieves": [
                {
                    "name": "Sieve2",
                    "configuration": {"date": "2015-09-15", "foo": "bar", "package_name": "selinon"},
                    "unit_run": False,
                }
            ],
            "steps": [
                {
                    "name": "Step1",
                    "configuration": {
                        "guido_retirement": 2019,
                        "package_name": "tensorflow",
                        "multi_package_resolution": False,
                    },
                    "unit_run": False,
                }
            ],
            "strides": [
                {"name": "Stride2", "configuration": {"foo": None, "package_name": "thamos"}, "unit_run": False},
                {"name": "Stride1", "configuration": {"linus": "torvalds", "package_name": None}, "unit_run": False},
            ],
            "wraps": [{"name": "Wrap2", "configuration": {"package_name": "hexsticker"}, "unit_run": False}],
        }

        pipeline = PipelineBuilder.from_dict(dict(dict_))
        pipeline_dict = pipeline.to_dict()
        assert pipeline_dict == dict_
        assert isinstance(pipeline.boots[0], Boot)
        assert isinstance(pipeline.pseudonyms[0], Pseudonym)
        assert isinstance(pipeline.sieves[0], Sieve)
        assert isinstance(pipeline.steps[0], Step)
        assert isinstance(pipeline.strides[0], Stride)
        assert isinstance(pipeline.strides[1], Stride)
        assert isinstance(pipeline.wraps[0], Wrap)

    @use_test_units
    def test_load(self, tmp_path: Path) -> None:
        """Test instantiation of a pipeline from a dictionary."""
        expected_dict_ = {
            "boots": [
                {"configuration": {"package_name": "flask", "some_parameter": -0.2}, "name": "Boot1", "unit_run": False}
            ],
            "pseudonyms": [],
            "sieves": [],
            "steps": [
                {
                    "configuration": {
                        "guido_retirement": 2019,
                        "package_name": "tensorflow",
                        "multi_package_resolution": False,
                    },
                    "name": "Step1",
                    "unit_run": False,
                }
            ],
            "strides": [
                {"configuration": {"foo": None, "package_name": "thamos"}, "name": "Stride2", "unit_run": False}
            ],
            "wraps": [],
        }

        dict_ = {
            "boots": [{"name": "Boot1"}],
            "pseudonyms": [],
            "sieves": [],
            "steps": [
                {
                    "name": "Step1",
                    "unit_run": False,
                    "configuration": {"guido_retirement": 2019, "package_name": "tensorflow"},
                }
            ],
            "strides": [{"name": "Stride2", "unit_run": False}],
            "wraps": [],
        }

        yaml_path = tmp_path / "config.yaml"
        with open(str(yaml_path), "w") as f:
            yaml.safe_dump(dict_, f)

        pipeline = PipelineBuilder.load(yaml_path)

        assert isinstance(pipeline.boots[0], Boot)
        assert not pipeline.pseudonyms
        assert not pipeline.sieves
        assert isinstance(pipeline.steps[0], Step)
        assert isinstance(pipeline.strides[0], Stride)
        assert not pipeline.wraps
        pipeline_dict = pipeline.to_dict()
        assert pipeline_dict == expected_dict_

        json_path = tmp_path / "config.json"
        with open(str(json_path), "w") as f:
            json.dump(dict_, f)

        pipeline = PipelineBuilder.load(json_path)
        assert isinstance(pipeline.boots[0], Boot)
        assert not pipeline.pseudonyms
        assert not pipeline.sieves
        assert isinstance(pipeline.steps[0], Step)
        assert isinstance(pipeline.strides[0], Stride)
        assert not pipeline.wraps
        pipeline_dict = pipeline.to_dict()
        assert pipeline_dict == expected_dict_

    @use_test_units
    def test_from_dict_unit_configuration_error(self) -> None:
        """Test instantiation of a pipeline unit in case configuration errors.."""
        dict_ = {
            "boots": [{"name": "Boot1", "configuration": {"foo": "bar"}}],
        }

        flexmock(units.boots.Boot1)
        units.boots.Boot1.should_receive("update_configuration").with_args({"foo": "bar"}).and_raise(ValueError)

        with pytest.raises(PipelineConfigurationError):
            PipelineBuilder.from_dict(dict_)

    @use_test_units
    def test_from_dict_unit_not_exist_error(self) -> None:
        """Test instantiation of a pipeline from a dictionary in case of missing unit."""
        dict_ = {
            "sieves": [{"name": "SieveThatDoesNotExist", "configuration": {"foo": "bar"}}],
        }

        with pytest.raises(UnknownPipelineUnitError):
            PipelineBuilder.from_dict(dict_)


import pandas as pd
import numpy
from datetime import date

_cache = {}

# wraps a dataframe to make it easier / more readible

class MyDF(object):
    def __init__(self, df: pd.DataFrame):
        self.df = df

    def _call(self, fname, *args, **kw):
        res = None
        if fname == 'region':
            res = self.get_region(*args, **kw)
        elif fname == 'previous':
            res = self.get_previous(*args, **kw)
        elif fname == 'after':
            res = self.get_after(*args, **kw)
        elif fname == 'new_cases':
            res = self.get_new_cases(*args, **kw)
        elif fname == 'hospitalized':
            res = self.get_hospitalized(*args, **kw)
        elif fname == 'intensive':
            res = self.get_intensive(*args, **kw)
        elif fname == 'deaths':
            res = self.get_deaths(*args, **kw)
        elif fname == 'dates':
            res = self.get_dates(*args, **kw)
        elif fname == 'dates_as_int':
            res = self.get_dates_as_int(*args, **kw)

        if not res:
            raise(Exception(f'{fname} not found'))
        return res

    def get_region(self, region_name='Veneto'):
        return MyDF(self.df[self.df['denominazione_regione'] == region_name])

    def get_previous(self, date: str) -> '(aaaa-mm-gg) => [...]':
        return MyDF(self.df[self.df['data'] < date])

    def get_after(self, date: str) -> '(aaaa-mm-gg) => [...]':
        return MyDF(self.df[self.df['data'] > date])

    def get_new_cases(self):
        return self.df['nuovi_positivi'].values.tolist()

    def get_hospitalized(self):
        return self.df['totale_ospedalizzati'].values.tolist()

    def get_intensive(self):
        return self.df['terapia_intensiva'].values.tolist()

    def get_deaths(self):
        a = self.df['deceduti'].values.tolist()
        res = [0]
        for i in range(len(a)):
            res.append(max(a[i]-a[i-1], 0))
        return res

    def get_dates(self):
        tmp = self.df['data'].values.tolist()
        tmp = [x[:10] for x in tmp]
        return tmp

    # returns a list of integers represinting the distance of each date from the zero_date
    def get_dates_as_int(self, zero_date):
        tmp = self.df['data'].values.tolist()
        tmp = [x[:10] for x in tmp]

        bd = date(*[int(x) for x in zero_date.split('-')])
        tmp2 = []
        for dd in tmp:
            # solve bug: dataset dates have _ instead of -
            dd = '-'.join(dd.split('_'))

            d = date(*[int(x) for x in dd.split('-')])
            tmp2.append((d-bd).days)

        return tmp2

    def compose(self, todos):
        res = self
        if isinstance(todos, str):
            res = res._call(todos)
        elif isinstance(todos, (tuple, list)):
            for todo in todos:
                if isinstance(todo, str):
                    res = res._call(todo)
                else:
                    res = res._call(*todo)

        return res

# load file into memory
def load_file(fpath):
    global _cache
    if fpath not in _cache:
        _cache[fpath] = pd.read_json(fpath)
    return MyDF(_cache[fpath])


import argparse
import inspect
from pathlib import Path
import requests
import shutil

import docstring_parser
import numpy as np

def exporter(export_self=False):
    """Export utility modified from https://stackoverflow.com/a/41895194
    Returns export decorator, __all__ list
    """
    all_ = []
    if export_self:
        all_.append('exporter')

    def decorator(obj):
        all_.append(obj.__name__)
        return obj

    return decorator, all_

export, __all__ = exporter(export_self=True)

@export
def make_cli(main_f):
    """Wrap main_f in an argparse command-line interface

    Docstring and type annotations determine argument parsing and help message.

    Un-annotated arguments will be passed as strings.
    """
    # Get the signature, used for getting argument names and types
    signature = inspect.signature(main_f).parameters

    # Parse the docstring to get the argument descriptions
    doc = docstring_parser.parse(main_f.__doc__)
    descs = {x.arg_name: x.description for x in doc.params}

    # Auto-generate and and run an argparse parser
    # There are libraries that do this, but I haven't found one that parses
    # the docstring for argument descriptions.
    desc = doc.short_description
    if doc.long_description:
        desc += "\n\n" + doc.long_description
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=desc
    )
    for pname, param in signature.items():
        kwargs = dict(help=descs.get(pname, None))
        has_default = param.default != param.empty
        if has_default and param.annotation is bool:
            # Flag argument. Note true/false inversion, gotta love argparse
            if param.default is True:
                kwargs["action"] = "store_false"
            elif param.default is False:
                kwargs["action"] = "store_true"
            else:
                raise ValueError("flag args should default to true or false")
        else:
            # Regular argument
            if has_default:
                kwargs["default"] = param.default
            if param.annotation != param.empty:
                kwargs["type"] = param.annotation
            if param.kind == param.VAR_POSITIONAL:
                kwargs["nargs"] = "*"
        parser.add_argument(("--" if has_default else "") + pname, **kwargs)

    args = parser.parse_args()

    # If there is a *args, we need to call the main function differently
    (var_pos_name,) = [
        pname
        for pname, param in signature.items()
        if param.kind == param.VAR_POSITIONAL
    ][:1] or (None,)
    if var_pos_name:
        var_pos = getattr(args, var_pos_name)
        if not var_pos:
            var_pos = tuple()
        main_f(
            *var_pos,
            **{
                pname: getattr(args, pname)
                for pname in signature.keys()
                if pname != var_pos_name
            }
        )
    else:
        main_f(**vars(args))

@export
def symmetrize_batch(x):
	"""Return symmetrized version of an array of matrices"""
	return (x.transpose((0, 2, 1)) + x)/2

@export
def cov_to_std(cov):
	"""Return (std errors, correlation coefficent matrix)
	given covariance matrix cov
	"""
	std_errs = np.diag(cov) ** 0.5
	corr = cov * np.outer(1 / std_errs, 1 / std_errs)
	return std_errs, corr

# Works: tested against paltas' unnormalize
@export
def denormalize(x, means, scales):
    x = x[:,:len(means)]
    return x * scales[None,:] + means[None,:]

@export
def download_and_save(url: str, path: Path):
    """Download a file from url and save it to path

    Arguments:
        url {str} -- URL to download from
        path {pathlib.Path} -- Path to save to
    """
    if path.exists():
        return
    path.parent.mkdir(parents=True, exist_ok=True)
    with requests.get(url, stream=True) as r:
        with open(path, 'wb') as f:
            shutil.copyfileobj(r.raw, f)


import torch.nn as nn
from . import block as B
from collections import OrderedDict
import torch

class IMDN(nn.Module):
    def __init__(self, in_nc=3, nf=64, num_modules=6, out_nc=3, upscale=4):
        super(IMDN, self).__init__()

        self.fea_conv = B.conv_layer(in_nc, nf, kernel_size=3)

        # IMDBs
        self.IMDB1 = B.IMDModule(in_channels=nf)
        self.IMDB2 = B.IMDModule(in_channels=nf)
        self.IMDB3 = B.IMDModule(in_channels=nf)
        self.IMDB4 = B.IMDModule(in_channels=nf)
        self.IMDB5 = B.IMDModule(in_channels=nf)
        self.IMDB6 = B.IMDModule(in_channels=nf)
        self.c = B.conv_block(nf * num_modules, nf, kernel_size=1, act_type='lrelu')

        self.LR_conv = B.conv_layer(nf, nf, kernel_size=3)

        upsample_block = B.pixelshuffle_block
        self.upsampler = upsample_block(nf, out_nc, upscale_factor=upscale)

    def forward(self, input):
        out_fea = self.fea_conv(input)
        out_B1 = self.IMDB1(out_fea)
        out_B2 = self.IMDB2(out_B1)
        out_B3 = self.IMDB3(out_B2)
        out_B4 = self.IMDB4(out_B3)
        out_B5 = self.IMDB5(out_B4)
        out_B6 = self.IMDB6(out_B5)

        out_B = self.c(torch.cat([out_B1, out_B2, out_B3, out_B4, out_B5, out_B6], dim=1))
        out_lr = self.LR_conv(out_B) + out_fea
        output = self.upsampler(out_lr)
        return output

def load_state_dict(path):

    if torch.cuda.is_available():
        state_dict = torch.load(path)
    else:
        state_dict = torch.load(path, map_location='cpu')

    new_state_dcit = OrderedDict()
    for k, v in state_dict.items():
        if 'module' in k:
            name = k[7:]
        else:
            name = k
        new_state_dcit[name] = v
    return new_state_dcit

def get_IMDN(upscale=4, checkpoint=None):

    model = IMDN(upscale=upscale)
    if checkpoint is not None:
        checkpoint = './Checkpoints/IMDN/' + checkpoint
        model_dict = load_state_dict(checkpoint)
        model.load_state_dict(model_dict, strict=True)

    return model


import socket
import re
import math
import itertools

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c = s.connect(('pwnable.kr', 9008))

def combinatoria(n, p):
    return math.factorial(n)//(math.factorial(p) * math.factorial(n-p))

def recv(s, num):
    return s.recv(num).decode('utf-8')

def sum(arrays):
    query = ''
    for arr in arrays:
        query += '-' + ' '.join(str(e) for e in arr)
    query = query[1:]
    s.send(query.encode() + b'\n')
    return [ int(x) for x in recv(s, 1024)[:-1].split('-') ]

def maxIter(N, C):
    total = 0
    for p in range(C):
        total += combinatoria(C, p)
        if total >= N:
            return p

def solve(N, C):
    #print(str(N) + ' ' + str(C))

    arrays = [[] for i in range(C)]
    num = 0
    for choises in range(1, 10):
        for positions in itertools.combinations(range(C), choises):
            if num == N:
                break
            for pos in positions:
                #print('agrego pos:' + str(pos) + ' num:' + str(num))
                arrays[pos].append(num)
            num += 1

    summed = sum(arrays)
    impares = []
    for i, summ in enumerate(summed):
        if summ % 2 == 1:
            impares.append(i)

    idx = impares.pop()
    for num in arrays[idx]:
        isInAll = True
        for impar in impares:
            if num not in arrays[impar]:
                isInAll = False
        if isInAll:
            return str(num)
    print('Failed!!')

def main():
    r = s.recv(1024 * 2)
    for i in range(100):
        r = recv(s, 200)
        rta = re.search(r'N=(\d+) C=(\d+)', r)
        N = int(rta.group(1))
        C = int(rta.group(2))
        solution = solve(N, C)
        s.send(solution.encode() + b'\n')
        print(recv(s, 200))
    print(recv(s, 200))

if __name__ == '__main__':
    main()


import os
import json
import requests
import statistics
import datetime
from trade import Trade

class Bollingers_Bot():
    def __init__(self):
        self.account_balance = 0
        self.alert_sent = False
        self.upper_bollinger_band = 0
        self.lower_bollinger_band = 0
        self.lower_bollinger_alert = 0
        self.upper_bollinger_alert = 0
        self.last_price = 0
        self.moving_average = 0
        self.tick_average = []
        self.stock_json = {}
        self.in_trade = False
        self.alert = False
        self.previous_trades = []
        self.current_trade = None
        self.band = ""
        self.last_date = None
        self.last_tick = False
        self.alert_gap = 0.75
        self.upper_trade_exit = 0.9875
        self.lower_trade_exit = 1.0125
        self.upper_trade_multipler = 1.0125
        self.lower_trade_multipler = 0.975

    def process_tick_data(self,tick_data):
        self.tick_average = round(statistics.mean(tick_data),2)
        self.moving_average = self.tick_average
        self.stand_dev = statistics.stdev(tick_data)
        self.upper_bollinger_band = round(self.moving_average + 2 * self.stand_dev,2)
        self.lower_bollinger_band = round(self.moving_average - 2 * self.stand_dev,2)
        self.last_price = tick_data[-1]
        self.bollinger_spread = (self.upper_bollinger_band - self.lower_bollinger_band)*.1
        #self.upper_bollinger_alert = round(self.upper_bollinger_band - self.bollinger_spread,2)
        #self.lower_bollinger_alert = round(self.lower_bollinger_band + self.bollinger_spread,2)
        self.upper_bollinger_alert = round(self.upper_bollinger_band - self.alert_gap,2)
        self.lower_bollinger_alert = round(self.lower_bollinger_band + self.alert_gap,2)
        self.process_bollinger_bands()

    def process_bollinger_bands(self):
        if self.last_price >= self.upper_bollinger_alert:
            self.alert = True
            self.band = "UPPER"
            alert_message = "Price has crossed Upper Bollinger Alert Threshold"
        elif self.last_price <= self.lower_bollinger_alert:
            self.alert = True
            self.band = "LOWER"
            alert_message = "Price has crossed Lower Bollinger Alert Threshold"
        elif self.last_price >= self.upper_bollinger_band:
            self.alert = True
            self.band = "UPPER"
            alert_message = "Price has crossed Upper Bollinger Band"
        elif self.last_price <= self.lower_bollinger_band:
            self.alert = True
            self.band = "LOWER"
            alert_message = "Price has crossed Lower Bollinger Band"
        else:
            alert_message = "All normal"
            self.band = "NORMAL"
            self.alert = False
        self.manage_trade()

    def manage_trade(self):
        if self.in_trade == False and self.alert == True:
            self.current_trade = Trade(self.last_date, self.last_price, self.band, self.upper_trade_multipler, self.lower_trade_multipler)
            self.in_trade = True
            self.alert = False
        elif self.in_trade == True:
            if self.current_trade.band == "UPPER" and self.last_price <= (self.current_trade.alert_price * self.upper_trade_exit):
                self.exit_position()
            elif self.current_trade.band == "LOWER" and self.last_price >= (self.current_trade.alert_price * self.lower_trade_exit):
                self.exit_position()
            elif self.current_trade.trade_start_day < 2:
                 if self.last_date.weekday() == 2 and self.last_tick == True:
                     self.exit_position()
            elif self.current_trade.trade_start_day >= 2 and self.current_trade.trade_start_day <= 4:
                if self.last_date.weekday() == 4 and self.last_tick == True:
                    self.exit_position()

    def convert_datetime(self,epochtime):
        fmt = "%Y-%m-%d %H:%M:%S"
        t = datetime.datetime.fromtimestamp(float(epochtime)/1000.)
        return t.strftime(fmt)

    def exit_position(self):
        self.current_trade.close_trade(self.last_date, self.last_price)
        self.previous_trades.append(self.current_trade)
        self.in_trade = False
        self.alert = False


import jpype as jp
import common, utilities

__author__ = 'darkoa'

def correlation_basedfeat_sel(bunch):
    """Correlation-based Feature Subset Selection, as implemented by the CfsSubsetEval class of Weka

    :param bunch: dataset
    :return: new dataset
    """

    if not jp.isThreadAttachedToJVM():
        jp.attachThreadToJVM()

    # Instances data!
    data = utilities.convertBunchToWekaInstances(bunch)

    Filter = jp.JClass('weka.filters.Filter')

    AttributeSelection = jp.JClass('weka.filters.supervised.attribute.AttributeSelection')
    attsel_filter = AttributeSelection()

    CfsSubsetEval = jp.JClass('weka.attributeSelection.CfsSubsetEval')
    attsel_eval = CfsSubsetEval()

    GreedyStepwise = jp.JClass('weka.attributeSelection.BestFirst')
    attsel_search = GreedyStepwise()

    # attsel_search.setSearchBackwards(True) # True, true
    attsel_filter.setEvaluator(attsel_eval)
    attsel_filter.setSearch(attsel_search)
    attsel_filter.setInputFormat(data)

    new_instances = Filter.useFilter(data, attsel_filter)

    return utilities.convertWekaInstancesToBunch(new_instances)

def normalize(bunch, params=None):
    '''Normalizes all numeric values in the given dataset (apart from the class attribute, if set)

    :param bunch: dataset
    :param params: parameters in textual form to pass to the Normalize Weka class
    :return: dataset
    '''
    if not jp.isThreadAttachedToJVM():
        jp.attachThreadToJVM()

    # Instances data!
    data = utilities.convertBunchToWekaInstances(bunch)

    Filter = jp.JClass('weka.filters.Filter')

    Normalize = jp.JClass('weka.filters.unsupervised.attribute.Normalize')
    normalize_filter = Normalize()
    normalize_filter.setOptions(common.parse_options(params))
    normalize_filter.setInputFormat(data)

    new_instances = Filter.useFilter(data, normalize_filter)

    return utilities.convertWekaInstancesToBunch(new_instances)


import sys
import os
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
import speccado as sc
import simcado as sim

def main(configfile, datadir):
    if configfile == "spectro_HK.config":
        filters = "HK"
    elif configfile == "spectro_J.config":
        filters = "J"
    elif configfile == "spectro_IJ.config":
        filters = "IzJ"
    else:
        filters = ""
    cmds = sim.UserCommands(configfile, datadir)
    tracelist = sc.layout.read_spec_order(cmds['SPEC_ORDER_LAYOUT'])
    fpa = sim.Detector(cmds, small_fov=False)
    sim.detector.plot_detector_layout(fpa, plane='fpa', label=False,
                                      color='k', linestyle='-', linewidth=1)

    colorlist = ['r', 'b', 'g', 'c', 'm', 'k', 'orange', 'chartreuse',
                 'k', 'k', 'k', 'k']
    colorlist.reverse()
    ax = plt.gca()
    thecol = colorlist.pop()
    for trace in tracelist:
        xy = trace.write_reg("/dev/null", slit_length=cmds['SPEC_SLIT_LENGTH'],
                             waveband=cmds['INST_FILTER_TC'])
        if xy is not None:
            print("Hallo: ", trace.name, thecol)
            ax.add_patch(Polygon(xy, closed=True, fill=False, color=thecol,
                                 label=trace.name.split('.')[0]))
            thecol = colorlist.pop()
    plt.text(90, 90, filters, ha='right', va='top', fontsize=14,
             style='italic')
    #    plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1))
    plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
               ncol=3, mode="expand", borderaxespad=0., fontsize='small')
    outfile = configfile.split('.')[0] + "_layout.pdf"
    plt.savefig(outfile, bbox_inches='tight')
    plt.show()

if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])


from tree_visual import deserialize, TreeNode, drawtree
from typing import List
from queue import Queue

# Umberalla Traverse
# vertical order ->
#   1. left child's right child
#   2. right child's left child

# we need to rank all the nodes
# left = parent - 1
# right = parent + 1

class Solution:
    def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
        root.rank = 0
        minrank, maxrank = self.rank_tree(root)
        anslen = abs(minrank) + abs(maxrank) + 1
        ans = [[] for i in range(anslen)]
        self.traverse(root, ans, abs(minrank))
        return ans

    def traverse(self, root, ans, zeroindex):
        if not root:
            return
        # since we report the value in the order of top to botton
        # use the level order traversal
        queue = Queue()
        queue.put([root])
        while not queue.empty():
            nodes = queue.get()
            # sort the nodes in ascending order
            nodes = sorted(nodes, key=lambda node: node.val)
            next_level_nodes = []
            for node in nodes:
                rank = node.rank
                index = zeroindex + rank
                ans[index].append(node.val)
                next_level_nodes.extend(self.get_children(node))
            if next_level_nodes:
                queue.put(next_level_nodes)

    def get_children(self, root):
        ans = []
        if root.left:
            ans.append(root.left)
        if root.right:
            ans.append(root.right)
        return ans

    def rank_tree(self, root):
        """ ranks all the root's childern """
        parent_rank = root.rank
        max_rank = min_rank = parent_rank
        if root.left:
            root.left.rank = parent_rank - 1
            # rank the left subtree
            left_ranks = self.rank_tree(root.left)
            min_rank = min([left_ranks[0], min_rank])
            max_rank = max([left_ranks[1], max_rank])
        if root.right:
            root.right.rank = parent_rank + 1
            # rank the right subtree
            right_ranks = self.rank_tree(root.right)
            min_rank = min([right_ranks[0], min_rank])
            max_rank = max([right_ranks[1], max_rank])
        return (min_rank, max_rank)

if __name__ == "__main__":
    # tree = deserialize("[3,9,20,5,null,15,7,null,6]")
    # tree = deserialize("[0,2,1,null,4,null,3]")
    # tree = deserialize("[0,1,null,null,2,6,3,null,null,null,4,null,5]")
    # tree = deserialize("[3,9,20,5,null,15,7,null,6]")
    # tree = deserialize("[0,8,1,null,null,3,2,null,4,5,null,null,7,6]")
    tree = deserialize("[0,2,1,3,null,null,null,4,5,null,7,6,null,10,8,11,9]")
    ans = Solution().verticalTraversal(tree)
    drawtree(tree)
    print(ans)


# Author: Plato (palt0)

from __future__ import annotations

import re
import urllib
from typing import TYPE_CHECKING

import aiohttp
from domify import html_elements as e
from domify.base_element import BaseElement

from cerbottana.plugins import command_wrapper
from cerbottana.typedefs import JsonDict

if TYPE_CHECKING:
    from cerbottana.models.message import Message

async def query_scryfall(url: str, resp_type: str) -> JsonDict | None:
    """Queries the Scryfall API.

    Args:
        url (str): Query.
        resp_type (str): Expected Scryfall API object type.

    Returns:
        JsonDict | None: Valid JSON received from the API, None if data is not valid.
    """
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            if resp.status != 200:
                return None
            json_body: JsonDict = await resp.json()

    # API error handling
    # Check response type and trust the API that it has the required parameters.
    if json_body["object"] != resp_type:
        print(f'Scryfall API error: Response object is "{resp_type}", expected "list"')
        return None

    return json_body

def to_card_id(card_name: str) -> str:
    """Transform a MtG card name into a string ID.

    Args:
        card_name (str): MtG card name. Case insensitive.

    Returns:
        str: Card ID. Lowercase, alphanumeric characters.
    """
    return "".join(ch.lower() for ch in card_name if ch.isalpha())

def to_card_thumbnail(card_json: JsonDict) -> BaseElement:
    """Generates HTML that shows card thumbnail(s).

    Args:
        card_json (JsonDict): JSON of a Scryfall Card object.

    Returns:
        BaseElement: htmlbox code.
    """

    # img_uris ~ URI for card thumbnail(s)
    if "card_faces" in card_json and "image_uris" in card_json["card_faces"][0]:
        # Double-faced cards have 2 thumbnails, i.e. transform cards.
        img_uris = [face["image_uris"]["normal"] for face in card_json["card_faces"]]
    elif "image_uris" in card_json:
        # Most cards have 1 thumbnail. Split cards fall under this category.
        img_uris = [card_json["image_uris"]["normal"]]
    else:
        # Fallback: image_uris isn't guaranteed to exist or be non-null but the previous
        # conditional cases should cover most cards.
        return (
            "Immagine per "
            + e.A(card_json["name"], href=card_json["scryfall_uri"])
            + " non disponibile."
        )

    html = e.A(href=card_json["scryfall_uri"])
    for img_uri in img_uris:
        html.add(
            e.Img(
                src=img_uri,
                width=251,
                height=350,
                style="border-radius: 4.75% / 3.5%; margin-right: 5px",
            )
        )
    return html

@command_wrapper(
    aliases=("carta", "magic", "mtg"),
    helpstr="Mostra una carta di Magic: the Gathering",
    allow_pm=False,
)
async def card(msg: Message) -> None:
    if not msg.arg:
        await msg.reply("Che carta devo cercare?")
        return

    query = urllib.parse.quote(msg.arg)
    url = "https://api.scryfall.com/cards/search?include_multilingual=true&q=" + query
    json_body = await query_scryfall(url, "list")

    # If the search didn't match any cards, broaden the scope to include extras (tokens,
    # planes, ...).
    if json_body is None:
        url += "&include_extras=true"
        json_body = await query_scryfall(url, "list")

    if json_body is None:
        await msg.reply("Nome non valido")
        return

    cards = json_body["data"]  # Scryfall lists are always non-empty.
    if len(cards) == 1:
        card_ = cards[0]
    else:
        # If there is an exact match, discard other results.
        # Use case: "Black Lotus" -> ["Black Lotus", "Blacker Lotus"]
        my_card_id = to_card_id(msg.arg)
        card_ = next((c for c in cards if to_card_id(c["name"]) == my_card_id), None)

    if card_:
        # Show card thumbnail(s) if there's only 1 query result.
        await msg.reply_htmlbox(to_card_thumbnail(card_))
    elif len(cards) <= 40:
        # Show a list of all query results.
        html = BaseElement()
        for c in cards:
            html.add(e.A(c["name"], href=c["scryfall_uri"]) + e.Br())
        await msg.reply_htmlbox(html)
    else:
        await msg.reply(f"**{len(cards)}** risultati! Usa un nome più specifico...")

@command_wrapper(
    aliases=("cardhangman", "gtc", "hangmancard"),
    helpstr="Indovina una carta di Magic: the Gathering!",
    allow_pm=False,
)
async def guessthecard(msg: Message) -> None:
    filters = (
        "legal:standard",
        "-type:basic",  # Basic lands
    )
    query = "+".join([urllib.parse.quote(param) for param in filters])
    url = "https://api.scryfall.com/cards/random?q=" + query

    card_ = await query_scryfall(url, "card")
    if card_ is None:  # Safety check. Error is propagated from query_scryfall().
        return

    # Strip PS parameter separators from cardname.
    cardname = re.sub(",|", "", card_["name"])

    # Hint generation logic: type line, mana cost, flavor text
    if "planeswalker" in card_["type_line"].lower():
        # Type lines of planeswalkers contain their name.
        hint = "Planeswalker"
    else:
        hint = card_["type_line"]
    if "mana_cost" in card_ and card_["mana_cost"]:
        hint += ", " + card_["mana_cost"]
    if "flavor_text" in card_ and card_["flavor_text"]:
        # Add flavor text if the hint won't exceed PS' limits.
        hint_with_flavor = hint + " ~ " + card_["flavor_text"]
        hint = hint_with_flavor if len(hint_with_flavor) <= 150 else hint
    hint = hint.replace("\n", " ")

    await msg.reply(f"/hangman create {cardname}, {hint}", False)

@command_wrapper(aliases=("randomcard",), allow_pm=False)
async def randcard(msg: Message) -> None:
    url = "https://api.scryfall.com/cards/random"
    if msg.arg:
        # Users can input an optional query to restrict the cardpool.
        url += "?q=" + urllib.parse.quote(msg.arg)

    card_ = await query_scryfall(url, "card")
    if card_ is None:
        await msg.reply("Ricerca non valida")
        return

    await msg.reply_htmlbox(to_card_thumbnail(card_))


# personal assistant, nvc empathy bot.
import random
import datetime
from time import sleep
from mod_get_empathy import *
from mod_visualize import *
from mod_is_it_feeling import *
from mod_coda_inventory import *
from mod_coda_inv_review import *

# Write timestamp of program launch
launch_date = open("timestamps/launch_date.txt", "a")
launch_date.write(str(datetime.datetime.now()) + "\n")

# TO DO: Check last login date and comment on how long it has been.

if datetime.datetime.now().hour < 12:
    greeting_time = "Good morning"
elif datetime.datetime.now().hour < 17:
    greeting_time = "Good afternoon"
elif datetime.datetime.now().hour <= 23:
    greeting_time = "Good evening"
else:
    greeting_time = "My, you are up late"

print(greeting_time + " my friend.")
sleep(0.1)

while True:
    print("How would you like to practice?")
    sleep(0.1)
    print("'g' to play the 'is it a feeling?' game.")
    sleep(0.1)
    print("'v' to visualize feelings.")
    sleep(0.1)
    print("'e' to receive empathy.")
    sleep(0.1)
    print("'c' to inventory CoDa patterns.")
    sleep(0.1)
    print("'r' to review CoDa pattern inventories.")

    greeting_response = input()

    if greeting_response == "e":
        sleep(0.1)
        get_empathy()
    elif greeting_response == "g":
        sleep(0.1)
        is_it_feeling()
    elif greeting_response == "c":
        sleep(0.1)
        coda_inventory()
    elif greeting_response == "v":
        sleep(0.1)
        visualize()
    elif greeting_response == "r":
        sleep(0.1)
        coda_inv_review()
    else:
        sleep(0.1)
        print("That's not an option right now.")

    print("Now that we've done that...")
    sleep(0.1)

# To Do:
# Only list the option to inventory CoDa patterns if there is no inventory file already present for the day.


import numpy as np
import heapq
from enum import Enum

class TileType(Enum):
    EMPTY = -1
    GROUND = 0
    WALL = 1
    START = 2
    ENEMY = 3

def is_in_bounds(pos, grid):
    # Is index inside the grid, is the tile ground, and is there anyone standing there already?
    return 0 <= pos[0] < grid.shape[1] and 0 <= pos[1] < grid.shape[0]\

def is_valid_move(pos, move, grid):
    return move == (0,0) or is_in_bounds((pos[0] + move[0], pos[1] + move[1]), grid)

# Neighbors of a tile
NEIGHBORS = [(0, -1), (-1, 0), (0, 0), (1, 0), (0, 1)]

def get_neighbors(pos, grid):
    x, y = pos
    return [(x + direction[0], y + direction[1]) for direction in NEIGHBORS if is_valid_move(pos, direction, grid)]

def dist(a, b):
    # easy distance for two tuples so we don't have to type this so much.
    return abs(b[0] - a[0]) + abs(b[1] - a[1])

# Priority Queue class, needed for A*
class PriorityQueue:

    def __init__(self):
        self.elements = []

    def empty(self):
        return len(self.elements) == 0

    def put(self, item, priority):
        heapq.heappush(self.elements, (priority, item))

    def get(self):
        return heapq.heappop(self.elements)[1]

def find_path(pos, goal, grid):

    search_queue = PriorityQueue()
    search_queue.put(pos, 0)
    node_paths = {pos: None}
    node_costs = {pos: 0}

    # We'll use the closest we managed to get if no path exists.
    closest_distance = dist(pos, goal)
    closest_point = pos

    while not search_queue.empty():
        current_pos = search_queue.get()

        if current_pos == goal:
            # we did it
            break
        neighbors = get_neighbors(current_pos, grid)
        for position in neighbors:
            position_cost = node_costs[current_pos] + 1
            # Every position costs 1 to move to.
            if position not in node_costs or position_cost < node_costs[position]:
                node_costs[position] = position_cost
                distance_score = dist(position, goal)
                if distance_score < closest_distance:
                    closest_distance = distance_score
                    closest_point = position
                position_priority = position_cost + distance_score
                search_queue.put(position, position_priority)
                node_paths[position] = current_pos

    # Start path from the closest point found.
    next_move = closest_point

    path_points = [next_move]
    while node_paths[next_move] is not None and node_paths[next_move] != pos:
        next_move = node_paths[next_move]
        path_points.append(next_move)

    return path_points

TILE_TYPE_DICT = {
    TileType.EMPTY: " ",
    TileType.GROUND: " - ",
    TileType.WALL: " # ",
    TileType.START: " S ",
    TileType.ENEMY: " E ",
}

def print_map(grid, player):
    map_str = ""
    map_height, map_width = grid.shape

    for row in range(map_height):
        for col in range(map_width):
            tile = TileType(grid[row, col])
            map_str += TILE_TYPE_DICT[tile]
        map_str += "\n"
    return map_str

class Room:
    def __init__(self,pos,size):
        self.pos = pos
        self.size = size
    def center(self):
        x,y = self.pos
        width, height = self.size
        return x+width // 2, y + height // 2

    def set_tiles(self,grid):
        x,y = self.pos
        width, height = self.size
        room_chunk = grid[y:y+height, x:x+width]
        room_chunk[1:height-1, 1:width-1] = TileType.GROUND.value

        set_slice_walls(room_chunk[0:height,0])
        set_slice_walls(room_chunk[0:height, width-1])
        set_slice_walls(room_chunk[0,1:width-1])
        set_slice_walls(room_chunk[height-1, 1:width-1])

def set_slice_walls(self, slice):
    for index in np.index(slice.shape):
        if slice[index] != TileType.GROUND.value:
            slice[index] = TileType.WALL


import datetime
import os.path
from googleapiclient.discovery import build
from pprint import pprint
import configparser

config = configparser.ConfigParser()
config.read('instance/config.ini')

platform = os.getenv('MY_ENV')
print(f'MY_ENV - {platform}')

if platform == 'development':
    devel = True
    conf = config['DEVEL']
else:
    devel = False
    conf = config['PRODUCTION']

CLIENT_SECRETS_FILE = conf['GG_CLIENT_SECRETS_FILE']

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

def get_google_calendar_list(creds):
    print('Get Calendar List')
    service = build('calendar', 'v3', credentials=creds)

    calendar_list_result = service.calendarList().list().execute()

    # pprint(calendar_list_result)

    calendar_list = []

    for calIdx in calendar_list_result['items']:
        print(calIdx['summary'])
        calendar_list.append(
            {
                'id': calIdx['id'],
                'summary': calIdx['summary']
            }
        )

    return calendar_list

def google_get_calendar_events(creds, calendarId='primary'):
    # print(f'creds - {creds}')
    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow()
    timeMin = now.isoformat() + 'Z'  # 'Z' indicates UTC time
    # Add 1 minute for timeMax
    add_min = now + datetime.timedelta(0, 60)
    date_time_obj = datetime.datetime.strptime(str(add_min), '%Y-%m-%d %H:%M:%S.%f')
    timeMax = date_time_obj.isoformat() + 'Z'

    print('Time being used:')
    print(timeMin)
    print(timeMax)

    print()
    print('Getting current event')
    events_result = service.events().list(calendarId=calendarId, timeMin=timeMin, timeMax=timeMax,
                                          maxResults=10, singleEvents=True,
                                          orderBy='startTime').execute()
    pprint(events_result)
    events = events_result.get('items', [])

    if not events:
        print('No current events found.')
        return False
    else:
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            print(start, event['summary'])

        return events[0]['summary']


import numpy as np
import matplotlib.pyplot as plt
from mltools import plot_data, plot_frontiere, make_grid, gen_arti

def reshape(w, X, y):
    """Reshape les entrées.

    Parameters
    ----------
    w : array
        Vecteur poids.
    X : array
        Données.
    y : array
        Labels.

    Returns
    ----------
    w : array de taille (d, 1)
        Vecteur poids.
    X : array de taille (n, d)
        Données.
    y : array de taille (n, 1)
        Labels.
    """
    return w.reshape(-1, 1), X.reshape(y.shape[0], w.shape[0]), y.reshape(-1, 1)

def mse(w, X, y):
    """Renvoie le coût des moindres carrés pour une fonction linéaire.

    Parameters
    ----------
    w : array de taille (d, 1)
        Vecteur poids.
    X : array de taille (n, d)
        Données.
    y : array de taille (n, 1)
        Labels.

    Returns
    ----------
    z : array (n, 1)
        Coût des moindres carrés.
    """
    w, X, y = reshape(w, X, y)
    return (np.dot(X, w) - y) ** 2

def mse_grad(w, X, y):
    """Renvoie le gradient des moindres carrés sous forme d'une matrice (n, d).

    Parameters
    ----------
    w : array de taille (d, 1)
        Vecteur poids.
    X : array de taille (n, d)
        Données.
    y : array de taille (n, 1)
        Labels.

    Returns
    ----------
    z : array (n, 1)
        Gradient des moindres carrés.
    """
    w, X, y = reshape(w, X, y)
    return 2 * X * (np.dot(X, w) - y)

def reglog(w, X, y):
    """Renvoie le coût de la régression logistique.

    Parameters
    ----------
    w : array de taille (d, 1)
        Vecteur poids.
    X : array de taille (n, d)
        Données.
    y : array de taille (n, 1)
        Labels.

    Returns
    ----------
    z : array (n, 1)
        Coût de la régression logistique..
    """
    w, X, y = reshape(w, X, y)
    return np.log(1 + np.exp(-y * np.dot(X, w)))

def reglog_grad(w, X, y):
    """Renvoie le gradient de la régression logistique sous forme d'une matrice

    Parameters
    ----------
    w : array de taille (d, 1)
        Vecteur poids.
    X : array de taille (n, d)
        Données.
    y : array de taille (n, 1)
        Labels.

    Returns
    ----------
    z : array (n, 1)
        Gradient de la régression logistique.
    """
    w, X, y = reshape(w, X, y)
    return (-y * X) / (1 + np.exp(y * np.dot(X, w)))

def check_fonctions():
    ## On fixe la seed de l'aléatoire pour vérifier les fonctions
    np.random.seed(0)
    datax, datay = gen_arti(epsilon=0.1)
    wrandom = np.random.randn(datax.shape[1], 1)
    assert np.isclose(mse(wrandom, datax, datay).mean(), 0.54731, rtol=1e-4)
    assert np.isclose(reglog(wrandom, datax, datay).mean(), 0.57053, rtol=1e-4)
    assert np.isclose(mse_grad(wrandom, datax, datay).mean(), -1.43120, rtol=1e-4)
    assert np.isclose(reglog_grad(wrandom, datax, datay).mean(), -0.42714, rtol=1e-4)
    np.random.seed()

def grad_check(f, f_grad, N=100):
    pass

def descente_gradient(X, y, f_loss, f_grad, eps, iter):
    """Performe une descente de gradient.

    Parameters
    ----------
    X : array de taille (n, d)
        Données.
    y : array de taille (n, 1)
        Labels.
    f_loss : callable
        Fonction de coût.
    f_grad : callable
        Gradient de la fonction de coût.
    eps : float
        Pas d'apprentissage.
    iter : int
        Nombre d'itérations.

    Returns
    ----------
    w : array (d, 1)
        Vecteur poids optimal.
    weights : array(self.max_iter + 1, d, 10)
        Historique des vecteurs poids au fur et à mesure de la descente de gradient.
    losses : array(self.max_iter)
        Historique des coûts au fur et à mesure de la descente de gradient.
    """
    w = np.random.randn(X.shape[1], 1)
    weights = [w]  # liste des w
    losses = []  # valeurs de la fonction de coût
    for _ in range(iter):
        w = w - eps * f_grad(w, X, y).mean(0).reshape(-1, 1)
        # if np.allclose(w, weights[i], rtol=1e-4):
        #     break  # convergence du gradient
        losses.append(f_loss(w, X, y).mean())
        weights.append(w)
    return w, np.array(weights), np.array(losses)

if __name__ == "__main__":
    ## Tirage d'un jeu de données aléatoire avec un bruit de 0.1
    datax, datay = gen_arti(epsilon=0.1)
    ## Fabrication d'une grille de discrétisation pour la visualisation de la fonction de coût
    grid, x_grid, y_grid = make_grid(xmin=-2, xmax=2, ymin=-2, ymax=2, step=100)

    plt.figure()
    ## Visualisation des données et de la frontière de décision pour un vecteur de poids w
    w = np.random.randn(datax.shape[1], 1)
    plot_frontiere(datax, lambda x: np.sign(x.dot(w)), step=100)
    plot_data(datax, datay)

    ## Visualisation de la fonction de coût en 2D
    plt.figure()
    plt.contourf(
        x_grid,
        y_grid,
        np.array([mse(w, datax, datay).mean() for w in grid]).reshape(x_grid.shape),
        levels=20,
    )


from tkinter import *
from tkinter import ttk
import pymysql

win=Tk()
win.title("student management system")
win.geometry("1350x700+0+0")

title=Label(win,text="Student Management System",font=("times new roman",40,"bold"),bg='black',fg='white',bd=10,relief=GROOVE)
title.pack(fill=X)
frame1=Frame(win,bd=4,relief=RIDGE,bg='#2C3539')
frame1.place(x=30,y=100,width=450,height=560)

# variable
Roll_var=StringVar()
Name_var=StringVar()
Email_var=StringVar()
Gender_var=StringVar()
Contact_var=StringVar()
Dob_var=StringVar()
sby=StringVar()
s=StringVar()
# ?function
def add_():
    con=pymysql.connect(host="localhost",user='root',password='',database='stm')
    cur=con.cursor()
    cur.execute("insert into stu values(%s,%s,%s,%s,%s,%s,%s)",(Roll_var.get(),
    Name_var.get(),
    Email_var.get(),
    Gender_var.get(),
    Contact_var.get(),
    Dob_var.get(),
    title8_f.get('1.0',END)
    ))
    con.commit()
    showdata()
    clear_()

    con.close()
    # print(Roll_var.get(),
    # Name_var.get(),
    # Email_var.get(),
    # Gender_var,
    # Contact_var,
    # Dob_var)
def showdata():
    con=pymysql.connect(host="localhost",user='root',password='',database='stm')
    cur=con.cursor()
    cur.execute("select * from stu")
    row=cur.fetchall()
    if len(row)!=0:
        stable.delete(*stable.get_children())
        for r in row:
            stable.insert('',END,values=r)
        con.commit()
    con.close()
def clear_():
    Roll_var.set(''),
    Name_var.set(''),
    Email_var.set(''),
    Gender_var.set(''),
    Contact_var.set(''),
    Dob_var.set(''),
    title8_f.delete('1.0',END)

def info(even):
    row=stable.focus()
    content=stable.item(row)
    row1=content['values']
    # print(row)
    # print(row1)
    Roll_var.set(row1[0])
    Name_var.set(row1[1])
    Email_var.set(row1[2])
    Gender_var.set(row1[3])
    Contact_var.set(row1[4])
    Dob_var.set(row1[5])
    title8_f.delete('1.0',END)
    title8_f.insert(END,row1[6])

def update_():
    con=pymysql.connect(host="localhost",user='root',password='',database='stm')
    cur=con.cursor()
    cur.execute("update  stu set name=%s,email=%s,gender=%s,contact=%s,Dob=%s,adress=%s where Roll=%s",(
    Name_var.get(),
    Email_var.get(),
    Gender_var.get(),
    Contact_var.get(),
    Dob_var.get(),
    title8_f.get('1.0',END),
    Roll_var.get()
    ))
    con.commit()
    showdata()
    clear_()

    con.close()
    # a
# Full texts
# Roll
# name
# email
# gender
# contact
# Dob
# adress
# sql = "UPDATE customers SET address = %s WHERE address = %s"
# val = ("Valley 345", "Canyon 123")

def delete_():
    con=pymysql.connect(host="localhost",user='root',password='',database='stm')
    cur=con.cursor()
    cur.execute("delete from stu where Roll=%s",Roll_var.get())
    con.commit()
    showdata()
    clear_()

    con.close()

def search_():
    con=pymysql.connect(host="localhost",user='root',password='',database='stm')
    cur=con.cursor()
    cur.execute(f"SELECT * FROM stu WHERE {str(sby.get())}={str(s.get())}")
    row=cur.fetchall()
    if len(row)!=0:
        stable.delete(*stable.get_children())
        for r in row:
            stable.insert('',END,values=r)
        con.commit()
    con.close()

# ?part 1?
title1=Label(frame1,text='Manage student',font=("times new roman",30,'bold'),bg="#2C3539",fg='white')
title1.grid(row=0,column=2)

title2=Label(frame1,text='Roll Number',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title2.grid(row=4,column=0)
title2_f=Entry(frame1,font=("times new roman",15,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,textvariable=Roll_var)
title2_f.grid(row=4,column=2,pady=10)

title3=Label(frame1,text='Name',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title3.grid(row=8,column=0)
title3_f=Entry(frame1,font=("times new roman",15,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,textvariable=Name_var)
title3_f.grid(row=8,column=2,pady=10)

title4=Label(frame1,text='Email',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title4.grid(row=12,column=0)
title4_f=Entry(frame1,font=("times new roman",15,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,textvariable=Email_var)
title4_f.grid(row=12,column=2,pady=10)

title5=Label(frame1,text='Gender',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title5.grid(row=16,column=0)
title5_f=ttk.Combobox(frame1,font=("times new roman",15,'bold'),width=19,state='readonly',textvariable=Gender_var)
title5_f['values']=['Male','Female','Other']
title5_f.grid(row=16,column=2,pady=10)

title6=Label(frame1,text='Contact',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title6.grid(row=17,column=0)
title6_f=Entry(frame1,font=("times new roman",15,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,textvariable=Contact_var)
title6_f.grid(row=17,column=2,pady=10)

title7=Label(frame1,text='D.O.B',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title7.grid(row=18,column=0)
title7_f=Entry(frame1,font=("times new roman",15,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,textvariable=Dob_var)
title7_f.grid(row=18,column=2,pady=10)

title8=Label(frame1,text='Adress',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title8.grid(row=19,column=0)
title8_f=Text(frame1,font=("times new roman",15,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,width=19,height=2)
title8_f.grid(row=19,column=2,pady=10)

button=Button(frame1,text='Add',cursor="hand2",font=("times new roman", 15 ,'bold'),bg='grey',fg='white',width=5,command=add_)
button.grid(row=20,column=0,pady=5)

button1=Button(frame1,text='Delete',cursor="hand2",font=("times new roman", 15 ,'bold'),bg='grey',fg='white',width=5,command=delete_)
button1.grid(row=20,column=2,pady=5)

button2=Button(frame1,text='Update',cursor="hand2",font=("times new roman", 15 ,'bold'),bg='grey',fg='white',width=5,command=update_)
button2.grid(row=21,column=0,pady=3)

button3=Button(frame1,text='Clear',cursor="hand2",font=("times new roman", 15,'bold'),bg='grey',fg='white',width=5,command=clear_)
button3.grid(row=21,column=2,pady=3)

frame2=Frame(win,bd=4,relief=RIDGE,bg='#2C3539')
frame2.place(x=600,y=100,width=700,height=560)

title9=Label(frame2,text='Search By',font=("times new roman",15,'bold'),bg="#2C3539",fg='white')
title9.grid(row=0,column=0,padx=3)
title9_f=ttk.Combobox(frame2,font=("times new roman",15,'bold'),state='readonly',width=10,textvariable=sby)
title9_f['values']=['Roll','contact','name']
title9_f.grid(row=0,column=1,pady=10,padx=3)

button4=Button(frame2,text='Serach',cursor="hand2",font=("times new roman", 13,'bold'),bg='grey',fg='white',width=5,command=search_)
button4.grid(row=0,column=2,pady=10,padx=30)
title10_f=Entry(frame2,font=("times new roman",12,'bold'),bg="white",fg='black',bd=5,relief=GROOVE,width=16,textvariable=s)
title10_f.grid(row=0,column=3,pady=10)

button5=Button(frame2,text='Show All',cursor="hand2",font=("times new roman", 13,'bold'),bg='grey',fg='white',width=16)
# button5.grid(row=0,column=4,pady=10,padx=3)
button5.place(x=90,y=500)

# table frame
frame3=Frame(frame2,bd=4,relief=RIDGE,bg='white')
frame3.place(x=90,y=70,width=500,height=420)

scroll_x=Scrollbar(frame3,orient=HORIZONTAL)
scroll_y=Scrollbar(frame3,orient=VERTICAL)

stable=ttk.Treeview(frame3,column=('Roll','Name','Email','Gender','Contact','D.O.B','Adress'),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)
scroll_x.pack(side=BOTTOM,fill=X)
scroll_y.pack(side=RIGHT,fill=Y)
scroll_x.config(command=stable.xview)
scroll_y.config(command=stable.yview)
stable.heading('Roll',text='Roll no')
stable.heading('Name',text='SName')
stable.heading('Email',text='SEmail')
stable.heading('Gender',text='SGender')
stable.heading('Contact',text='SContact')
stable.heading('D.O.B',text='D.O.B')
stable.heading('Adress',text='SAdress')
stable['show']='headings'

stable.column('Roll',width=100)
stable.column('Name',width=100)
stable.column('Email',width=100)
stable.column('Gender',width=100)
stable.column('Contact',width=100)
stable.column('D.O.B',width=100)
stable.column('Adress',width=100)

stable.pack(expand=1,fill=BOTH)
showdata()
stable.bind('<ButtonRelease-1>',info)
win.mainloop()


from typing import Dict, List, Tuple
from uuid import UUID

from fastapi import Depends
from sqlalchemy import update, delete, select, text as sa_text
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from fastapi_server.apps.todos.schemas import TodoOrderByType

from fastapi_server.resources.database.postgres import (
    OrderDirectionType,
    get_db_session,
    paginate_query,
)
from ..models import Todo

class TodosDB:
    session: Session

    def __init__(self, session: Session):
        self.session = session

    async def get_todos_by_owner(
        self,
        owner: str,
        *,
        order_by: TodoOrderByType = "created_on",
        order_direction: OrderDirectionType = "asc",
        page: int = 1,
        page_size: int = 10,
    ) -> List[Todo]:
        order = (
            sa_text(f"{order_by} desc")
            if order_direction == "desc"
            else sa_text(order_by)
        )
        query = select(Todo).filter(Todo.owner == owner).order_by(order)
        paginated_query, count_query = paginate_query(query, page, page_size)
        todos = (await self.session.execute(paginated_query)).scalars().all()
        count = (await self.session.execute(count_query)).scalar()
        return todos, count

    async def get_todos_by_project_id(
        self,
        project_id: UUID,
        *,
        order_by: TodoOrderByType = "created_on",
        order_direction: OrderDirectionType = "asc",
        page: int = 1,
        page_size: int = 10,
    ) -> Tuple[List[Todo], int]:
        order = (
            sa_text(f"{order_by} desc")
            if order_direction == "desc"
            else sa_text(order_by)
        )
        query = select(Todo).filter(Todo.project_id == project_id).order_by(order)
        paginated_query, count_query = paginate_query(query, page, page_size)
        todos = (await self.session.execute(paginated_query)).scalars().all()
        count = (await self.session.execute(count_query)).scalar()
        return todos, count

    async def get_todo_by_id(self, todo_id: UUID) -> Todo:
        result = await self.session.execute(select(Todo).filter(Todo.id == todo_id))
        return result.scalar()

    async def add_todo(self, todo: Dict) -> Todo:
        db_todo = Todo(**todo)
        self.session.add(db_todo)
        await self.session.commit()
        await self.session.refresh(db_todo)
        return db_todo

    async def update_todo(self, todo_id: UUID, update_values) -> Todo:
        q = update(Todo).where(Todo.id == todo_id).values(update_values)
        q.execution_options(synchronize_session="fetch")
        await self.session.execute(q)
        await self.session.commit()
        return await self.get_todo_by_id(todo_id)

    async def delete_todo_by_id(self, todo_id: UUID):
        q = delete(Todo).where(Todo.id == todo_id)
        q.execution_options(synchronize_session="fetch")
        await self.session.execute(q)
        await self.session.commit()

def get_todos_db(session: AsyncSession = Depends(get_db_session)) -> TodosDB:
    return TodosDB(session)