We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
prettytoml deletes unrelated elements when removing items
From #1507.

prettytoml has a bug in `table.py::TableElement.__delitem__` that it deletes a key when the line before it contains inline comment. A minimal example:

```python
import pipenv   # noqa

from prettytoml import lexer
from prettytoml.elements.atomic import AtomicElement
from prettytoml.elements.metadata import (
    WhitespaceElement, PunctuationElement, CommentElement,
)
from prettytoml.elements.table import TableElement


def test_table():

    initial_toml = """id=42 # My id\nage=14"""
    tokens = tuple(lexer.tokenize(initial_toml))
    table = TableElement([
        AtomicElement(tokens[0:1]),
        PunctuationElement(tokens[1:2]),
        AtomicElement(tokens[2:3]),
        WhitespaceElement(tokens[3:4]),
        CommentElement(tokens[4:6]),

        AtomicElement(tokens[6:7]),
        PunctuationElement(tokens[7:8]),
        AtomicElement(tokens[8:9]),
    ])

    assert set(table.items()) == {('id', 42), ('age', 14)}

    del table['id']
    assert set(table.items()) == {('age', 14)}
```

This test case would fail on the final assertion. `table` at this point would be empty, but it should not.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pipenv/patched/prettytoml/elements/table.py`
Content:
```
1 from prettytoml.elements import abstracttable, factory
2 from prettytoml.elements.errors import InvalidElementError
3 from prettytoml.elements.common import Element
4 from prettytoml.elements.metadata import CommentElement, NewlineElement, WhitespaceElement
5 from . import common
6 
7 
8 class TableElement(abstracttable.AbstractTable):
9     """
10     An Element containing an unnamed top-level table.
11 
12     Implements dict-like interface.
13 
14     Assumes input sub_elements are correct.
15 
16     Raises InvalidElementError on duplicate keys.
17     """
18 
19     def __init__(self, sub_elements):
20         abstracttable.AbstractTable.__init__(self, sub_elements)
21 
22         self._check_for_duplicate_keys()
23 
24     def _check_for_duplicate_keys(self):
25         if len(set(self.keys())) < len(self.keys()):
26             raise InvalidElementError('Duplicate keys found')
27 
28     def __setitem__(self, key, value):
29         if key in self:
30             self._update(key, value)
31         else:
32             self._insert(key, value)
33 
34     def _update(self, key, value):
35         _, value_i = self._find_key_and_value(key)
36         self._sub_elements[value_i] = value if isinstance(value, Element) else factory.create_element(value)
37 
38     def _find_insertion_index(self):
39         """
40         Returns the self.sub_elements index in which new entries should be inserted.
41         """
42 
43         non_metadata_elements = tuple(self._enumerate_non_metadata_sub_elements())
44 
45         if not non_metadata_elements:
46             return 0
47 
48         last_entry_i = non_metadata_elements[-1][0]
49         following_newline_i = self._find_following_line_terminator(last_entry_i)
50 
51         return following_newline_i + 1
52 
53     def _detect_indentation_size(self):
54         """
55         Detects the level of indentation used in this table.
56         """
57 
58         def lines():
59             # Returns a sequence of sequences of elements belonging to each line
60             start = 0
61             for i, element in enumerate(self.elements):
62                 if isinstance(element, (CommentElement, NewlineElement)):
63                     yield self.elements[start:i+1]
64                     start = i+1
65 
66         def indentation(line):
67             # Counts the number of whitespace tokens at the beginning of this line
68             try:
69                 first_non_whitespace_i = next(i for (i, e) in enumerate(line) if not isinstance(e, WhitespaceElement))
70                 return sum(space.length for space in line[:first_non_whitespace_i])
71             except StopIteration:
72                 return 0
73 
74         def is_empty_line(line):
75             return all(e.type == common.TYPE_METADATA for e in line)
76 
77         try:
78             return min(indentation(line) for line in lines() if len(line) > 1 and not is_empty_line(line))
79         except ValueError:  # Raised by ValueError when no matching lines found
80             return 0
81 
82     def _insert(self, key, value):
83 
84         value_element = value if isinstance(value, Element) else factory.create_element(value)
85 
86         indentation_size = self._detect_indentation_size()
87         indentation = [factory.create_whitespace_element(self._detect_indentation_size())] if indentation_size else []
88 
89         inserted_elements = indentation + [
90             factory.create_string_element(key, bare_allowed=True),
91             factory.create_whitespace_element(),
92             factory.create_operator_element('='),
93             factory.create_whitespace_element(),
94             value_element,
95             factory.create_newline_element(),
96         ]
97 
98         insertion_index = self._find_insertion_index()
99 
100         self._sub_elements = \
101             self.sub_elements[:insertion_index] + inserted_elements + self.sub_elements[insertion_index:]
102 
103     def __delitem__(self, key):
104         begin, _ = self._find_key_and_value(key)
105         preceding_newline = self._find_preceding_newline(begin)
106         if preceding_newline >= 0:
107             begin = preceding_newline
108         end = self._find_following_newline(begin)
109         if end < 0:
110             end = len(tuple(self._sub_elements))
111         self._sub_elements = self.sub_elements[:begin] + self.sub_elements[end:]
112 
113     def pop(self, key):
114         v = self[key]
115         del self[key]
116         return v
117 
118     def value(self):
119         return self
120 
121     def __str__(self):
122         return str(self.primitive_value)
123
```

Path: `pipenv/patched/prettytoml/elements/traversal/__init__.py`
Content:
```
1 from prettytoml import tokens
2 from prettytoml.elements import common
3 from prettytoml.elements.metadata import PunctuationElement, NewlineElement
4 from prettytoml.elements.traversal import predicates
5 
6 
7 class TraversalMixin:
8     """
9     A mix-in that provides convenient sub-element traversal to any class with
10     an `elements` member that is a sequence of Element instances
11     """
12 
13     def __find_following_element(self, index, predicate):
14         """
15         Finds and returns the index of element in self.elements that evaluates the given predicate to True
16         and whose index is higher than the given index, or returns -Infinity on failure.
17         """
18         return find_following(self.elements, predicate, index)
19 
20     def __find_preceding_element(self, index, predicate):
21         """
22         Finds and returns the index of the element in self.elements that evaluates the given predicate to True
23         and whose index is lower than the given index.
24         """
25         i = find_previous(self.elements, predicate, index)
26         if i == float('inf'):
27             return float('-inf')
28         return i
29 
30     def __must_find_following_element(self, predicate):
31         """
32         Finds and returns the index to the element in self.elements that evaluatest the predicate to True, or raises
33         an error.
34         """
35         i = self.__find_following_element(-1, predicate)
36         if i < 0:
37             raise RuntimeError('Could not find non-optional element')
38         return i
39 
40     def _enumerate_non_metadata_sub_elements(self):
41         """
42         Returns a sequence of of (index, sub_element) of the non-metadata sub-elements.
43         """
44         return ((i, element) for i, element in enumerate(self.elements) if element.type != common.TYPE_METADATA)
45 
46     def _find_preceding_comma(self, index):
47         """
48         Returns the index of the preceding comma element to the given index, or -Infinity.
49         """
50         return self.__find_preceding_element(index, predicates.op_comma)
51 
52     def _find_following_comma(self, index):
53         """
54         Returns the index of the following comma element after the given index, or -Infinity.
55         """
56         def predicate(element):
57             return isinstance(element, PunctuationElement) and element.token.type == tokens.TYPE_OP_COMMA
58         return self.__find_following_element(index, predicate)
59 
60     def _find_following_newline(self, index):
61         """
62         Returns the index of the following newline element after the given index, or -Infinity.
63         """
64         return self.__find_following_element(index, lambda e: isinstance(e, NewlineElement))
65 
66     def _find_following_comment(self, index):
67         """
68         Returns the index of the following comment element after the given index, or -Infinity.
69         """
70         return self.__find_following_element(index, predicates.comment)
71 
72     def _find_following_line_terminator(self, index):
73         """
74         Returns the index of the following comment or newline element after the given index, or -Infinity.
75         """
76         following_comment = self._find_following_comment(index)
77         following_newline = self._find_following_newline(index)
78 
79         if following_comment == float('-inf'):
80             return following_newline
81         if following_newline == float('inf'):
82             return following_comment
83 
84         if following_newline < following_comment:
85             return following_newline
86         else:
87             return following_comment
88 
89     def _find_preceding_newline(self, index):
90         """
91         Returns the index of the preceding newline element to the given index, or -Infinity.
92         """
93         return self.__find_preceding_element(index, predicates.newline)
94 
95     def _find_following_non_metadata(self, index):
96         """
97         Returns the index to the following non-metadata element after the given index, or -Infinity.
98         """
99         return self.__find_following_element(index, predicates.non_metadata)
100 
101     def _find_closing_square_bracket(self):
102         """
103         Returns the index to the closing square bracket, or raises an Error.
104         """
105 
106         return self.__must_find_following_element(predicates.closing_square_bracket)
107 
108     def _find_following_opening_square_bracket(self, index):
109         """
110         Returns the index to the opening square bracket, or -Infinity.
111         """
112         return self.__find_following_element(index, predicates.opening_square_bracket)
113 
114     def _find_following_closing_square_bracket(self, index):
115         """
116         Returns the index to the closing square bracket, or -Infinity.
117         """
118         return self.__find_following_element(index, predicates.closing_square_bracket)
119 
120     def _find_following_table(self, index):
121         """
122         Returns the index to the next TableElement after the specified index, or -Infinity.
123         """
124         return self.__find_following_element(index, predicates.table)
125 
126     def _find_preceding_table(self, index):
127         """
128         Returns the index to the preceding TableElement to the specified index, or -Infinity.
129         """
130         return self.__find_preceding_element(index,predicates.table)
131 
132     def _find_closing_curly_bracket(self):
133         """
134         Returns the index to the closing curly bracket, or raises an Error.
135         """
136         def predicate(element):
137             return isinstance(element, PunctuationElement) and element.token.type == tokens.TYPE_OP_CURLY_RIGHT_BRACKET
138         return self.__must_find_following_element(predicate)
139 
140     def _find_following_table_header(self, index):
141         """
142         Returns the index to the table header after the given element index, or -Infinity.
143         """
144         return self.__find_following_element(index, predicates.table_header)
145 
146 
147 def find_following(element_seq, predicate, index=None):
148     """
149     Finds and returns the index of the next element fulfilling the specified predicate after the specified
150     index, or -Infinity.
151 
152     Starts searching linearly from the start_from index.
153     """
154 
155     if isinstance(index, (int, float)) and index < 0:
156         index = None
157 
158     for i, element in tuple(enumerate(element_seq))[index+1 if index is not None else index:]:
159         if predicate(element):
160             return i
161     return float('-inf')
162 
163 
164 def find_previous(element_seq, predicate, index=None):
165     """
166     Finds and returns the index of the previous element fulfilling the specified predicate preceding to the specified
167     index, or Infinity.
168     """
169     if isinstance(index, (int, float)) and index >= len(element_seq):
170         index = None
171 
172     for i, element in reversed(tuple(enumerate(element_seq))[:index]):
173         if predicate(element):
174             return i
175     return float('inf')
176
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pipenv/patched/prettytoml/elements/table.py b/pipenv/patched/prettytoml/elements/table.py
--- a/pipenv/patched/prettytoml/elements/table.py
+++ b/pipenv/patched/prettytoml/elements/table.py
@@ -105,7 +105,7 @@
         preceding_newline = self._find_preceding_newline(begin)
         if preceding_newline >= 0:
             begin = preceding_newline
