#from __future__ import print_function
import cv2
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torchnet.meter as meter
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
from dataset import multiPIE
from siamese_model_2nd import Siamese
from contrastive import ContrastiveLoss
import numpy as np
# import cv2
#from pycrayon import CrayonClient

#for plotting loss
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import time,math
from logger import Logger
# from models_Parsing import ParseNet
saveFile = open('/home/shumao/wyw_files/siamese_output_M_3/record.txt', 'w')
saveFile.write("niter:" + str(50000) + "\n")
saveFile.write("---lr:" + str(0.0001) + "\n")
saveFile.write("beta1:" + str(0.7) + "\n")
saveFile.write("W:-1-x-x-x-x-x-" + "\n")
saveFile.write("L1 Loss" + "\n")
saveFile.write("after load model from: train-3-28000pth")
logger = Logger('./log_1');

parser = argparse.ArgumentParser()
parser.add_argument('--batchSize', type=int, default=64, help='input batch size')
parser.add_argument('--loadSize', type=int, default=100, help='the height / width of the input image to network')
parser.add_argument('--fineSize', type=int, default=96, help='the height / width of the input image to network')
parser.add_argument('--id_num', type=int, default=200, help='Total training identity.')
parser.add_argument('--pose_num', type=int, default=9, help='Total training pose.')
parser.add_argument('--light_num', type=int, default=20, help='Total training light.')
parser.add_argument('--niter', type=int, default=50000, help='number of iterations to train for')
parser.add_argument('--lr', type=float, default=0.0001, help='learning rate, default=0.0002')
parser.add_argument('--beta1', type=float, default=0.7, help='beta1 for adam. default=0.7')
parser.add_argument('--cuda', action='store_true', help='enables cuda')
parser.add_argument('--outf', default='/home/shumao/wyw_files/siamese_output_M_3', help='folder to output images and model checkpoints')
parser.add_argument('--manualSeed', type=int, help='manual seed')
parser.add_argument('--dataPath', default='/home/shumao/dr-gan/Data_new_realigned2/setting2/train/', help='which dataset to train on')
parser.add_argument('--modelPath', default='/home/shumao/wyw_files/siamese_output_3/netS_28000.pth', help='which dataset to train on')
parser.add_argument('--save_step', type=int, default=400, help='save weights every 400 iterations ')
parser.add_argument('--labelPath', default='/home/shumao/dr-gan/Data_new_realigned2/setting2/Facedata/', help='which dataset to train on')

opt = parser.parse_args()
print(opt) # print every parser arguments
# print(opt.niter)

try:
    os.makedirs(opt.outf)
except OSError:
    pass

w_r = 1
# w_cL = 0.02
# w_cP = 0.02
# w_cI = 0.02
# w_P = 0.02
# w_L = 0.02

if opt.manualSeed is None:
    opt.manualSeed = random.randint(1, 10000)
print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
if opt.cuda:
    torch.cuda.manual_seed_all(opt.manualSeed)

cudnn.benchmark = True
#---------------------Load Mask-------------------
mask = np.load('mask_20.npy')
mask = mask.astype(np.float32)
M = torch.from_numpy(mask.transpose((2, 0, 1)))
FinalMask = M.expand(opt.batchSize,3,96,96)
# print m.size()
# 3x96x96

#---------------------Load DATA-------------------------
dataset_1 = multiPIE(opt.dataPath,opt.loadSize,opt.fineSize,labelPath = opt.labelPath)
# dataset_2 = multiPIE(opt.dataPath,opt.loadSize,opt.fineSize,opt.labelPath)
dataset_test = multiPIE('/home/shumao/dr-gan/comparison/',opt.loadSize,opt.fineSize,labelPath = opt.labelPath)
loader_train_1 = torch.utils.data.DataLoader(dataset=dataset_1,
                                      batch_size = opt.batchSize,
                                      shuffle=True,
                                      num_workers=4,
                                      drop_last = True)
# loader_train_2 = torch.utils.data.Dataloader(dataset=dataset_1,
#                                       batch_size = opt.batchSize,
#                                       shuffle=True,
#                                       num_workers=4)

loader_test = torch.utils.data.DataLoader(dataset=dataset_test,
                                          batch_size = 9,
                                          shuffle=False,
                                          num_workers=4)
data_train_1 = iter(loader_train_1)
# data_train_2 = iter(loader_train_2)
data_test = iter(loader_test)

#----------------------Parameters-----------------------
num_pose = opt.pose_num
num_light = opt.light_num
num_iden = opt.id_num

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') !=-1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') !=-1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

netS = Siamese()
netS.load_state_dict(torch.load(opt.modelPath))

#-----------------params freeze-----------------
for param in netS.conv11.parameters():
    param.requires_grad = False
for param in netS.conv1r.parameters():
    param.requires_grad = False
for param in netS.conv12.parameters():
    param.requires_grad = False
for param in netS.conv21.parameters():
    param.requires_grad = False
for param in netS.conv22.parameters():
    param.requires_grad = False
for param in netS.conv23.parameters():
    param.requires_grad = False
for param in netS.conv31.parameters():
    param.requires_grad = False
for param in netS.conv32.parameters():
    param.requires_grad = False
for param in netS.conv33.parameters():
    param.requires_grad = False
for param in netS.conv41.parameters():
    param.requires_grad = False
for param in netS.conv42.parameters():
    param.requires_grad = False
for param in netS.conv43.parameters():
    param.requires_grad = False
for param in netS.conv51.parameters():
    param.requires_grad = False
for param in netS.conv52.parameters():
    param.requires_grad = False
for param in netS.conv53.parameters():
    param.requires_grad = False
for param in netS.convfc.parameters():
    param.requires_grad = False

#-----------------params freeze-----------------
if(opt.cuda):
    netS.cuda()

#-------------------Loss & Optimization

optimizerS = torch.optim.Adam(filter(lambda p: p.requires_grad, netS.parameters()),lr=opt.lr, betas=(opt.beta1, 0.999))

poss_contrastive_loss = ContrastiveLoss() # load from the begining
light_contrastive_loss = ContrastiveLoss()
identity_contrastive_loss = ContrastiveLoss()
reconstructe_loss = nn.L1Loss()
pose_class_loss = nn.CrossEntropyLoss()
light_class_loss = nn.CrossEntropyLoss()

#------------------ Global Variables------------------
input_pose_1 = torch.LongTensor(opt.batchSize)
input_light_1 = torch.LongTensor(opt.batchSize)
# input_pose_2 = torch.LongTensor(opt.batchSize)
# input_light_2 = torch.LongTensor(opt.batchSize)

inputImg_1 = torch.FloatTensor(opt.batchSize, 3, opt.fineSize, opt.fineSize)
inputImg_2 = torch.FloatTensor(opt.batchSize, 3, opt.fineSize, opt.fineSize)
GT = torch.FloatTensor(opt.batchSize, 3,opt.fineSize, opt.fineSize)
same_pose = torch.FloatTensor(opt.batchSize)
same_iden = torch.FloatTensor(opt.batchSize)
same_light = torch.FloatTensor(opt.batchSize)

# w_1 = torch.FloatTensor(1)
# w_2 = torch.FloatTensor(20)
# w_3 = torch.FloatTensor(10)
# w_4 = torch.FloatTensor(10)
# w_5 = torch.FloatTensor(10)
# w_6 = torch.FloatTensor(20)
# output_pose_1_label = torch.LongTensor(opt.batchSize)
# output_pose_2_label = torch.LongTensor(opt.batchSize)
# output_light_1_label = torch.LongTensor(opt.batchSize)
# output_light_2_label = torch.LongTensor(opt.batchSize)

input_pose_1 = Variable(input_pose_1)
# input_pose_2 = Variable(input_pose_2)
input_light_1 = Variable(input_light_1)
# input_light_2 = Variable(input_light_2)

inputImg_1 = Variable(inputImg_1)
inputImg_2 = Variable(inputImg_2)
GT = Variable(GT)
same_pose = Variable(same_pose)
same_iden = Variable(same_iden)
same_light = Variable(same_light)

FinalMask = Variable(FinalMask)

# w_1 = Variable(w_1, requires_grad = False)
# w_2 = Variable(w_2, requires_grad = False)
# w_3 = Variable(w_3, requires_grad = False)
# w_4 = Variable(w_4, requires_grad = False)
# w_5 = Variable(w_5, requires_grad = False)
# w_6 = Variable(w_6, requires_grad = False)

pose_mtr = meter.ConfusionMeter(k=opt.pose_num)
light_mtr = meter.ConfusionMeter(k=opt.light_num)

if(opt.cuda):

    input_pose_1 = input_pose_1.cuda()
    # input_pose_2 = input_pose_2.cuda()
    input_light_1 = input_light_1.cuda()
    # input_light_2 = input_light_2.cuda()
    inputImg_1 = inputImg_1.cuda()
    inputImg_2 = inputImg_2.cuda()
    GT = GT.cuda()
    same_pose = same_pose.cuda()
    same_light = same_light.cuda()
    same_iden = same_iden.cuda()

    FinalMask = FinalMask.cuda()

    # w_1 = w_1.cuda()
    # w_2 = w_1.cuda()
    # w_3 = w_1.cuda()
    # w_4 = w_1.cuda()
    # w_5 = w_1.cuda()
    # w_6 = w_1.cuda()
    # poss_contrastive_loss.cuda()
    # light_contrastive_loss.cuda()
    # identity_contrastive_loss.cuda()
    pose_class_loss.cuda()
    light_class_loss.cuda()
    reconstructe_loss.cuda()

#------------------test---------

# k = 0 # for meter

err_total = 0
err_recon = 0
err_contraL = 0
err_contraP = 0
err_contraI = 0
err_classP = 0
err_classL = 0

def test(iteration, data_test, loader_test):
    try:
        images_1,po_1,li_1,GT_1,by_image,same_po,same_li,same_id = data_test.next()
    except StopIteration:
        data_test = iter(loader_test)
        images_1,po_1,li_1,GT_1,by_image,same_po,same_li,same_id = data_test.next()

    GT.data.resize_(GT_1.size()).copy_(GT_1)
    inputImg_1.data.resize_(images_1.size()).copy_(images_1)
    inputImg_2.data.resize_(by_image.size()).copy_(by_image)
    input_pose_1.data.resize_(po_1.size()).copy_(po_1)
    input_light_1.data.resize_(li_1.size()).copy_(li_1)

    output_pose_1, output_pose_2, output_light_1, output_light_2, out_f_1, out_f_2, out = netS(inputImg_1, inputImg_2)
    vutils.save_image(out.data,
        '%s/fake_samples_iteration_%03d.png' % (opt.outf, iteration), normalize=True)
    vutils.save_image(inputImg_1.data,
            '%s/input_samples_iteration_%03d.png' % (opt.outf, iteration), normalize=True)

