gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_resource_tags(resource_type, entity_config):
    if "_" not in resource_type:
        return None  # probably not a resource block
    provider = resource_type[: resource_type.index("_")]
    provider_tag_function = provider_tag_mapping.get(provider)
    if provider_tag_function:
        return provider_tag_function(entity_config)
    else:
        return None


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/robeden/git/third-party/checkov/checkov/common/checks/base_check.py", line 62, in run
raise e
File "/Users/robeden/git/third-party/checkov/checkov/common/checks/base_check.py", line 42, in run
check_result['result'] = self.scan_entity_conf(entity_configuration, entity_type)
File "/Users/robeden/git/third-party/checkov/checkov/terraform/checks/resource/base_resource_check.py", line 16, in scan_entity_conf
self.handle_dynamic_values(conf)
File "/Users/robeden/git/third-party/checkov/checkov/terraform/checks/resource/base_resource_check.py", line 38, in handle_dynamic_values
for dynamic_element in conf.get("dynamic", []):
AttributeError: 'list' object has no attribute 'get'

# Fixed code
def get_resource_tags(resource_type, entity_config):
    if not isinstance(entity_config, dict):
        return None

    if "_" not in resource_type:
        return None  # probably not a resource block
    provider = resource_type[: resource_type.index("_")]
    provider_tag_function = provider_tag_mapping.get(provider)
    if provider_tag_function:
        return provider_tag_function(entity_config)
    else:
        return None
# Buggy code
def scan_resource_conf(self, conf):
    """
        Looks for configuration at security group ingress rules :
        https://www.terraform.io/docs/providers/aws/r/security_group.html
    :param conf: aws_security_group configuration
    :return: <CheckResult>
    """
    if "ingress" in conf.keys():
        ingress_conf = conf["ingress"]
        for rule in ingress_conf:
            if (
                rule["from_port"] == [PORT]
                and rule["to_port"] == [PORT]
                and rule["cidr_blocks"] == [["0.0.0.0/0"]]
                and "self" not in rule.keys()
                and "security_groups" not in rule.keys()
            ):
                return CheckResult.FAILED

    return CheckResult.PASSED


