gurudesh/pytracebugs huggingface dataset:
# 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__
# Buggy code
def _get_msiexec(use_msiexec):
    """
    Return if msiexec.exe will be used and the command to invoke it.
    """
    if use_msiexec is False:
        return (False, "")
    if os.path.isfile(use_msiexec):
        return (True, use_msiexec)
    else:
        log.warning(
            (
                "msiexec path '{0}' not found. Using system registered msiexec instead"
            ).format(use_msiexec)
        )
        use_msiexec = True
    if use_msiexec is True:
        return (True, "msiexec")


# Traceback (TypeError)
[root@li279-162 salt]# salt win2012 state.sls test
win2012:
----------
ID: winpkgs
Function: pkg.installed
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 1746, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt\loader.py", line 1704, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt\states\pkg.py", line 1442, in installed
**kwargs)
File "c:\salt\bin\lib\site-packages\salt\modules\win_pkg.py", line 1157, in install
use_msiexec, msiexec = _get_msiexec(pkginfo[version_num].get('msiexec', False))
File "c:\salt\bin\lib\site-packages\salt\modules\win_pkg.py", line 846, in _get_msiexec
if os.path.isfile(use_msiexec):
File "c:\salt\bin\lib\genericpath.py", line 37, in isfile
st = os.stat(path)
TypeError: coercing to Unicode: need string or buffer, bool found
Started: 10:32:15.301000
Duration: 31953.0 ms
Changes:

Summary for win2012
------------
Succeeded: 0
Failed:    1
------------
Total states run:     1
Total run time:  31.953 s
ERROR: Minions returned with non-zero exit code

# Fixed code
def _get_msiexec(use_msiexec):
    """
    Return if msiexec.exe will be used and the command to invoke it.
    """
    if use_msiexec is False:
        return False, ""
    if isinstance(use_msiexec, six.string_types):
        if os.path.isfile(use_msiexec):
            return True, use_msiexec
        else:
            log.warning(
                (
                    "msiexec path '{0}' not found. Using system registered"
                    " msiexec instead"
                ).format(use_msiexec)
            )
            use_msiexec = True
    if use_msiexec is True:
        return True, "msiexec"
# Buggy code
def action(fun=None, cloudmap=None, names=None, provider=None, instance=None, **kwargs):
    """
    Execute a single action on the given provider/instance

    CLI Example:

    .. code-block:: bash

        salt '*' cloud.action start instance=myinstance
        salt '*' cloud.action stop instance=myinstance
        salt '*' cloud.action show_image provider=my-ec2-config image=ami-1624987f
    """
    client = _get_client()
    info = client.action(fun, cloudmap, names, provider, instance, kwargs)
    return info


