gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, *objs):
    self.objs = objs


# Traceback (AttributeError)
$ vd --debug -b -p newCol.vd
Think about what you're doing
opening newCol as vd
"."
opening . as dir
"1"
c=addColumn(SettableColumn("", width=options.default_width), cursorColIndex+1); draw(vd.scr); cursorVisibleColIndex=visibleCols.index(c); c.name=editCell(cursorVisibleColIndex, -1); c.width=None
AttributeError: 'NoneType' object has no attribute 'erase'
AttributeError: 'NoneType' object has no attribute 'erase'
Traceback (most recent call last):
File "/usr/local/bin/vd", line 4, in <module>
__import__('pkg_resources').run_script('visidata==1.6.dev0', 'vd')
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 664, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1451, in run_script
exec(script_code, namespace, namespace)
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 169, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 152, in main
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 289, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 455, in exceptionCaught
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 284, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 264, in replayOne
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1132, in exec_command
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1126, in exec_command
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/_sheet.py", line 566, in draw
AttributeError: 'NoneType' object has no attribute 'erase'

# Fixed code
def __init__(self, *objs):
    self.locals = {}
    self.objs = list(objs) + [self.locals]
# Buggy code
def keys(self):
    return list(sum(set(dir(obj)) for obj in objs))


# Traceback (AttributeError)
$ vd --debug -b -p newCol.vd
Think about what you're doing
opening newCol as vd
"."
opening . as dir
"1"
c=addColumn(SettableColumn("", width=options.default_width), cursorColIndex+1); draw(vd.scr); cursorVisibleColIndex=visibleCols.index(c); c.name=editCell(cursorVisibleColIndex, -1); c.width=None
AttributeError: 'NoneType' object has no attribute 'erase'
AttributeError: 'NoneType' object has no attribute 'erase'
Traceback (most recent call last):
File "/usr/local/bin/vd", line 4, in <module>
__import__('pkg_resources').run_script('visidata==1.6.dev0', 'vd')
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 664, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1451, in run_script
exec(script_code, namespace, namespace)
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 169, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 152, in main
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 289, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 455, in exceptionCaught
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 284, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 264, in replayOne
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1132, in exec_command
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1126, in exec_command
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/_sheet.py", line 566, in draw
AttributeError: 'NoneType' object has no attribute 'erase'

# Fixed code
def keys(self):
    return list(sum(set(dir(obj)) for obj in self.objs))
# Buggy code
def __getitem__(self, k):
    for obj in self.objs:
        if k in dir(obj):
            return getattr(obj, k)
    raise KeyError(k)


# Traceback (AttributeError)
$ vd --debug -b -p newCol.vd
Think about what you're doing
opening newCol as vd
"."
opening . as dir
"1"
c=addColumn(SettableColumn("", width=options.default_width), cursorColIndex+1); draw(vd.scr); cursorVisibleColIndex=visibleCols.index(c); c.name=editCell(cursorVisibleColIndex, -1); c.width=None
AttributeError: 'NoneType' object has no attribute 'erase'
AttributeError: 'NoneType' object has no attribute 'erase'
Traceback (most recent call last):
File "/usr/local/bin/vd", line 4, in <module>
__import__('pkg_resources').run_script('visidata==1.6.dev0', 'vd')
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 664, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1451, in run_script
exec(script_code, namespace, namespace)
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 169, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 152, in main
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 289, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 455, in exceptionCaught
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 284, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 264, in replayOne
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1132, in exec_command
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1126, in exec_command
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/_sheet.py", line 566, in draw
AttributeError: 'NoneType' object has no attribute 'erase'

# Fixed code
def __getitem__(self, k):
    for obj in self.objs:
        if k in dir(obj):
            return getattr(obj, k)
    return self.locals[k]
# Buggy code
def __setitem__(self, k, v):
    for obj in self.objs:
        if k in dir(obj):
            return setattr(self.objs[0], k, v)
    return setattr(self.objs[-1], k, v)


