Ejemplo n.º 1
0
 def __init__(self, ser, default = RGBState.STATE_OFF):
   Controller.__init__(self)
   self.ser = ser
   self.default = default
   self.keepalive = False
   self.state = self.default
   self.lock = threading.Lock()
    def test_TextSave_03(self, mock_isfile, mock_open):
        """
        Add 2 Records, then expect the text save to produce 2 text lines
        """
        def doText():
            doText.theText = theTextStream.getvalue()

        theTextStream = StringIO()
        theTextStream.close = Mock(side_effect=doText)
        mock_isfile.return_value = False
        mock_open.return_value = theTextStream

        theController = Controller(TestView.TestView(), None)
        self._addSomeRecordsViaController(theController, 2)

        TestView.clearLog()
        theController.do_text_save("")

        # Part 1: Text data
        expectedData = "A000 M 0 0 Normal 0\nA001 M 0 0 Normal 0"
        actualData = doText.theText
        self.assertEqual(expectedData, actualData)

        # Part 2: Show
        expectedShow = "Saved As Text"
        actualShow = TestView.theLog[0]
        self.assertEqual(expectedShow, actualShow)
    def test_SerialSave_01(self, mock_isfile, mock_open):
        """
        Saving a RecordCollection with 10 Records
        """
        def doDump():
            doDump.theDump = theDumpStream.getvalue()

        theDumpStream = BytesIO()
        theDumpStream.close = Mock(side_effect=doDump)

        # So that it is know that file does not exist
        mock_isfile.return_value = False
        mock_open.return_value = theDumpStream
        theController = Controller(TestView.TestView(), None)
        # add 10 Records, reset view log, then serial save
        self._addSomeRecordsViaController(theController, 10)
        TestView.clearLog()
        theController.do_serial_save("")

        # Part 1: Check contents of theDumpStream
        # theDump = theDumpStream.getvalue()
        expectedRecords = 10
        fromDump = pickle.load(BytesIO(doDump.theDump))
        actualRecords = len(fromDump.getAllRecords())
        self.assertEqual(expectedRecords, actualRecords)

        # Part 2: Check no show() messages on theLog
        expectedLog = 0
        actualLog = len(TestView.theLog)
        self.assertEqual(expectedLog, actualLog)
    def test_TextLoad_01(self, mockMeth):
        """
        Load a record from text, test for correct attribute parsing
        - This test does not add coverage if test_TextLoad_02 is exercised
        - Asserted by expecting TestView().show() to get a message,
           representing the record in the same string format
        """
        expID = "A001"
        expGender = "F"
        expAge = 36
        expSales = 92
        expBMI = "Normal"
        expIncome = 700
        theData = "{} {} {} {} {} {}".format(expID, expGender, expAge,
                                             expSales, expBMI, expIncome)

        mockMeth.return_value = StringIO(theData)
        theController = Controller(TestView.TestView(), None)
        theController.do_text_load("")

        TestView.clearLog()
        expectedMessage = theData + "\n"
        theController.do_view_records("")
        actualMessage = TestView.theLog[0]
        self.assertEqual(expectedMessage, actualMessage)
Ejemplo n.º 5
0
    def __init__(self, speed, min_altitude, max_altitudeGoal, height_diff, \
    timeout, bbx, bby, pid_x, pid_y, pid_z, pid_theta, bounding_box=True):
        # Initialize the node and rate
        Mode.__init__(self, 'land_mode')
        Controller.__init__(self, pid_x, pid_y, pid_z, pid_theta, bounding_box)

        # Subscribers
        # self.sub_navdata = rospy.Subscriber('/ardrone/navdata', Navdata, self.navdata_cb)
        ##self.sub_state = rospy.Subscriber('/smach/state', String, self.state_cb)
        self.sub_state = rospy.Subscriber('/smach/state',String, self.handle_timer_cb)

        # Publishers
        self.pub_altitude = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
        self.pub_land = rospy.Publisher('/ardrone/land', Empty, queue_size=100) #this turns off the motors

        # NOTE changed to passing transition and state info along
        # /smach/transition and /smach/state topics, respectively
        # self.pub_return_to_state = rospy.Publisher('qc_smach/transitions', String, queue_size=1)
        self.pub_transition = rospy.Publisher('smach/transition', String, queue_size=1)

        # Initialize member variables
        self.transition = String()
        self.state = 'nada'
        self.timer = rospy.Timer(rospy.Duration(timeout), self.goto_reacquisition)

        self.altitude_command = Twist()
        self.altitude_command.linear.z = speed

        self.min_altitude = min_altitude
        self.speed = speed
        self.max_altitudeGoal = max_altitudeGoal
        self.height_diff = height_diff
Ejemplo n.º 6
0
class Game(object):

    def __init__(self):
        self.TITLE = "TEST (by zeeisl)"
        self.WIDTH = 800
        self.HEIGHT = 600
        
        self.controller = Controller()
        
        # game things
        self.char = Player("res//hero.png")
        self.map = Map()
        
        self.char1 = Character("res//hero.png", 100, 100, 32, 32)
        
    def key_input(self, event):
        self.controller.getButtonStates(event)
        self.char.key_input(event)
    
    def update(self, delta):
        self.map.update()
        self.char.update(self.char1)
        self.char1.update()
    
    def render(self, screen):
        self.map.render(screen)
        self.char.render(screen)
        self.char1.render(screen)
Ejemplo n.º 7
0
class ControllerThread(threading.Thread):
    
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
        '''
        Initialize class attributes.
        '''
        threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
        self.controller = Controller()
        self.state = True
        
    def stop_communication(self):
        '''
        Change the state to False, this will finish the communication
        cylce.
        '''
        self.state = False
        self.controller.quit_commands()
    
    def run(self):
        '''
        Perform the joystick connection and get the bluetooth list.
        '''
        try:
            while self.state:
                self.controller.send_commands()
        except:
            print str(traceback.format_exc())