# Traceback (KeyError)
Traceback (most recent call last):
File "/path/tf-checks/bin/checkov", line 34, in <module>
report = Runner().run(root_folder, external_checks_dir=args.external_checks_dir)
File "/path/tf-checks/lib/python3.7/site-packages/checkov/terraform/runner.py", line 38, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/pathtf-checks/lib/python3.7/site-packages/checkov/terraform/checks/resource/registry.py", line 38, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/path/tf-checks/lib/python3.7/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/path/tf-checks/lib/python3.7/site-packages/checkov/terraform/checks/resource/aws/SecurityGroupUnrestrictedIngress22.py", line 25, in scan_resource_conf
if rule['from_port'] == [PORT] and rule['to_port'] == [PORT] and rule['cidr_blocks'] == [[
KeyError: 'cidr_blocks'

# Fixed code
def scan_resource_conf(self, conf):
    """
        Looks for configuration at security group ingress rules :
        https://www.terraform.io/docs/providers/aws/r/security_group.html
    :param conf: aws_security_group configuration
    :return: <CheckResult>
    """
    if "ingress" in conf.keys():
        ingress_conf = conf["ingress"]
        for rule in ingress_conf:
            if rule["from_port"] == [PORT] and rule["to_port"] == [PORT]:
                if "cidr_blocks" in rule.keys():
                    if (
                        rule["cidr_blocks"] == [["0.0.0.0/0"]]
                        and "security_groups" not in rule.keys()
                    ):
                        return CheckResult.FAILED

    return CheckResult.PASSED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "max_password_age"
    if key in conf.keys():
        if conf[key] >= 90:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "max_password_age"
    if key in conf.keys():
        if conf[key][0] >= 90:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "minimum_password_length"
    if key in conf.keys():
        if conf[key] >= 14:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "minimum_password_length"
    if key in conf.keys():
        if conf[key][0] >= 14:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_lowercase_characters"
    if key in conf.keys():
        if conf[key]:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_lowercase_characters"
    if key in conf.keys():
        if conf[key][0]:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_numbers"
    if key in conf.keys():
        if conf[key]:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_numbers"
    if key in conf.keys():
        if conf[key][0]:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "password_reuse_prevention"
    if key in conf.keys():
        if conf[key] >= 24:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "password_reuse_prevention"
    if key in conf.keys():
        if conf[key][0] >= 24:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_symbols"
    if key in conf.keys():
        if conf[key]:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_symbols"
    if key in conf.keys():
        if conf[key][0]:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_uppercase_characters"
    if key in conf.keys():
        if conf[key]:
            return CheckResult.PASSED
    return CheckResult.FAILED


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/arkadiyt/.pyenv/versions/3.6.0/bin/checkov", line 24, in <module>
report = Runner().run(root_folder)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/runner.py", line 34, in run
results = resource_registry.scan(resource, scanned_file, skipped_checks)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/registry.py", line 34, in scan
resource_name=resource_name, resource_type=resource, skip_info=skip_info)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/base_check.py", line 31, in run
check_result['result'] = self.scan_resource_conf(resource_configuration)
File "/Users/arkadiyt/.pyenv/versions/3.6.0/lib/python3.6/site-packages/checkov/terraform/checks/resource/aws/PasswordPolicyLength.py", line 22, in scan_resource_conf
if conf[key] >= 14:
TypeError: '>=' not supported between instances of 'list' and 'int'

# Fixed code
def scan_resource_conf(self, conf):
    """
        validates iam password policy
        https://www.terraform.io/docs/providers/aws/r/iam_account_password_policy.html
    :param conf: aws_iam_account_password_policy configuration
    :return: <CheckResult>
    """
    key = "require_uppercase_characters"
    if key in conf.keys():
        if conf[key][0]:
            return CheckResult.PASSED
    return CheckResult.FAILED
# Buggy code
def initialize(
    self,
    path,
    default_filename=None,
    as_attachment=False,
    allow_client_caching=True,
    access_validation=None,
    path_validation=None,
    etag_generator=None,
    name_generator=None,
    mime_type_guesser=None,
    is_pre_compressed=False,
):
    tornado.web.StaticFileHandler.initialize(
        self, os.path.abspath(path), default_filename
    )
    self._as_attachment = as_attachment
    self._allow_client_caching = allow_client_caching
    self._access_validation = access_validation
    self._path_validation = path_validation
    self._etag_generator = etag_generator
    self._name_generator = name_generator
    self._mime_type_guesser = mime_type_guesser
    self._is_pre_compressed = is_pre_compressed


# Traceback (tornado.httputil.HTTPOutputError)
2020-09-14 12:32:33,718 - tornado.application - ERROR - Uncaught exception GET /downloads/logs/octoprint.log (::ffff:73.122.180.167)
Traceback (most recent call last):
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/web.py", line 1592, in _execute
result = yield result
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/gen.py", line 1133, in run
value = future.result()
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/gen.py", line 1147, in run
yielded = self.gen.send(value)
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/web.py", line 2528, in get
yield self.flush()
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/web.py", line 1000, in flush
return self.request.connection.write(chunk, callback=callback)
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/http1connection.py", line 451, in write
self._pending_write = self.stream.write(self._format_chunk(chunk))
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/http1connection.py", line 424, in _format_chunk
"Tried to write more data than Content-Length")
tornado.httputil.HTTPOutputError: Tried to write more data than Content-Length

# Fixed code
def initialize(
    self,
    path,
    default_filename=None,
    as_attachment=False,
    allow_client_caching=True,
    access_validation=None,
    path_validation=None,
    etag_generator=None,
    name_generator=None,
    mime_type_guesser=None,
    is_pre_compressed=False,
    stream_body=False,
):
    tornado.web.StaticFileHandler.initialize(
        self, os.path.abspath(path), default_filename
    )
    self._as_attachment = as_attachment
    self._allow_client_caching = allow_client_caching
    self._access_validation = access_validation
    self._path_validation = path_validation
    self._etag_generator = etag_generator
    self._name_generator = name_generator
    self._mime_type_guesser = mime_type_guesser
    self._is_pre_compressed = is_pre_compressed
    self._stream_body = stream_body
# Buggy code
def get(self, path, include_body=True):
    if self._access_validation is not None:
        self._access_validation(self.request)
    if self._path_validation is not None:
        self._path_validation(path)

    if "cookie" in self.request.arguments:
        self.set_cookie(self.request.arguments["cookie"][0], "true", path="/")

    if self.should_use_precompressed():
        if os.path.exists(os.path.join(self.root, path + ".gz")):
            self.set_header("Content-Encoding", "gzip")
            path = path + ".gz"
        else:
            logging.getLogger(__name__).warning(
                "Precompressed assets expected but {}.gz does not exist "
                "in {}, using plain file instead.".format(path, self.root)
            )

    return tornado.web.StaticFileHandler.get(self, path, include_body=include_body)


