import cv2
import numpy as np
import math
import time
import subprocess

MIN_MATCH_COUNT=5

detector=cv2.xfeatures2d.SIFT_create()

FLANN_INDEX_KDTREE = 0
flannParam=dict(algorithm=FLANN_INDEX_KDTREE,tree=5)

searchParam=dict(checks = 100)
flann=cv2.FlannBasedMatcher(flannParam,searchParam)

img_check_A = cv2.imread("gray_a.jpg",0)
trainKP_A,trainDesc_A=detector.detectAndCompute(img_check_A,None)

img_check_B = cv2.imread("gray_b.jpg",0)
trainKP_B,trainDesc_B=detector.detectAndCompute(img_check_B,None)

img_check_C = cv2.imread("gray_c.jpg",0)
trainKP_C,trainDesc_C=detector.detectAndCompute(img_check_C,None)

img_check_D = cv2.imread("gray_d.jpg",0)
trainKP,trainDesc_D=detector.detectAndCompute(img_check_D,None)

img_check_E = cv2.imread("gray_e1.jpg",0)
trainKP,trainDesc_E=detector.detectAndCompute(img_check_E,None)

img_check_F = cv2.imread("gray_f.jpg",0)
trainKP,trainDesc_F=detector.detectAndCompute(img_check_F,None)

img_check_love = cv2.imread("love.jpg",0)
trainKP,trainDesc_love=detector.detectAndCompute(img_check_love,None)

img_check_gjob = cv2.imread("gjob.jpg",0)
trainKP,trainDesc_gjob=detector.detectAndCompute(img_check_gjob,None)

cap = cv2.VideoCapture(0)

