Ejemplo n.º 1
0
def poke_lab():
    print("You're in the famous Kanto Pokemon Laboratory. What would you like to do next? ")
    print("[A] Look around\n[B] Approach Lab Assistant\n[C] Approach Professor Oak\n[D] Exit Outside")
    ans = input("> ")
    if ans == "A":  # Look around
        Actions.look()
        print("You see all sorts of machines and gadgets. You even see Pokemon relaxing and waddling around.")
        Actions.tap()
        print("After glancing around you go back to the task at hand.")
        Actions.tap()
        poke_lab()
    elif ans == "B":  # Approach  Lab Assistant
        print(" You find a man in lab coat that is busy at work")
        Actions.tap()
        dialouge.assistant_diag_1()
        poke_lab()
    elif ans == "C":  # Approach Professor
        oak_intro(player_name)

    elif ans == "D":  # Exit lab
        print("You turn around and exit back from where you entered.")
        Actions.tap()
        pallet_town()
    else:
        print(invalid)
        poke_lab()
Ejemplo n.º 2
0
 def close_page(self, ensure=True):
     """
     Close the current page.
     If the notebook becomes empty, and ensure is true,
     call new page upon exit to ensure that at least one page exists.
     
     Args:
         ensure: boolean
     """
     if not self.page_to_be_closed: self.page_to_be_closed = self.get_page()
     #show the page if it has an executing flow graph or is unsaved
     if self.page_to_be_closed.get_proc() or not self.page_to_be_closed.get_saved():
         self._set_page(self.page_to_be_closed)
     #unsaved? ask the user
     if not self.page_to_be_closed.get_saved() and self._save_changes():
         Actions.FLOW_GRAPH_SAVE() #try to save
         if not self.page_to_be_closed.get_saved(): #still unsaved?
             self.page_to_be_closed = None #set the page to be closed back to None
             return
     #stop the flow graph if executing
     if self.page_to_be_closed.get_proc(): Actions.FLOW_GRAPH_KILL()
     #remove the page
     self.notebook.remove_page(self.notebook.page_num(self.page_to_be_closed))
     if ensure and self.notebook.get_n_pages() == 0: self.new_page() #no pages, make a new one
     self.page_to_be_closed = None #set the page to be closed back to None
def Main():
    try:    
        lastColor = 'green'
        distanceActions = DistanceActions(trigger, echo)
        servoActions = Actions()
        while True:
            distance = distanceActions.TakeDistance()
            print(distance)
            if(distance <= minDistance):
                GPIO.output(ledRojo, GPIO.HIGH)
                GPIO.output(ledAmarillo, GPIO.LOW)
                GPIO.output(ledVerde, GPIO.LOW)
                if(lastColor != 'red'):
                    servoActions.Deg0(servo)
                lastColor = 'red'
            else:
                if(distance >= minDistance and distance <= midDistance):
                    GPIO.output(ledRojo, GPIO.LOW)
                    GPIO.output(ledAmarillo, GPIO.HIGH)
                    GPIO.output(ledVerde, GPIO.LOW)
                    if(lastColor != 'yellow'):
                        servoActions.Deg90(servo)
                    lastColor = 'yellow'
                else:
                    GPIO.output(ledRojo, GPIO.LOW)
                    GPIO.output(ledAmarillo, GPIO.LOW)
                    GPIO.output(ledVerde, GPIO.HIGH)
                    if(lastColor != 'green'):
                        servoActions.Deg180(servo)
                    lastColor = 'green'
            time.sleep(0.3)
    except (KeyboardInterrupt, SystemExit):
        raise
    finally:  
        GPIO.cleanup() 		
Ejemplo n.º 4
0
 def __init__( self, parent ):
     
     Qt.QWidget.__init__( self, parent )
     
     #   Actions
     #
     Actions.createGraphEditorActions( self )
     
     #   Menus
     #
     #menuBar = Qt.QMenuBar( self )
     #
     #fileMenu = menuBar.addMenu( 'File' )
     #viewMenu = menuBar.addMenu( 'View' )
     #
     #fileMenu.addAction( Actions.graphEditor.loadDynamicNode )
     #viewMenu.addAction( Actions.graphEditor.frameAll        )
     
     #   Graph editor
     #
     graphEditor    = Cellule.appli.createGraphEditor( Cellule.fromSIP( self ) )
     graphEditorSIP = Cellule.toSIP( graphEditor, Qt.QWidget )
     
     #   Layout
     #
     layout = Qt.QVBoxLayout( self )
     
     #layout.addWidget( menuBar        )
     layout.addWidget( graphEditorSIP )
Ejemplo n.º 5
0
def createNodesForTransactions(transactions, position):
    if (TransactionsData[0][position] == 'n'):  #if the attribute is nominal
        lists = Actions.createListsForNominal(
            transactions, position
        )  #call the method that creates lists for the nominal attribute
        lisPos = 0  #Initialize the lisPos to 0 for placing the value left or right in the node(0-left,1-right)
        for tranList in lists:
            result = Actions.checkAttributes(
                tranList, TransactionsData
            )  # method to check if the list is pure(0/1) or not(2)
            checkResult(
                result, tranList, position, lisPos
            )  #checking the result if we need recusion that is furthur split or not
            lisPos += 1
    elif (TransactionsData[0][position] == 'c'
          ):  #if the attribute is continuous
        lists = Actions.createListsForContinuous(
            transactions, position
        )  #call the method that creates lists for the continuous attribute
        lisPos = 0  #Initialize the lisPos to 0 for placing the value left or right in the node(0-left,1-right)
        for tranList in lists:
            result = Actions.checkAttributes(
                tranList, TransactionsData
            )  # method to check if the list is pure(0/1) or not(2)
            checkResult(
                result, tranList, position, lisPos
            )  #checking the result if we need recusion that is furthur split or not
            lisPos += 1
Ejemplo n.º 6
0
 def actPlace(self, player, loc, value):
     self.logAction()
     piece = (-1) * ((-1)**player) * value
     if self.turnCount <= 2:
         piece = piece * (-1) // abs(piece)
     act.place(self.board, loc, piece)
     self.turnCount += 1
Ejemplo n.º 7
0
def make_post(sub, post, comment):
    try:
        #make post and comment
        post = Actions.make_post_url(sub, post.title, post.url)
        Actions.make_comment(post, comment)
    except Exception, e:
        print str(e)
