gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, module):
    self.module = module
    self.name = module.params["name"]
    if self.platform == "Linux" and Facts(module).is_systemd_managed():
        self.strategy = SystemdStrategy(module)
    else:
        self.strategy = self.strategy_class(module)


# Traceback (NameError)
74024 1496367398.68545: _low_level_execute_command() done: rc=0, stdout=
Traceback (most recent call last):
File "/tmp/ansible_OtWEyM/ansible_module_hostname.py", line 766, in <module>
main()
File "/tmp/ansible_OtWEyM/ansible_module_hostname.py", line 755, in main
hostname = Hostname(module)
File "/tmp/ansible_OtWEyM/ansible_module_hostname.py", line 115, in __init__
if self.platform == 'Linux' and Facts(module).is_systemd_managed():
NameError: global name 'Facts' is not defined
, stderr=OpenSSH_7.4p1, LibreSSL 2.5.0

# Fixed code
def __init__(self, module):
    self.module = module
    self.name = module.params["name"]
    if self.platform == "Linux" and ServiceMgrFactCollector.is_systemd_managed(module):
        self.strategy = SystemdStrategy(module)
    else:
        self.strategy = self.strategy_class(module)
# Buggy code
def update_fields(p):
    """This updates the module field names
    to match the field names tower-cli expects to make
    calling of the modify/delete methods easier.
    """
    params = p.copy()
    field_map = {
        "ask_extra_vars": "ask_variables_on_launch",
        "ask_limit": "ask_limit_on_launch",
        "ask_tags": "ask_tags_on_launch",
        "ask_job_type": "ask_job_type_on_launch",
        "machine_credential": "credential",
    }

    params_update = {}
    for old_k, new_k in field_map.items():
        v = params.pop(old_k)
        params_update[new_k] = v

    extra_vars = params.get("extra_vars_path")
    if extra_vars is not None:
        params_update["extra_vars"] = "@" + extra_vars

    params.update(params_update)
    return params


# Traceback (IOError)
TASK [tower_config : Create aws-infrastructure job template] ****************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IOError: [Errno 2] No such file or directory: ''
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_VOikLO/ansible_module_tower_job_template.py\", line 329, in <module>\n    main()\n  File \"/tmp/ansible_VOikLO/ansible_module_tower_job_template.py\", line 316, in main\n    result = jt.modify(**params)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/models/base.py\", line 1234, in modify\n    force_on_exists=True, **kwargs)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/resources/job_template.py\", line 107, in write\n    return super(Resource, self).write(*args, **kwargs)\n  File \"/usr/lib/python2.7/site-packages/tower_cli/models/base.py\", line 1249, in write\n    kwargs['extra_vars'])\n  File \"/usr/lib/python2.7/site-packages/tower_cli/utils/parser.py\", line 123, in process_extra_vars\n    with open(extra_vars_opt[1:], 'r') as f:\nIOError: [Errno 2] No such file or directory: ''\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}
to retry, use: --limit @/home/ec2-user/openshift-ansible-contrib/reference-architecture/ansible-tower-integration/tower_config/tower_config.retry

# Fixed code
def update_fields(p):
    """This updates the module field names
    to match the field names tower-cli expects to make
    calling of the modify/delete methods easier.
    """
    params = p.copy()
    field_map = {
        "ask_extra_vars": "ask_variables_on_launch",
        "ask_limit": "ask_limit_on_launch",
        "ask_tags": "ask_tags_on_launch",
        "ask_job_type": "ask_job_type_on_launch",
        "machine_credential": "credential",
    }

    params_update = {}
    for old_k, new_k in field_map.items():
        v = params.pop(old_k)
        params_update[new_k] = v

    extra_vars = params.get("extra_vars_path")
    if extra_vars is not None:
        params_update["extra_vars"] = ["@" + extra_vars]

    params.update(params_update)
    return params
# Buggy code
def load_config(
    module,
    candidate,
    warnings,
    action="merge",
    commit=False,
    format="xml",
    comment=None,
    confirm=False,
    confirm_timeout=None,
):
    with locked_config(module):
        if isinstance(candidate, list):
            candidate = "\n".join(candidate)

        reply = load_configuration(module, candidate, action=action, format=format)
        if isinstance(reply, list):
            warnings.extend(reply)

        validate(module)
        diff = get_diff(module)

        if diff:
            if commit:
                commit_configuration(
                    module,
                    confirm=confirm,
                    comment=comment,
                    confirm_timeout=confirm_timeout,
                )
            else:
                discard_changes(module)

        return diff


