gurudesh/pytracebugs huggingface dataset:
# Buggy code
def run(self):
    """
    Run the api
    """
    import salt.client.netapi

    self.parse_args()
    self.setup_logfile_logger()
    verify_log(self.config)
    self.daemonize_if_required()
    client = salt.client.netapi.NetapiClient(self.config)
    self.set_pidfile()
    client.run()


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def run(self):
    import salt.utils

    salt.utils.warn_until(
        "Nitrogen",
        "Please stop calling 'SaltAPI.run()' and instead call "
        "'SaltAPI.start()'. 'SaltAPI.run()' will be supported "
        "until Salt {version}.",
    )
    self.start()
# Buggy code
def start(self):
    """
    Start the actual master.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(Master, self).start()
    if check_user(self.config["user"]):
        logger.info("The salt master is starting up")
        self.master.start()


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def start(self):
    """
    Start the actual master.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(Master, self).start()
    if check_user(self.config["user"]):
        log.info("The salt master is starting up")
        self.master.start()
# Buggy code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    logger.info("The salt master is shutting down..")
    msg = "The salt master is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(Master, self).shutdown(exitcode, exitmsg)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    log.info("The salt master is shutting down..")
    msg = "The salt master is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(Master, self).shutdown(exitcode, exitmsg)
# Buggy code
def start(self):
    """
    Start the actual minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(Minion, self).start()
    try:
        if check_user(self.config["user"]):
            logger.info("The salt minion is starting up")
            self.minion.tune_in()
    except (KeyboardInterrupt, SaltSystemExit) as exc:
        logger.warn("Stopping the Salt Minion")
        if isinstance(exc, KeyboardInterrupt):
            logger.warn("Exiting on Ctrl-c")
            self.shutdown()
        else:
            logger.error(str(exc))
            self.shutdown(exc.code)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def start(self):
    """
    Start the actual minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(Minion, self).start()
    try:
        if check_user(self.config["user"]):
            log.info("The salt minion is starting up")
            self.minion.tune_in()
    except (KeyboardInterrupt, SaltSystemExit) as exc:
        log.warn("Stopping the Salt Minion")
        if isinstance(exc, KeyboardInterrupt):
            log.warn("Exiting on Ctrl-c")
            self.shutdown()
        else:
            log.error(str(exc))
            self.shutdown(exc.code)
# Buggy code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    logger.info("The salt minion is shutting down..")
    if hasattr(self, "minion"):
        self.minion.destroy()
    msg = "The salt minion is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(Minion, self).shutdown(exitcode, exitmsg)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    log.info("The salt minion is shutting down..")
    if hasattr(self, "minion"):
        self.minion.destroy()
    msg = "The salt minion is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(Minion, self).shutdown(exitcode, exitmsg)
# Buggy code
def start(self):
    """
    Start the actual proxy minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(ProxyMinion, self).start()
    try:
        if check_user(self.config["user"]):
            logger.info("The proxy minion is starting up")
            self.minion.tune_in()
    except (KeyboardInterrupt, SaltSystemExit) as exc:
        logger.warn("Stopping the Salt Proxy Minion")
        if isinstance(exc, KeyboardInterrupt):
            logger.warn("Exiting on Ctrl-c")
            self.shutdown()
        else:
            logger.error(str(exc))
            self.shutdown(exc.code)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def start(self):
    """
    Start the actual proxy minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(ProxyMinion, self).start()
    try:
        if check_user(self.config["user"]):
            log.info("The proxy minion is starting up")
            self.minion.tune_in()
    except (KeyboardInterrupt, SaltSystemExit) as exc:
        log.warn("Stopping the Salt Proxy Minion")
        if isinstance(exc, KeyboardInterrupt):
            log.warn("Exiting on Ctrl-c")
            self.shutdown()
        else:
            log.error(str(exc))
            self.shutdown(exc.code)
# Buggy code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    if hasattr(self, "minion") and "proxymodule" in self.minion.opts:
        proxy_fn = self.minion.opts["proxymodule"].loaded_base_name + ".shutdown"
        self.minion.opts["proxymodule"][proxy_fn](self.minion.opts)
    logger.info("The proxy minion is shutting down..")
    msg = "The proxy minion is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(ProxyMinion, self).shutdown(exitcode, exitmsg)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    if hasattr(self, "minion") and "proxymodule" in self.minion.opts:
        proxy_fn = self.minion.opts["proxymodule"].loaded_base_name + ".shutdown"
        self.minion.opts["proxymodule"][proxy_fn](self.minion.opts)
    log.info("The proxy minion is shutting down..")
    msg = "The proxy minion is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(ProxyMinion, self).shutdown(exitcode, exitmsg)
