Пример #1
0
def write ( value ):

	global activeSector
	global activeCursor

	# Start going through the value from the start
	positionInValue = 0

	# Stop when all characters have been written
	while positionInValue < len(value):

		# If the cursor was reset, clear the next sector before proceeding
		if activeCursor == 0:
			clearNextSector()

		# Number of bytes we can still fill
		remainingInPage = Interface.CHUNK_SIZE - (activeCursor % Interface.CHUNK_SIZE)

		# Get the part of the value that fits in the current page
		chunk = value[positionInValue:(positionInValue + remainingInPage)]
		chunkLength = len(chunk)

		Interface.writeData(activeSector, activeCursor, chunk)

		# Move pointers
		activeCursor = activeCursor + chunkLength
		positionInValue = positionInValue + chunkLength

		# Wrap both the page cursor and the sector pointer, if needed
		if activeCursor > Interface.SECTOR_SIZE - 1:
			activeCursor = 0
			activeSector = activeSector + 1
			if activeSector > Interface.SECTOR_COUNT - 1:
				activeSector = 0
class Application:

    #. Contructor .#
    def __init__ (self):
        self.interface = Interface(self.ButtonCallBack)    # Create an interface
        self.graph = Graph()                               # Create a graph
        self.graph.formGraph()                             # Form the graph
        
    #. Call back function when button is pressed .#
    def ButtonCallBack(self):
        startName = self.interface.getStartEntry().encode('gbk')
        destName = self.interface.getDestEntry().encode('gbk')
        start = self.graph.findVertex(startName)           # Find the start vertex
        dest = self.graph.findVertex(destName)             # Find the dest vertex
        # If start or dest are not found
        if start == None:
            result = startName.encode('utf8') + ' doesn\'t exist'
        elif dest == None:
            result = destName.encode('utf8') + ' doesn\'t exist'
        else:    # Normal case
            self.graph.BFS(start)
            result = self.graph.shortestPath(dest).encode('utf8')
        self.interface.updateText(result)

    #. Run the program .#
    def run(self):
        mainloop()
Пример #3
0
def initialize ( ):

	global activeSector
	global activeCursor
	global sessionStart
	global readSector

	sector = 0x00

	while 1:

		# Read at sector start
		fetch = Interface.readFirstSectorByte(sector)

		if fetch == 0xFF:
			Interface.readFirstSectorByte(sector)
			break;

		sector = sector + 1

		# Wrap back to the first sector on overflow
		if sector > Interface.SECTOR_COUNT - 1:
			sector = 0x00
			break;

	# Make very sure the sector is empty.
	#Interface.eraseSector(sector)

	activeSector = sector
	activeCursor = 0x00

	sessionStart = activeSector
	readSector = activeSector

	return sessionStart
Пример #4
0
def camera_worker(queue,camera_values,arduino_values,trigger,gui=None):
    """
    The thread worker used to start, format, and end communication with the Ximea camera integral for the operation of ProjectScarberry.
        :argument queue: The queue used to store all of the pictures recieved from XimeaController.
        :type queue: Queue.Queue
        :argument camera_values: All of the XimeaController settings in ScarberrySettings.
        :type camera_values: dict
        :argument arduino_values: All of the Arduino settings in ScarberrySettings.
        :type arduino_values: dict
        :argument trigger: The ThreadTrigger which contains all of the booleans for thread syncing.
        :type trigger: ThreadTrigger
        :keyword gui: Optional interface used to print.
        :type gui: Interface.ScarberryGui
    """
    global abort
    camera = XimeaController.XimeaCamera(arduino_values.get("FrameRate"),
                                         gain=camera_values.get("Gain"),
                                         gui=gui)
    wait = True
    trigger.set_on('startArduino')
    while not trigger.get(name='startCamera') and wait:
        if abort:
            wait = False
    if not abort:
        camera.start_acquisition()
        while trigger.get(name='startCamera') and not abort:
            current_image = camera.get_image()
            queue.put(current_image)
        camera.stop_acquisition()
        trigger.set_off('runProcess')
    Interface.choose_print(gui, 'camera', 'CameraThread: Finished')
Пример #5
0
def arduino_worker(arduino_values,main_values,trigger,gui=None):
    """
    The thread worker used to start, format, and end communication with the Arduino integral for the operation of ProjectScarberry.
        :argument arduino_values: All of the Arduino settings in ScarberrySettings.
        :type arduino_values: dict
        :argument main_values: All of the Main settings in ScarberrySettings.
        :type main_values: dict
        :argument trigger: The ThreadTrigger which contains all of the booleans for thread syncing.
        :type trigger: ThreadTrigger
        :keyword gui: Optional interface used to print.
        :type gui: Interface.ScarberryGui
    """
    global abort
    wait = True
    controller = ArduinoController.ArduinoController(arduino_values.get("SerialPort"),gui=gui)
    if not abort:
        controller.write_value(arduino_values.get("FrameRate"))
        controller.write_value(arduino_values.get("StrobeCount"))
        controller.write_value(arduino_values.get("DutyCycle"))
    while not trigger.get(name='startArduino') and wait:
        if abort:
            wait = False
    if not abort:
        controller.write_value(1)
        trigger.set_on('startCamera')
        time.sleep(float(main_values.get("RunTime"))+1)
        controller.write_value(4)
        trigger.set_off('startCamera')
    Interface.choose_print(gui, 'arduino', 'ArduinoThread: Finished')
Пример #6
0
class Manipulator(avango.script.Script):
  #InterfaceTransform = avango.gua.SFMatrix4()
  ObjectTransform = avango.gua.SFMatrix4()
  Keyboard = KeyboardDevice()
  Pointer = PointerDevice()

  def __init__(self):
    self.super(Manipulator).__init__()
    self.always_evaluate(True)

  def my_constructor(self, SCENE, OBJECT):
	  #self.OutTransform.value = OBJECT.Transform.value
    self.SCENE = SCENE
    self.OBJECT = OBJECT
    self.ACTIV = False
    self.INTERFACE = Interface()

  def evaluate(self):
    if self.Pointer.sf_key_pageup.value and self.ACTIV == False:
      self.ACTIV = True
      self.INTERFACE.my_constructor(self.SCENE, self.OBJECT.Transform.value.get_scale(), 2)
    if self.Pointer.sf_key_pagedown.value and self.ACTIV == True:
      self.ACTIV = False
      self.SCENE.Root.value.Children.value.remove(self.INTERFACE.interface_node)

    if self.ACTIV:
      if self.Keyboard.KeyLeft.value:
        self.OBJECT.Transform.value *= avango.gua.make_scale_mat(0.9, 0.9, 0.9)
#        self.InterfaceTransform
      if self.Keyboard.KeyRight.value:
        self.OBJECT.Transform.value *= avango.gua.make_scale_mat(1.1, 1.1, 1.1)
Пример #7
0
def save_worker(save_queue, data_queue, process_values, trigger, session_count, gui=None):
    """
    The thread worker used save and analyze the pictures from CameraThread.
        :argument queue: The queue used to store all of the pictures recieved from XimeaController.
        :type queue: Queue.Queue
        :argument process_values: All of the ProcessImage settings in ScarberrySettings.
        :type process_values: dict
        :argument trigger: The ThreadTrigger which contains all of the booleans for thread syncing.
        :type trigger: ThreadTrigger
        :argument session_count: The number of the current instance of the threads
        :type session_count: int
        :keyword gui: Optional interface used to print.
        :type gui: Interface.ScarberryGui
    """
    global abort
    pic_count = 0
    while trigger.get(name='runProcess') and not abort:
        while not save_queue.empty() and not abort:
            pic = save_queue.get()
            Interface.choose_print(gui, 'save', 'pic {} hex: {}'.format(pic_count,pic))
            formated_number = ProcessImage.format_number(pic_count,int(process_values.get("NumberPadding")))
            save_name = process_values.get("BaseName")
            if process_values.get("Count") > 0:
                save_name = '{}.{}'.format(save_name,session_count)
            ProcessImage.save_image(pic,
                                    formated_number,
                                    image_direcoty=process_values.get("ImageDirectory"),
                                    name=save_name,
                                    extention=process_values.get("FileExtension"))
            data_queue.put(pic)
            pic_count += 1
    trigger.set_off('runData')
    Interface.choose_print(gui, 'save', 'SaveImageThread: Finished')
Пример #8
0
    def parse(cls, desc):
        """
        
        Parse the description of this IP object from a dictionary
        return a defaultdictionary built from the key-value pairs.

        Arguments:

        d -- A dictionary with the parameters for this Description object
        
        """
        d = dict()
        cls.parse_keys(desc)
        n = cls.parse_name(desc)
        d["name"] = n
        ifs = cls.parse_interfaces(desc)
        d["interfaces"] = ifs
        for i in ifs:
            d[i] = Interface.construct(i)(desc[i])
        if("Kernel" not in ifs):
            ifs.append("Kernel")
            d["Kernel"] = Interface.construct("Kernel")({"type":"Kernel"})

        if("Host" not in ifs):
            ifs.append("Host")
            d["Host"] = Interface.construct("Host")({"type":"Host"})
        return d
