Пример #1
0
    def updateCanvas(self, *args):
        global MIN_MARGIN
        carViewSize = [
            Window.width * Variables().getCarViewSizeHint()[0],
            Window.height * Variables().getCarViewSizeHint()[1]
        ]
        carSize = [carViewSize[0] / 7, carViewSize[1] / 4]

        MAX_DIST_SIDE = 150  #cm
        MAX_DIST_FRONT = 100  #cm
        multiplierSide = (float(carViewSize[0]) - float(carViewSize[0]) / 2 -
                          float(carSize[0]) / 2 - 10) / MAX_DIST_SIDE
        multiplierFront = (float(carViewSize[1]) - float(carViewSize[1]) / 2 -
                           float(carSize[1]) / 2 - 10) / MAX_DIST_FRONT

        with layout.canvas:
            layout.canvas.clear()
            car = Rectangle(source='images/car.jpg',
                            pos=(carViewSize[0] / 2 - carSize[0] / 2,
                                 carViewSize[1] / 2 - carSize[1] / 2),
                            size=carSize)

            leftDist = float(
                vehicle.vehicleList.getLDist(
                    vehicle.vehicleList.selectedVehicle))
            rightDist = float(
                vehicle.vehicleList.getRDist(
                    vehicle.vehicleList.selectedVehicle))
            frontDist = float(
                vehicle.vehicleList.getFDist(
                    vehicle.vehicleList.selectedVehicle))

            leftMargin = carViewSize[0] / 2 - carSize[
                0] / 2 - leftDist * multiplierSide
            rightMargin = carViewSize[0] / 2 + carSize[
                0] / 2 + rightDist * multiplierSide
            frontMargin = carViewSize[1] / 2 + carSize[
                1] / 2 + frontDist * multiplierFront
            if leftMargin < MIN_MARGIN:
                leftMargin = MIN_MARGIN
            # Create line to left object
            Line(points=[leftMargin, 0, leftMargin, frontMargin], width=2)

            # Create line to right object
            Line(points=[rightMargin, 0, rightMargin, frontMargin], width=2)

            # Create line to front object
            Line(points=[leftMargin, frontMargin, rightMargin, frontMargin],
                 width=2)
Пример #2
0
def buttonDisableBoiler(channel):
    module_logger.info('Button Disable Boiler pressed, channel %s' % channel)
    boilerState = Variables().readVariables(['BoilerEnabled'])
    if boilerState == 1:
        boilerState = 0
    else:
        boilerState = 1
    Variables().writeVariable([['BoilerEnabled', boilerState]])

    # Set Boiler State
    if boilerState:
        module_logger.debug('GPIO boiler on')
        GPIO.output(B_OFF, GPIO.LOW)
    else:
        module_logger.debug('GPIO boiler off')
        GPIO.output(B_OFF, GPIO.HIGH)
Пример #3
0
 def __init__(self, params):
     self.workdir = params['general']['workdir']
     self.outputfile = params['study']['outputfile']
     self.method = get_method(params)
     self.njobs = params['study']['njobs']
     self.variables = Variables(params)
     self.restart = params['study']['restart']
Пример #4
0
 def __init__(self, screenmanager, **kwargs):
     super(MainScreen, self).__init__(**kwargs)
     #Set screenmanager
     sm = screenmanager
     #Set backgroundcolor
     Window.clearcolor = (.2, .2, .2, 1)
     #Create master box layout
     layout = BoxLayout(spacing=10)
     #Create infobox
     infobox = InfoBox(sm, size_hint=Variables().getInfoboxSizeHint())
     #Create carview
     carViewLayout = CarView(sm, size_hint=Variables().getCarViewSizeHint())
     #Add layouts to the master layout
     layout.add_widget(infobox)
     layout.add_widget(carViewLayout)
     self.add_widget(layout)
Пример #5
0
 def test_backtracking_can_find_a_solution(self):
     problem = Variables(4)
     forwardchecking = ForwardChecking(Constraints(4))
     forwardchecking.findSolution(problem)
     self.assertTrue(
         self.fourByFourSolution(problem.queens)
         or self.altFourByFourSolution(problem.queens))