Ejemplo n.º 8
0
class ControllerTest(unittest.TestCase):

	def setUp(self):
		self.clerk = MockClerk()
		self.clerk.store(Goal(name="Test Goal 1"))
		self.clerk.store(Goal(name="Test Goal 2"))
		self.clerk.store(Task(name="Test Task 1"))
		self.clerk.store(Task(name="Test Task 2"))
		self.clerk.store(User(name="Durran"))
		self.clerk.store(User(name="Michal"))
		self.clerk.store(Plan())
		self.controller = Controller(self.clerk)
		
	# Test the listing of goals
	def testListGoals(self):
		g = self.controller.list_goal()
		assert len(g) == 2
		
	# Test the listing of tasks
	def testListTasks(self):
		t = self.controller.list_task()
		assert len(t) == 2
		
	# Test the user list
	def testListUsers(self):
		u = self.controller.list_user()
		assert len(u) == 2
		
	# test the plan list
	def testListPlan(self):
		p = self.controller.list_plan()
		assert len(p) == 1
    def test_SelectedRecord_EditBMI(self):
        """
        A RecordCollection with one Record will be provided to Controller
        - Random ID, male, default attributes
        - New BMI will be Overweight
        """
        theRC = self._getRecordColl_OneMaleRecord_RandomID()
        theRecord = theRC.getAllRecords()[0]
        theID = theRecord.getID()
        newBMI = "Overweight"
        theController = Controller(TestView.TestView(), theRC)
        # From here the record will be manipulated via theController
        # Successful calls will represent the record via show message
        expected_1 = self._getRecordStateMessage(theID)
        expected_2 = self._getRecordStateMessage(theID, bmi=newBMI)

        # Call 1, selecting the record. 3 show messages
        expectedList = [TestObjectSelectionClass._expRecordHeader, expected_1,
                        TestObjectSelectionClass._expRecordFunctions]
        TestView.clearLog()
        theController.do_select_rec(theID)
        self.assertEqual(expectedList, TestView.theLog)

        # Call 2, editing the BMI. 3 show messages
        expectedList[1] = expected_2
        TestView.clearLog()
        theController.do_edit_bmi(newBMI)
        self.assertEqual(expectedList, TestView.theLog)
Ejemplo n.º 10
0
 def __init__(self, prefs):
     '''
     Constructor
     '''
     Controller.__init__(self)
     self.shared_prefs = prefs
     
Ejemplo n.º 11
0
	def __init__(self, enemy, player, director):
		Controller.__init__(self, enemy, director)
		self.player = player
		self.enemy_speed = 0.10
		self.ttl = 0
		self.lastSpeedX = 0
		self.lastSpeedY = 0
	def __init__(self, model, view):
		Controller.__init__(self, model, view)
		self.choices = {
			1: self._choice_insert_stop,
			2: self._choice_insert_time,
			3: self._choice_insert_local,
			"sair": self.finish}
 def test_update_temperature_range(self):
     t_lower = 15
     t_upper = 18
     c = Controller(t_lower, t_upper)
     c.update_temperature_range(16,17)
     assert c.set_point_lower == 16
     assert c.set_point_upper == 17
    def test_SelectedRecord_EditIncome(self):
        """
        A RecordCollection with one Record will be provided to Controller
        - Random ID, male, default attributes
        - Randomise an income
        - Methodology for picking a new income will be
           (original sales + 1) % 1000
        """
        theRC = self._getRecordColl_OneMaleRecord_RandomID()
        theRecord = theRC.getAllRecords()[0]
        theID = theRecord.getID()
        theRecord.setIncome(random.randrange(1000))
        originalIncome = theRecord.getIncome()
        newIncome = (originalIncome + 1) % 1000  # 1000 is income limit
        theController = Controller(TestView.TestView(), theRC)
        # From here the record will be manipulated via theController
        # Successful calls will represent the record via show message
        expected_1 = self._getRecordStateMessage(theID, income=originalIncome)
        expected_2 = self._getRecordStateMessage(theID, income=newIncome)

        # Call 1, selecting the record. 3 show messages
        expectedList = [TestObjectSelectionClass._expRecordHeader, expected_1,
                        TestObjectSelectionClass._expRecordFunctions]
        TestView.clearLog()
        theController.do_select_rec(theID)
        self.assertEqual(expectedList, TestView.theLog)

        # Call 2, editing the income. 3 show messages
        expectedList[1] = expected_2
        TestView.clearLog()
        theController.do_edit_income(newIncome)
        self.assertEqual(expectedList, TestView.theLog)
Ejemplo n.º 15
0
 def test_wrong_delimiter2(self):
     """
     testet ob ein falscher delimiter verwendet wird
     """
     c = Controller()
     c.delimiter = ','
     self.assertEqual(c.delimiter, ',')
Ejemplo n.º 16
0
 def test_delimiter(self):
     """
     testet ob der richtige delimiter benutzt wird
     """
     c = Controller()
     c.delimiter = ';'
     self.assertEqual(c.delimiter, ';')
