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

# In[1]:

import argparse
import os
import random
import shutil
import time
import warnings

import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models

from sklearn.metrics import precision_recall_fscore_support, confusion_matrix

from my_data import *
from net import *
#np.set_printoptions(precision=3, suppress=True)

# In[2]:

args = {
    'arch': 'resnet18',#None,
    #'workers':4,
    'train_batch_size' :128,
    'test_batch_size':256,
    'epochs':100,
    'start_epoch':0,  #to resume training from specified epoch where model and parameter are saved
    'lr':0.01,
    'lr_decay':9,
    'momentum':0.75,
    'weight_decay':1e-4,
    'cuda':False,
    'seed':1,
    'print_freq':7,
    'save_model':True,
    'save_directory':'trained_models',
    'resume':'model_best.pth.tar',
    'evaluate':True,
    #'pretrained':False,
    'phase':'train',
    'loading':False,
    'locked_layers':0,
    'cls_weight':1.2,
    'pts_weight':1,
}

min_loss = -1

#num_classes = 42

# In[3]:

if not args['cuda'] and torch.cuda.is_available():
    device = torch.device("cuda" )
else:
    device = torch.device("cpu")

# In[4]:

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv2d') != -1:
        init.xavier_normal_(m.weight.data)
        init.constant_(m.bias.data, 0.0)
    elif classname.find('Linear') != -1:
        init.xavier_normal_(m.weight.data)
        init.constant_(m.bias.data, 0.0)

# In[5]:

def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
    torch.save(state, filename)
    if is_best:
        shutil.copyfile(filename, 'model_best.pth.tar')

# In[6]:

