gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, opts):
    # Late setup of the opts grains, so we can log from the grains module
    opts["grains"] = salt.loader.grains(opts)
    super(SMinion, self).__init__(opts)

    # Clean out the proc directory (default /var/cache/salt/minion/proc)
    if self.opts.get("file_client", "remote") == "remote" or self.opts.get(
        "use_master_when_local", False
    ):
        self.eval_master(self.opts, failed=True)
    self.gen_modules(initial_load=True)


# Traceback (KeyError)
C:\salt>salt-call -l debug test.ping
[DEBUG   ] Reading configuration from c:\salt\conf\minion
[DEBUG   ] Configuration file path: c:\salt\conf\minion
[INFO    ] Got list of available master addresses: ['salt-mastera', 'salt-masterb', 'salt-masterc', 'salt-masterd', 'salt-mastere']
[DEBUG   ] Initializing new SAuth for ('c:\\salt\\conf\\pki\\minion', 'salt-minion-007', 'tcp://12.46.94.123:1235')
[DEBUG   ] Generated random reconnect delay between '500ms' and '10500ms' (4813)
[DEBUG   ] Setting zmq_reconnect_ivl to '4813ms'
[DEBUG   ] Setting zmq_reconnect_ivl_max to '10500ms'
[DEBUG   ] Initializing new AsyncZeroMQReqChannel for ('c:\\salt\\conf\\pki\\minion', 'salt-minion-007', 'tcp://12.46.94.123:1235', 'aes')
[DEBUG   ] Initializing new SAuth for ('c:\\salt\\conf\\pki\\minion', 'salt-minion-007', 'tcp://12.46.94.123:1235')
[DEBUG   ] Initializing new AsyncZeroMQReqChannel for ('c:\\salt\\conf\\pki\\minion', 'salt-minion-007', 'tcp://12.46.94.123:1235', 'clear')
Attempt to authenticate with the salt master failed
[DEBUG   ] Error deleting fd from IOLoop
Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\tornado\ioloop.py", line 715, in remove_handler
self._impl.unregister(fd)
File "C:\salt\bin\lib\site-packages\zmq\eventloop\ioloop.py", line 115, in unregister
return self._poller.unregister(fd)
File "C:\salt\bin\lib\site-packages\zmq\sugar\poll.py", line 71, in unregister

idx = self._map.pop(socket)
KeyError: None
[DEBUG   ] Error deleting fd from IOLoop
Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\tornado\ioloop.py", line 715, in remove_handler
self._impl.unregister(fd)
File "C:\salt\bin\lib\site-packages\zmq\eventloop\ioloop.py", line 115, in unregister
return self._poller.unregister(fd)
File "C:\salt\bin\lib\site-packages\zmq\sugar\poll.py", line 71, in unregister

idx = self._map.pop(socket)
KeyError: None

# Fixed code
def __init__(self, opts):
    # Late setup of the opts grains, so we can log from the grains module
    opts["grains"] = salt.loader.grains(opts)
    super(SMinion, self).__init__(opts)

    # Clean out the proc directory (default /var/cache/salt/minion/proc)
    if self.opts.get("file_client", "remote") == "remote" or self.opts.get(
        "use_master_when_local", False
    ):
        # actually eval_master returns the future and we need to wait for it
        self.io_loop = zmq.eventloop.ioloop.ZMQIOLoop()
        self.io_loop.run_sync(lambda: self.eval_master(self.opts, failed=True))
    self.gen_modules(initial_load=True)
# Buggy code
def call_parallel(self, cdata, low):
    """
    Call the state defined in the given cdata in parallel
    """
    proc = salt.utils.process.MultiprocessingProcess(
        target=self._call_parallel_target, args=(cdata, low)
    )
    proc.start()
    ret = {
        "name": cdata["args"][0],
        "result": None,
        "changes": {},
        "comment": "Started in a separate process",
        "proc": proc,
    }
    return ret


