gurudesh/pytracebugs huggingface dataset:
# Buggy code
def wait_for_active_job():
    """
    Wait for the active job to finish, to be killed by SIGINT, or to be
    suspended by ctrl-z.
    """
    _clear_dead_jobs()

    active_task = get_next_task()

    # Return when there are no foreground active task
    if active_task is None:
        _give_terminal_to(_shell_pgrp)  # give terminal back to the shell
        return

    pgrp = active_task["pgrp"]
    obj = active_task["obj"]
    # give the terminal over to the fg process
    _give_terminal_to(pgrp)

    _continue(active_task)

    _, wcode = os.waitpid(obj.pid, os.WUNTRACED)
    if os.WIFSTOPPED(wcode):
        print()  # get a newline because ^Z will have been printed
        active_task["status"] = "stopped"
    elif os.WIFSIGNALED(wcode):
        print()  # get a newline because ^C will have been printed
        obj.signal = (os.WTERMSIG(wcode), os.WCOREDUMP(wcode))
        obj.returncode = None
    else:
        obj.returncode = os.WEXITSTATUS(wcode)
        obj.signal = None

    return wait_for_active_job()


# Traceback (TypeError)
└─> % history zsh | grep nvidia
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
204: nvidia-smi -l
Traceback (most recent call last):
File "/home/home51/lunz8748/usr/xonsh/xonsh/base_shell.py", line 167, in default
run_compiled_code(code, self.ctx, None, 'single')
File "/home/home51/lunz8748/usr/xonsh/xonsh/codecache.py", line 66, in run_compiled_code
func(code, glb, loc)
File "<xonsh-code>", line 1, in <module>
File "/home/home51/lunz8748/usr/xonsh/xonsh/built_ins.py", line 635, in subproc_captured_hiddenobject
return run_subproc(cmds, captured='hiddenobject')
File "/home/home51/lunz8748/usr/xonsh/xonsh/built_ins.py", line 517, in run_subproc
'bg': background
File "/home/home51/lunz8748/usr/xonsh/xonsh/jobs.py", line 260, in add_job
_set_pgrp(info)
File "/home/home51/lunz8748/usr/xonsh/xonsh/jobs.py", line 103, in _set_pgrp
info['pgrp'] = os.getpgid(info['pids'][0])
TypeError: an integer is required (got type NoneType)

# Fixed code
def wait_for_active_job():
    """
    Wait for the active job to finish, to be killed by SIGINT, or to be
    suspended by ctrl-z.
    """
    _clear_dead_jobs()
    active_task = get_next_task()
    # Return when there are no foreground active task
    if active_task is None:
        _give_terminal_to(_shell_pgrp)  # give terminal back to the shell
        return
    pgrp = active_task.get("pgrp", None)
    obj = active_task["obj"]
    # give the terminal over to the fg process
    if pgrp is not None:
        _give_terminal_to(pgrp)
    _continue(active_task)
    _, wcode = os.waitpid(obj.pid, os.WUNTRACED)
    if os.WIFSTOPPED(wcode):
        print()  # get a newline because ^Z will have been printed
        active_task["status"] = "stopped"
    elif os.WIFSIGNALED(wcode):
        print()  # get a newline because ^C will have been printed
        obj.signal = (os.WTERMSIG(wcode), os.WCOREDUMP(wcode))
        obj.returncode = None
    else:
        obj.returncode = os.WEXITSTATUS(wcode)
        obj.signal = None
    return wait_for_active_job()
# Buggy code
def _executables_in_posix(path):
    if PYTHON_VERSION_INFO < (3, 5, 0):
        for fname in os.listdir(path):
            fpath = os.path.join(path, fname)
            if (
                os.path.exists(fpath)
                and os.access(fpath, os.X_OK)
                and (not os.path.isdir(fpath))
            ):
                yield fname
    else:
        yield from _yield_accessible_unix_file_names(path)


# Traceback (FileNotFoundError)
cheaterman@cmans-laptop ~ $ echo 'Owiii bliblibli ^__^'
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 13095, in default
run_compiled_code(code, self.ctx, None, 'single')
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 2876, in run_compiled_code
func(code, glb, loc)
File "<xonsh-code>", line 1, in <module>
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 15734, in subproc_captured_hiddenobject
return run_subproc(cmds, captured='hiddenobject')
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 15515, in run_subproc
binary_loc = locate_binary(cmd[0])
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 11592, in locate_binary
return builtins.__xonsh_commands_cache__.locate_binary(name)
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 10761, in locate_binary
_ = self.all_commands
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 10723, in all_commands
for cmd in executables_in(path):
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 5567, in executables_in
yield from func(path)
File "/usr/lib64/python3.4/site-packages/xonsh/__amalgam__.py", line 5529, in _executables_in_posix
for fname in os.listdir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/opt/bin'
cheaterman@cmans-laptop ~ $

# Fixed code
def _executables_in_posix(path):
    if not os.path.exists(path):
        return
    elif PYTHON_VERSION_INFO < (3, 5, 0):
        for fname in os.listdir(path):
            fpath = os.path.join(path, fname)
            if (
                os.path.exists(fpath)
                and os.access(fpath, os.X_OK)
                and (not os.path.isdir(fpath))
            ):
                yield fname
    else:
        yield from _yield_accessible_unix_file_names(path)