# Traceback (AttributeError)
$ vd --debug -b -p newCol.vd
Think about what you're doing
opening newCol as vd
"."
opening . as dir
"1"
c=addColumn(SettableColumn("", width=options.default_width), cursorColIndex+1); draw(vd.scr); cursorVisibleColIndex=visibleCols.index(c); c.name=editCell(cursorVisibleColIndex, -1); c.width=None
AttributeError: 'NoneType' object has no attribute 'erase'
AttributeError: 'NoneType' object has no attribute 'erase'
Traceback (most recent call last):
File "/usr/local/bin/vd", line 4, in <module>
__import__('pkg_resources').run_script('visidata==1.6.dev0', 'vd')
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 664, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/cwarden/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1451, in run_script
exec(script_code, namespace, namespace)
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 169, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/EGG-INFO/scripts/vd", line 152, in main
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 289, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 455, in exceptionCaught
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 284, in replay_sync
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/cmdlog.py", line 264, in replayOne
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1132, in exec_command
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/__init__.py", line 1126, in exec_command
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/visidata-1.6.dev0-py3.6.egg/visidata/vdtui/_sheet.py", line 566, in draw
AttributeError: 'NoneType' object has no attribute 'erase'

# Fixed code
def __setitem__(self, k, v):
    for obj in self.objs:
        if k in dir(obj):
            return setattr(obj, k, v)
    self.locals[k] = v
# Buggy code
def _to_timestamp(dt: datetime.datetime):
    return timestamp_pb2.Timestamp(seconds=int(dt.timestamp()))


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/lingyihu/miniconda3/envs/recirq/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/home/lingyihu/miniconda3/envs/recirq/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/lingyihu/projects/ReCirq/recirq/quantum_chess/experiments/batch_moves.py", line 94, in <module>
main_loop(parse())
File "/home/lingyihu/projects/ReCirq/recirq/quantum_chess/experiments/batch_moves.py", line 60, in main_loop
available_processors = utils.get_available_processors(utils.QUANTUM_PROCESSORS.keys())
File "/home/lingyihu/projects/ReCirq/recirq/engine_utils.py", line 405, in get_available_processors
time_slot = EngineTimeSlot.from_proto(time_slot)
File "/home/lingyihu/miniconda3/envs/recirq/lib/python3.9/site-packages/cirq/google/engine/engine_timeslot.py", line 75, in from_proto
end_time=datetime.datetime.fromtimestamp(
ValueError: year 0 is out of range

# Fixed code
def _to_timestamp(dt: Optional[datetime.datetime]) -> Optional[timestamp_pb2.Timestamp]:
    if dt is not None:
        return timestamp_pb2.Timestamp(seconds=int(dt.timestamp()))
    return None
# Buggy code
def _main_shell_completion(self, prog_name, complete_var=None):
    """Check if the shell is asking for tab completion, process
    that, then exit early. Called from :meth:`main` before the
    program is invoked.

    :param prog_name: Name of the executable in the shell.
    :param complete_var: Name of the environment variable that holds
        the completion instruction. Defaults to
        ``_{PROG_NAME}_COMPLETE``.
    """
    if complete_var is None:
        complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()

    instruction = os.environ.get(complete_var)

    if not instruction:
        return

    from .shell_completion import shell_complete

    rv = shell_complete(self, prog_name, complete_var, instruction)
    _fast_exit(rv)


# Traceback (TypeError)
$ ./testclick subcommand <TAB>Traceback (most recent call last):
File "./testclick", line 23, in <module>
entrypoint(obj={'completions': ['abc', 'def', 'ghi', ]})
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 731, in __call__
return self.main(*args, **kwargs)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 701, in main
_bashcomplete(self, prog_name, complete_var)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 46, in _bashcomplete
if bashcomplete(cmd, prog_name, complete_var, complete_instr):
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 216, in bashcomplete
return do_complete(cli, prog_name)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 205, in do_complete
for item in get_choices(cli, prog_name, args, incomplete):
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 186, in get_choices
ctx, all_args, incomplete, param))
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 124, in get_user_autocompletions
incomplete=incomplete)
File "./testclick", line 7, in _complete
return ctx.obj['completions']
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def _main_shell_completion(self, ctx_args, prog_name, complete_var=None):
    """Check if the shell is asking for tab completion, process
    that, then exit early. Called from :meth:`main` before the
    program is invoked.

    :param prog_name: Name of the executable in the shell.
    :param complete_var: Name of the environment variable that holds
        the completion instruction. Defaults to
        ``_{PROG_NAME}_COMPLETE``.
    """
    if complete_var is None:
        complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()

    instruction = os.environ.get(complete_var)

    if not instruction:
        return

    from .shell_completion import shell_complete

    rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
    _fast_exit(rv)
# Buggy code
def __init__(self, cli, prog_name, complete_var):
    self.cli = cli
    self.prog_name = prog_name
    self.complete_var = complete_var