Ejemplo n.º 8
0
def player_awake():
    Actions.tap()
    print("You wake up in comfortable bed in room that Mom always keeps clean.You see 3 Options:\n[PC]\n[Door]\n[Bed].")
    ans = input("> ")
    if ans == "Bed":  # Go to bed
        print("It's like 11AM are you sure you want to  go back to bed?")
        Actions.tap()
        print("[A] Yes I am sad and I want to go back to bed. or [B] No I'm going to do something today.")
        ans = input("> ")
        if ans == "A":  # I'm sure, Go to bed
            print("Congratulations you wasted an entire day!~~~")
            player_awake()
        elif ans == "B":  # Don't go to bed
            print("That's the spirit!")
            player_room()
        else:
            print(invalid)
            player_room()
    elif ans == "PC":  # open PC
        print("You walk and sit at your PC")
        player_pc()

    elif ans == "Door":  # Exit to the living room
        print("You exit your room and walk out your room.")
        door()

    else:
        print(invalid)
        player_awake()
 def update_mods(self, author=None):
     """
     Update the internal mod-list (who can execute queries)
     :param author: if specified, the bot will respond to this user to let them know success/failure
     :return: None
     """
     try:
         mlist = [mod.name for mod in Actions.get_mods(self.praw, self.sub)]
         if mlist is None or not len(mlist):
             return False
         # only update if it's valid
         self.mod_list = mlist
         self.last_mod_update = datetime.datetime.now()
         if author is not None:
             Actions.send_message(self.praw, author, u"RE: Modlist update", u"Success!")
         return True
     except Exception, e:
         if author is not None:
             Actions.send_message(self.praw, author, u"RE: Modlist update",
                                 u"Error encountered, please try again later.")
         logging.error(u"Could not update moderator list!")
         self.log_error()
         if __debug__:
             logging.exception(e)
         return False
Ejemplo n.º 10
0
def clear_sub(credentials, sub, num=20):
    """Removes all* old posts from a sub (use with care)

    * up to 900
    :param credentials:
    :param sub:
    :return:
    """
    num = min(num, 900)
    if num < 0:
        num = int(1e6)
    mypraw = create_multiprocess_praw(credentials)
    sub = get_subreddit(credentials, mypraw, sub)
    old_stream = p.helpers.submission_stream(mypraw, sub, limit=num)
    results = []
    try:
        #delete all old posts
        for i in range(num):
            try:
                post = old_stream.next()
                Actions.remove_post(post, delete=True)
                print("# {} deleted...".format(i))
            except AttributeError:
                # Post or Comment may have been deleted between retrieving it
                # and accessing its fields
                pass
    except AssertionError, e:
        logging.log(logging.DEBUG, str(e) + "\nNo Posts!")
Ejemplo n.º 11
0
 def __info(self, author, subject, text):
     try:
         limit = 10
         #first find a limit if it exists
         match = self.limit_match.search(subject)
         if match:
             limit = int(match.group(1))
         #we must figure out the case
         if self.list_command.search(subject):
             return self.__info_list(author, subject, text)
         elif self.channel_command.search(subject):
             return self.__info_channels(author, subject, text, limit)
         elif self.user_command.search(subject):
             return self.__info_user(author, subject, text, limit)
         else:
             return Actions.send_message(self.praw,
                                         author,
                                         u'Message text not recognized',
                                         u'Message w/ \n'
                                         u'subject: {}\n'.format(subject) +
                                         u'and body: {}\n'.format(text) +
                                         u'not recognized, please consult documentation or help.')
     except Exception as e:
         logging.exception(e)
         Actions.send_message(self.praw,
                              author, u'Re: {}'.format(subject),
                              u'An error occured processing the following text, please file a bug report with'
                              u' /u/arghdos:  \n{}'.format(text))
Ejemplo n.º 12
0
    def adjacent_moves(self):
        """
		Determines which of the 4 directions the player can move in, i.e. where player can move

		Output:
			moves [<Actions>]
		"""
        moves = []

        moves.append(Actions.MoveNorth())

        moves.append(Actions.MoveSouth())

        moves.append(Actions.MoveEast())

        moves.append(Actions.MoveWest())

        random.shuffle(moves)

        remove_move = random.randint(0, 3)

        for removed in range(0, remove_move):

            moves.pop()

        return moves
Ejemplo n.º 13
0
	def adjacent_moves(self):
		"""
		Describes all actions for adjacent tiles, i.e. where player can move
		 Shuffles the list for the movements and eliminates two of them to give the sense of walls

		Output:
			moves [<Actions>]
		"""
		moves = []

		moves.append(Actions.MoveNorth())

		moves.append(Actions.MoveSouth())

		moves.append(Actions.MoveEast())

		moves.append(Actions.MoveWest())

		random.shuffle(moves)

		moves.pop()

		moves.pop()


		return moves
Ejemplo n.º 14
0
    def __init__(self, file_paths, platform):
        """
        ActionHandler constructor.
        Create the main window, setup the message handler, import the preferences,
        and connect all of the action handlers. Finally, enter the gtk main loop and block.

        Args:
            file_paths: a list of flow graph file passed from command line
            platform: platform module
        """
        self.clipboard = None
        for action in Actions.get_all_actions():
            action.connect('activate', self._handle_action)
        #setup the main window
        self.platform = platform
        self.main_window = MainWindow(platform)
        self.main_window.connect('delete-event', self._quit)
        self.main_window.connect('key-press-event', self._handle_key_press)
        self.get_page = self.main_window.get_page
        self.get_flow_graph = self.main_window.get_flow_graph
        self.get_focus_flag = self.main_window.get_focus_flag
        #setup the messages
        Messages.register_messenger(self.main_window.add_report_line)
        Messages.send_init(platform)
        #initialize
        self.init_file_paths = file_paths
        Actions.APPLICATION_INITIALIZE()
        #enter the mainloop
        gtk.main()
Ejemplo n.º 15
0
 def pokedex(self):
     Actions.tap()
     print(
         f"This Pokemon is called {self.name} and it is a {self.poke_type} type from the {self.region} region."
     )
     Actions.tap()
     print(f"This particular {self.name} is level {self.level}")
Ejemplo n.º 16
0
    def set_available_actions(self):
        """
		Appends actions to all_moves
		"""
        self.all_moves = self.adjacent_movements
        self.all_moves.append(Actions.ViewInventory())
        self.all_moves.append(Actions.Equip())
        self.all_moves.append(Actions.ViewCharacter())