# Buggy code
def start(self):
    """
    Start the actual syndic.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(Syndic, self).start()
    if check_user(self.config["user"]):
        logger.info("The salt syndic is starting up")
        try:
            self.syndic.tune_in()
        except KeyboardInterrupt:
            logger.warn("Stopping the Salt Syndic Minion")
            self.shutdown()


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def start(self):
    """
    Start the actual syndic.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(Syndic, self).start()
    if check_user(self.config["user"]):
        log.info("The salt syndic is starting up")
        try:
            self.syndic.tune_in()
        except KeyboardInterrupt:
            log.warn("Stopping the Salt Syndic Minion")
            self.shutdown()
# Buggy code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    logger.info("The salt syndic is shutting down..")
    msg = "The salt syndic is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(Syndic, self).shutdown(exitcode, exitmsg)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def shutdown(self, exitcode=0, exitmsg=None):
    """
    If sub-classed, run any shutdown operations on this method.
    """
    log.info("The salt syndic is shutting down..")
    msg = "The salt syndic is shutdown. "
    if exitmsg is not None:
        exitmsg = msg + exitmsg
    else:
        exitmsg = msg.strip()
    super(Syndic, self).shutdown(exitcode, exitmsg)
# Buggy code
def __init__(self, opts):
    self.opts = opts
    self.process_manager = salt.utils.process.ProcessManager()
    self.netapi = salt.loader.netapi(self.opts)


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def __init__(self, opts):
    self.opts = opts
    self.process_manager = salt.utils.process.ProcessManager(
        name="NetAPIProcessManager"
    )
    self.netapi = salt.loader.netapi(self.opts)
# Buggy code
def run(self):
    """
    Load and start all available api modules
    """
    if not len(self.netapi):
        logger.error("Did not find any netapi configurations, nothing to start")

    for fun in self.netapi:
        if fun.endswith(".start"):
            logger.info("Starting {0} netapi module".format(fun))
            self.process_manager.add_process(self.netapi[fun])

    self.process_manager.run()


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def run(self):
    """
    Load and start all available api modules
    """
    if not len(self.netapi):
        log.error("Did not find any netapi configurations, nothing to start")

    for fun in self.netapi:
        if fun.endswith(".start"):
            log.info("Starting {0} netapi module".format(fun))
            self.process_manager.add_process(self.netapi[fun])

    # Install the SIGINT/SIGTERM handlers if not done so far
    if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
        # No custom signal handling was added, install our own
        signal.signal(signal.SIGINT, self._handle_signals)

    if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
        # No custom signal handling was added, install our own
        signal.signal(signal.SIGINT, self._handle_signals)

    self.process_manager.run()
# Buggy code
def salt_api():
    """
    The main function for salt-api
    """
    import salt.cli.api

    sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
    sapi.run()


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def salt_api():
    """
    The main function for salt-api
    """
    import salt.cli.api

    sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
    sapi.start()
# Buggy code
def setup_config(self):
    return salt.config.spm_config(self.get_config_file_path())


# Traceback (optparse.OptionConflictError)
/usr/lib/python2.7/dist-packages/salt/utils/parsers.py:953: DeprecationWarning: Please stop sub-classing PidfileMix and instead subclass DaemonMixIn which contains the same behavior. PidfileMixin will be supported until Salt Nitrogen (Unreleased).
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 441, in salt_api
sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 152, in __init__
optparse.OptionParser.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 1220, in __init__
add_help=add_help_option)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 233, in _populate_option_list
mixin_setup_func(self)
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 962, in _mixin_setup
help=('Specify the location of the pidfile. Default: %default')
File "/usr/lib/python2.7/optparse.py", line 1021, in add_option
self._check_conflict(option)
File "/usr/lib/python2.7/optparse.py", line 996, in _check_conflict
option)
optparse.OptionConflictError: option --pid-file: conflicting option string(s): --pid-file

# Fixed code
def setup_config(self):
    return salt.config.api_config(self.get_config_file_path())  # pylint: disable=no-member
