Beispiel #1
0
 def test_new_tree_add_2_nodes_and_print_it(self):
     t = Tree()
     n = Node(title='test', id='1', parent_id='root')
     t.add(n)
     n = Node(title='test2', id='2', parent_id='1')
     t.add(n)
     print(t)
Beispiel #2
0
 def test_new_tree_add_2_nodes_and_search_it(self):
     t = Tree()
     n = Node(title='test', id='1', parent_id='root')
     t.add(n)
     n = Node(title='test2', id='2', parent_id='1')
     t.add(n)
     #print(t)
     result = t.search('2')
     self.assertEqual(result.get_id(), '2')
def grow_trees(stream):
    tree = Tree()
    node_added = signal('node_added')
    for parent, child, created_at in stream:
        candidate = Edge(parent, child, created_at)
        if tree.should_add(candidate):
            tree.add(candidate)
            if tree.is_root(candidate):
                node_added.send('grow_trees', tree_name=tree.name, edge=candidate) 
            node_added.send('grow_trees', tree_name=tree.name, edge=candidate)
    return tree
Beispiel #4
0
    def _accept(self):
        lhs, rhs = self.productions[0]

        parse_tree = Tree()
        parse_tree.data = lhs
        for tree in self.trees:
            parse_tree.add(tree)

        self._is_accepted = True
        self.trees = [parse_tree]

        return self.stack.raw_stack()
Beispiel #5
0
    def _reduce(self, look_up):
        lhs, rhs = self.productions[look_up]

        new_tree = Tree(lhs)
        for tree in self.trees[-len(rhs):]:
            new_tree.add(tree)

        self.trees = self.trees[:-len(rhs)] + [new_tree]

        reduced_stack = self.stack.raw_stack()[:-len(rhs) * 2]
        temp_state = reduced_stack[-1]
        new_state = self.gotos[temp_state][lhs]

        return reduced_stack + [lhs, new_state]
