#****************************************************************************#
#************ LOG to Track Log to Route Plan to Waypoints - GUI *************#
#****************************************************************************#
# Copyright (c) 2016, Kristian Husum Terkildsen <krter12@student.sdu.dk> /
#                                            <kristian.h.terkildsen@gmail.com>
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#   1. Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#   2. Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#   3. Neither the name of the copyright holder nor the names of its
#      contributors may be used to endorse or promote products derived from
#      this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#****************************************************************************#

"""
2016-03-12 KHT Created first version
2016-03-13 KHT Implemented the LOG parser class
"""

import sys
import string
import Tkinter
import tkMessageBox
import tkFileDialog
from functools import partial
from L2T2R2WClass import L2T2R2W #Originally: from src.L2T2R2WClass import L2T2R2W. Somehow doesn't work now.
from AQLog import aqLogConverter #Originally: from src.AQLog import aqLogConverter. Somehow doesn't work now.

#Instantiate class
cl = L2T2R2W()

allowedChars = set(string.digits + ".")

#GUI functions:
def exitProgram():
    exitButton.flash()
    sys.exit()

def findFilename(integer):
    filename = tkFileDialog.askopenfilename(parent = root, title = "Choose a file")
    while "/" in filename:
        filename = filename.split("/", 1)[1]
        filenameClean = filename.partition(".")[0]
    if integer == 0:
        inputFilenameEntryLog.delete(0, "end")
        inputFilenameEntryLog.insert(0, filenameClean)
    elif integer == 1:
        outputFilenameEntryLog.delete(0, "end")
        outputFilenameEntryLog.insert(0, filenameClean)
    elif integer == 2:
        inputFilenameEntryTrack.delete(0, "end")
        inputFilenameEntryTrack.insert(0, filenameClean)
    elif integer == 3:
        outputFilenameEntryTrack.delete(0, "end")
        outputFilenameEntryTrack.insert(0, filenameClean)
    elif integer == 4:
        inputFilenameEntryRoute.delete(0, "end")
        inputFilenameEntryRoute.insert(0, filenameClean)
    elif integer == 5:
        outputFilenameEntryRoute.delete(0, "end")
        outputFilenameEntryRoute.insert(0, filenameClean)

def parseAll():
    inputBool = False
    epsInput = epsEntryTrack.get()
    heading = headingEntryRoute.get()
    accptInput = accptRadEntryRoute.get()
    loiterInput = loiterEntryRoute.get()
    maxHSInput = maxHoriEntryRoute.get()
    maxVSInput = maxVertEntryRoute.get()

    if inputFilenameEntryLog.get() == "":
        tkMessageBox.showerror("Error", "Missing log input filename")
    elif radioVarLog.get() != 1 and radioVarLog.get() != 2 and radioVarLog.get() != 3:
        tkMessageBox.showerror("Error", "Choose a log file type")
    elif radioVarTrack.get() != 1 and radioVarTrack.get() != 2:
        tkMessageBox.showerror("Error", "Choose an algorithm")
    elif epsInput == "":
        tkMessageBox.showerror("Error", "Choose an epsilon value")
    elif heading == "":
        tkMessageBox.showerror("Error", "Choose a heading that is a number, or set to 'none' if heading from log data is wanted")
    elif accptInput == "":
        tkMessageBox.showerror("Error", "Choose an accepted radius for achieved waypoint in meters")
    elif loiterInput == "":
        tkMessageBox.showerror("Error", "Choose a loiter time for each waypoint in milliseconds")
    elif maxHSInput == "":
        tkMessageBox.showerror("Error", "Choose a maximum horizontal speed for waypoints in meters per second")
    elif maxVSInput == "":
        tkMessageBox.showerror("Error", "Choose a maximum vertical speed for take off and landing in meters per second")
    elif allowedCheck(epsInput) == False:
        tkMessageBox.showerror("Error", "Epsilon must be a number")
    elif heading != "none" and heading != "None" and allowedCheck(heading) == False:
        tkMessageBox.showerror("Error", "Choose a heading that is a number, or set to 'none' if heading from log data is wanted")
    elif allowedCheck(accptInput) == False:
        tkMessageBox.showerror("Error", "Accepted radius in meters must be a number")
    elif allowedCheck(loiterInput) == False:
        tkMessageBox.showerror("Error", "Loiter time in milliseconds must be a number")
    elif allowedCheck(maxHSInput) == False:
        tkMessageBox.showerror("Error", "Maximum horizontal speed in meters per second must be a number")
    elif allowedCheck(maxVSInput) == False:
        tkMessageBox.showerror("Error", "Maximum vertical speed in meters per second must be a number")
    elif autoVar.get() == 0:
        if outputFilenameEntryLog.get() == "":
            tkMessageBox.showerror("Error", "Missing track log output filename")
        elif inputFilenameEntryTrack.get() == "":
            tkMessageBox.showerror("Error", "Missing track log input filename")
        elif outputFilenameEntryTrack.get() == "":
            tkMessageBox.showerror("Error", "Missing route plan output filename")
        elif inputFilenameEntryRoute.get() == "":
            tkMessageBox.showerror("Error", "Missing route plan input filename")
        elif outputFilenameEntryRoute.get() == "":
            tkMessageBox.showerror("Error", "Missing waypoints output filename")
        else:
            inputBool = True
    elif autoVar.get() == 1:
        outputFilenameEntryLog.delete(0, "end")
        outputFilenameEntryLog.insert(0, "trackLog")
        inputFilenameEntryTrack.delete(0, "end")
        inputFilenameEntryTrack.insert(0, "trackLog")
        outputFilenameEntryTrack.delete(0, "end")
        outputFilenameEntryTrack.insert(0, "routePlan")
        inputFilenameEntryRoute.delete(0, "end")
        inputFilenameEntryRoute.insert(0, "routePlan")
        outputFilenameEntryRoute.delete(0, "end")
        outputFilenameEntryRoute.insert(0, "waypoints")
        inputBool = True

    if inputBool == True:
        inputLog = inputFilenameEntryLog.get()
        outputLog = outputFilenameEntryLog.get()
        inputTrack = inputFilenameEntryTrack.get()
        outputTrack = outputFilenameEntryTrack.get()
        inputRoute = inputFilenameEntryRoute.get()
        outputRoute = outputFilenameEntryRoute.get()
        accptRad = float(accptInput)
        loiter = float(loiterInput)
        maxHoriSpeed = float(maxHSInput)
        maxVertSpeed = float(maxVSInput)
        coordFrame = 0 #lat., lon. and abs. altitude
        autoContinue = 1 #1: Yes
        if radioVarLog.get() == 1:
            cl.csvLOGToTrackLog(inputLog, outputLog)
        elif radioVarLog.get() == 2:
            cl.NMEAToTrackLog(inputLog, outputLog)
        elif radioVarLog.get() == 3:
            AQL = aqLogConverter(inputLog + ".LOG")
            AQL.logToCsv(outputLog + ".csv")
        if radioVarTrack.get() == 1:
            cl.trackLogToRoutePlanRDP(inputTrack, outputTrack, float(epsInput))
        elif radioVarTrack.get() == 2:
            cl.trackLogToRoutePlanRW(inputTrack, outputTrack, float(epsInput))
        cl.routePlanToWaypoints(inputRoute, outputRoute, heading, accptRad, loiter, maxHoriSpeed, maxVertSpeed, coordFrame, autoContinue)
        if kmlVarLog.get() == 1:
            cl.exportToKml(outputLog)
        if kmlVarTrack.get() == 1:
            cl.exportToKml(outputTrack)

def parseLog():
    inputLog = inputFilenameEntryLog.get()
    outputLog = outputFilenameEntryLog.get()
    if radioVarLog.get() != 1 and radioVarLog.get() != 2 and radioVarLog.get() != 3:
        tkMessageBox.showerror("Error", "Choose a log file type")
    elif inputLog == "":
        tkMessageBox.showerror("Error", "Missing log input filename")
    elif outputLog == "":
        tkMessageBox.showerror("Error", "Missing track log output filename")
    else:
        if radioVarLog.get() == 1:
            cl.csvLOGToTrackLog(inputLog, outputLog)
        elif radioVarLog.get() == 2:
            cl.NMEAToTrackLog(inputLog, outputLog)
        elif radioVarLog.get() == 3:
            AQL = aqLogConverter(inputLog + ".LOG")
            AQL.logToCsv(outputLog + ".csv")
        if kmlVarLog.get() == 1:
            cl.exportToKml(outputLog)

def parseTrack():
    inputTrack = inputFilenameEntryTrack.get()
    outputTrack = outputFilenameEntryTrack.get()
    epsInput = epsEntryTrack.get()
    if radioVarTrack.get() != 1 and radioVarTrack.get() != 2:
        tkMessageBox.showerror("Error", "Choose an algorithm")
    elif epsInput == "":
        tkMessageBox.showerror("Error", "Choose an epsilon value")
    elif allowedCheck(epsInput) == False:
        tkMessageBox.showerror("Error", "Epsilon must be a number")
    elif inputTrack == "":
        tkMessageBox.showerror("Error", "Missing track log input filename")
    elif outputTrack == "":
        tkMessageBox.showerror("Error", "Missing route plan output filename")
    else:
        if radioVarTrack.get() == 1:
            cl.trackLogToRoutePlanRDP(inputTrack, outputTrack, float(epsInput))
        elif radioVarTrack.get() == 2:
            cl.trackLogToRoutePlanRW(inputTrack, outputTrack, float(epsInput))
            if kmlVarTrack.get() == 1:
                cl.exportToKml(outputTrack)

def parseRoute():
    inputRoute = inputFilenameEntryRoute.get()
    outputRoute = outputFilenameEntryRoute.get()
    heading = headingEntryRoute.get()
    accptInput = accptRadEntryRoute.get()
    loiterInput = loiterEntryRoute.get()
    maxHSInput = maxHoriEntryRoute.get()
    maxVSInput = maxVertEntryRoute.get()

    if heading == "":
        tkMessageBox.showerror("Error", "Choose a heading that is a number, or set to 'none' if heading from log data is wanted")
    elif accptInput == "":
        tkMessageBox.showerror("Error", "Choose an accepted radius for achieved waypoint in meters")
    elif loiterInput == "":
        tkMessageBox.showerror("Error", "Choose a loiter time for each waypoint in milliseconds")
    elif maxHSInput == "":
        tkMessageBox.showerror("Error", "Choose a maximum horizontal speed for waypoints in meters per second")
    elif maxVSInput == "":
        tkMessageBox.showerror("Error", "Choose a maximum vertical speed for take off and landing in meters per second")
    elif heading != "none" and heading != "None" and allowedCheck(heading) == False:
        tkMessageBox.showerror("Error", "Choose a heading that is a number, or set to 'none' if heading from log data is wanted")
    elif allowedCheck(accptInput) == False:
        tkMessageBox.showerror("Error", "Accepted radius in meters must be a number")
    elif allowedCheck(loiterInput) == False:
        tkMessageBox.showerror("Error", "Loiter time in milliseconds must be a number")
    elif allowedCheck(maxHSInput) == False:
        tkMessageBox.showerror("Error", "Maximum horizontal speed in meters per second must be a number")
    elif allowedCheck(maxVSInput) == False:
        tkMessageBox.showerror("Error", "Maximum vertical speed in meters per second must be a number")
    elif inputRoute == "":
        tkMessageBox.showerror("Error", "Missing route plan input filename")
    elif outputRoute == "":
        tkMessageBox.showerror("Error", "Missing waypoints output filename")
    else:
        accptRad = float(accptRadEntryRoute.get())
        loiter = float(loiterEntryRoute.get())
        maxHoriSpeed = float(maxHoriEntryRoute.get())
        maxVertSpeed = float(maxVertEntryRoute.get())
        coordFrame = 0 #lat., lon. and abs. altitude
        autoContinue = 1 #1: Yes
        cl.routePlanToWaypoints(inputRoute, outputRoute, heading, accptRad, loiter, maxHoriSpeed, maxVertSpeed, coordFrame, autoContinue)