def adjust_learning_rate(optimizer, epoch, args):
    """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""

    lr = args['lr'] * (0.1 ** (epoch // args['lr_decay']))
    if lr <0.00001:
        lr = 0.00001
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

# In[12]:

def train(train_loader, model, criterion_pts, criterion_cls, optimizer, epoch, args):
    # switch to train mode

    model.train()
    since = time.time()
    for batch_idx, batch in enumerate(train_loader):

        #load data to GPU if used or CPU
        images = batch['image'].to(device)
        targets = batch['target'].to(device)
        landmarks = batch['landmarks'].to(device)

        #得到标签为1（即图像有人脸）的sample的索引
        indices = torch.nonzero(targets).flatten()
        landmarks = torch.index_select(landmarks, 0, indices)
        #print('epoch',epoch,'targets',targets.size(),'landmarks',landmarks.size())
        batch_size = len(images)

        # compute output
        output_pts, output_cls = model(images)
        output_pts = torch.index_select(output_pts, 0, indices)
        #print(output_cls.size(),targets.size())

        #Loss
        loss_cls = criterion_cls(output_cls,targets)                       #nn.CrossEntropyLoss, default: reduction = 'mean'
        loss_pts = criterion_pts(output_pts, landmarks)

        total_loss = loss_cls * args['cls_weight'] + loss_pts * args['pts_weight']

        #Accuracy
        prediction = nn.Softmax(1)(output_cls).argmax(dim=1)
        acc = (prediction == targets).float().mean()

        # compute gradient and do SGD step
        optimizer.zero_grad()
        total_loss.backward()
        optimizer.step()

        #every 'print_freq' batches, print log
        if batch_idx % args['print_freq'] == 0:
            print("Training epoch: [{}], \t batch_idx: [{}], \t acc: {:.3f} \t Loss: {:.3f}".format(epoch,batch_idx,acc,total_loss.item()))

    # measure elapsed time
    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
    #return total_loss

# In[13]:

def validate(valid_loader, model, criterion_pts,criterion_cls, args):
    # switch to evaluate mode
    model.eval()
    since = time.time()
    bool_2 = 1
    num_data = 0
    loss = 0
    all_label = []
    all_prediction = []
    #out_file = 'out.txt'
    #f = open(out_file,'w')
    with torch.no_grad():
        for batch_idx, batch in enumerate(valid_loader):
            #load data to GPU if used or CPU
            images = batch['image'].to(device)
            targets = batch['target'].to(device)
            landmarks = batch['landmarks'].to(device)

            indices = torch.nonzero(targets).flatten()
            landmarks = torch.index_select(landmarks, 0, indices)

            #print('targets',targets.size(),landmarks.size())
            #total num of valid samples
            batch_size = len(images)
            num_data += batch_size

            # compute output
            output_pts, output_cls = model(images) #model.to(device)
            output_pts = torch.index_select(output_pts, 0, indices)  #last batch of data contains no positive sample,
                                                                         #when compute loss, we get NaN error.
            #print('output_pts.size:',output_pts.size(),landmarks.size())

            #Loss
            loss_cls = criterion_cls(output_cls,targets)
            if output_pts.size(0) == 0:
                loss_pts = torch.tensor(0)
            else:
                loss_pts = criterion_pts(output_pts, landmarks)
            #print('loss_cls:',loss_cls,'\tloss_pts:',loss_pts)

            #accumulated loss
            total_loss = loss_cls.item() * args['cls_weight'] + loss_pts.item() * args['pts_weight']
            loss += total_loss * batch_size #may set loss function "reduction='sum'" to avoid this row of code

            #print('batch_size:',batch_size,'\ttotal_loss:',total_loss,'\tloss:',loss)

            # Save label and predictions.
            prediction = torch.argmax(nn.Softmax(dim=1)(output_cls), dim=1)
            all_label.append(targets.cpu().numpy())
            all_prediction.append(prediction.cpu().numpy())

            #if batch_idx % args['print_freq'] == 0:
                #print("Validate batch_idx: [{}], \t acc: {:.3f}\t Loss: {:.3f}".format(batch_idx,acc,total_loss.item()))

        #compute accuracy, precision, recall, and f1 value
        all_label = np.concatenate(all_label)
        #print(all_label)
        assert len(all_label.shape) == 1
        all_prediction = np.concatenate(all_prediction)
        #print(all_prediction)
        assert all_label.shape == all_prediction.shape
        p, r, f1, _ = precision_recall_fscore_support(all_label, all_prediction,average='binary')
        #confusion_mat = sklearn.metrics.confusion_matrix(all_label, all_prediction, labels=range(num_classes))
        acc = np.mean(all_prediction==all_label)

        # measure elapsed time
        time_elapsed = time.time() - since
        loss = loss/num_data
        print('Validation step: accuracy:{:.3f},\tprecision:{:.3f},\trecall:{:.3f},\tf1:{:.3f},\tloss:{:.3f},\t time:{:.0f}m {:.0f}s'              .format(acc, p, r, f1, loss, time_elapsed // 60, time_elapsed % 60))

        return loss

# In[14]:

def train_worker(args, train_loader, valid_loader):
    # create model
    global min_loss
    if args['arch'] == 'resnet18':
        print("===> creating model '{}'".format(args['arch']))
        model = ResNet(BasicBlock)
        #print(net)
    else:
        print("===> creating model 'Net'")
        model = Net()
        model.apply(weights_init)

    # Using GPU or CPU
    model = model.to(device)

    #Fineturning
    if args['locked_layers'] > 0:
        params_to_update = []
        c = 0
        for param in model.parameters():
            if c<= args['locked_layers']:
                param.requires_grad = False
            else:
                params_to_update.append(param)
            c += 1
        optimizer = torch.optim.SGD(params_to_update, args['lr'],
                                    momentum=args['momentum'],
                                    weight_decay=args['weight_decay'])
    else:
        optimizer = torch.optim.SGD(model.parameters(), args['lr'],
                                    momentum=args['momentum'],
                                    weight_decay=args['weight_decay'])
        print('===> no layers locked')

    #load model and params
    if args['resume'] and args['loading']:  # When training, set args['loading'] to False
        if os.path.isfile(args['resume']):
            print("===> loading checkpoint '{}'".format(args['resume']))
            checkpoint = torch.load(args['resume'])
            args['start_epoch'] = checkpoint['epoch']
            min_loss = checkpoint['min_loss']
            model.load_state_dict(checkpoint['state_dict'])
            optimizer.load_state_dict(checkpoint['optimizer'])
            print("===> loaded checkpoint '{}' (epoch {})"
                .format(args['resume'], checkpoint['epoch']))
        else:
            print("===> no checkpoint found at '{}'".format(args['resume']))
    else:
        print("===> no resumed model loaded.")

    # define loss function (criterion) and optimizer
    #criterion_pts = nn.MSELoss().to(device)
    criterion_pts = nn.SmoothL1Loss(reduction='mean').to(device)
    criterion_cls = nn.CrossEntropyLoss(weight=torch.tensor([1.,1.]), reduction='mean').to(device)

    #valid_losses = []
    patience = 3 #set auto stop training when loss didn't improve at a patience
    for epoch in range(args['start_epoch'],args['epochs']):
        #调整学习率
        adjust_learning_rate(optimizer, epoch, args)

        # train for one epoch
        if train_loader is not None:
            train(train_loader, model, criterion_pts,criterion_cls, optimizer, epoch, args)

        # evaluate on validation set
        valid_loss = validate(valid_loader, model, criterion_pts,criterion_cls, args)
        #valid_losses.append(valid_loss)

        # remember best min_loss and save checkpoint
        if min_loss < 0:
            min_loss = valid_loss
            is_best = False
        else:
            is_best = valid_loss < min_loss

        if is_best:
            patience = 3
            min_loss = valid_loss
        else:
            patience -= 1
        #min_loss = min(valid_loss, min_loss)

        if args['resume']: #saved at every epoch
            save_checkpoint({
                'epoch': epoch + 1,
                'arch': args['arch'],
                'state_dict': model.state_dict(),
                'min_loss': min_loss,
                'optimizer' : optimizer.state_dict(),
            }, is_best)

        if patience == 0:
            break

    #return train_losses, valid_losses

# In[15]:

def main():
    print('===> Loading Datasets')
    train_set = load_data('train')
    valid_set = load_data('valid')
    train_loader = torch.utils.data.DataLoader(train_set, batch_size=args['train_batch_size'], shuffle=True)
    valid_loader = torch.utils.data.DataLoader(valid_set, batch_size=args['test_batch_size'])
    print('len of train_loader and valid_loader', len(train_loader), len(valid_loader))

    if args['phase'].lower() == 'train':
        print('===> Start Training')
        train_worker(args, train_loader, valid_loader)
        #print('train loss:', train_losses,'/n valid loss:',valid_losses)
        print('====================================================')
    elif args['phase'].lower() == 'test':
        print('===> Test')
        # how to do test?
        train_worker(args, None, valid_loader)
        print('====================================================')

    elif args['phase'].lower() == 'finetune':
        print('===> Finetune')
        # how to do finetune?  Set args['phase'],args['loading'],args['locked_layers']
        args['loading'] = True
        args['locked_layers'] = 10
        train_worker(args, train_loader, valid_loader)
        print('====================================================')

    elif args['phase'].lower() == 'predict':
        print('===> Predict')
        # how to do predict?
        predict(txt_path, args)
        print('====================================================')

# In[17]:

#predict
def predict(txt_path, args):
    with open(txt_path) as f:
        lines = f.readlines();

    num_data = len(lines)
    print('number of data is ',num_data)
    model = ResNet(BasicBlock)
    checkpoint = torch.load(args['resume'])
    model.load_state_dict(checkpoint['state_dict'])
    model.eval()

    predictions = 0
    for line in lines:
        img_name, bbox, landmarks = parse_line(line)

        #img_path = 'ND.jpg'
        img_path = os.path.join('E:/jupyter/Python_Scripts/cv/cv/week6/project1/data/II',img_name)
        img_ = Image.open(img_path).convert('L').crop(bbox).resize(size)
        img = transforms.ToTensor()(img_)
        img = img.unsqueeze(0)
        #print(img.size(),type(img))

        pts,cls = model(img)
        prediction = torch.argmax(nn.Softmax(dim=1)(cls), dim=1)
        predictions += prediction.item()
        if prediction.item():
            pred_landmarks = pts.data.numpy()[0]
            #print('pred_landmarks',pred_landmarks.shape, type(pred_landmarks))
            #pred_landmarks = pred_landmarks.reshape(-1, 2)
            print('Show predicted landmarks:')
            show_landmarks(img_, pred_landmarks)
        else:
            pass
            #print('Image', img_name, 'is not a face image')
    print("Accuracy:", predictions/num_data)

# In[16]:

if __name__ == '__main__':
    main()
    txt_file = 'E:/jupyter/Python_Scripts/cv/cv/week6/project1/data/II/label.txt'
    predict(txt_file,args)

# In[ ]:

# In[20]:

def predict_(img_path):
    img_ = Image.open(img_path).convert('L').resize(size)
    img = transforms.ToTensor()(img_)
    img = img.unsqueeze(0)
    #print(img.size(),type(img))

    model = ResNet(BasicBlock)
    checkpoint = torch.load(args['resume'])
    model.load_state_dict(checkpoint['state_dict'])

    model.eval()
    pts,cls = model(img)
    print(cls)
    prediction = torch.argmax(nn.Softmax(dim=1)(cls), dim=1)
    print(prediction.item())
    if prediction.item():
        pred_landmarks = pts.data.numpy()[0]
        #print('pred_landmarks',pred_landmarks.shape, type(pred_landmarks))
        #pred_landmarks = pred_landmarks.reshape(-1, 2)
        print('Show predicted landmarks:')
        show_landmarks(img_, pred_landmarks)
    else:
        print('this is not a face image')

# In[21]:

img_paths = ['circle_cover.png','ND.jpg']
for img_path in img_paths:
    predict_(img_path)

# In[22]:

predict_('003932.jpg')

# In[ ]:


from numpy import *

def addColumnOne(X):
    # addColumnOne adds a column of ones at the end of the matrix X
    (n, p) = X.shape
    res = zeros((n, p+1))

    res[:, 1:] += X
    res[:, 0] += 1.0

    return res

def removeFirstColumn(X):
    # removeFirstColumn removes a column of ones at the beginning of the matrix X
    (n, p) = X.shape
    res = zeros((n, p-1))

    res += X[:, 1:]

    return res


import matplotlib.pyplot as plt
import os
import pickle
import torch
import json

from collections import defaultdict

def save_best_model(state_dict, model_dir: str, best_epoch: int, keep: int):
    save_to = os.path.join(model_dir, '{}.pkl'.format(best_epoch))
    torch.save(state_dict, save_to)
    model_files = [f for f in os.listdir(model_dir) if os.path.splitext(f)[-1] == '.pkl']
    epochs = [int(os.path.splitext(f)[0]) for f in model_files if str.isdigit(f[0])]
    outdated = sorted(epochs, reverse=True)[keep:]
    for n in outdated:
        os.remove(os.path.join(model_dir, '{}.pkl'.format(n)))

def find_best_model(model_dir: str):
    model_files = [f for f in os.listdir(model_dir) if os.path.splitext(f)[-1] == '.pkl']
    epochs = [int(os.path.splitext(f)[0]) for f in model_files if str.isdigit(f[0])]
    best_epoch = max(epochs)
    return os.path.join(model_dir, '{}.pkl'.format(best_epoch))

def save_and_visual_loss(loss: list, loss_file: str,
                         title: str = None, xlabel: str = None, ylabel: str = None, step: int = 1):
    with open(loss_file, 'wb') as f:
        pickle.dump(loss, f)

    plt.figure()
    plt.plot(range(step, step * len(loss) + 1, step), loss)
    if title:
        plt.title(title)
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    plt.savefig(loss_file[:-3] + 'png')

def save_args(args, save_to: str):
    args_dict = args.__dict__
    with open(save_to, 'w') as f:
        json.dump(args_dict, f, indent=2)

def load_args(args, load_from: str):
    args_dict = args.__dict__
    with open(load_from, 'r') as f:
        tmp_dict = json.load(f)
    for k, v in tmp_dict.items():
        args_dict[k] = v

def drop_feature(x, drop_prob):
    drop_mask = torch.empty(
        (x.shape[1],),
        dtype=torch.float32,
        device=x.device).uniform_(0, 1) < drop_prob
    x = x.clone()
    x[:, drop_mask] = 0
    return x

def read_map(map_file, multi=False):
    if multi:
        d = defaultdict(list)
    else:
        d = {}
    with open(map_file, 'r') as f:
        f.readline()
        if multi:
            for line in f:
                k, v = line.rstrip().split('\t')
                d[k].append(int(v))
        else:
            for line in f:
                k, v = line.rstrip().split('\t')
                d[k] = int(v)
    return d


from django.urls import path
from . import views
urlpatterns = [
    path('', views.home , name='home'),
    path('ajouter/', views.post_new, name='add'),
    path('modifier/<int:id>', views.update, name='update'),
    path('detail/<int:id>', views.detail, name='detail'),
    path('delete/<int:id>', views.delete, name='delete'),

]


a = list(input())

stack = []
result = 0
tmp = 1

for i in range(len(a)):
    if a[i] == '(':
        stack.append(a[i])
        tmp *= 2

    elif a[i] == '[':
        stack.append(a[i])
        tmp *= 3

    elif a[i] == ')':
        if not stack or stack[-1] == '[':
            result = 0
            break
        if a[i-1] == '(':
            result += tmp
        stack.pop()
        tmp //= 2

    else:
        if not stack or stack[-1] == '(':
            result = 0
            break
        if a[i-1] == '[':
            result += tmp
        stack.pop()
        tmp //= 3

if stack:
    print(0)
else:
    print(result)


from surprise import KNNWithMeans
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import train_test_split
import matplotlib.pyplot as plt

def main():

    # Charge movielens-100k dataset
    movielens_ds = Dataset.load_builtin('ml-100k')

    # Creer un jeu de test et de train ( 15%, 85%)
    trainset, testset = train_test_split(movielens_ds, test_size=.15)

    algo = KNNWithMeans()

    # Train sur le jeu de donnée trainset
    algo.fit(trainset)
    # Prediction sur le jeu de donnée testset
    predictions = algo.test(testset)

    # Affiche le RMSE
    accuracy.rmse(predictions)

    #print(predictions)

    result =[]
    for prediction in predictions:
        # Difference prediction et realite
        result.append(prediction.r_ui - prediction.est)

    # Histogramme du resultat
    plt.hist(result, 100)

    plt.show()

if __name__ == "__main__":
    main()


from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect

from forms import SolicitudForm, GestionForm
from django.contrib.auth.admin import User
from models import Solicitud
# Create your views here.

def home(request):

    user = User.objects.get(id=request.user.pk)

    solicitudes_propias = Solicitud.objects.filter(usuario_solicitante=user)
    solicitudes_asignadas = Solicitud.objects.filter(usuario_receptor=user)

    data = {
        'user':user,
        'solicitudes_propias':solicitudes_propias,
        'solicitudes_asignadas':solicitudes_asignadas,
    }

    return render(request, "home/index.html", data)

def crear_solicitud(request):

    if request.method == 'POST':

        form = SolicitudForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/home')

    else:
        form = SolicitudForm()

    return render(request, 'solicitud/crear_solicitud.html', {'form': form})

def eliminar_solicitud(request, solicitud_id):

    solicitud = Solicitud.objects.get(id=solicitud_id)
    solicitud.delete()

    return HttpResponseRedirect('/home')

def gestionar_solicitud(request, solicitud_id):

    if request.method == 'POST':

        form = GestionForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/home')

    else:
        form = GestionForm()

    solicitud = Solicitud.objects.get(id=solicitud_id)

    data = {
        'form':form,
        'solicitud':solicitud
    }

    return render(request, 'solicitud/gestionar_solicitud.html', data )


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

import pigpio
import time
pi=pigpio.pi()
pi.write(6, 0) # BCM 将6号引脚设置为低电平
pi.read(6)
pi.set_PWM_frequency(6, 50)#设定6号引脚产生的pwm波形的频率为50Hz
pi.set_PWM_range(6, 2000)
#指定要把14号引脚上的一个pwm周期分成多少份，这里是分成2000份，这个数据的范围是25-40000
#The range of pwm is (50,250),One serving corresponds to 0.9°
#It is recommended to adjust every two copies
#range:95(CCW)~140(vertical)~185(CW)
pi.set_PWM_dutycycle(6,140)
time.sleep(0.5)
#指定pwm波形的占空比，这里的占空比为140/2000,2000是上一个函数设定的

# import RPi.GPIO as GPIO
# import time
# GPIO.setwarnings(False)
# servopin = 12
# GPIO.setmode(GPIO.BOARD)
# GPIO.setup(servopin, GPIO.OUT)
# p = GPIO.PWM(servopin,50) #50HZ
# p.start(0)
# p.ChangeDutyCycle(7)
# time.sleep(0.5)#归零信号
# p.stop()


import argparse

import LIMS2DB.classes as lclasses
import LIMS2DB.parallel as lpar
import LIMS2DB.utils as lutils

from genologics_sql.tables import *
from genologics_sql.utils import *
from genologics_sql.queries import *
from sqlalchemy import text

def main(args):

    log = lutils.setupLog('worksetlogger', args.logfile)
    session=get_session()
    if args.ws:
        step=session.query(Process).filter_by(luid=args.ws).one()
        ws=lclasses.Workset_SQL(session, log, step)
        with open(args.conf) as conf_file:
            conf=yaml.load(conf_file, Loader=yaml.SafeLoader)
        couch=lutils.setupServer(conf)
        db=couch["worksets"]
        doc={}
        for row in db.view('worksets/lims_id')[ws.obj['id']]:
            doc=db.get(row.id)

        final_doc=lutils.merge(ws.obj, doc)

        db.save(final_doc)

    elif args.recent:
         recent_processes=get_last_modified_processes(session,[8,46,117,204,1454,1908], args.interval)
         processes_to_update=set()
         for p in recent_processes:
             if p.typeid in [117, 204] and p.daterun:#will only catch finished setup workset plate
                 processes_to_update.add(p)
             else:
                 processes_to_update.update(get_processes_in_history(session, p.processid, [117, 204]))

         log.info("the following processes will be updated : {0}".format(processes_to_update))
         lpar.masterProcessSQL(args, processes_to_update, log)

if __name__ == '__main__':
    usage = "Usage:       python workset_upload_sql.py [options]"
    parser = argparse.ArgumentParser(description=usage)

    parser.add_argument("-p", "--procs", dest="procs", type=int, default=8 ,
    help = "number of processes to spawn")

    parser.add_argument("-a", "--all", dest="recent", action='store_true', default=False,
    help = "tries to work on the recent worksets")

    parser.add_argument("-i", "--interval", dest="interval", default="2 hours",
    help = "interval to look at to grab worksets")

    parser.add_argument("-w", "--workset", dest="ws", default=None,
    help = "tries to work on the given ws")

    parser.add_argument("-c", "--conf", dest="conf",
    default=os.path.join(os.environ['HOME'],'opt/config/post_process.yaml'),
    help = "Config file.  Default: ~/opt/config/post_process.yaml")

    parser.add_argument("-l", "--log", dest="logfile",
    default=os.path.join(os.environ['HOME'],'workset_upload.log'),
    help = "log file.  Default: ~/workset_upload.log")
    args = parser.parse_args()

    main(args)


import gc
import os

import torch.cuda
from detectron2.config import get_cfg
import numpy as np
import pandas as pd
from trainers import TI_Trainer
from detectron2.data import build_detection_train_loader, DatasetMapper
from detectron2.evaluation import COCOEvaluator
import hooks
import detectron2.data.transforms as T
from data_utils import get_data_dicts,register_data

pd.set_option('display.max_columns', None)
data_dir = "/pers_files/Combined_final/Filet"
input_dir1 = f'{data_dir}/output'
input_dir2 = f'{data_dir}/output2'
model_name_base = "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x"
output_dir = os.path.join(data_dir,'output_train')
os.makedirs(output_dir,exist_ok=True)
splits = ['train','val']
data_dir = "/pers_files/Combined_final/Filet"
COCO_dicts = {split: get_data_dicts(data_dir,split) for split in splits } #converting TI-annotation of pictures to COCO annotations.
data_names = register_data('filet',['train','val'],COCO_dicts,{'thing_classes' : ['filet']}) #register data by str name in D2 api
model_name = "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x"

dfs = []
for i, input_dir in enumerate([input_dir1,input_dir2]):
    files = os.listdir(input_dir)
    for str in files:
        if str.endswith(".csv"):
            df = pd.read_csv(os.path.join(input_dir,str))
            df['round']= i
            dfs.append(df)
df = pd.concat(dfs,axis=0,ignore_index=False)
df = df.iloc[:,1:]
print()
df_alive =df.loc[np.logical_not(df['pruned']),:]
df_alive = df_alive.sort_values(by="score")
print(df_alive)
cfgs = []
df_alive['score_final'] = 0

df_alive.to_csv(os.path.join(output_dir,'pd_result_pre.csv'))

class Trainer(TI_Trainer):
    '''
    Example of a trainer that applies argumentations at runtime. Argumentations available can be found here:
    https://detectron2.readthedocs.io/en/latest/modules/data_transforms.html
    '''
    def __init__(self,augmentations,**params_to_Trainer):
        self.augmentations=augmentations
        self.period_between_evals = cfg.TEST.EVAL_PERIOD
        self.top_score_achieved = 0
        super().__init__(**params_to_Trainer)
    #overwrites default build_train_loader
    @classmethod
    def build_train_loader(cls, cfg):
          mapper = DatasetMapper(cfg, is_train=True, augmentations=augmentations)
          return build_detection_train_loader(cfg,mapper=mapper)

    @classmethod
    def build_evaluator(cls,cfg,dataset_name,output_folder=None):
        if output_folder is None:
            output_folder = cfg.OUTPUT_DIR
        return COCOEvaluator(dataset_name, ('bbox', 'segm'), False, output_dir=output_folder)

    def build_hooks(self):
        res = super().build_hooks()

        res.append(hooks.StopByProgressHook(patience=25*self.period_between_evals,delta_improvement=0.5,score_storage_key='segm/AP',save_name_base="best_model"))
        return res

    def helper_after_train(self,**kwargs):
        self.top_score_achieved = self.storage.latest()[f'best_segm/AP']

    def handle_stop(self,**kwargs):
        self.helper_after_train()

    def handle_else(self,**kwargs):
        self.helper_after_train()

augmentations = [
          T.RandomFlip(prob=0.5, horizontal=True, vertical=False),
          T.RandomFlip(prob=0.5, horizontal=False, vertical=True),
          T.RandomBrightness(0.9,1.1),
          T.RandomExtent([0.9, 1], [0, 0]),
          T.RandomRotation(angle=[-10, 10], expand=False, center=None, sample_style='range'),
          T.Resize((1024,1024)),

]

def do_train(augmentations,cfg):
    trainer = Trainer(augmentations=augmentations, cfg=cfg)
    trainer.resume_or_load(resume=True)
    trainer.train()
    return trainer.top_score_achieved[0]

for i in range(1,df_alive.shape[0]):
    model_specs = df_alive.iloc[i,:]
    output_dir = input_dir1 if model_specs['round']== 0 else input_dir2
    model_name = f"{model_name_base}_{model_specs.name}_output"
    cfg_dir =  os.path.join(data_dir,output_dir,'trials',model_name,'cfg.yaml')
    cfg = get_cfg()
    cfg.merge_from_file(cfg_dir)
    cfg.SOLVER.STEPS = (6000,12000,18000,24000,30000,)
    cfg.SOLVER.GAMMA = 0.75
    cfg.TEST.EVAL_PERIOD = 250
    cfg.DATASETS.TEST = ('filet_val',)
    cfgs.append(cfg)
    df_alive.iloc[i,-1] = do_train(augmentations,cfg)
    torch.cuda.empty_cache()
    gc.collect()

df_alive.to_csv(os.path.join(output_dir,'pd_result.csv'))

print(df_alive)

#--------------------------------------------


from django.shortcuts import get_object_or_404
from rest_framework import permissions

from accounts.models import Child
from studies.models import Response
from studies.permissions import StudyPermission

class FeedbackPermissions(permissions.BasePermission):
    def has_permission(self, request, view):
        """
        Only have permission to create the feedback if the user has permission to
        edit the associated study.
        """
        if request.method not in permissions.SAFE_METHODS:
            response = request.data.get("response")
            if response and response.get("id"):
                related_study = get_object_or_404(Response, id=response.get("id")).study
                user = request.user
                if not user.has_study_perms(
                    StudyPermission.EDIT_STUDY_FEEDBACK, related_study
                ):
                    return False
        return True

class ResponsePermissions(permissions.BasePermission):
    def has_permission(self, request, view):
        """
        Only have permission to create a response if the user is the parent of the
        associated child
        """
        if request.method not in permissions.SAFE_METHODS:
            child_id = request.data.get("child")
            if child_id and child_id.get("id"):
                child = get_object_or_404(Child, id=child_id.get("id"))
                if child.user != request.user:
                    return False
        return True


"""
You have a set of people, and most of these people have friends (who have other friends etc).