#-------------------train----------------------
for iteration in range(1,opt.niter+1):
    running_corrects = 0
    running_corrects_light = 0
    try:
        images_1,po_1,li_1,GT_1,by_image,same_po,same_li,same_id= data_train_1.next()
    except StopIteration:
        data_train_1 = iter(loader_train_1)
        images_1,po_1,li_1,GT_1,by_image,same_po,same_li,same_id = data_train_1.next()

    GT.data.resize_(GT_1.size()).copy_(GT_1)

    inputImg_1.data.resize_(images_1.size()).copy_(images_1)
    inputImg_2.data.resize_(by_image.size()).copy_(by_image)

    input_pose_1.data.resize_(po_1.size()).copy_(po_1)
    input_light_1.data.resize_(li_1.size()).copy_(li_1)

    same_pose.data.resize_(same_po.size()).copy_(same_po)
    same_light.data.resize_(same_li.size()).copy_(same_li)
    same_iden.data.resize_(same_id.size()).copy_(same_id)
    netS.zero_grad()

    output_pose_1, output_pose_2, output_light_1, output_light_2, out_f_1, out_f_2, out = netS(inputImg_1, inputImg_2)
    #-----------------mask test area-----------------------------
    # print out.data.type()
    # print GT.data.type()
    # print FinalMask.data.type() same
    # print FinalMask.data.size() 64x3x96x96
    # print FinalMask.data.size()
    # print out.data.size()

    Final_out = FinalMask * out

    Final_GT = FinalMask * GT

    #-----------------mask test area-----------------------------
    # f_1 & f_2 variable
    # same_iden variable
    err_recon = reconstructe_loss(Final_out, Final_GT)
    err_contraI = identity_contrastive_loss(out_f_1, out_f_2, same_iden)
    err_contraP = poss_contrastive_loss(output_pose_1, output_pose_2, same_pose)
    err_contraL = light_contrastive_loss(output_light_1,output_light_2, same_light)
    err_classL = light_class_loss(output_light_1, input_light_1)
    err_classP = pose_class_loss(output_pose_1, input_pose_1)
    # print(err_recon.data.size())
    # print(err_contraL.data.size())
    # print(err_classP.data.size())
    # modify the contrastive loss function to make contrastive loss be 1Lx1L
    # contrastive loss and Softmax and Loss1 are all requires_grad
    # err_total = 1 * err_recon + 10 * err_contraP + 10 * err_contraI + 10 * err_classP + 20 * err_classL
    # err_total = err_recon + err_contraI + err_contraP + err_contraL + err_classL + err_classP
    err_total = w_r * err_recon
    err_total.backward()
    optimizerS.step()

    #----------------------Visualize-----------
    if(iteration % 200 == 0):

        pose_mtr.add(output_pose_1.data, input_pose_1.data)
        pose_trainacc = pose_mtr.value().diagonal().sum()*1.0/opt.batchSize
        pose_mtr.reset()

        light_mtr.add(output_light_1.data, input_light_1.data)
        light_trainacc = light_mtr.value().diagonal().sum()*1.0/opt.batchSize
        light_mtr.reset()
        #-----------------------------------------
        test(iteration, data_test, loader_test)
    # #pose prediction

    # preds_pose = torch.max(output_pose_1.data, 1)
    # running_corrects += torch.sum(preds == input_pose_1)
    # print('pose_accuracy: %.2f'
    #         % (running_corrects * 1.0/images.size(0)))

    # #light prediction
    # preds_light = torch.max(output_light_1.data, 1)
    # running_corrects_light += torch.sum(preds_light == input_light_1)
    # print('light_accuracy: %.2f'
    #         % (running_corrects_light * 1.0/images.size(0)))

    print('----------------------------------------')
    print('[%d/%d] Loss_S: %.4f ' %(iteration, opt.niter, err_total.data[0]))
    print('        Reco_S: %.4f ' %(err_recon.data[0]))
    print('        conL_S: %.4f ' %(err_contraL.data[0]))
    print('        conP_S: %.4f ' %(err_contraP.data[0]))
    print('        conI_S: %.4f ' %(err_contraI.data[0]))
    print('        Clas_P: %.4f ' %(err_classP.data[0]))
    print('        Clas_L: %.4f ' %(err_classL.data[0]))

    if(iteration % opt.save_step == 0):
        torch.save(netS.state_dict(), '%s/netS_%d.pth' % (opt.outf,iteration))


#--coding:utf-8

__author__ = 'peic'

#------------enum class demo-----------------

from enum import Enum

#继承定义枚举类
class Week(Enum):
    Sunday = 0
    Monday = 1
    Tuesday = 2
    Wednesday = 3
    Thursday = 4
    Friday = 5
    Saturday = 6

#定义枚举类的另一种形式
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

if __name__ == '__main__':
    # Week操作
    day1 = Week.Monday
    print(day1)                 #Week.Monday

    print(Week.Tuesday)
    print(Week['Tuesday'])      #Week.Tuesday

    print(Week(1))              #Week.Monday

    for name, member in Week.__members__.items():
        print('name:%s --> member:%s' %(name, member))

    # Month操作
    print(Month(1))             #Month.Jan

    for name, member in Month.__members__.items():
        print('name:%s --> member:%s' %(name, member))


from lark import Lark
import torch.utils.data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from enum import Enum
import numpy as np
from sklearn.model_selection import train_test_split
from torch.utils.tensorboard import SummaryWriter

class lalrDataset(torch.utils.data.Dataset):
    """LALR dataset."""

    def __init__(self, lines_s, lines_p):
        self.lines_s=lines_s.copy()
        self.lines_p=lines_p.copy()
        self.length_s=[]
        self.length_p=[]
        for line in self.lines_s:
            self.length_s.append(len(line))
        for line in self.lines_p:
            self.length_p.append(len(line))
        assert self.length_s == self.length_p
        max_lenght = np.max(self.length_s)
        '''sets for chars'''
        self.s_chars = ['_'] + sorted(set(''.join(self.lines_s)))
        self.p_chars = ['_'] + sorted(set(''.join(self.lines_p)))
        ''' padding '''
        for i in range(len(self.lines_s)):
            while len(self.lines_s[i]) < max_lenght+1:
                self.lines_s[i] += '_'
        for i in range(len(self.lines_p)):
            while len(self.lines_p[i]) < max_lenght+1:
                self.lines_p[i] += '_'
        ''' int2chars and chars2int dictionaries '''
        self.int2s_char = enumerate(self.s_chars)
        self.s_char2int = {char: ind for ind, char in self.int2s_char}
        self.s_int2char = {self.s_char2int[char]: char for char in self.s_char2int}
        self.int2p_char = enumerate(self.p_chars)
        self.p_char2int = {char: ind for ind, char in self.int2p_char}
        ''' creating index value arrays'''
        input_seq = []
        target_seq = []
        for i in range(len(self.lines_p)):
            input_seq.append([self.p_char2int[character] for character in self.lines_p[i]])
            target_seq.append([self.s_char2int[character] for character in self.lines_s[i]])
        '''one hot encoding'''
        dict_size = len(self.p_char2int)
        seq_len = max_lenght+1
        batch_size = len(self.lines_p)
        self.input_seq = self.one_hot_encode(input_seq, dict_size, seq_len, batch_size)
        self.input_seq=torch.tensor(self.input_seq).cuda(0)
        dict_size = len(self.s_char2int)
        self.target_seq = self.one_hot_encode(target_seq, dict_size, seq_len, batch_size)
        self.target_seq=torch.tensor(self.target_seq).cuda(0)

    def __len__(self):
        return self.input_seq.shape[0]

    def __getitem__(self, idx):
        return [self.input_seq[idx],self.target_seq[idx],]

    def lastpadindex(self,batch):
        "I'm sure there's a more clever way to do this.."
        input = batch[0]
        target = batch[1]
        for i in range(input.shape[1]):
            if (input[:, i].equal(input[:, -1])):
                return input[:, :i + 1], target[:, :i + 1]
        return input, target
    def get_s_chars(self):
        return set(self.s_chars)
    def get_s_char2int(self):
        return self.s_char2int
    def get_tokenmap(self):
        return [self.s_int2char[i] for i in sorted(self.s_int2char.keys())]
    def one_hot_encode(self,sequence, dict_size, seq_len, batch_size):
        ''' Creating a multi-dimensional array of zeros with the desired output shape '''
        features = np.zeros((batch_size, seq_len, dict_size), dtype=np.float32)

        ''' Replacing the 0 at the relevant character index with a 1 to represent that character '''
        for i in range(batch_size):
            for u in range(seq_len):
                features[i, u, sequence[i][u]] = 1
        return features

class EncoderRNN(nn.Module):
    def __init__(self, input_size, hidden_size):
        super(EncoderRNN, self).__init__()
        self.hidden_size = hidden_size
        self.gru = nn.GRU(input_size, hidden_size, batch_first=True,bidirectional=True)

    def forward(self, input):
        output, hidden = self.gru(input)
        return output, hidden

    def reinit(self):
        '''Reinitialize weights'''

        def weights_init(l):
            if hasattr(l, 'weight') and isinstance(l.weight, torch.Tensor):
                nn.init.xavier_uniform_(l.weight.data)
            if hasattr(l, 'bias') and isinstance(l.bias, torch.Tensor):
                nn.init.uniform_(l.bias)

        self.apply(weights_init)

'''5s_rna_data files'''
with open("/home/rishal/lalrnn/5s_data/5s_shortlisted/dbn_can.txt") as f:
    lines_s_5srna = [line.strip() for line in f.readlines()]
with open("/home/rishal/lalrnn/5s_data/5s_shortlisted/seq_can.txt") as f:
    lines_p_5srna = [line.strip() for line in f.readlines()]
f.close()

lines_p_5srna_train1, lines_p_5srna_test, lines_s_5srna_train1, lines_s_5srna_test = train_test_split(lines_p_5srna, lines_s_5srna, test_size=0.1, random_state=42)
lines_p_5srna_train, lines_p_5srna_val, lines_s_5srna_train, lines_s_5srna_val = train_test_split(lines_p_5srna_train1, lines_s_5srna_train1, test_size=0.22, random_state=42)

'''srp_rna_data files'''
with open("/home/rishal/lalrnn/srp_data/srp_shortlisted/dbn_can.txt") as f:
    lines_s_srprna = [line.strip() for line in f.readlines()]
with open("/home/rishal/lalrnn/srp_data/srp_shortlisted/seq_can.txt") as f:
    lines_p_srprna = [line.strip() for line in f.readlines()]
f.close()

lines_p_srprna_train1, lines_p_srprna_test, lines_s_srprna_train1, lines_s_srprna_test = train_test_split(lines_p_srprna, lines_s_srprna, test_size=0.1, random_state=42)
lines_p_srprna_train, lines_p_srprna_val, lines_s_srprna_train, lines_s_srprna_val = train_test_split(lines_p_srprna_train1, lines_s_srprna_train1, test_size=0.22, random_state=42)

'''trna_data files'''
with open("/home/rishal/lalrnn/trna_data/trna_shortlisted/dbn_can.txt") as f:
    lines_s_trna = [line.strip() for line in f.readlines()]
with open("/home/rishal/lalrnn/trna_data/trna_shortlisted/seq_can.txt") as f:
    lines_p_trna = [line.strip() for line in f.readlines()]
f.close()

lines_p_trna_train1, lines_p_trna_test, lines_s_trna_train1, lines_s_trna_test = train_test_split(lines_p_trna, lines_s_trna, test_size=0.1, random_state=42)
lines_p_trna_train, lines_p_trna_val, lines_s_trna_train, lines_s_trna_val = train_test_split(lines_p_trna_train1, lines_s_trna_train1, test_size=0.22, random_state=42)

for i in range(len(lines_s_trna_test)):
    if i==36:
        print(lines_s_trna_test[i],lines_p_trna_test[i])