Пример #6
0
    def parseData(self, message):
        print_on = int(Variables().readVariables(['PrintData']))
        message = message.split('\r\n')

        for lines in message:
            # print lines
            try:
                if lines[0] == 'H':
                    self.maxCmd_H(lines)
                elif lines[0] == 'M':
                    self.maxCmd_M(lines, 0)
                elif lines[0] == 'C':
                    self.maxCmd_C(lines)
                elif lines[0] == 'L':
                    self.maxCmd_L(lines)
                else:
                    break
            except:
                pass

        if print_on:
            for keys in maxDetails:
                print keys, maxDetails[keys]
            print "Rooms"
            for keys in rooms:
                print keys, rooms[keys]
            print "devices"
            for keys in devices:
                print keys, devices[keys]
            print "valves"
            for keys in valves:
                print keys, valves[keys]
 def test_a_copy_variable_list_is_indepentent(self):
     varis = Variables(4)
     newVaris = varis.copy()
     varis.queens[0].value = 1
     varis.queens[0].domain = set([1, 2, 3])
     self.assertNotEqual(1, newVaris.queens[0].value)
     self.assertNotEqual(set([1, 2, 3]), newVaris.queens[0].domain)
Пример #8
0
    def __init__(self, folder):
        self.var = Variables()
        self.folder = folder
        if Path(self.var.root + self.folder + 'gazedata.gz').is_file():
            _ = os.system('gunzip ' + self.var.root + self.folder +
                          'gazedata.gz')
            _ = os.system('gunzip ' + self.var.root + self.folder +
                          'imudata.gz')

        with open(self.var.root + self.folder + 'gazedata') as f:
            for jsonObj in f:
                self.var.gaze_dataList.append(json.loads(jsonObj))

        with open(self.var.root + self.folder + 'imudata') as f:
            for jsonObj in f:
                self.var.imu_dataList.append(json.loads(jsonObj))

        self.imu_start_timestamp = float(self.var.imu_dataList[0]['timestamp'])
        self.gaze_start_timestamp = float(
            self.var.gaze_dataList[0]['timestamp'])
        self.start_timestamp = (
            self.imu_start_timestamp if self.gaze_start_timestamp <
            self.imu_start_timestamp else self.gaze_start_timestamp) - 0.01

        self.gaze_dict = {}
        self.imu_dict = {}
Пример #9
0
 def checkHeat(self, input_queue):
     useNeoPixel = Variables().readVariables(['UseNeoPixel'])
     MAXData, validData = self.getData()
     if validData:
         self.parseData(MAXData)
         self.switchHeat()
     if useNeoPixel:
         self.setNeoPixel(1, input_queue)
Пример #10
0
    def __scrape_post(self, post, url):
        """ Sets up dictionaries and calls relevant scraping functions """

        var = Variables(post, url, self.info)
        self.info = var.parse_info(logger=self.log)

        self.catalogue['id'].append(str(uuid.uuid4())[:utils['UUID_LEN']])
        self.catalogue['search_id'].append(self.current_searchid)
Пример #11
0
 def test_arc_will_not_backtrack_too_far_when_it_sees_a_failure(self):
     ac = ArcConsistency(Arcs(4))
     problem = Variables(4)
     problem.queens[0].value = 2
     problem.queens[3].value = 4
     ac.arcConsistent(problem, problem.queens[3])
     self.assertEqual(set([3]), problem.queens[3].domain)
     self.assertEqual(-1, problem.queens[3].value)
Пример #12
0
 def test_arc_will_restore_all_domains_when_not_given_the_last_queen(self):
     ac = ArcConsistency(Arcs(4))
     problem = Variables(4)
     problem.queens[0].value = 1
     problem.queens[1].value = 3
     ac.arcConsistent(problem)
     self.assertEqual(set([1, 2, 3, 4]), problem.queens[1].domain)
     self.assertEqual(3, problem.queens[1].value)
Пример #13
0
 def __init__(self):
     self.name = self.__class__.__name__
     self.problem = LpProblem(self.name, LpMinimize)
     self.problem += self.objective
     self.variables = Variables()
     self.rules = ComposedRule(self.variables)
     self.board = Board(self.variables.ROWS, self.variables.COLUMNS)
     self.result = Board(self.variables.ROWS, self.variables.COLUMNS)