# Traceback (IndexError)
Function: cloudflare.manage_zone_records
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/salt/state.py", line 1817, in call
ret = self.call_parallel(cdata, low)
File "/usr/lib/python3.6/site-packages/salt/state.py", line 1699, in call_parallel
ret = {'name': cdata['args'][0],
IndexError: list index out of range
Started: 19:38:35.127274
Duration: 3.431 ms

# Fixed code
def call_parallel(self, cdata, low):
    """
    Call the state defined in the given cdata in parallel
    """
    # There are a number of possibilities to not have the cdata
    # populated with what we might have expected, so just be smart
    # enough to not raise another KeyError as the name is easily
    # guessable and fallback in all cases to present the real
    # exception to the user
    if len(cdata["args"]) > 0:
        name = cdata["args"][0]
    elif "name" in cdata["kwargs"]:
        name = cdata["kwargs"]["name"]
    else:
        name = low.get("name", low.get("__id__"))

    proc = salt.utils.process.MultiprocessingProcess(
        target=self._call_parallel_target, args=(name, cdata, low)
    )
    proc.start()
    ret = {
        "name": name,
        "result": None,
        "changes": {},
        "comment": "Started in a separate process",
        "proc": proc,
    }
    return ret
# Buggy code
def set_policy(
    vhost, name, pattern, definition, priority=None, apply_to=None, runas=None
):
    """
    Set a policy based on rabbitmqctl set_policy.

    Reference: http://www.rabbitmq.com/ha.html

    CLI Example:

    .. code-block:: bash

        salt '*' rabbitmq.set_policy / HA '.*' '{"ha-mode":"all"}'
    """
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    if isinstance(definition, dict):
        definition = salt.utils.json.dumps(definition)
    if not isinstance(definition, six.string_types):
        raise SaltInvocationError(
            "The 'definition' argument must be a dictionary or JSON string"
        )
    cmd = [RABBITMQCTL, "set_policy", "-p", vhost]
    if priority:
        cmd.extend(["--priority", priority])
    if apply_to:
        cmd.extend(["--apply-to", apply_to])
    cmd.extend([name, pattern, definition])
    res = __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False)
    log.debug("Set policy: %s", res["stdout"])
    return _format_response(res, "Set")


# Traceback (TypeError)
----------
ID: rabbit_ha_policy
Function: rabbitmq_policy.present
Name: ha-all-queues
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/rabbitmq_policy.py", line 108, in present
runas=runas)
TypeError: set_policy() got multiple values for keyword argument 'priority'
Started: 21:37:25.570994
Duration: 575.121 ms
Changes:

# Fixed code
def set_policy(
    vhost, name, pattern, definition, priority=None, runas=None, apply_to=None
):
    """
    Set a policy based on rabbitmqctl set_policy.

    Reference: http://www.rabbitmq.com/ha.html

    CLI Example:

    .. code-block:: bash

        salt '*' rabbitmq.set_policy / HA '.*' '{"ha-mode":"all"}'
    """
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    if isinstance(definition, dict):
        definition = salt.utils.json.dumps(definition)
    if not isinstance(definition, six.string_types):
        raise SaltInvocationError(
            "The 'definition' argument must be a dictionary or JSON string"
        )
    cmd = [RABBITMQCTL, "set_policy", "-p", vhost]
    if priority:
        cmd.extend(["--priority", priority])
    if apply_to:
        cmd.extend(["--apply-to", apply_to])
    cmd.extend([name, pattern, definition])
    res = __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False)
    log.debug("Set policy: %s", res["stdout"])
    return _format_response(res, "Set")
# Buggy code
def shutdown_multiprocessing_logging():
    global __MP_LOGGING_CONFIGURED
    global __MP_LOGGING_QUEUE_HANDLER

    if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER:
        return

    try:
        logging._acquireLock()
        # Let's remove the queue handler from the logging root handlers
        logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER)
        __MP_LOGGING_QUEUE_HANDLER = None
        __MP_LOGGING_CONFIGURED = False
    finally:
        logging._releaseLock()


# Traceback (IOError)
Traceback (most recent call last):
File "c:\dev\salt\salt\log\handlers\__init__.py", line 211, in emit
self.enqueue(self.prepare(record))
File "c:\dev\salt\salt\log\handlers\__init__.py", line 177, in enqueue
File "c:\python27\lib\multiprocessing\queues.py", line 264, in _feed
self.queue.put_nowait(record)
File "c:\python27\lib\multiprocessing\queues.py", line 155, in put_nowait
return self.put(obj, False)
File "c:\python27\lib\multiprocessing\queues.py", line 100, in put
assert not self._closed
AssertionError
Logged from file setup.py, line 973
send(obj)
IOError: [Errno 232] The pipe is being closed

# Fixed code
def shutdown_multiprocessing_logging():
    global __MP_LOGGING_CONFIGURED
    global __MP_LOGGING_QUEUE_HANDLER

    if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER:
        return

    try:
        logging._acquireLock()
        # Let's remove the queue handler from the logging root handlers
        logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER)
        __MP_LOGGING_QUEUE_HANDLER = None
        __MP_LOGGING_CONFIGURED = False
        if not logging.root.handlers:
            # Ensure we have at least one logging root handler so
            # something can handle logging messages. This case should
            # only occur on Windows since on Windows we log to console
            # and file through the Multiprocessing Logging Listener.
            setup_console_logger()
    finally:
        logging._releaseLock()