Ejemplo n.º 17
0
def main():
    parser = OptionParser()
    parser.add_option("-v", "--verbose", dest="verbose", help="verbose log output", default=False)
    parser.add_option("-l", "--label", dest="label", help="label of the agent", default=None)
    parser.add_option("--host", dest="host", help="AppMaster host", default=None)
    parser.add_option("--port", dest="port", help="AppMaster port", default=None)
    (options, args) = parser.parse_args()

    if not "AGENT_WORK_ROOT" in os.environ:
        parser.error("AGENT_WORK_ROOT environment variable must be set.")
    options.root_folder = os.environ["AGENT_WORK_ROOT"]
    if not "AGENT_LOG_ROOT" in os.environ:
        parser.error("AGENT_LOG_ROOT environment variable must be set.")
    options.log_folder = os.environ["AGENT_LOG_ROOT"]
    if not options.label:
        parser.error("label is required.")

    bind_signal_handlers()

    # Check for configuration file.
    agentConfig = AgentConfig(options.root_folder, options.log_folder, options.label)
    update_config_from_file(agentConfig)

    # update configurations if needed
    if options.host:
        agentConfig.set(AgentConfig.SERVER_SECTION, "hostname", options.host)

    if options.port:
        agentConfig.set(AgentConfig.SERVER_SECTION, "port", options.port)

    logFile = os.path.join(agentConfig.getResolvedPath(AgentConfig.LOG_DIR), logFileName)
    perform_prestart_checks(agentConfig)
    ensure_folder_layout(agentConfig)

    setup_logging(options.verbose, logFile)
    update_log_level(agentConfig, logFile)
    write_pid()

    logger.info("Using AGENT_WORK_ROOT = " + options.root_folder)
    logger.info("Using AGENT_LOG_ROOT = " + options.log_folder)

    server_url = SERVER_STATUS_URL.format(
        agentConfig.get(AgentConfig.SERVER_SECTION, "hostname"),
        agentConfig.get(AgentConfig.SERVER_SECTION, "port"),
        agentConfig.get(AgentConfig.SERVER_SECTION, "check_path"),
    )
    print("Connecting to the server at " + server_url + "...")
    logger.info("Connecting to the server at: " + server_url)

    # Wait until server is reachable
    netutil = NetUtil()
    netutil.try_to_connect(server_url, -1, logger)

    # Launch Controller communication
    controller = Controller(agentConfig)
    controller.start()
    controller.join()
    stop_agent()
    logger.info("... agent finished")
Ejemplo n.º 18
0
def main():
	# set up logging for the application
	
	logger.info("Starting BreakfastAlarm App for user: {}".format(user_id))

	controller = Controller(user_id, logger)
	controller.set_profile(get_breakfast_profile())
	controller.start()
Ejemplo n.º 19
0
def main():
        app = QApplication(sys.argv)

        controller = Controller()
        controller.create()
        controller.show()

        sys.exit(app.exec_())
Ejemplo n.º 20
0
 def __init__( self ):
   # ui
   self._tl_label = "tl"
   self._tm_label = "tm"
   self._tr_label = "tr"
   self._bl_label = "bl"
   self._bm_label = "bm"
   self._br_label = "br"
   Controller.__init__( self, view=PrototypeController.PrototypeView(self) )
Ejemplo n.º 21
0
def main():
  global config
  parser = OptionParser()
  parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="verbose log output", default=False)
  parser.add_option("-e", "--expected-hostname", dest="expected_hostname", action="store",
                    help="expected hostname of current host. If hostname differs, agent will fail", default=None)
  (options, args) = parser.parse_args()

  expected_hostname = options.expected_hostname

  setup_logging(options.verbose)

  default_cfg = { 'agent' : { 'prefix' : '/home/ambari' } }
  config = ConfigParser.RawConfigParser(default_cfg)
  bind_signal_handlers()

  if (len(sys.argv) >1) and sys.argv[1]=='stop':
    stop_agent()

  # Check for ambari configuration file.
  config = resolve_ambari_config()

  # Starting data cleanup daemon
  data_cleaner = None
  if int(config.get('agent','data_cleanup_interval')) > 0:
    data_cleaner = DataCleaner(config)
    data_cleaner.start()

  perform_prestart_checks(expected_hostname)
  daemonize()

  # Starting ping port listener
  try:
    ping_port_listener = PingPortListener(config)
  except Exception as ex:
    err_message = "Failed to start ping port listener of: " + str(ex)
    logger.error(err_message);
    sys.stderr.write(err_message)
    sys.exit(1)
  ping_port_listener.start()

  update_log_level(config)

  server_url = 'https://' + config.get('server', 'hostname') + ':' + config.get('server', 'url_port')
  print("Connecting to the server at " + server_url + "...")
  logger.info('Connecting to the server at: ' + server_url)

  # Wait until server is reachable
  netutil = NetUtil()
  netutil.try_to_connect(server_url, -1, logger)

  # Launch Controller communication
  controller = Controller(config)
  controller.start()
  controller.join()
  stop_agent()
  logger.info("finished")
Ejemplo n.º 22
0
	def __init__(self, model, view):
		Controller.__init__(self, model, view)
		self.choices = {
			1: self._choice_list_location_schedule,
			2: self._choice_lines_having_a_spot,
			3: self._choice_list_line_schedule,
			4: self._choice_list_itinerary_lines,
			5: self._choice_list_bus_spot_near_location,
			6: self._choice_list_available_schedules_of_initial_itinerary_bus_stop,
			"sair": self.finish}
Ejemplo n.º 23
0
	def run(self,edit,toggle):
		print toggle
		#config = configig(self.view)
		#config.run(edit)
		self.edit = edit
		if (toggle == "on"):
			Controller.turnOn(self.view,edit,self)
		else:
			print self.ctrl
			Controller.turnOff()
Ejemplo n.º 24
0
 def __init__(self, event_handler):
     Controller.__init__(self, event_handler)
     self.modifiers=set(map(str, ['RIGHT SHIFT','LEFT SHIFT','RIGHT CTRL', 'LEFT CTRL','RIGHT ALT', 'LEFT ALT']))
     
     self.keys=set(['F'+str(x) for x in range(12)]) \
         | set(map(chr, range(ord('A'), ord('Z')))) \
         | set(['ESC', 'SPACE', 'ENTER']) \
         | set(map(chr, range(ord('0'), ord('9'))))
     '''TODO: more keys'''
     self.registered_keys=dict()
     self.key_codes=dict()
 def getController(self):
     Ki = self.getKi()
     Kp = self.getKp()
     Kd = self.getKd()
     
     controller_dummy = Controller(Ki=Ki, Kp=Kp, Kd=Kd)
     
     controller_dummy.setMax(self.editWindow.getMax())
     controller_dummy.setMin(self.editWindow.getMin())
     
     return controller_dummy
 def test_DoesNotSelectOption(self):
     """
     To successfully select an option, the correct code must be provided
     - No correct code provided would expect an alternative show message
     """
     expected = "There is no option\n"
     incorrectCode = ""
     theController = Controller(TestView.TestView(), None)
     TestView.clearLog()
     # Call
     theController.do_select_option(incorrectCode)
     self.assertEqual(expected, TestView.theLog[0])
 def test_DoesNotSelectRecord(self):
     """
     To successfully select a record, the correct ID must be provided
     - No correct ID provided would expect an alternative show message
     """
     expected = "There is no record with that ID\n"
     incorrectID = ""
     theController = Controller(TestView.TestView(), None)
     TestView.clearLog()
     # Call
     theController.do_select_rec(incorrectID)
     self.assertEqual(expected, TestView.theLog[0])