Пример #14
0
 def email(self):
     try:
         variables = Variables(self.csv_file)
         variables.read()
     except IOError:
         raise SystemExit("%s not found" % self.csv_file)
     except csv.Error, e:
         raise SystemExit(e.message)
Пример #15
0
 def test_arc_can_detect_an_inconsistency(self):
     problem = Variables(8)
     problem.queens[5].value = 5
     problem.queens[1].value = 3
     problem.queens[2].value = 1
     problem.queens[3].value = 4
     problem.queens[4].value = 7
     self.assertFalse(self.ac.arcConsistent(problem))
Пример #16
0
def preprocess(dataset, start_year, end_year, final_dataset):
    """
    1. Imports dataset
    2. Selects only PLWHA without RF in start_year
    3. For each disease, if disease in any year from start_year to end_year-1, then disease present in end_year

    Arguments:
      - dataset: xls or csv
          Absolute path to the dataset xls file
      - start_year: int
          Starting year
      - end_year: int
          Ending year
      - final_dataset: str
          Absolute path to the file where the preprocessed data must be written to

    Returns:
      - No return values
  """
    h = Helpers()
    v = Variables()

    # Diagnostics
    h.check_file_existence(dataset)
    h.check_year(start_year, end_year)
    h.check_dir(os.path.dirname(final_dataset))

    # Import dataset
    data = h.import_dataset(dataset)

    # Individuals in data who have HIV at start_year
    data_hiv = data[data["HIV" + str(start_year)] == 1]

    # Individuals in data_HIV who don't have RF at start_year
    data_hiv_no_rf = data_hiv[data_hiv["RF" + str(start_year)] == 0]
    logger.info("{0} PLWHA without RF in {1}".format(data_hiv_no_rf.shape[0],
                                                     start_year))

    # Read diseases from disease file
    diseases = h.read_feature_file(v.diseases_f)

    # Make a copy of data_hiv_no_rf
    data_hiv_no_rf_copy = data_hiv_no_rf.copy()

    logger.info(
        "Processing disease values of {0} based on previous years".format(
            end_year))
    # For each disease, set value 1 at end_year if value is 1 at any previous year
    for year in range(start_year, end_year):
        for disease in diseases:
            data_hiv_no_rf_copy.ix[data_hiv_no_rf_copy[disease +
                                                       str(year)] == 1,
                                   [disease + str(end_year)]] = 1

    # Save data_hiv_no_rf_copy to final_dataset
    h.write_dataset(data_hiv_no_rf_copy, final_dataset)

    return None
Пример #17
0
def DT(input_list, results_path, seed=123, criterion='gini', splitter='best', max_depth=None):
  """
    1. Perform pruned decision tree classification on X and Y
    2. Get heatmap of confusion matrix
    3. Get decision tree
    4. Get ROC curve

    Arguments:
      - input_list: list, length = 4
          Absolute path to [X_train, Y_train, X_test, Y_test]
      - results_path: str
          Absolute path to the directory where the files will be saved
      - seed: int, optional, default = 123
          Random seed
      - criterion: {gini, entropy}, optional, default = gini
          Function to measure the quality of a split
      - splitter: {best, random}, optional, default = best
          Strategy used to choose the split at each node
      - max_depth: int, value <= length of tree, optional, default = None
          Maximum depth of the tree
     
    Returns:
      - Trained pruned decision tree classifier
  """
  h = Helpers()
  v = Variables()

  # Diagnostics
  h.check_dir(results_path)

  if len(input_list) != 4:
    logger.error("{0} files found in input_list, expected 4".format(len(input_list)))
    h.error()
    
  X_train, Y_train, X_test, Y_test = input_list
  h.check_file_existence(X_train)
  h.check_file_existence(Y_train)
  h.check_file_existence(X_test)
  h.check_file_existence(Y_test)

  # Import datasets
  X_train = h.import_dataset(X_train)
  Y_train = h.import_dataset(Y_train)
  X_test = h.import_dataset(X_test)
  Y_test = h.import_dataset(Y_test)

  # Train DT
  dt = DecisionTreeClassifier(criterion=criterion, splitter=splitter, max_depth=max_depth, random_state=seed)
  dt.fit(X_train, Y_train)

  # get accuracy, confusion matrix and ROC AUC
  h.get_metrics(dt, [X_train, Y_train, X_test, Y_test], results_path)

  # build decision tree
  h.decision_tree_viz(dt, os.path.join(results_path,'decision_tree.png'))

  return dt
