gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _summary_coord_extra(self, coord, indent):
    # Returns the text needed to ensure this coordinate can be
    # distinguished from all others with the same name.
    extra = ""
    similar_coords = self.coords(coord.name())
    if len(similar_coords) > 1:
        # Find all the attribute keys
        keys = set()
        for similar_coord in similar_coords:
            keys.update(similar_coord.attributes.keys())
        # Look for any attributes that vary
        vary = set()
        attributes = {}
        for key in keys:
            for similar_coord in similar_coords:
                if key not in similar_coord.attributes:
                    vary.add(key)
                    break
                value = similar_coord.attributes[key]
                if attributes.setdefault(key, value) != value:
                    vary.add(key)
                    break
        keys = sorted(vary & set(coord.attributes.keys()))
        bits = ["{}={!r}".format(key, coord.attributes[key]) for key in keys]
        if bits:
            extra = indent + ", ".join(bits)
    return extra


# Traceback (ValueError)
Traceback (most recent call last):
File "iris3_cube_print_fail.py", line 13, in <module>
print(cube)
File "[site-packages-path]/lib/python3.6/site-packages/iris/cube.py", line 2599, in __str__
return self.summary()
File "[site-packages-path]/lib/python3.6/site-packages/iris/cube.py", line 2445, in summary
vector_dim_coords, cube_header, max_line_offset
File "[site-packages-path]/lib/python3.6/site-packages/iris/cube.py", line 2423, in vector_summary
vectors, vector_summary, extra_indent
File "[site-packages-path]/lib/python3.6/site-packages/iris/cube.py", line 2215, in _summary_extra
extra = self._summary_coord_extra(coord, indent)
File "[site-packages-path]/lib/python3.6/site-packages/iris/cube.py", line 2198, in _summary_coord_extra
if attributes.setdefault(key, value) != value:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Fixed code
def _summary_coord_extra(self, coord, indent):
    # Returns the text needed to ensure this coordinate can be
    # distinguished from all others with the same name.
    extra = ""
    similar_coords = self.coords(coord.name())
    if len(similar_coords) > 1:
        similar_coords.remove(coord)
        # Look for any attributes that vary.
        vary = set()
        for key, value in coord.attributes.items():
            for similar_coord in similar_coords:
                if key not in similar_coord.attributes:
                    vary.add(key)
                    break
                if not np.array_equal(similar_coord.attributes[key], value):
                    vary.add(key)
                    break
        keys = sorted(vary)
        bits = ["{}={!r}".format(key, coord.attributes[key]) for key in keys]
        if bits:
            extra = indent + ", ".join(bits)
    return extra
# Buggy code
def reorder_item():
    """Reorder item if stock reaches reorder level"""
    # if initial setup not completed, return
    if not frappe.db.sql("select name from `tabFiscal Year` limit 1"):
        return

    if cint(frappe.db.get_value("Stock Settings", None, "auto_indent")):
        return _reorder_item()


# Traceback (IndexError)
Traceback (most recent call last):
File "/home/frappe/press/benches/1505261338/env/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/home/frappe/press/benches/1505261338/env/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/home/frappe/press/benches/1505261338/apps/frappe/frappe/tasks.py", line 77, in scheduler_task
frappe.get_attr(handler)()
File "/home/frappe/press/benches/1505261338/apps/erpnext/erpnext/stock/reorder_item.py", line 15, in reorder_item
return _reorder_item()
File "/home/frappe/press/benches/1505261338/apps/erpnext/erpnext/stock/reorder_item.py", line 24, in _reorder_item
frappe.db.sql("""select name from tabCompany limit 1""")[0][0])
IndexError: tuple index out of range

# Fixed code
def reorder_item():
    """Reorder item if stock reaches reorder level"""
    # if initial setup not completed, return
    if not (
        frappe.db.a_row_exists("Company") and frappe.db.a_row_exists("Fiscal Year")
    ):
        return

    if cint(frappe.db.get_value("Stock Settings", None, "auto_indent")):
        return _reorder_item()
# Buggy code
def parse(self, report):
    if self.mode == "fixed":
        return self.parse_csv_dict(report)

    # Set config to parse report
    self.report_name = report.get("extra.file_name")
    filename_search = self.__is_filename_regex.search(self.report_name)

    if not filename_search:
        raise ValueError(
            "Report's 'extra.file_name' {!r} is not valid.".format(self.report_name)
        )
    else:
        self.report_name = filename_search.group(1)
        self.logger.debug("Detected report's file name: {!r}.".format(self.report_name))
        retval = config.get_feed_by_filename(self.report_name)

        if not retval:
            raise ValueError(
                "Could not get a config for {!r}, check the documentation.".format(
                    self.report_name
                )
            )
        self.feedname, self.sparser_config = retval

    # Set default csv parse function
    return self.parse_csv_dict(report)