Ejemplo n.º 28
0
class GUI_main(tk.Tk):
    '''
    classdocs
    '''
    
    def __init__(self, parent):
        '''
        Constructor
        '''
        tk.Tk.__init__(self,parent)
        self.parent = parent
        self.name = "main"   

        # if on linux, set the icon
#        if Utils.isLinux():                
#            os.path.join("..", "dcs.xbm")     
#            self.iconbitmap('@../dcs.xbm')    
        
        # instantiate the controller, register with the controller
        self.controller = Controller()
        self.controller.register(self, self.name)
        self.initialize()
        
    def initialize(self):
        # make the main window cover the entire screen
        if Utils.isLinux():
            self.w, self.h = self.winfo_screenwidth(), self.winfo_screenheight()
            self.geometry("%dx%d+0+0" % (self.w, self.h))
        if Utils.isWindows():
            self.wm_state('zoomed')    

        # bind exit command
        self.protocol("WM_DELETE_WINDOW", self.shutdown)
        
        #create menu
        self.menu = GUI_menubar(self, self.controller)
        self.config(menu=self.menu)
        
        
        # create frame structure
        self.big_frame = tk.Frame(self, bd=2, relief=tk.FLAT, background="grey")
        self.big_frame.pack(anchor=tk.NW, expand=tk.TRUE, fill=tk.BOTH)
        
        # display frame
        #self.graph_frame = GUI_graph_frame(self.big_frame, self.controller)
        #self.graph_frame.pack(side=tk.TOP, expand=tk.TRUE, fill=tk.BOTH)  
                
    
    def shutdown(self):
        self.destroy()
        raise SystemExit
Ejemplo n.º 29
0
 def __init__(self):
     '''
     Constructor
     '''
     Controller.__init__(self)
     self.controllers = []
     self.zoom_controller = None
     self.manual_direction_controller = None
     self.sensor_orientation_controller = None
     #self.time_travel_clock = TimeTravelClock();
     #self.transitioning_clock = TransitioningCompositeClock(timeTravelClock, RealClock())
     self.teleporting_controller = None
     self.using_auto_mode = True
     
Ejemplo n.º 30
0
    def __init__(self, view, world_model, event_handler):
        '''
        Constructor
        '''
        Controller.__init__(self, event_handler)
        self.view=view
        self.world=world_model
        #registers sprite on model and view. Grabs it to disallow physics modification
        ch_id=world_model.add_entity((0,0), (0,0))
        view.add_entity(ch_id, shape='s')
        world_model.grab_entity(ch_id)

        self.ch_id=ch_id
        
        self.DAMAGE_EVENT=world_model.DAMAGE_EVENT
Ejemplo n.º 31
0
Archivo: main.py Proyecto: fkpp/ambari
def main(heartbeat_stop_callback=None):
    global config
    parser = OptionParser()
    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      action="store_true",
                      help="verbose log output",
                      default=False)
    parser.add_option(
        "-e",
        "--expected-hostname",
        dest="expected_hostname",
        action="store",
        help=
        "expected hostname of current host. If hostname differs, agent will fail",
        default=None)
    (options, args) = parser.parse_args()

    expected_hostname = options.expected_hostname

    logging_level = logging.DEBUG if options.verbose else logging.INFO

    setup_logging(logger, AmbariConfig.AmbariConfig.getLogFile(),
                  logging_level)
    global is_logger_setup
    is_logger_setup = True
    setup_logging(alerts_logger, AmbariConfig.AmbariConfig.getAlertsLogFile(),
                  logging_level)
    Logger.initialize_logger('resource_management',
                             logging_level=logging_level)

    # use the host's locale for numeric formatting
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error as ex:
        logger.warning(
            "Cannot set locale for ambari-agent. Please check your systemwide locale settings. Failed due to: {0}."
            .format(str(ex)))

    default_cfg = {'agent': {'prefix': '/home/ambari'}}
    config.load(default_cfg)

    if (len(sys.argv) > 1) and sys.argv[1] == 'stop':
        stop_agent()

    if (len(sys.argv) > 2) and sys.argv[1] == 'reset':
        reset_agent(sys.argv)

    # Check for ambari configuration file.
    resolve_ambari_config()

    # Add syslog hanlder based on ambari config file
    add_syslog_handler(logger)

    # Starting data cleanup daemon
    data_cleaner = None
    if config.has_option('agent', 'data_cleanup_interval') and int(
            config.get('agent', 'data_cleanup_interval')) > 0:
        data_cleaner = DataCleaner(config)
        data_cleaner.start()

    perform_prestart_checks(expected_hostname)

    # Starting ping port listener
    try:
        #This acts as a single process machine-wide lock (albeit incomplete, since
        # we still need an extra file to track the Agent PID)
        ping_port_listener = PingPortListener(config)
    except Exception as ex:
        err_message = "Failed to start ping port listener of: " + str(ex)
        logger.error(err_message)
        sys.stderr.write(err_message)
        sys.exit(1)
    ping_port_listener.start()

    update_log_level(config)

    if not OSCheck.get_os_family() == OSConst.WINSRV_FAMILY:
        daemonize()

    #
    # Iterate through the list of server hostnames and connect to the first active server
    #

    active_server = None
    server_hostnames = hostname.server_hostnames(config)

    connected = False
    stopped = False

    # Keep trying to connect to a server or bail out if ambari-agent was stopped
    while not connected and not stopped:
        for server_hostname in server_hostnames:
            try:
                server_ip = socket.gethostbyname(server_hostname)
                server_url = config.get_api_url(server_hostname)
                logger.info('Connecting to Ambari server at %s (%s)',
                            server_url, server_ip)
            except socket.error:
                logger.warn(
                    "Unable to determine the IP address of the Ambari server '%s'",
                    server_hostname)

            # Wait until MAX_RETRIES to see if server is reachable
            netutil = NetUtil(config, heartbeat_stop_callback)
            (retries, connected,
             stopped) = netutil.try_to_connect(server_url, MAX_RETRIES, logger)

            # if connected, launch controller
            if connected:
                logger.info('Connected to Ambari server %s', server_hostname)
                # Set the active server
                active_server = server_hostname
                # Launch Controller communication
                controller = Controller(config, server_hostname,
                                        heartbeat_stop_callback)
                controller.start()
                while controller.is_alive():
                    time.sleep(0.1)

            #
            # If Ambari Agent connected to the server or
            # Ambari Agent was stopped using stop event
            # Clean up if not Windows OS
            #
            if connected or stopped:
                ExitHelper().exit(0)
                logger.info("finished")
                break
        pass  # for server_hostname in server_hostnames
    pass  # while not (connected or stopped)

    return active_server