#Other functions:
def allowedCheck(stringInput):
    if set(stringInput) <= allowedChars:
        return True
    else:
        return False

#GUI
root = Tkinter.Tk()
root.wm_title("L2T2R2W")

licenceFrame = Tkinter.Frame(root)
licenceFrame.pack()

bottomFrame = Tkinter.Frame(root)
bottomFrame.pack(side = Tkinter.BOTTOM)

exportFrame = Tkinter.Frame(root)
exportFrame.pack()

logFrame = Tkinter.Frame(root)
logFrame.pack()

trackFrame = Tkinter.Frame(root)
trackFrame.pack()

routeFrame = Tkinter.Frame(root)
routeFrame.pack()

#****************************************#

titleLabelLog = Tkinter.Label(logFrame, text = "Log to track log", font = "Verdana 10 bold")
titleLabelLog.grid(row = 0, column = 0)

inputTypeLabelLog = Tkinter.Label(logFrame, text = "Log type:")
inputTypeLabelLog.grid(row = 1, column = 0)
kmlVarLog = Tkinter.IntVar()
kmlCheckButtonLog = Tkinter.Checkbutton(logFrame, text = "Export to .kml", variable = kmlVarLog, onvalue = 1, offvalue = 0)
kmlCheckButtonLog.grid(row = 2, column = 0)
radioVarLog = Tkinter.IntVar()
csvLOGRadioButton = Tkinter.Radiobutton(logFrame, text = "csvLOG", variable = radioVarLog, value = 1)
csvLOGRadioButton.grid(row = 1, column = 1)
NMEARadioButton = Tkinter.Radiobutton(logFrame, text = "NMEA", variable = radioVarLog, value = 2)
NMEARadioButton.grid(row = 2, column = 1)
LOGRadioButton = Tkinter.Radiobutton(logFrame, text = ".LOG", variable = radioVarLog, value = 3)
LOGRadioButton.grid(row = 3, column = 1)

inputFilenameButtonLog = Tkinter.Button(logFrame, text = "Input file name:", command = partial(findFilename, 0))
inputFilenameButtonLog.config(width = 12)
inputFilenameButtonLog.grid(row = 4, column = 0)
inputFilenameEntryLog = Tkinter.Entry(logFrame)
inputFilenameEntryLog.config(width = 8)
inputFilenameEntryLog.grid(row = 4, column = 1)
outputFilenameButtonLog = Tkinter.Button(logFrame, text = "Output file name:", command = partial(findFilename, 1))
outputFilenameButtonLog.config(width = 12)
outputFilenameButtonLog.grid(row = 5, column = 0)
outputFilenameEntryLog = Tkinter.Entry(logFrame)
outputFilenameEntryLog.config(width = 8)
outputFilenameEntryLog.grid(row = 5, column = 1)
parseDataButtonLog = Tkinter.Button(logFrame, text = "Parse", command = parseLog)
parseDataButtonLog.config(width = 12)
parseDataButtonLog.grid(row = 6, column = 0)

#---

titleLabelTrack = Tkinter.Label(trackFrame, text = "Track log to\nroute plan", font = "Verdana 10 bold")
titleLabelTrack.grid(row = 0, column = 0)

inputTypeLabelTrack = Tkinter.Label(trackFrame, text = "Algorithm:")
inputTypeLabelTrack.grid(row = 1, column = 0)
kmlVarTrack = Tkinter.IntVar()
kmlCheckButtonTrack = Tkinter.Checkbutton(trackFrame, text = "Export to .kml", variable = kmlVarTrack, onvalue = 1, offvalue = 0)
kmlCheckButtonTrack.grid(row = 2, column = 0)
radioVarTrack = Tkinter.IntVar()
RDPRadioButton = Tkinter.Radiobutton(trackFrame, text = "RDP", variable = radioVarTrack, value = 1)
RDPRadioButton.grid(row = 1, column = 1)
RWLOGRadioButton = Tkinter.Radiobutton(trackFrame, text = "RW", variable = radioVarTrack, value = 2)
RWLOGRadioButton.grid(row = 2, column = 1)

epsLabelTrack = Tkinter.Label(trackFrame, text = "Epsilon:")
epsLabelTrack.grid(row = 3, column = 0)
epsEntryTrack = Tkinter.Entry(trackFrame)
epsEntryTrack.config(width = 4)
epsEntryTrack.grid(row = 3, column = 1)

inputFilenameButtonTrack = Tkinter.Button(trackFrame, text = "Input file name:", command = partial(findFilename, 2))
inputFilenameButtonTrack.config(width = 12)
inputFilenameButtonTrack.grid(row = 4, column = 0)
inputFilenameEntryTrack = Tkinter.Entry(trackFrame)
inputFilenameEntryTrack.config(width = 8)
inputFilenameEntryTrack.grid(row = 4, column = 1)
outputFilenameButtonTrack = Tkinter.Button(trackFrame, text = "Output file name:", command = partial(findFilename, 3))
outputFilenameButtonTrack.config(width = 12)
outputFilenameButtonTrack.grid(row = 5, column = 0)
outputFilenameEntryTrack = Tkinter.Entry(trackFrame)
outputFilenameEntryTrack.config(width = 8)
outputFilenameEntryTrack.grid(row = 5, column = 1)
parseDataButtonTrack = Tkinter.Button(trackFrame, text = "Parse", command = parseTrack)
parseDataButtonTrack.config(width = 12)
parseDataButtonTrack.grid(row = 6, column = 0)

#---

titleLabelRoute = Tkinter.Label(routeFrame, text = "Route plan to\nwaypoints", font = "Verdana 10 bold")
titleLabelRoute.grid(row = 0, column = 0)

headingLabelRoute = Tkinter.Label(routeFrame, text = "Heading:")
headingLabelRoute.grid(row = 1, column = 0)
headingEntryRoute = Tkinter.Entry(routeFrame)
headingEntryRoute.config(width = 4)
headingEntryRoute.grid(row = 1, column = 1)
headingEntryRoute.insert(0, "None")

accptRadLabelRoute = Tkinter.Label(routeFrame, text = "Accepted rad.:")
accptRadLabelRoute.grid(row = 2, column = 0)
accptRadEntryRoute = Tkinter.Entry(routeFrame)
accptRadEntryRoute.config(width = 4)
accptRadEntryRoute.grid(row = 2, column = 1)

loiterLabelRoute = Tkinter.Label(routeFrame, text = "Loiter:")
loiterLabelRoute.grid(row = 3, column = 0)
loiterEntryRoute = Tkinter.Entry(routeFrame)
loiterEntryRoute.config(width = 4)
loiterEntryRoute.grid(row = 3, column = 1)

maxHoriLabelRoute = Tkinter.Label(routeFrame, text = "Max. hori. speed:")
maxHoriLabelRoute.grid(row = 4, column = 0)
maxHoriEntryRoute = Tkinter.Entry(routeFrame)
maxHoriEntryRoute.config(width = 4)
maxHoriEntryRoute.grid(row = 4, column = 1)

maxVertLabelRoute = Tkinter.Label(routeFrame, text = "Max. vert. speed:")
maxVertLabelRoute.grid(row = 5, column = 0)
maxVertEntryRoute = Tkinter.Entry(routeFrame)
maxVertEntryRoute.config(width = 4)
maxVertEntryRoute.grid(row = 5, column = 1)

inputFilenameButtonRoute = Tkinter.Button(routeFrame, text = "Input file name:", command = partial(findFilename, 4))
inputFilenameButtonRoute.config(width = 12)
inputFilenameButtonRoute.grid(row = 6, column = 0)
inputFilenameEntryRoute = Tkinter.Entry(routeFrame)
inputFilenameEntryRoute.config(width = 8)
inputFilenameEntryRoute.grid(row = 6, column = 1)
outputFilenameButtonRoute = Tkinter.Button(routeFrame, text = "Output file name:", command = partial(findFilename, 5))
outputFilenameButtonRoute.config(width = 12)
outputFilenameButtonRoute.grid(row = 7, column = 0)
outputFilenameEntryRoute = Tkinter.Entry(routeFrame)
outputFilenameEntryRoute.config(width = 8)
outputFilenameEntryRoute.grid(row = 7, column = 1)
parseDataButtonRoute = Tkinter.Button(routeFrame, text = "Parse", command = parseRoute)
parseDataButtonRoute.config(width = 12)
parseDataButtonRoute.grid(row = 8, column = 0)

autoVar = Tkinter.IntVar()
autoCheckButton = Tkinter.Checkbutton(bottomFrame, text = "Auto fill", variable = autoVar, onvalue = 1, offvalue = 0)
autoCheckButton.grid(row = 0, column = 0)
parseAllButton = Tkinter.Button(bottomFrame, text = "Parse all", command = parseAll)
parseAllButton.config(width = 12)
parseAllButton.grid(row = 1, column = 0)
exitButton = Tkinter.Button(bottomFrame, text = "Exit", command = exitProgram)
exitButton.config(width = 5)
exitButton.grid(row = 1, column = 1)

root.mainloop()


from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
from django.forms import ModelChoiceField, ModelMultipleChoiceField
from django.forms import modelformset_factory, inlineformset_factory

from .models import Variant, Question, Feedback, Task, Solution

"""form for radiobuttons"""
class VariantModelChoiceField(ModelChoiceField):
	def label_from_instance(self, obj):
		return obj.text

class VariantForm(forms.ModelForm):
	variants = VariantModelChoiceField(
		queryset=Variant.objects.none(),
		to_field_name='text',
		widget=forms.CheckboxSelectMultiple(),
		#empty_label=None,
		#label=form.instance.question_text
		)

	class Meta:
		model = Question
		fields = ['variants']

VariantFormSet = inlineformset_factory(
		Task,
		Question,
		form=VariantForm,
		fields = ('question_text', 'variants',),
		#formset=BaseModelFormSet,
		extra=0,
		)

SolutionFormSet = inlineformset_factory(
	Task,
	Solution,
	fields = ('task', 'variant',),
	form=VariantForm,
	extra=0
	)

def create_new_form(task):
	class NewForm(forms.ModelForm):
		class Meta:
			model = Solution
			questions = Question.objects.filter(task=task)
			fields = []
			for n, question in enumerate(questions):
				field = forms.MultipleChoiceField(
					choices=[(variant.id, variant.text) for variant in question.variants.all()])
				fields.append(field)

	#NewForm = type('NewForm', (forms.BaseForm,), {'base_fields': base_fields})
	print(NewForm)
	return NewForm


import asyncio
import logging
import sys

import numpy as np
from farm_ng.config import default_config
from farm_ng.ipc import get_event_bus
from farm_ng.ipc import make_event
from farm_ng.kinematics import TractorKinematics
from farm_ng.periodic import Periodic
from farm_ng.proto_utils import se3_to_proto
from farm_ng_proto.tractor.v1.geometry_pb2 import NamedSE3Pose
from liegroups import SE3

logger = logging.getLogger('pose_vis_toy')
logger.setLevel(logging.INFO)