# Traceback (TypeError)
Bot has found a problem.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/intelmq/lib/bot.py", line 267, in start
self.process()
File "/usr/local/lib/python3.6/dist-packages/intelmq/lib/bot.py", line 942, in process
for line in self.parse(report):
File "/usr/local/lib/python3.6/dist-packages/intelmq/bots/parsers/shadowserver/parser.py", line 65, in parse
filename_search = self.__is_filename_regex.search(self.report_name)
TypeError: expected string or bytes-like object

# Fixed code
def parse(self, report):
    if self.mode == "fixed":
        return self.parse_csv_dict(report)

    # Set config to parse report
    self.report_name = report.get("extra.file_name")
    if not self.report_name:
        raise ValueError(
            "No feedname given as parameter and the "
            "processed report has no 'extra.file_name'. "
            "Ensure that at least one is given. "
            "Also have a look at the documentation of the bot."
        )
    filename_search = self.__is_filename_regex.search(self.report_name)

    if not filename_search:
        raise ValueError(
            "Report's 'extra.file_name' {!r} is not valid.".format(self.report_name)
        )
    else:
        self.report_name = filename_search.group(1)
        self.logger.debug("Detected report's file name: {!r}.".format(self.report_name))
        retval = config.get_feed_by_filename(self.report_name)

        if not retval:
            raise ValueError(
                "Could not get a config for {!r}, check the documentation.".format(
                    self.report_name
                )
            )
        self.feedname, self.sparser_config = retval

    # Set default csv parse function
    return self.parse_csv_dict(report)
# Buggy code
def process(self):
    event = self.receive_message()
    procedure = Procedure.CONTINUE
    for rule in self.sieve.rules:
        procedure = self.process_rule(rule, event)
        if procedure == Procedure.KEEP:
            self.logger.debug(
                "Stop processing based on rule at %s: %s.",
                self.get_linecol(rule),
                event,
            )
            break
        elif procedure == Procedure.DROP:
            self.logger.debug(
                "Dropped event based on rule at %s: %s.", self.get_linecol(rule), event
            )
            break

    # forwarding decision
    if procedure != Procedure.DROP:
        path = getattr(event, "path", "_default")
        self.send_message(event, path=path)

    self.acknowledge_message()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/intelmq/lib/bot.py", line 167, in start
self.process()
File "/usr/lib/python3/dist-packages/intelmq/bots/experts/sieve/expert.py", line 86, in process
for rule in self.sieve.rules:
AttributeError: 'str' object has no attribute 'rules'

# Fixed code
def process(self):
    event = self.receive_message()
    procedure = Procedure.CONTINUE
    if self.sieve:  # empty rules file results in empty string
        for rule in self.sieve.rules:
            procedure = self.process_rule(rule, event)
            if procedure == Procedure.KEEP:
                self.logger.debug(
                    "Stop processing based on rule at %s: %s.",
                    self.get_linecol(rule),
                    event,
                )
                break
            elif procedure == Procedure.DROP:
                self.logger.debug(
                    "Dropped event based on rule at %s: %s.",
                    self.get_linecol(rule),
                    event,
                )
                break

    # forwarding decision
    if procedure != Procedure.DROP:
        path = getattr(event, "path", "_default")
        self.send_message(event, path=path)

    self.acknowledge_message()
# Buggy code
def process(self):
    """Stop the Bot if cannot connect to AMQP Server after the defined connection attempts"""

    # self.connection and self.channel can be None
    if getattr(self.connection, "is_closed", None) or getattr(
        self.channel, "is_closed", None
    ):
        self.connect_server()

    event = self.receive_message()

    if not self.keep_raw_field:
        del event["raw"]

    try:
        if not self.channel.basic_publish(
            exchange=self.exchange,
            routing_key=self.routing_key,
            body=event.to_json(),
            properties=self.properties,
            mandatory=True,
        ):
            if self.require_confirmation:
                raise ValueError("Message sent but not confirmed.")
            else:
                self.logger.info("Message sent but not confirmed.")
    except (
        pika.exceptions.ChannelError,
        pika.exceptions.AMQPChannelError,
        pika.exceptions.NackError,
    ):
        self.logger.exception("Error publishing the message.")
    else:
        self.acknowledge_message()


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/intelmq/lib/bot.py", line 167, in start
self.process()
File "/usr/lib/python3/dist-packages/intelmq/bots/outputs/amqptopic/output.py", line 81, in process
mandatory=True):
File "/usr/lib/python3/dist-packages/pika/adapters/blocking_connection.py", line 1978, in basic_publish
mandatory, immediate)
File "/usr/lib/python3/dist-packages/pika/adapters/blocking_connection.py", line 2026, in publish
immediate=immediate)
File "/usr/lib/python3/dist-packages/pika/channel.py", line 332, in basic_publish
body = body.encode('utf-8')
UnicodeEncodeError: 'utf-8' codec can't encode character '\udbef' in position 215395: surrogates not allowed