# Traceback (tornado.httputil.HTTPOutputError)
2020-09-14 12:32:33,718 - tornado.application - ERROR - Uncaught exception GET /downloads/logs/octoprint.log (::ffff:73.122.180.167)
Traceback (most recent call last):
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/web.py", line 1592, in _execute
result = yield result
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/gen.py", line 1133, in run
value = future.result()
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/gen.py", line 1147, in run
yielded = self.gen.send(value)
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/web.py", line 2528, in get
yield self.flush()
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/web.py", line 1000, in flush
return self.request.connection.write(chunk, callback=callback)
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/http1connection.py", line 451, in write
self._pending_write = self.stream.write(self._format_chunk(chunk))
File "/home/pi/oprint/lib/python3.7/site-packages/tornado/http1connection.py", line 424, in _format_chunk
"Tried to write more data than Content-Length")
tornado.httputil.HTTPOutputError: Tried to write more data than Content-Length

# Fixed code
def get(self, path, include_body=True):
    if self._access_validation is not None:
        self._access_validation(self.request)
    if self._path_validation is not None:
        self._path_validation(path)

    if "cookie" in self.request.arguments:
        self.set_cookie(self.request.arguments["cookie"][0], "true", path="/")

    if self.should_use_precompressed():
        if os.path.exists(os.path.join(self.root, path + ".gz")):
            self.set_header("Content-Encoding", "gzip")
            path = path + ".gz"
        else:
            logging.getLogger(__name__).warning(
                "Precompressed assets expected but {}.gz does not exist "
                "in {}, using plain file instead.".format(path, self.root)
            )

    if self._stream_body:
        return self.streamed_get(path, include_body=include_body)
    else:
        return tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
# Buggy code
def f(request):
    """
    Creates a custom wsgi and Flask request context in order to be able to process user information
    stored in the current session.

    :param request: The Tornado request for which to create the environment and context
    """
    import flask

    wsgi_environ = WsgiInputContainer.environ(request)
    with app.request_context(wsgi_environ):
        app.session_interface.open_session(app, flask.request)
        app.login_manager.reload_user()
        validator(flask.request, *args)


# Traceback (AttributeError)
2020-06-11 22:08:49,879 - tornado.application - ERROR - Uncaught exception GET /downloads/timelapse/circle_20200611141803-fail.mpg (10.125.0.1)
Traceback (most recent call last):
File "/home/bzed/tools/OctoPrint/venv/lib/python3.7/site-packages/tornado/web.py", line 1590, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/home/bzed/tools/OctoPrint/src/octoprint/server/util/tornado.py", line 1006, in get
self._access_validation(self.request)
File "/home/bzed/tools/OctoPrint/src/octoprint/server/util/tornado.py", line 1305, in f
validator(request)
File "/home/bzed/tools/OctoPrint/src/octoprint/server/util/tornado.py", line 1285, in f
app.login_manager.reload_user()
AttributeError: 'LoginManager' object has no attribute 'reload_user'

# Fixed code
def f(request):
    """
    Creates a custom wsgi and Flask request context in order to be able to process user information
    stored in the current session.

    :param request: The Tornado request for which to create the environment and context
    """
    import flask

    wsgi_environ = WsgiInputContainer.environ(request)
    with app.request_context(wsgi_environ):
        session = app.session_interface.open_session(app, flask.request)
        user_id = session.get("user_id")
        user = None

        # Yes, using protected methods is ugly. But these used to be publicly available in former versions
        # of flask-login, there are no replacements, and seeing them renamed & hidden in a minor version release
        # without any mention in the changelog means the public API ain't strictly stable either, so we might
        # as well make our life easier here and just use them...
        if user_id is not None and app.login_manager._user_callback is not None:
            user = app.login_manager._user_callback(user_id)
        app.login_manager._update_request_context_with_user(user)

        validator(flask.request, *args)