Model this problem and write a function in Python that tells you if a connection exists
between any two people  (regardless of the number of connections between them). For example,
if person A is friends with B, and B is friends with C, then A is connected to C.

What is the time and space complexity of your algorithm?

Can this problem be solved in constant time (e.g if you could somehow preprocess the data etc)?
If it can, feel free to write some code to demonstrate how.

"""

class FriendsGraph:
    def __init__(self, graph):
        self.graph = graph
        self.cache = set()
        self.preprocess()

    def preprocess(self):
        """
        Keep a cache to better check for connectivity
        between two people.
        """
        # Get a set of unique people names.
        # Iterate over such a set.

        # Complete the graph by using 'is friends'
        # and creating new pairs of relation.
        people = set(self.graph.keys())
        people.update(set(self.graph.values()))

        for indi in people:
            for indj in people.copy():
                if self.calc_friendship(indi, indj, []):
                    self.cache.add((indi, indj))

    def calc_friendship(self, m, n, visited):
        """
        Just checks whether two people are connected
        through friendship relation. It does so in a non
        cached manner.
        """
        x = None
        if m == n:
            return True
        elif m in visited:
            return False

        try:
            x = self.graph[m]
        except KeyError as excpt:
            return False

        visited.append(m)
        return self.calc_friendship(x, n, visited)

    def is_connected(self, m, n):
        """This method uses the cache to check whether
        two people are connected."""

        return (m, n) in self.cache

data = {
    'A':'B',
    'B':'C',
    'C':'D',
    'C':'J',
    'C':'K',
    'K':'A',
    'E':'F',

}

rels = FriendsGraph(data)

print('A and K:', rels.calc_friendship('A', 'K', []))
print('A and F:', rels.calc_friendship('A', 'F', []))

print('A and K:', rels.is_connected('A', 'K'))
print('A and F:', rels.is_connected('A', 'F'))


"""
Controller Robot Test Example
 Dans cette fonction on retrouve la complete manipulation de la classe Robot
 par les differents types de besoin pour le programme
 Liste de besoins:
 -Exercice Entrainement With Strike : ExerciceWithStrike
 -Robot Training with SparBar : RobotTrainSparbar
 -Robot training normal : RobotTrain
 -Main Menu IU Utilisateur: Main
 Ces besoins seront lances en paralleles et diriges par ce controlleur pour modeliser les differentes actions:

dfsd
"""
#Constantes Parametriques
from constants import CONST_FILE_ROBOT

#Implementation des Modules et Librairies Python
import re
import asyncio

#Implementation du des differents composants
from classes.classRobot import *
from classes.classDatabase import Database as BD
from classes.classMoyenne import Moyenne as Moyenne
from classes.classTimer import Timer as Timer
from classes.classCoup import Coup as Coup

class ControllerRobot:
    #Ports du robot qui seront transmis a la classe robot
    Robot = {}
    #Modules Installes du Robot
    RobotModules = {}

    InstalledModules = {'Ultrasonic','MotorDC'}

    def __init__(self, sControllerType,aParams = []):
        self.RobotModules = self.obtainRobotCaractersModules(CONST_FILE_ROBOT)
        self.Robot = self.recognizeTypes()
        self.Tasks = []
        if (sControllerType == "ExerciceWithStrike"):
            self.controllerExerciceWithStrike(aParams)
        elif (sControllerType == "RobotTrainSparbar"):
            self.controllerRobotTrainSparbar(aParams)
        elif (sControllerType == "RobotTrain"):
            self.controllerRobotTrain(aParams)
        elif (sControllerType == "Main"):
            self.controllerMain(aParams)
        else:
            #Remplace par module Error Not Train
            print("Error")
        return

    def recognizeTypes(self):
        Temporal = {}
        if(self.InstalledModules == {}):
            #Remplacer par module Error Not Installed
            print('Is not installed')
            return
        for element in self.RobotModules.keys():
            if(self.RobotModules[element]['Type']):
                if(self.getConfMod(element,'Type') in self.InstalledModules):
                    Temporal[element] = eval(self.getConfMod(element,'Type')+"("+str(self.getConfMod(element))+")")
                else:
                    #Remplacer par module Error Type not installed
                    print('Module Type is Not Installed')
            else:
                #Remplacer par module Error No Type
                print('Module Has No Type')
        return Temporal

    def controllerMain(self, aParams): return
    def controllerRobotTrain(self, aParams): return
    def controllerRobotTrainSparbar(self, aParams): return
    def controllerExerciceWithStrike(self, aParams): return
    def obtainRobotCaractersModules(self,sFile):
        ObjectsRegex = re.compile('Objects ?= ?/(.+?)/')
        file = open(sFile,'r').read()
        MatchesObjects = ObjectsRegex.match(file).groups(0)[0].split(',')
        DictRegex = {}
        ReturnReg = {}
        for match in MatchesObjects:
            DictRegex[match] = re.compile(r"<" + match + ">(.+?)<End" + match + ">")

        for Object in DictRegex.keys():
            if(DictRegex[Object].search(file) == None):
                #Remplace par Module erreur
                print(Object + 'Error')
            else:
                DictRegex[Object]= DictRegex[Object].search(file).groups(0)[0].strip().split(';')
                ReturnReg[Object] = {}
                for Caracteristique in DictRegex[Object]:
                    temporalVar = Caracteristique.split('=')

                    if(',' in temporalVar[1]):
                        ReturnReg[Object][temporalVar[0].strip()] = temporalVar[1].strip().split(',')
                    else:
                        ReturnReg[Object][temporalVar[0].strip()] = temporalVar[1].strip()

        return ReturnReg
    def getConfMod(self,Mod,Char=''):
        if(Mod not in self.RobotModules):
            #Module Dont exist Remplace Error
            print("Error")
            return
        else:
            if(Char == ''):
                return self.RobotModules[Mod]
            else:
                return self.RobotModules[Mod][Char]
    def displayModulesPrint(self):
        for material in self.RobotModules.keys():
            print("MATERIAL :" + material)
            for Specs in robot.RobotModules[material].keys():
                print(Specs+ " :: "+ str(robot.RobotModules[material][Specs]))
            print("\n")
    async def useModule(self,Mod,Method = "run",Requests = 1,Sleep = 0, aParams=[]):
        tasks = []
        if(Mod not in self.Robot.keys()):
            #Module Dont exist Remplace Error
            print("Error")
        else:
            if(Method in dir(self.Robot[Mod])):
                sParams = str(aParams).strip("[")
                sParams = sParams.strip("]")

                for idx in range(1, Requests+1):
                    Query = "self.Robot['" + Mod + "']." + Method + "(" + sParams + ")"
                    tsk = asyncio.ensure_future(eval(Query))
                    self.Tasks.append(tsk)
                    asyncio.sleep(Sleep)

            else:
                #Replace for Module Error, Method Composant Dont Exist
                print("Error h")

    def run(self):
        Loop = asyncio.get_event_loop()
        Loop.run_until_complete(asyncio.gather(*self.Tasks))
        self.Tasks = []
    async def _do(self, Funcs = []):
        await asyncio.wait(Funcs)

    def do(self,Funcs = []):
        try:
            loop = asyncio.get_event_loop()
            loop.run_until_complete(self._do(Funcs))
        except Exception:
            #Remplace error Execution not possible
            print("Error")
            return
        self.run()

""""

robot = ControllerRobot('Main')
print(robot.Robot['MoteurSparBar'].PWM)
robot.do(
    [
        robot.useModule('UltrasonGaucheTorse','mesureForce',10,0,[1]),
        robot.useModule('MoteurSparBar','turnSpeed',10,1,[2])
    ]
)