Beispiel #6
0
class GDriveMgrHelper:
    """
    Takes care of actually building a local structure that matches Google
    Drive's online and downloading all the files and folders into their
    correct places in the hierarchy.
    It uses gdrivefunctions.py to handle the gdrive API calls and auth
    """

    def __init__(self, root_dir):
        """:param: root_dir = a node to build tree off of"""
        # initialize directory Tree structure
        self.dir_tree = Tree()
        # this will be initialized in main where we get credentials and stuff
        self._service = None
        # where we will store all dl'd files
        self.root_dir = root_dir

    def set_service(self, service):
        self._service = service

    def get_service(self):
        return self._service

    def _get_files_in_folder(self, folder_id):
        """ 
        Gets the metadata for all the children inside a Google Drive folder
        
        :param: folder_id = the Google Drive id of a folder

        :return: list of dicts that have all the file metadata
        """
        children_ids = gdrive.get_children(self.get_service(), folder_id)
        total = 0
        files_list = []
        for child_id in children_ids:
            metadata = gdrive.get_file_metadata(self.get_service(), child_id)
            if metadata["labels"]["trashed"]:
                continue  # the file was marked as trash, don't download

            # add file's info as tuple to the returned list
            title = metadata["title"]
            mime = metadata["mimeType"]
            if len(metadata["parents"]) != 0:
                # parent id is in a dict inside a list
                parents = metadata["parents"][0]
                if parents["isRoot"]:
                    parent_id = "root"
                else:
                    parent_id = parents["id"]
            else:
                # some files have an empty parents list
                parent_id = None

            files_list.append(
                {"id": child_id, "mime": mime, "title": title, "parent_id": parent_id, "metadata": metadata}
            )

            # logging to stdout
            total += 1
            print("Retrieved file " + str(total) + ". " + title + " (" + mime + ")")

        return files_list

    def create_tree(self):
        """
        Generate a Tree object using file metadata from all of the files in
        Google Drive. then save it as a pickled object inside the data directory.
        """
        self._rec_create_tree("root")  # Google API uses "root" as id of root folder
        # pickle the object to a file so we can reuse it as a template to download files
        dir_tree_path = os.path.join(gdrive.DATA_DIR, "dir_tree.pickle")
        with open(dir_tree_path, "wb") as f:
            pickle.dump(self.dir_tree, f)

    def _rec_create_tree(self, folder_id):
        """
        Helper to create directory tree object

        :param: folder_id = Google Drive id of a folder
        """
        if folder_id is None:
            return

        if folder_id == "root":
            print("")
            print("----------------------------------------")
            print(" Starting to create tree from Root")
            print("----------------------------------------")
            print("")

        files_list = self._get_files_in_folder(folder_id)  # tuple

        for f in files_list:
            # add the file to the folder with id 'folder_id'
            new_node = Node(id=f["id"], title=f["title"], parent_id=f["parent_id"], metadata=f["metadata"])

            result = self.dir_tree.add(new_node)

            if result == 0:
                # parent_id was None, so it shouldn't be added
                continue
            elif result == -1:
                # parent node doesn't exist yet, so go get it
                self._rec_create_tree(f["parent_id"])

            # file is a folder that could have files in it...
            if f["mime"] == "application/vnd.google-apps.folder":
                print("")
                print("----------------------------------------")
                print(" New folder: " + f["title"])
                print("----------------------------------------")
                print("")

                self._rec_create_tree(f["id"])

        return

    def _rec_download_files(self, node):
        """Helper function to download_files()"""
        for child in node.get_children():
            if child.get_mime() == "application/vnd.google-apps.folder":
                try:
                    os.mkdir(child.get_title())
                except OSError as e:
                    print("Error:", e)
                    print("Tried to create '%s'" % child.get_title())
                try:
                    os.chdir(child.get_title())
                except OSError as e:
                    print("Error:", e)
                    print("Couldn't chdir to '%s'. Skipping download of this directory." % child.get_title())
                    continue

                self._rec_download_files(child)
            elif "vnd.google-apps" in child.get_mime():
                # file is a "google doc" file and can't be downloaded. Http error 400
                continue
            else:
                try:
                    gdrive.download_file(self.get_service(), child.get_id(), child.get_title())
                except OSError as e:
                    print("Error:", e)
                    print("Failed downloading '%s'" % child.get_title())
        os.chdir("../")

    def download_files(self):
        """ 
        Uses dir_tree to create folders and download all files except Google Docs.
        
        :return: 1 if encountered an OSError, 0 if no errors
        """
        with open("dir_tree.pickle", "rb") as f:
            print("loading tree...")
            tree = pickle.load(f)

        os.chdir(gdrive.GDRIVE_ROOT_DIR)

        try:
            self._rec_download_files(tree.get_root())
            return 0
        except OSError as e:
            return 1

    def update_gdrive_dir_tree(self):
        pass

    def push_local_file_changes_to_drive(self):
        pass