Пример #18
0
 def processSerial(self, data):
     global reboot_Timer
     global offTime
     global shutdown_Timer
     global shutOff_Timer
     
     self.logger.info("Processing Serial Data : %s" % data)
     if data == "checkSW_ON":
         MaxInterface().checkHeat(input_queue)
     elif data == "boilerSW_ON":
         boilerEnabled = Variables().readVariables(['BoilerEnabled'])
         if boilerEnabled:
             boilerEnabled = 0
         else:
             boilerEnabled = 1
         Variables().writeVariable([['BoilerEnabled', boilerEnabled]])
         MaxInterface().checkHeat(input_queue)
         
     elif data == "rebootSW_ON":
         reboot_Timer = time.time()
         MaxInterface().setNeoPixel(0, input_queue, 2)
     elif data == "rebootSW_OFF":
         offTime = time.time()
         if offTime - reboot_Timer >= 3:
             self.logger.info("Rebooting")
             system("sudo reboot")
             
     elif data == "shutdownSW_ON":
         shutdown_Timer = time.time()
         MaxInterface().setNeoPixel(0, input_queue, 1)
     elif data == "shutdownSW_OFF":
         shutOff_Timer = time.time()
         if shutOff_Timer - shutdown_Timer >= 3:
             self.logger.info("Shutting Down Python")
             system("sudo shutdown -h now")
             
     elif data == "overSW_ON":
         boiler_override = Variables().readVariables(['BoilerOverride'])
         boiler_override += 1
         if boiler_override > 2:
             boiler_override = 0
         print boiler_override
         Variables().writeVariable([['BoilerOverride', boiler_override]])
         MaxInterface().setNeoPixel(0, input_queue, 0)
Пример #19
0
    def veraSendTemp(self, roomID, temp):
        logger = logging.getLogger("main.veratemps.veraSendTemps")

        veraSendCommand = Variables().readVariables(['VeraUpdateTemps'])
        try:
            sendString = veraSendCommand.format(roomID, temp)
            logger.debug("Sending to Vera {}".format(sendString))
            _ = requests.get(sendString, timeout=5)
        except Exception, err:
            logger.info("vera send fault{}".format(err))
 def test_backtracking_can_find_a_larger_solution(self):
     problem = Variables(8)
     problem.queens[4].value = 5
     self.backtracking.findSolution(problem)
     self.assertNotEqual(-1, problem.queens[0].value)
     self.assertNotEqual(-1, problem.queens[1].value)
     self.assertNotEqual(-1, problem.queens[2].value)
     self.assertNotEqual(-1, problem.queens[4].value)
     self.assertNotEqual(-1, problem.queens[6].value)
     self.assertNotEqual(-1, problem.queens[7].value)
Пример #21
0
    def __call__(self, loader, output):
        questions = self._questions or loader.settings.get('QUESTIONS')
        if questions is None:
            LOGGER.debug('No questions to prompt')
            return

        if isinstance(questions, str):
            q = inquirer.load_from_json(questions)
        if isinstance(questions, list):
            q = inquirer.questions.load_from_list(questions)
        Variables().update(inquirer.prompt(q))
Пример #22
0
    def __init__(self, screenmanager, **kwargs):
        carViewSize = [
            Window.width * Variables().getCarViewSizeHint()[0],
            Window.height * Variables().getCarViewSizeHint()[1]
        ]
        carSize = [carViewSize[0] / 7, carViewSize[1] / 4]

        super(RelativeLayout, self).__init__(**kwargs)
        #Create carview layout
        global layout
        layout = RelativeLayout()
        with layout.canvas:
            car = Rectangle(source='images/car.jpg',
                            pos=(carViewSize[0] / 2 - carSize[0] / 2,
                                 carViewSize[1] / 2 - carSize[1] / 2),
                            size=carSize)

        Clock.schedule_interval(self.updateCanvas, 0.1)

        self.add_widget(layout)