# Buggy code
def exit(self, status=0, msg=None):
    # Run the functions on self._mixin_after_parsed_funcs
    for mixin_before_exit_func in self._mixin_before_exit_funcs:  # pylint: disable=no-member
        try:
            mixin_before_exit_func(self)
        except Exception as err:  # pylint: disable=broad-except
            logger = logging.getLogger(__name__)
            logger.exception(err)
            logger.error(
                "Error while processing {0}: {1}".format(
                    mixin_before_exit_func, traceback.format_exc(err)
                )
            )
    if self._setup_mp_logging_listener_ is True:
        # Stop the logging queue listener process
        log.shutdown_multiprocessing_logging_listener(daemonizing=True)
    if isinstance(msg, six.string_types) and msg and msg[-1] != "\n":
        msg = "{0}\n".format(msg)
    optparse.OptionParser.exit(self, status, msg)


# Traceback (IOError)
Traceback (most recent call last):
File "c:\dev\salt\salt\log\handlers\__init__.py", line 211, in emit
self.enqueue(self.prepare(record))
File "c:\dev\salt\salt\log\handlers\__init__.py", line 177, in enqueue
File "c:\python27\lib\multiprocessing\queues.py", line 264, in _feed
self.queue.put_nowait(record)
File "c:\python27\lib\multiprocessing\queues.py", line 155, in put_nowait
return self.put(obj, False)
File "c:\python27\lib\multiprocessing\queues.py", line 100, in put
assert not self._closed
AssertionError
Logged from file setup.py, line 973
send(obj)
IOError: [Errno 232] The pipe is being closed

# Fixed code
def exit(self, status=0, msg=None):
    # Run the functions on self._mixin_after_parsed_funcs
    for mixin_before_exit_func in self._mixin_before_exit_funcs:  # pylint: disable=no-member
        try:
            mixin_before_exit_func(self)
        except Exception as err:  # pylint: disable=broad-except
            logger = logging.getLogger(__name__)
            logger.exception(err)
            logger.error(
                "Error while processing {0}: {1}".format(
                    mixin_before_exit_func, traceback.format_exc(err)
                )
            )
    if self._setup_mp_logging_listener_ is True:
        # Stop logging through the queue
        log.shutdown_multiprocessing_logging()
        # Stop the logging queue listener process
        log.shutdown_multiprocessing_logging_listener(daemonizing=True)
    if isinstance(msg, six.string_types) and msg and msg[-1] != "\n":
        msg = "{0}\n".format(msg)
    optparse.OptionParser.exit(self, status, msg)
# Buggy code
def _text_or_file(input_):
    """
    Determines if input is a path to a file, or a string with the
    content to be parsed.
    """
    if os.path.isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            return salt.utils.stringutils.to_unicode(fp_.read())
    else:
        return input_


# Traceback (CommandExecutionError)
----------
ID: certificate.authority::private-key
Function: x509.private_key_managed
Name: /salt/pki/ca.key
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/state.py", line 1876, in call
**cdata['kwargs'])
File "/opt/local/lib/python2.7/site-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/states/x509.py", line 303, in private_key_managed
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
File "/opt/local/lib/python2.7/site-packages/salt/states/x509.py", line 240, in _check_private_key
'The provided passphrase cannot decrypt the private key.')
CommandExecutionError: The provided passphrase cannot decrypt the private key.
Started: 19:28:45.695662
Duration: 7.64 ms
Changes:
----------

# Fixed code
def _text_or_file(input_):
    """
    Determines if input is a path to a file, or a string with the
    content to be parsed.
    """
    if os.path.isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            return salt.utils.stringutils.to_bytes(fp_.read())
    else:
        return input_
# Buggy code
def _text_or_file(input_):
    """
    Determines if input is a path to a file, or a string with the
    content to be parsed.
    """
    if os.path.isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            return salt.utils.stringutils.to_bytes(fp_.read())
    else:
        return input_


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/root/salt/salt/state.py", line 1878, in call
**cdata['kwargs'])
File "/root/salt/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/root/salt/salt/states/x509.py", line 311, in private_key_managed
ret = __states__['file.managed'](**file_args)
File "/root/salt/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/root/salt/salt/states/file.py", line 2267, in managed
isinstance(use_contents, six.string_types) and '\0' in use_contents
TypeError: 'str' does not support the buffer interface

# Fixed code
def _text_or_file(input_):
    """
    Determines if input is a path to a file, or a string with the
    content to be parsed.
    """
    if os.path.isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            return salt.utils.stringutils.to_str(fp_.read())
    else:
        return salt.utils.stringutils.to_str(input_)
# Buggy code
def cmd_async(
    self, tgt, fun, arg=(), tgt_type="glob", ret="", jid="", kwarg=None, **kwargs
):
    """
    Asynchronously send a command to connected minions

    The function signature is the same as :py:meth:`cmd` with the
    following exceptions.

    :returns: A job ID or 0 on failure.

    .. code-block:: python

        >>> local.cmd_async('*', 'test.sleep', [300])
        '20131219215921857715'
    """
    arg = salt.utils.args.condition_input(arg, kwarg)
    pub_data = self.run_job(tgt, fun, arg, tgt_type, ret, jid=jid, **kwargs)
    try:
        return pub_data["jid"]
    except KeyError:
        return 0