Beispiel #7
0
class TestTreeMethods(unittest.TestCase):
    
    def setUp(self):
        self.n1 = Node(title='node1', id='1', parent_id='root')
        self.n2 = Node(title='node2', id='2', parent_id='1')
        self.n3 = Node(title='node3', id='3', parent_id='1')
        self.n4 = Node(title='node4', id='4', parent_id='2')
        self.n5 = Node(title='node5', id='5', parent_id='4') 
        
        # set up tree with multiple nodes
        self.t1 = Tree()
        self.t1.add(self.n1) # node1 has many children
        self.t1.add(self.n2)
        self.t1.add(self.n3)
        self.t1.add(self.n4)
        self.t1.add(self.n5)
        #print("Tree before the test:")
        #print(self.t1)
        
        # set up tree with only one node besides root
        self.n6 = Node('node6', '6', parent_id='root')
        self.one_node_tree = Tree()
        self.one_node_tree.add(self.n6)

    def tearDown(self):
        self.n1 = None
        self.n2 = None
        self.n3 = None
        self.n4 = None
        self.n5 = None
        self.n6 = None
        self.t1 = None
        self.t2 = None

    def test_get_root(self):
        self.assertEqual(self.t1.get_root().get_id(), 'root')

    def test_init_node_not_have_id_root(self):
        """ test init using a node who's id is not 'root'"""
        n = Node(title='foo', id=0)
        t = Tree(n)
        self.assertEqual(t.get_root().get_id(), 'root')

    def test_init_node_has_id_of_root(self):
        n = Node(title='foo', id='root')
        t = Tree(n)
        self.assertEqual(t.get_root().get_id(), 'root')
    
    def test_string_empty_tree(self):
        t2 = Tree(None)
        self.assertEqual(t2.__str__(), '|---Google_Drive\n')

    def test_string_non_empty_tree(self):
        print("You can't really test this...automatically")
        print(self.t1)

    def test_search_for_root(self):
        result = self.t1.search('root')
        self.assertTrue(result.get_id() == 'root')

    def test_search_for_first_node_added(self):
        result = self.t1.search('1')
        self.assertTrue(result.get_id() == '1')

    def test_search_for_nonexisting_node_in_one_node_tree(self):
        result = self.one_node_tree.search(self.n2.get_id())
        self.assertTrue(result == None)
    
    def test_new_tree_add_2_nodes_and_print_it(self):
        t = Tree()
        n = Node(title='test', id='1', parent_id='root')
        t.add(n)
        n = Node(title='test2', id='2', parent_id='1')
        t.add(n)
        print(t)

    def test_new_tree_add_2_nodes_and_search_it(self):
        t = Tree()
        n = Node(title='test', id='1', parent_id='root')
        t.add(n)
        n = Node(title='test2', id='2', parent_id='1')
        t.add(n)
        #print(t)
        result = t.search('2')
        self.assertEqual(result.get_id(), '2')

# From here down, tests are failing
    def test_search_for_nested_leaf_node(self):
        result = self.t1.search(self.n5.get_id())
        self.assertTrue('5' == result.get_id())

    def test_search_for_node1(self):
        result = self.t1.search(self.n1.get_id())
        self.assertTrue(result.get_id(), '1')

    def test_search_for_node2(self):
        result = self.t1.search(self.n2.get_id())
        self.assertTrue(result.get_id(), '2')

    def test_search_for_node3(self):
        result = self.t1.search(self.n3.get_id())
        self.assertTrue(result.get_id(), '3')

    def test_search_for_node4(self):
        result = self.t1.search(self.n4.get_id())
        self.assertTrue(result.get_id(), '4')

    def test_search_for_node5(self):
        result = self.t1.search(self.n5.get_id())
        self.assertTrue(result.get_id(), '5')

    def test_search_empty_tree(self):
        root = None
        empty_tree = Tree(root)
        result = empty_tree.search(self.n1.get_id())
        self.assertEqual(result, None)

    def test_check_that_node_was_added(self):
        n = Node('test_node', id='7', parent_id='4')
        was_added = self.t1.add(n)
        #print(self.t1)
        self.assertEqual(was_added, 1)

    def test_add_node_whose_parent_is_in_tree(self):
        """ test adding node whose parent is node4 """
        n = Node('test_node2', id='8', parent_id='4')
        was_added = self.t1.add(n) # should be 1
        #print(self.t1)
        self.assertEqual(was_added, 1)

    def test_add_node_whose_parent_is_not_in_tree(self):
        n = Node('test_node3', id='9', parent_id='0')
        was_added = self.t1.add(n) # should be -1
        self.assertEqual(was_added, -1)

    def test_add_node_whose_parent_is_none(self):
        n = Node('test_node', id='8')
        was_added = self.t1.add(n) # should be 0
        self.assertEqual(was_added, 0)