Пример #23
0
 def startKioskServer(self):
     webIP, webPort = Variables().readVariables(['WebIP', 'WebPort'])
     self.logger.info("Web UI Starting on : %s %s" %( webIP, webPort))
     try:
         server = ThreadingHTTPServer((webIP, webPort), MyRequestHandler, queue=input_queue)
         uithread = threading.Thread(target=server.serve_forever)
         uithread.setDaemon(True)
         uithread.start()
     except Exception, err:
         self.logger.error("Unable to start Web Server on %s %s %s" %(webIP, webPort, err))
         self.logger.critical("Killing all Python processes so cron can restart")
         system("sudo pkill python")
Пример #24
0
    def getData(self):
        logger = logging.getLogger("main.max.getData")
        validData = False
        message = ""
        Max_IP, Max_IP2, Max_Port = Variables().readVariables(
            ['MaxIP', 'MaxIP2', 'MaxPort'])
        logger.info(
            'Max Connection Starting on : IP1-%s or IP2-%s on port %s ' %
            (Max_IP, Max_IP2, Max_Port))
        cube1 = 0
        cube2 = 0
        success = False

        try:
            # Connect to Max Cube1
            while cube1 < 3 and not success:
                try:
                    logger.info(
                        'tyring to connect to Max1 on ip %s on try %s' %
                        (Max_IP, cube1))
                    s = self.createSocket()
                    s.connect((Max_IP, int(Max_Port)))
                    logger.info('Socket Connected to Max1 on ip %s on try %s' %
                                (Max_IP, cube1))
                    Variables().writeVariable([['ActiveCube', 1]])
                    Variables().writeVariable([['CubeOK', 1]])
                    success = True

                except Exception, err:
                    s.close()
                    Variables().writeVariable([['CubeOK', 0]])
                    logger.exception(
                        "unable to make connection, trying later %s" % err)
                    time.sleep(2)

                cube1 += 1

            if not success:
                raise Exception("Cube 1 fail")
Пример #25
0
    def move(self):
        # This function is called on every turn of a game. It's how your snake decides where to move.
        # Valid moves are "up", "down", "left", or "right".
        data_raw = cherrypy.request.json
        data = Variables(data_raw)

        if data.you_health < 55:
            move = seek_food(data)
        else:
            move = move_randomly(data)

        print(f"MOVE: {move}")
        return {"move": move, "taunt": "hello"}
Пример #26
0
 def __init__(self):
     #Initialise the Logger
     logLevel = Variables().readVariables(['LoggingLevel']).rstrip('\r')
     useNeoPixel = Variables().readVariables(['UseNeoPixel'])
     self.logger = logging.getLogger("main")
     level = logging.getLevelName(logLevel)
     self.logger.setLevel(level)
     
     fh = RotatingFileHandler("heating.log",
                              maxBytes=1000000, # 1Mb I think
                              backupCount=5)
     
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
     fh.setFormatter(formatter)
     self.logger.addHandler(fh)
     self.logger.info("Main has started __init__ has run logger level is %s" % logLevel)
     
     try:
         cube = DbUtils().getCubes()
         self.logger.info("Database OK cube %s found" % (cube[1]))
     except Exception, err:
         DbUtils().initialiseDB()
         self.logger.exception("Database Initialised %s" % err)
Пример #27
0
    def __init__(self, script):
        self.lines = clean_script(script)

        self.variables = Variables()

        self.parameters = Parameters()

        self.phases = Phases()

        self.runs = Runs()

        self.all_run_labels = list()

        self.postcmds = PostCmds()

        # Used to label unlabelled @run-statements with "run1", "run2", ...
        self.unnamed_run_cnt = 1

        # Used to label unlabelled @phase-statements with "phase1", "phase2", ...
        self.unnamed_phase_cnt = 1