# Traceback (SaltClientError)
2017-03-20 15:58:15,317 [salt.utils.event                         ][DEBUG   ][28048] MasterEvent PUB socket URI: ipc:///var/run/salt/master/master_event_pub.ipc2017-03-20 15:58:15,318 [salt.utils.event                         ][DEBUG   ][28048] MasterEvent PULL socket URI: ipc:///var/run/salt/master/master_event_pull.ipc
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/netapi/rest_cherrypy/app.py", line 507, in hypermedia_handler
File "/usr/lib/python2.6/site-packages/cherrypy/_cpdispatch.py", line 34, in __call__
File "/usr/lib/python2.6/site-packages/salt/netapi/rest_cherrypy/app.py", line 933, in POST
File "/usr/lib/python2.6/site-packages/salt/netapi/rest_cherrypy/app.py", line 775, in exec_lowstate
File "/usr/lib/python2.6/site-packages/salt/netapi/__init__.py", line 70, in run
File "/usr/lib/python2.6/site-packages/salt/netapi/__init__.py", line 98, in local
File "/usr/lib/python2.6/site-packages/salt/client/__init__.py", line 535, in cmd
File "/usr/lib/python2.6/site-packages/salt/client/__init__.py", line 290, in run_job
SaltClientError: [Errno 24] Too many open files
2017-03-20 15:58:15,751 [salt.utils.process                       ][INFO    ][28040] Process <function start at 0x1ce6b18> (28048) died with exit status None, restarting...
2017-03-20 15:58:16,757 [salt.utils.process                       ][DEBUG   ][28040] Started 'salt.loaded.int.netapi.rest_cherrypy.start' with pid 20716

# Fixed code
def cmd_async(
    self, tgt, fun, arg=(), tgt_type="glob", ret="", jid="", kwarg=None, **kwargs
):
    """
    Asynchronously send a command to connected minions

    The function signature is the same as :py:meth:`cmd` with the
    following exceptions.

    :returns: A job ID or 0 on failure.

    .. code-block:: python

        >>> local.cmd_async('*', 'test.sleep', [300])
        '20131219215921857715'
    """
    arg = salt.utils.args.condition_input(arg, kwarg)
    pub_data = self.run_job(
        tgt, fun, arg, tgt_type, ret, jid=jid, listen=False, **kwargs
    )
    try:
        return pub_data["jid"]
    except KeyError:
        return 0
# Buggy code
def __virtual__():
    """
    Only load the module if SenseHat is available
    """
    if has_sense_hat:
        rotation = __salt__["pillar.get"]("sensehat:rotation", 0)
        if rotation in [0, 90, 180, 270]:
            _sensehat.set_rotation(rotation, False)
        else:
            log.error(
                "{0} is not a valid rotation. Using default rotation.".format(rotation)
            )
        return True
    else:
        return (
            False,
            "The SenseHat excecution module can not be loaded: SenseHat unavailable.\nThis module can only be used on a Raspberry Pi with a SenseHat. Also make sure that the sense_hat python library is installed!",
        )


# Traceback (OSError)
[ERROR   ] Failed to import module sensehat, this is due most likely to a syntax error:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1411, in _load_module
mod = imp.load_module(mod_namespace, fn_, fpath, desc)
File "/usr/lib/python2.7/dist-packages/salt/modules/sensehat.py", line 26, in <module>
_sensehat = SenseHat()
File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 36, in __init__
raise OSError('Cannot detect %s device' % self.SENSE_HAT_FB_NAME)
OSError: Cannot detect RPi-Sense FB device

# Fixed code
def __virtual__():
    """
    Only load the module if SenseHat is available
    """
    if has_sense_hat:
        try:
            _sensehat = SenseHat()
        except OSError:
            return (
                False,
                "This module can only be used on a Raspberry Pi with a SenseHat.",
            )

        rotation = __salt__["pillar.get"]("sensehat:rotation", 0)
        if rotation in [0, 90, 180, 270]:
            _sensehat.set_rotation(rotation, False)
        else:
            log.error(
                "{0} is not a valid rotation. Using default rotation.".format(rotation)
            )
        return True

    return (
        False,
        "The SenseHat execution module cannot be loaded: 'sense_hat' python library unavailable.",
    )
# Buggy code
def _groupname():
    """
    Grain for the minion groupname
    """
    if grp:
        groupname = grp.getgrgid(os.getgid()).gr_name
    else:
        groupname = ""

    return groupname