def parse(input, grammar, actions, gotos):

    # TODO #1: create a list of trees

    trees = [] # List containing "trees", that is, the parent node of each tree

    stack = []
    stack.append(0)
    while True:
        print("stack: ", end = "")
        print(stack, end = " ")
        print("input: ", end = "")
        print(input, end = " ")
        state = stack[-1]
        token = input[0]
        action = actions[(state, token)]
        print("action: ", end = "")
        print(action)

        if action is None:
            return None  # tree building update

        # shift operation
        if action[0] == 's':
            input.pop(0)  # Get the symbol out of the input, removing it
            stack.append(token)  # Add the removed symbol that was already processed in the previous loop into the stack
            state = int(action[1])  # Loads the appropriate action to taken from the actions dictionary generated from the .csv table
            stack.append(state)

            # TODO #2: create a new tree, set data to token, and append it to the list of trees

            tree = Tree()       # Create new tree
            tree.data = token   # Parent node will be the token
            trees.append(tree)  # Add the tree to the list of trees we have





        # reduce operation
        elif action[0] == 'r':
            production = grammar[int(action[1])]
            lhs = getLHS(production)
            rhs = getRHS(production)
            for i in range(len(rhs) * 2):
                stack.pop()
            state = stack[-1]   # State for the goto value
            stack.append(lhs)
            stack.append(int(gotos[(state, lhs)]))

            # TODO #3: create a new tree and set data to lhs
            newTree = Tree()       # Create a new tree because both trees will unify under the new parent when reducing
            newTree.data = lhs     # Start with the tree on the left hand side


            # TODO #4: get "len(rhs)" trees from the right of the list of trees and add each of them as child of the new tree you created, preserving the left-right order
            for tree in trees[-len(rhs):]:      # Get each tree from the list of trees and add them as a child of our tree for reduction
                newTree.add(tree)   # Add the tree as a child


            # TODO #5: remove "len(rhs)" trees from the right of the list of trees
            # Because we do not want to keep the trees that were moved to the new tree (don't want duplicates)
            trees = trees[:-len(rhs)]       # Remove all the trees aside from the ones moved

            # TODO #6: append the new tree to the list of trees
            trees.append(newTree)   # Add the newly created tree to the list of trees

        # not a shift or reduce operation, must be an "accept" operation
        else:
            production = grammar[0]
            lhs = getLHS(production)
            rhs = getRHS(production)

            # TODO #7: same as reduce but using the 1st rule of the grammar
            # Merge all of the trees from the list and put them under the start symbol

            root = Tree()
            root.data = lhs

            for tree in trees:
                root.add(tree)
            # TODO #8: return the new tree
            return root