# Fixed code
def process(self):
    """Stop the Bot if cannot connect to AMQP Server after the defined connection attempts"""

    # self.connection and self.channel can be None
    if getattr(self.connection, "is_closed", None) or getattr(
        self.channel, "is_closed", None
    ):
        self.connect_server()

    event = self.receive_message()

    if not self.keep_raw_field:
        del event["raw"]

    try:
        if not self.channel.basic_publish(
            exchange=self.exchange,
            routing_key=self.routing_key,
            # replace unicode characters when encoding (#1296)
            body=event.to_json().encode(errors="backslashreplace"),
            properties=self.properties,
            mandatory=True,
        ):
            if self.require_confirmation:
                raise ValueError("Message sent but not confirmed.")
            else:
                self.logger.info("Message sent but not confirmed.")
    except (
        pika.exceptions.ChannelError,
        pika.exceptions.AMQPChannelError,
        pika.exceptions.NackError,
    ):
        self.logger.exception("Error publishing the message.")
    else:
        self.acknowledge_message()
# Buggy code
def acknowledge_message(self):
    self.__source_pipeline.acknowledge()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/intelmqctl", line 9, in <module>
load_entry_point('intelmq==1.1.0a1', 'console_scripts', 'intelmqctl')()
File "/home/sebastian/dev/intelmq/intelmq/bin/intelmqctl.py", line 1101, in main
return x.run()
File "/home/sebastian/dev/intelmq/intelmq/bin/intelmqctl.py", line 562, in run
retval, results = args.func(**args_dict)
File "/home/sebastian/dev/intelmq/intelmq/bin/intelmqctl.py", line 569, in bot_run
return self.bot_process_manager.bot_run(**kwargs), None
File "/home/sebastian/dev/intelmq/intelmq/bin/intelmqctl.py", line 145, in bot_run
console_type, dryrun, message_action_kind, msg)
File "/home/sebastian/dev/intelmq/intelmq/lib/bot_debugger.py", line 49, in __init__
self.instance.start()
File "/home/sebastian/dev/intelmq/intelmq/lib/bot.py", line 225, in start
self.acknowledge_message()
File "/home/sebastian/dev/intelmq/intelmq/lib/bot.py", line 393, in acknowledge_message
self.__source_pipeline.acknowledge()
AttributeError: 'NoneType' object has no attribute 'acknowledge'

# Fixed code
def acknowledge_message(self):
    """
    Acknowledges that the last message has been processed, if any.

    For bots without source pipeline (collectors), this is a no-op.
    """
    if self.__source_pipeline:
        self.__source_pipeline.acknowledge()
# Buggy code
@staticmethod
    def sanitize(value):
        value = value.strip('.')
        if value:
            return value.encode('idna').decode().lower()


# Traceback (UnicodeError)
Traceback (most recent call last):
File ".../intelmq/intelmq/lib/bot.py", line 153, in start
self.process()
File ".../intelmq/intelmq/bots/parsers/spamhaus/parser_cert.py",
line 59, in process
event.add('destination.fqdn', row_splitted[5], raise_failure=False)
File ".../intelmq/intelmq/lib/message.py", line 194, in add
value = self.__sanitize_value(key, value)
File ".../intelmq/intelmq/lib/message.py", line 281, in __sanitize_value
return class_reference().sanitize(value)
File ".../intelmq/intelmq/lib/harmonization.py", line 381, in sanitize
return value.encode('idna').decode().lower()
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label empty or too long)

# Fixed code
@staticmethod
    def sanitize(value):
        value = value.strip('.')
        if value:
            try:
                return value.encode('idna').decode().lower()
            except UnicodeError:
                return
# Buggy code
@staticmethod
    def sanitize(value):
        value = value.rstrip('.')
        if value:
            return value.encode('idna').decode().lower()


# Traceback (UnicodeError)
'source_queue': 'shadowserver-parser-dns-open-resolvers-queue',
'traceback': ['Traceback (most recent call last):',
'  File "/usr/lib/python3.4/encodings/idna.py", line 165, in '
'encode',
'    raise UnicodeError("label empty or too long")',
'UnicodeError: label empty or too long',
'',
'The above exception was the direct cause of the following '
'exception:',
'',
'Traceback (most recent call last):',
'  File "/usr/lib/python3/dist-packages/intelmq/lib/bot.py", '
'line 606, in process',
'    events = list(filter(bool, self.parse_line(line,
report)))',
'  File '
'"/usr/lib/python3/dist-packages/intelmq/bots/parsers/shadowserver/parser.py", '
'line 150, in parse_line',
'    event.add(intelmqkey, value)',
'  File '
'"/usr/lib/python3/dist-packages/intelmq/lib/message.py",
line '
'202, in add',
'    value = self.__sanitize_value(key, value)',
'  File '
'"/usr/lib/python3/dist-packages/intelmq/lib/message.py",
line '
'298, in __sanitize_value',
'    return class_reference().sanitize(value)',
'  File '
'"/usr/lib/python3/dist-packages/intelmq/lib/harmonization.py", '
'line 374, in sanitize',
"    return value.encode('idna').decode().lower()",
"UnicodeError: encoding with 'idna' codec failed
(UnicodeError: "
'label empty or too long)']}