# Traceback (KeyError)
[CRITICAL] Failed to load grains defined in grain file minion_process.grains in function <function grains at 0x107650ed8>, error:
Traceback (most recent call last):
File "/Users/steinhof/src/salt/salt/loader.py", line 756, in grains
ret = funcs[key]()
File "/Users/steinhof/src/salt/salt/grains/minion_process.py", line 74, in grains
'groupname': _groupname(),
File "/Users/steinhof/src/salt/salt/grains/minion_process.py", line 60, in _groupname
groupname = grp.getgrgid(os.getgid()).gr_name
KeyError: 'getgrgid(): gid not found: 123'

# Fixed code
def _groupname():
    """
    Grain for the minion groupname
    """
    if grp:
        try:
            groupname = grp.getgrgid(os.getgid()).gr_name
        except KeyError:
            groupname = ""
    else:
        groupname = ""

    return groupname
# Buggy code
def __new__(
    cls, opts, functions, returners=None, intervals=None, cleanup=None, proxy=None
):
    """
    Only create one instance of Schedule
    """
    if cls.instance is None:
        log.debug("Initializing new Schedule")
        # we need to make a local variable for this, as we are going to store
        # it in a WeakValueDictionary-- which will remove the item if no one
        # references it-- this forces a reference while we return to the caller
        cls.instance = object.__new__(cls)
        cls.instance.__singleton_init__(
            opts, functions, returners, intervals, cleanup, proxy
        )
    else:
        log.debug("Re-using Schedule")
    return cls.instance


# Traceback (KeyError)
2018-03-13 14:41:48,257 [salt.utils.schedule:923 ][ERROR   ][10105] Unhandled exception running git.pull
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/schedule.py", line 890, in handle_func
ret['return'] = self.functions[func](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/git.py", line 3143, in pull
saltenv=saltenv)['stdout']
File "/usr/lib/python2.7/dist-packages/salt/modules/git.py", line 283, in _git_run
and __utils__['ssh.key_is_encrypted'](id_file):
File "/usr/lib/python2.7/dist-packages/salt/utils/context.py", line 227, in __getitem__
return self._dict()[key]
KeyError: 'ssh.key_is_encrypted'

# Fixed code
def __new__(
    cls,
    opts,
    functions,
    returners=None,
    intervals=None,
    cleanup=None,
    proxy=None,
    utils=None,
):
    """
    Only create one instance of Schedule
    """
    if cls.instance is None:
        log.debug("Initializing new Schedule")
        # we need to make a local variable for this, as we are going to store
        # it in a WeakValueDictionary-- which will remove the item if no one
        # references it-- this forces a reference while we return to the caller
        cls.instance = object.__new__(cls)
        cls.instance.__singleton_init__(
            opts, functions, returners, intervals, cleanup, proxy, utils
        )
    else:
        log.debug("Re-using Schedule")
    return cls.instance
# Buggy code
def __init__(
    self, opts, functions, returners=None, intervals=None, cleanup=None, proxy=None
):
    pass


# Traceback (KeyError)
2018-03-13 14:41:48,257 [salt.utils.schedule:923 ][ERROR   ][10105] Unhandled exception running git.pull
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/schedule.py", line 890, in handle_func
ret['return'] = self.functions[func](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/git.py", line 3143, in pull
saltenv=saltenv)['stdout']
File "/usr/lib/python2.7/dist-packages/salt/modules/git.py", line 283, in _git_run
and __utils__['ssh.key_is_encrypted'](id_file):
File "/usr/lib/python2.7/dist-packages/salt/utils/context.py", line 227, in __getitem__
return self._dict()[key]
KeyError: 'ssh.key_is_encrypted'

# Fixed code
def __init__(
    self,
    opts,
    functions,
    returners=None,
    intervals=None,
    cleanup=None,
    proxy=None,
    utils=None,
):
    pass
# Buggy code
def __singleton_init__(
    self, opts, functions, returners=None, intervals=None, cleanup=None, proxy=None
):
    self.opts = opts
    self.proxy = proxy
    self.functions = functions
    if isinstance(intervals, dict):
        self.intervals = intervals
    else:
        self.intervals = {}
    if hasattr(returners, "__getitem__"):
        self.returners = returners
    else:
        self.returners = returners.loader.gen_functions()
    self.time_offset = self.functions.get("timezone.get_offset", lambda: "0000")()
    self.schedule_returner = self.option("schedule_returner")
    # Keep track of the lowest loop interval needed in this variable
    self.loop_interval = six.MAXSIZE
    clean_proc_dir(opts)
    if cleanup:
        for prefix in cleanup:
            self.delete_job_prefix(prefix)


# Traceback (KeyError)
2018-03-13 14:41:48,257 [salt.utils.schedule:923 ][ERROR   ][10105] Unhandled exception running git.pull
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/schedule.py", line 890, in handle_func
ret['return'] = self.functions[func](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/git.py", line 3143, in pull
saltenv=saltenv)['stdout']
File "/usr/lib/python2.7/dist-packages/salt/modules/git.py", line 283, in _git_run
and __utils__['ssh.key_is_encrypted'](id_file):
File "/usr/lib/python2.7/dist-packages/salt/utils/context.py", line 227, in __getitem__
return self._dict()[key]
KeyError: 'ssh.key_is_encrypted'