# Buggy code
def __init__(self):
    self._logger = logging.getLogger(__name__)

    self.on_log_call = lambda *args, **kwargs: None
    """Callback for the called command line"""

    self.on_log_stdout = lambda *args, **kwargs: None
    """Callback for stdout output"""

    self.on_log_stderr = lambda *args, **kwargs: None
    """Callback for stderr output"""


# Traceback (TypeError)
2019-12-31 14:26:39,831 - octoprint.util.comm - INFO - Changing monitoring state from "Cancelling" to "Operational"
2019-12-31 14:26:40,448 - octoprint.timelapse - ERROR - Could not render movie due to unknown error
Traceback (most recent call last):
File "/home/pi/OctoPrint/venv/lib/python3.7/site-packages/octoprint/timelapse.py", line 901, in _render
returncode, stdout_text, stderr_text = c.call(command_str, universal_newlines=True)
File "/home/pi/OctoPrint/venv/lib/python3.7/site-packages/octoprint/util/commandline.py", line 209, in call
all_stderr += process_stderr(p.stderr.readlines(timeout=0.5))
File "/home/pi/OctoPrint/venv/lib/python3.7/site-packages/sarge/__init__.py", line 352, in readlines
data = self.read(sizehint, block, timeout)
File "/home/pi/OctoPrint/venv/lib/python3.7/site-packages/sarge/__init__.py", line 296, in read
result = b''.join(b)
TypeError: sequence item 0: expected a bytes-like object, str found

# Fixed code
def __init__(self, delimiter=b"\n", *args, **kwargs):
    self._delimiter = delimiter
    sarge.Capture.__init__(self, *args, **kwargs)
# Buggy code
def decorator(func):
    func.__qualname__ = to_native_str("warning_decorator_factory")
    func.__annotations__ = dict()

    @wraps(func)
    def func_wrapper(*args, **kwargs):
        # we need to increment the stacklevel by one because otherwise we'll get the location of our
        # func_wrapper in the log, instead of our caller (which is the real caller of the wrapped function)
        warnings.warn(message, warning_type, stacklevel=stacklevel + 1)
        return func(*args, **kwargs)

    if includedoc is not None and since is not None:
        docstring = "\n.. deprecated:: {since}\n   {message}\n\n".format(
            since=since, message=includedoc
        )
        if (
            extenddoc
            and hasattr(func_wrapper, "__doc__")
            and func_wrapper.__doc__ is not None
        ):
            docstring = func_wrapper.__doc__ + "\n" + docstring
        func_wrapper.__doc__ = docstring

    return func_wrapper


# Traceback (AttributeError)
2019-11-25 17:59:12,930 - octoprint.plugin - ERROR - Error while calling plugin fanspeedslider
Traceback (most recent call last):
File "/home/nas/OctoPrint/venv/local/lib/python2.7/site-packages/octoprint/plugin/__init__.py", line 224, in call_plugin
result = getattr(plugin, method)(*args, **kwargs)
File "/home/nas/OctoPrint/venv/local/lib/python2.7/site-packages/octoprint_fanspeedslider/__init__.py", line 19, in on_after_startup
self.get_settings_updates()
File "/home/nas/OctoPrint/venv/local/lib/python2.7/site-packages/octoprint_fanspeedslider/__init__.py", line 90, in get_settings_updates
self.defaultFanSpeed = self._settings.getInt(["defaultFanSpeed"])
File "/home/nas/OctoPrint/venv/local/lib/python2.7/site-packages/octoprint/plugin/__init__.py", line 521, in __getattr__
orig_func = decorator(orig_func)
File "/home/nas/OctoPrint/venv/local/lib/python2.7/site-packages/octoprint/util/__init__.py", line 134, in decorator
func.__qualname__ = to_native_str('warning_decorator_factory')
AttributeError: 'instancemethod' object has no attribute '__qualname__'