# Buggy code
def run(self):
    hist = builtins.__xonsh_history__
    buf = None
    ptkhist = self.ptkhist
    while self.wait_for_gc and hist.gc.is_alive():
        time.sleep(0.011)  # gc sleeps for 0.01 secs, sleep a beat longer
    files = hist.gc.files()
    for _, _, f in files:
        try:
            lj = lazyjson.LazyJSON(f, reopen=False)
            for cmd in lj["cmds"]:
                line = cmd["inp"].rstrip()
                if line == "EOF":
                    continue
                if len(ptkhist) == 0 or line != ptkhist[-1]:
                    ptkhist.append(line)
                    if buf is None:
                        buf = self._buf()
                        if buf is None:
                            continue
                    buf.reset(initial_document=buf.document)
            lj.close()
        except (IOError, OSError):
            continue


# Traceback (json.decoder.JSONDecodeError)
hugo@mbp: ~$ Exception in thread Thread-2:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 914,r
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/n
lj = lazyjson.LazyJSON(f, reopen=False)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/lazy_
self._load_index()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/lazyx
locs = json.loads(locs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line s
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 3e
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 3e
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

# Fixed code
def run(self):
    hist = builtins.__xonsh_history__
    buf = None
    ptkhist = self.ptkhist
    while self.wait_for_gc and hist.gc.is_alive():
        time.sleep(0.011)  # gc sleeps for 0.01 secs, sleep a beat longer
    files = hist.gc.files()
    for _, _, f in files:
        try:
            lj = lazyjson.LazyJSON(f, reopen=False)
            for cmd in lj["cmds"]:
                line = cmd["inp"].rstrip()
                if line == "EOF":
                    continue
                if len(ptkhist) == 0 or line != ptkhist[-1]:
                    ptkhist.append(line)
                    if buf is None:
                        buf = self._buf()
                        if buf is None:
                            continue
                    buf.reset(initial_document=buf.document)
            lj.close()
        except (IOError, OSError, ValueError):
            continue
# Buggy code
def run(self):
    try:
        import readline
    except ImportError:
        return
    hist = builtins.__xonsh_history__
    while self.wait_for_gc and hist.gc.is_alive():
        time.sleep(0.011)  # gc sleeps for 0.01 secs, sleep a beat longer
    files = hist.gc.files()
    i = 1
    for _, _, f in files:
        try:
            lj = LazyJSON(f, reopen=False)
            for cmd in lj["cmds"]:
                inp = cmd["inp"].splitlines()
                for line in inp:
                    if line == "EOF":
                        continue
                    readline.add_history(line)
                    if RL_LIB is not None:
                        RL_LIB.history_set_pos(i)
                    i += 1
            lj.close()
        except (IOError, OSError):
            continue


# Traceback (json.decoder.JSONDecodeError)
hugo@mbp: ~$ Exception in thread Thread-2:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 914,r
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/ptk/n
lj = lazyjson.LazyJSON(f, reopen=False)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/lazy_
self._load_index()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xonsh/lazyx
locs = json.loads(locs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line s
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 3e
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 3e
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

# Fixed code
def run(self):
    try:
        import readline
    except ImportError:
        return
    hist = builtins.__xonsh_history__
    while self.wait_for_gc and hist.gc.is_alive():
        time.sleep(0.011)  # gc sleeps for 0.01 secs, sleep a beat longer
    files = hist.gc.files()
    i = 1
    for _, _, f in files:
        try:
            lj = LazyJSON(f, reopen=False)
            for cmd in lj["cmds"]:
                inp = cmd["inp"].splitlines()
                for line in inp:
                    if line == "EOF":
                        continue
                    readline.add_history(line)
                    if RL_LIB is not None:
                        RL_LIB.history_set_pos(i)
                    i += 1
            lj.close()
        except (IOError, OSError, ValueError):
            continue
# Buggy code
def xonfig(args, stdin=None):
    """Runs the xonsh configuration utility."""
    from xonsh.xonfig import main  # lazy import

    return main(args)


# Traceback (ImportError)
$ xonfig
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\proc.py", line 336, in wrapped_simple_command
r = f(args, i)
File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\aliases.py", line 453, in xonfig
from xonsh.xonfig import main  # lazy import
ImportError: cannot import name 'main'

# Fixed code
def xonfig(args, stdin=None):
    """Runs the xonsh configuration utility."""
    from xonsh.xonfig import xonfig_main  # lazy import

    return xonfig_main(args)
# Buggy code
def _info(ns):
    data = [
        ("xonsh", XONSH_VERSION),
        ("Python", "{}.{}.{}".format(*PYTHON_VERSION_INFO)),
        ("PLY", ply.__version__),
        ("have readline", is_readline_available()),
        ("prompt toolkit", ptk_version() or None),
        ("shell type", builtins.__xonsh_env__.get("SHELL_TYPE")),
        ("pygments", pygments_version()),
        ("on posix", ON_POSIX),
        ("on linux", ON_LINUX),
    ]
    if ON_LINUX:
        data.append(("distro", linux_distro()))
    data.extend(
        [
            ("on darwin", ON_DARWIN),
            ("on windows", ON_WINDOWS),
            ("on cygwin", ON_CYGWIN),
            ("is superuser", is_superuser()),
            ("default encoding", DEFAULT_ENCODING),
        ]
    )
    formatter = _xonfig_format_json if ns.json else __xonfig_format_human
    s = formatter(data)
    return s


# Traceback (ImportError)
$ xonfig
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\proc.py", line 336, in wrapped_simple_command
r = f(args, i)
File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\aliases.py", line 453, in xonfig
from xonsh.xonfig import main  # lazy import
ImportError: cannot import name 'main'

# Fixed code
def _info(ns):
    data = [
        ("xonsh", XONSH_VERSION),
        ("Python", "{}.{}.{}".format(*PYTHON_VERSION_INFO)),
        ("PLY", ply.__version__),
        ("have readline", is_readline_available()),
        ("prompt toolkit", ptk_version() or None),
        ("shell type", builtins.__xonsh_env__.get("SHELL_TYPE")),
        ("pygments", pygments_version()),
        ("on posix", ON_POSIX),
        ("on linux", ON_LINUX),
    ]
    if ON_LINUX:
        data.append(("distro", linux_distro()))
    data.extend(
        [
            ("on darwin", ON_DARWIN),
            ("on windows", ON_WINDOWS),
            ("on cygwin", ON_CYGWIN),
            ("is superuser", is_superuser()),
            ("default encoding", DEFAULT_ENCODING),
        ]
    )
    formatter = _xonfig_format_json if ns.json else _xonfig_format_human
    s = formatter(data)
    return s
# Buggy code
def executables_in(path):
    """Returns a generator of files in `path` that the user could execute."""
    if PYTHON_VERSION_INFO < (3, 5, 0):
        for i in os.listdir(path):
            name = os.path.join(path, i)
            if (
                os.path.exists(name)
                and os.access(name, os.X_OK)
                and (not os.path.isdir(name))
            ):
                yield i
    else:
        yield from (
            x.name for x in scandir(path) if x.is_file() and os.access(x.path, os.X_OK)
        )


# Traceback (PermissionError)
sympy-paperpre-print🐚 e reaException in thread Thread-32:
Traceback (most recent call last):
File "/Users/aaronmeurer/anaconda3/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/Users/aaronmeurer/anaconda3/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/prompt_toolkit/interface.py", line 759, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/xonsh/ptk/completer.py", line 36, in get_completions
self.ctx)
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/xonsh/completer.py", line 224, in complete
if cmd in self._cmds_cache:
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/xonsh/tools.py", line 1142, in __contains__
return item in self.all_commands
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/xonsh/tools.py", line 1174, in all_commands
allcmds |= set(executables_in(path))
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/xonsh/tools.py", line 329, in executables_in
yield from (x.name for x in scandir(path)
File "/Users/aaronmeurer/anaconda3/lib/python3.5/site-packages/xonsh/tools.py", line 330, in <genexpr>
if x.is_file() and os.access(x.path, os.X_OK))
PermissionError: [Errno 13] Permission denied: '/usr/sbin/weakpass_edit'

# Fixed code
def executables_in(path):
    """Returns a generator of files in `path` that the user could execute."""
    try:
        if PYTHON_VERSION_INFO < (3, 5, 0):
            for i in os.listdir(path):
                name = os.path.join(path, i)
                if (
                    os.path.exists(name)
                    and os.access(name, os.X_OK)
                    and (not os.path.isdir(name))
                ):
                    yield i
        else:
            yield from (
                x.name
                for x in scandir(path)
                if x.is_file() and os.access(x.path, os.X_OK)
            )
    except PermissionError:
        return
# Buggy code
def partial_color_tokenize(template):
    """Tokenizes a template string containing colors. Will return a list
    of tuples mapping the token to the string which has that color.
    These sub-strings maybe templates themselves.
    """
    if hasattr(builtins, "__xonsh_shell__"):
        styles = __xonsh_shell__.shell.styler.styles
    else:
        styles = None
    color = Color.NO_COLOR
    try:
        toks, color = _partial_color_tokenize_main(template)
    except:
        toks = [(Color.NO_COLOR, template)]
    if styles is not None:
        styles[color]  # ensure color is available
    return toks


# Traceback (ValueError)
hartz@tabby-3 ~ $ $PROMPT = "{{hello"
Traceback (most recent call last):
File "/usr/local/bin/xonsh", line 9, in <module>
load_entry_point('xonsh==0.3.2', 'console_scripts', 'xonsh')()
File "/usr/local/lib/python3.5/site-packages/xonsh/main.py", line 260, in main
shell.cmdloop()
File "/usr/local/lib/python3.5/site-packages/xonsh/ptk/shell.py", line 116, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File "/usr/local/lib/python3.5/site-packages/xonsh/ptk/shell.py", line 63, in singleline
prompt_tokens = self.prompt_tokens(None)
File "/usr/local/lib/python3.5/site-packages/xonsh/ptk/shell.py", line 137, in prompt_tokens
toks = partial_color_tokenize(p)
File "/usr/local/lib/python3.5/site-packages/xonsh/pyghooks.py", line 206, in partial_color_tokenize
for literal, field, spec, conv in formatter.parse(template):
ValueError: expected '}' before end of string

# Fixed code
def partial_color_tokenize(template):
    """Tokenizes a template string containing colors. Will return a list
    of tuples mapping the token to the string which has that color.
    These sub-strings maybe templates themselves.
    """
    if hasattr(builtins, "__xonsh_shell__"):
        styles = __xonsh_shell__.shell.styler.styles
    else:
        styles = None
    color = Color.NO_COLOR
    try:
        toks, color = _partial_color_tokenize_main(template, styles)
    except:
        toks = [(Color.NO_COLOR, template)]
    if styles is not None:
        styles[color]  # ensure color is available
    return toks
# Buggy code
def can_compile(src):
    """Returns whether the code can be compiled, i.e. it is valid xonsh."""
    src = src if src.endswith("\n") else src + "\n"
    src = src.lstrip()
    try:
        builtins.__xonsh_execer__.compile(
            src, mode="single", glbs=None, locs=builtins.__xonsh_ctx__
        )
        rtn = True
    except SyntaxError:
        rtn = False
    return rtn


# Traceback (ValueError)
klonuo@home C:\temp $ del "test.txt"
Traceback (most recent call last):
File "C:\Python35\Scripts\xonsh-script.py", line 9, in <module>
load_entry_point('xonsh==0.3.2', 'console_scripts', 'xonsh')()
File "c:\python35\lib\site-packages\xonsh\main.py", line 254, in main
shell.cmdloop()
File "c:\python35\lib\site-packages\xonsh\ptk\shell.py", line 115, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File "c:\python35\lib\site-packages\xonsh\ptk\shell.py", line 84, in singleline
line = self.prompter.prompt(**prompt_args)
File "c:\python35\lib\site-packages\xonsh\ptk\shortcuts.py", line 109, in prompt
document = cli.run(reset_current_buffer=False)
File "c:\python35\lib\site-packages\prompt_toolkit\interface.py", line 387, in run
self.eventloop.run(self.input, self.create_eventloop_callbacks())
File "c:\python35\lib\site-packages\prompt_toolkit\eventloop\win32.py", line 78, in run
callbacks.feed_key(k)
File "c:\python35\lib\site-packages\prompt_toolkit\interface.py", line 916, in feed_key
self._active_cli.input_processor.feed_key(key_press)
File "c:\python35\lib\site-packages\prompt_toolkit\key_binding\input_processor.py", line 174, in feed_key
self._process_coroutine.send(key_press)
File "c:\python35\lib\site-packages\prompt_toolkit\key_binding\input_processor.py", line 146, in _process
self._call_handler(matches[-1], key_sequence=buffer)
File "c:\python35\lib\site-packages\prompt_toolkit\key_binding\input_processor.py", line 190, in _call_handler
handler.call(event)
File "c:\python35\lib\site-packages\prompt_toolkit\key_binding\registry.py", line 32, in call
return self.handler(event)
File "c:\python35\lib\site-packages\xonsh\ptk\key_bindings.py", line 132, in multiline_carriage_return
carriage_return(b, event.cli)
File "c:\python35\lib\site-packages\xonsh\ptk\key_bindings.py", line 55, in carriage_return
elif not current_line_blank and not can_compile(b.document.text):
File "c:\python35\lib\site-packages\xonsh\ptk\key_bindings.py", line 102, in can_compile
locs=builtins.__xonsh_ctx__)
File "c:\python35\lib\site-packages\xonsh\execer.py", line 99, in compile
code = compile(tree, filename, mode)
ValueError: expression which can't be assigned to in Del context

