gurudesh/pytracebugs huggingface dataset:
# Buggy code
def delete_group_policy(
    group_name, policy_name, region=None, key=None, keyid=None, profile=None
):
    """
    Delete a group policy.

    CLI Example::

    .. code-block:: bash

        salt myminion boto_iam.delete_group_policy mygroup mypolicy
    """
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return False
    _policy = get_group_policy(group_name, policy_name, region, key, keyid, profile)
    if not _policy:
        return True
    try:
        conn.delete_group_policy(group_name, policy_name)
        msg = "Successfully deleted {0} policy for group {1}."
        log.info(msg.format(policy_name, group_name))
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete {0} policy for group {1}."
        log.error(msg.format(policy_name, group_name))
        return False


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1591, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/boto_elasticache.py", line 290, in subnet_group_present
keyid=keyid, profile=profile)
File "/usr/lib/python2.7/dist-packages/salt/modules/boto_elasticache.py", line 341, in subnet_group_exists
conn = _get_conn(region, key, keyid, profile)
TypeError: get_connection() got multiple values for keyword argument 'module'

# Fixed code
def delete_group_policy(
    group_name, policy_name, region=None, key=None, keyid=None, profile=None
):
    """
    Delete a group policy.

    CLI Example::

    .. code-block:: bash

        salt myminion boto_iam.delete_group_policy mygroup mypolicy
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    _policy = get_group_policy(group_name, policy_name, region, key, keyid, profile)
    if not _policy:
        return True
    try:
        conn.delete_group_policy(group_name, policy_name)
        msg = "Successfully deleted {0} policy for group {1}."
        log.info(msg.format(policy_name, group_name))
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete {0} policy for group {1}."
        log.error(msg.format(policy_name, group_name))
        return False
# Buggy code
def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None):
    """
    Get a list of policy names from a group.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.get_all_group_policies mygroup
    """
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return False
    try:
        response = conn.get_all_group_policies(group_name)
        _list = response.list_group_policies_response.list_group_policies_result
        return _list.policy_names
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return []


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1591, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/boto_elasticache.py", line 290, in subnet_group_present
keyid=keyid, profile=profile)
File "/usr/lib/python2.7/dist-packages/salt/modules/boto_elasticache.py", line 341, in subnet_group_exists
conn = _get_conn(region, key, keyid, profile)
TypeError: get_connection() got multiple values for keyword argument 'module'

# Fixed code
def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None):
    """
    Get a list of policy names from a group.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.get_all_group_policies mygroup
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    try:
        response = conn.get_all_group_policies(group_name)
        _list = response.list_group_policies_response.list_group_policies_result
        return _list.policy_names
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return []
# Buggy code
def put_user_policy(
    user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None
):
    """
    Adds or updates the specified policy document for the specified user.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.put_user_policy myuser policyname policyrules
    """
    user = get_user(user_name, region, key, keyid, profile)
    if not user:
        log.error("User {0} does not exist".format(user_name))
        return False
    conn = _get_conn(region, key, keyid, profile)
    try:
        if not isinstance(policy_json, string_types):
            policy_json = json.dumps(policy_json)
        created = conn.put_user_policy(user_name, policy_name, policy_json)
        if created:
            log.info("Created policy for user {0}.".format(user_name))
            return True
        msg = "Could not create policy for user {0}."
        log.error(msg.format(user_name))
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to create policy for user {0}."
        log.error(msg.format(user_name))
    return False


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1591, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/boto_elasticache.py", line 290, in subnet_group_present
keyid=keyid, profile=profile)
File "/usr/lib/python2.7/dist-packages/salt/modules/boto_elasticache.py", line 341, in subnet_group_exists
conn = _get_conn(region, key, keyid, profile)
TypeError: get_connection() got multiple values for keyword argument 'module'

# Fixed code
def put_user_policy(
    user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None
):
    """
    Adds or updates the specified policy document for the specified user.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.put_user_policy myuser policyname policyrules
    """
    user = get_user(user_name, region, key, keyid, profile)
    if not user:
        log.error("User {0} does not exist".format(user_name))
        return False
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        if not isinstance(policy_json, string_types):
            policy_json = json.dumps(policy_json)
        created = conn.put_user_policy(user_name, policy_name, policy_json)
        if created:
            log.info("Created policy for user {0}.".format(user_name))
            return True
        msg = "Could not create policy for user {0}."
        log.error(msg.format(user_name))
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to create policy for user {0}."
        log.error(msg.format(user_name))
    return False