class PoseVisToy:
    def __init__(self, event_loop):
        self.event_loop = event_loop
        self.command_rate_hz = 50
        self.command_period_seconds = 1.0 / self.command_rate_hz
        self.event_bus = get_event_bus('farm_ng.pose_vis_toy')
        self.odom_pose_tractor = SE3.identity()
        self.tractor_pose_wheel_left = SE3.exp((0.0, 1.0, 0, 0, 0, 0)).dot(SE3.exp((0.0, 0.0, 0, -np.pi/2, 0, 0)))
        self.tractor_pose_wheel_right = SE3.exp((0.0, -1.0, 0, 0, 0, 0)).dot(SE3.exp((0.0, 0.0, 0, -np.pi/2, 0, 0)))

        self.kinematic_model = TractorKinematics(default_config())

        self.control_timer = Periodic(
            self.command_period_seconds, self.event_loop,
            self._command_loop, name='control_loop',
        )

    def _command_loop(self, n_periods):
        pose_msg = NamedSE3Pose()
        left_speed = 1.0
        right_speed = 0.5
        self.odom_pose_tractor = self.kinematic_model.evolve_world_pose_tractor(
            self.odom_pose_tractor, left_speed, right_speed, n_periods*self.command_period_seconds,
        )
        pose_msg.a_pose_b.CopyFrom(se3_to_proto(self.odom_pose_tractor))
        pose_msg.frame_a = 'odometry/wheel'
        pose_msg.frame_b = 'tractor/base'
        self.event_bus.send(make_event('pose/tractor/base', pose_msg))

        pose_msg = NamedSE3Pose()
        radius = self.kinematic_model.wheel_radius
        self.tractor_pose_wheel_left = self.tractor_pose_wheel_left.dot(SE3.exp((0, 0, 0, 0, 0, left_speed/radius*self.command_period_seconds*n_periods)))
        pose_msg.a_pose_b.CopyFrom(se3_to_proto(self.tractor_pose_wheel_left))
        pose_msg.frame_a = 'tractor/base'
        pose_msg.frame_b = 'tractor/wheel/left'
        self.event_bus.send(make_event('pose/tractor/wheel/left', pose_msg))

        pose_msg = NamedSE3Pose()
        self.tractor_pose_wheel_right = self.tractor_pose_wheel_right.dot(SE3.exp((0, 0, 0, 0, 0, right_speed/radius*self.command_period_seconds*n_periods)))
        pose_msg.a_pose_b.CopyFrom(se3_to_proto(self.tractor_pose_wheel_right))
        pose_msg.frame_a = 'tractor/base'
        pose_msg.frame_b = 'tractor/wheel/right'
        self.event_bus.send(make_event('pose/tractor/wheel/right', pose_msg))

        pose_msg = NamedSE3Pose()
        pose_msg.a_pose_b.position.z = 1.0
        pose_msg.a_pose_b.position.y = 0.5
        pose_msg.frame_a = 'tractor/base'
        pose_msg.frame_b = 'tractor/camera'
        self.event_bus.send(make_event('pose/tractor/camera', pose_msg))

def main():
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)
    event_loop = asyncio.get_event_loop()

    controller = PoseVisToy(event_loop)
    logger.info('Created controller %s', controller)
    event_loop.run_forever()

if __name__ == '__main__':
    main()


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

import collections

from oslo_db import api as oslo_db_api
from oslo_log import log as logging

from placement.db import graph_db as db
from placement import db_api
from placement import exception
from placement.objects import consumer as consumer_obj
from placement.objects import project as project_obj
from placement.objects import resource_provider as rp_obj
from placement.objects import user as user_obj

LOG = logging.getLogger(__name__)

# The number of times to retry set_allocations if there has
# been a resource provider (not consumer) generation coflict.
RP_CONFLICT_RETRY_COUNT = 10

class Allocation(object):

    def __init__(self, resource_provider=None, consumer=None,
                 resource_class=None, used=0, updated_at=None,
                 created_at=None):
        self.resource_provider = resource_provider
        self.resource_class = resource_class
        self.consumer = consumer
        self.used = used
        self.updated_at = updated_at
        self.created_at = created_at

@db_api.placement_context_manager.reader
def _list_allocations_for_consumer(context, consumer_uuid):
    """Deletes any existing allocations that correspond to the allocations to
    be written. This is wrapped in a transaction, so if the write subsequently
    fails, the deletion will also be rolled back.
    """
    query = """
            MATCH p=(:CONSUMER {uuid: '%s'})-[:USES]->()
            WITH relationships(p)[0] AS usages
            RETURN usages
    """ % consumer_uuid
    result = context.tx.run(query).data()
    return [db.pythonize(rec["usages"]) for rec in result]

@db_api.placement_context_manager.writer
def _delete_allocations_for_consumer(context, consumer_uuid):
    """Deletes any existing allocations that correspond to the allocations to
    be written. This is wrapped in a transaction, so if the write subsequently
    fails, the deletion will also be rolled back.
    """
    query = """
            MATCH p=(:CONSUMER {uuid: '%s'})-[:USES]->()
            WITH relationships(p)[0] AS usages
            DELETE usages
    """ % consumer_uuid
    context.tx.run(query)

def _check_capacity_exceeded(context, allocs):
    """Checks to see if the supplied allocation records would result in any of
    the inventories involved having their capacity exceeded.

    Raises an InvalidAllocationCapacityExceeded exception if any inventory
    would be exhausted by the allocation. Raises an
    InvalidAllocationConstraintsViolated exception if any of the `step_size`,
    `min_unit` or `max_unit` constraints in an inventory will be violated
    by any one of the allocations.

    If no inventories would be exceeded or violated by the allocations, the
    function returns a list of `ResourceProvider` objects that contain the
    generation at the time of the check.

    :param ctx: `placement.context.RequestContext` that has an oslo_db
                Session
    :param allocs: List of `Allocation` objects to check
    """
    rc_names = set([a.resource_class for a in allocs])
    # Make sure that all the rc_names are valid
    query = """
            MATCH (rc:RESOURCE_CLASS)
            WHERE rc.name IN {names}
            RETURN rc.name AS rc_name
    """
    result = context.tx.run(query, names=list(rc_names))
    db_names = set([rec["rc_name"] for rec in result])
    set_bad_names = rc_names - db_names
    if set_bad_names:
        bad_names = ",".join(set_bad_names)
        raise exception.ResourceClassNotFound(resource_class=bad_names)

    provider_uuids = set([a.resource_provider.uuid for a in allocs])
    query = """
            MATCH (rp:RESOURCE_PROVIDER)-[:PROVIDES]->(rc)
            WHERE rp.uuid IN {rp_uuids}
            AND labels(rc)[0] IN {labels}
            WITH rp, rc
            OPTIONAL MATCH p=(cs:CONSUMER)-[:USES]->(rc)
            WITH rp, rc, relationships(p)[0] AS allocs
            WITH rp, rc, sum(allocs.amount) AS total_usages
            RETURN rp, rc, labels(rc)[0] AS rc_name, total_usages
    """
    result = context.tx.run(query, rp_uuids=list(provider_uuids),
            labels=list(rc_names)).data()

    # Create a map keyed by (rp_uuid, res_class) for the records in the DB
    usage_map = {}
    provs_with_inv = set()
    for record in result:
        map_key = (record["rp"]["uuid"], record["rc_name"])
        if map_key in usage_map:
            raise KeyError("%s already in usage_map, bad query" % str(map_key))
        usage_map[map_key] = record
        provs_with_inv.add(record["rp"]["uuid"])
    # Ensure that all providers have existing inventory
    missing_provs = provider_uuids - provs_with_inv
    if missing_provs:
        class_str = ", ".join(rc_names)
        provider_str = ", ".join(missing_provs)
        raise exception.InvalidInventory(
            resource_class=class_str, resource_provider=provider_str)

    res_providers = {}
    rp_resource_class_sum = collections.defaultdict(
        lambda: collections.defaultdict(int))
    for alloc in allocs:
        rc_name = alloc.resource_class
        rp_uuid = alloc.resource_provider.uuid
        if rp_uuid not in res_providers:
            res_providers[rp_uuid] = alloc.resource_provider
        amount_needed = alloc.used
        # No use checking usage if we're not asking for anything
        if amount_needed == 0:
            continue
        rp_resource_class_sum[rp_uuid][rc_name] += amount_needed
        key = (rp_uuid, rc_name)
        try:
            usage_record = usage_map[key]
        except KeyError:
            # The resource class at rc_name is not in the usage map.
            raise exception.InvalidInventory(
                resource_class=alloc.resource_class,
                resource_provider=rp_uuid)
        rc_record = usage_record["rc"]
        allocation_ratio = rc_record["allocation_ratio"]
        min_unit = rc_record["min_unit"]
        max_unit = rc_record["max_unit"]
        step_size = rc_record["step_size"]
        total = rc_record["total"]
        reserved = rc_record["reserved"]

        # check min_unit, max_unit, step_size
        if ((amount_needed < min_unit) or (amount_needed > max_unit) or
                (amount_needed % step_size)):
            LOG.warning(
                    "Allocation for %(rc)s on resource provider %(rp)s "
                    "violates min_unit, max_unit, or step_size. "
                    "Requested: %(requested)s, min_unit: %(min_unit)s, "
                    "max_unit: %(max_unit)s, step_size: %(step_size)s",
                    {"rc": alloc.resource_class,
                     "rp": rp_uuid,
                     "requested": amount_needed,
                     "min_unit": min_unit,
                     "max_unit": max_unit,
                     "step_size": step_size})
            raise exception.InvalidAllocationConstraintsViolated(
                    resource_class=alloc.resource_class,
                    resource_provider=rp_uuid)

        # Should never be null, but just in case...
        used = usage_record["total_usages"] or 0
        capacity = (total - reserved) * allocation_ratio
        if (capacity < (used + amount_needed) or
                capacity < (used + rp_resource_class_sum[rp_uuid][rc_name])):
            LOG.warning(
                "Over capacity for %(rc)s on resource provider %(rp)s. "
                "Needed: %(needed)s, Used: %(used)s, Capacity: %(cap)s",
                {"rc": alloc.resource_class,
                 "rp": rp_uuid,
                 "needed": amount_needed,
                 "used": used,
                 "cap": capacity})
            raise exception.InvalidAllocationCapacityExceeded(
                resource_class=alloc.resource_class,
                resource_provider=rp_uuid)
    return res_providers

@db_api.placement_context_manager.reader
def _get_allocations_by_provider_uuid(context, rp_uuid):
    query = """
            MATCH (rp:RESOURCE_PROVIDER {uuid: '%s'})
            WITH rp
            MATCH (rp)-[:PROVIDES]->(rc)
            WITH rp, rc
            MATCH p=(cs:CONSUMER)-[:USES]->(rc)
            WITH rp, rc, labels(rc)[0] AS rc_name, cs,
                relationships(p)[0] AS usages
            OPTIONAL MATCH (pj:PROJECT)-[:OWNS]->(user:USER)-[:OWNS]->(cs)
            RETURN rp, rc, rc_name, cs, usages, pj, user
    """ % rp_uuid
    result = context.tx.run(query).data()
    allocs = []
    for record in result:
        rec_cs = db.pythonize(record["cs"])
        pj_uuid = record["pj"].get("uuid") if record["pj"] else None
        user_uuid = record["user"].get("uuid") if record["user"] else None
        allocs.append({
            "resource_provider_name": record["rp"]["name"],
            "resource_provider_uuid": record["rp"]["uuid"],
            "resource_provider_generation": record["rp"]["generation"],
            "resource_class_name": record["rc_name"],
            "used": record["usages"]["amount"],
            "consumer_uuid": rec_cs["uuid"],
            "consumer_generation": rec_cs["generation"],
            "project_uuid": pj_uuid,
            "user_uuid": user_uuid,
            "created_at": rec_cs["created_at"],
            "updated_at": rec_cs["updated_at"],
        })
    return allocs