# Fixed code
def can_compile(src):
    """Returns whether the code can be compiled, i.e. it is valid xonsh."""
    src = src if src.endswith("\n") else src + "\n"
    src = src.lstrip()
    try:
        builtins.__xonsh_execer__.compile(
            src, mode="single", glbs=None, locs=builtins.__xonsh_ctx__
        )
        rtn = True
    except SyntaxError:
        rtn = False
    except Exception:
        rtn = True
    return rtn
# Buggy code
def files(self, only_unlocked=False):
    """Find and return the history files. Optionally locked files may be
    excluded.

    This is sorted by the last closed time. Returns a list of (timestamp,
    file) tuples.
    """
    _ = self  # this could be a function but is intimate to this class
    # pylint: disable=no-member
    xdd = os.path.abspath(builtins.__xonsh_env__.get("XONSH_DATA_DIR"))
    fs = [f for f in iglob(os.path.join(xdd, "xonsh-*.json"))]
    files = []
    for f in fs:
        try:
            lj = lazyjson.LazyJSON(f, reopen=False)
            if only_unlocked and lj["locked"]:
                continue
            # info: closing timestamp, number of commands, filename
            files.append((lj["ts"][1] or time.time(), len(lj.sizes["cmds"]) - 1, f))
            lj.close()
        except (IOError, OSError, ValueError):
            continue
    files.sort()
    return files