# Fixed code
def decorator(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        # we need to increment the stacklevel by one because otherwise we'll get the location of our
        # func_wrapper in the log, instead of our caller (which is the real caller of the wrapped function)
        warnings.warn(message, warning_type, stacklevel=stacklevel + 1)
        return func(*args, **kwargs)

    if includedoc is not None and since is not None:
        docstring = "\n.. deprecated:: {since}\n   {message}\n\n".format(
            since=since, message=includedoc
        )
        if (
            extenddoc
            and hasattr(func_wrapper, "__doc__")
            and func_wrapper.__doc__ is not None
        ):
            docstring = func_wrapper.__doc__ + "\n" + docstring
        func_wrapper.__doc__ = docstring

    return func_wrapper
# Buggy code
def permission_validator(request, permission):
    """
    Validates that the given request is made by an authorized user, identified either by API key or existing Flask
    session.

    Must be executed in an existing Flask request context!

    :param request: The Flask request object
    :param request: The required permission
    """

    user = get_flask_user_from_request(request)
    if user is None or not user.is_authenticated or not user.has_permission(permission):
        raise tornado.web.HTTPError(403)


# Traceback (AttributeError)
2018-08-03 16:57:12,579 - tornado.application - ERROR - Uncaught exception GET /downloads/files/local/test.gcode (127.0.0.1)
Traceback (most recent call last):
File "~/OctoPrint/venv/local/lib/python2.7/site-packages/tornado/web.py", line 1510, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "~/OctoPrint/src/octoprint/server/util/tornado.py", line 918, in get
self._access_validation(self.request)
File "~/OctoPrint/src/octoprint/server/util/tornado.py", line 1150, in f
validator(flask.request, permission)
File "~/OctoPrint/src/octoprint/server/util/flask.py", line 1066, in permission_validator
user = _get_flask_user_from_request(request)
File "~/OctoPrint/src/octoprint/server/util/flask.py", line 1093, in _get_flask_user_from_request
user = octoprint.server.util.get_user_for_apikey(apikey)
File "~/OctoPrint/src/octoprint/server/util/__init__.py", line 187, in get_user_for_apikey
return octoprint.server.userManager.find_user(session=flask_login.current_user.session)
File "~/OctoPrint/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'AnonymousUser' object has no attribute 'session'
2018-08-03 16:57:12,581 - tornado.access - ERROR - 500 GET /downloads/files/local/test.gcode (127.0.0.1) 3.56ms

# Fixed code
def permission_validator(request, permission):
    """
    Validates that the given request is made by an authorized user, identified either by API key or existing Flask
    session.

    Must be executed in an existing Flask request context!

    :param request: The Flask request object
    :param request: The required permission
    """

    user = get_flask_user_from_request(request)
    if not user.has_permission(permission):
        raise tornado.web.HTTPError(403)
# Buggy code
def get_flask_user_from_request(request):
    """
    Retrieves the current flask user from the request context. Uses API key if available, otherwise the current
    user session if available.

    :param request: flask request from which to retrieve the current user
    :return: the user or None if no user could be determined
    """
    import octoprint.server.util
    import flask_login

    user = None

    apikey = octoprint.server.util.get_api_key(request)
    if apikey is not None:
        user = octoprint.server.util.get_user_for_apikey(apikey)

    if user is None:
        user = flask_login.current_user

    return user


# Traceback (AttributeError)
2018-08-03 16:57:12,579 - tornado.application - ERROR - Uncaught exception GET /downloads/files/local/test.gcode (127.0.0.1)
Traceback (most recent call last):
File "~/OctoPrint/venv/local/lib/python2.7/site-packages/tornado/web.py", line 1510, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "~/OctoPrint/src/octoprint/server/util/tornado.py", line 918, in get
self._access_validation(self.request)
File "~/OctoPrint/src/octoprint/server/util/tornado.py", line 1150, in f
validator(flask.request, permission)
File "~/OctoPrint/src/octoprint/server/util/flask.py", line 1066, in permission_validator
user = _get_flask_user_from_request(request)
File "~/OctoPrint/src/octoprint/server/util/flask.py", line 1093, in _get_flask_user_from_request
user = octoprint.server.util.get_user_for_apikey(apikey)
File "~/OctoPrint/src/octoprint/server/util/__init__.py", line 187, in get_user_for_apikey
return octoprint.server.userManager.find_user(session=flask_login.current_user.session)
File "~/OctoPrint/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'AnonymousUser' object has no attribute 'session'
2018-08-03 16:57:12,581 - tornado.access - ERROR - 500 GET /downloads/files/local/test.gcode (127.0.0.1) 3.56ms

# Fixed code
def get_flask_user_from_request(request):
    """
    Retrieves the current flask user from the request context. Uses API key if available, otherwise the current
    user session if available.

    :param request: flask request from which to retrieve the current user
    :return: the user (might be an anonymous user)
    """
    import octoprint.server.util
    import flask_login

    user = None

    apikey = octoprint.server.util.get_api_key(request)
    if apikey is not None:
        # user from api key?
        user = octoprint.server.util.get_user_for_apikey(apikey)

    if user is None:
        # user still None -> current session user
        user = flask_login.current_user

    if user is None:
        # user still None -> anonymous
        from octoprint.server import userManager

        user = userManager.anonymous_user_factory()

    return user
# Buggy code
def get_python_version_string():
    from platform import python_version

    version_string = python_version()

    # Debian has the python version set to 2.7.15+ which is not PEP440 compliant (bug 914072)
    if version_string.endswith("+"):
        version_string = python_version[:-1]

    return version_string


# Traceback (TypeError)
2019-08-21 11:55:47,421 - octoprint.plugin - ERROR - Error while calling plugin softwareupdate
Traceback (most recent call last):
File "/home/multipass/OctoPrint/src/octoprint/plugin/__init__.py", line 219, in call_plugin
result = getattr(plugin, method)(*args, **kwargs)
File "/home/multipass/OctoPrint/src/octoprint/plugins/softwareupdate/__init__.py", line 102, in on_after_startup
self._check_environment()
File "/home/multipass/OctoPrint/src/octoprint/plugins/softwareupdate/__init__.py", line 184, in _check_environment
versions = dict(python=get_python_version_string(),
File "/home/multipass/OctoPrint/src/octoprint/util/version.py", line 126, in get_python_version_string
version_string = python_version[:-1]
TypeError: 'function' object has no attribute '__getitem__'

# Fixed code
def get_python_version_string():
    from platform import python_version

    version_string = python_version()

    # Debian has the python version set to 2.7.15+ which is not PEP440 compliant (bug 914072)
    if version_string.endswith("+"):
        version_string = version_string[:-1]

    return version_string
# Buggy code
def average_total_rolling(self):
    if not self._count or self._count < self._rolling_window:
        return None
    else:
        return sum(self._totals) / len(self._totals)


# Traceback (ZeroDivisionError)
2019-04-08 17:22:53,104 - octoprint.printer.standard - ERROR - Looks like something crashed inside the state update worker. Please report this on the OctoPrint issue tracker (make sure to include logs!)
Traceback (most recent call last):
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1346, in _work
data = self.get_current_data()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1356, in get_current_data
self._progress = self._get_current_progress()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1282, in _get_current_progress
return self._on_get_progress()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 793, in _updateProgressDataCallback
statisticalTotalPrintTimeType)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 106, in estimate
estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 166, in estimate_total
return self._data.update(printTime / progress)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 207, in update
if -1.0 * self._threshold < self.average_distance < self._threshold:
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 239, in average_distance
return sum(self._distances) / len(self._distances)
ZeroDivisionError: division by zero

# Fixed code
def average_total_rolling(self):
    if not self._count or self._count < self._rolling_window or not len(self._totals):
        return None
    else:
        return sum(self._totals) / len(self._totals)
# Buggy code
def average_distance(self):
    if not self._count or self._count < self._rolling_window + 1:
        return None
    else:
        return sum(self._distances) / len(self._distances)


# Traceback (ZeroDivisionError)
2019-04-08 17:22:53,104 - octoprint.printer.standard - ERROR - Looks like something crashed inside the state update worker. Please report this on the OctoPrint issue tracker (make sure to include logs!)
Traceback (most recent call last):
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1346, in _work
data = self.get_current_data()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1356, in get_current_data
self._progress = self._get_current_progress()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1282, in _get_current_progress
return self._on_get_progress()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 793, in _updateProgressDataCallback
statisticalTotalPrintTimeType)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 106, in estimate
estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 166, in estimate_total
return self._data.update(printTime / progress)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 207, in update
if -1.0 * self._threshold < self.average_distance < self._threshold:
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/estimation.py", line 239, in average_distance
return sum(self._distances) / len(self._distances)
ZeroDivisionError: division by zero