@db_api.placement_context_manager.reader
def _get_allocations_by_consumer_uuid(context, consumer_uuid):
    query = """
            MATCH p=(cs:CONSUMER {uuid: '%s'})-[:USES]->(rc)
            WITH cs, rc, labels(rc)[0] AS rc_name,
                relationships(p)[0] AS usages
            OPTIONAL MATCH (pj:PROJECT)-[:OWNS]->(user:USER)-[:OWNS]->(cs)
            WITH rc, rc_name, cs, usages, pj, user
            MATCH (rp:RESOURCE_PROVIDER)-[:PROVIDES]->(rc)
            RETURN rp, rc, rc_name, cs, usages, pj, user
    """ % consumer_uuid
    result = context.tx.run(query).data()
    allocs = []
    for record in result:
        rec_cs = db.pythonize(record["cs"])
        pj_uuid = record["pj"].get("uuid") if record["pj"] else None
        user_uuid = record["user"].get("uuid") if record["user"] else None
        allocs.append({
            "resource_provider_name": record["rp"]["name"],
            "resource_provider_uuid": record["rp"]["uuid"],
            "resource_provider_generation": record["rp"]["generation"],
            "resource_class_name": record["rc_name"],
            "used": record["usages"]["amount"],
            "consumer_uuid": rec_cs["uuid"],
            "consumer_generation": rec_cs["generation"],
            "project_uuid": pj_uuid,
            "user_uuid": user_uuid,
            "created_at": rec_cs["created_at"],
            "updated_at": rec_cs["updated_at"],
        })
    return allocs

@db_api.placement_context_manager.writer.independent
def _create_incomplete_consumers_for_provider(context, rp_id):
    # TODO(jaypipes): Remove in Stein after a blocker migration is added.
    """Creates consumer record if consumer relationship between allocations ->
    consumers table is missing for any allocation on the supplied provider
    internal ID, using the "incomplete consumer" project and user CONF options.

    NOTE: using a graph database, an allocation is a relation between a
    consumer and a resource. There cannot be an allocation without a consumer,
    so this method is not necessary.
    """
    return

@db_api.placement_context_manager.writer.independent
def _create_incomplete_consumer(context, consumer_id):
    # TODO(jaypipes): Remove in Stein after a blocker migration is added.
    """Creates consumer record if consumer relationship between allocations ->
    consumers table is missing for the supplied consumer UUID, using the
    "incomplete consumer" project and user CONF options.

    NOTE: using a graph database, an allocation is a relation between a
    consumer and a resource. There cannot be an allocation without a consumer,
    so this method is not necessary.
    """
    return

@db_api.placement_context_manager.writer
def _set_allocations(context, allocs):
    """Write a set of allocations.

    We must check that there is capacity for each allocation.
    If there is not we roll back the entire set.

    :raises `exception.ResourceClassNotFound` if any resource class in any
            allocation in allocs cannot be found in either the DB.
    :raises `exception.InvalidAllocationCapacityExceeded` if any inventory
            would be exhausted by the allocation.
    :raises `InvalidAllocationConstraintsViolated` if any of the
            `step_size`, `min_unit` or `max_unit` constraints in an
            inventory will be violated by any one of the allocations.
    :raises `ConcurrentUpdateDetected` if a generation for a resource
            provider or consumer failed its increment check.
    """
    # First delete any existing allocations for any consumers. This
    # provides a clean slate for the consumers mentioned in the list of
    # allocations being manipulated.
    consumer_uuids = set(alloc.consumer.uuid for alloc in allocs)
    for consumer_uuid in consumer_uuids:
        _delete_allocations_for_consumer(context, consumer_uuid)

    # Before writing any allocation records, we check that the submitted
    # allocations do not cause any inventory capacity to be exceeded for
    # any resource provider and resource class involved in the allocation
    # transaction. _check_capacity_exceeded() raises an exception if any
    # inventory capacity is exceeded. If capacity is not exceeeded, the
    # function returns a list of ResourceProvider objects containing the
    # generation of the resource provider at the time of the check. These
    # objects are used at the end of the allocation transaction as a guard
    # against concurrent updates.
    #
    # Don't check capacity when alloc.used is zero. Zero is not a valid
    # amount when making an allocation (the minimum consumption of a
    # resource is one) but is used in this method to indicate a need for
    # removal. Providing 0 is controlled at the HTTP API layer where PUT
    # /allocations does not allow empty allocations. When POST /allocations
    # is implemented it will for the special case of atomically setting and
    # removing different allocations in the same request.
    # _check_capacity_exceeded will raise a ResourceClassNotFound if any
    # allocation is using a resource class that does not exist.
    visited_consumers = {}
    visited_rps = _check_capacity_exceeded(context, allocs)
    for alloc in allocs:
        if alloc.consumer.uuid not in visited_consumers:
            visited_consumers[alloc.consumer.uuid] = alloc.consumer

        # If alloc.used is set to zero that is a signal that we don't want
        # to (re-)create any allocations for this resource class.
        # _delete_current_allocs has already wiped out allocations so just
        # continue
        if alloc.used == 0:
            continue
        consumer_uuid = alloc.consumer.uuid
        rp = alloc.resource_provider
        rc_name = alloc.resource_class
        query = """
                MATCH (rp:RESOURCE_PROVIDER {uuid: '%s'})
                WITH rp
                MATCH (rp)-[:PROVIDES]->(rc:%s)
                WITH rp, rc
                MATCH (cs:CONSUMER {uuid: '%s'})
                WITH rp, rc, cs
                CREATE p=(cs)-[:USES {amount: %s}]->(rc)
                RETURN p
        """ % (rp.uuid, rc_name, consumer_uuid, alloc.used)
        result = context.tx.run(query)

    # Generation checking happens here. If the inventory for this resource
    # provider changed out from under us, this will raise a
    # ConcurrentUpdateDetected which can be caught by the caller to choose
    # to try again. It will also rollback the transaction so that these
    # changes always happen atomically.
    for rp in visited_rps.values():
        rp.increment_generation()
    for consumer in visited_consumers.values():
        consumer.increment_generation()
    # If any consumers involved in this transaction ended up having no
    # allocations, delete the consumer records. Exclude consumers that had
    # *some resource* in the allocation list with a total > 0 since clearly
    # those consumers have allocations...
    cons_with_allocs = set(a.consumer.uuid for a in allocs if a.used > 0)
    all_cons = set(c.uuid for c in visited_consumers.values())
    consumers_to_check = all_cons - cons_with_allocs
    consumer_obj.delete_consumers_if_no_allocations(context,
            consumers_to_check)

def get_all_by_resource_provider(context, rp):
    _create_incomplete_consumers_for_provider(context, rp.uuid)
    db_allocs = _get_allocations_by_provider_uuid(context, rp.uuid)
    # Build up a list of Allocation objects, setting the Allocation object
    # fields to the same-named database record field we got from
    # _get_allocations_by_provider_uuid(). We already have the
    # ResourceProvider object so we just pass that object to the Allocation
    # object constructor as-is
    objs = []
    for rec in db_allocs:
        consumer = consumer_obj.Consumer(
                context, uuid=rec["consumer_uuid"],
                generation=rec["consumer_generation"],
                project=project_obj.Project(context, uuid=rec["project_uuid"]),
                user=user_obj.User(context, uuid=rec["user_uuid"]))
        objs.append(
            Allocation(
                resource_provider=rp,
                resource_class=rec["resource_class_name"],
                consumer=consumer,
                used=rec["used"],
                created_at=rec["created_at"],
                updated_at=rec["updated_at"]))
    return objs

def get_all_by_consumer_id(context, consumer_id):
    _create_incomplete_consumer(context, consumer_id)
    db_allocs = _get_allocations_by_consumer_uuid(context, consumer_id)

    if not db_allocs:
        return []

    # Build up the Consumer object (it's the same for all allocations
    # since we looked up by consumer ID)
    db_first = db_allocs[0]
    consumer = consumer_obj.Consumer(
        context, uuid=db_first['consumer_uuid'],
        generation=db_first['consumer_generation'],
        project=project_obj.Project(context, uuid=db_first['project_uuid']),
        user=user_obj.User(context, uuid=db_first['user_uuid']))

    # Build up a list of Allocation objects, setting the Allocation object
    # fields to the same-named database record field we got from
    # _get_allocations_by_consumer_id().
    #
    # NOTE(jaypipes):  Unlike with get_all_by_resource_provider(), we do
    # NOT already have the ResourceProvider object so we construct a new
    # ResourceProvider object below by looking at the resource provider
    # fields returned by _get_allocations_by_consumer_id().
    alloc_list = [
        Allocation(
            resource_provider=rp_obj.ResourceProvider(
                context,
                uuid=rec["resource_provider_uuid"],
                name=rec["resource_provider_name"],
                generation=rec["resource_provider_generation"]),
            resource_class=rec["resource_class_name"],
            consumer=consumer,
            used=rec["used"],
            created_at=rec.get("created_at"),
            updated_at=rec.get("updated_at"))
        for rec in db_allocs
    ]
    return alloc_list

def replace_all(context, alloc_list):
    """Replace the supplied allocations.

    :note: This method always deletes all allocations for all consumers
           referenced in the list of Allocation objects and then replaces
           the consumer's allocations with the Allocation objects. In doing
           so, it will end up setting the Allocation.id attribute of each
           Allocation object.
    """
    # Retry _set_allocations server side if there is a
    # ResourceProviderConcurrentUpdateDetected. We don't care about
    # sleeping, we simply want to reset the resource provider objects
    # and try again. For sake of simplicity (and because we don't have
    # easy access to the information) we reload all the resource
    # providers that may be present.
    retries = RP_CONFLICT_RETRY_COUNT
    while retries:
        retries -= 1
        try:
            _set_allocations(context, alloc_list)
            break
        except exception.ResourceProviderConcurrentUpdateDetected:
            LOG.debug("Retrying allocations write on resource provider "
                      "generation conflict")
            # We only want to reload each unique resource provider once.
            alloc_rp_uuids = set(
                    alloc.resource_provider.uuid for alloc in alloc_list)
            seen_rps = {}
            for rp_uuid in alloc_rp_uuids:
                seen_rps[rp_uuid] = rp_obj.ResourceProvider.get_by_uuid(
                        context, rp_uuid)
            for alloc in alloc_list:
                rp_uuid = alloc.resource_provider.uuid
                alloc.resource_provider = seen_rps[rp_uuid]
    else:
        # We ran out of retries so we need to raise again.
        # The log will automatically have request id info associated with
        # it that will allow tracing back to specific allocations.
        # Attempting to extract specific consumer or resource provider
        # information from the allocations is not coherent as this
        # could be multiple consumers and providers.
        LOG.warning("Exceeded retry limit of %d on allocations write",
                    RP_CONFLICT_RETRY_COUNT)
        raise exception.ResourceProviderConcurrentUpdateDetected()

def delete_all(context, alloc_list):
    consumer_uuids = set(alloc.consumer.uuid for alloc in alloc_list)
    for consumer_uuid in consumer_uuids:
        _delete_allocations_for_consumer(context, consumer_uuid)
    consumer_obj.delete_consumers_if_no_allocations(context, consumer_uuids)


import graph
import random
import perebor

def formicaio_main(graph, n, coeff):
	fero = []
	for i in range(n):
		fero.append([])
		for j in range(n):
			fero[i].append(0)
	i = 0
	while i < 50:
		fero, L = choice_way(graph, n, fero, coeff)
		i += 1
	return(L)