-        end = self._find_following_newline(begin)
+        end = self._find_following_line_terminator(begin)
         if end < 0:
             end = len(tuple(self._sub_elements))
         self._sub_elements = self.sub_elements[:begin] + self.sub_elements[end:]
diff --git a/pipenv/patched/prettytoml/elements/traversal/__init__.py b/pipenv/patched/prettytoml/elements/traversal/__init__.py
--- a/pipenv/patched/prettytoml/elements/traversal/__init__.py
+++ b/pipenv/patched/prettytoml/elements/traversal/__init__.py
@@ -76,9 +76,9 @@
         following_comment = self._find_following_comment(index)
         following_newline = self._find_following_newline(index)
 
-        if following_comment == float('-inf'):
+        if following_comment == float('inf'):
             return following_newline
-        if following_newline == float('inf'):
+        if following_newline == float('-inf'):
             return following_comment
 
         if following_newline < following_comment:

{"golden_diff": "diff --git a/pipenv/patched/prettytoml/elements/table.py b/pipenv/patched/prettytoml/elements/table.py\n--- a/pipenv/patched/prettytoml/elements/table.py\n+++ b/pipenv/patched/prettytoml/elements/table.py\n@@ -105,7 +105,7 @@\n         preceding_newline = self._find_preceding_newline(begin)\n         if preceding_newline >= 0:\n             begin = preceding_newline\n-        end = self._find_following_newline(begin)\n+        end = self._find_following_line_terminator(begin)\n         if end < 0:\n             end = len(tuple(self._sub_elements))\n         self._sub_elements = self.sub_elements[:begin] + self.sub_elements[end:]\ndiff --git a/pipenv/patched/prettytoml/elements/traversal/__init__.py b/pipenv/patched/prettytoml/elements/traversal/__init__.py\n--- a/pipenv/patched/prettytoml/elements/traversal/__init__.py\n+++ b/pipenv/patched/prettytoml/elements/traversal/__init__.py\n@@ -76,9 +76,9 @@\n         following_comment = self._find_following_comment(index)\n         following_newline = self._find_following_newline(index)\n \n-        if following_comment == float('-inf'):\n+        if following_comment == float('inf'):\n             return following_newline\n-        if following_newline == float('inf'):\n+        if following_newline == float('-inf'):\n             return following_comment\n \n         if following_newline < following_comment:\n", "issue": "prettytoml deletes unrelated elements when removing items\nFrom #1507.\r\n\r\nprettytoml has a bug in `table.py::TableElement.__delitem__` that it deletes a key when the line before it contains inline comment. A minimal example:\r\n\r\n```python\r\nimport pipenv   # noqa\r\n\r\nfrom prettytoml import lexer\r\nfrom prettytoml.elements.atomic import AtomicElement\r\nfrom prettytoml.elements.metadata import (\r\n    WhitespaceElement, PunctuationElement, CommentElement,\r\n)\r\nfrom prettytoml.elements.table import TableElement\r\n\r\n\r\ndef test_table():\r\n\r\n    initial_toml = \"\"\"id=42 # My id\\nage=14\"\"\"\r\n    tokens = tuple(lexer.tokenize(initial_toml))\r\n    table = TableElement([\r\n        AtomicElement(tokens[0:1]),\r\n        PunctuationElement(tokens[1:2]),\r\n        AtomicElement(tokens[2:3]),\r\n        WhitespaceElement(tokens[3:4]),\r\n        CommentElement(tokens[4:6]),\r\n\r\n        AtomicElement(tokens[6:7]),\r\n        PunctuationElement(tokens[7:8]),\r\n        AtomicElement(tokens[8:9]),\r\n    ])\r\n\r\n    assert set(table.items()) == {('id', 42), ('age', 14)}\r\n\r\n    del table['id']\r\n    assert set(table.items()) == {('age', 14)}\r\n```\r\n\r\nThis test case would fail on the final assertion. `table` at this point would be empty, but it should not.\n", "before_files": [{"content": "from prettytoml.elements import abstracttable, factory\nfrom prettytoml.elements.errors import InvalidElementError\nfrom prettytoml.elements.common import Element\nfrom prettytoml.elements.metadata import CommentElement, NewlineElement, WhitespaceElement\nfrom . import common\n\n\nclass TableElement(abstracttable.AbstractTable):\n    \"\"\"\n    An Element containing an unnamed top-level table.\n\n    Implements dict-like interface.\n\n    Assumes input sub_elements are correct.\n\n    Raises InvalidElementError on duplicate keys.\n    \"\"\"\n\n    def __init__(self, sub_elements):\n        abstracttable.AbstractTable.__init__(self, sub_elements)\n\n        self._check_for_duplicate_keys()\n\n    def _check_for_duplicate_keys(self):\n        if len(set(self.keys())) < len(self.keys()):\n            raise InvalidElementError('Duplicate keys found')\n\n    def __setitem__(self, key, value):\n        if key in self:\n            self._update(key, value)\n        else:\n            self._insert(key, value)\n\n    def _update(self, key, value):\n        _, value_i = self._find_key_and_value(key)\n        self._sub_elements[value_i] = value if isinstance(value, Element) else factory.create_element(value)\n\n    def _find_insertion_index(self):\n        \"\"\"\n        Returns the self.sub_elements index in which new entries should be inserted.\n        \"\"\"\n\n        non_metadata_elements = tuple(self._enumerate_non_metadata_sub_elements())\n\n        if not non_metadata_elements:\n            return 0\n\n        last_entry_i = non_metadata_elements[-1][0]\n        following_newline_i = self._find_following_line_terminator(last_entry_i)\n\n        return following_newline_i + 1\n\n    def _detect_indentation_size(self):\n        \"\"\"\n        Detects the level of indentation used in this table.\n        \"\"\"\n\n        def lines():\n            # Returns a sequence of sequences of elements belonging to each line\n            start = 0\n            for i, element in enumerate(self.elements):\n                if isinstance(element, (CommentElement, NewlineElement)):\n                    yield self.elements[start:i+1]\n                    start = i+1\n\n        def indentation(line):\n            # Counts the number of whitespace tokens at the beginning of this line\n            try:\n                first_non_whitespace_i = next(i for (i, e) in enumerate(line) if not isinstance(e, WhitespaceElement))\n                return sum(space.length for space in line[:first_non_whitespace_i])\n            except StopIteration:\n                return 0\n\n        def is_empty_line(line):\n            return all(e.type == common.TYPE_METADATA for e in line)\n\n        try:\n            return min(indentation(line) for line in lines() if len(line) > 1 and not is_empty_line(line))\n        except ValueError:  # Raised by ValueError when no matching lines found\n            return 0\n\n    def _insert(self, key, value):\n\n        value_element = value if isinstance(value, Element) else factory.create_element(value)\n\n        indentation_size = self._detect_indentation_size()\n        indentation = [factory.create_whitespace_element(self._detect_indentation_size())] if indentation_size else []\n\n        inserted_elements = indentation + [\n            factory.create_string_element(key, bare_allowed=True),\n            factory.create_whitespace_element(),\n            factory.create_operator_element('='),\n            factory.create_whitespace_element(),\n            value_element,\n            factory.create_newline_element(),\n        ]\n\n        insertion_index = self._find_insertion_index()\n\n        self._sub_elements = \\\n            self.sub_elements[:insertion_index] + inserted_elements + self.sub_elements[insertion_index:]\n\n    def __delitem__(self, key):\n        begin, _ = self._find_key_and_value(key)\n        preceding_newline = self._find_preceding_newline(begin)\n        if preceding_newline >= 0:\n            begin = preceding_newline\n        end = self._find_following_newline(begin)\n        if end < 0:\n            end = len(tuple(self._sub_elements))\n        self._sub_elements = self.sub_elements[:begin] + self.sub_elements[end:]\n\n    def pop(self, key):\n        v = self[key]\n        del self[key]\n        return v\n\n    def value(self):\n        return self\n\n    def __str__(self):\n        return str(self.primitive_value)\n", "path": "pipenv/patched/prettytoml/elements/table.py"}, {"content": "from prettytoml import tokens\nfrom prettytoml.elements import common\nfrom prettytoml.elements.metadata import PunctuationElement, NewlineElement\nfrom prettytoml.elements.traversal import predicates\n\n\nclass TraversalMixin:\n    \"\"\"\n    A mix-in that provides convenient sub-element traversal to any class with\n    an `elements` member that is a sequence of Element instances\n    \"\"\"\n\n    def __find_following_element(self, index, predicate):\n        \"\"\"\n        Finds and returns the index of element in self.elements that evaluates the given predicate to True\n        and whose index is higher than the given index, or returns -Infinity on failure.\n        \"\"\"\n        return find_following(self.elements, predicate, index)\n\n    def __find_preceding_element(self, index, predicate):\n        \"\"\"\n        Finds and returns the index of the element in self.elements that evaluates the given predicate to True\n        and whose index is lower than the given index.\n        \"\"\"\n        i = find_previous(self.elements, predicate, index)\n        if i == float('inf'):\n            return float('-inf')\n        return i\n\n    def __must_find_following_element(self, predicate):\n        \"\"\"\n        Finds and returns the index to the element in self.elements that evaluatest the predicate to True, or raises\n        an error.\n        \"\"\"\n        i = self.__find_following_element(-1, predicate)\n        if i < 0:\n            raise RuntimeError('Could not find non-optional element')\n        return i\n\n    def _enumerate_non_metadata_sub_elements(self):\n        \"\"\"\n        Returns a sequence of of (index, sub_element) of the non-metadata sub-elements.\n        \"\"\"\n        return ((i, element) for i, element in enumerate(self.elements) if element.type != common.TYPE_METADATA)\n\n    def _find_preceding_comma(self, index):\n        \"\"\"\n        Returns the index of the preceding comma element to the given index, or -Infinity.\n        \"\"\"\n        return self.__find_preceding_element(index, predicates.op_comma)\n\n    def _find_following_comma(self, index):\n        \"\"\"\n        Returns the index of the following comma element after the given index, or -Infinity.\n        \"\"\"\n        def predicate(element):\n            return isinstance(element, PunctuationElement) and element.token.type == tokens.TYPE_OP_COMMA\n        return self.__find_following_element(index, predicate)\n\n    def _find_following_newline(self, index):\n        \"\"\"\n        Returns the index of the following newline element after the given index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, lambda e: isinstance(e, NewlineElement))\n\n    def _find_following_comment(self, index):\n        \"\"\"\n        Returns the index of the following comment element after the given index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.comment)\n\n    def _find_following_line_terminator(self, index):\n        \"\"\"\n        Returns the index of the following comment or newline element after the given index, or -Infinity.\n        \"\"\"\n        following_comment = self._find_following_comment(index)\n        following_newline = self._find_following_newline(index)\n\n        if following_comment == float('-inf'):\n            return following_newline\n        if following_newline == float('inf'):\n            return following_comment\n\n        if following_newline < following_comment:\n            return following_newline\n        else:\n            return following_comment\n\n    def _find_preceding_newline(self, index):\n        \"\"\"\n        Returns the index of the preceding newline element to the given index, or -Infinity.\n        \"\"\"\n        return self.__find_preceding_element(index, predicates.newline)\n\n    def _find_following_non_metadata(self, index):\n        \"\"\"\n        Returns the index to the following non-metadata element after the given index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.non_metadata)\n\n    def _find_closing_square_bracket(self):\n        \"\"\"\n        Returns the index to the closing square bracket, or raises an Error.\n        \"\"\"\n\n        return self.__must_find_following_element(predicates.closing_square_bracket)\n\n    def _find_following_opening_square_bracket(self, index):\n        \"\"\"\n        Returns the index to the opening square bracket, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.opening_square_bracket)\n\n    def _find_following_closing_square_bracket(self, index):\n        \"\"\"\n        Returns the index to the closing square bracket, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.closing_square_bracket)\n\n    def _find_following_table(self, index):\n        \"\"\"\n        Returns the index to the next TableElement after the specified index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.table)\n\n    def _find_preceding_table(self, index):\n        \"\"\"\n        Returns the index to the preceding TableElement to the specified index, or -Infinity.\n        \"\"\"\n        return self.__find_preceding_element(index,predicates.table)\n\n    def _find_closing_curly_bracket(self):\n        \"\"\"\n        Returns the index to the closing curly bracket, or raises an Error.\n        \"\"\"\n        def predicate(element):\n            return isinstance(element, PunctuationElement) and element.token.type == tokens.TYPE_OP_CURLY_RIGHT_BRACKET\n        return self.__must_find_following_element(predicate)\n\n    def _find_following_table_header(self, index):\n        \"\"\"\n        Returns the index to the table header after the given element index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.table_header)\n\n\ndef find_following(element_seq, predicate, index=None):\n    \"\"\"\n    Finds and returns the index of the next element fulfilling the specified predicate after the specified\n    index, or -Infinity.\n\n    Starts searching linearly from the start_from index.\n    \"\"\"\n\n    if isinstance(index, (int, float)) and index < 0:\n        index = None\n\n    for i, element in tuple(enumerate(element_seq))[index+1 if index is not None else index:]:\n        if predicate(element):\n            return i\n    return float('-inf')\n\n\ndef find_previous(element_seq, predicate, index=None):\n    \"\"\"\n    Finds and returns the index of the previous element fulfilling the specified predicate preceding to the specified\n    index, or Infinity.\n    \"\"\"\n    if isinstance(index, (int, float)) and index >= len(element_seq):\n        index = None\n\n    for i, element in reversed(tuple(enumerate(element_seq))[:index]):\n        if predicate(element):\n            return i\n    return float('inf')\n", "path": "pipenv/patched/prettytoml/elements/traversal/__init__.py"}], "after_files": [{"content": "from prettytoml.elements import abstracttable, factory\nfrom prettytoml.elements.errors import InvalidElementError\nfrom prettytoml.elements.common import Element\nfrom prettytoml.elements.metadata import CommentElement, NewlineElement, WhitespaceElement\nfrom . import common\n\n\nclass TableElement(abstracttable.AbstractTable):\n    \"\"\"\n    An Element containing an unnamed top-level table.\n\n    Implements dict-like interface.\n\n    Assumes input sub_elements are correct.\n\n    Raises InvalidElementError on duplicate keys.\n    \"\"\"\n\n    def __init__(self, sub_elements):\n        abstracttable.AbstractTable.__init__(self, sub_elements)\n\n        self._check_for_duplicate_keys()\n\n    def _check_for_duplicate_keys(self):\n        if len(set(self.keys())) < len(self.keys()):\n            raise InvalidElementError('Duplicate keys found')\n\n    def __setitem__(self, key, value):\n        if key in self:\n            self._update(key, value)\n        else:\n            self._insert(key, value)\n\n    def _update(self, key, value):\n        _, value_i = self._find_key_and_value(key)\n        self._sub_elements[value_i] = value if isinstance(value, Element) else factory.create_element(value)\n\n    def _find_insertion_index(self):\n        \"\"\"\n        Returns the self.sub_elements index in which new entries should be inserted.\n        \"\"\"\n\n        non_metadata_elements = tuple(self._enumerate_non_metadata_sub_elements())\n\n        if not non_metadata_elements:\n            return 0\n\n        last_entry_i = non_metadata_elements[-1][0]\n        following_newline_i = self._find_following_line_terminator(last_entry_i)\n\n        return following_newline_i + 1\n\n    def _detect_indentation_size(self):\n        \"\"\"\n        Detects the level of indentation used in this table.\n        \"\"\"\n\n        def lines():\n            # Returns a sequence of sequences of elements belonging to each line\n            start = 0\n            for i, element in enumerate(self.elements):\n                if isinstance(element, (CommentElement, NewlineElement)):\n                    yield self.elements[start:i+1]\n                    start = i+1\n\n        def indentation(line):\n            # Counts the number of whitespace tokens at the beginning of this line\n            try:\n                first_non_whitespace_i = next(i for (i, e) in enumerate(line) if not isinstance(e, WhitespaceElement))\n                return sum(space.length for space in line[:first_non_whitespace_i])\n            except StopIteration:\n                return 0\n\n        def is_empty_line(line):\n            return all(e.type == common.TYPE_METADATA for e in line)\n\n        try:\n            return min(indentation(line) for line in lines() if len(line) > 1 and not is_empty_line(line))\n        except ValueError:  # Raised by ValueError when no matching lines found\n            return 0\n\n    def _insert(self, key, value):\n\n        value_element = value if isinstance(value, Element) else factory.create_element(value)\n\n        indentation_size = self._detect_indentation_size()\n        indentation = [factory.create_whitespace_element(self._detect_indentation_size())] if indentation_size else []\n\n        inserted_elements = indentation + [\n            factory.create_string_element(key, bare_allowed=True),\n            factory.create_whitespace_element(),\n            factory.create_operator_element('='),\n            factory.create_whitespace_element(),\n            value_element,\n            factory.create_newline_element(),\n        ]\n\n        insertion_index = self._find_insertion_index()\n\n        self._sub_elements = \\\n            self.sub_elements[:insertion_index] + inserted_elements + self.sub_elements[insertion_index:]\n\n    def __delitem__(self, key):\n        begin, _ = self._find_key_and_value(key)\n        preceding_newline = self._find_preceding_newline(begin)\n        if preceding_newline >= 0:\n            begin = preceding_newline\n        end = self._find_following_line_terminator(begin)\n        if end < 0:\n            end = len(tuple(self._sub_elements))\n        self._sub_elements = self.sub_elements[:begin] + self.sub_elements[end:]\n\n    def pop(self, key):\n        v = self[key]\n        del self[key]\n        return v\n\n    def value(self):\n        return self\n\n    def __str__(self):\n        return str(self.primitive_value)\n", "path": "pipenv/patched/prettytoml/elements/table.py"}, {"content": "from prettytoml import tokens\nfrom prettytoml.elements import common\nfrom prettytoml.elements.metadata import PunctuationElement, NewlineElement\nfrom prettytoml.elements.traversal import predicates\n\n\nclass TraversalMixin:\n    \"\"\"\n    A mix-in that provides convenient sub-element traversal to any class with\n    an `elements` member that is a sequence of Element instances\n    \"\"\"\n\n    def __find_following_element(self, index, predicate):\n        \"\"\"\n        Finds and returns the index of element in self.elements that evaluates the given predicate to True\n        and whose index is higher than the given index, or returns -Infinity on failure.\n        \"\"\"\n        return find_following(self.elements, predicate, index)\n\n    def __find_preceding_element(self, index, predicate):\n        \"\"\"\n        Finds and returns the index of the element in self.elements that evaluates the given predicate to True\n        and whose index is lower than the given index.\n        \"\"\"\n        i = find_previous(self.elements, predicate, index)\n        if i == float('inf'):\n            return float('-inf')\n        return i\n\n    def __must_find_following_element(self, predicate):\n        \"\"\"\n        Finds and returns the index to the element in self.elements that evaluatest the predicate to True, or raises\n        an error.\n        \"\"\"\n        i = self.__find_following_element(-1, predicate)\n        if i < 0:\n            raise RuntimeError('Could not find non-optional element')\n        return i\n\n    def _enumerate_non_metadata_sub_elements(self):\n        \"\"\"\n        Returns a sequence of of (index, sub_element) of the non-metadata sub-elements.\n        \"\"\"\n        return ((i, element) for i, element in enumerate(self.elements) if element.type != common.TYPE_METADATA)\n\n    def _find_preceding_comma(self, index):\n        \"\"\"\n        Returns the index of the preceding comma element to the given index, or -Infinity.\n        \"\"\"\n        return self.__find_preceding_element(index, predicates.op_comma)\n\n    def _find_following_comma(self, index):\n        \"\"\"\n        Returns the index of the following comma element after the given index, or -Infinity.\n        \"\"\"\n        def predicate(element):\n            return isinstance(element, PunctuationElement) and element.token.type == tokens.TYPE_OP_COMMA\n        return self.__find_following_element(index, predicate)\n\n    def _find_following_newline(self, index):\n        \"\"\"\n        Returns the index of the following newline element after the given index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, lambda e: isinstance(e, NewlineElement))\n\n    def _find_following_comment(self, index):\n        \"\"\"\n        Returns the index of the following comment element after the given index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.comment)\n\n    def _find_following_line_terminator(self, index):\n        \"\"\"\n        Returns the index of the following comment or newline element after the given index, or -Infinity.\n        \"\"\"\n        following_comment = self._find_following_comment(index)\n        following_newline = self._find_following_newline(index)\n\n        if following_comment == float('inf'):\n            return following_newline\n        if following_newline == float('-inf'):\n            return following_comment\n\n        if following_newline < following_comment:\n            return following_newline\n        else:\n            return following_comment\n\n    def _find_preceding_newline(self, index):\n        \"\"\"\n        Returns the index of the preceding newline element to the given index, or -Infinity.\n        \"\"\"\n        return self.__find_preceding_element(index, predicates.newline)\n\n    def _find_following_non_metadata(self, index):\n        \"\"\"\n        Returns the index to the following non-metadata element after the given index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.non_metadata)\n\n    def _find_closing_square_bracket(self):\n        \"\"\"\n        Returns the index to the closing square bracket, or raises an Error.\n        \"\"\"\n\n        return self.__must_find_following_element(predicates.closing_square_bracket)\n\n    def _find_following_opening_square_bracket(self, index):\n        \"\"\"\n        Returns the index to the opening square bracket, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.opening_square_bracket)\n\n    def _find_following_closing_square_bracket(self, index):\n        \"\"\"\n        Returns the index to the closing square bracket, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.closing_square_bracket)\n\n    def _find_following_table(self, index):\n        \"\"\"\n        Returns the index to the next TableElement after the specified index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.table)\n\n    def _find_preceding_table(self, index):\n        \"\"\"\n        Returns the index to the preceding TableElement to the specified index, or -Infinity.\n        \"\"\"\n        return self.__find_preceding_element(index,predicates.table)\n\n    def _find_closing_curly_bracket(self):\n        \"\"\"\n        Returns the index to the closing curly bracket, or raises an Error.\n        \"\"\"\n        def predicate(element):\n            return isinstance(element, PunctuationElement) and element.token.type == tokens.TYPE_OP_CURLY_RIGHT_BRACKET\n        return self.__must_find_following_element(predicate)\n\n    def _find_following_table_header(self, index):\n        \"\"\"\n        Returns the index to the table header after the given element index, or -Infinity.\n        \"\"\"\n        return self.__find_following_element(index, predicates.table_header)\n\n\ndef find_following(element_seq, predicate, index=None):\n    \"\"\"\n    Finds and returns the index of the next element fulfilling the specified predicate after the specified\n    index, or -Infinity.\n\n    Starts searching linearly from the start_from index.\n    \"\"\"\n\n    if isinstance(index, (int, float)) and index < 0:\n        index = None\n\n    for i, element in tuple(enumerate(element_seq))[index+1 if index is not None else index:]:\n        if predicate(element):\n            return i\n    return float('-inf')\n\n\ndef find_previous(element_seq, predicate, index=None):\n    \"\"\"\n    Finds and returns the index of the previous element fulfilling the specified predicate preceding to the specified\n    index, or Infinity.\n    \"\"\"\n    if isinstance(index, (int, float)) and index >= len(element_seq):\n        index = None\n\n    for i, element in reversed(tuple(enumerate(element_seq))[:index]):\n        if predicate(element):\n            return i\n    return float('inf')\n", "path": "pipenv/patched/prettytoml/elements/traversal/__init__.py"}]}