# Fixed code
def average_distance(self):
    if (
        not self._count
        or self._count < self._rolling_window + 1
        or not len(self._distances)
    ):
        return None
    else:
        return sum(self._distances) / len(self._distances)
# Buggy code
def to_ipnetwork(address):
    try:
        prefix = address["netmask"]
        if "/" in prefix:
            # v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
            _, prefix = prefix.split("/")

        addr = address["addr"]
        if "%" in addr:
            # interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0"
            addr = addr[: addr.find("%")]
        return netaddr.IPNetwork("{}/{}".format(addr, prefix))
    except:
        pass


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/pi/oprint/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/pi/oprint/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/pi/oprint/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/pi/oprint/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/pi/oprint/local/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/server/views.py", line 404, in index
if plugin.will_handle_ui(request):
File "/home/pi/oprint/lib/python2.7/site-packages/octoprint/plugins/forcelogin/__init__.py", line 29, in will_handle_ui
result = passive_login()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/server/util/flask.py", line 531, in passive_login
additional_private=ipCheckTrusted)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/util/net.py", line 59, in is_lan_address
subnets.add(to_ipnetwork(v6))
File "/home/pi/oprint/local/lib/python2.7/site-packages/netaddr/ip/sets.py", line 293, in add
addr = IPNetwork(addr)
File "/home/pi/oprint/local/lib/python2.7/site-packages/netaddr/ip/__init__.py", line 928, in __init__
implicit_prefix, flags)
File "/home/pi/oprint/local/lib/python2.7/site-packages/netaddr/ip/__init__.py", line 823, in parse_ip_network
raise TypeError('unexpected type %s for addr arg' % type(addr))
TypeError: unexpected type <type 'NoneType'> for addr arg