Ejemplo n.º 17
0
def mom_intro_event(player_name):
    print("You gently open your eyes and you see a more than familiar face.")
    Actions.tap()
    print("You see your mother staring you straight in the face. gitty with excitement.")
    Actions.tap()
    dialouge.mom_diag_1(player_name)
    print("She sneaks out the room closing the door behind her.")
    player_awake()
Ejemplo n.º 18
0
 def sort_function(cls, model, iter1, iter2, column):
     """ Overrides default sorting behaviour """
     data1, data2 = [model.get_value(x, column) for x in (iter1, iter2)]
     try:
         first = Actions.MachineSortableDate(data1)
         second = Actions.MachineSortableDate(data2)
     except ValueError, err:
         print err
         return cmp(first, second)
Ejemplo n.º 19
0
    def __info_user(self, author, subject, text, limit):
        # check that we have text
        lines = [l.strip() for l in self.line_splitter.split(text) if l is not None and len(l.strip())]
        if not len(lines):
            Actions.send_message(self.praw, author, u"RE: info user",
                                 u"No users specified in text:  \n{}".format(text))
            return False

        invalid_users = []
        valid_users = []
        #now go through the lines and make sure they're all usernames
        for line in lines:
            match = self.user_name_match.search(line)
            if not match:
                invalid_users.append(line)
            else:
                valid_users.append(match.group(1))

        if not len(valid_users):
            if len(invalid_users):
                message = u'The following were not recognized as usernames:  \n{}'.format(u', '.join(invalid_users))
            else:
                message = u"No users specified in text: ".format(text)
            Actions.send_message(self.praw, author, u"RE: info user", message)
            return False

        valid_users = list(set(valid_users))
        return_string = self.__create_table((u'Date',
                                             u'Link', u'Submitter', u'Channel', u'Domain', u'Deleted', u'Exception'))
        #with our list of usernames, query DB for submissions
        with DataBaseWrapper(self.owner.database_file, False) as db:
            for user in valid_users:
                #val is (short_url, channel_id, domain, date_added, processed, exception
                val = db.get_reddit(submitter=user, return_channel_id=True, return_domain=True, return_processed=True,
                                    return_exception=True, sort_by_new=True, limit=limit, return_dateadded=True)
                if val is not None and len(val):
                    for submission in val:
                        return_string += self.__table_entry((
                            str(submission[3]),
                            u'http://redd.it/{}'.format(submission[0][submission[0].index('t3_')+ 3:]),
                            user,
                            submission[1], submission[2],
                            u'True' if submission[4] == 1 else u'False',
                            u'True' if submission[5] == 0 and submission[4] == 1 else u'False'))
                else:
                   return_string += self.__table_entry((u'Not Found', user, u'N/A', u'N/A', u'N/A', u'N/A'))
        if invalid_users:
            return_string += u'\n\n'
            return_string += u"The following were not recognized as users:\n"
            return_string += u'\n'.join(invalid_users)

        return_string += u'\n\n'
        return_string += u'Note: Deletions and Exceptions are processed every {:.1} day(s),'.format(
                         self.policy.Historial_Scan_Period / (24.0 * 60.0 * 60.0)) + \
                         u' and thus may not be updated within that time window.'

        return Actions.send_message(self.praw, author, u'Re: User Info query', return_string)
Ejemplo n.º 20
0
 def tearDownClass(self):
     driver = self.driver
     print("Searching finished, waiting for all downloads to complete...")
     Actions.downloads_done()
     print("Test Two, number of downloaded beatmapsets: %s" % len(OsuAutomationTwo.downloaded_beatmapsets))
     driver.switch_to.window(driver.window_handles[1])
     driver.close()
     driver.switch_to.window(driver.window_handles[0])
     driver.close()
def perimeter_detect(action):
    zymkey.client.set_perimeter_event_actions(1,
                                              action_notify=True,
                                              action_self_destruct=False)
    while True:
        try:
            logInfo = ""
            #detect perimeter breach every 2 seconds
            zymkey.client.wait_for_perimeter_event(timeout_ms=2000)
            perimeter_status = ""
            plst = zymkey.client.get_perimeter_detect_info()
            #print(plst)
            now = datetime.now()
            #print warning, date and time of the breach
            print("\nPerimeter event detected at (%s %s):" %
                  (datetime.date(now), datetime.time(now)))
            logInfo += "\nPerimeter event detected at " + str(
                datetime.date(now)) + "  " + str(datetime.time(now))
            #Detect in which loop the perimeter has been detected.
            for z in range(len(plst)):
                p = plst[z]
                if p:
                    #first loop is broken (inner loop)
                    if z == 0:
                        print("  Breach in the inner loop has been detected!")
                        logInfo += "\n  Breach in the inner loop has been detected!"
                    #second loop is broken (outer loop)
                    elif z == 1:
                        print("  Breach in the outer loop has been detected!")
                        logInfo += "\n  Breach in the outer loop has been detected!"
            for j in range(len(plst)):
                p = plst[j]
                #log perimeter detection info
                perimeter_status = "    perimeter[%d] timestamp = %d" % (j, p)
                logInfo += "\n     perimeter[" + str(
                    j) + "] timestamp = " + str(p)
                print(perimeter_status)
            misc.logInfo_perim(logInfo)
            if action == '1':
                subject = "Security Alert - Perimeter Breach Detected: " + str(
                    datetime.date(now)) + " " + str(datetime.time(now))
                act.send_email(subject, logInfo)
            elif action == '2':
                #add self destruct code here.
                Actions.selfDestruct()
                print("selfDestruct")
            zymkey.client.clear_perimeter_detect_info()
        except zymkey.exceptions.ZymkeyTimeoutError:
            logInfo = ""
            now = datetime.now()
            #no perimeter breach has been detected
            print("Nothing going on at (%s %s):" %
                  (datetime.date(now), datetime.time(now)))
            logInfo += "\nNothing going on at " + str(
                datetime.date(now)) + "  " + str(datetime.time(now))
            misc.logInfo_perim(logInfo)
Ejemplo n.º 22
0
    def __init__(self):

        Classe.__init__(self)
        self.name = "Mage"

        self.baseAP = 3
        self.baseHP = 2
        self.char = chr(244)
        self.type = 'mage'

        self.base_skills.append(Actions.Attack())
        self.base_skills.append(Actions.Paralyse())