# Fixed code
@staticmethod
    def sanitize(value):
        value = value.strip('.')
        if value:
            return value.encode('idna').decode().lower()
# Buggy code
def __init__(self, execer, ctx, **kwargs):
    super().__init__()
    self.execer = execer
    self.ctx = ctx
    if kwargs.get("completer", True):
        self.completer = Completer()
    self.buffer = []
    self.need_more_lines = False
    self.mlprompt = None
    if HAS_PYGMENTS:
        env = builtins.__xonsh_env__
        self.styler = XonshStyle(env.get("XONSH_COLOR_STYLE"))
    else:
        self.styler = None


# Traceback (AttributeError)
cryzed@arch ~ $ xonsh update-aur-gits.xsh
Traceback (most recent call last):
File "/usr/bin/xonsh", line 9, in <module>
load_entry_point('xonsh==0.3.2', 'console_scripts', 'xonsh')()
File "/usr/lib/python3.5/site-packages/xonsh/main.py", line 228, in main
args = premain(argv)
File "/usr/lib/python3.5/site-packages/xonsh/main.py", line 215, in premain
shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
File "/usr/lib/python3.5/site-packages/xonsh/shell.py", line 72, in __init__
ctx=self.ctx, **kwargs)
File "/usr/lib/python3.5/site-packages/xonsh/ptk/shell.py", line 33, in __init__
self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
AttributeError: 'PromptToolkitShell' object has no attribute 'completer'

# Fixed code
def __init__(self, execer, ctx, **kwargs):
    super().__init__()
    self.execer = execer
    self.ctx = ctx
    self.completer = Completer() if kwargs.get("completer", True) else None
    self.buffer = []
    self.need_more_lines = False
    self.mlprompt = None
    if HAS_PYGMENTS:
        env = builtins.__xonsh_env__
        self.styler = XonshStyle(env.get("XONSH_COLOR_STYLE"))
    else:
        self.styler = None
# Buggy code
def find_spec(self, fullname, path, target=None):
    """Finds the spec for a xonsh module if it exists."""
    dot = "."
    spec = None
    path = sys.path if path is None else path
    if dot not in fullname and dot not in path:
        path = [dot] + path
    name = fullname.rsplit(dot, 1)[-1]
    fname = name + ".xsh"
    for p in path:
        if not isinstance(p, str):
            continue
        if not os.path.isdir(p):
            continue
        if fname not in (x.name for x in scandir(p)):
            continue
        spec = ModuleSpec(fullname, self)
        self._filenames[fullname] = os.path.join(p, fname)
        break
    return spec


# Traceback (PermissionError)
(C:\Anaconda3) C:\Users\kpr>xonsh
Traceback (most recent call last):
File "C:\Anaconda3\Scripts\xonsh-script.py", line 5, in <module>
sys.exit(xonsh.main.main())
File "C:\Anaconda3\lib\site-packages\xonsh\main.py", line 209, in main
args = premain(argv)
File "C:\Anaconda3\lib\site-packages\xonsh\main.py", line 201, in premain
setup_win_unicode_console(env.get('WIN_UNICODE_CONSOLE', True))
File "C:\Anaconda3\lib\site-packages\xonsh\tools.py", line 1091, in setup_win_unicode_console
import win_unicode_console
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 954, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 896, in _find_spec
File "C:\Anaconda3\lib\site-packages\xonsh\imphooks.py", line 53, in find_spec
if fname not in (x.name for x in scandir(p)):
PermissionError: [WinError 5] Access is denied: '.'

# Fixed code
def find_spec(self, fullname, path, target=None):
    """Finds the spec for a xonsh module if it exists."""
    dot = "."
    spec = None
    path = sys.path if path is None else path
    if dot not in fullname and dot not in path:
        path = [dot] + path
    name = fullname.rsplit(dot, 1)[-1]
    fname = name + ".xsh"
    for p in path:
        if not isinstance(p, str):
            continue
        if not os.path.isdir(p) or not os.access(p, os.R_OK):
            continue
        if fname not in (x.name for x in scandir(p)):
            continue
        spec = ModuleSpec(fullname, self)
        self._filenames[fullname] = os.path.join(p, fname)
        break
    return spec