# Traceback (FileNotFoundError)
$ xonsh
Traceback (most recent call last):
File "/usr/local/bin/xonsh", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.5/dist-packages/xonsh/main.py", line 180, in main
args = premain(argv)
File "/usr/local/lib/python3.5/dist-packages/xonsh/main.py", line 165, in premain
shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
File "/usr/local/lib/python3.5/dist-packages/xonsh/shell.py", line 76, in __init__
self._init_environ(ctx, config, rc)
File "/usr/local/lib/python3.5/dist-packages/xonsh/shell.py", line 116, in _init_environ
self.execer = Execer(config=config)
File "/usr/local/lib/python3.5/dist-packages/xonsh/execer.py", line 40, in __init__
load_builtins(execer=self, config=config)
File "/usr/local/lib/python3.5/dist-packages/xonsh/built_ins.py", line 780, in load_builtins
ts=[time.time(), None], locked=True)
File "/usr/local/lib/python3.5/dist-packages/xonsh/history.py", line 268, in __init__
with open(self.filename, 'w', newline='\n') as f:
FileNotFoundError: [Errno 2] No such file or directory: '~/.local/share/xonsh/xonsh-328aa1da-e158-4be1-af29-1f90be87a349.json'

# Fixed code
def files(self, only_unlocked=False):
    """Find and return the history files. Optionally locked files may be
    excluded.

    This is sorted by the last closed time. Returns a list of (timestamp,
    file) tuples.
    """
    _ = self  # this could be a function but is intimate to this class
    # pylint: disable=no-member
    xdd = os.path.expanduser(builtins.__xonsh_env__.get("XONSH_DATA_DIR"))
    xdd = os.path.abspath(xdd)
    fs = [f for f in iglob(os.path.join(xdd, "xonsh-*.json"))]
    files = []
    for f in fs:
        try:
            lj = lazyjson.LazyJSON(f, reopen=False)
            if only_unlocked and lj["locked"]:
                continue
            # info: closing timestamp, number of commands, filename
            files.append((lj["ts"][1] or time.time(), len(lj.sizes["cmds"]) - 1, f))
            lj.close()
        except (IOError, OSError, ValueError):
            continue
    files.sort()
    return files