Ejemplo n.º 23
0
 def adjacent_moves(self):
     """Returns all move actions for adjacent tiles."""
     moves = []
     if World.tile_exists(self.x + 1, self.y):
         moves.append(Actions.MoveEast())
     if World.tile_exists(self.x - 1, self.y):
         moves.append(Actions.MoveWest())
     if World.tile_exists(self.x, self.y + 1):
         moves.append(Actions.MoveNorth())
     if World.tile_exists(self.x, self.y - 1):
         moves.append(Actions.MoveSouth())
     return moves
Ejemplo n.º 24
0
    def __init__(self):

        Classe.__init__(self)
        self.name = "Assasin"

        self.baseAP = 4
        self.baseHP = 3
        self.char = chr(105)
        self.type = 'stealth'

        self.base_skills.append(Actions.Attack())
        self.base_skills.append(Actions.BackStab())
Ejemplo n.º 25
0
 def update_selected_elements(self):
     """
     Update the selected elements.
     The update behavior depends on the state of the mouse button.
     When the mouse button pressed the selection will change when
     the control mask is set or the new selection is not in the current group.
     When the mouse button is released the selection will change when
     the mouse has moved and the control mask is set or the current group is empty.
     Attempt to make a new connection if the old and ports are filled.
     If the control mask is set, merge with the current elements.
     """
     selected_elements = None
     if self.mouse_pressed:
         new_selections = self.what_is_selected(self.get_coordinate())
         #update the selections if the new selection is not in the current selections
         #allows us to move entire selected groups of elements
         if self.get_ctrl_mask() or not (new_selections
                                         and new_selections[0]
                                         in self.get_selected_elements()):
             selected_elements = new_selections
         if self._old_selected_port:
             self._old_selected_port.force_label_unhidden(False)
             self.create_shapes()
             self.queue_draw()
         elif self._new_selected_port:
             self._new_selected_port.force_label_unhidden()
     else:  # called from a mouse release
         if not self.element_moved and (not self.get_selected_elements()
                                        or self.get_ctrl_mask()):
             selected_elements = self.what_is_selected(
                 self.get_coordinate(), self.press_coor)
     #this selection and the last were ports, try to connect them
     if self._old_selected_port and self._new_selected_port:
         try:
             self.connect(self._old_selected_port, self._new_selected_port)
             Actions.ELEMENT_CREATE()
         except:
             Messages.send_fail_connection()
         self._old_selected_port = None
         self._new_selected_port = None
         return
     #update selected elements
     if selected_elements is None: return
     old_elements = set(self.get_selected_elements())
     self._selected_elements = list(set(selected_elements))
     new_elements = set(self.get_selected_elements())
     #if ctrl, set the selected elements to the union - intersection of old and new
     if self.get_ctrl_mask():
         self._selected_elements = list(
             set.union(old_elements, new_elements) -
             set.intersection(old_elements, new_elements))
     Actions.ELEMENT_SELECT()
Ejemplo n.º 26
0
    def __init__(self):

        Classe.__init__(self)
        self.name = "Archer"

        self.baseAP = 3
        self.baseHP = 3
        self.char = chr(68)
        self.type = 'range'

        self.base_skills.append(Actions.RangeAttack())

        self.base_skills.append(Actions.Kick())
Ejemplo n.º 27
0
 def __init__(self):
     self._pokename = "Electrode_" + str(random.randint(1, 100000))
     self._max_health = 50
     self.attack = 0.20
     self.defence = 0.10
     self.speed = 23
     self.poketype = PokemonType.ELECTRIC
     self.actions = list([Actions.Attack("Electrospit", 1, 14, 0.7),
                          Actions.Attack("Electroblow", 1, 22, 0.6),
                          Actions.Defence("Electroshield", 1, 0.1),
                          Actions.Defence("Electrobulb", 1, 0.3),
                          Actions.Waiting()])
     self.effects = list()
Ejemplo n.º 28
0
    def __init__(self):

        Classe.__init__(self)
        self.name = "Warrior"

        self.baseAP = 3
        self.baseHP = 4
        self.char = chr(82)

        self.type = 'fight'

        self.base_skills.append(Actions.Attack())
        self.base_skills.append(Actions.Lock())
Ejemplo n.º 29
0
    def available_actions(self):
        """
		Describes all methods Actions can call in this room
		 Is default behavior, different tiles(subclasses) will specify more actions

		Output:
			moves [<Actions>]
		"""
        moves = self.adjacent_moves()
        moves.append(Actions.ViewInventory())
        moves.append(Actions.Quit())

        return moves
Ejemplo n.º 30
0
def poke_selection():

    print("We have 3 Pokemon to adopt from.")
    Actions.tap()
    print("Please choose from either, \n[A] Cyndaquil\n[B] Totodile\n[C] Chikorita")
    ans = input("> ")
    if ans == "A":  # choose Cyndaquil
        print(" This is Cyndiquil, a fire type! Are you sure this is who you want? [Y] or [N]")
        ans = input("> ")
    if ans == "Y":
        print("You Chose Cyndiquil!")
        Actions.tap()
        player_poke = poke_characters.cyndiquil_l5
        return player_poke

    elif ans == "B":  # choose Totodile
        print(" This is Totodile, a water type! Are you sure this is who you want? [Y] or [N]")
        ans = input("> ")
    if ans == "Y":
        print("You Chose Totodile!")
        Actions.tap()
        player_poke = poke_characters.totodile_l5
        return player_poke

    elif ans == "C":  # choose Chikorita
        print("This is Chikorita, a grass type! Are you sure this is who you want? [Y] or [N]")
        ans = input("> ")
    if ans == "Y":
        print("You chose Chikorita!")
        player_poke = poke_characters.chikorita_l5
        Actions.tap()
        return player_poke

    print("No problem Take your time!")
    return None
Ejemplo n.º 31
0
def pallet_town():
    print("You see gorgeous blue skies, the field of short green grass that surround your small town. You see..."
          "\n [A] The Pallet Town PokeLab"
          "\n [B] The Westward Ocean Coastline"
          "\n [C] You're House.")
    print("Which would you like to visit first?")
    ans = input("> ")
    if ans == "A":  # For Pallet Town Poke Lab
        print("You make your way over to the Pallet Town PokeLab")
        Actions.tap()
        print("As you approach the building the automatic doors swing open and you find yourself in the lobby.")
        poke_lab()
    elif ans == "B":  # For Westward Ocean Coastline
        print("You look left and you walk down the path to the Westward Ocean Coastline")
        Actions.tap()
        westward_coast()
        print(indev)
        pass  # Add method for the "West Ward Ocean Coast line", and loop back to outside world
    elif ans == "C":  # For Home
        print("You take a look front yard and the house you grew up in...")
        Actions.tap()
        print("You walk towards the door and enter your childhood home.")
        Actions.tap()
        door_2()
    else:
        print(invalid)
        pallet_town()