Пример #9
0
def clearNextSector ( ):
	global activeSector

	next = activeSector + 1
	if next > Interface.SECTOR_COUNT - 1:
		next = 0

	Interface.eraseSector( next )
Пример #10
0
 def get_image(self):
     """
     Prompts the Ximea camera to capture a photo after the next GPI spike.
     """
     try:
         self.camera.get_image(self.image)
         return self.image.get_image_data_numpy()
     except xiapi.Xi_error:
         Interface.choose_print(self.gui, 'camera', 'Xi_error: ERROR 10: Timeout')
         Main.abort_session()
         return None
Пример #11
0
def initialize():
    """Initializes interface, images, and other global variables we need."""
    
    #Initialize all the windows and other things needed for the program interface
    #Set up the windows containing the image from the kinect camera, the altered 
    #	threshold image the threshold sliders, and the kinect range image.  
    Interface.initialize(D)

    #Set the method to handle incoming mouse data in the Image window
    cv.SetMouseCallback('Image', HandleData.mouseImage, None)
    
    #Set the method to handle incoming mouse data in the Range window
    cv.SetMouseCallback('Range', HandleData.mouseRange, None)
Пример #12
0
def data_worker(queue, process_values, trigger, session_count, gui=None):
    """
    The thread worker used save and analyze the pictures from CameraThread.
        :argument queue: The queue used to store all of the pictures recieved from XimeaController.
        :type queue: Queue.Queue
        :argument process_values: All of the ProcessImage settings in ScarberrySettings.
        :type process_values: dict
        :argument trigger: The ThreadTrigger which contains all of the booleans for thread syncing.
        :type trigger: ThreadTrigger
        :argument session_count: The number of the current instance of the threads
        :type session_count: int
        :keyword gui: Optional interface used to print.
        :type gui: Interface.ScarberryGui
    """
    global abort
    pic_count = 0
    data_directory = process_values.get("ImageDirectory") + '\\data'
    if not os.path.exists(data_directory):
        os.makedirs(data_directory)
    while trigger.get(name='runData') and not abort:
        while not queue.empty() and not abort:
            pic = queue.get()
            Interface.choose_print(gui, 'data', 'pic {} hex: {}'.format(pic_count, pic))
            formated_number = ProcessImage.format_number(pic_count, int(process_values.get("NumberPadding")))
            save_name = process_values.get("BaseName")
            if process_values.get("Count") > 0:
                save_name = '{}.{}'.format(save_name, session_count)
            data_filename = '{}\\data-{}_{}{}'.format(data_directory,
                                                      save_name,
                                                      formated_number,
                                                      '.txt')
            if process_values.get("SaveDraw"):
                ProcessImage.draw_and_data(pic,
                                           '{}\\data\\data-{}_{}{}'.format(process_values.get("ImageDirectory"),
                                                                           save_name,
                                                                           formated_number,
                                                                           process_values.get("FileExtension")),
                                           data_filename,
                                           process_values.get("BlurValue"),
                                           process_values.get("ThreshLimit"),
                                           draw_rois=process_values.get("DrawROIs"),
                                           draw_centroid=process_values.get("DrawCentroid"),
                                           draw_colours=process_values.get("DrawColour"),
                                           draw_count=process_values.get("DrawCount"))
            else:
                data = ProcessImage.get_data(pic,
                                             process_values.get("BlurValue"),
                                             process_values.get("ThreshLimit"))
                ProcessImage.save_data(data, data_filename)
            pic_count += 1
    Interface.choose_print(gui, 'data', 'DataImageThread: Finished')
Пример #13
0
 def __init__(self,screen,font):
     self.ui = Interface.interface(screen,font)
     self.screen = screen
     self.font = font
     self.player_init()
     self.run()
     self.over()
Пример #14
0
 def run(self):
     from Datas.Globals import worlds_locks
     file_name = "User_code." + self.name
     import_file = importlib.import_module(file_name, package="User_code")
     
     worlds_locks[self.name].acquire()
     import_file.declaration()
     Interface.add_methods("turtle", import_file.turtles_methods_dictionary)
     Interface.add_methods("patch", import_file.patches_methods_dictionary)
     import_file.setup()
     worlds_locks[self.name].release()
            
     while self.run_bool == True:
         worlds_locks[self.name].acquire()
         self.world_processing(import_file.go)
         worlds_locks[self.name].release()
Пример #15
0
    def on_message(self,message):    
        print 'server received:', message

        # get name of floorplan and send back wall candidates
        if message.startswith('act_pos#'):
            lat,lon = message.split('#')[1].split('$')
            lat,lon = float(lat), float(lon)
            ### FAKY FAKY
            #lat,lon = ( 52.480658, 13.465260 )
            client_connections[self.id].act_pos = (lat,lon)
            print 'new act_pos', client_connections[self.id].act_pos

        if message.startswith('dst_pos#'):
            lat,lon = message.split('#')[1].split('$')
            lat,lon = float(lat), float(lon)
            client_connections[self.id].dst_pos = (lat,lon)
            print 'dst lat',lat,'lon',lon
    
            _number_of_bikes,_radius = 10, 0.5
            list_of_jobs = Interface.get_closest_bikes(db_connection, client_connections[self.id].act_pos[0],client_connections[self.id].act_pos[1],lat,lon, number_of_bikes = _number_of_bikes, radius = _radius)
            print 'list len',len(list_of_jobs)
            print 'act',client_connections[self.id].act_pos
            for _job in list_of_jobs:
                # possible _job.value, _job.position, _job.target
                client_connections[self.id].ws.write_message('bike_pos#'+str(_job.position.latitude)+'$'+str(_job.position.longitude)+'$'+str(_job.value))
                print 'bike_pos', client_connections[self.id].act_pos, 'dst_pos', client_connections[self.id].dst_pos, 'job to do',_job
                _job.print_job()
Пример #16
0
 def __init__(self):
     # This is called on program startup.
     self.filepath = "C:/lab/cultmaker/savedgames"
     self.cult = False
     # self.enemies = False //pointed to by cult?
     # self.government = False
     self.interface = Interface()
     pass
def testloadratings(ratingstablename, filepath, openconnection, rowsininpfile):
    """
    Tests the load ratings function
    :param ratingstablename: Argument for function to be tested
    :param filepath: Argument for function to be tested
    :param openconnection: Argument for function to be tested
    :param rowsininpfile: Number of rows in the input file provided for assertion
    :return:Raises exception if any test fails
    """
    MyAssignment.loadratings(ratingstablename, filepath, openconnection)
    # Test 1: Count the number of rows inserted
    with openconnection.cursor() as cur:
        cur.execute('SELECT COUNT(*) from {0}'.format(RATINGS_TABLE))
        count = int(cur.fetchone()[0])
        if count != rowsininpfile:
            raise Exception(
                'Expected {0} rows, but {1} rows in \'{2}\' table'.format(rowsininpfile, count, RATINGS_TABLE))
def testroundrobinpartition(ratingstablename, numberofpartitions, openconnection, robinpartitiontableprefix,
                            partitionstartindex):
    """
    Tests the round robin partitioning for Completness, Disjointness and Reconstruction
    :param ratingstablename: Argument for function to be tested
    :param numberofpartitions: Argument for function to be tested
    :param openconnection: Argument for function to be tested
    :param robinpartitiontableprefix: This function assumes that you tables are named in an order. Eg: robinpart1, robinpart2...
    :param partitionstartindex: Indicates how the table names are indexed. Do they start as robinpart1, 2 ... or robinpart0, 1, 2...
    :return:Raises exception if any test fails
    """
    try:
        MyAssignment.roundrobinpartition(ratingstablename, numberofpartitions, openconnection)
    except Exception:
        # ignore any exceptions raised by function
        pass
    testrangeandrobinpartitioning(numberofpartitions, openconnection, robinpartitiontableprefix, partitionstartindex)
Пример #19
0
def editMeny():

    repty = Interface.inpyt_meny(outBD())

    if repty == 'add':
        add()
    elif repty == 'exit':
        return 0
def testrangeinsert(ratingstablename, userid, itemid, rating, openconnection, expectedtablename):
    """
    Tests the range insert function by checking whether the tuple is inserted in he Expected table you provide
    :param ratingstablename: Argument for function to be tested
    :param userid: Argument for function to be tested
    :param itemid: Argument for function to be tested
    :param rating: Argument for function to be tested
    :param openconnection: Argument for function to be tested
    :param expectedtablename: The expected table to which the record has to be saved
    :return:Raises exception if any test fails
    """
    try:
        MyAssignment.rangeinsert(ratingstablename, userid, itemid, rating, openconnection)
    except Exception:
        # ignore any exceptions raised by function
        pass
    if not testrangerobininsert(expectedtablename, itemid, openconnection, rating, userid):
        raise Exception(
            'Range insert failed! Couldnt find ({0}, {1}, {2}) tuple in {3} table'.format(userid, itemid, rating,
                                                                                          expectedtablename))