Beispiel #9
0
class Commands:
    """Helper class, contains command for bind events, menu and buttons."""

    def __init__(self, drawer):
        """Initialization commands class."""
        self.drawer = drawer
        self.phrases = self.drawer.phrases
        self.message = Message(self.drawer)
        self.notes = Notes(self.message, self.phrases)
        self.config = self.drawer.config
        self.config.checker(self.message, self.phrases)
        self.tree = Tree()
        self.actions = Actions(self.tree, self.notes)

        self.set_window()

    def set_window(self):
        """Set size and position window from saving data."""
        self.drawer.SetPosition(self.config.get_pos())
        self.drawer.SetSize(self.config.get_size())
        self.drawer.Layout()

    def donate(self, event):
        """Run donate hyperlink in browser."""
        webbrowser.open(self.config.donate_url)

    def home(self, event):
        """Run home page hyperlink in browser."""
        webbrowser.open(self.phrases.about.url)

    def about(self, event):
        """Run about dialog."""
        About(
              self.drawer,
              self.phrases.about.title,
              self.phrases.about.name,
              version.VERSION,
              self.phrases.about.author
             ).ShowModal()

    def close(self, event):
        """Close event for button close."""
        self.drawer.Close(True)

    def close_window(self, event):
        """Close window event."""
        if self.config.general_expand == 'true':
            self.expand_tree_save()
        self.notes.close()

        self.config.set_pos(self.drawer.GetScreenPosition())
        self.config.set_size(self.drawer.GetSize())
        self.config.close()

        self.drawer.Destroy()

    def __sort(self, titles, parents):
        """Sort titles and parents dictionaries by order_sort field."""
        sort_notes = OrderedDict()
        parents_list = [0]
        childs = []
        while parents:
            for parent in parents_list:
                order_dict = self.notes.get_order(parent)
                if order_dict:
                    order_id = [item[0] for item in sorted(list(order_dict.items()), key=lambda i: i[1])]
                    for index in order_id:
                        sort_notes[index] = (parent, titles[index])
                        parents.pop(index)
                    childs.append(copy.copy(order_id))
            parents_list = childs.pop(0)
        return sort_notes

    def init_tree(self):
        """Initialization tree widget."""
        titles = self.notes.get_titles()
        parents = self.notes.get_parents()
        sort_notes = self.__sort(titles, parents)
        wx_tree_id = self.drawer.tree.AddRoot(self.phrases.widgets.tree.root)
        self.tree.add(0, -1, wx_tree_id)
        for index, note in sort_notes.items():
            parent_wx_tree_id = self.tree.id2wx_tree_id(note[0])
            wx_tree_id = self.drawer.tree.AppendItem(parent_wx_tree_id, note[1])
            self.tree.add(index, note[0], wx_tree_id)
        if self.config.general_expand == 'true':
            self.expand_tree_init()

    def expand_tree_init(self):
        """Init expand tree if set config settings."""
        expands = self.notes.get_expands()
        wx_tree_id = self.tree.id2wx_tree_id(0)
        self.drawer.tree.Expand(wx_tree_id)
        for index in range(1, self.tree.get_count()):
            wx_tree_id = self.tree.id2wx_tree_id(index)
            if expands.get(index, 0) == 1:
                self.drawer.tree.Expand(wx_tree_id)
            else:
                self.drawer.tree.Collapse(wx_tree_id)

    def expand_tree_save(self):
        """Save expand tree if set config settings."""
        expands = {}
        for index in range(1, self.tree.get_count()):
            wx_tree_id = self.tree.id2wx_tree_id(index)
            if self.drawer.tree.IsExpanded(wx_tree_id):
                expands[index] = 1
            else:
                expands[index] = 0
        self.notes.set_expands(expands)

    def __set_state_order_menuitem(self, state):
        """Set state menu items order."""
        self.drawer.order_up.Enable(state)
        self.drawer.order_down.Enable(state)
        self.drawer.order_parent_up.Enable(state)
        self.drawer.order_parent_down.Enable(state)

    def __set_state_sort_menuitem(self, state):
        """Set state menu items sort."""
        self.drawer.sort_titles.Enable(state)
        self.drawer.sort_childcount_up.Enable(state)
        self.drawer.sort_childcount_down.Enable(state)
        self.drawer.sort_state_up.Enable(state)
        self.drawer.sort_state_down.Enable(state)

    def __set_state_undo_menuitem(self):
        """Set menu items undo and redo."""
        if self.actions.isUndo():
            self.drawer.undo.Enable(True)
        else:
            self.drawer.undo.Enable(False)
        if self.actions.isRedo():
            self.drawer.redo.Enable(True)
        else:
            self.drawer.redo.Enable(False)

    def __set_state_del(self, state):
        """Set state to delete button and delete menu item."""
        self.drawer.but_del.Enable(state)
        self.drawer.del_note.Enable(state)

    def __disable_widgets(self):
        """Disable state for all widgets."""
        self.__set_state_del(False)
        self.drawer.data.SetValue('')
        self.drawer.data.Disable()
        self.drawer.readonly.Enable(False)
        self.drawer.state_check.Enable(False)
        self.drawer.states.Enable(False)

    def __tree_select(self):
        """Change select item in tree with program select."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        if index is None:
            self.__set_state_order_menuitem(False)
            self.__set_state_sort_menuitem(False)
            self.__disable_widgets()
            self.drawer.but_create.Disable()
            self.drawer.create_child.Enable(False)
            self.drawer.info_date.Enable(False)
        elif index == 0:
            self.__set_state_order_menuitem(False)
            self.__set_state_sort_menuitem(True)
            self.__disable_widgets()
            self.drawer.but_create.Enable(True)
            self.drawer.create_child.Enable(True)
            self.drawer.info_date.Enable(False)
        else:
            self.__set_state_order_menuitem(True)
            self.__set_state_sort_menuitem(True)
            self.drawer.info_date.Enable(True)
            self.drawer.data.Enable()
            data = self.notes.get_note(index)
            self.drawer.data.SetValue(data)
            self.drawer.readonly.Enable(True)
            readonly = self.notes.get_readonly(index)
            self.drawer.readonly.SetValue(readonly)
            self.__set_state_text_note(not readonly)
            self.__set_state_del(not readonly)
            self.drawer.state_check.Enable(True)
            state_check = self.notes.get_state_check(index)
            self.drawer.state_check.SetValue(state_check)
            self.drawer.states.Enable(state_check)
            self.__set_state(index)
            self.drawer.but_create.Enable(True)
            self.drawer.create_child.Enable(True)
        self.drawer.but_save.Disable()
        self.drawer.save_note.Enable(False)

    def tree_select(self, event):
        """Change select item in tree."""
        self.__tree_select()

    def tree_activated(self, event):
        """Activated edit label on tree item."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        readonly = self.drawer.readonly.GetValue()
        if readonly:
            if (self.config.readonly_password_check == "true") and self.__check_password():
                readonly = False
        if (index != 0) and (not readonly):
            self.drawer.tree.EditLabel(event.GetItem())

    def tree_end_edit(self, event):
        """Finish edit label item tree."""
        wx_tree_id = self.drawer.tree.GetSelection()
        index = self.tree.wx_tree_id2id(wx_tree_id)
        title = event.GetLabel()
        if title != '':
            self.actions.run(SaveTitle(index, title))
            self.__set_state_undo_menuitem()

    def text_change(self, event):
        """Change text controls note."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        if index != 0:
            self.drawer.but_save.Enable()
            self.drawer.save_note.Enable(True)

    def __set_state_text_note(self, state):
        """Set data text control note readonly state."""
        self.drawer.data.SetEditable(state)

    def __check_password(self):
        """Check state readonly password."""
        result = False
        dlg = PasswordEntryDialog(self.drawer, self.drawer.phrases.titles.password)
        if RetCode.OK == dlg.ShowModal():
            hashpass= hashlib.sha1(dlg.GetValue().encode("utf-8"))
            if hashpass.hexdigest() == self.config.readonly_password:
                result = True
        dlg.Destroy()
        return result

    def __change_readonly(self, index, readonly):
        """Change readonly attribute for widgets."""
        self.actions.run(SetReadonly(index, readonly))
        self.__set_state_text_note(not readonly)
        self.__set_state_del(not readonly)

    def change_readonly(self, event):
        """Change readonly attribute for note."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        readonly = self.drawer.readonly.GetValue()
        if readonly:
            self.__change_readonly(index, readonly)
        elif self.config.readonly_password_check != "true":
            self.__change_readonly(index, readonly)
        elif self.__check_password():
            self.__change_readonly(index, readonly)
        else:
            self.drawer.readonly.SetValue(True)
        self.__set_state_undo_menuitem()

    def change_state(self, event):
        """Change state attribute for note."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        state_check = self.drawer.state_check.GetValue()
        self.actions.run(SetStateCheck(index, state_check))
        self.drawer.states.Enable(state_check)
        self.__set_state_undo_menuitem()

    def choice_state(self, event):
        """Set state for note."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        state = self.drawer.states.GetString(self.drawer.states.GetSelection())
        self.actions.run(SetState(index, state))
        self.__set_state_undo_menuitem()

    def __set_state(self, index):
        """Set string in choice states."""
        state = self.notes.get_state(index)
        select = self.drawer.states.FindString(state)
        if select == self.drawer.get_not_found():
            select = 0
        self.drawer.states.SetSelection(select)

    def save(self, event):
        """Save data note in database."""
        wx_tree_id = self.drawer.tree.GetSelection()
        index = self.tree.wx_tree_id2id(wx_tree_id)
        data = self.drawer.data.GetValue()
        self.actions.run(SaveNote(index, data))
        self.__set_state_undo_menuitem()
        self.drawer.but_save.Disable()
        self.drawer.save_note.Enable(False)

    def delete(self, event):
        """Delete note from database."""
        if self.message.question(self.phrases.titles.warning, self.phrases.questions.del_note):
            index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
            parent_id = self.tree.get_parent_id(index)
            self.drawer.tree.DeleteAllItems()
            self.actions.run(DelNote(index))
            self.__set_state_undo_menuitem()
            self.tree.clear()
            self.init_tree()
            self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(parent_id))
            self.__tree_select()

    def create(self, event):
        """Create new note."""
        if event.GetId() == self.drawer.create_root.GetId():
            parent_id = 0
        else:
            parent_id = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        index = self.tree.get_count()
        parent_wx_tree_id = self.tree.id2wx_tree_id(parent_id)
        wx_tree_id = self.drawer.tree.AppendItem(parent_wx_tree_id, self.phrases.widgets.tree.new_note)
        self.drawer.tree.Expand(parent_wx_tree_id)
        self.drawer.tree.SelectItem(wx_tree_id)
        self.tree.add(index, parent_id, wx_tree_id)
        self.actions.run(CreateNote(index, self.drawer.tree.GetItemText(wx_tree_id)))
        self.__set_state_undo_menuitem()
        self.__tree_select()

    def insert(self, event):
        """Insert new note."""
        before_item = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        if before_item != 0:
            parent_id = self.tree.get_parent_id(before_item)
            index = self.tree.get_count()
            parent_wx_tree_id = self.tree.id2wx_tree_id(parent_id)
            wx_tree_id = self.drawer.tree.AppendItem(parent_wx_tree_id, self.phrases.widgets.tree.new_note)
            self.actions.run(InsertNote(index, before_item, self.drawer.tree.GetItemText(wx_tree_id)))
            self.__set_state_undo_menuitem()
            self.expand_tree_save()
            self.tree.clear()
            self.drawer.tree.DeleteAllItems()
            self.init_tree()
            parent_wx_tree_id = self.tree.id2wx_tree_id(parent_id)
            self.drawer.tree.Expand(parent_wx_tree_id)
            self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(index))
            self.__tree_select()

    def rollback(self, event):
        """Process menu commands undo and redo."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        parent = self.tree.get_parent_id(index)
        if event.GetId() == self.drawer.undo.GetId():
            self.actions.undo()
        elif event.GetId() == self.drawer.redo.GetId():
            self.actions.redo()
        self.__set_state_undo_menuitem()
        self.expand_tree_save()
        self.tree.clear()
        self.drawer.tree.DeleteAllItems()
        self.init_tree()
        select = self.tree.id2wx_tree_id(index)
        if select is None:
            select = self.tree.id2wx_tree_id(parent)
        self.drawer.tree.SelectItem(select)
        self.__tree_select()

    def order(self, event):
        """Order items."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        if event.GetId() == self.drawer.order_up.GetId():
            self.actions.run(OrderUp(index))
        elif event.GetId() == self.drawer.order_down.GetId():
            self.actions.run(OrderDown(index))
        elif event.GetId() == self.drawer.order_parent_up.GetId():
            self.actions.run(OrderParentUp(index))
        elif event.GetId() == self.drawer.order_parent_down.GetId():
            self.actions.run(OrderParentDown(index))
        self.__set_state_undo_menuitem()
        self.expand_tree_save()
        self.tree.clear()
        self.drawer.tree.DeleteAllItems()
        self.init_tree()
        self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(index))
        self.__tree_select()

    def sort(self, event):
        """Sort items."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        if event.GetId() == self.drawer.sort_titles.GetId():
            self.actions.run(SortTitle(index))
        elif event.GetId() == self.drawer.sort_childcount_up.GetId():
            self.actions.run(SortChildCountUp(index))
        elif event.GetId() == self.drawer.sort_childcount_down.GetId():
            self.actions.run(SortChildCountDown(index))
        elif event.GetId() == self.drawer.sort_state_up.GetId():
            self.actions.run(SortStateUp(index))
        elif event.GetId() == self.drawer.sort_state_down.GetId():
            self.actions.run(SortStateDown(index))
        self.__set_state_undo_menuitem()
        self.expand_tree_save()
        self.tree.clear()
        self.drawer.tree.DeleteAllItems()
        self.init_tree()
        self.drawer.tree.SelectItem(self.tree.id2wx_tree_id(index))
        self.__tree_select()

    def count(self, event):
        """Show information of count notes."""
        if event.GetId() == self.drawer.count_root.GetId():
            self.message.information(self.phrases.titles.info, self.phrases.info.count.root % self.tree.get_count_childs(0))
        elif event.GetId() == self.drawer.count_child.GetId():
            index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
            self.message.information(self.phrases.titles.info, self.phrases.info.count.child % self.tree.get_count_childs(index))
        else:
            self.message.information(self.phrases.titles.info, self.phrases.info.count.total % (self.tree.get_count() - 1))

    def info_date(self, event):
        """Show info of date create and date update note."""
        index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
        date_create, date_update = self.notes.get_date(index)
        create = self.phrases.info.date.create.format(date_create)
        update = self.phrases.info.date.update.format(date_update)
        self.message.information(self.phrases.titles.info, '\n'.join([create, update]))

    def options(self, event):
        """Run settings dialog."""
        if self.config.open_settings(self.drawer):
            self.drawer.states.Set(self.config.get_states(self.phrases.widgets.states))
            index = self.tree.wx_tree_id2id(self.drawer.tree.GetSelection())
            self.drawer.Layout()
            state = self.notes.get_state(index)
            self.drawer.states.SetSelection(self.drawer.states.FindString(state))
            self.message.information(self.phrases.titles.info, self.phrases.info.need_restart)
Beispiel #10
0
def parse(input, grammar, actions, gotos):
    # create a list of trees
    trees = []

    stack = []
    stack.append(0)
    while True:
        print("stack: ", end="")
        print(stack, end=" ")
        print("input: ", end="")

        print("stack: ", end="")
        print(stack, end=" ")
        print("input: ", end="")
        print(input, end=" ")
        state = stack[-1]
        token = input[0]
        action = actions[(state, token)]
        print("action: ", end="")
        print(action)

        if action is None:
            if state == 1 and input[0] != "program":
                print(errorMessage(7))
            if state == 2 and input[0] != "var":
                print(errorMessage(8))
            if state == 24 and input[0] != ":=":
                print(errorMessage(9))
            if state == 44 and input[0] != ("+" or "-"):
                print(errorMessage(9))
            if state == 30 and input[0] != ("integer" or "boolean"):
                print(errorMessage(10))
            if state == 34 and input[0] != ("identifier" or "integer_literal"
                                            or "true" or "false"):
                print(errorMessage(11))
            if state == 8 and input[0] != "$":
                print(errorMessage(6))
            return None

        # shift operation
        if action[0] == 's':
            input.pop(0)
            stack.append(token)
            if len(action) == 3:
                state = int(action[1] + action[2])
            else:
                state = int(action[1])
            stack.append(state)

            # create a new tree, set data to token, and append it to the list of trees
            tree = Tree()
            tree.data = token
            trees.append(tree)

        # reduce operation
        elif action[0] == 'r':
            if len(action) == 3:
                production = grammar[int(action[1] + action[2])]
            else:
                production = grammar[int(action[1])]
            lhs = getLHS(production)
            rhs = getRHS(production)
            for i in range(len(rhs) * 2):
                stack.pop()
            state = stack[-1]
            stack.append(lhs)
            stack.append(int(gotos[(state, lhs)]))

            # create a new tree and set data to lhs
            newTree = Tree()
            newTree.data = lhs

            # get "len(rhs)" trees from the right of the list of trees and add each of them as child of the new tree you created, preserving the left-right order
            for tree in trees[-len(rhs):]:
                newTree.add(tree)

            # remove "len(rhs)" trees from the right of the list of trees
            trees = trees[:-len(rhs)]

            # append the new tree to the list of trees
            trees.append(newTree)

        # not a shift or reduce operation, must be an "accept" operation
        else:
            production = grammar[0]
            lhs = getLHS(production)
            rhs = getRHS(production)

            # same as reduce but using the 1st rule of the grammar
            root = Tree()
            root.data = lhs
            for tree in trees:
                root.add(tree)

            # return the new tree
            return root