gurudesh/pytracebugs huggingface dataset:
# Buggy code
def make_filename(cls, entry):
    return entry.date.strftime(
        "%Y-%m-%d_{}.{}".format(cls._slugify(str(entry.title)), cls.extension)
    )


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "c:\python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\micah\.local\bin\jrnl.exe\__main__.py", line 7, in <module>
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\cli.py", line 47, in cli
return run(args)
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\jrnl.py", line 61, in run
search_mode(**kwargs)
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\jrnl.py", line 157, in search_mode
_display_search_results(**kwargs)
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\jrnl.py", line 302, in _display_search_results
print(exporter.export(journal, args.filename))
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\plugins\text_exporter.py", line 73, in export
return cls.write_files(journal, output)
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\plugins\text_exporter.py", line 49, in write_files
full_path = os.path.join(path, cls.make_filename(entry))
File "c:\users\micah\.local\pipx\venvs\jrnl\lib\site-packages\jrnl\plugins\text_exporter.py", line 41, in make_filename
"%Y-%m-%d_{}.{}".format(cls._slugify(str(entry.title)), cls.extension)
UnicodeEncodeError: 'locale' codec can't encode character '\u043f' in position 9: encoding error

# Fixed code
def make_filename(cls, entry):
    return entry.date.strftime("%Y-%m-%d") + "_{}.{}".format(
        cls._slugify(str(entry.title)), cls.extension
    )
# Buggy code
def _parse_text(self):
    raw_text = self.text
    lines = raw_text.splitlines()
    if lines[0].strip().endswith("*"):
        self.starred = True
        raw_text = lines[0].strip("\n *") + "\n" + "\n".join(lines[1:])
    self._title, self._body = split_title(raw_text)
    if self._tags is None:
        self._tags = list(self._parse_tags())


# Traceback (IndexError)
fbreunig@nighttrain:~ $ jrnl --short
Traceback (most recent call last):
File "/usr/local/bin/jrnl", line 8, in <module>
sys.exit(run())
File "/usr/local/lib/python3.7/site-packages/jrnl/cli.py", line 248, in run
print(journal.pprint(short=True))
File "/usr/local/lib/python3.7/site-packages/jrnl/Journal.py", line 148, in pprint
pp = sep.join([e.pprint(short=short) for e in self.entries])
File "/usr/local/lib/python3.7/site-packages/jrnl/Journal.py", line 148, in <listcomp>
pp = sep.join([e.pprint(short=short) for e in self.entries])
File "/usr/local/lib/python3.7/site-packages/jrnl/Entry.py", line 91, in pprint
title = date_str + " " + self.title.rstrip("\n ")
File "/usr/local/lib/python3.7/site-packages/jrnl/Entry.py", line 35, in title
self._parse_text()
File "/usr/local/lib/python3.7/site-packages/jrnl/Entry.py", line 25, in _parse_text
if lines[0].strip().endswith("*"):
IndexError: list index out of range

# Fixed code
def _parse_text(self):
    raw_text = self.text
    lines = raw_text.splitlines()
    if lines and lines[0].strip().endswith("*"):
        self.starred = True
        raw_text = lines[0].strip("\n *") + "\n" + "\n".join(lines[1:])
    self._title, self._body = split_title(raw_text)
    if self._tags is None:
        self._tags = list(self._parse_tags())