# Buggy code
def delete_user_policy(
    user_name, policy_name, region=None, key=None, keyid=None, profile=None
):
    """
    Delete a user policy.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.delete_user_policy myuser mypolicy
    """
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return False
    _policy = get_user_policy(user_name, policy_name, region, key, keyid, profile)
    if not _policy:
        return True
    try:
        conn.delete_user_policy(user_name, policy_name)
        msg = "Successfully deleted {0} policy for user {1}."
        log.info(msg.format(policy_name, user_name))
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete {0} policy for user {1}."
        log.error(msg.format(policy_name, user_name))
        return False


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1591, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/boto_elasticache.py", line 290, in subnet_group_present
keyid=keyid, profile=profile)
File "/usr/lib/python2.7/dist-packages/salt/modules/boto_elasticache.py", line 341, in subnet_group_exists
conn = _get_conn(region, key, keyid, profile)
TypeError: get_connection() got multiple values for keyword argument 'module'

# Fixed code
def delete_user_policy(
    user_name, policy_name, region=None, key=None, keyid=None, profile=None
):
    """
    Delete a user policy.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.delete_user_policy myuser mypolicy
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    _policy = get_user_policy(user_name, policy_name, region, key, keyid, profile)
    if not _policy:
        return True
    try:
        conn.delete_user_policy(user_name, policy_name)
        msg = "Successfully deleted {0} policy for user {1}."
        log.info(msg.format(policy_name, user_name))
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete {0} policy for user {1}."
        log.error(msg.format(policy_name, user_name))
        return False
# Buggy code
def avail_locations(call=None):
    """
    List all available locations
    """
    if call == "action":
        raise SaltCloudSystemExit(
            "The avail_locations function must be called with "
            "-f or --function, or with the --list-locations option"
        )

    ret = {}
    conn = get_conn(service="SoftLayer_Product_Package")

    locations = conn.getLocations(id=50)
    for location in locations:
        ret[location["id"]] = {
            "id": location["id"],
            "name": location["name"],
            "location": location["longName"],
        }

    available = conn.getAvailableLocations(id=50)
    for location in available:
        ret[location["locationId"]]["available"] = True

    return ret


# Traceback (TypeError)
[ERROR   ] There was a profile error: 'bool' object is not iterable
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/cli.py", line 254, in run
self.config.get('names')
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1391, in run_profile
ret[name] = self.create(vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1241, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/softlayer_hw.py", line 448, in create
for product in optional_products:
TypeError: 'bool' object is not iterable

# Fixed code
def avail_locations(call=None):
    """
    List all available locations
    """
    if call == "action":
        raise SaltCloudSystemExit(
            "The avail_locations function must be called with "
            "-f or --function, or with the --list-locations option"
        )

    ret = {}
    conn = get_conn(service="SoftLayer_Product_Package")

    locations = conn.getLocations(id=50)
    for location in locations:
        ret[location["id"]] = {
            "id": location["id"],
            "name": location["name"],
            "location": location["longName"],
        }

    available = conn.getAvailableLocations(id=50)
    for location in available:
        if location.get("isAvailable", 0) is 0:
            continue
        ret[location["locationId"]]["available"] = True

    return ret
# Buggy code
def get_top(self):
    """
    Returns the high data derived from the top file
    """
    tops = self.get_tops()
    return self.merge_tops(tops)


# Traceback (TypeError)
Passed invalid arguments: can't serialize ConstructorError()
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 129, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/state.py", line 343, in highstate
serial.dump(ret, fp_)
File "/usr/lib/python2.7/dist-packages/salt/payload.py", line 149, in dump
fn_.write(self.dumps(msg))
File "/usr/lib/python2.7/dist-packages/salt/payload.py", line 115, in dumps
return msgpack.dumps(msg)
File "_packer.pyx", line 259, in msgpack._packer.packb (msgpack/_packer.cpp:259)
File "_packer.pyx", line 184, in msgpack._packer.Packer.pack (msgpack/_packer.cpp:184)
File "_packer.pyx", line 159, in msgpack._packer.Packer._pack (msgpack/_packer.cpp:159)
File "_packer.pyx", line 159, in msgpack._packer.Packer._pack (msgpack/_packer.cpp:159)
File "_packer.pyx", line 179, in msgpack._packer.Packer._pack (msgpack/_packer.cpp:179)
TypeError: can't serialize ConstructorError()

# Fixed code
def get_top(self):
    """
    Returns the high data derived from the top file
    """
    try:
        tops = self.get_tops()
    except SaltRenderError as err:
        log.error("Unable to render top file: " + str(err.error))
        return {}
    return self.merge_tops(tops)
# Buggy code
def _conf(family="ipv4"):
    """
    Some distros have a specific location for config files
    """
    if __grains__["os_family"] == "RedHat":
        if family == "ipv6":
            return "/etc/sysconfig/ip6tables"
        else:
            return "/etc/sysconfig/iptables"
    elif __grains__["os_family"] == "Arch":
        if family == "ipv6":
            return "/etc/iptables/ip6tables.rules"
        else:
            return "/etc/iptables/iptables.rules"
    elif __grains__["os_family"] == "Debian":
        if family == "ipv6":
            return "/etc/iptables/rules.v6"
        else:
            return "/etc/iptables/rules.v4"
    elif __grains__["os"] == "Gentoo":
        if family == "ipv6":
            return "/var/lib/ip6tables/rules-save"
        else:
            return "/var/lib/iptables/rules-save"
    else:
        return False


# Traceback (AttributeError)
ID: iptables_ftp_pasv
Function: iptables.append
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1561, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/states/iptables.py", line 420, in append
out = __salt__['iptables.save'](filename, family=family)
File "/usr/lib/python2.7/site-packages/salt/modules/iptables.py", line 540, in save
parent_dir = os.path.dirname(filename)
File "/usr/lib64/python2.7/posixpath.py", line 129, in dirname
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
Started: 00:21:04.194480
Duration: 20.835 ms
Changes:

# Fixed code
def _conf(family="ipv4"):
    """
    Some distros have a specific location for config files
    """
    if __grains__["os_family"] == "RedHat":
        if family == "ipv6":
            return "/etc/sysconfig/ip6tables"
        else:
            return "/etc/sysconfig/iptables"
    elif __grains__["os_family"] == "Arch":
        if family == "ipv6":
            return "/etc/iptables/ip6tables.rules"
        else:
            return "/etc/iptables/iptables.rules"
    elif __grains__["os_family"] == "Debian":
        if family == "ipv6":
            return "/etc/iptables/rules.v6"
        else:
            return "/etc/iptables/rules.v4"
    elif __grains__["os"] == "Gentoo":
        if family == "ipv6":
            return "/var/lib/ip6tables/rules-save"
        else:
            return "/var/lib/iptables/rules-save"
    elif __grains__["os_family"] == "Suse":
        # SuSE does not seem to use separate files for IPv4 and IPv6
        return "/etc/sysconfig/scripts/SuSEfirewall2-custom"
    else:
        raise SaltException(
            "Saving iptables to file is not"
            + " supported on {0}.".format(__grains__["os"])
            + " Please file an issue with SaltStack"
        )
# Buggy code
def _validate_name(name):
    """
    Checks if the provided name fits Linode's labeling parameters.

    .. versionadded:: 2015.5.6

    name
        The VM name to validate
    """
    name_length = len(name)
    regex = re.compile(r"^[a-zA-Z0-9][A-Za-z0-9_-]*[a-zA-Z0-9]$")

    if name_length < 3 or name_length > 48:
        ret = False
    elif not re.match(regex, name):
        ret = False
    else:
        ret = True

    if ret is False:
        log.warning(
            "A Linode label may only contain ASCII letters or numbers, dashes, and "
            "underscores, must begin and end with letters or numbers, and be at least "
            "three characters in length."
        )

    return ret


# Traceback (TypeError)
[INFO    ] Status for Linode 1279023 is 'Being Created', waiting for 'Brand New'.
[DEBUG   ] file_roots is /root/salt-pkg-tests
[DEBUG   ] file_roots is /root/precipitate
[DEBUG   ] Requesting URL https://api.linode.com/?api_key=XXXXXXXXXX using GET method
[DEBUG   ] Response Status Code: 200
[DEBUG   ] Linode Response Status Code: 200
[ERROR   ] There was a profile error: object of type 'int' has no len()
Traceback (most recent call last):
File "/root/salt/salt/cloud/cli.py", line 275, in run
self.config.get('names')
File "/root/salt/salt/cloud/__init__.py", line 1410, in run_profile
ret[name] = self.create(vm_)
File "/root/salt/salt/cloud/__init__.py", line 1256, in create
output = self.clouds[func](vm_)
File "/root/salt/salt/cloud/clouds/linode.py", line 436, in create
update_linode(node_id, update_args={'Label': vm_['name']})
File "/root/salt/salt/cloud/clouds/linode.py", line 1280, in update_linode
if _validate_name(linode_id) is False:
File "/root/salt/salt/cloud/clouds/linode.py", line 1523, in _validate_name
name_length = len(name)
TypeError: object of type 'int' has no len()

# Fixed code
def _validate_name(name):
    """
    Checks if the provided name fits Linode's labeling parameters.

    .. versionadded:: 2015.5.6

    name
        The VM name to validate
    """
    name = str(name)
    name_length = len(name)
    regex = re.compile(r"^[a-zA-Z0-9][A-Za-z0-9_-]*[a-zA-Z0-9]$")

    if name_length < 3 or name_length > 48:
        ret = False
    elif not re.match(regex, name):
        ret = False
    else:
        ret = True

    if ret is False:
        log.warning(
            "A Linode label may only contain ASCII letters or numbers, dashes, and "
            "underscores, must begin and end with letters or numbers, and be at least "
            "three characters in length."
        )

    return ret
# Buggy code
def run(self):
    """
    Execute salt-run
    """
    import salt.runner

    self.parse_args()

    if self.config["verify_env"]:
        verify_env(
            [
                self.config["pki_dir"],
                self.config["cachedir"],
            ],
            self.config["user"],
            permissive=self.config["permissive_pki_access"],
            pki_dir=self.config["pki_dir"],
        )
        if not self.config["log_file"].startswith(("tcp://", "udp://", "file://")):
            # Logfile is not using Syslog, verify
            verify_files([self.config["log_file"]], self.config["user"])

    # Setup file logging!
    self.setup_logfile_logger()

    runner = salt.runner.Runner(self.config)
    if self.options.doc:
        runner.print_docs()
        self.exit(os.EX_OK)

    # Run this here so SystemExit isn't raised anywhere else when
    # someone tries to use the runners via the python API
    try:
        if check_user(self.config["user"]):
            runner.run()
    except SaltClientError as exc:
        raise SystemExit(str(exc))


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 227, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 67, in run
self.exit(os.EX_OK)
AttributeError: 'module' object has no attribute 'EX_OK'

# Fixed code
def run(self):
    """
    Execute salt-run
    """
    import salt.runner

    self.parse_args()

    if self.config["verify_env"]:
        verify_env(
            [
                self.config["pki_dir"],
                self.config["cachedir"],
            ],
            self.config["user"],
            permissive=self.config["permissive_pki_access"],
            pki_dir=self.config["pki_dir"],
        )
        if not self.config["log_file"].startswith(("tcp://", "udp://", "file://")):
            # Logfile is not using Syslog, verify
            verify_files([self.config["log_file"]], self.config["user"])

    # Setup file logging!
    self.setup_logfile_logger()

    runner = salt.runner.Runner(self.config)
    if self.options.doc:
        runner.print_docs()
        self.exit(salt.defaults.exitcodes.EX_OK)

    # Run this here so SystemExit isn't raised anywhere else when
    # someone tries to use the runners via the python API
    try:
        if check_user(self.config["user"]):
            runner.run()
    except SaltClientError as exc:
        raise SystemExit(str(exc))
# Buggy code
def opts():
    """
    Return the minion configuration settings
    """
    if __opts__.get("grain_opts", False) or __pillar__.get("grain_opts", False):
        return __opts__
    return {}


# Traceback (AttributeError)
# salt nt-u14 test.ping
[CRITICAL] Failed to load grains defined in grain file opts.opts in function <function opts at 0x7fe2047a1c08>, error:
Traceback (most recent call last):
File "/root/SaltStack/salt/salt/loader.py", line 622, in grains
ret = fun()
File "/root/SaltStack/salt/salt/grains/opts.py", line 12, in opts
if __opts__.get('grain_opts', False) or __pillar__.get('grain_opts', False):
AttributeError: 'bool' object has no attribute 'get'
nt-u14:
True

# Fixed code
def opts():
    """
    Return the minion configuration settings
    """
    if __opts__.get("grain_opts", False) or (
        isinstance(__pillar__, dict) and __pillar__.get("grain_opts", False)
    ):
        return __opts__
    return {}
# Buggy code
def avail_images(call=None):
    """
    Return a list of all the templates present in this VMware environment with basic
    details

    CLI Example:

    .. code-block:: bash

        salt-cloud --list-images my-vmware-config
    """
    if call == "action":
        raise SaltCloudSystemExit(
            "The avail_images function must be called with "
            "-f or --function, or with the --list-images option."
        )

    templates = {}
    vm_properties = [
        "name",
        "config.template",
        "config.guestFullName",
        "config.hardware.numCPU",
        "config.hardware.memoryMB",
    ]

    vm_list = _get_mors_with_properties(vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if vm["config.template"]:
            templates[vm["name"]] = {
                "name": vm["name"],
                "guest_fullname": vm["config.guestFullName"],
                "cpus": vm["config.hardware.numCPU"],
                "ram": vm["config.hardware.memoryMB"],
            }

    return templates


# Traceback (KeyError)
[ERROR   ] Failed to get the output of 'vmware.avail_images()': 'config.template'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 842, in image_list
data[alias][driver] = self.clouds[fun]()
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/clouds/vmware.py", line 1672, in avail_images
if vm["config.template"]:
KeyError: 'config.template'
[DEBUG   ] LazyLoaded nested.output

# Fixed code
def avail_images(call=None):
    """
    Return a list of all the templates present in this VMware environment with basic
    details

    CLI Example:

    .. code-block:: bash

        salt-cloud --list-images my-vmware-config
    """
    if call == "action":
        raise SaltCloudSystemExit(
            "The avail_images function must be called with "
            "-f or --function, or with the --list-images option."
        )

    templates = {}
    vm_properties = [
        "name",
        "config.template",
        "config.guestFullName",
        "config.hardware.numCPU",
        "config.hardware.memoryMB",
    ]

    vm_list = _get_mors_with_properties(vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if "config.template" in vm and vm["config.template"]:
            templates[vm["name"]] = {
                "name": vm["name"],
                "guest_fullname": vm["config.guestFullName"]
                if "config.guestFullName" in vm
                else "N/A",
                "cpus": vm["config.hardware.numCPU"]
                if "config.hardware.numCPU" in vm
                else "N/A",
                "ram": vm["config.hardware.memoryMB"]
                if "config.hardware.memoryMB" in vm
                else "N/A",
            }

    return templates
# Buggy code
def show_management_certificate(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Return information about a management_certificate

    CLI Example:

    .. code-block:: bash

        salt-cloud -f get_management_certificate my-azure name=my_management_certificate \
            thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The get_management_certificate function must be called with -f or --function."
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if "thumbprint" not in kwargs:
        raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')

    data = conn.get_management_certificate(kwargs["thumbprint"])
    return object_to_dict(data)


# Traceback (TypeError)
# salt-cloud -f add_input_endpoint az-mysetup name=http    port=80    protocol=tcp deployment=myproject service=myproject role=myproject

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/cloud/cli.py", line 245, in run
self.function_provider, self.function_name, kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1525, in do_function
call='function', kwargs=kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2190, in add_input_endpoint
activity='add',
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2109, in update_input_endpoint
old_endpoints = list_input_endpoints(kwargs, call='function')
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2013, in list_input_endpoints
for item in data:
TypeError: 'NoneType' object is not iterable

# Fixed code
def show_management_certificate(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Return information about a management_certificate

    CLI Example:

    .. code-block:: bash

        salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
            thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The get_management_certificate function must be called with -f or --function."
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if "thumbprint" not in kwargs:
        raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')

    data = conn.get_management_certificate(kwargs["thumbprint"])
    return object_to_dict(data)
# Buggy code
def delete_management_certificate(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Delete a specific certificate associated with the management

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \
            thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The delete_management_certificate function must be called with -f or --function."
        )

    if kwargs is None:
        kwargs = {}

    if "thumbprint" not in kwargs:
        raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')

    if not conn:
        conn = get_conn()

    try:
        data = conn.delete_management_certificate(kwargs["thumbprint"])
        return {"Success": "The management certificate was successfully deleted"}
    except WindowsAzureMissingResourceError as exc:
        return {"Error": exc.message}


# Traceback (TypeError)
# salt-cloud -f add_input_endpoint az-mysetup name=http    port=80    protocol=tcp deployment=myproject service=myproject role=myproject

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/cloud/cli.py", line 245, in run
self.function_provider, self.function_name, kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1525, in do_function
call='function', kwargs=kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2190, in add_input_endpoint
activity='add',
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2109, in update_input_endpoint
old_endpoints = list_input_endpoints(kwargs, call='function')
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2013, in list_input_endpoints
for item in data:
TypeError: 'NoneType' object is not iterable

# Fixed code
def delete_management_certificate(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Delete a specific certificate associated with the management

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
            thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The delete_management_certificate function must be called with -f or --function."
        )

    if kwargs is None:
        kwargs = {}

    if "thumbprint" not in kwargs:
        raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')

    if not conn:
        conn = get_conn()

    try:
        data = conn.delete_management_certificate(kwargs["thumbprint"])
        return {"Success": "The management certificate was successfully deleted"}
    except WindowsAzureMissingResourceError as exc:
        return {"Error": exc.message}
# Buggy code
def show_input_endpoint(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Show an input endpoint associated with the deployment

    CLI Example:

    .. code-block:: bash

        salt-cloud -f show_input_endpoint my-azure service=myservice \
            deployment=mydeployment name=SSH
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_input_endpoint function must be called with -f or --function."
        )

    if kwargs is None:
        kwargs = {}

    if "name" not in kwargs:
        raise SaltCloudSystemExit('An endpoint name must be specified as "name"')

    data = list_input_endpoints(kwargs=kwargs, call="function")
    return data.get(kwargs["name"], None)


# Traceback (TypeError)
# salt-cloud -f add_input_endpoint az-mysetup name=http    port=80    protocol=tcp deployment=myproject service=myproject role=myproject

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/cloud/cli.py", line 245, in run
self.function_provider, self.function_name, kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1525, in do_function
call='function', kwargs=kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2190, in add_input_endpoint
activity='add',
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2109, in update_input_endpoint
old_endpoints = list_input_endpoints(kwargs, call='function')
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2013, in list_input_endpoints
for item in data:
TypeError: 'NoneType' object is not iterable

# Fixed code
def show_input_endpoint(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Show an input endpoint associated with the deployment

    CLI Example:

    .. code-block:: bash

        salt-cloud -f show_input_endpoint my-azure service=myservice \\
            deployment=mydeployment name=SSH
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_input_endpoint function must be called with -f or --function."
        )

    if kwargs is None:
        kwargs = {}

    if "name" not in kwargs:
        raise SaltCloudSystemExit('An endpoint name must be specified as "name"')

    data = list_input_endpoints(kwargs=kwargs, call="function")
    return data.get(kwargs["name"], None)
# Buggy code
def add_input_endpoint(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Add an input endpoint to the deployment. Please note that
    there may be a delay before the changes show up.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f add_input_endpoint my-azure service=myservice \
            deployment=mydeployment role=myrole name=HTTP local_port=80 \
            port=80 protocol=tcp enable_direct_server_return=False \
            timeout_for_tcp_idle_connection=4
    """
    return update_input_endpoint(
        kwargs=kwargs,
        conn=conn,
        call="function",
        activity="add",
    )


