import cv2
import numpy as np

pc = 1
bx = 150
by = 150
bh = 550
bw = 370
c1 = 0  # pedestrian
c2 = 1  # car
c3 = 0  # traffic light

y = [pc, bx, by, bh, bw, c1, c2, c3]

print(y)

# Python program to explain cv2.rectangle() method

# Reading an image in default mode
image = cv2.imread('mer.png')

# Window name in which image is displayed
window_name = 'Image'

# Start coordinate, here (5, 5)
# represents the top left corner of rectangle
start_point = (bx, by)

# Ending coordinate, here (220, 220)
# represents the bottom right corner of rectangle
end_point = (bh, bw)

# Blue color in BGR
color = (255, 0, 0)

# Line thickness of 2 px
thickness = 2

# Using cv2.rectangle() method
# Draw a rectangle with blue line borders of thickness of 2 px
image = cv2.rectangle(image, start_point, end_point, color, thickness)

# Displaying the image
cv2.imshow(window_name, image)
cv2.waitKey(0)
cv2.destroyAllWindows()


from unittest import TestResult
import sys, time, re

class _BasicTestResult(TestResult):
    """Test result similar to unittest module _TextTestResult"""

    separator1 = '=' * 77
    separator2 = '-' * 77

    def __init__(self, stream, iterations):
        TestResult.__init__(self)
        self.stream = stream
        self.iterations = iterations > 1

    def getDescription(self, test):
        desc=test.shortDescription()
        func=str(test)
        match=re.search("test_(.*) \(.*\.test_(.*)_.*\)", func)
        if not match: return desc or func
        else: return "%2d.%3d: %-67s" % (int(match.group(2)), int(match.group(1)), desc)

    def startTest(self, test):
        TestResult.startTest(self, test)
        if not self.iterations:
            self.stream.write("%-75s" % self.getDescription(test))

    def addSuccess(self, test):
        TestResult.addSuccess(self, test)
        if not self.iterations:
            self.stream.write("ok\n")

    def addError(self, test, err):
        TestResult.addError(self, test, err)
        if not self.iterations:
            self.stream.write("ERR\n")

    def addFailure(self, test, err):
        TestResult.addFailure(self, test, err)
        if not self.iterations:
            self.stream.write("FAIL\n")

    def printErrors(self):
        if not self.iterations:
            self.printErrorList('ERROR', self.errors)
            self.printErrorList('FAIL', self.failures)

    def printErrorList(self, flavour, errors):
        for test, err in errors:
            self.stream.write("\n"+self.separator1+"\n")
            self.stream.write("%s: %s\n" % (flavour,self.getDescription(test)))
            self.stream.write(self.separator2+"\n")
            self.stream.write("%s\n" % err)

class BasicTestRunner:
    """Test runner similar to unittest TextTestRunner"""

    def __init__(self, stream=sys.stderr, iterations=1):

        try: iterations=int(iterations)
        except: iterations=1

        self.stream = stream
        self.iterations = iterations

    def _makeResult(self):
        return _BasicTestResult(self.stream, self.iterations)

    def run(self, test):
        "Run the given test case or test suite."
        result = self._makeResult()
        startTime = time.time()

        # test execution
        for i in range(self.iterations):
            if self.stream == sys.stderr:
                self.stream.write("Iteration:%6d\r" % (i+1))
            test(result)
        if self.stream == sys.stderr: self.stream.write("\n")

        stopTime = time.time()
        timeTaken = stopTime - startTime
        result.printErrors()
        if not self.iterations > 1: self.stream.write(result.separator2+"\n")
        run = result.testsRun
        self.stream.write("Ran %d test%s in %.3fs\n" %
                            (run, run != 1 and "s" or "", timeTaken))
        self.stream.write("\n")
        if not result.wasSuccessful():
            self.stream.write("FAILED (")
            failed, errored = map(len, (result.failures, result.errors))
            if failed:
                self.stream.write("failures=%d" % failed)
            if errored:
                if failed: self.stream.write(", ")
                self.stream.write("errors=%d" % errored)
            self.stream.write(")\n")
        else:
            self.stream.write("OK\n")
        return result


# MIT License
#
# Copyright (c) 2018, Andrew Warrington.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
mhSolver.py
AW

TL;DR -
"""

# Import stock modules.
import numpy as np
import matplotlib.pyplot as plt

# Import custom modules.
import homogenousKF.evaluateSchedule as es

def run_chain():

	# Define parameters of MH.
	mh_steps = 10000
	transition_prob = [0.2, 0.6, 0.2]  # The local transition kernel.
	transition_kern = [-1, 0, 1]       # Transition kernel space.

	# Do automated stuff.
	samples = [None] * mh_steps

	n = np.random.randint(es.t_max)
	samples[0] = es.calculate_kalman_cost(n)

	for i in range(1, mh_steps):

		if n == 0:
			n_new = n + np.random.choice(transition_kern, p=[0, 1 - transition_prob[2], transition_prob[2]])
		else:
			n_new = n + np.random.choice(transition_kern, p=transition_prob)

		s = es.calculate_kalman_cost(n_new)

		# Now calculate the MH ratio.
		A = np.min((1., s['r'] / samples[i-1]['r']))
		if np.random.rand() < A:
			n = n_new
			samples[i] = s
		else:
			samples[i] = samples[i-1]

		if s['r'] == 1:
			p = 0

	return samples

if __name__ == '__main__':

	print('Weird bug that optimum is flat...')

	mhSamples = run_chain()


## example bot ##

rooms = ["room", "roomhere"]

from irc import IRCBot, run_bot

owner = "theholder" # put your irc nick here

class bot(IRCBot):

	def say(self, nick, message, channel):
		if nick.lower() != owner:
			return
		else:
			ret = message[4:]
			return ret

	def command_patterns(self):
		return(
			self.command("say", self.say),
		)

host = "irc.domain.tld"
port = 6667
nick = "bot"

run_bot(bot,
	host,
	port,
	nick,
	rooms)


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

#连续子数组最大和
#题目描述
# HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学，
# 今天测试组开完会后,他又发话了:在古老的一维模式识别中,
# 常常需要计算连续子向量的最大和,
# 当向量全为正数的时候,问题很好解决
# 但是,如果向量中包含负数,是否应该包含某个负数,
# 并期望旁边的正数会弥补它呢
# 例如:{6,-3,-2,7,-15,1,2,2},
# 连续子向量的最大和为8
# (从第0个开始,到第3个为止)
# 你会不会被他忽悠住，
# (子向量的长度至少是1)

#最优方法，时间复杂度O(n)
#和最大的子序列的第一个元素肯定是正数
#因为元素有正有负,因此子序列的最大和一定大于0
#此算法针对有正有负的情况，如果全是负数，需要特殊处理

class Solution:
	def FindGreatestSumOfSubArray(self,arr):
		"""
        :param arr:List[int]
        :return: int
        """
		maxSum=0
		curSum=0
		maxN=max(arr)
		if maxN<0:
			return maxN

		for i in range(len(arr)):
			curSum+=arr[i]
			if curSum>maxSum:
				maxSum=curSum
			if curSum<0:
				curSum=0
		return maxSum

so=Solution()
nums=[6,-3,-2,7,-15,1,2,2]
nums=[-2,-8,-1,-5,-9]
res=so.FindGreatestSumOfSubArray(nums)
print(res)


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 09:50:32 2015

@author: mamauer
"""
import os
import glob
from morphablegraphs.animation_data.bvh import BVHReader
import numpy as np
from morphablegraphs.construction.preprocessing import bitvector as bv
from morphablegraphs.construction.fpca.fpca_semantic_data import FPCASemanticData
from morphablegraphs.construction.motion_primitive.statistical_model_trainer import StatisticalModelTrainer
from morphablegraphs.motion_model.motion_primitive import MotionPrimitive
import matplotlib.pyplot as plt
import copy
import json
import scipy.interpolate as si

def test_bitvector_calulation():
    test_file = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\sidestepLeft\walk_001_4_sidestepLeft_139_263.bvh'
    bvhfile = BVHReader(test_file)
    features = ['Bip01_L_Toe0', 'Bip01_R_Toe0']
    bitvector = bv.calc_bitvector_walking(bvhfile.frames,
                                          features,
                                          verbose=True)
    print(bitvector)

def test_keyframe_annotation():
    skeleton_file = r'..\..\..\skeleton.bvh'
    test_file = r'C:\repo\data\1 - MoCap\2 - Rocketbox retargeting\Take_walk\walk_001_1.bvh'
    bvhfile = BVHReader(test_file)
    features = ['Bip01_L_Toe0', 'Bip01_R_Toe0']
    keyframes = bv.detect_keyframes(bvhfile.frames, features, verbose=False)
    print(keyframes)

def majority_vote(index, vector, w):
    selected_elements = vector[index-w: index+w+1]
    one_counter = sum(selected_elements == 1)
    zero_counter = sum(selected_elements == 0)
    if one_counter > zero_counter:
        vector[index] = 1
    else:
        vector[index] = 0

def smooth_bitvector(tmp, w=2):
    bitvectors = copy.deepcopy(tmp)
    features = bitvectors.keys()
    for feature in features:
        extented_bitvector = np.zeros(len(bitvectors[feature]) + 2*w)
        extented_bitvector[:w] = bitvectors[feature][0]
        extented_bitvector[-w:] = bitvectors[feature][-1]
        extented_bitvector[w: -w] = bitvectors[feature]
        # print(len(extented_bitvector))
        # print(extented_bitvector)
        for i in range(len(bitvectors[feature])):
            majority_vote(i+w, extented_bitvector, w)
        bitvectors[feature] = extented_bitvector[w : -w]
    return bitvectors

def test_smooth_bitvector():
    bitvector = {"left": np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1])}
    # print(len(bitvector['left']))
    blocks1 = bv.count_blocks(bitvector['left'])
    n_blocks1 = len(blocks1)

    smoothed_bitvector = smooth_bitvector(bitvector)
    print(smoothed_bitvector)
    blocks2 = bv.count_blocks(smoothed_bitvector['left'])
    n_blocks2 = len(blocks2)

    fig = plt.figure()
    plt.plot(bitvector['left'], 'b')
    plt.plot(smoothed_bitvector['left'], 'g')
    plt.ylim([-1, 2])
    plt.show()

def test_gen_annotation():
    # bvhfile = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\leftStance\
    bvhfile = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\rightStance\walk_001_1_rightStance_472_514.bvh'
    feature_points = ['Bip01_L_Toe0', 'Bip01_R_Toe0']
    motion_primitive_model = 'walk_rightStance'
    anno_vec = bv.gen_foot_contact_annotation(bvhfile, feature_points, motion_primitive_model)
    print(anno_vec)

def gen_walk_annotation():
    test_folder = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\rightStance'
    motion_primitive_model = 'walk_rightStance'
    feature_points = ['Bip01_L_Toe0', 'Bip01_R_Toe0']
    annotation_data = {}
    test_bvbfiles = glob.glob(test_folder + os.sep + '*.bvh')
    for item in test_bvbfiles:
        filename = os.path.split(item)[-1]
        anno_vec = bv.gen_foot_contact_annotation(item, feature_points, motion_primitive_model)
        # anno_vec['left_contact'] = anno_vec['left_contact'].tolist()
        # anno_vec['right_contact'] = anno_vec['right_contact'].tolist()
        annotation_data[filename] = anno_vec
    output_filename = test_folder + os.sep + 'walk_rightStance_semantic_annotation.json'
    with open(output_filename, 'w') as outfile:
        json.dump(annotation_data, outfile)

def load_spatial_temporal_params():
    test_file = r'C:\repo\data\2 - PCA\combine_spatial_temporal\walk_leftStance_low_dimensional_motion_data.json'
    with open(test_file, 'r') as infile:
        low_dimensional_data = json.load(infile)
    print(low_dimensional_data.keys())
    print(len(low_dimensional_data['motion_data']))
    print(low_dimensional_data['n_basis_temporal'])