Пример #21
0
    def run(self):
        from Datas.Globals import worlds_locks
        
        # Load the file corresponding to this world
        file_name = "User_code." + self.name
        import_file = importlib.import_module(file_name, package="User_code")
        
        worlds_locks[self.name].acquire()
        # The declaration method creates new classes and add attributes to existing ones
        import_file.declaration()
        # Add every methods created by the user to their class
        Interface.add_methods("turtle", import_file.turtles_methods_dictionary)
        Interface.add_methods("patch", import_file.patches_methods_dictionary)
        # Setup the world with the initial values given by the user
        import_file.setup()
        worlds_locks[self.name].release()

        while self.run_bool == True :
            worlds_locks[self.name].acquire()
            self.world_processing(import_file.go)
            worlds_locks[self.name].release()
            time.sleep(self.sleep_time)
Пример #22
0
    def __init__(self,framerate,gain=0,gui=None):
        """
        Initializes an instance of XimeaCamera.
            :argument framerate: Number of pictures taken a second.
            :type framerate: int
            :keyword gain: Brightness modifier of pictures taken.
            type gain: int, float [0 to 6](default 0)
            :keyword gui: Optional interface used to print(default None).
            :type gui: Interface.ScarberryGui
        """
        self.gui = gui
        self.image = xiapi.Image()

        self.camera = xiapi.Camera()
        Interface.choose_print(gui, 'camera', 'Opening camera...')
        try:
            self.camera.open_device()

            exposure = (1000000 / (int(framerate)))
            exposure -= math.pow(10, math.floor(math.log(exposure, 10)) - 1)
            self.camera.set_exposure(int(exposure))

            if gain < 0:
                gain = 0
            if gain > 6:
                gain = 6
            self.camera.set_gain(float(gain))

            self.camera.set_trigger_source('XI_TRG_EDGE_RISING')
            self.camera.set_gpi_mode('XI_GPI_TRIGGER')
            self.camera.set_gpo_selector('XI_GPO_PORT1')
            self.camera.set_gpo_mode('XI_GPO_FRAME_TRIGGER_WAIT')
            self.camera.set_imgdataformat('XI_MONO8')
        except xiapi.Xi_error:
            Interface.choose_print(gui, 'camera', 'Xi_error: ERROR 56: No Devices Found')
            Main.abort_session()
Пример #23
0
def read ( ):

	global readSector
	global activeSector

	if readSector > activeSector:
		return 0

	data = Interface.readSector(readSector)

	readSector = readSector + 1
	if readSector >= Interface.SECTOR_COUNT:
		readSector = 0

	return data
Пример #24
0
Файл: Main.py Проект: oJieg/engl
def menMain():

    repty = Interface.general_memy()
    if repty == 'edit':
        InpWord.editMeny()
        menMain()
        # elif inp == '2':
        # outBD()
    elif repty == 'test':
        TestWord.HelloTestMeny("ru")
        menMain()
    # elif repty == "exit":

    elif repty == "new bd":
        con = sqlite3.connect("MaimBD.db")
        cur = con.cursor()
        cur.execute(
            "create table Glassary (ID integer primary key, EngWord, RuWord, coif DEFAULT 10, dataRepeat, Enable BLOB)")
Пример #25
0
 def write_value(self,value):
     """
     Write a value to the Arduino over Serial.
         :argument value: Value to be written to Arduino
         :type value: string, int, float
         :argument pause: Amount of time spent paused in seconds
         :type pause: int, float
     """
     Interface.choose_print(self.gui, 'arduino', 'Writing "{}"...'.format(value))
     try:
         self.serial.write('{}'.format(value))
         self.serial.readline()
         Interface.choose_print(self.gui, 'arduino', 'Wrote: {}'.format(value))
     except serial.SerialException:
         Interface.choose_print(self.gui,
                                'arduino',
                                'SerialException: WriteFile failed')
         Main.abort_session()
Пример #26
0
 def __init__(self,com_number,gui=None):
     """
     Initializes an instance of ArduinoController.
         :argument com_number: Port number of the Arduino.
         :type com_number: int
         :keyword gui: Optional interface used to print(default None).
         :type gui: Interface.ScarberryGui
     """
     self.gui = gui
     try:
         self.serial = serial.Serial('COM{}'.format(com_number),115200)
         Interface.choose_print(gui, 'arduino', 'Waiting for COM{}...'.format(com_number))
         print('Waiting for COM{}...'.format(com_number))
         time.sleep(ArduinoController.INITIAL_SLEEP);
         Interface.choose_print(gui, 'arduino', 'Connected to COM{}.'.format(com_number))
         print('Connected to COM{}.'.format(com_number))
     except serial.SerialException:
         Interface.choose_print(self.gui,
                                'arduino',
                                'SerialException: could not open COM{}'.format(com_number))
         Main.abort_session()
Пример #27
0
game = Core.Game(screen, screen_height, screen_width, N, signs, game_font)
menu = pygame.image.load("pics/qop_arcana_bg.png").convert()
menu = pygame.transform.scale(menu, (screen_height, screen_height))
side = 0

while not finished:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finished = True
        else:
            if condition == 0:
                screen.blit(menu, (0, 0))
                for option in options:
                    option.draw()
                text = Interface.menu_event(options)
                if text == "START GAME":
                    game = Core.Game(screen, screen_height, screen_width, N,
                                     signs, game_font)
                    game.start_game()
                    condition = 1
                elif text == "EXIT":
                    finished = True
                    pygame.quit()
                    sys.exit()
            elif condition == 1:
                condition, side = game.check_end_game()
                game.redraw()
                game.draw_moves()
                game.unit.light()
                finish = Interface.game_event(event, game)
Пример #28
0
def testInterface():
    # test constructor __init__, getFactList, addFact, and deleteFact
    errorList = []
    interface1 = Interface.Interface(errorList.append)
    assert (interface1.getFactList() == [])

    relation1 = Relation.Relation("1")
    interface1.addFact(relation1)
    assert (interface1.getFactList() == [relation1])

    relation2 = Relation.Relation("0")
    interface1.addFact(relation2)
    assert (interface1.getFactList() == [relation1, relation2])

    relation3 = Relation.Relation("[0]")
    interface1.addFact(relation3)
    assert (interface1.getFactList() == [relation1, relation2, relation3])

    assert (len(errorList) == 0)
    interface1.deleteFact(-1)
    assert (interface1.getFactList() == [relation1, relation2, relation3])
    assert (len(errorList) == 1)

    interface1.deleteFact(0)
    assert (interface1.getFactList() == [relation2, relation3])
    interface1.deleteFact(1)
    assert (interface1.getFactList() == [relation2])

    interface1.deleteFact(1)
    assert (interface1.getFactList() == [relation2])
    assert (len(errorList) == 2)

    relation4 = Relation.Relation("2")
    interface1.addFact(relation4)
    assert (interface1.getFactList() == [relation2])
    assert (len(errorList) == 3)

    # testing setRequest, and getRequest
    interface1.setRequest(relation4)
    assert (len(errorList) == 4)
    request = interface1.getRequest()
    assert (request == None)
    assert (len(errorList) == 5)

    relation5 = Relation.Relation("[1]")
    interface1.setRequest(relation5)
    request = interface1.getRequest()
    assert (request == relation5)
    assert (len(errorList) == 5)

    errorList.clear()

    # testing generateProcessor, and retrieveSoughtInformation
    interface2 = Interface.Interface(errorList.append)
    interface2.retrieveResponse()
    assert (len(errorList) == 1)
    interface2.generateProcessor()
    assert (len(errorList) == 2)

    interface2.addFact(Relation.Relation("1"))
    interface2.setRequest(Relation.Relation("1"))
    interface2.generateProcessor()
    assert (len(errorList) == 2)
    interface2.generateProcessor()
    assert (len(errorList) == 2)

    errorList.clear()

    interface3 = Interface.Interface(errorList.append)
    handler = interface3.generateProcessor()
    assert (handler == None)
    assert (len(errorList) == 1)

    interface3.addFact(Relation.Relation("[1]"))
    interface3.setRequest(Relation.Relation("[1]"))
    handler = interface3.generateProcessor()
    assert (len(errorList) == 1)
    assert (handler != None)

    interface3.retrieveResponse()
    assert (len(errorList) == 2)
    handler()
    interface3.retrieveResponse()

    quaesitum = interface3.retrieveResponse()
    assert (len(errorList) == 2)
    assert (quaesitum.getNumerator().evaluate() /
            quaesitum.getDenominator().evaluate() == 0)

    errorList.clear()

    interface3 = Interface.Interface(errorList.append)
    interface3.addFact(Relation.Relation("[1](1 - [0])"))
    interface3.addFact(Relation.Relation("[0](1 - [1])"))
    interface3.setRequest(Relation.Relation("[1]"))
    quaesitum = interface3.retrieveResponse()
    assert (len(errorList) == 1)
    handler = interface3.generateProcessor()
    quaesitum = interface3.retrieveResponse()
    assert (quaesitum == None)
    assert (len(errorList) == 2)
    handler()
    quaesitum = interface3.retrieveResponse()
    assert (quaesitum != None)
    assert (len(errorList) == 2)