# Fixed code
def __singleton_init__(
    self,
    opts,
    functions,
    returners=None,
    intervals=None,
    cleanup=None,
    proxy=None,
    utils=None,
):
    self.opts = opts
    self.proxy = proxy
    self.functions = functions
    self.utils = utils
    if isinstance(intervals, dict):
        self.intervals = intervals
    else:
        self.intervals = {}
    if hasattr(returners, "__getitem__"):
        self.returners = returners
    else:
        self.returners = returners.loader.gen_functions()
    self.time_offset = self.functions.get("timezone.get_offset", lambda: "0000")()
    self.schedule_returner = self.option("schedule_returner")
    # Keep track of the lowest loop interval needed in this variable
    self.loop_interval = six.MAXSIZE
    clean_proc_dir(opts)
    if cleanup:
        for prefix in cleanup:
            self.delete_job_prefix(prefix)
# Buggy code
def _get_config(**kwargs):
    """
    Return configuration
    """
    config = {
        "box_type": "sealedbox",
        "sk": None,
        "sk_file": "/etc/salt/pki/master/nacl",
        "pk": None,
        "pk_file": "/etc/salt/pki/master/nacl.pub",
    }
    config_key = "{0}.config".format(__virtualname__)
    try:
        config.update(__salt__["config.get"](config_key, {}))
    except (NameError, KeyError) as e:
        # likly using salt-run so fallback to __opts__
        config.update(__opts__.get(config_key, {}))
    # pylint: disable=C0201
    for k in set(config.keys()) & set(kwargs.keys()):
        config[k] = kwargs[k]
    return config


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def _get_config(**kwargs):
    """
    Return configuration
    """
    config = {
        "box_type": "sealedbox",
        "sk": None,
        "sk_file": os.path.join(__opts__["pki_dir"], "master/nacl"),
        "pk": None,
        "pk_file": os.path.join(__opts__["pki_dir"], "master/nacl.pub"),
    }
    config_key = "{0}.config".format(__virtualname__)
    try:
        config.update(__salt__["config.get"](config_key, {}))
    except (NameError, KeyError) as e:
        # likly using salt-run so fallback to __opts__
        config.update(__opts__.get(config_key, {}))
    # pylint: disable=C0201
    for k in set(config.keys()) & set(kwargs.keys()):
        config[k] = kwargs[k]
    return config
# Buggy code
def enc(data, **kwargs):
    """
    Alias to `{box_type}_encrypt`

    box_type: secretbox, sealedbox(default)
    """
    box_type = _get_config(**kwargs)["box_type"]
    if box_type == "sealedbox":
        return sealedbox_encrypt(data, **kwargs)
    if box_type == "secretbox":
        return secretbox_encrypt(data, **kwargs)
    return sealedbox_encrypt(data, **kwargs)


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def enc(data, **kwargs):
    """
    Alias to `{box_type}_encrypt`

    box_type: secretbox, sealedbox(default)
    """
    if "keyfile" in kwargs:
        salt.utils.versions.warn_until(
            "Fluorine",
            "The 'keyfile' argument has been deprecated and will be removed in Salt "
            "{version}. Please use 'sk_file' argument instead.",
        )
        kwargs["sk_file"] = kwargs["keyfile"]

    if "key" in kwargs:
        salt.utils.versions.warn_until(
            "Fluorine",
            "The 'key' argument has been deprecated and will be removed in Salt "
            "{version}. Please use 'sk' argument instead.",
        )
        kwargs["sk"] = kwargs["key"]

    # ensure data is in bytes
    data = salt.utils.stringutils.to_bytes(data)

    box_type = _get_config(**kwargs)["box_type"]
    if box_type == "sealedbox":
        return sealedbox_encrypt(data, **kwargs)
    if box_type == "secretbox":
        return secretbox_encrypt(data, **kwargs)
    return sealedbox_encrypt(data, **kwargs)