# Traceback (TypeError)
$  sudo salt-run cloud.action start instance=myinstance provider=amazon-frankfurt
Exception occurred in runner cloud.action: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/client/mixins.py", line 337, in low
data['return'] = self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/runners/cloud.py", line 139, in action
info = client.action(func, cloudmap, instances, provider, instance, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 466, in action
return mapper.do_function(provider, fun, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1511, in do_function
call='function', kwargs=kwargs
TypeError: start() got an unexpected keyword argument 'kwargs'

# Fixed code
def action(fun=None, cloudmap=None, names=None, provider=None, instance=None, **kwargs):
    """
    Execute a single action on the given provider/instance

    CLI Example:

    .. code-block:: bash

        salt '*' cloud.action start instance=myinstance
        salt '*' cloud.action stop instance=myinstance
        salt '*' cloud.action show_image provider=my-ec2-config image=ami-1624987f
    """
    client = _get_client()
    try:
        info = client.action(fun, cloudmap, names, provider, instance, kwargs)
    except SaltCloudConfigError as err:
        log.error(err)
        return None

    return info
# Buggy code
def action(
    func=None, cloudmap=None, instances=None, provider=None, instance=None, **kwargs
):
    """
    Execute a single action on the given map/provider/instance

    CLI Example:

    .. code-block:: bash

        salt-run cloud.action start my-salt-vm
    """
    client = _get_client()
    info = client.action(
        func, cloudmap, instances, provider, instance, **_filter_kwargs(kwargs)
    )
    return info


# Traceback (TypeError)
$  sudo salt-run cloud.action start instance=myinstance provider=amazon-frankfurt
Exception occurred in runner cloud.action: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/client/mixins.py", line 337, in low
data['return'] = self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/runners/cloud.py", line 139, in action
info = client.action(func, cloudmap, instances, provider, instance, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 466, in action
return mapper.do_function(provider, fun, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1511, in do_function
call='function', kwargs=kwargs
TypeError: start() got an unexpected keyword argument 'kwargs'

# Fixed code
def action(
    func=None, cloudmap=None, instances=None, provider=None, instance=None, **kwargs
):
    """
    Execute a single action on the given map/provider/instance

    CLI Example:

    .. code-block:: bash

        salt-run cloud.action start my-salt-vm
    """
    info = {}
    client = _get_client()
    try:
        info = client.action(
            func, cloudmap, instances, provider, instance, **_filter_kwargs(kwargs)
        )
    except SaltCloudConfigError as err:
        log.error(err)
    return info
# Buggy code
def action(
    self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None
):
    """
    Execute a single action via the cloud plugin backend

    Examples:

    .. code-block:: python

        client.action(fun='show_instance', names=['myinstance'])
        client.action(fun='show_image', provider='my-ec2-config',
            kwargs={'image': 'ami-10314d79'}
        )
    """
    mapper = salt.cloud.Map(self._opts_defaults(action=fun, names=names))
    if names and not provider:
        self.opts["action"] = fun
        return mapper.do_action(names, kwargs)
    if provider:
        return mapper.do_function(provider, fun, kwargs)
    else:
        # This should not be called without either an instance or a
        # provider.
        raise SaltCloudConfigError(
            "Either an instance or a provider must be specified."
        )


# Traceback (TypeError)
$  sudo salt-run cloud.action start instance=myinstance provider=amazon-frankfurt
Exception occurred in runner cloud.action: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/client/mixins.py", line 337, in low
data['return'] = self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/runners/cloud.py", line 139, in action
info = client.action(func, cloudmap, instances, provider, instance, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 466, in action
return mapper.do_function(provider, fun, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1511, in do_function
call='function', kwargs=kwargs
TypeError: start() got an unexpected keyword argument 'kwargs'

# Fixed code
def action(
    self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None
):
    """
    Execute a single action via the cloud plugin backend

    Examples:

    .. code-block:: python

        client.action(fun='show_instance', names=['myinstance'])
        client.action(fun='show_image', provider='my-ec2-config',
            kwargs={'image': 'ami-10314d79'}
        )
    """
    mapper = salt.cloud.Map(self._opts_defaults(action=fun, names=names))
    if instance:
        if names:
            raise SaltCloudConfigError(
                "Please specify either a list of 'names' or a single "
                "'instance', but not both."
            )
        names = [instance]

    if names and not provider:
        self.opts["action"] = fun
        return mapper.do_action(names, kwargs)

    if provider and not names:
        return mapper.do_function(provider, fun, kwargs)
    else:
        # This should not be called without either an instance or a
        # provider. If both an instance/list of names and a provider
        # are given, then we also need to exit. We can only have one
        # or the other.
        raise SaltCloudConfigError(
            "Either an instance (or list of names) or a provider must be "
            "specified, but not both."
        )
# Buggy code
def action(*args, **kwargs):
    """
    Execute a single action on the given map/provider/instance

    CLI Example:

    .. code-block:: bash

        salt-run cloud.actions start my-salt-vm
    """
    client = _get_client()
    info = client.action(
        args[0],
        kwargs.get("cloudmap", None),
        args[1:],
        kwargs.get("provider", None),
        kwargs.get("instance", None),
        kwargs,
    )
    return info


# Traceback (TypeError)
$  sudo salt-run cloud.action start instance=myinstance provider=amazon-frankfurt
Exception occurred in runner cloud.action: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/client/mixins.py", line 337, in low
data['return'] = self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/runners/cloud.py", line 139, in action
info = client.action(func, cloudmap, instances, provider, instance, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 466, in action
return mapper.do_function(provider, fun, kwargs)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1511, in do_function
call='function', kwargs=kwargs
TypeError: start() got an unexpected keyword argument 'kwargs'

# Fixed code
def action(*args, **kwargs):
    """
    Execute a single action on the given map/provider/instance

    CLI Example:

    .. code-block:: bash

        salt-run cloud.actions start my-salt-vm
    """
    client = _get_client()
    try:
        info = client.action(
            args[0],
            kwargs.get("cloudmap", None),
            args[1:],
            kwargs.get("provider", None),
            kwargs.get("instance", None),
            kwargs,
        )
    except SaltCloudConfigError as err:
        log.error(err)
        return {}

    return info
# Buggy code
def hash_file(path, hashobj, conn=None):
    """
    Get the hexdigest hash value of a file
    """
    if os.path.isdir(path):
        return ""

    with salt.utils.fopen(path, "r") as f:
        hashobj.update(f.read())
        return hashobj.hexdigest()


# Traceback (TypeError)
spm install apache
Installing packages:
apache

Proceed? [N/y] y
... installing apache
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
TypeError: Unicode-objects must be encoded before hashing
Traceback (most recent call last):
File "/usr/bin/spm", line 6, in <module>
exec(compile(open(__file__).read(), __file__, 'exec'))
File "/root/salt/scripts/spm", line 12, in <module>
salt_spm()
File "/root/salt/salt/scripts.py", line 487, in salt_spm
spm.run()
File "/root/salt/salt/cli/spm.py", line 34, in run
client.run(self.args)
File "/root/salt/salt/spm/__init__.py", line 114, in run
self._install(args)
File "/root/salt/salt/spm/__init__.py", line 365, in _install
self._install_indv_pkg(package, out_file)
File "/root/salt/salt/spm/__init__.py", line 522, in _install_indv_pkg
self.files_conn)
File "/root/salt/salt/spm/__init__.py", line 146, in _pkgfiles_fun
return getattr(getattr(self.pkgfiles, self.files_prov), func)(*args, **kwargs)
File "/root/salt/salt/spm/pkgfiles/local.py", line 183, in hash_file
hashobj.update(f.read())
TypeError: Unicode-objects must be encoded before hashing
Traceback (most recent call last):
File "/usr/bin/spm", line 6, in <module>
exec(compile(open(__file__).read(), __file__, 'exec'))
File "/root/salt/scripts/spm", line 12, in <module>
salt_spm()
File "/root/salt/salt/scripts.py", line 487, in salt_spm
spm.run()
File "/root/salt/salt/cli/spm.py", line 34, in run
client.run(self.args)
File "/root/salt/salt/spm/__init__.py", line 114, in run
self._install(args)
File "/root/salt/salt/spm/__init__.py", line 365, in _install
self._install_indv_pkg(package, out_file)
File "/root/salt/salt/spm/__init__.py", line 522, in _install_indv_pkg
self.files_conn)
File "/root/salt/salt/spm/__init__.py", line 146, in _pkgfiles_fun
return getattr(getattr(self.pkgfiles, self.files_prov), func)(*args, **kwargs)
File "/root/salt/salt/spm/pkgfiles/local.py", line 183, in hash_file
hashobj.update(f.read())
TypeError: Unicode-objects must be encoded before hashing

# Fixed code
def hash_file(path, hashobj, conn=None):
    """
    Get the hexdigest hash value of a file
    """
    if os.path.isdir(path):
        return ""

    with salt.utils.fopen(path, "r") as f:
        hashobj.update(salt.utils.to_bytes(f.read()))
        return hashobj.hexdigest()
# Buggy code
def _restore_ownership(func):
    @functools.wraps(func)
    def func_wrapper(*args, **kwargs):
        """
        Wrap gpg function calls to fix permissions
        """
        user = kwargs.get("user")
        gnupghome = kwargs.get("gnupghome")

        if not gnupghome:
            gnupghome = _get_user_gnupghome(user)

        userinfo = _get_user_info(user)
        run_user = _get_user_info()

        if userinfo["uid"] != run_user["uid"] and os.path.exists(gnupghome):
            # Given user is different from one who runs Salt process,
            # need to fix ownership permissions for GnuPG home dir
            group = __salt__["file.gid_to_group"](run_user["gid"])
            for path in [gnupghome] + __salt__["file.find"](gnupghome):
                __salt__["file.chown"](path, run_user["name"], group)

        # Filter special kwargs
        for key in kwargs:
            if key.startswith("__"):
                del kwargs[key]

        ret = func(*args, **kwargs)

        if userinfo["uid"] != run_user["uid"]:
            group = __salt__["file.gid_to_group"](userinfo["gid"])
            for path in [gnupghome] + __salt__["file.find"](gnupghome):
                __salt__["file.chown"](path, user, group)

        return ret

    return func_wrapper


# Traceback (RuntimeError)
saltdev:
The minion function caused an exception: Traceback (most recent call last):
File "/home/artanicus/salt.git/salt/minion.py", line 1446, in _thread_return
try:
File "/home/artanicus/salt.git/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/home/artanicus/salt.git/salt/modules/gpg.py", line 166, in func_wrapper
for key in kwargs:
RuntimeError: dictionary changed size during iteration

# Fixed code
def _restore_ownership(func):
    @functools.wraps(func)
    def func_wrapper(*args, **kwargs):
        """
        Wrap gpg function calls to fix permissions
        """
        user = kwargs.get("user")
        gnupghome = kwargs.get("gnupghome")

        if not gnupghome:
            gnupghome = _get_user_gnupghome(user)

        userinfo = _get_user_info(user)
        run_user = _get_user_info()

        if userinfo["uid"] != run_user["uid"] and os.path.exists(gnupghome):
            # Given user is different from one who runs Salt process,
            # need to fix ownership permissions for GnuPG home dir
            group = __salt__["file.gid_to_group"](run_user["gid"])
            for path in [gnupghome] + __salt__["file.find"](gnupghome):
                __salt__["file.chown"](path, run_user["name"], group)

        # Filter special kwargs
        for key in list(kwargs):
            if key.startswith("__"):
                del kwargs[key]

        ret = func(*args, **kwargs)

        if userinfo["uid"] != run_user["uid"]:
            group = __salt__["file.gid_to_group"](userinfo["gid"])
            for path in [gnupghome] + __salt__["file.find"](gnupghome):
                __salt__["file.chown"](path, user, group)

        return ret

    return func_wrapper
# Buggy code
def func_wrapper(*args, **kwargs):
    """
    Wrap gpg function calls to fix permissions
    """
    user = kwargs.get("user")
    gnupghome = kwargs.get("gnupghome")

    if not gnupghome:
        gnupghome = _get_user_gnupghome(user)

    userinfo = _get_user_info(user)
    run_user = _get_user_info()

    if userinfo["uid"] != run_user["uid"] and os.path.exists(gnupghome):
        # Given user is different from one who runs Salt process,
        # need to fix ownership permissions for GnuPG home dir
        group = __salt__["file.gid_to_group"](run_user["gid"])
        for path in [gnupghome] + __salt__["file.find"](gnupghome):
            __salt__["file.chown"](path, run_user["name"], group)

    # Filter special kwargs
    for key in kwargs:
        if key.startswith("__"):
            del kwargs[key]

    ret = func(*args, **kwargs)

    if userinfo["uid"] != run_user["uid"]:
        group = __salt__["file.gid_to_group"](userinfo["gid"])
        for path in [gnupghome] + __salt__["file.find"](gnupghome):
            __salt__["file.chown"](path, user, group)

    return ret


# Traceback (RuntimeError)
saltdev:
The minion function caused an exception: Traceback (most recent call last):
File "/home/artanicus/salt.git/salt/minion.py", line 1446, in _thread_return
try:
File "/home/artanicus/salt.git/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/home/artanicus/salt.git/salt/modules/gpg.py", line 166, in func_wrapper
for key in kwargs:
RuntimeError: dictionary changed size during iteration

# Fixed code
def func_wrapper(*args, **kwargs):
    """
    Wrap gpg function calls to fix permissions
    """
    user = kwargs.get("user")
    gnupghome = kwargs.get("gnupghome")

    if not gnupghome:
        gnupghome = _get_user_gnupghome(user)

    userinfo = _get_user_info(user)
    run_user = _get_user_info()

    if userinfo["uid"] != run_user["uid"] and os.path.exists(gnupghome):
        # Given user is different from one who runs Salt process,
        # need to fix ownership permissions for GnuPG home dir
        group = __salt__["file.gid_to_group"](run_user["gid"])
        for path in [gnupghome] + __salt__["file.find"](gnupghome):
            __salt__["file.chown"](path, run_user["name"], group)

    # Filter special kwargs
    for key in list(kwargs):
        if key.startswith("__"):
            del kwargs[key]

    ret = func(*args, **kwargs)

    if userinfo["uid"] != run_user["uid"]:
        group = __salt__["file.gid_to_group"](userinfo["gid"])
        for path in [gnupghome] + __salt__["file.find"](gnupghome):
            __salt__["file.chown"](path, user, group)

    return ret
# Buggy code
def Search(self, searchString):
    try:
        log.debug("beginning search of the passed string: {0}".format(searchString))
        self.search_results = self.win_searcher.Search(searchString)
        log.debug("search completed successfully.")
    except Exception as exc:
        log.info("search for updates failed. {0}".format(exc))
        return exc

    log.debug(
        "parsing results. {0} updates were found.".format(
            self.search_results.Updates.Count
        )
    )
    try:
        for update in self.search_results.Updates:
            if update.InstallationBehavior.CanRequestUserInput:
                log.debug("Skipped update {0}".format(update))
                continue
            for category in update.Categories:
                if self.skipDownloaded and update.IsDownloaded:
                    continue
                if self.categories is None or category.Name in self.categories:
                    self.download_collection.Add(update)
                    log.debug("added update {0}".format(update))
        self.foundCategories = _gather_update_categories(self.download_collection)
        return True
    except Exception as exc:
        log.info("parsing updates failed. {0}".format(exc))
        return exc


# Traceback (UnicodeEncodeError)
SERVER2008R2GUI:
The minion function caused an exception: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\minion.py", line 1039, in _thread_return
return_data = func(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_wua2.py", line 735, in install_update
return install_updates([guid])
File "c:\salt\var\cache\salt\minion\extmods\modules\win_wua2.py", line 811, in install_updates
log.debug('\tTitle: {0}'.format(update.Title))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 19: ordinal not in range(128)

# Fixed code
def Search(self, searchString):
    try:
        log.debug("beginning search of the passed string: {0}".format(searchString))
        self.search_results = self.win_searcher.Search(searchString)
        log.debug("search completed successfully.")
    except Exception as exc:
        log.info("search for updates failed. {0}".format(exc))
        return exc

    log.debug(
        "parsing results. {0} updates were found.".format(
            self.search_results.Updates.Count
        )
    )
    try:
        for update in self.search_results.Updates:
            if update.InstallationBehavior.CanRequestUserInput:
                log.debug("Skipped update {0}".format(update.title))
                continue
            for category in update.Categories:
                if self.skipDownloaded and update.IsDownloaded:
                    continue
                if self.categories is None or category.Name in self.categories:
                    self.download_collection.Add(update)
                    log.debug("added update {0}".format(update.title))
        self.foundCategories = _gather_update_categories(self.download_collection)
        return True
    except Exception as exc:
        log.info("parsing updates failed. {0}".format(exc))
        return exc
# Buggy code
def Install(self):
    try:
        for update in self.search_results.Updates:
            if update.IsDownloaded:
                self.install_collection.Add(update)
        log.debug("Updates prepared. beginning installation")
    except Exception as exc:
        log.info("Preparing install list failed: {0}".format(exc))
        return exc

    if self.install_collection.Count != 0:
        log.debug("Install list created, about to install")
        updates = []
        try:
            self.install_results = self.win_installer.Install()
            log.info("Installation of updates complete")
            return True
        except Exception as exc:
            log.info("Installation failed: {0}".format(exc))
            return exc
    else:
        log.info("no new updates.")
        return True


# Traceback (UnicodeEncodeError)
SERVER2008R2GUI:
The minion function caused an exception: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\minion.py", line 1039, in _thread_return
return_data = func(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_wua2.py", line 735, in install_update
return install_updates([guid])
File "c:\salt\var\cache\salt\minion\extmods\modules\win_wua2.py", line 811, in install_updates
log.debug('\tTitle: {0}'.format(update.Title))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 19: ordinal not in range(128)

# Fixed code
def Install(self):
    try:
        for update in self.search_results.Updates:
            if update.IsDownloaded:
                self.install_collection.Add(update)
        log.debug("Updates prepared. beginning installation")
    except Exception as exc:
        log.info("Preparing install list failed: {0}".format(exc))
        return exc

    # accept eula if not accepted
    try:
        for update in self.search_results.Updates:
            if not update.EulaAccepted:
                log.debug("Accepting EULA: {0}".format(update.Title))
                update.AcceptEula()
    except Exception as exc:
        log.info("Accepting Eula failed: {0}".format(exc))
        return exc

    if self.install_collection.Count != 0:
        log.debug("Install list created, about to install")
        updates = []
        try:
            self.install_results = self.win_installer.Install()
            log.info("Installation of updates complete")
            return True
        except Exception as exc:
            log.info("Installation failed: {0}".format(exc))
            return exc
    else:
        log.info("no new updates.")
        return True
# Buggy code
def check_failhard(self, low, running):
    """
    Check if the low data chunk should send a failhard signal
    """
    tag = _gen_tag(low)
    if self.opts.get("test", False):
        return False
    if low.get("failhard", False) or self.opts["failhard"] and tag in running:
        if running[tag]["result"] is None:
            return False
        return not running[tag]["result"]
    return False


# Traceback (KeyError)
m1-linux:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/minion.py", line 1332, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.6/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.6/site-packages/salt/modules/state.py", line 455, in apply_
return sls(mods, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/modules/state.py", line 942, in sls
ret = st_.state.call_high(high_)
File "/usr/lib/python2.6/site-packages/salt/state.py", line 2279, in call_high
ret = dict(list(disabled.items()) + list(self.call_chunks(chunks).items()))
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1800, in call_chunks
if self.check_failhard(low, running):
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1812, in check_failhard
return not running[tag]['result']
KeyError: 'test_|-a_|-a_|-show_notification'

# Fixed code
def check_failhard(self, low, running):
    """
    Check if the low data chunk should send a failhard signal
    """
    tag = _gen_tag(low)
    if self.opts.get("test", False):
        return False
    if (low.get("failhard", False) or self.opts["failhard"]) and tag in running:
        if running[tag]["result"] is None:
            return False
        return not running[tag]["result"]
    return False
# Buggy code
def _get_size_spec(device, size_gb):
    size_kb = int(size_gb * 1024.0 * 1024.0)
    disk_spec = (
        _edit_existing_hard_disk_helper(disk=device, size_kb=size_kb)
        if device.capacityInKB < size_kb
        else None
    )
    return disk_spec


# Traceback (TypeError)
salt-cloud -l debug -m /etc/salt/cloud.maps.d/vc01.map
<snipped>
[DEBUG   ] Virtual hardware version already set to vmx-08
[DEBUG   ] Setting cpu to: 2
[DEBUG   ] Setting memory to: 2048 MB
[DEBUG   ] Changing type of 'Network adapter 1' from 'e1000' to 'vmxnet3'
[ERROR   ] There was a query error: Required field "deviceChange" not provided (not @optional)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 348, in run
ret = mapper.run_map(dmap)
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 2231, in run_map
profile, local_master=local_master
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1288, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/site-packages/salt/cloud/clouds/vmware.py", line 2496, in create
config_spec.deviceChange = specs['device_specs']
File "/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py", line 537, in __setattr__
CheckField(self._GetPropertyInfo(name), val)
File "/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py", line 954, in CheckField
CheckField(itemInfo, it)
File "/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py", line 915, in CheckField
raise TypeError('Required field "%s" not provided (not @optional)' % info.name)
TypeError: Required field "deviceChange" not provided (not @optional)
[root@salt01t cloud.profiles.d]#

# Fixed code
def _get_size_spec(device, size_gb=None, size_kb=None):
    if size_kb is None and size_gb is not None:
        size_kb = int(size_gb * 1024.0 * 1024.0)
    disk_spec = (
        _edit_existing_hard_disk_helper(disk=device, size_kb=size_kb)
        if device.capacityInKB < size_kb
        else None
    )
    return disk_spec
# Buggy code
def __virtual__():
    """
    Only load if libcloud libraries exist.
    """
    if not HAS_LIBCLOUD:
        msg = (
            "A apache-libcloud library with version at least {0} was not found"
        ).format(REQUIRED_LIBCLOUD_VERSION)
        return (False, msg)
    return True


# Traceback (NameError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/salt/state.py", line 1746, in call
**cdata['kwargs'])
File "/usr/local/lib/python2.7/dist-packages/salt/loader.py", line 1704, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/salt/states/libcloud_dns.py", line 169, in record_present
zones = libcloud_dns_module.list_zones(profile)
File "/usr/local/lib/python2.7/dist-packages/salt/modules/libcloud_dns.py", line 109, in list_zones
conn = _get_driver(profile=profile)
File "/usr/local/lib/python2.7/dist-packages/salt/modules/libcloud_dns.py", line 69, in _get_driver
config = __salt__['config.option']('libcloud_dns')[profile]
NameError: global name '__salt__' is not defined

# Fixed code
def __virtual__():
    return True
# Buggy code
def zone_present(domain, type, profile):
    """
    Ensures a record is present.

    :param domain: Zone name, i.e. the domain name
    :type  domain: ``str``

    :param type: Zone type (master / slave), defaults to master
    :type  type: ``str``

    :param profile: The profile key
    :type  profile: ``str``
    """
    zones = libcloud_dns_module.list_zones(profile)
    if not type:
        type = "master"
    matching_zone = [z for z in zones if z.domain == domain]
    if len(matching_zone) > 0:
        return state_result(True, "Zone already exists")
    else:
        result = libcloud_dns_module.create_zone(domain, profile, type)
        return state_result(result, "Created new zone")


# Traceback (NameError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/salt/state.py", line 1746, in call
**cdata['kwargs'])
File "/usr/local/lib/python2.7/dist-packages/salt/loader.py", line 1704, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/salt/states/libcloud_dns.py", line 169, in record_present
zones = libcloud_dns_module.list_zones(profile)
File "/usr/local/lib/python2.7/dist-packages/salt/modules/libcloud_dns.py", line 109, in list_zones
conn = _get_driver(profile=profile)
File "/usr/local/lib/python2.7/dist-packages/salt/modules/libcloud_dns.py", line 69, in _get_driver
config = __salt__['config.option']('libcloud_dns')[profile]
NameError: global name '__salt__' is not defined

# Fixed code
def zone_present(domain, type, profile):
    """
    Ensures a record is present.

    :param domain: Zone name, i.e. the domain name
    :type  domain: ``str``

    :param type: Zone type (master / slave), defaults to master
    :type  type: ``str``

    :param profile: The profile key
    :type  profile: ``str``
    """
    zones = __salt__["libcloud_dns.list_zones"](profile)
    if not type:
        type = "master"
    matching_zone = [z for z in zones if z.domain == domain]
    if len(matching_zone) > 0:
        return state_result(True, "Zone already exists")
    else:
        result = __salt__["libcloud_dns.create_zone"](domain, profile, type)
        return state_result(result, "Created new zone")
# Buggy code
def zone_absent(domain, profile):
    """
    Ensures a record is absent.

    :param domain: Zone name, i.e. the domain name
    :type  domain: ``str``

    :param profile: The profile key
    :type  profile: ``str``
    """
    zones = libcloud_dns_module.list_zones(profile)
    matching_zone = [z for z in zones if z.domain == domain]
    if len(matching_zone) == 0:
        return state_result(True, "Zone already absent")
    else:
        result = libcloud_dns_module.delete_zone(matching_zone[0].id, profile)
        return state_result(result, "Deleted zone")


# Traceback (NameError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/salt/state.py", line 1746, in call
**cdata['kwargs'])
File "/usr/local/lib/python2.7/dist-packages/salt/loader.py", line 1704, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/salt/states/libcloud_dns.py", line 169, in record_present
zones = libcloud_dns_module.list_zones(profile)
File "/usr/local/lib/python2.7/dist-packages/salt/modules/libcloud_dns.py", line 109, in list_zones
conn = _get_driver(profile=profile)
File "/usr/local/lib/python2.7/dist-packages/salt/modules/libcloud_dns.py", line 69, in _get_driver
config = __salt__['config.option']('libcloud_dns')[profile]
NameError: global name '__salt__' is not defined

# Fixed code
def zone_absent(domain, profile):
    """
    Ensures a record is absent.

    :param domain: Zone name, i.e. the domain name
    :type  domain: ``str``

    :param profile: The profile key
    :type  profile: ``str``
    """
    zones = __salt__["libcloud_dns.list_zones"](profile)
    matching_zone = [z for z in zones if z.domain == domain]
    if len(matching_zone) == 0:
        return state_result(True, "Zone already absent")
    else:
        result = __salt__["libcloud_dns.delete_zone"](matching_zone[0].id, profile)
        return state_result(result, "Deleted zone")
# Buggy code
def __init__(self, opts, functions, returners=None, intervals=None, cleanup=None):
    pass


# Traceback (KeyError)
[INFO    ] Running scheduled job: napalm_keepalive
[DEBUG   ] schedule: This job was scheduled with jid_include, adding to cache (jid_include defaults to True)
[DEBUG   ] schedule: This job was scheduled with a max number of 2
[DEBUG   ] schedule.handle_func: adding this job to the jobcache with data {'fun_args': [], 'jid': '20170302001945879004', 'schedule': 'napalm_keepalive', 'pid': 18056, 'fun': 'napalm_proxy.reconnect', 'id': 'device1'}
[DEBUG   ] LazyLoaded napalm_proxy.reconnect
[ERROR   ] Unhandled exception running napalm_proxy.reconnect
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/schedule.py", line 836, in handle_func
ret['return'] = self.functions[func](*args, **kwargs)
File "/var/cache/salt/minion/extmods/modules/napalm_proxy.py", line 101, in reconnect
is_alive = alive()
File "/var/cache/salt/minion/extmods/modules/napalm_proxy.py", line 80, in alive
return __proxy__['napalm.call'](
File "/usr/lib/python2.7/dist-packages/salt/utils/context.py", line 203, in __getitem__
return self._dict()[key]
KeyError: 'napalm.call'
[DEBUG   ] SaltEvent PUB socket URI: /var/run/salt/minion/minion_event_18faa0dd7a_pub.ipc
[DEBUG   ] SaltEvent PULL socket URI: /var/run/salt/minion/minion_event_18faa0dd7a_pull.ipc
[DEBUG   ] Initializing new IPCClient for path: /var/run/salt/minion/minion_event_18faa0dd7a_pull.ipc
[DEBUG   ] Sending event: tag = __schedule_return; data = {'fun_args': [], 'jid': 'req', 'return': 'Unhandled exception running napalm_proxy.reconnect', 'retcode': 254, 'success': False, 'schedule': 'napalm_keepalive', 'cmd': '_return', 'pid': 18056, '_stamp': '2017-03-02T00:19:45.881385', 'fun': 'napalm_proxy.reconnect', 'id': 'device1'}
[DEBUG   ] schedule.handle_func: Removing /var/cache/salt/proxy/device1/proc/20170302001945879004

# Fixed code
def __init__(
    self, opts, functions, returners=None, intervals=None, cleanup=None, proxy=None
):
    pass
# Buggy code
def proxy(opts, functions=None, returners=None, whitelist=None):
    """
    Returns the proxy module for this salt-proxy-minion
    """
    ret = LazyLoader(
        _module_dirs(opts, "proxy", "proxy"),
        opts,
        tag="proxy",
        pack={"__salt__": functions, "__ret__": returners},
    )

    ret.pack["__proxy__"] = ret

    return ret


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None):
    """
    Returns the proxy module for this salt-proxy-minion
    """
    ret = LazyLoader(
        _module_dirs(opts, "proxy", "proxy"),
        opts,
        tag="proxy",
        pack={"__salt__": functions, "__ret__": returners, "__utils__": utils},
    )

    ret.pack["__proxy__"] = ret

    return ret
# Buggy code
def returners(opts, functions, whitelist=None, context=None):
    """
    Returns the returner modules
    """
    return LazyLoader(
        _module_dirs(opts, "returners", "returner"),
        opts,
        tag="returner",
        whitelist=whitelist,
        pack={"__salt__": functions, "__context__": context},
    )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def returners(opts, functions, whitelist=None, context=None, proxy=None):
    """
    Returns the returner modules
    """
    return LazyLoader(
        _module_dirs(opts, "returners", "returner"),
        opts,
        tag="returner",
        whitelist=whitelist,
        pack={"__salt__": functions, "__context__": context, "__proxy__": proxy or {}},
    )
# Buggy code
def utils(opts, whitelist=None, context=None):
    """
    Returns the utility modules
    """
    return LazyLoader(
        _module_dirs(opts, "utils", "utils", ext_type_dirs="utils_dirs"),
        opts,
        tag="utils",
        whitelist=whitelist,
        pack={"__context__": context},
    )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def utils(opts, whitelist=None, context=None, proxy=proxy):
    """
    Returns the utility modules
    """
    return LazyLoader(
        _module_dirs(opts, "utils", "utils", ext_type_dirs="utils_dirs"),
        opts,
        tag="utils",
        whitelist=whitelist,
        pack={"__context__": context, "__proxy__": proxy or {}},
    )