# Traceback (TypeError)
$ ./testclick subcommand <TAB>Traceback (most recent call last):
File "./testclick", line 23, in <module>
entrypoint(obj={'completions': ['abc', 'def', 'ghi', ]})
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 731, in __call__
return self.main(*args, **kwargs)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 701, in main
_bashcomplete(self, prog_name, complete_var)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 46, in _bashcomplete
if bashcomplete(cmd, prog_name, complete_var, complete_instr):
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 216, in bashcomplete
return do_complete(cli, prog_name)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 205, in do_complete
for item in get_choices(cli, prog_name, args, incomplete):
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 186, in get_choices
ctx, all_args, incomplete, param))
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 124, in get_user_autocompletions
incomplete=incomplete)
File "./testclick", line 7, in _complete
return ctx.obj['completions']
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def __init__(self, cli, ctx_args, prog_name, complete_var):
    self.cli = cli
    self.ctx_args = ctx_args
    self.prog_name = prog_name
    self.complete_var = complete_var
# Buggy code
def get_completions(self, args, incomplete):
    """Determine the context and last complete command or parameter
    from the complete args. Call that object's ``shell_complete``
    method to get the completions for the incomplete value.

    :param args: List of complete args before the incomplete value.
    :param incomplete: Value being completed. May be empty.
    """
    ctx = _resolve_context(self.cli, self.prog_name, args)

    if ctx is None:
        return []

    obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
    return obj.shell_complete(ctx, incomplete)


# Traceback (TypeError)
$ ./testclick subcommand <TAB>Traceback (most recent call last):
File "./testclick", line 23, in <module>
entrypoint(obj={'completions': ['abc', 'def', 'ghi', ]})
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 731, in __call__
return self.main(*args, **kwargs)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 701, in main
_bashcomplete(self, prog_name, complete_var)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/core.py", line 46, in _bashcomplete
if bashcomplete(cmd, prog_name, complete_var, complete_instr):
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 216, in bashcomplete
return do_complete(cli, prog_name)
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 205, in do_complete
for item in get_choices(cli, prog_name, args, incomplete):
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 186, in get_choices
ctx, all_args, incomplete, param))
File "/home/user/testclick/venv/lib/python3.6/site-packages/click/_bashcomplete.py", line 124, in get_user_autocompletions
incomplete=incomplete)
File "./testclick", line 7, in _complete
return ctx.obj['completions']
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def get_completions(self, args, incomplete):
    """Determine the context and last complete command or parameter
    from the complete args. Call that object's ``shell_complete``
    method to get the completions for the incomplete value.

    :param args: List of complete args before the incomplete value.
    :param incomplete: Value being completed. May be empty.
    """
    ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)

    if ctx is None:
        return []

    obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
    return obj.shell_complete(ctx, incomplete)
# Buggy code
def resolve_ctx(cli, prog_name, args):
    """
    Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
    :param cli: command definition
    :param prog_name: the program that is running
    :param args: full list of args
    :return: the final context/command parsed
    """
    ctx = cli.make_context(prog_name, args, resilient_parsing=True)
    args_remaining = ctx.protected_args + ctx.args
    while ctx is not None and args_remaining:
        if isinstance(ctx.command, MultiCommand):
            cmd = ctx.command.get_command(ctx, args_remaining[0])
            if cmd is None:
                return None
            ctx = cmd.make_context(
                args_remaining[0],
                args_remaining[1:],
                parent=ctx,
                resilient_parsing=True,
            )
            args_remaining = ctx.protected_args + ctx.args
        else:
            ctx = ctx.parent

    return ctx


# Traceback (AssertionError)
Traceback (most recent call last):
File "test_compl.py", line 19, in <module>
test_argument_choice()
File "test_compl.py", line 14, in test_argument_choice
assert list(get_choices(cli, 'lol', ['arg11'], '')) == ['arg21', 'arg22']
AssertionError