# Выбор пути
def choice_way(graph, n, fero, coeff):
	i = 0
	way = [i]
	L = 0
	for x in range(n-1):
		probability = [(fero[i][j])**coeff[0] + (graph[i][j])**(-coeff[1]) for j in range(n)]
		for l in way:
			probability[l] = 0
		sum_ = sum(probability)
		for l in range(n):
			probability[l] /= sum_
		rand = random.random() - 0.00001
		for l in range(n):
			rand -= probability[l]
			if rand < 0:
				i = l
				break
		L += graph[way[x]][i]
		way += [i]
	L += graph[i][0]

	d = []
	for l in range(n):
		d.append([])
		for p in range(n):
			d[l].append(0)
	for l in range(len(way)-1):
		d[way[l]][way[l+1]] = coeff[2]/L
		d[way[l+1]][way[l]] = coeff[2]/L
	d[way[0]][way[-1]] = coeff[2]/L
	d[way[-1]][way[0]] = coeff[2]/L

	for l in range(n):
		for p in range(n):
			fero[l][p] = coeff[3]*fero[l][p] + d[l][p]

	way += [0]
	return(fero, L)

if __name__ == "__main__":
	graph, n = graph.generate_graph()

	print(formicaio_main(graph, n, [3.5, 3.5, 2, 4]))
	print(perebor.mainus(graph, n))


import pandas as pd
import unittest
import stockmarket
from datetime import datetime, timedelta

class TestStockMarket(unittest.TestCase):

    def test_calc_divYield(self):
        # Tests for Type = Common
        stocksData = pd.DataFrame({"Stock Market": ["JOE"], "Type": ["Common"],
                                   "Last Dividend": [18], "Fixed Dividend": [""],
                                   "Par Value": [120]})
        result = stockmarket.calc_divYield(stocksData, 12)
        self.assertEqual(result.iloc[0]["Dividend Yield"], "150%")

        # Tests for Type == Preferred
        stocksData = pd.DataFrame({"Stock Market": ["GIN"], "Type": ["Preferred"],
                                   "Last Dividend": [18], "Fixed Dividend": ["8%"],
                                   "Par Value": [120]})
        result = stockmarket.calc_divYield(stocksData, 12)
        self.assertEqual(result.iloc[0]["Dividend Yield"], "80%")

    def test_calc_PERatio(self):
        stocksData = pd.DataFrame({"Stock Market": ["JOE"], "Type": ["Common"],
                                   "Last Dividend": [11], "Fixed Dividend": [""],
                                   "Par Value": [120]})
        result = stockmarket.calc_PERatio(stocksData, 65)
        self.assertEqual(result.iloc[0]["P/E Ratio"], 5.91)

    def test_calc_VWSP(self):
        # Generate test data
        dttime = [dttime for dttime in range(24, 0, -6)]
        timestamp = [(datetime.now() - timedelta(minutes=dt)) \
                    .strftime("%m/%d/%Y %H:%M:%S") for dt in dttime]
        trades = pd.DataFrame({"Stock Market": ["TEA", "TEA", "GIN"],
                               "Timestamp": [timestamp[0], timestamp[1], timestamp[2]],
                               "Quantity of Shares": [25, 12, 7],
                               "BUY/SELL": ["BUY", "SELL", "BUY"],
                               "Price": [22, 24, 19]})
        result = stockmarket.calc_VWSP(trades)
        self.assertEqual(len(result), 1)
        self.assertEqual(result.iloc[0]["Volume Weighted Stock Price"], 19.0)

    def test_calc_AllShareIndex(self):
        # Generate test data
        dttime = [dttime for dttime in range(24, 0, -6)]
        timestamp = [(datetime.now() - timedelta(minutes=dt)) \
                    .strftime("%m/%d/%Y %H:%M:%S") for dt in dttime]
        trades = pd.DataFrame({"Stock Market": ["TEA", "TEA", "GIN"],
                               "Timestamp": [timestamp[0], timestamp[1], timestamp[2]],
                               "Quantity of Shares": [25, 12, 7],
                               "BUY/SELL": ["BUY", "SELL", "BUY"],
                               "Price": [22, 24, 19]})
        result = stockmarket.calc_AllShareIndex(trades)
        self.assertEqual(result, 21.57)

    def test_save_trade(self):
        trades = pd.DataFrame({"Stock Market": [], "Timestamp": [], "Quantity of Shares": [], "BUY/SELL": [], "Price": []})
        result = stockmarket.save_trade(trades, "JOE", "10/07/2019 08:00:00", 21, "BUY", 11)
        self.assertEqual(len(result), 1)

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


import sys

infilename = sys.argv[1]
outfilename = sys.argv[2]

taxon_seq_dict = {}
num_heliconius = 0
num_nymphalid = 0
e_and_a = 0

heliconius_list = ["HeraHhimHyb", "Hhim", "HeraDisco", "HeraRef",
                    "Hhsa", "Hdem", "Hsar", "Htel", "HmelRef", "HmelDisco",
                    "Htim", "Hcyd", "Hpar", "Hbes", "Hnum", "Ldor"]

nymphalid_out_list = ["Mcin", "Dple", "Bany"]

with open(infilename) as infile:
    seq = ''
    for count,line in enumerate(infile):
        if line[0] == ">":
            if count > 1:
                num_chars = len(seq)
                the_as = seq.count("A")
                the_as += seq.count("a")
                the_cs = seq.count("C")
                the_cs += seq.count("c")
                the_gs = seq.count("G")
                the_gs += seq.count("g")
                the_ts = seq.count("T")
                the_ts += seq.count("t")
                the_all = the_as + the_cs + the_gs + the_ts
                if the_all/num_chars >= 0.70:
                    taxon_seq_dict[taxon] = seq
                seq = ''
                taxon = line.strip()[1:]
            else:
                taxon = line.strip()[1:]
        else:
            seq += line.strip()
    num_chars = len(seq)
    the_as = seq.count("A")
    the_as += seq.count("a")
    the_cs = seq.count("C")
    the_cs += seq.count("c")
    the_gs = seq.count("G")
    the_gs += seq.count("g")
    the_ts = seq.count("T")
    the_ts += seq.count("t")
    the_all = the_as + the_cs + the_gs + the_ts
    if the_all/num_chars >= 0.70:
        taxon_seq_dict[taxon] = seq

    for the_taxon in taxon_seq_dict:
        if the_taxon in heliconius_list:
            num_heliconius += 1
        elif "Etal" in the_taxon:
            e_and_a += 1
        elif "Avan" in the_taxon:
            e_and_a += 1
        elif the_taxon in nymphalid_out_list:
            num_nymphalid += 1
    if num_heliconius >= 12 and e_and_a >= 1:# and num_nymphalid >= 2:
        with open(outfilename, "w") as outfile:
            for the_taxon in taxon_seq_dict:
                #print(len(taxon_seq_dict[the_taxon]))
                outfile.write(">" + the_taxon + "\n")
                outfile.write(taxon_seq_dict[the_taxon] + "\n")


################################################################################
# ble_final
# Created at 2018-03-12 21:29:47.291436
# Made by: Danni Liu
################################################################################

# Importer pour Bluetooth
from nxp.hexiwear.kw40z import kw40z
import streams
import threading

streams.serial()

# Fonction pour Button gauche
def toggle_ble():
    try:
        # Quand taper Button gauche, il va afficher "Left Button Pressed" dans le COMS
        print("Left Button Pressed")
        # Changer le statut du processus de publicité. Active / désactive l'état Bluetooth
        bt_driver.toggle_adv_mode()
    except Exception as e:
        print("error on left_pressed", e)

# Fonction pour connecter par code
def print_paircode():
    # Il génère un code d'appariement stocké dans l'attribut de classe de clé d'accès
    print("Your Pair Code:",bt_driver.passkey)

# Configurer LED1 en mode OUTPUT, on peut l'allumer et l'éteindre
pinMode(LED1, OUTPUT)

# Fonction pour vérifier l'état du bluetooth
def check_status():
    print("Device Settings")
    # Récupère les informations de la bluetooth
    # Bluetooth Status (bool): 1 Bluetooth est activé, 0 Bluetooth est désactivé;
    # Boutons tactiles capacitifs (bool): 1 paire droite active, 0 paire gauche active;
    # Link Status (bool): 1 appareil est connecté, 0 appareil est déconnecté.
    bt_on, bt_touch, bt_link = bt_driver.info()
    print("Bluetooth State: ", ("On" if bt_on == 1 else "Off"))
    # LED pour indiquer l'état de Bluetooth
    digitalWrite(LED1, 0 if bt_on==1 else 1)
    print("Capacitive Button Active: ", ("Left" if bt_touch == 0 else "Right"))
    print("Link State: ", ("Connected" if bt_link == 1 else "Disconnected"))
    # Boucle pour toujours
    # Mise à jour l'état de Bluetooth
    while True:
        bt_on_new, bt_touch_new, bt_link_new = bt_driver.info()
        if bt_on_new != bt_on:
            print("Bluetooth State: ", ("On" if bt_on_new == 1 else "Off"))
            digitalWrite(LED1, 0 if bt_on_new==1 else 1)
            bt_on = bt_on_new
        if bt_touch_new != bt_touch:
            print("Capacitive Button Active: ", ("Left" if bt_touch_new == 0 else "Right"))
            bt_touch = bt_touch_new
        if bt_link_new != bt_link:
            print("Link State: ", ("Connected" if bt_link_new == 1 else "Disconnected"))
            bt_link = bt_link_new
        sleep(500)

try:
    # Configurer la puce ble
    print("init...")
    bt_driver = kw40z.KW40Z_HEXI_APP(SERIAL1)
    print("start")
    # Démarrer la communication série avec le KW40Z
    # Vérifier l'état du KW40Z:
    # Vérifier si le Bluetooth est actif
    # Vérifier s'il y a des connexions avec d'autres appareils
    # Vérifier quel bouton est actif
    bt_driver.start()
    # Attendre le démarrage de la puce ble
    sleep(1000)
    # Démarrer thread pour vérifier le statut
    thread(check_status)
    # Attacher la fonction de rappel au bouton gauche
    bt_driver.attach_button_left(toggle_ble)
    bt_driver.attach_passkey(print_paircode)
except Exception as e:
    print("error1:", e)

# Détecter et envoyer les données de capteurs
level = 0
while True:
    try:
        print("...")
        # Mise à jour les données des capteurs Hexiwear de la puce KW40Z
        # Batterie - met à jour la valeur du niveau de la batterie en pourcentage
        bt_driver.upd_sensors(battery=level)
        # Tous les 5000 incréments jusqu'au 100
        level += 1
        if level > 100:
            level = 0
        sleep(5000)
    except Exception as e:
        print("error2", e)
        sleep(1000)


#DD1310 Tilda, Matthew Norström 19970313-6052, Linus Ekelöf 19960923-2054
from bfs import svenska_bintree, gamla_bintree, makewords
from LinkedQFile import LinkedQ

#Skapar alla barn till startordet som skickas in
def makechildren(startord,slutord, gamla, svenska, q):
    gamla.put(startord)
    words = makewords(startord)
    for word in words:
        if word == slutord:
            return True
        elif word != startord and word in svenska and word not in gamla:
            gamla.put(word)
            q.enqueue(word)

def main():

    startord = "söt"
    slutord = "sur"
    svenska = svenska_bintree()
    gamla = gamla_bintree()
    q = LinkedQ()
    q.enqueue(startord)

    while not q.isEmpty():
        nod = q.dequeue()
        path_found = makechildren(nod, slutord, gamla, svenska,q)
        if path_found:
            print("Det finns en väg till:", slutord)
            break
    if not path_found:
        print("Det finns ingen väg till", slutord)