# Traceback (TypeError)
# salt-cloud -f add_input_endpoint az-mysetup name=http    port=80    protocol=tcp deployment=myproject service=myproject role=myproject

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/cloud/cli.py", line 245, in run
self.function_provider, self.function_name, kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1525, in do_function
call='function', kwargs=kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2190, in add_input_endpoint
activity='add',
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2109, in update_input_endpoint
old_endpoints = list_input_endpoints(kwargs, call='function')
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2013, in list_input_endpoints
for item in data:
TypeError: 'NoneType' object is not iterable

# Fixed code
def add_input_endpoint(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Add an input endpoint to the deployment. Please note that
    there may be a delay before the changes show up.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f add_input_endpoint my-azure service=myservice \\
            deployment=mydeployment role=myrole name=HTTP local_port=80 \\
            port=80 protocol=tcp enable_direct_server_return=False \\
            timeout_for_tcp_idle_connection=4
    """
    return update_input_endpoint(
        kwargs=kwargs,
        conn=conn,
        call="function",
        activity="add",
    )
# Buggy code
def delete_input_endpoint(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Delete an input endpoint from the deployment. Please note that
    there may be a delay before the changes show up.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f delete_input_endpoint my-azure service=myservice \
            deployment=mydeployment role=myrole name=HTTP
    """
    return update_input_endpoint(
        kwargs=kwargs,
        conn=conn,
        call="function",
        activity="delete",
    )


# Traceback (TypeError)
# salt-cloud -f add_input_endpoint az-mysetup name=http    port=80    protocol=tcp deployment=myproject service=myproject role=myproject

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/cloud/cli.py", line 245, in run
self.function_provider, self.function_name, kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1525, in do_function
call='function', kwargs=kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2190, in add_input_endpoint
activity='add',
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2109, in update_input_endpoint
old_endpoints = list_input_endpoints(kwargs, call='function')
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2013, in list_input_endpoints
for item in data:
TypeError: 'NoneType' object is not iterable

# Fixed code
def delete_input_endpoint(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Delete an input endpoint from the deployment. Please note that
    there may be a delay before the changes show up.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f delete_input_endpoint my-azure service=myservice \\
            deployment=mydeployment role=myrole name=HTTP
    """
    return update_input_endpoint(
        kwargs=kwargs,
        conn=conn,
        call="function",
        activity="delete",
    )
# Buggy code
def show_affinity_group(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Show an affinity group associated with the account

    CLI Example:

    .. code-block:: bash

        salt-cloud -f show_affinity_group my-azure service=myservice \
            deployment=mydeployment name=SSH
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_affinity_group function must be called with -f or --function."
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if "name" not in kwargs:
        raise SaltCloudSystemExit('An affinity group name must be specified as "name"')

    data = conn.get_affinity_group_properties(affinity_group_name=kwargs["name"])
    return object_to_dict(data)


# Traceback (TypeError)
# salt-cloud -f add_input_endpoint az-mysetup name=http    port=80    protocol=tcp deployment=myproject service=myproject role=myproject

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/cloud/cli.py", line 245, in run
self.function_provider, self.function_name, kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1525, in do_function
call='function', kwargs=kwargs
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2190, in add_input_endpoint
activity='add',
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2109, in update_input_endpoint
old_endpoints = list_input_endpoints(kwargs, call='function')
File "/usr/local/lib/python2.7/site-packages/salt/cloud/clouds/msazure.py", line 2013, in list_input_endpoints
for item in data:
TypeError: 'NoneType' object is not iterable

# Fixed code
def show_affinity_group(kwargs=None, conn=None, call=None):
    """
    .. versionadded:: 2015.8.0

    Show an affinity group associated with the account

    CLI Example:

    .. code-block:: bash

        salt-cloud -f show_affinity_group my-azure service=myservice \\
            deployment=mydeployment name=SSH
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_affinity_group function must be called with -f or --function."
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if "name" not in kwargs:
        raise SaltCloudSystemExit('An affinity group name must be specified as "name"')

    data = conn.get_affinity_group_properties(affinity_group_name=kwargs["name"])
    return object_to_dict(data)
# Buggy code
def create_multiprocessing(parallel_data, queue=None):
    """
    This function will be called from another process when running a map in
    parallel mode. The result from the create is always a json object.
    """
    reinit_crypto()

    parallel_data["opts"]["output"] = "json"
    cloud = Cloud(parallel_data["opts"])
    try:
        output = cloud.create(
            parallel_data["profile"], local_master=parallel_data["local_master"]
        )
    except SaltCloudException as exc:
        log.error(
            "Failed to deploy {0[name]!r}. Error: {1}".format(parallel_data, exc),
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG,
        )
        return {parallel_data["name"]: {"Error": str(exc)}}

    if parallel_data["opts"].get("show_deploy_args", False) is False:
        output.pop("deploy_kwargs", None)

    return {parallel_data["name"]: salt.utils.cloud.simple_types_filter(output)}


# Traceback (AttributeError)
[ERROR   ] Caught Exception, terminating workers
TRACE: 'bool' object has no attribute 'pop'
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/cloud/__init__.py", line 60, in _call
ret = func(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/cloud/__init__.py", line 2222, in create_multiprocessing
output.pop('deploy_kwargs', None)
AttributeError: 'bool' object has no attribute 'pop'

# Fixed code
def create_multiprocessing(parallel_data, queue=None):
    """
    This function will be called from another process when running a map in
    parallel mode. The result from the create is always a json object.
    """
    reinit_crypto()

    parallel_data["opts"]["output"] = "json"
    cloud = Cloud(parallel_data["opts"])
    try:
        output = cloud.create(
            parallel_data["profile"], local_master=parallel_data["local_master"]
        )
    except SaltCloudException as exc:
        log.error(
            "Failed to deploy {0[name]!r}. Error: {1}".format(parallel_data, exc),
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG,
        )
        return {parallel_data["name"]: {"Error": str(exc)}}

    if parallel_data["opts"].get("show_deploy_args", False) is False and isinstance(
        output, dict
    ):
        output.pop("deploy_kwargs", None)

    return {parallel_data["name"]: salt.utils.cloud.simple_types_filter(output)}
# Buggy code
def _mod_init(self, low):
    """
    Check the module initialization function, if this is the first run
    of a state package that has a mod_init function, then execute the
    mod_init function in the state module.
    """
    # ensure that the module is loaded
    self.states["{0}.{1}".format(low["state"], low["fun"])]  # pylint: disable=W0106
    minit = "{0}.mod_init".format(low["state"])
    if low["state"] not in self.mod_init:
        if minit in self.states._dict:
            mret = self.states[minit](low)
            if not mret:
                return
            self.mod_init.add(low["state"])


# Traceback (KeyError)
ctrl.wolfcloud.bad4.us:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 1045, in _thread_return
return_data = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/state.py", line 698, in sls
ret = st_.state.call_high(high_)
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 2119, in call_high
ret = dict(list(disabled.items()) + list(self.call_chunks(chunks).items()))
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1651, in call_chunks
running = self.call_chunk(low, running, chunks)
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1819, in call_chunk
self._mod_init(low)
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 635, in _mod_init
self.states['{0}.{1}'.format(low['state'], low['fun'])]  # pylint: disable=W0106
File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'debconf.set'

# Fixed code
def _mod_init(self, low):
    """
    Check the module initialization function, if this is the first run
    of a state package that has a mod_init function, then execute the
    mod_init function in the state module.
    """
    # ensure that the module is loaded
    try:
        self.states["{0}.{1}".format(low["state"], low["fun"])]  # pylint: disable=W0106
    except KeyError:
        return
    minit = "{0}.mod_init".format(low["state"])
    if low["state"] not in self.mod_init:
        if minit in self.states._dict:
            mret = self.states[minit](low)
            if not mret:
                return
            self.mod_init.add(low["state"])
# Buggy code
def _progress_ret(self, progress, out):
    """
    Print progress events
    """
    import salt.output

    # Get the progress bar
    if not hasattr(self, "progress_bar"):
        self.progress_bar = salt.output.get_progress(self.config, out, progress)
    salt.output.update_progress(self.config, progress, self.progress_bar, out)


# Traceback (NameError)
$ salt blah state.highstate --summary -p
[WARNING ] Failed to open log file, do you have permission to write to /var/log/salt/master?
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
NameError: global name 'progressbar' is not defined
Traceback (most recent call last):
File "/usr/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 349, in salt_main
client.run()
File "/usr/lib/python2.6/site-packages/salt/cli/salt.py", line 179, in run
self._progress_ret(progress, out)
File "/usr/lib/python2.6/site-packages/salt/cli/salt.py", line 271, in _progress_ret
self.progress_bar = salt.output.get_progress(self.config, out, progress)
File "/usr/lib/python2.6/site-packages/salt/output/__init__.py", line 64, in get_progress
mod='output')['{0}.progress_iter'.format(out)](progress)
File "/usr/lib/python2.6/site-packages/salt/output/progress.py", line 29, in progress_iter
widgets = [progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer(), ' Returns: [', progressbar.Counter(), '/{0}]'.format(progress['minion_count'])]
NameError: global name 'progressbar' is not defined
Traceback (most recent call last):
File "/usr/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 349, in salt_main
client.run()
File "/usr/lib/python2.6/site-packages/salt/cli/salt.py", line 179, in run
self._progress_ret(progress, out)
File "/usr/lib/python2.6/site-packages/salt/cli/salt.py", line 271, in _progress_ret
self.progress_bar = salt.output.get_progress(self.config, out, progress)
File "/usr/lib/python2.6/site-packages/salt/output/__init__.py", line 64, in get_progress
mod='output')['{0}.progress_iter'.format(out)](progress)
File "/usr/lib/python2.6/site-packages/salt/output/progress.py", line 29, in progress_iter
widgets = [progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer(), ' Returns: [', progressbar.Counter(), '/{0}]'.format(progress['minion_count'])]
NameError: global name 'progressbar' is not defined

# Fixed code
def _progress_ret(self, progress, out):
    """
    Print progress events
    """
    import salt.output

    # Get the progress bar
    if not hasattr(self, "progress_bar"):
        try:
            self.progress_bar = salt.output.get_progress(self.config, out, progress)
        except Exception as exc:
            raise salt.exceptions.LoaderError(
                "\nWARNING: Install the `progressbar` python package. "
                "Requested job was still run but output cannot be displayed.\n"
            )
    salt.output.update_progress(self.config, progress, self.progress_bar, out)