# Buggy code
def __exporter_from_file(template_file):
    """Create a template class from a file"""
    name = os.path.basename(template_file).replace(".template", "")
    template = Template.from_file(template_file)
    return type(
        "{}Exporter".format(name.title()),
        (GenericTemplateExporter,),
        {"names": [name], "extension": template.extension, "template": template},
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Util\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Util\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "d:\Projects\jrnl-nb\jrnl\__main__.py", line 4, in <module>
from . import cli
File "jrnl\cli.py", line 15, in <module>
from . import plugins
File "jrnl\plugins\__init__.py", line 13, in <module>
from .template_exporter import __all__ as template_exporters
File "jrnl\plugins\template_exporter.py", line 49, in <module>
__all__.append(__exporter_from_file(template_file))
File "jrnl\plugins\template_exporter.py", line 42, in __exporter_from_file
"template": template
TypeError: type() argument 1 must be string, not unicode

# Fixed code
def __exporter_from_file(template_file):
    """Create a template class from a file"""
    name = os.path.basename(template_file).replace(".template", "")
    template = Template.from_file(template_file)
    return type(
        str("{}Exporter".format(name.title())),
        (GenericTemplateExporter,),
        {"names": [name], "extension": template.extension, "template": template},
    )
# Buggy code
def getpass(prompt="Password: "):
    if not TEST:
        return gp.getpass(prompt)
    else:
        return py23_input(prompt)


# Traceback (TypeError)
Traceback (most recent call last):
File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "c:\python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\jrnl.exe\__main__.py", line 9, in <module>
File "c:\python27\lib\site-packages\jrnl\cli.py", line 257, in run
encrypt(journal, filename=args.encrypt)
File "c:\python27\lib\site-packages\jrnl\cli.py", line 76, in encrypt
password = util.getpass("Enter new password: ")
File "c:\python27\lib\site-packages\jrnl\util.py", line 31, in getpass
return gp.getpass(prompt)
File "c:\python27\lib\getpass.py", line 95, in win_getpass
msvcrt.putch(c)
TypeError: must be char, not unicode

# Fixed code
def getpass(prompt="Password: "):
    if not TEST:
        return gp.getpass(bytes(prompt))
    else:
        return py23_input(prompt)
# Buggy code
def export(journal, format, output=None):
    """Exports the journal to various formats.
    format should be one of json, txt, text, md, markdown.
    If output is None, returns a unicode representation of the output.
    If output is a directory, exports entries into individual files.
    Otherwise, exports to the given output file.
    """
    maps = {
        "json": to_json,
        "txt": to_txt,
        "text": to_txt,
        "md": to_md,
        "markdown": to_md,
    }
    if output and os.path.isdir(output):  # multiple files
        return write_files(journal, output, format)
    else:
        content = maps[format](journal)
        if output:
            try:
                with codecs.open(output, "w", "utf-8") as f:
                    f.write(content)
                return "[Journal exported to {0}]".format(output)
            except IOError as e:
                return "[ERROR: {0} {1}]".format(e.filename, e.strerror)
        else:
            return content


# Traceback (UnboundLocalError)
$ ls output
ls: cannot access output: No such file or directory
$ jrnl --export text -o output
[Journal exported to output]
$ rm output
$ mkdir output
$ jrnl --export text -o output
Traceback (most recent call last):
File "/home/michael/bin/jrnl", line 9, in <module>
load_entry_point('jrnl==1.8.1', 'console_scripts', 'jrnl')()
File "/home/michael/.local/lib/python2.7/site-packages/jrnl/cli.py", line 221, in run
print(util.py2encode(exporters.export(journal, args.export, args.output)))
File "/home/michael/.local/lib/python2.7/site-packages/jrnl/exporters.py", line 80, in export
return write_files(journal, output, format)
File "/home/michael/.local/lib/python2.7/site-packages/jrnl/exporters.py", line 106, in write_files
f.write(content)
UnboundLocalError: local variable 'content' referenced before assignment

# Fixed code
def export(journal, format, output=None):
    """Exports the journal to various formats.
    format should be one of json, txt, text, md, markdown.
    If output is None, returns a unicode representation of the output.
    If output is a directory, exports entries into individual files.
    Otherwise, exports to the given output file.
    """
    maps = {
        "json": to_json,
        "txt": to_txt,
        "text": to_txt,
        "md": to_md,
        "markdown": to_md,
    }
    if format not in maps:
        return "[ERROR: can't export to {0}. Valid options are 'md', 'txt', and 'json']".format(
            format
        )
    if output and os.path.isdir(output):  # multiple files
        return write_files(journal, output, format)
    else:
        content = maps[format](journal)
        if output:
            try:
                with codecs.open(output, "w", "utf-8") as f:
                    f.write(content)
                return "[Journal exported to {0}]".format(output)
            except IOError as e:
                return "[ERROR: {0} {1}]".format(e.filename, e.strerror)
        else:
            return content
# Buggy code
def write_files(journal, path, format):
    """Turns your journal into separate files for each entry.
    Format should be either json, md or txt."""
    make_filename = lambda entry: e.date.strftime(
        "%C-%m-%d_{0}.{1}".format(slugify(u(e.title)), format)
    )
    for e in journal.entries:
        full_path = os.path.join(path, make_filename(e))
        if format == "json":
            content = json.dumps(e.to_dict(), indent=2) + "\n"
        elif format == "md":
            content = e.to_md()
        elif format == "txt":
            content = u(e)
        with codecs.open(full_path, "w", "utf-8") as f:
            f.write(content)
    return "[Journal exported individual files in {0}]".format(path)


# Traceback (UnboundLocalError)
$ ls output
ls: cannot access output: No such file or directory
$ jrnl --export text -o output
[Journal exported to output]
$ rm output
$ mkdir output
$ jrnl --export text -o output
Traceback (most recent call last):
File "/home/michael/bin/jrnl", line 9, in <module>
load_entry_point('jrnl==1.8.1', 'console_scripts', 'jrnl')()
File "/home/michael/.local/lib/python2.7/site-packages/jrnl/cli.py", line 221, in run
print(util.py2encode(exporters.export(journal, args.export, args.output)))
File "/home/michael/.local/lib/python2.7/site-packages/jrnl/exporters.py", line 80, in export
return write_files(journal, output, format)
File "/home/michael/.local/lib/python2.7/site-packages/jrnl/exporters.py", line 106, in write_files
f.write(content)
UnboundLocalError: local variable 'content' referenced before assignment

# Fixed code
def write_files(journal, path, format):
    """Turns your journal into separate files for each entry.
    Format should be either json, md or txt."""
    make_filename = lambda entry: e.date.strftime(
        "%C-%m-%d_{0}.{1}".format(slugify(u(e.title)), format)
    )
    for e in journal.entries:
        full_path = os.path.join(path, make_filename(e))
        if format == "json":
            content = json.dumps(e.to_dict(), indent=2) + "\n"
        elif format in ("md", "markdown"):
            content = e.to_md()
        elif format in ("txt", "text"):
            content = u(e)
        with codecs.open(full_path, "w", "utf-8") as f:
            f.write(content)
    return "[Journal exported individual files in {0}]".format(path)
# Buggy code
def _decrypt(self, cipher):
    """Decrypts a cipher string using self.key as the key and the first 16 byte of the cipher as the IV"""
    if not cipher:
        return ""
    crypto = AES.new(self.key, AES.MODE_CBC, cipher[:16])
    plain = crypto.decrypt(cipher[16:])
    if plain[-1] != " ":  # Journals are always padded
        return None
    else:
        return plain


# Traceback (ValueError)
Traceback (most recent call last):
(...)
File "/Users/maebert/code/jrnl/jrnl.py", line 118, in _decrypt
plain = crypto.decrypt(cipher[16:])
ValueError: Input strings must be a multiple of 16 in length

# Fixed code
def _decrypt(self, cipher):
    """Decrypts a cipher string using self.key as the key and the first 16 byte of the cipher as the IV"""
    if not cipher:
        return ""
    crypto = AES.new(self.key, AES.MODE_CBC, cipher[:16])
    try:
        plain = crypto.decrypt(cipher[16:])
    except ValueError:
        print(
            "ERROR: Your journal file seems to be corrupted. You do have a backup, don't you?"
        )
        sys.exit(-1)
    if plain[-1] != " ":  # Journals are always padded
        return None
    else:
        return plain
# Buggy code
def indentBody(self, event=None):
    """
    The indent-region command indents each line of the selected body text.
    Unlike the always-indent-region command, this command inserts a tab
    (soft or hard) when there is no selected text.

    The @tabwidth directive in effect determines amount of indentation.
    """
    c, w = self, self.frame.body.wrapper
    # # 1739. Special case for a *plain* tab bound to indent-region.
    sel_1, sel_2 = w.getSelectionRange()
    if sel_1 == sel_2:
        char = getattr(event, "char", None)
        stroke = getattr(event, "stroke", None)
        if char == "\t" and stroke and stroke.isPlainKey():
            c.editCommands.selfInsertCommand(event)  # Handles undo.
            return
    c.alwaysIndentBody(event)


# Traceback (AttributeError)
Traceback (most recent call last):
File "...leo\core\leoCommands.py", line 2252, in doCommand
return_value = command_func(event)
File "...leo\core\leoGlobals.py", line 244, in commander_command_wrapper
method(event=event)
File "...\leo\commands\commanderEditCommands.py", line 714, in indentBody
c.editCommands.selfInsertCommand(event)  # Handles undo.
File "...leo\commands\editCommands.py", line 1678, in selfInsertCommand
oldYview = w.getYScrollPosition()
AttributeError: 'QHeadlineWrapper' object has no attribute 'getYScrollPosition'

# Fixed code
def indentBody(self, event=None):
    """
    The indent-region command indents each line of the selected body text.
    Unlike the always-indent-region command, this command inserts a tab
    (soft or hard) when there is no selected text.

    The @tabwidth directive in effect determines amount of indentation.
    """
    c, event_w, w = self, event and event.w, self.frame.body.wrapper
    # #1801: Don't rely on bindings to ensure that we are editing the body.
    if event_w != w:
        c.insertCharFromEvent(event)
        return
    # # 1739. Special case for a *plain* tab bound to indent-region.
    sel_1, sel_2 = w.getSelectionRange()
    if sel_1 == sel_2:
        char = getattr(event, "char", None)
        stroke = getattr(event, "stroke", None)
        if char == "\t" and stroke and stroke.isPlainKey():
            c.editCommands.selfInsertCommand(event)  # Handles undo.
            return
    c.alwaysIndentBody(event)
# Buggy code
def insertNewLineAndTab(self, event):
    """Insert a newline and tab at the cursor."""
    trace = "keys" in g.app.debug
    c, k = self.c, self.c.k
    p = c.p
    w = self.editWidget(event)
    if not w:
        return
    if not g.isTextWrapper(w):
        return
    name = c.widget_name(w)
    if name.startswith("head"):
        return
    if trace:
        g.trace("(newline-and-indent)")
    self.beginCommand(w, undoType="insert-newline-and-indent")
    oldSel = w.getSelectionRange()
    self.insertNewlineHelper(w=w, oldSel=oldSel, undoType=None)
    self.updateTab(p, w, smartTab=False)
    k.setInputState("insert")
    k.showStateAndMode()
    self.endCommand(changed=True, setLabel=False)


# Traceback (AttributeError)
Traceback (most recent call last):
File "...leo\core\leoCommands.py", line 2252, in doCommand
return_value = command_func(event)
File "...leo\core\leoGlobals.py", line 244, in commander_command_wrapper
method(event=event)
File "...\leo\commands\commanderEditCommands.py", line 714, in indentBody
c.editCommands.selfInsertCommand(event)  # Handles undo.
File "...leo\commands\editCommands.py", line 1678, in selfInsertCommand
oldYview = w.getYScrollPosition()
AttributeError: 'QHeadlineWrapper' object has no attribute 'getYScrollPosition'

# Fixed code
def insertNewLineAndTab(self, event):
    """Insert a newline and tab at the cursor."""
    trace = "keys" in g.app.debug
    c, k = self.c, self.c.k
    p = c.p
    w = self.editWidget(event)
    if not w:
        return
    if not g.isTextWrapper(w):
        return
    name = c.widget_name(w)
    if name.startswith("head"):
        return
    if trace:
        g.trace("(newline-and-indent)")
    self.beginCommand(w, undoType="insert-newline-and-indent")
    oldSel = w.getSelectionRange()
    self.insertNewlineHelper(w=w, oldSel=oldSel, undoType=None)
    self.updateTab(event, p, w, smartTab=False)
    k.setInputState("insert")
    k.showStateAndMode()
    self.endCommand(changed=True, setLabel=False)
# Buggy code
def updateTab(self, p, w, smartTab=True):
    """
    A helper for selfInsertCommand.

    Add spaces equivalent to a tab.
    """
    c = self.c
    i, j = w.getSelectionRange()
    # Returns insert point if no selection, with i <= j.
    if i != j:
        c.indentBody()
        return
    tab_width = c.getTabWidth(p)
    # Get the preceeding characters.
    s = w.getAllText()
    start, end = g.getLine(s, i)
    after = s[i:end]
    if after.endswith("\n"):
        after = after[:-1]
    # Only do smart tab at the start of a blank line.
    doSmartTab = smartTab and c.smart_tab and i == start
    # Truly at the start of the line.
    # and not after # Nothing *at all* after the cursor.
    if doSmartTab:
        self.updateAutoIndent(p, w)
        # Add a tab if otherwise nothing would happen.
        if s == w.getAllText():
            self.doPlainTab(s, i, tab_width, w)
    else:
        self.doPlainTab(s, i, tab_width, w)


# Traceback (AttributeError)
Traceback (most recent call last):
File "...leo\core\leoCommands.py", line 2252, in doCommand
return_value = command_func(event)
File "...leo\core\leoGlobals.py", line 244, in commander_command_wrapper
method(event=event)
File "...\leo\commands\commanderEditCommands.py", line 714, in indentBody
c.editCommands.selfInsertCommand(event)  # Handles undo.
File "...leo\commands\editCommands.py", line 1678, in selfInsertCommand
oldYview = w.getYScrollPosition()
AttributeError: 'QHeadlineWrapper' object has no attribute 'getYScrollPosition'

# Fixed code
def updateTab(self, event, p, w, smartTab=True):
    """
    A helper for selfInsertCommand.

    Add spaces equivalent to a tab.
    """
    c = self.c
    i, j = w.getSelectionRange()
    # Returns insert point if no selection, with i <= j.
    if i != j:
        c.indentBody(event)
        return
    tab_width = c.getTabWidth(p)
    # Get the preceeding characters.
    s = w.getAllText()
    start, end = g.getLine(s, i)
    after = s[i:end]
    if after.endswith("\n"):
        after = after[:-1]
    # Only do smart tab at the start of a blank line.
    doSmartTab = smartTab and c.smart_tab and i == start
    # Truly at the start of the line.
    # and not after # Nothing *at all* after the cursor.
    if doSmartTab:
        self.updateAutoIndent(p, w)
        # Add a tab if otherwise nothing would happen.
        if s == w.getAllText():
            self.doPlainTab(s, i, tab_width, w)
    else:
        self.doPlainTab(s, i, tab_width, w)
# Buggy code
def show_all_tags(self):
    """Show all tags, organized by node."""
    c, tc = self.c, self
    d = {}
    for p in c.all_unique_positions():
        u = p.v.u
        tags = set(u.get(tc.TAG_LIST_KEY, set([])))
        for tag in tags:
            aList = d.get(tag, [])
            aList.append(p.h)
            d[tag] = aList
    # Print all tags.
    for key in sorted(d):
        aList = d.get(key)
        for h in sorted(aList):
            print(f"{key:>8} {h}")


# Traceback (AttributeError)
Traceback (most recent call last):
File "...leo\core\leoCommands.py", line 2252, in doCommand
return_value = command_func(event)
File "...leo\core\leoGlobals.py", line 244, in commander_command_wrapper
method(event=event)
File "...\leo\commands\commanderEditCommands.py", line 714, in indentBody
c.editCommands.selfInsertCommand(event)  # Handles undo.
File "...leo\commands\editCommands.py", line 1678, in selfInsertCommand
oldYview = w.getYScrollPosition()
AttributeError: 'QHeadlineWrapper' object has no attribute 'getYScrollPosition'

# Fixed code
def show_all_tags(self):
    """Show all tags, organized by node."""
    c, tc = self.c, self
    d = {}
    for p in c.all_unique_positions():
        u = p.v.u
        tags = set(u.get(tc.TAG_LIST_KEY, set([])))
        for tag in tags:
            aList = d.get(tag, [])
            aList.append(p.h)
            d[tag] = aList
    # Print all tags.
    if d:
        for key in sorted(d):
            aList = d.get(key)
            for h in sorted(aList):
                print(f"{key:>8} {h}")
    else:
        print(f"no tags in {c.shortFileName()}")
# Buggy code
def openFileHelper(self, fileName):
    """Open a file, reporting all exceptions."""
    at = self
    s = None
    try:
        with open(fileName, "rb") as f:
            s = f.read()
    except IOError:
        at.error(f"can not open {fileName}")
    except Exception:
        at.error(f"Exception reading {fileName}")
        g.es_exception()
    return s


# Traceback (AttributeError)
readFileIntoString not a file: C:/Users/edreamleo/RustProjects/hello_cargo/src

Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\plugins\contextmenu.py", line 332, in refresh_rclick_cb
c.refreshFromDisk()
File "c:\leo.repo\leo-editor\leo\commands\commanderFileCommands.py", line 305, in refreshFromDisk
p = at.readOneAtAutoNode(fn, p)
File "c:\leo.repo\leo-editor\leo\core\leoAtFile.py", line 597, in readOneAtAutoNode
c.persistenceController.update_after_read_foreign_file(p)
File "c:\leo.repo\leo-editor\leo\core\leoPersistence.py", line 126, in update_after_read_foreign_file
if not self.is_foreign_file(root):
File "c:\leo.repo\leo-editor\leo\core\leoPersistence.py", line 461, in is_foreign_file
self.is_at_auto_node(p) or
File "c:\leo.repo\leo-editor\leo\core\leoPersistence.py", line 448, in is_at_auto_node
return p.isAtAutoNode()
AttributeError: 'NoneType' object has no attribute 'isAtAutoNode'

# Fixed code
def openFileHelper(self, fileName):
    """Open a file, reporting all exceptions."""
    at = self
    s = ""
    try:
        with open(fileName, "rb") as f:
            s = f.read()
    except IOError:
        at.error(f"can not open {fileName}")
    except Exception:
        at.error(f"Exception reading {fileName}")
        g.es_exception()
    return s
# Buggy code
def update_after_read_foreign_file(self, root):
    """Restore gnx's, uAs and clone links using @gnxs nodes and @uas trees."""
    self.at_persistence = self.find_at_persistence_node()
    if not self.at_persistence:
        return
    if not self.is_foreign_file(root):
        return
    # Create clone links from @gnxs node
    at_gnxs = self.has_at_gnxs_node(root)
    if at_gnxs:
        self.restore_gnxs(at_gnxs, root)
    # Create uas from @uas tree.
    at_uas = self.has_at_uas_node(root)
    if at_uas:
        self.create_uas(at_uas, root)


# Traceback (AttributeError)
readFileIntoString not a file: C:/Users/edreamleo/RustProjects/hello_cargo/src

Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\plugins\contextmenu.py", line 332, in refresh_rclick_cb
c.refreshFromDisk()
File "c:\leo.repo\leo-editor\leo\commands\commanderFileCommands.py", line 305, in refreshFromDisk
p = at.readOneAtAutoNode(fn, p)
File "c:\leo.repo\leo-editor\leo\core\leoAtFile.py", line 597, in readOneAtAutoNode
c.persistenceController.update_after_read_foreign_file(p)
File "c:\leo.repo\leo-editor\leo\core\leoPersistence.py", line 126, in update_after_read_foreign_file
if not self.is_foreign_file(root):
File "c:\leo.repo\leo-editor\leo\core\leoPersistence.py", line 461, in is_foreign_file
self.is_at_auto_node(p) or
File "c:\leo.repo\leo-editor\leo\core\leoPersistence.py", line 448, in is_at_auto_node
return p.isAtAutoNode()
AttributeError: 'NoneType' object has no attribute 'isAtAutoNode'

# Fixed code
def update_after_read_foreign_file(self, root):
    """Restore gnx's, uAs and clone links using @gnxs nodes and @uas trees."""
    self.at_persistence = self.find_at_persistence_node()
    if not self.at_persistence:
        return
    if not root:
        return
    if not self.is_foreign_file(root):
        return
    # Create clone links from @gnxs node
    at_gnxs = self.has_at_gnxs_node(root)
    if at_gnxs:
        self.restore_gnxs(at_gnxs, root)
    # Create uas from @uas tree.
    at_uas = self.has_at_uas_node(root)
    if at_uas:
        self.create_uas(at_uas, root)
# Buggy code
def readFile(self, path):
    """Read the file, change splitter ratiors, and return its hidden vnode."""
    with open(path, "rb") as f:
        s = f.read()
    v, g_element = self.readWithElementTree(path, s)
    self.scanGlobals(g_element)
    # Fix #1047: only this method changes splitter sizes.
    #
    # Fix bug #1111: ensure that all outlines have at least one node.
    if not v.children:
        new_vnode = leoNodes.VNode(context=self.c)
        new_vnode.h = "newHeadline"
        v.children = [new_vnode]
    return v


# Traceback (TypeError)
bad .leo file: WORK.leo
g.toUnicode: unexpected argument of type ParseError
toUnicode openLeoFile,getLeoFile,readFile,readWithElementTree


Traceback (most recent call last):

File "E:\git\leo\leo\core\leoCommands.py", line 2278, in executeAnyCommand
return command(event)

File "E:\git\leo\leo\core\leoGlobals.py", line 240, in commander_command_wrapper
method(event=event)

File "E:\git\leo\leo\commands\commanderFileCommands.py", line 261, in open_outline
open_completer(c, closeFlag, fileName)

File "E:\git\leo\leo\commands\commanderFileCommands.py", line 204, in open_completer
c2 = g.openWithFileName(fileName, old_c=c)

File "E:\git\leo\leo\core\leoGlobals.py", line 3920, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)

