gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get(self, path: str, params: Optional[Union[str, Dict[str, str]]] = None):
    """Return parsed objects returned from a GET request to ``path``.

    :param path: The path to fetch.
    :param params: The query parameters to add to the request (default:
        None).

    """
    data = self.request("GET", path, params=params)
    return self._objector.objectify(data)


# Traceback (APIException)
---------------------------------------------------------------------------
APIException                              Traceback (most recent call last)
<ipython-input-14-5b88e4f8d60d> in <module>
1 while True:
----> 2     print(repr(s[1].reply("F")))
3

/usr/local/lib/python3.7/site-packages/praw/models/reddit/mixins/replyable.py in reply(self, body)
31         """
32         data = {"text": body, "thing_id": self.fullname}
---> 33         comments = self._reddit.post(API_PATH["comment"], data=data)
34         try:
35             return comments[0]

/usr/local/lib/python3.7/site-packages/praw/reddit.py in post(self, path, data, files, params)
553             "POST", path, data=data or {}, files=files, params=params
554         )
--> 555         return self._objector.objectify(data)
556
557     def put(

/usr/local/lib/python3.7/site-packages/praw/objector.py in objectify(self, data)
168             errors = data["json"]["errors"]
169             if len(errors) == 1:
--> 170                 raise APIException(*errors[0])
171             assert not errors
172         elif isinstance(data, dict):

APIException: RATELIMIT: 'you are doing that too much. try again in 5 seconds.' on field 'ratelimit'

# Fixed code
def get(self, path: str, params: Optional[Union[str, Dict[str, str]]] = None):
    """Return parsed objects returned from a GET request to ``path``.

    :param path: The path to fetch.
    :param params: The query parameters to add to the request (default:
        None).

    """
    return self._objectify_request(method="GET", params=params, path=path)
# Buggy code
def patch(
    self,
    path: str,
    data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None,
) -> Any:
    """Return parsed objects returned from a PATCH request to ``path``.

    :param path: The path to fetch.
    :param data: Dictionary, bytes, or file-like object to send in the body
        of the request (default: None).

    """
    data = self.request("PATCH", path, data=data)
    return self._objector.objectify(data)


# Traceback (APIException)
---------------------------------------------------------------------------
APIException                              Traceback (most recent call last)
<ipython-input-14-5b88e4f8d60d> in <module>
1 while True:
----> 2     print(repr(s[1].reply("F")))
3

/usr/local/lib/python3.7/site-packages/praw/models/reddit/mixins/replyable.py in reply(self, body)
31         """
32         data = {"text": body, "thing_id": self.fullname}
---> 33         comments = self._reddit.post(API_PATH["comment"], data=data)
34         try:
35             return comments[0]