"""


def eyes():
    #to create timelapse videos from still you need to: sudo apt-get install libav-tools
    #to playback the video using mplayer you need to : sudo apt-get install mplayer
    import os
    import numpy as np
    import cv2
    import datetime
    import imutils
    import time
    import subprocess

    # need opencv  library
    # sudo pip3 install imutils
    # " sudo python3 mogmog.py "

    cap = cv2.VideoCapture(0)
    #codec = cv2.VideoWriter_fourcc(*'X264')

    out = cv2.VideoWriter('test.mp4', 0x00000021, 20.0, (320,240))

    #cap = cv2.resize(capp, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
    fgbg = cv2.createBackgroundSubtractorMOG2(varThreshold=150)
    #carsPerSecond = 0
    eachCar = 0
    oldX = 0
    oldY = 0
    oldSec = 0
    totalCarsSeen = 0
    start = time.time()
    runSince = time.strftime("%H:%M:%S")

    i = 0

    left = '../eyes/1.bmp'
    left = cv2.imread(left)
    left = cv2.resize(left, (800,480))

    right = '../eyes/7.bmp'
    right = cv2.imread(right)
    right = cv2.resize(right, (800,480))

    mid = '../eyes/4.bmp'
    mid = cv2.imread(mid)
    mid = cv2.resize(mid, (800,480))

    while(1):
        ret, frame = cap.read()
        #out.write(frame)

        count = cap.get(cv2.CAP_PROP_POS_FRAMES)
    # left = '1.bmp'
    # left = cv2.imread(left) #, cv2.IMREAD_GRAYSCALE)
    # left = cv2.resize(left, (800,480))

        show = mid
    #    warning = 'warning.png'
    #    warning = cv2.imread(warning, cv2.IMREAD_GRAYSCALE)
    #    mid = cv2.resize(mid, (100,80))
        if int(count)%1 == 0:
            frame = cv2.resize(frame, (320, 240))
            out.write(frame)
    ##
    #        kernel = np.ones((2,2), np.float32)/4 # / k*2
    #        frame = cv2.filter2D(frame, -1, kernel)
    ##
            fgmask = fgbg.apply(frame)
    #        fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
            kernel2 = np.ones((5,5),np.uint8)
            erosion = cv2.erode(fgmask,kernel2,iterations = 2)
            dilation = cv2.dilate(erosion,kernel2,iterations = 2)
    #        cv2.rectangle(frame, (80, 25), (250, 100), (0, 255, 0), 2) # DEBUG Displays co-ordinates and size of countours detected

            im2, contours, hierarchy = cv2.findContours(dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            for c in contours:
            # if the contour is too small, ignore it
                if cv2.contourArea(c) < 500:
                    continue

        # compute the bounding box for the contour, draw it on the frame,
        # and update the text
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
    #            print("x=", x, "y=", y, "width=", w, "height=", h) #DEBUG line: Displays co-ordinates and size of countours detected

                #if y < 30 and w > 50 and w < 200 and h > 200:
                #    timestr = time.strftime("%S")
                #print("timestr=" + str(timestr) + "oldSec=" + str(oldSec)) #Debug line
                #    if timestr == oldSec or int(timestr) == int(oldSec) + 1:
                #        end = time.time()
                #        elapsed = end - start
                #        if elapsed > 10:
                #            totalCarsSeen += 1
                #            print("------------------------------------------")
                #            print("Total Human Seen Since " + str(runSince) + " = " + str(totalCarsSeen))
                #            print("------------------------------------------")
                #            oldX = 0
                #            oldY = 0
                        #cv2.imwrite('car{0:04d}.png'.format(totalCarsSeen), frame) # only saves one frame for each car, moved it.

                #        fulltimestr = time.strftime("%H:%M:%S")
                #        print("Detect Human " + fulltimestr)
    #               cv2.imwrite('car{0:04d}.png'.format(eachCar), frame) # this saves each car frame to a PNG file and numbers them sequantially.
                #        eachCar += 1
                #        if oldX != 0 and oldX > x:
                #            print("going left")
                #        if oldX != 0 and oldX < x:
                #            print("going right")
                #        oldX = x
                #        oldY = y
                #        start = time.time()

                #    oldSec = timestr
    #            if x > 475 and h > 100:
    #                print("Intruders")
                #    timestrI = time.strftime("%Y%m%d-%H%M%S")
    #            cv2.imwrite('intruder' + timestrI + '.png', frame)
        if w < 120:
            if x < 108:
    #		subprocess.call("cat left.txt", shell=True)
                show = left
#                print "left"
            elif x < 216:
    #		subprocess.call("cat mid.txt", shell=True)
                show = mid
#                print "middle"
            elif x < 320:
    #		subprocess.call("cat right.txt", shell=True)
                show = right
#                print "right"
        else:
    #	    show = warning
            pass #	    print "Too close ... Warning !!"
    #        cv2.imshow('Background Subtractor MOG2',fgmask)
    #        cv2.imshow("Security Feed", frame)
            cv2.namedWindow("change", cv2.WND_PROP_FULLSCREEN)
            cv2.setWindowProperty("change",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
            cv2.imshow("change", show)
    #       cv2.imshow("Erosion", erosion)
    #      cv2.imshow("Dilation", dilation)

        # You have to click on a Video Window for the control keys to work, not the terminal window
        key=cv2.waitKey(30) & 0xFF
        # Press c to create a timelapse video - you need libav-tools installed
    #        if key == 99:
    #            print("Creating timelapse video")
    #            os.system("rm cartimelapse.mp4")
    #            os.system("avconv -r 10 -i car%04d.png -r 10 -vcodec libx264 -vf scale=640:480 cartimelapse.mp4 &")
    #            os.system("clear")
        # Press p to playback the timelapse video - you need mplayer installed
    #        elif key == 112:
    #            print("Play timelapse video")
    #            os.system("mplayer cartimelapse.mp4 &")
    #            os.system("clear")
        # Press ESC to Exit
        if key  == 27:
            break

        else:
            pass
    cap.release()
    out.release()
    cv2.destroyAllWindows()


import json
import os

import gspread
from oauth2client.service_account import ServiceAccountCredentials

GOOGLE_SERVICE_CREDS_JSON = os.environ.get("GOOGLE_SERVICE_CREDS_JSON")
GOOGLE_SHEET_NAME = os.environ.get("GOOGLE_SHEET_NAME")
GOOGLE_SHEET_TAB_NAME = os.environ.get("GOOGLE_SHEET_TAB_NAME")

def setup_gspread_worksheet():
    print("Authorizing gspread..")
    scope = [
        "https://www.googleapis.com/auth/drive",
        "https://www.googleapis.com/auth/spreadsheets",
    ]
    credentials = ServiceAccountCredentials.from_json_keyfile_dict(
        json.loads(GOOGLE_SERVICE_CREDS_JSON), scopes=scope,
    )
    gc = gspread.authorize(credentials)
    sh = gc.open(GOOGLE_SHEET_NAME)
    return sh.worksheet(GOOGLE_SHEET_TAB_NAME)

def write_header_row(worksheet, column_names):
    print("Updating the header row..")
    row = 1
    column = 1
    for key in column_names:
        worksheet.update_cell(row, column, key)
        column += 1

def append_row(worksheet, row):
    worksheet.append_row(row, value_input_option='USER_ENTERED')

def insert_row(worksheet, row, row_number):
    worksheet.insert_row(row, row_number, value_input_option='USER_ENTERED')

def update_cell(worksheet, column, row, new_value):
    worksheet.update_cell(row, column, new_value)


from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
from flask_pagedown import PageDown

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
pagedown = PageDown()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'

class ReverseProxied(object):
    '''Wrap the application in this middleware and configure the
    front-end server to add these headers, to let you quietly bind
    this to a URL other than / and to an HTTP scheme that is
    different than what is used locally.

    In nginx:
    location /myprefix {
        proxy_pass http://192.168.0.1:5001;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Scheme $scheme;
        proxy_set_header X-Script-Name /myprefix;
        }

    :param app: the WSGI application
    '''
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
        if script_name:
            environ['SCRIPT_NAME'] = script_name
            path_info = environ['PATH_INFO']
            if path_info.startswith(script_name):
                environ['PATH_INFO'] = path_info[len(script_name):]

        # scheme = environ.get('HTTP_X_SCHEME', '')
        # if scheme:
        #     environ['wsgi.url_scheme'] = scheme
        return self.app(environ, start_response)

def create_app(config_name):
    app = Flask(__name__)

    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
    photos = UploadSet('photos', IMAGES)
    configure_uploads(app, photos)
    patch_request_class(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api_1_0 import api as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')

    return app


from PIL import Image
import random
import matplotlib.pyplot as plt

x=0.0
y=0.0
plt.figure(figsize=(20,30))
X=[]
Y=[]
for k in range(0,300000):
    p=random.random()
    if p <0.01:
        next_x = 0
        next_y = 0.16*y
    elif p < 0.86:
        next_x = 0.85*x + 0.04*y
        next_y = -0.04*x+0.85*y+1.6
    elif p <0.93:
        next_x = 0.2*x - 0.26*y
        next_y = 0.23*x + 0.22*y + 1.6
    else:
        next_x = -0.15*x + 0.28*y
        next_y = 0.26*x + 0.24*y + 0.44

    x = next_x
    y = next_y
    X.append(x)
    Y.append(y)

plt.scatter(X,Y,marker='o', color='g',s=0.5)
plt.show()


from django.conf.urls import patterns, url
from viewcam import views, ajaxurl

urlpatterns = patterns('',

	# html url
	url(r'^$', views.template, name='index'),
	url(r'test$', views.test, name='test'),
	url(r'highchart$', views.load_high_chart, name='test'),
	url(r'testcal$', views.openCal, name='testcal'),
	url(r'template$', views.template, name='template'),

	# ajax url
	url(r'^gettime$', ajaxurl.get_time, name='getTime'),
	url(r'^getrealinfo$', ajaxurl.get_info, name='getinfo'),
	url(r'^gettemp$', ajaxurl.get_temp, name='getTem'),
	url(r'^control/dev(?P<device_id>\d+)/(?P<action_id>\d+)/$', ajaxurl.control_device, name='control'),
	url(r'getallstatus', ajaxurl.get_all_status, name='get_all_status'),
	url(r'getstatus/dev(?P<device_id>\d+)/$', ajaxurl.get_device_status, name='get_status'),

	# set alarm time
	url(r'^alarm/dev(?P<device_id>\d+)/timer(?P<timer>\d+)/(?P<action>\w+)/(?P<day>\d{1,2})/(?P<month>\d{1,2})/(?P<year>\d{4})/(?P<hour>\d{1,2})/(?P<minute>\d{1,2})/$',
		ajaxurl.alarm_by_date, name='alarm_date'),

	url(r'^alarm/dev(?P<device_id>\d+)/timer(?P<timer>\d+)/(?P<action>\w+)/(?P<minute>\d{1,10})/$',
		ajaxurl.alarm_by_minute, name='alarm_minute'),

	url(r'^alarmtemp/dev(?P<device_id>\d+)/(?P<action>\w+)/(?P<condition>\w+)/(?P<value>\d{1,10})/$',
		ajaxurl.alarm_by_temp, name='alarm_by_temp'),

	url(r'^alarmtemp/dev(?P<device_id>\d+)/remove/$',
		ajaxurl.remove_alarm_by_temp, name='remove_alarm_by_temp'),

	url(r'^alarm/dev(?P<device_id>\d+)/timer(?P<timer>\d+)/remove/$',
		ajaxurl.remove_alarm_by_time, name='remove_alarm_by_time'),

	#get alert time infor
	url(r'^alarmtime/dev(?P<device_id>\d+)/timer(?P<timer>\d+)/$', ajaxurl.get_alarm_by_time, name='get_alarm_by_time'),
	url(r'^alarmtime/all/$', ajaxurl.get_all_alarm_by_time, name='get_all_alarm_by_time'),

	url(r'^alarmtemp/dev(?P<device_id>\d+)/$', ajaxurl.get_alarm_by_temp, name='get_alarm_by_temp'),
	url(r'^alarmtemp/all$', ajaxurl.get_all_alarm_by_temp, name='get_alarm_by_temp'),

	url(r'^gettemplist/(?P<interval>\d{1,10})/(?P<unit>\w+)$', ajaxurl.get_temp_list, name='get_temp_list'),

    # control camera

    url(r'^controlcam/(?P<action>\w+)$', ajaxurl.control_camera, name='control_cam'),

    # px, bit_rate, frame_ps, sharpness, contrast, brightness, saturation, iso, ev, ex, awb
    url(r'^controlcam/(?P<px>\w+)/(?P<bit_rate>\w+)/(?P<frame_ps>\w+)/(?P<sharpness>-?\w+)/(?P<contrast>-?\w+)'
        r'/(?P<brightness>\w+)/(?P<saturation>-?\w+)/(?P<iso>\w+)/(?P<ev>-?\w+)/(?P<ex>\w+)/(?P<awb>\w+)$',
        ajaxurl.set_property_camera, name='set_property_cam'),

	url(r'^testhightchart/$', ajaxurl.test_high_chart, name='test_hight_chart'),

	#action/(?P<day>\d{2})/(?P<month>\d{2})/(?P<year>\d{4})/(?P<hour>\d{2})/(?P<minute>\d{2})/$

)


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

import json
from flask import Blueprint, render_template, session, request, redirect
from main.models import Country,Objeto
from main.database import engine
from sqlalchemy import select

view = Blueprint('admin_bludprint', __name__)

@view.route('/country/list')
def country_list():
    resp = None
    status = 200
    try:
        conn = engine.connect()
        stmt = select([Country])
        rs = conn.execute(stmt)
        resp = [dict(r) for r in conn.execute(stmt)]
    except Exception as e:
        resp = [
            'Se ha producido un error en listar los paises',
            str(e)
        ]
        status = 500
    return json.dumps(resp), status

@view.route('/objeto/list')
def objeto_list():
    resp = None
    status = 200
    try:
        conn = engine.connect()
        stmt = select([Objeto])
        rs = conn.execute(stmt)
        for r in conn.execute(stmt):
            print(r)
        resp = [dict(r) for r in conn.execute(stmt)]
    except Exception as e:
        resp = [
            'Se ha producido un error en listar los paises',
            str(e)
        ]
        status = 500
    return json.dumps(resp), status


import requests
from lxml import etree
import re
def fangtx():
    print('数据爬取中,请等待...')
    start_url = 'http://xian.newhouse.fang.com/house/s/b9{}'
    with open('/Users/zlinzhang/Downloads/ftx.csv', 'a') as f:
        f.write('小区，大小，区域，详细信息，价格，电话'+'\n')
        for i in range(36):
            url=start_url.format(i+1)
            headers = {
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"

            }
            res = requests.get(url, headers=headers)
            ret = res.content.decode('gbk')
            result = etree.HTML(ret)
            content_list = result.xpath(".//div[@id='newhouse_loupai_list']/ul/li")
            if content_list:
                for content in content_list:
                    if content_list.index(content)==5:
                        continue
                    title=content.xpath(".//div[@class='nlcd_name']/ a / text()")
                    title = title[0].strip() if len(title) > 0 else ''
                    #print(title)

                    area = content.xpath(".//span[@class='sngrey']/text()")
                    area = area[0].strip() if len(area) > 0 else ''
                    #print(area)

                    address = content.xpath(".//span[@class='snarey']/../text()")
                    address = address[1].strip() if len(address) > 0 else ''
                   # print(address)

                    size = content.xpath(".//div[contains(@class,'house_type')]/text()[last()]")
                    size = re.sub(r"\t|\n|", '', size[0]) if len(size) > 0 else ''
                   # print(size)

                    price1 = content.xpath(".//div[@class='nhouse_price']/span/text()")
                    price3 = content.xpath(".//div[@class='kanzx']/h3/a/text()")
                    price2 = content.xpath(".//div[@class='nhouse_price']/em/text()")
                 #   price = html.xpath('//*[@class="nhouse_price"]//span|//*[@class="kanesf"]//p//a|//*[@class="kanzx"]//h3//a')

                    if price3:
                        price = '优惠楼盘'
                    if price1:
                        if price1[0]=='价格待定':
                            price='价格待定'
                        else:
                            price = price1[0]+price2[0]

                    #print(price1)

                    phone=content.xpath(".//div[@class='tel']/p//text()")
                    phone=''.join(phone)

                    f.write(title+','+size+','+area+','+address+'+'+price+','+phone+','+'\n')

if __name__ == '__main__':
    fangtx()
    print('爬取完毕')


import json
import copy
import stripe
import uuid
from decimal import Decimal

from django.contrib.auth.models import User
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse, JsonResponse
from django.db.models import Sum
from django.conf import settings

#from bonusly import *
from giftbit import (
    giftbit_sendcard,
    list_rewards,
)
from credits.models import *
from parent.models import *
from common.exceptions import ApiException
from common.decorators import login_required_api
from pd import settings

def get_total_points(user_id=None):
    # points are thanks
    if not user_id:
        user_id = request.user.id
    current_user = get_object_or_404(User, id=user_id)
    total = Points.objects.filter(user=current_user).aggregate(Sum('amount'))['amount__sum']
    if not total:
        total = 0
    return total

def get_balance(user_id):
    # SocialCoins come from dollars earned and spent on gift cards
    balance = SocialCoins.objects.filter(user__id=user_id).aggregate(balance=Sum('amount'))
    return balance['balance'] if balance['balance'] else 0

def get_dollars_earned(user_id):
    # dollars only come to the system from counterparty's credit card
    total = Transactions.objects.filter(user__id=user_id, amount__gt=0).aggregate(total=Sum('amount'))
    return total

def get_fee(amount):
    return APP_FEE * abs(amount)

def record_transaction_fee(transaction):
    tr = {}
    tr['transaction'] = transaction
    tr['amount'] = get_fee(transaction.amount)
    Fees.objects.create(**tr)

@require_POST
@csrf_exempt
@login_required_api
def give(request, type):
    # credits_points, credits_transactions, credits_fees;
    try:
        give_json = json.loads(request.body)
    except (ValueError, TypeError) as e:
        raise ApiException('Invalid json ' + request.body, 400)
    required_fields = ['counterparty', 'amount']
    for f in required_fields:
        if f not in give_json:
            raise ApiException('{} is required'.format(f), 400)
    try:
        to_user = User.objects.get(id=give_json['counterparty'])
    except User.DoesNotExist:
        raise ApiException('to_user_id {} does not exist'.format(give_json['to_user_id']), 400)
    try:
        give_json['amount'] = abs(int(give_json['amount']))
    except ValueError:
        raise ApiException('amount {} must be an integer '.format(give_json['amount']), 400)
    if type == 'giftcard' and not 'brand_code' in give_json:
        raise ApiException('brand_code is mandatory', 400)

    current_user = get_object_or_404(User, id=request.user.id)
    debit_o = None
    giftcard_info = None
    if (type in ['giftcard', 'money']):
        token = give_json['token'] if 'token' in give_json else None
        save_info = False if 'save_info' in give_json and give_json['save_info'] == 0 else True

        charge_o = charge_user(current_user, give_json['amount'], token, save_info)
        give_json.pop('token', None)

        debit_o = Transactions.objects.create(
            user=to_user,
            counterparty=current_user,
            amount=give_json['amount'],
            charge_id=charge_o["id"],    #  "ch_1Abxo9IbhKiecKLZCindPGrb",
            balance_transaction_id=charge_o["balance_transaction"], # "txn_1Abxo9IbhKiecKLZwT9RTmiQ",
            hashtag=give_json['hashtag'],
            reason=give_json['reason']
        )
        credit_o = Transactions.objects.create(
            user=current_user,
            counterparty=to_user,
            amount=-give_json['amount'],
            charge_id=charge_o["id"],
            balance_transaction_id=charge_o["balance_transaction"],
            hashtag=give_json['hashtag'],
            reason=give_json['reason']
        )
        record_transaction_fee(credit_o)
        # award socail coins. Each coin equals to 1 dollar
        sc = SocialCoins.objects.create(
            user=to_user,
            counterparty=current_user,
            amount=abs(give_json['amount']),
            transaction=debit_o,
            hashtag=give_json['hashtag'],
            reason=give_json['reason']
        )
    if type == 'giftcard':
        giftcard_info = send_giftcard(request, give_json)
    # award 1 thank you point in case a user gives either thanks or dollars
    points_o = Points.objects.create(
        user=to_user,
        counterparty=current_user,
        amount=1,
        transaction=debit_o,
        hashtag=give_json['hashtag'],
        reason=give_json['reason']
    )
    # do not post points to bonusly unless they are monetary or the user will get more than was gifted
    #if (type == 'money'):
    #    post_points(abs(give_json['amount']), give_json['hashtag'] if 'hashtag' in give_json else None)
    return JsonResponse(
        {
        'from' : debit_o.serialize() if debit_o else current_user.id,
        'to' : credit_o.serialize() if debit_o else to_user.id,
        'points' : points_o.serialize(),
        'giftcard': giftcard_info if giftcard_info else {}
        }
    )

def charge_user(user, amount, token=None, save_info=True):
    # Set your secret key: remember to change this to your live secret key in production
    # See your keys here: https://dashboard.stripe.com/account/apikeys
    stripe.api_key = settings.STRIPE_API_KEY
    amount += get_fee(amount)
    amount = int(amount*100)

    if not token and user.parent_profile.stripe_id:
        # No token means the user want to re-use his previous credit card
        # When it's time to charge the customer again, retrieve the customer ID.
        # TODO figure out a way to test this without front-end: get sample stripe_id or generate test token in python.
        try:
            charge = stripe.Charge.create(
              amount=amount,
              currency="usd",
              customer=user.parent_profile.stripe_id, # Previously stored, then retrieved
            )
        # save_info does not matter cause it is the same card.
        except Exception as e:
            raise ApiException('Payment Exception ' + str(e), 400)
    elif token:
        # User got the token from stripe in exchange for his credit card info
        try:
            if not save_info:
                # Charge the user's card:
                charge = stripe.Charge.create(
                    amount=amount,
                    currency="usd",
                    description="{0} {1} was charged {2}".format(user.first_name, user.last_name, amount),
                    source=token,
                    receipt_email=user.email
                )
            else:
                # TODO - will this work?
                # first search to make sure the customer does not yet exist
                # if it does, attach the new token to her.
                if user.parent_profile.stripe_id:
                    # user wants to save on file new credit card
                    customer = stripe.Customer.retrieve(user.parent_profile.stripe_id)
                    customer.source = token
                    customer.save()
                else:
                    # user never saved a cardit card on file
                    customer = stripe.Customer.create(
                        email=user.email,
                        source=token
                    )
                    # Save the customer ID and other info in a database for later.
                    pp = get_object_or_404(ParentProfile, user=user)
                    pp.stripe_id = customer.id
                    pp.save()
                # Charge the Customer instead of the card:
                # This is not that great cause UI probably does better error handling
                charge = stripe.Charge.create(
                    amount=amount,
                    currency="usd",
                    customer=customer.id,
                )
        except Exception as e:
            raise ApiException('Payment Exception ' + str(e), 400)
    else:
        raise ApiException('Token is not provided (card not entered) and no customer.id (credit card) on file', 400)
    return charge

#@login_required_api
def display_rewards(request):
    #ceiling = get_balance(request.user.id)
    #rewards = list_rewards(ceiling=ceiling)
    rewards = list_rewards()
    return JsonResponse(rewards, safe=False)

@login_required_api
@require_POST
@csrf_exempt
def cash_out(request):
    card = json.loads(request.body)
    current_user = get_object_or_404(User, id=request.user.id)
    redemption = redeem_points(card)
    redemption = redemption['redemption']
    r = Redemptions(claim_url=redemption['claim_url'],
        certificate_url=redemption['certificate_url'],
        denomination_id=card['denomination_id'],
        name=card['name'])
    r.save()
    sc = SocialCoins(user=current_user,
        counterparty=bonusly_user,
        amount=-card['price'],
        redemption=r)
    sc.save()
    return show_balance(request, request.user.id)
    #return JsonResponse(r, safe=False) #? TODO why TypeError: <Redemptions: Redemptions object> is not JSON serializable

@login_required_api
def show_dollars_earned(request, user_id=None):
    total = get_dollars_earned(request.user.id if not user_id else user_id)
    return JsonResponse(total)

@login_required_api
def show_points(request, user_id=None):
    total = get_total_points(request.user.id if not user_id else user_id)
    return JsonResponse({'total points' : total})

@login_required_api
def show_balance(request, user_id=None):
    total = get_balance(request.user.id if not user_id else user_id)
    return JsonResponse({'total $$' : total})

@login_required_api
@require_GET
def show_withfee(request):
    amount = request.GET.get('amount', 0)
    if not amount:
        raise ApiException('?amount= is required in the url', 400)
    total = int(amount) + get_fee(int(amount))
    return JsonResponse({'total $$' : total})

def generate_giftcard_id():
    # TODO
    return 0

def send_giftcard(request, gift_info):
    current_user = get_object_or_404(User, id=request.user.id)
    #sender = get_object_or_404(ParentProfile, user=current_user)
    if not 'brand_code' in gift_info:
        raise ApiException('Please select a gift card', 400)
    if not 'amount' in gift_info:
        raise ApiException('Please select a amount', 400)
    if not 'counterparty' in gift_info:
        raise ApiException('Please specify counterparty', 400)
    if not 'reason' in gift_info:
        gift_info['message'] = ('With much gratitude plase accept my '
         'thank you!\n{} {}'.format(current_user.first_name, current_user.last_name))
    else:
        gift_info['message'] = gift_info['reason']
    gift_info['subject'] = '{} {} sent you a gift card.'.format(current_user.first_name, current_user.last_name)
    receiver_u = get_object_or_404(User, id=gift_info['counterparty'])
    gift_info['contacts'] = [
        {
            'email':     receiver_u.email,
            'firstname': receiver_u.first_name,
            'lastname':  receiver_u.last_name
        }
    ]
    gift_info['price_in_cents'] = gift_info['amount'] * 100
    gift_info['brand_codes']    = [gift_info['brand_code']]
    gift_info['id']             = str(uuid.uuid4())
    giftbit_sendcard(gift_info)
    giftcard = UserGiftcards(
        user=receiver_u,
        sender=current_user,
        campaign_id=gift_info['id']
    )
    giftcard.save()
    return giftcard.serialize()


# python3

class HeapBuilder:
  def __init__(self):
    self._swaps = []
    self._data = []

  def ReadData(self):
    n = int(input())
    self._data = [int(s) for s in input().split()]
    assert n == len(self._data)

  def WriteResponse(self):
    print(len(self._swaps))
    for swap in self._swaps:
      print(swap[0], swap[1])

  def SiftDown(self,i):
    leftChild = i*2 + 1
    rightChild = i*2 + 2
    length = len(self._data)
    while leftChild < length:
      # store default min value to be left
      m = self._data[leftChild]

      # if right child is < length take min of left and right children
      if rightChild < length:
        m = min(self._data[rightChild],self._data[leftChild])

      # swap with the minimum of left or right, if that respective child
      # is greater than the parent which is i
      if m == self._data[leftChild] and self._data[leftChild] < self._data[i]:
        self._swaps.append((i,leftChild))
        self._data[leftChild],self._data[i] = self._data[i],self._data[leftChild]
        i = leftChild
      elif rightChild < length and m == self._data[rightChild] and self._data[rightChild] < self._data[i]:
        self._swaps.append((i,rightChild))
        self._data[rightChild],self._data[i] = self._data[i],self._data[rightChild]
        i = rightChild
      else:
        # if parent is not greater than either left or right child, just traverse down
        i = leftChild

      leftChild = 2*i + 1
      rightChild = 2*i + 2

  def GenerateSwaps(self):
    size = len(self._data)

    if size > 1:
      for i in range(size//2,-1,-1):
        self.SiftDown(i)

  def Solve(self):
    self.ReadData()
    self.GenerateSwaps()
    self.WriteResponse()

if __name__ == '__main__':
    heap_builder = HeapBuilder()
    heap_builder.Solve()


from .motor import Motor, MotorDirection
import Encoder
from .pins import *
from .sensors import Sensors
from .GPIOhelpers import *
from .PID import *
setGPIO()
import time
import signal, sys

MOTOR_SPEED = 47
TICKS_CELL = 260
TICKS_TURN = 231
WALL_THRESHOLD_DIAG = 85
WALL_DISTANCE_DIAG = 75
WALL_DIST = 80
TIME = 3000
KP3 = 0.5
KP = 0.4
KP2 = .17
KI = 0.01
KD = 0.05
class Motors:
    def __init__(self):
        self.sensors = Sensors([pins.tof_front,pins.tof_rear,pins.tof_fleft,pins.tof_fright,pins.tof_rleft,pins.tof_rright], ["front", "rear","fleft","fright","rleft","rright"], [0x30,0x31,0x32,0x33,0x34,0x35])
        self._frontIR = self.sensors.sensors["front"]
        self._fleftIR = self.sensors.sensors["fleft"]
        self._frightIR = self.sensors.sensors["fright"]
        self._rearIR = self.sensors.sensors["rear"]
        self._rleftIR = self.sensors.sensors["rleft"]
        self._rrightIR = self.sensors.sensors["rright"]

        self.dir = True

        Encoder.init(pins.encoder_pin_l1, pins.encoder_pin_l2, 0)
        Encoder.init(pins.encoder_pin_r1, pins.encoder_pin_r2, 1)

        self.left_motor = Motor("Left", pins.motor_speed_l, pins.motor_direction_l, 0)

        self.right_motor = Motor("Right", pins.motor_speed_r, pins.motor_direction_r, 0)

        self.setpointL = 0
        self.inputL = 0
        self.PIDLeft = PID(self.inputL, self.setpointL, KP3, 0.002, 0.000, DIRECT, Timer)
        self.PIDLeft.set_output_limits(-1 * MOTOR_SPEED*1.5, MOTOR_SPEED*1.5)
        self.PIDLeft.set_mode(AUTOMATIC)

        self.setpointR = 0
        self.inputR = 0
        self.PIDRight = PID(self.inputR, self.setpointR, KP3, 0.002, 0.000, DIRECT, Timer)
        self.PIDRight.set_output_limits(-1 * MOTOR_SPEED*1.5, MOTOR_SPEED*1.5)
        self.PIDRight.set_mode(AUTOMATIC)

        self.setpointfL = 0
        self.inputfL = 0
        self.PIDfLeft = PID(self.inputfL, self.setpointfL, 2.0, 0.002, 0.000, DIRECT, Timer)
        self.PIDfLeft.set_output_limits(-1 * MOTOR_SPEED, MOTOR_SPEED)
        self.PIDfLeft.set_mode(AUTOMATIC)

        self.setpointfR = 0
        self.inputfR = 0
        self.PIDfRight = PID(self.inputfR, self.setpointfR, 2.0, 0.002, 0.000, DIRECT, Timer)
        self.PIDfRight.set_output_limits(-1 * MOTOR_SPEED, MOTOR_SPEED)
        self.PIDfRight.set_mode(AUTOMATIC)

        self.setpointrL = 0
        self.inputrL = 0
        self.PIDrLeft = PID(self.inputrL, self.setpointrL, 2.0, 0.002, 0.000, DIRECT, Timer)
        self.PIDrLeft.set_output_limits(-1 * MOTOR_SPEED, MOTOR_SPEED)
        self.PIDrLeft.set_mode(AUTOMATIC)

        self.setpointrR = 0
        self.inputrR = 0
        self.PIDrRight = PID(self.inputrR, self.setpointrR, 2.0, 0.002, 0.000, DIRECT, Timer)
        self.PIDrRight.set_output_limits(-1 * MOTOR_SPEED, MOTOR_SPEED)
        self.PIDrRight.set_mode(AUTOMATIC)

    def read_encoders(self):
        if self.dir:
            return (-Encoder.read(0), Encoder.read(1))
        else:
            return (Encoder.read(0), -Encoder.read(1))

    def raw_encoders(self):
        return (Encoder.read(0), Encoder.read(1))

    def reverse_direction(self):
        self.dir = not self.dir

    def move_motors(self, left, right):
        if left >= 0:
            self.left_motor.move(MotorDirection.FORWARD, abs(left))
        else:
            self.left_motor.move(MotorDirection.BACKWARD, abs(left))
        if right >= 0:
            self.right_motor.move(MotorDirection.FORWARD, abs(right))
        else:
            self.right_motor.move(MotorDirection.BACKWARD, abs(right))

    def stop(self):
        print("stopped")
        self.right_motor.stop()
        self.left_motor.stop()

    def move_ticks(self, ticks_l, ticks_r):
        Encoder.write(0, 0)
        Encoder.write(0, 1)

        factor = abs(ticks_l)/TICKS_CELL

        self.setpointL = ticks_l
        self.setpointR = ticks_r

        self.inputR = 0
        self.inputL = 0

        start = time.time() * 1000
        while ((abs(self.inputL - self.setpointL) > 5 or abs(self.inputR - self.setpointR) > 5) and (time.time()* 1000 - start < factor *TIME)):
            self.inputL , self.inputR = self.read_encoders()
            #print(self.inputL)
            #print(self.inputR)

            self.PIDRight.compute(self.inputR, self.setpointR)
            self.PIDLeft.compute(self.inputL, self.setpointL)

            l_rem = abs(self.inputL - self.setpointL)
            r_rem = abs(self.inputR - self.setpointR)

            if l_rem > r_rem and (abs(l_rem - r_rem) > 10 or r_rem < 10):
                self.move_motors(self.PIDLeft.output(),0)
            elif r_rem > l_rem and (abs(l_rem - r_rem) > 10 or l_rem < 10):
                self.move_motors(0,self.PIDRight.output())
            else:
                self.move_motors(self.PIDLeft.output(),self.PIDRight.output())

        self.stop()

    def move_cells(self, cells):
        """for _ in range(cells):
            self.advance(TICKS_CELL)
        """
        self.advance(cells*TICKS_CELL)
    def advance(self, ticks):
        Encoder.write(0, 0)
        Encoder.write(0, 1)

        factor = ticks/TICKS_CELL

        distance_l, distance_r = self.read_encoders()
        added = 0
        have_driven = False
        start = time.time()*1000
        while (min(distance_r, distance_l) < ticks and (time.time()*1000 - start < factor * TIME)):
            if have_driven and self.dir and self._frontIR.get_distance() < 40  and self._fleftIR.get_distance() < 65 and  self._frightIR.get_distance() < 65:
                print("break:",self._frontIR.get_distance())
                break
            elif have_driven and not self.dir and self._rearIR.get_distance() < 40 and (self._rleftIR.get_distance() < 65 or  self._rrightIR.get_distance() < 65):
                break

            if abs(distance_l - distance_r) > 140:
                print('added: {}'.format(added))
                added += 4
                ticks += 4
            distance_l, distance_r = self.read_encoders()
            #print(distance_l)
            #print(distance_r)
            dists = {
                'fr': self._frightIR.get_distance(),
                'fl': self._fleftIR.get_distance(),
                'rr': self._rrightIR.get_distance(),
                'rl': self._rleftIR.get_distance()
            }

            front_valid = dists['fr'] < WALL_THRESHOLD_DIAG and dists['fl'] < WALL_THRESHOLD_DIAG and (dists['fr'] < WALL_DIST or dists['fl'] < WALL_DIST)
            rear_valid = dists['rr'] < WALL_THRESHOLD_DIAG and dists['rl'] < WALL_THRESHOLD_DIAG and (dists['rr'] < WALL_DIST or dists['rl'] < WALL_DIST)
            left_valid = dists['fl'] <  WALL_THRESHOLD_DIAG and dists['rr'] <  WALL_THRESHOLD_DIAG and (dists['fl'] <  WALL_DIST or dists['rr'] <  WALL_DIST)
            right_valid = dists['fr'] <  WALL_THRESHOLD_DIAG and dists['rl'] <  WALL_THRESHOLD_DIAG and (dists['fr'] <  WALL_DIST or dists['rl'] <  WALL_DIST)

            if self.dir:
                max2 = min(dists, key = lambda k: dists[k] if (dists[k] < WALL_THRESHOLD_DIAG and k[0] != 'r') else float('inf'))
                single_sensor_functions = {
                        'fr': self.follow_front_right,
                        'fl': self.follow_front_left
                }
            else:
                max2 = min(dists, key = lambda k: dists[k] if (dists[k] < WALL_THRESHOLD_DIAG and k[0] != 'f') else float('inf'))
                single_sensor_functions = {
                        'rr': self.follow_rear_right,
                        'rl': self.follow_rear_left
                }

            if front_valid and self.dir:
                self.follow_front()
            elif rear_valid and not self.dir:
                self.follow_rear()
            elif dists[max2] < WALL_THRESHOLD_DIAG and max2[0] != 'r' and self.dir:
                #print(max2)
                single_sensor_functions[max2]()
            elif dists[max2] < WALL_THRESHOLD_DIAG and max2[0] != 'f' and not self.dir:
                single_sensor_functions[max2]()
            else:
                self.straight()
            have_driven = True

            """
            elif left_valid:
                self.follow_left()
            elif right_valid:
                print("right")
                self.follow_right()

            """
        self.stop()

    def reverse(self, ticks):
        self.reverse_direction()
        self.move_cells(ticks)
        self.reverse_direction()

    def back(self):
        if(self._rearIR.get_distance() > 25 and self._rleftIR.get_distance()> 10 and self._rrightIR.get_distance() > 10):
            print("back")
            self.move_ticks(-TICKS_CELL/4, -TICKS_CELL/4)
        else:
            print("not back")

    def turn_slight_left(self):
        print("turn_slight_left")
        self.PIDLeft.set_tunings(KP3,0.01,0)
        self.PIDRight.set_tunings(KP3,0.01,0)
        self.move_ticks(-1 * TICKS_TURN/6, TICKS_TURN/6)

    def turn_slight_right(self):
        print("turn_slight_right")
        self.PIDLeft.set_tunings(KP3,0.01,0)
        self.PIDRight.set_tunings(KP3,0.01,0)
        self.move_ticks(1 * TICKS_TURN/6, -1*TICKS_TURN/6)

    def attempt_escape(self):
        if(self._frontIR.get_distance() > 40 and self._fleftIR.get_distance()> 60 and self._frightIR.get_distance() > 60):
            print("attempted")
            self.move_cells(1)
            return True
        else:
            print("could not")
            return False

    def escape(self):
        escaped = False
        self.dir = True
        if self._frightIR.get_distance() <= self._fleftIR.get_distance():
            while not escaped:
                print('stuck')
                self.back()
                self.turn_slight_left()
                escaped = self.attempt_escape()
            if(self._frontIR.get_distance() < 40  or self._fleftIR.get_distance() < 10 or self._frightIR.get_distance() < 10):
                print("second escape")
                self.turn_left()
                self.move_cells(2)
        else:
            while not escaped:
                print('stuck')
                self.back()
                self.turn_slight_right()
                escaped = self.attempt_escape()
            if(self._frontIR.get_distance() < 40  or self._fleftIR.get_distance() < 10 or self._frightIR.get_distance() < 10):
                print("second escape")
                self.turn_right()
                self.move_cells(2)

    def turn_around_l(self):
        self.turn_left()
        self.turn_left()

    def turn_around_r(self):
        self.turn_right()
        self.turn_right()

    def turn_left(self):
        self.PIDLeft.set_tunings(KP3,0.01,0)
        self.PIDRight.set_tunings(KP3,0.01,0)
        if self.dir:
            self.move_ticks(-1 * TICKS_TURN, TICKS_TURN)
        else:
            self.move_ticks(TICKS_TURN, -1*TICKS_TURN)
            self.reverse_direction()

    def turn_right(self):
        self.PIDLeft.set_tunings(KP3,0.01,0)
        self.PIDRight.set_tunings(KP3,0.01,0)
        if self.dir:
            self.move_ticks(TICKS_TURN, -1 * TICKS_TURN)
        else:
            self.move_ticks(-1 * TICKS_TURN, TICKS_TURN)
            self.reverse_direction()

    def follow_front(self):
        #print("fFront")
        self.PIDfLeft.set_tunings(KP, KI, KD)
        self.PIDfRight.set_tunings(KP, KI, KD)
        self.setpointfR = WALL_DISTANCE_DIAG
        self.setpointfL = WALL_DISTANCE_DIAG

        self.inputfR = self._frightIR.get_distance()
        self.inputfL = self._fleftIR.get_distance()

        self.PIDfRight.compute(self.inputfR, self.setpointfR)
        self.PIDfLeft.compute(self.inputfL, self.setpointfL)

        self.move_motors((MOTOR_SPEED + self.PIDfLeft.output())/2, (MOTOR_SPEED + self.PIDfRight.output())/2)

    def follow_rear(self):
        #print("fRear")

        self.PIDrLeft.set_tunings(KP, KI, KD)
        self.PIDrRight.set_tunings(KP, KI, KD)
        self.setpointrR = WALL_DISTANCE_DIAG
        self.setpointrL = WALL_DISTANCE_DIAG

        self.inputrR = self._rrightIR.get_distance()
        self.inputrL = self._rleftIR.get_distance()

        #print("R:",self.inputrR)
        #print("L:",self.inputrL)
        self.PIDrRight.compute(self.inputrR, self.setpointrR)
        self.PIDrLeft.compute(self.inputrL, self.setpointrL)

        self.move_motors(-(MOTOR_SPEED + self.PIDrLeft.output())/2, -(MOTOR_SPEED + self.PIDrRight.output())/2)

    def follow_left(self):
        #print("fLeft")

        self.PIDfLeft.set_tunings(KP, KI, KD)
        self.PIDrLeft.set_tunings(KP, KI, KD)
        self.setpointfL = WALL_DISTANCE_DIAG
        self.setpointrR = WALL_DISTANCE_DIAG

        self.inputfL = self._fleftIR.get_distance()
        self.inputrR = self._rrightIR.get_distance()

        self.PIDfLeft.compute(self.inputfL, self.setpointfL)
        self.PIDrRightt.compute(self.inputrR, self.setpointrR)

        if self.dir:
            self.move_motors((MOTOR_SPEED + self.PIDfLeft.output())/2, (MOTOR_SPEED + self.PIDrRight.output())/2)
        else:
            self.move_motors(-(MOTOR_SPEED + self.PIDfLeft.output())/2, -(MOTOR_SPEED + self.PIDrRight.output())/2)

    def follow_right(self):
        #print("fRight")

        self.PIDfRight.set_tunings(KP, KI, KD)
        self.PIDrRight.set_tunings(KP, KI, KD)
        self.setpointfR = WALL_DISTANCE_DIAG
        self.setpointrL = WALL_DISTANCE_DIAG

        self.inputfR = self._frightIR.get_distance()
        self.inputrL = self._rleftIR.get_distance()

        self.PIDfRight.compute(self.inputfR, self.setpointfR)
        self.PIDrLeft.compute(self.inputrL, self.setpointrL)

        if self.dir:
            self.move_motors((MOTOR_SPEED + self.PIDrLeft.output())/2, (MOTOR_SPEED + self.PIDfRight.output())/2)
        else:
            self.move_motors(-(MOTOR_SPEED + self.PIDrLeft.output())/2, -(MOTOR_SPEED + self.PIDfRight.output())/2)

    def follow_front_right(self):
        #print("ffRight")

        self.PIDfRight.set_tunings(KP2, KI, KD)
        self.setpointfR = WALL_DISTANCE_DIAG

        self.inputfR = self._frightIR.get_distance()

        self.PIDfRight.compute(self.inputfR, self.setpointfR)

        if self.dir:
            self.move_motors((MOTOR_SPEED - self.PIDfRight.output())/2, (MOTOR_SPEED + self.PIDfRight.output())/2)
        else:
            self.move_motors(-(MOTOR_SPEED - self.PIDfRight.output())/2, -(MOTOR_SPEED + self.PIDfRight.output())/2)

    def follow_front_left(self):
        #print("ffLeft")

        self.PIDfLeft.set_tunings(KP2, KI, KD)
        self.setpointfL = WALL_DISTANCE_DIAG

        self.inputfL = self._fleftIR.get_distance()

        self.PIDfLeft.compute(self.inputfL, self.setpointfL)

        if self.dir:
            self.move_motors((MOTOR_SPEED + self.PIDfLeft.output())/2, (MOTOR_SPEED - self.PIDfLeft.output())/2)
        else:
            self.move_motors(-(MOTOR_SPEED + self.PIDfLeft.output())/2, -(MOTOR_SPEED - self.PIDfLeft.output())/2)

    def follow_rear_right(self):
        #print("frRight")

        self.PIDrRight.set_tunings(KP2, KI, KD)
        self.setpointrR = WALL_DISTANCE_DIAG

        self.inputrR = self._rrightIR.get_distance()

        self.PIDrRight.compute(self.inputrR, self.setpointrR)

        if self.dir:
            self.move_motors((MOTOR_SPEED - self.PIDrRight.output())/2, (MOTOR_SPEED + self.PIDrRight.output())/2)
        else:
            self.move_motors(-(MOTOR_SPEED - self.PIDrRight.output())/2, -(MOTOR_SPEED + self.PIDrRight.output())/2)

    def follow_rear_left(self):
        #print("frLeft")

        self.PIDrLeft.set_tunings(KP2, KI, KD)
        self.setpointrL = WALL_DISTANCE_DIAG

        self.inputrL = self._rleftIR.get_distance()

        self.PIDrLeft.compute(self.inputrL, self.setpointrL)

        if self.dir:
            self.move_motors((MOTOR_SPEED + self.PIDrLeft.output())/2, (MOTOR_SPEED - self.PIDrLeft.output())/2)
        else:
            self.move_motors(-(MOTOR_SPEED + self.PIDrLeft.output())/2, -(MOTOR_SPEED - self.PIDrLeft.output())/2)

    def straight(self):
        #print("straight")
        if self.dir:
            self.move_motors(MOTOR_SPEED/2, MOTOR_SPEED/2)
        else:
            self.move_motors(-MOTOR_SPEED/2, -MOTOR_SPEED/2)


import csv
import numpy as np
from sklearn.model_selection import train_test_split
import nltk
from nltk.tokenize import word_tokenize
from random import shuffle
from sklearn.model_selection import KFold
from statistics import mode
import re

documents = []
with open("data.csv") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for record in csv_reader:
        ap = (' '.join(re.sub("(@[A-Za-z0-9]+)|(\w+:\/\/\S+)", " ", record[1]).split()))
        ap = word_tokenize(ap)
        documents.append((ap, record[0]))

shuffle(documents)

all_words = []
for tweet in documents:
    for w in tweet[0]:
        all_words.append(w.lower())

all_words = nltk.FreqDist(all_words)
print("getting features")
word_features = list(all_words.keys())[:1000]
print(word_features)

def find_features(tweet):
    words = set(tweet)
    features = {}
    for w in word_features:
        features[w] = (w in words)
    return features

print("setting features per tweet")
feature_sets = np.array([[find_features(tweet), category] for (tweet, category) in documents])

data = feature_sets[:, 0]
target = feature_sets[:, 1]

testing_set = feature_sets[5000:]
training_set = feature_sets[:5000]

print("training")
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.1, random_state=0)
classifier = nltk.NaiveBayesClassifier.train(training_set)

print("testing")
print("Classifier accuracy percent:", (nltk.classify.accuracy(classifier, testing_set)) * 100)

def sentiment(text):
    feats = find_features(word_tokenize(text))
    v = classifier.classify(feats)
    return mode(v)

print(sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
print(sentiment("sorry. Horrible movie, 0/10"))


from . import *
import cupy as np
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical

d = Model([
    Dense(512, 784),
    LeakyReLU(0.3),]\
    + [Dense(512, 512), LeakyReLU(0.3)] * 2\
    + [Dense(343, 512),
    LeakyReLU(0.3),
    Dense(128, 343),
    LeakyReLU(0.3),
    Dense(100, 128),
    LeakyReLU(0.3),
    Dense(10, 100),
    Activation("softmax"),
])

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = np.array(x_train).reshape((60000, 784))
x_test = np.array(x_test).reshape((10000, 784))

y_train = np.array(to_categorical(y_train))
y_test = np.array(to_categorical(y_test))

TEST_BATCH_SIZE = 1000
TRAIN_BATCH_SIZE = 1000

lr = 1e-3

for epoch in range(100000):
    print("="*10, "EPOCH", epoch, "="*10)
    test_indices = np.random.randint(x_test.shape[0], size=TEST_BATCH_SIZE)
    test_pred, test_real = d(x_test[test_indices]), y_test[test_indices]
    print("Loss:", np.average(-np.log(test_pred[:, np.argmax(test_real, -1)])))
    print("Accuracy:", np.sum(np.argmax(test_pred, -1) == np.argmax(test_real, -1))/(test_pred.shape[0]) * 100, "%")
    for i in range(100):
        train_indices = np.random.randint(x_train.shape[0], size=TRAIN_BATCH_SIZE)
        d.train_batch(x_train[train_indices], y_train[train_indices], lr=lr, cross_entropy=True)
        lr *= 0.999


wordnums = {
    '1': 'One',
    '2': "Two",
    '3': 'Three',
    '4': 'Four',
    '5': 'Five',
    '6': 'Six',
    '7': 'Seven',
    '8': 'Eight',
    '9': 'Nine',
    '0': 'Zero'
}

value = input("A number to convert: ")

result = ''
for number in value:
    result += f"{wordnums.get(number)} "

print(result)


INPUT_FILE = "A-small-attempt0.in"
OUTPUT_FILE = "A-small.out"
def solve(d, numbers, prepotential):
    if all(d[key] == 0 for key in d):
        return prepotential
    for letternumber in numbers.keys():
        potential = [x for x in prepotential]
        dcopy = d.copy()
        bad = False
        for letter in letternumber:
            if letter in dcopy and dcopy[letter] > 0:
                dcopy[letter] -= 1
            else:
                bad = True
                break
        if not bad:
            potential.append(numbers[letternumber])
            val = solve(dcopy, numbers, potential)
            if val:
                return val

with open(INPUT_FILE) as f:
    with open(OUTPUT_FILE, "w") as of:
        cases = int(f.readline())
        i = 1
        for x in f.readlines():
            x = x.strip()
            d = {}
            for letter in x:
                if letter in d:
                    d[letter] = d[letter] + 1
                else:
                    d[letter] = 1
            numbers = {"ZERO":0, "ONE":1, "TWO":2, "THREE":3, "FOUR":4, "FIVE":5, "SIX":6, "SEVEN":7, "EIGHT":8, "NINE":9}
            nrs = [str(x) for x in sorted(solve(d, numbers, list()))]
            of.write("CASE #{0}: {1}".format(i, ''.join(nrs)))
            of.write("\n")
            i = i + 1


import re
import sys
import os
import numpy as np

sys.path.append('..')

import datainterface.dataconversion as dataconversion
# from .fragility.util.utils import *

# Main function to call which uses EDFConverter object to sift through all relevant files and
# create the necessary meta data.

def preprocessconvert(patient, datadir, npyfile,
                      headerfile, chanfile, annotationsfile):
    # add a file checker in case, we needed to alter the edf file name
    if 'pt' in patient or 'jh' in patient:
        # edffilepath = os.path.join(datadir, patient + '_0001.edf')
        edffilepath = os.path.join(datadir, patient + '.edf')
    else:
        edffilepath = os.path.join(datadir, patient + '.edf')

    print(edffilepath)
    # convert data into csv files and numpy raw data file
    converter = dataconversion.EDFConverter(edffilepath)
    converter.edfrawtonumpy(npyfile)
    converter.edfmetatocsv(headerfile,
                           chanfile,
                           annotationsfile)

if __name__ == '__main__':
    patients = [
        # 'id001_ac_absence', 'id001_ac_comp',
        # 'id001_ac_sz2',
        # 'id001_ac_sz2_2',
        # 'id001_ac_sz3',
        # 'id002_cj_sz1','id002_cj_sz2','id002_cj_sz3','id002_cj_sz4',
        # 'id002_cj_sz5','id002_cj_sz6',
        # 'id003_cm_sz1',
        # 'id007_fo_sz1',
        # 'id008_gc_sz1', 'id008_gc_sz2', 'id008_gc_sz3',
        # 'id010_js_sz1',
        # 'id011_ml_sz1', 'id011_ml_sz2',
        # 'id012_pc_sz1',
        # 'id012_pc_sz2', 'id012_pc_sz3',
        # 'id013_pg_sz1',
        # 'id013_pg_sz2', 'id013_pg_sz3',
        # 'id014_rb_sz1',
        # 'id014_rb_sz2'
        # 'id014_1', 'id014_2'
        # 'id013_pg_sz1'
        # 'la09_ictal_2'
        # 'la01_ictal_2'
        # 'jh103sz1', 'jh103sz2', 'jh103sz3',
        # 'jh105sz1', 'jh105sz2', 'jh105sz3', 'jh105sz4', 'jh105sz5'
        # 'jh103aslp1', 'jh103aw1', 'jh105aslp1', 'jh105aw1',
        # 'ummc001_sz1', 'ummc001_sz2', 'ummc001_sz3',
        # 'ummc002_sz1', 'ummc002_sz2', 'ummc002_sz3',
        # 'ummc003_sz1', 'ummc003_sz2', 'ummc003_sz3',
        # 'ummc004_sz1', 'ummc004_sz2', 'ummc004_sz3',
        # 'ummc005_sz2', 'ummc005_sz3',
        # 'ummc006_sz1', 'ummc006_sz2', 'ummc006_sz3',
        # 'ummc007_sz1', 'ummc007_sz2', 'ummc007_sz3',
        # 'ummc008_sz1', 'ummc008_sz2', 'ummc008_sz3',
        # 'ummc009_sz1', 'ummc009_sz2', 'ummc009_sz3',
        # 'pt1sz2', 'pt1sz3', 'pt1sz4',
        # 'pt2sz1', 'pt2sz3', 'pt2sz4',
        # 'pt3sz2', 'pt3sz4',
        # 'pt4sz4', 'pt4sz2', 'pt4sz3', 'pt4sz5', 'pt4sz6',
        # 'pt5sz1_0001', 'pt5sz2_0001', 'pt5sz3_0001', 'pt8scalp1'

        # 'pt6sz3', 'pt6sz4', 'pt6sz5',
        # 'pt7sz19', 'pt7sz21', 'pt7sz22',
        # 'pt8sz1', 'pt8sz2', 'pt8sz3',
        # 'pt10sz1', 'pt10sz2', 'pt10sz3',
        # 'pt11sz1', 'pt11sz2', 'pt11sz3', 'pt11sz4',
        # 'pt12sz1', 'pt12sz2',
        # 'pt13sz1', 'pt13sz2', 'pt13sz3', 'pt13sz5',
        # 'pt14sz1', 'pt14sz2', 'pt14sz3',
        # 'pt15sz1', 'pt15sz2', 'pt15sz3', 'pt15sz4',
        # 'pt16sz1', 'pt16sz2', 'pt16sz3',
        # 'pt17sz1', 'pt17sz2', 'pt17sz3'
        # 'pt1aslp1', 'pt1aslp2', 'pt1aw1', 'pt1aw2',
        # 'pt2aslp1', 'pt2aslp2', 'pt2aw1', 'pt2aw2',
        # 'pt3aslp1', 'pt3aslp2', 'pt3aw1'
    ]
    # patients = [
    #             # 'LA01_ICTAL', 'LA01_Inter', 'LA01_Inter_2',
    #             # 'LA02_ICTAL', 'LA02_Inter',
    #             # 'LA03_ICTAL', 'LA03_Inter',
    #             # 'LA04_ICTAL', 'LA04_Inter',
    #             # 'LA12_ICTAL', 'LA17_ICTAL'
    #             'LA01_Inter_2',
    #             'LA07_ICTAL', 'LA07_Inter'
    #             'LA08_ICTAL', 'LA08_Inter',
    #             'LA09_ICTAL', 'LA09_Inter'
    #             'LA13_ICTAL', 'LA13_Inter'
    # ]

    # loop through all patients and convert
    edfdir = '/Volumes/ADAM LI/rawdata/_edf/'
    for patient in patients:
        # initialize converted data directory
        # -> should receive headers, channels, annotations, and rawdata file
        outputdir = '/Volumes/ADAM LI/pydata/convertedtng/' + patient.lower()
        if not os.path.exists(outputdir):
            os.makedirs(outputdir)

        # 1. setting filename
        npyfile = os.path.join(outputdir, '') + patient.lower() + '_rawnpy.npy'
        chanfile = os.path.join(outputdir, '') + patient.lower() + '_chans.csv'
        headerfile = os.path.join(outputdir, '') + \
            patient.lower() + '_headers.csv'
        annotationsfile = os.path.join(
            outputdir, '') + patient.lower() + '_annotations.csv'

        # 1. first run data conversion
        preprocessconvert(
            patient,
            edfdir,
            npyfile,
            headerfile,
            chanfile,
            annotationsfile)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 16:31:47 2018

@author: xsxsz
"""