def load_morphable_model():
    test_morphable_model = r'C:\repo\data\3 - Motion primitives\motion_primitives_quaternion_PCA95\elementary_action_models\elementary_action_walk\walk_leftStance_quaternion_mm.json'
    with open(test_morphable_model, 'r') as infile:
        data = json.load(infile)
    print(data.keys())
    # print(data['b_spline_knots_time'])
    # knots = data['b_spline_knots_time']
    # annotation_data_file = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\leftStance\walk_leftStance_semantic_annotation.json'
    # with open(annotation_data_file, 'r') as infile:
    #     annotation_data = json.load(infile)
    # keys = annotation_data.keys()
    # print(annotation_data[keys[0]])
    # left_annotation = annotation_data[keys[1]]['left_contact']
    # right_annotation = annotation_data[keys[0]]['right_contact']
    # x = range(len(left_annotation))
    # s_knots, s_coeffs, s_degree = si.splrep(x, left_annotation, t=knots[4:-4])
    # print(s_knots)
    # print(s_coeffs)
    # print(s_degree)
    # # evaluate fitted spline
    # evaluate_points = np.linspace(s_knots[0], s_knots[-1], 200)
    # points = si.splev(evaluate_points, (s_knots, s_coeffs[:-4], s_degree))
    # fig = plt.figure()
    # plt.plot(evaluate_points, points)
    # plt.plot(range(len(left_annotation)), left_annotation)
    # plt.show()

def test_fpca_semantic_data():
    data_file = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\leftStance\walk_leftStance_semantic_annotation.json'
    motion_primitive_model_file = r'C:\repo\data\3 - Motion primitives\motion_primitives_quaternion_PCA95\elementary_action_models\elementary_action_walk\walk_leftStance_quaternion_mm.json'
    with open(motion_primitive_model_file, 'r') as infile:
        model_data = json.load(infile)
    knots = model_data['b_spline_knots_time']
    fpca_semantic = FPCASemanticData()
    fpca_semantic.load_data_from_file(data_file)

    fpca_semantic.set_knots(knots)
    fpca_semantic.spline_representation()
    print(np.array(fpca_semantic.semantic_spline.values()).shape)
    fpca_semantic.dimension_reduction()
    fpca_semantic.save_data('walk_leftStance_semantic_low_dimensional_data.json')

def test_model_semantic_statistical_model():
    spatial_temporal_file = r'C:\repo\data\2 - PCA\combine_spatial_temporal\walk_rightStance_low_dimensional_motion_data.json'
    semantic_file = r'walk_rightStance_semantic_low_dimensional_data.json'
    model_trainer = StatisticalModelTrainer()
    model_trainer.load_data_from_file(spatial_temporal_file, semantic_file)
    model_trainer._train_gmm()
    model_trainer._create_gmm()
    # print(model_trainer.get_b_spline_knots(8, 46))
    model_trainer._save_model()

def check_semantic_labels():
    semantic_file = r'C:\repo\data\1 - MoCap\4 - Alignment\elementary_action_walk\rightStance\walk_rightStance_semantic_annotation.json'
    with open(semantic_file, 'r') as infile:
        semantic_data = json.load(infile)
    # count = 0
    # for filename in semantic_data.keys():
    #     count += 1
    #     if semantic_data[filename]['left_contact'][-1] != 1.0:
    #         print(filename, 'left_contact')
    #     if semantic_data[filename]['right_contact'][-1] != 1.0:
    #         print(filename, 'right_contact')
    # print(count)

    # spatial_temporal_file = r'C:\repo\data\2 - PCA\combine_spatial_temporal\walk_rightStance_low_dimensional_motion_data.json'
    # with open(spatial_temporal_file, 'r') as infile:
    #     spatial_temporal_data = json.load(infile)
    # print(spatial_temporal_data.keys())
    model_file = r'C:\git-repo\mgrd\data\walk_leftStance_quaternion_mm_with_semantic.json'
    with open(model_file, 'r') as infile:
        model_data = json.load(infile)
    print(model_data.keys())
    print(model_data['n_dim_semantic'])
    print(model_data['n_dim_spatial'])
    print(model_data['n_dim_time'])
    # knots = model_data['b_spline_knots_time']
    # print(knots)

    # semantci_file = r'walk_leftStance_semantic_low_dimensional_data.json'
    # with open(semantci_file, 'r') as infile:
    #     semantic_data = json.load(infile)
    # print(semantic_data.keys())
    # low_dimensional_data = np.array(semantic_data['semantic_low_dimensional_data'])
    # print(low_dimensional_data.shape)
    # s = np.sum(low_dimensional_data, axis=0)
    # print(s)

    # mean_vec = semantic_data['semantic_mean_vec']
    # left_contact_mean = mean_vec[:8]
    # right_contact_mean = mean_vec[8:]
    # left_contact_spline = (knots, left_contact_mean, 3)
    # right_contact_spline = (knots, right_contact_mean, 3)
    # x = np.linspace(knots[0], knots[-1], 100)
    # left_contact_points = si.splev(x, left_contact_spline)
    # right_contact_points = si.splev(x, right_contact_spline)
    # fig = plt.figure()
    # plt.plot(x, left_contact_points, label='left contact')
    # plt.plot(x, right_contact_points, label='right contact')
    # plt.legend()
    # plt.show()
    # # print(mean_vec)

def add_mean_info_spatial_temporal_params():
    spatial_temporal_file = r'C:\repo\data\2 - PCA\combine_spatial_temporal\walk_rightStance_low_dimensional_motion_data.json'
    morphable_model_file = r'C:\repo\data\3 - Motion primitives\motion_primitives_quaternion_PCA95\elementary_action_models\elementary_action_walk\walk_rightStance_quaternion_mm.json'
    with open(morphable_model_file, 'r') as infile:
        morphable_model_data = json.load(infile)
    with open(spatial_temporal_file, 'r') as infile:
        spatial_temporal_data = json.load(infile)
    # write mean_spatial, mean_temporal and n_dim_spatial into spatial_temporal_data
    spatial_temporal_data['mean_spatial_vector'] = morphable_model_data['mean_spatial_vector']
    spatial_temporal_data['mean_time_vector'] = morphable_model_data['mean_time_vector']
    spatial_temporal_data['n_dim_spatial'] = morphable_model_data['n_dim_spatial']
    with open(spatial_temporal_file, 'w') as outfile:
        json.dump(spatial_temporal_data, outfile)

def evaluate_semantic_spline(spline, granularity=100):
    knots, coeffs, degree = spline
    time_vector = np.linspace(knots[0], knots[-1], granularity)
    return si.splev(time_vector, spline)

def test_sample_semantic_morphable_model():
    model_file = r'C:\repo\data\3 - Motion primitives\motion_primitives_quaternion_PCA95\elementary_action_semantic_models\elementary_action_walk\walk_rightStance_quaternion_mm_with_low_level_semantic.json'
    # with open(model_file, 'r') as infile:
    #     semantic_model_data = json.load(infile)
    # print(semantic_model_data.keys())
    # print(semantic_model_data['semantic_annotation'])
    walk_leftStance = MotionPrimitive(model_file)
    sample = walk_leftStance.sample_low_dimensional_vector()
    print(sample)
    sample = walk_leftStance.sample()
    print(sample.semantic_spline)
    # points = evaluate_semantic_spline(sample.semantic_spline, granularity=100)
    # for vec in points:
    #     print(vec[-1])
    # print(points[-1])
    # semantic_annotation = sample.gen_semantic_annotation()
    # print(semantic_annotation)
    # N = 100
    # # bad_samples = 0
    # for i in range(N):
    #     sample = walk_leftStance.sample()
    #     points = evaluate_semantic_spline(sample.semantic_spline, granularity=100)
    #     for vec in points:
    #         print(vec[-1])
    #     sample = walk_leftStance.sample()
    #     annotations = sample.gen_semantic_annotation()
    #     count = 0
    #     for annot in annotations:
    #         if annot[-1] != 1:
    #             count += 1
    #     if count > 0:
    #         bad_samples += 1
    # print(bad_samples)
    # print(sample)
    # print(walk_leftStance.semantic_pca['n_components'])
    # print(walk_leftStance.s_pca['n_components'])
    # print(walk_leftStance.t_pca['n_components'])

def check_functional_data():
    pass

""" Main part, for testing purpose """
if __name__ == '__main__':
    # test_keyframe_annotation()
    # test_bitvector_calulation()
    # test_smooth_bitvector()
    # test_gen_annotation()
    # gen_walk_annotation()
    # load_spatial_temporal_params()
    # load_morphable_model()
    # test_fpca_semantic_data()
    # check_semantic_labels()
    # check_functional_data()
    test_sample_semantic_morphable_model()
    # add_mean_info_spatial_temporal_params()
#     data_folder = os.sep.join(('C:', 'MarkusMauer', 'motiongraph', 'data',
#                                '1 - MoCap', '2 - Rocketbox retargeting'))
#
#     skeleton_file = r'..\..\..\skeleton.bvh'
#
#     features = ['Bip01_L_Toe0', 'Bip01_R_Toe0']
# #    features = ['LeftFoot', 'RightFoot']
#
#     sourcefolder = os.sep.join((data_folder, 'Take_walk')) + os.sep
#     files = glob.glob(sourcefolder + r'*.bvh')
#     for f in files:
#         print f
#         reader = BVHReader(f)
#         frames = reader.frames
#
#         try:
#             keyframes = bv.detect_keyframes(frames, features, verbose=False)
#             bv.splitt_motion(frames, keyframes, f.split(os.sep)[-1])
#
#         except:
#             bitvector = bv.calc_bitvector_walking(frames, features,
#                                                   verbose=True, threshold=0.2)


from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.bubble import Bubble
from kivy.garden.mapview import MapView, MapMarker, MapMarkerPopup
from mapview.geojson import GeoJsonMapLayer
from kivy.storage.jsonstore import JsonStore
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior

class ImageButton(ButtonBehavior, Image):
    pass

class MapIcons(GridLayout):
    def __init__(self, *args, **kwargs):
        super(MapIcons, self).__init__(**kwargs)

        self.rows = 3
        self.cols = 1
        self.padding = '8sp'
        self.spacing = '8sp'
        self.size_hint = (None, None)
        self.height = 3 * self.width

        self.btn_zoom_in = ImageButton(size_hint=(1, 1./3.),
                                       allow_stretch=True,
                                       keep_ratio=True,
                                       source="assets/icon_zoom_in.png")
        self.btn_zoom_out = ImageButton(size_hint=(1, 1./3.),
                                        allow_stretch=True,
                                        keep_ratio=True,
                                        source="assets/icon_zoom_out.png")
        self.btn_center_on = ImageButton(size_hint=(1, 1./3.),
                                         allow_stretch=True,
                                         keep_ratio=True,
                                         source="assets/icon_crosshair.png")

        self.add_widget(self.btn_zoom_in)
        self.add_widget(self.btn_zoom_out)
        self.add_widget(self.btn_center_on)

class ShowMap(BoxLayout):
    def __init__(self, *args, **kwargs):
        super(ShowMap, self).__init__(**kwargs)

        points = JsonStore("points_of_interest.json")

        self.view = MapView(lat=points["center"]['lat'],
                            lon=points["center"]['lon'],
                            zoom=15,
                            cache_dir="cache")

        # Add Route
        layer = GeoJsonMapLayer(source="route.json")
        self.view.add_layer(layer)

        # Add User
        user_marker = MapMarker(lat=points["center"]['lat'],
                                lon=points["center"]['lon'],
                                source='assets/icon_user.png')
        self.view.add_widget(user_marker)

        # Add Icons
        self.icons = MapIcons(width='60sp')

        def zoom_in(instance):
            print('Zoom In:', self.view.zoom)
            if self.view.zoom == 19:
                return
            self.view.zoom += 1
        self.icons.btn_zoom_in.bind(on_press=zoom_in)

        def zoom_out(instance):
            print('Zoom Out:', self.view.zoom)
            if self.view.zoom == 1:
                return
            self.view.zoom -= 1
        self.icons.btn_zoom_out.bind(on_press=zoom_out)

        def center_on(instance):
            print('Center On:', user_marker.lat, user_marker.lon)
            self.view.center_on(user_marker.lat, user_marker.lon)
        self.icons.btn_center_on.bind(on_press=center_on)

        self.view.add_widget(self.icons)

        for point in points["list"]:
            bubble = Bubble(orientation='vertical', background_image=point['image'])
            map_marker = MapMarkerPopup(id="marker",
                                        lat=point['lat'],
                                        lon=point['lon'],
                                        source='assets/icon_marker.png')
            map_marker.add_widget(bubble)
            self.view.add_marker(map_marker)

        self.add_widget(self.view)

        ### Begin Close Bubble ###
        def close_bubbles(arg, touch):
            for c in self.view.children:
                for cc in c.children:
                    if cc.id == 'marker':
                        if len(cc.children) and cc.is_open:
                            cc.is_open = False
                            cc.refresh_open_status()
        self.view.children[-1].bind(on_touch_up=close_bubbles)
        ### End Close Bubble ###

    def on_size(self, *args):
        if self.view:
            self.icons.pos = (self.width - self.icons.width, (self.height - self.icons.height)/2.)

