import os
import datetime
import shutil

nume_videoclipuri = os.listdir()
inceput_facultate = datetime.datetime.strptime('2021-2-8','%Y-%m-%d')
path = os.path.dirname(os.path.abspath(__file__))

def check_para_impara(ziua):
    if (int(str((ziua - inceput_facultate)/7).split(" ")[0])+1)%2==1:
        return False
        # print("saptamana impara")
    else:
        # print("saptamana para")
        return True

def ordonare():
    orar = open("Orar.txt", "r")
    linii  = orar.readlines()
    for x in nume_videoclipuri:
        if ".mp4" in x:
            data_fisier = x.split(' ')[0]
            ora_fisier = int(x.split(' ')[1].split('.')[0].split('-')[0])
            minut_fisier = int(x.split(' ')[1].split('.')[0].split('-')[1])
            timp_fisier = datetime.datetime.strptime(data_fisier, '%Y-%m-%d').strftime('%A')
            zi_fisier = datetime.datetime.strptime(data_fisier, '%Y-%m-%d')
            print(timp_fisier, ' - ' ,ora_fisier,':',minut_fisier)
            for linie in linii:
                ore_curs = linie.split("(")[1].split("-")
                for ora_curs in ore_curs:
                    if linie.split("(")[0] in timp_fisier:
                        if ((int(ora_curs.split("_")[1].split(":")[0])-1==ora_fisier and minut_fisier>=50 and minut_fisier<=59) or (int(ora_curs.split("_")[1].split(":")[0])==ora_fisier and minut_fisier>=0 and minut_fisier<=29)):
                            if ora_curs.split("_")[0]=="M":
                                shutil.move('{}'.format(x),'{}/{}/{}'.format(path, ora_curs.split("_")[2],x))
                                print("{} mutat in {}".format(ora_curs.split("_")[2],x))
                            elif ora_curs.split("_")[0]=="P":
                                if check_para_impara(zi_fisier) == True:
                                    shutil.move('{}'.format(x),'{}/{}/{}'.format(path, ora_curs.split("_")[2],x))
                                    print("{} mutat in {}".format(ora_curs.split("_")[2],x))
                                else:
                                    pass
                            elif ora_curs.split("_")[0]=="I":
                                if check_para_impara(zi_fisier) == False:
                                    shutil.move('{}'.format(x),'{}/{}/{}'.format(path, ora_curs.split("_")[2],x))
                                    print("{} mutat in {}".format(ora_curs.split("_")[2],x))
                                else:
                                    pass
def main():
    ordonare()

if __name__ == "__main__":
    main()


import sys
_module = sys.modules[__name__]
del sys
ArgsTools = _module
base_args = _module
base_args_jupyter = _module
test_args = _module
FileTools = _module
Prepro = _module
DataTools = _module
metrics = _module
LogTools = _module
logger_tensorboard = _module
VGG = _module
LossTools = _module
loss = _module
TorchTools = _module
progress_bar = _module
crop_imgs = _module
crop_mats = _module
generate_train_df2k = _module
generate_train_mat = _module
load_dataset = _module
model = _module
common = _module
ddsr = _module
demo = _module
denoraw = _module
denorgb = _module
ruofan = _module
srraw = _module
srrgb = _module
tenet1 = _module
tenet2 = _module
rgb2raw = _module
test = _module
train = _module
train_mat = _module

from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Module
import abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings
import numpy as np
from torch import Tensor
patch_functional()
open = mock_open()
yaml = logging = sys = argparse = MagicMock()
ArgumentParser = argparse.ArgumentParser
_global_config = args = argv = cfg = config = params = _mock_config()
argparse.ArgumentParser.return_value.parse_args.return_value = _global_config
yaml.load.return_value = _global_config
sys.argv = _global_config
__version__ = '1.0.0'
xrange = range
wraps = functools.wraps

import torch

import numpy as np

import torch.nn as nn

import torch.nn.functional as F

import torch.utils.model_zoo as model_zoo

import math

import torch.nn

from torch.autograd import Variable

from torchvision import models

import torch.nn.init as init

import torch.utils.data as data

import random

from scipy.io import loadmat

from torch.utils.data import DataLoader

class VGG(nn.Module):

    def __init__(self, features, num_classes=1000):
        super(VGG, self).__init__()
        self.features = features
        self.classifier = nn.Sequential(nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes))
        self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2.0 / n))
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.01)
                m.bias.data.zero_()

class Charbonnier_loss(nn.Module):
    """L1 Charbonnierloss."""

    def __init__(self, epsilon=1e-06):
        super(Charbonnier_loss, self).__init__()
        self.eps = epsilon ** 2

    def forward(self, X, Y):
        diff = X - Y
        loss = torch.mean(torch.sqrt(diff ** 2 + self.eps))
        return loss

class L1_TVLoss(nn.Module):

    def __init__(self, TVLoss_weight=1):
        super(L1_TVLoss, self).__init__()

    def forward(self, x):
        batch_size = x.size()[0]
        h_tv = torch.abs(x[:, :, 1:, :] - x[:, :, :-1, :]).sum()
        w_tv = torch.abs(x[:, :, :, 1:] - x[:, :, :, :-1]).sum()
        return h_tv + w_tv

class L1_TVLoss_Charbonnier(nn.Module):

    def __init__(self, TVLoss_weight=1):
        super(L1_TVLoss_Charbonnier, self).__init__()
        self.e = 1e-06 ** 2

    def forward(self, x):
        batch_size = x.size()[0]
        h_tv = torch.abs(x[:, :, 1:, :] - x[:, :, :-1, :])
        h_tv = torch.mean(torch.sqrt(h_tv ** 2 + self.e))
        w_tv = torch.abs(x[:, :, :, 1:] - x[:, :, :, :-1])
        w_tv = torch.mean(torch.sqrt(w_tv ** 2 + self.e))
        return h_tv + w_tv

class TV_L1LOSS(nn.Module):

    def __init__(self, TVLoss_weight=1):
        super(TV_L1LOSS, self).__init__()

    def forward(self, x, y):
        size = x.size()
        h_tv_diff = torch.abs(x[:, :, 1:, :] - x[:, :, :-1, :] - (y[:, :, 1:, :] - y[:, :, :-1, :])).sum()
        w_tv_diff = torch.abs(x[:, :, :, 1:] - x[:, :, :, :-1] - (y[:, :, :, 1:] - y[:, :, :, :-1])).sum()
        return (h_tv_diff + w_tv_diff) / size[0] / size[1] / size[2] / size[3]

class MSEloss(nn.Module):
    """L1 Charbonnierloss."""

    def __init__(self, epsilon=0.001):
        super(MSEloss, self).__init__()
        self.eps = epsilon ** 2

    def forward(self, X, Y):
        diff = torch.add(X, -Y)
        sum_square_err = torch.sum(diff * diff)
        loss = sum_square_err / X.data.shape[0] / 2.0
        return loss

class Perceptual_loss(nn.Module):

    def __init__(self, content_layer):
        super(Perceptual_loss, self).__init__()
        vgg = models.vgg19(pretrained=True).features
        model = nn.Sequential()
        i = 1
        j = 1
        temp = list(vgg)
        for layer in list(vgg):
            if isinstance(layer, nn.Conv2d):
                name = 'conv_' + str(i)
                model.add_module(name, layer)
                if name == content_layer:
                    break
            if isinstance(layer, nn.ReLU):
                name = 'relu_' + str(i)
                model.add_module(name, layer)
                if name == content_layer:
                    break
                i += 1
            if isinstance(layer, nn.MaxPool2d):
                name = 'pool_' + str(j)
                model.add_module(name, layer)
                j += 1
        self.model = model
        self.criteria = nn.MSELoss()

    def forward(self, X, Y):
        X_content = self.model(X)
        Y_content = self.model(Y)
        loss = ((X_content - Y_content) ** 2).sum()
        loss /= X_content.size()[0] * X_content.size()[1] * X_content.size()[2] * X_content.size()[3]
        return loss

def l1_loss(input, output):
    return torch.mean(torch.abs(input - output))

class VGGLoss(nn.Module):
    """
    VGG(
    (features): Sequential(
    (0): Conv2d (3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d (64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1))

    (5): Conv2d (64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d (128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1))

    (10): Conv2d (128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d (256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d (256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): Conv2d (256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (17): ReLU(inplace)
    (18): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1))

    (19): Conv2d (256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (24): ReLU(inplace)
    (25): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (26): ReLU(inplace)
    (27): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1))

    (28): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (31): ReLU(inplace)
    (32): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (33): ReLU(inplace)
    (34): Conv2d (512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (35): ReLU(inplace)
    (36): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1))
    )

    """

    def __init__(self, vgg_path, layers='45', input='RGB', loss='l1'):
        super(VGGLoss, self).__init__()
        self.input = input
        vgg = models.vgg19(pretrained=False)
        if vgg_path is not '':
            vgg.load_state_dict(torch.load(vgg_path))
        self.layers = [int(l) for l in layers]
        layers_dict = [0, 4, 9, 18, 27, 36]
        self.vgg = []
        if loss == 'l1':
            self.loss_func = l1_loss
        elif loss == 'l2':
            self.loss_func = nn.functional.mse_loss
        else:
            raise Exception('Do not support this loss.')
        i = 0
        for j in self.layers:
            self.vgg.append(nn.Sequential(*list(vgg.features.children())[layers_dict[i]:layers_dict[j]]))
            i = j

    def cuda(self, device=None):
        for Seq in self.vgg:
            Seq

    def forward(self, input, target):
        if self.input == 'RGB':
            input_R, input_G, input_B = torch.split(input, 1, dim=1)
            target_R, target_G, target_B = torch.split(target, 1, dim=1)
            input_BGR = torch.cat([input_B, input_G, input_R], dim=1)
            target_BGR = torch.cat([target_B, target_G, target_R], dim=1)
        else:
            input_BGR = input
            target_BGR = target
        input_list = [input_BGR]
        target_list = [target_BGR]
        for Sequential in self.vgg:
            input_list.append(Sequential(input_list[-1]))
            target_list.append(Sequential(target_list[-1]))
        loss = []
        for i in range(len(self.layers)):
            loss.append(self.loss_func(input_list[i + 1], target_list[i + 1]))
        return sum(loss)

def act_layer(act_type, inplace=False, neg_slope=0.2, n_prelu=1):
    act_type = act_type.lower()
    if act_type == 'relu':
        layer = nn.ReLU(inplace)
    elif act_type == 'leakyrelu':
        layer = nn.LeakyReLU(neg_slope, inplace)
    elif act_type == 'prelu':
        layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope)
    else:
        raise NotImplementedError('activation layer [%s] is not found' % act_type)
    return layer