# Buggy code
def run(self):
    clean_tables()
    build_tables()
    install_jupyter_hook(self.root if self.root else None)
    install.run(self)


# Traceback (FileNotFoundError)
Exception:
Traceback (most recent call last):
File "/home/nejl/.pyenv/versions/3.5.1/lib/python3.5/site-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/home/nejl/.pyenv/versions/3.5.1/lib/python3.5/site-packages/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/home/nejl/.pyenv/versions/3.5.1/lib/python3.5/site-packages/pip/req/req_set.py", line 732, in install
**kwargs
File "/home/nejl/.pyenv/versions/3.5.1/lib/python3.5/site-packages/pip/req/req_install.py", line 928, in install
with open(inst_files_path, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'home/nejl/.pyenv/versions/3.5.1/lib/python3.5/site-packages/xonsh-0.2.7-py3.5.egg-info/installed-files.txt'

# Fixed code
def run(self):
    clean_tables()
    build_tables()
    # install Jupyter hook
    root = self.root if self.root else None
    prefix = self.prefix if self.prefix else None
    try:
        install_jupyter_hook(prefix=prefix, root=root)
    except Exception:
        import traceback

        traceback.print_exc()
        print("Installing Jupyter hook failed.")
    install.run(self)
# Buggy code
def xonshrc_context(rcfile=None, execer=None):
    """Attempts to read in xonshrc file, and return the contents."""
    if rcfile is None or execer is None or not os.path.isfile(rcfile):
        return {}
    with open(rcfile, "r") as f:
        rc = f.read()
    if not rc.endswith("\n"):
        rc += "\n"
    fname = execer.filename
    env = {}
    try:
        execer.filename = rcfile
        execer.exec(rc, glbs={}, locs=env)
    except SyntaxError as err:
        msg = "syntax error in xonsh run control file {0!r}: {1!s}"
        warn(msg.format(rcfile, err), RuntimeWarning)
    finally:
        execer.filename = fname
    return env


# Traceback (NameError)
Traceback (most recent call last):
File "scripts/xonsh", line 3, in <module>
main()
File "/srv/git/wishlist/xonsh/xonsh/main.py", line 36, in main
shell = Shell()
File "/srv/git/wishlist/xonsh/xonsh/shell.py", line 94, in __init__
execer=self.execer)
File "/srv/git/wishlist/xonsh/xonsh/environ.py", line 168, in xonshrc_context
execer.exec(rc, glbs={}, locs=env)
File "/srv/git/wishlist/xonsh/xonsh/execer.py", line 110, in exec
return exec(code, glbs, locs)
File "/home/badger/.xonshrc", line 7, in <module>

File "/home/badger/.xonshrc", line 259, in get_tty
NameError: name 'subprocess' is not defined
Exception ignored in: <bound method Shell.__del__ of <xonsh.shell.Shell object at 0x7f383127e4e0>>
Traceback (most recent call last):
File "/srv/git/wishlist/xonsh/xonsh/shell.py", line 102, in __del__
teardown_readline()
File "/srv/git/wishlist/xonsh/xonsh/shell.py", line 65, in teardown_readline
import readline
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2222, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 2164, in _find_spec
File "<frozen importlib._bootstrap>", line 1940, in find_spec
File "<frozen importlib._bootstrap>", line 1908, in _get_spec
TypeError: 'NoneType' object is not iterable

# Fixed code
def xonshrc_context(rcfile=None, execer=None):
    """Attempts to read in xonshrc file, and return the contents."""
    if rcfile is None or execer is None or not os.path.isfile(rcfile):
        return {}
    with open(rcfile, "r") as f:
        rc = f.read()
    if not rc.endswith("\n"):
        rc += "\n"
    fname = execer.filename
    env = {}
    try:
        execer.filename = rcfile
        execer.exec(rc, glbs=env)
    except SyntaxError as err:
        msg = "syntax error in xonsh run control file {0!r}: {1!s}"
        warn(msg.format(rcfile, err), RuntimeWarning)
    finally:
        execer.filename = fname
    return env
# Buggy code
def get_slack_api_data(slack_api_url: str, get_param: str, **kwargs: Any) -> Any:
    if not kwargs.get("token"):
        raise AssertionError("Slack token missing in kwargs")
    data = requests.get(slack_api_url, kwargs)

    if data.status_code == requests.codes.ok:
        result = data.json()
        if not result["ok"]:
            raise Exception("Error accessing Slack API: {}".format(result["error"]))
        return result[get_param]

    raise Exception("HTTP error accessing the Slack API.")