Ejemplo n.º 32
0
def without_breakfast():
    print("You're really going to leave without eating Mom's famous breakfast? [Y] or [N]")
    ans = input("> ")
    if ans == "Y":  # Leave with an empty stomach
        print("You leave at your own loss then...")
        Actions.tap()
        Actions.faint()
        player_awake()
    elif ans == "N":  # go back to eat breakfast
        print("Good lad, Now go eat that breakfast.")
        door()
    else:
        print(invalid)
        without_breakfast()
Ejemplo n.º 33
0
def listen(txt):
    global flag

    txt.delete('1.0', END)
    txt.update()

    if flag:
        wish_me(txt)
        flag = False

    dictionary = dict([
        ('play_media', ['play', 'music', 'mp3', 'song', 'video']),
        ('movie', ['play', 'movie', 'movies']),
        ('google', ['google', 'search', 'web', 'internet']),
        ('youtube', ['youtube', 'play', 'video', 'videos', 'entertainment']),
        ('wikipedia',
         ['wikipedia', 'encyclopedia', 'search', 'article', 'articles']),
        ('weather', ['weather', 'temperature', 'climate']),
        ('news', ['news', 'headlines']),
        ('day_date_time', ['day', 'date', 'time']),
        ('horoscope', ['horoscope', 'fortune', 'luck']),
        ('joke', ['joke', 'jokes', 'fun', 'funny']),
        ('note', ['note', 'notes', 'memorize']), ('email', ['mail', 'email']),
        ('repeat', ['repeat', 'sorry', 'pardon']),
        ('bye', ['goodbye', 'bye', 'exit', 'close'])
    ])

    score = dict([('play_media', 0), ('movie', 0),
                  ('google', 0), ('youtube', 0), ('wikipedia', 0),
                  ('weather', 0), ('news', 0), ('day_date_time', 0),
                  ('horoscope', 0), ('joke', 0), ('note', 0), ('email', 0),
                  ('repeat', 0), ('bye', 0)])

    query = take_command(txt).lower()
    words = query.split(' ')

    for word in words:
        for keyword in dictionary:
            for value in dictionary.get(keyword):
                if word == value:
                    score[keyword] += 1
                    break

    max_score = max(score, key=score.get)

    if score.get(max_score) == 0:
        Actions.general_conversation(query, txt)
    else:
        getattr(Actions, max_score)(query, txt)
Ejemplo n.º 34
0
 def __init__(self):
     self._pokename = "Krabby_" + str(random.randint(1, 100000))
     self._max_health = 75
     self.attack = 0.15
     self._defence = 0.10
     self.speed = 17
     self.poketype = PokemonType.WATER
     self.actions = list([Actions.Attack("Claw Bite", 1, 12, 0.8),
                          Actions.Attack("Claw Smash", 1, 17, 0.6, effects=[
                              Effects.Stun("Claw Smash", 100)
                          ]),
                          Actions.Defence("Crab Defence", 1, 0.2),
                          Actions.Defence("Super Crab Defence", 1, 0.4),
                          Actions.Waiting()])
     self.effects = list()
Ejemplo n.º 35
0
 def _level_up(self, level):
     if 2 == level:
         self._max_health = 100
         self.attack = 0.20
         self._defence = 0.15
         self.speed = 21
         self.actions.append(Actions.Attack("Claw Slash", 1, 14, 0.7, effects=[
             Effects.Poisoning("Отравление", 150, 6)
         ]))
     if 3 == level:
         self._max_health = 130
         self.attack = 0.30
         self._defence = 0.20
         self.speed = 25
         self.actions.append(Actions.Attack("Mighty Smash", 1, 28, 0.8))
Ejemplo n.º 36
0
    def available_actions(self):
        """
		Changes the base available actions, 
		 if the enemy is alive only allow the player to attack or flee
		 otherwise the default moves
		"""
        if self.enemy.is_alive():
            return [Actions.Flee(tile=self), Actions.Attack(enemy=self.enemy)]

        else:
            moves = self.adjacent_moves()
            moves.append(Actions.ViewInventory())
            moves.append(Actions.Quit())

            return moves
Ejemplo n.º 37
0
 def check_exception(self, post):
     try:
         #check for link flair
         if post.link_flair_css_class is None:
             return True
     except:
         pass
     try:
         #check for removal reason
         if post.removal_reason is not None:
             return True
     except:
         pass
     #check top level comments for specific keyword matches
     try:
         success = True
         #check comments
         for comment in post.comments:
             #test comment
             if not Actions.is_deleted(comment) and comment.distinguished == 'moderator':
                 #test keyword
                 for exception in self.policy.exception_list:
                     if re.search(exception, comment.body):
                         return True
         return False
     except Exception, e:
         success = False
         time.sleep(1)
Ejemplo n.º 38
0
def test_approve_post(post):
    print "Approve Post:"
    if a.approve_post(post):
        print "Passed"
        return True
    print "Failed"
    return False
Ejemplo n.º 39
0
def test_send_message(reddit, credentials):
    if a.send_message(reddit, credentials['ALTUSER'], "test", "testmessage"):
        print "Test Message Send: Passed"
        return True
    else:
        print "Test Message Send: Failed"
        return False
Ejemplo n.º 40
0
	def __init__(self, file_paths, platform):
		"""
		ActionHandler constructor.
		Create the main window, setup the message handler, import the preferences,
		and connect all of the action handlers. Finally, enter the gtk main loop and block.
		@param file_paths a list of flow graph file passed from command line
		@param platform platform module
		"""
		self.clipboard = None
		for action in Actions.get_all_actions(): action.connect('activate', self._handle_action)
		#setup the main window
		self.main_window = MainWindow(platform)
		self.main_window.connect('delete-event', self._quit)
		self.main_window.connect('key-press-event', self._handle_key_press)
		self.get_page = self.main_window.get_page
		self.get_flow_graph = self.main_window.get_flow_graph
		self.get_focus_flag = self.main_window.get_focus_flag
		#setup the messages
		Messages.register_messenger(self.main_window.add_report_line)
		Messages.send_init(platform)
		#initialize
		self.init_file_paths = file_paths
		Actions.APPLICATION_INITIALIZE()
		#enter the mainloop
		gtk.main()
