gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _read_regpol_file(reg_pol_path):
    """
    helper function to read a reg policy file and return decoded data
    """
    returndata = None
    if os.path.exists(reg_pol_path):
        with open(reg_pol_path, "rb") as pol_file:
            returndata = pol_file.read()
        returndata = returndata.decode("utf-16-le")
    return returndata


# Traceback (UnicodeEncodeError)
win2016-3:
----------
ID: router_gpo_1
Function: lgpo.set
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt\state.py", line 1843, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt\loader.py", line 1795, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt\states\win_lgpo.py", line 244, in set_
hierarchical_return=False)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 5021, in get
return_not_configured=return_not_configured))
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 3810, in _checkAllAdmxPolicies
policy_filedata):
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 3250, in _checkValueItemParent
check_deleted=check_deleted)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 3501, in _processValueItem
six.unichr(len(this_element_value.encode('utf-16-le'))),
UnicodeEncodeError: 'utf-16-le' codec can't encode character '\udd00' in position 0: surrogates not allowed
Started: 18:44:09.868773
Duration: 6765.204 ms
Changes:

Summary for win2016-3
------------
Succeeded: 0
Failed:    1
------------
Total states run:     1
Total run time:   6.765 s

# Fixed code
def _read_regpol_file(reg_pol_path):
    """
    helper function to read a reg policy file and return decoded data
    """
    returndata = None
    if os.path.exists(reg_pol_path):
        with open(reg_pol_path, "rb") as pol_file:
            returndata = pol_file.read()
    return returndata
# Buggy code
def _regexSearchKeyValueCombo(policy_data, policy_regpath, policy_regkey):
    """
    helper function to do a search of Policy data from a registry.pol file
    for a policy_regpath and policy_regkey combo
    """
    if policy_data:
        specialValueRegex = r"(\*\*Del\.|\*\*DelVals\.){0,1}"
        _thisSearch = r"\[{1}{0};{3}{2}{0};".format(
            chr(0),
            re.escape(policy_regpath),
            re.escape(policy_regkey),
            specialValueRegex,
        )
        match = re.search(_thisSearch, policy_data, re.IGNORECASE)
        if match:
            return policy_data[
                match.start() : (policy_data.index("]", match.end())) + 1
            ]

    return None


# Traceback (UnicodeEncodeError)
win2016-3:
----------
ID: router_gpo_1
Function: lgpo.set
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt\state.py", line 1843, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt\loader.py", line 1795, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt\states\win_lgpo.py", line 244, in set_
hierarchical_return=False)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 5021, in get
return_not_configured=return_not_configured))
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 3810, in _checkAllAdmxPolicies
policy_filedata):
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 3250, in _checkValueItemParent
check_deleted=check_deleted)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_lgpo.py", line 3501, in _processValueItem
six.unichr(len(this_element_value.encode('utf-16-le'))),
UnicodeEncodeError: 'utf-16-le' codec can't encode character '\udd00' in position 0: surrogates not allowed
Started: 18:44:09.868773
Duration: 6765.204 ms
Changes:

Summary for win2016-3
------------
Succeeded: 0
Failed:    1
------------
Total states run:     1
Total run time:   6.765 s

# Fixed code
def _regexSearchKeyValueCombo(policy_data, policy_regpath, policy_regkey):
    """
    helper function to do a search of Policy data from a registry.pol file
    for a policy_regpath and policy_regkey combo
    """
    if policy_data:
        specialValueRegex = salt.utils.to_bytes(r"(\*\*Del\.|\*\*DelVals\.){0,1}")
        _thisSearch = b"".join(
            [
                salt.utils.to_bytes(r"\["),
                re.escape(policy_regpath),
                b"\00;",
                specialValueRegex,
                re.escape(policy_regkey),
                b"\00;",
            ]
        )
        match = re.search(_thisSearch, policy_data, re.IGNORECASE)
        if match:
            return policy_data[
                match.start() : (policy_data.index("]", match.end())) + 1
            ]

    return None
# Buggy code
def _parse_member(settype, member, strict=False):
    subtypes = settype.split(":")[1].split(",")

    parts = member.split(" ")

    parsed_member = []
    for i in range(len(subtypes)):
        subtype = subtypes[i]
        part = parts[i]

        if subtype in ["ip", "net"]:
            try:
                if "/" in part:
                    part = ipaddress.ip_network(part, strict=strict)
                elif "-" in part:
                    start, end = list(map(ipaddress.ip_address, part.split("-")))

                    part = list(ipaddress.summarize_address_range(start, end))
                else:
                    part = ipaddress.ip_address(part)
            except ValueError:
                pass

        elif subtype == "port":
            part = int(part)

        parsed_member.append(part)

    if len(parts) > len(subtypes):
        parsed_member.append(" ".join(parts[len(subtypes) :]))

    return parsed_member


# Traceback (IndexError)
ID: mac_ip_addr_allowed_entries
Function: ipset.present
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 1843, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1795, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/ipset.py", line 211, in present
family) is True:
File "/usr/lib/python2.7/site-packages/salt/modules/ipset.py", line 431, in check
current_members = _parse_members(settype, _find_set_members(set))
File "/usr/lib/python2.7/site-packages/salt/modules/ipset.py", line 582, in _parse_members
return [_parse_member(settype, member) for member in members]
File "/usr/lib/python2.7/site-packages/salt/modules/ipset.py", line 593, in _parse_member
part = parts[i]
IndexError: list index out of range
Started: 14:40:57.583261
Duration: 24.065 ms