Ejemplo n.º 32
0
from Ui import Console
from Controller import Controller
from Repository import Repo
from Validators import Validate


repoGame = Repo()
validate = Validate()


controller = Controller(repoGame, validate)

console = Console(controller)

console.run()
Ejemplo n.º 33
0
 def setup(self):
     self.__bot__ = Controller()
     self.__ai__ = AIModule()
Ejemplo n.º 34
0
from Controller import Controller
from GA_population import GA_population
from NeuralNetworks import save_model
import numpy as np
import sys
import torch

#Instantiate genetic algorithm
population = int(sys.argv[1])
n_father = int(sys.argv[2])
npermanent = int(sys.argv[3])
nH = int(sys.argv[4])
genetic = GA_population(population, n_father, npermanent, nH)

#Instanciate Controller
controller = Controller()
controller.load_circuit()
controller.register_genetic(genetic, GUI=False)

n_change = 100
best_fitness = 0
for generation in range(10000):
    try:
        print('Generation:', generation)
        #if generation % n_change == 0:
        #    controller.load_circuit()
        controller.reset()
        done = False

        while not done:
Ejemplo n.º 35
0
#app.py
from Controller import Controller

refactoring = True

#while True:
if refactoring:
    controller = Controller()
    refactoring = False

    #print("como era que se hacia?")

    #controller.listar_usuarios()
    #controller.agregar_usuario()
    #controller.listar_usuarios()
    #controller.buscarPorCedula()
Ejemplo n.º 36
0
from Parts import *
from Controller import Controller

powerSupply = PowerSupply()
legs = Legs()
arms = Arms()
vision = Vision()
speech = Speech()
stats = Stats()
leftArm = LeftArm()
rightArm = RightArm()
controller = Controller()
controller.roboCopController(powerSupply)
Ejemplo n.º 37
0
    homeTeamTag = 'team1'
    enemyTeamTag = 'team2'
elif ROBOT_ID == team2.id:
    homeTeamTag = 'team2'
    enemyTeamTag = 'team1'
else:
    print('Robot ne tekmuje.')
    sys.exit(0)

print('Robot tekmuje in ima interno oznako "' + homeTeamTag + '"')

# ------------------------------------------------------------------------------------------------------------------- #
# GLOBAL VARIABLES

gameData = GameData(gameState, homeTeamTag, enemyTeamTag)
controller = Controller(initialState=State.GET_HEALTHY_HIVE)

robotNearTargetOld = False

target = None
timeOld = time()

# ------------------------------------------------------------------------------------------------------------------- #
# MAIN LOOP

print('Izvajam glavno zanko. Prekini jo s pritiskom na tipko DOL.')
print('Cakam na zacetek tekme ...')

doMainLoop = True
while doMainLoop and not btn.down:
Ejemplo n.º 38
0
                   action='store_true',
                   help='Change control mode manual')
    p.add_argument('-ud',
                   '--uplinkdelay',
                   help='Uplink delay: Set uplink delay [ms]')
    p.add_argument('-dd',
                   '--downlinkdelay',
                   help='Downlink delay: Set downlink delay [ms]')
    p.add_argument('-ip', help='IP address')

    config = {}  #設定データは辞書で保持
    args = p.parse_args()
    if args.manual:
        config['manual'] = args.manual
    else:
        config['manual'] = False
    if args.uplinkdelay:
        config['uplinkdelay'] = float(args.uplinkdelay)
    else:
        config['uplinkdelay'] = 0.0
    if args.downlinkdelay:
        config['downlinkdelay'] = float(args.downlinkdelay)
    else:
        config['downlinkdelay'] = 0.0
    if args.ip:
        config['ip'] = str(args.ip)
    else:
        config['ip'] = 'localhost'

    geme = Controller(config)
"""
Created on Tue Apr  7 12:27:10 2020

@author: Bogdan
"""

'''
Decision Tree
'''

from Repository import Repo
from Controller import Controller
import sys

r = Repo('balance-scale.data')
c = Controller(r)

nrTests = 30

minv = sys.maxsize
maxv = 0
sumv = 0
for i in range(nrTests):
    r.loadFromFile(0.8)
    c.train()
    val = c.test()
    
    sumv += val
    if val > maxv:
        maxv = val
    if val < minv:
Ejemplo n.º 40
0
from Controller import Controller
import random


def test(pos, n):
    a = "panda"
    left = a[max(0, pos - n):pos]
    right = a[pos + 1:pos + n + 1]
    pattern = (n - len(left)) * '_' + left + '*' + right + (n -
                                                            len(right)) * '_'
    return pattern


if __name__ == "__main__":
    controller = Controller()
    controller.run()
    '''for p in range(4):
		print(test(p, 3))'''
    cost = tf.reduce_mean(cross_entropy)
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(
        cost, global_step=global_step)
    correct_prediction = tf.equal(y_pred_cls, tf_y_train_cls)
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    tf.summary.scalar('Accuracy', accuracy)
    tf.summary.scalar('loss/cost', cost)
    merged = tf.summary.merge_all()
    saver = tf.train.Saver()