class MapsApp(App):
    def build(self):
        self.title = 'Route Map'
        return ShowMap()

if __name__ == '__main__':
    MapsApp().run()


import tkinter as tk
import sys
import os

win = tk.Tk()

win.title("Medical ID")

win.resizable(False,False)

win.attributes('-fullscreen',True)

win.bind("<Escape>", lambda x: win.destroy())

titleLbl = tk.Label(win, text = "Medical ID\n__________________")

labelfont = ('Ariel', 40, 'bold')

titleLbl.config(font=labelfont)

titleLbl.config(fg='#03adfc')

label2 = tk.Label(win, text = "Scan Phone Here\n...")
label2.config(font=labelfont)

fName = "Yousif"

label3 = tk.Label(win, text = "Data Transfer Complete!\nWelcome " + fName)
label3.config(font=labelfont)

def nfcScan():
	label2.destroy()
	simBtn.destroy()
	label3.pack(pady=300)
	win.after(5000,refresh)

def refresh():
	python = sys.executable
	os.execl(python, python, * sys.argv)

simBtn = tk.Button(text = "Simulate Scan", command = nfcScan)

titleLbl.pack()
simBtn.pack()

label2.pack(pady=300)

win.mainloop()


# To help streamline certain development activities, ISO
# (the International Organization for Standardization) provides
# a table of codes, short abbreviations, and long abbreviations
# for every nation in the world. We have created a class called
# Nation to structure this information. The Nation class
# contains 6 attributes:
#
# - short_name: The short, common form of a country's name,
#   such as "Albania".
# - long_name: The long, official form of a country's name,
#   such as "Republic of Albania".
# - iso_code: The numeric code corresponding to the nation,
#   such as 8.
# - iso_short: The short abbreviation corresponding to the
#   nation, such as AL.
# - iso_long: The long abbreviation corresponding to the
#   nation, such as ALB.
# - capital: The capital city, such as Tirana.
#
# To let you debug, we've provided you the class here. Your
# code will have access to this.
class Nation:
    def __init__(self, short_name, long_name, iso_code, iso_short, iso_long, capital):
        self.short_name = short_name
        self.long_name = long_name
        self.iso_code = iso_code
        self.iso_short = iso_short
        self.iso_long = iso_long
        self.capital = capital

# Write a function called to_dictionaries that will take as
# input a list of instances of this class. It should return a
# dictionary of dictionaries. The keys for the dictionaries
# should be the short names of the nations. The values should
# be additional dictionaries, each with five keys: long_name,
# iso_code, iso_short, iso_long, and capital.
#
# For example, if we created two instances of Nation like this:
# new_nation_1 = Nation("Albania", "Republic of Albania", 8, "AL", "ALB", "Tirana")
# new_nation_2 = Nation("Angola", "Republic of Angola", 24, "AO", "AGO", "Luanda")
#
# ...then made them into a list like this:
# nation_list = [new_nation_1, new_nation_2]
#
# ...then called the function:
# new_dict = to_dictionaries(nation_list)
#
# ...then we would get this dictionary in return:
# {"Albania": {"long_name": "Republic of Albania", "iso_code": 8, "iso_short": "AL", "iso_long": "ALB", "capital": "Tirana"},
# "Angola": {"long_name": "Republic of Angola", "iso_code": 24, "iso_short": "AO", "iso_long": "AGO", "capital": "Luanda"}}
#
# HINT: This problem looks long, but don't overcomplicate
# it. Each part is something you've done lots of times:
# iterate through a list of instances, get the key, create
# a new dictionary, add the other key-values one-by-one,
# and return the overall dictionary.

# Add your code here!
def to_dictionaries(nations):
    nation_dictionary = {}

    for nation in nations:
        nation_dictionary[nation.short_name] = {"long_name": nation.long_name,
                                                "iso_code": nation.iso_code,
                                                "iso_short": nation.iso_short,
                                                "iso_long" : nation.iso_long,
                                                "capital" : nation.capital}

    return nation_dictionary

# Below are some lines of code that will test your function.
# You can change the value of the variable(s) to test your
# function with different inputs.
#
# If your function works correctly, this will originally
# print (although the order of the keys may vary) the
# sample dictionaries shown in the directions.
new_nation_1 = Nation("Albania", "Republic of Albania", 8, "AL", "ALB", "Tirana")
new_nation_2 = Nation("Angola", "Republic of Angola", 24, "AO", "AGO", "Luanda")
nation_list = [new_nation_1, new_nation_2]
print(to_dictionaries(nation_list))


import pathlib as pl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.metrics
import statsmodels.api as sm
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, LinearRegression
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.model_selection import KFold, GridSearchCV
from sklearn.base import BaseEstimator, TransformerMixin

""" ##############################################################
Preprocessing
###############################################################"""
path_to_data = pl.Path(__file__).parent.joinpath('prostate_poprawione.csv')
df = pd.read_csv(path_to_data)
df = df.drop(['id'], axis=1)
df_train = df[df['train'] == 'T'].drop(['train'], axis=1)
X, y = df_train.values[:, :-1], df_train.values[:, -1]
scaler = StandardScaler()
scaler.fit(df_train)
df_train_scaled = scaler.transform(df_train)
X_scaled, y_scaled = df_train_scaled[:, :-1], df_train_scaled[:, -1]

""" ##############################################################
Zheng Log method implementation (for PCR_ord)
###############################################################"""
def compute_sort_keys_from_tvalues(X):
    if_passed = False
    while if_passed is False:
        try:
            X_pca = PCA(n_components=X.shape[1]).fit_transform(X)
        except np.linalg.LinAlgError:
            pass
        else:
            if_passed = True

    tvalues = sm.OLS(y_scaled, sm.add_constant(X_pca)).fit().tvalues[1:]
    tvalues_square = tvalues * tvalues
    return np.argsort(-tvalues_square)

SORT_KEYS = compute_sort_keys_from_tvalues(X_scaled)

class ZhengLohTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, n_components=None):
        self.n_components = n_components

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        global SORT_KEYS
        return X[:, SORT_KEYS][:, 0:self.n_components]

""" ##############################################################
Cross validation
###############################################################"""
def perform_cv(model, param_name, param_range, X=X_scaled):
    cv = KFold(n_splits=10)
    scorer = sklearn.metrics.make_scorer(sklearn.metrics.mean_squared_error)
    grid = GridSearchCV(model, scoring=scorer, param_grid={param_name: param_range}, cv=cv)
    grid.fit(X, y_scaled)
    results = pd.DataFrame.from_dict(grid.cv_results_)[['param_' + param_name, 'mean_test_score', 'std_test_score']]
    results['std_test_score'] = results['std_test_score'] / np.sqrt(results.shape[0])
    return results

results_RR = perform_cv(
    Ridge(), 'alpha', [0.1, 4.3, 11.2, 22.8, 36.6, 74.4, 151.1, 388.8, 1000.0]
)
results_PCR = perform_cv(
    Pipeline(steps=[('pca', PCA()), ('linreg', LinearRegression())]), 'pca__n_components', [1, 2, 3, 4, 5, 6, 7, 8]
)
results_PCRord = perform_cv(
    Pipeline(steps=[('zlt', ZhengLohTransformer()), ('linreg', LinearRegression())]), 'zlt__n_components',
    [1, 2, 3, 4, 5, 6, 7, 8], X=PCA(n_components=8).fit_transform(X_scaled)
)

""" ##############################################################
Converting  "alpha" from RR to the "degrees of freedom".
###############################################################"""
def calculate_degrees_freedom(X, alpha):
    """ function which converts  "alpha" from RR to "degrees of freedom"""
    inner_factor = np.linalg.inv(X.T.__matmul__(X) + alpha * np.identity(X.shape[1]))
    hat_matrix = (X.__matmul__(inner_factor)).__matmul__(X.T)
    return np.trace(hat_matrix)

results_RR['param_alpha'] = results_RR['param_alpha'].apply(lambda x: calculate_degrees_freedom(X_scaled, x))
results_RR = results_RR.rename(columns={'param_alpha': 'param_df'})
results_RR = results_RR.sort_values(by=['param_df'])
results_RR = results_RR.reset_index(drop=True)

""" ##############################################################
Plotting
###############################################################"""
def plot_results(ax, results, param_name, title):
    """ function which creates plot for single model"""
    ax.plot(results[param_name], results['mean_test_score'])
    ax.scatter(results[param_name], results['mean_test_score'])
    ax.errorbar(results[param_name], results['mean_test_score'], results['std_test_score'])
    one_error_above_min = results['mean_test_score'].min() + results['std_test_score'][results['mean_test_score'].argmin()]
    one_error_below_min = results['mean_test_score'].min() - results['std_test_score'][results['mean_test_score'].argmin()]
    ax.hlines(one_error_above_min, 0, 8, linestyles='dashed')
    ax.hlines(one_error_below_min, 0, 8, linestyles='dashed')
    ax.set_xticks(np.linspace(0, 8, 9))
    ax.set_yticks(np.linspace(0, 1.6, 9))
    ax.set_xlabel(param_name)
    ax.set_ylabel('mean squared error')
    ax.set_title(title)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
plot_results(ax1, results_RR, 'param_df', 'ridge')
plot_results(ax2, results_PCR, 'param_pca__n_components', 'pcr')
plot_results(ax3, results_PCRord, 'param_zlt__n_components', 'pcr_ord')


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/electrum_chi/electrum/base_crash_reporter.py
# Compiled at: 2019-08-24 06:06:43
# Size of source mod 2**32: 5458 bytes
import asyncio, json, locale, traceback, subprocess, sys, os
from .version import ELECTRUM_VERSION
from . import constants
from .i18n import _
from .util import make_aiohttp_session
from .logging import describe_os_version, Logger

class BaseCrashReporter(Logger):
    report_server = 'https://crashhub.electrum.org'
    config_key = 'show_crash_reporter'
    issue_template = '
Traceback
\n
\n{traceback}\n
\n\n
Additional information
\n
\n
Electrum version: {app_version}
\n
Python version: {python_version}
\n
Operating system: {os}
\n
Wallet type: {wallet_type}
\n
Locale: {locale}
\n
\n    '
    CRASH_MESSAGE = _('Something went wrong while executing Electrum-CHI.')
    CRASH_TITLE = _('Sorry!')
    REQUEST_HELP_MESSAGE = _('To help us diagnose and fix the problem, you can send us a bug report that contains useful debug information:')
    DESCRIBE_ERROR_MESSAGE = _('Please briefly describe what led to the error (optional):')
    ASK_CONFIRM_SEND = _('Do you want to send this report?')

    def __init__(self, exctype, value, tb):
        Logger.__init__(self)
        self.exc_args = (exctype, value, tb)

    def send_report(self, asyncio_loop, proxy, endpoint='/crash', *, timeout=None):
        if constants.net.GENESIS[-4:] not in ('4943', 'e26f'):
            if '.electrum.org' in BaseCrashReporter.report_server:
                raise Exception(_('Missing report URL.'))
        report = self.get_traceback_info()
        report.update(self.get_additional_info())
        report = json.dumps(report)
        coro = self.do_post(proxy, (BaseCrashReporter.report_server + endpoint), data=report)
        response = asyncio.run_coroutine_threadsafe(coro, asyncio_loop).result(timeout)
        return response

    async def do_post(self, proxy, url, data):
        async with make_aiohttp_session(proxy) as session:
            async with session.post(url, data=data) as resp:
                return await resp.text()

    def get_traceback_info(self):
        exc_string = str(self.exc_args[1])
        stack = traceback.extract_tb(self.exc_args[2])
        readable_trace = ''.join(traceback.format_list(stack))
        id = {'file':stack[(-1)].filename,
         'name':stack[(-1)].name,
         'type':self.exc_args[0].__name__}
        return {'exc_string':exc_string,
         'stack':readable_trace,
         'id':id}

    def get_additional_info(self):
        args = {'app_version':ELECTRUM_VERSION,
         'python_version':sys.version,
         'os':describe_os_version(),
         'wallet_type':'unknown',
         'locale':locale.getdefaultlocale()[0] or '?',
         'description':self.get_user_description()}
        try:
            args['wallet_type'] = self.get_wallet_type()
        except:
            pass

        try:
            args['app_version'] = self.get_git_version()
        except:
            pass

        return args

    @staticmethod
    def get_git_version():
        dir = os.path.dirname(os.path.realpath(sys.argv[0]))
        version = subprocess.check_output([
         'git', 'describe', '--always', '--dirty'],
          cwd=dir)
        return str(version, 'utf8').strip()

    def get_report_string(self):
        info = self.get_additional_info()
        info['traceback'] = ''.join((traceback.format_exception)(*self.exc_args))
        return (self.issue_template.format)(**info)

    def get_user_description(self):
        raise NotImplementedError

    def get_wallet_type(self):
        raise NotImplementedError