# Fixed code
def _parse_member(settype, member, strict=False):
    subtypes = settype.split(":")[1].split(",")

    all_parts = member.split(" ", 1)
    parts = all_parts[0].split(",")

    parsed_member = []
    for i in range(len(subtypes)):
        subtype = subtypes[i]
        part = parts[i]

        if subtype in ["ip", "net"]:
            try:
                if "/" in part:
                    part = ipaddress.ip_network(part, strict=strict)
                elif "-" in part:
                    start, end = list(map(ipaddress.ip_address, part.split("-")))

                    part = list(ipaddress.summarize_address_range(start, end))
                else:
                    part = ipaddress.ip_address(part)
            except ValueError:
                pass

        elif subtype == "port":
            part = int(part)

        parsed_member.append(part)

    if len(all_parts) > 1:
        parsed_member.append(all_parts[1])

    return parsed_member
# Buggy code
def _zfs_support():
    """
    Provide information about zfs kernel module
    """
    grains = {"zfs_support": False}

    # Check for zfs support
    # NOTE: ZFS on Windows is in development
    # NOTE: ZFS on NetBSD is in development
    on_supported_platform = False
    if salt.utils.platform.is_sunos() and salt.utils.path.which("zfs"):
        on_supported_platform = True
    elif salt.utils.platform.is_freebsd() and _check_retcode("kldstat -q -m zfs"):
        on_supported_platform = True
    elif salt.utils.platform.is_linux():
        modinfo = salt.utils.path.which("modinfo")
        if modinfo:
            on_supported_platform = _check_retcode("{0} zfs".format(modinfo))
        else:
            on_supported_platform = _check_retcode("ls /sys/module/zfs")

        # NOTE: fallback to zfs-fuse if needed
        if not on_supported_platform:
            _zfs_fuse = lambda f: __salt__["service." + f]("zfs-fuse")
            if _zfs_fuse("available") and (_zfs_fuse("status") or _zfs_fuse("start")):
                on_supported_platform = True

    # Additional check for the zpool command
    if on_supported_platform and salt.utils.path.which("zpool"):
        grains["zfs_support"] = True

    return grains


# Traceback (KeyError)
# salt-call --local test.ping
[CRITICAL] Failed to load grains defined in grain file zfs.zfs in function <function zfs at 0x7f438e6b1c08>, error:
Traceback (most recent call last):
File "/root/SaltStack/salt/salt/loader.py", line 752, in grains
ret = funcs[key]()
File "/root/SaltStack/salt/salt/grains/zfs.py", line 109, in zfs
grains = salt.utils.dictupdate.update(grains, _zfs_support(), merge_lists=True)
File "/root/SaltStack/salt/salt/grains/zfs.py", line 75, in _zfs_support
if _zfs_fuse('available') and (_zfs_fuse('status') or _zfs_fuse('start')):
File "/root/SaltStack/salt/salt/grains/zfs.py", line 74, in <lambda>
_zfs_fuse = lambda f: __salt__['service.' + f]('zfs-fuse')
KeyError: 'service.available'

# Fixed code
def _zfs_support():
    """
    Provide information about zfs kernel module
    """
    grains = {"zfs_support": False}

    # Check for zfs support
    # NOTE: ZFS on Windows is in development
    # NOTE: ZFS on NetBSD is in development
    on_supported_platform = False
    if salt.utils.platform.is_sunos() and salt.utils.path.which("zfs"):
        on_supported_platform = True
    elif salt.utils.platform.is_freebsd() and _check_retcode("kldstat -q -m zfs"):
        on_supported_platform = True
    elif salt.utils.platform.is_linux():
        modinfo = salt.utils.path.which("modinfo")
        if modinfo:
            on_supported_platform = _check_retcode("{0} zfs".format(modinfo))
        else:
            on_supported_platform = _check_retcode("ls /sys/module/zfs")

        # NOTE: fallback to zfs-fuse if needed
        if not on_supported_platform and salt.utils.path.which("zfs-fuse"):
            on_supported_platform = True

    # Additional check for the zpool command
    if on_supported_platform and salt.utils.path.which("zpool"):
        grains["zfs_support"] = True

    return grains
# Buggy code
def optional_args(proxy=None):
    """
    Return the connection optional args.

    .. note::

        Sensible data will not be returned.

    .. versionadded:: 2017.7.0

    CLI Example - select all devices connecting via port 1234:

    .. code-block:: bash

        salt -G 'optional_args:port:1234' test.ping

    Output:

    .. code-block:: yaml

        device1:
            True
        device2:
            True
    """
    opt_args = _get_device_grain("optional_args", proxy=proxy)
    if _FORBIDDEN_OPT_ARGS:
        for arg in _FORBIDDEN_OPT_ARGS:
            opt_args.pop(arg, None)
    return {"optional_args": opt_args}


# Traceback (AttributeError)
2017-08-29 12:06:46,748 [salt.loader      ][CRITICAL][23751] Failed to load grains defined in grain file napalm.optional_args in function <function optional_args at 0x7fb0a4114a28>, error:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 738, in grains
ret = funcs[key](proxy)
File "/usr/lib/python2.7/dist-packages/salt/grains/napalm.py", line 453, in optional_args
opt_args.pop(arg, None)
AttributeError: 'NoneType' object has no attribute 'pop'