# Traceback (IndexError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IndexError: list assignment index out of range
fatal: [vmx1.retevia.eu]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 342, in <module>\n    main()\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 332, in main\n    diff = configure_device(module, warnings)\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 264, in configure_device\n    candidate = filter_delete_statements(module, candidate)\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 231, in filter_delete_statements\n    del modified_candidate[index]\nIndexError: list assignment index out of range\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def load_config(
    module,
    candidate,
    warnings,
    action="merge",
    commit=False,
    format="xml",
    comment=None,
    confirm=False,
    confirm_timeout=None,
):
    if not candidate:
        return

    with locked_config(module):
        if isinstance(candidate, list):
            candidate = "\n".join(candidate)

        reply = load_configuration(module, candidate, action=action, format=format)
        if isinstance(reply, list):
            warnings.extend(reply)

        validate(module)
        diff = get_diff(module)

        if diff:
            if commit:
                commit_configuration(
                    module,
                    confirm=confirm,
                    comment=comment,
                    confirm_timeout=confirm_timeout,
                )
            else:
                discard_changes(module)

        return diff
# Buggy code
def filter_delete_statements(module, candidate):
    reply = get_configuration(module, format="set")
    match = reply.find(".//configuration-set")
    if match is None:
        # Could not find configuration-set in reply, perhaps device does not support it?
        return candidate
    config = to_native(match.text, encoding="latin1")

    modified_candidate = candidate[:]
    for index, line in enumerate(candidate):
        if line.startswith("delete"):
            newline = re.sub("^delete", "set", line)
            if newline not in config:
                del modified_candidate[index]

    return modified_candidate


# Traceback (IndexError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IndexError: list assignment index out of range
fatal: [vmx1.retevia.eu]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 342, in <module>\n    main()\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 332, in main\n    diff = configure_device(module, warnings)\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 264, in configure_device\n    candidate = filter_delete_statements(module, candidate)\n  File \"/var/folders/xs/nwtp76d53vv5_4mvq3cyfsrh0000gn/T/ansible__wWeAO/ansible_module_junos_config.py\", line 231, in filter_delete_statements\n    del modified_candidate[index]\nIndexError: list assignment index out of range\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def filter_delete_statements(module, candidate):
    reply = get_configuration(module, format="set")
    match = reply.find(".//configuration-set")
    if match is None:
        # Could not find configuration-set in reply, perhaps device does not support it?
        return candidate
    config = to_native(match.text, encoding="latin1")

    modified_candidate = candidate[:]
    for index, line in reversed(list(enumerate(candidate))):
        if line.startswith("delete"):
            newline = re.sub("^delete", "set", line)
            if newline not in config:
                del modified_candidate[index]

    return modified_candidate
# Buggy code
def container_names_in_network(network):
    return [c["Name"] for c in network["Containers"].values()]


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 392, in <module>
main()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 385, in main
cm = DockerNetworkManager(client)
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 218, in __init__
self.present()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 352, in present
self.disconnect_missing()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 323, in disconnect_missing
for c in self.existing_network['Containers'].values():
AttributeError: 'NoneType' object has no attribute 'values'