grammar='''?e: DOT
 | LPARENA RPARENU
 | LPARENC RPARENG
 | LPARENG RPARENC
 | LPARENG RPARENU
 | LPARENU RPARENG
 | LPARENU RPARENA
 | e LPARENA e RPARENU
 | e LPARENC e RPARENG
 | e LPARENG e RPARENC
 | e LPARENG e RPARENU
 | e LPARENU e RPARENG
 | e LPARENU e RPARENA
 | e DOT
 | LPARENA e RPARENU
 | LPARENC e RPARENG
 | LPARENG e RPARENC
 | LPARENG e RPARENU
 | LPARENU e RPARENG
 | LPARENU e RPARENA
 | e LPARENA RPARENU
 | e LPARENC RPARENG
 | e LPARENG RPARENC
 | e LPARENG RPARENU
 | e LPARENU RPARENG
 | e LPARENU RPARENA
DOT: "."
LPARENA: "A"
LPARENC: "C"
LPARENG: "G"
LPARENU: "U"
RPARENA: "a"
RPARENC: "c"
RPARENG: "g"
RPARENU: "u"
'''
test_data=lalrDataset(lines_s_srprna_test,lines_p_srprna_test)
testloader = torch.utils.data.DataLoader(test_data, batch_size=1, shuffle=False, num_workers=0)
parser = Lark(grammar, start='e', parser='lalr')
tokenmap = [str(t.pattern).replace(r'\\', '').strip("'") for t in parser.terminals]
tokenmap.append("_")
assert set(tokenmap)==test_data.get_s_chars()
tokenmap=test_data.get_tokenmap()

from lalrnn_all_lets import SimpleGenerativeLALRNN
#decoder = DecoderRNN(100,4)
decoder = SimpleGenerativeLALRNN(grammar, 'e', tokenmap, '_', test_data.get_s_char2int())
encoder = EncoderRNN(5,300)
encoder.cuda(0)
decoder.cuda(0)

checkpoint=torch.load('/home/rishal/lalrnn/lets_l300_bi_dropout2_wd1e5_best.pth.tar')
encoder.load_state_dict(checkpoint['encoder_state_dict'])
decoder.load_state_dict(checkpoint['decoder_state_dict'])

ppv_list=[]
sensitivity_list=[]
valid_num=0
lalrnn=True
for i, data in enumerate(testloader):
    if lalrnn==True:
        decoder.set_test()
        decoder.eval()
        if i==36:
            print('lol')
        input,target = test_data.lastpadindex(data)
        encoder_outputs, encoder_hidden = encoder(input)
        encoder_hidden = (encoder_hidden[0] +
                          encoder_hidden[1])
        decoder_input=target
        #encoder_hidden = encoder_hidden.squeeze(0)
        decoder_hidden = encoder_hidden
        decoder_output, _ = decoder(decoder_input, decoder_hidden,input)
    else:
        input, target = test_data.lastpadindex(data)
        encoder_outputs, encoder_hidden = encoder(input)
        decoder_output=decoder.predict(encoder_hidden,target.size(1))
    string1=torch.argmax(decoder_output[:, :target.size(1), :], dim=2)
    #print(string1)
    string1=string1.squeeze(0)
    string2=torch.argmax(target,dim=2)
    string2=string2.squeeze(0)
    str1=[]
    str2=[]
    for x in range(len(string1)):
        str1.append(tokenmap[string1[x]])
    str1=''.join(str1)
    print('predicted')
    print(str1)
    for x in range(len(string2)):
        str2.append(tokenmap[string2[x]])
    str2=''.join(str2)
    print('true')
    print(str2)
    str2=str2.replace('_','')
    str1=str1.replace('_','')
    stack_s1 = []
    stack_s2 = []
    pairs_s1 = set()
    pairs_s2 = set()
    str1 = list(str1)
    str2 = list(str2)
    assert len(str1) == len(str2)
    for i in range(len(str1)):
        if str1[i] == '(' or str1[i]=='[' or str1[i]=='{' or str1[i].isupper():
            stack_s1.append(i)
        if str2[i] == '(' or str2[i]=='[' or str2[i]=='{' or str2[i].isupper():
            stack_s2.append(i)
        if str1[i] == ')' or str1[i]==']' or str1[i]=='}' or str1[i].islower():
            pairs_s1.add((stack_s1[-1], i))
            stack_s1.pop()
        if str2[i] == ')'or str2[i]==']' or str2[i]=='}' or str2[i].islower():
            pairs_s2.add((stack_s2[-1], i))
            stack_s2.pop()
    TP = len(pairs_s1 & pairs_s2)
    FP = len(pairs_s1 - pairs_s2)
    FN = len(pairs_s2 - pairs_s1)
    #print(TP,FP,FN)
    if TP+FP==0:
        FP=1
    if TP+FN==0:
        FN=1
    ppv_list.append(TP/(TP+FP))
    #print(ppv_list)
    sensitivity_list.append(TP/(TP+FN))

print('validity ', valid_num/(i+1))
ppv_list=np.array(ppv_list)
sensitivity_list=np.array(sensitivity_list)
f1=(2*ppv_list*sensitivity_list)/(ppv_list+sensitivity_list)
f1=np.nan_to_num(f1)
print('ppv',ppv_list.mean())
print('sensitivity',sensitivity_list.mean())
print('f1',f1.mean())


'''
@Author       : sean cheng
@Email        : aya234@163.com
@CreateTime   : 2018/9/6
@Program      : 欧几里得算法--求两个数的最大公约数算法
'''

def GreatCommonDivisor(a,b):
    if a < b:
        a,b = b,a
    r = 1
    while r !=0:
        r = a % b
        a = b
        b = r
    return a

m = eval(input())
n = eval(input())
print(GreatCommonDivisor(m,n))


# coding:utf-8
__author__ = 'Albert'

from django.conf.urls import patterns, url

from materials import views

materials_views = patterns(
    '',
    url(r'^mis/update/student/materials$',  views.update_student_material),
    url(r'^mis/material/packages$', views.list_material_packages),
    url(r'^mis/set/student/material$', views.set_student_material),
    url(r'^mis/material/upload$', views.material_upload),
    url(r'^mis/material/preview$', views.material_preview),
    url(r'^mis/unfinished/classes$', views.unfinished_classes),
)


import ROOT,math,os
from BaseObject import BaseObject
from mkdir_p import mkdir_p

# ________________________________________________________________________________________________________________________ ||
ROOT.gROOT.SetBatch(ROOT.kTRUE)

# ________________________________________________________________________________________________________________________ ||
hist_cfgs = [
                BaseObject(
                    "ALP_ElEl",
                    cfgs=[ BaseObject(
                            "H-To-ALP-ALP_M"+str(m),
                            inputPath="/home/lucien/AnalysisCode/Higgs/ALP/genproductions/bin/MadGraph5_aMCatNLO/workDir_acc_study_hTOalpalp_eps2e-2_mZd%s/UnpackTarball/cmsgrid_final_lhe.root"%str(m),
                            x_label = str(m)+ "GeV",
                            mass = m,
                            )
                            for m in [4,7,15,20,25,30,33,] ],
                    color = ROOT.kRed,
                    ),
                BaseObject(
                    "ALP_MuMu",
                    cfgs=[ BaseObject(
                            "H-To-ALP-ALP_M"+str(m),
                            inputPath="/home/lucien/AnalysisCode/Higgs/ALP/genproductions/bin/MadGraph5_aMCatNLO/workDir_acc_study_hTOalpalpTOmumu_eps2e-2_mZd%s/UnpackTarball/cmsgrid_final_lhe.root"%str(m),
                            x_label = str(m)+ "GeV",
                            mass = m,
                            )
                            for m in [4,7,15,20,25,30,33,] ],
                    color = ROOT.kOrange,
                    ),
                BaseObject(
                    "Zd_ElEl",
                    cfgs=[ BaseObject(
                            "H-To-Zd-Zd_M"+str(m),
                            inputPath="/home/lucien/AnalysisCode/Higgs/ALP/genproductions/bin/MadGraph5_aMCatNLO/workDir_acc_study_hTOzpzpTO4e_eps2e-2_mZd%s/UnpackTarball/cmsgrid_final_lhe.root"%str(m),
                            x_label = str(m)+ "GeV",
                            mass = m,
                            )
                            for m in [4,7,15,20,25,30,33,] ],
                    color = ROOT.kBlue,
                    ),
                BaseObject(
                    "Zd_MuMu",
                    cfgs=[ BaseObject(
                            "H-To-Zd-Zd_M"+str(m),
                            inputPath="/home/lucien/AnalysisCode/Higgs/ALP/genproductions/bin/MadGraph5_aMCatNLO/workDir_acc_study_hTOzpzpTO4mu_eps2e-2_mZd%s/UnpackTarball/cmsgrid_final_lhe.root"%str(m),
                            x_label = str(m)+ "GeV",
                            mass = m,
                            )
                            for m in [4,7,15,20,25,30,33,] ],
                    color = ROOT.kViolet,
                    ),
                ]
treeName    = "lheEvents_tchan"
histName    = "acc"
n_tot_evts  = 10000.
outputPath  = "/home/lucien/public_html/Higgs/ALP/AcceptanceStudy/2019-11-26_hToXX/plot.pdf"
y_range     = [0.,1.]
selection   = "(massZ2 > %s) && (massZ2 < %s)"
width       = 0.02

# ________________________________________________________________________________________________________________________ ||
mkdir_p(os.path.dirname(outputPath))
c = ROOT.TCanvas()
leg = ROOT.TLegend(0.70,0.65,0.89,0.87)
for i,hist_cfg in enumerate(hist_cfgs):
    hist_cfg.hist = ROOT.TH1D(hist_cfg.name,"",len(hist_cfg.cfgs),-0.5,len(hist_cfg.cfgs)-0.5)
    leg.AddEntry(hist_cfg.hist,hist_cfg.name,"l")
    for ibin,cfg in enumerate(hist_cfg.cfgs):
        f = ROOT.TFile(cfg.inputPath,"READ")
        t = f.Get(treeName)
        #acc = float(t.GetEntries())/float(n_tot_evts)
        selectionStr = selection%(str(cfg.mass*(1.-width)),str(cfg.mass*(1.+width)))
        acc = float(t.GetEntries(selectionStr)/float(n_tot_evts))
        hist_cfg.hist.SetBinContent(ibin+1,acc)
        hist_cfg.hist.SetBinError(ibin+1,math.sqrt(1./float(t.GetEntries())+1./float(n_tot_evts))*acc)
        hist_cfg.hist.GetXaxis().SetBinLabel(ibin+1,cfg.x_label)
        f.Close()
    hist_cfg.hist.SetStats(0)
    hist_cfg.hist.SetLineColor(hist_cfg.color),
    hist_cfg.hist.GetYaxis().SetRangeUser(*y_range)
    if not i:
        hist_cfg.hist.Draw()
    else:
        hist_cfg.hist.Draw("same")
leg.Draw("same")
c.SaveAs(outputPath)


import json
from django.db import transaction
from django.db.models import F
from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver
from django.utils import timezone
from django_celery_beat.models import PeriodicTask, IntervalSchedule

from .models import Book, BookChapter
from .tasks import book_scraper_info, book_scraper_chaps

@receiver(post_save, sender=Book)
def book_scraper_initial_signal(sender, instance, created=False, **kwargs):
    if not instance.visited and instance.visit_id:
        schedule, created = IntervalSchedule.objects.get_or_create(
            every=15,
            period=IntervalSchedule.SECONDS,
        )
        PeriodicTask.objects.create(
            one_off=True,
            interval=schedule,
            name=f'Update book: {instance.title}',
            task='novel2read.apps.books.tasks.book_scraper_info',
            args=json.dumps([instance.pk]),
        )

        if not instance.chapters_count:
            schedule, created = IntervalSchedule.objects.get_or_create(
                every=50,
                period=IntervalSchedule.SECONDS,
            )
            PeriodicTask.objects.create(
                one_off=True,
                interval=schedule,
                name=f'Update book chapters init: {instance.title}',
                task='novel2read.apps.books.tasks.book_scraper_chaps',
                args=json.dumps([instance.pk]),
            )