# Traceback (Exception)
replace slack_data/overwatch/2018-09-08.json? [y]es, [n]o, [A]ll, [N]one, [r]ename: A
Traceback (most recent call last):
File "./manage.py", line 50, in <module>
execute_from_command_line(sys.argv)
File "/home/zulip/deployments/2020-12-01-22-47-56/zulip-py3-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/zulip/deployments/2020-12-01-22-47-56/zulip-py3-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/zulip/deployments/2020-12-01-22-47-56/zulip-py3-venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/zulip/deployments/2020-12-01-22-47-56/zulip-py3-venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/zulip/deployments/2020-12-01-22-47-56/zerver/management/commands/convert_slack_data.py", line 55, in handle
do_convert_data(path, output_dir, token, threads=num_threads)
File "/home/zulip/deployments/2020-12-01-22-47-56/zerver/data_import/slack.py", line 1072, in do_convert_data
user_list = get_slack_api_data("https://slack.com/api/users.list", "members", token=token)
File "/home/zulip/deployments/2020-12-01-22-47-56/zerver/data_import/slack.py", line 1142, in get_slack_api_data
raise Exception('Error accessing Slack API: {}'.format(result['error']))
Exception: Error accessing Slack API: invalid_auth

# Fixed code
def get_slack_api_data(slack_api_url: str, get_param: str, **kwargs: Any) -> Any:
    if not kwargs.get("token"):
        raise AssertionError("Slack token missing in kwargs")
    token = kwargs.pop("token")
    data = requests.get(
        slack_api_url, headers={"Authorization": "Bearer {}".format(token)}, **kwargs
    )

    if data.status_code == requests.codes.ok:
        result = data.json()
        if not result["ok"]:
            raise Exception("Error accessing Slack API: {}".format(result["error"]))
        return result[get_param]

    raise Exception("HTTP error accessing the Slack API.")
# Buggy code
def process_success_response(
    event: Dict[str, Any], service_handler: Any, response: Response
) -> None:
    try:
        response_json = json.loads(response.text)
    except ValueError:
        fail_with_message(event, "Invalid JSON in response")
        return

    success_data = service_handler.process_success(response_json)

    if success_data is None:
        return

    content = success_data.get("content")

    if content is None:
        return

    widget_content = success_data.get("widget_content")
    bot_id = event["user_profile_id"]
    message_info = event["message"]
    response_data = dict(content=content, widget_content=widget_content)
    send_response_message(
        bot_id=bot_id, message_info=message_info, response_data=response_data
    )


# Traceback (zerver.lib.exceptions.JsonableError)
Traceback (most recent call last):
File "/home/zulip/deployments/2020-05-27-05-59-05/zerver/worker/queue_processors.py", line 171, in do_consume
consume_func(events)
File "/home/zulip/deployments/2020-05-27-05-59-05/zerver/worker/queue_processors.py", line 200, in <lambda>
consume_func = lambda events: self.consume(events[0])
File "/home/zulip/deployments/2020-05-27-05-59-05/zerver/worker/queue_processors.py", line 589, in consume
service_handler)
File "/home/zulip/deployments/2020-05-27-05-59-05/zerver/lib/outgoing_webhook.py", line 289, in do_rest_call
process_success_response(event, service_handler, response)
File "/home/zulip/deployments/2020-05-27-05-59-05/zerver/lib/outgoing_webhook.py", line 277, in process_success_response
send_response_message(bot_id=bot_id, message_info=message_info, response_data=response_data)
File "/home/zulip/deployments/2020-05-27-05-59-05/zerver/lib/outgoing_webhook.py", line 166, in send_response_message
raise JsonableError(_("Missing content"))
zerver.lib.exceptions.JsonableError: Missing content

# Fixed code
def process_success_response(
    event: Dict[str, Any], service_handler: Any, response: Response
) -> None:
    try:
        response_json = json.loads(response.text)
    except ValueError:
        fail_with_message(event, "Invalid JSON in response")
        return

    success_data = service_handler.process_success(response_json)

    if success_data is None:
        return

    content = success_data.get("content")

    if content is None or content.strip() == "":
        return

    widget_content = success_data.get("widget_content")
    bot_id = event["user_profile_id"]
    message_info = event["message"]
    response_data = dict(content=content, widget_content=widget_content)
    send_response_message(
        bot_id=bot_id, message_info=message_info, response_data=response_data
    )
# Buggy code
def setup_path() -> None:
    if os.path.basename(sys.prefix) != "zulip-py3-venv":
        BASE_DIR = os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        )
        venv = os.path.join(BASE_DIR, "zulip-py3-venv")
        activate_this = os.path.join(venv, "bin", "activate_this.py")
        activate_locals = dict(__file__=activate_this)
        exec(open(activate_this).read(), activate_locals)
        if not os.path.exists(activate_locals["site_packages"]):
            raise RuntimeError(venv + " was not set up for this Python version")