/usr/local/lib/python3.7/site-packages/praw/reddit.py in post(self, path, data, files, params)
553             "POST", path, data=data or {}, files=files, params=params
554         )
--> 555         return self._objector.objectify(data)
556
557     def put(

/usr/local/lib/python3.7/site-packages/praw/objector.py in objectify(self, data)
168             errors = data["json"]["errors"]
169             if len(errors) == 1:
--> 170                 raise APIException(*errors[0])
171             assert not errors
172         elif isinstance(data, dict):

APIException: RATELIMIT: 'you are doing that too much. try again in 5 seconds.' on field 'ratelimit'

# Fixed code
def patch(
    self,
    path: str,
    data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None,
) -> Any:
    """Return parsed objects returned from a PATCH request to ``path``.

    :param path: The path to fetch.
    :param data: Dictionary, bytes, or file-like object to send in the body
        of the request (default: None).

    """
    return self._objectify_request(data=data, method="PATCH", path=path)
# Buggy code
def put(
    self,
    path: str,
    data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None,
):
    """Return parsed objects returned from a PUT request to ``path``.

    :param path: The path to fetch.
    :param data: Dictionary, bytes, or file-like object to send in the body
        of the request (default: None).

    """
    data = self.request("PUT", path, data=data)
    return self._objector.objectify(data)


# Traceback (APIException)
---------------------------------------------------------------------------
APIException                              Traceback (most recent call last)
<ipython-input-14-5b88e4f8d60d> in <module>
1 while True:
----> 2     print(repr(s[1].reply("F")))
3

/usr/local/lib/python3.7/site-packages/praw/models/reddit/mixins/replyable.py in reply(self, body)
31         """
32         data = {"text": body, "thing_id": self.fullname}
---> 33         comments = self._reddit.post(API_PATH["comment"], data=data)
34         try:
35             return comments[0]

/usr/local/lib/python3.7/site-packages/praw/reddit.py in post(self, path, data, files, params)
553             "POST", path, data=data or {}, files=files, params=params
554         )
--> 555         return self._objector.objectify(data)
556
557     def put(

/usr/local/lib/python3.7/site-packages/praw/objector.py in objectify(self, data)
168             errors = data["json"]["errors"]
169             if len(errors) == 1:
--> 170                 raise APIException(*errors[0])
171             assert not errors
172         elif isinstance(data, dict):

APIException: RATELIMIT: 'you are doing that too much. try again in 5 seconds.' on field 'ratelimit'

# Fixed code
def put(
    self,
    path: str,
    data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None,
):
    """Return parsed objects returned from a PUT request to ``path``.

    :param path: The path to fetch.
    :param data: Dictionary, bytes, or file-like object to send in the body
        of the request (default: None).

    """
    return self._objectify_request(
        data=data,
        method="PUT",
        path=path,
    )
# Buggy code
def refresh(self):
    """Refresh the comment's attributes.

    If using :meth:`.Reddit.comment` this method must be called in order to
    obtain the comment's replies.

    """
    if "context" in self.__dict__:  # Using hasattr triggers a fetch
        comment_path = self.context.split("?", 1)[0]
    else:
        comment_path = "{}_/{}".format(
            self.submission._info_path(),  # pylint: disable=no-member
            self.id,
        )

    # The context limit appears to be 8, but let's ask for more anyway.
    comment_list = self._reddit.get(comment_path, params={"context": 100})[1].children
    if not comment_list:
        raise ClientException(self.MISSING_COMMENT_MESSAGE)

    # With context, the comment may be nested so we have to find it
    comment = None
    queue = comment_list[:]
    while queue and (comment is None or comment.id != self.id):
        comment = queue.pop()
        queue.extend(comment._replies)

    if comment.id != self.id:
        raise ClientException(self.MISSING_COMMENT_MESSAGE)

    if self._submission is not None:
        del comment.__dict__["_submission"]  # Don't replace if set
    self.__dict__.update(comment.__dict__)

    for reply in comment_list:
        reply.submission = self.submission
    return self


# Traceback (AttributeError)
Traceback (most recent call last):
File "./test.py", line 12, in <module>
comment.refresh()
File "/usr/local/lib/python3.4/dist-packages/praw/models/reddit/comment.py", line 196, in refresh
queue.extend(comment._replies)
AttributeError: 'MoreComments' object has no attribute '_replies'

# Fixed code
def refresh(self):
    """Refresh the comment's attributes.

    If using :meth:`.Reddit.comment` this method must be called in order to
    obtain the comment's replies.

    """
    if "context" in self.__dict__:  # Using hasattr triggers a fetch
        comment_path = self.context.split("?", 1)[0]
    else:
        comment_path = "{}_/{}".format(
            self.submission._info_path(),  # pylint: disable=no-member
            self.id,
        )

    # The context limit appears to be 8, but let's ask for more anyway.
    comment_list = self._reddit.get(comment_path, params={"context": 100})[1].children
    if not comment_list:
        raise ClientException(self.MISSING_COMMENT_MESSAGE)

    # With context, the comment may be nested so we have to find it
    comment = None
    queue = comment_list[:]
    while queue and (comment is None or comment.id != self.id):
        comment = queue.pop()
        if isinstance(comment, Comment):
            queue.extend(comment._replies)

    if comment.id != self.id:
        raise ClientException(self.MISSING_COMMENT_MESSAGE)

    if self._submission is not None:
        del comment.__dict__["_submission"]  # Don't replace if set
    self.__dict__.update(comment.__dict__)

    for reply in comment_list:
        reply.submission = self.submission
    return self
# Buggy code
def __init__(self, _id, dp_id, conf, prom_client):
    self.db = None  # pylint: disable=invalid-name
    self.dbs = None
    self.dp = None  # pylint: disable=invalid-name
    self.all_dps = None
    self.type = None
    self.interval = None
    self.db_type = None
    self.dps = None
    self.compress = None
    self.file = None
    self.influx_db = None
    self.influx_host = None
    self.influx_port = None
    self.influx_user = None
    self.influx_pwd = None
    self.influx_timeout = None
    self.influx_retries = None
    self.name = None
    self.prometheus_port = None
    self.prometheus_addr = None
    self.prometheus_test_thread = None
    super(WatcherConf, self).__init__(_id, dp_id, conf)
    self.name = str(self._id)
    self.prom_client = prom_client


# Traceback (FileNotFoundError)
Oct 26 13:31:16 gauge.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3/dist-packages/faucet/gauge.py", line 101, in _update_watcher
watcher.update(ryu_event.timestamp, ryu_dp.id, msg)
File "/usr/lib/python3/dist-packages/faucet/watcher.py", line 148, in update
with gzip.open(filename, 'at') as outfile:
File "/usr/lib/python3.5/gzip.py", line 53, in open
binary_file = GzipFile(filename, gz_mode, compresslevel)
File "/usr/lib/python3.5/gzip.py", line 163, in __init__
fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/var/log/faucet/flowtable/ft.yml.gz'

# Fixed code
def __init__(self, _id, dp_id, conf, prom_client):
    self.db = None  # pylint: disable=invalid-name
    self.dbs = None
    self.dp = None  # pylint: disable=invalid-name
    self.all_dps = None
    self.type = None
    self.interval = None
    self.db_type = None
    self.dps = None
    self.compress = None
    self.file = None
    self.influx_db = None
    self.influx_host = None
    self.influx_port = None
    self.influx_user = None
    self.influx_pwd = None
    self.influx_timeout = None
    self.influx_retries = None
    self.name = None
    self.prometheus_port = None
    self.prometheus_addr = None
    self.prometheus_test_thread = None
    self.defaults.update(self.db_defaults)
    self.defaults_types.update(self.db_defaults_types)
    super(WatcherConf, self).__init__(_id, dp_id, conf)
    self.name = str(self._id)
    self.prom_client = prom_client
# Buggy code
def add_db(self, db_conf):
    """Add database config to this watcher."""
    db_conf = deepcopy(db_conf)
    db_type = db_conf.pop("type")
    db_conf["db_type"] = db_type
    self.update(db_conf)


# Traceback (FileNotFoundError)
Oct 26 13:31:16 gauge.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3/dist-packages/faucet/gauge.py", line 101, in _update_watcher
watcher.update(ryu_event.timestamp, ryu_dp.id, msg)
File "/usr/lib/python3/dist-packages/faucet/watcher.py", line 148, in update
with gzip.open(filename, 'at') as outfile:
File "/usr/lib/python3.5/gzip.py", line 53, in open
binary_file = GzipFile(filename, gz_mode, compresslevel)
File "/usr/lib/python3.5/gzip.py", line 163, in __init__
fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/var/log/faucet/flowtable/ft.yml.gz'

# Fixed code
def add_db(self, db_conf):
    """Add database config to this watcher."""
    self._check_conf_types(db_conf, self.db_defaults_types)
    db_conf = deepcopy(db_conf)
    db_type = db_conf.pop("type")
    db_conf["db_type"] = db_type
    self.update(db_conf)
    test_config_condition(
        self.file is not None
        and not (
            os.path.dirname(self.file)
            and os.access(os.path.dirname(self.file), os.W_OK)
        ),
        "%s is not writable" % self.file,
    )
# Buggy code
def reset_ports(self, ports):
    """Reset tagged and untagged port lists."""
    self.tagged = tuple([port for port in ports if self in port.tagged_vlans])
    self.untagged = tuple([port for port in ports if self == port.native_vlan])


# Traceback (AssertionError)
test_tagged (mininet_tests.FaucetTaggedIPv4RouteTest) ... FaucetTaggedIPv4RouteTest-test_tagged: 260 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 262 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 266 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 255 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 262 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 263 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 259 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 260 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 256 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 260 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 257 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 265 mbps to 10.0.1.1
FAIL

======================================================================
FAIL: test_tagged (mininet_tests.FaucetTaggedIPv4RouteTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/faucet-src/tests/integration/mininet_tests.py", line 5183, in test_tagged
restart=True, cold_start=False)
File "/faucet-src/clib/mininet_test_base.py", line 1191, in change_port_config
restart, cold_start, hup=hup)
File "/faucet-src/clib/mininet_test_base.py", line 1151, in reload_conf
verify_faucet_reconf_func()
File "/faucet-src/clib/mininet_test_base.py", line 1656, in verify_faucet_reconf
msg='%s did not increment: %u' % (var, new_count))
AssertionError: 1 != 0 : faucet_config_reload_warm did not increment: 0

----------------------------------------------------------------------
Ran 1 test in 129.772s

FAILED (failures=1)

# Fixed code
def reset_ports(self, ports):
    """Reset tagged and untagged port lists."""
    sorted_ports = sorted(ports, key=lambda i: i.number)
    self.tagged = tuple([port for port in sorted_ports if self in port.tagged_vlans])
    self.untagged = tuple([port for port in sorted_ports if self == port.native_vlan])
# Buggy code
def __str__(self):
    port_list = tuple([str(x) for x in self.get_ports()])
    ports = ",".join(port_list)
    return "VLAN %s vid:%s ports:%s" % (self.name, self.vid, ports)


# Traceback (AssertionError)
test_tagged (mininet_tests.FaucetTaggedIPv4RouteTest) ... FaucetTaggedIPv4RouteTest-test_tagged: 260 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 262 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 266 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 255 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 262 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 263 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 259 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 260 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 256 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 260 mbps to 10.0.1.1
FaucetTaggedIPv4RouteTest-test_tagged: 257 mbps to 10.0.2.1
FaucetTaggedIPv4RouteTest-test_tagged: 265 mbps to 10.0.1.1
FAIL

======================================================================
FAIL: test_tagged (mininet_tests.FaucetTaggedIPv4RouteTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/faucet-src/tests/integration/mininet_tests.py", line 5183, in test_tagged
restart=True, cold_start=False)
File "/faucet-src/clib/mininet_test_base.py", line 1191, in change_port_config
restart, cold_start, hup=hup)
File "/faucet-src/clib/mininet_test_base.py", line 1151, in reload_conf
verify_faucet_reconf_func()
File "/faucet-src/clib/mininet_test_base.py", line 1656, in verify_faucet_reconf
msg='%s did not increment: %u' % (var, new_count))
AssertionError: 1 != 0 : faucet_config_reload_warm did not increment: 0

----------------------------------------------------------------------
Ran 1 test in 129.772s

FAILED (failures=1)

# Fixed code
def __str__(self):
    str_ports = []
    if self.tagged:
        str_ports.append("tagged: %s" % ",".join([str(p) for p in self.tagged]))
    if self.untagged:
        str_ports.append("untagged: %s" % ",".join([str(p) for p in self.untagged]))
    return "VLAN %s vid:%s %s" % (self.name, self.vid, " ".join(str_ports))
# Buggy code
def __str__(self):
    return self._id


# Traceback (TypeError)
Oct 30 03:20:12 faucet.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/faucet/faucet.py", line 156, in reload_config
time.time(), self.config_file, delete_dp=self._delete_deconfigured_dp)
File "/usr/lib/python3.6/site-packages/faucet/valves_manager.py", line 139, in request_reload_configs
self.load_configs(now, new_config_file, delete_dp=delete_dp)
File "/usr/lib/python3.6/site-packages/faucet/valves_manager.py", line 108, in load_configs
new_dps = self.parse_configs(new_config_file)
File "/usr/lib/python3.6/site-packages/faucet/valves_manager.py", line 88, in parse_configs
new_config_hashes, new_dps = dp_parser(new_config_file, self.logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 51, in dp_parser
config_hashes, dps = _config_parser_v2(config_file, logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 213, in _config_parser_v2
top_confs['vlans'])
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 177, in _dp_parser_v2
for dp_key, dp_conf in dps_conf.items()]
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 177, in <listcomp>
for dp_key, dp_conf in dps_conf.items()]
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 164, in _parse_dp
router = Router(router_key, dp_id, router_conf)
File "/usr/lib/python3.6/site-packages/faucet/router.py", line 38, in __init__
super(Router, self).__init__(_id, dp_id, conf)
File "/usr/lib/python3.6/site-packages/faucet/conf.py", line 54, in __init__
self.check_config()
File "/usr/lib/python3.6/site-packages/faucet/router.py", line 46, in check_config
'router %s must have at least 2 VLANs configured' % self))
TypeError: __str__ returned non-string (type int)

# Fixed code
def __str__(self):
    return str(self._id)
# Buggy code
def __init__(self, _id, dp_id, conf):
    self.rules = []
    self.exact_match = None
    self.meter = False
    self.matches = {}
    self.set_fields = set()
    conf = copy.deepcopy(conf)
    if isinstance(conf, dict):
        rules = conf.get("rules", [])
    elif isinstance(conf, list):
        rules = conf
        conf = {}
    else:
        raise InvalidConfigError("ACL conf is an invalid type %s" % self._id)
    conf["rules"] = []
    for rule in rules:
        test_config_condition(
            not isinstance(rule, dict), ("ACL rule is %s not %s" % (type(rule), dict))
        )
        conf["rules"].append(rule.get("rule", rule))
    super(ACL, self).__init__(_id, dp_id, conf)


# Traceback (AttributeError)
Oct 30 03:15:23 faucet.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/faucet/faucet.py", line 156, in reload_config
time.time(), self.config_file, delete_dp=self._delete_deconfigured_dp)
File "/usr/lib/python3.6/site-packages/faucet/valves_manager.py", line 139, in request_reload_configs
self.load_configs(now, new_config_file, delete_dp=delete_dp)
File "/usr/lib/python3.6/site-packages/faucet/valves_manager.py", line 108, in load_configs
new_dps = self.parse_configs(new_config_file)
File "/usr/lib/python3.6/site-packages/faucet/valves_manager.py", line 88, in parse_configs
new_config_hashes, new_dps = dp_parser(new_config_file, self.logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 51, in dp_parser
config_hashes, dps = _config_parser_v2(config_file, logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 213, in _config_parser_v2
top_confs['vlans'])
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 177, in _dp_parser_v2
for dp_key, dp_conf in dps_conf.items()]
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 177, in <listcomp>
for dp_key, dp_conf in dps_conf.items()]
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 161, in _parse_dp
acl = ACL(acl_key, dp_id, acl_conf)
File "/usr/lib/python3.6/site-packages/faucet/acl.py", line 112, in __init__
'ACL conf is an invalid type %s' % self._id)
AttributeError: 'ACL' object has no attribute '_id'

# Fixed code
def __init__(self, _id, dp_id, conf):
    self.rules = []
    self.exact_match = None
    self.meter = False
    self.matches = {}
    self.set_fields = set()
    conf = copy.deepcopy(conf)
    if isinstance(conf, dict):
        rules = conf.get("rules", [])
    elif isinstance(conf, list):
        rules = conf
        conf = {}
    else:
        raise InvalidConfigError("ACL conf is an invalid type %s" % _id)
    conf["rules"] = []
    for rule in rules:
        test_config_condition(
            not isinstance(rule, dict), ("ACL rule is %s not %s" % (type(rule), dict))
        )
        conf["rules"].append(rule.get("rule", rule))
    super(ACL, self).__init__(_id, dp_id, conf)
# Buggy code
def _watcher_parser_v2(conf, logname, prom_client):
    logger = config_parser_util.get_logger(logname)
    result = []

    dps = {}
    for faucet_file in conf["faucet_configs"]:
        _, dp_list = dp_parser(faucet_file, logname)
        if dp_list:
            for dp in dp_list:
                dps[dp.name] = dp

    dbs = conf.pop("dbs")

    for watcher_name, watcher_conf in list(conf["watchers"].items()):
        watcher_dps = watcher_conf["dps"]
        if watcher_conf.get("all_dps", False):
            watcher_dps = list(dps.keys())
        # Watcher config has a list of DPs, but actually a WatcherConf is
        # created for each DP.
        # TODO: refactor watcher_conf as a container.
        for dp_name in watcher_dps:
            if dp_name not in dps:
                logger.error("DP %s in Gauge but not configured in FAUCET", dp_name)
                continue
            dp = dps[dp_name]
            watcher = WatcherConf(watcher_name, dp.dp_id, watcher_conf, prom_client)
            watcher.add_db(dbs[watcher.db])
            watcher.add_dp(dp)
            result.append(watcher)

    return result


# Traceback (KeyError)
Dec 20 14:06:38 gauge.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/faucet/gauge.py", line 99, in _load_config
new_confs = watcher_parser(self.config_file, self.logname, self.prom_client)
File "/usr/local/lib/python3.5/dist-packages/faucet/config_parser.py", line 212, in watcher_parser
return _watcher_parser_v2(conf, logname, prom_client)
File "/usr/local/lib/python3.5/dist-packages/faucet/config_parser.py", line 229, in _watcher_parser_v2
watcher_dps = watcher_conf['dps']
KeyError: 'dps'

# Fixed code
def _watcher_parser_v2(conf, logname, prom_client):
    logger = config_parser_util.get_logger(logname)
    result = []

    dps = {}
    for faucet_file in conf["faucet_configs"]:
        _, dp_list = dp_parser(faucet_file, logname)
        if dp_list:
            for dp in dp_list:
                dps[dp.name] = dp

    dbs = conf.pop("dbs")

    for watcher_name, watcher_conf in list(conf["watchers"].items()):
        if watcher_conf.get("all_dps", False):
            watcher_dps = list(dps.keys())
        else:
            watcher_dps = watcher_conf["dps"]
        # Watcher config has a list of DPs, but actually a WatcherConf is
        # created for each DP.
        # TODO: refactor watcher_conf as a container.
        for dp_name in watcher_dps:
            if dp_name not in dps:
                logger.error("DP %s in Gauge but not configured in FAUCET", dp_name)
                continue
            dp = dps[dp_name]
            watcher = WatcherConf(watcher_name, dp.dp_id, watcher_conf, prom_client)
            watcher.add_db(dbs[watcher.db])
            watcher.add_dp(dp)
            result.append(watcher)

    return result
# Buggy code
def resolve_acls():
    """Resolve ACL references in config."""

    def build_acl(acl, vid=None):
        """Check that ACL can be built from config."""
        if acl.rules:
            assert valve_acl.build_acl_ofmsgs(
                [acl],
                self.wildcard_table,
                valve_of.goto_table(self.wildcard_table),
                2**16,
                self.meters,
                acl.exact_match,
                vlan_vid=vid,
            )

    for vlan in list(self.vlans.values()):
        if vlan.acl_in:
            vlan.acl_in = self.acls[vlan.acl_in]
            build_acl(vlan.acl_in, vid=1)
    for port in list(self.ports.values()):
        if port.acl_in:
            if port.acl_in in self.acls:
                port.acl_in = self.acls[port.acl_in]
                build_acl(port.acl_in)
            else:
                assert False, "Unconfigured acl for %s" % self.name


# Traceback (KeyError)
Nov 16 02:50:28 faucet.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/faucet/faucet.py", line 146, in _load_configs
new_config_file, self.logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 50, in dp_parser
config_hashes, dps = _config_parser_v2(config_file, logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 165, in _config_parser_v2
top_confs['vlans'])
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 133, in _dp_parser_v2
dp.finalize_config(dps)
File "/usr/lib/python3.6/site-packages/faucet/dp.py", line 509, in finalize_config
resolve_acls()
File "/usr/lib/python3.6/site-packages/faucet/dp.py", line 472, in resolve_acls
vlan.acl_in = self.acls[vlan.acl_in]
KeyError: 'office-vlan-protect'

# Fixed code
def resolve_acls():
    """Resolve ACL references in config."""

    def build_acl(acl, vid=None):
        """Check that ACL can be built from config."""
        if acl.rules:
            assert valve_acl.build_acl_ofmsgs(
                [acl],
                self.wildcard_table,
                valve_of.goto_table(self.wildcard_table),
                2**16,
                self.meters,
                acl.exact_match,
                vlan_vid=vid,
            )

    for vlan in list(self.vlans.values()):
        if vlan.acl_in:
            if vlan.acl_in in self.acls:
                vlan.acl_in = self.acls[vlan.acl_in]
                build_acl(vlan.acl_in, vid=1)
            else:
                assert False, "Unconfigured vlan for %s" % self.name
    for port in list(self.ports.values()):
        if port.acl_in:
            if port.acl_in in self.acls:
                port.acl_in = self.acls[port.acl_in]
                build_acl(port.acl_in)
            else:
                assert False, "Unconfigured acl for %s" % self.name
# Buggy code
def dp_parser(config_file, logname):
    logger = config_parser_util.get_logger(logname)
    conf = config_parser_util.read_config(config_file, logname)
    config_hashes = None
    dps = None

    if conf is not None:
        version = conf.pop("version", 2)
        if version != 2:
            logger.fatal("Only config version 2 is supported")

        config_hashes, dps = _config_parser_v2(config_file, logname)
    return config_hashes, dps


# Traceback (AttributeError)
Nov 15 20:44:01 faucet.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/faucet/faucet.py", line 146, in _load_configs
new_config_file, self.logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 46, in dp_parser
version = conf.pop('version', 2)
AttributeError: 'str' object has no attribute 'pop'

# Fixed code
def dp_parser(config_file, logname):
    logger = config_parser_util.get_logger(logname)
    conf = config_parser_util.read_config(config_file, logname)
    config_hashes = None
    dps = None

    if conf is not None:
        if type(conf) is dict:
            version = conf.pop("version", 2)
            if version != 2:
                logger.fatal("Only config version 2 is supported")

        else:
            logger.fatal("Config file does not form a dictionary")
            return None, None

        config_hashes, dps = _config_parser_v2(config_file, logname)
    return config_hashes, dps
# Buggy code
def resolve_acls():
    """Resolve ACL references in config."""

    def build_acl(acl, vid=None):
        """Check that ACL can be built from config."""
        if acl.rules:
            assert valve_acl.build_acl_ofmsgs(
                [acl],
                self.wildcard_table,
                valve_of.goto_table(self.wildcard_table),
                2**16,
                self.meters,
                acl.exact_match,
                vlan_vid=vid,
            )

    for vlan in list(self.vlans.values()):
        if vlan.acl_in:
            vlan.acl_in = self.acls[vlan.acl_in]
            build_acl(vlan.acl_in, vid=1)
    for port in list(self.ports.values()):
        if port.acl_in:
            port.acl_in = self.acls[port.acl_in]
            build_acl(port.acl_in)


# Traceback (KeyError)
Nov 15 01:59:34 faucet.exception ERROR    Unhandled exception, killing RYU
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/faucet/valve_util.py", line 34, in __koe
func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/faucet/faucet.py", line 146, in _load_configs
new_config_file, self.logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 50, in dp_parser
config_hashes, dps = _config_parser_v2(config_file, logname)
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 165, in _config_parser_v2
top_confs['vlans'])
File "/usr/lib/python3.6/site-packages/faucet/config_parser.py", line 133, in _dp_parser_v2
dp.finalize_config(dps)
File "/usr/lib/python3.6/site-packages/faucet/dp.py", line 508, in finalize_config
resolve_acls()
File "/usr/lib/python3.6/site-packages/faucet/dp.py", line 476, in resolve_acls
port.acl_in = self.acls[port.acl_in]
KeyError: 'access-port-protect'

# Fixed code
def resolve_acls():
    """Resolve ACL references in config."""

    def build_acl(acl, vid=None):
        """Check that ACL can be built from config."""
        if acl.rules:
            assert valve_acl.build_acl_ofmsgs(
                [acl],
                self.wildcard_table,
                valve_of.goto_table(self.wildcard_table),
                2**16,
                self.meters,
                acl.exact_match,
                vlan_vid=vid,
            )

    for vlan in list(self.vlans.values()):
        if vlan.acl_in:
            vlan.acl_in = self.acls[vlan.acl_in]
            build_acl(vlan.acl_in, vid=1)
    for port in list(self.ports.values()):
        if port.acl_in:
            if port.acl_in in self.acls:
                port.acl_in = self.acls[port.acl_in]
                build_acl(port.acl_in)
            else:
                assert False, "Unconfigured acl for %s" % self.name
# Buggy code
def _unpack_json_args(args):
    """Restore arguments from --json-args after a restart.

    When restarting, we serialize the argparse namespace into json, and
    construct a "fake" argparse.Namespace here based on the data loaded
    from json.
    """
    data = json.loads(args.json_args)
    return argparse.Namespace(**data)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/bin/qutebrowser", line 33, in <module>
sys.exit(load_entry_point('qutebrowser==1.14.1', 'gui_scripts', 'qutebrowser')())
File "/usr/lib/python3.9/site-packages/qutebrowser/qutebrowser.py", line 204, in main
return app.run(args)
File "/usr/lib/python3.9/site-packages/qutebrowser/app.py", line 127, in run
init(args=args)
File "/usr/lib/python3.9/site-packages/qutebrowser/app.py", line 156, in init
_init_modules(args=args)
File "/usr/lib/python3.9/site-packages/qutebrowser/app.py", line 469, in _init_modules
websettings.init(args)
File "/usr/lib/python3.9/site-packages/qutebrowser/config/websettings.py", line 271, in init
webenginesettings.init(args)
File "/usr/lib/python3.9/site-packages/qutebrowser/browser/webengine/webenginesettings.py", line 482, in init
if (args.enable_webengine_inspector and
AttributeError: 'Namespace' object has no attribute 'enable_webengine_inspector'

# Fixed code
def _unpack_json_args(args):
    """Restore arguments from --json-args after a restart.

    When restarting, we serialize the argparse namespace into json, and
    construct a "fake" argparse.Namespace here based on the data loaded
    from json.
    """
    new_args = vars(args)
    data = json.loads(args.json_args)
    new_args.update(data)
    return argparse.Namespace(**new_args)
# Buggy code
def preload_resources() -> None:
    """Load resource files into the cache."""
    resource_path = _resource_path("")
    for subdir, ext in [("html", ".html"), ("javascript", ".js")]:
        for name in _glob_resources(resource_path, subdir, ext):
            _resource_cache[name] = read_file(name)


# Traceback (FileNotFoundError)
Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/commands/runners.py", line 319, in run_safely
File "/home/florian/proj/qutebrowser/git/qutebrowser/commands/runners.py", line 374, in run
File "/home/florian/proj/qutebrowser/git/qutebrowser/commands/command.py", line 553, in run
debug_utils.format_call(self.handler, posargs, kwargs)))
File "/home/florian/proj/qutebrowser/git/qutebrowser/browser/commands.py", line 319, in openurl
self._open(cur_url, tab, bg, window, related=related,
File "/home/florian/proj/qutebrowser/git/qutebrowser/browser/commands.py", line 134, in _open
tabbed_browser.tabopen(url, background=False, related=related)
File "/home/florian/proj/qutebrowser/git/qutebrowser/mainwindow/tabbedbrowser.py", line 607, in tabopen
self.widget.insertTab(idx, tab, "")
File "/home/florian/proj/qutebrowser/git/qutebrowser/browser/browsertab.py", line 78, in create
from qutebrowser.browser.webkit import webkittab
File "/home/florian/proj/qutebrowser/git/qutebrowser/browser/webengine/webenginetab.py", line 1235, in __init__
File "/home/florian/proj/qutebrowser/git/qutebrowser/browser/webengine/webenginetab.py", line 1038, in init
self._tab = tab
File "/home/florian/proj/qutebrowser/git/qutebrowser/browser/webengine/webenginetab.py", line 1164, in _inject_site_specific_quirks
.format(
File "/home/florian/proj/qutebrowser/git/qutebrowser/utils/utils.py", line 243, in read_file
File "/usr/lib/python3.9/pathlib.py", line 1255, in read_text
with self.open(mode='r', encoding=encoding, errors=errors) as f:
File "/usr/lib/python3.9/pathlib.py", line 1241, in open
return io.open(self, mode, buffering, encoding, errors, newline,
File "/usr/lib/python3.9/pathlib.py", line 1109, in _opener
return self._accessor.open(self, flags, mode)
FileNotFoundError: [Errno 2] No such file or directory: '/home/florian/proj/qutebrowser/git/qutebrowser/javascript/quirks/whatsapp_web.user.js'

# Fixed code
def preload_resources() -> None:
    """Load resource files into the cache."""
    resource_path = _resource_path("")
    for subdir, ext in [
        ("html", ".html"),
        ("javascript", ".js"),
        ("javascript/quirks", ".js"),
    ]:
        for name in _glob_resources(resource_path, subdir, ext):
            _resource_cache[name] = read_file(name)
# Buggy code
def check_libraries():
    """Check if all needed Python libraries are installed."""
    modules = {
        "jinja2": _missing_str("jinja2"),
        "yaml": _missing_str("PyYAML"),
        "dataclasses": _missing_str("dataclasses"),
        "PyQt5.QtQml": _missing_str("PyQt5.QtQml"),
        "PyQt5.QtSql": _missing_str("PyQt5.QtSql"),
        "PyQt5.QtOpenGL": _missing_str("PyQt5.QtOpenGL"),
    }
    _check_modules(modules)


# Traceback (ModuleNotFoundError)
Traceback (most recent call last):
File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/root/qutebrowser/qutebrowser/__main__.py", line 29, in <module>
sys.exit(qutebrowser.qutebrowser.main())
File "/root/qutebrowser/qutebrowser/qutebrowser.py", line 200, in main
from qutebrowser import app
File "/root/qutebrowser/qutebrowser/app.py", line 54, in <module>
from qutebrowser.commands import runners
File "/root/qutebrowser/qutebrowser/commands/runners.py", line 31, in <module>
from qutebrowser.api import cmdutils
File "/root/qutebrowser/qutebrowser/api/cmdutils.py", line 55, in <module>
from qutebrowser.utils import qtutils
File "/root/qutebrowser/qutebrowser/utils/qtutils.py", line 49, in <module>
from qutebrowser.utils import usertypes, utils
File "/root/qutebrowser/qutebrowser/utils/usertypes.py", line 30, in <module>
from qutebrowser.utils import log, qtutils, utils
File "/root/qutebrowser/qutebrowser/utils/utils.py", line 57, in <module>
import importlib_resources
ModuleNotFoundError: No module named 'importlib_resources'

# Fixed code
def check_libraries():
    """Check if all needed Python libraries are installed."""
    modules = {
        "jinja2": _missing_str("jinja2"),
        "yaml": _missing_str("PyYAML"),
        "dataclasses": _missing_str("dataclasses"),
        "PyQt5.QtQml": _missing_str("PyQt5.QtQml"),
        "PyQt5.QtSql": _missing_str("PyQt5.QtSql"),
        "PyQt5.QtOpenGL": _missing_str("PyQt5.QtOpenGL"),
    }
    try:
        import importlib.resources
    except ImportError:
        # Backport required
        modules["importlib_resources"] = _missing_str("importlib_resources")
    _check_modules(modules)
# Buggy code
def _pop(self):
    """Pop a question from the queue and ask it, if there are any."""
    log.prompt.debug("Popping from queue {}".format(self._queue))
    if self._queue:
        question = self._queue.popleft()
        if not sip.isdeleted(question):
            # the question could already be deleted, e.g. by a cancelled
            # download. See
            # https://github.com/qutebrowser/qutebrowser/issues/415
            self.ask_question(question, blocking=False)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/lib/python3.5/site-packages/qutebrowser/app.py", line 846, in eventFilter
return handler(event)
File "/usr/lib/python3.5/site-packages/qutebrowser/app.py", line 803, in _handle_key_event
return man.eventFilter(event)
File "/usr/lib/python3.5/site-packages/qutebrowser/keyinput/modeman.py", line 317, in eventFilter
return self._eventFilter_keypress(event)
File "/usr/lib/python3.5/site-packages/qutebrowser/keyinput/modeman.py", line 169, in _eventFilter_keypress
handled = parser.handle(event)
File "/usr/lib/python3.5/site-packages/qutebrowser/keyinput/basekeyparser.py", line 301, in handle
handled = self._handle_special_key(e)
File "/usr/lib/python3.5/site-packages/qutebrowser/keyinput/basekeyparser.py", line 130, in _handle_special_key
self.execute(cmdstr, self.Type.special)
File "/usr/lib/python3.5/site-packages/qutebrowser/keyinput/keyparser.py", line 42, in execute
self._commandrunner.run(cmdstr, count)
File "/usr/lib/python3.5/site-packages/qutebrowser/commands/runners.py", line 221, in run
result.cmd.run(self._win_id, args)
File "/usr/lib/python3.5/site-packages/qutebrowser/commands/command.py", line 505, in run
self.handler(*posargs, **kwargs)
File "/usr/lib/python3.5/site-packages/qutebrowser/mainwindow/statusbar/prompter.py", line 256, in prompt_accept
self._question.done()
File "/usr/lib/python3.5/site-packages/qutebrowser/utils/usertypes.py", line 318, in done
self.answered.emit(self.answer)
RuntimeError: wrapped C/C++ object of type Question has been deleted

# Fixed code
def _pop(self):
    """Pop a question from the queue and ask it, if there are any."""
    log.prompt.debug("Popping from queue {}".format(self._queue))
    if self._queue:
        question = self._queue.popleft()
        if not question.is_aborted:
            # the question could already be aborted, e.g. by a cancelled
            # download. See
            # https://github.com/qutebrowser/qutebrowser/issues/415 and
            # https://github.com/qutebrowser/qutebrowser/issues/1249
            self.ask_question(question, blocking=False)
# Buggy code
def _is_surrogate(key):
    """Check for Unicode characters such as emoji and extended CJK characters
    Necessary to work around poor handling of higher codepoints by QKeyEvent
    This checks for unicode codepoints above ASCII range. The highest unicode
    is below Qt::Key modifiers and "special" keys, which start at 0x1000000
    """
    return 0xD800 <= key <= 0xDFFF


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 82, in _check_valid_utf8
s.encode('utf-8')
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83c' in position 0: surrogates not allowed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/app.py", line 929, in eventFilter
return handler(event)
File "/home/florian/proj/qutebrowser/git/qutebrowser/app.py", line 902, in _handle_key_event
return man.handle_event(event)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/modeman.py", line 353, in handle_event
return handler(event)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/modeman.py", line 173, in _handle_keypress
match = parser.handle(event, dry_run=dry_run)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/modeparsers.py", line 99, in handle
match = super().handle(e, dry_run=dry_run)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/basekeyparser.py", line 167, in handle
txt = str(keyutils.KeyInfo.from_event(e))
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 316, in __str__
key_string = _key_to_string(self.key)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 201, in _key_to_string
_check_valid_utf8(result, key)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 85, in _check_valid_utf8
.format(data, s, e))
ValueError: Invalid encoding in 0xd83c -> \ud83c: 'utf-8' codec can't encode character '\ud83c' in position 0: surrogates not allowed

# Fixed code
def _is_surrogate(key):
    """Check if a codepoint is a UTF-16 surrogate.

    UTF-16 surrogates are a reserved range of Unicode from 0xd800
    to 0xd8ff, used to encode Unicode codepoints above the BMP
    (Base Multilingual Plane)"""
    return 0xD800 <= key <= 0xDFFF
# Buggy code
def _remap_unicode(key, text):
    """Work around Qt having bad values for UTF-16 surrogates
    Qt events have the upper half of the UTF-16 representation as key()
    instead of the unicode codepoint. We re-parse these from text()
    """
    if _is_surrogate(key):
        if len(text) != 1:
            raise KeyParseError(text, "Key had too many characters!")
        else:
            return ord(text[0])
    else:
        return key


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 82, in _check_valid_utf8
s.encode('utf-8')
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83c' in position 0: surrogates not allowed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/app.py", line 929, in eventFilter
return handler(event)
File "/home/florian/proj/qutebrowser/git/qutebrowser/app.py", line 902, in _handle_key_event
return man.handle_event(event)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/modeman.py", line 353, in handle_event
return handler(event)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/modeman.py", line 173, in _handle_keypress
match = parser.handle(event, dry_run=dry_run)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/modeparsers.py", line 99, in handle
match = super().handle(e, dry_run=dry_run)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/basekeyparser.py", line 167, in handle
txt = str(keyutils.KeyInfo.from_event(e))
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 316, in __str__
key_string = _key_to_string(self.key)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 201, in _key_to_string
_check_valid_utf8(result, key)
File "/home/florian/proj/qutebrowser/git/qutebrowser/keyinput/keyutils.py", line 85, in _check_valid_utf8
.format(data, s, e))
ValueError: Invalid encoding in 0xd83c -> \ud83c: 'utf-8' codec can't encode character '\ud83c' in position 0: surrogates not allowed

# Fixed code
def _remap_unicode(key, text):
    """Work around QtKeyEvent's bad values for high codepoints.

    QKeyEvent handles higher unicode codepoints poorly (see
    QTBUG-72776). It uses UTF-16 to handle key events, and for
    higher codepoints that require UTF-16 surrogates (e.g. emoji
    and some CJK characters), it sets the keycode to just the
    upper half of the surrogate, which renders it useless, and
    breaks UTF-8 encoding, causing crashes. So we detect this
    case, and reassign the key code to be the full Unicode
    codepoint, which we can recover from the text() property,
    wihch has the full character."""
    if _is_surrogate(key):
        if len(text) != 1:
            raise KeyParseError(text, "Key had too many characters!")
        else:
            return ord(text[0])
    else:
        return key