while True:
    ret, source=cap.read()
    cv2.rectangle(source, (300, 300), (100, 100), (0, 255, 0), 2)

    crop_image = source[100:300, 100:300]
    gray = cv2.cvtColor(crop_image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (15, 15), 0)
    ret, QueryImg = cv2.threshold(blur, 70, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    (version, _, _) = cv2.__version__.split('.')

    if version is '3':
        image, contours, hierarchy = cv2.findContours(QueryImg.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    elif version is '2':
        contours, hierarchy = cv2.findContours(QueryImg.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    gray1 = np.float32(gray)

    corners = cv2.goodFeaturesToTrack(gray1, 100, 0.01, 10)
    corners = np.int0(corners)

    for corner in corners:
        x,y = corner.ravel()
        cv2.circle(crop_image,(x,y),3,255,-1)

    cnt = max(contours, key=lambda x: cv2.contourArea(x))

    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(crop_image, (x, y), (x + w, y + h), (0, 0, 255), 0)

    drawing_a = np.zeros(crop_image.shape, np.uint8)

    max_area = 0

    hull = cv2.convexHull(cnt)
    moments = cv2.moments(cnt)

    if moments['m00'] != 0:
        cx = int(moments['m10'] / moments['m00'])  # cx = M10/M00
        cy = int(moments['m01'] / moments['m00'])  # cy = M01/M00

    centr = (cx, cy)
    cv2.circle(crop_image, centr, 5, [0, 0, 255], 2)
    cv2.drawContours(drawing_a, [cnt], 0, (0, 255, 0), 2)
    cv2.drawContours(drawing_a, [hull], 0, (0, 255, 0), 2)

    hull = cv2.convexHull(cnt, returnPoints=False)

    defects = cv2.convexityDefects(cnt, hull)
    count_defects = 0
    cv2.drawContours(QueryImg, contours, -1, (0, 255, 0), 3)

    for i in range(defects.shape[0]):
        s, e, f, d = defects[i, 0]
        start = tuple(cnt[s][0])
        end = tuple(cnt[e][0])
        far = tuple(cnt[f][0])
        a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)
        b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)
        c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)
        angle = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 57

        if angle <= 90:
            count_defects += 1
            cv2.circle(crop_image, far, 3, [0, 0, 255], -1)
        # dist = cv2.pointPolygonTest(cnt,far,True)
        cv2.line(crop_image, start, end, [0, 255, 0], 2)

    a=2
    if (a==1):
                     # cv2.circle(crop_img,far,5,[0,0,255],-1)
        if count_defects == 1:
          cv2.putText(source, "This is 2 ...", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2,[0,0,255], 3)
        elif count_defects == 2:
          cv2.putText(source, "This is 3 ...", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, [0,0,255], 3)
        elif count_defects == 3:
          cv2.putText(source, "This is 4 ...", (50, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, [0,0,255], 3)
        elif count_defects == 4:
          cv2.putText(source, "This is 5 ...", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, [0,0,255], 3)
        else:
          str = "This is a basic hand gesture recognizer"
          cv2.putText(source, str, (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 3)
        cv2.imshow('frame',source)

        if cv2.waitKey(1) & 0xFF == ord('q'):
          break

    if (a==2):

     queryKP, queryDesc= detector.detectAndCompute(gray,None)
     matches_A=flann.knnMatch(queryDesc,trainDesc_A,k=2)
     matches_B=flann.knnMatch(queryDesc,trainDesc_B,k=2)
     matches_C=flann.knnMatch(queryDesc,trainDesc_C,k=2)
     matches_D=flann.knnMatch(queryDesc,trainDesc_D,k=2)
     matches_E=flann.knnMatch(queryDesc,trainDesc_E,k=2)
     matches_F=flann.knnMatch(queryDesc,trainDesc_F,k=2)

     goodMatch_A=[]
     goodMatch_B=[]
     goodMatch_C=[]
     goodMatch_D=[]
     goodMatch_E=[]
     goodMatch_F=[]

     for a1,a2 in matches_A:
        if(a1.distance<0.4*a2.distance):
            goodMatch_A.append(a1)
     for b1,b2 in matches_B:
        if(b1.distance<0.4*b2.distance):
            goodMatch_B.append(b1)
     for c1,c2 in matches_C:
        if(c1.distance<0.4*c2.distance):
            goodMatch_C.append(c1)
     for d1,d2 in matches_D:
        if(d1.distance<0.4*d2.distance):
            goodMatch_D.append(d1)
     for e1,e2 in matches_E:
        if(e1.distance<0.4*e2.distance):
            goodMatch_E.append(e1)
     for f1,f2 in matches_F:
        if(f1.distance<0.4*f2.distance):
            goodMatch_F.append(f1)

     print ("Number of Good Matches in alphabetical order  - %d %d %d %d %d %d"%(len(goodMatch_A),len(goodMatch_B),len(goodMatch_C),len(goodMatch_D),len(goodMatch_E),len(goodMatch_F)))

     if(len(goodMatch_A)>len(goodMatch_B) and len(goodMatch_A)>len(goodMatch_C) and len(goodMatch_A)>len(goodMatch_D) and len(goodMatch_A)>len(goodMatch_E) and len(goodMatch_A)>len(goodMatch_F)):
       cv2.putText(source, "A", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
     else:
       if(len(goodMatch_B)>len(goodMatch_A) and len(goodMatch_B)>len(goodMatch_C) and len(goodMatch_B)>len(goodMatch_D) and len(goodMatch_B)>len(goodMatch_E) and len(goodMatch_B)>len(goodMatch_F)):
           cv2.putText(source, "B", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
       else:
           if(len(goodMatch_C)>len(goodMatch_A) and len(goodMatch_C)>len(goodMatch_B) and len(goodMatch_C)>len(goodMatch_D) and len(goodMatch_C)>len(goodMatch_E) and len(goodMatch_C)>len(goodMatch_F)):
                cv2.putText(source, "C", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
           else:
            if(len(goodMatch_D)>len(goodMatch_A) and len(goodMatch_D)>len(goodMatch_B) and len(goodMatch_D)>len(goodMatch_C) and len(goodMatch_D)>len(goodMatch_E) and len(goodMatch_D)>len(goodMatch_F)):
                     cv2.putText(source, "D", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
            else:
                if(len(goodMatch_E)>len(goodMatch_A) and len(goodMatch_E)>len(goodMatch_B) and len(goodMatch_E)>len(goodMatch_C) and len(goodMatch_E)>len(goodMatch_D) and len(goodMatch_E)>len(goodMatch_F)):
                       cv2.putText(source, "E", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
                else:
                    if(len(goodMatch_F)>len(goodMatch_A) and len(goodMatch_F)>len(goodMatch_B) and len(goodMatch_F)>len(goodMatch_C) and len(goodMatch_F)>len(goodMatch_D) and len(goodMatch_F)>len(goodMatch_E)):
                            cv2.putText(source, "F", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
                    else:
                            cv2.putText(source, "not enough matches", (3, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, 3)

     cv2.imshow('result',source)
    # cv2.imshow('threshold',QueryImg)
     #cv2.imshow('gray',gray)

     if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    if(a==3):
         queryKP, queryDesc= detector.detectAndCompute(gray,None)

         matches_love=flann.knnMatch(queryDesc,trainDesc_love,k=2)
         matches_gjob=flann.knnMatch(queryDesc,trainDesc_gjob,k=2)

         goodMatch_L=[]
         goodMatch_GJ=[]

         for l1,l2 in matches_love:
            if(l1.distance<0.4*l2.distance):
              goodMatch_L.append(l1)
         for gj1,gj2 in matches_gjob:
            if(gj1.distance<0.4*gj2.distance):
              goodMatch_GJ.append(gj1)

         #print "Number of Good Matches in love and good job  - %d %d "%(len(goodMatch_L),len(goodMatch_GJ))

         if ((count_defects == 1) and len(goodMatch_GJ)<= len(goodMatch_L)):
            cv2.putText(source, "VICTORY!!", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
         else:
            if(count_defects==4):
                cv2.putText(source, "HI / HELLO ", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
            else:
                if(len(goodMatch_L)>len(goodMatch_GJ)):
                   cv2.putText(source, "  I LOVE YOU  ", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
                else:
                    if(len(goodMatch_GJ)>len(goodMatch_L)):
                      cv2.putText(source, "  GOOD JOB / KEEP IT UP  ", (5, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)

         cv2.imshow('frame',source)
         cv2.imshow('gray',gray)

         if cv2.waitKey(1) & 0xFF == ord('q'):
           break

cap.release()
cv2.destroyAllWindows()


import requests
import string

# lua types
#'any',
#'string',
#'number',
#'integer',
#'boolean',
#'table',
#'function',
#'nil',
#'userdata',
#'thread',
#

typeTranslationTable = {
    "float": "number",
    "int": "number",
    "bool": "boolean",
    "BOOL": "boolean",
    "Any": "any",
    "char": "string",
    "Vector3": "vector3"
}

# Lua keywords
blacklistedParams = ["and", "end", "in", "repeat", "break", "false", "local", "return", "do", "for", "nil", "then", "else", "function", "not", "true", "elseif", "if", "or", "until", "while",]

docs = ["https://runtime.fivem.net/doc/natives.json", "https://runtime.fivem.net/doc/natives_cfx.json"]
for doc in docs:
    print(doc)
    resp = requests.get(doc)
    respBody = resp.json()
    for nativeNamespace in respBody:
        output = open("stubs/natives_{}.lua".format(nativeNamespace.lower()), "w", encoding="utf-8")

        linesWritten = 0
        fileCounter = 0
        for nativeHash in respBody[nativeNamespace]:
            # Split bigger files into smaller files - https://github.com/sumneko/lua-language-server/issues/64
            if linesWritten >= 1000:
                output.close()
                linesWritten = 0
                fileCounter += 1
                output = open("stubs/natives_{}_{}.lua".format(nativeNamespace.lower(), fileCounter), "w", encoding="utf-8")

            nativeFunc = respBody[nativeNamespace][nativeHash]
            if not "name" in nativeFunc:
                continue
            nativeUnfriendlyName = nativeFunc['name']
            nativeParams = nativeFunc['params']
            nativeDesc = nativeFunc['description'].replace("`", "").replace("\n", "\n--- ")
            if len(nativeDesc) > 1 and not nativeDesc.startswith("---"):
                nativeDesc = "--- " + nativeDesc

            nativeExamples = nativeFunc['description']
            nativeReturnType = nativeFunc['results'].replace("*", "")

            #if nativeUnfriendlyName != "REGISTER_COMMAND":
            #    continue

            #print(nativeFunc)
            # _LOCK_RADIO_STATION -> LockRadioStation
            #env.addFilter(new Twing.TwingFilter('makenative', input => {
            #    return input.toLowerCase().replace('0x', 'n_0x')
            #        .replace(/_([a-z])/g, (sub, bit) => bit.toUpperCase())
            #        .replace(/^([a-z])/, (sub, bit) => bit.toUpperCase());
            #}));

            #N_0x8db8cffd58b62552
            nativeName = nativeUnfriendlyName.lower().replace("0x", "N_0x")
            nativeName = nativeName.replace("_", " ")
            nativeName = string.capwords(nativeName)
            nativeName = nativeName.replace(" ", "")
            output.write("{}\n".format(nativeDesc))

            functionDefParams = ""
            for i, nativeParam in enumerate(nativeParams):
                paramName = nativeParam['name']
                if paramName in blacklistedParams:
                    paramName = "_b_{}".format(paramName)

                paramType = nativeParam['type'].replace("*", "")

                # Convert type to Lua type
                if paramType in typeTranslationTable:
                    paramType = typeTranslationTable[paramType]

                if i == len(nativeParams) - 1:
                    functionDefParams += paramName
                else:
                    functionDefParams += paramName + ", "
                # TODO: Convert types to Lua types

                output.write("--- @param {} {}\n".format(paramName, paramType))

            if nativeReturnType != "void":
                if nativeReturnType in typeTranslationTable:
                    nativeReturnType = typeTranslationTable[nativeReturnType]

                output.write("--- @return {}\n".format(nativeReturnType))
            output.write("function {}({}) end\n\n".format(nativeName, functionDefParams))

            linesWritten += (3 + len(nativeParams) + nativeDesc.count('\n'))

        output.close()


'''
Author: Simon Graham
Tissue Image Analytics Lab
Department of Computer Science,
University of Warwick, UK.
'''

import Segmentation_train
import test_classification
import Segmentation_input
import mean_images
import tensorflow as tf
import glob
import os
import sys
import scipy.io as sio
from PIL import Image
import numpy as np
import scipy.misc
import cv2 as cv

FLAGS = tf.app.flags.FLAGS

##############################################################################
def main(argv):
    # Training
  if argv[0] == 'train':

    if not os.path.exists(FLAGS.stats_dir):
      os.mkdir(FLAGS.stats_dir)

    if not os.path.exists(os.path.join(FLAGS.stats_dir,'mean_calc')):
      os.mkdir(os.path.join(FLAGS.stats_dir,'mean_calc'))

    '''
    Below we calculate the mean and variance of all training and validation images. This
    is so that we can use mean subtraction and normalization. If the target size
    is different to the source size, we must first crop the source images so that we can
    subsequently use mean subratction and normalization.

    Images created for the calculation will be written to /stats/mean_calc

    If the images are cropped, the cropped image size is displayed in the folder name
    '''

    if FLAGS.train_image_source_size != FLAGS.train_image_target_size:
      network_stats_file_path = os.path.join(FLAGS.stats_dir,'network_stats.mat')
      if not os.path.isfile(network_stats_file_path):
        if not os.path.exists(os.path.join(FLAGS.stats_dir,'mean_calc','Images_')+str(FLAGS.train_image_target_size)):
          os.mkdir(os.path.join(FLAGS.stats_dir,'mean_calc','Images_')+str(FLAGS.train_image_target_size))
          print('Cropping and writing images for mean and variance calculation...')
          mean_images.crop_and_write()
        list_images = glob.glob(os.path.join(FLAGS.stats_dir,'mean_calc','Images_')+str(FLAGS.train_image_target_size)+'/*'+FLAGS.image_ext)
        print('Calculating mean and variance...')
        mean_image, variance_image = Segmentation_input.calculate_mean_variance_image(list_images)
        sio.savemat(network_stats_file_path,
          {'mean_image': mean_image, 'variance_image': variance_image})

    else:
      network_stats_file_path = os.path.join(FLAGS.stats_dir,'network_stats.mat')
      if not os.path.isfile(network_stats_file_path):
        if not os.path.exists(os.path.join(FLAGS.stats_dir,'mean_calc','Images')):
          os.mkdir(os.path.join(FLAGS.stats_dir,'mean_calc','Images'))
          print('Writing images for mean and variance calculation...')
          mean_images.write()
        list_images = glob.glob(os.path.join(FLAGS.stats_dir,'mean_calc','Images', '*') + FLAGS.image_ext)
        print('Calculating mean and variance...')
        mean_image, variance_image = Segmentation_input.calculate_mean_variance_image(list_images)
        sio.savemat(network_stats_file_path,
          {'mean_image': mean_image, 'variance_image': variance_image})

    if not os.path.exists(FLAGS.checkpoint_dir):
      os.mkdir(FLAGS.checkpoint_dir)

    if not os.path.exists(FLAGS.log_dir):
      os.mkdir(FLAGS.log_dir)

    Segmentation_train.train()

    # Testing
  elif argv[0] == 'test':
    #model_path = Segmentation_train.find_optim_net()
    model_path = FLAGS.checkpoint_dir + '/model.ckpt-172198'
    path_id = os.path.basename(model_path)
    path_id = path_id.split('-')[1]

    print(model_path)

    if not os.path.exists(os.path.join('Results')):
      os.mkdir(os.path.join('Results'))

    result_dir = FLAGS.result_dir
    images_path = FLAGS.test_dir

    images_list = test_classification.get_image_list(images_path)
    filename_list = images_list
    print('Processing test images ...')
    test_classification.testing(model_path, path_id, filename_list)

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


import unittest, json, os, shutil
import pandas as pd
from igf_data.utils.fileutils import get_temp_dir, remove_dir
from igf_data.igfdb.igfTables import Base
from igf_data.igfdb.baseadaptor import BaseAdaptor
from igf_data.igfdb.projectadaptor import ProjectAdaptor
from igf_data.igfdb.sampleadaptor import SampleAdaptor
from igf_data.igfdb.platformadaptor import PlatformAdaptor
from igf_data.igfdb.seqrunadaptor import SeqrunAdaptor
from igf_data.igfdb.experimentadaptor import ExperimentAdaptor
from igf_data.igfdb.runadaptor import RunAdaptor
from igf_portal.metadata_utils import get_db_data_and_create_json_dump
from igf_portal.metadata_utils import _create_json_for_metadata_upload
from igf_portal.metadata_utils import _get_metadata_csv_files_from_metadata_dir

class Metadata_dump_test(unittest.TestCase):
  def setUp(self):
    self.dbconfig = 'data/dbconfig.json'
    dbparam = None
    with open(self.dbconfig, 'r') as json_data:
      dbparam = json.load(json_data)
    base = BaseAdaptor(**dbparam)
    self.engine = base.engine
    self.dbname = dbparam['dbname']
    if os.path.exists(self.dbname):
      os.remove(self.dbname)
    Base.metadata.create_all(self.engine)
    self.session_class = base.session_class
    base.start_session()
    platform_data = [{
      "platform_igf_id" : "M00001" ,
      "model_name" : "MISEQ" ,
      "vendor_name" : "ILLUMINA" ,
      "software_name" : "RTA" ,
      "software_version" : "RTA1.18.54"}]
    flowcell_rule_data = [{
      "platform_igf_id": "M00001",
      "flowcell_type": "MISEQ",
      "index_1": "NO_CHANGE",
      "index_2": "NO_CHANGE"}]
    pl = PlatformAdaptor(**{'session':base.session})
    pl.store_platform_data(data=platform_data)
    pl.store_flowcell_barcode_rule(data=flowcell_rule_data)
    project_data = [{
      'project_igf_id': 'IGFP0001_test_22-8-2017_rna',
      'project_name': 'test_22-8-2017_rna',
      'description': 'Its project 1',
      'project_deadline': 'Before August 2017',
      'comments': 'Some samples are treated with drug X'},{
      'project_igf_id': 'IGFP0001_test_22-8-2017_rna2'}]
    pa = ProjectAdaptor(**{'session':base.session})
    pa.store_project_and_attribute_data(data=project_data)
    sample_data = [{
      'sample_igf_id':'IGF00001',
      'project_igf_id':'IGFP0001_test_22-8-2017_rna',}]
    sa = SampleAdaptor(**{'session':base.session})
    sa.store_sample_and_attribute_data(data=sample_data)
    seqrun_data = [{
      'seqrun_igf_id': '171003_M00001_0089_000000000-TEST',
      'flowcell_id': '000000000-D0YLK',
      'platform_igf_id': 'M00001',
      'flowcell':'MISEQ'}]
    sra = SeqrunAdaptor(**{'session':base.session})
    sra.store_seqrun_and_attribute_data(data=seqrun_data)
    experiment_data = [{
      'experiment_igf_id': 'IGF00001_MISEQ',
      'project_igf_id': 'IGFP0001_test_22-8-2017_rna',
      'library_name': 'IGF00001',
      'sample_igf_id': 'IGF00001'}]
    ea = ExperimentAdaptor(**{'session':base.session})
    ea.store_project_and_attribute_data(data=experiment_data)
    run_data = [{
      'run_igf_id': 'IGF00001_MISEQ_000000000-D0YLK_1',
      'experiment_igf_id': 'IGF00001_MISEQ',
      'seqrun_igf_id': '171003_M00001_0089_000000000-TEST',
      'lane_number': '1',
      'R1_READ_COUNT': 1000}]
    ra = RunAdaptor(**{'session':base.session})
    ra.store_run_and_attribute_data(data=run_data)
    base.close_session()
    self.temp_dir = get_temp_dir()

  def tearDown(self):
    Base.metadata.drop_all(self.engine)
    if os.path.exists(self.dbname):
      os.remove(self.dbname)
    if os.path.exists(self.temp_dir):
      remove_dir(self.temp_dir)

  def test_get_db_data_and_create_json_dump(self):
    temp_dir = get_temp_dir()
    json_path = os.path.join(temp_dir, 'metadata_dump.json')
    get_db_data_and_create_json_dump(
      dbconfig_json=self.dbconfig,
      output_json_path=json_path)
    self.assertTrue(os.path.exists(json_path))
    with open(json_path, 'r') as fp:
      json_data = json.load(fp)
    self.assertTrue(isinstance(json_data, dict))
    self.assertTrue('project' in json_data.keys())
    self.assertTrue('sample' in json_data.keys())
    sample_data = json_data.get('sample')
    self.assertEqual(len(sample_data), 1)
    self.assertTrue('sample_igf_id' in sample_data[0].keys())
    self.assertEqual(sample_data[0].get('sample_igf_id'), 'IGF00001')
    project_data = json_data.get('project')
    self.assertEqual(len(project_data), 2)
    project_record = [
      entry.get('project_igf_id')
        for entry in project_data
          if entry.get('project_id')==sample_data[0].get('project_id')][0]
    self.assertEqual(project_record, 'IGFP0001_test_22-8-2017_rna')

class Metadata_load_test(unittest.TestCase):
  def setUp(self):
    self.temp_dir = get_temp_dir()
    formatted_dir = os.path.join(self.temp_dir, 'metadata', 'formatted_data')
    raw_dir = os.path.join(self.temp_dir, 'metadata', 'raw_data')
    os.makedirs(formatted_dir, exist_ok=True)
    os.makedirs(raw_dir, exist_ok=True)
    self.metadata_list = [
      'formatted_data/project1_reformatted.csv',
      'raw_data/project1.csv',
      'raw_data/project1_SampleSheet.csv',
      'formatted_data/project1_SampleSheet_reformatted.csv',
      'formatted_data/project2_reformatted.csv',
      'raw_data/project2.csv',
      'raw_data/project2_SampleSheet.csv',
      'formatted_data/project2_SampleSheet_reformatted.csv'
      ]
    metadata = pd.DataFrame([{'project_igf_id':'project', 'sample_igf_id':'sample1'}])
    for entry in self.metadata_list:
      path = os.path.join(self.temp_dir, 'metadata', entry)
      metadata.to_csv(path, index=False)

  def tearDown(self):
    remove_dir(self.temp_dir)

  def test_get_metadata_csv_files_from_metadata_dir(self):
    final_metadata_dict = \
      _get_metadata_csv_files_from_metadata_dir(
        metadata_dir=self.temp_dir)
    self.assertEqual(len(final_metadata_dict.keys()), 2)
    self.assertTrue('project1' in final_metadata_dict)
    self.assertTrue(isinstance(final_metadata_dict.get('project1'), dict))
    self.assertTrue('raw_csv' in final_metadata_dict.get('project1'))
    self.assertTrue('formatted_csv' in final_metadata_dict.get('project1'))
    self.assertEqual(
      final_metadata_dict.get('project1').get('raw_csv'),
      os.path.join(self.temp_dir, 'metadata', 'raw_data/project1.csv'))
    self.assertEqual(
      final_metadata_dict.get('project2').get('formatted_csv'),
      os.path.join(self.temp_dir, 'metadata', 'formatted_data/project2_reformatted.csv'))

  def test_create_json_for_metadata_upload(self):
    final_metadata_dict = \
      _get_metadata_csv_files_from_metadata_dir(
        metadata_dir=self.temp_dir)
    project_list = list(final_metadata_dict.keys())
    temp_json = \
      _create_json_for_metadata_upload(
        project_list=project_list,
        metadata_dict=final_metadata_dict)
    self.assertTrue(os.path.exists(temp_json))
    with open(temp_json, 'r') as fp:
      json_data = json.load(fp)
    self.assertEqual(len(json_data), 2)
    self.assertTrue('metadata_tag' in json_data[0])
    self.assertTrue('raw_csv_data' in json_data[0])
    self.assertTrue('formatted_csv_data' in json_data[0])
    self.assertTrue(isinstance(json_data[0].get('formatted_csv_data'), list))
    self.assertEqual(len(json_data[0].get('formatted_csv_data')), 1)
    self.assertTrue('project_igf_id' in json_data[0].get('formatted_csv_data')[0])
    self.assertEqual(json_data[0].get('formatted_csv_data')[0].get('project_igf_id'), 'project')
    self.assertTrue('sample_igf_id' in json_data[0].get('formatted_csv_data')[0])
    self.assertEqual(json_data[0].get('formatted_csv_data')[0].get('sample_igf_id'), 'sample1')

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


from isa.inst import *
import numpy as np
import math

class Vsoxsegxeix_v(Inst):
    name = 'vsoxsegxeix.v'

    def golden(self):
        vl = self['vs2'].size
        vd_size = vl * self['nfields']
        vd = np.zeros( vd_size, dtype=self['vs3'].dtype )
        for no in range( 0, self['vs2'].size ):
            if 'mask' in self:
                mask = ( self['mask'][np.floor(no/8).astype(np.int8)] >> (no % 8) ) & 1
            else:
                mask = 1
            if mask == 1:
                for idx in range( 0, self['nfields']):
                    vd[int( self['vs2'][no]/self['vs3'].itemsize + idx)] = self['vs3'][ no*self['nfields']+idx]

        return vd


#!/usr/bin/env python3

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

def main():

    total_notsee = [10, 20, 30, 40, 50]
    # total_notsee_x = [0, 10, 20, 30, 40, 50]

    plt.rcParams.update({"font.size": 6})

    fig = plt.figure(figsize=(80/25.4, 35/25.4))

    gs = fig.add_gridspec(1, 3, hspace=0.0)
    axs = gs.subplots(sharey="row")

    for d in [0, 1, 2]:
        m = np.load("data/transferlearning_m_mean_dim{}.npy".format(d), allow_pickle=False)
        h = np.load("data/transferlearning_h_std_dim{}.npy".format(d), allow_pickle=False)

        axs[d].set_title("Dimension %d" %(d))
        axs[d].plot(total_notsee, m, c="C%d" %(d))
        axs[d].fill_between(total_notsee, m-h, m+h, alpha=.2, zorder=0, color="C%d" %(d))
        axs[d].set_xlim((10, 50))
        axs[d].set_ylim((55, 95))
        axs[d].set_xticks([10, 20, 30, 40, 50])
        axs[d].set_yticks([60, 70, 80, 90])

    axs[0].set_ylabel("Accuracy")
    axs[1].set_xlabel("% missing")

    fig.tight_layout()
    filename = os.path.splitext(os.path.basename(__file__))[0] + '.pdf'
    fig.savefig(filename)

if __name__ == "__main__":
    main()


from sklearn.cluster import KMeans
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import svm
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt; plt.rcdefaults()
from ttictoc import TicToc
import pre_hot as pre
import numpy as np
t = TicToc()
import  os
from sklearn.externals import joblib
import pandas as pd

TrainTimeList=[]

def fit_model(X,Y,model,filename):
    if (os.path.exists(filename)):
        resmodel=joblib.load(filename)
        #print("ffffffff")
    else:
        t.tic()
        resmodel=model.fit(X,Y)
        t.toc()
        TrainTimeList.append(t.elapsed)
        print("total train =",t.elapsed)
        joblib.dump(resmodel,filename)

    return resmodel

#classsssifier
from sklearn.linear_model import LogisticRegression
def Class_model(X_T ,Y_T,X_Test,Y_test,rootFolder=''):
    TestTimeList=[]
    accracy_bar=[]
    print('-------Logistic Regression-------')
    logistic = LogisticRegression(C=10000,multi_class='auto',solver='liblinear')
    #logistic.fit(X_T,Y_T)
    logistic = fit_model(X_T,Y_T,logistic,rootFolder+'LogisticRegression')
    y = logistic.predict(X_Test)
    acc = accuracy_score(Y_test, y) * 100
    print("Accuracy Logistic Regression : ", acc)
    accracy_bar.append(acc)
    print("Confusion Matrix for Logistic Regression : ")
    print(confusion_matrix(Y_test, y))

    ''''
    print("      ----------- KNN ------------")
    model = KNeighborsClassifier(n_neighbors=20)
    t.tic()
    #model.fit(X_T,Y_T)
    model = fit_model(X_T,Y_T,model,rootFolder+'Knn')
    t.toc()
    TrainTimeList.append(t.elapsed)
    print("total train =", t.elapsed)
    t.tic()
    y=model.predict(X_Test)
    t.toc()

    TestTimeList.append(t.elapsed)
    print("total test =", t.elapsed)

    acc = accuracy_score(Y_test, y) * 100
    print("Accuracy Knn : ", acc)
    accracy_bar.append(acc)
    print("Confusion Matrix for Knn : ")
    print(confusion_matrix(Y_test, y))

    '''
    print("      ------- Tree----------")
    tree = DecisionTreeClassifier(random_state=100, max_depth=15, min_samples_leaf=4)
    R_tree= fit_model(X_T, Y_T, tree, rootFolder+"tree_model_15")
    t.tic()
    y_pred = R_tree.predict(X_Test)
    t.toc()
    TestTimeList.append(t.elapsed)
    print("total test =", t.elapsed )
    acc = accuracy_score(Y_test, y_pred) * 100
    print("Accuracy tree : ", acc)
    accracy_bar.append(acc)
    print("Confusion Matrix for tree : ")
    print(confusion_matrix(Y_test, y_pred))

    print("    ---------- SVM ------------")
    clf = svm.SVC(kernel='linear',gamma='auto')
    R=fit_model(X_T,Y_T,clf,rootFolder+"svm_model_linear ")

    t.tic()
    y_p=R.predict(X_Test)
    t.toc()
    TestTimeList.append(t.elapsed)
    print("total test =", t.elapsed)
    acc=accuracy_score(Y_test, y_p) * 100
    print("Accuracy : ", acc)
    accracy_bar.append(acc)

    print("Confusion Matrix for Svm: ")
    print(confusion_matrix(Y_test, y_p))

    print("      ----- addabos tree ---------")

    bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=15),
                             algorithm="SAMME.R",
                             n_estimators=50)
    Res_bdt = fit_model(X_T, Y_T, bdt, rootFolder+"addbos_tree_model_15")

    t.tic()
    y_prediction = Res_bdt.predict(X_Test)
    t.toc()
    TestTimeList.append(t.elapsed)
    print("total test =",t.elapsed)

    acc=accuracy_score(Y_test, y_prediction) * 100
    print("Accuracy addapost tree : ", acc)
    accracy_bar.append(acc)

 #   print("Train=",TrainTimeList)
    #plot_time(TrainTimeList)
#    print("Test=",TestTimeList)

    #plot_time(TestTimeList ,'Test')
    #plot_time(accracy_bar,'Accuracy')

def ModelWithPCA(X_Train ,Y_T,X_Test,Y_test,n_components,rootFolder=''):
    print("    ------------ PCA ----------------")

    train_pca,test_pca=pca(X_Train,X_Test,n_components)

    print('After Applying PCA With n_components = ',n_components)

    print('The data feature was',X_Train.shape,'has reduced to be',train_pca.shape)
    test_Time_List=[]
    accuracy=[]
    print(" ******** SVM _PCA :")
    svm_pca = svm.SVC(decision_function_shape='ovr', gamma='auto')
    print(train_pca.shape)
    svm_result = fit_model(train_pca, Y_T, svm_pca, rootFolder+ "svm_pca_"+str(n_components))
    #clf.fit(train_pca,Y_Train)
    t.tic()
    y_p = svm_result.predict(test_pca)
    t.toc()
    test_Time_List.append(t.elapsed)
    acc=accuracy_score(Y_test, y_p) * 100
    accuracy.append(acc)
    print("PCA--Accuracy svm : ",acc )
    print("confusion_matrix :")
    print(confusion_matrix(Y_test, y_p))

    print(" ******** Tree _PCA :")
    tree_pca=DecisionTreeClassifier()#criterion = "entropy", min_samples_leaf=5)
    tree_result = fit_model(train_pca, Y_T, tree_pca, rootFolder+"tree_pca_"+str(n_components))
    t.tic()
    y_p = tree_result.predict(test_pca)
    t.toc()
    test_Time_List.append(t.elapsed)
    acc=accuracy_score(Y_test, y_p) * 100
    accuracy.append(acc)
    print("PCA--Accuracy tree : ", acc)
    print("confusion_matrix :")
    print(confusion_matrix(Y_test, y_p))

    print(" ******** KNN _PCA :")
    knn_pca= KNeighborsClassifier(n_neighbors=1)
    knn_result = fit_model(train_pca, Y_T, knn_pca,rootFolder+ "knnpca_"+str(n_components))
    t.tic()
    y_p = knn_result.predict(test_pca)
    t.toc()
    test_Time_List.append(t.elapsed)
    acc=accuracy_score(Y_test, y_p) * 100
    accuracy.append(acc)
    print("PCA--Accuracy knn : ", acc)
    print("confusion_matrix :")
    print(confusion_matrix(Y_test, y_p))

    print(" ******** AdaBoost _PCA :")
    bdt_pca= AdaBoostClassifier(DecisionTreeClassifier(max_depth=15),
                             algorithm="SAMME.R",
                             n_estimators=50)
    bdt_result = fit_model(train_pca, Y_T, bdt_pca,rootFolder+ "bdt_pca_"+str(n_components))
    t.tic()
    y_p = bdt_result.predict(test_pca)
    t.toc()
    test_Time_List.append(t.elapsed)
    acc=accuracy_score(Y_test, y_p) * 100
    accuracy.append(acc)
    print("PCA--Accuracy tree-adabost : ", acc)
    print("confusion_matrix :")
    print(confusion_matrix(Y_test, y_p))

    #plot_time(TrainTimeList,"Train")
    plot_time(test_Time_List,"Test")
    plot_time(accuracy,"Accuracy")

def plot_time(draw_list,str):

    objects = ('Svm', 'Tree', 'KNN', 'Adapost_tree')
    y_pos = np.arange(len(objects))
    performance = draw_list
    plt.bar(y_pos, performance, align='center', alpha=0.5)
    plt.xticks(y_pos, objects)
    plt.ylabel(str+'in second')
    plt.title('Models')
    plt.show()

def pca(train,test,n_components):
    scaler = StandardScaler()
    #scaler = MinMaxScaler()
    train = scaler.fit_transform(train)
    test=scaler.transform(test)
    pca = PCA(n_components=n_components)
    principalComponents = pca.fit_transform(train)
    principalComponents_test=pca.transform(test)
    #print("pca",pca.explained_variance_ratio_)
    print("train",principalComponents.shape)
    print("test",principalComponents_test.shape)
    return  principalComponents,principalComponents_test

def Run(rootFolder='',train_val_split=True,pca_n_components=0.98):
    print("--------------------------------------------------")
    print("------------------ Classification Model -------------------")
    datasetpath = 'classification_train_data.csv'
    datasetscaler = 'datasetscaler'
    X_train, y_train = pre.ReadDataset('tmdb_5000_movies_classification.csv', 'tmdb_5000_credits.csv', 'rate')

    if train_val_split:
        X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.20)
    else:
        X_test, y_test = pre.ReadDataset('tmdb_5000_movies_testing_classification.xlsx',
                                         'tmdb_5000_credits_test.csv', 'rate')

    if (os.path.exists(rootFolder+datasetpath)):
        X_train = pd.read_csv(rootFolder+datasetpath)
        X_train = X_train.drop(labels=[X_train.columns[0]],axis=1)
        scaler = joblib.load(rootFolder+datasetscaler)
    else:
        X_train.index = range(len(X_train))
        X_train, scaler = pre.prefull(X_train)
        X_train.to_csv(rootFolder+datasetpath)

        joblib.dump(scaler,rootFolder+datasetscaler)

    #print(scaler)

    y_train = pre.class_label(y_train)

    #X_test, y_test = pre.ReadDataset('samples_tmdb_5000_movies_testing_classification.xlsx','samples_tmdb_5000_credits_test.csv','rate')
    y_test = pre.class_label(y_test)

    X_test.index = range(len(X_test))
    X_test=pre.pre_test(X_test,X_train,scaler)

    #X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20,shuffle=True)
    print ("train after_pre=",X_train.shape)
    print("test after pre=",X_test.shape)

    Class_model(X_train, y_train,X_test, y_test ,rootFolder)
    ModelWithPCA(X_train, y_train, X_test, y_test,pca_n_components,rootFolder)


import matplotlib.pyplot as plt
from random import randint
from timeit import Timer

solution_performance = {'listcomp': [], 'for_loop': [], 'set_add_discard': [], \
                        'via_counter': [], 'custom_counter': []}

for array_size in range(100, 1000000, 100000):

    sample_list = [randint(1, 100) for _ in range(array_size)]
    sample_list.append(101)

    stat1 = 'listcomp('+str(sample_list)+')'
    time1 = Timer(stat1, 'from captains_room import listcomp').timeit(3)/3
    solution_performance['listcomp'].append(time1)

    stat2 = 'for_loop('+str(sample_list)+')'
    time2 = Timer(stat2, 'from captains_room import for_loop').timeit(3)/3
    solution_performance['for_loop'].append(time2)

    stat3 = 'custom_counter('+str(sample_list)+')'
    time3 = Timer(stat3, 'from captains_room import custom_counter').timeit(3)/3
    solution_performance['custom_counter'].append(time3)

    stat4 = 'via_counter('+str(sample_list)+')'
    time4 = Timer(stat4, 'from captains_room import via_counter').timeit(3)/3
    solution_performance['via_counter'].append(time4)

    stat5 = 'set_add_discard('+str(sample_list)+')'
    time5 = Timer(stat5, 'from captains_room import set_add_discard').timeit(3)/3
    solution_performance['set_add_discard'].append(time5)

#Plotting time of execution of each function
x = list(range(100, 1000000, 100000))

plt.plot(x, solution_performance['for_loop'], 'r', label="for_loop")
plt.plot(x, solution_performance['listcomp'], 'b', label="listcomp")
plt.plot(x, solution_performance['custom_counter'], 'g', label="custom_counter")
plt.plot(x, solution_performance['set_add_discard'], 'y', label='set_add_discard')
plt.plot(x, solution_performance['via_counter'], 'm', label="via_counter")

plt.legend(loc=2)

plt.xlabel('Length of array')
plt.ylabel('Time, sec')
plt.title('Search for a single element in array')
plt.grid(True)
plt.show()


# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@version: 0.1
@Author: yangguang02
@license: Apache Licence
@contact: yangguang1900@163.com
@site: https://github.com/AubreyYoung/blog
@software: PyCharm
@file: pandas_execl
@ProjectName: python-demo
@Date: 2020/11/2 13:46
-------------------------------------------------
"""

# 导入pandas包
import pandas as pd

# 读取Excel数据，选取nyse这一页
nyse = pd.read_excel('A2-MAPS- LLD-Expansion Update 2020-10-21.xlsx', sheet_name='EXPANSION PLAN', na_values='n/a')

# 显示前几行
print(nyse.head())

# 显示摘要信息
nyse.info()

# 将Excel文件读取成 ExcelFile 格式
xls = pd.ExcelFile('A2-MAPS- LLD-Expansion Update 2020-10-21.xlsx')

# 获取sheet表的名称
exchanges = xls.sheet_names
print(exchanges)

# 读取所有sheet的数据，存储在字典中
listings = pd.read_excel(xls, sheet_name=exchanges, na_values='n/a')

# 查看 nasdaq 表的摘要信息
listings['StorageLUNs'].info()

# 创建 ExcelFile 变量
xls = pd.ExcelFile('A2-MAPS- LLD-Expansion Update 2020-10-21.xlsx')

# 获取sheet名
exchanges = xls.sheet_names

# 创建空列表
listings = []

# 使用循环逐一导入每一页的数据，并存储在列表中
for exchange in exchanges:
    listing = pd.read_excel(xls, sheet_name=exchange, na_values='n/a')
    listing['Exchange'] = exchange
    listings.append(listing)

# 合并数据
listing_data = pd.concat(listings)

# 查看合并后数据的摘要
listing_data.info()

# 读取 nyse 和nasdaq 这两张表的数据
nyse = pd.read_excel('listings.xlsx', sheet_name='nyse', na_values='n/a')
nasdaq = pd.read_excel('listings.xlsx', sheet_name='nasdaq', na_values='n/a')

# 添加一列 Exchange，标记来自哪张表的数据
nyse['Exchange'] = 'NYSE'
nasdaq['Exchange'] = 'NASDAQ'

# 拼接两个DataFrame
combined_listings = pd.concat([nyse, nasdaq])  # 注意这里的[ ]
combined_listings.info()


import pytest

import pandas as pd
from sklearn.datasets import load_digits
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss

from gama import GamaClassifier

@pytest.fixture
def gamaclassifier():
    return GamaClassifier(random_state=0, max_total_time=60)

def _gama_on_digits(gama):
    X, y = load_digits(return_X_y=True)
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, stratify=y, random_state=0
    )

    # Add checks on individuals (reproducibility)
    gama.fit(X_train, y_train)

    # Add checks
    _ = gama.predict(X_test)
    y_proba = gama.predict_proba(X_test)

    assert log_loss(y_test, y_proba) == gama.score(X_test, y_test)
    assert log_loss(y_test, y_proba) == gama.score(X_test, pd.Series(y_test))
    assert log_loss(y_test, y_proba) == gama.score(
        X_test, LabelEncoder().fit_transform(y_test.reshape(-1, 1))
    )

def test_full_system_single_core(gamaclassifier):
    from gama.utilities.generic.async_evaluator import AsyncEvaluator

    AsyncEvaluator.n_jobs = 1
    _gama_on_digits(gamaclassifier)

def test_full_system_multi_core(gamaclassifier):
    from gama.utilities.generic.async_evaluator import AsyncEvaluator

    AsyncEvaluator.n_jobs = 2
    _gama_on_digits(gamaclassifier)


import requests
import json

def get_practitioner(npi):
    """Returns a Practitioner Resource from Djmongo"""
    url = "https://registry.npi.io/search/fhir/Practitioner.json" \
          "?identifier.value=%s" % (npi)
    response = requests.get(url)
    try:
        jr = json.loads(response.text)

        if 'results' not in jr:
            jr = {'error', 'The lookup failed. Invalid response from server'}

        if not jr['results']:
                jr = {'error', 'Invalid NPI'}
    except ValueError:
        jr = {'error',
              'The lookup failed. JSON was not returned from the server.'}

    return jr['results'][0]

def convert_practitioner_fhir_to_form(pract_res, user):
    """Converts a Practitioner Resource into Values for Form"""
    data = {}
    data['user'] = user
    data['first_name']= pract_res['name'][0]['given'][0]
    data['last_name']= pract_res['name'][0]['family'][0]
    data['npi']= pract_res['identifier'][0]['value']
    data['fhir_id']= pract_res['id']

    return data

def convert_practitioner_fhir_to_meta(pract_res, user):
    """Converts a Practitioner Resource into Values for Meta"""
    data = {}
    data['user'] = user
    data['npi']= pract_res['identifier'][0]['value']
    data['fhir_id']= pract_res['id']

    return data

def get_pecos_individual_affliliation(npi):
    """Returns a Pecos Affiliation Resource from Djmongo"""
    url = "https://registry.npi.io/search/pecos/compiled_individuals." \
          "json?NPI=%s" % (npi)
    response = requests.get(url)
    try:
        jr = json.loads(response.text)

        if 'results' not in jr:
            jr = {'error', 'The lookup failed. Invalid response from server'}

        if not jr['results']:
                jr = {'error', 'Invalid NPI'}
    except ValueError:
        jr = {'error',
              'The lookup failed. JSON was not returned from the server.'}

    return jr['results'][0]['works_for']

def convert_pecos_to_form(pecos_res, user):
    """Converts a Practitioner Resource into Values for Form"""
    data = {}
    data['user'] = user
    data['name']= pecos_res[0]['NAME']
    data['npi']= pecos_res[0]['NPI']
    data['description']= pecos_res[0]['DESCRIPTION']

    return data

def convert_pecos_to_meta(pecos_res, user):
    """Converts a Practitioner Resource into Values for Meta"""
    data = {}
    data['user'] = user
    data['npi']= pecos_res['identifier'][0]['value']
    data['fhir_id']= pecos_res['id']

    return data

# if __name__ == "__main__":
#     print(get_pecos_individual_affliliation(1205824083))


fname = input('File name: ')
try:
    fhand = open(fname)
except:
    print('There is an exception.')
    exit()

count = 0
for line in fhand:
    if not line.startswith('From'): continue
    count = count + 1
    words = line.split()
    print(words[1])
print('There is ', count, ' From lines.')


from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

from rollcall.groups.views import (
    GroupListView,
    GroupDetailView,
    GroupStatesView,
    GroupStateListView,
    GroupUpdate,
)
from rollcall.people.views import PersonListView, PersonDetailView

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'rollcall.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),

    url(
        r'^people/$',
            PersonListView.as_view(),
            name='person-list',
    ),
    url(
        r'^people/(?P<slug>.*)$',
            PersonDetailView.as_view(),
            name='person-detail',
    ),

    url(
        r'^group/$',
            GroupListView.as_view(),
            name='group-list',
    ),
    url(
        r'^group/(?P<slug>.*?)/state$',
        GroupUpdate.as_view(),
        name='group-state',
    ),
    url(
        r'^group/(?P<slug>.*)$',
            GroupDetailView.as_view(),
            name='group-detail',
    ),
    url(
        r'^group-state/$',
            GroupStatesView.as_view(),
            name='group-list-states',
    ),
    url(
        r'^group-state/(?P<state>.*)$',
            GroupStateListView.as_view(),
            name='group-list-by-state',
    ),
)


# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

# pecan imports
import ConfigParser
import socket
import json
from pecan import expose, response, request, conf
from pecan.rest import RestController
from libra.common.api.lbaas import Device, db_session
from libra.common.api.lbaas import Vip, Limits, Counters, TenantLimits
from libra.openstack.common import log
from libra.admin_api.acl import tenant_is_admin, tenant_is_user

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from oslo.config import cfg

LOG = log.getLogger(__name__)

class LimitsController(RestController):
    """ a sub-controller for StatusController """
    @expose('json')
    def get_one(self, tenant_id):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )
        ret = {}
        with db_session() as session:
            limit = session.query(TenantLimits.loadbalancers).\
                filter(TenantLimits.tenantid == tenant_id).scalar()

            ret['maxLoadBalancers'] = limit
            session.commit()
        return ret

    @expose('json')
    def get_all(self):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )
        ret = {}
        with db_session() as session:
            limits = session.query(Limits.name, Limits.value).all()
            if limits is None:
                response.status = 500
                return dict(
                    faultcode="Server",
                    faultstring="Error obtaining limits"
                )
            for limit in limits:
                ret[limit.name] = limit.value
            session.commit()
        return ret

    @expose('json')
    def put(self, tenant_id=None):
        if not tenant_is_admin(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )
        try:
            data = json.loads(request.body)
        except:
            response.status = 400
            return dict(
                faultcode="Client",
                faultstring="Invalid JSON received"
            )
        with db_session() as session:
            if tenant_id is None:
                for key, value in data.iteritems():
                    limit = session.query(Limits).filter(Limits.name == key).\
                        first()
                    if limit is None:
                        session.rollback()
                        response.status = 400
                        return dict(
                            faultcode="Client",
                            faultstring="Limit not found: {0}".format(key)
                        )
                    limit.value = value
            else:
                if 'maxLoadBalancers' in data:
                    limit = session.query(TenantLimits).\
                        filter(TenantLimits.tenantid == tenant_id).first()
                    if limit is not None:
                        limit.loadbalancers = data['maxLoadBalancers']
                    else:
                        new_limit = TenantLimits()
                        new_limit.tenantid = tenant_id
                        new_limit.loadbalancers = data['maxLoadBalancers']
                        session.add(new_limit)
                else:
                    session.rollback()
                    response.status = 400
                    return dict(
                        faultcode="Client",
                        faultstring="No user settable limit in json"
                    )
            session.commit()

class PoolController(RestController):
    @expose('json')
    def get(self):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )
        NULL = None  # For pep8
        with db_session() as session:
            dev_use = session.query(Device).\
                filter(Device.status == 'ONLINE').count()
            dev_free = session.query(Device).\
                filter(Device.status == 'OFFLINE').count()
            dev_error = session.query(Device).\
                filter(Device.status == 'ERROR').count()
            dev_pending = session.query(Device).\
                filter(Device.status == 'DELETED').count()
            vips_use = session.query(Vip).\
                filter(Vip.device > 0).count()
            vips_free = session.query(Vip).\
                filter(Vip.device == NULL).count()
            vips_bad = session.query(Vip).\
                filter(Vip.device == 0).count()
            status = {
                "devices": {
                    "used": dev_use,
                    "available": dev_free,
                    "error": dev_error,
                    "pendingDelete": dev_pending
                },
                "vips": {
                    "used": vips_use,
                    "available": vips_free,
                    "bad": vips_bad
                }
            }
            session.commit()
        return status

class ServiceController(RestController):
    @expose('json')
    def get(self):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )

        ret = {
            'mysql': [],
            'gearman': []
        }
        config = ConfigParser.SafeConfigParser()
        config.read(cfg.CONF['config_file'])

        # Connect to all MySQL servers and test
        for section in conf.database:
            db_conf = config._sections[section]
            conn_string = '''mysql+mysqlconnector://%s:%s@%s:%s/%s''' % (
                db_conf['username'],
                db_conf['password'],
                db_conf['host'],
                db_conf['port'],
                db_conf['schema']
            )

            if 'ssl_key' in db_conf:
                ssl_args = {'ssl': {
                    'cert': db_conf['ssl_cert'],
                    'key': db_conf['ssl_key'],
                    'ca': db_conf['ssl_ca']
                }}

                engine = create_engine(
                    conn_string, isolation_level="READ COMMITTED",
                    pool_size=1, connect_args=ssl_args, pool_recycle=3600
                )
            else:
                engine = create_engine(
                    conn_string, isolation_level="READ COMMITTED",
                    pool_size=1, pool_recycle=3600
                )
            session = sessionmaker(bind=engine)()
            try:
                session.execute("SELECT 1")
                session.close()
                ret['mysql'].append(
                    {"ip": db_conf['host'], "status": 'ONLINE'}
                )
            except:
                ret['mysql'].append(
                    {"ip": db_conf['host'], "status": 'OFFLINE'}
                )

        # Socket connect to all gearman servers, TODO: a better gearman test
        for server in conf.gearman.server:
            ghost, gport = server.split(':')
            try:
                sock = socket.socket()
                sock.settimeout(5)
                sock.connect((ghost, int(gport)))
                sock.close()
                ret['gearman'].append({"ip": ghost, "status": 'ONLINE'})
            except socket.error:
                ret['gearman'].append({"ip": ghost, "status": 'OFFLINE'})
                try:
                    sock.close()
                except:
                    pass

        return ret

class CountersController(RestController):
    @expose('json')
    def get(self):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )
        with db_session() as session:
            counters = session.query(Counters.name, Counters.value).all()
            return counters

class StatusController(RestController):
    pool = PoolController()
    service = ServiceController()
    counters = CountersController()
    limits = LimitsController()


# OK I don't give a fuck I'll just write this function somehow
def collect_search_statistics(db_conn, search):
    cursor = db_conn.cursor()
    # took this huge query from stackoverflow question 36359440 or something actually I'm just a student ok whatever
    # who made product_title primary key I guess it is smart or maybe not I dunno
    cursor.execute(
        "INSERT INTO search_statistics (product_title, num_searched) "
        "VALUES ('" + str(search) + "', 1) ON CONFLICT (product_title)"
        "DO UPDATE SET num_searched = search_statistics.num_searched + 1"
    )
    db_conn.commit() # dunno what it does but did not work without it lol


# -*- coding: utf-8 -*-
# pp/utils/test_tasksort.py

from datetime import datetime
from dateutil.parser import parse as dt
from pprint import pprint

import pytest
import mock

from pp.utils.optionlines import OptionLines

@pytest.mark.xfail
def test_sort_tasks_by_urgency123():
    source_text = """\
* [ ] Sometime 2
**[ ] Today 1
* [ ] Sometime 1
  [ ] This week 2
**[ ] Today 2
  [ ] This week 1
* [ ] Sometime 3
"""
    option_lines = OptionLines(source_text)
    assert len(option_lines) == 7
    assert 0 == 56


from pyspark import SparkContext, SparkConf
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.regression import LinearRegression
from pyspark.sql import SQLContext, Row
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import UserDefinedFunction
from pyspark.ml.linalg import Vectors

import os
import pyspark_csv as pycsv

os.environ["SPARK_LOCAL_IP"] = "127.0.0.1" # set local IP

DATADIR = "./Desktop/BDP/predict3/AQI/data"
 # data directory

def mySparkContext():
    """
    Sets the Spark Context
    """
    conf = (SparkConf()
            .setMaster("local")
            .setAppName("predictAQI")
            .set("spark.executor.memory", "4g"))
    sc = SparkContext(conf = conf)
    return sc

sc = mySparkContext()
sqlCtx = SQLContext(sc)
sc.addPyFile("Desktop/BDP/predict3/AQI/pyspark_csv.py")

def loadDF(filename):
    """
    Load and parse filename as pyspark.sql.DataFrame
    using pyspark_csv.py
    """
    path = os.path.join(DATADIR, filename)
    plain = sc.textFile(path)
    df = pycsv.csvToDataFrame(sqlCtx, plain, sep=',')
    return df

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

if __name__ == "__main__":

    train = loadDF("train.csv")
    test = loadDF("test.csv")

    testNumber = test.select('Number').rdd.map(lambda x: x.Number)

    train = train.select('AQI', 'Temp Arithmetic Mean', 'Wind SpeedArithmetic Mean',
    'Wind Direction Arithmetic Mean', 'Barometric pressure Arithmetic Mean', 'CO Arithmetic Mean',
    'SO2 Arithmetic Mean', 'NO2 Arithmetic Mean', 'Ozone Arithmetic Mean', 'PM25 Mean')

    test = test.select('Temp Arithmetic Mean', 'Wind SpeedArithmetic Mean',
    'Wind Direction Arithmetic Mean', 'Barometric pressure Arithmetic Mean', 'CO Arithmetic Mean',
    'SO2 Arithmetic Mean', 'NO2 Arithmetic Mean', 'Ozone Arithmetic Mean', 'PM25 Mean')

    # format train for Linear Regression as (label, features)
    ntrain = train.rdd.map(lambda x: Row(label = float(x[0]) \
         ,features = Vectors.dense(x[1:]))).toDF().cache() # Linear Regression is iterative, need caching
    ntest = test.rdd.map(lambda x: Row(features = Vectors.dense(x[0:]))).toDF()

    lr = LinearRegression(maxIter = 100, regParam = 0.4, elasticNetParam=0.7)
    model = lr.fit(ntrain)

    print("Coefficients: " + str(model.coefficients))
    print("Intercept: " + str(model.intercept))

    pred = model.transform(ntest).select('prediction').rdd.map(lambda x: x.prediction)

    # configure the submission format as follows
    submit = sqlCtx.createDataFrame(testNumber.zip(pred), ["Number", "AQI"])
    """
    NOTE: rdd1.zip(rdd2) works provided that both RDDs have the same partitioner and the same number
    of elements per partition, otherwise should either repartition or can do:

    """
    os.chdir(DATADIR)
    # file is small so can save pandas.DataFrame as csv
    submit.toPandas().to_csv("prediction.csv", index = False)
    # if not, should saveAsTextFile:
    # submit.rdd.saveAsTextFile("/BDP/data/prediction")
    sc.stop()


from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView

from apps.consumption.views import dcf, complete_dcf
from apps.general import views as general_views
from apps.juliana.views import juliana
from apps.scheduling import views as scheduling_views

urlpatterns = [
    # Root
    url(r'^$', scheduling_views.overview, name='root'),

    # Short urls to 'subsystems'
    url(r'^dcf/(?P<pk>\d+)/$', dcf, name='dcf'),
    url(r'^dcf/(?P<pk>\d+)/check/$', complete_dcf, name='dcf-complete'),
    url(r'^juliana/(?P<pk>\d+)/$', juliana, name='juliana'),

    # Apps
    url(r'^billing/', include('apps.billing.urls')),
    url(r'^consumption/', include('apps.consumption.urls')),
    url(r'^organization/', include('apps.organization.urls')),
    url(r'^profile/', include('apps.profile.urls')),
    url(r'^scheduling/', include('apps.scheduling.urls')),
    url(r'^ical$', scheduling_views.ical),
    url(r'^ical/(?P<ical_id>[^/]+)$', scheduling_views.personal_ical, name='ical'),

    url(r'^api/', include('api.urls')),

    # "Static" general_views
    url(r'^about/$', general_views.about, name='about'),
    url(r'^help/$', general_views.help, name='help'),
    url(r'^login/$', general_views.login, name='login'),
    url(r'^logout/$', general_views.logout, name='logout'),
    url(r'^register/$', general_views.register, name='register'),
    url(r'^change_current_organization/(?P<organization>[-\w]+)/$',
        general_views.change_current_organization, name='change-current-organization'),
    url(r'^change_current_language/$', general_views.change_current_language, name='change-current-language'),

    # Django Admin
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    # Robots
    url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls))
    ]


# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 14:12:51 2018

@author: soumy
"""

def merge(a,b):
    (c,m,n)=([],len(a),len(b))
    (i,j)=(0,0)
    print('merge called')
    while i+j < m+n:
        if(i==m):
            c.append(b[j])
            print ("C when A finished=",c)
            j=j+1
        elif(j==n):
            c.append(a[i])
            print ("C when B finished=",c)
            i=i+1
        elif(a[i]<b[j]):
            c.append(a[i])
            print ("C when A lesser=",c)
            i=i+1
        elif(b[j]<a[i]):
            c.append(b[j])
            print ("C when B lesser=",c)
            j=j+1
        elif (a[i]==b[j]):
            c.append(a[i])
            i+=1
            j+=1
    return c

def mergesort(a,left, right):
    print('mergesort called')
    print('a in mergesort',a[left:right])
    if right-left<=1:
        return(a[left:right])
    if(right-left>1):
        mid=(left+right)//2
        L=mergesort(a,left, mid)
        print('L=',L,'  ',mid)
        R=mergesort(a,mid,right)
        print('R=',R,'  ',mid)
        return merge(L,R)


import cv2 as cv
import numpy as np
import os
# print(os.getcwd())
# Load an image
originalImage = cv.imread(os.getcwd()+'\\images\\10_dr.JPG', 1)
# Resize image
image = cv.resize(originalImage, (701, 468))
# Changing colorspace from BGR to Grayscale
image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# Applying median blur
image = cv.medianBlur(image, 3)
# Display the image
cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.imshow('image', image)
cv.waitKey(2000)
cv.destroyAllWindows()

# create a CLAHE object (Arguments are optional).
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
image = clahe.apply(image)
# image = cv.GaussianBlur(image, (11, 11), 0)
# Thresholding to extract bright regions
image = cv.threshold(image, 170, 255, cv.THRESH_BINARY)[1]
# Display the image
cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.imshow('image', image)
cv.waitKey(10000)
cv.destroyAllWindows()


from basetypes import *
import os,logging,datetime,json
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

def datefromiso(isodate):
    y=int(isodate[:4])
    m=int(isodate[5:7])
    d=int(isodate[8:10])
    return datetime.date(y,m,d)

class Add(webapp.RequestHandler):
    def get(self):
        template_values = {
            }
        path = os.path.join(os.path.dirname(__file__), './template/upload.html')
        self.response.out.write(template.render(path,template_values))

    def post(self):
        #get all the infomation
        logging.info(self.request.arguments())
        jsondata = self.request.get('jsondata')
        logging.info(jsondata)
        data = json.loads(jsondata)
        #generate and put game object
        record_temp = Record()
        record_temp.Name = data['name'];
        record_temp.Date = datefromiso(data['date'])
        item_list = []
        count = 1
        for item in data['items']:
            item_temp = Item()
            item_temp.Name = item['name']
            item_temp.Number = int(item['num'])
            item_temp.Price = float(item['unitprice'])
            item_temp.Order = count
            count += 1
            key = item_temp.put()
            item_list.append(str(key))
        record_temp.Items = item_list
        record_temp.put()
        self.response.out.write('{"error":"no"}')
        # self.redirect('/main')

def main():
    application = webapp.WSGIApplication([
        (r'.*', Add)
        ],debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()


# Plot xy vs drift time
import pylab as pl
import numpy as np
import random
from plot_PMT import plot_PMT
import matplotlib as mpl
from matplotlib.patches import Rectangle

#fC = 'drift_1_5_6_7_5_2_4_5_5_4_2_4_5_5_4.npz'
#fC = '../LUX_data/Kr_lux10_20140903T1918_cp17059.npz'
#fC = 'drift_dt3_2.3_3.8_6.5_4.7_4.0_1.5_4.7_3.4_4.2_2.8_3.9_1.8_3.6_2.4_2.1.npz'
#fC = 'drift_.4,2.3,4.8,6.0,6.5,4.8,5.8_1.6,1.4,5.0,5.4,6.2,5.3,6.1_2.0,1.9,3.7,5.0,5.5,4.6,3.5_6.8,2.5,1.7,2.0,6.0,5.1,3.5_0.4,2.0,3.3,5.7,3.1,5.6,2.8_.7,2.0,3.0,4.8,6.5,2.9,4.6.npz'
fC = 'drift_1,2,5,6,6,6,5_1,2,5,6,6,6,5_2,2,4,5,5,5,4_2,2,4,5,5,5,4_1,2,3,5,5,5,4_1,2,3,5,5,5,4.npz'
dataC = np.load(fC)
#rC = dataC['r']
#thetaC = dataC['theta']
xC = dataC['x']
yC = dataC['y']
drift_timeC = dataC['drift_time']
#xC = np.multiply(rC, np.cos(thetaC))
#yC = np.multiply(rC, np.sin(thetaC))

cathode = (-0.34175)*100
liquid_surface = 0.14505*100

#define PMTs
xP, yP, xP0, yP0 = plot_PMT()

x = [[] for i in range(9)]
y = [[] for i in range (9)]
max_drift = np.amax(drift_timeC)
for index, item in enumerate(drift_timeC):
	if item > 10 and item <= 50:
		x[0].append(xC[index])
		y[0].append(yC[index])
	elif item > 50 and item <= 90:
		x[1].append(xC[index])
		y[1].append(yC[index])
	elif item > 90 and item <= 130:
		x[2].append(xC[index])
		y[2].append(yC[index])
	elif item > 130 and item <= 170:
		x[3].append(xC[index])
		y[3].append(yC[index])
	elif item > 170 and item <= 210:
		x[4].append(xC[index])
		y[4].append(yC[index])
	elif item > 210 and item <= 250:
		x[5].append(xC[index])
		y[5].append(yC[index])
	elif item > 250 and item <= 290:
		x[6].append(xC[index])
		y[6].append(yC[index])
	elif item > 290 and item <= 330:
		x[7].append(xC[index])
		y[7].append(yC[index])
	elif item > 330 and item <= max_drift:
		x[8].append(xC[index])
		y[8].append(yC[index])
	else:
		continue

x = np.asarray(x)
y = np.asarray(y)
h = range(9)
for k in range(9):
    h[k], yedges, xedges = np.histogram2d(y[k], x[k], bins = 250, range = [[-25, 25], [-25, 25]])
    h[k] = np.flipud(h[k])

vm = 1
cm = 'Blues'
#cm = 'Reds'
fig, ax = pl.subplots(3, 3, sharex = 'col', sharey = 'row', subplot_kw = {'aspect':1})
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.0001, hspace=0.2)
fig.suptitle(fC, fontsize = 16)
im = ax[0][0].imshow(h[0], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[0][0].set_title('10-50us')
ax[0][1].imshow(h[1], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[0][1].set_title('50-90us')
ax[0][2].imshow(h[2], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[0][2].set_title('90-130us')
ax[1][0].imshow(h[3], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[1][0].set_title('130-170us')
ax[1][1].imshow(h[4], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[1][1].set_title('170-210us')
ax[1][2].imshow(h[5], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[1][2].set_title('210-250us')
ax[2][0].imshow(h[6], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[2][0].set_title('250-290us')
ax[2][1].imshow(h[7], vmin = 0, vmax = vm, extent = (-25, 25, -25, 25), interpolation = 'nearest', cmap = cm, zorder = 0)
ax[2][1].set_title('290-330us')
ax[2][2].scatter(x[8], y[8], s = 3, facecolor='b', lw = 0, zorder = 0)
ax[2][2].set_title('330-'+str(int(max_drift))+'us')

for i in range(3):
	for j in range(3):
		ax[i][j].grid()
		ax[i][j].plot(xP,yP,'-', c = '.5')
		ax[i][j].plot(xP0,yP0,'-', c = 'k')
		ax[i][j].set_ylim(-25,25)
		ax[i][j].set_xlim(-25,25)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)


# Will Pankiewicz

from tkinter import *
from tkinter.messagebox import showinfo

class BMI(Frame):
    'Body Mass Index app'
    def __init__(self,parent=None):
        'constructor'
        Frame.__init__(self, parent)
        # If you use pack for the widgets in make_widgets, change
        # this to pack
        self.grid()
        BMI.make_widgets(self)

    def make_widgets(self):
        'create the widgets for the GUI and attach the handler'
        Label(self, text='Enter your height:').grid(row=0, column=0)
        self.height=Entry(self)
        self.height.grid(row=0, column=1)
        Label(self, text='Enter your weight:').grid(row=1, column=0)
        self.weight=Entry(self)
        self.weight.grid(row=1, column=1)
        Button(self, text='Calculate BMI', command=self.compute).grid(row=3, columnspan=2)

    def compute(self):
        'the handler for button "Compute BMI"'
        try:
            height=int(self.height.get())
            weight=int(self.weight.get())
            bmi=(weight*703)/(height**2)
            if bmi<18.5:
                showinfo(title='Results', message='Your BMI is {} \n You are underweight.'.format(bmi))
            if bmi>18.5 and bmi<25:
                showinfo(title='Results', message='Your BMI is {} \n You are in the normal range.'.format(bmi))
            if bmi>25:
                showinfo(title='Results', message='Your BMI is {} \n You are overweight.'.format(bmi))
        except:
            showinfo(title='OOOOOOPPPSS!', message='Sorry! You have entered an invalid number!')
# Test the class by writing:
BMI().mainloop()


import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
def plot_one_trajectory(traj):
    """ plots one trajectory which is a dictionary"""
    plt.plot(traj['lon'],traj['lat'])

def plot_one_trajectory_color(traj):
    """ plots one trajectory with colored dots
    SAD it doesn't work :((( """
    cmap = plt.cm.coolwarm(np.linspace(-10.,10.,50))
    fig, ax = plt.subplots()
    grid = np.array([np.array(traj['lon']),np.array(traj['lat'])]).T.reshape(-1,1,2)
    lc = LineCollection(grid, cmap="coolwarm")
    lc.set_array(np.array(traj['temp']))
    ax.add_collection(lc)
    ax.autoscale_view()
    plt.show()

def plot_temp_contour(d):
    """ plot temp contour plot"""
    for j in range(len(d)):
        lats = d[j]['lat']
        lon = np.mean(np.array(d[j]['lon']))
        temp = d[j]['temp']

        plt.plot(lats,temp)

def plot_temp_contour(d):
    """ plot temp contour plot"""
    meanlat = []
    meantemp = []
    meanlon = []
    for j in range(len(d)):
        lats = d[j]['lat']
        lon = np.mean(np.array(d[j]['lon']))
        temp = d[j]['temp']

        meanlat.append(np.mean(np.array(lats)))
        meantemp.append(np.mean(np.array(temp)))
        meanlon.append(lon)
    plt.contourf(np.array(meanlon),np.array(meanlat),np.array(meantemp))