# Fixed code
def optional_args(proxy=None):
    """
    Return the connection optional args.

    .. note::

        Sensible data will not be returned.

    .. versionadded:: 2017.7.0

    CLI Example - select all devices connecting via port 1234:

    .. code-block:: bash

        salt -G 'optional_args:port:1234' test.ping

    Output:

    .. code-block:: yaml

        device1:
            True
        device2:
            True
    """
    opt_args = _get_device_grain("optional_args", proxy=proxy) or {}
    if opt_args and _FORBIDDEN_OPT_ARGS:
        for arg in _FORBIDDEN_OPT_ARGS:
            opt_args.pop(arg, None)
    return {"optional_args": opt_args}
# Buggy code
def _search(prefix="latest/"):
    """
    Recursively look up all grains in the metadata server
    """
    ret = {}
    for line in http.query(os.path.join(HOST, prefix))["body"].split("\n"):
        if line.endswith("/"):
            ret[line[:-1]] = _search(prefix=os.path.join(prefix, line))
        elif "=" in line:
            key, value = line.split("=")
            ret[value] = _search(prefix=os.path.join(prefix, key))
        else:
            ret[line] = http.query(os.path.join(HOST, prefix, line))["body"]
    return ret


# Traceback (KeyError)
[CRITICAL] Failed to load grains defined in grain file metadata.metadata in function <function metadata at 0x1e8c320>, error:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 740, in grains
ret = funcs[key]()
File "/usr/lib/python2.7/site-packages/salt/grains/metadata.py", line 62, in metadata
return _search()
File "/usr/lib/python2.7/site-packages/salt/grains/metadata.py", line 57, in _search
ret[line] = http.query(os.path.join(HOST, prefix, line))['body']
KeyError: 'body'

# Fixed code
def _search(prefix="latest/"):
    """
    Recursively look up all grains in the metadata server
    """
    ret = {}
    linedata = http.query(os.path.join(HOST, prefix))
    if "body" not in linedata:
        return ret
    for line in linedata["body"].split("\n"):
        if line.endswith("/"):
            ret[line[:-1]] = _search(prefix=os.path.join(prefix, line))
        elif prefix == "latest/":
            # (gtmanfred) The first level should have a forward slash since
            # they have stuff underneath. This will not be doubled up though,
            # because lines ending with a slash are checked first.
            ret[line] = _search(prefix=os.path.join(prefix, line + "/"))
        elif "=" in line:
            key, value = line.split("=")
            ret[value] = _search(prefix=os.path.join(prefix, key))
        else:
            retdata = http.query(os.path.join(HOST, prefix, line)).get("body", None)
            # (gtmanfred) This try except block is slightly faster than
            # checking if the string starts with a curly brace
            try:
                ret[line] = json.loads(retdata)
            except ValueError:
                ret[line] = retdata
    return ret
# Buggy code
def _validate(
    template_body=None,
    template_url=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    # Validates template. returns true if template syntax is correct.
    validate = __salt__["boto_cfn.validate_template"](
        template_body, template_url, region, key, keyid, profile
    )
    log.debug("Validate is result is {0}.".format(str(validate)))
    if isinstance(validate, str):
        code, message = _get_error(validate)
        log.debug("Validate error is {0} and message is {1}.".format(code, message))
        return code, message
    return True


# Traceback (AttributeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/local/lib/python2.6/site-packages/salt/state.py", line 1735, in call
**cdata['kwargs'])
File "/usr/local/lib/python2.6/site-packages/salt/loader.py", line 1653, in wrapper
return f(*args, **kwargs)
File "/usr/lib64/python2.6/contextlib.py", line 34, in __exit__
self.gen.throw(type, value, traceback)
File "/usr/local/lib/python2.6/site-packages/salt/utils/context.py", line 48, in func_globals_inject
yield
File "/usr/local/lib/python2.6/site-packages/salt/loader.py", line 1653, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/salt/states/boto_cfn.py", line 147, in present
code, message = _get_error(_valid)
File "/usr/local/lib/python2.6/site-packages/salt/states/boto_cfn.py", line 263, in _get_error
error = '\n'.join(error.split('\n')[1:])
AttributeError: 'tuple' object has no attribute 'split'