def trigger_crash():

    class TestingException(Exception):
        pass

    def crash_test():
        raise TestingException('triggered crash for testing purposes')

    import threading
    t = threading.Thread(target=crash_test)
    t.start()


import nltk
import tts_amazonpolly
from datetime import datetime
import time

conversation = False

def process_speech(inputspeech):
    processedspeech = inputspeech + " - Speech Processed"
    tokens = nltk.word_tokenize(inputspeech)
    print (tokens)
    tagged = nltk.pos_tag(tokens)
    print (tagged[0:6])
    entities = nltk.chunk.ne_chunk(tagged)
    print (entities)
    return processedspeech

"""def interpret_input(inputspeech):
    wordtokens = nltk.word_tokenize(inputspeech)
    print (wordtokens)
    if "shopping" in wordtokens:
        print ("Enable shopping speech sequence")"""

def check_for_wake_signal():
    listentext = raw_input("Enter Wake Signal (Hi Margo, Margo): ")
    listentexttokens = nltk.word_tokenize(listentext)
    print (listentexttokens)
    if "Margo" in listentexttokens:
        return True
    else:
        return False

def check_for_speech():
    listentext = raw_input("Enter speech: ")
    listentexttokens = nltk.word_tokenize(listentext)
    print (listentexttokens)
    return listentexttokens

def margo_greeting():
    hour = time.strftime("%H")
    print (hour)
    if hour == "18" or "19" or "20" or "21" or "22" or "23":
        speak_response("Good evening!  How can I help?")
    elif hour == "6" or "7" or "8" or "9" or "10":
        speak_response("Good morning!  How can I help?")
    elif hour == "12" or "13" or "14" or "15" or "16" or "17":
        speak_response("Good afternoon!  How can I help?")
    else:
        speak_response("Hi!  How can I help?")
    return

def speak_response(inputspeech):
    tts_amazonpolly.convert_text_to_speach(inputspeech)
    return


# apply a tranformation matrix no new coordinates from
# a previous ProCare alignment
# matrices are stored in ProCare output procare.tsv

import numpy as np
from time import strftime, localtime
import os

def xtract_matrix(procare_file_, line_number_):
    with open(procare_file_, 'r') as f:
        data = f.read().split('\n')
    matrix_line = data[line_number_]
    matrix_cpnts = matrix_line.split('\t')[33:49]
    matrix_cpnts = [float(n) for n in matrix_cpnts]
    matrix = np.array([[n for n in matrix_cpnts[0:4]],
                      [n for n in matrix_cpnts[4:8]],
                      [n for n in matrix_cpnts[8:12]],
                      [n for n in matrix_cpnts[12:16]]])

    return matrix

def transform(mol2_, matrix_, ofile_):
    with open(mol2_, 'r') as f:
        mol2 = f.read()
        molecule_area = mol2.split('@<TRIPOS>MOLECULE\n')[1].split('@<TRIPOS>')[0]
        molecule_area = "@<TRIPOS>MOLECULE\n" + molecule_area
        atom_area = mol2.split('@<TRIPOS>ATOM\n')[1].split('@<TRIPOS>')[0]
        atoms = atom_area.split('\n')
        #print(atoms)
        del atoms[-1]
        new_atom_area = "@<TRIPOS>ATOM"
        for l in atoms:
            cols = l.split()
            coords = np.array([float(cols[2]), float(cols[3]), float(cols[4]), 1])
                # Umeyama Rt matrix [x, y, z, 1]
            matrix = np.array(matrix_)
            trans_coords = np.matmul(matrix, coords)
            #print(trans_coords, coords)
            new_atom_area += ("\n{:>7} {:<8} {:>9.4f} {:>9.4f} {:>9.4f} "
                              "{:<5} {:>5} {:<8} {:>9}".format(cols[0],
                                                     cols[1],
                                                     trans_coords[0],
                                                     trans_coords[1],
                                                     trans_coords[2],
                                                     cols[5],
                                                     cols[6],
                                                     cols[7],
                                                     cols[8]
                                                    ))
        new_atom_area += "\n"
        final_area = mol2.split('@<TRIPOS>BOND\n')[1]
        final_area = "@<TRIPOS>BOND\n" + final_area

    if ofile_[-5:] != '.mol2':
            ofile_ += '.mol2'
    basename = os.path.basename(ofile_)
    name = os.path.splitext(basename)[0]

    header = ""
    header += "# Modified by ProCare\n"
    header += "# Modification time: {}\n".format(
                            strftime("%a %d %b %Y %H:%M:%S", localtime()))
    header += "# Name: {}.mol2\n\n".format(name)

    with open(ofile_, 'w') as of:
        of.write('{}{}{}{}'.format(header, molecule_area, new_atom_area, final_area))

    print('output to {}'.format(ofile_))

if __name__ == '__main__':

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--fileprocare', type=str, required=True,
                help='procare matrix file')
    parser.add_argument('-l', '--line', type=int, required=True,
                help='line number where to extract matrix components. Starts with 0 = header')
    parser.add_argument('-a', '--appliedtomol2', type=str, required=True, nargs='+',
                help='mol2 file to applied transformation')
    parser.add_argument('--prefix', type=str, required=False,
                help='prefix to output files')
    args = parser.parse_args()

    matrix = xtract_matrix(args.fileprocare, args.line)
    for mol2 in args.appliedtomol2:
        filename = os.path.basename(mol2)
        prefix = 'rot_'
        if args.prefix is not None:
            prefix = args.prefix
        ofile = '{}_{}'.format(prefix, filename)
        transform(mol2, matrix, ofile)


import pygame, sys, random, time, math
from pygame.locals import *
from Sound_assets import *

# colour   R    G    B

WHITE  = (255, 255, 255)
BLACK  = (  0,   0,   0)
RED    = (255,   0,   0)
GREEN  = (  0, 255,   0)
ORANGE = (255, 128,   0)
YELLOW = (255, 255,   0)
BLUE   = (0  ,   0, 255)

list_bullets=[]
list_asteroids=[]

pygame.init()

SCORE = 0

text_score = 'Score : ' + str(SCORE)
loss_text = "You Lose"
win_text = "You Win"
font_Score = pygame.font.Font('freesansbold.ttf', 20)
font_END = pygame.font.SysFont("Impact", 48)
win_surf = font_END.render(win_text, True, WHITE, BLACK)
loss_surf = font_END.render(loss_text, True, WHITE, BLACK)

score_Surf = font_Score.render(text_score, True, WHITE, BLACK)
textRectObj = score_Surf.get_rect()
textRectObj.topleft = (10, 10)