failed: [192.168.1.120 -> 127.0.0.1] (item={u'driver': u'overlay', u'name': u'networks_default_1'}) => {
"failed": true,
"item": {
"driver": "overlay",
"name": "networks_default_1"
},
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 392, in <module>\n    main()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 385, in main\n    cm = DockerNetworkManager(client)\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 218, in __init__\n    self.present()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 352, in present\n    self.disconnect_missing()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 323, in disconnect_missing\n    for c in self.existing_network['Containers'].values():\nAttributeError: 'NoneType' object has no attribute 'values'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0

# Fixed code
def container_names_in_network(network):
    return (
        [c["Name"] for c in network["Containers"].values()]
        if network["Containers"]
        else []
    )
# Buggy code
def disconnect_missing(self):
    for c in self.existing_network["Containers"].values():
        name = c["Name"]
        if name not in self.parameters.connected:
            self.disconnect_container(name)


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 392, in <module>
main()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 385, in main
cm = DockerNetworkManager(client)
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 218, in __init__
self.present()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 352, in present
self.disconnect_missing()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 323, in disconnect_missing
for c in self.existing_network['Containers'].values():
AttributeError: 'NoneType' object has no attribute 'values'

failed: [192.168.1.120 -> 127.0.0.1] (item={u'driver': u'overlay', u'name': u'networks_default_1'}) => {
"failed": true,
"item": {
"driver": "overlay",
"name": "networks_default_1"
},
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 392, in <module>\n    main()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 385, in main\n    cm = DockerNetworkManager(client)\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 218, in __init__\n    self.present()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 352, in present\n    self.disconnect_missing()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 323, in disconnect_missing\n    for c in self.existing_network['Containers'].values():\nAttributeError: 'NoneType' object has no attribute 'values'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0

# Fixed code
def disconnect_missing(self):
    containers = self.existing_network["Containers"]
    if not containers:
        return
    for c in containers.values():
        name = c["Name"]
        if name not in self.parameters.connected:
            self.disconnect_container(name)
# Buggy code
def _csrf_enabled(self):
    csrf_data = self._get_json_data("%s/%s" % (self.url, "api/json"), "CSRF")

    return csrf_data["useCrumbs"]


# Traceback (AttributeError)
TASK [geerlingguy.jenkins : Install Jenkins plugins.] ******************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'TypeError' object has no attribute 'message'
failed: [1.2.3.4] (item=git) => {"failed": true, "item": "git", "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 341, in _get_json_data\n    json_data = json.load(r)\n  File \"/usr/lib/python3.5/json/__init__.py\", line 268, in load\n    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)\n  File \"/usr/lib/python3.5/json/__init__.py\", line 312, in loads\n    s.__class__.__name__))\nTypeError: the JSON object must be str, not 'bytes'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 823, in <module>\n    main()\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 802, in main\n    jp = JenkinsPlugin(module)\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 323, in __init__\n    if self._csrf_enabled():\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 331, in _csrf_enabled\n    \"%s/%s\" % (self.url, \"api/json\"), 'CSRF')\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 346, in _get_json_data\n    details=e.message)\nAttributeError: 'TypeError' object has no attribute 'message'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'TypeError' object has no attribute 'message'

# Fixed code
def _csrf_enabled(self):
    csrf_data = self._get_json_data("%s/%s" % (self.url, "api/json"), "CSRF")

    try:
        return csrf_data["useCrumbs"]
    except:
        self.module.fail_json(
            msg="Required fields not found in the Crum response.", details=csrf_data
        )
# Buggy code
def _get_json_data(self, url, what, **kwargs):
    # Get the JSON data
    r = self._get_url_data(url, what, **kwargs)

    # Parse the JSON data
    try:
        json_data = json.load(r)
    except Exception:
        e = get_exception()
        self.module.fail_json(
            msg="Cannot parse %s JSON data." % what, details=e.message
        )

    return json_data


# Traceback (AttributeError)
TASK [geerlingguy.jenkins : Install Jenkins plugins.] ******************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'TypeError' object has no attribute 'message'
failed: [1.2.3.4] (item=git) => {"failed": true, "item": "git", "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 341, in _get_json_data\n    json_data = json.load(r)\n  File \"/usr/lib/python3.5/json/__init__.py\", line 268, in load\n    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)\n  File \"/usr/lib/python3.5/json/__init__.py\", line 312, in loads\n    s.__class__.__name__))\nTypeError: the JSON object must be str, not 'bytes'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 823, in <module>\n    main()\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 802, in main\n    jp = JenkinsPlugin(module)\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 323, in __init__\n    if self._csrf_enabled():\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 331, in _csrf_enabled\n    \"%s/%s\" % (self.url, \"api/json\"), 'CSRF')\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 346, in _get_json_data\n    details=e.message)\nAttributeError: 'TypeError' object has no attribute 'message'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'TypeError' object has no attribute 'message'

# Fixed code
def _get_json_data(self, url, what, **kwargs):
    # Get the JSON data
    r = self._get_url_data(url, what, **kwargs)

    # Parse the JSON data
    try:
        json_data = json.loads(to_native(r.read()))
    except Exception:
        e = get_exception()
        self.module.fail_json(
            msg="Cannot parse %s JSON data." % what, details=to_native(e)
        )

    return json_data
# Buggy code
def _get_url_data(self, url, what=None, msg_status=None, msg_exception=None, **kwargs):
    # Compose default messages
    if msg_status is None:
        msg_status = "Cannot get %s" % what

    if msg_exception is None:
        msg_exception = "Retrieval of %s failed." % what

    # Get the URL data
    try:
        response, info = fetch_url(self.module, url, timeout=self.timeout, **kwargs)

        if info["status"] != 200:
            self.module.fail_json(msg=msg_status, details=info["msg"])
    except Exception:
        e = get_exception()
        self.module.fail_json(msg=msg_exception, details=e.message)

    return response


# Traceback (AttributeError)
TASK [geerlingguy.jenkins : Install Jenkins plugins.] ******************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'TypeError' object has no attribute 'message'
failed: [1.2.3.4] (item=git) => {"failed": true, "item": "git", "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 341, in _get_json_data\n    json_data = json.load(r)\n  File \"/usr/lib/python3.5/json/__init__.py\", line 268, in load\n    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)\n  File \"/usr/lib/python3.5/json/__init__.py\", line 312, in loads\n    s.__class__.__name__))\nTypeError: the JSON object must be str, not 'bytes'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 823, in <module>\n    main()\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 802, in main\n    jp = JenkinsPlugin(module)\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 323, in __init__\n    if self._csrf_enabled():\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 331, in _csrf_enabled\n    \"%s/%s\" % (self.url, \"api/json\"), 'CSRF')\n  File \"/tmp/ansible_42hz6qg4/ansible_module_jenkins_plugin.py\", line 346, in _get_json_data\n    details=e.message)\nAttributeError: 'TypeError' object has no attribute 'message'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'TypeError' object has no attribute 'message'

# Fixed code
def _get_url_data(self, url, what=None, msg_status=None, msg_exception=None, **kwargs):
    # Compose default messages
    if msg_status is None:
        msg_status = "Cannot get %s" % what

    if msg_exception is None:
        msg_exception = "Retrieval of %s failed." % what

    # Get the URL data
    try:
        response, info = fetch_url(self.module, url, timeout=self.timeout, **kwargs)

        if info["status"] != 200:
            self.module.fail_json(msg=msg_status, details=info["msg"])
    except Exception:
        e = get_exception()
        self.module.fail_json(msg=msg_exception, details=to_native(e))

    return response
# Buggy code
def _return_formatted(self, kwargs):
    self.add_path_info(kwargs)

    if "invocation" not in kwargs:
        kwargs["invocation"] = {"module_args": self.params}

    if "warnings" in kwargs:
        if isinstance(kwargs["warnings"], list):
            for w in kwargs["warnings"]:
                self.warn(w)
        else:
            self.warn(kwargs["warnings"])

    if self._warnings:
        kwargs["warnings"] = self._warnings

    if "deprecations" in kwargs:
        if isinstance(kwargs["deprecations"], list):
            for d in kwargs["deprecations"]:
                if isinstance(d, SEQUENCETYPE) and len(d) == 2:
                    self.deprecate(d[0], version=d[1])
                else:
                    self.deprecate(d)
        else:
            self.deprecate(d)

    if self._deprecations:
        kwargs["deprecations"] = self._deprecations

    kwargs = remove_values(kwargs, self.no_log_values)
    print("\n%s" % self.jsonify(kwargs))


# Traceback (UnboundLocalError)
# ansible -m demo -a "state=present passwordfile=/etc/hosts src=/tmp"  localhost
[WARNING]: provided hosts list is empty, only localhost is available

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: UnboundLocalError: local variable 'd' referenced before assignment
localhost | FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_eio1be8x/ansible_module_demo.py\", line 21, in <module>\n    main()\n  File \"/tmp/ansible_eio1be8x/ansible_module_demo.py\", line 18, in main\n    module.exit_json(**result)\n  File \"/tmp/ansible_eio1be8x/ansible_modlib.zip/ansible/module_utils/basic.py\", line 2017, in exit_json\n  File \"/tmp/ansible_eio1be8x/ansible_modlib.zip/ansible/module_utils/basic.py\", line 2002, in _return_formatted\nUnboundLocalError: local variable 'd' referenced before assignment\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def _return_formatted(self, kwargs):
    self.add_path_info(kwargs)

    if "invocation" not in kwargs:
        kwargs["invocation"] = {"module_args": self.params}

    if "warnings" in kwargs:
        if isinstance(kwargs["warnings"], list):
            for w in kwargs["warnings"]:
                self.warn(w)
        else:
            self.warn(kwargs["warnings"])

    if self._warnings:
        kwargs["warnings"] = self._warnings

    if "deprecations" in kwargs:
        if isinstance(kwargs["deprecations"], list):
            for d in kwargs["deprecations"]:
                if isinstance(d, SEQUENCETYPE) and len(d) == 2:
                    self.deprecate(d[0], version=d[1])
                else:
                    self.deprecate(d)
        else:
            self.deprecate(kwargs["deprecations"])

    if self._deprecations:
        kwargs["deprecations"] = self._deprecations

    kwargs = remove_values(kwargs, self.no_log_values)
    print("\n%s" % self.jsonify(kwargs))
# Buggy code
def addRulesToLookup(rules, prefix, dict):
    for rule in rules:
        for grant in rule.grants:
            dict[make_rule_key(prefix, rule, grant.group_id, grant.cidr_ip)] = (
                rule,
                grant,
            )


# Traceback (boto.exception.EC2ResponseError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_em0SmM/ansible_module_ec2_group.py", line 487, in <module>
main()
File "/tmp/ansible_em0SmM/ansible_module_ec2_group.py", line 439, in main
cidr_ip=thisip)
File "/usr/lib/python2.7/site-packages/boto/ec2/connection.py", line 3245, in authorize_security_group_egress
params, verb='POST')
File "/usr/lib/python2.7/site-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidPermission.Duplicate</Code><Message>the specified rule "peer: 0.0.0.0/0, TCP, from port: 443, to port: 443, ALLOW" already exists</Message></Error></Errors><RequestID>871be7ab-957c-4c41-8982-706e7a5dc64c</RequestID></Response>

fatal: [remotehost -> localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_em0SmM/ansible_module_ec2_group.py\", line 487, in <module>\n    main()\n  File \"/tmp/ansible_em0SmM/ansible_module_ec2_group.py\", line 439, in main\n    cidr_ip=thisip)\n  File \"/usr/lib/python2.7/site-packages/boto/ec2/connection.py\", line 3245, in authorize_security_group_egress\n    params, verb='POST')\n  File \"/usr/lib/python2.7/site-packages/boto/connection.py\", line 1227, in get_status\n    raise self.ResponseError(response.status, response.reason, body)\nboto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response><Errors><Error><Code>InvalidPermission.Duplicate</Code><Message>the specified rule \"peer: 0.0.0.0/0, TCP, from port: 443, to port: 443, ALLOW\" already exists</Message></Error></Errors><RequestID>871be7ab-957c-4c41-8982-706e7a5dc64c</RequestID></Response>\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def addRulesToLookup(rules, prefix, rules_dict):
    for rule in rules:
        for grant in rule.grants:
            rules_dict[make_rule_key(prefix, rule, grant.group_id, grant.cidr_ip)] = (
                rule,
                grant,
            )
# Buggy code
def _parse_value(self, value):
    if value is None:
        return ""
    elif isinstance(value, bool):
        if value:
            return "1"
        else:
            return "0"
    elif isinstance(value, basestring):
        if value.lower() in BOOLEANS_TRUE:
            return "1"
        elif value.lower() in BOOLEANS_FALSE:
            return "0"
        else:
            return value.strip()
    else:
        return value


# Traceback (NameError)
2017-05-04 01:13:20 The full traceback is:
2017-05-04 01:13:20 Traceback (most recent call last):
2017-05-04 01:13:20   File "/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py", line 397, in <module>
2017-05-04 01:13:20     main()
2017-05-04 01:13:20   File "/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py", line 391, in main
2017-05-04 01:13:20     result = SysctlModule(module)
2017-05-04 01:13:20   File "/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py", line 142, in __init__
2017-05-04 01:13:20     self.process()
2017-05-04 01:13:20   File "/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py", line 154, in process
2017-05-04 01:13:20     self.args['value'] = self._parse_value(self.args['value'])
2017-05-04 01:13:20   File "/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py", line 219, in _parse_value
2017-05-04 01:13:20     elif isinstance(value, basestring):
2017-05-04 01:13:20 NameError: name 'basestring' is not defined
2017-05-04 01:13:20
2017-05-04 01:13:20 fatal: [testhost]: FAILED! => {
2017-05-04 01:13:20     "changed": false,
2017-05-04 01:13:20     "failed": true,
2017-05-04 01:13:20     "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py\", line 397, in <module>\n    main()\n  File \"/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py\", line 391, in main\n    result = SysctlModule(module)\n  File \"/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py\", line 142, in __init__\n    self.process()\n  File \"/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py\", line 154, in process\n    self.args['value'] = self._parse_value(self.args['value'])\n  File \"/tmp/ansible_2cdc4_pp/ansible_module_sysctl.py\", line 219, in _parse_value\n    elif isinstance(value, basestring):\nNameError: name 'basestring' is not defined\n",
2017-05-04 01:13:20     "module_stdout": "",
2017-05-04 01:13:20     "msg": "MODULE FAILURE",
2017-05-04 01:13:20     "rc": 0
2017-05-04 01:13:20 }

# Fixed code
def _parse_value(self, value):
    if value is None:
        return ""
    elif isinstance(value, bool):
        if value:
            return "1"
        else:
            return "0"
    elif isinstance(value, string_types):
        if value.lower() in BOOLEANS_TRUE:
            return "1"
        elif value.lower() in BOOLEANS_FALSE:
            return "0"
        else:
            return value.strip()
    else:
        return value
# Buggy code
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(names={"default": [], "type": "list"}))
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    if not HAS_BOTO:
        module.fail_json(msg="boto required for this module")

    try:
        region, ec2_url, aws_connect_params = get_aws_connection_info(module)
        if not region:
            module.fail_json(msg="region must be specified")

        names = module.params["names"]
        elb_information = ElbInformation(module, names, region, **aws_connect_params)

        ec2_facts_result = dict(changed=False, elbs=elb_information.list_elbs())

    except BotoServerError as err:
        self.module.fail_json(
            msg="{0}: {1}".format(err.error_code, err.error_message),
            exception=traceback.format_exc(),
        )

    module.exit_json(**ec2_facts_result)


# Traceback (nNameError)
fatal: [10.30.0.143 -> localhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_eFbJEs/ansible_module_ec2_elb_facts.py\", line 267, in <module>\n    main()\n  File \"/tmp/ansible_eFbJEs/ansible_module_ec2_elb_facts.py\", line 260, in main\n    self.module.fail_json(msg=\"{0}: {1}\".format(err.error_code, err.error_message),\nNameError: global name 'self' is not defined\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(names={"default": [], "type": "list"}))
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    if not HAS_BOTO:
        module.fail_json(msg="boto required for this module")

    try:
        region, ec2_url, aws_connect_params = get_aws_connection_info(module)
        if not region:
            module.fail_json(msg="region must be specified")

        names = module.params["names"]
        elb_information = ElbInformation(module, names, region, **aws_connect_params)

        ec2_facts_result = dict(changed=False, elbs=elb_information.list_elbs())

    except BotoServerError as err:
        module.fail_json(
            msg="{0}: {1}".format(err.error_code, err.error_message),
            exception=traceback.format_exc(),
        )

    module.exit_json(**ec2_facts_result)
# Buggy code
def get_connection(module):
    global _DEVICE_CONNECTION
    if not _DEVICE_CONNECTION:
        load_params(module)
        transport = module.params["transport"]
        provider_transport = (module.params["provider"] or {}).get("transport")
        if "eapi" in (transport, provider_transport):
            conn = Eapi(module)
        else:
            conn = Cli(module)
        _DEVICE_CONNECTION = conn
    return _DEVICE_CONNECTION


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_ovFb9b/ansible_module_eos_banner.py", line 184, in <module>
main()
File "/tmp/ansible_ovFb9b/ansible_module_eos_banner.py", line 175, in main
response = load_config(module, commands, commit=commit)
File "/tmp/ansible_ovFb9b/ansible_modlib.zip/ansible/module_utils/eos.py", line 459, in load_config
File "/tmp/ansible_ovFb9b/ansible_modlib.zip/ansible/module_utils/eos.py", line 233, in load_config
File "/tmp/ansible_ovFb9b/ansible_modlib.zip/ansible/module_utils/eos.py", line 176, in send_config
AttributeError: 'dict' object has no attribute 'startswith'

fatal: [172.26.4.24]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_ovFb9b/ansible_module_eos_banner.py\", line 184, in <module>\n    main()\n  File \"/tmp/ansible_ovFb9b/ansible_module_eos_banner.py\", line 175, in main\n    response = load_config(module, commands, commit=commit)\n  File \"/tmp/ansible_ovFb9b/ansible_modlib.zip/ansible/module_utils/eos.py\", line 459, in load_config\n  File \"/tmp/ansible_ovFb9b/ansible_modlib.zip/ansible/module_utils/eos.py\", line 233, in load_config\n  File \"/tmp/ansible_ovFb9b/ansible_modlib.zip/ansible/module_utils/eos.py\", line 176, in send_config\nAttributeError: 'dict' object has no attribute 'startswith'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_connection(module):
    global _DEVICE_CONNECTION
    if not _DEVICE_CONNECTION:
        load_params(module)
        if is_eapi(module):
            conn = Eapi(module)
        else:
            conn = Cli(module)
        _DEVICE_CONNECTION = conn
    return _DEVICE_CONNECTION
# Buggy code
def _is_role(self, path):
    """imperfect role detection, roles are still valid w/o tasks|meta/main.yml|yaml|etc"""

    b_path = to_bytes(path, errors="surrogate_or_strict")
    b_upath = to_bytes(unfrackpath(path, follow=False), errors="surrogate_or_strict")

    for finddir in (b"meta", b"tasks"):
        for suffix in (b".yml", b".yaml", b""):
            b_main = b"main%s" % (suffix)
            b_tasked = b"%s/%s" % (finddir, b_main)

            if (
                RE_TASKS.search(path)
                and os.path.exists(os.path.join(b_path, b_main))
                or os.path.exists(os.path.join(b_upath, b_tasked))
                or os.path.exists(os.path.join(os.path.dirname(b_path), b_tasked))
            ):
                return True
    return False


# Traceback (TypeError)
task path: /home/centos/os-data-miner-jupyter-ansible/jupyterhub-install.yaml:31
The full traceback is:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/ansible/executor/task_executor.py", line 125, in run
res = self._execute()
File "/usr/lib/python3.4/site-packages/ansible/executor/task_executor.py", line 521, in _execute
result = self._handler.run(task_vars=variables)
File "/usr/lib/python3.4/site-packages/ansible/plugins/action/copy.py", line 97, in run
source = self._find_needle('files', source)
File "/usr/lib/python3.4/site-packages/ansible/plugins/action/__init__.py", line 986, in _find_needle
result = self._loader.path_dwim_relative_stack(path_stack, dirname, needle)
File "/usr/lib/python3.4/site-packages/ansible/parsing/dataloader.py", line 330, in path_dwim_relative_stack
if is_role or self._is_role(path):
File "/usr/lib/python3.4/site-packages/ansible/parsing/dataloader.py", line 237, in _is_role
b_main = b'main%s' % (suffix)
TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'

fatal: [up-premium]: FAILED! => {
"failed": true,
"msg": "Unexpected failure during module execution.",
"stdout": ""
}

# Fixed code
def _is_role(self, path):
    """imperfect role detection, roles are still valid w/o tasks|meta/main.yml|yaml|etc"""

    b_path = to_bytes(path, errors="surrogate_or_strict")
    b_upath = to_bytes(unfrackpath(path, follow=False), errors="surrogate_or_strict")

    for b_finddir in (b"meta", b"tasks"):
        for b_suffix in (b".yml", b".yaml", b""):
            b_main = b"main%s" % (b_suffix)
            b_tasked = os.path.join(b_finddir, b_main)

            if (
                RE_TASKS.search(path)
                and os.path.exists(os.path.join(b_path, b_main))
                or os.path.exists(os.path.join(b_upath, b_tasked))
                or os.path.exists(os.path.join(os.path.dirname(b_path), b_tasked))
            ):
                return True
    return False
# Buggy code
def query_virtual(module, name):
    cmd = "%s -v info --description %s" % (APK_PATH, name)
    rc, stdout, stderr = module.run_command(cmd, check_rc=False)
    search_pattern = "^%s: virtual meta package" % (name)
    if re.search(search_pattern, stdout):
        return True
    return False


# Traceback (sre_constants.error)
Traceback (most recent call last):
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 248, in <module>
main()
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 241, in main
install_packages(module, p['name'], p['state'])
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 154, in install_packages
if query_virtual(module, name):
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 123, in query_virtual
if re.search(search_pattern, stdout):
File "/usr/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: multiple repeat

# Fixed code
def query_virtual(module, name):
    cmd = "%s -v info --description %s" % (APK_PATH, name)
    rc, stdout, stderr = module.run_command(cmd, check_rc=False)
    search_pattern = r"^%s: virtual meta package" % (re.escape(name))
    if re.search(search_pattern, stdout):
        return True
    return False
# Buggy code
def upgrade_packages(module):
    if module.check_mode:
        cmd = "%s upgrade --simulate" % (APK_PATH)
    else:
        cmd = "%s upgrade" % (APK_PATH)
    rc, stdout, stderr = module.run_command(cmd, check_rc=False)
    if rc != 0:
        module.fail_json(msg="failed to upgrade packages")
    if re.search("^OK", stdout):
        module.exit_json(changed=False, msg="packages already upgraded")
    module.exit_json(changed=True, msg="upgraded packages")


# Traceback (sre_constants.error)
Traceback (most recent call last):
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 248, in <module>
main()
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 241, in main
install_packages(module, p['name'], p['state'])
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 154, in install_packages
if query_virtual(module, name):
File "/tmp/ansible_XeAiQG/ansible_module_apk.py", line 123, in query_virtual
if re.search(search_pattern, stdout):
File "/usr/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: multiple repeat

# Fixed code
def upgrade_packages(module):
    if module.check_mode:
        cmd = "%s upgrade --simulate" % (APK_PATH)
    else:
        cmd = "%s upgrade" % (APK_PATH)
    rc, stdout, stderr = module.run_command(cmd, check_rc=False)
    if rc != 0:
        module.fail_json(msg="failed to upgrade packages")
    if re.search(r"^OK", stdout):
        module.exit_json(changed=False, msg="packages already upgraded")
    module.exit_json(changed=True, msg="upgraded packages")
# Buggy code
def expand_section(self, configobj, S=None):
    if S is None:
        S = list()
    S.append(configobj)
    for child in configobj.children:
        if child in S:
            continue
        self.expand_section(child, S)
    return S


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def expand_section(self, configobj, S=None):
    if S is None:
        S = list()
    S.append(configobj)
    for child in configobj.child_objs:
        if child in S:
            continue
        self.expand_section(child, S)
    return S
# Buggy code
def get_object(self, path):
    for item in self.items:
        if item.text == path[-1]:
            parents = [p.text for p in item.parents]
            if parents == path[:-1]:
                return item


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_object(self, path):
    for item in self.items:
        if item.text == path[-1]:
            if item.parents == path[:-1]:
                return item
# Buggy code
def get_existing(module, args):
    existing = {}
    netcfg = get_config(module)
    parents = ["evpn", "vni {0} l2".format(module.params["vni"])]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            if arg != "vni":
                if arg == "route_distinguisher":
                    existing[arg] = get_value(arg, config, module)
                else:
                    existing[arg] = get_route_target_value(arg, config, module)

        existing_fix = dict((k, v) for k, v in existing.items() if v)
        if existing_fix:
            existing["vni"] = module.params["vni"]
        else:
            existing = existing_fix

    return existing


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ["evpn", "vni {0} l2".format(module.params["vni"])]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            if arg != "vni":
                if arg == "route_distinguisher":
                    existing[arg] = get_value(arg, config, module)
                else:
                    existing[arg] = get_route_target_value(arg, config, module)

        existing_fix = dict((k, v) for k, v in existing.items() if v)
        if existing_fix:
            existing["vni"] = module.params["vni"]
        else:
            existing = existing_fix

    return existing