# Traceback (KeyError)
Successfully installed Yarn 1.19.1!
+ mkdir -p /etc/zulip
+ cat
+ '[' -n '' ']'
+ dpkg-query --showformat '${Status}\n' -W rabbitmq-server
+ grep -vq ' not-installed$'
+ cat
+ '[' -n '' ']'
+ case ",$PUPPET_CLASSES," in
+ '[' -z '' ']'
+ cp -a /tmp/tmp.yliyQLjARE/zulip-server-2.1.2/zproject/prod_settings_template.py /etc/zulip/settings.py
+ '[' -n zulip ']'
+ sed -i 's/^EXTERNAL_HOST =.*/EXTERNAL_HOST = '\''zulip'\''/' /etc/zulip/settings.py
+ '[' -n root@localhost.localdomain ']'
+ sed -i 's/^ZULIP_ADMINISTRATOR =.*/ZULIP_ADMINISTRATOR = '\''root@localhost.localdomain'\''/' /etc/zulip/settings.py
+ ln -nsf /etc/zulip/settings.py /tmp/tmp.yliyQLjARE/zulip-server-2.1.2/zproject/prod_settings.py
+ /tmp/tmp.yliyQLjARE/zulip-server-2.1.2/scripts/setup/generate_secrets.py --production
Traceback (most recent call last):
File "/tmp/tmp.yliyQLjARE/zulip-server-2.1.2/scripts/setup/generate_secrets.py", line 11, in <module>
import scripts.lib.setup_path_on_import
File "/tmp/tmp.yliyQLjARE/zulip-server-2.1.2/scripts/lib/setup_path_on_import.py", line 14, in <module>
if not os.path.exists(activate_locals["site_packages"]):
KeyError: 'site_packages'

Zulip installation failed (exit code 1)!

The install process is designed to be idempotent, so you can retry after resolving whatever issue caused the failure (there should be a traceback above). A log of this installation is available in /var/log/zulip/install.log
root@zulip-2001:/tmp/tmp.yliyQLjARE/zulip-server-2.1.2#

# Fixed code
def setup_path() -> None:
    if os.path.basename(sys.prefix) != "zulip-py3-venv":
        BASE_DIR = os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        )
        venv = os.path.join(BASE_DIR, "zulip-py3-venv")
        activate_this = os.path.join(venv, "bin", "activate_this.py")
        activate_locals = dict(__file__=activate_this)
        exec(open(activate_this).read(), activate_locals)
        # Check that the python version running this function
        # is same as python version that created the virtualenv.
        python_version = "python{}.{}".format(*sys.version_info[:2])
        if not os.path.exists(os.path.join(venv, "lib", python_version)):
            raise RuntimeError(venv + " was not set up for this Python version")
# Buggy code
def auth_complete(self, *args, **kwargs):
    # type: (*Any, **Any) -> Optional[HttpResponse]
    """
    Returning `None` from this function will redirect the browser
    to the login page.
    """
    try:
        # Call the auth_complete method of social_core.backends.oauth.BaseOAuth2
        return super(SocialAuthMixin, self).auth_complete(*args, **kwargs)  # type: ignore # monkey-patching
    except AuthFailed:
        return None
    except SocialAuthBaseException as e:
        logging.exception(e)
        return None


# Traceback (social_core.exceptions.AuthStateMissing)
Traceback (most recent call last):
File "./zproject/backends.py", line 255, in auth_complete
return super(SocialAuthMixin, self).auth_complete(*args, **kwargs)  # type: ignore # monkey-patching
File "/home/zulip/deployments/2017-10-06-23-10-28/zulip-py3-venv/lib/python3.5/site-packages/social_core/utils.py", line 252, in wrapper
return func(*args, **kwargs)
File "/home/zulip/deployments/2017-10-06-23-10-28/zulip-py3-venv/lib/python3.5/site-packages/social_core/backends/oauth.py", line 387, in auth_complete
state = self.validate_state()
File "/home/zulip/deployments/2017-10-06-23-10-28/zulip-py3-venv/lib/python3.5/site-packages/social_core/backends/oauth.py", line 89, in validate_state
raise AuthStateMissing(self, 'state')
social_core.exceptions.AuthStateMissing: Session value state missing.

# Fixed code
def auth_complete(self, *args, **kwargs):
    # type: (*Any, **Any) -> Optional[HttpResponse]
    """
    Returning `None` from this function will redirect the browser
    to the login page.
    """
    try:
        # Call the auth_complete method of social_core.backends.oauth.BaseOAuth2
        return super(SocialAuthMixin, self).auth_complete(*args, **kwargs)  # type: ignore # monkey-patching
    except AuthFailed:
        return None
    except SocialAuthBaseException as e:
        logging.warning(str(e))
        return None
# Buggy code
def request_retry(event, request_data, failure_message):
    # type: (Dict[str, Any], Dict[str, Any], Text) -> None
    def failure_processor(event):
        # type: (Dict[str, Any]) -> None
        """
        The name of the argument is 'event' on purpose. This argument will hide
        the 'event' argument of the request_retry function. Keeping the same name
        results in a smaller diff.
        """
        bot_user = get_user_profile_by_id(event["user_profile_id"])
        fail_with_message(event, "Maximum retries exceeded! " + failure_message)
        notify_bot_owner(event, request_data)
        logging.warning(
            "Maximum retries exceeded for trigger:%s event:%s"
            % (bot_user.email, event["command"])
        )

    retry_event("outgoing_webhooks", event, failure_processor)


