import fileinput
from random import *
from tkinter import *
from time import *
import tkinter

def draw_rooms(rooms):
    global scale
    global start
    global end
    colors = ['lime', 'red', 'yellow']
    for key in rooms:
        rooms[key][0] = rooms[key][0] * scale
        rooms[key][1] = rooms[key][1] * scale
        x = rooms[key][0]
        y = rooms[key][1]
        if (key == start):
            f = 0
        elif (key == end):
            f = 1
        else:
            f = 2
        canvas.create_oval(x, y, x+scale, y+scale, fill=colors[f], outline='black', width=2)
        canvas.create_text(x + scale/2, y + scale/2, anchor=W, font="Purisa", text=key)
    canvas.create_text(5, size - 80, anchor=W, font=("Courier", 30), text="start room - ")
    canvas.create_text(230, size - 80, anchor=W, fill="green", font=("Purisa", 30), text=start)
    canvas.create_text(5, size - 50, anchor=W, font=("Courier", 30), text="end room - ")
    canvas.create_text(230, size - 50, anchor=W, fill="red", font=("Purisa", 30), text=end)
    root.update()
    sleep(0.5)

def draw_links(rooms, links):
    global scale
    for el in links:
        f = rooms[el[0]]
        s = rooms[el[1]]
        canvas.create_line(f[0] + scale/2, f[1] + scale/2, s[0] + scale/2, s[1] + scale/2)

def read_map(rooms, links, action):
    global num
    global start
    global end
    global num_room
    f = 0
    # num = input()
    for line in fileinput.input():
        line = line.rstrip()
        #print(line)
        if line == "KARAMBA!":
            break
        elif line == "ERROR":
            print("Something wrong")
            exit()
        elif line != "" and line[0] == 'L':
            action.append(line)
        elif line == "##start":
            f = 1
        elif line == "##end":
            f = 2
        elif line == "" or line[0] == '#':
            continue
        elif num_room == 0 and num == "":
            num = line
        elif line.find(' ') != -1:
            num_room += 1
            new = line.split(maxsplit=1)
            coordi = new[1].split(' ')
            coordi[0] = (int(coordi[0])  + randint(10,20))
            coordi[1] = (int(coordi[1])  + randint(10,20))
            rooms[new[0]] = coordi
            if f == 1:
                start = new[0]
                f = 0
            if f == 2:
                end = new[0]
                f = 0
        elif line.find('-') != -1:
            new = line.split('-')
            links.append(new)

def draw_ant(key, number):
    global rooms
    global img
    global scale
    colors = ['aqua', 'blue', 'fuchsia', 'green', 'maroon', 'orange',
                  'pink', 'purple', 'red','yellow', 'violet', 'indigo', 'chartreuse', 'lime']
    x = rooms[key][0]
    y = rooms[key][1]
    ant = canvas.create_rectangle(x , y , x + scale, y + scale, outline=colors[number], fill=colors[number], width=1, tag='ant')
    #canvas.create_image(x+10, y+10, anchor=NW, image=img, tag='ant')

def draw_action(action):
    global num
    global start
    global speed
    global size
    global end

    f = 0
    newa = "L" + num
    draw_ant(start, 11)
    root.update()
    sleep(speed)
    i = 1
    # canvas.create_text(5, size - 80, anchor=W, font=("Purisa", 30), text="start room - ")
    # canvas.create_text(150, size - 80, anchor=W, fill="green", font=("Purisa", 30), text=start)
    # canvas.create_text(5, size - 50, anchor=W, font=("Purisa", 30), text="end room - ")
    # canvas.create_text(150, size - 50, anchor=W, fill="red", font=("Purisa", 30), text=end)
    for value in action:
        canvas.delete('ant')
        canvas.create_text(5, size - 25, anchor=W, tag='ant', font="Courier", text="iterations: " + (str)(i))
        canvas.create_text(5, size - 5, anchor=W, tag='ant', font="Courier", text="speed: " + (str)(2.5 - speed))
        i = i + 1
        if (f == 0):
            if (value.find(newa) != -1):
                f = 1
            else:
                draw_ant(start, 11)
        new = value.split(' ')
        for value1 in new:
            new1 = value1.split('-')
            draw_ant(new1[1], int(new1[0][-1]))
        root.update()
        #Button(root, text="Quit", command=root.destroy).pack()
        sleep(speed)

def speedd():
    global speed
    if (speed > 0.5):
        speed = speed - 0.5
    #print(speed)

rooms = {}
links = []
action = []
num = ""
start = ""
end = ""
size = 1000

speed = 2
num_room = 0
root = Tk()
canvas = Canvas(root, width=size * 2 - 300, height=size)
canvas.pack()
#img = PhotoImage(file="py/smoking_ant.png")
#img = img.subsample(7)
#canvas.create_image(0, 0, anchor=NW, image=img)
read_map(rooms, links, action)
if num_room < 10:
    scale = 30
elif num_room < 50:
    scale = 10
else:
    scale = 5
draw_rooms(rooms)
draw_links(rooms, links)
print(action)

#допустим, я знаю start и end уже
#движение одного муравья
Button(root, text="Speed", command=speedd).pack()
Button(root, text="Quit", command=root.destroy).pack()
canvas.create_text(size * 2 - 450, size - 5, anchor=W, font="Courier", text=u"\u00A9" + " dholiday, mkami")

root.update()
draw_action(action)

sleep(5)
root.destroy()
#input('Press ENTER to exit')
#Button(root, text="Speed", command=speedd).pack()
#Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()


import os
import sys
import logging
from pathlib import Path
from datetime import timedelta

import numpy as np
import torch
import torch.optim as optim
import torch.distributed as dist
import torch.multiprocessing as mp

from torch.utils.tensorboard import SummaryWriter
from torch.nn.parallel import DistributedDataParallel
import detectron2.utils.comm as comm
from detectron2.data import build_detection_train_loader
from detectron2.utils.env import seed_all_rng

import utils
import models
import checkpoint

_PORT = 2**15 + 2**14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2**14
_DIST_URL = f"tcp://127.0.0.1:{_PORT}"
_DEFAULT_TIMEOUT = timedelta(minutes=30)

def train(cfg):
    n_gpu = len(cfg.cuda.indices)
    cfg.output_dir = cfg.output_dir

    if n_gpu > 1:
        mp.spawn(
            _dist_train_worker,
            nprocs=n_gpu,
            args=(
                _train_for_object_detection,
                n_gpu,
                n_gpu,
                0,
                _DIST_URL,
                (cfg,),
                _DEFAULT_TIMEOUT,
            ),
            daemon=False,
        )
    else:
        _train_for_object_detection(cfg)

def _dist_train_worker(
    local_rank,
    main_func,
    world_size,
    num_gpus_per_machine,
    machine_rank,
    dist_url,
    args,
    timeout,
):
    global_rank = machine_rank * num_gpus_per_machine + local_rank
    dist.init_process_group(
        backend="NCCL",
        init_method=dist_url,
        world_size=world_size,
        rank=global_rank,
        timeout=timeout,
    )
    num_machines = world_size // num_gpus_per_machine
    for i in range(num_machines):
        ranks_on_i = list(range(i * num_gpus_per_machine, (i + 1) * num_gpus_per_machine))
        pg = dist.new_group(ranks_on_i)
        if i == machine_rank:
            comm._LOCAL_PROCESS_GROUP = pg

    assert num_gpus_per_machine <= torch.cuda.device_count()
    torch.cuda.set_device(local_rank)
    comm.synchronize()
    main_func(*args)