if __name__ == main():
    main()


from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.http import HttpResponse
from django.views.generic.base import View
import json, re, requests
from .models import Source
from urllib.parse import quote
from lxml import etree

# Create your views here.

headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "cookie": "__cfduid=d1240b10758285a08a37f9ed80f2c4fe21560276635; UM_distinctid=16b47bc0d183a2-0e9cf74bce3f78-9333061-1fa400-16b47bc0d19640; bookid=134128; chapterid=6815295; chaptername=%25u5E8F%253A%25u795E%25u77F3%25u964D%2520%25u5929%25u5730%25u846C; CNZZDATA1257156613=700615596-1560271565-%7C1560276965",
    "upgrade-insecure-requests": "1",
    "cache-control": "max-age=0",
    "accept-language": "zh-CN,zh;q=0.9",
    "accept-encoding": "gzip, deflate, br",

}

def findHtmlCode(getfindpage, getfconstant):  # html编码
    """

    :param getfindpage: 搜索页
    :param getfconstant: 全局常量
    :return:
    """
    encoding = getfindpage.get("findhtmlcode", None)
    if encoding == None:
        encoding = getfconstant.get("htmlcode", "utf-8")
    return encoding

def listToStr(l):  # xpath转str
    try:
        text = l[0].xpath('string(.)').strip()
    except Exception:
        text = l[0]

    # print(["listToStr",text])
    return text

def by_book_find(request, url, getfindpage, getfconstant, adddict, findFrist=None):
    # 有findFrist则使用findFrist 不用再次请求网页
    if findFrist:
        text = findFrist
    else:
        html = requests.get(url=url, headers=headers, verify=getfconstant.get("requests_verify", True), timeout=10)
        html.encoding = findHtmlCode(getfindpage, getfconstant)
        text = html.text

    dom_tree = etree.HTML(text)
    xpath_root = dom_tree.xpath(getfindpage.get("book_xpath_root"))
    print(len(xpath_root))
    print(["by_book_find-搜索页URL","第一次搜索" if findFrist else url])
    # print(getfindpage.get("book_xpath_root"))
    # print(html.text)
    book_lists = [adddict]  # {'sub_page':sub_page}
    for mxpath in xpath_root:
        try:
            book_url = mxpath.xpath(getfindpage.get('book_url'))[0]  # 小说URL
            # print(book_url)
            book_title = listToStr(mxpath.xpath(getfindpage.get('book_title')))  # 小说名
            # print(book_title)
            book_author = listToStr(mxpath.xpath(getfindpage.get('book_author')))  # 小说作者
            # print(book_author)
            try:
                book_img = mxpath.xpath(getfindpage.get('book_img'))[0]  # 小说图片
            except Exception:
                book_img="/static/img/nocover.jpg"
            try:
                book_brief = listToStr(mxpath.xpath(getfindpage.get('book_brief')))  # 小说简介
            except Exception:
                book_brief = "<i style='color:red'>暂无小说简介</i>"

            book_lists.append(
                {'book_img': book_img, 'book_url': book_url, 'book_title': book_title, 'book_author': book_author,
                 'book_brief': book_brief})

        except Exception as e:
            print(['by_book_find', e.args])

    response_json = json.dumps({str(a): b for a, b in enumerate(book_lists)})

    return response_json

class Mainpage(View):
    def get(self, request):
        agent = request.META.get('HTTP_USER_AGENT', None)
        is_windows = "1" if "Windows" in agent else "0"

        return render(request, 'books/mainpage.html', {"is_windows": is_windows})

    def post(self, request):
        mark = request.POST.get('mark', 'no')
        sources = []
        if mark == "loadsource": #加载书源
            db = Source.objects.all()
            for i in db:
                l = {"describe": i.describe, "id": i.id}
                sources.append(l)
            rejson = json.dumps({str(a): b for a, b in enumerate(sources)})

            return HttpResponse(rejson)
        elif mark == "add_script":  # 加载书源定义的js脚本
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfindpage = eval(r"{0}".format(fdb.findpage))
            getchapterpage = eval(r"{0}".format(fdb.chapterpage))
            book_url_js = "<script>\nfunction data_url_js(book_url){0}\n{1}\n{2}\n</script>".format("{",
                                                                                getfindpage.get(
                                                                                "book_url_js"),
                                                                                "}")
            chapter_url_js = "<script>\nfunction chapter_url_js(chapter_url,book_url){0}\n{1}\n{2}\n</script>".format(
                "{", getchapterpage.get("chapter_url_js"), "}")
            return HttpResponse(
                json.dumps({"book_url_js": mark_safe(book_url_js), "chapter_url_js": mark_safe(chapter_url_js)}))

        elif mark == "find":  # 搜索
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfindpage = eval(r"{0}".format(fdb.findpage))
            getfconstant = eval(r"{0}".format(fdb.constant))
            title = quote(request.POST.get('title', None).encode(getfconstant.get("urlcode", "utf-8")))
            find_url = getfindpage['furl'] + title
            print(["find-搜索的URL", find_url])
            html = requests.get(url=find_url, headers=headers, verify=getfconstant.get("requests_verify", True),
                                timeout=10)
            # 指定html的编码
            html.encoding = findHtmlCode(getfindpage, getfconstant)
            dom_tree = etree.HTML(html.text)
            sub_url = getfindpage.get("sub_url", None).replace(r"*title*", title)
            sub_page = getfindpage.get("sub_page", None)
            sub_page_split = eval(getfindpage.get("sub_page_split", None))

            # 解析 搜索的小说页数
            if sub_page:
                try:
                    sub_page = dom_tree.xpath(sub_page)[0]
                    sub_page = re.split(sub_page_split[0], sub_page)[int(sub_page_split[1])]
                except Exception as e:
                    print(['find-页码解析错误', e.args])
                    sub_page = "1"
            else:
                sub_page = "1"
            print(["sub_page-小说页码", sub_page])

            response_json = by_book_find(request, None, getfindpage, getfconstant,
                                         {'sub_page': sub_page, "sub_url": sub_url}, findFrist=html.text)

            return HttpResponse(response_json)

        elif mark == "source":  # 保存源
            return HttpResponse(json.dumps({"m":"不开放此功能"}))  # 前端写书源保存到数据库，注释这行代码即可使用。
            describe = request.POST.get('describe', None)
            constant = request.POST.get('constant', None)
            findpage = request.POST.get('findpage', None)
            chapterpage = request.POST.get('chapterpage', None)
            contentpage = request.POST.get('contentpage', None)
            print(['-------------', findpage, chapterpage, contentpage])
            try:
                Source.objects.create(describe=describe, constant=constant, findpage=findpage, chapterpage=chapterpage,
                                      contentpage=contentpage).save()
            except Exception as e:
                rejson = {'m': str(e.args)}
            else:
                rejson = {'m': '保存成功'}
            return HttpResponse(json.dumps(rejson))

        elif mark == "up_page":  # 到上一页（搜索页）
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfindpage = eval(r"{0}".format(fdb.findpage))
            getfconstant = eval(r"{0}".format(fdb.constant))
            current_page = request.POST.get("current_page", None)
            data_sub_url = request.POST.get("data_sub_url", None)
            sub_url = '{0}{1}'.format(data_sub_url, int(current_page) - 1)
            response_json = by_book_find(request, sub_url, getfindpage, getfconstant,
                                         {'current_page': str(int(current_page) - 1)})

            return HttpResponse(response_json)

        elif mark == "load_page":  # 到下一页（搜索页）
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfindpage = eval(r"{0}".format(fdb.findpage))
            getfconstant = eval(r"{0}".format(fdb.constant))
            current_page = request.POST.get("current_page", None)
            data_sub_url = request.POST.get("data_sub_url", None)
            sub_url = '{0}{1}'.format(data_sub_url, int(current_page) + 1)

            response_json = by_book_find(request, sub_url, getfindpage, getfconstant,
                                         {'current_page': str(int(current_page) + 1)})

            return HttpResponse(response_json)

        elif mark == "jump_page":  # 跳到某一页（搜索页）
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfindpage = eval(r"{0}".format(fdb.findpage))
            getfconstant = eval(r"{0}".format(fdb.constant))
            jump_page = request.POST.get("jump_page", None)
            data_sub_url = request.POST.get("data_sub_url", None)
            sub_url = '{0}{1}'.format(data_sub_url, int(jump_page))

            response_json = by_book_find(request, sub_url, getfindpage, getfconstant,
                                         {'current_page': jump_page})

            return HttpResponse(response_json)

        elif mark == "book_urls":  # 到章节页
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfconstant = eval(r"{0}".format(fdb.constant))
            getchapterpage = eval(r"{0}".format(fdb.chapterpage))
            book_url = request.POST.get("book_url")

            if "http" not in book_url:
                book_url = getfconstant.get("host") + book_url
            print(["book_url", book_url])

            html = requests.get(book_url, headers=headers, verify=getfconstant.get("requests_verify", True))
            html.encoding = getfconstant.get("htmlcode", "utf-8")
            dom_tree = etree.HTML(html.text)

            # print(html.text)

            chapter_xpath_root = dom_tree.xpath(getchapterpage.get("chapter_xpath_root"))
            print(len(chapter_xpath_root))
            chapter_list = []
            for mchapter in chapter_xpath_root:
                chapter_url = listToStr(mchapter.xpath(getchapterpage.get("chapter_url")))
                chapter_title = listToStr(mchapter.xpath(getchapterpage.get("chapter_title")))
                chapter_list.append({"chapter_url": chapter_url, "chapter_title": chapter_title})

            response_json = json.dumps({str(a): b for a, b in enumerate(chapter_list)})
            return HttpResponse(json.dumps(response_json))

        elif mark == "content_url":  # 到正文页
            fdb = Source.objects.get(id=request.POST.get("selectid"))
            getfconstant = eval(r"{0}".format(fdb.constant))
            getcontent = eval(r"{0}".format(fdb.contentpage))
            content_url = request.POST.get("content_url")

            if "http" not in content_url:
                content_url = getfconstant.get("host") + content_url

            print(["正文url", content_url])

            html = requests.get(content_url, headers=headers, verify=getfconstant.get("requests_verify", True))
            html.encoding = getfconstant.get("htmlcode", "utf-8")
            dom_tree = etree.HTML(html.text)
            content = dom_tree.xpath(getcontent.get("content"))[0]
            content = etree.tostring(content, method='html')
            # print(content_url)

            return HttpResponse(content)
        else:
            return HttpResponse(json.dumps({"Error": " 你提交的mark参数不对！"}))


#!/usr/bin/python3
""" holds class State"""
from models.state import State
from flask import jsonify, abort, request, Response, make_response
from models import storage
from api.v1.views import app_views

@app_views.route('/states',
                 methods=['GET'],
                 strict_slashes=False,
                 defaults={'state_id': 0})
@app_views.route('/states/<state_id>', methods=['GET'], strict_slashes=False)
def get_states(state_id):
    dic = storage.all(State)
    ids = "State." + str(state_id)
    if (state_id == 0):
        state_list = []
        for k, v in dic.items():
            state_list.append(v.to_dict())
        return jsonify(state_list)
    elif (ids not in dic.keys()):
        abort(404)
    else:
        return jsonify(dic[ids].to_dict())

@app_views.route('/states/<state_id>',
                 methods=['DELETE'],
                 strict_slashes=False)
def delete_states(state_id):
    dic = storage.all(State)
    ids = "State." + str(state_id)
    if (ids not in dic.keys()):
        abort(404)
    else:
        storage.delete(dic[ids])
        storage.save()
        return jsonify({})