Ejemplo n.º 41
0
    def run(self):
        while True:
            if not self.check_status():
                break

            # see if we need to update mods
            if datetime.datetime.now() - self.last_mod_update > self.policy.Mod_Update_Period:
                if __debug__:
                    logging.info(u"Blacklist Query updating mod list...")
                self.update_mods()
                if __debug__:
                    logging.info(u"Modlist updated to: {}".format(u", ".join(self.mod_list)))

            # get unread
            unread = Actions.get_unread(self.praw, limit=self.policy.Unread_To_Load)
            try:
                messages = [message for message in unread]
                if __debug__:
                    logging.info(u"Blacklist query processing {} messages...".format(len(messages)))
                for message in messages:
                    self.process_message(message)
                    if __debug__:
                        logging.info(u"Blacklist query processing message from user {}.\nSubject:{}\nBody:{}".
                                     format(message.author.name if message.author.name is not None else u"DELETED",
                                            message.subject, message.body))
            except Exception, e:
                logging.error(u"Error on retrieving unread messages")
                if __debug__:
                    logging.exception(e)
                self.log_error()

            self.message_cache = []

            # and wait (min of 30s to prevent return of cached answers on default PRAW install)
            time.sleep(max(self.policy.Blacklist_Query_Period, 30))
Ejemplo n.º 42
0
    def scan(self, limit=None):
        """Scans the sub.

        :param limit: If None, the limit in the policy will be used
        :return: True if self.last_seen was reached, False otherwise
        """

        lim = limit if limit else self.policy.Posts_To_Load
        # first ask for posts
        posts = self.get_posts(lim)
        if posts is None:
            return scan_result.Error
        found_old = False

        post_data = []
        for post in posts:
            try:
                if not post.is_self:
                    post_data.append((
                        post.created_utc, post.name, post.url,
                        Actions.get_username(post), post))
            except socket.error, e:
                if e.errno == 10061:
                    logging.critical("praw-multiprocess not started!")
                else:
                    logging.error(str(e))
                return scan_result.Error
            except (HTTPError, NotFound) as e:
                # bad resolve
                logging.warn('Bad resolve for post {}'.format(post))
Ejemplo n.º 43
0
 def historical_scan(self, goto):
     posts = self.get_historial_posts(goto)
     if posts is not None and len(posts):
         post_data = [(post.created_utc, post.name, post.url, Actions.get_username(post), post) for post in posts if not post.is_self]
         self.__process_post_list(post_data)
         return scan_result.FoundOld
     return scan_result.Error
Ejemplo n.º 44
0
def test_strike_counter():
    try:
        os.remove("test_database.db")
    except:
        pass
    credentials = CRImport("TestCredentials.cred")

    mypraw = u.create_multiprocess_praw(credentials)
    pol = Policies.DebugPolicy(None)
    sub = u.get_subreddit(credentials, mypraw)

    cs = CentralScrutinizer.CentralScrutinizer(credentials, pol, "test_database.db")
    scount = cs.scount

    print "Simple strike count test:"
    #make post
    post = a.make_post_url(sub, "test", "https://www.youtube.com/watch?v=vmT0lCfybR4")

    with DataBase.DataBaseWrapper("test_database.db") as db:
        db.add_reddit([(post.name, "arghdos", "youtube", datetime.datetime.today())])
        db.add_channels([("arghdos", "youtube", "http://www.youtube.com/user/arghdos", Blacklist.BlacklistEnums.NotFound, 2)])

    post.set_flair("test")

    #delete
    post.delete()

    #run counter
    scount.scan()

    #check strikes
    with DataBase.DataBaseWrapper("test_database.db") as db:
        result = db.get_channels(id_filter="arghdos", return_strikes=True)[0][-1]

    if result != 3:
        print "Failed"
        return False

    with DataBase.DataBaseWrapper("test_database.db") as db:
        result = db.get_blacklist([("arghdos", "youtube")])[0] == Blacklist.BlacklistEnums.Blacklisted
    if not result:
        print "Failed"
        return False

    #set to non-blacklisted and run again to check deletion
    db.set_blacklist([("arghdos", "youtube")], Blacklist.BlacklistEnums.NotFound)

     #run counter
    scount.scan()

    #check strikes
    with DataBase.DataBaseWrapper("test_database.db") as db:
        result = db.get_channels(id_filter="arghdos", return_strikes=True)[0][-1]

    if result != 3:
        print "Failed"
        return False

    print "Passed"
Ejemplo n.º 45
0
def test_get_moderators(r, sub):
    print "Test Get Mods:"
    mods = a.get_mods(r, sub)
    if len([u for u in mods if any(name == u.name for name in ['arghdos', 'centralscruuutinizer'])]) == 2:
        print "Passed"
        return True
    print "Failed"
    return False
Ejemplo n.º 46
0
def test_get_by_id(praw, ids):
    list = a.get_by_ids(praw, ids)
    if list:
        list = [l for l in list]
        if len(list):
            print "Passed"
            return True
    print "Failed"
    return False
Ejemplo n.º 47
0
 def get_posts(self, lim):
     # first ask for posts
     try:
         posts = self.sub.mod.log(action="removelink", limit=lim)
         posts = [posts.next().target_fullname for i in range(lim)]
         return Actions.get_by_ids(self.praw, posts)
     except Exception, e:
         logging.error(str(e))
         if __debug__:
             logging.exception(e)
Ejemplo n.º 48
0
def test_xpost(post, credentials, praw, sub):
    mysub = u.get_subreddit(credentials, praw, sub)
    val = a.xpost(post, mysub, "test")
    print "Xpost:"
    if val:
        print "Passed"
        return True
    else:
        print "Failed"
        return False