def _train_for_object_detection(cfg):

    output_path = Path(cfg.output_dir)

    # Seed random number generator.
    seed_all_rng(cfg.seed + comm.get_rank())
    torch.manual_seed(cfg.seed)

    if comm.is_main_process():
        logging.info(f"Output path: {output_path}")

    # Build data loader.
    if hasattr(cfg.setting, 'vision_network'):
        vision_task = cfg.setting.vision_network.task
        vision_model = cfg.setting.vision_network.model
    else:  # dummy for dataloader
        vision_task = 'detection'
        vision_model = 'faster_rcnn_X_101_32x8d_FPN_3x'
    _od_cfg = utils.get_od_cfg(vision_task, vision_model)
    _od_cfg.SOLVER.IMS_PER_BATCH = cfg.batch_size
    dataloader = build_detection_train_loader(_od_cfg)

    # Build end-to-end model.
    end2end_network = models.EndToEndNetwork(cfg)

    # Load on GPU.
    end2end_network.cuda()

    # Set mode as training.
    end2end_network.train()

    filter_train_flag = hasattr(cfg.setting, 'filtering_network') and cfg.setting.filtering_network.train
    estimator_train_flag = hasattr(cfg.setting, 'rate_estimator') and cfg.setting.rate_estimator.train
    estimator_restore_flag = hasattr(cfg.setting, 'rate_estimator') and cfg.setting.rate_estimator.pretrained

    # Build optimizers.
    if filter_train_flag:
        filtering_cfg = cfg.setting.filtering_network
        filtering_params = list(end2end_network.filtering_network.parameters())
        filtering_optimizer, filtering_optimizer_scheduler = _create_optimizer(
            filtering_params,
            filtering_cfg.optimizer.name,
            filtering_cfg.optimizer.scheduler,
            filtering_cfg.optimizer.learning_rate,
            cfg.total_step,
            filtering_cfg.optimizer.final_lr_ratio)
        if comm.is_main_process():
            filtering_ckpt = checkpoint.Checkpoint(output_path / 'filtering_network')

    if estimator_train_flag:
        estimator_cfg = cfg.setting.rate_estimator
        estimator_params = list(end2end_network.rate_estimator.parameters())
        estimator_optimizer, estimator_optimizer_scheduler = _create_optimizer(
            estimator_params,
            estimator_cfg.optimizer.name,
            estimator_cfg.optimizer.scheduler,
            estimator_cfg.optimizer.learning_rate,
            cfg.total_step,
            estimator_cfg.optimizer.final_lr_ratio)
        if comm.is_main_process():
            estimator_ckpt = checkpoint.Checkpoint(output_path / 'rate_estimator')

    if estimator_restore_flag:
        _ckpt_path = Path(cfg.setting.rate_estimator.pretrained)
        _ckpt = checkpoint.Checkpoint(_ckpt_path / 'train' / 'rate_estimator')
        _ckpt.load(end2end_network.rate_estimator, cfg.setting.rate_estimator.pretrained_step)

    # Distributed.
    distributed = comm.get_world_size() > 1
    if distributed:
        end2end_network = DistributedDataParallel(
            end2end_network,
            device_ids=[comm.get_local_rank()],
            broadcast_buffers=False,
            find_unused_parameters=True
        )

    # Create summary writer.
    if comm.is_main_process():
        writer = SummaryWriter(output_path)

    # Run training loop.
    logging.info("Start training.")
    end_step = cfg.total_step

    for data, step in zip(dataloader, range(1, end_step + 1)):

        # Prepare control input.
        if cfg.setting.control_input == 'none':
            control_input = None
        elif cfg.setting.control_input == 'random':
            control_input = np.random.rand(cfg.batch_size // comm.get_world_size())
        else:
            control_input = np.ones((cfg.batch_size // comm.get_world_size(),)) * cfg.setting.control_input

        # Forward pass.
        outs = end2end_network(data, control_input=control_input)

        # Backpropagation.
        if filter_train_flag:
            filtering_optimizer.zero_grad()
            loss_rd = outs['loss_r'] + outs['loss_d']
            loss_rd.backward(retain_graph=estimator_train_flag)
            filtering_optimizer.step()
            filtering_optimizer_scheduler.step()

        if estimator_train_flag:
            estimator_optimizer.zero_grad()
            loss_aux = outs['loss_aux']
            loss_aux.backward(inputs=estimator_params)
            estimator_optimizer.step()
            estimator_optimizer_scheduler.step()

        # Write on tensorboard.
        if comm.is_main_process():
            scalars = dict()
            for k, v in outs.items():
                if len(v.shape) == 0:
                    scalars[k] = v
            scalars = comm.reduce_dict(scalars)
            if filter_train_flag:
                scalars.update({'learning_rate/filtering_network': filtering_optimizer_scheduler.get_last_lr()[0]})
            if estimator_train_flag:
                scalars.update({'learning_rate/rate_estimator': estimator_optimizer_scheduler.get_last_lr()[0]})
            writer.add_scalars('train', scalars, step)

            if step % 100 == 0:
                info_msg = f"step: {step:6} "
                for k, v in scalars.items():
                    info_msg += f"| {k}: {v:7.4f} "
                logging.info(info_msg)

                if step % cfg.saving_period == 0:
                    if distributed:
                        if filter_train_flag:
                            network = end2end_network.module.filtering_network
                            filtering_ckpt.save(network, step)
                        if estimator_train_flag:
                            network = end2end_network.module.rate_estimator
                            estimator_ckpt.save(network, step)
                    else:
                        if filter_train_flag:
                            network = end2end_network.filtering_network
                            filtering_ckpt.save(network, step)
                        if estimator_train_flag:
                            network = end2end_network.rate_estimator
                            estimator_ckpt.save(network, step)

def _create_optimizer(parameters, optim_name, scheduler_name, initial_lr, total_steps, final_rate=.1):
    if optim_name == 'sgd':
        optimizer = optim.SGD(parameters, lr=initial_lr, momentum=0.9)
    elif optim_name == 'adam':
        optimizer = optim.Adam(parameters, lr=initial_lr)
    else:
        raise NotImplemented("Currently supported optimizers are 'adam' and 'sgd'.")

    if scheduler_name == 'constant':
        scheduler = optim.lr_scheduler.ConstantLR(optimizer, factor=1.0)
    elif scheduler_name == 'exponential':
        gamma = final_rate ** (1 / total_steps)
        scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=gamma)
    else:
        raise NotImplemented("Currently supported schedulers are 'constant' and 'exponential'.")
    return optimizer, scheduler


import deeplab_v3_plus.data.transforms as T

from deeplab_v3_plus.data.dataset.bdd import BDDSegmentation
from deeplab_v3_plus.data.dataset.mapillary import MapillaryVistas
from deeplab_v3_plus.data.dataset.pascal import VOCSegmentation
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.distributed import DistributedSampler

def build_transform(augmentation):
    """
    Build the transform (aka data augmentation)

    Args:
        augmentation: A tuple of transform methods. A method can be a name of a method that takes no argument
        (a string), or a method that takes argument (a tuple starts with a string, and follows by the arguments)

    Returns:

    """
    transform_list = []
    for method in augmentation:
        if isinstance(method, tuple):
            name = method[0]
            args = method[1:]
        else:
            name = method
            args = None

        if not hasattr(T, name):
            raise NotImplementedError

        trans = getattr(T, name)
        if args:
            transform_list.append(trans(*args))
        else:
            transform_list.append(trans())

    transform = T.Compose(transform_list)
    return transform

def build_dataloader(cfg, mode='train', distributed=False):
    """
    Build the dataloader
    Args:
        cfg: configuration dictionary
        mode (str): Must be one of three modes ['train', 'val', 'test']
            mode help us to control which part of the configuration file we should read
        distributed (bool): True if we are using distributed data parallel

    Returns:

    """
    if mode == 'train':
        batch_size = cfg.TRAIN.BATCH_SIZE
        augmentation = cfg.TRAIN.AUGMENTATION
    elif mode == 'val':
        batch_size = cfg.VALIDATE.BATCH_SIZE
        augmentation = cfg.VALIDATE.AUGMENTATION
    elif mode == 'test':
        batch_size = cfg.TEST.BATCH_SIZE
        augmentation = cfg.TEST.AUGMENTATION
    else:
        raise NotImplementedError

    # Load transform
    transform = build_transform(augmentation)

    if cfg.DATASET.NAME == "Pascal":
        dataset = VOCSegmentation(root_dir=cfg.DATASET.ROOT_DIR,
                                  type=mode,
                                  transform=transform)
    elif cfg.DATASET.NAME == "BDD":
        dataset = BDDSegmentation(root_dir=cfg.DATASET.ROOT_DIR,
                                  type=mode,
                                  transform=transform,
                                  ignore_index=255)
    elif cfg.DATASET.NAME == "Mapillary":
        dataset = MapillaryVistas(root_dir=cfg.DATASET.ROOT_DIR,
                                  type=mode,
                                  transform=transform)
    else:
        raise NotImplementedError('Unsupported dataset: {}'.format(cfg.DATASET.NAME))

    is_train = (mode == 'train')
    if distributed:
        sampler = DistributedSampler(dataset, shuffle=is_train)
        is_train = False
        # Warning: when using DistributedSampler() the batch_size is not the total batch size
        # it is the batch size per process.
    else:
        sampler = None

    dataloader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=is_train,
        sampler=sampler,
        drop_last=(is_train and cfg.DATALOADER.DROP_LAST),
        num_workers=cfg.DATALOADER.NUM_WORKERS,
        pin_memory=cfg.DATALOADER.PIN_MEMORY,
    )
    return dataloader


#

import pytest
import py
from unittest.mock import patch

from docstats.config import parseconfig, geturls, getbranches, getbranchparts

# Our global variables which is used in our configuration parser
# will be overwritten bei setup_module()
config = None
configfiles = None
tmpdir = None
tmpfile = None

def setup_module(module):
    if config is not None:
        return

    try:
        module.tmpdir = py.path.local('/tmp').mkdtemp()

    except py.error.EEXIST:
        module.tmpdir = py.path.local('/tmp/pytest/config')
    module.tmpfile = tmpdir / "docstats.ini"
    module.tmpfile.write("""[globals]
branch = develop

[doc-a]
url = git://doc-a.git

[doc-b]
url = git://doc-b.git
branches =
    maint/a
    maint/b  abce
    maint/c  ..f123
    maint/d  abce..
    maint/e  1234..345a
    # maint/f  1234..56789

[doc-c]
url =
        """)
    # module is our global scope
    module.configfiles, module.config = parseconfig(tmpfile.strpath)

def teardown_module(module):
    module.tmpdir.remove(ignore_errors=True)

# --------------------------------------------------------
def test_config_files():
    assert len(configfiles) == 1

def test_config_global():
    assert config['globals']

def test_config_global_branch():
    assert config['globals']['branch']

def test_config_sections():
    sec = config.sections()
    assert config.sections() == ['doc-a', 'doc-b', 'doc-c']

def test_config_url():
    assert config['doc-a']['url'] == 'git://doc-a.git'

# --------------------------------------------------------
def test_geturls():
    urls = list(geturls(config))
    assert len(urls) == 2
    assert urls == [('doc-a', 'git://doc-a.git'), ('doc-b', 'git://doc-b.git')]

def test_geturls_with_section():
    urls = list(geturls(config, ['doc-a']))
    assert len(urls) == 1
    assert urls == [('doc-a', 'git://doc-a.git'),]

def test_geturls_with_section_and_empty_url():
    urls = list(geturls(config, ['doc-c']))
    assert urls == []

def test_geturls_with_unknown_section():
    urls = list(geturls(config, ['missing']))
    assert urls == []

@patch('docstats.config.ConfigParser')
def test_geturls_with_patching(mock_config):
    mock_config.sections.return_value = ['foo']
    mock_config.get.return_value = 'url-value'
    urls = list(geturls(mock_config))
    assert urls == [('foo', 'url-value')]

# --------------------------------------------------------
@pytest.mark.parametrize('string,expected', [
    #
    (None, []),
    #
    ('', []),
    #
    ('''name br/a
    ''', [('name', 'br/a', '', '')]),
    #
    ('''
 # br/null  adfadf..affee
 name br/a   abc..def
 # This is an additional comment
 name br/b
''', [('name', 'br/a', 'abc', 'def'), ('name', 'br/b', '', '')]),
    #
    ('''
 # br/null  adfadf..affee
 name  br/a   abc..
 name br/b   ..def
 name br/c   bcd..eff
''', [('name', 'br/a', 'abc', ''),
      ('name', 'br/b', '', 'def'),
      ('name', 'br/c', 'bcd', 'eff')])

])
def test_getbranches(string, expected):
    assert list(getbranches(string)) == expected

@pytest.mark.parametrize('string,expected', [
    #
    ('name',                              [('name', 'develop', '', '')]),
    #
    ('name maintenance/SLE12',            [('name', 'maintenance/SLE12', '', '')]),
    #
    (' name maintenance/SLE12   abc\n',   [('name', 'maintenance/SLE12', 'abc', '')]),
    #
    ('name maintenance/SLE12   abc..',    [('name', 'maintenance/SLE12', 'abc', '')]),
    #
    ('name maintenance/SLE12   ..abc',    [('name', 'maintenance/SLE12', '', 'abc')]),
    #
    ('name maintenance/SLE12   abc..def', [('name', 'maintenance/SLE12', 'abc', 'def')]),
])
def test_getbranchparts(string, expected):
    assert list(getbranchparts(string)) == expected


# -*- coding: utf-8 -*-
from __future__ import absolute_import
from soma.spm.custom_decorator_pattern import checkIfArgumentTypeIsAllowed

class TContrast(object):
  """
  * Simple one-dimensional contrasts for an SPM{T}
  A  simple  contrast  for  an  SPM{T}  tests  the  null  hypothesis  c'B=0 against the
  one-sided alternative c'B>0, where c is a column vector.
      Note  that  throughout  SPM, the transpose of the contrast weights is used for
      display  and  input.  That is, you'll enter and visualise c'. For an SPM{T} this will
      be a row vector.
  """
  @checkIfArgumentTypeIsAllowed(list, 1)
  def setVector(self, vector):
    self.vector = vector

  def setReplicateOverSessions(self, option):
    if option in self.possible_options:
      self.replicate_over_sessions = self.possible_options[option]
    else:
      raise ValueError('Replicate over sessions possibilities are : ' + str(list(self.possible_options.keys())))

  def getStringListForBatch( self ):
    if not None in [self.vector, self.name]:
      batch_list = []
      batch_list.append("tcon.name = '%s';" % self.name)
      vector_list = [str(coeff) for coeff in self.vector]
      vector_str = ' '.join(vector_list)
      batch_list.append("tcon.convec = [%s];" % vector_str)
      batch_list.append("tcon.sessrep = '%s';" % self.replicate_over_sessions)
      return batch_list
    else:
      raise ValueError('Unvalid contrast, name or vector not found')


hp_dedee = float(input()) # บรรทัด 1 เลือดของดีดี้(float)
adapt_dedee = float(input()) # บรรทัด 2 ค่าการปรับตัวที่ต้องครบ(float)
count_attack_paloy = int(input()) # บรรทัด 3 จำนวนการโจมตีของพาลอย(int)
adjustment = 0

for i in range(count_attack_paloy):
    damage_paloy = float(input())
    adjustment += damage_paloy * 0.03
    hp_dedee -= damage_paloy

if hp_dedee <= 0: # ดีดี้ HP หมด
    print("ดีดี้โดนัท")
elif adjustment >= adapt_dedee:  # HP ดีดี้เหลือและค่าปรับตัวมากกว่าหรือเท่ากับที่กำหนด
    print("พาลอยซาชิมิ")
elif hp_dedee > 0 and adjustment < adapt_dedee:  # เมื่อดีดี้พลังชีวิตเหลือและค่าปรับตัวน้อยกว่าที่กำหนด
    print("ตายคู่")

# อันนี้พี่ว่าพลังพาลอยมันมากไปหน่อยนะใบ้ให้

# ดีดี้จะรับการโจมตีและนำไปเป็นค่าการปรับตัว โดยเมื่อดีดี้ได้รับการโจมตีจะนำความเสียหายที่ได้รับจำนวน 0.03 เท่าของค่าแดมเมจที่ได้รับ
# นำไปเป็นค่าการปรับตัว กล่าวคือเมื่อค่าปรับตัวครบ n หน่วย ดีดี้จะสามารถโจมตีพาลอยได้
# โดยถ้าดีดี้ยังมีพลังชีวิตเหลือจะสามารถโจมตีพาลอยได้(พาลอยจะซาชิมิทันที) แต่ถ้าดีดี้ Hp หมด ดีดี้จะกลายเป็นโดนัท
# โดยพาลอยจะต้องโจมตีจนครบทุกครั้งก่อนดีดี้จึงจะมีโอกาสโจมตีสวน(ถ้าดีดี้ยังไม่โดนัทละก็นะ)

# ถ้าดีดี้ HP หมด = ดีดี้โดนัท ถ้า HP ดีดี้เหลือและค่าปรับตัวมากกว่าหรือเท่าที่กำหนด = พาลอยซาชิมิ เมื่อดีดี้พลังชีวิตเหลือและค่าปรับตัวน้อยกว่าที่กำหนด = ตายคู่5


import frappe
from frappe.model.document import Document
from propertymgt_dxb.public.telegram_updates import sendMessage
from frappe.utils import get_files_path
from frappe.utils.file_manager import save_file, get_file_url
import base64

class RoomBill(Document):

	def on_submit(self):

		pdf_data = frappe.get_print(self.doctype,self.name, print_format = 'Room Bill', as_pdf=True)
		file_id=save_file(f"{self.name}.pdf",pdf_data,self.doctype,self.name,"Home/Attachments/Room Bill",is_private=0)
		direct_url = get_file_url(file_id.name)
		message = f"Attached the flat bill of {self.flat_no}"

		frappe.enqueue(sendMessage,queue="short", message=message,document_path=direct_url)

		room_bill_doc = frappe.get_doc("Room Bill", self.name)

		flat_no_to_remove = room_bill_doc.flat_no

		for bill_item in room_bill_doc.water_bill_table:
			customer = frappe.get_doc("Customer", bill_item.customer)
			if customer.room_list!=[]:
				for flat in customer.room_list:
					if flat.flat == flat_no_to_remove and not flat.current_room:
						customer.room_list.remove(flat)
						customer.save(ignore_permissions=True)


from fastapi import status
from fastapi.testclient import TestClient

from fastapi_demo import app

client = TestClient(app)

def test_delete(existing_sauce):
    resp = client.delete(f"/sauces/{existing_sauce.id}")
    assert resp.status_code == status.HTTP_204_NO_CONTENT
    assert client.get(f"/sauces/{existing_sauce.id}").status_code == status.HTTP_404_NOT_FOUND

def test_get_all(existing_sauce):
    resp = client.get("/sauces/")
    assert resp.status_code == status.HTTP_200_OK
    content = resp.json()
    assert isinstance(content, list)
    assert existing_sauce.data in content

def test_get_one(existing_sauce):
    resp = client.get(f"/sauces/{existing_sauce.id}")
    assert resp.status_code == status.HTTP_200_OK
    content = resp.json()
    assert existing_sauce.data == content

def test_get_nonexistent():
    bad_id = 2000001
    resp = client.get(f"/sauces/{bad_id}")
    assert resp.status_code == status.HTTP_404_NOT_FOUND
    error = resp.json()["detail"]
    assert str(bad_id) in error
    assert "does not exist" in error

def test_create(new_sauce):
    resp = client.post(f"/sauces/{new_sauce.id}", json=new_sauce.data)
    assert resp.status_code == status.HTTP_201_CREATED
    assert new_sauce.data.items() <= resp.json().items()
    assert client.get(f"/sauces/{new_sauce.id}").status_code == status.HTTP_200_OK

def test_create_gen_id(new_sauce):
    resp = client.post("/sauces/", json=new_sauce.data)
    assert resp.status_code == status.HTTP_201_CREATED
    assert new_sauce.data.items() <= resp.json().items()

def test_create_already_exists(existing_sauce, new_sauce):
    resp = client.post(f"/sauces/{existing_sauce.id}", json=new_sauce.data)
    assert resp.status_code == status.HTTP_400_BAD_REQUEST
    error = resp.json()["detail"]
    assert str(existing_sauce.id) in error
    assert "already exists" in error

def test_create_bad_data():
    resp = client.post(
        "/sauces/",
        json={
            "name": "bad",
            "brand": "bad",
            "scoville_scale": "not a number",
        },
    )
    assert resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
    content = resp.json()["detail"]
    assert content[0]["type"] == "int_parsing"
    assert content[0]["loc"] == ["body", "scoville_scale"]

def test_create_missing_data():
    resp = client.post(
        "/sauces/",
        json={
            "brand": "incomplete",
        },
    )
    assert resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
    content = resp.json()["detail"]
    assert content[0]["type"] == "missing"
    assert content[0]["loc"] == ["body", "name"]

def test_update(existing_sauce_2):
    updates = {
        "name": "updated name",
        "brand": "updated brand",
        "scoville_scale": 12,
        "flavor_notes": ["Bright"],
    }
    resp = client.put(f"/sauces/{existing_sauce_2.id}", json=updates)
    resp.status_code == status.HTTP_200_OK
    assert {**existing_sauce_2.data, **updates}.items() <= resp.json().items()
    assert client.get(f"/sauces/{existing_sauce_2.id}").json() == resp.json()

def test_update_incomplete_data(existing_sauce_2):
    updates = {
        "flavor_notes": ["Bright"],
    }
    resp = client.put(f"/sauces/{existing_sauce_2.id}", json=updates)
    resp.status_code == status.HTTP_200_OK
    assert {**existing_sauce_2.data, **updates}.items() <= resp.json().items()
    assert client.get(f"/sauces/{existing_sauce_2.id}").json() == resp.json()

def test_bad_update(existing_sauce_2):
    updates = {
        "name": "updated name",
        "brand": "updated brand",
        "bottle_size": -3,
    }
    resp = client.put(f"/sauces/{existing_sauce_2.id}", json=updates)
    resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
    content = resp.json()["detail"]
    assert content[0]["type"] == "greater_than"
    assert content[0]["loc"] == ["body", "bottle_size"]

def test_update_does_not_exist():
    nonexistent_id = 789
    updates = {
        "name": "updated name",
        "brand": "updated brand",
        "bottle_size": 10,
    }
    resp = client.put(f"/sauces/{nonexistent_id}", json=updates)
    assert resp.status_code == status.HTTP_404_NOT_FOUND
    content = resp.json()["detail"]
    assert str(nonexistent_id) in content
    assert "does not exist" in content


class User:
    def __init__(self,name,email):
        self.name = name
        self.email = email
        self.account_balance = 0

    # def display_user_balance(self):
    #     print(self.account_balance)

    def make_withdrawl(self,amount):
        self.account_balance -= amount
        return self

    def make_deposit(self,amount):
        self.account_balance += amount
        return self

    def transfer_money(self,amount,user):
        self.account_balance -= amount
        user.make_deposit(amount)
        return self

lisa = User("lisa","lisa@gmail.com")

lisa.make_deposit(200).make_deposit(400).make_deposit(1000).make_withdrawl(600)

elliot = User("elliot","elliot@elliot.com")
elliot.make_deposit(2000).make_deposit(2000).make_withdrawl(100).make_withdrawl(400)

nat = User("Natalie","nat@nat.com")
nat.make_deposit(50).make_deposit(20).make_withdrawl(15).make_withdrawl(30)

#BONUS
# print(lisa.account_balance)
# print(nat.account_balance)

lisa.transfer_money(100,nat)

# print(lisa.account_balance)
# print(nat.account_balance)


k = int(input("How many sets do you want to check?"))
for i in range(k):
    ls = list(map(int, input("Enter the 3 side lengths separated by spaces").split()))
    lar = max(ls)
    sma = min(ls)
    ls2 = ls.copy()
    ls2.remove(lar)
    ls2.remove(sma)
    if pow(ls2[0], 2) + pow(sma, 2) == pow(lar, 2):
        print("The triangle is a Pythagorean Triple")
    else:
        print("The triangle is not a Pythagorean Triple")


from utils import data_transform
import metrics
import numpy as np

class LinearRegression:

	def __init__(self, solve_by='ols', regularized=False):
		self.solve_by = solve_by
		self.regularized = regularized

	def train(self, features, labels):
		X = data_transform.insert_ones(features)
		y = labels

		if self.solve_by == 'ols':
			self.weights = self.__ols(X, y)

		elif self.solve_by == 'gdesc':
			self.weights = self.__gradient_descent(X, y)

	def __ols(self, X, y):
		return np.matmul(np.matmul(np.linalg.pinv(np.matmul(X.T, X)), X.T), y)

	def __gradient_descent(self, X, y, learning_rate=10e-2, num_iter=1000, stopping_threshold=10e-4):
		# initial weights
		n = X.shape[0]
		weights = np.zeros(X.shape[1])

		for _iter in range(num_iter):
			gradients = (1 / n) * np.matmul(X.T, np.dot(X, weights) - y)	# vectorized gradient calculation

			old_weights = weights
			weights = weights - learning_rate * gradients 	# gradient descent
			weight_difference = np.linalg.norm(weights - old_weights)

			if weight_difference <= stopping_threshold:		# break early if we're doing well
				break

		return weights

	def predict(self, features):
		X = data_transform.insert_ones(features)
		predictions = np.matmul(X, self.weights)
		return predictions

	def compare_sklearn(self, training_features, training_labels, test_features, test_labels, my_mse, my_r2):

		# do linear regression with sklearn
		from sklearn.linear_model import LinearRegression
		skmodel = LinearRegression()
		skmodel.fit(training_features, training_labels)
		skpreds = skmodel.predict(test_features)

		# get sklearn mse and r2 score
		skmse = metrics.mean_squared_error(test_labels, skpreds)
		skr2 = metrics.r2_score(test_labels, skpreds)

		print("Your model's MSE: {}\nsklearn's MSE: {}".format(my_mse, skmse))
		print()
		print("Your model's R2 score: {}\nsklearn's R2 score: {}".format(my_r2, skr2))


def adjacent_seats(prev_rs, next_rs, s_r, s_c):
    to_change = prev_rs[s_r][s_c]
    if to_change == ".":
        return False

    r_lower = max(0, s_r - 1)
    r_upper = min(len(prev_rs), s_r + 2)
    c_lower = max(0, s_c - 1)
    c_upper = min(len(prev_rs[0]), s_c + 2)

    occupied = 0
    for r in range(r_lower, r_upper):
        for c in range(c_lower, c_upper):
            if r == s_r and c == s_c:
                continue
            if prev_rs[r][c] == "#":
                occupied += 1

    if occupied == 0 and to_change == "L":
        next_rs[s_r][s_c] = "#"
        return True
    elif occupied >= 4 and to_change == "#":
        next_rs[s_r][s_c] = "L"
        return True
    return False

with open("input.txt") as file:
    rows = [list(row) for row in file.read().split("\n")]

swaps = 1
while swaps > 0:
    next_rows = [r[:] for r in rows]
    swaps = 0
    for i in range(len(rows)):
        for j in range(len(rows[0])):
            swaps += adjacent_seats(rows, next_rows, i, j)
    rows = next_rows

total = 0
for row in rows:
    for seat in row:
        total += seat == "#"
print(total)


from events import Event
from collections import deque
from packet import LinkStatePacket

class Link(object):
    def __init__(self, event_manager, i, source, dest, rate, delay,
                 buffer_capacity, debug=True):
        self.debug = debug

        self.em = event_manager
        self.i = i
        self.source = source  # Each end is either a router or a host
        self.dest = dest
        self.rate = rate  # bits per second
        self.delay = delay  # seconds

        self.usable = True  # Whether the link accepts new packets
        self.buffer = deque()
        self.buffer_usage = 0
        self.buffer_capacity = buffer_capacity  # bits

        self.interval_usage = 0 #total buffer usage since last linkstate req

    def set_usable(self, usable_status):
        #  can simulate a physical link cut
        self.usable = usable_status

    def on_packet_entry(self, t, p):
        if not self.usable:
            if self.debug:
                print("t={}: Link {} disabled.".format(round(t, 6), self))
            return  # Packet loss.
        if self.buffer_usage + p.size > self.buffer_capacity:
            if self.debug:
                print("t={}: Link {} lost a packet.".format(round(t, 6), self))
            ### Per-link packet loss ###
            self.em.log_it('LINK|{}'.format(self.i), 'T|{}|LOSS|1'.format(t))
            return  # Packet loss.

        self.buffer.append(p)
        self.update_buffer_usage(t, p.size)
        self.interval_usage += p.size

        if self.debug and type(p) is not LinkStatePacket:
            print('t={}, Link {} enqueueing packet into buffer: {}'.
                  format(round(t, 6), self, p.i))

        if len(self.buffer) == 1: # First packet
            self.transmit_next_packet(t)

    def transmit_next_packet(self, t):
        # Only pay the transmission delay here.
        p = self.buffer[0]
        self.em.enqueue(LinkBufferRelease(t + p.size / self.rate, self))

    def on_buffer_release(self, t):
        p = self.buffer.popleft()
        self.update_buffer_usage(t, -p.size)

        self.em.enqueue(LinkExit(t + self.delay, self, p))
        if len(self.buffer) > 0:
            self.transmit_next_packet(t)

    def update_buffer_usage(self, t, amount):
        self.buffer_usage += amount
        ### Per-link buffer occupancy ###
        self.em.log_it('LINK|{}'.format(self.i), 'T|{}|BUFF|{}'.format(t, amount))

    def on_packet_exit(self, t, exiting_packet):
        if self.debug and type(exiting_packet) is not LinkStatePacket:
            print("t={}: Link {} packet exit, details: {}".
                    format(round(t, 6), self, exiting_packet))

        self.dest.on_reception(t, exiting_packet)
        ### Per-link flow rate ###
        self.em.log_it('LINK|{}'.format(self.i), 'T|{}|FLOW|{}'.format(t, exiting_packet.size))

    def __str__(self):
        return "{} ({} -> {})".format(self.i, self.source.i, self.dest.i)

    def __eq__(self, other):
        return self.i == other.i if isinstance(other, Link) else False

    def __hash__(self):
        return hash(self.i)

class LinkBufferRelease(Event):
    # When a packet is released from the link's buffer.
    def __init__(self, t, link):
        super().__init__(t)
        self.link = link

    def run(self):
        self.link.on_buffer_release(self.t)

class LinkExit(Event):
    # When a packet reaches the end of a link.
    def __init__(self, t, link, packet):
        super().__init__(t)
        self.link = link
        self.packet = packet

    def run(self):
        self.link.on_packet_exit(self.t, self.packet)

class LinkSetUsable(Event):
    def __init__(self, t, link, usable):
        super().__init__(t)
        self.link = link
        self.usable = usable

    def run(self):
        self.link.set_usable(self.usable)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2020/5/27 19:57
Desc: 新浪财经-股票-机构持股
http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml
"""
from mssdk.utils import demjson
import pandas as pd
import requests

def stock_institute_hold(quarter: str = "20051") -> pd.DataFrame:
    """
    新浪财经-股票-机构持股一览表
    http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml
    :param quarter: 从 2005 年开始, {"一季报":1, "中报":2 "三季报":3 "年报":4}, e.g., "20191", 其中的 1 表示一季报; "20193", 其中的 3 表示三季报;
    :type quarter: str
    :return: 机构持股一览表
    :rtype: pandas.DataFrame
    """
    url = "http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml?symbol=%D6%A4%C8%AF%BC%F2%B3%C6%BB%F2%B4%FA%C2%EB"
    params = {
        "p": "1",
        "num": "5000",
        "reportdate": quarter[:-1],
        "quarter": quarter[-1],
    }
    r = requests.get(url, params=params)
    temp_df = pd.read_html(r.text)[0]
    temp_df["证券代码"] = temp_df["证券代码"].astype(str).str.zfill(6)
    del temp_df["明细"]
    temp_df.columns = ['证券代码', '证券简称', '机构数', '机构数变化', '持股比例', '持股比例增幅', '占流通股比例', '占流通股比例增幅']
    return temp_df

def stock_institute_hold_detail(stock: str = "600433", quarter: str = "20201") -> pd.DataFrame:
    """
    新浪财经-股票-机构持股详情
    http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml
    :param stock: 股票代码
    :type stock: str
    :param quarter: 从 2005 年开始, {"一季报":1, "中报":2 "三季报":3 "年报":4}, e.g., "20191", 其中的 1 表示一季报; "20193", 其中的 3 表示三季报;
    :type quarter: str
    :return: 指定股票和财报时间的机构持股数据
    :rtype: pandas.DataFrame
    """
    url = "http://vip.stock.finance.sina.com.cn/q/api/jsonp.php/var%20details=/ComStockHoldService.getJGCGDetail"
    params = {
        "symbol": stock,
        "quarter": quarter,
        }
    r = requests.get(url, params=params)
    text_data = r.text
    json_data = demjson.decode(text_data[text_data.find("{"):-2])
    big_df = pd.DataFrame()
    for item in json_data["data"].keys():
        inner_temp_df = pd.DataFrame(json_data["data"][item]).T.iloc[:-1, :]
        inner_temp_df.reset_index(inplace=True)
        big_df = big_df.append(inner_temp_df, ignore_index=True)
    if not big_df.empty:
        big_df["index"] = big_df["index"].str.split("_", expand=True)[0]
        big_df.rename(columns={"index": "institute"}, inplace=True)
        big_df = big_df.iloc[:, :12]
        big_df.columns = ["持股机构类型",
                          "持股机构代码",
                          "持股机构简称",
                          "持股机构全称",
                          "持股数",
                          "最新持股数",
                          "持股比例",
                          "最新持股比例",
                          "占流通股比例",
                          "最新占流通股比例",
                          "持股比例增幅",
                          "占流通股比例增幅",
                          ]
        big_df["持股机构类型"] = big_df["持股机构类型"].str.replace("fund", "基金")
        big_df["持股机构类型"] = big_df["持股机构类型"].str.replace("socialSecurity", "全国社保")
        big_df["持股机构类型"] = big_df["持股机构类型"].str.replace("qfii", "QFII")
        return big_df
    else:
        return None

if __name__ == '__main__':
    stock_institute_hold_df = stock_institute_hold(quarter="20201")
    print(stock_institute_hold_df)

    stock_institute_hold_detail_df = stock_institute_hold_detail(stock="300003", quarter="20201")
    print(stock_institute_hold_detail_df)


"""
https://github.com/LevinJ/SSD_tensorflow_VOC
training gitproject

"""

import numpy as np
import xml.etree.ElementTree as ET
from tensorflow.keras.utils import Sequence
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import cv2
from utils.utils import imshow

voc_path = 'data/dataset/VOCdevkit/'

voc_2012_image_folder = 'VOC2012/JPEGImages/'
voc_2012_annot_folder = 'VOC2012/Annotations/'
voc_2012_train_image_folder = 'VOC2012/ImageSets/Main/train.txt'
voc_2012_valid_image_folder = 'VOC2012/ImageSets/Main/val.txt'

voc_2007_image_folder = 'VOC2007/JPEGImages/'
voc_2007_annot_folder = 'VOC2007/Annotations/'
voc_2007_train_image_folder = 'VOC2007/ImageSets/Main/train.txt'
voc_2007_valid_image_folder = 'VOC2007/ImageSets/Main/val.txt'
voc_2007_test_image_folder = 'VOC2007/ImageSets/Main/test.txt'

voc_class = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle',
'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
'horse', 'motorbike', 'person', 'pottedplant', 'sheep',
'sofa', 'train', 'tvmonitor']

voc_class_key = {key:item for item, key in enumerate(voc_class)}
voc_class_idx = np.zeros((len(voc_class)))

VOC_2007 = 0
VOC_2012 = 1
VOC_ALL  = 2

BATCH_SIZE = 4
NUM_CLASSES = 20
EPOCHS = 1
DATASET = "."
INPUT_DIM = (227, 227, 3)

config = {
    'dataset': 'voc',
    'data_mode': 'none',
    'batch_size': BATCH_SIZE,
    'img_h': INPUT_DIM[0],
    'img_w': INPUT_DIM[1],
    'img_c': INPUT_DIM[2],
    'num_class': NUM_CLASSES,
    'epochs': EPOCHS,
    'shuffle': 1,
    'do_augment': 0
}

class VOC2007(object):
    image_folder = voc_2007_image_folder
    annot_folder = voc_2007_annot_folder
    train_image_folder = voc_2007_train_image_folder
    valid_image_folder = voc_2007_valid_image_folder
    test_image_folder  = voc_2007_test_image_folder
    trainval_img_folder = [train_image_folder, valid_image_folder]
    test_img_folder = [test_image_folder]

class VOC2012(object):
    image_folder = voc_2012_image_folder
    annot_folder = voc_2012_annot_folder
    train_image_folder = voc_2012_train_image_folder
    valid_image_folder = voc_2012_valid_image_folder
    trainval_img_folder = [ train_image_folder, valid_image_folder ]

class VOC(object):

    datagen = ImageDataGenerator(
                featurewise_center=False,
                samplewise_center=False,
                featurewise_std_normalization=False,
                samplewise_std_normalization=False,
                zca_whitening=False,
                zca_epsilon=1e-6,
                rotation_range=20,
                width_shift_range=0.1,
                height_shift_range=0.1,
                shear_range=0.3,
                zoom_range=0.1,
                channel_shift_range=30,
                fill_mode='nearest',
                cval=0.,
                horizontal_flip=True,
                vertical_flip=False,
                rescale=None,
                preprocessing_function=None)

    VOC_2007 = VOC_2007
    VOC_2012 = VOC_2012
    VOC_ALL  = VOC_ALL
    voc_class = voc_class
    def __init__(self, voc_data= VOC_2012):

        self.dirs = {'voc_path': voc_path }

        if voc_data == VOC_2012:
            self.train_image_folder = [VOC2012.train_image_folder]
            self.valid_image_folder = [VOC2012.valid_image_folder]
        elif voc_data == VOC_2007:
            self.train_image_folder = VOC2007.trainval_img_folder
            self.valid_image_folder = VOC2007.test_img_folder
        elif voc_data == VOC_ALL:
            self.train_image_folder = VOC2007.trainval_img_folder + VOC2012.trainval_img_folder
            self.valid_image_folder = VOC2007.test_img_folder

    def set(self, voc_path):
        self.dirs['voc_path'] = voc_path

        if not os.path.exists(self.dir['voc_path']):
            print("Cannot find dataset from %s", voc_path)
            exit()

    def getFileList(self):
        print("[INFO] Loading File list ...")
        self.train_img_list = []
        self.train_annot_list = []

        for filepath in self.train_image_folder:
            filepath = self.dirs['voc_path'] + filepath
            with  open(filepath, 'r') as f:
                img_list = f.read().split('\n')
            if filepath.find('2012')>=0:
                image_folder = VOC2012.image_folder
                annot_folder = VOC2012.annot_folder
            else:
                image_folder = VOC2007.image_folder
                annot_folder = VOC2007.annot_folder
            print(filepath, image_folder,  annot_folder)
            for l in img_list:
                if l:
                    img_path = '%s%s%s.jpg' % (self.dirs['voc_path'],
                            image_folder, l)
                    self.train_img_list.append(img_path)
                    annot_path = '%s%s%s.xml' % (self.dirs['voc_path'],
                            annot_folder, l)
                    self.train_annot_list.append(annot_path)

        self.valid_img_list = []
        self.valid_annot_list = []

        for filepath in self.valid_image_folder:
            filepath = self.dirs['voc_path'] + filepath
            with  open(filepath, 'r') as f:
                img_list = f.read().split('\n')
            if filepath.find('2012')>=0:
                image_folder = VOC2012.image_folder
                annot_folder = VOC2012.annot_folder
            else:
                image_folder = VOC2007.image_folder
                annot_folder = VOC2007.annot_folder
            print(filepath, image_folder,  annot_folder)
            for l in img_list:
                if l:
                    img_path = '%s%s%s.jpg' % (self.dirs['voc_path'],
                            image_folder, l)
                    self.valid_img_list.append(img_path)
                    annot_path = '%s%s%s.xml' % (self.dirs['voc_path'],
                            annot_folder, l)
                    self.valid_annot_list.append(annot_path)

    def getClassAnnot(self):
        print("[INFO] Getting Class annot  ...")
        _len = len(self.train_annot)
        self.train_label = np.zeros((_len, len(voc_class)))
        j = 0
        for i in self.train_annot:
            objs = i.findall('object')
            for obj in objs:
                self.train_label[j, voc_class_key[obj[0].text]] = 1
            j += 1

        _len = len(self.valid_annot)
        self.valid_label = np.zeros((_len, len(voc_class)))
        j = 0
        for i in self.valid_annot:
            objs = i.findall('object')
            for obj in objs:
                self.valid_label[j, voc_class_key[obj[0].text]] = 1
            j += 1

    def getAnnot(self):
        print("[INFO] Load annot from list ...")
        self.train_annot = []
        for i in self.train_annot_list:
            f = open(i, 'r')
            self.train_annot.append(ET.fromstring(f.read()))
            f.close()

        self.valid_annot = []
        for i in self.valid_annot_list:
            f = open(i, 'r')
            self.valid_annot.append(ET.fromstring(f.read()))
            f.close()

    def setGeneratorConfig(self, config=config):
        """
        batch_size : 64
        img_h : 224
        img_w : 224
        img_c : 3
        norm : 1
        num_classes: 20
        shuffle : 0
        """
        self.config = config
        self.shuffle = config['shuffle']
        if self.config['data_mode'] == 'on_memory':
            self.getImage()

    def getImage(self):
        print("[INFO] Load image from list to memory ...")
        _len = len(self.train_annot)
        self.train_images = np.zeros((_len,
                            self.config['img_h'],
                            self.config['img_w'],
                            self.config['img_c']))
        for j in range(_len):
            img_path = self.train_img_list[j]
            img = cv2.imread(img_path)[:,:,::-1]
            img = cv2.resize(img, (self.config['img_w'],self.config['img_h']))
            self.train_images[j, ...] = img

        _len = len(self.valid_annot)
        self.valid_images = np.zeros((_len,
                            self.config['img_h'],
                            self.config['img_w'],
                            self.config['img_c']))
        for j in range(_len):
            img_path = self.train_img_list[j]
            img = cv2.imread(img_path)
            img = cv2.resize(img, (self.config['img_w'],self.config['img_h']))
            self.valid_images[j, ...] = img

    def getTrainBatch(self):
        if self.config['data_mode'] == 'on_memory':
            return self.train_image, self.train_label
        return VOC_TRAIN_BATCH(self)

    def getValidBatch(self):
        if self.config['data_mode'] == 'on_memory':
            return self.valid_images, self.valid_label
        return VOC_VAL_BATCH(self)

    def preprocessData(img):
        #img = img.astype(np.float32) / 255 - 0.5
        return img

    def augment_data(img_batch, y_batch, batch_size):
        img_batch, y_batch = VOC.datagen.flow((img_batch, y_batch), batch_size=batch_size).next()
        return img_batch, y_batch

class VOC_TRAIN_BATCH(Sequence):

    def __init__(self, voc):
        self.config = voc.config
        self.train_label = voc.train_label
        self.train_img_list = voc.train_img_list
        self.shuffle = voc.config['shuffle']
        self.generate_list = list(range(len(self)))
        self.augment_data = 0
        print("[INFO] total %d training images" % len(voc.train_img_list))

    def __len__(self):
        return int((self.train_label.shape[0] / self.config['batch_size']) + 0.5)

    def size(self):
        return self.train_label.shape[0]

    def on_epoch_end(self):
        if self.shuffle: np.random.shuffle(self.generate_list)
        if self.config['do_augment']: self.augment_data = 1

    def __getitem__(self, idx):
        x_batch = np.empty((self.config['batch_size'],
                            self.config['img_h'],
                            self.config['img_w'],
                            self.config['img_c']))
        y_batch = np.empty((self.config['batch_size'],
                            self.config['num_class']))
        idx = self.generate_list[idx]
        idx_base = idx * self.config['batch_size']
        idx_top = idx_base + self.config['batch_size']
        if idx_top > self.size():
            idx_top = self.size()
            size = idx_top - idx_base
            x_batch = x_batch[:size, ...]
            y_batch = y_batch[:size, ...]
        i = 0
        for j in range(idx_base, idx_top):
            img_path = self.train_img_list[j]
            img = cv2.imread(img_path)[:,:,::-1]
            img = cv2.resize(img, (self.config['img_w'], self.config['img_h']))
            x_batch[i, ...] = img
            y_batch[i, ...] = self.train_label[j, ...]
            i += 1
        if self.augment_data:
            x_batch, y_batch = VOC.augment_data(x_batch, y_batch, batch_size=self.config['batch_size'])
        x_batch = VOC.preprocessData(x_batch)
        return x_batch, y_batch

class VOC_VAL_BATCH(Sequence):

    def __init__(self, voc):
        self.config = voc.config
        self.valid_label = voc.valid_label
        self.valid_img_list = voc.valid_img_list
        self.shuffle = voc.config['shuffle']
        self.generate_list = list(range(len(self)))
        print("[INFO] total %d validation images" % len(voc.valid_img_list))

    def __len__(self):
        return int((self.valid_label.shape[0] / self.config['batch_size']) + 0.5)

    def size(self):
        return self.valid_label.shape[0]

    def on_epoch_end(self):
        if self.shuffle: np.random.shuffle(self.generate_list)
        self.augment_data = 1

    def __getitem__(self, idx):
        x_batch = np.empty((self.config['batch_size'],
                            self.config['img_h'],
                            self.config['img_w'],
                            self.config['img_c']))
        y_batch = np.empty((self.config['batch_size'],
                            self.config['num_class']))

        #for idx in self.generate_list:
        idx_base = idx * self.config['batch_size']
        idx_top = idx_base + self.config['batch_size']
        if idx_top > self.size():
            idx_top = self.size()
            size = idx_top - idx_base
            x_batch = x_batch[:size, ...]
            y_batch = y_batch[:size, ...]
        i = 0
        for j in range(idx_base, idx_top):
            img_path = self.valid_img_list[j]
            img = cv2.imread(img_path)[:,:,::-1]
            img = cv2.resize(img, (self.config['img_w'], self.config['img_h']))
            x_batch[i, ...] = img
            y_batch[i, ...] = self.valid_label[j, ...]
            i += 1
        x_batch = VOC.preprocessData(x_batch)
        return x_batch, y_batch
                #yield x_batch, y_batch


import logging
from argparse import ArgumentParser
from typing import Any, Dict, List, Optional, Tuple

from ....arg_parser.utils import str2bool
from ..base_model import GranularBaseModel
from ..loss import LOSS_FACTORY
from ..module import Mlp

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

class MlpPredictor(GranularBaseModel):
    """MlpPredictor - Multi Layer Perceptron predictor."""

    def __init__(
        self,
        name: str,
        from_position: List[int],
        data: Dict[str, str],
        input_size: int,
        hidden_size: int,
        output_size: int,
        n_layers: int,
        activation: str,
        dropout: float,
        loss_function: str,
        class_weights: Optional[List[float]] = None,
        **kwargs,
    ) -> None:
        """Construct MlpPredictor.

        Args:
            name: model name.
            from_position: list of input model positions.
            data: data name mappings.
            input_size: size of the input.
            hidden_size: size of the hidden layers.
            output_size: size of the output.
            n_layers: number of layers.
            activation: name of the activation.
            dropout: dropout rate.
            loss_function: name of the loss function.
            class_weights: weights for the classes. Defaults to None, a.k.a., no weighting.

        Raises:
            ValueError: in case the provided loss function is not supported.
        """
        super().__init__(name=name, data=data)
        self.from_position = from_position
        self.target_key = name + "_" + data["target"]
        self.loss_function_name = loss_function.lower()
        if self.loss_function_name not in LOSS_FACTORY:
            raise ValueError(
                f"loss_function={self.loss_function_name} not supported. Pick a valid one: {sorted(list(LOSS_FACTORY.keys()))}"
            )
        self.loss_function = LOSS_FACTORY[self.loss_function_name]
        self.class_weights = class_weights
        self.mlp = Mlp(
            input_size=input_size,
            hidden_size=hidden_size,
            output_size=output_size,
            n_layers=n_layers,
            activation=activation,
            dropout=dropout,
        )

    def _run_step(self, x: Any, *args, **kwargs) -> Any:
        """Run a step in the model.

        Args:
            x: model input.

        Returns:
            model step output.
        """
        return self.mlp(x)

    def predict(self, x: Any, *args, **kwargs) -> Any:
        """Forward pass in the model.

        Args:
            x: model input.

        Returns:
            model output.
        """
        return self._run_step(x)

    def step(
        self,
        input_data: Any,
        target_data: Any,
        device: str = "cpu",
        current_epoch: int = 0,
        *args,
        **kwargs,
    ) -> Tuple[Any, Any, Any]:
        """Training step for the model.

        Args:
            input_data: input for the step.
            target_data: target for the step.
            device: string representing the device to use. Defaults to "cpu".
            current_epoch: current epoch. Defaults to 0.

        Returns:
            a tuple containing the step output, the loss and the logs for the module.
        """
        output = self._run_step(input_data)
        loss = self.loss_function(output, target_data)
        logs = {f"{self.loss_function_name}_loss": loss, "loss": loss}
        return output, loss, logs

    def val_step(
        self,
        input_data: Any,
        target_data: Any,
        device: str = "cpu",
        current_epoch: int = 0,
        *args,
        **kwargs,
    ) -> Any:
        """Validation step for the model.

        Args:
            input_data: input for the step.
            target_data: target for the step.
            device: string representing the device to use. Defaults to "cpu".
            current_epoch: current epoch. Defaults to 0.

        Returns:
            a tuple containing the step output, the loss and the logs for the module.
        """
        output = self._run_step(input_data)
        loss = self.loss_function(output, target_data)
        logs = {f"{self.loss_function_name}_loss": loss, "loss": loss}

        if self.loss_function_name == "bce":
            output_label = (output > 0.5).float()
            correct_label = (output_label == target_data).float().sum()
            accuracy = correct_label / output_label.shape[0]
            logs["accuracy"] = accuracy
        return output, loss, logs

    @staticmethod
    def add_model_specific_args(
        parent_parser: ArgumentParser, name: str, *args, **kwargs
    ) -> ArgumentParser:
        """Adding to a parser model specific arguments.

        Args:
            parent_parser: patent parser.
            name: model name.

        Returns:
            updated parser.
        """
        parser = ArgumentParser(parents=[parent_parser], add_help=False)

        parser.add_argument(f"--data_path_{name}", type=str)
        parser.add_argument(f"--data_file_{name}", type=str)
        parser.add_argument(f"--dataset_type_{name}", type=str)
        parser.add_argument(f"--target_{name}", type=str)
        parser.add_argument(f"--from_position_{name}", type=int, nargs="+")
        parser.add_argument(f"--checkpoint_path_{name}", type=str)
        parser.add_argument(f"--checkpoint_model_name_{name}", type=str)
        parser.add_argument(f"--start_from_checkpoint_{name}", type=str2bool)
        parser.add_argument(f"--freeze_weights_{name}", type=str2bool)
        parser.add_argument(f"--n_layers_{name}", type=int)
        parser.add_argument(f"--activation_{name}", type=str)
        parser.add_argument(f"--dropout_{name}", type=float)
        parser.add_argument(f"--loss_function_{name}", type=str)
        parser.add_argument(f"--hidden_size_{name}", type=int)
        parser.add_argument(f"--output_size_{name}", type=int)

        return parser


# NOTE: The Canvas class has been developed by Jon Carr (https://github.com/jwcarr/svg-polygons)

import os
import pickle
from sys import argv

class Canvas:

    canvas = ''
    shape_count = 0

    def __init__(self, width=500, height=500):
        self.width = width
        self.height = height

    def polygon(self, shape, border_colour=None, fill_colour=None, opacity=1.0):
        canvas = "\n  <g id='shape%s'>" % self.shape_count
        points = [(str(vertex[0]) + "," + str(vertex[1])) for vertex in shape]
        canvas += "\n    <polygon points='" + (" ".join(points)) + "' style='fill:%s; stroke:%s; fill-opacity:%s; stroke-opacity:%s; stroke-width:3; stroke-linejoin:miter;' />" % (fill_colour, border_colour, opacity, opacity)
        canvas += "\n  </g>\n"
        self.canvas += canvas
        self.shape_count += 1

    def __add_header(self):
        return "<svg xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' version='1.1' width='" + str(self.width) + "' height='" + str(self.height) + "'>\n"

    def __add_canvas(self):
        return self.canvas + "\n"

    def __add_footer(self):
        return "</svg>"

    def save(self, filename='drawing'):
        canvas = self.__add_header()
        canvas += self.__add_canvas()
        canvas += self.__add_footer()
        with open(filename + '.svg', 'w') as f:
            f.write(canvas)
        print("\nImage saved at %s.svg" % filename)

def hex_string(rgb_list):
    return "#%0.2X%0.2X%0.2X" % (rgb_list[0], rgb_list[1], rgb_list[2])

def convert_and_save(dna_path, save_path, prefix=None):
    with open(dna_path, 'rb') as f:
        dna_obj = pickle.load(f)

    width, height, bg_color = dna_obj['width'], dna_obj['height'], dna_obj['bg_color']
    drawing = Canvas(width, height)
    drawing.polygon(shape=[(0, 0), (width-1, 0), (width-1, height-1), (0, height-1)], fill_colour=hex_string(bg_color), opacity=1.0)

    for color, polygon in zip(dna_obj['colors'], dna_obj['polygons']):
        polygon = [(x, y) for (x, y) in zip(polygon[0::2], polygon[1::2])] # [x, y, x, y, ...] -> [(x, y), (x, y), ...]
        drawing.polygon(shape=polygon, fill_colour=hex_string(color), opacity=color[3] / 255)

    if not prefix: prefix = os.path.splitext(os.path.basename(os.path.normpath(dna_path)))[0]
    drawing.save(filename=os.path.join(save_path, prefix))

try:
    dna_path = argv[1]
    save_path = argv[2]
    prefix = None if len(argv) <= 3 else argv[3]
    convert_and_save(dna_path, save_path, prefix)
except:
    print("usage: python converter.py dna_path save_path [prefix]")

# you can directly convert it, as for example:
# convert_and_save(os.path.join("generated", "dna", "dna_ml_400000.pkl"), os.path.join("generated", "vector"))


class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        answer = set()
        sorted_nums = sorted(nums)
        for i in range(0, len(sorted_nums) - 2):
            from_num_idx = i + 1
            to_num_idx = len(sorted_nums) - 1

            while from_num_idx < to_num_idx:
                target_value = sorted_nums[i]
                first_value = sorted_nums[from_num_idx]
                second_value = sorted_nums[to_num_idx]

                if target_value + first_value + second_value < 0:
                    from_num_idx += 1
                elif target_value + first_value + second_value > 0:
                    to_num_idx -= 1
                else:
                    target_answer = (target_value, first_value, second_value)
                    answer.add(target_answer)
                    from_num_idx += 1
                    to_num_idx -= 1

        return [ list(tup) for tup in answer ][::-1]


import errno
import socket

listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(('127.0.0.1', 0))
listener.listen(1)
client = socket.create_connection(listener.getsockname())
server, _ = listener.accept()
client.setblocking(False)  # make non-blocking

try:
    while True:
        client.sendall(b'*'*1024)
except socket.error as e:
    # Instead of pausing the process sendall raises BlockingIOError
    assert e.errno == errno.EAGAIN  # OS reports: stop writing

server.setblocking(False)
try:
    while True:
        print(server.send(b'*'*1024))
except socket.error as e:
    # Send buffer is full
    print('terminated with EAGAIN', e.errno)


from bot.serverconfig import ServerConfig

COLUMN_SERVER_ID = "server_id"
COLUMN_EVENT_CHANNEL_ID = "event_channel_id"

class ServerConfigProxy(object):
    table = "serverconfig"

    db_mapping = [
        COLUMN_SERVER_ID,
        COLUMN_EVENT_CHANNEL_ID
    ]

    @staticmethod
    def create_server_config_statement(config: ServerConfig):
        columns = ",".join(ServerConfigProxy.db_mapping)
        values = ",".join(f"%({attr})s" for attr in ServerConfigProxy.db_mapping)
        sql = f"INSERT INTO {ServerConfigProxy.table}({columns}) VALUES({values});"
        data = {a: getattr(config, a) for a in ServerConfigProxy.db_mapping}

        return sql, data

    @staticmethod
    def get_server_config_statement(server_id):
        sql = f"SELECT * from {ServerConfigProxy.table} where {COLUMN_SERVER_ID} = %s"
        data = (str(server_id),)

        return sql, data

    @staticmethod
    def update_server_config_statement(config: ServerConfig):
        columns = ",".join(ServerConfigProxy.db_mapping)
        values = ",".join(f"%({attr})s" for attr in ServerConfigProxy.db_mapping)
        sql = f"UPDATE {ServerConfigProxy.table} set ({columns}) = ({values}) where {COLUMN_SERVER_ID} = " \
              f"%({COLUMN_SERVER_ID})s"
        data = {a: getattr(config, a) for a in ServerConfigProxy.db_mapping}

        return sql, data

    @staticmethod
    def delete_server_config_statement(server_id):
        sql = f"DELETE from {ServerConfigProxy.table} where {COLUMN_SERVER_ID} = %s"
        data = (str(server_id),)

        return sql, data

    @staticmethod
    def create_server_config_from_record(record):
        config = ServerConfig()
        for index, value in enumerate(ServerConfigProxy.db_mapping):
            setattr(config, value, record[index])
        return config


import matplotlib.pyplot as pit
import matplotlib.animation as animation
import threading
import numpy as np
import serial

#from mpl_toolkits.mplot3d import Axes3D

serialData = []
serialData.append([0.0])
serialData.append([0.0])

def optenerdatos(out_dato):
    with serial.Serial("COM3", 9600) as arduino:
        while True:
            val = arduino.readline().decode('ascii')
            try:
                out_dato[1].append(float(val))
                if len(out_dato[1]) > 200:
                    out_dato[1].pop(0)
                    print(out_dato[1])
            except:
                pass

dataColector = threading.Thread(target = optenerdatos, args = (serialData,))
dataColector.start()

def actualizar(num, hl, data):
    dx = np.array(range(len(data[1])))
    dy = np.array(data[1])
    hl.set_data(dx, dy)
    return hl,

fig = pit.figure()
hl, = pit.plot(serialData[0], serialData[1])
pit.ylim(-7, 7)
pit.xlim(0, 200)

line_ani = animation.FuncAnimation(fig, actualizar, fargs=(hl, serialData), interval = 50, blit= False)

pit.show()
dataColector.join()


"""
The REST interface for ERP distribution center resources.
"""
import server.services.distribution_centers as distribution_center_service
import server.services.shipments as shipment_service
from flask import g, request, Response, Blueprint
from server.web.utils import logged_in, check_null_input

distribution_centers_v1_blueprint = Blueprint('distribution_centers_v1_api', __name__)

@distribution_centers_v1_blueprint.route('/distribution-centers', methods=['GET'])
@logged_in
def get_distribution_centers():
    """
    Get all distribution center objects.

    :return: [{
        "id": "D2",
        "address": {Address},
        "contact": {Contact}
    }, {...}]

    """

    distribution_centers = distribution_center_service.get_distribution_centers(token=g.auth['loopback_token'])
    return Response(distribution_centers,
                    status=200,
                    mimetype='application/json')

@distribution_centers_v1_blueprint.route('/distribution-centers/<string:dc_id>', methods=['GET'])
@logged_in
def get_distribution_center(dc_id):
    """
    Retrieve a single distribution center object.

    :param dc_id:   The distribution center's id

    :return: {
        "id": "D2",
        "address": {Address},
        "contact": {Contact}
    }

    """
    check_null_input((dc_id, 'distribution center to retrieve'))

    distribution_center = distribution_center_service.get_distribution_center(token=g.auth['loopback_token'],
                                                                              dc_id=dc_id)
    return Response(distribution_center,
                    status=200,
                    mimetype='application/json')

@distribution_centers_v1_blueprint.route('/distribution-centers/<string:dc_id>/shipments', methods=['GET'])
@logged_in
def get_distribution_centers_shipments(dc_id):
    """
    Retrieve all shipments originating from the specified distribution center.

    :param dc_id:   The distribution center's id

    :return: [{
        "id": "123",
        "status": "SHIPPED",
        "createdAt": "2015-11-05T22:00:51.692765",
        "updatedAt": "2015-11-08T22:00:51.692765",
        "deliveredAt": "2015-11-08T22:00:51.692765",
        "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
        "currentLocation": {Address},
        "fromId": "123",
        "toId:": "123"
    }, {...}]

    """
    check_null_input((dc_id, 'distribution center whose shipments you want to retrieve'))
    status = request.args.get('status')

    shipments = shipment_service.get_shipments(token=g.auth['loopback_token'],
                                               dc_id=dc_id,
                                               status=status)
    return Response(shipments,
                    status=200,
                    mimetype='application/json')

@distribution_centers_v1_blueprint.route('/distribution-centers/<string:dc_id>/inventory', methods=['GET'])
@logged_in
def get_distribution_center_inventory(dc_id):
    """
    Retrieve all inventory at the specified distribution center.

    :param dc_id:   The distribution center's id

    :return: [{
        "id": "123",
        "quantity": 10,
        "productId": "123",
        "locationId": "123",
        "locationType": "DistributionCenter"
    }, {...}]
    """
    check_null_input((dc_id, 'distribution center whose inventory you want to retrieve'))

    inventory = distribution_center_service.get_distribution_center_inventory(token=g.auth['loopback_token'],
                                                                              dc_id=dc_id)
    return Response(inventory,
                    status=200,
                    mimetype='application/json')


from Bio.Blast import NCBIWWW
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna

# read nucleotides
handle = open("myseqs.fna", "rU")
records = list(SeqIO.parse(handle, "fasta"))
handle.close()

# translate nucleotides to proteins
for i in range(0,len(records)):
    records[i].seq = records[i].seq.translate()

# define output file
save_file = open("biopython_blast.xml", "w")

# blast over the internet
for record in records:
    result_handle = NCBIWWW.qblast("blastp", "swissprot", record, expect=0.00001, format_type='XML', hitlist_size=5)
    save_file.write(result_handle.read())
    result_handle.close()

save_file.close()


from PyQt5.QtWidgets import *
from GUI.Report import Ui_Report

from FAE.FeatureAnalysis.Classifier import *
from FAE.FeatureAnalysis.FeaturePipeline import FeatureAnalysisPipelines, OnePipeline
from FAE.Report.Report import Report

from FAE.Visualization.DrawROCList import DrawROCList
from FAE.Visualization.PlotMetricVsFeatureNumber import DrawCurve, DrawBar
import os

class ReportConnection(QWidget, Ui_Report):
    def __init__(self, parent=None):
        self._root_folder = ''
        self._fae = FeatureAnalysisPipelines()
        self._training_data_container = DataContainer()
        self._testing_data_container = DataContainer()
        self._current_pipeline = OnePipeline()

        super(ReportConnection, self).__init__(parent)
        self.setupUi(self)

        self.buttonLoadTrainingData.clicked.connect(self.LoadTrainingData)
        self.buttonClearTrainingData.clicked.connect(self.ClearTrainingData)
        self.buttonLoadTestingData.clicked.connect(self.LoadTestingData)
        self.buttonClearTestingData.clicked.connect(self.ClearTestingData)

        self.buttonLoadResult.clicked.connect(self.LoadAll)
        self.buttonClearResult.clicked.connect(self.ClearAll)

        self.buttonGenerate.clicked.connect(self.Generate)

        self.__plt_roc = self.canvasROC.getFigure().add_subplot(111)

        # Update ROC canvas
        self.comboNormalizer.currentIndexChanged.connect(self.UpdateROC)
        self.comboDimensionReduction.currentIndexChanged.connect(self.UpdateROC)
        self.comboFeatureSelector.currentIndexChanged.connect(self.UpdateROC)
        self.comboClassifier.currentIndexChanged.connect(self.UpdateROC)
        self.spinBoxFeatureNumber.valueChanged.connect(self.UpdateROC)
        self.checkROCTrain.stateChanged.connect(self.UpdateROC)
        self.checkROCValidation.stateChanged.connect(self.UpdateROC)
        self.checkROCTest.stateChanged.connect(self.UpdateROC)

        self.SetPipelineStateButton(False)

    def Generate(self):
        if self._training_data_container.IsEmpty():
            QMessageBox.about(self, '', 'Load training data at least')
            return

        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.DirectoryOnly)
        dlg.setOption(QFileDialog.ShowDirsOnly)

        if dlg.exec_():
            store_folder = dlg.selectedFiles()[0]
            roc_path = os.path.join(store_folder, 'ROC.jpg')
            self.canvasROC.getFigure().savefig(roc_path, dpi=300)

            report = Report()
            try:
                report.Run(self._training_data_container, self._current_pipeline, self._root_folder, store_folder, self._testing_data_container)
                os.system("explorer.exe {:s}".format(os.path.normpath(store_folder)))
            except Exception as ex:
                QMessageBox.about(self, 'Report Generate Error: ', ex.__str__())
                self.logger.log('Report Generate Error:  ' + str(ex))

    def LoadTrainingData(self):
        dlg = QFileDialog()
        file_name, _ = dlg.getOpenFileName(self, 'Open SCV file', directory=r'C:\MyCode\FAE\Example', filter="csv files (*.csv)")
        try:
            self._training_data_container.Load(file_name)
            # self.SetStateButtonBeforeLoading(True)
            self.lineEditTrainingData.setText(file_name)
            self.UpdateDataDescription()
        except Exception as ex:
            QMessageBox.about(self, "Load Error", ex.__str__())
            self.logger.log('Open SCV file Error, The reason is ' + str(ex))
        except ValueError:
            self.logger.error('Open SCV file ' + file_name + ' Failed. because of value error.')
            QMessageBox.information(self, 'Error',
                                    'The selected training data mismatch.')

    def ClearTrainingData(self):
        self._training_data_container = DataContainer()
        # self.SetStateButtonBeforeLoading(False)
        self.lineEditTrainingData.setText("")
        self.UpdateDataDescription()

    def LoadTestingData(self):
        dlg = QFileDialog()
        file_name, _ = dlg.getOpenFileName(self, 'Open SCV file', filter="csv files (*.csv)")
        try:
            self._testing_data_container.Load(file_name)
            self.lineEditTestingData.setText(file_name)
            self.UpdateDataDescription()
        except Exception as ex:
            QMessageBox.about(self, "Load Error", ex.__str__())
            self.logger.log('Open SCV file Error, The reason is ' + str(ex))
        except ValueError:
            self.logger.error('Open SCV file ' + file_name + ' Failed. because of value error.')
            QMessageBox.information(self, 'Error',
                                    'The selected testing data mismatch.')

    def ClearTestingData(self):
        self._testing_data_container = DataContainer()
        self.lineEditTestingData.setText("")
        self.UpdateDataDescription()

    def UpdateDataDescription(self):
        show_text = ''
        if not self._training_data_container.IsEmpty():
            show_text += "The number of training cases: {:d}\n".format(len(self._training_data_container.GetCaseName()))
            show_text += "The number of training features: {:d}\n".format(len(self._training_data_container.GetFeatureName()))
            if len(np.unique(self._training_data_container.GetLabel())) == 2:
                positive_number = len(
                    np.where(self._training_data_container.GetLabel() == np.max(self._training_data_container.GetLabel()))[0])
                negative_number = len(self._training_data_container.GetLabel()) - positive_number
                assert (positive_number + negative_number == len(self._training_data_container.GetLabel()))
                show_text += "The number of training positive samples: {:d}\n".format(positive_number)
                show_text += "The number of training negative samples: {:d}\n".format(negative_number)

        show_text += '\n'
        if not self._testing_data_container.IsEmpty():
            show_text += "The number of testing cases: {:d}\n".format(len(self._testing_data_container.GetCaseName()))
            show_text += "The number of testing features: {:d}\n".format(
                len(self._testing_data_container.GetFeatureName()))
            if len(np.unique(self._testing_data_container.GetLabel())) == 2:
                positive_number = len(
                    np.where(
                        self._testing_data_container.GetLabel() == np.max(self._testing_data_container.GetLabel()))[0])
                negative_number = len(self._testing_data_container.GetLabel()) - positive_number
                assert (positive_number + negative_number == len(self._testing_data_container.GetLabel()))
                show_text += "The number of testing positive samples: {:d}\n".format(positive_number)
                show_text += "The number of testing negative samples: {:d}\n".format(negative_number)

        self.textEditDataDescription.setText(show_text)

    def LoadAll(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.DirectoryOnly)
        dlg.setOption(QFileDialog.ShowDirsOnly)

        if dlg.exec_():
            self._root_folder = dlg.selectedFiles()[0]

            if not os.path.exists(self._root_folder):
                return
            if not r'.FAEresult4129074093819729087' in os.listdir(self._root_folder):
                QMessageBox.about(self, 'Load Error', 'This folder is not supported for import')
                return
            try:
                self.lineEditResultPath.setText(self._root_folder)
                self._fae.LoadAll(self._root_folder)
                self.SetResultDescription()
                self.InitialUi()
            except Exception as ex:
                QMessageBox.about(self, "Load Error", ex.__str__())
                self.logger.log('Load Error, The reason is ' + str(ex))
                self.ClearAll()
                return

            self.SetPipelineStateButton(True)

    def ClearAll(self):
        self.buttonLoadResult.setEnabled(True)
        self.buttonClearResult.setEnabled(False)

        self._fae = FeatureAnalysisPipelines()
        self.textEditDescription.setPlainText('')
        self.lineEditResultPath.setText('')
        self.InitialUi()

        self.checkROCTrain.setChecked(False)
        self.checkROCValidation.setChecked(False)
        self.checkROCTest.setChecked(False)

        self.spinBoxFeatureNumber.setValue(1)

        self.canvasROC.getFigure().clear()
        self.canvasROC.draw()

        self.SetPipelineStateButton(False)

    def SetPipelineStateButton(self, state):
        self.checkROCTrain.setEnabled(state)
        self.checkROCValidation.setEnabled(state)
        self.checkROCTest.setEnabled(state)

        self.comboNormalizer.setEnabled(state)
        self.comboDimensionReduction.setEnabled(state)
        self.comboFeatureSelector.setEnabled(state)
        self.comboClassifier.setEnabled(state)
        self.spinBoxFeatureNumber.setEnabled(state)

        self.buttonClearResult.setEnabled(state)
        self.buttonLoadResult.setEnabled(not state)

        self.buttonGenerate.setEnabled(state)

    def InitialUi(self):
        # Update ROC canvers
        self.comboNormalizer.clear()
        for normalizer in self._fae.GetNormalizerList():
            self.comboNormalizer.addItem(normalizer.GetName())
        self.comboDimensionReduction.clear()
        for dimension_reduction in self._fae.GetDimensionReductionList():
            self.comboDimensionReduction.addItem(dimension_reduction.GetName())
        self.comboClassifier.clear()
        for classifier in self._fae.GetClassifierList():
            self.comboClassifier.addItem(classifier.GetName())
        self.comboFeatureSelector.clear()
        for feature_selector in self._fae.GetFeatureSelectorList():
            self.comboFeatureSelector.addItem(feature_selector.GetName())

        if self._fae.GetFeatureNumberList() != []:
            self.spinBoxFeatureNumber.setMinimum(int(self._fae.GetFeatureNumberList()[0]))
            self.spinBoxFeatureNumber.setMaximum(int(self._fae.GetFeatureNumberList()[-1]))

    def SetResultDescription(self):
        text = "Normalizer:\n"
        for index in self._fae.GetNormalizerList():
            text += (index.GetName() + '\n')
        text += '\n'

        text += "Dimension Reduction:\n"
        for index in self._fae.GetDimensionReductionList():
            text += (index.GetName() + '\n')
        text += '\n'

        text += "Feature Selector:\n"
        for index in self._fae.GetFeatureSelectorList():
            text += (index.GetName() + '\n')
        text += '\n'

        text += "Feature Number:\n"
        text += "{:s} - {:s}\n".format(self._fae.GetFeatureNumberList()[0], self._fae.GetFeatureNumberList()[-1])
        text += '\n'

        text += "Classifier:\n"
        for index in self._fae.GetClassifierList():
            text += (index.GetName() + '\n')
        text += '\n'

        self.textEditDescription.setPlainText(text)

    def UpdateROC(self):
        if (self.comboNormalizer.count() == 0) or \
                (self.comboDimensionReduction.count() == 0) or \
                (self.comboFeatureSelector.count() == 0) or \
                (self.comboClassifier.count() == 0) or \
                (self.spinBoxFeatureNumber.value() == 0):
            return

        case_name = self.comboNormalizer.currentText() + '_' + \
                    self.comboDimensionReduction.currentText() + '_' + \
                    self.comboFeatureSelector.currentText() + '_' + \
                    str(self.spinBoxFeatureNumber.value()) + '_' + \
                    self.comboClassifier.currentText()

        case_folder = os.path.join(self._root_folder, case_name)
        try:
            self._current_pipeline.LoadPipeline(os.path.join(case_folder, 'pipeline_info.csv'))
        except Exception as ex:
            QMessageBox.about(self, "Load Error", ex.__str__())
            self.logger.log('Load Pipeline Error, The reason is ' + str(ex))

        pred_list, label_list, name_list = [], [], []
        if self.checkROCTrain.isChecked():
            train_pred = np.load(os.path.join(case_folder, 'train_predict.npy'))
            train_label = np.load(os.path.join(case_folder, 'train_label.npy'))
            pred_list.append(train_pred)
            label_list.append(train_label)
            name_list.append('train')
        if self.checkROCValidation.isChecked():
            val_pred = np.load(os.path.join(case_folder, 'val_predict.npy'))
            val_label = np.load(os.path.join(case_folder, 'val_label.npy'))
            pred_list.append(val_pred)
            label_list.append(val_label)
            name_list.append('validation')
        if self.checkROCTest.isChecked():
            if os.path.exists(os.path.join(case_folder, 'test_label.npy')):
                test_pred = np.load(os.path.join(case_folder, 'test_predict.npy'))
                test_label = np.load(os.path.join(case_folder, 'test_label.npy'))
                pred_list.append(test_pred)
                label_list.append(test_label)
                name_list.append('Test')

        if len(pred_list) > 0:
            DrawROCList(pred_list, label_list, name_list=name_list, is_show=False, fig=self.canvasROC.getFigure())

        self.canvasROC.draw()


#!/usr/bin/python2
#-*- coding:utf-8 -*-
# 윗줄은 shebang line 이 프로그램이 실행될 파이썬 인터프리터를 가리킴
# env 세팅 혹은 venv을 이용하면 한기기 여러환경에서 여러 인터프리터를 사용 가능할듯
# 파이썬 2 쓰도록 바꾸고 인코딩 utf-8로 변경

import rospy    # 파이썬 기반
from std_msgs.msg import Int32

rospy.init_node('topic_publisher')

pub = rospy.Publisher('counter', Int32)

rate = rospy.Rate(2)

count = 0

while not rospy.is_shutdown():
    pub.publish(count)
    count += 1
    rate.sleep()

# 디렉터리 수정


import pandas as pd
import os
import matplotlib.pyplot as plt
import numpy as np

N_HOURS = 4

df = pd.read_csv(r'C:\Users\LUCA SANDRI\Desktop\Tesi\07_Risultati\FF_genopt_SUBDAILY.csv')
print(len(df))

df.columns = ['Date/Time', 'Outdoor Temp', 'Diffuse Rad', 'Direct Rad', 'Occupants',
       'EC state', 'nhrs_occ', 'nhrs_sim',
        'UDI_f', 'UDI_s', 'UDI_a', 'UDI_e',                                 #a autonomous --> Only solar radiation,  e excess,   f fell short,   s supplementary --> lighting required  a+s= USEFULL
        'DGPoutputcost', 'DGPoutputcostocc', 'DGPcost', # ???
       'ILLoutput', 'Ep heat', 'Ep cool', 'Ep light', #ILLoutput
       'Termination', 'Warmup',
       'Primary energy', 'PV energy opt',
        'DayOfWeek', 'TimeOfDay', 'Zone Mean Air Temperature']
outdoor = df['Outdoor Temp']
radiation = df['Diffuse Rad'] + df['Direct Rad']

total_steps = len(df.index)
forecast_rad = []
forecast_temp = []
for k in list(range(total_steps)):
    T_FORE = outdoor[k + 1:k + 1 + N_HOURS].sum()
    forecast_temp.append(T_FORE)
    I_FORE = radiation[k + 1:k + 1 + N_HOURS].sum()
    forecast_rad.append(I_FORE)

weather = pd.DataFrame({'Outdoor Temp':outdoor,'Forecast Temp':forecast_temp,
                        'Radiation':radiation,'Forecast Rad':forecast_rad})
print(weather[8340:])

path=r'C:\Users\LUCA SANDRI\PycharmProjects\THMcontrol\Utility'
weather.to_csv(os.path.join(path,r'weather.csv'),header=True, encoding = 'utf8', index=False)

forecast_rad = weather['Forecast Rad']
forecast_temp = weather['Forecast Temp']
data = np.array(forecast_temp)
T_33 = np.nanpercentile(data, 33)
T_66 = np.nanpercentile(data, 66)
data = np.array(forecast_rad[forecast_rad>0])
I_33 = np.nanpercentile(data, 33)
I_66 = np.nanpercentile(data, 66)
max_temp = forecast_temp.max()
min_temp = forecast_temp.min()
max_rad = forecast_rad.max()
min_rad = forecast_rad.min()
print('Temperature: min = {}, 33 p = {}, 66 p = {}, max = {}'.format(min_temp, T_33, T_66, max_temp))
print('Radiation: min = {}, 33 p = {}, 66 p = {}, max = {}'.format(min_rad, I_33, I_66, max_rad))

plt.close()

constant_x = [0, len(forecast_temp)]
max_fore = max_temp
min_fore = min_temp
fig1, ax1 = plt.subplots()
ax1.set_xlabel("Time step [hours]", size=24)
ax1.set_ylabel("Cumulative temperature of the next {} steps [°C]".format(N_HOURS), size=24)
ax1.set_title("Temperature forecast set", size=24)
ax1.tick_params(labelsize=15)
ax1.scatter(forecast_temp.index,forecast_temp,s=1)
ax1.plot(constant_x, [max_fore, max_fore], color='red', label = "Max")
ax1.plot(constant_x, [min_fore,min_fore], color='red', label = "Min")
ax1.plot(constant_x, [T_33,T_33], color='blue', label = "33 percentile")
ax1.plot(constant_x, [T_66,T_66], color='blue', label = "66 percentile")
plt.legend(loc=1, fontsize=15)

#label = "curve 2", linestyle=":"

constant_x = [0, len(forecast_rad)]
max_fore = max_rad
min_fore = min_rad
fig2, ax2 = plt.subplots()
ax2.set_xlabel("Time step [hours]", size=24)
ax2.set_ylabel("Total radiation of the next {} steps [W]".format(N_HOURS), size=24)
ax2.set_title("Radiation forecast set", size=24)
ax2.tick_params(labelsize=15)
ax2.scatter(forecast_rad.index,forecast_rad,s=1)
ax2.plot(constant_x, [max_fore,max_fore], color='red', label = "Max")
ax2.plot(constant_x, [min_fore,min_fore], color='red', label = "Min")
ax2.plot(constant_x, [I_33,I_33], color='blue', label = "33 percentile")
ax2.plot(constant_x, [I_66,I_66], color='blue', label = "66 percentile")
plt.legend(loc=1, fontsize=15)
plt.yscale('log')

#OPTIMUM MONTHLY INDOOR OPERATIVE TEMPERATURE
df['Month'] = 0                                             #Create Month column
df['DayOfYear'] = 0                                        #Create Day Of the Year column
for i in df.index:
    df.loc[i, 'DayOfYear'] = df['Date/Time'].iloc[i].split()[0]
    df.loc[i,'Month'] = int(df.loc[i, 'DayOfYear'].split('/')[0])
month_list = list(df.Month.unique())
optimum_temp = []
for i in month_list:
    copy_df = df[df['Month']==i]
    mean_temp = copy_df['Outdoor Temp'].mean()
    optimum_temp.append(0.31 * mean_temp + 17.8)
opt_mon_temp = pd.DataFrame({'Month':month_list,'Optimum temperature':optimum_temp})
print(opt_mon_temp)

comparison = df[['Month','Outdoor Temp']]
comparison['Opt temp'] = 0
for i in month_list:
    opt_temp = opt_mon_temp.loc[opt_mon_temp['Month'] == i,
                                'Optimum temperature'].iloc[0]
    comparison.loc[comparison['Month'] == i, 'Opt temp'] = opt_temp

monthly_limit_temp = comparison['Opt temp'] + 2.5

daily_limit_temp = 0.31 * df['Outdoor Temp'] + 17.8 + 2.5

path=r'C:\Users\LUCA SANDRI\PycharmProjects\THMcontrol\Utility'
monthly_limit_temp.to_csv(os.path.join(path,r'monthly_limit_temp.csv'),header=True, encoding = 'utf8', index=False)
daily_limit_temp.to_csv(os.path.join(path,r'daily_limit_temp.csv'),header=True, encoding = 'utf8', index=False)
print(monthly_limit_temp)

fig, ax = plt.subplots()
ax.scatter(comparison.index, comparison['Opt temp'], s=20, c='green')
ax.scatter(monthly_limit_temp.index, monthly_limit_temp, s=20, c='red')
df['Outdoor Temp'].plot()
plt.show()


from classes.Floor import Floor
from classes.Ticket import Ticket
from models.VehicleFactory import VehicleFactory

class ParkingLot:
    def __init__(self, parking_lot_id, number_of_floors, number_of_slots_per_floor):
        '''
        {
            0: {},
            1: {},
            2: {}
        }
        '''
        self.parking_lot_id = parking_lot_id
        self.floors = []
        self.number_of_floors = number_of_floors
        self.number_of_slots_per_floor = number_of_slots_per_floor
        self.tickets = {}
        self.create_parking_lot()

    def create_parking_lot(self):
        for i in range(0, self.number_of_floors):
            self.add_floor()

        print(f'Created parking lot with {self.number_of_floors} floors and {self.number_of_slots_per_floor} slots per floor')

    def add_floor(self):
        floor = Floor(self.number_of_slots_per_floor, len(self.floors))
        self.floors.append(floor)

    def park_vehicle(self, vehicle_type, registration_no, color):
        vehicle = VehicleFactory().get_vehicle(vehicle_type, registration_no, color)
        # print('park vehicle: ', vehicle)

        for floor in self.floors:
            for slot in floor.get_free_slots(vehicle_type):
                if slot.get_allowed_vehicle_type() == vehicle_type:
                    floor.park_vehicle_to_slot(slot, vehicle)
                    slot_id = slot.get_slot_id()
                    floor_id = floor.get_floor_id()
                    ticket_id = Ticket(self.parking_lot_id, floor_id, slot_id).get_ticket_id()
                    if ticket_id in self.tickets:
                        print('Duplicate ticket id')
                        return
                    self.tickets[ticket_id] = { 'vehicle': vehicle, 'slot_id': slot, 'floor_id': floor }
                    print(f'Parked vehicle. Ticket ID: {ticket_id}')
                    return

        print('\nParking Lot Full')

    def unpark_vehicle(self, ticket_id):
        if ticket_id not in self.tickets:
            print('\nInvalid Ticket')
            return None
        vehicle_detail = self.tickets[ticket_id]
        vehicle = vehicle_detail['vehicle']
        slot = vehicle_detail['slot_id']
        floor = vehicle_detail['floor_id']
        floor.unpark_vehicle_from_slot(slot)
        del self.tickets[ticket_id]
        print(f'Unparked vehicle with Registration Number: {vehicle.get_registration_no()} and Color: {vehicle.get_vehicle_color()}')

    def get_number_of_free_slots_per_floor(self, vehicle_type):
        for floor in self.floors:
            free_slots = floor.get_free_slots(vehicle_type)
            print(f'No. of free slots for {vehicle_type} on Floor {floor.get_floor_id()}: {len(free_slots)}')

    def get_free_slots_per_floor(self, vehicle_type):
        for floor in self.floors:
            free_slots = floor.get_free_slots(vehicle_type)
            comma_separated_values_of_slot_nos = ""
            for slot in free_slots:
                comma_separated_values_of_slot_nos += str(slot.get_slot_id()) + ", "
            print(f'Free slots for {vehicle_type} on Floor {floor.get_floor_id()}: {comma_separated_values_of_slot_nos}')

    def get_occupied_slots(self, vehicle_type):
        for floor in self.floors:
            free_slots = floor.get_occupied_slots(vehicle_type)
            comma_separated_values_of_slot_nos = ""
            for slot in free_slots:
                comma_separated_values_of_slot_nos += str(slot.get_slot_id()) + ", "
            print(f'Occupied slots for f{vehicle_type} on Floor {floor.get_floor_id()}: {comma_separated_values_of_slot_nos}')


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        stack = []
        this_node = root
        while this_node:
            if this_node.right:
                stack.append(this_node.right)
            if this_node.left:
                stack.append(this_node.left)
            this_node.left = None
            next_node = stack.pop() if stack else None
            this_node.right = next_node
            this_node = next_node


import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer
from string import punctuation
import nltk
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
import pickle
from sklearn.externals import joblib
import os

#stop word for cleaning pitches that were input by users
stopwords = stopwords.words( 'english' ) + list(punctuation)
stemmer = PorterStemmer()

def run_model(input_pitch, input_amount, input_exchange, input_gender, input_category):
    #Define veriables from page POST method
    dealloc = "Deal_Status_model.pkl"
    dealvoc = "Deal_Status_vocab.pkl"
    sharkloc = "Deal_Shark 1_model.pkl"
    sharkvoc = "Deal_Shark 1_vocab.pkl"
    path = os.path.join("Shark_Data","static","py",dealloc)
    vocpath = os.path.join("Shark_Data","static","py",dealvoc)
    sharkpath = os.path.join("Shark_Data","static","py",sharkloc)
    sharkvocpath = os.path.join("Shark_Data","static","py",sharkvoc)

    #Load the trained models
    #This model predicts whether a deal would be made or not
    deal_model = joblib.load(path)

    #This model predicts who would make the deal
    shark_model = joblib.load(sharkpath)

    #Deal Model
    #Creates the vector for the pitch word input
    transformer = TfidfTransformer()
    loaded_vectorizer = TfidfVectorizer(decode_error="replace",vocabulary=pickle.load(open(vocpath, "rb")))
    tfidf = transformer.fit_transform(loaded_vectorizer.fit_transform(np.array(input_pitch)))
    input_df = pd.DataFrame(tfidf.toarray(), columns=loaded_vectorizer.get_feature_names())

    #Adds the numerical and catagorical factors to the table
    input_df.loc[0,"Amount_Asked_For"] = input_amount
    input_df.loc[0,"Exchange_For_Stake"] = input_exchange
    input_df.loc[0,f"Gender_{input_gender}"] = 1
    input_df.loc[0,f"Category_{input_category}"] = 1

    #If the model predicts 1, then a deal has been made, 0 no deal
    dealprediction = deal_model.predict(input_df)

    #If a deal has been made, run the second model to predict who might pick it up
    if (dealprediction[0] == 1):

        #Shark Model
        transformer = TfidfTransformer()
        loaded_vectorizer = TfidfVectorizer(decode_error="replace",vocabulary=pickle.load(open(sharkvocpath, "rb")))
        tfidf = transformer.fit_transform(loaded_vectorizer.fit_transform(np.array(input_pitch)))
        input_df_shark = pd.DataFrame(tfidf.toarray(), columns=loaded_vectorizer.get_feature_names())

        input_df_shark.loc[0,"Amount_Asked_For"] = input_amount
        input_df_shark.loc[0,"Exchange_For_Stake"] = input_exchange
        input_df_shark.loc[0,f"Gender_{input_gender}"] = 1
        input_df_shark.loc[0,f"Category_{input_category}"] = 1

        sharkprediction = shark_model.predict(input_df_shark)

        #Returns the deal status and the deal shark
        return dealprediction[0], sharkprediction

    else:
        #Returns just the deal status
        return dealprediction[0], np.nan


# The downloaded JGI files are structured according to the taxonomy
# This code puts all species GFF and fasta files into two separate folders
# Input are the downloaded JGI files in taxonomy order
# Output are two folders containing the GFF and fasta files

# Import packages
import os
import shutil

# Define the new folders
new_assembly_path = '/home/i.huitink_cbs-niob.local/h/data/copy_jgi/classes/assemblies'
new_gff_path = '/home/i.huitink_cbs-niob.local/h/data/copy_jgi/classes/gffs'

# Get current working directory
dir = os.getcwd()

folders_to_remove = []

# Loop over downloaded JGI data
for root, dirs, files in os.walk(dir):
    # The new GFF and fasta folder need to be skipped
    if root != '/home/i.huitink_cbs-niob.local/h/data/copy_jgi/classes/gffs' and root != '/home/i.huitink_cbs-niob.local/h/data/copy_jgi/classes/assemblies':
        for file in files:
            if file.endswith('gff.gz') or file.endswith('gff3.gz'):
                old_assembly_path = os.path.join(root, root, file)
                shutil.move(old_assembly_path, new_gff_path)
            elif file.endswith('fasta.gz'):
                old_gff_path = os.path.join(root, root, file)
                shutil.move(old_gff_path, new_assembly_path)
            else:
                print('Other end: ', file)