gurudesh/pytracebugs huggingface dataset:
# Buggy code
def visit_yield_expr(self, expr: YieldExpr) -> None:
    if not self.is_func_scope():
        self.fail("'yield' outside function", expr)
    else:
        self.function_stack[-1].is_generator = True
    if expr.expr:
        expr.expr.accept(self)


# Traceback (IndexError)
Traceback (most recent call last):
File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module>
main(__file__)
[...]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt
self.binder.allow_jump(self.binder.loop_frames[-1] - 1)
IndexError: list index out of range

*** INTERNAL ERROR ***

break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues

NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.

# Fixed code
def visit_yield_expr(self, expr: YieldExpr) -> None:
    if not self.is_func_scope():
        self.fail("'yield' outside function", expr, True, blocker=True)
    else:
        self.function_stack[-1].is_generator = True
    if expr.expr:
        expr.expr.accept(self)
# Buggy code
def fail(self, msg: str, ctx: Context, serious: bool = False) -> None:
    if (
        not serious
        and not self.check_untyped_defs
        and self.function_stack
        and self.function_stack[-1].is_dynamic()
    ):
        return
    self.errors.report(ctx.get_line(), msg)


# Traceback (IndexError)
Traceback (most recent call last):
File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module>
main(__file__)
[...]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt
self.binder.allow_jump(self.binder.loop_frames[-1] - 1)
IndexError: list index out of range

*** INTERNAL ERROR ***

break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues

NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.

# Fixed code
def fail(
    self, msg: str, ctx: Context, serious: bool = False, *, blocker: bool = False
) -> None:
    if (
        not serious
        and not self.check_untyped_defs
        and self.function_stack
        and self.function_stack[-1].is_dynamic()
    ):
        return
    self.errors.report(ctx.get_line(), msg, blocker=blocker)
# Buggy code
def visit_for_stmt(self, s: ForStmt) -> None:
    self.analyze_lvalue(s.index)
    s.body.accept(self)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/bin/mypy", line 6, in <module>
main(__file__)
File "/usr/lib/python3.5/site-packages/mypy/main.py", line 54, in main
res = type_check_only(sources, bin_dir, options)
File "/usr/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only
python_path=options.python_path)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 209, in build
dispatch(sources, manager)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch
process_graph(graph, manager)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph
process_stale_scc(graph, scc)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1412, in process_stale_scc
graph[id].semantic_analysis()
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1222, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 241, in visit_file
self.accept(d)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept
node.accept(self)
File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 783, in accept
return visitor.visit_while_stmt(self)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1620, in visit_while_stmt
s.body.accept(self)
File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept
return visitor.visit_block(self)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1003, in visit_block
self.accept(s)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept
node.accept(self)
File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept
return visitor.visit_func_def(self)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 295, in visit_func_def
if isinstance(symbol.node, FuncDef) and symbol.node != defn:
AttributeError: 'NoneType' object has no attribute 'node'

*** INTERNAL ERROR ***

# Fixed code
def visit_for_stmt(self, s: ForStmt) -> None:
    self.analyze_lvalue(s.index)
    s.body.accept(self)
    if s.else_body:
        s.else_body.accept(self)
# Buggy code
def visit_while_stmt(self, s: WhileStmt) -> None:
    s.expr.accept(self)
    self.loop_depth += 1
    s.body.accept(self)
    self.loop_depth -= 1
    self.visit_block_maybe(s.else_body)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/bin/mypy", line 6, in <module>
main(__file__)
File "/usr/lib/python3.5/site-packages/mypy/main.py", line 54, in main
res = type_check_only(sources, bin_dir, options)
File "/usr/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only
python_path=options.python_path)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 209, in build
dispatch(sources, manager)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch
process_graph(graph, manager)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph
process_stale_scc(graph, scc)
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1412, in process_stale_scc
graph[id].semantic_analysis()
File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1222, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 241, in visit_file
self.accept(d)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept
node.accept(self)
File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 783, in accept
return visitor.visit_while_stmt(self)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1620, in visit_while_stmt
s.body.accept(self)
File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept
return visitor.visit_block(self)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1003, in visit_block
self.accept(s)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept
node.accept(self)
File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept
return visitor.visit_func_def(self)
File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 295, in visit_func_def
if isinstance(symbol.node, FuncDef) and symbol.node != defn:
AttributeError: 'NoneType' object has no attribute 'node'

*** INTERNAL ERROR ***

# Fixed code
def visit_while_stmt(self, s: WhileStmt) -> None:
    s.body.accept(self)
    if s.else_body:
        s.else_body.accept(self)
# Buggy code
def visit_assignment_stmt(self, s: AssignmentStmt) -> Type:
    """Type check an assignment statement.

    Handle all kinds of assignment statements (simple, indexed, multiple).
    """
    self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None)

    if len(s.lvalues) > 1:
        # Chained assignment (e.g. x = y = ...).
        # Make sure that rvalue type will not be reinferred.
        rvalue = self.temp_node(self.type_map[s.rvalue], s)
        for lv in s.lvalues[:-1]:
            self.check_assignment(lv, rvalue, s.type is None)