Ejemplo n.º 49
0
 def __init__(self, platform, action_handler_callback):
     """
     MainWindow contructor
     Setup the menu, toolbar, flowgraph editor notebook, block selection window...
     """
     self._platform = platform
     gen_opts = platform.get_block('options').get_param('generate_options')
     generate_mode_default = gen_opts.get_value()
     generate_modes = [
         (o.get_key(), o.get_name(), o.get_key() == generate_mode_default)
         for o in gen_opts.get_options()]
     # load preferences
     Preferences.load(platform)
     #setup window
     gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
     vbox = gtk.VBox()
     self.hpaned = gtk.HPaned()
     self.add(vbox)
     #create the menu bar and toolbar
     self.add_accel_group(Actions.get_accel_group())
     self.menu_bar = Bars.MenuBar(generate_modes, action_handler_callback)
     vbox.pack_start(self.menu_bar, False)
     self.tool_bar = Bars.Toolbar(generate_modes, action_handler_callback )
     vbox.pack_start(self.tool_bar, False)
     vbox.pack_start(self.hpaned)
     #create the notebook
     self.notebook = gtk.Notebook()
     self.page_to_be_closed = None
     self.current_page = None
     self.notebook.set_show_border(False)
     self.notebook.set_scrollable(True) #scroll arrows for page tabs
     self.notebook.connect('switch-page', self._handle_page_change)
     #setup containers
     self.flow_graph_vpaned = gtk.VPaned()
     #flow_graph_box.pack_start(self.scrolled_window)
     self.flow_graph_vpaned.pack1(self.notebook)
     self.hpaned.pack1(self.flow_graph_vpaned)
     self.btwin = BlockTreeWindow(platform, self.get_flow_graph);
     self.hpaned.pack2(self.btwin, False) #dont allow resize
     #create the reports window
     self.text_display = TextDisplay()
     #house the reports in a scrolled window
     self.reports_scrolled_window = gtk.ScrolledWindow()
     self.reports_scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
     self.reports_scrolled_window.add(self.text_display)
     self.reports_scrolled_window.set_size_request(-1, DEFAULT_REPORTS_WINDOW_WIDTH)
     self.flow_graph_vpaned.pack2(self.reports_scrolled_window, False) #dont allow resize
     #load preferences and show the main window
     self.resize(*Preferences.main_window_size())
     self.flow_graph_vpaned.set_position(Preferences.reports_window_position())
     self.hpaned.set_position(Preferences.blocks_window_position())
     self.show_all()
     self.reports_scrolled_window.hide()
     self.btwin.hide()
Ejemplo n.º 50
0
def test_get_message(credentials):
    r = praw.Reddit(user_agent=credentials['USERAGENT'])
    r.login(username=credentials['ALTUSER'], password=credentials['ALTPASS'])
    messages = a.get_unread(r)
    message = messages.next()
    success = message.author.name == 'centralscruuutinizer' and message.body == "testmessage" and message.subject == "test"
    if success:
        print "Test Get Message: Passed"
        return True
    print "Test Get Message: Failed"
    return True
Ejemplo n.º 51
0
	def _handle_key_press(self, widget, event):
		"""
		Handle key presses from the keyboard and translate key combinations into actions.
		This key press handler is called prior to the gtk key press handler.
		This handler bypasses built in accelerator key handling when in focus because
		* some keys are ignored by the accelerators like the direction keys,
		* some keys are not registered to any accelerators but are still used.
		When not in focus, gtk and the accelerators handle the the key press.
		@return false to let gtk handle the key action
		"""
		if not self.get_focus_flag(): return False
		return Actions.handle_key_press(event)
Ejemplo n.º 52
0
def main():
    from CredentialsImport import CRImport
    import utilitymethods as u
    import logging

    testbed = None
    saved_posts = {}

    # mark true if the script should remove all old posts from the testbed
    DELETE_OLD = True

    #import credentials
    credentials = CRImport("TestCredentials.cred")

    #create my reddit
    r = u.create_multiprocess_praw(credentials)

    #get testbed sub
    testbed = u.get_subreddit(credentials, r)

    #create datasource object
    datasource = u.get_subreddit(credentials, r, credentials["DATAMININGSUB"])

    if DELETE_OLD:
        old_stream = praw.helpers.submission_stream(r, testbed, limit=POST_LIMIT)
        results = []
        try:
            #delete all old posts
            for post in old_stream:
                try:
                    Actions.remove_post(post, delete=True)
                    print("deleted old post: %s..." % post.title[:20])
                except AttributeError:
                    # Post or Comment may have been deleted between retrieving it
                    # and accessing its fields
                    pass
        except AssertionError, e:
            logging.log(logging.DEBUG, str(e) + "\nNo Posts!")
Ejemplo n.º 53
0
	def __init__(self):
		"""
		Parse the list of action names in the toolbar list.
		Look up the action for each name in the action list and add it to the toolbar.
		"""
		gtk.Toolbar.__init__(self)
		self.set_style(gtk.TOOLBAR_ICONS)
		for action_name in TOOLBAR_LIST:
			if action_name:	#add a tool item
				action = Actions.get_action_from_name(action_name)
				self.add(action.create_tool_item())
				#this reset of the tooltip property is required (after creating the tool item) for the tooltip to show
				action.set_property('tooltip', action.get_property('tooltip'))
			else: self.add(gtk.SeparatorToolItem())
Ejemplo n.º 54
0
    def process_message(self, message):
        """
        Handles the processing of unread messages
        :param message: the message to process
        """
        result = None
        # valid author check
        if message.author and any(name == message.author.name for name in self.mod_list) and not self.is_cached(message.id):
            subject = message.subject
            text = message.body
            # check that it matches one of the basic commands
            matches = [bc for bc in self.base_commands if bc.search(subject)]
            if len(matches) == 1:
                # take care of add /removes
                if matches[0] == self.add_command:
                    self.__add_remove(message.author.name, subject, text, True)
                elif matches[0] == self.remove_command:
                    self.__add_remove(message.author.name, subject, text, False)
                # update mods
                elif matches[0] == self.update_command:
                    self.update_mods(message.author.name)
                # print query
                elif matches[0] == self.info_command:
                    result = self.__info(message.author.name, subject, text)
                # help query
                elif matches[0] == self.help_command:
                    Actions.send_message(self.praw, message.author.name, u"RE:{}".format(message.subject),
                                         self.doc_string)

            if len(matches) != 1:
                Actions.send_message(self.praw, message.author.name, u"RE:{}".format(message.subject),
                                     u"Sorry, I did not recognize your query.  \n".format(text) + self.short_doc_string)

        self.message_cache.append(message.id)
        # don't need to see this again
        message.mark_read()
        return result
Ejemplo n.º 55
0
	def update_exec_stop(self):
		"""
		Update the exec and stop buttons.
		Lock and unlock the mutex for race conditions with exec flow graph threads.
		"""
		sensitive = self.get_flow_graph().is_valid() and not self.get_page().get_pid()
		Actions.get_action_from_name(Actions.FLOW_GRAPH_GEN).set_sensitive(sensitive)
		Actions.get_action_from_name(Actions.FLOW_GRAPH_EXEC).set_sensitive(sensitive)
		Actions.get_action_from_name(Actions.FLOW_GRAPH_KILL).set_sensitive(self.get_page().get_pid() != None)