# Traceback (ConnectionError)
Traceback (most recent call last):
File "/home/zulip/deployments/2017-08-14-16-02-48/zerver/lib/outgoing_webhook.py", line 192, in do_rest_call
response = requests.request(http_method, final_url, data=request_data, **request_kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/sessions.py", line 502, in request
resp = self.send(prep, **send_kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/sessions.py", line 612, in send
r = adapter.send(request, **kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/adapters.py", line 504, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='zulipbotserver.herokuapp.com', port=33507): Max retries exceeded with url: /bots/converter (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fc5ebd84490>: Failed to establish a new connection: [Errno 111] Connection refused',))

# Fixed code
def request_retry(event, request_data, failure_message, exception=None):
    # type: (Dict[str, Any], Dict[str, Any], Text, Optional[Exception]) -> None
    def failure_processor(event):
        # type: (Dict[str, Any]) -> None
        """
        The name of the argument is 'event' on purpose. This argument will hide
        the 'event' argument of the request_retry function. Keeping the same name
        results in a smaller diff.
        """
        bot_user = get_user_profile_by_id(event["user_profile_id"])
        fail_with_message(event, "Maximum retries exceeded! " + failure_message)
        notify_bot_owner(event, request_data, exception=exception)
        logging.warning(
            "Maximum retries exceeded for trigger:%s event:%s"
            % (bot_user.email, event["command"])
        )

    retry_event("outgoing_webhooks", event, failure_processor)
# Buggy code
def failure_processor(event):
    # type: (Dict[str, Any]) -> None
    """
    The name of the argument is 'event' on purpose. This argument will hide
    the 'event' argument of the request_retry function. Keeping the same name
    results in a smaller diff.
    """
    bot_user = get_user_profile_by_id(event["user_profile_id"])
    fail_with_message(event, "Maximum retries exceeded! " + failure_message)
    notify_bot_owner(event, request_data)
    logging.warning(
        "Maximum retries exceeded for trigger:%s event:%s"
        % (bot_user.email, event["command"])
    )


# Traceback (ConnectionError)
Traceback (most recent call last):
File "/home/zulip/deployments/2017-08-14-16-02-48/zerver/lib/outgoing_webhook.py", line 192, in do_rest_call
response = requests.request(http_method, final_url, data=request_data, **request_kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/sessions.py", line 502, in request
resp = self.send(prep, **send_kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/sessions.py", line 612, in send
r = adapter.send(request, **kwargs)
File "/home/zulip/deployments/2017-08-14-16-02-48/zulip-venv/lib/python2.7/site-packages/requests/adapters.py", line 504, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='zulipbotserver.herokuapp.com', port=33507): Max retries exceeded with url: /bots/converter (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fc5ebd84490>: Failed to establish a new connection: [Errno 111] Connection refused',))

# Fixed code
def failure_processor(event):
    # type: (Dict[str, Any]) -> None
    """
    The name of the argument is 'event' on purpose. This argument will hide
    the 'event' argument of the request_retry function. Keeping the same name
    results in a smaller diff.
    """
    bot_user = get_user_profile_by_id(event["user_profile_id"])
    fail_with_message(event, "Maximum retries exceeded! " + failure_message)
    notify_bot_owner(event, request_data, exception=exception)
    logging.warning(
        "Maximum retries exceeded for trigger:%s event:%s"
        % (bot_user.email, event["command"])
    )
# Buggy code
def get_push_commits_body(payload):
    # type: (Dict[str, Any]) -> Text
    commits_data = [
        {
            "name": (
                commit.get("author").get("username") or commit.get("author").get("name")
            ),
            "sha": commit["id"],
            "url": commit["url"],
            "message": commit["message"],
        }
        for commit in payload["commits"]
    ]
    return get_push_commits_event_message(
        get_sender_name(payload),
        payload["compare"],
        get_branch_name_from_ref(payload["ref"]),
        commits_data,
    )


# Traceback (IndexError)
Traceback (most recent call last):
File "/home/zulip/deployments/2017-05-10-06-16-16/zulip-venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/zulip/deployments/2017-05-10-06-16-16/zulip-venv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "./zerver/webhooks/github_dispatcher.py", line 15, in api_github_webhook_dispatch
return api_github_landing(request)
File "/home/zulip/deployments/2017-05-10-06-16-16/zulip-venv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "./zerver/decorator.py", line 104, in wrapper
return func(request, *args, **kwargs)
File "./zerver/lib/request.py", line 166, in _wrapped_view_func
return view_func(request, *args, **kwargs)
File "./zerver/decorator.py", line 384, in _wrapped_func_arguments
return limited_func(request, user_profile, *args, **kwargs)
File "./zerver/decorator.py", line 664, in wrapped_func
return func(request, *args, **kwargs)
File "./zerver/lib/request.py", line 166, in _wrapped_view_func
return view_func(request, *args, **kwargs)
File "./zerver/webhooks/github/view.py", line 270, in api_github_landing
**kwargs)
File "./zerver/webhooks/github/view.py", line 175, in api_github_v2
created=payload['created'])
File "./zerver/webhooks/github/view.py", line 294, in build_message_from_gitlog
content = get_push_commits_event_message(pusher, url, short_ref, commits)
File "./zerver/lib/webhooks/git.py", line 64, in get_push_commits_event_message
committers_details = "{} ({})".format(*committers_items[0])
IndexError: list index out of range

# Fixed code
def get_push_commits_body(payload):
    # type: (Dict[str, Any]) -> Text
    commits_data = [
        {
            "name": (
                commit.get("author").get("username") or commit.get("author").get("name")
            ),
            "sha": commit["id"],
            "url": commit["url"],
            "message": commit["message"],
        }
        for commit in payload["commits"]
    ]
    return get_push_commits_event_message(
        get_sender_name(payload),
        payload["compare"],
        get_branch_name_from_ref(payload["ref"]),
        commits_data,
        deleted=payload["deleted"],
    )