class Ship:
    "Ship Object"
    def __init__(self, x, y, speed):
        self.pos_x = (x*.5)
        self.pos_y = (y*0.85)
        self.vel = speed

    def update_pos(self, direction):
        if direction == "left":
            self.pos_x-=self.vel
        if direction == "right":
            self.pos_x+=self.vel

    def display(self, x, y):
        pygame.draw.polygon(DISPLAYSURF,WHITE, ((self.pos_x, self.pos_y), (self.pos_x -  x//60, self.pos_y + y//40), (self.pos_x, self.pos_y + y//60), (self.pos_x + x//60,  self.pos_y + y//40)))

class Bullet:
    "Bullet Object"

    def __init__(self, pos_x, pos_y, radius=1):
        self.pos_x = pos_x
        self.pos_y = pos_y
        self.vel = y/100
        self.radius = radius
        play_sound(laser_fire)

    def update_pos(self):
        self.pos_y -= self.vel

def gen_bullet(pos_x,pos_y,r=1):
    list_bullets.append(Bullet(pos_x, pos_y, r))

def del_bullet(list_bullets):
    for bullet_i in list_bullets:
        if bullet_i.pos_y<=0:
            list_bullets.remove(bullet_i)

def bullet_disp():
    """ Print on the screen the asteroids """
    for bullet_i in range(len(list_bullets)):
        list_bullets[bullet_i].update_pos()
        x_coor = int(list_bullets[bullet_i].pos_x)
        y_coor = int(list_bullets[bullet_i].pos_y)
        r = list_bullets[bullet_i].radius
        pygame.draw.circle(DISPLAYSURF, WHITE, (x_coor,y_coor), r)

class Asteroid:
    """ Asteroid object """

    def __init__(self, size, vel, position_x, position_y = 0.0):
        """ Define attributes """

        self.pos_x = position_x
        self.pos_y = position_y

        self.vect_x = 0.0
        self.vect_y = vel * 2.0

        self.radius_asteroid = 3 + 2*size
        self.width = size

        self.life = size

    def update_pos(self, d_time):
        """ Update the position with the vector coordonate """

        self.pos_x += self.vect_x * d_time
        self.pos_y += self.vect_y * d_time

def asteroid_gen():
    """ Generate one asteroid """

    nb_of_object = random.randint(0,4)
    list_quarter = [[50,180],[210,340],[360,490],[520,650]]

    for obj_i in range(nb_of_object):
        #- - - - - - - - - - - - - -#
        #way to avoid any troubles with asteroids to much close#
        size = random.randint(1,4)
        quarter = random.choice(list_quarter)
        list_quarter.remove(quarter)
        #- - - - - - - - - - - - - -#
        x = random.randint(quarter[0],quarter[1])
        s = (random.random()*3) + 14.0
        aster = Asteroid(size, s, x)

        list_asteroids.append(aster)

    return nb_of_object

def collision(list_bullets, list_asteroids, SCORE):
    """ Loops through all asteroids and bullets between the two list and checks if any bullet lies within the range of an asteroid"""
    hits = 0
    for bullet_i in list_bullets:
        for aster_i in list_asteroids:
            if (bullet_i.pos_x > aster_i.pos_x-aster_i.radius_asteroid*1.1)and(bullet_i.pos_x < aster_i.pos_x+aster_i.radius_asteroid*1.1):
                if (bullet_i.pos_y > aster_i.pos_y-aster_i.radius_asteroid*1.1)and(bullet_i.pos_y < aster_i.pos_y+aster_i.radius_asteroid*1.1):

                    play_sound(aster_damage)
                    list_bullets.remove(bullet_i)
                    aster_i.life-=1
                    aster_i.radius_asteroid-=2
                    aster_i.width-=1
                    hits += 1
                    SCORE = update_score('hit', SCORE)

                if aster_i.life == 0:
                    play_sound(asteroid_breaks)
                    list_asteroids.remove(aster_i)
    return hits, SCORE

############################################## BOSS LIFE

def boss_collision(list_bullets, boss_x, boss_y):
    boss_damage = 0
    for bullet_i in list_bullets:
        if (bullet_i.pos_x > boss_x -30) and (bullet_i.pos_x < boss_x +30):
            if (bullet_i.pos_y > boss_y-30)and(bullet_i.pos_y < boss_y+30):
                list_bullets.remove(bullet_i)
                boss_damage += 1
    return boss_damage

def boss_life_tracker(total_boss_life, boss_hit, boss_x, boss_y):
        boss_life_length = total_boss_life -(boss_hit*2)
        if boss_life_length >= 0:
            COLOR = BLACK
            if boss_life_length > 0.75*total_boss_life:
                COLOR = GREEN
            elif boss_life_length > 0.5*total_boss_life:
                COLOR = ORANGE
            elif boss_life_length > 0*total_boss_life:
                COLOR = RED
            pygame.draw.rect(DISPLAYSURF,COLOR,(boss_x-x//35,boss_y+y//30,boss_life_length,y//80)) #draws health bar
        else:
            DISPLAYSURF.fill(GREEN) #END SCREEN - Remove Green Later

##################################### GROUND COLLISIONS
def ground_collision(list_asteroids, score):
    damage = 0
    for aster_i in list_asteroids:
        if (aster_i.pos_y >= player.pos_y+y // 21):
            damage += 1
            list_asteroids.remove(aster_i)
            score = update_score('hurt', score)
            play_sound(base_damage)

            lose_life = True
        else:
            lose_life = False

    return damage, score
######################################

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

def asteroid_disp():
    """ Print on the screen the asteroids """

    for aster_i in range(len(list_asteroids)):
        x = int(list_asteroids[aster_i].pos_x)
        y = int(list_asteroids[aster_i].pos_y)
        r = list_asteroids[aster_i].radius_asteroid
        w = list_asteroids[aster_i].width
        pygame.draw.circle(DISPLAYSURF, WHITE, (x, y), r, w)

##def destroy_asteroids(list_aster, ship_pos_y):
##    """ Will remove the asteroids under the ship """
##
##    list_remove = []
##    for aster in list_aster:
##        if aster.pos_y >= ship_pos_y:
##            list_remove.append(aster)
##    for aster in list_remove:
##        list_aster.remove(aster)

class Boss:
    """ Boss Asteroid """

    def __init__(self, SW, SH):
        # Begining stats : positions
        self.radius = 30
        self.width = int(self.radius * 0.15)

        self.min_x = - self.radius
        self.max_x = SW + self.radius
        self.start_y = 0.285 * SH

        self.vel_x = 1/1200 * SH

        # Define position
        self.pos_x = self.min_x
        self.pos_y = self.start_y

        # Life point stats
        self.alive = True
        self.lifePoints = 20

        # Behaviour stats
        self.rest = False
        self.phase = 'right'

    def trajectory(self, x, SW, SH):
        y = (0.76 * SH) / (SW ** 2) * (x ** 2) - (0.76 * SH * x) / SW + 0.285 * SH
        return y

    def update_pos(self, SW, SH):
        #for boss from left to right
        if self.phase == 'right':
            self.pos_x += self.vel_x
            self.pos_y = self.trajectory(self.pos_x, SW, SH)
            if self.pos_x >= self.max_x:
                self.phase = 'left'
                self.rest = True

                self.pos_x = self.max_x
                self.pos_y = self.start_y

        #for boss from right to left
        elif self.phase == 'left':
            self.pos_x -= self.vel_x
            self.pos_y = self.trajectory(self.pos_x, SW, SH)
            if self.pos_x <= self.min_x:
                self.phase = 'right'
                self.rest = True

                self.pos_x = self.min_x
                self.pos_y = self.start_y

def boss_disp():
    """ Print on the screen the boss """

    x = int(BOSS.pos_x)
    y = int(BOSS.pos_y)
    r = BOSS.radius
    w = BOSS.width
    pygame.draw.circle(DISPLAYSURF, WHITE, (x,y), r, w)
    return x, y

def in_zone():
    """ Check if BOSS is in the correct zone to create a child
    return True if yes, False otherwise """

    return (BOSS.pos_x < (0.938*x)) and (BOSS.pos_x > (0.071*y))

def boss_child_gen():
    """ Generate 1 asteroid at the x of BOSS """

    speed = (random.random()*3) + 14.0
    size  = (random.randint(1,4))
    aster = Asteroid(size, speed, BOSS.pos_x - 10, BOSS.pos_y + 10)

    list_asteroids.append(aster)

    return 1

def end_of_game():
    """ Last screen with :
    - score
    - time spent on game
    - option to go back to menu """
    if life_length == 0:
        DISPLAYSURF.fill(BLACK)
        DISPLAYSURF.blit(loss_surf, (((x - loss_surf.get_width())//2), (y - loss_surf.get_height())//2))
        # DISPLAYSURF.blit(Sco)
        pygame.display.update()
        time.sleep(10)
        pygame.quit()
        sys.exit()
        # print loss screen
    elif not BOSS.alive:
        DISPLAYSURF.fill(BLACK)
        DISPLAYSURF.blit(win_surf, (((x - win_surf.get_width()) // 2), (y - win_surf.get_height()) // 2))
        pygame.display.update()
        time.sleep(10)
        pygame.quit()
        sys.exit()
        # print win screen
    DISPLAYSURF.fill(BLACK)

def aim_pu():
    z1 = player.pos_x
    z2 = player.pos_y
    for z in range(y):
        if z % 2 == 0:
            pygame.draw.line(DISPLAYSURF, RED, (z1, z2), (z1, z2-z))
        z2 = z2 - z

def laser_power_up(score):
    z1 = player.pos_x
    z2 = player.pos_y
    z3 = player.vel
    player.pos_x = x
    player.vel = x // 200

    score = update_score('laser', score)

    wait = True
    while player.pos_x > 0:
        DISPLAYSURF.fill(BLACK)
        player.update_pos("left")
        pygame.draw.line(DISPLAYSURF,RED,(player.pos_x, player.pos_y), (player.pos_x, 0), x // 20)
        player.display(x, y)
        pygame.draw.polygon(DISPLAYSURF, RED, ((0, player.pos_y + y // 20), (x, player.pos_y + y // 20), (x, y), (0, y)))
        asteroid_disp()
        pygame.display.update()
        if wait:
            time.sleep(0.5)
        wait=False
        fpsClock.tick(FPS)
        play_sound(super_laser_fire)
        for aster_i in list_asteroids:
            if (aster_i.pos_x < player.pos_x + x // 60) and (aster_i.pos_x > player.pos_x - x // 60) and(aster_i.pos_y < player.pos_y):
                print("aster removed")
                list_asteroids.remove(aster_i)
                play_sound(asteroid_breaks)
    player.pos_x = z1
    player.pos_y = z2
    player.vel = z3
    laser_available = False

    return score

def update_score(phase, SCORE):
    """ Update score """
    if phase == 'sec':
        SCORE += 50/120
    elif phase == 'hit':
        SCORE += 250
    elif phase == 'hurt':
        SCORE -= 1000
    elif phase == 'laser':
        SCORE *= (1-0.2)

    if SCORE < 0:
        SCORE = 0

    return SCORE

###################################################################################################
FPS = 60 # frames per second setting
fpsClock = pygame.time.Clock()

x = 700
y = 700
#x sets display width and y sets height

BOSS = Boss(x, y)
WAVE, nb_obj = 0, 0 #initialise WAVE and nb_obj (the number of objects [asteroids] per WAVE)
time_sec = 0.0
end = False

pygame.display.set_caption('Asteroids')
DISPLAYSURF = pygame.display.set_mode((x, y))

DISPLAYSURF.fill(BLACK)
#draws background

speed = x // 400

player = Ship(x, y, speed)##creates player
scope = False
lose_life = True
successful_hit = 0
ground_hit = 0
boss_hit = 0
bar_length = 0
total_boss_life = 100
total_life = 100

bg_music()
######################################################################################
while True:
    text_score = 'Score: ' + str(int(SCORE))
    score_Surf = font_Score.render(text_score, True, WHITE, BLACK)
    textRectObj = score_Surf.get_rect()
    textRectObj.topleft = (10, 10)

    DISPLAYSURF.fill(BLACK)
    DISPLAYSURF.blit(score_Surf, textRectObj)

    player.vel = speed
    player.display(x, y)##draws player

    #Health Bar Depletion
    life_length = total_life - (ground_hit * 10)
    if life_length > 0:
        if life_length > 0.75 * total_life:
            COLOR = GREEN
        elif life_length > 0.5 * total_life:
            COLOR = ORANGE
        elif life_length > 0 * total_life:
            COLOR = RED
        pygame.draw.rect(DISPLAYSURF, COLOR, (player.pos_x - x // 35, player.pos_y + y // 35, life_length, y // 80)) #draws health bar
    else:

        ## WIN OR LOSS SCREEN ##
        end_of_game()

    pygame.draw.polygon(DISPLAYSURF, RED, ((0,player.pos_y + y // 20), (x,player.pos_y + y // 20), (x, y),(0, y)))#draws base

    if scope:
        aim_pu()

    if player.pos_x <= 0:
        player.pos_x = x-1
    if player.pos_x >= x:
        player.pos_x = 1
    if player.pos_y <= 0:
        player.pos_y = y-1
    if player.pos_y >= y:
        player.pos_y = 1

    SCORE = update_score('sec', SCORE)

    hits, SCORE = collision(list_bullets,list_asteroids, SCORE)##checks for collisions
    successful_hit += hits

    gr_hit, SCORE = ground_collision(list_asteroids, SCORE) ## checks for ground collisions
    ground_hit += gr_hit

    del_bullet(list_bullets)##deletes stray bullets
    bullet_disp()##displays bullets
    asteroid_disp()##displays asteroids
    boss_disp()##displays boss
    boss_x, boss_y = boss_disp()

    boss_hit += boss_collision(list_bullets,boss_x,boss_y)## checks for an attack on boss

    key_i = pygame.key.get_pressed()##returns a list storing true if a key is pressed and false if not pressed for all keys
    if key_i[305] or key_i[306]:##305, 306 are the index for control key L & R
        player.vel = speed * 3

##    if key_i[32]:##32 is the index for space
##        gen_bullet(player.pos_x,player.pos_y)

    if key_i[275]:##275 is index for right key
        player.update_pos("right")

    if key_i[276]:##276 is the index for left key
        player.update_pos("left")

    for event in pygame.event.get():

        if event.type == KEYDOWN:
            if event.key == K_SPACE:
                if len(list_bullets) <= 4:
                    gen_bullet(player.pos_x, player.pos_y)

            if event.key == K_l:
                SCORE = laser_power_up(SCORE)

            if event.key == K_s:
                scope = True

            if event.key == K_a:
                scope = False

        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    if WAVE < 3:
    # waves 1 to 5
        if nb_obj < (WAVE * 5+5):
            if time_sec >= (5-WAVE):
                nb_obj += asteroid_gen()
                time_sec = 0.0
        else:
            if len(list_asteroids) == 0:
                WAVE += 1
                nb_obj = 0
                time_sec = 0.0

    elif BOSS.alive: #implicit WAVE == 5
    # waves 6 with BOSS
        if not BOSS.rest:
            BOSS.update_pos(x, y)
            boss_life_tracker(total_boss_life, boss_hit, boss_x,boss_y)
            if time_sec >= 5 and in_zone():
                list_ = [1, 0, 0, 0, 0]
                if random.choice(list_):
                    boss_child_gen()
                #time_sec = 0.0
        #if nb_obj < 10:
        if time_sec >= 5:
            nb_obj += asteroid_gen()
            time_sec = 0.0
        #else:
            # if len(list_asteroids) == 0:
            #     nb_obj = 0
            #     time_sec = 0.0
            #     BOSS.rest = False
    else:
    # after wave 6 : stop game
        end_of_game()

    for aster_i in range(len(list_asteroids)):
        list_asteroids[aster_i].update_pos(1 / 60)

##    SCORE = destroy_asteroids(list_asteroids, player.pos_y+y//20, SCORE)
    time_sec += 1 / 60

    if end:
        end_of_game()

    pygame.display.update()
    fpsClock.tick(FPS)


import pygame, sys, os, random
from pygame.locals import*

pygame.init()
all_fonts = pygame.font.get_fonts()

BLACK = (0, 0, 0)
GREY = (200, 200, 200)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
ORANGE = (255,97,3)

class Button:
    def __init__(self, txt, location, action, bg=BLACK, fg=WHITE, size=(145, 30), font_name="timesnewroman", font_size=20):
        self.color = bg  # the static (normal) color
        self.bg = bg  # actual background color, can change on mouseover
        self.fg = fg  # text color
        self.size = size

        self.font = pygame.font.SysFont(font_name, font_size)
        self.font.set_bold(1)
        self.txt = txt
        self.txt_surf = self.font.render(self.txt, 1, self.fg)
        self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])

        self.surface = pygame.surface.Surface(size)
        self.rect = self.surface.get_rect(center=location)

        self.call_back_ = action

    def draw(self):
        self.mouseover()

        self.surface.fill(self.bg)
        self.surface.blit(self.txt_surf, self.txt_rect)
        screen.blit(self.surface, self.rect)

    def mouseover(self):
        self.bg = self.color
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            self.bg = GREY  # mouseover color

    def call_back(self):
        self.call_back_()

def run_single():
    print("SINGLE PLAYER")

def run_ai():
    print("AI FUNCTION")

def mousebuttondown():
    pos = pygame.mouse.get_pos()
    for button in buttons:
        if button.rect.collidepoint(pos):
            button.call_back()

def text_to_screen(text, xpos, ypos, color, size=70):
    c = color
    font = pygame.font.SysFont('timesnewroman', size)
    font.set_bold(1)
    text = str(text)
    text = font.render(text, True, c)
    screen.blit(text, (xpos, ypos))

def HUD(surface, fuel, lives, score, bullets=0, powerup=['t','t'], poweruptime=[70,50]):
    global WHITE, RED, BLACK

    if fuel < 0:
        length = 0
    else:
        length = 200*(fuel/100)

    font = pygame.font.SysFont('timesnewroman', 20)
    font.set_bold(1)

    text = ['E', '1/2', 'F']

    empty = font.render(text[0], True, BLACK)
    divide = font.render(text[1], True, BLACK)
    full = font.render(text[2], True, BLACK)

    xstart = 60
    ystart = 500
    fuel_full = 230
    fuel_empt = 60

    # assume fuel_start = 100
    location = 230 - (100-fuel)*(fuel_full-fuel_empt)/100
    # original box
    pygame.draw.rect(surface, WHITE, (50, 500, 200, 40))
    # fuel line
    pygame.draw.rect(surface, RED, (location, 500, 10, 40))
    # outside edge
    pygame.draw.rect(surface, BLACK, (50, 500, 200, 40), 5)
    # indicator lines
    pygame.draw.rect(surface, BLACK, (xstart, 500, 10, 10))
    pygame.draw.rect(surface, BLACK, (230, 500, 10, 10))
    pygame.draw.rect(surface, BLACK, ((50+230)/2, 500, 10, 10))
    # indicator text
    surface.blit(empty, (60, 510))
    surface.blit(divide, ((50+230)/2-10, 510))
    surface.blit(full, (230, 510))

    # lives display
    i = 0
    xpos_img = 210
    while i < lives:
        i += 1
        xpos_img += 50
        img = pygame.image.load("plane2.png")
        surface.blit(img, (xpos_img, 500))

    score_txt = "SCORE: " + str(score)
    font2 = pygame.font.SysFont('timesnewroman', 20)
    font2.set_bold(1)
    score_txt = font2.render(score_txt, True, BLACK)
    surface.blit(score_txt, (50, 475))

    # powerups
    xpos_powerup = xpos_img
    if len(powerup) > 0:
        for i in range(len(powerup)):
            xpos_powerup += 50
            # img = pygame.image.load(os.path.relpath("Plane1.png"))
            # win.blit(self.img, (self.rect.x, self.rect.y))

            pygame.draw.rect(surface, WHITE, (xpos_powerup, 500, 30, 30))
            pygame.draw.rect(surface, BLACK, (xpos_powerup, 500, 30, 30), 2)

            timepos = poweruptime[i]/100 * 30
            pygame.draw.rect(surface, WHITE, (xpos_powerup, 530, 30, 10))
            pygame.draw.rect(surface, RED, (xpos_powerup, 530, timepos, 10))
            pygame.draw.rect(surface, BLACK, (xpos_powerup, 530, 30, 10), 2)

screen = pygame.display.set_mode((600, 600))

button_01 = Button("Single Player", (100, 100), run_single)
button_02 = Button("AI Test", (100, 140), run_ai)

def show_high_scores(surface):
    high_score = ['H','I','G','H',' ', 'S','C','O','R','E',':']

    start_pos_x = 10
    start_pos_y = 155
    '''
    for i in range(len(high_score)):
        rand_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        start_pos_x += 18
        text_to_screen(high_score[i], start_pos_x, start_pos_y, rand_color, size=30)
    '''
    rand_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    text_to_screen("HIGH SCORES", 30, start_pos_y, rand_color, size=30)

    high_scores = open("high scores", "r")
    lines = high_scores.read().split('\n')

    pygame.draw.rect(surface, WHITE, (30, 190, 145, 200))
    pygame.draw.rect(surface, BLACK, (30, 190, 145, 200), 3)

    y_pos = start_pos_y+15
    for line in lines:
        y_pos += 20
        text_to_screen(str(line), 35, y_pos, BLACK, size=20)

buttons = [button_01, button_02]

fuel = 100

while True:
    image = pygame.image.load("backround.png")
    screen.blit(image, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mousebuttondown()
    for button in buttons:
        button.draw()

    text_to_screen("RIVER RUN", 30, 25, BLACK, size=60)
    text_to_screen("RIVER RUN", 35, 20, ORANGE, size=60)
    show_high_scores(screen)
    HUD(screen, fuel, 2, 100000)
    fuel -= .1
    if fuel < 0:
        fuel = 100
    pygame.display.flip()
    pygame.time.wait(40)


many_rooms = int(input())

room_counter = 0
free_chairs_counter = 0
negative = 0

for oom in range(many_rooms):
    command = input()
    room_counter += 1
    chairs, people = command.split()
    chairs = len(chairs)
    people = int(people)

    if chairs >= people:
        free_chairs = chairs - people
        free_chairs_counter += free_chairs
    else:
        need_chairs = people - chairs
        negative +=1
        print(f'{need_chairs} more chairs needed in room {room_counter}')

if negative ==0:
    print(f"Game On, {free_chairs_counter} free chairs left")


import numpy as np
import json
import pickle
import math
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Activation, Convolution2D, Flatten, Lambda, Dropout, Lambda, ELU
from keras.optimizers import Adam

# Load the data
data = {}
with open('data/driving_data.p', 'rb') as f:
    data = pickle.load(f)

# Split data into training and validation
X_train, X_val, y_train, y_val = train_test_split(data['features'], data['labels'], random_state=0, test_size=0.33)

# normalize: mean zero and range -0.5 to 0.5
print('Normalizing data')
def normalize_data(x):
    x = x.astype('float32')
    x = x / 255 - 0.5
    return x
# will use Lambda instead
X_train = normalize_data(X_train)
X_val = normalize_data(X_val)

# model
img_shape = (160, 320, 3)

model = Sequential()
model.add(Lambda(lambda x: x/127.5 - 1., input_shape=img_shape, output_shape=img_shape))
model.add(Convolution2D(16, 8, 8, subsample=(4, 4), border_mode="same"))
model.add(ELU())
model.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode="same"))
model.add(ELU())
model.add(Convolution2D(64, 5, 5, subsample=(2, 2), border_mode="same"))
model.add(Flatten())
model.add(Dropout(.2))
model.add(ELU())
model.add(Dense(512))
model.add(Dropout(.5))
model.add(ELU())
model.add(Dense(1))
model.compile(optimizer="adam", loss="mse")
model.fit(X_train, y_train, batch_size=100, nb_epoch=100,validation_data=(X_val, y_val), shuffle=True)

# save model
print('Saving Model Weights!!')
model.save_weights('model.h5')
with open('model.json','w') as f:
    json.dump(model.to_json(),f,ensure_ascii=False)


"""
Plot comparison of turbine models
"""
import sys
libpath = 'C:\\Users\\jrinker\\Documents\\GitHub\\dissertation'
if (libpath not in sys.path): sys.path.append(libpath)

import JR_Library.main as jr
import numpy as np
import os
import matplotlib.pyplot as plt

# set directory and turbine name
#turb_dir,TName = 'C:\\Users\\jrinker\\Documents\\GitHub' + \
#        '\\dissertation\\FAST_models\\verification\\WP0.75A08V00','WP0.75A08V00'
turb_dir,TName = 'C:\\Users\\jrinker\\Documents\\GitHub\\' + \
    'dissertation\\FAST_models\\FAST7\\WP0.75A08V00','WP0.75A08V00'
fileID,fignum = '42331',1
#fileID,fignum = '93013',2

#PlotFields = ['Time','WindVxi','RotSpeed','GenPwr',
#              'BldPitch1','TSR','GenTq','TTDspFA','OoPDefl1']
PlotFields = ['Time','WindVxi','RotSpeed',
              'BldPitch1','GenTq','TTDspFA','OoPDefl1']

# initialize figure
fig = plt.figure(fignum,figsize=(6.5,10))
plt.clf()

# load fast file
FASTfname = TName+'_'+fileID
FASTfpath = os.path.join(turb_dir,FASTfname+'.out')
FAST = jr.ReadFASTFile(FASTfpath)

# plot results
t = FAST['Data'][:,FAST['Fields'].index('Time')]

tplot = [150,155]
mask = (t >= tplot[0]) & (t <= tplot[1])

for i_plot in range(len(PlotFields)-1):
    PlotField = PlotFields[i_plot+1]

    ax = fig.add_subplot(len(PlotFields)-1,1,i_plot+1)

    if PlotField == 'WindVxi':
        ax.plot(t[mask],11*np.ones(t[mask].shape),'k:')

    y = FAST['Data'][:,FAST['Fields'].index(PlotField)]

    ax.plot(t[mask],y[mask])
    ax.set_title(PlotFields[i_plot+1])

    plt.locator_params(axis='y',nbins=4)
    #        if i_plot < len(PlotFields)-2:
    #            ax.set_ylim([np.mean(y)*0.95,np.mean(y)*1.05])
#    ax.set_xlim([150,160])
#    ax.margins(y=.1)

plt.tight_layout()
fig.suptitle(FASTfname,x=0.01,y=0.99,fontsize='large',ha='left')


import numpy as np
import matplotlib.pyplot as pl

velo_accel = 4
velo_maxspeed = 25
human_accel = 2
human_maxspeed = 6

d = 10

dt = 1e-6

class Entity:
	def __init__(self, pos, a, v_max):
		self.x = pos[0]
		self.y = pos[1]
		self.a = a
		self.vmax = v_max

def r_full(t, a, v_max):
	return v_max*(v_max*(np.exp(-a*t/v_max) - 1)/a + t)

def r_accel(t, a, v_max):
	return 0.5*a*t**2

def r_vmax(t, a, v_max):
	return v_max*t

def mid_time(r, human, velo):
	t_up = d*velo_maxspeed/velo_accel
	t_down = 0
	while np.abs(t_up-t_down)>dt:
		t_mid = 0.5*(t_up+t_down)
		m = r(t_mid, velo.a, velo.vmax) - np.sqrt(velo.x**2+velo.y**2)
		if m>0:
			t_up = t_mid
		elif m<0:
			t_down = t_mid
		else:
			break
	return t_mid

def first_last_time(r, human, velo):
	t_thresh = mid_time(r, human, velo)

	t_down = 0
	t_up = t_thresh
	while np.abs(t_up-t_down)>dt:
		t_mid = 0.5*(t_up+t_down)
		r_Hsq = r(t_mid, human.a, human.vmax)**2
		r_Asq = r(t_mid, velo.a, velo.vmax)**2
		distsq = velo.x**2+velo.y**2
		m = 4*r_Hsq*distsq - (distsq - r_Asq + r_Hsq)**2
		if m>0:
			t_up = t_mid
		elif m<0:
			t_down = t_mid
		else:
			t_up = t_mid
			break
	t_first = t_up

	t_down = t_thresh
	t_up = d*velo_maxspeed/velo_accel
	while np.abs(t_up-t_down)>dt:
		t_mid = 0.5*(t_up+t_down)
		r_Hsq = r(t_mid, human.a, human.vmax)**2
		r_Asq = r(t_mid, velo.a, velo.vmax)**2
		distsq = velo.x**2+velo.y**2
		m = 4*r_Hsq*distsq - (distsq - r_Asq + r_Hsq)**2
		if m>0:
			t_down = t_mid
		elif m<0:
			t_up = t_mid
		else:
			t_down = t_mid
			break
	t_last = t_down

	return t_first, t_last

def x_pos(t, r, human, velo):
	r_Hsq = r(t, human.a, human.vmax)**2
	r_Asq = r(t, velo.a, velo.vmax)**2
	distsq = velo.x**2+velo.y**2
	D = r_Asq - r_Hsq - distsq
	x_1 = (-D*velo.x + velo.y*np.sqrt(4*distsq*r_Hsq - D**2))/(2*distsq)
	x_2 = (-D*velo.x - velo.y*np.sqrt(4*r_Hsq*distsq - D**2))/(2*distsq)
	return x_1, x_2

def y_pos(t, r, human, velo):
	r_Hsq = r(t, human.a, human.vmax)**2
	r_Asq = r(t, velo.a, velo.vmax)**2
	distsq = velo.x**2+velo.y**2
	D = r_Asq - r_Hsq - distsq
	y_1 = (-velo.y*D + velo.x*np.sqrt(4*distsq*r_Hsq - D**2))/(2*distsq)
	y_2 = (-velo.y*D - velo.x*np.sqrt(4*distsq*r_Hsq - D**2))/(2*distsq)
	return y_1, y_2

def plot(r, title):
	human = Entity((0,0), human_accel, human_maxspeed)
	pos_top = (0, d/np.sqrt(3))
	pos_left = (-0.5*d, -0.5*d/np.sqrt(3))
	pos_right = (0.5*d, -0.5*d/np.sqrt(3))
	velos = [Entity(pos_top, velo_accel/2.5, velo_maxspeed/2.5),
				Entity(pos_left, velo_accel, velo_maxspeed),
				Entity(pos_right, velo_accel, velo_maxspeed)]
	fig = pl.figure()
	ax = pl.subplot(111)
	M_x = []
	M_y = []
	c = []
	colors = ["red", "green", "blue"]
	for i,v in enumerate(velos):
		t_b, t_e = first_last_time(r, human, v)
		first_contact = -np.sqrt(x_pos(t_b, r, human, v)[0]**2 + y_pos(t_b, r, human, v)[0]**2)
		last_contact = np.sqrt(x_pos(t_e, r, human, v)[0]**2 + y_pos(t_e, r, human, v)[0]**2)
		for t in np.linspace(t_b, t_e, 1e4):
			r_Hsq = r(t, human.a, human.vmax)**2
			x1, x2 = x_pos(t, r, human, v)
			y1, y2 = y_pos(t, r, human, v)
			if np.abs(r_Hsq - x1**2 - y1**2)<dt:
				M_x.append(x1)
				M_y.append(y1)
				c.append(colors[i])
				M_x.append(x2)
				M_y.append(y2)
				c.append(colors[i])
			elif np.abs(r_Hsq - x1**2 - y2**2)<dt:
				M_x.append(x1)
				M_y.append(y2)
				c.append(colors[i])
				M_x.append(x2)
				M_y.append(y1)
				c.append(colors[i])
			else:
				print("Failure to find proper point")
	pl.scatter(M_x, M_y, color=c, edgecolor="none")
	pl.scatter([v.x for v in velos], [v.y for v in velos], color=colors, marker="*")
	pl.scatter([0], [0], color="black", marker="x")

	ax.set_aspect("equal", "datalim")
	pl.title(title)
	pl.savefig("imp-{}.png".format(title))
	pl.clf()

plot(r_full, "Full Model")
plot(r_accel, "Accel Model")
plot(r_vmax, "Vmax Model")


"""
Helper methods to display genomic sequences.
"""
from qtools.lib.helpers.html import recursive_class_tag
from qtools.lib.helpers.numeric import *

__all__ = ['amplicon_length_vdisp','primer_tm_vdisp','probe_tm_vdisp',
           'intra_primer_delta_tm_vdisp','primer_probe_delta_tm_vdisp',
           'oligo_dg_vdisp','amplicon_dg_vdisp','gc_content_vdisp']

OK = 'validation_ok'
WARN = 'validation_warn'
UHOH = 'validation_uhoh'
UNKNOWN = 'validation_unknown'

def __merge_class_attrs(klass, **attrs):
	if 'class_' in attrs:
		attrs['class_'] = "%s %s" % (klass, attrs['class_'])
	else:
		attrs['class_'] = klass
	# way to return keyword args?
	return attrs

def amplicon_length_vdisp(length=None, *tags, **attrs):
	if not length:
		klass = UNKNOWN
	elif length < 120:
		klass = OK
	elif length >= 120 and length < 150:
		klass = WARN
	else:
		klass = UHOH
	return recursive_class_tag(tags, str(length) if length else 'Unknown', **__merge_class_attrs(klass, **attrs))

def primer_tm_vdisp(tm=None, *tags, **attrs):
	if not tm:
		klass = UNKNOWN
	elif tm >= 58.95 and tm < 63.05:
		klass = OK
	elif (tm > 55 and tm < 58.95) or tm >= 63.05:
		klass = WARN
	else:
		klass = UHOH

	return recursive_class_tag(tags, sig1(tm) if tm else 'Unknown', **__merge_class_attrs(klass, **attrs))

# TODO add SNP precision
def probe_tm_vdisp(tm=None, *tags, **attrs):
	if attrs.pop('snp', False):
		max_tm = 68.05
	else:
		max_tm = 70.05
	if not tm:
		klass = UNKNOWN
	elif tm >= 64.95 and tm < max_tm:
		klass = OK
	else:
		klass = WARN
	return recursive_class_tag(tags, sig1(tm) if tm else 'Unknown', **__merge_class_attrs(klass, **attrs))

def intra_primer_delta_tm_vdisp(fp_tm=None, rp_tm=None, *tags, **attrs):
	if not fp_tm or not rp_tm:
		klass = UNKNOWN
		diff = None
	else:
		diff = abs(rp_tm-fp_tm)
		if abs(rp_tm-fp_tm) < 2:
			klass = OK
		else:
			klass = WARN
	return recursive_class_tag(tags, sig1(diff) if diff is not None else 'Unknown', **__merge_class_attrs(klass, **attrs))

def primer_probe_delta_tm_vdisp(primer_tm=None, probe_tm=None, *tags, **attrs):
	if not primer_tm or not probe_tm:
		klass = UNKNOWN
		diff = None
	else:
		diff = probe_tm-primer_tm
		if diff > 1:
			klass = OK
		elif diff > 0:
			klass = WARN
		else:
			klass = UHOH

	return recursive_class_tag(tags, sig1(diff) if diff is not None else 'Unknown', **__merge_class_attrs(klass, **attrs))

def oligo_dg_vdisp(dg=None, *tags, **attrs):
	if dg is None:
		klass = UNKNOWN
	elif dg == 0:
		klass = OK
	else:
		klass = WARN
	return recursive_class_tag(tags, sig2(dg) if dg is not None else 'Unknown', **__merge_class_attrs(klass, **attrs))

def amplicon_dg_vdisp(dg=None, *tags, **attrs):
	if dg is None:
		klass = UNKNOWN
	elif dg >= -2:
		klass = OK
	elif dg >= -4 and dg < -2:
		klass = WARN
	else:
		klass = UHOH
	return recursive_class_tag(tags, sig2(dg) if dg is not None else 'Unknown', **__merge_class_attrs(klass, **attrs))

def gc_content_vdisp(gc=None, *tags, **attrs):
	if gc is None:
		klass = UNKNOWN
	if gc >= 40 and gc <= 60:
		klass = OK
	elif (gc >= 35 and gc < 40) or (gc > 60 and gc <= 65):
		klass = WARN
	else:
		klass = UHOH
	return recursive_class_tag(tags, "%s%%" % sig0(gc) if gc is not None else 'Unknown', **__merge_class_attrs(klass, **attrs))

def max_overlap_vdisp(overlap=None, *tags, **attrs):
	"""
	Assumes output comes from max_overlap function (len, (off, off))
	"""
	if overlap is None:
		klass = UNKNOWN
	elif overlap[0] < 6:
		klass = OK
	elif overlap[0] < 8:
		klass = WARN
	else:
		klass = UHOH

	return recursive_class_tag(tags, str(overlap[0]) if overlap is not None else 'Unknown', **__merge_class_attrs(klass, **attrs))


from odoo import http
from odoo.http import request
from odoo.addons.portal.controllers.web import \
    Home as home

class ViseducatHome(home):

    @http.route()
    def web_login(self, redirect=None, *args, **kw):
        response = super(ViseducatHome, self).web_login(
            redirect=redirect, *args, **kw)
        if not redirect and request.params['login_success']:
            if request.env['res.users'].browse(request.uid).has_group(
                    'base.group_user'):
                redirect = b'/web?' + request.httprequest.query_string
            else:
                if request.env.user.is_parent:
                    redirect = '/my/child'
                else:
                    redirect = '/my/home'
            return http.redirect_with_hash(redirect)
        return response

    def _login_redirect(self, uid, redirect=None):
        if request.env.user.is_parent:
            return '/my/child'
        return '/my/home'


import os
import psutil

import numpy as np

from tensorflow.keras.preprocessing import image as keras_img
from tensorflow.keras.preprocessing.image import Iterator
from tensorflow.python.keras.utils import to_categorical
from keras_preprocessing.image.iterator import BatchFromFilesMixin

class DataFrameIterator(BatchFromFilesMixin, Iterator):
    """Iterator capable of reading multiple images from a directory on disk and custom data
        through a dataframe.
    # Arguments
        dataframe: Pandas dataframe containing the relative paths of the
                   images in some columns and raw data in other columns
        directory: Path to the directory with images.
        image_data_generator: Instance of `ImageDataGenerator`
            to use for random transformations and normalization.
        x_col: Column or list of columns in dataframe with input data.
        y_col: Column or list of columns in dataframe with label data.
        target_size: tuple of integers, dimensions to resize input images to.
        batch_size: Integer, size of a batch.
        n_mix: Number of batches generated to produce a single transformed batch (used for mixup-type augmentations)
        shuffle: Boolean, whether to shuffle the data between epochs.
        seed: Random seed for data shuffling.
        data_format: String, one of `channels_first`, `channels_last`.
        subset: Subset of data (`"training"` or `"validation"`) if
            validation_split is set in ImageDataGenerator.
        interpolation: Interpolation method used to resample the image if the
            target size is different from that of the loaded image.
            Supported methods are "nearest", "bilinear", and "bicubic".
            If PIL version 1.1.3 or newer is installed, "lanczos" is also
            supported. If PIL version 3.4.0 or newer is installed, "box" and
            "hamming" are also supported. By default, "nearest" is used.
        dtype: tensor dtype for images
        return_ino: Boolean, whether to return information about batch as (dataframe indice, class names, image names)
        cache: None if not using cache, path to dumped dictionary in JSON format otherwise. If path doesn't exist dictionary
            will be initialized and filled.
        max_memory_used: limit of virtual memory used to save cache, from 0.0 to 1.0
        min_space_available: minimal space available in bytes
    """
    def __init__(self,
                 dataframe,
                 directory,
                 image_data_generator,
                 x_col,
                 y_col,
                 target_size=(224, 224),
                 batch_size=32,
                 n_mix=1,
                 shuffle=False,
                 seed=42,
                 interpolation='bilinear',
                 data_format='channels_last',
                 subset=None,
                 dtype='float32',
                 return_info=False,
                 cache=None,
                 max_memory_used=0.5,
                 min_space_available=500*1024*1024):

        super(DataFrameIterator, self).set_processing_attrs(image_data_generator,
                                                            target_size,
                                                            'rgb',
                                                            data_format,
                                                            save_to_dir=False,
                                                            save_prefix='',
                                                            save_format='png',
                                                            subset=subset,
                                                            interpolation=interpolation)
        assert (set((x_col, y_col))) <= set(dataframe.columns)

        self.x = dataframe[x_col].astype(str)
        self.y = dataframe[y_col]
        self.index = dataframe.index.values

        self.classes = sorted(self.y.unique())
        self.n_classes = len(self.classes)
        self.encoding = {class_name: to_categorical(class_index, num_classes=self.n_classes) \
                         for class_index, class_name in enumerate(self.classes)}

        self.num_samples = len(dataframe)
        self.directory = directory
        self.dtype = dtype

        self.return_info = return_info

        self.use_cache = cache is not None
        self.set_cache(cache)

        self.max_memory_used = max_memory_used
        self.min_space_available = min_space_available

        self.n_mix = n_mix

        super(DataFrameIterator, self).__init__(
            self.num_samples,
            batch_size,
            shuffle,
            seed)

    def set_cache(self, cache):
        if self.use_cache:
            assert isinstance(cache, dict)
            if len(cache) == 0:
                print('Set empty cache')
        self.cache = cache

    def memory_safe(self):
        mem = psutil.virtual_memory()
        return (mem.percent < self.max_memory_used * 100. and mem.available > self.min_space_available)

    def _get_image(self, filename):
        filepath = os.path.join(self.directory, filename)
        if self.use_cache and filepath in self.cache:
            img_arr = self.cache[filepath]
        else:
            img = keras_img.load_img(filepath, target_size=self.target_size, interpolation=self.interpolation)
            img_arr = keras_img.img_to_array(img)
            if self.use_cache and self.memory_safe():
                self.cache[filepath] = img_arr

        if img_arr is None:
            return None

        return img_arr.copy()

    def _transform_samples(self, x, y, image_data_generator=None):
        if image_data_generator is not None:
            seed = np.random.randint(1000000)
            params = self.image_data_generator.get_random_transform(self.target_size, seed)
            transformed_x, transformed_y = self.image_data_generator.apply_transform(x[0], params), y[0]
            #will replace three lines above with the following line:
            #transformed_x, transformed_y = self.image_data_generator.apply_transform(x, y, params)
        else:
            assert len(x) == 1
            transformed_x = x[0]
            transformed_y = y[0]
        return transformed_x, transformed_y

    def _get_batches_of_transformed_samples(self, index_arrays, image_data_generator=None):
        batch_size = len(index_arrays[0])
        batch_x = np.zeros((batch_size, self.target_size[0], self.target_size[1], 3), dtype=self.dtype)
        batch_y = np.zeros((batch_size, self.n_classes))
        for index_in_batch, index_group in enumerate(zip(*index_arrays)):
            index_group = list(index_group)
            image_group = [self._get_image(filename) for filename in self.x.iloc[index_group]]
            label_group = self.y.iloc[index_group].map(self.encoding).values
            image_arr, label = self._transform_samples(image_group, label_group, image_data_generator)
            batch_x[index_in_batch] = image_arr
            batch_y[index_in_batch] = label

        if self.return_info:
            index_array = index_arrays[0] # identify index group by its first index
            batch_info = np.stack([self.index[index_array],
                                   self.y.iloc[index_array].values,
                                   self.x.iloc[index_array].values,
                                   ]).T
            batch = (batch_x, batch_y, batch_info)
        else:
            batch = (batch_x, batch_y)
        return batch

    def next(self):
        """For python 2.x.
        # Returns
            The next batch.
        """
        with self.lock:
            index_arrays = [next(self.index_generator) for _ in range(self.n_mix)]
        # The transformation of images is not under thread lock
        # so it can be done in parallel
        return self._get_batches_of_transformed_samples(index_arrays, self.image_data_generator)

class FewShotDataFrameIterator(DataFrameIterator):
    def __init__(self,
                 dataframe,
                 directory,
                 image_data_generator,
                 query_image_data_generator,
                 n_way,
                 k_shot,
                 query_samples_per_class=None,
                 *args, **kwargs):
        super(FewShotDataFrameIterator, self).__init__(dataframe,
                                                       directory,
                                                       image_data_generator=image_data_generator,
                                                       *args, **kwargs)
        self.query_image_data_generator = query_image_data_generator
        self.n_way = n_way
        self.support_samples_per_class = k_shot
        self.query_samples_per_class = query_samples_per_class

    def next(self):
        """For python 2.x.
        # Returns
            The next batch.
        """
        with self.lock:
            sample_classes = np.random.choice(self.classes, self.n_way)
            support_index_arrays = [[] for _ in range(self.n_mix)]
            query_index_arrays = [[] for _ in range(self.n_mix)]
            for class_name in sample_classes:
                class_index = self.y[self.y==class_name].index
                support_class_multiindex = np.random.choice(
                        class_index, size=self.support_samples_per_class * self.n_mix,
                        replace=len(class_index) < self.support_samples_per_class)
                query_class_index = [index for index in class_index if not index in support_class_multiindex]
                support_class_multiindex = support_class_multiindex.reshape((self.n_mix, -1)).tolist()
                for index_in_mix, support_class_index in enumerate(support_class_multiindex):
                    if self.query_samples_per_class is not None:
                        query_size = min(self.query_samples_per_class, len(query_class_index))
                    else:
                        query_size = len(query_class_index)

                    query_class_index = np.random.choice(query_class_index, size=query_size).tolist()
                    support_index_arrays[index_in_mix] += support_class_index
                    query_index_arrays[index_in_mix] += query_class_index

        # The transformation of images is not under thread lock
        # so it can be done in parallel
        support = self._get_batches_of_transformed_samples(support_index_arrays, self.image_data_generator)
        query = self._get_batches_of_transformed_samples(query_index_arrays, self.query_image_data_generator)
        return support, query


import immlib
from collections import defaultdict

imm = immlib.Debugger()

'''
   initStatsKey()
           Value of the address that is added to the stats dictionary is a list.
           The list needs to be initialized so that it contains two int that is zero
'''
def initStatsKey(stats, oldValue):
    stats[oldValue].append(0)
    stats[oldValue].append(0)

'''
   initFuncCount()
           Value of the address that is added to the funcCount dictionary is a list.
           The list needs to be initialized so that it contains two int that is zero
'''
def initFuncCount(funcCount, funcAddr):
    funcCount[funcAddr].append(0)
    funcCount[funcAddr].append(0)

'''
   statsForAddr()
           Write to the file the statistic for a particular address
'''
def statsForAddr(statsFile, stats, key):
    #stats is a dictionary.
    #Key: address. Value: a list with two element.
    #First element contains amount of time it is true.
    #Second element contains amount of time it is false.
    statsFile.write(str(key)) #Address
    statsFile.write("\t\t")
    trueP = str((float(stats[key][0])/(stats[key][0]+stats[key][1]))*100)
    statsFile.write(trueP.split(".")[0]+"."+trueP.split(".")[1][0]) #Percentage of times it is true
    statsFile.write("\t\t")
    falseP = str((float(stats[key][1])/(stats[key][0]+stats[key][1]))*100)
    statsFile.write(falseP.split(".")[0]+"."+falseP.split(".")[1][0])#Percentage of times it is false
    statsFile.write("\n")

'''
   writeStatsHeader()
           The header for the file statsFile
'''
def writeStatsHeader(statsFile):
    statsFile.write("Branch Address")
    statsFile.write("\t")
    statsFile.write("Percent True")
    statsFile.write("\t")
    statsFile.write("Percent False")
    statsFile.write("\n")

'''
   statfForFunc()
           Write to the file the statistic for a particular address
'''
def statfForFunc(statfFile, funcCount, key):
    #stats is a dictionary.
    #Key: address. Value: a list with two element.
    #First element contains count of how many times user function is called.
    statfFile.write(str(key)) #Address
    statfFile.write("\t\t")
    statfFile.write(str(funcCount[key][0])) #Count
    statfFile.write("\n")

'''
   writeStatfHeader()
           The header for the file statfFile
'''
def writeStatfHeader(statfFile):
    statfFile.write("Function Address")
    statfFile.write("\t")
    statfFile.write("Count")
    statfFile.write("\n")

'''
   findEndAddr()
           Find the end address of program, 'cexit'
'''
def findEndAddr(imm, address):
    while(1) :
        opcode = imm.disasm(address)
        opcode_str = opcode.getDisasm().lower()

        if "cexit" in opcode_str:
            endAddr = address
            address -= 1
            break
        else :
            address += opcode.getOpSize()
    return address

'''
   findStartAddr()
           Find the start address of main function
'''
def findStartAddr(imm, base, address):
    while(address > base):
        opcode = imm.disasm(address)
        opcode_str = opcode.getDisasm().lower()

        if "call" in opcode_str:
            #callmain = address
            startAddr = int(opcode_str.split(".")[1], 16)
            break
        else:
            address -= 1
    address = imm.getCurrentAddress()
    imm.run()
    imm.run(startAddr)
    return startAddr

'''
   traceAddr()
           Trace the address line-by-line and search all of branch & CALL instruction
           1. Branch
               Compare current address and next address.
               Next, set the value whether it is true or false and write file
           2.  CALL
               Find the start address of function and write file
'''
def traceAddr(imm, address, endAddr, stats, oldValue, rawFile, funcFile, funcCount):
    prefixCall = 0
    CBIflag = 0
    stepAddr = 0
    nextAddr = 0
    while(address != endAddr):
        #Finish searching
        if(address == endAddr):
             imm.quitDebugger()

        opcode = imm.disasm(address)
        opcode_str = opcode.getDisasm().lower()
        #If PC points CALL instruction, get the start address of function
        if "call" in opcode_str:
            #Ignore superprefix section
            if(prefixCall == 0):
                name = opcode_str.split(".")[0].lower()
                prefixCall = 1
            elif name in opcode_str:
                calledAddr = opcode_str.split(".")[1].upper()
                funcFile.write(calledAddr)
                funcFile.write("\n")
                if calledAddr not in funcCount:
                    initFuncCount(funcCount, calledAddr)
                funcCount[calledAddr][0]+=1
                imm.stepIn(endAddr)
                address = imm.getCurrentAddress()

        #Ignore JMP instruction
        elif "jmp" in opcode_str:
             address = int(opcode_str.split(".")[1], 16)

        #Searching all control branch instruction
        elif ("cmp" in opcode_str) or ("test" in opcode_str):
             imm.stepOver(endAddr)
             address = imm.getCurrentAddress()
             opcode = imm.disasm(address)
             opcode_str = opcode.getDisasm()
             instruct = opcode_str.split(" ")[0]
            #If PC points to branch instruction, compare current address and next address
             if "J" in instruct:
                  stepAddr = int(opcode_str.split(".")[1], 16)
                  nextAddr = address + opcode.getOpSize()
                  CBIflag = 1
        prevAddr = address
        imm.stepOver(endAddr)
        address = imm.getCurrentAddress()

        #Determine the branch's value whether is true or false
        if(CBIflag):
             CBIflag = 0
             oldValue=hex(prevAddr).upper()
             initStatsKey(stats, oldValue)
             if(address == stepAddr):
                 rawFile.write(hex(prevAddr).upper()+":True \n")
                 stats[oldValue][0]+=1
             elif(address == nextAddr):
                 rawFile.write(hex(prevAddr).upper()+":False \n")
                 stats[oldValue][1]+=1

'''
    main()

        Step1. Using our function 'findEndAddr()' to search 'cexit' instruction.
        Step2. Using our function 'findStartAddr()' to search the begginning of the main function in executable file and run to start address.
        Step3. Using 'stepOver()' or 'stepIn()' function from start address to find conditional branch and function call instruction.
            - If we find the conditional branch instruction, check and write the value of branch instruction in file which name is 'rawFile'
              and go to next instruction by using the 'stepOver()' function.
            - If we find the function call instruction, count and write ,that how many times of function call, in file which name is 'funcFile'
              and go to next instruction by using the 'stepIn()' function.
            - Iterating this step from start address to end address.
        Step4. Creating the statistics file by using the function 'writeStatsHeader()' and 'writeStatfHeader()'.
        Step5. Closing all files and we create four files 'funcFile', 'rawFile', 'statsFile' and 'statfFile'.

        Note: The 'jmp' instruction is an unconditional jump, so we ignore that instruction in step3.

        Key Assumptions:

            Superfluous prefix appear just one time ,so all call instructions after that mean function calls.
            'Cmp' or 'test' instructions are always in front of conditional branch instructions.
            The command should be started before run state in immunity debugger.
'''
def main(args):

    #Initializing variables

    # rawFile =  controlbranch addr : boolean
    # funcFile = functionaddr
    # statsFile = percentage of true at each control branch
    # statfFile = count how many times local function is called
    rawFile = open('data.txt', 'a')
    funcFile = open('func.txt', 'a')
    statsFile = open('stats.txt', 'a')
    statfFile = open('statf.txt', 'a')
    files = [rawFile, funcFile, statsFile, statfFile]
    oldValue = ""
    funcAddr = ""
    stats = defaultdict(list)
    funcCount = defaultdict(list)
    name=imm.getDebuggedName()
    module=imm.getModule(name)
    address=module.getBaseAddress()
    base = address

    #Step 1 -- Find 'cexit' address
    address = findEndAddr(imm, address)
    endAddr = address - 1

    #Step 2 -- Find start address of main
    address = findStartAddr(imm, base, address)

    #Step 3 -- Get the branch execution and function call results
    traceAddr(imm, address, endAddr, stats, oldValue, rawFile, funcFile, funcCount)

    #Step 4 -- Create the statistics file
    writeStatsHeader(statsFile)
    writeStatfHeader(statfFile)
    for key in stats:
        statsForAddr(statsFile, stats, key)
    for key in funcCount:
        statfForFunc(statfFile, funcCount, key)
    #Close all files
    for f in files:
        f.close()

    return "Search completed!"


import controllers.notifications
from webapp.shop_dashboard.api import DashboardPlugin

class InboxDashboardPlugin(DashboardPlugin):
    def load_context(self, shop):
        notifications = controllers.notifications.get_notifications_for_shop(shop)
        return dict(notifications=notifications, shop=shop)

inbox_tab = InboxDashboardPlugin(name="inbox",
                                 display_name="Inbox",
                                 icon="archive",
                                 template="tab-inbox.html")