Ejemplo n.º 56
0
 def _handle_key_press(self, widget, event):
     """
     Handle key presses from the keyboard and translate key combinations into actions.
     This key press handler is called prior to the gtk key press handler.
     This handler bypasses built in accelerator key handling when in focus because
     * some keys are ignored by the accelerators like the direction keys,
     * some keys are not registered to any accelerators but are still used.
     When not in focus, gtk and the accelerators handle the the key press.
     
     Returns:
         false to let gtk handle the key action
     """
     # prevent key event stealing while the search box is active
     if self.main_window.btwin.search_entry.has_focus(): return False
     if not self.get_focus_flag(): return False
     return Actions.handle_key_press(event)
Ejemplo n.º 57
0
 def get_historial_posts(self, goto):
     """Scans the sub with more intensive detection of previously found reddit posts
     Allows for mass processing of past posts
     """
     last_id = None
     last_seen = datetime.datetime.now()
     posts = []
     if self.policy.Use_Reddit_Analytics_For_Historical_Scan:
         while last_seen > goto:
             raise NotImplementedError
             if last_id:
                 self.RA_params["after"] = last_id
             try:
                 data = requests.get("http://api.redditanalytics.com/getPosts", params=self.RA_params,
                                     headers=self.RA_headers)
                 json_data = json.loads(data.content)
                 ids = [post["name"] for post in json_data["data"]]
                 with DataBase.DataBaseWrapper(self.file) as db:
                     exists = db.reddit_exists(ids)
                 if exists is not None:
                     ids = [ids[i] for i in range(len(ids)) if not exists[i]]
                 else:
                     return None
                 if not len(ids):
                     continue
                 temp_posts = Actions.get_by_ids(self.praw, ids)
                 if temp_posts is not None:
                     posts.extend(temp_posts)
                 else:
                     return None
                 last_id = json_data["metadata"]["oldest_id"]
                 last_seen = datetime.datetime.fromtimestamp(json_data["metadata"]["oldest_date"])
             except ValueError, e:
                 if str(e).startswith("No JSON object"):
                     logging.error("Reddit-Analytics is down, retrying historical scan after pause...")
                 else:
                     logging.error(str(e))
                     if __debug__:
                         logging.exception(e)
                 #temporary fix to avoid endless waiting while RA is down
                 return []
             except Exception, e:
                 logging.error(str(e))
                 if __debug__:
                     logging.exception(e)
                 #temporary fix to avoid endless waiting while RA is down
                 return []
Ejemplo n.º 58
0
    def __init__(self, platform):
        """
		MainWindow contructor
		Setup the menu, toolbar, flowgraph editor notebook, block selection window...
		"""
        self._platform = platform
        # setup window
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
        vbox = gtk.VBox()
        self.hpaned = gtk.HPaned()
        self.add(vbox)
        # create the menu bar and toolbar
        self.add_accel_group(Actions.get_accel_group())
        vbox.pack_start(Bars.MenuBar(), False)
        vbox.pack_start(Bars.Toolbar(), False)
        vbox.pack_start(self.hpaned)
        # create the notebook
        self.notebook = gtk.Notebook()
        self.page_to_be_closed = None
        self.current_page = None
        self.notebook.set_show_border(False)
        self.notebook.set_scrollable(True)  # scroll arrows for page tabs
        self.notebook.connect("switch-page", self._handle_page_change)
        # setup containers
        self.flow_graph_vpaned = gtk.VPaned()
        # flow_graph_box.pack_start(self.scrolled_window)
        self.flow_graph_vpaned.pack1(self.notebook)
        self.hpaned.pack1(self.flow_graph_vpaned)
        self.btwin = BlockTreeWindow(platform, self.get_flow_graph)
        self.hpaned.pack2(self.btwin, False)  # dont allow resize
        # create the reports window
        self.text_display = TextDisplay()
        # house the reports in a scrolled window
        self.reports_scrolled_window = gtk.ScrolledWindow()
        self.reports_scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.reports_scrolled_window.add_with_viewport(self.text_display)
        self.reports_scrolled_window.set_size_request(-1, DEFAULT_REPORTS_WINDOW_WIDTH)
        self.flow_graph_vpaned.pack2(self.reports_scrolled_window, False)  # dont allow resize
        # load preferences and show the main window
        Preferences.load(platform)
        self.resize(*Preferences.main_window_size())
        self.flow_graph_vpaned.set_position(Preferences.reports_window_position())
        self.hpaned.set_position(Preferences.blocks_window_position())
        self.show_all()
Ejemplo n.º 59
0
	def _handle_key_press(self, widget, event):
		"""
		Handle key presses from the keyboard and translate key combinations into actions.
		This key press handler is called prior to the gtk key press handler.
		This handler bypasses built in accelerator key handling when in focus because
		* some keys are ignored by the accelerators like the direction keys,
		* some keys are not registered to any accelerators but are still used.
		When not in focus, gtk and the accelerators handle the the key press.
		@return false to let gtk handle the key action
		"""
		#dont allow key presses to queue up
		if gtk.events_pending(): return True
		#extract action name from this key press
		key_name = gtk.gdk.keyval_name(event.keyval)
		mod_mask = event.state
		action_name = Actions.get_action_name_from_key_name(key_name, mod_mask)
		#handle the action if flow graph is in focus
		if action_name and self.get_focus_flag():
			self.handle_states(action_name)
			return True #handled by this method
		return False #let gtk handle the key press
Ejemplo n.º 60
0
	def __init__(self):
		"""
		Parse the list of submenus from the menubar list.
		For each submenu, get a list of action names.
		Look up the action for each name in the action list and add it to the submenu.
		Add the submenu to the menu bar.
		"""
		gtk.MenuBar.__init__(self)
		for main_action,action_names in MENU_BAR_LIST:
			#create the main menu item
			main_menu_item = main_action.create_menu_item()
			self.append(main_menu_item)
			#create the menu
			main_menu = gtk.Menu()
			main_menu_item.set_submenu(main_menu)
			for action_name in action_names:
				if action_name: #append a menu item
					action = Actions.get_action_from_name(action_name)
					main_menu.append(action.create_menu_item())
				else: main_menu.append(gtk.SeparatorMenuItem())
			main_menu.show_all() #this show all is required for the separators to show