# Buggy code
def __virtual__():
    """
    Only load if boto is available.
    """
    return "boto_cfn.exists" in __salt__


# Traceback (ImportError)
[DEBUG   ] Failed to import states boto_cfn:
Traceback (most recent call last):
File "salt/loader.py", line 1215, in _load_module
File "salt/states/boto_cfn.py", line 45, in <module>
File "xml/etree/cElementTree.py", line 3, in <module>
ImportError: No module named _elementtree

# Fixed code
def __virtual__():
    """
    Only load if elementtree xml library and boto are available.
    """
    if not HAS_ELEMENT_TREE:
        return (
            False,
            "Cannot load {0} state: ElementTree library unavailable".format(
                __virtualname__
            ),
        )

    if "boto_cfn.exists" in __salt__:
        return True
    else:
        return (
            False,
            "Cannot load {0} state: boto_cfn module unavailable".format(
                __virtualname__
            ),
        )
# Buggy code
def _get_error(error):
    # Converts boto exception to string that can be used to output error.
    error = "\n".join(error.split("\n")[1:])
    error = xml.fromstring(error)
    code = error[0][1].text
    message = error[0][2].text
    return code, message


# Traceback (ImportError)
[DEBUG   ] Failed to import states boto_cfn:
Traceback (most recent call last):
File "salt/loader.py", line 1215, in _load_module
File "salt/states/boto_cfn.py", line 45, in <module>
File "xml/etree/cElementTree.py", line 3, in <module>
ImportError: No module named _elementtree

# Fixed code
def _get_error(error):
    # Converts boto exception to string that can be used to output error.
    error = "\n".join(error.split("\n")[1:])
    error = ET.fromstring(error)
    code = error[0][1].text
    message = error[0][2].text
    return code, message
# Buggy code
def create(path, saltenv=None):
    """
    join `path` and `saltenv` into a 'salt://' URL.
    """
    if salt.utils.is_windows():
        path = salt.utils.sanitize_win_path_string(path)

    query = "saltenv={0}".format(saltenv) if saltenv else ""
    url = urlunparse(("file", "", path, "", query, ""))
    return "salt://{0}".format(url[len("file:///") :])


# Traceback (UnicodeDecodeError)
minion-x:
----------
file_|-/opt/deploy_|-/opt/deploy_|-recurse:
----------
__run_num__:
0
changes:
----------
comment:
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1560, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/file.py", line 2317, in recurse
src = u'salt://{0}'.format(fn_)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 45: ordinal not in range(128)
duration:
8868.469
name:
/opt/deploy
result:
False
start_time:
15:56:11.275353

# Fixed code
def create(path, saltenv=None):
    """
    join `path` and `saltenv` into a 'salt://' URL.
    """
    if salt.utils.is_windows():
        path = salt.utils.sanitize_win_path_string(path)
    path = sdecode(path)

    query = "saltenv={0}".format(saltenv) if saltenv else ""
    url = sdecode(urlunparse(("file", "", path, "", query, "")))
    return "salt://{0}".format(url[len("file:///") :])
# Buggy code
def _get_gecos(name):
    """
    Retrieve GECOS field info and return it in dictionary form
    """
    gecos_field = pwd.getpwnam(name).pw_gecos.split(",", 3)
    if not gecos_field:
        return {}
    else:
        # Assign empty strings for any unspecified trailing GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append("")
        return {
            "fullname": str(gecos_field[0]),
            "roomnumber": str(gecos_field[1]),
            "workphone": str(gecos_field[2]),
            "homephone": str(gecos_field[3]),
        }


# Traceback (UnicodeEncodeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1563, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/user.py", line 383, in present
ret['comment'] += '{0}: {1}\n'.format(key, salt.utils.sdecode(val))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 22: ordinal not in range(128)

# Fixed code
def _get_gecos(name):
    """
    Retrieve GECOS field info and return it in dictionary form
    """
    gecos_field = pwd.getpwnam(name).pw_gecos.split(",", 3)
    if not gecos_field:
        return {}
    else:
        # Assign empty strings for any unspecified trailing GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append("")
        return {
            "fullname": locales.sdecode(gecos_field[0]),
            "roomnumber": locales.sdecode(gecos_field[1]),
            "workphone": locales.sdecode(gecos_field[2]),
            "homephone": locales.sdecode(gecos_field[3]),
        }