def default_conv(in_channelss, out_channels, kernel_size, stride=1, bias=False):
    return nn.Conv2d(in_channelss, out_channels, kernel_size, padding=kernel_size // 2, stride=stride, bias=bias)

def norm_layer(norm_type, nc):
    norm_type = norm_type.lower()
    if norm_type == 'batch':
        layer = nn.BatchNorm2d(nc, affine=True)
    elif norm_type == 'instance':
        layer = nn.InstanceNorm2d(nc, affine=False)
    else:
        raise NotImplementedError('normalization layer [%s] is not found' % norm_type)
    return layer

class ConvBlock(nn.Sequential):

    def __init__(self, in_channelss, out_channels, kernel_size=3, stride=1, bias=False, norm_type=False, act_type='relu'):
        m = [default_conv(in_channelss, out_channels, kernel_size, stride=stride, bias=bias)]
        act = act_layer(act_type) if act_type else None
        norm = norm_layer(norm_type, out_channels) if norm_type else None
        if norm:
            m.append(norm)
        if act is not None:
            m.append(act)
        super(ConvBlock, self).__init__(*m)

class ShortcutBlock(nn.Module):

    def __init__(self, submodule):
        super(ShortcutBlock, self).__init__()
        self.sub = submodule

    def forward(self, x):
        output = x + self.sub(x)
        return output

    def __repr__(self):
        tmpstr = 'Identity + \n|'
        modstr = self.sub.__repr__().replace('\n', '\n|')
        tmpstr = tmpstr + modstr
        return tmpstr

class ResBlock(nn.Module):

    def __init__(self, n_feats, kernel_size=3, norm_type=False, act_type='relu', bias=False, res_scale=1):
        super(ResBlock, self).__init__()
        m = []
        act = act_layer(act_type) if act_type else None
        norm = norm_layer(norm_type, n_feats) if norm_type else None
        for i in range(2):
            m.append(default_conv(n_feats, n_feats, kernel_size, bias=bias))
            if norm:
                m.append(norm)
            if i == 0:
                m.append(act)
        self.body = nn.Sequential(*m)
        self.res_scale = res_scale

    def forward(self, x):
        res = self.body(x).mul(self.res_scale)
        res += x
        return res

class ResidualDenseBlock5(nn.Module):
    """
    Residual Dense Block
    style: 5 convs
    The core module of paper: (Residual Dense Network for Image Super-Resolution, CVPR18)
    """

    def __init__(self, nc, gc=32, kernel_size=3, stride=1, bias=True, norm_type=None, act_type='leakyrelu', res_scale=0.2):
        super(ResidualDenseBlock5, self).__init__()
        self.res_scale = res_scale
        self.conv1 = ConvBlock(nc, gc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)
        self.conv2 = ConvBlock(nc + gc, gc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)
        self.conv3 = ConvBlock(nc + 2 * gc, gc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)
        self.conv4 = ConvBlock(nc + 3 * gc, gc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)
        self.conv5 = ConvBlock(nc + 4 * gc, gc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)

    def forward(self, x):
        x1 = self.conv1(x)
        x2 = self.conv2(torch.cat((x, x1), 1))
        x3 = self.conv3(torch.cat((x, x1, x2), 1))
        x4 = self.conv4(torch.cat((x, x1, x2, x3), 1))
        x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
        return x5.mul(self.res_scale) + x

class RRDB(nn.Module):
    """
    Residual in Residual Dense Block
    """

    def __init__(self, nc, gc=32, kernel_size=3, stride=1, bias=True, norm_type=None, act_type='leakyrelu', res_scale=0.2):
        super(RRDB, self).__init__()
        self.res_scale = res_scale
        self.RDB1 = ResidualDenseBlock5(nc, gc, kernel_size, stride, bias, norm_type, act_type, res_scale)
        self.RDB2 = ResidualDenseBlock5(nc, gc, kernel_size, stride, bias, norm_type, act_type, res_scale)
        self.RDB3 = ResidualDenseBlock5(nc, gc, kernel_size, stride, bias, norm_type, act_type, res_scale)

    def forward(self, x):
        out = self.RDB1(x)
        out = self.RDB2(out)
        out = self.RDB3(out)
        return out.mul(self.res_scale) + x

class SkipUpDownBlock(nn.Module):
    """
    Residual Dense Block
    style: 5 convs
    The core module of paper: (Residual Dense Network for Image Super-Resolution, CVPR18)
    """

    def __init__(self, nc, kernel_size=3, stride=1, bias=True, norm_type=None, act_type='leakyrelu', res_scale=0.2):
        super(SkipUpDownBlock, self).__init__()
        self.res_scale = res_scale
        self.conv1 = ConvBlock(nc, nc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)
        self.conv2 = ConvBlock(2 * nc, 2 * nc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)
        self.up = nn.PixelShuffle(2)
        self.pool = nn.MaxPool2d(2)
        self.conv3 = ConvBlock(nc, nc, kernel_size, stride, bias=bias, norm_type=norm_type, act_type=act_type)

    def forward(self, x):
        x1 = self.conv1(x)
        x2 = self.conv2(torch.cat((x, x1), 1))
        x3 = self.up(torch.cat((x, x1, x2), 1))
        x3 = self.conv3(self.pool(x3))
        return x3.mul(self.res_scale) + x

class DUDB(nn.Module):
    """
    Dense Up Down Block
    """

    def __init__(self, nc, kernel_size=3, stride=1, bias=True, norm_type=None, act_type='leakyrelu', res_scale=0.2):
        super(DUDB, self).__init__()
        self.res_scale = res_scale
        self.UDB1 = SkipUpDownBlock(nc, kernel_size, stride, bias, norm_type, act_type, res_scale)
        self.UDB2 = SkipUpDownBlock(nc, kernel_size, stride, bias, norm_type, act_type, res_scale)
        self.UDB3 = SkipUpDownBlock(nc, kernel_size, stride, bias, norm_type, act_type, res_scale)

    def forward(self, x):
        return self.UDB3(self.UDB2(self.UDB1(x))).mul(self.res_scale) + x

class Upsampler(nn.Sequential):

    def __init__(self, scale, n_feats, norm_type=False, act_type='relu', bias=False):
        m = []
        act = act_layer(act_type) if act_type else None
        norm = norm_layer(norm_type, n_feats) if norm_type else None
        if scale & scale - 1 == 0:
            for _ in range(int(math.log(scale, 2))):
                m.append(default_conv(n_feats, 4 * n_feats, 3, bias=bias))
                m.append(nn.PixelShuffle(2))
                if norm:
                    m.append(norm)
                if act is not None:
                    m.append(act)
        elif scale == 3:
            m.append(default_conv(n_feats, 9 * n_feats, 3, bias=bias))
            m.append(nn.PixelShuffle(3))
            if norm:
                m.append(norm)
            if act is not None:
                m.append(act)
        else:
            raise NotImplementedError
        super(Upsampler, self).__init__(*m)

class DownsamplingShuffle(nn.Module):

    def __init__(self, scale):
        super(DownsamplingShuffle, self).__init__()
        self.scale = scale

    def forward(self, input):
        """
        input should be 4D tensor N, C, H, W
        :return: N, C*scale**2,H//scale,W//scale
        """
        N, C, H, W = input.size()
        assert H % self.scale == 0, 'Please Check input and scale'
        assert W % self.scale == 0, 'Please Check input and scale'
        map_channels = self.scale ** 2
        channels = C * map_channels
        out_height = H // self.scale
        out_width = W // self.scale
        input_view = input.contiguous().view(N, C, out_height, self.scale, out_width, self.scale)
        shuffle_out = input_view.permute(0, 1, 3, 5, 2, 4).contiguous()
        return shuffle_out.view(N, channels, out_height, out_width)

class NET(nn.Module):

    def __init__(self, opt):
        super(NET, self).__init__()
        sr_n_resblocks = opt.sr_n_resblocks
        dm_n_resblocks = opt.dm_n_resblocks
        sr_n_feats = opt.channels
        dm_n_feats = opt.channels
        scale = opt.scale
        denoise = opt.denoise
        block_type = opt.block_type
        act_type = opt.act_type
        bias = opt.bias
        norm_type = opt.norm_type
        if denoise:
            m_sr_head = [common.ConvBlock(5, sr_n_feats, 5, act_type=act_type, bias=True)]
        else:
            m_sr_head = [common.ConvBlock(4, sr_n_feats, 5, act_type=act_type, bias=True)]
        if block_type.lower() == 'rrdb':
            m_sr_resblock = [common.RRDB(sr_n_feats, sr_n_feats, 3, 1, bias, norm_type, act_type, 0.2) for _ in range(sr_n_resblocks)]
        elif block_type.lower() == 'dudb':
            m_sr_resblock = [common.DUDB(sr_n_feats, 3, 1, bias, norm_type, act_type, 0.2) for _ in range(sr_n_resblocks)]
        elif block_type.lower() == 'res':
            m_sr_resblock = [common.ResBlock(sr_n_feats, 3, norm_type, act_type, res_scale=1, bias=bias) for _ in range(sr_n_resblocks)]
        else:
            raise RuntimeError('block_type is not supported')
        m_sr_resblock += [common.ConvBlock(sr_n_feats, sr_n_feats, 3, bias=bias)]
        m_sr_up = [common.Upsampler(scale, sr_n_feats, norm_type, act_type, bias=bias), common.ConvBlock(sr_n_feats, 4, 3, bias=True)]
        m_sr_tail = [nn.PixelShuffle(2)]
        m_dm_head = [common.ConvBlock(4, dm_n_feats, 5, act_type=act_type, bias=True)]
        if block_type.lower() == 'rrdb':
            m_dm_resblock = [common.RRDB(dm_n_feats, dm_n_feats, 3, 1, bias, norm_type, act_type, 0.2) for _ in range(dm_n_resblocks)]
        elif block_type.lower() == 'dudb':
            m_dm_resblock = [common.DUDB(dm_n_feats, 3, 1, bias, norm_type, act_type, 0.2) for _ in range(dm_n_resblocks)]
        elif block_type.lower() == 'res':
            m_dm_resblock = [common.ResBlock(dm_n_feats, 3, norm_type, act_type, res_scale=1, bias=bias) for _ in range(dm_n_resblocks)]
        else:
            raise RuntimeError('block_type is not supported')
        m_dm_resblock += [common.ConvBlock(dm_n_feats, dm_n_feats, 3, bias=bias)]
        m_dm_up = [common.Upsampler(2, dm_n_feats, norm_type, act_type, bias=bias), common.ConvBlock(dm_n_feats, 3, 3, bias=True)]
        self.model_sr = nn.Sequential(*m_sr_head, common.ShortcutBlock(nn.Sequential(*m_sr_resblock)), *m_sr_up)
        self.sr_output = nn.Sequential(*m_sr_tail)
        self.model_dm = nn.Sequential(*m_dm_head, common.ShortcutBlock(nn.Sequential(*m_dm_resblock)), *m_dm_up)
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.xavier_normal_(m.weight)
                m.weight.requires_grad = True
                if m.bias is not None:
                    m.bias.data.zero_()
                    m.bias.requires_grad = True

    def forward(self, x):
        x = self.model_sr(x)
        sr_raw = self.sr_output(x)
        x = self.model_dm(x)
        return sr_raw, x

import torch
from torch.nn import MSELoss, ReLU
from _paritybench_helpers import _mock_config, _mock_layer, _paritybench_base, _fails_compile

TESTCASES = [
    # (nn.Module, init_args, forward_args, jit_compiles)
    (Charbonnier_loss,
     lambda: ([], {}),
     lambda: ([torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])], {}),
     True),
    (ConvBlock,
     lambda: ([], {'in_channelss': 4, 'out_channels': 4}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (DUDB,
     lambda: ([], {'nc': 4}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (L1_TVLoss,
     lambda: ([], {}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (L1_TVLoss_Charbonnier,
     lambda: ([], {}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (MSEloss,
     lambda: ([], {}),
     lambda: ([torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])], {}),
     True),
    (Perceptual_loss,
     lambda: ([], {'content_layer': 1}),
     lambda: ([torch.rand([4, 3, 64, 64]), torch.rand([4, 3, 64, 64])], {}),
     True),
    (ResBlock,
     lambda: ([], {'n_feats': 4}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (ShortcutBlock,
     lambda: ([], {'submodule': _mock_layer()}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (SkipUpDownBlock,
     lambda: ([], {'nc': 4}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     True),
    (TV_L1LOSS,
     lambda: ([], {}),
     lambda: ([torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])], {}),
     True),
]

class Test_guochengqian_TENet(_paritybench_base):
    def test_000(self):
        self._check(*TESTCASES[0])

    def test_001(self):
        self._check(*TESTCASES[1])

    def test_002(self):
        self._check(*TESTCASES[2])

    def test_003(self):
        self._check(*TESTCASES[3])

    def test_004(self):
        self._check(*TESTCASES[4])

    def test_005(self):
        self._check(*TESTCASES[5])

    def test_006(self):
        self._check(*TESTCASES[6])

    def test_007(self):
        self._check(*TESTCASES[7])

    def test_008(self):
        self._check(*TESTCASES[8])

    def test_009(self):
        self._check(*TESTCASES[9])

    def test_010(self):
        self._check(*TESTCASES[10])


from ..epilog import epilog

import argparse

def define_parser():
    parser = argparse.ArgumentParser(
            description=__doc__,
            epilog=epilog)

    ####################################################################
    # Specific arguments
    ####################################################################

    specific = parser.add_argument_group(
        """Creating a standard space isometric to the reference space.""")

    specific.add_argument('--diffeomorphism-nb',
        default='scanner',
        choices=['scanner', 'identity', 'fit'],
        help="""Image space of diffeomorphism.""")

    specific.add_argument('--new-diffeomorphism',
        help="""Name to use for the fitted diffeomorphisms.""")

    specific.add_argument('--resolution',
        default=2.,
        type=float,
        help="""The resolution of the template in standard space. If set
        to 0, the resolution of the scanner will be used.""")

    specific.add_argument('--cycle',
        type=int,
        nargs='+',
        help="""Use the data in scan cycle CYCLE as a template for
        the subject reference space. Enumeration starts at 0 (i.e. the
        first scan cycle is cycle 0). It will be checked whether the
        specified cycle has been marked as a potential outlier (i.e. a
        scan cycle that shows more head movements that usual). You won't
        be able to set an outlying scan cycle as reference. More than
        one cycle can be specified, though, and the list will be used as
        fall backs. If --cycle is given, DIFFEOMORPHISM_NB will be set
        to scan_cycle.""")

    ####################################################################
    # File handling
    ####################################################################

    file_handling = parser.add_argument_group(
        """File handling""")

    lock_handling = file_handling.add_mutually_exclusive_group()

    lock_handling.add_argument('-r', '--remove-lock',
        action='store_true',
        help="""Remove lock, if file is locked. This is useful, if used
        together with -s/--skip to remove orphan locks.""")

    lock_handling.add_argument('-i', '--ignore-lock',
        action='store_true',
        help="""Ignore lock, if file is locked. Together with -s/--skip
        this will also remove orphan locks.""")

    skip_force = file_handling.add_mutually_exclusive_group()

    skip_force.add_argument('-f', '--force',
        action='store_true',
        help="""Force re-writing any files""")

    skip_force.add_argument('-s', '--skip',
        action='store_true',
        help="""Do not perform any calculations.""")

    ####################################################################
    # Verbosity
    ####################################################################

    control_verbosity  = parser.add_argument_group(
        """Control the level of verbosity""")

    control_verbosity.add_argument('-v', '--verbose',
        action='count',
        default=0,
        help="""Increase output verbosity""")

    ####################################################################
    # Push
    ####################################################################

    control_verbosity  = parser.add_argument_group(
        """Control whether to save the modified (thus overwrite the
        existing) study instance.""")

    control_verbosity.add_argument('-p', '--push',
        action='store_true',
        help="""Will save the modified (and thus overwrite the existing)
        study instance.""")

    ####################################################################
    # Multiprocessing
    ####################################################################

    control_multiprocessing  = parser.add_argument_group(
        """Multiprocessing""")

    control_multiprocessing.add_argument('-j', '--cores',
        type=int,
        help="""Number of cores to use. Default is the number of cores
        on the machine.""")

    return parser

from .fmristudy import add_study_arguments

def cmd():
    parser = define_parser()
    add_study_arguments(parser)
    args = parser.parse_args()
    call(args)

cmd.__doc__ = __doc__

########################################################################
#
# Load libraries
#
########################################################################

import os

from os.path import isfile, isdir, join

from multiprocessing.dummy import Pool as ThreadPool

import numpy as np

from .fmristudy import get_study

from ..lock import Lock

from ..study import Study

from ..diffeomorphisms import Image

from ..session import Session

from ..reference import ReferenceMaps

from ..pmap import PopulationMap, pmap_scanner

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

def call(args):

    ####################################################################
    # Options
    ####################################################################

    remove_lock       = args.remove_lock
    ignore_lock       = args.ignore_lock
    force             = args.force
    skip              = args.skip
    verbose           = args.verbose

    scan_cycle         = args.cycle
    resolution         = args.resolution
    diffeomorphism_nb  = args.diffeomorphism_nb

    if args.new_diffeomorphism is None:
        new_diffeomorphism = diffeomorphism_nb
    else:
        new_diffeomorphism = args.new_diffeomorphism

    if (resolution is None) or (resolution == 'native') or np.isclose(resolution, 0):
        resolution = None

    ####################################################################
    # Study
    ####################################################################

    study = get_study(args)

    if study is None:
        print('No study found. Nothing to do.')
        return

    study.set_rigids(args.rigids)
    study.set_diffeomorphism(new_diffeomorphism)
    #study.set_standard_space('isometric')

    ####################################################################
    # Create iterator
    ####################################################################

    study_iterator = study.iterate(
            'session',
            'reference_maps',
            'result',
            'population_map', new=['population_map'],
            integer_index=True,
            verbose=args.verbose)

    df = study_iterator.df.copy()

    df['locked'] = False

    ####################################################################
    # Wrapper
    ####################################################################

    def wm(index, name, session, reference_maps, population_map, result,
            file_population_map):

        if type(population_map) is Lock:
            if remove_lock or ignore_lock:
                if verbose:
                    print('{}: Remove lock'.format(name.name()))
                population_map.unlock()
                if remove_lock:
                    return
            else:
                if verbose:
                    print('{}: Locked'.format(name.name()))
                return

        elif population_map is not None and not force:
            if verbose:
                print('{}: PopulationMap already exists. Use -f/--force to overwrite'.format(
                    name.name()))
            return

        if skip:
            return

        if verbose:
            print('{}: Lock: {}'.format(name.name(), file_population_map))

        lock = Lock(name, 'fmripop', file_population_map)
        df.ix[index, 'locked'] = True

        dfile = os.path.dirname(file_population_map)
        if dfile and not isdir(dfile):
           os.makedirs(dfile)

        lock.save(file_population_map)

        ####################################################################
        # Create population map from a session instance
        ####################################################################

        if session is None:
            print('{}: No session found'.format(name.name()))
            df.ix[index,'valid'] = False
            lock.conditional_unlock(df, index, verbose)
            return

        if diffeomorphism_nb == 'identity':
            population_map = pmap_scanner(
                    session=session,
                    resolution=resolution,
                    name=new_diffeomorphism)

            if verbose:
                if resolution:
                    print("""{}:
                    Standard space equals scanner space. Diffeomorphism
                    equals identity. Resolution is ({} mm)**3.""".format(
                        name.name(), resolution))
                else:
                    print("""{}:
                    Standard space equals scanner space. Diffeomorphism
                    equals identity. Resolution is native.""".format(
                        name.name()))

        ####################################################################
        # Create population map from a session and reference instance
        ####################################################################

        elif diffeomorphism_nb == 'scanner':
            if reference_maps is None:
                print('{}: No ReferenceMaps found'.format(name.name()))
                df.ix[index,'valid'] = False
                lock.conditional_unlock(df, index, verbose)
                return

            if scan_cycle is None:
                population_map = pmap_scanner(
                        session=session,
                        reference_maps = reference_maps,
                        resolution=resolution,
                        name=new_diffeomorphism)

                if verbose:
                    if resolution:
                        print("""{}:
                        Standard space equals scanner space. Diffeomorphism
                        maps to the average position of the subject in the
                        scanner. Resolution is ({} mm)**3.""".format(
                            name.name(), resolution))
                    else:
                        print("""{}:
                        Standard space equals scanner space. Diffeomorphism
                        maps to the average position of the subject in the
                        scanner. Resolution is native.""".format(
                            name.name()))

            else:
                try:
                    outlying_cycles = reference_maps.outlying_cycles
                except:
                    if verbose:
                        print("""{}:
                        I have found no information
                        about outlying scan cycles!""".format(name.name()))
                    outlying_cycles = None

                if outlying_cycles is None:
                    scan_cycle_to_use = cycle[0]
                else:
                    if outlying_cycles[scan_cycle].all():
                        df.ix[index,'valid'] = False
                        print("""{}:
                        All suggested reference cycles have been marked as
                        outlying. Unable to proceed. Please specify a
                        different scan cycle (using --cycle) as
                        reference.""".format(name.name()))
                        lock.conditional_unlock(df, index, verbose, True)
                        return
                    elif outlying_cycles[scan_cycle].any():
                        for c, co in zip (scan_cycle, outlying_cycles[scan_cycle]):
                            if co:
                                if verbose:
                                    print("""{}:
                                    Scan cycle {:d} marked as outlying,
                                    using fallback.""".format( name.name(), c))
                            else:
                                scan_cycle_to_use = c
                                break
                    else:
                        scan_cycle_to_use = scan_cycle[0]

                population_map = pmap_scanner(
                        session=session,
                        reference_maps = reference_maps,
                        scan_cycle = scan_cycle_to_use,
                        resolution=resolution,
                        name=new_diffeomorphism)

                population_map.set_nb(Image(
                    reference=session.reference,
                    data=session.data[scan_cycle_to_use],
                    name=session.name.name()+'-{:d}'.format(scan_cycle_to_use)))

                if verbose:
                    if resolution:
                        print("""{}:
                        Standard space equals scanner space,
                        diffeomorphism maps to subject position during
                        scan cycle: {:d}. Resolution is ({} mm)**3.""".format(
                            name.name(), scan_cycle_to_use, resolution))
                    else:
                        print("""{}:
                        Standard space equals scanner space,
                        diffeomorphism maps to subject position during
                        scan cycle: {:d}. Resolution is native.""".format(
                            name.name(), scan_cycle_to_use))

        ####################################################################
        # Create population map instance from a result instance
        ####################################################################

        elif (diffeomorphism_nb == 'fit'):

            if result is None:
                print('{}: No fit found'.format(name.name()))
                df.ix[index,'valid'] = False
                lock.conditional_unlock(df, index, verbose)
                return

            population_map = result.population_map
            population_map.set_vb(template=result.get_field('intercept', 'point'))

            if verbose:
                print('{}: VB space equals reference space as given by fit'.format(
                    name.name()))

        else:
            print('{}: Diffeomorphism type not supported'.format(name.name()))

        if verbose > 2:
            print("""{}:
                {}
                {}""".format(name.name(),
                    population_map.diffeomorphism.describe(),
                    population_map.describe()))

        try:
            if verbose:
                print('{}: Save: {}'.format(name.name(),
                    file_population_map))

            population_map.save(file_population_map)
            df.ix[index,'locked'] = False

        except Exception as e:
            df.ix[index,'valid'] = False
            print('{}: Unable to create: {}, {}'.format(name.name(),
                file_population_map, e))
            lock.conditional_unlock(df, index, verbose, True)
            return

        return

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

    if len(df) > 1 and ((args.cores is None) or (args.cores > 1)):
        try:
            pool = ThreadPool(args.cores)
            for index, name, files, instances in study_iterator:
                session         = instances['session']
                reference_maps  = instances['reference_maps']
                population_map  = instances['population_map']
                result          = instances['result']
                file_population_map = files['population_map']
                wm
                pool.apply_async(wm, args=(index, name, session,
                    reference_maps, population_map, result,
                    file_population_map))
            pool.close()
            pool.join()
        except Exception as e:
            pool.close()
            pool.terminate()
            print('Pool execution has been terminated')
            print(e)
        finally:
            files = df.ix[df.locked, 'population_map'].values
            if len(files) > 0:
                for f in files:
                    print('Unlock: {}'.format(f))
                    os.remove(f)
    else:
        try:
            print('Process protocol entries sequentially')
            for index, name, files, instances in study_iterator:
                session         = instances['session']
                reference_maps  = instances['reference_maps']
                population_map  = instances['population_map']
                result          = instances['result']
                file_population_map = files['population_map']
                wm(index, name, session, reference_maps, population_map,
                        result, file_population_map)
        finally:
            files = df.ix[df.locked, 'population_map'].values
            if len(files) > 0:
                for f in files:
                    print('Unlock: {}'.format(f))
                    os.remove(f)

    ####################################################################
    # Write study to disk
    ####################################################################

    if args.out is not None:
        if args.verbose:
            print('Save: {}'.format(args.out))

        dfile = os.path.dirname(args.out)
        if dfile and not isdir(dfile):
           os.makedirs(dfile)

        study.save(args.out)

    if args.push:
        if args.verbose:
            print('Save: {}'.format(args.study))
        study.save(args.study)


from logging import error
import matplotlib.pyplot as plt
import numpy as np
import csv

from numpy.core.einsumfunc import _einsum_path_dispatcher

def read_layout_file(filename,TURBS=True):

    nturbs = np.array([])
    nrows = np.array([])
    percent_increase = np.array([])
    start_aep = np.array([])
    opt_aep = np.array([])
    time = np.array([])
    funcs = np.array([])

    with open(filename) as f:
        reader = csv.reader(f)

        x = False
        y = False

        for row in reader:
            if len(row) > 0:
                if TURBS == True:
                    if row[0].split()[0] == "nturbs":
                        nturbs = np.append(nturbs,float(row[0].split()[2]))
                else:
                    if row[0].split()[0] == "nrows":
                        nrows = np.append(nrows,float(row[0].split()[2]))
                if row[0].split()[0] == "percent_increase":
                    percent_increase = np.append(percent_increase,float(row[0].split()[2]))
                if row[0].split()[0] == "start_aep":
                    start_aep = np.append(start_aep,float(row[0].split()[2]))
                if row[0].split()[0] == "opt_aep":
                    opt_aep = np.append(opt_aep,float(row[0].split()[2]))
                if row[0].split()[0] == "time":
                    time = np.append(time,float(row[0].split()[2]))
                if row[0].split()[0] == "funcs":
                    funcs = np.append(funcs,float(row[0].split()[2]))

    if TURBS == True:
        return nturbs,percent_increase,start_aep,opt_aep,time,funcs
    else:
        return nrows,percent_increase,start_aep,opt_aep,time,funcs

spacing = [3,4,5,6,7,8]
pd = np.zeros((len(spacing),5))
pc = np.zeros((len(spacing),5))

td = np.zeros((len(spacing),5))
tc = np.zeros((len(spacing),5))

ad = np.zeros((len(spacing),5))
ac = np.zeros((len(spacing),5))

for i in range(len(spacing)):
    nturbs,percent_discrete,start_aep,opt_discrete,time_discrete,funcs_discrete = read_layout_file("../line_layout/discrete/discrete_%sspacing_20yaw.txt"%spacing[i])
    nturbs_c,percent_continuous,start_aep_c,opt_continuous,time_continuous,funcs_continuous = read_layout_file("../line_layout/continuous/continuous_%sspacing.txt"%spacing[i])

    pd[i,:] = percent_discrete[:]
    pc[i,:] = percent_continuous[:]
    td[i,:] = time_discrete[:]
    tc[i,:] = time_continuous[:]
    ad[i,:] = opt_discrete[:]
    ac[i,:] = opt_continuous[:]

plt.figure(figsize=(6,4))
ax1 = plt.subplot(221)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
ax2 = plt.subplot(222)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
ax3 = plt.subplot(223)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
ax4 = plt.subplot(224)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)

ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax4.spines['right'].set_visible(False)
ax4.spines['top'].set_visible(False)

ax1.plot(spacing,pc[:,4],"o",label="continuous")
ax1.plot(spacing,pd[:,4],"o",label="Boolean")
ax1.set_ylim(0,330)
ax1.set_ylabel("% power increase\nfrom baseline",fontsize=8)
ax1.legend(fontsize=8)

ax2.plot(spacing,ac[:,4]/ad[:,4],"o",color="C3")
ax2.set_ylabel("opt power continuous/\nopt power Boolean",fontsize=8)

ax3.plot(spacing,tc[:,4],"o")
ax3.plot(spacing,td[:,4],"o")
ax3.set_ylabel("time to run\noptimization (s)",fontsize=8)
ax3.set_ylim(-50,1100)
ax3.set_xlabel("turbine spacing (D)",fontsize=8)
# ax3.set_ylabel("time continuous/\ntime boolean)",fontsize=8)

ax4.plot(spacing,tc[:,4]/td[:,4],"o",color="C3")
# ax4.set_ylim(0,70)
ax4.set_ylabel("time continuous/\ntime Boolean",fontsize=8)
ax4.set_xlabel("turbine spacing (D)",fontsize=8)

plt.suptitle(r"50 turbines in-line: $\bf{varied}$ $\bf{turbine}$ $\bf{spacing}$",fontsize=8)
plt.subplots_adjust(top=0.93,left=0.13,right=0.99,bottom=0.1,
            wspace=0.5,hspace=0.2)

ax1.set_xticks((3,4,5,6,7,8))
ax2.set_xticks((3,4,5,6,7,8))
ax3.set_xticks((3,4,5,6,7,8))
ax4.set_xticks((3,4,5,6,7,8))

dy = 0.02
dx = 0.08
limx = ax1.get_xlim()
limy = ax1.get_ylim()
ax1.text(limx[0]+dx*(limx[1]-limx[0]),limy[1]-dy*(limy[1]-limy[0]),"a",fontsize=10,weight="bold")
limx = ax2.get_xlim()
limy = ax2.get_ylim()
ax2.text(limx[0]+dx*(limx[1]-limx[0]),limy[1]-dy*(limy[1]-limy[0]),"b",fontsize=10,weight="bold")
limx = ax3.get_xlim()
limy = ax3.get_ylim()
ax3.text(limx[0]+dx*(limx[1]-limx[0]),limy[1]-dy*(limy[1]-limy[0]),"c",fontsize=10,weight="bold")
limx = ax4.get_xlim()
limy = ax4.get_ylim()
ax4.text(limx[0]+dx*(limx[1]-limx[0]),limy[1]-dy*(limy[1]-limy[0]),"d",fontsize=10,weight="bold")

plt.savefig("figures/line_results_spacing.pdf",transparent=True)

plt.show()


# This file is the main file for the ECE 760 Graphic Probability Model in 2018 Fall, Texas A & M University.
# Author: Tianqi Li
# the file is the Problem 2 in hw2, which validate the d-sepration ALG for a DAG

import numpy as np
import graph
import sys

def output_1(graph, observe, source, end):
    # test if the end point is in the Y set
    Y = graph.D_sep(source, observe)
    if end in Y:
        return False
    else:
        return True

def result_hw1():
    # to aviod trivial query in hw1, I hand coded the queries.
    g = {"a": ["d"],
         "b": ["d"],
         "c": ["e"],
         "d": ["g", "h"],
         "e": ["i"],
         "f": ["i", "j"],
         "g": ["k"],
         "h": ["k", "e"],
         "i": ["l"],
         "j": ["m"],
         "k": [],
         "l": [],
         "m": []
         }  # graph with all nodes and their children

    # initialize graph
    Graph = graph.DAG(g)

    problems = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    observes = [{'g', 'l'}, {'l'}, {'d'}, {'d', 'k', 'm'},
                {'c', 'g', 'l'}, {'k', 'e'}, {'l'}]
    sources = ['a', 'a', 'g', 'g', 'b', 'a', 'b']  # all source node
    ends = ['j', 'c', 'l', 'l', 'f']  # end point for prob a - e

    for i in range(5):
        print(problems[i], "). Y = ", Graph.D_sep(sources[i], observes[i]), " The flow can reach from node ",
              sources[i], "to node ", ends[i], " is ", output_1(Graph, observes[i], sources[i], ends[i]))

    for i in range(2):
        i += 5
        print(problems[i], "). The Y set contains all nodes are d-separated from ",
              sources[i], ", given Z = ", observes[i], " are Y = ", Graph.D_sep(sources[i], observes[i]))
    return

def read_txt(filename):
    # this function opens a txt file, convert contains to graph and queries

    # open file
    file = open(filename, 'r')
    a = file.read().split('\n')

    # first line read V, M, Q
    # where V and M are the number of nodes and edges in the BN, respectively,
    # Q is the number of queries
    try:
        V, M, Q = list(map(int, a[0].split(' ')))
    except ValueError:
        return print("first line is not V, M, Q pattern, please check :)")

    g, L = dict(), []  # g is the graph structure, L is all keys of the graph
    for i in range(M):
        # explore all vertices in all edges
        try:
            L.append(a[i+1].split(' ')[0])
            L.append(a[i+1].split(' ')[1])
        except IndexError:
            return print('edges are not well determind at', i+1, 'th line.')
    # initialize the graph by giving all keys
    keys = set(L)
    # check correctness of V value
    if len(keys) != V:
        print('V is not the number of vertices, while it is ', V, '.')
        return
    # add children to each vertices
    for key in keys:
        g[key] = []
    for i in range(M):
        try:
            g[a[i+1].split(' ')[0]].append(a[i+1].split(' ')[1])  # check edge is complete
        except IndexError:
            return print('edge is not well determind at', i+1, 'th line :(')
    # graph is constructed completed!

    # grab queries info
    observes, sources = [], []
    for i in range(Q):
        # queries are in 'source | observation' mode
        if a[i + M + 1].find('|') < 0:
            print('The query in', i + M + 2, 'th line is not complete :)')
            return
        sources.append(a[i + M + 1].split('|')[0].split(' ')[0])
        observes.append(set(a[i + M + 1].split('|')[1][1:].split(' ')))

    return g, observes, sources

def main():

    filename = sys.argv[1]
    # print(infile)

    if filename == 'hw1':
        # output the result of hw1
        result_hw1()
        return
    else:
        g, observes, sources = read_txt(filename)

    # start calculating, initilize the graph structure
    Graph = graph.DAG(g)

    import string
    # show the results
    Y = []
    for i in range(len(observes)):
        result = Graph.D_sep(sources[i], observes[i])
        print(string.ascii_lowercase[i], "). The Y set contains all nodes are d-separated from ",
              sources[i], ", given Z = ", observes[i], " are Y = ", result)
        Y.append(result)
    # write all Ys into stdout.txt
    output = open('stdout.txt', 'w')
    for y in Y:
        #     print(" ".join(y))
        output.writelines(" ".join(y)+'\n')
    output.close()

if __name__ == "__main__":
    main()


# 0, 1， 8转了一样
# 6，9互为reverse
class Solution(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool
        """
        length = len(num)
        for i in range((length + 1) // 2):
            if (num[i] in ['8', '1', '0'] and num[length - i - 1] == num[i]) or (
                    num[i] in ['6', '9'] and num[length - i - 1] in ['6', '9'] and num[i] != num[length - i - 1]):
                continue
            else:
                return False
        return True


from yacos.info.compy.extractors.extractors import Visitor
from yacos.info.compy.extractors.extractors import ClangDriver
from yacos.info.compy.extractors.extractors import ClangExtractor
from yacos.info.compy.extractors.extractors import clang
from yacos.info.compy import common

class SyntaxSeqVisitor(Visitor):
    """Syntax Sequence Visitor."""

    def __init__(self):
        """Init a SyntaxSeq Visitor."""
        Visitor.__init__(self)
        self.S = []

    def visit(self, v):
        """Visit method."""
        if isinstance(v, clang.seq.TokenInfo):
            self.S.append(v.name)

class SyntaxTokenkindVisitor(Visitor):
    """Syntax Token Visitor."""

    def __init__(self):
        """Init a Token Visitor."""
        Visitor.__init__(self)
        self.S = []

    def visit(self, v):
        """Visit method."""
        if isinstance(v, clang.seq.TokenInfo):
            self.S.append(v.kind)

class SyntaxTokenkindVariableVisitor(Visitor):
    """Syntax Token + Variable Visitor."""

    def __init__(self):
        """Init a Token+Variable Visitor."""
        Visitor.__init__(self)
        self.S = []

    def visit(self, v):
        """Visit method."""
        if isinstance(v, clang.seq.TokenInfo):
            if v.kind == "raw_identifier" and "var" in v.name:
                self.S.append(v.name)
            elif (
                v.name in ["for", "while", "do", "if", "else", "return"]
                or v.name in ["fn_0"]
                or v.name.startswith("int")
                or v.name.startswith("float")
            ):
                self.S.append(v.name)
            else:
                self.S.append(v.kind)

class SyntaxSeqBuilder(common.RepresentationBuilder):
    """Syntax Sequence builder."""

    def __init__(self, clang_driver=None):
        """Init the builder."""
        common.RepresentationBuilder.__init__(self)

        if clang_driver:
            self.__clang_driver = clang_driver
        else:
            self.__clang_driver = ClangDriver(
                ClangDriver.ProgrammingLanguage.C,
                ClangDriver.OptimizationLevel.O3,
                [],
                ["-Wall"],
            )
        self.__extractor = ClangExtractor(self.__clang_driver)

    def source_to_info(self, filename, additional_include_dir=None):
        """Extract information to build the representation."""
        if additional_include_dir:
            self.__clang_driver.addIncludeDir(
                additional_include_dir, ClangDriver.IncludeDirType.User
            )
        info = self.__extractor.SeqFromSource(filename)
        if additional_include_dir:
            self.__clang_driver.removeIncludeDir(
                additional_include_dir, ClangDriver.IncludeDirType.User
            )

        return info

    def info_to_representation(self, info, visitor=SyntaxSeqVisitor):
        """Build the representation for each function."""
        vis = visitor()
        info.accept(vis)

        for token in vis.S:
            if token not in self._tokens:
                self._tokens[token] = 1
            self._tokens[token] += 1

        return common.Sequence(vis.S, self.get_tokens())


from connexion import FlaskApp
from flask_sqlalchemy import SQLAlchemy
import os

basedir = os.path.abspath(os.path.dirname(__file__))

connexion_app = FlaskApp(__name__)
app=connexion_app.app
uri = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

if __name__ == '__main__':
    db.create_all()
    connexion_app.add_api('openapi.yaml')
    connexion_app.run(host='0.0.0.0', port=5000, debug=True)


import numpy as np
import pandas as pd

df = pd.read_csv('data/new_github/new_github_descr.csv')
new_github_label_names = ['COVID-19', 'COVID-19, ARDS', 'SARS', 'No Finding']
labels = list()
for index, row in df.iterrows():
    labels.append({'filename': row['filename'], 'label': row['finding']})
df_new_github = pd.DataFrame.from_dict(labels)
df_new_github.to_csv('data/new_github/labels.csv', index=False)

covid_label_names = ['COVID-19', 'Other']
df_covid = pd.read_csv('data/new_github/covid_New_Github_Outputs.csv', usecols=['filename', 'ensemble out'])
preds = list()
for i, row in df_covid.iterrows():
    probs = np.asarray([float(x) for x in row['ensemble out'].split()])
    predicted = covid_label_names[probs.argmax(axis=0)]
    preds.append(predicted)
df_covid['predicted'] = preds
df_covid.to_csv('data/new_github/covid.csv', index=False)

print(df.head())
print(len(df_covid))
print(len(df_new_github))

filenames = list()
labels = list()
ensemble_outs = list()
predicteds = list()
i = 0
while i < len(df_new_github):
    filenames.append(df_new_github['filename'][i])
    labels.append(df_new_github['label'][i])
    ensemble_outs.append(df_covid['ensemble out'][i])
    predicteds.append(df_covid['predicted'][i])
    i += 1
df_full = pd.DataFrame()
df_full['filename'] = filenames
df_full['label'] = labels
df_full['ensemble_out'] = ensemble_outs
df_full['predicted'] = predicteds
df_full.to_csv('data/new_github/new_github.csv', index=False)


# -*- coding: utf-8 -*-

from __future__ import print_function

import sys

from code import InteractiveInterpreter
from threading import Thread
from .compat import PY2, input, print, queue, StringIO
from .highlighter import HAVE_HIGHLIGHTING, highlight, ansiformat, Token
from .highlighter import TerminalFormatter, get_color_for, COLOR_SCHEMES
from .highlighter import Python3Lexer, TracebackLexer, LineLexer
from .interactions import layout_code, simulate_typing, ask_index

class PresenterInterpreter(InteractiveInterpreter):
    def compilesource(self, source, filename='<stdin>', symbol='single'):
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            self.showsyntaxerror(filename)
            return False, None
        return code is None, code

class HighlightingInterpreter(PresenterInterpreter):
    def __init__(self, *args, **kwargs):
        scheme = COLOR_SCHEMES.get(kwargs.pop('color_scheme', 'default'), {})
        PresenterInterpreter.__init__(self, *args, **kwargs)
        self._lexer = TracebackLexer()
        colors = {token: (color, color) for token, color in scheme.items()}
        self._formatter = TerminalFormatter(colorscheme=colors)

    def highlight_error(self, method, *args, **kwargs):
        new_stderr = StringIO()
        old_stderr, sys.stderr = sys.stderr, new_stderr
        try:
            method(self, *args, **kwargs)
        finally:
            sys.stderr = old_stderr
        output = new_stderr.getvalue()
        print(end=highlight(output, self._lexer, self._formatter),
              file=sys.stderr, flush=True)

    def showtraceback(self):
        self.highlight_error(PresenterInterpreter.showtraceback)

    def showsyntaxerror(self, filename=None):
        self.highlight_error(PresenterInterpreter.showsyntaxerror, filename)

class Quitter(object):
    def __init__(self, shell, func):
        self.__shell = shell
        self.__func = func

    def __call__(self):
        if self.__shell._interacting:
            self.__shell._interacting = False
        else:
            return self.__func()

    def __repr__(self):
        return repr(self.__func)

class PresenterShell(object):
    def __init__(self, color_scheme='default', use_ipython=False):
        self._color_scheme = color_scheme
        self._use_ipython = use_ipython
        self._interpreter = None
        self._hl_ps1 = self._ps1 = '>>> '
        self._hl_ps2 = self._ps2 = '... '
        self._output = None
        if color_scheme:
            color = get_color_for(Token.Generic.Prompt, color_scheme)
            self._hl_ps1 = ansiformat(color, self._ps1)
            self._hl_ps2 = ansiformat(color, self._ps2)
            self._lexer = Python3Lexer()
        else:
            self._lexer = LineLexer()

    def _colored(self, color, text):
        return ansiformat(color, text) if self._color_scheme else text

    def reset_interpreter(self):
        if self._use_ipython:
            import IPython
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell

            class IPythonInterpreter(TerminalInteractiveShell,
                                     PresenterInterpreter):
                pass

            self._interpreter = IPythonInterpreter(confirm_exit=False)
            if not HAVE_HIGHLIGHTING or not self._color_scheme:
                self._interpreter.run_line_magic('colors', 'NoColor')

            interpreter = self._interpreter
            session_id = interpreter.history_manager.session_number
            history_queue = self._history_queue = queue.Queue()
            def monitor():
                if not self._interacting:
                    return
                it = interpreter.history_manager.get_range(session_id, -1)
                last_input = next(it, None)
                if last_input is not None:
                    history_queue.put(last_input[-1])

            if IPython.version_info < (2, 0):
                self._interpreter.register_post_execute(monitor)
            else:
                self._interpreter.events.register('post_run_cell', monitor)

            # Customize IPython to make it look like the CPYthon shell
            if IPython.version_info >= (5, 0):
                from IPython.terminal.prompts import ClassicPrompts
                self._interpreter.prompts = ClassicPrompts(self._interpreter)
            else:
                self._interpreter.prompt_manager.in_template = self._ps1
                self._interpreter.prompt_manager.in2_template = self._ps2
                self._interpreter.prompt_manager.out_template = ''
                self._interpreter.prompt_manager.justify = False
            self._interpreter.separate_in = ''
        else:
            ns = {'exit': Quitter(self, exit), 'quit': Quitter(self, quit)}
            if HAVE_HIGHLIGHTING and self._color_scheme:
                self._interpreter = HighlightingInterpreter(
                    color_scheme=self._color_scheme, locals=ns)
            else:
                self._interpreter = PresenterInterpreter(locals=ns)
            have_readline = True
            try:
                import readline
            except ImportError:
                try:
                    import pyreadline as readline
                except ImportError:
                    have_readline = False
            if have_readline:
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(ns).complete)
                readline.parse_and_bind("tab: complete")

    def begin(self):
        self.reset_interpreter()
        print('AutoPython {} on {}'.format(sys.version, sys.platform),
              'Type "help", "copyright", "credits" or "license" '
              'for more information.', self._hl_ps1,
              sep='\n', end='', flush=True)

    def control_c(self):
        self._cleanup_pagination()
        print('^C', self._colored('*red*', 'KeyboardInterrupt'),
              self._hl_ps1, sep='\n', end='', flush=True)

    def _cleanup_pagination(self):
        if self._output is not None:
            self._output.close()
            self._output = None

    def show(self, statement, prompts, index=None, index_line=-1,
             typing_delay=0, paginate=False, context_lines=0):
        ps1 = self._hl_ps1, len(self._ps1)
        ps2 = self._hl_ps2, len(self._ps2)
        hl_prompts = (ps1 if p == 'ps1' else ps2 for p in prompts)
        tokens = layout_code(self._lexer, statement, hl_prompts,
                             index, index_line, context_lines)
        output = simulate_typing(tokens, self._color_scheme, typing_delay)
        if paginate:
            max_line = statement.count('\n') - 1
            for line_number, console_filled in output:
                if console_filled and line_number != max_line:
                    self._output = output
                    return True
        else:
            for _ in output:
                pass
        return False

    def show_more(self):
        for _, console_filled in self._output:
            if console_filled:
                return True
        return False

    def execute(self, statement, code=None):
        print(flush=True)
        if code is not None:
            self._interpreter.runcode(code)
        else:
            self._interpreter.compilesource(statement)
        print(end=self._hl_ps1, flush=True)

    def interact(self):
        self._cleanup_pagination()
        print(end='\r')
        self._interacting = True
        if self._use_ipython:
            thread = Thread(target=self._interpreter.interact)
            thread.start()
            while thread.is_alive():
                try:
                    statement = self._history_queue.get(timeout=0.2)
                    yield statement.splitlines()
                except queue.Empty:
                    pass
        else:
            ps1 = self._colored('*green*', self._ps1)
            ps2 = self._colored('*green*', self._ps2)
            lines = []
            need_more = False
            print(end='\r', flush=True)
            while self._interacting:
                try:
                    try:
                        line = input(ps2 if need_more else ps1)
                        if PY2:
                            line = line.decode(sys.stdin.encoding)
                        lines.append(line)
                    except EOFError:
                        break
                    else:
                        source = '\n'.join(lines)
                        if PY2:
                            source = source.encode(sys.stdin.encoding)
                        need_more = self._interpreter.runsource(source)
                        if not need_more:
                            yield lines
                            lines = []
                except KeyboardInterrupt:
                    print(self._colored('*red*', '\nKeyboardInterrupt'),
                          flush=True)
                    lines = []
                    need_more = False
            print(flush=True)
        print(end=self._hl_ps1, flush=True)
        self._interacting = False

    def ask_where_to_go(self, max_index):
        new_index = ask_index(max_index, self._color_scheme)
        print(end=self._hl_ps1, flush=True)
        return new_index

    def help(self, commands_help):
        self.show('help()', ['ps1'], typing_delay=30)
        print()
        for command, keys, description in commands_help:
            hl_keys = ','.join('[' + self._colored('*yellow*', key) + ']'
                               for key in keys)
            print(' {}: {}\n   {}'.format(
                self._colored('*green*', command), hl_keys, description))
        print(end=self._hl_ps1, flush=True)

    def quit(self):
        self.show('quit()', ['ps1'], typing_delay=30)

    def end(self):
        print(flush=True)


import sys
import heapq
input = sys.stdin.readline

myheap = []
result = []

n = int(input())

def compareDate(a1, a2, b1, b2): #날짜 비교
  if a1*100 + a2 > b1*100 + b2:
    return 1
  elif a1*100 + a2 == b1*100 + b2:
    return 0
  else:
    return -1

for _ in range(n):
  temp = list(map(int, input().split()))
  heapq.heappush(myheap, [-temp[2], -temp[3], -temp[0], -temp[1]])

while len(myheap) != 0:
  cur = heapq.heappop(myheap)
  cur[0], cur[1], cur[2], cur[3] = -cur[0], -cur[1], -cur[2], -cur[3]
  if len(result) != 0 and (compareDate(cur[2], cur[3], result[-1][2], result[-1][3]) >= 0 or (compareDate(result[-1][2], result[-1][3], 3, 1) <= 0)): #이전에 넣은 시기에 완전히 포함되면 건너뜀
    continue
  if compareDate(cur[0], cur[1], 11, 30) == 1: #11월 30일에 더 근접하면 결과 리스트 비움
    result = []
  temp = -1
  for idx in range(len(result)-1, -1, -1):
    if compareDate(result[idx][2], result[idx][3], cur[0], cur[1]) <= 0: #겹쳐지는 부분이 생략 가능하면 삭제
      temp = idx
  if temp != -1:
    result = result[0:temp+1]
  result.append(cur)

check = True

for idx in range(0, len(result)-1):
  if compareDate(result[idx][2], result[idx][3], result[idx+1][0], result[idx+1][1]) > 0: #중간에 포개어지지 않는 경우
    check = False
    break

if compareDate(result[0][0], result[0][1], 11, 30) <= 0 or compareDate(result[-1][2], result[-1][3], 3, 1) > 0: #다 이어붙여도 시기가 안맞는 경우
  check = False

if check:
  print(len(result))
else:
  print(0)


import numpy as np

def entry_date():
    coefficient = quantity = eval(input('Digite o valor do coeficiente: '))
    return coefficient

def calc_delta(a, b, c):
    delta = b * b - 4 * a * c
    return delta

def calc_root(a, b, c, delta):
    if(delta < 0):
        result = 'A equação não possui raízes nos números reais.'
    elif(delta == 0):
        x = -b / (2 * a)
        result = f'A equação possui apenas a raiz: {x}'
    else:
        x1 = (-b - np.sqrt(delta)) / (2 * a)
        x2 = (-b + np.sqrt(delta)) / (2 * a)
        result = f'A equação possui as raízes: {x1}, {x2}'

    return result

a = entry_date()
b = entry_date()
c = entry_date()

delta = calc_delta(a, b, c)

result = calc_root(a, b, c, delta)

print(result)


from copy import deepcopy
import numpy as np
from scipy.special import factorial

from sklearn.base import BaseEstimator, ClassifierMixin

class MLEClassifier(BaseEstimator, ClassifierMixin):
    """An example of classifier"""

    def __init__(self, idx=[19, 20]):
        """
        Called when initializing the classifier
        """
        self.idx = idx

    def fit(self, X, y=None):
        """
        This should fit classifier. All the "work" should be done here.
        """

        return self

    # def predict(self, X, y=None):
    #     probs = self.predict_proba(X)
    #     preds = np.argmax(probs, axis=1)

    #     return preds

    def predict(self, X, y=None):

    # def predict_proba(self, X, y=None):
        ab_gts = np.argmax(X[:, -10:-7], axis=1)
        mo_gts = np.argmax(X[:, -7:-4], axis=1)
        # predictions = deepcopy(ab_gts)
        idx_candidates = np.logical_and(ab_gts==1,  mo_gts==1)
        contaminations = X[:, -1].astype(np.float64)

        ad0 = X[:, self.idx[0]].astype(np.int64)
        ad1 = X[:, self.idx[1]].astype(np.int64)

        with np.errstate(divide='ignore', invalid='ignore'):
            p0 = (contaminations/2)**ad1 * (1 - contaminations/2)**ad0
            p1 = (1/2)**ad1*(1/2)**ad0
            p2 = (contaminations/2)**ad0 * (1 - contaminations/2)**ad1

        probs = np.array([p0, p1, p2]).T
        probs[~idx_candidates, :] = 0
        probs[~idx_candidates, ab_gts[~idx_candidates]] = 1
        # probs[np.arange(preds.shape[0]), preds] = 1

        preds = np.argmax(probs, axis=1)

        return preds

    def predict_proba(self, X, y=None):
        preds = self.predict(X)
        probs = np.zeros((preds.shape[0], 3))
        probs[np.arange(preds.shape[0]), preds] = 1

        return probs

    def score(self, X, y=None):
        return(np.sum(self.predict(X) == y))


#!/usr/bin/env python3
"""Test if the Parameter object used in NodeBase behaves as expected."""
import unittest

from simulation.utils.ros_base.node_base import ParameterObject

class TestParameterObject(unittest.TestCase):
    def setUp(self):
        # Construct a complete parameter object for testing

        dummy_ns = "ns/"
        self.param_dict = {
            "dummy_param": "value",
            "outer_dict": {"inner_param": "inner_value"},
            "very_outer_dict": {"inner_dict": {"very_inner_param": "verry_inner_value"}},
        }

        def get_param(key: str):
            if key.startswith(dummy_ns):
                keys = key.split("/")[1:]
                val = self.param_dict
                for k in keys:
                    val = val[k]
                return val

            return None

        def set_param(key, val):
            self.last_key = key
            self.last_val = val

        self.param_object = ParameterObject(
            ns=dummy_ns, set_param_func=set_param, get_param_func=get_param
        )

    def test_getting_params(self):

        self.assertEqual(self.param_object.dummy_param, self.param_dict["dummy_param"])
        self.assertEqual(
            self.param_object.outer_dict.inner_param,
            self.param_dict["outer_dict"]["inner_param"],
        )
        self.assertEqual(
            self.param_object.very_outer_dict.inner_dict.very_inner_param,
            self.param_dict["very_outer_dict"]["inner_dict"]["very_inner_param"],
        )

    def test_setting_params(self):
        dummy_value = "value"

        # Test if setting a simple parameter works
        self.param_object.parameter1 = dummy_value
        self.assertEqual(self.last_key, "ns/parameter1")
        self.assertEqual(self.last_val, dummy_value)

        self.param_object.outer_dict.inner_param = dummy_value
        self.assertEqual(self.last_key, "ns/outer_dict/inner_param")
        self.assertEqual(self.last_val, dummy_value)

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


import sys
sys.path.insert(0,'../')
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import cv2

from epochs import create_epoch, create_file_info_df, parse_dicom_file, parse_contour_file, poly_to_mask

class check_file_info_outputs():
    """
    This checks that the file inputs and outputs are as expected. Currently, this uses visual
    inspection of the outputs to verify that the contours are what they should be. With more time,
    a testing framework with setup/teardown would have examples of images with known masks
    (e.g. a square region) and compare the values created by the mask.
    """
    def __init__(self, all_files_dir):
        self.all_files_dir = all_files_dir
        self.file_info_df = create_file_info_df(all_files_dir)

    def save_input_and_target_files(self):
        """
        This function saves the input and target files in directories with matching image names, in order to check that
        the inputs and target files are as expected. Once the files are exported, these can be visually inspected.
        :return: folders containing input and target files
        """
        input_dir = os.path.join(self.all_files_dir,'inputs')
        target_dir = os.path.join(self.all_files_dir,'targets')

        if os.path.isdir(input_dir):
            shutil.rmtree(input_dir)
        os.mkdir(input_dir)

        if os.path.isdir(target_dir):
            shutil.rmtree(target_dir)
        os.mkdir(target_dir)

        for idx, row in self.file_info_df.iterrows():
            dicom_img = parse_dicom_file(row.dicom_file_name_with_path)
            img_mask = poly_to_mask(row.o_coords, dicom_img.shape[0], dicom_img.shape[1])
            cv2.imwrite(os.path.join(input_dir,'patient'+str(row.patient_num)+'image'+str(row.image_num)+'.png'),dicom_img)
            cv2.imwrite(os.path.join(target_dir, 'patient' + str(row.patient_num) + 'image' + str(row.image_num) + '.png'),255*img_mask.astype(int))

    def save_images_with_masks(self,annotated_images_dir='test_image_matching'):
        """
        This function saves the input and target images alongside
        each other in order to verify that they match.
        :param annotated_images_dir: Directory containing the annotated images
        :return:images outlined with the contours alongside the masks
        """
        saved_images_dir = annotated_images_dir
        if os.path.isdir(saved_images_dir):
            shutil.rmtree(saved_images_dir)
        os.mkdir(saved_images_dir)

        for idx, row in self.file_info_df.iterrows():
            dicom_img = parse_dicom_file(row.dicom_file_name_with_path)
            img_mask_o = poly_to_mask(row.o_coords, dicom_img.shape[0], dicom_img.shape[1])
            img_mask_i = poly_to_mask(row.i_coords, dicom_img.shape[0], dicom_img.shape[1])
            fig, ax = plt.subplots(1, 3, figsize=(15, 5))
            ax[0].imshow(dicom_img, cmap='gray')
            ax[0].plot(np.array(row.o_coords)[:, 0], np.array(row.o_coords)[:, 1], 'r')
            ax[0].plot(np.array(row.i_coords)[:, 0], np.array(row.i_coords)[:, 1], 'r')
            ax[0].axis('off')
            ax[1].imshow(img_mask_o, cmap='gray')
            ax[1].axis('off')
            ax[2].imshow(img_mask_i, cmap='gray')
            ax[2].axis('off')
            plt.savefig(os.path.join(saved_images_dir, 'patient' + str(row.patient_id) + 'image' + str(int(row.image_num)) + '.png'))
            plt.close()

    def export_image_info(self,csv_filename='file_info.csv'):
        self.file_info_df.to_csv(csv_filename)

def check_epochs(filename,out_dir = 'test_epoch_dir'):
    """
    This checks that the batches are being generated properly by
    saving the batches into folders with images and masks. Once the files
    are exported, these can be visually inspected.
    :param filename: top-level directory name
    :param out_dir: output directory containing the image/mask files
    """
    if os.path.isdir(out_dir):
        shutil.rmtree(out_dir)
    os.mkdir(out_dir)
    epoch = create_epoch(filename)
    images, targets = epoch.get_current_batch()
    batch_num = 0
    while images is not None:
        images, targets = epoch.get_current_batch()
        if images is not None:
            os.mkdir(os.path.join(out_dir,str(batch_num)))
            os.mkdir(os.path.join(out_dir, str(batch_num),'images'))
            os.mkdir(os.path.join(out_dir, str(batch_num),'targets'))
            for image_num in range(images.shape[0]):
                cv2.imwrite(os.path.join(out_dir, str(batch_num),'images','image'+str(image_num)+'.jpg'),images[image_num,:,:])
                cv2.imwrite(os.path.join(out_dir, str(batch_num), 'targets', 'target' + str(image_num) + '.jpg'),
                            targets[image_num, :, :]*255)
            batch_num += 1

if __name__=="__main__":
    C = check_file_info_outputs('../final_data')
    C.save_images_with_masks(annotated_images_dir='test_image_matching')
    C.save_input_and_target_files()
    C.export_image_info()
    check_epochs('../final_data')


#!/usr/bin/env python3

import json
import os
import sys

PRODUCTS_DIR = "products"
SOURCES = "../../hw/addr_sel.vhd  ../../hw/dmuxn.vhd  ../../hw/efuse_bank.vhd  ../../hw/efuse_ctrl.vhd  ../../hw/efuse_rom.vhd"
TOP = "efuse_ctrl"

VERILOG = TOP + "_fromvhdl.v"
MACRO_DIR = "../../macros"
CELLS = MACRO_DIR + "/cells.v"
BBOX = MACRO_DIR + "/efuse_array"
OL_CFG = "config.json"
PDN_CFG = "../pdn_cfg.tcl"
PIN_CFG = "../pin.cfg"
MACRO_FILE = "macro_placement.cfg"

SIZE_X          = 2175
SIZE_Y          = 2370
MACRO_OFF_X     = 40
MACRO_OFF_Y     = 60
MACRO_STEP_X    = 88
MACRO_STEP_Y    = 760
MACRO_X         = 24
MACRO_Y         = 3

PDN_HOR_START   = 42
PDN_HOR_WDT     = 15
PDN_HOR_STEP    = 45
M5_OBS_DELTA    = 0
M5_OBS_SIDES    = 10

MACRO_FORMAT = "efuse_rom_inst.gen_efuse_banks:{i}.efuse_bank_inst.efuse_array_inst"

# Go to directory for implementation files
os.system("mkdir -p " + PRODUCTS_DIR)
os.chdir(PRODUCTS_DIR)

# Generate macro placement
f = open(MACRO_FILE, "w")

for y in range(MACRO_Y):
    for x in range(MACRO_X):
        line = MACRO_FORMAT.format(i=y*MACRO_X + x + 1)
        line += " " + str(MACRO_OFF_X + x*MACRO_STEP_X) + " " + str(MACRO_OFF_Y + y*MACRO_STEP_Y) + " N"
        print(line, file=f)

# Generate Met5 obstruction for top PDN
obs = ""
obs_lef = ""
y = PDN_HOR_START
y_prev = 0
while y < SIZE_Y:
    y0 = y-PDN_HOR_WDT/2
    y1 = y+PDN_HOR_WDT/2
    obs += "Metal5 0 {y0} {x1} {y1}, ".format(y0 = y0, x1 = SIZE_X, y1 = y1)
    obs_lef += "        RECT {x0} {y0} {x1} {y1} ;\n".format(x0 = M5_OBS_SIDES, y0 = y_prev-M5_OBS_DELTA, x1 = SIZE_X-M5_OBS_SIDES, y1 = y0+M5_OBS_DELTA)
    y_prev = y1
    y += PDN_HOR_STEP

# Create config dict
config = {
    "DESIGN_NAME" : TOP,
    "VERILOG_FILES" : VERILOG + " " + CELLS,
    "DESIGN_IS_CORE" : 0,
    "FP_SIZING" : "absolute",
    "DIE_AREA" : "0 0 " + str(SIZE_X) + " " + str(SIZE_Y),
    "SYNTH_STRATEGY" : "AREA 3",
    "PL_TARGET_DENSITY" : 0.55,

    "PDN_CFG" : PDN_CFG,
    "FP_TAP_HORIZONTAL_HALO" : 1,
    "FP_PDN_HORIZONTAL_HALO" : 1,
    "FP_PDN_AUTO_ADJUST" : 0,
    "FP_PDN_VOFFSET" : 20,
    "FP_PDN_VPITCH" : 190,
    "FP_PDN_VSPACING" : 8,
    "FP_PIN_ORDER_CFG" : PIN_CFG,

    "PL_MAX_DISPLACEMENT_X" : 2000,
    "PL_MAX_DISPLACEMENT_Y" : 2000,

    "LVS_CONNECT_BY_LABEL" : 1,

    "EXTRA_LEFS" : os.path.abspath(BBOX + ".lef"),
    "EXTRA_GDS_FILES" : os.path.abspath(BBOX + ".gds"),
    # ~ "EXTRA_LIBS" : os.path.abspath(BBOX + ".lib"),
    "VERILOG_FILES_BLACKBOX" : os.path.abspath(BBOX + ".v"),
    "MACRO_PLACEMENT_CFG" : "macro_placement.cfg",

    "ROUTING_CORES" : "24",
    "GRT_ALLOW_CONGESTION" : 1,
    "GRT_OBS" : obs[:-2],

    "CLOCK_PORT" : "wb_clk_i",
    "CLOCK_PERIOD" : 20
}

# Dump config JSON
json.dump(config, open(OL_CFG, "w"), indent=4)

# LEF obstruction needed for chip-level PDN
# ~ print(obs_lef)

# Launch Yosys+GHDL VHDL->Verilog conversion
err = os.system(r'''yosys -m ghdl -p "ghdl -fsynopsys --std=08 --work=efuselib {SOURCES} -e {TOP}; hierarchy -check -top {TOP}; write_verilog {VERILOG}"'''\
    .format(SOURCES=SOURCES, TOP=TOP, VERILOG=VERILOG))
if err != 0:
    sys.exit(err)

# Launch Openlane implementation
os.environ["PDK"] = "gf180mcuC"
os.environ["STD_CELL_LIBRARY"] = "gf180mcu_fd_sc_mcu7t5v0"
err = os.system("flow.tcl -ignore_mismatches -design .")
if err != 0:
    sys.exit(err)


# Quiz description URL:
# https://leetcode.com/problems/most-common-word/

# result
# Runtime: 32 ms, faster than 88.43% of Python3 online submissions for Reorder Data in Log Files.
# Memory Usage: 14.4 MB, less than 63.62% of Python3 online submissions for Reorder Data in Log Files.

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        word_hit = dict()

        paragraph = re.sub('[^a-zA-Z0-9 ]', ' ', paragraph)

        words = [w.lower() for w in paragraph.split()]
        words = [w for w in words if w not in banned]

        max_val = 0
        max_val_key = words[0]

        for w in words:
            if w in banned:
                continue
            else:
                if w in word_hit:
                    word_hit[w] += 1
                    if word_hit[w] > max_val:
                        max_val = word_hit[w]
                        max_val_key = w
                else:
                    word_hit[w] = 1

        return max_val_key

python_algo_interview/ch.6_string_manipulation/ex.4_Most Common Word/ex4_Most Common Word_mytry1.py


#!/usr/bin/env python3

import os

on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'temporal-django'
copyright = '2017, Clover Health Labs, LLC'

version = '0.0.1'
release = version
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

pygments_style = 'sphinx'

if not on_rtd:
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

html_static_path = ['_static']
htmlhelp_basename = 'temporal-djangodoc'


import metview as mv
import numpy as np

# define the curves to be plotted
x = np.arange(-2, 0.6, 0.1)
y = np.exp(x)
y1 = y * 0.7
y2 = y * 1.3

# define area bounded by two curves (y1 and y2)
vis_area = mv.input_visualiser(
    input_plot_type="xy_area",
    input_x_values=x,
    input_y_values=y1,
    input_x2_values=x,
    input_y2_values=y2,
)

# define area style
gr_area = mv.mgraph(
    legend="on",
    graph_type="area",
    graph_line_colour="lavender",
    graph_shade_colour="RGB(0.6888,0.6888,0.8641)",
)

# define curve
vis_curve = mv.input_visualiser(input_x_values=x, input_y_values=y)

# define curve style
gr_curve = mv.mgraph(
    legend="on", graph_type="curve", graph_line_colour="coral", graph_line_thickness=3
)

# define view
view = mv.cartesianview(x_automatic="on", y_min=0, y_max=1.5, subpage_clipping="on")

# define legend
legend = mv.mlegend(
    legend_display_type="disjoint",
    legend_text_font_size=0.4,
    legend_text_composition="user_text_only",
    legend_user_lines=["Area", "Curve"],
)

# define the output plot file
mv.setoutput(mv.pdf_output(output_name="fill_between_curves"))

# generate plot
mv.plot(view, vis_area, gr_area, vis_curve, gr_curve, legend)


import numpy as np

def GetComplex(P,A):

	A2= A**2.0
	tP2 = np.tan(P)**2.0

	a2 = A2/(tP2 + 1)
	b2 = A2 - a2

	c = np.sqrt(a2) + np.sqrt(b2)*1.0j

	return c


from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from api import deps
from schemas import ProductSchema, ProductCreate, ProductUpdate
import crud

router = APIRouter()

@router.get("/", response_model=list)
def get_products(db: Session = Depends(deps.get_db)):
    return crud.product.get_all(db)

@router.get("/{product_id}", response_model=ProductSchema)
def get_product(product_id: int, db: Session = Depends(deps.get_db)):
    product = crud.product.get(db, id=product_id)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Product with ID {product_id} not found",
        )
    return product

@router.post("/", response_model=ProductSchema)
def create_product(product_in: ProductCreate, db: Session = Depends(deps.get_db)):
    product = crud.product.create(db, obj_in=product_in)
    return product

@router.put("/{product_id}", response_model=ProductSchema)
def update_product(
    product_id: int, product_in: ProductUpdate, db: Session = Depends(deps.get_db)
):
    product = crud.product.get(db, id=product_id)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Product with ID {product_id} not found",
        )
    return crud.product.update(db, db_obj=product, obj_in=product_in)

@router.delete("/{product_id}", response_model=bool)
def remove_product(product_id: int, db: Session = Depends(deps.get_db)):
    product = crud.product.get(db, id=product_id)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Product with ID {product_id} not found",
        )
    return crud.product.remove(db, obj=product)


import os
from auxfuncs import*

path = os.getcwd() + "/elecfiles/"

def checkVoter(cmd, addr):

	lengh = len(cmd)

	if lengh>=1:

		#INFO
		if cmd[0] == "info" and lengh == 1:
			return info("all", 0, addr)
		elif cmd[0] == "info" and lengh == 2:
			if cmd[1] == "-help":
				return sendMessage(helpTextVoter.info, addr)
			else:
				return info("espec", cmd[1], addr)
		elif cmd[0] == "info" and lengh > 2:
			return sendMessage(errors.more, addr)

		if cmd[0] == "vota" and lengh == 2:
			if cmd[1] == "-help":
				return sendMessage(helpTextVoter.vota, addr)
			else:
				sendMessage(errorsVoter.unknwn, addr)

		if cmd[0] == "vota" and lengh < 4:
			return sendMessage(errorsVoter.less, addr)
		elif cmd[0] == "vota" and lengh > 4:
			return sendMessage(errorsVoter.more, addr)
		elif cmd[0] == "vota" and lengh == 4:
			return votar(cmd[1], cmd[2], cmd[3], addr)
		elif lengh == 1 and cmd[0] == "commands":
			return sendMessage(helpTextVoter.comandos, addr)

		if cmd[0] == "resultados" and lengh == 2 and cmd[1] == "-help":
			return sendMessage(helpTextVoter.resultados, addr)
		elif cmd[0] == "resultados" and lengh == 2 and cmd[1] != "-help":
			return resultado(cmd[1], addr)
		elif cmd[0] == "resultados" and lengh > 2:
			return sendMessage(errorsVoter.more, addr)
		elif cmd[0] == "resultados" and lengh < 2:
			return sendMessage(errorsVoter.less, addr)

		else:
			return sendMessage(errorsVoter.unknwn, addr)
	else:
		return sendMessage(errorsVoter.unknwn, addr)

def candidatoinfo(candidato):
    infocand=candidato.split()
    return infocand

def candidatoIndice(lista, candidato):
	for x in range(len(lista)):
		nome = candidatoinfo(lista[x])
		if nome[0] == str(candidato):
			return x
	return "erro"

#votacao.votos - cc
def votar(votacao, cc, candidato, addr):
	if votacao_existe(votacao, addr) and cc_val(cc, votacao, addr) and cc_unico(cc, votacao, addr) and candidato_val(votacao, candidato, addr):
		print("true \n")
		#votos = ficheiroToList(votacao + ".votes")

		if not os.path.exists(path + votacao + ".votes"):
			return sendMessage(errors.Voter.corr, addr)

		candidatos = ficheiroToList(votacao + ".votes")
		print(candidatos)
		indice = candidatoIndice(candidatos, candidato)
		print(indice)
		info = candidatoinfo(candidatos[indice])
		print(info[0] + " , " + info[1])
		#info[0] = nome info[1]+votos
		info[1] = int(info[1])
		info[1] += 1
		act = info[0] + " " + str(info[1])
		candidatos[indice] = act

		if not os.path.exists(path + "votacoes.txt"):
			return sendMessage(errors.Voter.corr, addr)
		actual = open(path + votacao + ".votes", "w")
		for x in range(len(candidatos)):
		    actual.write(str(candidatos[x]) + "\n")

		if not os.path.exists(path + votacao + ".cc"):
			return sendMessage(errors.Voter.corr, addr)
		votos = open(path + votacao + ".cc", "a")
		votos.write(str(cc) + "\n")

		send = "Voto contabilizado!"
		return sendMessage(send, addr)

def votacao_existe(votacao, addr):
	if os.path.exists(path + "votacoes.txt"):
		lista = ficheiroToList("votacoes.txt")
		if str(votacao + " 1") in lista:
			return True
		else:
			return sendMessage(errorsVoter.voteinv, addr)
	else:
		return sendMessage(errorsVoter.corr, addr)

def votacao_concluida(votacao, addr):
	if os.path.exists(path + "votacoes.txt"):
		lista = ficheiroToList("votacoes.txt")
		if str(votacao + " 2") in lista:
			return True
		else:
			return sendMessage(errorsVoter.voteinv, addr)
	else:
		return sendMessage(errorsVoter.corr, addr)

def cc_unico(cc, votacao, addr):
    lista = ficheiroToList(votacao + ".cc")
    if str(cc) in lista:
    	return sendMessage(errorsVoter.revote, addr)
    else:
    	return True

def cc_val(cc, votacao, addr):
    try:
      int(cc)
      if len(str(cc))==8:
        return True
      else:
        sendMessage(errorsVoter.ccinv, addr)
    except:
      return sendMessage(errorsVoter.ccinv, addr)

def candidato_val(votacao, candidato, addr):
    lista = ficheiroToList(votacao + ".candidates")
    if str(candidato) in lista:
    	return True
    else:
    	return sendMessage(errorsVoter.candinv, addr)

def votacaoNome(votacao):
	return str(votacao[0:len(votacao)-2])

def votacaoEstado(votacao):
	return str(votacao[-1])

def createInfo(vot):
	part = color.BOLD + votacaoNome(vot)+ color.END + "\n-"
	if votacaoEstado(vot) == "0":
		part += "Criada\n"
	elif votacaoEstado(vot) == "1":
		part += color.BOLD + color.YELLOW + "Aberta\n" + color.END
	elif votacaoEstado(vot) == "2":
		part += "Fechada\n"
	return part

def info(tipo, nome, addr):
	#import server
	if str(tipo) == "all":
		send = "\n\n"
		lista = ficheiroToList("votacoes.txt")

		if len(lista) == 1:
			send += createInfo(lista[0]) + "\n"
		else:
			for x in range(len(lista)):
				send += createInfo(lista[x]) + "\n"
		return sendMessage(send, addr)

	elif str(tipo) == "espec":

		lista = ficheiroToList("votacoes.txt")
		indice = votacaoIndice(lista, nome)
		if indice == "erro":
			return sendMessage(errorsManager.voteinexist, addr)
		send = "\n\n\n"
		send += createInfo(lista[indice]) + "\n"
		return sendMessage(send, addr)

def resultado(nome, addr):
	send = "\nOs resultados para a votacao " + nome + " sao:\n\n"
	if votacao_concluida(nome, addr):
		file = open(path + nome + ".votes", "r")
		send += file.read()
		sendMessage(send, addr)
	else:
		return sendMessage(errorsVoter.voteinv, addr)

	'''

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

#Variaveis de teste

votacoes_existentes=['Benfica', 'Sporting']

candidatos=['candA', 'candB']

dados={'Benfica':[88888888,11111111],'Sporting':[]}

reg={'candA':1, 'candB':0}

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

#FUNCOES

def votacao_existe(v):							#verifica se a votacao existe
	return v in votacoes_existentes

#def votacao_aberta(v):

def cc_val(id):								#verifica se a identificacao e valida
	return isinstance(id,str) and len(id)==8

def candidato_val(cand):						#verifica se o candidato existe na votacao
	return cand in candidatos

def resultados_finais(votacao):
	#if votacao_aberta==False:
	return reg

	'''