@receiver(post_save, sender=BookChapter)
def create_update_chapter_cid(sender, instance, created=False, **kwargs):
    if created:
        instance.book.update_chapters_count()
        instance.c_id = instance.book.chapters_count
        instance.save(update_fields=['c_id'])

@receiver(post_delete, sender=BookChapter)
def delete_update_chapter_cid(sender, instance, **kwargs):
    instance.book.update_chapters_count()
    c_id_del = instance.c_id
    book_chaps = BookChapter.objects.filter(book__slug=instance.book.slug).filter(c_id__gt=c_id_del)
    book_chaps.update(c_id=F('c_id') - 1)


from django.contrib import admin
from django.urls import path, include
from pastes import views as paste_views

urlpatterns = [
    path('', include('home.urls', 'home')),
    path('admin/', admin.site.urls),
    path('pastes/', paste_views.ShowQueryResults.as_view(), name="query_results"),
    path('pastes/<str:char_id>', paste_views.ShowPaste.as_view(), name="show_paste"),
    path('pastes/<str:char_id>/confirm_delete', paste_views.ConfirmDelete.as_view(), name="confirm_delete"),
    path('pastes/<str:char_id>/delete', paste_views.DeletePaste.as_view(), name='delete_paste'),
]


# -*- coding: utf-8 -*-
from zabbix_api import ZabbixAPI
from datetime import datetime
import time

zapi = ZabbixAPI("https://endereco.com.br/zabbix")
# Disable SSL certificate verification
zapi.session.verify = False
# Specify a timeout (in seconds)
zapi.timeout = 10.1
# informacoes de acesso
zapi.login("usuario.zabbix", "senhaUsuario")
# mostra versao do zabbix
print("Connected to Zabbix API Version %s" % zapi.api_version())

for hosts in zapi.host.get({'output': ['host','interface']}):
    print(hosts)

#item_id = 1879051

# Create a time range
#time_till = time.mktime(datetime.now().timetuple())
#time_from = time_till - 60 * 60 * 4  # 4 hours

#time_from = time.mktime(datetime.now().timetuple()) - 60 * 5  # 5 min

#historico = zapi.history.get({ 'itemids': [ item_id ],
#'history': 0,
#'output': 'extend',
#'time_from': time_from,
#'time_till': “1439250959”
#    })

# Print out each datapoint
#for point in historico:
#    print("{0}: {1}".format(datetime.fromtimestamp(int(point['clock']))
#                            .strftime("%x %X"), point['value']))

# 0 pertence a data
# 1 pertence a valor


from bot.models import User, Schedule, Spec, Group
from .__utils import bot, MAIN_ACTIVITY_FLAG, SCHEDULE_ACTIVITY_FLAG, REGISTRATION_YEAR, REGISTRATION_ACTIVITY_FLAG
from .__utils import MY_SCHEDULE, OTHER_SCHEDULES, CHANGE_MY_GROUP
from .__utils import OTHER_SCHEDULE_SPEC, OTHER_SCHEDULE_GROUP, OTHER_SCHEDULE_SUBGROUP, OTHER_SCHEDULE_DISPLAY
from .__fillers import ScheduleMessageFiller, ScheduleKeyboardFiller
from telegram import Bot, InlineKeyboardMarkup, InlineKeyboardButton
from datetime import datetime

message_filler = ScheduleMessageFiller()
keyboard_filler = ScheduleKeyboardFiller()