@app_views.route('/states', methods=['POST'], strict_slashes=False)
def post_states():
    try:
        json = request.get_json()
    except:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    if json is None:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    if ('name' not in json.keys()):
        return make_response(jsonify({'error': "Missing name"}), 400)
    obj = State(**json)
    storage.new(obj)
    storage.save()
    return make_response(jsonify(obj.to_dict()), 201)

@app_views.route('/states/<state_id>', methods=['PUT'], strict_slashes=False)
def update_states(state_id):
    try:
        json = request.get_json()
    except:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    if json is None:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    dic = storage.all(State)
    ids = "State." + str(state_id)
    if (ids not in dic.keys()):
        abort(404)
    else:
        for k, v in json.items():
            if (k != 'id' and k != 'created_at' and k != "updated_at"):
                setattr(dic[ids], k, v)
        storage.save()
        return make_response(jsonify(dic[ids].to_dict()), 200)


import speech_recognition as sr
import subprocess
while True:
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("I'm listening . . . ")
        audio = r.listen(source)
        try:
            text = r.recognize_google(audio)
            print(format(text))
            if(text == "stop"):
                break
            else:
                if text == "open downloads" or text == "see my downloads":
                    subprocess.check_output("Downloads.bat")
                    break

                elif text == "open Torrent folder" or text == "open my movies folder":
                    subprocess.check_output("BiglyBt.bat")
                    break

                elif text == "open my project" or text == "project folder":
                    subprocess.check_output("Project.bat")
                    break

                else:
                    print("Not match with given instruction")

        except:
            print("I can't recognize you voice, Sir")


# @version: 1.0  date: 05/06/2015 by Sidney Barthe
# @author: robin.scheibler@epfl.ch, ivan.dokmanic@epfl.ch, sidney.barthe@epfl.ch
# @copyright: EPFL-IC-LCAV 2015

from unittest import TestCase
import numpy as np

import pyroomacoustics as pra

fs = 8000
t0 = 1./(fs*np.pi*1e-2)
absorption = 0.90
max_order_sim = 2
sigma2_n = 5e-7

dimension = [4, 4]
room1 = pra.Room.shoeBox2D(
    [0, 0],
    dimension,
    absorption,
    fs,
    t0,
    max_order_sim,
    sigma2_n)

room1.addSource([2, 2], None, 0)

class TestVisibilityShoeBox2D(TestCase):

    def test_visibility_middle(self):
        computed = room1.checkVisibilityForAllImages(room1.sources[0], np.array([2, 2]))
        expected = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
        self.assertTrue(all(computed == expected))

    def test_visibility_outside(self):
        computed = room1.checkVisibilityForAllImages(room1.sources[0], np.array([5, 5]))
        expected = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        self.assertTrue(all(computed == expected))

    def test_visibility_upperRight(self):
        computed = room1.checkVisibilityForAllImages(room1.sources[0], np.array([3, 3]))
        expected = [1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1]
        self.assertTrue(all(computed == expected))

    def test_visibility_lowerLeft(self):
        computed = room1.checkVisibilityForAllImages(room1.sources[0], np.array([1, 1]))
        expected = [1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1]
        self.assertTrue(all(computed == expected))

    def test_visibility_lowMiddle(self):
        computed = room1.checkVisibilityForAllImages(room1.sources[0], np.array([2, 1]))
        expected = [1,1,1,1,1,1,0,1,0,1,1,1,1,0,0,1,1]
        self.assertTrue(all(computed == expected))


# Windows uses \ for directory separators while *nix uses /
# Root for windows is C:\, *nix is /
# easy to handle both cases, must import os
# then run os.path.join()
# windows will be path\path\path
# *nix will be path/path/path
# depends on which system it is run on
import os
print(os.path.join("usr", "bin", "spam"))

# Current working directory os.getcwd() returns current working directory
# we can change working dir by using os.chdir("path")
print(os.getcwd())
# os.chdir("C:\\Users") would change to C:\Users
# this will return error if directory does not exist.. need to handle with try

# we can create new directories
# os.makedirs("C:\\Waffles\\Chocolate\\Syrup")
# the above will create the Waffles, and the Chocolate, and the Syrup dirs

'''
    open() to return a file object
    read() or write() on the file object
    close() to close the file object
'''

# read will take entire contents into a string
helloFile = open('Hello.txt')
helloContent = helloFile.read()
print(helloContent)
helloFile.close()

# readlines() will return a list of strings
sonnetFile = open('sonnet.txt')
sonnet = sonnetFile.readlines()
print(sonnet)  # prints out the list of lines
print(sonnet[0])  # prints out just the first line
sonnetFile.close()

# write to a file, pass in 'w' for write mode
# or 'a' for append mode
baconFile = open("bacon.txt", 'w')
baconFile.write("Hello World!\n")
baconFile.close()  # the file should be closed before using to read..

baconFile = open("bacon.txt", 'a')
baconFile.write("Bacon is not a veggie\n")
baconFile.close()

baconFile = open("bacon.txt")
bacon = baconFile.read()
baconFile.close()
print(bacon)

# saving variables to binary files with shelve
import shelve

shelfFile = shelve.open("myData")
cats = ["Brannigan", "Pookie", "X_X"]
shelfFile["cats"] = cats  # create the list in the file, "cats" is the key like a dict
shelfFile.close()

shelfFile = shelve.open("myData")
print(type(shelfFile))  # prints out <class 'shelve.DbfilenameShelf'>
print(shelfFile["cats"])  # prints out the list of cats
shelfFile.close()

# shelves have keys and values just like dicts
shelfFile = shelve.open("myData")
print(list(shelfFile.keys()))  # prints out the key ['cats']
print(list(shelfFile.values()))  # prints out the values of the key ['cats']

'''
    Plaintext is great for when data from programs is needed to edited
    But if not, it is best to use shelve to store the data in binary
'''

import pprint

# pretty print (pprint) can be used to save a dict to file, then use it as an import
# to use later

cats = [{"name": "chester", "desc": "chubby"}, {"name": "pooky", "desc": "fluffy"}]
print(pprint.pformat(cats))

# create a file object to save dict to
fileObj = open('myCats.py', 'w')
# write to the file.  set it up as to actually be a variable cats = [{'key': 'val'}]
fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
fileObj.close()

# import myCats.py, then can access the variable created with pprint
import myCats
print(myCats.cats[0]['name'])  # access first list item, then pass in 'name key


# importation de librairie nécessaires
import urllib.request
import cv2
import numpy as np
import os

# fonction qui enregistre les images et les numérotes
def enregistrement_image():
    neg_images_link = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n02123597'
    neg_image_urls = urllib.request.urlopen(neg_images_link).read().decode()
    pic_num = 1

    if not os.path.exists('neg'):
        os.makedirs('neg')

    for i in neg_image_urls.split('\n'):
        try:
            print(i)
            urllib.request.urlretrieve(i, "neg/" + str(pic_num) + ".jpg")
            img = cv2.imread("neg/" + str(pic_num) + ".jpg", cv2.IMREAD_GRAYSCALE)
            # les images négatives doivent être plus grande que les positives pour qu'on puisse placé les positives

            # dessus

            resized_image = cv2.resize(img, (100, 100))

            cv2.imwrite("neg/" + str(pic_num) + ".jpg", resized_image)

            pic_num += 1

        except Exception as e:
            print(str(e))

enregistrement_image()


# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/battle/event/consumables_panel.py
from gui.impl import backport
from gui.impl.gen import R
from gui.shared.formatters import text_styles
from gui.shared.gui_items import getKpiValueString
from gui.Scaleform.daapi.view.battle.shared.consumables_panel import ConsumablesPanel, TOOLTIP_FORMAT

class EventConsumablesPanel(ConsumablesPanel):
    _AMMO_START_IDX = 0
    _AMMO_END_IDX = 0
    _EQUIPMENT_START_IDX = 1
    _EQUIPMENT_END_IDX = 6
    _ORDERS_START_IDX = 8
    _ORDERS_END_IDX = 8

    def _buildEquipmentSlotTooltipText(self, item):
        descriptor = item.getDescriptor()
        reloadingTime = descriptor.cooldownSeconds
        body = descriptor.description
        if not {'repairkit', 'medkit'} & descriptor.tags:
            additionalStr = self.__getAdditionalTooltipBodyString(item)
            body = ''.join((body, additionalStr))
        if reloadingTime > 0:
            tooltipStr = R.strings.ingame_gui.consumables_panel.equipment.cooldownSeconds()
            cooldownSeconds = str(int(reloadingTime))
            paramsString = backport.text(tooltipStr, cooldownSeconds=cooldownSeconds)
            body = '\n\n'.join((body, paramsString))
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString, body)
        return toolTip

    def __getAdditionalTooltipBodyString(self, item):
        attribs = R.strings.artefacts.dyn(item.getDescriptor().name)
        if not attribs:
            return ''
        resultStr = ''
        emptyStr = backport.text(R.strings.artefacts.empty())
        kpiArgs = {kpi.name:getKpiValueString(kpi, kpi.value) for kpi in item.getDescriptor().kpi}
        attributes = ('onUse', 'always', 'restriction')
        for atr in attributes:
            strText = backport.text(getattr(attribs, atr)(), **kpiArgs)
            if strText and strText != emptyStr:
                eq = R.strings.tooltips.equipment
                description = text_styles.middleTitle(backport.text(getattr(eq, atr)()))
                block = '\n'.join((description, strText))
                resultStr = '\n\n'.join((resultStr, block))

        return resultStr


#!python

import random
import time
from tries import Trie

def get_words(filename):
    with open(filename, 'r') as f:
        words_list = f.read().split()

    return words_list

def binarysearch(list_, item, left=None, right=None):
    if left is None and right is None:
        left = 0
        right = len(list_) - 1
    middle = (right + left) // 2
    item_length = len(item)
    middle_item = list_[middle]
    if middle_item[:item_length].lower() == item.lower():
        return find_all_words(list_, item, middle)
    elif middle_item[:item_length].lower() < item.lower():
        return binarysearch(list_, item, middle + 1, right)
    elif middle_item[:item_length].lower() > item.lower():
        return binarysearch(list_, item, left, middle - 1)
    elif left > right:
        return None

def find_all_words(list_, item, middle):
    predicted_words = [list_[middle]]
    item_length = len(item)
    left_match = True
    right_match = True
    left_index = middle
    right_index = middle
    while left_match:
        left_index -= 1
        if left_index < 0:
            left_match = False
        else:
            word = list_[left_index]
            if word[:item_length].lower() == item.lower():
                predicted_words.append(word)
            else:
                left_match = False
    while right_match:
        right_index += 1
        if right_index >= len(list_):
            right_match = False
        else:
            word = list_[right_index]
            if word[:item_length].lower() == item.lower():
                predicted_words.append(word)
            else:
                right_match = False
    return predicted_words

def insert_word(words_list):
    trie = Trie()
    for word in words_list:
        trie.insert(word)
    return trie

def find_prefix(trie, prefix):
    node = trie.root
    for letter in prefix:
        node = node.next[letter]
    return node.next

def find_words(nodes, words=[]):
    if nodes != {}:
        for letter in nodes:
            if nodes[letter].data[1]:
                words.append(nodes[letter].data[0])

            words = find_words(nodes[letter].next, words)
        return words
    else:
        return words

def find_all_words_with_trie(trie, prefix):
    nodes = find_prefix(trie, prefix)
    all_words = find_words(nodes)
    return all_words

def autocomplete(words_list, prefix=""):
    # prefix_length = len(prefix)
    # predicted_words = []
    # for word in words_list:
    #     # if word.startswith(prefix):
    #     if word[:prefix_length] == prefix:
    #         predicted_words.append(word)
    # predicted_words = binarysearch(words_list, prefix)
    predicted_words = find_all_words_with_trie(words_list, prefix)
    return predicted_words