# Buggy code
def _build_gecos(gecos_dict):
    """
    Accepts a dictionary entry containing GECOS field names and their values,
    and returns a full GECOS comment string, to be used with usermod.
    """
    return "{0},{1},{2},{3}".format(
        gecos_dict.get("fullname", ""),
        gecos_dict.get("roomnumber", ""),
        gecos_dict.get("workphone", ""),
        gecos_dict.get("homephone", ""),
    )


# Traceback (UnicodeEncodeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1563, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/user.py", line 383, in present
ret['comment'] += '{0}: {1}\n'.format(key, salt.utils.sdecode(val))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 22: ordinal not in range(128)

# Fixed code
def _build_gecos(gecos_dict):
    """
    Accepts a dictionary entry containing GECOS field names and their values,
    and returns a full GECOS comment string, to be used with usermod.
    """
    return "{0},{1},{2},{3}".format(
        gecos_dict.get("fullname", ""),
        gecos_dict.get("roomnumber", ""),
        gecos_dict.get("workphone", ""),
        gecos_dict.get("homephone", ""),
    )
# Buggy code
def _get_gecos(name):
    """
    Retrieve GECOS field info and return it in dictionary form
    """
    try:
        gecos_field = pwd.getpwnam(name).pw_gecos.split(",", 3)
    except KeyError:
        raise CommandExecutionError("User '{0}' does not exist".format(name))
    if not gecos_field:
        return {}
    else:
        # Assign empty strings for any unspecified trailing GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append("")
        return {
            "fullname": str(gecos_field[0]),
            "roomnumber": str(gecos_field[1]),
            "workphone": str(gecos_field[2]),
            "homephone": str(gecos_field[3]),
        }


# Traceback (UnicodeEncodeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1563, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/user.py", line 383, in present
ret['comment'] += '{0}: {1}\n'.format(key, salt.utils.sdecode(val))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 22: ordinal not in range(128)

# Fixed code
def _get_gecos(name):
    """
    Retrieve GECOS field info and return it in dictionary form
    """
    try:
        gecos_field = pwd.getpwnam(name).pw_gecos.split(",", 3)
    except KeyError:
        raise CommandExecutionError("User '{0}' does not exist".format(name))
    if not gecos_field:
        return {}
    else:
        # Assign empty strings for any unspecified trailing GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append("")
        return {
            "fullname": locales.sdecode(gecos_field[0]),
            "roomnumber": locales.sdecode(gecos_field[1]),
            "workphone": locales.sdecode(gecos_field[2]),
            "homephone": locales.sdecode(gecos_field[3]),
        }
# Buggy code
def _build_gecos(gecos_dict):
    """
    Accepts a dictionary entry containing GECOS field names and their values,
    and returns a full GECOS comment string, to be used with pw usermod.
    """
    return "{0},{1},{2},{3}".format(
        gecos_dict.get("fullname", ""),
        gecos_dict.get("roomnumber", ""),
        gecos_dict.get("workphone", ""),
        gecos_dict.get("homephone", ""),
    )


# Traceback (UnicodeEncodeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1563, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/user.py", line 383, in present
ret['comment'] += '{0}: {1}\n'.format(key, salt.utils.sdecode(val))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 22: ordinal not in range(128)

# Fixed code
def _build_gecos(gecos_dict):
    """
    Accepts a dictionary entry containing GECOS field names and their values,
    and returns a full GECOS comment string, to be used with pw usermod.
    """
    return "{0},{1},{2},{3}".format(
        gecos_dict.get("fullname", ""),
        gecos_dict.get("roomnumber", ""),
        gecos_dict.get("workphone", ""),
        gecos_dict.get("homephone", ""),
    )
# Buggy code
def get_loginclass(name):
    """
    Get the login class of the user

    .. versionadded:: 2016.3.0

    CLI Example:

    .. code-block:: bash

        salt '*' user.get_loginclass foo

    """

    userinfo = __salt__["cmd.run_stdout"]("pw usershow -n {0}".format(name))
    userinfo = userinfo.split(":")

    return {"loginclass": userinfo[4] if len(userinfo) == 10 else ""}


# Traceback (UnicodeEncodeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1563, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/user.py", line 383, in present
ret['comment'] += '{0}: {1}\n'.format(key, salt.utils.sdecode(val))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 22: ordinal not in range(128)