def start_schedule_activity(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. start shcedule activity\n')

    chat_id = context.chat_data.get('chat_id')

    start_schedule_activity_message = message_filler.start_schedule_activity_message

    my_schedule_button = InlineKeyboardButton(keyboard_filler.my_schedule_button_text,
                                              callback_data=MY_SCHEDULE)

    other_schedules_button = InlineKeyboardButton(keyboard_filler.other_schedules_button_text,
                                              callback_data=OTHER_SCHEDULES)

    keyboard = [[my_schedule_button],
                [other_schedules_button]]

    inline_markup = InlineKeyboardMarkup(keyboard)

    context.chat_data['message_id'] = bot.send_message(chat_id=chat_id, text=start_schedule_activity_message,
                                                       reply_markup=inline_markup).message_id

    return SCHEDULE_ACTIVITY_FLAG

def start_my_schedule_activity(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. start my schedule activity\n')

    chat_id = context.chat_data.get('chat_id')
    message_id = context.chat_data.get('message_id')

    bot.edit_message_reply_markup(chat_id=chat_id, message_id=message_id)

    user_id = context.chat_data.get('user_id')

    user = User.objects.get(telegram_id=user_id)

    if user.group is None:
        print('---unregistered user---')

        unregistered_user_message = message_filler.unregistered_user_message

        bot.send_message(chat_id=chat_id, text=unregistered_user_message)

        return MAIN_ACTIVITY_FLAG

    schedule = Schedule.objects.filter(group=user.group, subgroup=user.subgroup).first()

    if schedule == None:
        print('---no schedule by this parameters---')

        no_schedule_message = message_filler.schedule_not_found_message

        bot.send_message(chat_id=chat_id, text=no_schedule_message)
    else:
        bot_before_schedule_message = message_filler.before_display_schedule_message

        bot.send_message(chat_id=chat_id, text=bot_before_schedule_message)

        schedule_message = schedule.schedule

        bot.send_message(chat_id=chat_id, text=schedule_message)

    return MAIN_ACTIVITY_FLAG

def start_other_schedules_activity(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. start other schedules activity. choise course\n')

    chat_id = context.chat_data.get('chat_id')
    last_message_id = context.chat_data.get('message_id')

    bot.edit_message_reply_markup(chat_id=chat_id, message_id=last_message_id, reply_markup=None)

    years = keyboard_filler.courses_buttons_texts
    current_date = datetime.today()

    SEPTEMBER = 9
    education_year = 0

    if current_date.month < SEPTEMBER:
        education_year = current_date.year - 1
    else:
        education_year = current_date.year

    keyboard = []

    COURSES_AMOUNT = 6

    for index in range(0, COURSES_AMOUNT):
        course_button = InlineKeyboardButton(years[index],
                        callback_data=OTHER_SCHEDULE_SPEC + ' ' + str(education_year - index))
        keyboard.append([course_button])

    inline_markup = InlineKeyboardMarkup(keyboard)

    context.chat_data['message_id'] = bot.send_message(chat_id=chat_id, text=message_filler.choise_course_message,
                                                       reply_markup=inline_markup).message_id

    print(f'Sent message: {context.chat_data.get("message_id")}')

    return SCHEDULE_ACTIVITY_FLAG

def choise_spec(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. other schedules. choise spec\n')

    chat_id = context.chat_data.get('chat_id')
    last_message_id = context.chat_data.get('message_id')

    bot.edit_message_reply_markup(chat_id=chat_id, message_id=last_message_id, reply_markup=None)

    context.chat_data['year'] = int(update.callback_query.data.split(' ')[1])

    specs = Spec.objects.all()
    print(f'specs: {specs}')

    keyboard = []

    for spec in specs:
        keyboard.append([InlineKeyboardButton(str(spec),
                         callback_data=str(OTHER_SCHEDULE_GROUP) + ' ' + str(spec.spec_id))])

    inline_markup = InlineKeyboardMarkup(keyboard)

    context.chat_data['message_id'] = bot.send_message(chat_id=chat_id, text=message_filler.choise_spec_message,
                                                       reply_markup=inline_markup).message_id

    print(f'sent message: {context.chat_data.get("message_id")}')

    return SCHEDULE_ACTIVITY_FLAG

def choise_group(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. other schedules. choise group\n')

    chat_id = context.chat_data.get('chat_id')
    last_message_id = context.chat_data.get('message_id')

    bot.edit_message_reply_markup(chat_id=chat_id, message_id=last_message_id, reply_markup=None)

    year = context.chat_data.get('year')
    spec_id = int(update.callback_query.data.split(' ')[1])
    context.chat_data['spec_id'] = spec_id

    groups = Group.objects.all().filter(year=year, spec__spec_id=spec_id)

    if len(groups) == 0:
        print('---No groups for this year---')

        group_not_found_message = message_filler.group_not_found_message

        bot.send_message(chat_id=chat_id, text=group_not_found_message)

        return MAIN_ACTIVITY_FLAG

    print(groups)

    keyboard = []

    for group in groups:
        keyboard.append([InlineKeyboardButton(str(group),
                         callback_data=str(OTHER_SCHEDULE_SUBGROUP) + ' ' + str(group.pk))])

    inline_markup = InlineKeyboardMarkup(keyboard)
    print(inline_markup)

    context.chat_data['message_id'] = bot.send_message(chat_id=chat_id, text=message_filler.choise_group_message,
                                                       reply_markup=inline_markup).message_id

    print(f'sent message: {context.chat_data.get("message_id")}')

    return SCHEDULE_ACTIVITY_FLAG

def choise_subgroup(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. other schedules. choise subgroup\n')

    chat_id = context.chat_data.get('chat_id')
    last_message_id = context.chat_data.get('message_id')

    bot.edit_message_reply_markup(chat_id=chat_id, message_id=last_message_id, reply_markup=None)

    group_pk = int(update.callback_query.data.split(' ')[1])
    context.chat_data['group_pk'] = group_pk

    group = Group.objects.get(pk=group_pk)
    print(f'subgroup: {group.subgroup_amount}')

    if group.subgroup_amount == 0:
        context.chat_data['is_subgroups_zero'] = True
        return display_schedule(update, context)

    context.chat_data['is_subgroups_zero'] = False
    keyboard = []

    for subgroup_number in range(1, group.subgroup_amount + 1):
        print(subgroup_number)
        keyboard.append([InlineKeyboardButton(str(subgroup_number),
                        callback_data=str(OTHER_SCHEDULE_DISPLAY) + ' ' + str(subgroup_number))])

    inline_markup = InlineKeyboardMarkup(keyboard)
    print(inline_markup)

    context.chat_data['message_id'] = bot.send_message(chat_id=chat_id, text=message_filler.choise_subgroup_message,
                                                    reply_markup=inline_markup).message_id

    print(f'sent message: {context.chat_data.get("message_id")}')

    return SCHEDULE_ACTIVITY_FLAG

def display_schedule(update, context):
    print('---------------------------------------------------------------------')
    print('schedule. other schedules. display schedule\n')

    chat_id = context.chat_data.get('chat_id')

    group_pk = context.chat_data.get('group_pk')

    group = Group.objects.get(pk=group_pk)
    subgroup = 0

    is_subgroups_zero = context.chat_data.get('is_subgroups_zero')
    if not is_subgroups_zero:
        last_message_id = context.chat_data.get('message_id')
        bot.edit_message_reply_markup(chat_id=chat_id, message_id=last_message_id, reply_markup=None)

        subgroup = int(update.callback_query.data.split(' ')[1])

    schedule = Schedule.objects.filter(group=group, subgroup=subgroup).first()

    if schedule == None:
        bot.send_message(chat_id=chat_id, text=message_filler.schedule_not_found_message)
    else:
        bot.send_message(chat_id=chat_id, text=message_filler.before_display_schedule_message)
        bot.send_message(chat_id=chat_id, text=schedule.schedule)

    return MAIN_ACTIVITY_FLAG


# -*- coding: utf-8 -*-
# pylint: disable=W0621
import pytest
from unittestzero import Assert
from fixtures.server_roles import default_roles, server_roles

@pytest.mark.nondestructive
@pytest.mark.fixtureconf(server_roles=default_roles+('automate',))
@pytest.mark.usefixtures(
        "maximized",
        "setup_infrastructure_providers",
        "setup_pxe_provision",
        "mgmt_sys_api_clients")
class TestTemplateProvisioning:
    def test_linux_template_cancel(
            self,
            provisioning_start_page,
            provisioning_data_basic_only):
        '''Test Cancel button'''
        provisioning_start_page.click_on_template_item(
                provisioning_data_basic_only["template"])
        provision_pg = provisioning_start_page.click_on_continue()
        vm_pg = provision_pg.click_on_cancel()
        Assert.true(vm_pg.is_the_current_page,
                "not returned to the correct page")

    def test_linux_template_workflow(
            self,
            server_roles,
            provisioning_start_page,
            provisioning_data,
            mgmt_sys_api_clients,
            random_name):
        '''Test Basic Provisioning Workflow'''
        assert len(server_roles) == len(default_roles) + 1
        provisioning_start_page.click_on_template_item(
            provisioning_data["template"])
        provision_pg = provisioning_start_page.click_on_continue()
        self.complete_provision_pages_info(provisioning_data, provision_pg, \
            random_name)
        vm_pg = assert_vm_state(provisioning_data, provision_pg, "on", \
            random_name)
        remove_vm(provisioning_data, vm_pg, mgmt_sys_api_clients, \
            random_name)

    def complete_provision_pages_info(self,
        provisioning_data, provision_pg, random_name):
        ''' Fills in data for Provisioning tabs'''
        tab_buttons = provision_pg.tabbutton_region
        request_pg = tab_buttons.tabbutton_by_name("Request").click()
        request_pg = request_pg.fill_fields(
                "admin@example.com",
                "admin",
                "admin",
                "Adding a test note",
                "Manager Name")
        purpose_pg = tab_buttons.tabbutton_by_name("Purpose").click()
        # tree = purpose_pg.click_on_nodes(provisioning_data["node"],
        #        provisioning_data["child_node")
        catalog_pg = tab_buttons.tabbutton_by_name("Catalog").click()
        catalog_pg.fill_fields(
                provisioning_data["provision_type"],
                provisioning_data["pxe_server"],
                provisioning_data["server_image"],
                str(provisioning_data["count"]),
                '%s%s' % (provisioning_data["vm_name"], random_name),
                provisioning_data["vm_description"])
        environment_pg = tab_buttons.tabbutton_by_name("Environment").click()
        environment_pg.fill_fields(
                unicode(provisioning_data["host"]),
                unicode(provisioning_data["datastore"]))
        hardware_pg = tab_buttons.tabbutton_by_name("Hardware").click()
        network_pg = tab_buttons.tabbutton_by_name("Network").click()
        if ("PXE" in provisioning_data["provision_type"]) or \
           ("ISO" in provisioning_data["provision_type"]):
            customize_pg = tab_buttons.tabbutton_by_name("Customize").click()
            customize_pg.fill_fields(
                provisioning_data["root_password"],
                provisioning_data["address_node_value"],
                provisioning_data["customization_template"])
        schedule_pg = tab_buttons.tabbutton_by_name("Schedule").click()
        schedule_pg.fill_fields(
                provisioning_data["when_to_provision"],
                provisioning_data["power_on"],
                str(provisioning_data["time_until_retirement"]))

        services_requests_pg = schedule_pg.click_on_submit()
        Assert.true(services_requests_pg.is_the_current_page,
                "not returned to the correct page")
        Assert.equal(services_requests_pg.flash_message,
                "VM Provision Request was Submitted, "\
                "you will be notified when your VMs are ready")
        services_requests_pg.approve_request(1)
        services_requests_pg.wait_for_request_status("Last 24 Hours", \
                "Finished", 12)

def assert_vm_state(provisioning_data, current_page, \
    current_state, random_name):
    ''' Asserts that the VM is created in the expected state '''
    vm_pg = current_page.header.site_navigation_menu(
            'Infrastructure').sub_navigation_menu('Virtual Machines').click()
    vm_pg.refresh()
    vm_pg.wait_for_vm_state_change( '%s%s' % (provisioning_data["vm_name"],
            random_name), 'on', 12)
    Assert.equal(vm_pg.quadicon_region.get_quadicon_by_title(
        '%s%s' % (provisioning_data["vm_name"], random_name))\
        .current_state, current_state,
        "vm not in correct state: " + current_state)
    return vm_pg

def remove_vm(provisioning_data,
    current_page, provider_api_clients, random_name):
    '''Powers off and removes the VM'''
    vm_pg = current_page.header.site_navigation_menu(
            'Infrastructure').sub_navigation_menu('Virtual Machines').click()
    vm_pg.power_off(['%s%s' % (provisioning_data["vm_name"], random_name)])
    Assert.true(vm_pg.flash.message.startswith("Stop initiated"))
    vm_pg.wait_for_vm_state_change(
            '%s%s' % (provisioning_data["vm_name"], random_name), 'off', 12)
    Assert.equal(vm_pg.quadicon_region.get_quadicon_by_title(
            '%s%s' % (provisioning_data["vm_name"], random_name))\
            .current_state, 'off', "vm running")
    for provider in provider_api_clients.values():
        if ('%s%s' % (provisioning_data["vm_name"], random_name) + "/" +
                '%s%s' % (provisioning_data["vm_name"], random_name) + ".vmx"
                ) in provider.list_vm() or \
                '%s%s' % (provisioning_data["vm_name"], random_name) \
                in provider.list_vm():
            provider.delete_vm('%s%s' % (provisioning_data["vm_name"], \
                random_name))


from tkinter import *
root = Tk()

def printName(*args):
    print ("Hello, world!")

var = StringVar()
var.set("test")
var.trace('w', printName)

entry_1 = Entry(root, textvariable = var)
entry_1.pack()

root.mainloop()


import json
import logging
import os

import requests
from django.core.management.base import BaseCommand
from django.utils.http import urlencode

from public_data_collector.models import Area, Sigungu, SmallArea

class Collector:
    def __init__(self):
        super(Collector, self).__init__()
        self.base_url = 'http://api.visitkorea.or.kr/openapi/service/rest/KorService'
        self.endpoint = self.base_url
        with open('/etc/secrets/culturedata_proto/service_key.txt') as f:
            self.service_key = f.read().strip()
        self.base_query_params = {
            'pageNo': 1,
            'MobileOS': 'ETC',
            'MobileApp': 'culterdata_proto',
        }

    def send_request(self):
        return requests.get(self.endpoint)

class Command(Collector, BaseCommand):
    help = 'Collect public data'

    def __init__(self):
        super(Command, self).__init__()

    def update_setting(self, query_params):
        self.query_params = self.base_query_params.copy()
        self.query_params.update(query_params)
        self.endpoint = self.base_url \
                        + '/areaCode?ServiceKey={}&{}'.format(self.service_key, urlencode(self.query_params))

    def handle(self, *args, **options):
        self.update_setting({
            'numOfRows': 1000,
            '_type': 'json',
        })
        response = self.send_request()
        areas = json.loads(response.text)['response']['body']['items']['item']
        for area in areas:
            area_instance = Area.objects.get_or_create(
                code=int(area['code']),
                name=area['name']
            )[0]
            self.update_setting({
                'numOfRows': 1000,
                '_type': 'json',
                'areaCode': area['code'],
            })
            response = self.send_request()
            sigungus = json.loads(response.text)['response']['body']['items']['item']
            if type(sigungus) is not list:
                sigungus = [sigungus]
            for sigungu in sigungus:
                sigungu_instance = Sigungu.objects.get_or_create(
                    area=area_instance,
                    code=int(sigungu['code']),
                    name=sigungu['name']
                )[0]
                self.update_setting({
                    'numOfRows': 1000,
                    '_type': 'json',
                    'areaCode': area['code'],
                    'sigunguCode': sigungu['code']
                })
                response = self.send_request()
                if json.loads(response.text)['response']['body']['totalCount'] == 0:
                    continue
                small_areas = json.loads(response.text)['response']['body']['items']['item']
                for small_area in small_areas:
                    SmallArea.objects.get_or_create(
                        sigungu=sigungu_instance,
                        code=int(small_area['code']),
                        name=small_area['name']
                    )

        return 'collect data complete.'


def mediaTotal(idh, qtd_linhas, qtd_colunas):
    lin=0
    col=0
    total=0
    for lin in range(qtd_linhas):
        for col in range(qtd_colunas):
            total = total + idh[lin][col]
    print("A média dos IDHs é: " , round(total/(qtd_linhas*qtd_colunas),2))

def mediaPaises(idh, paises, qtd_linhas, qtd_colunas):
    i=0
    j=0
    for i in range(qtd_linhas):
        total = 0
        for j in range(qtd_colunas):
            total = total + idh[i][j]
        print("O IDH do ", paises[i], " é: ", round(total/qtd_colunas,2))

def mediaAno(idh, anos, qtd_linhas, qtd_colunas):
    i = 0
    j = 0
    for j in range(qtd_colunas):
        total = 0
        for i in range(qtd_linhas):
            total = total + idh[i][j]
        print("No ano de ", anos[j], " o IDH médio dos países é: ",round(total/qtd_linhas,2))

def maiorIDH(idh, anos, paises, k, h):
    i =0
    j = 0
    maior = idh[0][0]
    pais = paises[0]
    ano = anos[0]
    for i in range(k):
        for j in range(h):
            if idh[i][j] > maior:
                maior = idh[i][j]
                pais = paises[i]
                ano = anos[j]
    print(pais, " em " , ano , " teve o maior IDH, sendo de: " , maior)

#bloco principal
anos = [2015,2016,2017,2018]
paises = ["Brasil","Angola","Austrália","EUA","Argentina"]
idh =[[0.75,0.85,0.56,0.89],
      [0.89,0.50,0.20,0.12],
      [0.10,0.45,0.12,0.78],
      [0.67,0.90,1.00,0.90],
      [0.11,0.67,0.30,0.39]]

mediaTotal(idh,5,4)
print("**********************************************************")
mediaPaises(idh, paises, len(paises), len(anos))
print("**********************************************************")
mediaAno(idh, anos, len(paises), len(anos))
print("**********************************************************")
maiorIDH(idh, anos, paises, len(paises), len(anos))
print("**********************************************************")


def binary(A,l,r,key):
	mid = (l+r)//2
	if l>r:
		return -1
	if A[mid]==key:
		return mid
	elif A[mid]>key:
		return binary(A,l,mid-1,key)
	else :
		return binary(A,mid+1,r,key)

n=int(input("Enter the range of the array : "))
A=[]
for i in range(0,n):
	A.append(i)
l=0
r=len(A)-1
key=int(input("Enter key to be searched : "))
s=t.time()
print("The key is found at : ",binary(A,l,r,key))
f=t.time()
print("The time taken to search is : {} seconds ".format(f-s))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

import time
from PyQt5.QtWidgets import QApplication, QMessageBox

from print__hprof_or_big_size_file import find_files_by_dirs, DIRS

if __name__ == '__main__':
    app = QApplication([])

    while True:
        result = find_files_by_dirs(DIRS)
        if result:
            QMessageBox.warning(None, 'Warn', '\n'.join(result))

        time.sleep(5 * 60 * 60)


from django.shortcuts import (
    render, redirect, reverse, HttpResponse, get_object_or_404
)
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.template.loader import render_to_string
from .forms import WishlistForm
from products.models import Product
from profiles.models import UserProfile
from .models import Wishlist

@login_required
def view_wishlist(request):
    """ A view that renders the wishlist contents page """

    # basic view for displaying User wishlist page

    user = UserProfile.objects.get(user=request.user)

    # wishlist = get_object_or_404(Wishlist, user=user)

    try:
        wishlist = Wishlist.objects.get(user=user)
    except Wishlist.DoesNotExist:
        wishlist = None
        messages.warning(request, "No items in the Wishlist yet!")
    if wishlist:
    # user exist
        pass
    else:
    # user does not exist
        pass

    context={
        'wishlist': wishlist,
    }

    return render(request, 'wishlist/wishlist.html', context)

@login_required
def add_to_wishlist(request, product_id):

    product_wish = get_object_or_404(Product, pk=product_id) # get product

    wishlist, created = Wishlist.objects.get_or_create(
        user=request.user.userprofile,
        name='rick'
    )

    if wishlist.products.filter(name=product_wish).exists():
        messages.warning(request, "Item already added to wishlist")
        return redirect(reverse('view_wishlist'))
    else:
        wishlist.products.add(product_wish)
        messages.success(request, "Item added to Wishlist!")
        return redirect(reverse('view_wishlist'))

@login_required
def remove_from_wishlist(request, product_id):

    product_wish = get_object_or_404(Product, pk=product_id) # get product
    user = UserProfile.objects.get(user=request.user) # get user

    wishlist = get_object_or_404(Wishlist, user=user) # filter wishlist item from with user

    wishlist.products.remove(product_wish) # remove item
    messages.success(request, 'Product Removed From Wishlist')

    return redirect(reverse('view_wishlist'))


import os

from torch.utils import data
from torchvision import transforms
from PIL import Image

def get_transform():
    """Module for image pre-processing definition.

    You can customize this module.
    """
    normalize = transforms.Normalize(
        mean=[x / 255.0 for x in [125.3, 123.0, 113.9]],
        std=[x / 255.0 for x in [63.0, 62.1, 66.7]])
    transform = [
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        normalize
    ]
    return transforms.Compose(transform)

class CustomDataset(data.Dataset):
    """Dataset class.

    This class is used for internal NSML inference system.
    You can modify this module for improving your data loading efficiency.
    """
    def __init__(self, root, transform):
        self.data_root = os.path.join(root, 'test_data')
        self.transform = transform
        self.image_ids = [img for img in os.listdir(self.data_root)]

    def __getitem__(self, idx):
        image_id = self.image_ids[idx]
        image = Image.open(os.path.join(self.data_root, image_id))
        image = image.convert('RGB')
        image = self.transform(image)
        return image, image_id

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

def data_loader(root, batch_size=64):
    """Test data loading module.

    Args:
        root: string. dataset path.
        batch_size: int.

    Returns:
        DataLoader instance
    """
    input_transform = get_transform()
    dataset = CustomDataset(root, input_transform)
    return data.DataLoader(dataset=dataset,
                           batch_size=batch_size,
                           shuffle=False)


import numpy as np

def export_obj(vertices, triangles, filename):
    """
    Exports a mesh in the (.obj) format.
    """

    with open(filename, 'w') as fh:

        for v in vertices:
            fh.write("v {} {} {}\n".format(*v))

        for f in triangles:
            fh.write("f {} {} {}\n".format(*(f + 1)))

def export_off(vertices, triangles, filename):
    """
    Exports a mesh in the (.off) format.
    """

    with open(filename, 'w') as fh:
        fh.write('OFF\n')
        fh.write('{} {} 0\n'.format(len(vertices), len(triangles)))

        for v in vertices:
            fh.write("{} {} {}\n".format(*v))

        for f in triangles:
            fh.write("3 {} {} {}\n".format(*f))

def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh"):
    """
    Exports a mesh in the COLLADA (.dae) format.

    Needs PyCollada (https://github.com/pycollada/pycollada).
    """

    import collada

    mesh = collada.Collada()

    vert_src = collada.source.FloatSource("verts-array", vertices, ('X','Y','Z'))
    geom = collada.geometry.Geometry(mesh, "geometry0", mesh_name, [vert_src])

    input_list = collada.source.InputList()
    input_list.addInput(0, 'VERTEX', "#verts-array")

    triset = geom.createTriangleSet(np.copy(triangles), input_list, "")
    geom.primitives.append(triset)
    mesh.geometries.append(geom)

    geomnode = collada.scene.GeometryNode(geom, [])
    node = collada.scene.Node(mesh_name, children=[geomnode])

    myscene = collada.scene.Scene("mcubes_scene", [node])
    mesh.scenes.append(myscene)
    mesh.scene = myscene

    mesh.write(filename)


from graph import *
from tkinter import *
from tabulate import tabulate

OPTIONS = [
    'Матрица смежности',
    'Матрица инцидентности',
    'Степень вершин',
    'Изолированные и висячие',
    'Матрица растояний',
    'Матрица доступности',
    'Простые циклы',
    'BFS',
    'DFS'
]

def strong_connections():
    colors = ['yellow', 'orange', 'blue', 'green', 'red']
    for i in graph.get_cycles():
        color = colors.pop()
        image_of_graph.change_vertex_color(i, vertex_color=color)

def full_update(path):
    global gif, image_of_graph, graph
    graph = Graph()
    graph.read_file(path)
    image_of_graph = GraphImage (graph)
    image_of_graph.fill_graph()
    image_of_graph.process_image()
    gif = PhotoImage(file="source/image.gif")
    image_label.configure(image=gif)
    left_label.configure(text='')
    right_label.configure(text=get_text_label_2())

def load_case_1():
    full_update('source/case_1.txt')

def load_case_2():
    full_update('source/case_2.txt')

def load_case_3():
    full_update('source/case_3.txt')

def adjacency_matrix_out():
    image_of_graph.change_vertex_color(range(graph.vertices))
    return graph.wrap(graph.adjacency_matrix, 'v', 'v')

def incidence_matrix_out():
    image_of_graph.change_vertex_color(range(graph.vertices))
    return graph.wrap(graph.incidence_matrix, 'v', 'e')

def vertex_power_out():
    image_of_graph.change_vertex_color(range(graph.vertices))
    matrix_list = []
    for i in range(graph.vertices):
        matrix_list.append(graph.get_vertex_power(i))
    return graph.wrap(matrix_list, custom_horizontal=['d-', 'd+'])

def isolated_vertices_out():
    image_of_graph.change_vertex_color(graph.get_isolated(), vertex_color='red')
    image_of_graph.change_vertex_color(graph.get_pendant(), vertex_color='green')
    pre_string = 'Изолированные:\n'
    for i in graph.get_isolated():
        pre_string += 'v' + str(i + 1) + '\t'
    pre_string += '\nВисячие:\n'
    for i in graph.get_pendant():
        pre_string += 'v' + str(i + 1) + '\t'
    return pre_string

def distance_matrix_out():
    image_of_graph.change_vertex_color(range(graph.vertices))
    pre_string = graph.wrap(graph.get_distance_matrix(), 'v', 'v')
    return pre_string

def availability_matrix_out():
    image_of_graph.change_vertex_color(range(graph.vertices))
    pre_string = graph.wrap(graph.get_availability_matrix(), 'v', 'v')
    return pre_string

def bfs_out():
    str_out = tabulate(graph.bfs_protocol(0))
    return str_out

def dfs_out():
    str_out = tabulate(graph.dfs_protocol(0))
    return str_out

def cycles_out():
    pre_string = ''
    image_of_graph.change_vertex_color(range(graph.vertices))
    for cycle in graph.get_cycles():
        pre_string += ' '.join([str(i + 1) for i in cycle])[::-1] + '\n'
    return pre_string

def storeys_out():
    pre_string = ''
    for storey in graph.get_storeys().keys():
        pre_string += 'Ярус: ' + str(storey) + '\n'
        for vertex in graph.get_storeys()[storey]:
            pre_string += 'v' + str(vertex + 1) + '  '
        pre_string += '\n'
    return pre_string

def topological_sort_out():
    return graph.topological_sort()

def graph_type():
    type = int(graph.connectivity_type())
    if type == 1:
        pre_string = 'Сильно связный'
    elif type == 2:
        pre_string = 'Односторенне-связый'
    elif type == 3:
        pre_string = 'Слабо связный'
    else:
        pre_string = 'Несвязный'
    return pre_string

def get_text_label_1():
    global gif
    choiсe = variable.get()
    output_string = ''
    if choiсe == OPTIONS[0]:
        output_string = adjacency_matrix_out()
    elif choiсe == OPTIONS[1]:
        output_string = incidence_matrix_out()
    elif choiсe == OPTIONS[2]:
        output_string = vertex_power_out()
    elif choiсe == OPTIONS[3]:
        output_string = isolated_vertices_out()
    elif choiсe == OPTIONS[4]:
        output_string = distance_matrix_out()
    elif choiсe == OPTIONS[5]:
        output_string = availability_matrix_out()
    elif choiсe == OPTIONS[6]:
        output_string = cycles_out()
    elif choiсe == OPTIONS[7]:
        output_string = bfs_out()
    elif choiсe == OPTIONS[8]:
        output_string = dfs_out()

    strong_connections()
    gif = PhotoImage(file="source/image.gif")
    image_label.configure(image=gif)
    left_label.configure(text='\n' + output_string)

def get_text_label_2():
    pre_string = ''
    pre_string += graph_type()
    pre_string += '\nРадиус: ' + str(graph.get_radius()) + '\n'
    pre_string += 'Диаметр: ' + str(graph.get_diameter()) + '\n'
    pre_string += 'Центр: \n'
    for i in graph.get_centers():
        pre_string += 'v' + str(i + 1) + ' '
    pre_string += '\n\n' + storeys_out()

    pre_string += '\nТопологическая сортировка\n' + str(topological_sort_out())
    return pre_string

graph = Graph()
graph.read_file('source/case_1.txt')

image_of_graph = GraphImage(graph)
image_of_graph.fill_graph()
image_of_graph.process_image()

root = Tk()

# Create window frames
f_1 = Frame(root)
f_2 = Frame(root)
f_2_1 = Frame(f_2)
f_2_1_1 = Frame(f_2_1)
f_2_1_2 = Frame(f_2_1)
f_2_2 = Frame(f_2)
f_3 = Frame(root)

# Case botton
button_case_1 = Button(root, text='case 1', command=load_case_1)
button_case_2 = Button(root, text='case 2', command=load_case_2)
button_case_3 = Button(root, text='case 3', command=load_case_3)

# Label with image of graph
gif = PhotoImage(file='source/image.gif')
image_label = Label(f_1, image=gif, width=400)

# Left button
button = Button(f_2_1_1, text='Вычислить', command=get_text_label_1)

# Dropdown list
variable = StringVar(root)
variable.set(OPTIONS[0])
option = OptionMenu(f_2_1_2, variable, *OPTIONS)

# Label with printed matrix
left_label = Label(f_2_2, text='\n', font=('Monaco', 20), justify=LEFT)

# Properties label
right_label = Label(f_3, text=get_text_label_2(), font=('Monaco', 16), justify=LEFT)

# Pack frames
f_1.pack(side=LEFT)
f_2.pack(side=LEFT)
f_2_1.pack()
f_2_1_1.pack(side=LEFT)
f_2_1_2.pack(side=RIGHT)
f_2_2.pack()
f_3.pack(side=LEFT)

# Pack widgets
button_case_1.pack()
button_case_2.pack()
button_case_3.pack()
image_label.pack()
option.pack()
button.pack()
left_label.pack()
right_label.pack()

root.mainloop()


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Alex Li

#count = 0
#while True:
#    print("你是风儿我是沙,缠缠绵绵到天涯...",count)
#    count +=1

count = 0
while True:
    count +=1
    if count > 50 and count <60:
        continue
    print("你是风儿我是沙,缠缠绵绵到天涯...",count)

    if count == 100:
        print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼的臭男人..")
        break


class Version:
    def __init__(self, s=None):
        self.major = 0
        self.minor = 0
        self.patch = 0
        self.pre_release = None
        if s:
            items = s.split(".")
            self.major = items[0]
            if len(items)>1:
                self.minor = items[1]
                if len(items)>2:
                    self.patch = items[2]
                    if "-" in self.patch:
                        self.pre_release = self.patch.split("-")[1]
                        self.patch = self.patch.split("-")[0]

    # return True of self > other
    def compare (self, other):
        if self.major > other.major:
            return True
        elif self.major == other.major:
            if self.minor > other.minor:
                return True
            elif self.minor == other.minor:
                if self.patch > other.patch:
                    return True
                elif self.patch == other.patch:
                    if (self.pre_release is None and not other.pre_release is None) or self.pre_release > other.pre_release:
                        return True
        return False

    def __str__ (self):
        return "%s %s %s %s" % (self.major, self.minor, self.patch, self.pre_release)
    __repr__= __str__

def is_later_version (a, b):
    ver_a = Version(a)
    return ver_a.compare (Version(b))


import json
import numpy as np
import torch
import os
import shutil
from torchvision.models import vgg11, resnet18

def load_config(path):
    with open(path, 'r') as file:
        config = json.load(file)

        if config["data"]['place'] == "department":
            config["data"]["min_pos"] = torch.tensor([-1.4, -5.2, 1.3]).cuda()
            config["data"]["max_pos"] = torch.tensor([0.5, -3.3, 1.8]).cuda()
            config["data"]["number_images"]
            assert True == False, "Need to put number of images "
            config["sampler"]["no_fly_zone"] = None

        elif config["data"]["place"] == "living_room":
            config["data"]["min_pos"] = torch.tensor([-1.3, -0.5, 0.2,0.]).cuda()
            config["data"]["max_pos"] = torch.tensor([1.8, 1.4, 1.7,270.]).cuda()
            if config["sampler"]["no_fly"] == "True":
                config["sampler"]["no_fly_zone"] = torch.tensor([[[0.5,-0.5,0.2],[1.7,1.1,0.9]],[[-1.3,0.5,0.1],[-0.1,1.7,1.1]]]).cuda()
            elif config["sampler"]["no_fly"] == "False":
                config["sampler"]["no_fly_zone"] = None

    return config

def write_to_file(path,content):
    log_file = open(path,'a')
    log_file.write(content)
    log_file.flush()
    log_file.close()

def create_directories(exp_path):
    os.mkdir(exp_path)
    os.mkdir(exp_path + '/visualisations')
    os.mkdir(exp_path + '/visualisations/poses')
    os.mkdir(exp_path + '/visualisations/history')
    os.mkdir(exp_path + '/checkpoints')
    shutil.copy(exp_path +'/../../config.json',exp_path +'/config.json')
    shutil.copytree(exp_path +'/../../code',exp_path +'/code')


def reverse_other(t):
    """Mutates the tree such that nodes on every other (odd-depth) level
    have the labels of their branches all reversed.

    >>> t = Tree(1, [Tree(2), Tree(3), Tree(4)])
    >>> reverse_other(t)
    >>> t
    Tree(1, [Tree(4), Tree(3), Tree(2)])
    >>> t = Tree(1, [Tree(2, [Tree(3, [Tree(4), Tree(5)]), Tree(6, [Tree(7)])]), Tree(8)])
    >>> reverse_other(t)
    >>> t
    Tree(1, [Tree(8, [Tree(3, [Tree(5), Tree(4)]), Tree(6, [Tree(7)])]), Tree(2)])
    """
    "*** YOUR CODE HERE ***"
    if not t.is_leaf():            # if t is a leaf, then do nothing.
        a = []
        for b in t.branches:
            a.append(b.label)     # Using a to store the label of the nodes.
        for b in t.branches:
            b.label = a.pop()     # reassign every node in a reversed order. Attention: a.pop() has a reverse effect.
        for b in t.branches:
            if not b.is_leaf():
                for next_b in b.branches:  # to reverse the other level tree.
                    reverse_other(next_b)
    # Official answer:
    "*** YOUR CODE HERE ***"
    def reverse_odd(tree, odd=True):
        if tree.is_leaf():
            return
        else:
            branch_labels_reversed = [b.label for b in tree.branches][::-1]    # a[::-1] means get a new reversed list.
            for branch, label_reversed in zip(tree.branches, branch_labels_reversed):   # get the branch and the corresponding reversed label.
                if odd:
                    branch.label = label_reversed
                reverse_odd(branch, not odd)
    return reverse_odd(t)


from re import fullmatch

class StdIn:
    """
    StdIn.
    """
    keys = (
        'date',
        'begin_time',
        'end_time',
        'place',
        'speaker',
        'affiliation',
        'title',
        'abstract_file',
        'slide_file',
    )

    suggestion = {
        'date': ' (YYYY-MM-DD)',
        'begin_time': ' (HH:MM)',
        'end_time': ' (HH:MM)',
        'place': '',
        'speaker': '',
        'affiliation': '',
        'title': '',
        'abstract_file': ' (*.txt)',
        'slide_file': ' (*.pdf)',
    }

    re = {
        'date': r'\d{4}[-/]\d{2}[-/]\d{2}',
        'begin_time': r'\d{2}:\d{2}',
        'end_time': r'\d{2}:\d{2}',
        'place': r'.+',
        'speaker': r'.+',
        'affiliation': r'.+',
        'title': r'.+',
        'abstract_file': r'.+\.txt',
        'slide_file': r'.+\.pdf',
    }

    def read(self, key):
        """
        Read standard input.

        Returns
        -------
        value : str or None

        Raises
        ------
        VakueError
            If input value does not match regex.

        Examples
        --------
        >>> StdIn().read('date')
        Input date (YYYY-HH-MM): '20000-01-01'
        ValueError: Invalid input: '20000-01-01'
        Input date (YYYY-HH-MM): '2000-01-01'
        '2000-01-01'
        """
        while True:
            try:
                value = input(f'Input {key}{self.suggestion[key]} : ')
                value = self._check(key, value)
            except ValueError as e:
                print(e)
            else:
                return value

    def read_all(self):
        """
        Returns
        -------
        dict
        """
        return {key: self.read(key) for key in self.keys}

    def _check(self, key, value):
        """
        Check if value is a valid input for key.

        Returns
        -------
        value
            If value is empty or value matches with regex.

        Raises
        ------
        ValueError
            If value is not empty and does not match with regex.
        """
        if not value:
            return value
        if fullmatch(self.re[key], value):
            return value
        raise ValueError(f'Invalid input: {value}')


#!/usr/bin/env python3

import sys
import traceback
import time
import serial
import serial.tools.list_ports

# feature toggles
usb = False
uart = True

# if all the following are False then exit right away
local = False
competition = True
# dynamic not working properly, keep at False
dynamic = False

# note: since this program is in /usr/bin/ on the OBC
# it was necessary to also add the connection.py
# class in /usr/bin and change the following line to
# from connection import Connection
# for the startup service to work properly
from robot.comms.connection import Connection
from robot.comms.uart import Uart

# returns current time in milliseconds
current_millis = lambda: int(round(time.time() * 1000))

def get_commands_list():
    return """'q': quit\n
'w': forward\n
's': back\n
'a': left\n
'd': right\n
'i': increase throttle speed\n
'j': decrease throttle speed\n
'o': increase steering speed\n
'k': decrease steering speed\n
'l': list commands\n\n"""

# returns current time in milliseconds
current_millis = lambda: int(round(time.time() * 1000))

if len(sys.argv) == 2:
    ROVER_PORT = int(sys.argv[1])
elif len(sys.argv) >= 3:
    print(
        "too many arguments, one optional argument is the port number, otherwise default to 5010"
    )
    print("example usage: python ServerListener.py <port>")

if not local and not competition and not dynamic:
    print("local, competition and dynamic flags set to false, exiting")
    sys.exit(0)

if usb:
    # set up connection to arduino
    ports = list(serial.tools.list_ports.comports())
    is_rover = False

    if len(ports) == 1:
        print("1 USB device detected")
        port = ports[0].name
        ser = serial.Serial('/dev/' + port, 9600)

        print("clearing buffer")
        while ser.in_waiting:
            print(ser.readline().decode())

        for i in 0, 3:
            who = ""
            print("identifying MCU")
            ser.write(str.encode("who\n"))

            # CRITICAL: give time for MCU to respond
            time.sleep(1)

            while ser.in_waiting:
                who = ser.readline().decode()
                print("who: " + who)

            if who.strip() == "rover":
                print("Rover MCU identified!")
                is_rover = True
    elif len(ports) == 2:
        print("2 USB devices detected")
        port = ports[1].name
        ser = serial.Serial('/dev/' + port, 9600)

        print("clearing buffer")
        while ser.in_waiting:
            print(ser.readline().decode())

        for i in 0, 3:
            who = ""
            print("identifying MCU")
            ser.write(str.encode("who\n"))

            # CRITICAL: give time for MCU to respond
            time.sleep(1)

            while ser.in_waiting:
                who = ser.readline().decode()
                print("who: " + who)

            if who.strip() == "rover":
                print("Rover MCU identified!")
                is_rover = True

        if not is_rover:
            port = ports[0].name
            ser = serial.Serial('/dev/' + port, 9600)

            print("clearing buffer")
            while ser.in_waiting:
                print(ser.readline().decode())

            for i in 0, 3:
                who = ""
                print("identifying MCU")
                ser.write(str.encode("who\n"))

                # CRITICAL: give time for MCU to respond
                time.sleep(1)

                while ser.in_waiting:
                    who = ser.readline().decode()
                    print("who: " + who)

                if who.strip() == "rover":
                    print("Rover MCU identified!")
                    is_rover = True

    else:
        print("No USB devices recognized, exiting")
        sys.exit(0)

    if is_rover:
        print("Connected to port: " + port)
    else:
        print("Incorrect MCU connected, terminating listener")
        sys.exit(0)
elif uart:
    u = Uart("/dev/ttySAC0", 9600, timeout=1)

# for local testing
if local:
    ROVER_IP = "127.0.0.1"
    ROVER_PORT = 5020
    BASE_IP = ROVER_IP
    BASE_PORT = 5025
# for competition
elif competition:
    ROVER_IP = "172.16.1.30"
    ROVER_PORT = 5030
    BASE_IP = "172.16.1.20"
    BASE_PORT = ROVER_PORT
# attempt to get: physicial ip, which should not need connection to internet to work
#elif dynamic:
#    ROVER_IP = ni.ifaddresses(ni.interfaces()[1])[AF_INET][0]['addr']

print("ROVER_IP: " + ROVER_IP)
print("BASE_IP: " + BASE_IP)

# Create connection object to send/receive data with base-station
receiver = Connection("rover_drive_receiver", ROVER_IP, ROVER_PORT)
sender = Connection("rover_feedback_sender", BASE_IP, BASE_PORT)

print("Rover server listening on port {} \n".format(ROVER_PORT))

print("Ready for incoming drive cmds!\n")

print(get_commands_list())

key_list = ['w', 'a', 's', 'd', 'i', 'j', 'l', 'o', 'k', 'm', 'n', 't', 'b', 'q']
# Arduino sketch considers this value to be the signal for the motors to not move
REST = 49.5

# initialize throttle/steering speeds to 0
throttle_speed = 0
steering_speed = 0

# impose safety limits, theoretical limit at 49.5
MIN_THROTTLE_SPEED = 0
MAX_THROTTLE_SPEED = 25
MIN_STEERING_SPEED = 0
MAX_STEERING_SPEED = 39

# for controlling command throughput
last_cmd_sent = 0 # to keep track of the time of the last command sent
THROTTLE_TIME = 25 # time to wait before receiving next command

while True:
    #while ser.in_waiting:
    #    print(ser.readline().decode())

    try:
        # only receive commands if last command was sent
        # THROTTLE_TIME ago (in milliseconds)
        if current_millis() - last_cmd_sent > THROTTLE_TIME:

            command = receiver.receive()

            # for throttle speed, no backwards
            if command in key_list:
                print("OPERATOR command: " + command + " recognized\n")

                if command == 'w':
                    feedback = "cmd: w --> Forward\n"
                    command = str(REST + throttle_speed) + ":" + str(REST) + "\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                    last_cmd_sent = current_millis()

                elif command == 'a':
                    feedback = "cmd: a --> Left\n"
                    command = str(REST + throttle_speed) + ":" + str(REST - steering_speed) + "\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                    last_cmd_sent = current_millis()

                elif command == 's':
                    feedback = "cmd: s --> Back\n"
                    command = str(REST - throttle_speed) + ":" + str(REST) + "\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                    last_cmd_sent = current_millis()

                elif command == 'd':
                    feedback = "cmd: d --> Right"
                    command = str(REST + throttle_speed) + ":" + str(REST + steering_speed) + "\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                    last_cmd_sent = current_millis()

                elif command == 'm':
                    feedback = "cmd: m --> enable motor controls"
                    command = "activate\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                elif command == 'n':
                    feedback = "cmd: n --> disable motor controls"
                    command = "deactivate\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                # 't' --> reset to 0 on release key, otherwise motor keeps spinning
                # 45.5:45.5
                elif command == 't':
                    feedback = "cmd: t --> stop moving"
                    command = str(REST) + ":" + str(REST) + "\n"
                    feedback += "\ncommand: " + str(command)
                    print(feedback)
                    sender.send(feedback)

                    if usb:
                        ser.write(str.encode(command))
                    elif uart:
                        u.tx(command)

                    last_cmd_sent = current_millis()

                elif command == 'i':
                    feedback = "cmd: i --> Increment throttle speed"

                    if throttle_speed < MAX_THROTTLE_SPEED:
                        throttle_speed += 0.5
                        feedback += "\nthrottle speed: " + str(throttle_speed)
                    else:
                        feedback += "\nthrottle speed upper limit reached"

                    print(feedback)
                    sender.send(feedback)

                elif command == 'j':
                    feedback = "cmd: j --> Decrement throttle speed"

                    if throttle_speed > MIN_THROTTLE_SPEED:
                        throttle_speed -= 0.5
                        feedback += "\nthrottle speed: " + str(throttle_speed)
                    else:
                        feedback += "\nthrottle speed lower limit reached"

                    print(feedback)
                    sender.send(feedback)

                elif command == 'o':
                    feedback = "cmd: o --> Increment steering speed"

                    if steering_speed < MAX_STEERING_SPEED:
                        steering_speed += 0.5
                        feedback += "\nsteering speed: " + str(steering_speed)
                    else:
                        feedback += "\nsteering speed upper limit reached"

                    print(feedback)
                    sender.send(feedback)

                elif command == 'k':
                    feedback = "cmd: k --> Decrement steering speed"

                    if steering_speed > MIN_STEERING_SPEED:
                        steering_speed -= 0.5
                        feedback += "\nsteering speed: " + str(steering_speed)
                    else:
                        feedback += "\nsteering speed lower limit reached"

                    print(feedback)
                    sender.send(feedback)

                elif command == 'q':
                    feedback = "\nTerminating connection."

                    print(feedback)
                    sender.send(feedback)

                    break

                elif command == 'l':
                    print(get_commands_list())
                    sender.send(get_commands_list())

                elif command == 'b':
                    if usb:
                        data = ""
                        while ser.in_waiting:
                            data += ser.readline().decode()

                        print(data)
                        sender.send(data)
                    elif uart:
                        data = u.rx()
                        print(data)
                        sender.send(data)
            else:
                print("UNKOWN command " + command + "\n")

            if usb:
                # flush buffer to avoid overflowing it
                ser.reset_input_buffer()
                ser.reset_output_buffer()

    except Exception:
        if usb:
            ser.close()
        print("Exception in user code:")
        print("-"*60)
        traceback.print_exc(file=sys.stdout)
        print("-"*60)
        break


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import math
import sys
import numpy as np

def isAtomLine(line):
    c = line[15]
    return (line[0:4] == "ATOM" or line[0:6] == "HETATM") \
            and line[13:15] == "CA" \
            and (c == " " or c == "A") \
            and line[21] == chain

def getRadiusOfGyration(filename, chain):
    with open(filename, "r") as f:
        atom_lines = filter(isAtomLine, f)
        xyz_list = [[float(s[30:37].strip()),\
                     float(s[38:45].strip()),\
                     float(s[46:53].strip())] for s in atom_lines]
        gravity = np.array(xyz_list).T.mean(axis=1)
        return np.linalg.norm(xyz_list - gravity,axis=1).mean()

if __name__ == "__main__":
    args = sys.argv
    argc = len(args)
    if argc != 3:
        sys.stderr.write('Usage: python ' + args[0] + ' <PDB file> <chain name>\n')
        sys.exit(1)

    filename = args[1]
    chain    = args[2]
    print(getRadiusOfGyration(filename, chain))


import random
import operator

elements = {
    "0000": 0,
    "0001": 1,
    "0010": 2,
    "0011": 3,
    "0100": 4,
    "0101": 5,
    "0110": 6,
    "0111": 7,
    "1000": 8,
    "1001": 9,
    "1010": operator.add,
    "1011": operator.sub,
}

def decode(chromosome):
    num_elements = len(chromosome) // 4
    decoded = []
    for i in range(0, num_elements):
        key = chromosome[i:i+4]
        if not key in elements:
            return [0] * num_elements # return invalid seq
        decoded.append(elements[key])

    return decoded

def fitness(chromosome, goal):
    decoded = decode(chromosome)
    end = len(decoded) - 2
    offset = 1
    for i in range(end):
        a = decoded[i]
        op = decoded[i + 1]
        b = decoded[i + 2]
        if type(a) == int  and type(op) != int and type(b) == int:
            offset += op(a, b)
        else:
            return 0

    if goal - offset == 0:
        return 1
    else:
        return 1 / goal - offset

def crossover(parents):
    threshold = len(parents[0]) - 2
    cross_point = random.randint(0, threshold)
    offspring = parents[0][0:cross_point]
    offspring += parents[1][cross_point:]

    return offspring

def mutate(chrom):
    if random.randint(0, 100) == 42:
        mutation_point = random.randint(0, len(chrom) - 1)
        value = chrom[mutation_point]
        if value == 0:
            chrom[mutation_point] = 1
        else:
            chrom[mutation_point] = 0

    return chrom

def init_population(goal, pop_size):
    num_chr = number_of_elements(goal)
    keys = list(elements)
    population = []
    for i in range(pop_size):
        offspring = "".join(random.sample(keys, num_chr))
        population.append(offspring)

    return population

def generate_offspring(best, pop_size):
    new_population = []
    for i in range(pop_size):
        new_population.append(crossover(random.sample(best, 2)))

    return new_population

def main():
    goal = 20
    population_size = 5000

    # genearte population
    cur_pop = init_population(goal, population_size)

    match = False
    best_fitness = 0
    cur_best_fitness = 0
    best_percent = 0.2  # get top best from current population in percents
    solution = ""
    no_better_cnt = 0
    while (not match) and no_better_cnt < 10:
        pop_len = len(cur_pop)
        fitness_result = []
        for i in range(pop_len):
            fitness_i = fitness(cur_pop[i], goal)
            if fitness_i == 1:
                match = True
                best = 1
                cur_best_fitness = fitness_i
                solution = cur_pop[i]
            else:
                fitness_result.append( (fitness_i, cur_pop[i]) )

        fitness_result.sort()
        cur_best_fitness, solution = fitness_result[0]

        if cur_best_fitness <= best_fitness:
            no_better_cnt = no_better_cnt + 1
        else:
            best_fitness = cur_best_fitness

        best = fitness_result[0:int(pop_len * best_percent)]
        best_chroms = [c for f, c in best]
        print(best_fitness, cur_best_fitness, solution)
        print(best_chroms)
        cur_pop = generate_offspring(best_chroms, population_size)

    if solution:
        print(best_fitness, decode(solution))

if __name__ == "__main__":
    main()


"""empty message

Revision ID: b48beb44344
Revises: 1407298ea779
Create Date: 2016-01-05 09:46:11.005519

"""

# revision identifiers, used by Alembic.
revision = 'b48beb44344'
down_revision = '1407298ea779'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('role_id', sa.Integer(), nullable=True))
    op.drop_column('users', 'role')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('role', sa.INTEGER(), nullable=True))
    op.drop_column('users', 'role_id')
    ### end Alembic commands ###


from fc.qemu.main import daemonize
import datetime
import sys
import subprocess
import time
import shlex

def run_supervised(cmd, name, logfile):
    daemonize()
    log = open(logfile, 'a+', buffering=0)
    now = datetime.datetime.now().isoformat()
    log.write('{} - starting command {}\n'.format(now, cmd))
    s = subprocess.Popen(
        shlex.split(cmd), close_fds=True, stdin=None, stdout=log, stderr=log)
    now = datetime.datetime.now().isoformat()
    log.write('{} - command has PID {}\n'.format(now, s.pid))
    exit_code = s.wait()
    now = datetime.datetime.now().isoformat()
    log.write('{} - command exited with exit code {}\n'.format(now, exit_code))

if __name__ == '__main__':
    run_supervised(*sys.argv[1:])


import cv2
import numpy as np

drawing = False
ix, iy = -1, -1
sel_rect_endpoint = []
tagged = np.empty((0, 4), dtype='int')

def tag_players(image, dx=0.2, dy=0.3):
    img = cv2.resize(image, (0, 0), fx=dx, fy=dy)

    def draw_rectangle(event, x, y, flags, param):
        global ix, iy, drawing, tagged, sel_rect_endpoint

        if event == cv2.EVENT_LBUTTONDOWN:
            drawing = True
            ix, iy = x, y

        elif event == cv2.EVENT_MOUSEMOVE and drawing:
            sel_rect_endpoint = (x, y)

        elif event == cv2.EVENT_LBUTTONUP:
            cv2.rectangle(img, (ix, iy), (x, y), (0, 0, 255), 1)
            tagged = np.vstack((tagged, np.array([ix, iy, x, y])))
            drawing = False
            sel_rect_endpoint = []

    win_name = 'Tagging players'
    cv2.namedWindow(win_name)
    cv2.setMouseCallback(win_name, draw_rectangle, None)

    while 1:
        if sel_rect_endpoint and drawing:
            clone = img.copy()
            cv2.rectangle(clone, (ix, iy), sel_rect_endpoint, (0, 0, 255), 1)
            cv2.imshow(win_name, clone)
        else:
            cv2.imshow(win_name, img)
        if cv2.waitKey(20) & 0xFF == 27:
            break
    cv2.destroyAllWindows()
    return tagged

sample = cv2.imread('output/images/sample.jpg')
print(tag_players(sample))