def benchmark(all_prefixes):
    t1 = time.time()
    filename = "/usr/share/dict/words"
    words_list = get_words(filename)
    t2 = time.time()
    print('Took {} seconds to create list'.format(t2-t1))
    trie = insert_word(words_list)
    t3 = time.time()
    print('Took {} seconds to create trie'.format(t3-t2))
    for prefix in all_prefixes:
        # print(autocomplete(words_list, prefix))
        # autocomplete(words_list, prefix)
        autocomplete(trie, prefix)
    t4 = time.time()
    return t4 - t3

def main():
    all_words = get_words('/usr/share/dict/words')
    all_prefixes = set([word[:len(word)//2] for word in all_words])
    time = benchmark(all_prefixes)
    print('Took {} seconds to benchmark {} prefixes on {} words'.format(time, len(all_prefixes), len(all_words)))
    # Took 3.200831890106201 seconds to benchmark 71244 prefixes on 235886 words
    # import sys
    # filename = "/usr/share/dict/words"
    # words_list = get_words(filename)
    # prefix = sys.argv[1]
    # words = autocomplete(words_list, prefix)
    # print(words)

if __name__ == '__main__':
    main()


from allhtml import settings
from db import handlers
import os

def parse_parts(content):
	parts = {}
	name = ''
	value = ''
	for line in content.split('\n'):
		line = line.strip()
		if len(line) > 0 and line[0] == '[':
			if len(name) > 0:
				parts[name] = value[:-1].strip()
				value = ''
			name = line[1:line.find(']')]
			continue
		value += line + '\n'
	parts[name] = value[:-1].strip()
	return parts

def parse(content):
	parts = parse_parts(content)
	result = {}
	for name in parts:
		result[name] = handle(name, parts[name])
	return result

def handle(name, content):
	if name in handlers.__dir__():
		return getattr(handlers, name)(content.strip())
	else:
		return content

def get_tags():
	tags = []
	for filename in os.listdir(settings.BASE_DIR + '/db/tags'):
		f = open(settings.BASE_DIR + '/db/tags/' + filename)
		tags.append(parse(f.read()))
		f.close()
	return tags

def get_tag(name):
	filename = settings.BASE_DIR + '/db/tags/' + name + '.td'
	f = open(filename)
	result = parse(f.read())
	f.close()
	return result


import tensorflow as tf
import numpy as np

class RNNTextGen:
    def __init__(self, text, seq_len, embedding_dims=30, rnn_size=256, n_layers=2, grad_clip=5.,
                 beam_width=3, sess=tf.Session()):
        self.sess = sess
        self.text = text
        self.seq_len = seq_len
        self.embedding_dims = embedding_dims
        self.rnn_size = rnn_size
        self.n_layers = n_layers
        self.grad_clip = grad_clip
        self.beam_width = beam_width
        self.preprocessing()
        self.build_graph()
    # end constructor

    def build_graph(self):
        self.add_input_layer()
        self.add_decoder()
        self.add_backward_path()
    # end method

    def add_input_layer(self):
        self.sequence = tf.placeholder(tf.int32, [None, None])
        self.sequence_length = tf.placeholder(tf.int32, [None])
        self._batch_size = tf.shape(self.sequence)[0]
        self.gen_seq_length = tf.placeholder(tf.int32, [])
    # end method

    def add_decoder(self):
        with tf.variable_scope('decode'):
            decoder_embedding = tf.get_variable('decoder_embedding', [self.vocab_size, self.embedding_dims],
                                                 tf.float32, tf.random_uniform_initializer(-1.0, 1.0))
            decoder_cell = tf.nn.rnn_cell.MultiRNNCell([self._rnn_cell() for _ in range(self.n_layers)])

            helper = tf.contrib.seq2seq.TrainingHelper(
                inputs = tf.nn.embedding_lookup(decoder_embedding, self._decoder_input()),
                sequence_length = self.sequence_length+1)
            decoder = tf.contrib.seq2seq.BasicDecoder(
                cell = decoder_cell,
                helper = helper,
                initial_state = decoder_cell.zero_state(self._batch_size, tf.float32),
                output_layer = tf.layers.Dense(self.vocab_size))
            decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
                decoder = decoder)
            self.logits = decoder_output.rnn_output

        with tf.variable_scope('decode', reuse=True):
            decoder = tf.contrib.seq2seq.BeamSearchDecoder(
                cell = tf.nn.rnn_cell.MultiRNNCell(
                    [self._rnn_cell(reuse=True) for _ in range(self.n_layers)]),
                embedding = tf.get_variable('decoder_embedding'),
                start_tokens = tf.tile(tf.constant(
                    [self.char2idx['<start>']], dtype=tf.int32), [self._batch_size]),
                end_token = self.char2idx['<end>'],
                initial_state = tf.contrib.seq2seq.tile_batch(
                    decoder_cell.zero_state(self._batch_size,tf.float32), self.beam_width),
                beam_width = self.beam_width,
                output_layer = tf.layers.Dense(self.vocab_size, _reuse=True))
            decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
                decoder = decoder,
                maximum_iterations = self.gen_seq_length)
            self.predicted_ids = decoder_output.predicted_ids[:, :, 0]
    # end method

    def add_backward_path(self):
        targets = self._decoder_output()
        self.loss = tf.reduce_mean(tf.contrib.seq2seq.sequence_loss(
            logits = self.logits,
            targets = targets,
            weights = tf.to_float(tf.ones_like(targets)),
            average_across_timesteps = True,
            average_across_batch = True))
        # gradient clipping
        params = tf.trainable_variables()
        gradients = tf.gradients(self.loss, params)
        clipped_gradients, _ = tf.clip_by_global_norm(gradients, self.grad_clip)
        self.train_op = tf.train.AdamOptimizer().apply_gradients(zip(clipped_gradients, params))
    # end method

    def preprocessing(self):
        text = self.text
        chars = set(text)
        self.char2idx = {c: i+2 for i, c in enumerate(chars)}
        self.char2idx['<start>'] = 0
        self.char2idx['<end>'] = 1
        self.vocab_size = len(self.char2idx)
        print('Vocabulary size:', self.vocab_size)
        self.idx2char = {i: c for c, i in self.char2idx.items()}
        self.idx2char[-1] = '-1'
        self.indexed = np.array([self.char2idx[char] for char in list(text)])
    # end method

    def next_batch(self, batch_size, text_iter_step):
        window = self.seq_len * batch_size
        for i in range(0, len(self.indexed)-window-1, text_iter_step):
            yield self.indexed[i : i+window].reshape(-1, self.seq_len)
    # end method

    def fit(self, text_iter_step=25, n_epoch=1, batch_size=128):
        n_batch = (len(self.indexed) - self.seq_len*batch_size - 1) // text_iter_step
        self.sess.run(tf.global_variables_initializer()) # initialize all variables

        for epoch in range(n_epoch):
            for local_step, seq_batch in enumerate(self.next_batch(batch_size, text_iter_step)):
                _, train_loss = self.sess.run([self.train_op, self.loss],
                                              {self.sequence: seq_batch,
                                               self.sequence_length: [self.seq_len]*len(seq_batch)})
                if local_step % 10 == 0:
                    print ('Epoch %d/%d | Batch %d/%d | train loss: %.4f' %
                          (epoch+1, n_epoch, local_step, n_batch, train_loss))
                if local_step % 100 == 0:
                    self.decode()
    # end method

    def decode(self):
        predicted_ids = self.sess.run(self.predicted_ids,
                                     {self._batch_size: 1,
                                      self.gen_seq_length: self.seq_len})[0]
        print('D: '+''.join([self.idx2char[idx] for idx in predicted_ids]), end='\n\n')
    # end method

    def _decoder_output(self):
        _end = tf.fill([self._batch_size, 1], self.char2idx['<end>'])
        return tf.concat([self.sequence, _end], 1)
    # end method

    def _decoder_input(self):
        _start = tf.fill([self._batch_size, 1], self.char2idx['<start>'])
        return tf.concat([_start, self.sequence], 1)
    # end method

    def _rnn_cell(self, reuse=False):
        return tf.nn.rnn_cell.GRUCell(self.rnn_size,
            kernel_initializer=tf.orthogonal_initializer(), reuse=reuse)
    # end method
# end class


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer

#Carregando a base de dados de treino e teste
treino = pd.read_csv('train.csv')
teste = pd.read_csv('test.csv')

#Array de colunas que nao existem no teste
colunasInexistentesTest = []

#Buscando as colunas que existem no treino mais nao existem no teste
for coluna in treino.columns:
    result = list(filter(lambda x:  x==coluna ,teste.columns))
    if not result:
        colunasInexistentesTest.append(coluna)

#Linha da nota de matematica
del(colunasInexistentesTest[69])

#Plotagem dos dados e suas correlacoes
corr = treino.corr()
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(corr,cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,len(treino.columns),1)
ax.set_xticks(ticks)
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(treino.columns)
ax.set_yticklabels(treino.columns)
plt.show()

#Apagando as colunas de treino que nao existem no teste e outras que nao tem correlacao com a target
treino = treino.drop(colunasInexistentesTest, axis=1)
colunasNaoImportantes = ["NU_INSCRICAO","SG_UF_RESIDENCIA", "CO_PROVA_CN", "CO_PROVA_CH",
                         "CO_PROVA_LC", "CO_PROVA_MT", "Q027",  "CO_UF_RESIDENCIA", "NU_IDADE",
                         "TP_COR_RACA", "TP_NACIONALIDADE", "TP_ST_CONCLUSAO", "TP_ANO_CONCLUIU",
                         "TP_ESCOLA", "TP_ENSINO", "TP_DEPENDENCIA_ADM_ESC", "IN_BAIXA_VISAO",
                         "IN_CEGUEIRA", "IN_SURDEZ", "IN_DISLEXIA", "IN_DISCALCULIA", "IN_SABATISTA",
                         "IN_GESTANTE","IN_IDOSO", "TP_PRESENCA_CN", "TP_PRESENCA_CH", "TP_PRESENCA_LC",
                         "TP_LINGUA", "TP_STATUS_REDACAO"]
for k in colunasNaoImportantes:
    treino = treino.drop(k, axis=1)
    teste = teste.drop(k, axis=1)

#Remocao dos valores faltantes
#teste
row = list(teste.isnull().any(axis=1))
idxx = [i for i, j in enumerate(row) if j is True]
teste = teste.drop(idxx)

#Nvalores faltantes, substituindo por -1
imputer = SimpleImputer(strategy='constant', fill_value = -1)
treino = imputer.fit_transform(treino)
treino = pd.DataFrame(data = treino)

#Transformando colunas categoricas em numericas
ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [0, 12,13,14,15,16,17,18])], remainder='passthrough')
treino = ct.fit_transform(treino)
treino = pd.DataFrame(data = treino)
treino.rename(columns = {54: "NU_MT"}, inplace=True)

ct2 = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [0, 11,12,13,14,15,16,17])], remainder='passthrough')
teste = ct2.fit_transform(teste)
teste = pd.DataFrame(data = teste)

#Parametrizacao
copia = treino['NU_MT']
treino["NU_NOTA_MT"] = copia
treino = treino.drop('NU_MT', axis=1)
base = treino
_, a = base.shape
atributos = base.iloc[:, 0:a - 1].values
classe = base.iloc[:, a - 1].values

#Faz o treinamento com regressao linear
regressor = LinearRegression()
regressor.fit(atributos, classe)

#Predicao do arquivo de teste
resultados = regressor.predict(teste)