# Fixed code
def resolve_ctx(cli, prog_name, args):
    """
    Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
    :param cli: command definition
    :param prog_name: the program that is running
    :param args: full list of args
    :return: the final context/command parsed
    """
    ctx = cli.make_context(prog_name, args, resilient_parsing=True)
    args = ctx.protected_args + ctx.args
    while args:
        if isinstance(ctx.command, MultiCommand):
            if not ctx.command.chain:
                cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
                if cmd is None:
                    return ctx
                ctx = cmd.make_context(
                    cmd_name, args, parent=ctx, resilient_parsing=True
                )
                args = ctx.protected_args + ctx.args
            else:
                # Walk chained subcommand contexts saving the last one.
                while args:
                    cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
                    if cmd is None:
                        return ctx
                    sub_ctx = cmd.make_context(
                        cmd_name,
                        args,
                        parent=ctx,
                        allow_extra_args=True,
                        allow_interspersed_args=False,
                        resilient_parsing=True,
                    )
                    args = sub_ctx.args
                ctx = sub_ctx
                args = sub_ctx.protected_args + sub_ctx.args
        else:
            break
    return ctx
# Buggy code
def resolve_command(self, ctx, args):
    cmd_name = make_str(args[0])
    original_cmd_name = cmd_name

    # Get the command
    cmd = self.get_command(ctx, cmd_name)

    # If we can't find the command but there is a normalization
    # function available, we try with that one.
    if cmd is None and ctx.token_normalize_func is not None:
        cmd_name = ctx.token_normalize_func(cmd_name)
        cmd = self.get_command(ctx, cmd_name)

    # If we don't find the command we want to show an error message
    # to the user that it was not provided.  However, there is
    # something else we should do: if the first argument looks like
    # an option we want to kick off parsing again for arguments to
    # resolve things like --help which now should go to the main
    # place.
    if cmd is None:
        if split_opt(cmd_name)[0]:
            self.parse_args(ctx, ctx.args)
        ctx.fail('No such command "%s".' % original_cmd_name)

    return cmd_name, cmd, args[1:]


# Traceback (AssertionError)
Traceback (most recent call last):
File "test_compl.py", line 19, in <module>
test_argument_choice()
File "test_compl.py", line 14, in test_argument_choice
assert list(get_choices(cli, 'lol', ['arg11'], '')) == ['arg21', 'arg22']
AssertionError

# Fixed code
def resolve_command(self, ctx, args):
    cmd_name = make_str(args[0])
    original_cmd_name = cmd_name

    # Get the command
    cmd = self.get_command(ctx, cmd_name)

    # If we can't find the command but there is a normalization
    # function available, we try with that one.
    if cmd is None and ctx.token_normalize_func is not None:
        cmd_name = ctx.token_normalize_func(cmd_name)
        cmd = self.get_command(ctx, cmd_name)

    # If we don't find the command we want to show an error message
    # to the user that it was not provided.  However, there is
    # something else we should do: if the first argument looks like
    # an option we want to kick off parsing again for arguments to
    # resolve things like --help which now should go to the main
    # place.
    if cmd is None and not ctx.resilient_parsing:
        if split_opt(cmd_name)[0]:
            self.parse_args(ctx, ctx.args)
        ctx.fail('No such command "%s".' % original_cmd_name)

    return cmd_name, cmd, args[1:]
# Buggy code
def full_process_value(self, ctx, value):
    value = self.process_value(ctx, value)

    if value is None:
        value = self.get_default(ctx)

    if self.required and self.value_is_missing(value):
        raise MissingParameter(ctx=ctx, param=self)

    return value


# Traceback (AssertionError)
Traceback (most recent call last):
File "test_compl.py", line 19, in <module>
test_argument_choice()
File "test_compl.py", line 14, in test_argument_choice
assert list(get_choices(cli, 'lol', ['arg11'], '')) == ['arg21', 'arg22']
AssertionError

# Fixed code
def full_process_value(self, ctx, value):
    value = self.process_value(ctx, value)

    if value is None and not ctx.resilient_parsing:
        value = self.get_default(ctx)

    if self.required and self.value_is_missing(value):
        raise MissingParameter(ctx=ctx, param=self)

    return value