# Traceback (KeyError)
Traceback (most recent call last):
  File "/Users/me/py-env/crf/bin/mypy", line 6, in <module>
    main(__file__)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/main.py", line 49, in main
    type_check_only(sources, bin_dir, options)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/main.py", line 92, in type_check_only
    python_path=options.python_path)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/build.py", line 196, in build
    result = manager.process(initial_states)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/build.py", line 378, in process
    next.process()
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/build.py", line 832, in process
    self.type_checker().visit_file(self.tree, self.tree.path)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/checker.py", line 371, in visit_file
    self.accept(d)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/checker.py", line 378, in accept
    typ = node.accept(self)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/nodes.py", line 538, in accept
    return visitor.visit_assignment_stmt(self)
  File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/checker.py", line 954, in visit_assignment_stmt
    rvalue = self.temp_node(self.type_map[s.rvalue], s)
KeyError: <mypy.nodes.TupleExpr object at 0x1017950b8>

# Fixed code
def visit_assignment_stmt(self, s: AssignmentStmt) -> Type:
    """Type check an assignment statement.

    Handle all kinds of assignment statements (simple, indexed, multiple).
    """
    self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None)

    if len(s.lvalues) > 1:
        # Chained assignment (e.g. x = y = ...).
        # Make sure that rvalue type will not be reinferred.
        if s.rvalue not in self.type_map:
            self.accept(s.rvalue)
        rvalue = self.temp_node(self.type_map[s.rvalue], s)
        for lv in s.lvalues[:-1]:
            self.check_assignment(lv, rvalue, s.type is None)
# Buggy code
def remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None:
    """Remove all imported names from the symbol table of a module."""
    removed = []  # type: List[str]
    for name, node in names.items():
        fullname = node.node.fullname()
        prefix = fullname[: fullname.rfind(".")]
        if prefix != module:
            removed.append(name)
    for name in removed:
        del names[name]


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/mypy", line 6, in <module>
main(__file__)
File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 53, in main
type_check_only(sources, bin_dir, options)
File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 96, in type_check_only
python_path=options.python_path)
File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 203, in build
result = manager.process(initial_states)
File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 386, in process
next.process()
File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 846, in process
main(__file__)
File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 53, in main
type_check_only(sources, bin_dir, options)
File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 96, in type_check_only
python_path=options.python_path)
File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 203, in build
result = manager.process(initial_states)
File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 386, in process
next.process()
File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 846, in process
self.semantic_analyzer().visit_file(self.tree, self.tree.path)
File "/usr/local/lib/python3.4/dist-packages/mypy/semanal.py", line 213, in visit_file
remove_imported_names_from_symtable(self.globals, 'builtins')
File "/usr/local/lib/python3.4/dist-packages/mypy/semanal.py", line 2445, in remove_imported_names_from_symtable
fullname = node.node.fullname()
AttributeError: 'NoneType' object has no attribute 'fullname'

# Fixed code
def remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None:
    """Remove all imported names from the symbol table of a module."""
    removed = []  # type: List[str]
    for name, node in names.items():
        if node.node is None:
            continue
        fullname = node.node.fullname()
        prefix = fullname[: fullname.rfind(".")]
        if prefix != module:
            removed.append(name)
    for name in removed:
        del names[name]