# Fixed code
def to_ipnetwork(address):
    prefix = address["netmask"]
    if "/" in prefix:
        # v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
        _, prefix = prefix.split("/")

    addr = address["addr"]
    if "%" in addr:
        # interface comment in netifaces output, e.g. "fe80::457f:bbee:d579:1063%wlan0"
        addr = addr[: addr.find("%")]
    return netaddr.IPNetwork("{}/{}".format(addr, prefix))
# Buggy code
def _create_estimator(self, job_type):
    self._estimator = self._estimator_factory(job_type)


# Traceback (AttributeError)
2018-07-05 05:17:16,231 - octoprint.util.comm - INFO - Externally triggered heatup detected
2018-07-05 05:18:34,517 - octoprint.util.comm - INFO - Printer seems to support the busy protocol, telling it to set the busy interval to our "communicationBusy" timeout - 1s = 2s
2018-07-05 05:19:27,589 - octoprint.util.comm - INFO - Timeout while in an active heatup, considering heatup to be over.
2018-07-05 05:19:30,594 - octoprint.util.comm - INFO - Communication timeout while idle, trying to trigger response from printer.
2018-07-05 05:19:32,426 - octoprint.util.comm - INFO - Changing monitoring state from "Operational" to "Printing from SD"
2018-07-05 05:19:32,512 - octoprint.plugins.Octoslack - ERROR - Error processing event: PrintStarted, Error: 'Printer' object has no attribute '_estimator'
Traceback (most recent call last):
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint_Octoslack/__init__.py", line 591, in handle_event
self.process_slack_event(event, event_settings, channel_override, payload)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint_Octoslack/__init__.py", line 648, in process_slack_event
printer_data = self._printer.get_current_data()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/server/__init__.py", line 384, in wrapper
return f(*args, **kwargs)
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 565, in get_current_data
return util.thaw_frozendict(self._stateMonitor.get_current_data())
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1326, in get_current_data
self._progress = self._get_current_progress()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 1255, in _get_current_progress
return self._on_get_progress()
File "/home/pi/oprint/local/lib/python2.7/site-packages/octoprint/printer/standard.py", line 773, in _updateProgressDataCallback
printTimeLeft, printTimeLeftOrigin = self._estimator.estimate(progress,
AttributeError: 'Printer' object has no attribute '_estimator'
2018-07-05 05:20:41,680 - octoprint.util.comm - INFO - Communication timeout while printing, trying to trigger response from printer.
2018-07-05 05:20:41,718 - octoprint.util.comm - INFO - Changing monitoring state from "Printing from SD" to "Cancelling"
2018-07-05 05:20:41,880 - octoprint.util.comm - INFO - Changing monitoring state from "Cancelling" to "Operational"
2018-07-05 05:21:35,678 - octoprint.server.api.system - INFO - Performing command for core:restart: sudo service octoprint restart

# Fixed code
def _create_estimator(self, job_type=None):
    if job_type is None:
        with self._selectedFileMutex:
            if self._selectedFile is None:
                return

            if self._selectedFile["sd"]:
                job_type = "sdcard"
            else:
                job_type = "local"

    self._estimator = self._estimator_factory(job_type)