Пример #29
0
 def OnExit(self, event):
     self.Hide()
     MyFrame = Interface.MainFrame()
     app.SetTopWindow(MyFrame)
     MyFrame.Show(True)
     event.Skip()
Пример #30
0
from __future__ import print_function
import Interface as foo

g = 25


def f(x):
    global g
    tmp = g * x
    g = 13
    return tmp


print("Python:", g)

foo.frontend(f)

print("Python:", g)

foo.frontend(f)
Пример #31
0
from Interface import *
from tkinter import *

window = Tk()
window.title("SudoKawaii")
interface = Interface(window)

window.mainloop()

window.destroy()
Пример #32
0
class Chip8:
    def __init__(self):
        self.key_inputs = [0] * 16
        self.display = [0] * 64 * 32
        self.mem = [0] * 4096

        self.opcode = 0
        self.vx = 0
        self.vy = 0
        self.r = 0
        self.registers = [0] * 16
        self.sound_timer = 0
        self.delay_timer = 0
        self.index = 0
        self.pc = 0x200

        self.key_wait = False

        self.stack = []
        self.interface = Interface(64, 32, 10)

        self.fonts = [0xF0, 0x90, 0x90, 0x90, 0xF0,  # 0
                      0x20, 0x60, 0x20, 0x20, 0x70,  # 1
                      0xF0, 0x10, 0xF0, 0x80, 0xF0,  # 2
                      0xF0, 0x10, 0xF0, 0x10, 0xF0,  # 3
                      0x90, 0x90, 0xF0, 0x10, 0x10,  # 4
                      0xF0, 0x80, 0xF0, 0x10, 0xF0,  # 5
                      0xF0, 0x80, 0xF0, 0x90, 0xF0,  # 6
                      0xF0, 0x10, 0x20, 0x40, 0x40,  # 7
                      0xF0, 0x90, 0xF0, 0x90, 0xF0,  # 8
                      0xF0, 0x90, 0xF0, 0x10, 0xF0,  # 9
                      0xF0, 0x90, 0xF0, 0x90, 0x90,  # A
                      0xE0, 0x90, 0xE0, 0x90, 0xE0,  # B
                      0xF0, 0x80, 0x80, 0x80, 0xF0,  # C
                      0xE0, 0x90, 0x90, 0x90, 0xE0,  # D
                      0xF0, 0x80, 0xF0, 0x80, 0xF0,  # E
                      0xF0, 0x80, 0xF0, 0x80, 0x80  # F
                      ]

        for i in range(80):
            self.mem[i] = self.fonts[i]

        self.funcmap = {
            0x0000: self._0ZZZ,
            0x00e0: self._00E0,
            0x00ee: self._00EE,
            0x1000: self._1NNN,
            0x2000: self._2NNN,
            0x3000: self._3XNN,
            0x4000: self._4XNN,
            0x5000: self._5XY0,
            0x6000: self._6XNN,
            0x7000: self._7XNN,
            0x8000: self._8ZZZ,
            0x8FF0: self._8XY0,
            0x8ff1: self._8XY1,
            0x8ff2: self._8XY2,
            0x8ff3: self._8XY3,
            0x8ff4: self._8XY4,
            0x8ff5: self._8XY5,
            0x8ff6: self._8XY6,
            0x8ff7: self._8XY7,
            0x8ffE: self._8XYE,
            0x9000: self._9XY0,
            0xA000: self._ANNN,
            0xB000: self._BNNN,
            0xC000: self._CXNN,
            0xD000: self._DXYN,
            0xE000: self._EZZZ,
            0xE00E: self._EX9E,
            0xE001: self._EXA1,
            0xF000: self._FZZZ,
            0xF007: self._FX07,
            0xF00A: self._FX0A,
            0xF015: self._FX15,
            0xF018: self._FX18,
            0xF01E: self._FX1E,
            0xF029: self._FX29,
            0xF033: self._FX33,
            0xF055: self._FX55,
            0xF065: self._FX65
        }

    def loadROM(self, rom):
        print("Проверка")
        romOpen = open(rom, 'rb').read()
        print(romOpen)
        for i in range(len(romOpen)):
            self.mem[i + 0x200] = romOpen[i]

        print("ГОТОВО")

    def cycle(self):
        self.opcode = (self.mem[self.pc] << 8) | self.mem[self.pc + 1]

        self.vx = (self.opcode & 0x0f00) >> 8
        self.vy = (self.opcode & 0x00f0) >> 4

        self.pc += 2

        extracted_opcode = self.opcode & 0xf000
        try:
            self.funcmap[extracted_opcode]()
        except:
            print("Unknown opcode: {0:x}".format(self.opcode))

        if self.delay_timer > 0:
            self.delay_timer -= 1
        if self.sound_timer > 0:
            self.sound_timer -= 1

            if self.sound_timer == 0:
                pass
                # play sounds here

    def _0ZZZ(self):
        """Поиск конкретного опкода с началом "0" """
        extracted_opcode = self.opcode & 0xf0ff
        try:
            self.funcmap[extracted_opcode]()
        except:
            print("Unknown opcode: {0:x}".format(self.opcode))


    def _00E0(self):
        """Очистить экран"""
        self.display = [0] * 64 * 32


    def _00EE(self):
        """Возвратиться из подпрограммы"""
        self.pc = self.stack.pop()


    def _1NNN(self):
        """Перейти по адресу NNN."""
        self.pc = (self.opcode & 0x0fff)


    def _2NNN(self):
        """Вызов подпрограммы по адресу NNN"""
        self.stack.append(self.pc)
        self.pc = self.opcode & 0x0fff


    def _3XNN(self):
        """Пропустить следующую инструкцию, если регистр Vx = NN
        """
        if self.registers[self.vx] == (self.opcode & 0x00ff):
            self.pc += 2


    def _4XNN(self):
        """Пропустить следующую инструкцию, если регистр Vx != NN
        """
        if self.registers[self.vx] != (self.opcode & 0x00ff):
            self.pc += 2


    def _5XY0(self):
        """Пропустить следующую инструкцию, если Vx = Vy
        """
        if self.registers[self.vx] == self.registers[self.vy]:
            self.pc += 2


    def _6XNN(self):
        """Загрузить в регистр Vx число NN, т.е. Vx = NN
        """
        self.registers[self.vx] = self.opcode & 0x00ff


    def _7XNN(self):
        """Установить Vx = Vx + NN
        """
        self.registers[self.vx] += (self.opcode & 0xff)
        self.registers[self.vx] &= 0xFF

    def _8ZZZ(self):
        """Поиск конкретного опкода с началом "8" """
        extracted_opcode = self.opcode & 0xf00f
        extracted_opcode += 0xff0
        try:
            self.funcmap[extracted_opcode]()
        except:
            print("Unknown opcode: {0:x}".format(self.opcode))


    def _8XY0(self):
        """Установить Vx = Vy
        """
        self.registers[self.vx] = self.registers[self.vy]
        self.registers[self.vx] &= 0xff


    def _8XY1(self):
        """Выполнить операцию дизъюнкция (логическое “ИЛИ”) над значениями регистров Vx и Vy,
         результат сохранить в Vx. Т.е. Vx = Vx | Vy
        """
        self.registers[self.vx] |= self.registers[self.vy]
        self.registers[self.vx] &= 0xff


    def _8XY2(self):
        """Выполнить операцию конъюнкция (логическое “И”) над значениями регистров Vx и Vy,
        результат сохранить в Vx. Т.е. Vx = Vx & Vy
        """
        self.registers[self.vx] &= self.registers[self.vy]
        self.registers[self.vx] &= 0xff


    def _8XY3(self):
        """Выполнить операцию “исключающее ИЛИ” над значениями регистров Vx и Vy,
        результат сохранить в Vx. Т.е. Vx = Vx ^ Vy
        """
        self.registers[self.vx] ^= self.registers[self.vy]
        self.registers[self.vx] &= 0xff


    def _8XY4(self):
        """Значения Vx и Vy суммируются. Если результат больше, чем 8 бит (т.е.> 255) VF устанавливается в 1, иначе 0.
        Только младшие 8 бит результата сохраняются в Vx. Т.е. Vx = Vx + Vy
        """
        if self.registers[self.vx] + self.registers[self.vy] > 0xff:
            self.registers[0xf] = 1
        else:
            self.registers[0xf] = 0
        self.registers[self.vx] += self.registers[self.vy]
        self.registers[self.vx] &= 0xff


    def _8XY5(self):
        """Если Vx >= Vy, то VF устанавливается в 1, иначе 0. Затем Vy вычитается из Vx,
        а результат сохраняется в Vx. Т.е. Vx = Vx - Vy
        """
        if self.registers[self.vy] > self.registers[self.vx]:
            self.registers[0xf] = 0
        else:
            self.registers[0xf] = 1

        self.registers[self.vx] -= self.registers[self.vy]
        self.registers[self.vx] &= 0xff


    def _8XY6(self):
        """Операция сдвига вправо на 1 бит. Сдвигается регистр Vx. Т.е. Vx = Vx >> 1.
        До операции сдвига выполняется следующее:
        если младший бит (самый правый) регистра Vx равен 1, то VF = 1, иначе VF = 0
        """
        self.registers[0xf] = self.registers[self.vx] & 0x0001
        self.registers[self.vx] = self.registers[self.vx] >> 1


    def _8XY7(self):
        """Если Vy >= Vx, то VF устанавливается в 1, иначе 0.
        Тогда Vx вычитается из Vy, и результат сохраняется в Vx.
        Т.е. Vx = Vy - Vx
        """
        if self.registers[self.vy] > self.registers[self.vx]:
            self.registers[0xf] = 1
        else:
            self.registers[0xf] = 0

        self.registers[self.vy] -= self.registers[self.vx]
        self.registers[self.vx] &= 0xff


    def _8XYE(self):
        """Операция сдвига влево на 1 бит. Сдвигается регистр Vx. Т.е. Vx = Vx << 1.
        До операции сдвига выполняется следующее:
        если младший бит (самый правый) регистра Vx равен 1, то VF = 1, иначе VF = 0
        """
        self.registers[0xf] = self.registers[self.vx] & 0x0001
        self.registers[self.vx] = self.registers[self.vx] << 1


    def _9XY0(self):
        """Пропустить следующую инструкцию, если Vx != Vy"""
        if self.registers[self.vx] != self.registers[self.vy]:
            self.pc += 2


    def _ANNN(self):
        """Значение регистра I устанавливается в nnn
        """
        self.index = self.opcode & 0x0fff


    def _BNNN(self):
        """Перейти по адресу nnn + значение в регистре V0.
        """
        self.pc = (self.opcode & 0x0fff) + self.registers[0]


    def _CXNN(self):
        """ Устанавливается Vx = (случайное число от 0 до 255) & kk
        """
        self.r = int(random.random() * 0xff)
        self.registers[self.vx] = self.r & (self.opcode & 0x00ff)
        self.registers[self.vx] &= 0xff


    def _DXYN(self):
        """Нарисовать на экране спрайт.
        Эта инструкция считывает n байт по адресу содержащемуся в регистре I
        и рисует их на экране в виде спрайта c координатой Vx, Vy.
        Спрайты рисуются на экран по методу операции XOR,
        то есть если в том месте где мы рисуем спрайт уже есть нарисованные пиксели - они стираются,
        если их нет - рисуются. Если хоть один пиксель был стерт, то VF устанавливается в 1, иначе в 0.
        """
        self.registers[0xf] = 0
        x_loc = self.registers[self.vx] & 0xff
        y_loc = self.registers[self.vy] & 0xff
        height = self.opcode & 0x000f
        for y in range(height):
            pixel = self.mem[y + self.index]
            for x in range(8):
                loc = x + x_loc + ((y+y_loc)*64)
                if pixel & (0x80 >> x) != 0 and not (y + y_loc >= 32 or x + x_loc >= 64):
                    if self.display[loc] == 1:
                        self.registers[0xf] = 1;
                    self.display[loc] ^= 1

    def _EZZZ(self):
        """Поиск конкретного опкода с началом "E" """
        extracted_opcode = self.opcode & 0xf00f
        try:
            self.funcmap[extracted_opcode]()
        except:
            print("Unknown opcode: {0:x}".format(self.opcode))


    def _EX9E(self):
        """Пропустить следующую команду если клавиша, номер которой хранится в регистре Vx, нажата
        """
        key = self.registers[self.vx] & 0xf
        if self.key_inputs[key] == 1:
            self.pc += 2


    def _EXA1(self):
        """Пропустить следующую команду если клавиша, номер которой хранится в регистре Vx, не нажата
        """
        key = self.registers[self.vx] & 0xf
        if self.key_inputs[key] == 0:
            self.pc += 2
        else:
            self.pc - 2


    def _FZZZ(self):
        """Поиск конкретного опкода с началом "F" """
        extracted_opcode = self.opcode & 0xf0ff
        try:
            self.funcmap[extracted_opcode]()
        except:
            print("Unknown opcode: {0:x}".format(self.opcode))


    def _FX07(self):
        """Скопировать значение таймера задержки в регистр Vx
        """
        self.registers[self.vx] = self.delay_timer


    def _FX0A(self):
        """Ждать нажатия любой клавиши.
        Как только клавиша будет нажата записать ее номер в регистр Vx и перейти к выполнению следующей инструкции.
        """
        ret = self.get_key()
        if ret >= 0:
            self.registers[self.vx] = ret
        else:
            self.pc -= 2


    def _FX15(self):
        """Установить значение таймера задержки равным значению регистра Vx
        """
        self.delay_timer = self.registers[self.vx]


    def _FX18(self):
        """Установить значение звукового таймера равным значению регистра Vx
        """
        self.sound_timer = self.registers[self.vx]


    def _FX1E(self):
        """Сложить значения регистров I и Vx, результат сохранить в I. Т.е. I = I + Vx
        """
        self.index += self.registers[self.vx]
        if self.index > 0xfff:
            self.registers[0xf] = 1
            self.index &= 0xfff
        else:
            self.registers[0xf] = 0


    def _FX29(self):
        """Используется для вывода на экран символов встроенного шрифта размером 4x5 пикселей.
        Команда загружает в регистр I адрес спрайта, значение которого находится в Vx.
        Например, нам надо вывести на экран цифру 5. Для этого загружаем в Vx число 5.
        Потом команда LD F, Vx загрузит адрес спрайта, содержащего цифру 5, в регистр I
        """
        self.index = (5*(self.registers[self.vx])) & 0xfff


    def _FX33(self):
        """Сохранить значение регистра Vx в двоично-десятичном (BCD) представлении по адресам I, I+1 и I+2
        """
        self.mem[self.index] = self.registers[self.vx] // 100
        self.mem[self.index+1] = (self.registers[self.vx] % 100) // 10
        self.mem[self.index+2] = self.registers[self.vx] % 10


    def _FX55(self):
        """Сохранить значения регистров от V0 до Vx в памяти, начиная с адреса находящегося в I
        """
        for i in range(self.vx):
            self.mem[self.index+i] = self.registers[i]
        self.index += self.vx + 1


    def _FX65(self):
        """Загрузить значения регистров от V0 до Vx из памяти, начиная с адреса находящегося в I
        """
        for i in range(self.vx):
            self.registers[i] = self.mem[self.index + i]
        self.index += self.vx + 1


    def handle_keys(self):
        events = self.interface.handle_events()
        for event in events:
            if event.type == pygame.KEYDOWN:
                self.on_key_press(event)
            elif event.type == pygame.KEYUP:
                self.on_key_release(event)


    def get_key(self):
        for i in range(0xf):
            if self.key_inputs[i] == 1:
                return i
        return -1

    def on_key_press(self, event):
        if event.key == pygame.K_F1:
            setSave = {
                'key_inputs': self.key_inputs,
                'display': self.display,
                'mem': self.mem,
                'opcode': self.opcode,
                'vx': self.vx,
                'vy': self.vy,
                'r': self.r,
                'registers': self.registers,
                'sound_timer': self.sound_timer,
                'delay_timer': self.delay_timer,
                'index': self.index,
                'pc': self.pc,
                'key_wait': self.key_wait,
                'stack': self.stack,
                'fonts': self.fonts,
            }
            with open(filedialog.asksaveasfilename(filetypes=[('Save File', '.save')]), 'wb') as output:
                pickle.dump(setSave, output, pickle.HIGHEST_PROTOCOL)
        if event.key in KeysKeybord.keys():
            self.key_inputs[KeysKeybord[event.key]] = 1
            if self.key_wait:
                self.key_wait = False

    def on_key_release(self, event):
        if event.key in KeysKeybord.keys():
            self.key_inputs[KeysKeybord[event.key]] = 0