# Buggy code
def visit_block(self, b: Block) -> None:
    if b.is_unreachable:
        return
    self.sem.block_depth[-1] += 1
    for node in b.body:
        node.accept(self)
    self.sem.block_depth[-1] -= 1


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/samuel/code/harrier/env/bin/mypy", line 6, in <module>
main(__file__)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/main.py", line 54, in main
type_check_only(sources, bin_dir, options)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/main.py", line 98, in type_check_only
python_path=options.python_path)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/build.py", line 206, in build
result = manager.process(initial_states)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/build.py", line 403, in process
next.process()
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/build.py", line 894, in process
self.semantic_analyzer_pass3().visit_file(self.tree, self.tree.path)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/semanal.py", line 2341, in visit_file
file_node.accept(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 171, in accept
return visitor.visit_mypy_file(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 34, in visit_mypy_file
d.accept(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 673, in accept
return visitor.visit_if_stmt(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 110, in visit_if_stmt
o.else_body.accept(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 526, in accept
return visitor.visit_block(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 38, in visit_block
s.accept(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 673, in accept
return visitor.visit_if_stmt(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 110, in visit_if_stmt
o.else_body.accept(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 526, in accept
return visitor.visit_block(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 38, in visit_block
s.accept(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 485, in accept
return visitor.visit_class_def(self)
File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/semanal.py", line 2350, in visit_class_def
for type in tdef.info.bases:
AttributeError: 'NoneType' object has no attribute 'bases'

# Fixed code
def visit_block(self, b: Block) -> None:
    if b.is_unreachable:
        return
    super().visit_block(b)
# Buggy code
def read_program(path: str, pyversion: Tuple[int, int]) -> str:
    try:
        text = read_with_python_encoding(path, pyversion)
    except IOError as ioerr:
        raise CompileError(
            ["mypy: can't read file '{}': {}".format(path, ioerr.strerror)]
        )
    return text


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/local/bin/mypy", line 6, in <module>
main(__file__)
File "/usr/local/lib/python3.5/dist-packages/mypy/main.py", line 54, in main
type_check_only(sources, bin_dir, options)
File "/usr/local/lib/python3.5/dist-packages/mypy/main.py", line 98, in type_check_only
python_path=options.python_path)
File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 200, in build
content = source.load(lib_path, pyversion)
File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 110, in load
return read_program(self.path, pyversion)
File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 292, in read_program
text = read_with_python_encoding(path, pyversion)
File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 1094, in read_with_python_encoding
return source_bytearray.decode(encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 1: ordinal not in range(128)

# Fixed code
def read_program(path: str, pyversion: Tuple[int, int]) -> str:
    try:
        text = read_with_python_encoding(path, pyversion)
    except IOError as ioerr:
        raise CompileError(
            ["mypy: can't read file '{}': {}".format(path, ioerr.strerror)]
        )
    except UnicodeDecodeError as decodeerr:
        raise CompileError(
            ["mypy: can't decode file '{}': {}".format(path, str(decodeerr))]
        )
    return text
# Buggy code
def analyze_typevar_declaration(self, t: Type) -> List[Tuple[str, TypeVarExpr]]:
    if not isinstance(t, UnboundType):
        return None
    unbound = cast(UnboundType, t)
    sym = self.lookup_qualified(unbound.name, unbound)
    if sym is None:
        return None
    if sym.node.fullname() == "typing.Generic":
        tvars = []  # type: List[Tuple[str, TypeVarExpr]]
        for arg in unbound.args:
            tvar = self.analyze_unbound_tvar(arg)
            if tvar:
                tvars.append(tvar)
            else:
                self.fail("Free type variable expected in %s[...]" % sym.node.name(), t)
        return tvars
    return None


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/guido/src/mypy/scripts/mypy", line 6, in <module>
main(__file__)
File "/Users/guido/src/mypy/mypy/main.py", line 49, in main
type_check_only(sources, bin_dir, options)
File "/Users/guido/src/mypy/mypy/main.py", line 92, in type_check_only
python_path=options.python_path)
File "/Users/guido/src/mypy/mypy/build.py", line 197, in build
result = manager.process(initial_states)
File "/Users/guido/src/mypy/mypy/build.py", line 383, in process
next.process()
File "/Users/guido/src/mypy/mypy/build.py", line 823, in process
self.semantic_analyzer().visit_file(self.tree, self.tree.path)
File "/Users/guido/src/mypy/mypy/semanal.py", line 210, in visit_file
d.accept(self)
File "/Users/guido/src/mypy/mypy/nodes.py", line 483, in accept
return visitor.visit_class_def(self)
File "/Users/guido/src/mypy/mypy/semanal.py", line 460, in visit_class_def
self.clean_up_bases_and_infer_type_variables(defn)
File "/Users/guido/src/mypy/mypy/semanal.py", line 593, in clean_up_bases_and_infer_type_variables
tvars = self.analyze_typevar_declaration(base)
File "/Users/guido/src/mypy/mypy/semanal.py", line 615, in analyze_typevar_declaration
if sym.node.fullname() == 'typing.Generic':
AttributeError: 'NoneType' object has no attribute 'fullname'

# Fixed code
def analyze_typevar_declaration(
    self, t: Type
) -> Optional[List[Tuple[str, TypeVarExpr]]]:
    if not isinstance(t, UnboundType):
        return None
    unbound = cast(UnboundType, t)
    sym = self.lookup_qualified(unbound.name, unbound)
    if sym is None or sym.node is None:
        return None
    if sym.node.fullname() == "typing.Generic":
        tvars = []  # type: List[Tuple[str, TypeVarExpr]]
        for arg in unbound.args:
            tvar = self.analyze_unbound_tvar(arg)
            if tvar:
                tvars.append(tvar)
            else:
                self.fail("Free type variable expected in %s[...]" % sym.node.name(), t)
        return tvars
    return None
# Buggy code
def visit_type_var(self, template: TypeVarType) -> List[Constraint]:
    return [Constraint(template.id, self.direction, self.actual)]


# Traceback (AttributeError)
Traceback (most recent call last):
File "scripts/mypy", line 182, in <module>
main()
File "scripts/mypy", line 36, in main
type_check_only(path, module, bin_dir, options)
File "scripts/mypy", line 80, in type_check_only
python_path=options.python_path)
File "/home/jukka/project/mypy/mypy/build.py", line 164, in build
result = manager.process(UnprocessedFile(info, program_text))
File "/home/jukka/project/mypy/mypy/build.py", line 341, in process
next.process()
File "/home/jukka/project/mypy/mypy/build.py", line 814, in process
self.type_checker().visit_file(self.tree, self.tree.path)
File "/home/jukka/project/mypy/mypy/checker.py", line 350, in visit_file
self.accept(d)
File "/home/jukka/project/mypy/mypy/checker.py", line 357, in accept
typ = node.accept(self)
File "/home/jukka/project/mypy/mypy/nodes.py", line 519, in accept
return visitor.visit_expression_stmt(self)
File "/home/jukka/project/mypy/mypy/checker.py", line 1302, in visit_expression_stmt
self.accept(s.expr)
File "/home/jukka/project/mypy/mypy/checker.py", line 357, in accept
typ = node.accept(self)
File "/home/jukka/project/mypy/mypy/nodes.py", line 938, in accept
return visitor.visit_call_expr(self)
File "/home/jukka/project/mypy/mypy/checker.py", line 1709, in visit_call_expr
result = self.expr_checker.visit_call_expr(e)
File "/home/jukka/project/mypy/mypy/checkexpr.py", line 118, in visit_call_expr
return self.check_call_expr_with_callee_type(callee_type, e)
File "/home/jukka/project/mypy/mypy/checkexpr.py", line 128, in check_call_expr_with_callee_type
e.arg_names, callable_node=e.callee)[0]
File "/home/jukka/project/mypy/mypy/checkexpr.py", line 171, in check_call
callee, args, arg_kinds, formal_to_actual, context)
File "/home/jukka/project/mypy/mypy/checkexpr.py", line 351, in infer_function_type_arguments
callee_type, pass1_args, arg_kinds, formal_to_actual)  # type: List[Type]
File "/home/jukka/project/mypy/mypy/infer.py", line 33, in infer_function_type_arguments
return solve_constraints(type_vars, constraints)
File "/home/jukka/project/mypy/mypy/solve.py", line 41, in solve_constraints
bottom = join_types(bottom, c.target)
File "/home/jukka/project/mypy/mypy/join.py", line 68, in join_types
return t.accept(TypeJoinVisitor(s))
AttributeError: 'NoneType' object has no attribute 'accept'

# Fixed code
def visit_type_var(self, template: TypeVarType) -> List[Constraint]:
    if self.actual:
        return [Constraint(template.id, self.direction, self.actual)]
    else:
        return []
# Buggy code
def copy(self):
    """Return a shallow copy of the instance."""
    rv = self.__class__(self.capacity)
    rv._mapping.update(self._mapping)
    rv._queue = deque(self._queue)
    return rv


# Traceback (IndexError)
from jinja2 import utils
cache = utils.LRUCache(1)
cache['foo'] = 'bar'
copy = cache.copy()
copy['blah'] = 'blargh'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "jinja2/utils.py", line 424, in __setitem__
del self._mapping[self._popleft()]
IndexError: pop from an empty deque
copy._popleft
<built-in method popleft of collections.deque object at 0x10160d670>
copy._queue.popleft
<built-in method popleft of collections.deque object at 0x101635360>

# Fixed code
def copy(self):
    """Return a shallow copy of the instance."""
    rv = self.__class__(self.capacity)
    rv._mapping.update(self._mapping)
    rv._queue.extend(self._queue)
    return rv
# Buggy code
def open_if_exists(filename, mode="rb"):
    """Returns a file descriptor for the filename if that file exists,
    otherwise `None`.
    """
    try:
        return open(filename, mode)
    except IOError as e:
        if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL):
            raise


# Traceback (IOError)
IOError: [Errno 20] Not a directory: 'dir1/foo/test'
from jinja2 import FileSystemLoader, Environment
loader = FileSystemLoader(['dir1', 'dir2'])
env = Environment(loader=loader)
env.get_template('foo/test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 830, in get_template
return self._load_template(name, self.make_globals(globals))
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 804, in _load_template
template = self.loader.load(self, name, globals)
File "/usr/lib/python2.7/site-packages/jinja2/loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "/usr/lib/python2.7/site-packages/jinja2/loaders.py", line 171, in get_source
f = open_if_exists(filename)
File "/usr/lib/python2.7/site-packages/jinja2/utils.py", line 154, in open_if_exists
return open(filename, mode)
IOError: [Errno 20] Not a directory: 'dir1/foo/test'

# Fixed code
def open_if_exists(filename, mode="rb"):
    """Returns a file descriptor for the filename if that file exists,
    otherwise ``None``.
    """
    if not os.path.isfile(filename):
        return None

    return open(filename, mode)
# Buggy code
def __init__(self, environment, parent, name, blocks):
    self.parent = parent
    self.vars = {}
    self.environment = environment
    self.eval_ctx = EvalContext(self.environment, name)
    self.exported_vars = set()
    self.name = name

    # create the initial mapping of blocks.  Whenever template inheritance
    # takes place the runtime will update this mapping with the new blocks
    # from the template.
    self.blocks = dict((k, [v]) for k, v in iteritems(blocks))

    # In case we detect the fast resolve mode we can set up an alias
    # here that bypasses the legacy code logic.
    if self._fast_resolve_mode:
        self.resolve_or_missing = resolve_or_missing


# Traceback (TypeError)
Traceback (most recent call last):
File "test.py", line 16, in <module>
print env.get_template('test').render(foobar='test')
File "/home/adrian/dev/indico/env/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/home/adrian/dev/indico/env/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 1, in top-level template code
File "<template>", line 1, in top-level template code
TypeError: resolve_or_missing() takes at least 2 arguments (1 given)

# Fixed code
def __init__(self, environment, parent, name, blocks):
    self.parent = parent
    self.vars = {}
    self.environment = environment
    self.eval_ctx = EvalContext(self.environment, name)
    self.exported_vars = set()
    self.name = name

    # create the initial mapping of blocks.  Whenever template inheritance
    # takes place the runtime will update this mapping with the new blocks
    # from the template.
    self.blocks = dict((k, [v]) for k, v in iteritems(blocks))

    # In case we detect the fast resolve mode we can set up an alias
    # here that bypasses the legacy code logic.
    if self._fast_resolve_mode:
        self.resolve_or_missing = MethodType(resolve_or_missing, self)
# Buggy code
def parseImageBookmark(page):
    imageList = list()

    image_bookmark = json.loads(page)
    for work in image_bookmark["body"]["works"]:
        if "isAdContainer" in work and work["isAdContainer"]:
            continue
        imageList.append(int(work["illustId"]))

    # temp = page.find('ul', attrs={'class': PixivBookmark.__re_imageULItemsClass})
    # temp = temp.findAll('a')
    # if temp is None or len(temp) == 0:
    #     return imageList
    # for item in temp:
    #     href = re.search(r'/artworks/(\d+)', str(item))
    #     if href is not None:
    #         href = href.group(1)
    #         if not int(href) in imageList:
    #             imageList.append(int(href))

    return imageList


# Traceback (KeyError)
Importing image bookmarks...
Importing user's bookmarked image from page 1
Source URL: https://www.pixiv.net/ajax/user/XXXXXXXX/illusts/bookmarks?tag=&amp;offset=0&amp;limit=48&amp;rest=show
Error at process_image_bookmark(): (<class 'KeyError'>, KeyError('illustId'), <traceback object at 0x044FB988>)
Traceback (most recent call last):
File "PixivUtil2.py", line 1252, in main
File "PixivUtil2.py", line 964, in main_loop
File "PixivUtil2.py", line 520, in menu_download_from_online_image_bookmark
File "PixivBookmarkHandler.pyc", line 73, in process_image_bookmark
File "PixivBookmarkHandler.pyc", line 342, in get_image_bookmark
File "PixivBookmark.pyc", line 64, in parseImageBookmark
KeyError: 'illustId'

# Fixed code
def parseImageBookmark(page):
    imageList = list()

    image_bookmark = json.loads(page)
    for work in image_bookmark["body"]["works"]:
        if "isAdContainer" in work and work["isAdContainer"]:
            continue
        # Issue #822
        if "illustId" in work:
            imageList.append(int(work["illustId"]))
        elif "id" in work:
            imageList.append(int(work["id"]))

    # temp = page.find('ul', attrs={'class': PixivBookmark.__re_imageULItemsClass})
    # temp = temp.findAll('a')
    # if temp is None or len(temp) == 0:
    #     return imageList
    # for item in temp:
    #     href = re.search(r'/artworks/(\d+)', str(item))
    #     if href is not None:
    #         href = href.group(1)
    #         if not int(href) in imageList:
    #             imageList.append(int(href))

    return imageList
# Buggy code
def parseImageBookmark(page):
    imageList = list()

    temp = page.find("ul", attrs={"class": PixivBookmark.__re_imageULItemsClass})
    temp = temp.findAll("a")
    if temp is None or len(temp) == 0:
        return imageList
    for item in temp:
        href = re.search(r"/artworks/(\d+)", str(item))
        if href is not None:
            href = href.group(1)
            if not int(href) in imageList:
                imageList.append(int(href))

    return imageList


# Traceback (ZeroDivisionError)
Input: 5
Include Private bookmarks [y/n/o]:
Start Page (default=1):
End Page (default=0, 0 for no limit):
Importing Bookmarks...
Exporting page 1
Source URL: https://www.pixiv.net/bookmark.php?type=user&amp;p=1
Using default DB Path: /mnt/c/PixivUtil2/db.sqlite
No more data
Result:  0 items.
Error at process_bookmark(): (<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x7fa7885a55a0>)
Traceback (most recent call last):
File "PixivUtil2.py", line 2407, in main
np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args)
File "PixivUtil2.py", line 2127, in main_loop
menu_download_from_online_user_bookmark(op_is_valid, args)
File "PixivUtil2.py", line 1722, in menu_download_from_online_user_bookmark
process_bookmark(hide, start_page, end_page)
File "PixivUtil2.py", line 1235, in process_bookmark
print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list))))
ZeroDivisionError: float division by zero
press enter to exit.

# Fixed code
def parseImageBookmark(page):
    imageList = list()

    image_bookmark = json.loads(page)
    for work in image_bookmark["body"]["works"]:
        if "isAdContainer" in work and work["isAdContainer"]:
            continue
        imageList.append(work["illustId"])

    # temp = page.find('ul', attrs={'class': PixivBookmark.__re_imageULItemsClass})
    # temp = temp.findAll('a')
    # if temp is None or len(temp) == 0:
    #     return imageList
    # for item in temp:
    #     href = re.search(r'/artworks/(\d+)', str(item))
    #     if href is not None:
    #         href = href.group(1)
    #         if not int(href) in imageList:
    #             imageList.append(int(href))

    return imageList
# Buggy code
def backward(ctx, grad_output):  # pragma: no cover
    """Implements the backwards pass QNode vector-Jacobian product"""
    # NOTE: This method is definitely tested by the `test_torch.py` test suite,
    # however does not show up in the coverage. This is likely due to
    # subtleties in the torch.autograd.FunctionMeta metaclass, specifically
    # the way in which the backward class is created on the fly

    # evaluate the Jacobian matrix of the QNode
    jacobian = qnode.jacobian(ctx.args, ctx.kwargs)
    jacobian = torch.as_tensor(jacobian, dtype=grad_output.dtype)

    vjp = torch.transpose(grad_output.view(-1, 1), 0, 1) @ jacobian
    vjp = vjp.flatten()

    # restore the nested structure of the input args
    grad_input_list = unflatten_torch(vjp, ctx.saved_tensors)[0]
    grad_input = []

    # match the type and device of the input tensors
    for i, j in zip(grad_input_list, ctx.saved_tensors):
        res = torch.as_tensor(i, dtype=j.dtype)
        if j.is_cuda:  # pragma: no cover
            cuda_device = j.get_device()
            res = torch.as_tensor(res, device=cuda_device)
        grad_input.append(res)

    return (None,) + tuple(grad_input)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "qdqn.py", line 328, in <module>
loss.backward() #computes gradient of loss with respect to all weights n biases in the policy net
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/tensor.py", line 198, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/autograd/__init__.py", line 98, in backward
Variable._execution_engine.run_backward(
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'mat2' in call to _th_mm

# Fixed code
def backward(ctx, grad_output):  # pragma: no cover
    """Implements the backwards pass QNode vector-Jacobian product"""
    # NOTE: This method is definitely tested by the `test_torch.py` test suite,
    # however does not show up in the coverage. This is likely due to
    # subtleties in the torch.autograd.FunctionMeta metaclass, specifically
    # the way in which the backward class is created on the fly

    # evaluate the Jacobian matrix of the QNode
    jacobian = qnode.jacobian(ctx.args, ctx.kwargs)
    jacobian = torch.as_tensor(jacobian, dtype=grad_output.dtype).to(grad_output)

    vjp = torch.transpose(grad_output.view(-1, 1), 0, 1) @ jacobian
    vjp = vjp.flatten()

    # restore the nested structure of the input args
    grad_input_list = unflatten_torch(vjp, ctx.saved_tensors)[0]
    grad_input = []

    # match the type and device of the input tensors
    for i, j in zip(grad_input_list, ctx.saved_tensors):
        res = torch.as_tensor(i, dtype=j.dtype)
        if j.is_cuda:  # pragma: no cover
            cuda_device = j.get_device()
            res = torch.as_tensor(res, device=cuda_device)
        grad_input.append(res)

    return (None,) + tuple(grad_input)
# Buggy code
def _evaluate_qnode(self, x):
    """Evaluates the QNode for a single input datapoint.

    Args:
        x (tensor): the datapoint

    Returns:
        tensor: output datapoint
    """
    if qml.tape_mode_active():
        return self._evaluate_qnode_tape_mode(x)

    qnode = self.qnode

    for arg in self.sig:
        if arg is not self.input_arg:  # Non-input arguments must always be positional
            w = self.qnode_weights[arg]

            qnode = functools.partial(qnode, w)
        else:
            if self.input_is_default:  # The input argument can be positional or keyword
                qnode = functools.partial(qnode, **{self.input_arg: x})
            else:
                qnode = functools.partial(qnode, x)
    return qnode().type(x.dtype)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "qdqn.py", line 328, in <module>
loss.backward() #computes gradient of loss with respect to all weights n biases in the policy net
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/tensor.py", line 198, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/autograd/__init__.py", line 98, in backward
Variable._execution_engine.run_backward(
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'mat2' in call to _th_mm

# Fixed code
def _evaluate_qnode(self, x):
    """Evaluates the QNode for a single input datapoint.

    Args:
        x (tensor): the datapoint

    Returns:
        tensor: output datapoint
    """
    if qml.tape_mode_active():
        return self._evaluate_qnode_tape_mode(x)

    qnode = self.qnode

    for arg in self.sig:
        if arg is not self.input_arg:  # Non-input arguments must always be positional
            w = self.qnode_weights[arg].to(x)

            qnode = functools.partial(qnode, w)
        else:
            if self.input_is_default:  # The input argument can be positional or keyword
                qnode = functools.partial(qnode, **{self.input_arg: x})
            else:
                qnode = functools.partial(qnode, x)
    return qnode().type(x.dtype)
# Buggy code
def _evaluate_qnode_tape_mode(self, x):
    """Evaluates a tape-mode QNode for a single input datapoint.

    Args:
        x (tensor): the datapoint

    Returns:
        tensor: output datapoint
    """
    kwargs = {**{self.input_arg: x}, **self.qnode_weights}
    return self.qnode(**kwargs).type(x.dtype)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "qdqn.py", line 328, in <module>
loss.backward() #computes gradient of loss with respect to all weights n biases in the policy net
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/tensor.py", line 198, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/autograd/__init__.py", line 98, in backward
Variable._execution_engine.run_backward(
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'mat2' in call to _th_mm

# Fixed code
def _evaluate_qnode_tape_mode(self, x):
    """Evaluates a tape-mode QNode for a single input datapoint.

    Args:
        x (tensor): the datapoint

    Returns:
        tensor: output datapoint
    """
    kwargs = {
        **{self.input_arg: x},
        **{arg: weight.to(x) for arg, weight in self.qnode_weights.items()},
    }
    return self.qnode(**kwargs).type(x.dtype)
# Buggy code
def backward(ctx, grad_output):  # pragma: no cover
    """Implements the backwards pass QNode vector-Jacobian product"""
    tape = ctx.kwargs["tape"]
    device = ctx.kwargs["device"]

    tape.set_parameters(ctx.all_params_unwrapped, trainable_only=False)
    jacobian = tape.jacobian(device, params=ctx.args, **tape.jacobian_options)
    tape.set_parameters(ctx.all_params, trainable_only=False)

    jacobian = torch.as_tensor(jacobian, dtype=grad_output.dtype)

    vjp = grad_output.view(1, -1) @ jacobian
    grad_input_list = torch.unbind(vjp.flatten())
    grad_input = []

    # match the type and device of the input tensors
    for i, j in zip(grad_input_list, ctx.saved_tensors):
        res = torch.as_tensor(i, dtype=tape.dtype)
        if j.is_cuda:  # pragma: no cover
            cuda_device = j.get_device()
            res = torch.as_tensor(res, device=cuda_device)
        grad_input.append(res)

    return (None,) + tuple(grad_input)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "qdqn.py", line 328, in <module>
loss.backward() #computes gradient of loss with respect to all weights n biases in the policy net
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/tensor.py", line 198, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/autograd/__init__.py", line 98, in backward
Variable._execution_engine.run_backward(
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'mat2' in call to _th_mm

# Fixed code
def backward(ctx, grad_output):  # pragma: no cover
    """Implements the backwards pass QNode vector-Jacobian product"""
    tape = ctx.kwargs["tape"]
    device = ctx.kwargs["device"]

    tape.set_parameters(ctx.all_params_unwrapped, trainable_only=False)
    jacobian = tape.jacobian(device, params=ctx.args, **tape.jacobian_options)
    tape.set_parameters(ctx.all_params, trainable_only=False)

    jacobian = torch.as_tensor(jacobian, dtype=grad_output.dtype).to(grad_output)

    vjp = grad_output.view(1, -1) @ jacobian
    grad_input_list = torch.unbind(vjp.flatten())
    grad_input = []

    # match the type and device of the input tensors
    for i, j in zip(grad_input_list, ctx.saved_tensors):
        res = torch.as_tensor(i, dtype=tape.dtype)
        if j.is_cuda:  # pragma: no cover
            cuda_device = j.get_device()
            res = torch.as_tensor(res, device=cuda_device)
        grad_input.append(res)

    return (None,) + tuple(grad_input)
# Buggy code
def write(data):
    assert headers_set, "write() before start_response"
    if not headers_sent:
        status, response_headers = headers_sent[:] = headers_set
        try:
            code, msg = status.split(None, 1)
        except ValueError:
            code, msg = status, ""
        code = int(code)
        self.send_response(code, msg)
        header_keys = set()
        for key, value in response_headers:
            self.send_header(key, value)
            key = key.lower()
            header_keys.add(key)
        if not (
            "content-length" in header_keys
            or environ["REQUEST_METHOD"] == "HEAD"
            or code < 200
            or code in (204, 304)
        ):
            self.close_connection = True
            self.send_header("Connection", "close")
        if "server" not in header_keys:
            self.send_header("Server", self.version_string())
        if "date" not in header_keys:
            self.send_header("Date", self.date_time_string())
        self.end_headers()

    assert isinstance(data, bytes), "applications must write bytes"
    self.wfile.write(data)
    self.wfile.flush()


# Traceback (ssl.SSLEOFError)
Error on request:
Traceback (most recent call last):
File "/home/relent95/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 303, in run_wsgi
execute(self.server.app)
File "/home/relent95/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 294, in execute
write(data)
File "/home/relent95/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 275, in write
self.wfile.write(data)
File "/usr/lib/python3.5/socket.py", line 593, in write
return self._sock.send(b)
File "/usr/lib/python3.5/ssl.py", line 861, in send
return self._sslobj.write(data)
File "/usr/lib/python3.5/ssl.py", line 586, in write
return self._sslobj.write(data)
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1848)

# Fixed code
def write(data):
    assert headers_set, "write() before start_response"
    if not headers_sent:
        status, response_headers = headers_sent[:] = headers_set
        try:
            code, msg = status.split(None, 1)
        except ValueError:
            code, msg = status, ""
        code = int(code)
        self.send_response(code, msg)
        header_keys = set()
        for key, value in response_headers:
            self.send_header(key, value)
            key = key.lower()
            header_keys.add(key)
        if not (
            "content-length" in header_keys
            or environ["REQUEST_METHOD"] == "HEAD"
            or code < 200
            or code in (204, 304)
        ):
            self.close_connection = True
            self.send_header("Connection", "close")
        if "server" not in header_keys:
            self.send_header("Server", self.version_string())
        if "date" not in header_keys:
            self.send_header("Date", self.date_time_string())
        self.end_headers()

    assert isinstance(data, bytes), "applications must write bytes"
    if data:
        # Only write data if there is any to avoid Python 3.5 SSL bug
        self.wfile.write(data)
    self.wfile.flush()
# Buggy code
def __init__(self, data=None, secret_key=None, new=True):
    ModificationTrackingDict.__init__(self, data or ())
    # explicitly convert it into a bytestring because python 2.6
    # no longer performs an implicit string conversion on hmac
    if secret_key is not None:
        secret_key = to_bytes(secret_key, "utf-8")
    self.secret_key = secret_key
    self.new = new


# Traceback (TypeError)
Traceback (most recent call last):
File "test_secure_cookie.py", line 10, in <module>
print(c.serialize())
File "/home/tonyo/reps/github/werkzeug/werkzeug/contrib/securecookie.py", line 224, in serialize
self.quote(value).decode('ascii')
File "/home/tonyo/reps/github/werkzeug/werkzeug/contrib/securecookie.py", line 183, in quote
value = b''.join(base64.b64encode(value).splitlines()).strip()
File "/home/tonyo/reps/github/werkzeug/env3/lib/python3.4/base64.py", line 62, in b64encode
encoded = binascii.b2a_base64(s)[:-1]
TypeError: 'str' does not support the buffer interface

# Fixed code
def __init__(self, data=None, secret_key=None, new=True):
    ModificationTrackingDict.__init__(self, data or ())
    # explicitly convert it into a bytestring because python 2.6
    # no longer performs an implicit string conversion on hmac
    if secret_key is not None:
        secret_key = to_bytes(secret_key, "utf-8")
    self.secret_key = secret_key
    self.new = new

    if self.serialization_method is pickle:
        warnings.warn(
            "The default SecureCookie.serialization_method will change from pickle"
            " to json in 1.0. To upgrade existing tokens, override unquote to try"
            " pickle if json fails."
        )
# Buggy code
def quote(cls, value):
    """Quote the value for the cookie.  This can be any object supported
    by :attr:`serialization_method`.

    :param value: the value to quote.
    """
    if cls.serialization_method is not None:
        value = cls.serialization_method.dumps(value)
    if cls.quote_base64:
        value = b"".join(base64.b64encode(value).splitlines()).strip()
    return value


# Traceback (TypeError)
Traceback (most recent call last):
File "test_secure_cookie.py", line 10, in <module>
print(c.serialize())
File "/home/tonyo/reps/github/werkzeug/werkzeug/contrib/securecookie.py", line 224, in serialize
self.quote(value).decode('ascii')
File "/home/tonyo/reps/github/werkzeug/werkzeug/contrib/securecookie.py", line 183, in quote
value = b''.join(base64.b64encode(value).splitlines()).strip()
File "/home/tonyo/reps/github/werkzeug/env3/lib/python3.4/base64.py", line 62, in b64encode
encoded = binascii.b2a_base64(s)[:-1]
TypeError: 'str' does not support the buffer interface

# Fixed code
def quote(cls, value):
    """Quote the value for the cookie.  This can be any object supported
    by :attr:`serialization_method`.

    :param value: the value to quote.
    """
    if cls.serialization_method is not None:
        value = cls.serialization_method.dumps(value)
    if cls.quote_base64:
        value = b"".join(base64.b64encode(to_bytes(value, "utf8")).splitlines()).strip()
    return value