# Buggy code
def styleSheet(self) -> Optional[StyleSheet]:
    model = self.model
    style_sheet = next(model.select(StyleSheet), None)
    if not style_sheet:
        style_sheet = self.model.create(StyleSheet)
        style_sheet.styleSheet = DEFAULT_STYLE_SHEET
    return style_sheet


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/dan/Projects/gaphor/gaphor/ui/actiongroup.py", line 138, in _action_activate
method(from_variant(param))
File "/home/dan/Projects/gaphor/gaphor/ui/appfilemanager.py", line 121, in action_open_recent
self.load(filename)
File "/home/dan/Projects/gaphor/gaphor/ui/appfilemanager.py", line 49, in load
file_manager.load(filename)
File "/home/dan/Projects/gaphor/gaphor/ui/filemanager.py", line 109, in load
worker.reraise()
File "/home/dan/Projects/gaphor/gaphor/ui/gidlethread.py", line 115, in reraise
raise exc
File "/home/dan/Projects/gaphor/gaphor/ui/gidlethread.py", line 119, in __generator_executer
result = next(self._generator)
File "/home/dan/Projects/gaphor/gaphor/storage/storage.py", line 308, in load_generator
factory.model_ready()
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 159, in model_ready
self.handle(ModelReady(self))
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 182, in handle
self.event_manager.handle(event)
File "/home/dan/Projects/gaphor/gaphor/core/eventmanager.py", line 55, in handle
self._events.handle(e)
File "/home/dan/Projects/gaphor/.venv/lib/python3.9/site-packages/generic/event.py", line 64, in handle
handler(event)
File "/home/dan/Projects/gaphor/gaphor/ui/mainwindow.py", line 237, in _new_model_content
for diagram in self.element_factory.select(
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 116, in select
yield from (e for e in self._elements.values() if expression(e))
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 116, in <genexpr>
yield from (e for e in self._elements.values() if expression(e))
RuntimeError: OrderedDict mutated during iteration

# Fixed code
def styleSheet(self) -> Optional[StyleSheet]:
    return next(self.model.select(StyleSheet), None)
# Buggy code
def style(self, node: StyleNode) -> Style:
    style_sheet = self.styleSheet
    return {
        **FALLBACK_STYLE,  # type: ignore[misc]
        **style_sheet.match(node),
    }


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/dan/Projects/gaphor/gaphor/ui/actiongroup.py", line 138, in _action_activate
method(from_variant(param))
File "/home/dan/Projects/gaphor/gaphor/ui/appfilemanager.py", line 121, in action_open_recent
self.load(filename)
File "/home/dan/Projects/gaphor/gaphor/ui/appfilemanager.py", line 49, in load
file_manager.load(filename)
File "/home/dan/Projects/gaphor/gaphor/ui/filemanager.py", line 109, in load
worker.reraise()
File "/home/dan/Projects/gaphor/gaphor/ui/gidlethread.py", line 115, in reraise
raise exc
File "/home/dan/Projects/gaphor/gaphor/ui/gidlethread.py", line 119, in __generator_executer
result = next(self._generator)
File "/home/dan/Projects/gaphor/gaphor/storage/storage.py", line 308, in load_generator
factory.model_ready()
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 159, in model_ready
self.handle(ModelReady(self))
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 182, in handle
self.event_manager.handle(event)
File "/home/dan/Projects/gaphor/gaphor/core/eventmanager.py", line 55, in handle
self._events.handle(e)
File "/home/dan/Projects/gaphor/.venv/lib/python3.9/site-packages/generic/event.py", line 64, in handle
handler(event)
File "/home/dan/Projects/gaphor/gaphor/ui/mainwindow.py", line 237, in _new_model_content
for diagram in self.element_factory.select(
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 116, in select
yield from (e for e in self._elements.values() if expression(e))
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 116, in <genexpr>
yield from (e for e in self._elements.values() if expression(e))
RuntimeError: OrderedDict mutated during iteration

# Fixed code
def style(self, node: StyleNode) -> Style:
    style_sheet = self.styleSheet
    return {
        **FALLBACK_STYLE,  # type: ignore[misc]
        **(style_sheet.match(node) if style_sheet else {}),
    }
# Buggy code
def load_default_model(session):
    element_factory = session.get_service("element_factory")
    element_factory.flush()
    with element_factory.block_events():
        model = element_factory.create(UML.Package)
        model.name = gettext("New model")
        diagram = element_factory.create(UML.Diagram)
        diagram.package = model
        diagram.name = gettext("main")
    element_factory.model_ready()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/dan/Projects/gaphor/gaphor/ui/actiongroup.py", line 138, in _action_activate
method(from_variant(param))
File "/home/dan/Projects/gaphor/gaphor/ui/appfilemanager.py", line 121, in action_open_recent
self.load(filename)
File "/home/dan/Projects/gaphor/gaphor/ui/appfilemanager.py", line 49, in load
file_manager.load(filename)
File "/home/dan/Projects/gaphor/gaphor/ui/filemanager.py", line 109, in load
worker.reraise()
File "/home/dan/Projects/gaphor/gaphor/ui/gidlethread.py", line 115, in reraise
raise exc
File "/home/dan/Projects/gaphor/gaphor/ui/gidlethread.py", line 119, in __generator_executer
result = next(self._generator)
File "/home/dan/Projects/gaphor/gaphor/storage/storage.py", line 308, in load_generator
factory.model_ready()
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 159, in model_ready
self.handle(ModelReady(self))
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 182, in handle
self.event_manager.handle(event)
File "/home/dan/Projects/gaphor/gaphor/core/eventmanager.py", line 55, in handle
self._events.handle(e)
File "/home/dan/Projects/gaphor/.venv/lib/python3.9/site-packages/generic/event.py", line 64, in handle
handler(event)
File "/home/dan/Projects/gaphor/gaphor/ui/mainwindow.py", line 237, in _new_model_content
for diagram in self.element_factory.select(
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 116, in select
yield from (e for e in self._elements.values() if expression(e))
File "/home/dan/Projects/gaphor/gaphor/core/modeling/elementfactory.py", line 116, in <genexpr>
yield from (e for e in self._elements.values() if expression(e))
RuntimeError: OrderedDict mutated during iteration

# Fixed code
def load_default_model(session):
    element_factory = session.get_service("element_factory")
    element_factory.flush()
    with element_factory.block_events():
        element_factory.create(StyleSheet)
        model = element_factory.create(UML.Package)
        model.name = gettext("New model")
        diagram = element_factory.create(UML.Diagram)
        diagram.package = model
        diagram.name = gettext("main")
    element_factory.model_ready()
# Buggy code
def namespace_popup_model(self):
    assert self.view
    model = Gio.Menu.new()

    part = Gio.Menu.new()
    part.append(gettext("_Open"), "tree-view.open")
    part.append(gettext("_Rename"), "tree-view.rename")
    model.append_section(None, part)

    part = Gio.Menu.new()
    part.append(gettext("New _Diagram"), "tree-view.create-diagram")
    part.append(gettext("New _Package"), "tree-view.create-package")
    model.append_section(None, part)

    part = Gio.Menu.new()
    part.append(gettext("De_lete"), "tree-view.delete")
    model.append_section(None, part)

    element = self.view.get_selected_element()

    part = Gio.Menu.new()
    for presentation in element.presentation:
        diagram = presentation.diagram
        menu_item = Gio.MenuItem.new(
            gettext('Show in "{diagram}"').format(diagram=diagram.name),
            "tree-view.show-in-diagram",
        )
        menu_item.set_attribute_value("target", GLib.Variant.new_string(diagram.id))
        part.append_item(menu_item)

        # Play it safe with an (arbitrary) upper bound
        if part.get_n_items() > 29:
            break

    if part.get_n_items() > 0:
        model.append_section(None, part)
    return model


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/dan/Projects/gaphor/gaphor/ui/namespace.py", line 568, in _on_view_event
menu = Gtk.Menu.new_from_model(self.namespace_popup_model())
File "/home/dan/Projects/gaphor/gaphor/ui/namespace.py", line 544, in namespace_popup_model
gettext('Show in "{diagram}"').format(diagram=diagram.name),
AttributeError: 'NoneType' object has no attribute 'name'

# Fixed code
def namespace_popup_model(self):
    assert self.view
    model = Gio.Menu.new()

    part = Gio.Menu.new()
    part.append(gettext("_Open"), "tree-view.open")
    part.append(gettext("_Rename"), "tree-view.rename")
    model.append_section(None, part)

    part = Gio.Menu.new()
    part.append(gettext("New _Diagram"), "tree-view.create-diagram")
    part.append(gettext("New _Package"), "tree-view.create-package")
    model.append_section(None, part)

    part = Gio.Menu.new()
    part.append(gettext("De_lete"), "tree-view.delete")
    model.append_section(None, part)

    element = self.view.get_selected_element()

    part = Gio.Menu.new()
    for presentation in element.presentation:
        diagram = presentation.diagram
        if diagram:
            menu_item = Gio.MenuItem.new(
                gettext('Show in "{diagram}"').format(diagram=diagram.name),
                "tree-view.show-in-diagram",
            )
            menu_item.set_attribute_value("target", GLib.Variant.new_string(diagram.id))
            part.append_item(menu_item)

        # Play it safe with an (arbitrary) upper bound
        if part.get_n_items() > 29:
            break

    if part.get_n_items() > 0:
        model.append_section(None, part)
    return model
# Buggy code
def create_as(self, type, id, parent=None, subject=None):
    item = type(id, self.model)
    if subject:
        item.subject = subject
    self.canvas.add(item, parent)
    self.model.handle(DiagramItemCreated(self.model, item))
    return item


# Traceback (AttributeError)
gaphor.storage.storage INFO Loading file deployment_diagram.gaphor
gaphor.storage.parser ERROR File corrupted, remove element 8cef44be-7376-11ea-80af-e4f89cae6ece and try again
NoneType: None
gaphor.storage.storage INFO Read 140 elements from file
gaphor.storage.storage WARNING file b'/home/lie/projects/test/deployment_diagram.gaphor' could not be loaded (module 'gaphor.UML' has no attribute 'CommentItem')
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/gaphor/misc/gidlethread.py", line 127, in __generator_executer
result = next(self._generator)
File "/usr/lib/python3.8/site-packages/gaphor/storage/storage.py", line 311, in load_generator
for percentage in load_elements_generator(
File "/usr/lib/python3.8/site-packages/gaphor/storage/storage.py", line 182, in load_elements_generator
yield from _load_elements_and_canvasitems(
File "/usr/lib/python3.8/site-packages/gaphor/storage/storage.py", line 222, in _load_elements_and_canvasitems
cls = getattr(UML, elem.type)
AttributeError: module 'gaphor.UML' has no attribute 'CommentItem'

# Fixed code
def create_as(self, type, id, parent=None, subject=None):
    if not type or not issubclass(type, gaphas.Item):
        raise TypeError(
            f"Type {type} can not be added to a diagram as it is not a diagram item"
        )
    item = type(id, self.model)
    if subject:
        item.subject = subject
    self.canvas.add(item, parent)
    self.model.handle(DiagramItemCreated(self.model, item))
    return item
# Buggy code
def create_as(self, type: Type[T], id: str) -> T:
    """
    Create a new model element of type 'type' with 'id' as its ID.
    This method should only be used when loading models, since it does
    not emit an ElementCreated event.
    """
    assert issubclass(type, Element)
    obj = type(id, self)
    self._elements[id] = obj
    return obj


# Traceback (AttributeError)
gaphor.storage.storage INFO Loading file deployment_diagram.gaphor
gaphor.storage.parser ERROR File corrupted, remove element 8cef44be-7376-11ea-80af-e4f89cae6ece and try again
NoneType: None
gaphor.storage.storage INFO Read 140 elements from file
gaphor.storage.storage WARNING file b'/home/lie/projects/test/deployment_diagram.gaphor' could not be loaded (module 'gaphor.UML' has no attribute 'CommentItem')
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/gaphor/misc/gidlethread.py", line 127, in __generator_executer
result = next(self._generator)
File "/usr/lib/python3.8/site-packages/gaphor/storage/storage.py", line 311, in load_generator
for percentage in load_elements_generator(
File "/usr/lib/python3.8/site-packages/gaphor/storage/storage.py", line 182, in load_elements_generator
yield from _load_elements_and_canvasitems(
File "/usr/lib/python3.8/site-packages/gaphor/storage/storage.py", line 222, in _load_elements_and_canvasitems
cls = getattr(UML, elem.type)
AttributeError: module 'gaphor.UML' has no attribute 'CommentItem'

# Fixed code
def create_as(self, type: Type[T], id: str) -> T:
    """
    Create a new model element of type 'type' with 'id' as its ID.
    This method should only be used when loading models, since it does
    not emit an ElementCreated event.
    """
    if not type or not issubclass(type, Element) or issubclass(type, Presentation):
        raise TypeError(f"Type {type} is not a valid model element")
    obj = type(id, self)
    self._elements[id] = obj
    return obj
# Buggy code
def _on_name_change(self, event):
    if event.property is UML.Diagram.name:
        for page in range(0, self._notebook.get_n_pages()):
            widget = self._notebook.get_nth_page(page)
            if event.element is widget.diagram_page.diagram:
                print("Name change", event.__dict__)
                self._notebook.set_tab_label(
                    widget, self.tab_label(event.new_value, widget)
                )


# Traceback (AttributeError)
gaphor.transaction ERROR Transaction terminated due to an exception, performing a rollback
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/action.py", line 179, in _action_activate
method()
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
``

### System Information
OS:
- [X] Linux (Please put in notes the specific distro)
- [ ] MacOS
- [ ] Windows 10
- [ ] Windows 7

NOTES:

# Fixed code
def _on_name_change(self, event):
    if event.property is UML.Diagram.name:
        for page in range(0, self._notebook.get_n_pages()):
            widget = self._notebook.get_nth_page(page)
            if event.element is widget.diagram_page.diagram:
                self._notebook.set_tab_label(
                    widget, self.tab_label(event.new_value, widget)
                )
# Buggy code
def iter_for_element(self, element, old_namespace=0):
    # Using `0` as sentinel
    if old_namespace != 0:
        parent_iter = self.iter_for_element(old_namespace)
    elif element and element.namespace:
        parent_iter = self.iter_for_element(element.namespace)
    else:
        parent_iter = None

    child_iter = self.model.iter_children(parent_iter)
    while child_iter:
        if self.model.get_value(child_iter, 0) is element:
            return child_iter
        child_iter = self.model.iter_next(child_iter)
    return None


# Traceback (AttributeError)
gaphor.transaction ERROR Transaction terminated due to an exception, performing a rollback
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/action.py", line 179, in _action_activate
method()
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
``

### System Information
OS:
- [X] Linux (Please put in notes the specific distro)
- [ ] MacOS
- [ ] Windows 10
- [ ] Windows 7

NOTES:

# Fixed code
def iter_for_element(self, element, old_namespace=0):
    """Get the Gtk.TreeIter for an element in the Namespace.

    Args:
        element: The element contained in the in the Namespace.
        old_namespace: The old namespace containing the element, optional.

    Returns: Gtk.TreeIter object
    """

    # Using `0` as sentinel
    if old_namespace != 0:
        parent_iter = self.iter_for_element(old_namespace)
    elif element and element.namespace:
        parent_iter = self.iter_for_element(element.namespace)
    else:
        parent_iter = None

    child_iter = self.model.iter_children(parent_iter)
    while child_iter:
        if self.model.get_value(child_iter, 0) is element:
            return child_iter
        child_iter = self.model.iter_next(child_iter)
    return None
# Buggy code
def _on_element_delete(self, event):
    element = event.element
    if type(element) in self.filter:
        iter = self.iter_for_element(element)
        # iter should be here, unless we try to delete an element who's parent element is already deleted, so let's be lenient.
        if iter:
            self.model.remove(iter)


# Traceback (AttributeError)
gaphor.transaction ERROR Transaction terminated due to an exception, performing a rollback
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/action.py", line 179, in _action_activate
method()
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
``

### System Information
OS:
- [X] Linux (Please put in notes the specific distro)
- [ ] MacOS
- [ ] Windows 10
- [ ] Windows 7

NOTES:

# Fixed code
def _on_element_delete(self, event):
    element = event.element
    if type(element) in self.filter:
        iter = self.iter_for_element(element)
        # iter should be here, unless we try to delete an element who's
        # parent element is already deleted, so let's be lenient.
        if iter:
            self.model.remove(iter)
# Buggy code
def select_element(self, element):
    """
    Select an element from the Namespace view.
    The element is selected. After this an action may be executed,
    such as OpenModelElement, which will try to open the element (if it's
    a Diagram).
    """
    path = Gtk.TreePath.new_from_indices(
        self._namespace.get_model().path_from_element(element)
    )
    # Expand the first row:
    if len(path.get_indices()) > 1:
        self._namespace.expand_row(path=path, open_all=False)
    selection = self._namespace.get_selection()
    selection.select_path(path)
    self._on_view_cursor_changed(self._namespace)


# Traceback (AttributeError)
gaphor.transaction ERROR Transaction terminated due to an exception, performing a rollback
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/action.py", line 179, in _action_activate
method()
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
``

### System Information
OS:
- [X] Linux (Please put in notes the specific distro)
- [ ] MacOS
- [ ] Windows 10
- [ ] Windows 7

NOTES:

# Fixed code
def select_element(self, element):
    """Select an element from the Namespace view.

    The element is selected. After this an action may be executed,
    such as OpenModelElement, which will try to open the element (if it's
    a Diagram).
    """

    tree_iter = self.iter_for_element(element)
    path = self.model.get_path(tree_iter)
    path_indices = path.get_indices()

    # Expand the parent row
    if len(path_indices) > 1:
        parent_path = Gtk.TreePath.new_from_indices(path_indices[:-1])
        self._namespace.expand_row(path=parent_path, open_all=False)

    selection = self._namespace.get_selection()
    selection.select_path(path)
    self._on_view_cursor_changed(self._namespace)