Пример #28
0
def setStatusLights():
    cube_state, vera_state, boiler_enabled, local_relay = Variables(
    ).readVariables(
        ['CubeOK', 'VeraOK', 'BoilerEnabled', 'ManualHeatingSwitch'])
    heating_state = DbUtils().getBoiler()[2]
    module_logger.info("setting status lights")
    if cube_state:
        GPIO.output(C_OK, GPIO.HIGH)
        GPIO.output(C_ERR, GPIO.LOW)
    else:
        GPIO.output(C_OK, GPIO.LOW)
        GPIO.output(C_ERR, GPIO.HIGH)

    # Set Vera Lights
    if vera_state:
        GPIO.output(V_OK, GPIO.HIGH)
        GPIO.output(V_ERR, GPIO.LOW)
    else:
        GPIO.output(V_OK, GPIO.LOW)
        GPIO.output(V_ERR, GPIO.HIGH)

    # Set Heating State
    if heating_state:
        GPIO.output(H_ON, GPIO.HIGH)
        GPIO.output(H_OFF, GPIO.LOW)
        if local_relay:
            module_logger.info("Switching local relay")
            GPIO.output(BOILER_SW, GPIO.LOW)  # Pull down Relay to switch on.
    else:
        GPIO.output(H_ON, GPIO.LOW)
        GPIO.output(H_OFF, GPIO.HIGH)
        if local_relay:
            module_logger.info("Switching local relay")
            GPIO.output(BOILER_SW, GPIO.HIGH)

    # Set Boiler State
    if boiler_enabled:
        GPIO.output(B_OFF, GPIO.LOW)
    else:
        GPIO.output(B_OFF, GPIO.HIGH)
        module_logger.info("Starting flashing boiler light")
Пример #29
0
    def doLoop(self):
        nextLoopCheck = time.time()
        while True:
            loopStartTime = time.time()
            if loopStartTime >= nextLoopCheck:
                print "running loop"
                checkInterval, boiler_enabled, useNeoPixel = Variables().readVariables(['Interval', 'BoilerEnabled', 'UseNeoPixel'])
                
                if boiler_enabled != 1:
                    checkInterval = checkInterval * 2
                if _platform == "linux" or _platform == "linux2":
                    if not useNeoPixel:
                        self.logger.info("checking heat levels")
                        buttonCheckHeat("main")
                        self.logger.info("starting heartbeat")
                        hBeat(checkInterval)
                        self.logger.info("Memory free this loop %s MB" % hardware.getRAM())
                        self.logger.info("CPU Usage this loop %s" % hardware.getCPUUse())
                        self.logger.debug( "loop interval : %s" %(checkInterval))
                        self.doLoop()
                    else:
                        self.logger.info("checking heat levels")
                        MaxInterface().checkHeat(input_queue)
                        self.logger.info('Running NeoPixel timer')
                        self.logger.info("Memory free this loop %s MB" % hardware.getRAM())
                        self.logger.info("CPU Usage this loop %s" % hardware.getCPUUse())
                        self.logger.debug( "loop interval : %s" %(checkInterval))
                else:
                    MaxInterface().checkHeat(input_queue)
                    self.logger.info('Running Windows timer')
                    
                
                    
                nextLoopCheck = loopStartTime + checkInterval
                
            if not output_queue.empty():
                serialData = output_queue.get().rstrip()
                self.processSerial(serialData)

            time.sleep(.2)
Пример #30
0
    def __init__(self):
        ## Cria os tipos que estão disponíveis
        self.bounds = Bounds()
        self.action = Action()
        self.loop = Functions()
        self.math = Math()
        self.variables = Variables()

        ## Adicona os tipos acima em uma lista
        self.buttons = [
            self.bounds, self.action, self.loop, self.math, self.variables
        ]

        ##Variavel que armazena o valor do botão que está ativo. Em caso de False, nenhum está
        self.buttonActive = False

        ## Define o Botão de Compilar
        self.sizeButtonComp = [75, 50]
        self.buttonComp = pygame.image.load(
            os.path.join("img", "buttonCompilar.png")).convert_alpha()
        self.buttonComp = pygame.transform.scale(self.buttonComp,
                                                 self.sizeButtonComp)
        self.posButtonComp = [10, 480]