Пример #33
0
	[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1],
	[1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
	[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1],
	[1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
	[1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
	[1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
	[1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 0, 1],
	[1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
	[1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
	[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1],
	[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

# Creating our objects
labyrinth = DataManager.Lab_Data_Manager(labyrinth)

interface = Interface.Viewer()
interface.config_basic() #setting window size values

da_vinci = Interface.Artist(interface.window, interface.canvas)

mickey = Actioner.Rat(1,1)

while True:

	#Showing the labyrinth
	da_vinci.draw(labyrinth.data)

	#Saving last position as 4, spaces already walked by the rat
	labyrinth.data[mickey.y][mickey.x] = 4

	# Rat chooses it's moviment.
Пример #34
0
def main():
    interface = Interface.Interface()
    interface.choice()
Пример #35
0
def main():
    app = QApplication(sys.argv)
    ex = Interface.App_Window()
    os.system("mode con: cols=50 lines=50")
    sys.exit(app.exec_())
Пример #36
0
#! Python 3.7 with usage of Tkinter and PIL for complete usage of the application
# Creator : Sean Morgan
# Site : github.com/Firesean

import Chess as Chs
import Interface as Ui

game = Ui.Interface(Chs.Chess(), 650)
Пример #37
0
import DB
import Interface
import Logic


def main():
    while True:
        try:
            command = Interface.get_command()
        except ValueError:
            print("Invalid command")
            continue
        if command == 'view':
            Logic.view(cursor)
        if command == 'history':
            Logic.history(cursor)
        if command == 'add':
            Logic.add(connect, cursor)
        if command == 'complete':
            Logic.complete(connect, cursor)
        if command == 'del':
            Logic.delete(connect, cursor)
        if command == 'exit':
            Logic.end()


if __name__ == "__main__":
    connect = DB.connect("task_list_db.sqlite")
    cursor = connect.cursor()
    Interface.command_menu()
    main()
Пример #38
0
def testdelete(openconnection):
    # Not testing this piece!!!
    MyAssignment.deletepartitionsandexit(openconnection)
Пример #39
0

import Interface as interface
import Communication as com
import time
import serial




# Ouverture de l'interface de contrôle
app = interface.application()

# Boucle de communication en serial
while(app.isrunning):
    if com.portArduino.readable():
        com.Arduino.read_one_value()
    time.sleep(0.05)
Пример #40
0
from Color import *  #Red(),Green(),Blue(),Black(),White()
from IRSensor import *
from MotorController import *
from Robot import *
from ServoMotor import *
from TempHumSensor import *
from UltrasoundSensor import *
from View import *
from Interface import *
from DummyObject import *
from WebCam import *

# Initialize the interface #
interface = Interface(300, 300, 100, 600, "F.I.R.E. -TempHumSensor TEST-", 100)
interface.build()
pygame.init()
############################
# Initialize the ServoMot. #
servoMotor = ServoMotor(11)  #FALTA poner el pin!
############################

#-#-#    MAIN  LOOP    #-#-#
text = " "
run = True
servoMotor.initialize()
#while(run):
#	pygame.time.delay(interface.delay)

#	for event in pygame.event.get():
#		if event.type == pygame.QUIT:
#			run = False
# -*-coding:utf-8 -*-

import Interface
import os
def menu():
	print("欢迎来到景区管理系统!")
	print("请按对应编号选择功能")
	print("1.输入景区信息")
	print("2.查询景点")
	print("3.旅游景点导航")
	print("4.路线查询")
	print("5.铺设电路规划")
	print("6.修改景区信息")
	print("7.输出景点图")
	print("8.保存并退出")



if __name__ == '__main__':
	test1 = Interface.Interface()
	t =True
	while t :
		menu()
		instruction=input('请根据相应需求输入对应功能前序号\n')
		test1.dispose(instruction)
		os.system('cls')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
Пример #42
0
             e] = testHelper.testrangepartition(MyAssignment, RATINGS_TABLE, 5,
                                                conn, 0,
                                                ACTUAL_ROWS_IN_INPUT_FILE)
            if result:
                print "rangepartition function pass!"

            # # ALERT:: Use only one at a time i.e. uncomment only one line at a time and run the script
            # [result, e] = testHelper.testrangeinsert(MyAssignment, RATINGS_TABLE, 100, 2, 3, conn, '2')
            [result,
             e] = testHelper.testrangeinsert(MyAssignment, RATINGS_TABLE, 100,
                                             2, 0, conn, '0')
            if result:
                print "rangeinsert function pass!"

            testHelper.deleteAllPublicTables(conn)
            MyAssignment.loadRatings(RATINGS_TABLE, INPUT_FILE_PATH, conn)

            [result, e
             ] = testHelper.testroundrobinpartition(MyAssignment,
                                                    RATINGS_TABLE, 5, conn, 0,
                                                    ACTUAL_ROWS_IN_INPUT_FILE)
            if result:
                print "roundrobinpartition function pass!"

            [result,
             e] = testHelper.testroundrobininsert(MyAssignment, RATINGS_TABLE,
                                                  100, 1, 3, conn, '0')
            [result,
             e] = testHelper.testroundrobininsert(MyAssignment, RATINGS_TABLE,
                                                  100, 1, 3, conn, '1')
            [result,
Пример #43
0
    def __init__(self):
        self.key_inputs = [0] * 16
        self.display = [0] * 64 * 32
        self.mem = [0] * 4096

        self.opcode = 0
        self.vx = 0
        self.vy = 0
        self.r = 0
        self.registers = [0] * 16
        self.sound_timer = 0
        self.delay_timer = 0
        self.index = 0
        self.pc = 0x200

        self.key_wait = False

        self.stack = []
        self.interface = Interface(64, 32, 10)

        self.fonts = [0xF0, 0x90, 0x90, 0x90, 0xF0,  # 0
                      0x20, 0x60, 0x20, 0x20, 0x70,  # 1
                      0xF0, 0x10, 0xF0, 0x80, 0xF0,  # 2
                      0xF0, 0x10, 0xF0, 0x10, 0xF0,  # 3
                      0x90, 0x90, 0xF0, 0x10, 0x10,  # 4
                      0xF0, 0x80, 0xF0, 0x10, 0xF0,  # 5
                      0xF0, 0x80, 0xF0, 0x90, 0xF0,  # 6
                      0xF0, 0x10, 0x20, 0x40, 0x40,  # 7
                      0xF0, 0x90, 0xF0, 0x90, 0xF0,  # 8
                      0xF0, 0x90, 0xF0, 0x10, 0xF0,  # 9
                      0xF0, 0x90, 0xF0, 0x90, 0x90,  # A
                      0xE0, 0x90, 0xE0, 0x90, 0xE0,  # B
                      0xF0, 0x80, 0x80, 0x80, 0xF0,  # C
                      0xE0, 0x90, 0x90, 0x90, 0xE0,  # D
                      0xF0, 0x80, 0xF0, 0x80, 0xF0,  # E
                      0xF0, 0x80, 0xF0, 0x80, 0x80  # F
                      ]

        for i in range(80):
            self.mem[i] = self.fonts[i]

        self.funcmap = {
            0x0000: self._0ZZZ,
            0x00e0: self._00E0,
            0x00ee: self._00EE,
            0x1000: self._1NNN,
            0x2000: self._2NNN,
            0x3000: self._3XNN,
            0x4000: self._4XNN,
            0x5000: self._5XY0,
            0x6000: self._6XNN,
            0x7000: self._7XNN,
            0x8000: self._8ZZZ,
            0x8FF0: self._8XY0,
            0x8ff1: self._8XY1,
            0x8ff2: self._8XY2,
            0x8ff3: self._8XY3,
            0x8ff4: self._8XY4,
            0x8ff5: self._8XY5,
            0x8ff6: self._8XY6,
            0x8ff7: self._8XY7,
            0x8ffE: self._8XYE,
            0x9000: self._9XY0,
            0xA000: self._ANNN,
            0xB000: self._BNNN,
            0xC000: self._CXNN,
            0xD000: self._DXYN,
            0xE000: self._EZZZ,
            0xE00E: self._EX9E,
            0xE001: self._EXA1,
            0xF000: self._FZZZ,
            0xF007: self._FX07,
            0xF00A: self._FX0A,
            0xF015: self._FX15,
            0xF018: self._FX18,
            0xF01E: self._FX1E,
            0xF029: self._FX29,
            0xF033: self._FX33,
            0xF055: self._FX55,
            0xF065: self._FX65
        }
Пример #44
0
    def _init_widgets(self):
        ################## 选择目录对话框 #################
        self.selectDialog = QtWidgets.QFileDialog(self)
        self.selectDialog.setWindowTitle(_tr("选择输出目录"))
        self.selectDialog.setDirectory(getRealText(self.edtOutDir))
        # self.selectDialog.setFilter(_tr("目录"))
        self.selectDialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly)
        self.selectDialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)

        ################# 模板列表 #################
        self.cbxTemplate.setEditable(False)
        self.loadTemplateDirs()

        ################# 实现的接口表 #################
        self.modelInterface = QtGui.QStandardItemModel(1, 1)
        self.modelInterface.setHeaderData(0, QtCore.Qt.Horizontal,
                                          QtCore.QVariant(_tr("GType函数/宏")))
        self.modelInterface.itemChanged.connect(self._onInterfaceTableChanged)
        self.delegateInterface = Interface.Delegate()
        self.lstImplInteface.setModel(self.modelInterface)
        self.lstImplInteface.setItemDelegate(self.delegateInterface)

        ################# 属性表 #################
        self.modelProperty = QtGui.QStandardItemModel(1, 5)
        self.modelProperty.setHeaderData(0, QtCore.Qt.Horizontal,
                                         QtCore.QVariant(_tr("名称")))
        self.modelProperty.setHeaderData(1, QtCore.Qt.Horizontal,
                                         QtCore.QVariant(_tr("类型")))
        self.modelProperty.setHeaderData(2, QtCore.Qt.Horizontal,
                                         QtCore.QVariant(_tr("默认值")))
        self.modelProperty.setHeaderData(3, QtCore.Qt.Horizontal,
                                         QtCore.QVariant(_tr("最大值")))
        self.modelProperty.setHeaderData(4, QtCore.Qt.Horizontal,
                                         QtCore.QVariant(_tr("最小值")))
        self.modelProperty.itemChanged.connect(self._onPropertyTableChanged)
        self.delegateProperty = Property.Delegate()
        self.lstProperties.setModel(self.modelProperty)
        self.lstProperties.setItemDelegate(self.delegateProperty)

        ################# 信号表 #################
        self.modelSignal = QtGui.QStandardItemModel(1, 2)
        self.modelSignal.setHeaderData(0, QtCore.Qt.Horizontal,
                                       QtCore.QVariant(_tr("名称")))
        self.modelSignal.setHeaderData(1, QtCore.Qt.Horizontal,
                                       QtCore.QVariant(_tr("回调类型")))
        self.modelSignal.itemChanged.connect(self._onSignalTableChanged)
        self.delegateSignal = Signal.Delegate()
        self.lstSignals.setModel(self.modelSignal)
        self.lstSignals.setItemDelegate(self.delegateSignal)

        ################# 自定义参数表 #################
        self.modelCustomParameter = QtGui.QStandardItemModel(1, 2)
        self.modelCustomParameter.setHeaderData(0, QtCore.Qt.Horizontal,
                                                QtCore.QVariant(_tr("名称")))
        self.modelCustomParameter.setHeaderData(1, QtCore.Qt.Horizontal,
                                                QtCore.QVariant(_tr("值")))
        self.modelCustomParameter.itemChanged.connect(
            self._onCustomParameterTableChanged)
        self.delegateCustomParameter = CustomParameter.Delegate()
        self.lstCustomParameters.setModel(self.modelCustomParameter)
        self.lstCustomParameters.setItemDelegate(self.delegateCustomParameter)
Пример #45
0
"""
      Автор: Ворожцов Михаил
      Цель: Аналог __init___ для запуска приложения
      Вход: -
      Выход: -

"""
import Interface as gp

if __name__ == "__main__":
    gp.main_loop()
def login(IP_user, PORT_user, IP_center, PORT_center):
    nonce_index = -1
    global flag_nonce, flag_login, flag_send_id
    try:
        sock = net.sk_listen(IP_user, PORT_user)
    except:
        print("Connection fail")
    if not flag_nonce:
        net.requestNonce(IP_center, PORT_center, IP_user, PORT_user)
    while True:
        connection, IP_address = sock.accept()
        numloop = False
        while True:
            data = connection.recv(1024)
            if flag_nonce == False and flag_login == False:
                noncetuple = tuple(eval(data.decode('utf-8')))
                if noncetuple[0] == 'nonce':
                    nonce = noncetuple[1]
                    nonce_index = noncetuple[2]
                    flag_nonce = True
                    continue
                elif numloop:
                    print('Get nonce fail')
                    option = input('y for try again, others to exit:')
                    if option == 'y':
                        break
                    else:
                        os._exit(0)
                numloop = True
            elif flag_nonce == True and flag_login == False and flag_send_id == False:
                id, password = Interface.login()
                cipher = ('login', id, hash256(password + nonce),
                          nonce_index).__str__()
                net.sendback(cipher, IP_center, PORT_center)
                flag_send_id = True
            elif flag_nonce == True and flag_login == False and flag_send_id == True:
                feedbackTuple = tuple(eval(data.decode('utf-8')))
                if feedbackTuple[0] == 'loginok':
                    flag_login == True
                    idList = feedbackTuple[1]
                    print('Login successful')
                    sock.close()
                    return True, id, idList
                elif feedbackTuple[0] == 'noid':
                    print('Username does not exist')
                    id, password = Interface.login()
                    cipher = ('login', id, hash256(password + nonce),
                              nonce_index).__str__()
                    net.sendback(cipher, IP_center, PORT_center)
                else:
                    print('username or password isn\'t correct')
                    option = input('y for try again, others to exit:')
                    if option == 'y':
                        id, password = Interface.login()
                        cipher = ('login', id, hash256(password + nonce),
                                  nonce_index).__str__()
                        net.sendback(cipher, IP_center, PORT_center)
                    else:
                        os._exit(0)
            elif flag_nonce == True and flag_login == True and flag_send_id == True:
                print('bigin to work')
            break
Пример #47
0
HOST = "localhost"
INTERFACE_PORT = 4000
TOTAL_STEPS = 1000
x_train = []
y_train = []


#Save training data to disk
def save_trainning_data():
    np_x_train = np.array(x_train)
    np.save("x_train_set", np_x_train)
    np_y_train = np.array(y_train)
    np.save("y_train_set", np_y_train)


i = Interface.Interface(HOST, INTERFACE_PORT)
c = Interface.Convert()
with pymorse.Morse(HOST, INTERFACE_PORT) as simu:
    try:
        motion = simu.atrv.motion

        for step in range(TOTAL_STEPS):

            #Get a screenshot from the simulator and store it for the CNN
            image = i.get_image()
            arr = c.image_to_3d_array(image)
            x_train.append(arr)

            #Get the current joystick position and convert to radians per second
            joystick_pos = i.get_joystick_horizontal_axis()
            desired_angular_velocity = c.joystick_to_radians_per_second(
Пример #48
0
  def my_constructor(self, SCENE, OBJECT):
	  #self.OutTransform.value = OBJECT.Transform.value
    self.SCENE = SCENE
    self.OBJECT = OBJECT
    self.ACTIV = False
    self.INTERFACE = Interface()
Пример #49
0
 def Run(self):
     self.loginWindow = Interface.Interface(
         self.loginClick)  #create a login window with loginClick callback
     self.loginWindow.Show()
Пример #50
0
    def uniqueValues(self, name=None, withLengths=0):
        """Returns the unique values for name.

        If 'withLengths' is true, returns a sequence of tuples of
        (value, length)"""

        pass

    def _apply_index(self, request, cid=''):
        """Apply the index to query parameters given in the argument, request.

        The argument should be a mapping object.

        If the request does not contain the needed parametrs, then None is
        returned.

        If the request contains a parameter with the name of the column
        + "_usage", it is sniffed for information on how to handle applying
        the index.

        Otherwise two objects are returned.  The first object is a ResultSet
        containing the record numbers of the matching records.  The second
        object is a tuple containing the names of all data fields used."""

        pass

PluggableIndexInterface = Interface.impliedInterface(PluggableIndex)

PluggableIndex.__implements__ = PluggableIndexInterface
Пример #51
0
import Settings
import Interface


class ClientParameters(object):
    def __init__(self,_id):
        self.id = _id
        self.ws = []
        self.act_pos  = (0,0)
        self.dst_pos  = (0,0)
        self.bike_pos = (0,0)

client_connections = {}

db_connection = Interface.get_connection()


define("port", default=80, help="run on the given port", type=int)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MapHandler),
            (r"/map/(\w+)",MapHandler),
            (r"/mapWS", MapWebSocketHandler),
            (r'/(.*)', tornado.web.StaticFileHandler, {'path': Settings.STATIC_PATH})

        ]
        settings = {
Пример #52
0
        Assignment1.loadRatings('ratings', 'test_data.txt', con)

        # Doing Range Partition
        print "Doing the Range Partitions"
        Assignment1.rangePartition('ratings', 5, con)

        # Doing Round Robin Partition
        print "Doing the Round Robin Partitions"
        Assignment1.roundRobinPartition('ratings', 5, con)

        # Deleting Ratings Table because Point Query and Range Query should not use ratings table instead they should use partitions.
        #Assignment1.deleteTables('ratings', con);

        # Calling RangeQuery
        print "Performing Range Query"
        Assignment2.RangeQuery('ratings', 1.5, 3.5, con)
        #Assignment2.RangeQuery('ratings',1,4,con);

        # Calling PointQuery
        print "Performing Point Query"
        #Assignment2.PointQuery('ratings', 4.5, con);
        Assignment2.PointQuery('ratings', 0.5, con)

        # Deleting All Tables
        #Assignment1.deleteTables('all', con);

        if con:
            con.close()

    except Exception as detail:
        traceback.print_exc()
def operation(listBlockchain, id, neighbours, IP_user, port_user, idList,
              path_blockchain):
    while True:
        option = Interface.option()
        balance = op.accountBalance(listBlockchain, id)
        if option == '1':
            listBlockchain = op.loadBlockchain(path_blockchain)
            balance = op.accountBalance(listBlockchain, id)
            print('username:'******'account balance:' + str(balance))
        elif option == '2':
            amount, payee = Interface.inputTrasfer()
            listBlockchain = op.loadBlockchain(path_blockchain)
            if payee not in idList:
                print('Payee inexistant')
                continue
            elif int(amount) > balance:
                print('Insufficient funds')
                continue
            else:
                block = op.newBlock(listBlockchain[-1], id, int(amount), payee)
                blockString = block.blockToString()
                for addr in neighbours:
                    try:
                        msg = 'mining&' + IP_user + '&' + str(
                            port_user) + '&' + blockString
                        sock2 = net.sk_send(addr[0], addr[1])
                        sock2.send(msg.encode('utf-8'))
                        sock2.close()
                        print("Mining request sent to " + addr[0])
                    except:
                        print(sys.exc_info())
                        print("Cannot connect to neighbour " + addr[0])
        elif option == '3':
            listBlockchain = op.loadBlockchain(path_blockchain)
            for i in listBlockchain:
                i.printBlock()
        elif option == '4':
            print('updating...')
            for addr in neighbours:
                try:
                    msg = 'update,' + IP_user + ',' + str(port_user)
                    sock4 = net.sk_send(addr[0], addr[1])
                    sock4.send(msg.encode('utf-8'))
                    sock4.close()
                    time.sleep(0.1)
                    print('Update from ' + addr[0])
                    break
                except:
                    print("Cannot connect to neighbour " + addr[0])
        elif option == '5':
            print('Waiting for mining:')
            MiningFlag = True
            while (MiningFlag):
                global MINING
                if len(MINING) > 0:
                    listBlockchain = op.loadBlockchain(path_blockchain)
                    block = op.stringToBlock(MINING)
                    if (block.index == listBlockchain[-1].index):
                        MINING = ""
                    else:
                        print('Begin mining')
                        block.mining()
                        listBlockchain = op.loadBlockchain(path_blockchain)
                        if len(listBlockchain) == int(block.index):
                            block.saveBlock(path_blockchain)
                            print('Mined block:\n')
                            block.printBlock()
                            MiningFlag = False
                            for addr in neighbours:
                                try:
                                    msg = 'broad,' + IP_user + ',' + str(
                                        port_user)
                                    sock2 = net.sk_send(addr[0], addr[1])
                                    sock2.send(msg.encode('utf-8'))
                                    time.sleep(0.1)
                                    net.sendFile(sock2, path_blockchain)
                                    sock2.close()
                                except:
                                    print(sys.exc_info())
                                    print("Cannot connect to neighbour " +
                                          addr[0])
                        else:
                            print('Current block is already mined by others.')
                        MINING = ""

        elif option == 'q':
            os._exit(0)
        else:
            print('Please enter a correct option')
Пример #54
0
    try:
        #Getting Connection from MongoDB
        conn = MongoClient('mongodb://localhost:27017/')

        #Creating a New DB in MongoDB
        print "Creating database in MongoDB named as " + DATABASE_NAME
        database   = conn[DATABASE_NAME]

        #Creating a collection named businessCollection in MongoDB
        print "Creating a collection in " + DATABASE_NAME + " named as " + COLLECTION_NAME
        collection = database[COLLECTION_NAME]

        #Loading BusinessCollection from a json file to MongoDB
        print "Loading testData.json file in the " + COLLECTION_NAME + " present inside " + DATABASE_NAME
        loadBusinessTable("testData.json", collection)
    
        #Finding All Business name and address(full_address, city and state) present in CITY_TO_SEARCH
        print "Executing FindBusinessBasedOnCity function"
        Interface.FindBusinessBasedOnCity(CITY_TO_SEARCH, SAVE_LOCATION_1, collection)

        #Finding All Business name and address(full_address, city and state) present in radius of MY_LOCATION for CATEGORIES_TO_SEARCH
        print "Executing FindBusinessBasedOnLocation function"
        Interface.FindBusinessBasedOnLocation(CATEGORIES_TO_SEARCH, MY_LOCATION, MAX_DISTANCE, SAVE_LOCATION_2, collection)

        #Delete database
        deleteDB(conn, DATABASE_NAME)
        conn.close()

    except Exception as detail:
        traceback.print_exc()
Пример #55
0
sys.path.append('./scripts')
sys.path.append('./scripts/libs')
import string
import Interface
import Event
import App
from chat import *             #Chat manager
from Interface import *
from Event import *
from App import *

import feedparser

###########################################################
######Global variables
I = Interface.get() #Interface manager
A = App.get()       #Application
E = Event.get()     #Event manager
##########################################################
#####Counter, returns new value every time
def counter():
 static_counter = 0
 while True:
  static_counter += 1
  yield static_counter
count = counter().next
#########################################################################
#####Function creates simple message box with specified title and name
#####Message box has one button - ok and is destroyed by interface manager
#####after pressing this button.
#####Every new popup window has unique id.
Пример #56
0
import DirControl
import VariableControl
import Interface

Interface.runBasic()
Пример #57
0
def main():
    #parse command line arguments
    parser = argparse.ArgumentParser(description='Initialize autoturret.')
    parser.add_argument('target_class',
                        type=str,
                        help='Pick a target class from the list')
    #parser.add_argument('pin_file', type=str, help='file path to file containing pin info')
    parser.add_argument(
        '--fire',
        action='store_true',
        default=False,
        help='just track target instead of automatically firing',
        dest='fire')
    parser.add_argument('--showStream',
                        action='store_true',
                        default=False,
                        help="if you want to see it work.q")

    results = parser.parse_args()
    USER_TARGET = results.target_class
    PIN_FILEPATH = 'pin_loc.txt'  #results.pin_file
    FIRE = results.fire
    SHOW_STREAM = results.showStream
    ACTIVE = True

    #import from file global constant pin locations
    pin_dict = Utils.parse_pinfile(PIN_FILEPATH)

    #initialize drivers
    print('Initializing Drivers....')
    m1 = Drivers.Motor1(pin_dict['M1A1'], pin_dict['M1A2'], pin_dict['M1B1'],
                        pin_dict['M1B2'])
    m2 = Drivers.Motor2(enable=pin_dict['en2'],
                        direction=pin_dict['dirpin2'],
                        pulse=pin_dict['pul2'])
    launcher = Drivers.Launcher(pin_dict['WaterPin'], pin_dict['AirPin'], 1,
                                .4)

    #initialize interface
    print("Setting up interface...")
    control = Interface.CannonControl(m1, m2, launcher)

    # import the correct version of tensorflow based on whats installed and define and interpreter
    # from on the .tflite file
    if importlib.util.find_spec('tflite_runtime'):
        import tflite_runtime.interpreter as tflite
        interpreter = tflite.Interpreter(model_path='model/detect.tflite')
    else:
        import tensorflow as tf
        interpreter = tf.lite.Interpreter(model_path='model/detect.tflite')

    interpreter.allocate_tensors()

    #load labels
    with open('model/labelmap.txt', 'r') as f:
        labels = [line.strip() for line in f.readlines()]

    #initialize detection model
    print("Starting detection model...")
    model = Detection.TargetStream(USER_TARGET, interpreter)
    model.start()
    time.sleep(2)
    print("Model ready...")

    #define autotarget functionality

    #toss that in a loop. consiter using threads
    while ACTIVE:
        if SHOW_STREAM:
            model.show_frame()

        if model.object_detected:
            location = model.target_location
            h, v, dist = Utils.auto_target((location))
            Utils.move(h, v, dist, control, 3)
            time.sleep(1)
Obj4 = p.loadURDF("Models/PhysicsTesting/small_sphere.urdf",
                  cubeStartPos,
                  cubeStartOrientation,
                  useFixedBase=1)

for joint_index in range(0, p.getNumJoints(TheArm)):
    print()
    info = p.getJointInfo(TheArm, joint_index)
    print("Joint index: " + str(info[0]))
    print("Joint name: " + str(info[1]))
    print("Joint type: " + str(info[2]))
    print()

#Grasping class
G = Grasp(p, TheArm)
I = Interface.Interface()
AC = ArmController(p, TheArm)

#LL, UL = G.returnLimits()
#IK = p.calculateInverseKinematics(TheArm,8,[0, 0.8, 0.2],targetOrientation = [0,0,0,0], lowerLimits = LL, upperLimits = UL)
#IK = p.calculateInverseKinematics(TheArm,9,[0, 0.5, 0.5],targetOrientation = [0,0,1,0])
#print(IK)
#for joint in range(0,7):
#   p.setJointMotorControl2(bodyUniqueId=TheArm, jointIndex=joint, controlMode=p.POSITION_CONTROL, targetPosition = IK[joint], maxVelocity = 1)

#for joint in [13,30,46]:
#    p.setJointMotorControl2(bodyUniqueId=TheArm, jointIndex=joint, controlMode=p.POSITION_CONTROL, targetPosition = 1.7, maxVelocity = 1)

#p.setJointMotorControl2(bodyUniqueId=TheArm, jointIndex=5, controlMode=p.POSITION_CONTROL, targetPosition = 2, maxVelocity = 1)

#Run the simulation
Пример #59
0
import sys, os

sys.path.append(os.path.join(sys.path[0], './interface/'))
import Interface
from PyQt5.QtWidgets import (QApplication)

if __name__ == '__main__':

    app = QApplication(sys.argv)

    w = Interface.TweetoTa()
    w.resize(650, 450)
    w.center()
    w.setWindowTitle('TweetoTa')
    w.show()

    sys.exit(app.exec_())
Пример #60
0
def main():
    Connector.create_partie_table()
    Connector.create_theme_table()
    Connector.create_question_table()
    cadre = Interface()