tf.reset_default_graph()
with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    saver.restore(session, 'checkpoints/model.ckpt')
    cnt = Controller("127.0.0.1", 5003)
    #cnt.startController()

    controlsStr = "0:0:0:0"
    posInMatrixStr = "0:0:0"
    isRestarted = 0
    posMatrixSize = [30, 30, 30]
    posMatrix = np.zeros(
        (posMatrixSize[0], posMatrixSize[1], posMatrixSize[2]))
    lastTime = time.time()

    posMatThread = Thread(target=updatePositionMatrix, args=[])
    posMatThread.start()

    while True:
        data = None
Ejemplo n.º 42
0
def test_start_button(qtbot):
    root = Tk()
    command = Controller(master=root)
    qtbot.addWidget(command)
    qtbot.mouseClick(command.start_button, QtCore.Qt.LeftButton)
Ejemplo n.º 43
0
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 11:39:52 2020

@author: tamas
"""
from Repository import Repository
from Controller import Controller
from UI import Console

if __name__=="__main__":
    repo = Repository()
    contr = Controller(repo)
    console = Console(contr)
    console.run()
Ejemplo n.º 44
0
 def __init__(self):
     Controller.__init__(self)
Ejemplo n.º 45
0
 def __init__(self, path):
     self.myController = Controller(path)
Ejemplo n.º 46
0
 def __init__(self):
     self.__controller = Controller(self)
     # do stuff
     self.__controller.start()
     atexit.register(self.stop)
Ejemplo n.º 47
0
'''
Created on Feb 20, 2019

@author: Adrian
'''

from Repository import Repository
from Controller import Controller
from Console import Console

if __name__ == '__main__':

    repository = Repository("rooms.txt", "reservations.txt")
    controller = Controller(repository)
    console = Console(controller)

    console.start()
Ejemplo n.º 48
0
class MediaPlayer:
    __controller = None
    __playerType = 'shell'
    __playerCommand = 'mplayer'
    __playerProcess = None
    __playingFile = None
    __fileData = None

    def __init__(self):
        self.__controller = Controller(self)
        # do stuff
        self.__controller.start()
        atexit.register(self.stop)

    def __del__(self):
        self.stop()

    def play(self, file, name=None):
        if self.isPlaying:
            self.stop()
        shell = False
        if self.__playerType == 'shell':
            shell = True
        self.__playerProcess = subprocess.Popen(self.__playerCommand + ' ' +
                                                file,
                                                shell=shell,
                                                stdout=subprocess.DEVNULL,
                                                stderr=subprocess.DEVNULL,
                                                preexec_fn=os.setsid)
        self.__playingFile = file
        self.__fillFileData(file, name)

    def stop(self):
        os.killpg(os.getpgid(self.__playerProcess.pid), signal.SIGTERM)
        self.__fileData.close()
        self.__playingFile = None
        self.__playerProcess = None

    def __fillFileData(self, file, name=None):
        if file.lower().startswith('http://') or file.lower().startswith(
                'https://'):
            self.__fileData = IcyData(r_url=file,
                                      onUpdate=self.__onIcyUpdate,
                                      name=name,
                                      onInit=self.sendStatus)

    def __onIcyUpdate(self, data):
        data['action'] = 'updateIcyData'
        self.__controller.sendMessage(json.dumps(data))

    @property
    def isPlaying(self):
        return self.__playingFile is not None

    @property
    def playingFile(self):
        return self.__playingFile

    def sendStatus(self, peer=None):
        if peer is not None:
            self.__controller.sendMessage(self.status, peer.appType, peer.uid)
        else:
            self.__controller.sendMessage(self.status)

    @property
    def playing(self):
        return self.__playingFile is not None

    @property
    def status(self):
        data = {
            'playing': self.playing,
        }
        if self.playing:
            data['fileData'] = self.__fileData.data
        return json.dumps(data)
Ejemplo n.º 49
0
        with open(args.settings, 'r') as settingsfile:
            settings = json.load(settingsfile)

        with open(args.script, 'r') as sriptFile:
            script = sriptFile.readlines()

        #coms = ArduinoCommunicator(settings['COM'], settings['sensor'])
        coms = DebugCommunicator(settings['COM'], settings['sensor'])

        app = QtWidgets.QApplication(sys.argv)
        app.setStyle(QtWidgets.QStyleFactory.create('Fusion'))
        MainWindow = QtWidgets.QMainWindow()
        ui = gui.Ui_MainWindow()
        ui.setupUi(MainWindow)
        control = Controller(settings, coms, script, MainWindow)

        update_list(control.program)

        control.pump_changed.connect(update_pump)
        control.temp_changed.connect(update_temp)
        control.program_changed.connect(update_list)
        control.sensors_changed.connect(update_sensors)

        ui.PumpCheckBox.stateChanged.connect(lambda x: control.pump_toggle(bool(x)))

        ui.TempUpButton.clicked.connect(lambda x: control.shift_temp(0.5))
        ui.TempDownButton.clicked.connect(lambda x: control.shift_temp(-0.5))
        ui.TimeUpButton.clicked.connect(lambda x: control.shift_time(30))
        ui.TimeDownButton.clicked.connect(lambda x: control.shift_time(-30))
        ui.StepUpButton.clicked.connect(lambda x: control.shift_step(1))
Ejemplo n.º 50
0
import time
from operator import attrgetter

import matplotlib.pyplot as plt
from numpy import average

from Controller import Controller
from domain.Ant import Ant
from domain.Traces import Traces
from domain.Traces2 import Traces2

traces = Traces(Controller().read_string(0))
ants_result = []
for i in range(1000):
    ants = [Ant() for i in range(10)]
    for ant in ants:
        while len(ant.solution) < len(traces.matrix):
            ant.step(traces)
    traces.leave_trace(max(ants, key=attrgetter("fitness")))
    print(str(traces))
    ants_result.append(average([i.fitness for i in ants]))

plt.plot(ants_result)
plt.show()
print(min(ants_result))
Ejemplo n.º 51
0
from Controller import Controller
from DiscordBot import Bot
import yaml

CONFIG_FILE = 'AdaptBot.yml'

with open(CONFIG_FILE, 'r') as config_file:
    config = yaml.full_load(config_file)

my_controller = Controller(config.get('controller'))
my_client = Bot(config.get('discord'), my_controller)
my_client.run(config.get('bot_id'))
Ejemplo n.º 52
0
 def setUp(self):
     self.repository = Repository("Test_rooms.txt")
     self.controller = Controller(self.repository)
Ejemplo n.º 53
0
class Game():
    __delegate__ = None
    __bot__ = None
    __ai__ = None
    __turn__ = None
    board = None
    finishGame = False
    count_muertas = 0
    

    def __init__(self, delegate):
        print("init game")
        self.__delegate__ = delegate
        self.__turn__ = TurnUser.USER
    
    def setup(self):
        self.__bot__ = Controller()
        self.__ai__ = AIModule()
        
    def reset(self):
        self.__turn__ = TurnUser.USER

    def run(self):
        self.backupBoard()
        while self.shouldFinishGame() == False:
            if self.__turn__ == TurnUser.USER:
                self.makePlayer(self.board)
            else:
                self.makeRobot()
            self.backupBoard()
            self.changeTurn()

    def changeTurn(self):
        if self.__turn__ == TurnUser.USER:
            self.__turn__ = TurnUser.ROBOT
            self.speak_robot()
        else:
            self.__turn__ = TurnUser.USER
            self.speak_user()

    def backupBoard(self):
        self.board = self.__ai__.getTablero()

    def shouldFinishGame(self):
        #TODO: Mirar si finaliza pendiente
        return self.finishGame

    def makePlayer(self, tablero):
        self.__ai__.scanf(tablero)
        
    def makeRobot(self):
        tirada, muertas = self.__ai__.getMovimiento()
        self.accionMuertas(muertas)
        print("Tirada: "+str(tirada))
        print("Muertas: "+str(muertas))
        self.__bot__.move(tirada, muertas)
        
    
    def accionMuertas(self, muertas):
        if len(muertas) > 0:
            self.count_muertas += 1
            if self.count_muertas == 1:
                self.__delegate__.doAction("Eres muy malo", "jaja")
            elif self.count_muertas == 2:
                self.__delegate__.doAction("No me estarás dejando ganar... eh", "pesimo")
            elif self.count_muertas == 3:
                self.__delegate__.doAction("No te lo quería decir pero...", "loser")
            else:
                self.__delegate__.doAction("¡Perdedor!", "lastima")
                count_muertas = 0

    def getTurn(self):
        return self.__turn__

    def doCheat(self):
        if self.__turn__ == TurnUser.USER:
            self.speakCheat()
            self.__delegate__.doAction("", "cheat")
            self.makeRobot()
            self.__delegate__.cheatFinished()

    def doAbort(self):
        self.__bot__.abort()
    
    def speak_user(self):
        gif = None
        text = ""
        value = random.randint(0,15)
        if value == 1:
            text = "Qué hace una abeja en el gimnasio...\n - zúmba"
        elif value == 3:
            text = "Qué conduce Papa Noel...\n un Renol"
        elif value == 5:
            text = "Sabes cual es la fruta más graciosa...\n - la naranjajajajajajajaja"
            gif = "naranja"
        elif value == 6:
            text = "Eres un pendejo!"
            gif = "pendejo"
        elif value == 8:
            text = "Aguanta -wey"
            gif = "wey"
        self.__delegate__.doAction(text, gif)
    
    def speak_robot(self):
        gif = None
        text = ""
        value = random.randint(0,8)
        if value == 1:
            text = "Mira y aprende del jefe"
            gif = "robocop"
        elif value == 4:
            text = "Alojomora"
            gif = "HarryPotter"
        elif value == 5:
            text = "Soy mago, -el mago pajas"
            gif = "Magic"
        elif value == 6:
            text = "emmh..."
            gif = "thinking"
        elif value == 2:
            text = "Si sabes como me pongo... -pa que me invitas?"
            gif = "si sabes como me pongo"
        self.__delegate__.doAction(text, gif)
        
    def speakCheat(self):
        gif = None
        text = ""
        value = random.randint(0,6)
        if value == 1:
            text = ""
            gif = "evil"
        elif value == 2:
            text = ""
            gif = "666"
        else:
            text = ""
            gif = "tricky"
        self.__delegate__.doAction(text, gif)
Ejemplo n.º 54
0
        self.profile_listing.delete(0, tk.END)

        for profile in self.profiles:
            self.profile_listing.insert(tk.END, profile["name"])

        if self.selected_profile is not None:
            nameVar = tk.StringVar(self.root)
            name = tk.Entry(self.root, textvariable=nameVar)
            name.pack()

    def run(self):
        self.profile_scrollbar = tk.Scrollbar(self.root)
        self.profile_scrollbar.pack(side=tk.LEFT, pady=30)

        self.profile_listing = tk.Listbox(self.root, yscrollcommand=self.profile_scrollbar.set)
        for profile in self.profiles:
            self.profile_listing.insert(tk.END, profile["name"])

        self.profile_listing.bind("<<ListboxSelect>>", self.on_profile_select)
        self.profile_listing.pack(side=tk.LEFT, fill=tk.BOTH, pady=30)
        self.profile_scrollbar.config(command=self.profile_listing.yview)

        tk.Button(self.root, command=self.add_profile, text="+").place(x=20, y=0, width=27, height=27)
        tk.Button(self.root, command=self.remove_profile, text="-").place(x=52, y=0, width=27, height=27)

        self.root.mainloop()


if __name__ == '__main__':
    c = Controller()
    c.start()
Ejemplo n.º 55
0
 def __init__(self, id):
     Controller.__init__(self, id)
Ejemplo n.º 56
0
def main():
    global config
    parser = OptionParser()
    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      action="store_true",
                      help="verbose log output",
                      default=False)
    parser.add_option(
        "-e",
        "--expected-hostname",
        dest="expected_hostname",
        action="store",
        help=
        "expected hostname of current host. If hostname differs, agent will fail",
        default=None)
    (options, args) = parser.parse_args()

    expected_hostname = options.expected_hostname

    setup_logging(options.verbose)

    default_cfg = {'agent': {'prefix': '/home/ambari'}}
    config = ConfigParser.RawConfigParser(default_cfg)
    bind_signal_handlers()

    if (len(sys.argv) > 1) and sys.argv[1] == 'stop':
        stop_agent()

    # Check for ambari configuration file.
    config = resolve_ambari_config()

    # Starting data cleanup daemon
    data_cleaner = None
    if int(config.get('agent', 'data_cleanup_interval')) > 0:
        data_cleaner = DataCleaner(config)
        data_cleaner.start()

    perform_prestart_checks(expected_hostname)
    daemonize()

    # Starting ping port listener
    ping_port_listener = PingPortListener(config)
    ping_port_listener.start()

    update_log_level(config)

    server_url = 'https://' + config.get(
        'server', 'hostname') + ':' + config.get('server', 'url_port')
    print("Connecting to the server at " + server_url + "...")
    logger.info('Connecting to the server at: ' + server_url)

    # Wait until server is reachable
    netutil = NetUtil()
    netutil.try_to_connect(server_url, -1, logger)

    # Launch Controller communication
    controller = Controller(config)
    controller.start()
    controller.join()
    stop_agent()
    logger.info("finished")
Ejemplo n.º 57
0
class GUI(object):
    def __init__(self):
        self.root = Tk()
        self.controller = Controller()
        self.images_extensions = (("Image files", ("*.jpg", "*.png")), )
        self.guitar = "guitar.mp3"

        # Label del titulo
        #self.title = Label(self.root,text="Seleccione el archivo pickle para cargarlo")
        #self.title.grid(row=0,column=0)

        # Boton de elegir pickle

        self.choose = Button(self.root,
                             text="Browse",
                             command=self.load_file,
                             width=30)
        self.choose.grid(row=1, column=0)

        # Mensaje de seleccionado
        self.choose_text = "Seleccione un archivo binario"
        self.choose_error = "Eso no es un archivo binario"
        self.choose_msg = Label(self.root, text=self.choose_text)
        self.choose_msg.grid(row=1, column=1)

        # Boton de clasificar
        self.classify = Button(self.root,
                               text="Seleccionar imágen y clasificar",
                               command=self.load_image,
                               width=30)
        self.classify.grid(row=2, column=0)

        # Mensaje de clasificado
        self.classify_text = "Seleccione una imágen"
        self.classify_wait = "Clasificando imágen..."
        self.classify_msg = Label(self.root, text=self.classify_text)
        self.classify_msg.grid(row=2, column=1)

        #self.setup()
        self.root.mainloop()

    def classification(self, image):
        return self.controller.classify(image)

    def set_file(self, file):
        return self.controller.set_file(file)

    def load_file(self):
        file = askopenfilename(filetypes=(("Binary files", "*.*"), ))

        if file:
            extension = file.split("/")[-1]
            if not "." in extension:
                # selecciono un binary
                # todo
                text = self.set_file(file)
                self.choose_msg.config(text=text)
            else:
                # selecciono uno con extension
                self.choose_msg.config(text=self.choose_error)
        else:
            self.choose_msg.config(text=self.choose_error)

    def load_image(self):
        image = askopenfilename(filetypes=self.images_extensions)

        if image:
            # selecciono una img
            # todo
            self.classify_msg.config(text=self.classify_wait)
            text = self.classification(image)
            self.classify_msg.config(text=text)
            self.play(self.guitar)
        else:
            # selecciono uno con extension
            self.classify_msg.config(text=self.classify_text)

    def play(self, sound):
        mixer.init()
        mixer.music.load(sound)
        mixer.music.play()
Ejemplo n.º 58
0
    # el arbol
    else:
        if contWait < 3:
            contWait += 1
        else:
            wait = False
            contWait = 0

    return trace_calls


command = "from " + file + " import " + function + " as func"
exec(command)

tr = sys.gettrace()  # Guardo la traza original del programa
sys.settrace(trace_calls)  # Traceo la ejecucion del programa

try:
    func()
except Exception:
    None

sys.settrace(tr)  # Cargo la traza original guardada

if fusion:
    arbol.fusionNodos()
arbol.calcularPeso()

controller = Controller(arbol, graphics)
controller.run()
Ejemplo n.º 59
0
import struct
from Controller import Controller

ctl = Controller(1)

axis_ids = {
    'x': 0x83,
    'y': 0x84,
    'z': 0x85,
    'rx': 0x86,
    'ry': 0x87,
    'rz': 0x88,
}

axis_lookup = {
    0x83: lambda ctl, v: ctl.set_x(v),
    0x84: lambda ctl, v: ctl.set_y(v),
    0x85: lambda ctl, v: ctl.set_z(v),
    0x86: lambda ctl, v: ctl.set_rx(v),
    0x87: lambda ctl, v: ctl.set_ry(v),
    0x88: lambda ctl, v: ctl.set_rz(v),
    0x89: lambda ctl, v: ctl.set_slider_0(v),
    0x90: lambda ctl, v: ctl.set_slider_1(v),
}


def on_packet(packet):
    m = list(packet)
    h = m[0]

    if h == 0xff:
Ejemplo n.º 60
0
import logging
from logging.handlers import TimedRotatingFileHandler

from Controller import Controller

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# TODO: This should be configurable
f_handler = TimedRotatingFileHandler("controller.log",
                                     when="d",
                                     interval=1,
                                     backupCount=7)
f_handler.setLevel(logging.INFO)
f_format = logging.Formatter("%(asctime)s:%(levelname)s: %(message)s")
f_handler.setFormatter(f_format)
logger.addHandler(f_handler)

logger.info("Controller started")

thisController = Controller(logger)

# Never reach here!
logger.info("Controller stopping")
logging.shutdown()