File "E:\git\leo\leo\core\leoApp.py", line 3288, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)

File "E:\git\leo\leo\core\leoApp.py", line 2241, in getPreviousSettings
c = lm.openSettingsFile(fn)

File "E:\git\leo\leo\core\leoApp.py", line 2412, in openSettingsFile
ok = c.fileCommands.openLeoFile(theFile, fn,

File "E:\git\leo\leo\core\leoFileCommands.py", line 692, in openLeoFile
ok, ratio = self.getLeoFile(

File "E:\git\leo\leo\core\leoFileCommands.py", line 559, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)

File "E:\git\leo\leo\core\leoFileCommands.py", line 60, in readFile
v, g_element = self.readWithElementTree(path, s)

TypeError: cannot unpack non-iterable NoneType object

Traceback (most recent call last):
File "E:\git\leo\leo\plugins\qt_frame.py", line 1638, in closeEvent
g.app.gui.close_event(event)
AttributeError: 'NullGui' object has no attribute 'close_event'

# Fixed code
def readFile(self, path):
    """Read the file, change splitter ratiors, and return its hidden vnode."""
    with open(path, "rb") as f:
        s = f.read()
    v, g_element = self.readWithElementTree(path, s)
    if not v:  # #1510.
        return None
    self.scanGlobals(g_element)
    # Fix #1047: only this method changes splitter sizes.
    #
    # Fix bug #1111: ensure that all outlines have at least one node.
    if not v.children:
        new_vnode = leoNodes.VNode(context=self.c)
        new_vnode.h = "newHeadline"
        v.children = [new_vnode]
    return v
# Buggy code
def readFileFromClipboard(self, s):
    """
    Recreate a file from a string s, and return its hidden vnode.

    Unlike readFile above, this does not affect splitter sizes.
    """
    v, g_element = self.readWithElementTree(path=None, s=s)
    #
    # Fix bug #1111: ensure that all outlines have at least one node.
    if not v.children:
        new_vnode = leoNodes.VNode(context=self.c)
        new_vnode.h = "newHeadline"
        v.children = [new_vnode]
    return v


# Traceback (TypeError)
bad .leo file: WORK.leo
g.toUnicode: unexpected argument of type ParseError
toUnicode openLeoFile,getLeoFile,readFile,readWithElementTree


Traceback (most recent call last):

File "E:\git\leo\leo\core\leoCommands.py", line 2278, in executeAnyCommand
return command(event)

File "E:\git\leo\leo\core\leoGlobals.py", line 240, in commander_command_wrapper
method(event=event)

File "E:\git\leo\leo\commands\commanderFileCommands.py", line 261, in open_outline
open_completer(c, closeFlag, fileName)

File "E:\git\leo\leo\commands\commanderFileCommands.py", line 204, in open_completer
c2 = g.openWithFileName(fileName, old_c=c)

File "E:\git\leo\leo\core\leoGlobals.py", line 3920, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)