import os
import struct
import numpy as np
import matplotlib.pyplot as plt

#Not so clear........................
def load_mnist(kind='train'):
     labels_path = os.path.join('/resource/repository_python/mnist/','%s-labels-idx1-ubyte'% kind)
     images_path = os.path.join('/resource/repository_python/mnist/','%s-images-idx3-ubyte'% kind)
     with open(labels_path, 'rb') as lbpath:
        magic, n = struct.unpack('>II',
                                 lbpath.read(8))
        labels = np.fromfile(lbpath,
                             dtype=np.uint8)

     with open(images_path, 'rb') as imgpath:
        magic, num, rows, cols = struct.unpack('>IIII',
                                               imgpath.read(16))
        images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784)
     return images, labels
#....................................
images,labels=load_mnist()
print(images.shape)
print('------------')
print(labels.shape)
plt.figure(figsize=(12,10))
fig,ax=plt.subplots(nrows=2,ncols=2,sharex=True,sharey=True)
ax=ax.flatten()
images=images.reshape(60000,28,28)
for i in range(4):
    ax[i].imshow(images[i,:],cmap='gray')


import pandas as pd

def create_df(station, period = '1d'):
    '''
    Takes a 3 letter station abbreviation from the user and
    returns all relevant met data as a dataframe.

    Parameters
    ----------
    station : str, 3 letter code representing the station needed
    period  : str, the time period to average by.  Default is '1d' for daily data
		input lenght followed by period code. Example( 1S, 1T, 1H, 1d, 1M, 1Y)
    Returns
    -------
    dataframe of all relevent met data indexed by day
    '''

    # Column List
    name_list = ["Station ID","Date [UTC]","Temp [F]","DP [F]","RH [%]",
                "W Dir [Deg]","W Spd [Kts]","Alt [inHg]","1Hr-Prcp [mm]",
                "Vis [mi]","SKC1","SKC2","SKC3","Cld Hgt1 [Ft]","Cld Hgt2 [Ft]",
                "Cld Hgt3 [Ft]","Prs Wx"]

    # Data Type List
    dtype_list = {"Station ID":"str","UTC":"str","Temp [F]":"float64",
                  "DP [F]":"float64","RH [%]":"float64","W Dir [Deg]":"float64",
                  "W Spd [Kts]":"float64","Alt [inHg]":"float64",
                  "1Hr-Prcp [mm]":"float64","Vis [mi]":"float64","SKC1":"str",
                  "SKC2":"str","SKC3":"str","Cld Hgt1 [Ft]":"float64",
                  "Cld Hgt2 [Ft]":"float64","Cld Hgt3 [Ft]":"float64",
                  "Prs Wx" : "str"}

    station_data = pd.read_csv('Data/{}.txt'.format(station), sep='\t',
                                header=0, names = name_list, dtype = dtype_list,
                                parse_dates = ['Date [UTC]'], index_col = 1) \
                                .resample(period).mean()

    return(station_data)


#this program looks for largest odd by testing variables first if odd then only after deciding which is the largest
def odd(x):
	if x%2!=0:
		return True
	return False

def maxodd(x,y,z):
	if odd(x) and odd(x) and odd(z):
		return max(x,y,z)
	elif odd(x) and odd(y):
		return max(x,y)
	elif odd(x) and odd(z):
		return max(x,z)
	elif odd(y) and odd(z):
		return max(y,z)
	elif odd(x):
		return x
	elif odd(y):
		return y
	elif odd(z):
		return z
	else:
		return("None of them are odd.")

print(maxodd(int(input('Enter x: ')), int(input('Enter y: ')), int(input('Enter z: '))))