# Fixed code
def get_loginclass(name):
    """
    Get the login class of the user

    .. versionadded:: 2016.3.0

    CLI Example:

    .. code-block:: bash

        salt '*' user.get_loginclass foo

    """

    userinfo = __salt__["cmd.run_stdout"](["pw", "usershow", "-n", name])
    userinfo = userinfo.split(":")

    return {"loginclass": userinfo[4] if len(userinfo) == 10 else ""}
# Buggy code
def subnet_group_exists(
    name, tags=None, region=None, key=None, keyid=None, profile=None
):
    """
    Check to see if an ElastiCache subnet group exists.

    CLI example::

        salt myminion boto_elasticache.subnet_group_exists my-param-group \
                region=us-east-1
    """
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return False
    try:
        ec = conn.describe_cache_subnet_groups(cache_subnet_group_name=name)
        if not ec:
            msg = "ElastiCache subnet group does not exist in region {0}".format(region)
            log.debug(msg)
            return False
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return False


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

# Fixed code
def subnet_group_exists(
    name, tags=None, region=None, key=None, keyid=None, profile=None
):
    """
    Check to see if an ElastiCache subnet group exists.

    CLI example::

        salt myminion boto_elasticache.subnet_group_exists my-param-group \
                region=us-east-1
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    try:
        ec = conn.describe_cache_subnet_groups(cache_subnet_group_name=name)
        if not ec:
            msg = "ElastiCache subnet group does not exist in region {0}".format(region)
            log.debug(msg)
            return False
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return False
# Buggy code
def create_subnet_group(
    name,
    description,
    subnet_ids,
    tags=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    """
    Create an ElastiCache subnet group

    CLI example to create an ElastiCache subnet group::

        salt myminion boto_elasticache.create_subnet_group my-subnet-group \
            "group description" '[subnet-12345678, subnet-87654321]' \
            region=us-east-1
    """
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return False
    if subnet_group_exists(name, tags, region, key, keyid, profile):
        return True
    try:
        ec = conn.create_cache_subnet_group(name, description, subnet_ids)
        if not ec:
            msg = "Failed to create ElastiCache subnet group {0}".format(name)
            log.error(msg)
            return False
        log.info("Created ElastiCache subnet group {0}".format(name))
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to create ElastiCache subnet group {0}".format(name)
        log.error(msg)
        return False


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

# Fixed code
def create_subnet_group(
    name,
    description,
    subnet_ids,
    tags=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    """
    Create an ElastiCache subnet group

    CLI example to create an ElastiCache subnet group::

        salt myminion boto_elasticache.create_subnet_group my-subnet-group \
            "group description" '[subnet-12345678, subnet-87654321]' \
            region=us-east-1
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    if subnet_group_exists(name, tags, region, key, keyid, profile):
        return True
    try:
        ec = conn.create_cache_subnet_group(name, description, subnet_ids)
        if not ec:
            msg = "Failed to create ElastiCache subnet group {0}".format(name)
            log.error(msg)
            return False
        log.info("Created ElastiCache subnet group {0}".format(name))
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to create ElastiCache subnet group {0}".format(name)
        log.error(msg)
        return False
# Buggy code
def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None):
    """
    Delete an ElastiCache subnet group.

    CLI example::

        salt myminion boto_elasticache.delete_subnet_group my-subnet-group \
                region=us-east-1
    """
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return False
    try:
        conn.delete_cache_subnet_group(name)
        msg = "Deleted ElastiCache subnet group {0}.".format(name)
        log.info(msg)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete ElastiCache subnet group {0}".format(name)
        log.error(msg)
        return False


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

# Fixed code
def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None):
    """
    Delete an ElastiCache subnet group.

    CLI example::

        salt myminion boto_elasticache.delete_subnet_group my-subnet-group \
                region=us-east-1
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if not conn:
        return False
    try:
        conn.delete_cache_subnet_group(name)
        msg = "Deleted ElastiCache subnet group {0}.".format(name)
        log.info(msg)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete ElastiCache subnet group {0}".format(name)
        log.error(msg)
        return False
# Buggy code
def put_group_policy(
    group_name,
    policy_name,
    policy_json,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    """
    Adds or updates the specified policy document for the specified group.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

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


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

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

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

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