# Buggy code
def dec(data, **kwargs):
    """
    Alias to `{box_type}_decrypt`

    box_type: secretbox, sealedbox(default)
    """
    box_type = _get_config(**kwargs)["box_type"]
    if box_type == "sealedbox":
        return sealedbox_decrypt(data, **kwargs)
    if box_type == "secretbox":
        return secretbox_decrypt(data, **kwargs)
    return sealedbox_decrypt(data, **kwargs)


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def dec(data, **kwargs):
    """
    Alias to `{box_type}_decrypt`

    box_type: secretbox, sealedbox(default)
    """
    if "keyfile" in kwargs:
        salt.utils.versions.warn_until(
            "Fluorine",
            "The 'keyfile' argument has been deprecated and will be removed in Salt "
            "{version}. Please use 'sk_file' argument instead.",
        )
        kwargs["sk_file"] = kwargs["keyfile"]

        # set boxtype to `secretbox` to maintain backward compatibility
        kwargs["box_type"] = "secretbox"

    if "key" in kwargs:
        salt.utils.versions.warn_until(
            "Fluorine",
            "The 'key' argument has been deprecated and will be removed in Salt "
            "{version}. Please use 'sk' argument instead.",
        )
        kwargs["sk"] = kwargs["key"]

        # set boxtype to `secretbox` to maintain backward compatibility
        kwargs["box_type"] = "secretbox"

    # ensure data is in bytes
    data = salt.utils.stringutils.to_bytes(data)

    box_type = _get_config(**kwargs)["box_type"]
    if box_type == "sealedbox":
        return sealedbox_decrypt(data, **kwargs)
    if box_type == "secretbox":
        return secretbox_decrypt(data, **kwargs)
    return sealedbox_decrypt(data, **kwargs)
# Buggy code
def sealedbox_encrypt(data, **kwargs):
    """
    Encrypt data using a public key generated from `nacl.keygen`.
    The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key.

    CLI Examples:

    .. code-block:: bash

        salt-run nacl.sealedbox_encrypt datatoenc
        salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub
        salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ='
    """
    pk = _get_pk(**kwargs)
    b = libnacl.sealed.SealedBox(pk)
    return base64.b64encode(b.encrypt(data))


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def sealedbox_encrypt(data, **kwargs):
    """
    Encrypt data using a public key generated from `nacl.keygen`.
    The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key.

    CLI Examples:

    .. code-block:: bash

        salt-run nacl.sealedbox_encrypt datatoenc
        salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub
        salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ='
    """
    # ensure data is in bytes
    data = salt.utils.stringutils.to_bytes(data)

    pk = _get_pk(**kwargs)
    b = libnacl.sealed.SealedBox(pk)
    return base64.b64encode(b.encrypt(data))
# Buggy code
def sealedbox_decrypt(data, **kwargs):
    """
    Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`.

    CLI Examples:

    .. code-block:: bash

        salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A=
        salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
        salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
    """
    if data is None:
        return None
    sk = _get_sk(**kwargs)
    keypair = libnacl.public.SecretKey(sk)
    b = libnacl.sealed.SealedBox(keypair)
    return b.decrypt(base64.b64decode(data))


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def sealedbox_decrypt(data, **kwargs):
    """
    Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`.

    CLI Examples:

    .. code-block:: bash

        salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A=
        salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
        salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
    """
    if data is None:
        return None

    # ensure data is in bytes
    data = salt.utils.stringutils.to_bytes(data)

    sk = _get_sk(**kwargs)
    keypair = libnacl.public.SecretKey(sk)
    b = libnacl.sealed.SealedBox(keypair)
    return b.decrypt(base64.b64decode(data))
# Buggy code
def secretbox_encrypt(data, **kwargs):
    """
    Encrypt data using a secret key generated from `nacl.keygen`.
    The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.

    CLI Examples:

    .. code-block:: bash

        salt-run nacl.secretbox_encrypt datatoenc
        salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl
        salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='
    """
    sk = _get_sk(**kwargs)
    b = libnacl.secret.SecretBox(sk)
    return base64.b64encode(b.encrypt(data))


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def secretbox_encrypt(data, **kwargs):
    """
    Encrypt data using a secret key generated from `nacl.keygen`.
    The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.

    CLI Examples:

    .. code-block:: bash

        salt-run nacl.secretbox_encrypt datatoenc
        salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl
        salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='
    """
    # ensure data is in bytes
    data = salt.utils.stringutils.to_bytes(data)

    sk = _get_sk(**kwargs)
    b = libnacl.secret.SecretBox(sk)
    return base64.b64encode(b.encrypt(data))
# Buggy code
def secretbox_decrypt(data, **kwargs):
    """
    Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key
    that was generated from `nacl.keygen`.

    CLI Examples:

    .. code-block:: bash

        salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=
        salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
        salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
    """
    if data is None:
        return None
    key = _get_sk(**kwargs)
    b = libnacl.secret.SecretBox(key=key)
    return b.decrypt(base64.b64decode(data))