# Fixed code
def _validate(
    template_body=None,
    template_url=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    # Validates template. returns true if template syntax is correct.
    validate = __salt__["boto_cfn.validate_template"](
        template_body, template_url, region, key, keyid, profile
    )
    log.debug("Validate result is {0}.".format(str(validate)))
    if isinstance(validate, str):
        code, message = _get_error(validate)
        log.debug("Validate error is {0} and message is {1}.".format(code, message))
        return code, message
    return True
# Buggy code
def destroy(name):
    """
    Remove a node from Vultr
    """
    node = show_instance(name, call="action")
    params = {"SUBID": node["SUBID"]}
    result = _query(
        "server/destroy", method="POST", decode=False, data=urllib.urlencode(params)
    )
    if result["body"] == "" and result["text"] == "":
        return True
    return result


# Traceback (KeyError)
1 durr@rwpscrape:/media/Storage/Scripts/AutoTriever/marshaller⟫ sudo python salt_runner.py destroy
Setting up loggers....
done
Main.MainThread - CRITICAL - Uncaught exception!
Main.MainThread - CRITICAL - Uncaught exception
Traceback (most recent call last):
File "salt_runner.py", line 282, in <module>
herder.destroy_client("test-1")
File "salt_runner.py", line 200, in destroy_client
self.cc.destroy(clientname)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 371, in destroy
mapper.destroy(names)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1032, in destroy
ret = self.clouds[fun](name)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/vultrpy.py", line 179, in destroy
if result['body'] == '' and result['text'] == '':
KeyError: 'body'

# Fixed code
def destroy(name):
    """
    Remove a node from Vultr
    """
    node = show_instance(name, call="action")
    params = {"SUBID": node["SUBID"]}
    result = _query(
        "server/destroy", method="POST", decode=False, data=urllib.urlencode(params)
    )

    # The return of a destroy call is empty in the case of a success.
    # Errors are only indicated via HTTP status code. Status code 200
    # effetively therefore means "success".
    if result.get("body") == "" and result.get("text") == "":
        return True
    return result
# Buggy code
def create(self, provider, names, **kwargs):
    """
    Create the named VMs, without using a profile

    Example:

    .. code-block:: python

        client.create(names=['myinstance'], provider='my-ec2-config',
            kwargs={'image': 'ami-1624987f', 'size': 't1.micro',
                    'ssh_username': 'ec2-user', 'securitygroup': 'default',
                    'delvol_on_destroy': True})
    """
    mapper = salt.cloud.Map(self._opts_defaults())
    providers = self.opts["providers"]
    if provider in providers:
        provider += ":{0}".format(next(six.iterkeys(providers[provider])))
    else:
        return False
    if isinstance(names, str):
        names = names.split(",")
    ret = {}
    for name in names:
        vm_ = kwargs.copy()
        vm_["name"] = name
        vm_["driver"] = provider
        vm_["profile"] = None
        ret[name] = salt.utils.simple_types_filter(mapper.create(vm_))
    return ret


# Traceback (KeyError)
Traceback (most recent call last):
File "salt_runner.py", line 147, in make_client
ret = self.cc.create(names=[clientname], provider=provider, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 404, in create
mapper.create(vm_))
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1182, in create
alias, driver = vm_['provider'].split(':')
KeyError: 'provider'

# Fixed code
def create(self, provider, names, **kwargs):
    """
    Create the named VMs, without using a profile

    Example:

    .. code-block:: python

        client.create(provider='my-ec2-config', names=['myinstance'],
            image='ami-1624987f', size='t1.micro', ssh_username='ec2-user',
            securitygroup='default', delvol_on_destroy=True)
    """
    mapper = salt.cloud.Map(self._opts_defaults())
    providers = self.opts["providers"]
    if provider in providers:
        provider += ":{0}".format(next(six.iterkeys(providers[provider])))
    else:
        return False
    if isinstance(names, str):
        names = names.split(",")
    ret = {}
    for name in names:
        vm_ = kwargs.copy()
        vm_["name"] = name
        vm_["driver"] = provider

        # This function doesn't require a profile, but many cloud drivers
        # check for profile information (which includes the provider key) to
        # help with config file debugging and setting up instances. Setting
        # the profile and provider defaults here avoids errors in other
        # cloud functions relying on these keys. See SaltStack Issue #41971
        # and PR #38166 for more information.
        vm_["profile"] = None
        vm_["provider"] = provider

        ret[name] = salt.utils.simple_types_filter(mapper.create(vm_))
    return ret
# Buggy code
def valid_id(opts, id_):
    """
    Returns if the passed id is valid
    """
    try:
        return bool(clean_path(opts["pki_dir"], id_))
    except (AttributeError, KeyError) as e:
        return False


# Traceback (TypeError)
2017-03-27 14:32:15,578 [salt.transport.mixins.auth                           ][INFO    ][25177] Authentication accepted from ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
2017-03-27 14:32:15,578 [tornado.application                                  ][ERROR   ][25177] Future exception was never retrieved: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 230, in wrapper
yielded = next(result)
File "/usr/lib/python2.7/dist-packages/salt/transport/zeromq.py", line 606, in handle_message
stream.send(self.serial.dumps(self._auth(payload['load'])))
File "/usr/lib/python2.7/dist-packages/salt/transport/mixins/auth.py", line 389, in _auth
if not os.path.isfile(pubfn) and not self.opts['open_mode']:
File "/usr/lib/python2.7/genericpath.py", line 29, in isfile
st = os.stat(path)
TypeError: must be encoded string without NULL bytes, not str

# Fixed code
def valid_id(opts, id_):
    """
    Returns if the passed id is valid
    """
    try:
        return bool(clean_path(opts["pki_dir"], id_))
    except (AttributeError, KeyError, TypeError) as e:
        return False
# Buggy code
def _add_new_ide_controller_helper(ide_controller_label, properties, bus_number):
    """
    Helper function for adding new IDE controllers

    .. versionadded:: 2016.3.0
    """
    random_key = randint(-200, -250)

    ide_spec = vim.vm.device.VirtualDeviceSpec()
    ide_spec.device = vim.vm.device.VirtualIDEController()

    ide_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

    ide_spec.device.key = random_key
    ide_spec.device.busNumber = bus_number
    ide_spec.device.deviceInfo = vim.Description()
    ide_spec.device.deviceInfo.label = ide_controller_label
    ide_spec.device.deviceInfo.summary = ide_controller_label

    return ide_spec


# Traceback (AttributeError)
[ERROR   ] There was a profile error: 'str' object has no attribute 'keys'
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/cli.py", line 284, in run
self.config.get('names')
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1446, in run_profile
ret[name] = self.create(vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1281, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/vmware.py", line 2319, in create
specs = _manage_devices(devices, object_ref)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/vmware.py", line 687, in _manage_devices
ide_controllers_to_create = list(set(devices['ide'].keys()) - set(existing_ide_controllers_label))
AttributeError: 'str' object has no attribute 'keys'

# Fixed code
def _add_new_ide_controller_helper(ide_controller_label, controller_key, bus_number):
    """
    Helper function for adding new IDE controllers

    .. versionadded:: 2016.3.0

    Args:
      ide_controller_label: label of the IDE controller
      controller_key: if not None, the controller key to use; otherwise it is randomly generated
      bus_number: bus number

    Returns: created device spec for an IDE controller

    """
    if controller_key is None:
        controller_key = randint(-200, 250)

    ide_spec = vim.vm.device.VirtualDeviceSpec()
    ide_spec.device = vim.vm.device.VirtualIDEController()

    ide_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

    ide_spec.device.key = controller_key
    ide_spec.device.busNumber = bus_number
    ide_spec.device.deviceInfo = vim.Description()
    ide_spec.device.deviceInfo.label = ide_controller_label
    ide_spec.device.deviceInfo.summary = ide_controller_label

    return ide_spec
# Buggy code
def __arg_comps(self):
    """
    Return the function name and the arg list
    """
    fun = self.argv[0] if self.argv else ""
    parsed = salt.utils.args.parse_input(self.argv[1:], condition=False)
    args = parsed[0]
    kws = parsed[1]
    return fun, args, kws


# Traceback (RestException)
2017-03-13 11:19:26.095 [INFO] 10.234.112.46 >> POST http://10.234.112.107/api/1.8/host/salt-host
{
"wwnlist":"['0011223344556677', '1122334455667788']"
}
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 97, in execute
(command, args) = get_args(command_list, version, params)
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 392, in get_args
raise RestException("Value of argument {} needs to be one of {}.".format(key, arg.arg_type), Code.BAD_REQUEST)
RestException: Value of argument wwnlist needs to be one of ['list'].
2017-03-13 11:19:26.101 [WARNING] << 400 BAD REQUEST
{
"msg":"Value of argument wwnlist needs to be one of ['list']."
}

# Fixed code
def __arg_comps(self):
    """
    Return the function name and the arg list
    """
    fun = self.argv[0] if self.argv else ""
    parsed = salt.utils.args.parse_input(
        self.argv[1:], condition=False, no_parse=self.opts.get("no_parse", [])
    )
    args = parsed[0]
    kws = parsed[1]
    return fun, args, kws
# Buggy code
def runner(fun, arg=None, timeout=5):
    """
    Execute a runner on the master and return the data from the runner
    function

    CLI Example:

    .. code-block:: bash

        salt publish.runner manage.down
    """
    arg = _parse_args(arg)

    if "master_uri" not in __opts__:
        return "No access to master. If using salt-call with --local, please remove."
    log.info("Publishing runner '{0}' to {master_uri}".format(fun, **__opts__))
    auth = salt.crypt.SAuth(__opts__)
    tok = auth.gen_token("salt")
    load = {
        "cmd": "minion_runner",
        "fun": fun,
        "arg": arg,
        "tok": tok,
        "tmo": timeout,
        "id": __opts__["id"],
    }

    channel = salt.transport.Channel.factory(__opts__)
    try:
        return channel.send(load)
    except SaltReqTimeoutError:
        return "'{0}' runner publish timed out".format(fun)


# Traceback (RestException)
2017-03-13 11:19:26.095 [INFO] 10.234.112.46 >> POST http://10.234.112.107/api/1.8/host/salt-host
{
"wwnlist":"['0011223344556677', '1122334455667788']"
}
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 97, in execute
(command, args) = get_args(command_list, version, params)
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 392, in get_args
raise RestException("Value of argument {} needs to be one of {}.".format(key, arg.arg_type), Code.BAD_REQUEST)
RestException: Value of argument wwnlist needs to be one of ['list'].
2017-03-13 11:19:26.101 [WARNING] << 400 BAD REQUEST
{
"msg":"Value of argument wwnlist needs to be one of ['list']."
}

# Fixed code
def runner(fun, arg=None, timeout=5):
    """
    Execute a runner on the master and return the data from the runner
    function

    CLI Example:

    .. code-block:: bash

        salt publish.runner manage.down
    """
    arg = _parse_args(arg)

    if "master_uri" not in __opts__:
        return "No access to master. If using salt-call with --local, please remove."
    log.info("Publishing runner '{0}' to {master_uri}".format(fun, **__opts__))
    auth = salt.crypt.SAuth(__opts__)
    tok = auth.gen_token("salt")
    load = {
        "cmd": "minion_runner",
        "fun": fun,
        "arg": arg,
        "tok": tok,
        "tmo": timeout,
        "id": __opts__["id"],
        "no_parse": __opts__.get("no_parse", []),
    }

    channel = salt.transport.Channel.factory(__opts__)
    try:
        return channel.send(load)
    except SaltReqTimeoutError:
        return "'{0}' runner publish timed out".format(fun)
# Buggy code
def parse_input(args, condition=True):
    """
    Parse out the args and kwargs from a list of input values. Optionally,
    return the args and kwargs without passing them to condition_input().

    Don't pull args with key=val apart if it has a newline in it.
    """
    _args = []
    _kwargs = {}
    for arg in args:
        if isinstance(arg, six.string_types):
            arg_name, arg_value = parse_kwarg(arg)
            if arg_name:
                _kwargs[arg_name] = yamlify_arg(arg_value)
            else:
                _args.append(yamlify_arg(arg))
        elif isinstance(arg, dict):
            # Yes, we're popping this key off and adding it back if
            # condition_input is called below, but this is the only way to
            # gracefully handle both CLI and API input.
            if arg.pop("__kwarg__", False) is True:
                _kwargs.update(arg)
            else:
                _args.append(arg)
        else:
            _args.append(arg)
    if condition:
        return condition_input(_args, _kwargs)
    return _args, _kwargs


# Traceback (RestException)
2017-03-13 11:19:26.095 [INFO] 10.234.112.46 >> POST http://10.234.112.107/api/1.8/host/salt-host
{
"wwnlist":"['0011223344556677', '1122334455667788']"
}
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 97, in execute
(command, args) = get_args(command_list, version, params)
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 392, in get_args
raise RestException("Value of argument {} needs to be one of {}.".format(key, arg.arg_type), Code.BAD_REQUEST)
RestException: Value of argument wwnlist needs to be one of ['list'].
2017-03-13 11:19:26.101 [WARNING] << 400 BAD REQUEST
{
"msg":"Value of argument wwnlist needs to be one of ['list']."
}

# Fixed code
def parse_input(args, condition=True, no_parse=None):
    """
    Parse out the args and kwargs from a list of input values. Optionally,
    return the args and kwargs without passing them to condition_input().

    Don't pull args with key=val apart if it has a newline in it.
    """
    if no_parse is None:
        no_parse = ()
    _args = []
    _kwargs = {}
    for arg in args:
        if isinstance(arg, six.string_types):
            arg_name, arg_value = parse_kwarg(arg)
            if arg_name:
                _kwargs[arg_name] = (
                    yamlify_arg(arg_value) if arg_name not in no_parse else arg_value
                )
            else:
                _args.append(yamlify_arg(arg))
        elif isinstance(arg, dict):
            # Yes, we're popping this key off and adding it back if
            # condition_input is called below, but this is the only way to
            # gracefully handle both CLI and API input.
            if arg.pop("__kwarg__", False) is True:
                _kwargs.update(arg)
            else:
                _args.append(arg)
        else:
            _args.append(arg)
    if condition:
        return condition_input(_args, _kwargs)
    return _args, _kwargs
# Buggy code
def _mixin_after_parsed(self):
    if not self.args:
        self.print_help()
        self.error("Insufficient arguments")

    if self.options.list:
        if "," in self.args[0]:
            self.config["tgt"] = self.args[0].split(",")
        else:
            self.config["tgt"] = self.args[0].split()
    else:
        self.config["tgt"] = self.args[0]

    self.config["argv"] = self.args[1:]
    if not self.config["argv"] or not self.config["tgt"]:
        self.print_help()
        self.error("Insufficient arguments")

    if self.options.ssh_askpass:
        self.options.ssh_passwd = getpass.getpass("Password: ")
        for group in self.option_groups:
            for option in group.option_list:
                if option.dest == "ssh_passwd":
                    option.explicit = True
                    break


# Traceback (RestException)
2017-03-13 11:19:26.095 [INFO] 10.234.112.46 >> POST http://10.234.112.107/api/1.8/host/salt-host
{
"wwnlist":"['0011223344556677', '1122334455667788']"
}
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 97, in execute
(command, args) = get_args(command_list, version, params)
File "/usr/lib/python2.7/dist-packages/pure/rest/controller/util.py", line 392, in get_args
raise RestException("Value of argument {} needs to be one of {}.".format(key, arg.arg_type), Code.BAD_REQUEST)
RestException: Value of argument wwnlist needs to be one of ['list'].
2017-03-13 11:19:26.101 [WARNING] << 400 BAD REQUEST
{
"msg":"Value of argument wwnlist needs to be one of ['list']."
}

# Fixed code
def _mixin_after_parsed(self):
    if not self.args:
        self.print_help()
        self.error("Insufficient arguments")

    if self.options.list:
        if "," in self.args[0]:
            self.config["tgt"] = self.args[0].split(",")
        else:
            self.config["tgt"] = self.args[0].split()
    else:
        self.config["tgt"] = self.args[0]

    self.config["argv"] = self.args[1:]
    if not self.config["argv"] or not self.config["tgt"]:
        self.print_help()
        self.error("Insufficient arguments")

    # Add back the --no-parse options so that shimmed/wrapped commands
    # handle the arguments correctly.
    if self.options.no_parse:
        self.config["argv"].append("--no-parse=" + ",".join(self.options.no_parse))

    if self.options.ssh_askpass:
        self.options.ssh_passwd = getpass.getpass("Password: ")
        for group in self.option_groups:
            for option in group.option_list:
                if option.dest == "ssh_passwd":
                    option.explicit = True
                    break
# Buggy code
def _get_node(name=None, instance_id=None, location=None):
    if location is None:
        location = get_location()

    params = {"Action": "DescribeInstances"}

    if str(name).startswith("i-") and (len(name) == 10 or len(name) == 19):
        instance_id = name

    if instance_id:
        params["InstanceId.1"] = instance_id
    else:
        params["Filter.1.Name"] = "tag:Name"
        params["Filter.1.Value.1"] = name

    log.trace(params)

    provider = get_provider()

    attempts = 10
    while attempts >= 0:
        try:
            instances = aws.query(
                params, location=location, provider=provider, opts=__opts__, sigver="4"
            )
            return _extract_instance_info(instances).values()[0]
        except IndexError:
            attempts -= 1
            log.debug(
                "Failed to get the data for node '{0}'. Remaining attempts: {1}".format(
                    instance_id or name, attempts
                )
            )
            # Just a little delay between attempts...
            time.sleep(0.5)
    return {}


# Traceback (TypeError)
[ERROR   ] There was a profile error: a bytes-like object is required, not 'str'
Traceback (most recent call last):
File "/root/salt/salt/cloud/cli.py", line 284, in run
self.config.get('names')
File "/root/salt/salt/cloud/__init__.py", line 1449, in run_profile
ret[name] = self.create(vm_)
File "/root/salt/salt/cloud/__init__.py", line 1279, in create
output = self.clouds[func](vm_)
File "/root/salt/salt/cloud/clouds/ec2.py", line 2558, in create
vm_['name'], vm_['profile'], 'ec2', vm_['driver']
File "/root/salt/salt/utils/cloud.py", line 2540, in cachedir_index_add
index = msgpack.load(fh_)
File "msgpack/_unpacker.pyx", line 164, in msgpack._unpacker.unpack (msgpack/_unpacker.cpp:2622)
File "msgpack/_unpacker.pyx", line 124, in msgpack._unpacker.unpackb (msgpack/_unpacker.cpp:1918)
TypeError: a bytes-like object is required, not 'str'

# Fixed code
def _get_node(name=None, instance_id=None, location=None):
    if location is None:
        location = get_location()

    params = {"Action": "DescribeInstances"}

    if str(name).startswith("i-") and (len(name) == 10 or len(name) == 19):
        instance_id = name

    if instance_id:
        params["InstanceId.1"] = instance_id
    else:
        params["Filter.1.Name"] = "tag:Name"
        params["Filter.1.Value.1"] = name

    log.trace(params)

    provider = get_provider()

    attempts = 10
    while attempts >= 0:
        try:
            instances = aws.query(
                params, location=location, provider=provider, opts=__opts__, sigver="4"
            )
            instance_info = _extract_instance_info(instances).values()
            return next(iter(instance_info))
        except IndexError:
            attempts -= 1
            log.debug(
                "Failed to get the data for node '{0}'. Remaining attempts: {1}".format(
                    instance_id or name, attempts
                )
            )
            # Just a little delay between attempts...
            time.sleep(0.5)
    return {}
# Buggy code
def _get_ttl():
    return __opts__["keep_jobs"] * 3600


# Traceback (KeyError)
2017-05-26 17:43:53,701 [salt.minion                                          ][ERROR   ][28880] The return failed for job 20170526175027868393 'keep_jobs'
2017-05-26 17:43:53,701 [salt.minion                                          ][ERROR   ][28880] Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 1575, in _thread_return
minion_instance.returners[returner_str](ret)
File "/usr/lib/python2.7/dist-packages/salt/returners/redis_return.py", line 131, in returner
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
File "/usr/lib/python2.7/dist-packages/salt/returners/redis_return.py", line 120, in _get_ttl
return __opts__['keep_jobs'] * 3600
KeyError: 'keep_jobs'

# Fixed code
def _get_ttl():
    return __opts__.get("keep_jobs", 24) * 3600
# Buggy code
def _mbcs_to_unicode_wrap(obj, vtype):
    """
    Wraps _mbcs_to_unicode for use with registry vdata
    """
    if vtype == "REG_BINARY":
        # We should be able to leave it alone if the user has passed binary data in yaml with
        # binary !!
        # In python < 3 this should have type str and in python 3+ this should be a byte array
        return obj
    if isinstance(obj, list):
        return [_mbcs_to_unicode(x) for x in obj]
    elif isinstance(obj, int):
        return obj
    else:
        return _mbcs_to_unicode(obj)


# Traceback (TypeError)
[ERROR   ] coercing to Unicode: need string or buffer, long found
Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\modules\reg.py", line 565, in set_value
local_vdata = _mbcs_to_unicode_wrap(vdata, local_vtype)
File "C:\salt\bin\lib\site-packages\salt\modules\reg.py", line 120, in _mbcs_to_unicode_wrap
return _mbcs_to_unicode(obj)
File "C:\salt\bin\lib\site-packages\salt\modules\reg.py", line 103, in _mbcs_to_unicode
return six.text_type(instr, 'mbcs')
TypeError: coercing to Unicode: need string or buffer, long found
[ERROR   ] Failed to add HKLM\SOFTWARE to HKLM\SOFTWARE

# Fixed code
def _mbcs_to_unicode_wrap(obj, vtype):
    """
    Wraps _mbcs_to_unicode for use with registry vdata
    """
    if vtype == "REG_BINARY":
        # We should be able to leave it alone if the user has passed binary data in yaml with
        # binary !!
        # In python < 3 this should have type str and in python 3+ this should be a byte array
        return obj
    if isinstance(obj, list):
        return [_mbcs_to_unicode(x) for x in obj]
    elif isinstance(obj, six.integer_types):
        return obj
    else:
        return _mbcs_to_unicode(obj)
# Buggy code
def start(
    docker_url="unix://var/run/docker.sock",
    timeout=CLIENT_TIMEOUT,
    tag="salt/engines/docker_events",
):
    """
    Scan for Docker events and fire events

    Example Config

    .. code-block:: yaml

        engines:
          docker_events:
            docker_url: unix://var/run/docker.sock

    The config above sets up engines to listen
    for events from the Docker daemon and publish
    them to the Salt event bus.
    """

    if __opts__.get("__role") == "master":
        fire_master = salt.utils.event.get_master_event(
            __opts__, __opts__["sock_dir"]
        ).fire_event
    else:
        fire_master = None

    def fire(tag, msg):
        """
        How to fire the event
        """
        if fire_master:
            fire_master(msg, tag)
        else:
            __salt__["event.send"](tag, msg)

    client = docker.Client(base_url=docker_url, timeout=timeout)
    try:
        events = client.events()
        for event in events:
            data = json.loads(event)
            fire("{0}/{1}".format(tag, data["status"]), data)
    except Exception:
        traceback.print_exc()


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/ezh/.virtualenvs/salt/lib/python3.4/site-packages/salt/engines/docker_events.py", line 82, in start
data = json.loads(event)
File "/usr/lib64/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
[INFO    ] Process <class 'salt.engines.Engine'> (12581) died with exit status 0, restarting...

# Fixed code
def start(
    docker_url="unix://var/run/docker.sock",
    timeout=CLIENT_TIMEOUT,
    tag="salt/engines/docker_events",
):
    """
    Scan for Docker events and fire events

    Example Config

    .. code-block:: yaml

        engines:
          docker_events:
            docker_url: unix://var/run/docker.sock

    The config above sets up engines to listen
    for events from the Docker daemon and publish
    them to the Salt event bus.
    """

    if __opts__.get("__role") == "master":
        fire_master = salt.utils.event.get_master_event(
            __opts__, __opts__["sock_dir"]
        ).fire_event
    else:
        fire_master = None

    def fire(tag, msg):
        """
        How to fire the event
        """
        if fire_master:
            fire_master(msg, tag)
        else:
            __salt__["event.send"](tag, msg)

    client = docker.Client(base_url=docker_url, timeout=timeout)
    try:
        events = client.events()
        for event in events:
            data = json.loads(event.decode(__salt_system_encoding__, errors="replace"))
            fire("{0}/{1}".format(tag, data["status"]), data)
    except Exception:
        traceback.print_exc()
# Buggy code
def __virtual__():
    """
    Only for MacOS with atrun enabled
    """
    if not salt.utils.is_darwin():
        return (
            False,
            "The mac_system module could not be loaded: "
            "module only works on MacOS systems.",
        )

    if not _atrun_enabled():
        if not _enable_atrun():
            return False, "atrun could not be enabled on this system"

    return __virtualname__


# Traceback (CommandExecutionError)
[DEBUG   ] LazyLoaded pkg.installed
[INFO    ] Executing command ['launchctl', 'list', 'com.apple.atrun'] in directory '/Users/will'
[ERROR   ] Command '['launchctl', 'list', 'com.apple.atrun']' failed with return code: 113
[ERROR   ] stderr: Could not find service "com.apple.atrun" in domain for
[ERROR   ] retcode: 113
[INFO    ] Executing command ['launchctl', 'enable', 'system/com.apple.atrun'] in directory '/Users/will'
[ERROR   ] Command '['launchctl', 'enable', 'system/com.apple.atrun']' failed with return code: 1
[ERROR   ] stderr: Could not enable service: 1: Operation not permitted
[ERROR   ] retcode: 1
[ERROR   ] Exception raised when processing __virtual__ function for salt.loaded.int.module.mac_system. Module will not be loaded: Failed to enable service:
stdout:
stderr: Could not enable service: 1: Operation not permitted
retcode: 1
Traceback (most recent call last):
File "/usr/local/Cellar/saltstack/HEAD-15e39d8/libexec/lib/python2.7/site-packages/salt/loader.py", line 1605, in process_virtual
virtual = getattr(mod, virtual_func)()
File "/usr/local/Cellar/saltstack/HEAD-15e39d8/libexec/lib/python2.7/site-packages/salt/modules/mac_system.py", line 36, in __virtual__
if not _enable_atrun():
File "/usr/local/Cellar/saltstack/HEAD-15e39d8/libexec/lib/python2.7/site-packages/salt/modules/mac_system.py", line 53, in _enable_atrun
__salt__['service.enable']('com.apple.atrun')
File "/usr/local/Cellar/saltstack/HEAD-15e39d8/libexec/lib/python2.7/site-packages/salt/modules/mac_service.py", line 277, in enable
return launchctl('enable', 'system/{0}'.format(label), runas=runas)
File "/usr/local/Cellar/saltstack/HEAD-15e39d8/libexec/lib/python2.7/site-packages/salt/modules/mac_service.py", line 212, in launchctl
raise CommandExecutionError(out)
CommandExecutionError: Failed to enable service:
stdout:
stderr: Could not enable service: 1: Operation not permitted
retcode: 1

[WARNING ] salt.loaded.int.module.mac_system.__virtual__() is wrongly returning `None`. It should either return `True`, `False` or a new name. If you're the developer of the module 'mac_system', please fix this.

# Fixed code
def __virtual__():
    """
    Only for MacOS with atrun enabled
    """
    if not salt.utils.is_darwin():
        return (
            False,
            "The mac_system module could not be loaded: "
            "module only works on MacOS systems.",
        )

    if getpass.getuser() != "root":
        return False, "The mac_system module is not useful for non-root users."

    if not _atrun_enabled():
        if not _enable_atrun():
            return False, "atrun could not be enabled on this system"

    return __virtualname__