File "E:\git\leo\leo\core\leoApp.py", line 3288, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)

File "E:\git\leo\leo\core\leoApp.py", line 2241, in getPreviousSettings
c = lm.openSettingsFile(fn)

File "E:\git\leo\leo\core\leoApp.py", line 2412, in openSettingsFile
ok = c.fileCommands.openLeoFile(theFile, fn,

File "E:\git\leo\leo\core\leoFileCommands.py", line 692, in openLeoFile
ok, ratio = self.getLeoFile(

File "E:\git\leo\leo\core\leoFileCommands.py", line 559, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)

File "E:\git\leo\leo\core\leoFileCommands.py", line 60, in readFile
v, g_element = self.readWithElementTree(path, s)

TypeError: cannot unpack non-iterable NoneType object

Traceback (most recent call last):
File "E:\git\leo\leo\plugins\qt_frame.py", line 1638, in closeEvent
g.app.gui.close_event(event)
AttributeError: 'NullGui' object has no attribute 'close_event'

# Fixed code
def readFileFromClipboard(self, s):
    """
    Recreate a file from a string s, and return its hidden vnode.

    Unlike readFile above, this does not affect splitter sizes.
    """
    v, g_element = self.readWithElementTree(path=None, s=s)
    if not v:  # #1510.
        return None
    #
    # Fix bug #1111: ensure that all outlines have at least one node.
    if not v.children:
        new_vnode = leoNodes.VNode(context=self.c)
        new_vnode.h = "newHeadline"
        v.children = [new_vnode]
    return v
# Buggy code
def writeAsisNode(self, p):
    """Write the p's node to an @asis file."""
    at = self
    # Write the headline only if it starts with '@@'.
    s = p.h
    if g.match(s, 0, "@@"):
        s = s[2:]
        if s:
            at.outputFile.write(s)
    # Write the body.
    s = p.b
    if s:
        s = g.toEncodedString(s, at.encoding, reportErrors=True)
        at.outputStringWithLineEndings(s)


# Traceback (AttributeError)
exception writing: C:/Users/jrhut/Documents/Active/My Maps/_foo.txt
Traceback (most recent call last):
File "C:\cygwin64\home\jrhut\src\leo-editor\leo-editor\leo\core\leoAtFile.py", line 1291, in asisWrite
at.writeAsisNode(p)
File "C:\cygwin64\home\jrhut\src\leo-editor\leo-editor\leo\core\leoAtFile.py", line 1307, in writeAsisNode
at.outputFile.write(s)
AttributeError: 'AtFile' object has no attribute 'outputFile'

# Fixed code
def writeAsisNode(self, p):
    """Write the p's node to an @asis file."""
    at = self

    def put(s):
        """Append s to self.output_list."""
        # #1480: Avoid calling at.os().
        s = g.toUnicode(s, at.encoding, reportErrors=True)
        at.outputList.append(s)

    # Write the headline only if it starts with '@@'.
    s = p.h
    if g.match(s, 0, "@@"):
        s = s[2:]
        if s:
            put("\n")  # Experimental.
            put(s)
            put("\n")
    # Write the body.
    s = p.b
    if s:
        put(s)
# Buggy code
def os(self, s):
    """
    Write a string to the output file or stream.

    All output produced by leoAtFile module goes here.
    """
    at = self
    if s.startswith(self.underindentEscapeString):
        try:
            junk, s = at.parseUnderindentTag(s)
        except Exception:
            at.exception("exception writing:" + s)
            return
    s = g.toUnicode(s, at.encoding)
    at.outputList.append(s)


# Traceback (AttributeError)
exception writing: C:/Users/jrhut/Documents/Active/My Maps/_foo.txt
Traceback (most recent call last):
File "C:\cygwin64\home\jrhut\src\leo-editor\leo-editor\leo\core\leoAtFile.py", line 1291, in asisWrite
at.writeAsisNode(p)
File "C:\cygwin64\home\jrhut\src\leo-editor\leo-editor\leo\core\leoAtFile.py", line 1307, in writeAsisNode
at.outputFile.write(s)
AttributeError: 'AtFile' object has no attribute 'outputFile'

# Fixed code
def os(self, s):
    """
    Append a string to at.outputList.

    All output produced by leoAtFile module goes here.
    """
    at = self
    if s.startswith(self.underindentEscapeString):
        try:
            junk, s = at.parseUnderindentTag(s)
        except Exception:
            at.exception("exception writing:" + s)
            return
    s = g.toUnicode(s, at.encoding)
    at.outputList.append(s)
# Buggy code
def bridge(self):
    import leo.core.leoBridge as leoBridge

    return leoBridge.controller(
        gui="nullGui",
        loadPlugins=False,
        readSettings=False,
        silent=False,
        verbose=False,
    )


# Traceback (FileNotFoundError)
exception writing: /tmp/pytest-of-btheado/pytest-85/test_save_after_external_file_0/1_renamed
Traceback (most recent call last):

File "/home/btheado/src/leo-editor/leo/core/leoAtFile.py", line 1323, in write
if not fileName or not at.precheck(fileName, root):

File "/home/btheado/src/leo-editor/leo/core/leoAtFile.py", line 2524, in precheck
if not at.shouldPromptForDangerousWrite(fileName, root):

File "/home/btheado/src/leo-editor/leo/core/leoAtFile.py", line 3085, in shouldPromptForDangerousWrite
if os.path.samefile(k, fn) and p.h in d.get(k, set()):

File "/usr/lib/python3.7/genericpath.py", line 100, in samefile
s1 = os.stat(f1)

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pytest-of-btheado/pytest-85/test_save_after_external_file_0/1'

# Fixed code
def bridge(self):
    """Return an instance of Leo's bridge."""
    import leo.core.leoBridge as leoBridge

    return leoBridge.controller(
        gui="nullGui",
        loadPlugins=False,
        readSettings=False,
        silent=True,
        verbose=False,
    )
# Buggy code
def create(self, fn):
    """Create the given file with empty contents."""
    theDir = g.os_path_dirname(fn)
    g.makeAllNonExistentDirectories(theDir, c=self.c, force=True, verbose=True)
    # Make the directories as needed.
    try:
        f = open(fn, mode="wb")
        f.close()
        g.note(f"created: {fn}")
    except IOError:
        g.error(f"can not create: {fn}")
    except Exception:
        g.error(f"unexpected error creating: {fn}")
        g.es_exception()


# Traceback (TypeError)
Leo Log Window
Leo 6.1-final, master branch, build b80e074204
2019-11-08 12:36:03 -0600
Python 3.8.0, PyQt version 5.13.0
Windows 10 AMD64 (build 10.0.17763) SP0
created directory: C:/Users/C050536/.leo
leoID='metaperl'
.leoID.txt created in C:/Users/C050536/.leo
current dir: C:/bin/leo-editor
load dir: C:/bin/leo-editor/leo/core
global config dir: C:/bin/leo-editor/leo/config
home dir: C:/Users/C050536
reading settings in C:/bin/leo-editor/leo/config/leoSettings.leo
Do spellpyx.txt file found
unexpected error creating: None
Traceback (most recent call last):

File "C:\bin\leo-editor\leo\commands\spellCommands.py", line 56, in create
f = open(fn, mode='wb')

TypeError: expected str, bytes or os.PathLike object, not NoneType

reading settings in C:/bin/leo-editor/leo/doc/CheatSheet.leo

# Fixed code
def create(self, fn):
    """Create the given file with empty contents."""
    theDir = g.os_path_dirname(fn)
    # Make the directories as needed.
    ok = g.makeAllNonExistentDirectories(theDir, c=self.c, force=True, verbose=True)
    # #1453: Don't assume the directory exists.
    if not ok:
        g.error(f"did not create: {theDir}")
        return
    try:
        f = open(fn, mode="wb")
        f.close()
        g.note(f"created: {fn}")
    except IOError:
        g.error(f"can not create: {fn}")
    except Exception:
        g.error(f"unexpected error creating: {fn}")
        g.es_exception()
# Buggy code
def computeHomeLeoDir(self):
    # lm = self
    homeLeoDir = g.os_path_finalize_join(g.app.homeDir, ".leo")
    if not g.os_path_exists(homeLeoDir):
        g.makeAllNonExistentDirectories(homeLeoDir, force=True)
    return homeLeoDir


# Traceback (TypeError)
Leo Log Window
Leo 6.1-final, master branch, build b80e074204
2019-11-08 12:36:03 -0600
Python 3.8.0, PyQt version 5.13.0
Windows 10 AMD64 (build 10.0.17763) SP0
created directory: C:/Users/C050536/.leo
leoID='metaperl'
.leoID.txt created in C:/Users/C050536/.leo
current dir: C:/bin/leo-editor
load dir: C:/bin/leo-editor/leo/core
global config dir: C:/bin/leo-editor/leo/config
home dir: C:/Users/C050536
reading settings in C:/bin/leo-editor/leo/config/leoSettings.leo
Do spellpyx.txt file found
unexpected error creating: None
Traceback (most recent call last):

File "C:\bin\leo-editor\leo\commands\spellCommands.py", line 56, in create
f = open(fn, mode='wb')

TypeError: expected str, bytes or os.PathLike object, not NoneType

reading settings in C:/bin/leo-editor/leo/doc/CheatSheet.leo

# Fixed code
def computeHomeLeoDir(self):
    # lm = self
    homeLeoDir = g.os_path_finalize_join(g.app.homeDir, ".leo")
    if g.os_path_exists(homeLeoDir):
        return homeLeoDir
    ok = g.makeAllNonExistentDirectories(homeLeoDir, force=True)
    return homeLeoDir if ok else ""  # #1450
# Buggy code
def update_file_if_changed(c, file_name, temp_name):
    """Compares two files.

    If they are different, we replace file_name with temp_name.
    Otherwise, we just delete temp_name. Both files should be closed."""
    if g.os_path_exists(file_name):
        if filecmp.cmp(temp_name, file_name):
            kind = "unchanged"
            ok = g.utils_remove(temp_name)
        else:
            kind = "***updating"
            mode = g.utils_stat(file_name)
            ok = g.utils_rename(c, temp_name, file_name, mode)
    else:
        kind = "creating"
        # 2010/02/04: g.utils_rename no longer calls
        # makeAllNonExistentDirectories
        head, tail = g.os_path_split(file_name)
        ok = True
        if head:
            ok = g.makeAllNonExistentDirectories(head, c=c)
        if ok:
            ok = g.utils_rename(c, temp_name, file_name)
    if ok:
        g.es("", f"{kind:12}: {file_name}")
    else:
        g.error("rename failed: no file created!")
        g.es("", file_name, " may be read-only or in use")


# Traceback (TypeError)
Leo Log Window
Leo 6.1-final, master branch, build b80e074204
2019-11-08 12:36:03 -0600
Python 3.8.0, PyQt version 5.13.0
Windows 10 AMD64 (build 10.0.17763) SP0
created directory: C:/Users/C050536/.leo
leoID='metaperl'
.leoID.txt created in C:/Users/C050536/.leo
current dir: C:/bin/leo-editor
load dir: C:/bin/leo-editor/leo/core
global config dir: C:/bin/leo-editor/leo/config
home dir: C:/Users/C050536
reading settings in C:/bin/leo-editor/leo/config/leoSettings.leo
Do spellpyx.txt file found
unexpected error creating: None
Traceback (most recent call last):

File "C:\bin\leo-editor\leo\commands\spellCommands.py", line 56, in create
f = open(fn, mode='wb')

TypeError: expected str, bytes or os.PathLike object, not NoneType

reading settings in C:/bin/leo-editor/leo/doc/CheatSheet.leo

# Fixed code
def update_file_if_changed(c, file_name, temp_name):
    """Compares two files.

    If they are different, we replace file_name with temp_name.
    Otherwise, we just delete temp_name. Both files should be closed."""
    if g.os_path_exists(file_name):
        if filecmp.cmp(temp_name, file_name):
            kind = "unchanged"
            ok = g.utils_remove(temp_name)
        else:
            kind = "***updating"
            mode = g.utils_stat(file_name)
            ok = g.utils_rename(c, temp_name, file_name, mode)
    else:
        kind = "creating"
        head, tail = g.os_path_split(file_name)
        ok = True
        if head:
            ok = g.makeAllNonExistentDirectories(head, c=c)
        if ok:
            ok = g.utils_rename(c, temp_name, file_name)
    if ok:
        g.es("", f"{kind:12}: {file_name}")
    else:
        g.error("rename failed: no file created!")
        g.es("", file_name, " may be read-only or in use")
# Buggy code
def utils_rename(c, src, dst, verbose=True):
    """Platform independent rename."""
    # Don't call g.makeAllNonExistentDirectories.
    # It's not right to do this here!!
    # head, tail = g.os_path_split(dst)
    # if head: g.makeAllNonExistentDirectories(head,c=c)
    try:
        shutil.move(src, dst)
        return True
    except Exception:
        if verbose:
            g.error("exception renaming", src, "to", dst)
            g.es_exception(full=False)
        return False


# Traceback (TypeError)
Leo Log Window
Leo 6.1-final, master branch, build b80e074204
2019-11-08 12:36:03 -0600
Python 3.8.0, PyQt version 5.13.0
Windows 10 AMD64 (build 10.0.17763) SP0
created directory: C:/Users/C050536/.leo
leoID='metaperl'
.leoID.txt created in C:/Users/C050536/.leo
current dir: C:/bin/leo-editor
load dir: C:/bin/leo-editor/leo/core
global config dir: C:/bin/leo-editor/leo/config
home dir: C:/Users/C050536
reading settings in C:/bin/leo-editor/leo/config/leoSettings.leo
Do spellpyx.txt file found
unexpected error creating: None
Traceback (most recent call last):

File "C:\bin\leo-editor\leo\commands\spellCommands.py", line 56, in create
f = open(fn, mode='wb')

TypeError: expected str, bytes or os.PathLike object, not NoneType

reading settings in C:/bin/leo-editor/leo/doc/CheatSheet.leo

# Fixed code
def utils_rename(c, src, dst, verbose=True):
    """Platform independent rename."""
    # Don't call g.makeAllNonExistentDirectories here!
    try:
        shutil.move(src, dst)
        return True
    except Exception:
        if verbose:
            g.error("exception renaming", src, "to", dst)
            g.es_exception(full=False)
        return False
# Buggy code
def create(self, fn):
    """Create the given file with empty contents."""
    theDir = g.os_path_dirname(fn)
    # Make the directories as needed.
    ok = g.makeAllNonExistentDirectories(theDir, c=self.c, force=True, verbose=True)
    # #1453: Don't assume the directory exists.
    if not ok:
        g.error(f"did not create: {theDir}")
        return
    try:
        f = open(fn, mode="wb")
        f.close()
        g.note(f"created: {fn}")
    except IOError:
        g.error(f"can not create: {fn}")
    except Exception:
        g.error(f"unexpected error creating: {fn}")
        g.es_exception()


# Traceback (TypeError)
Leo Log Window
Leo 6.1-final, master branch, build b80e074204
2019-11-08 12:36:03 -0600
Python 3.8.0, PyQt version 5.13.0
Windows 10 AMD64 (build 10.0.17763) SP0
created directory: C:/Users/C050536/.leo
leoID='metaperl'
.leoID.txt created in C:/Users/C050536/.leo
current dir: C:/bin/leo-editor
load dir: C:/bin/leo-editor/leo/core
global config dir: C:/bin/leo-editor/leo/config
home dir: C:/Users/C050536
reading settings in C:/bin/leo-editor/leo/config/leoSettings.leo
Do spellpyx.txt file found
unexpected error creating: None
Traceback (most recent call last):

File "C:\bin\leo-editor\leo\commands\spellCommands.py", line 56, in create
f = open(fn, mode='wb')

TypeError: expected str, bytes or os.PathLike object, not NoneType

reading settings in C:/bin/leo-editor/leo/doc/CheatSheet.leo

# Fixed code
def create(self, fn):
    """Create the given file with empty contents."""
    # Make the directories as needed.
    theDir = g.os_path_dirname(fn)
    if theDir:
        ok = g.makeAllNonExistentDirectories(theDir, c=self.c, force=True, verbose=True)
        # #1453: Don't assume the directory exists.
        if not ok:
            g.error(f"did not create directory: {theDir}")
            return
    # Create the file.
    try:
        f = open(fn, mode="wb")
        f.close()
        g.note(f"created: {fn}")
    except IOError:
        g.error(f"can not create: {fn}")
    except Exception:
        g.error(f"unexpected error creating: {fn}")
        g.es_exception()
# Buggy code
def makeAllNonExistentDirectories(theDir, c=None, force=False, verbose=True):
    """
    Attempt to make all non-existent directories.

    A wrapper from os.makedirs (new in Python 3.2).

    """
    if force:
        create = True  # Bug fix: g.app.config will not exist during startup.
    elif c:
        create = c.config and c.config.create_nonexistent_directories
    else:
        create = g.app and g.app.config and g.app.config.create_nonexistent_directories
    if c:
        theDir = c.expand_path_expression(theDir)
    #
    # Return True if the directory already exists.
    dir1 = theDir = g.os_path_normpath(theDir)
    exists = g.os_path_isdir(dir1) and g.os_path_exists(dir1)
    if exists:
        return True
    #
    # Return False if we aren't forcing the create.
    if not force and not create:
        return False
    #
    # Just use os.makedirs.
    try:
        os.makedirs(theDir, mode=0o777, exist_ok=False)
        return True
    except Exception:
        return False


# Traceback (TypeError)
Leo Log Window
Leo 6.1-final, master branch, build b80e074204
2019-11-08 12:36:03 -0600
Python 3.8.0, PyQt version 5.13.0
Windows 10 AMD64 (build 10.0.17763) SP0
created directory: C:/Users/C050536/.leo
leoID='metaperl'
.leoID.txt created in C:/Users/C050536/.leo
current dir: C:/bin/leo-editor
load dir: C:/bin/leo-editor/leo/core
global config dir: C:/bin/leo-editor/leo/config
home dir: C:/Users/C050536
reading settings in C:/bin/leo-editor/leo/config/leoSettings.leo
Do spellpyx.txt file found
unexpected error creating: None
Traceback (most recent call last):

File "C:\bin\leo-editor\leo\commands\spellCommands.py", line 56, in create
f = open(fn, mode='wb')

TypeError: expected str, bytes or os.PathLike object, not NoneType

reading settings in C:/bin/leo-editor/leo/doc/CheatSheet.leo

# Fixed code
def makeAllNonExistentDirectories(theDir, c=None, force=False, verbose=True):
    """
    Attempt to make all non-existent directories.
    Return the created directory, or None.

    If c is given, support {{expressions}}.

    A wrapper from os.makedirs (new in Python 3.2).

    """
    if force:
        # Bug fix: g.app.config will not exist during startup.
        create = True
    elif c:
        create = c and c.config and c.config.create_nonexistent_directories
    else:
        create = g.app and g.app.config and g.app.config.create_nonexistent_directories
    if c:
        theDir = c.expand_path_expression(theDir)
    #
    # Return True if the directory already exists.
    theDir = g.os_path_normpath(theDir)
    exists = g.os_path_isdir(theDir) and g.os_path_exists(theDir)
    if exists:
        return theDir
    #
    # Return False if we aren't forcing the create.
    if not force and not create:
        return None
    #
    # #1450: Just use os.makedirs.
    try:
        os.makedirs(theDir, mode=0o777, exist_ok=False)
        return theDir
    except Exception:
        return None