# Traceback (IOError)
2018-03-05 18:47:44,563 [salt.pillar                                                 :732 ][CRITICAL][339999] Rendering SLS 'common.account' failed, render error:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/utils/templates.py", line 553, in py
data = mod.run()
File "/salt/pillar/common/account/init.sls", line 121, in run
'password': __salt__['shadow.gen_password'](__salt__['nacl.dec'](data=user['password'], key=nacl['db']), 'BLBnVC', 'sha256') if user['password'] else None,
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 365, in dec
return sealedbox_decrypt(data, **kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 436, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/opt/local/lib/python2.7/site-packages/salt/modules/nacl.py", line 213, in _get_sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
File "/opt/local/lib/python2.7/site-packages/salt/utils/files.py", line 366, in fopen
f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: u'/etc/salt/pki/master/nacl'

# Fixed code
def secretbox_decrypt(data, **kwargs):
    """
    Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key
    that was generated from `nacl.keygen`.

    CLI Examples:

    .. code-block:: bash

        salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=
        salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
        salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
    """
    if data is None:
        return None

    # ensure data is in bytes
    data = salt.utils.stringutils.to_bytes(data)

    key = _get_sk(**kwargs)
    b = libnacl.secret.SecretBox(key=key)
    return b.decrypt(base64.b64decode(data))
# Buggy code
def _to_unicode(vdata):
    """
    Converts from current users character encoding to unicode. Use this for
    parameters being pass to reg functions
    """
    return salt.utils.stringutils.to_unicode(vdata, "utf-8")


# Traceback (TypeError)
ID: reg_default_value
Function: reg.present
Name: HKLM\SOFTWARE\Salt
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 1876, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt\loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt\states\reg.py", line 187, in present
use_32bit_registry=use_32bit_registry)
File "c:\salt\bin\lib\site-packages\salt\modules\reg.py", line 367, in read_value
local_vname = _to_unicode(vname)
File "c:\salt\bin\lib\site-packages\salt\modules\reg.py", line 86, in _to_unicode
return salt.utils.stringutils.to_unicode(vdata, 'utf-8')
File "c:\salt\bin\lib\site-packages\salt\utils\stringutils.py", line 115, in to_unicode
raise TypeError('expected str or bytearray')
TypeError: expected str or bytearray
Started: 21:35:54.939000
Duration: 0.0 ms
Changes:

# Fixed code
def _to_unicode(vdata):
    """
    Converts from current users character encoding to unicode. Use this for
    parameters being pass to reg functions
    """
    # None does not convert to Unicode
    if vdata is None:
        return None
    return salt.utils.stringutils.to_unicode(vdata, "utf-8")
# Buggy code
def _sunos_memdata():
    """
    Return the memory information for SunOS-like systems
    """
    grains = {"mem_total": 0, "swap_total": 0}

    prtconf = "/usr/sbin/prtconf 2>/dev/null"
    for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
        comps = line.split(" ")
        if comps[0].strip() == "Memory" and comps[1].strip() == "size:":
            grains["mem_total"] = int(comps[2].strip())

    swap_cmd = salt.utils.path.which("swap")
    swap_total = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()[1]
    grains["swap_total"] = int(swap_total) // 1024
    return grains


# Traceback (ValueError)
[root@carbon /opt/saltdev/bin]# ./salt-call --versions-report
Traceback (most recent call last):
File "./salt-call", line 14, in <module>
salt_call()
File "/opt/saltdev/lib/python2.7/site-packages/salt/scripts.py", line 390, in salt_call
import salt.cli.call
File "/opt/saltdev/lib/python2.7/site-packages/salt/cli/call.py", line 5, in <module>
import salt.utils.parsers
File "/opt/saltdev/lib/python2.7/site-packages/salt/utils/parsers.py", line 28, in <module>
import salt.config as config
File "/opt/saltdev/lib/python2.7/site-packages/salt/config/__init__.py", line 100, in <module>
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
File "/opt/saltdev/lib/python2.7/site-packages/salt/config/__init__.py", line 93, in _gather_buffer_space
grains = salt.grains.core._memdata(os_data)
File "/opt/saltdev/lib/python2.7/site-packages/salt/grains/core.py", line 509, in _memdata
grains.update(_sunos_memdata())
File "/opt/saltdev/lib/python2.7/site-packages/salt/grains/core.py", line 478, in _sunos_memdata
grains['swap_total'] = int(swap_total) // 1024
ValueError: invalid literal for int() with base 10: '3453084k'

# Fixed code
def _sunos_memdata():
    """
    Return the memory information for SunOS-like systems
    """
    grains = {"mem_total": 0, "swap_total": 0}

    prtconf = "/usr/sbin/prtconf 2>/dev/null"
    for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
        comps = line.split(" ")
        if comps[0].strip() == "Memory" and comps[1].strip() == "size:":
            grains["mem_total"] = int(comps[2].strip())

    swap_cmd = salt.utils.path.which("swap")
    swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
    try:
        swap_avail = int(swap_data[-2][:-1])
        swap_used = int(swap_data[-4][:-1])
        swap_total = (swap_avail + swap_used) // 1024
    except ValueError:
        swap_total = None
    grains["swap_total"] = swap_total
    return grains