Instruction:
How would you implement a function in Python 3 that
starts up the Tornado IPC server.

Response:
def start(self):
        '''
        Perform the work necessary to start up a Tornado IPC server

        Blocks until socket is established
        '''
        # Start up the ioloop
        log.trace('IPCMessagePublisher: binding to socket: %s', self.socket_path)
        if isinstance(self.socket_path, int):
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if self.opts.get('ipc_so_sndbuf'):
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.opts['ipc_so_sndbuf'])
            if self.opts.get('ipc_so_rcvbuf'):
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.opts['ipc_so_rcvbuf'])
            self.sock.setblocking(0)
            self.sock.bind(('127.0.0.1', self.socket_path))
            # Based on default used in tornado.netutil.bind_sockets()
            self.sock.listen(self.opts['ipc_so_backlog'])
        else:
            # sndbuf/rcvbuf does not apply to unix sockets
            self.sock = tornado.netutil.bind_unix_socket(self.socket_path, backlog=self.opts['ipc_so_backlog'])

        with salt.utils.asynchronous.current_ioloop(self.io_loop):
            tornado.netutil.add_accept_handler(
                self.sock,
                self.handle_connection,
            )
        self._started = True


Instruction:
Given the following Python 3 function, write the documentation
def publish(self, msg):
        '''
        Send message to all connected sockets
        '''
        if not self.streams:
            return

        pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)

        for stream in self.streams:
            self.io_loop.spawn_callback(self._write, stream, pack)

Response: Send message to all connected sockets


Instruction:
How would you code a function in Python 3 to
close the underlying socket and filehandles.

Response:
def close(self):
        '''
        Routines to handle any cleanup before the instance shuts down.
        Sockets and filehandles should be closed explicitly, to prevent
        leaks.
        '''
        if self._closing:
            return
        self._closing = True
        for stream in self.streams:
            stream.close()
        self.streams.clear()
        if hasattr(self.sock, 'close'):
            self.sock.close()


Instruction:
Can you implement a function in Python 3 that
reads a message from an IPC socket and return it.

Response:
def read_sync(self, timeout=None):
        '''
        Read a message from an IPC socket

        The socket must already be connected.
        The associated IO Loop must NOT be running.
        :param int timeout: Timeout when receiving message
        :return: message data if successful. None if timed out. Will raise an
                 exception for all other error conditions.
        '''
        if self.saved_data:
            return self.saved_data.pop(0)

        self._sync_ioloop_running = True
        self._read_sync_future = self._read_sync(timeout)
        self.io_loop.start()
        self._sync_ioloop_running = False

        ret_future = self._read_sync_future
        self._read_sync_future = None
        return ret_future.result()


Instruction:
Can you tell what is the following Python 3 function doing
def list_(show_all=False,
          show_disabled=True,
          where=None,
          return_yaml=True):
    '''
    List the jobs currently scheduled on the minion

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.list

        # Show all jobs including hidden internal jobs
        salt '*' schedule.list show_all=True

        # Hide disabled jobs from list of jobs
        salt '*' schedule.list show_disabled=False

    '''

    schedule = {}
    try:
        eventer = salt.utils.event.get_event('minion', opts=__opts__)
        res = __salt__['event.fire']({'func': 'list',
                                      'where': where}, 'manage_schedule')
        if res:
            event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)
            if event_ret and event_ret['complete']:
                schedule = event_ret['schedule']
    except KeyError:
        # Effectively a no-op, since we can't really return without an event system
        ret = {}
        ret['comment'] = 'Event module not available. Schedule list failed.'
        ret['result'] = True
        log.debug('Event module not available. Schedule list failed.')
        return ret

    _hidden = ['enabled',
               'skip_function',
               'skip_during_range']
    for job in list(schedule.keys()):  # iterate over a copy since we will mutate it
        if job in _hidden:
            continue

        # Default jobs added by salt begin with __
        # by default hide them unless show_all is True.
        if job.startswith('__') and not show_all:
            del schedule[job]
            continue

        # if enabled is not included in the job,
        # assume job is enabled.
        if 'enabled' not in schedule[job]:
            schedule[job]['enabled'] = True

        for item in pycopy.copy(schedule[job]):
            if item not in SCHEDULE_CONF:
                del schedule[job][item]
                continue
            if schedule[job][item] is None:
                del schedule[job][item]
                continue
            if schedule[job][item] == 'true':
                schedule[job][item] = True
            if schedule[job][item] == 'false':
                schedule[job][item] = False

        # if the job is disabled and show_disabled is False, skip job
        if not show_disabled and not schedule[job]['enabled']:
            del schedule[job]
            continue

        if '_seconds' in schedule[job]:
            # remove _seconds from the listing
            del schedule[job]['_seconds']

    if schedule:
        if return_yaml:
            tmp = {'schedule': schedule}
            return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)
        else:
            return schedule
    else:
        return {'schedule': {}}

Response: List the currently scheduled jobs on the minion


Instruction:
Can you tell what is the following Python 3 function doing
def is_enabled(name):
    '''
    List a Job only if its enabled

    .. versionadded:: 2015.5.3

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.is_enabled name=job_name
    '''

    current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False)
    if name in current_schedule:
        return current_schedule[name]
    else:
        return {}

Response: Return a Job only if its enabled


Instruction:
Here you have a function in Python 3, explain what it does
def purge(**kwargs):
    '''
    Purge all the jobs currently scheduled on the minion

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.purge
    '''

    ret = {'comment': [],
           'result': True}

    for name in list_(show_all=True, return_yaml=False):
        if name == 'enabled':
            continue
        if name.startswith('__'):
            continue

        if 'test' in kwargs and kwargs['test']:
            ret['result'] = True
            ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name))
        else:

            persist = True
            if 'persist' in kwargs:
                persist = kwargs['persist']

            try:
                eventer = salt.utils.event.get_event('minion', opts=__opts__)
                res = __salt__['event.fire']({'name': name,
                                              'func': 'delete',
                                              'persist': persist}, 'manage_schedule')
                if res:
                    event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30)
                    if event_ret and event_ret['complete']:
                        _schedule_ret = event_ret['schedule']
                        if name not in _schedule_ret:
                            ret['result'] = True
                            ret['comment'].append('Deleted job: {0} from schedule.'.format(name))
                        else:
                            ret['comment'].append('Failed to delete job {0} from schedule.'.format(name))
                            ret['result'] = True

            except KeyError:
                # Effectively a no-op, since we can't really return without an event system
                ret['comment'] = 'Event module not available. Schedule add failed.'
                ret['result'] = True
    return ret

Response: Purge all the jobs currently scheduled on the minion


Instruction:
Implement a function in Python 3 to
build a schedule item

Response:
def build_schedule_item(name, **kwargs):
    '''
    Build a schedule job

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600
    '''

    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False
        return ret

    schedule = {}
    schedule[name] = salt.utils.odict.OrderedDict()
    schedule[name]['function'] = kwargs['function']

    time_conflict = False
    for item in ['seconds', 'minutes', 'hours', 'days']:
        if item in kwargs and 'when' in kwargs:
            time_conflict = True

        if item in kwargs and 'cron' in kwargs:
            time_conflict = True

    if time_conflict:
        ret['result'] = False
        ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.'
        return ret

    if 'when' in kwargs and 'cron' in kwargs:
        ret['result'] = False
        ret['comment'] = 'Unable to use "when" and "cron" options together.  Ignoring.'
        return ret

    for item in ['seconds', 'minutes', 'hours', 'days']:
        if item in kwargs:
            schedule[name][item] = kwargs[item]

    if 'return_job' in kwargs:
        schedule[name]['return_job'] = kwargs['return_job']

    if 'metadata' in kwargs:
        schedule[name]['metadata'] = kwargs['metadata']

    if 'job_args' in kwargs:
        schedule[name]['args'] = kwargs['job_args']

    if 'job_kwargs' in kwargs:
        schedule[name]['kwargs'] = kwargs['job_kwargs']

    if 'maxrunning' in kwargs:
        schedule[name]['maxrunning'] = kwargs['maxrunning']
    else:
        schedule[name]['maxrunning'] = 1

    if 'name' in kwargs:
        schedule[name]['name'] = kwargs['name']
    else:
        schedule[name]['name'] = name

    if 'enabled' in kwargs:
        schedule[name]['enabled'] = kwargs['enabled']
    else:
        schedule[name]['enabled'] = True

    if 'jid_include' not in kwargs or kwargs['jid_include']:
        schedule[name]['jid_include'] = True

    if 'splay' in kwargs:
        if isinstance(kwargs['splay'], dict):
            # Ensure ordering of start and end arguments
            schedule[name]['splay'] = salt.utils.odict.OrderedDict()
            schedule[name]['splay']['start'] = kwargs['splay']['start']
            schedule[name]['splay']['end'] = kwargs['splay']['end']
        else:
            schedule[name]['splay'] = kwargs['splay']

    if 'when' in kwargs:
        if not _WHEN_SUPPORTED:
            ret['result'] = False
            ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.'
            return ret
        else:
            validate_when = kwargs['when']
            if not isinstance(validate_when, list):
                validate_when = [validate_when]
            for _when in validate_when:
                try:
                    dateutil_parser.parse(_when)
                except ValueError:
                    ret['result'] = False
                    ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when)
                    return ret

    for item in ['range', 'when', 'once', 'once_fmt', 'cron',
                 'returner', 'after', 'return_config', 'return_kwargs',
                 'until', 'run_on_start', 'skip_during_range']:
        if item in kwargs:
            schedule[name][item] = kwargs[item]

    return schedule[name]


Instruction:
How would you code a function in Python 3 to
add a job to the schedule.

Response:
def add(name, **kwargs):
    '''
    Add a job to the schedule

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.add job1 function='test.ping' seconds=3600
        # If function have some arguments, use job_args
        salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60
    '''

    ret = {'comment': 'Failed to add job {0} to schedule.'.format(name),
           'result': False}

    if name in list_(show_all=True, return_yaml=False):
        ret['comment'] = 'Job {0} already exists in schedule.'.format(name)
        ret['result'] = False
        return ret

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False

    time_conflict = False
    for item in ['seconds', 'minutes', 'hours', 'days']:
        if item in kwargs and 'when' in kwargs:
            time_conflict = True
        if item in kwargs and 'cron' in kwargs:
            time_conflict = True

    if time_conflict:
        ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.'
        return ret

    if 'when' in kwargs and 'cron' in kwargs:
        ret['comment'] = 'Unable to use "when" and "cron" options together.  Ignoring.'
        return ret

    persist = True
    if 'persist' in kwargs:
        persist = kwargs['persist']

    _new = build_schedule_item(name, **kwargs)
    if 'result' in _new and not _new['result']:
        return _new

    schedule_data = {}
    schedule_data[name] = _new

    if 'test' in kwargs and kwargs['test']:
        ret['comment'] = 'Job: {0} would be added to schedule.'.format(name)
        ret['result'] = True
    else:
        try:
            eventer = salt.utils.event.get_event('minion', opts=__opts__)
            res = __salt__['event.fire']({'name': name,
                                          'schedule': schedule_data,
                                          'func': 'add',
                                          'persist': persist}, 'manage_schedule')
            if res:
                event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30)
                if event_ret and event_ret['complete']:
                    schedule = event_ret['schedule']
                    if name in schedule:
                        ret['result'] = True
                        ret['comment'] = 'Added job: {0} to schedule.'.format(name)
                        return ret
        except KeyError:
            # Effectively a no-op, since we can't really return without an event system
            ret['comment'] = 'Event module not available. Schedule add failed.'
    return ret


Instruction:
Write a Python 3 function that can
modify an existing job in the schedule

Response:
def modify(name, **kwargs):
    '''
    Modify an existing job in the schedule

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.modify job1 function='test.ping' seconds=3600
    '''

    ret = {'comment': '',
           'changes': {},
           'result': True}

    time_conflict = False
    for item in ['seconds', 'minutes', 'hours', 'days']:
        if item in kwargs and 'when' in kwargs:
            time_conflict = True

        if item in kwargs and 'cron' in kwargs:
            time_conflict = True

    if time_conflict:
        ret['result'] = False
        ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.'
        return ret

    if 'when' in kwargs and 'cron' in kwargs:
        ret['result'] = False
        ret['comment'] = 'Unable to use "when" and "cron" options together.  Ignoring.'
        return ret

    current_schedule = list_(show_all=True, return_yaml=False)

    if name not in current_schedule:
        ret['comment'] = 'Job {0} does not exist in schedule.'.format(name)
        ret['result'] = False
        return ret

    _current = current_schedule[name]
    if '_seconds' in _current:
        _current['seconds'] = _current['_seconds']
        del _current['_seconds']

    _new = build_schedule_item(name, **kwargs)
    if 'result' in _new and not _new['result']:
        return _new

    if _new == _current:
        ret['comment'] = 'Job {0} in correct state'.format(name)
        return ret

    _current_lines = ['{0}:{1}\n'.format(key, value)
                      for (key, value) in sorted(_current.items())]
    _new_lines = ['{0}:{1}\n'.format(key, value)
                  for (key, value) in sorted(_new.items())]
    _diff = difflib.unified_diff(_current_lines, _new_lines)

    ret['changes']['diff'] = ''.join(_diff)

    if 'test' in kwargs and kwargs['test']:
        ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name)
    else:
        persist = True
        if 'persist' in kwargs:
            persist = kwargs['persist']
        if name in list_(show_all=True, where='opts', return_yaml=False):
            event_data = {'name': name,
                          'schedule': _new,
                          'func': 'modify',
                          'persist': persist}
        elif name in list_(show_all=True, where='pillar', return_yaml=False):
            event_data = {'name': name,
                          'schedule': _new,
                          'where': 'pillar',
                          'func': 'modify',
                          'persist': False}

        out = __salt__['event.fire'](event_data, 'manage_schedule')
        if out:
            ret['comment'] = 'Modified job: {0} in schedule.'.format(name)
        else:
            ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name)
            ret['result'] = False
    return ret


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run_job(name, force=False):
    '''
    Run a scheduled job on the minion immediately

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.run_job job1

        salt '*' schedule.run_job job1 force=True
        Force the job to run even if it is disabled.
    '''

    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False

    schedule = list_(show_all=True, return_yaml=False)
    if name in schedule:
        data = schedule[name]
        if 'enabled' in data and not data['enabled'] and not force:
            ret['comment'] = 'Job {0} is disabled.'.format(name)
        else:
            out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule')
            if out:
                ret['comment'] = 'Scheduling Job {0} on minion.'.format(name)
            else:
                ret['comment'] = 'Failed to run job {0} on minion.'.format(name)
                ret['result'] = False
    else:
        ret['comment'] = 'Job {0} does not exist.'.format(name)
        ret['result'] = False
    return ret

Response:
Run a scheduled job on the minion immediately
 archive.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def enable_job(name, **kwargs):
    '''
    Enable a job in the minion's schedule

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.enable_job job1
    '''

    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False

    if 'test' in __opts__ and __opts__['test']:
        ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name)
    else:
        persist = True
        if 'persist' in kwargs:
            persist = kwargs['persist']

        if name in list_(show_all=True, where='opts', return_yaml=False):
            event_data = {'name': name, 'func': 'enable_job', 'persist': persist}
        elif name in list_(show_all=True, where='pillar', return_yaml=False):
            event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False}
        else:
            ret['comment'] = 'Job {0} does not exist.'.format(name)
            ret['result'] = False
            return ret

        try:
            eventer = salt.utils.event.get_event('minion', opts=__opts__)
            res = __salt__['event.fire'](event_data, 'manage_schedule')
            if res:
                event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30)
                if event_ret and event_ret['complete']:
                    schedule = event_ret['schedule']
                    # check item exists in schedule and is enabled
                    if name in schedule and schedule[name]['enabled']:
                        ret['result'] = True
                        ret['comment'] = 'Enabled Job {0} in schedule.'.format(name)
                    else:
                        ret['result'] = False
                        ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name)
                    return ret
        except KeyError:
            # Effectively a no-op, since we can't really return without an event system
            ret['comment'] = 'Event module not available. Schedule enable job failed.'
    return ret

Response: Enable a job in the salt s schedule


Instruction:
How would you implement a function in Python 3 that
saves all scheduled jobs on the minion

Response:
def save(**kwargs):
    '''
    Save all scheduled jobs on the minion

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.save
    '''

    ret = {'comment': [],
           'result': True}

    if 'test' in kwargs and kwargs['test']:
        ret['comment'] = 'Schedule would be saved.'
    else:
        try:
            eventer = salt.utils.event.get_event('minion', opts=__opts__)
            res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule')
            if res:
                event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30)
                if event_ret and event_ret['complete']:
                    ret['result'] = True
                    ret['comment'] = 'Schedule (non-pillar items) saved.'
                else:
                    ret['result'] = False
                    ret['comment'] = 'Failed to save schedule.'
        except KeyError:
            # Effectively a no-op, since we can't really return without an event system
            ret['comment'] = 'Event module not available. Schedule save failed.'
    return ret


Instruction:
How would you code a function in Python 3 to
reload the current scheduler on the minion

Response:
def reload_():
    '''
    Reload saved scheduled jobs on the minion

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.reload
    '''

    ret = {'comment': [],
           'result': True}

    # If there a schedule defined in pillar, refresh it.
    if 'schedule' in __pillar__:
        out = __salt__['event.fire']({}, 'pillar_refresh')
        if out:
            ret['comment'].append('Reloaded schedule from pillar on minion.')
        else:
            ret['comment'].append('Failed to reload schedule from pillar on minion.')
            ret['result'] = False

    # move this file into an configurable opt
    sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include']))
    if os.path.isfile(sfn):
        with salt.utils.files.fopen(sfn, 'rb') as fp_:
            try:
                schedule = salt.utils.yaml.safe_load(fp_)
            except salt.utils.yaml.YAMLError as exc:
                ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc))

        if schedule:
            if 'schedule' in schedule and schedule['schedule']:
                out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule')
                if out:
                    ret['comment'].append('Reloaded schedule on minion from schedule.conf.')
                else:
                    ret['comment'].append('Failed to reload schedule on minion from schedule.conf.')
                    ret['result'] = False
            else:
                ret['comment'].append('Failed to reload schedule on minion.  Saved file is empty or invalid.')
                ret['result'] = False
        else:
            ret['comment'].append('Failed to reload schedule on minion.  Saved file is empty or invalid.')
            ret['result'] = False
    return ret


Instruction:
Implement a function in Python 3 to
move a scheduled job to another minion or minions.

Response:
def move(name, target, **kwargs):
    '''
    Move scheduled job to another minion or minions.

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.move jobname target
    '''

    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False

    if 'test' in kwargs and kwargs['test']:
        ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name)
    else:
        opts_schedule = list_(show_all=True, where='opts', return_yaml=False)
        pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False)

        if name in opts_schedule:
            schedule_data = opts_schedule[name]
            where = None
        elif name in pillar_schedule:
            schedule_data = pillar_schedule[name]
            where = 'pillar'
        else:
            ret['comment'] = 'Job {0} does not exist.'.format(name)
            ret['result'] = False
            return ret

        schedule_opts = []
        for key, value in six.iteritems(schedule_data):
            temp = '{0}={1}'.format(key, value)
            schedule_opts.append(temp)
        response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts)

        # Get errors and list of affeced minions
        errors = []
        minions = []
        for minion in response:
            minions.append(minion)
            if not response[minion]:
                errors.append(minion)

        # parse response
        if not response:
            ret['comment'] = 'no servers answered the published schedule.add command'
            return ret
        elif errors:
            ret['comment'] = 'the following minions return False'
            ret['minions'] = errors
            return ret
        else:
            delete(name, where=where)
            ret['result'] = True
            ret['comment'] = 'Moved Job {0} from schedule.'.format(name)
            ret['minions'] = minions
            return ret
    return ret


Instruction:
Implement a function in Python 3 to
postpone a job in the schedule

Response:
def postpone_job(name,
                 current_time,
                 new_time,
                 **kwargs):
    '''
    Postpone a job in the minion's schedule

    Current time and new time should be in date string format,
    default value is %Y-%m-%dT%H:%M:%S.

    .. versionadded:: 2018.3.0

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.postpone_job job current_time new_time

        salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S'
    '''

    time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S'
    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False
        return ret

    if not current_time:
        ret['comment'] = 'Job current time is required.'
        ret['result'] = False
        return ret
    else:
        try:
            # Validate date string
            datetime.datetime.strptime(current_time, time_fmt)
        except (TypeError, ValueError):
            log.error('Date string could not be parsed: %s, %s',
                      new_time, time_fmt)

            ret['comment'] = 'Date string could not be parsed.'
            ret['result'] = False
            return ret

    if not new_time:
        ret['comment'] = 'Job new_time is required.'
        ret['result'] = False
        return ret
    else:
        try:
            # Validate date string
            datetime.datetime.strptime(new_time, time_fmt)
        except (TypeError, ValueError):
            log.error('Date string could not be parsed: %s, %s',
                      new_time, time_fmt)

            ret['comment'] = 'Date string could not be parsed.'
            ret['result'] = False
            return ret

    if 'test' in __opts__ and __opts__['test']:
        ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name)
    else:

        if name in list_(show_all=True, where='opts', return_yaml=False):
            event_data = {'name': name,
                          'time': current_time,
                          'new_time': new_time,
                          'time_fmt': time_fmt,
                          'func': 'postpone_job'}
        elif name in list_(show_all=True, where='pillar', return_yaml=False):
            event_data = {'name': name,
                          'time': current_time,
                          'new_time': new_time,
                          'time_fmt': time_fmt,
                          'where': 'pillar',
                          'func': 'postpone_job'}
        else:
            ret['comment'] = 'Job {0} does not exist.'.format(name)
            ret['result'] = False
            return ret

        try:
            eventer = salt.utils.event.get_event('minion', opts=__opts__)
            res = __salt__['event.fire'](event_data, 'manage_schedule')
            if res:
                event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30)
                if event_ret and event_ret['complete']:
                    schedule = event_ret['schedule']
                    # check item exists in schedule and is enabled
                    if name in schedule and schedule[name]['enabled']:
                        ret['result'] = True
                        ret['comment'] = 'Postponed Job {0} in schedule.'.format(name)
                    else:
                        ret['result'] = False
                        ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name)
                    return ret
        except KeyError:
            # Effectively a no-op, since we can't really return without an event system
            ret['comment'] = 'Event module not available. Schedule postpone job failed.'
    return ret


Instruction:
Given the following Python 3 function, write the documentation
def is_proxy():
    '''
    Return True if this minion is a proxy minion.
    Leverages the fact that is_linux() and is_windows
    both return False for proxies.
    TODO: Need to extend this for proxies that might run on
    other Unices
    '''
    import __main__ as main
    # This is a hack.  If a proxy minion is started by other
    # means, e.g. a custom script that creates the minion objects
    # then this will fail.
    ret = False
    try:
        # Changed this from 'salt-proxy in main...' to 'proxy in main...'
        # to support the testsuite's temp script that is called 'cli_salt_proxy'
        #
        # Add '--proxyid' in sys.argv so that salt-call --proxyid
        # is seen as a proxy minion
        if 'proxy' in main.__file__ or '--proxyid' in sys.argv:
            ret = True
    except AttributeError:
        pass
    return ret

Response: Return True if this minion is a proxy minion.


Instruction:
Write a Python 3 script to
function to return if host is SmartOS global zone or not

Response:
def is_smartos_globalzone():
    '''
    Function to return if host is SmartOS (Illumos) global zone or not
    '''
    if not is_smartos():
        return False
    else:
        cmd = ['zonename']
        try:
            zonename = subprocess.Popen(
                cmd, shell=False,
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except OSError:
            return False
        if zonename.returncode:
            return False
        if zonename.stdout.read().strip() == 'global':
            return True

        return False


Instruction:
Write a Python 3 function that can
create a new image for a specific platform and root.

Response:
def bootstrap(
        platform,
        root,
        img_format='dir',
        fs_format='ext2',
        fs_opts=None,
        arch=None,
        flavor=None,
        repo_url=None,
        static_qemu=None,
        img_size=None,
        mount_dir=None,
        pkg_cache=None,
        pkgs=None,
        exclude_pkgs=None,
        epel_url=EPEL_URL,
    ):
    '''
    Create an image for a specific platform.

    Please note that this function *MUST* be run as root, as images that are
    created make files belonging to root.

    platform
        Which platform to use to create the image. Currently supported platforms
        are rpm, deb and pacman.

    root
        Local path to create the root of the image filesystem.

    img_format
        Which format to create the image in. By default, just copies files into
        a directory on the local filesystem (``dir``). Future support will exist
        for ``sparse``.

    fs_format
        When using a non-``dir`` ``img_format``, which filesystem to format the
        image to. By default, ``ext2``.

    fs_opts
        When using a non-``dir`` ``img_format``, a dict of opts may be
        specified.

    arch
        Architecture to install packages for, if supported by the underlying
        bootstrap tool. Currently only used for deb.

    flavor
        Which flavor of operating system to install. This correlates to a
        specific directory on the distribution repositories. For instance,
        ``wheezy`` on Debian.

    repo_url
        Mainly important for Debian-based repos. Base URL for the mirror to
        install from. (e.x.: http://ftp.debian.org/debian/)

    static_qemu
        Local path to the static qemu binary required for this arch.
        (e.x.: /usr/bin/qemu-amd64-static)

    pkg_confs
        The location of the conf files to copy into the image, to point the
        installer to the right repos and configuration.

    img_size
        If img_format is not ``dir``, then the size of the image must be
        specified.

    mount_dir
        If img_format is not ``dir``, then the image must be mounted somewhere.
        If the ``mount_dir`` is not specified, then it will be created at
        ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted
        and removed when the process is finished.

    pkg_cache
        This points to a directory containing a cache of package files to be
        copied to the image. It does not need to be specified.

    pkgs
        A list of packages to be installed on this image. For RedHat, this
        will include ``yum``, ``centos-release`` and ``iputils`` by default.

    exclude_pkgs
        A list of packages to be excluded. If you do not want to install the
        defaults, you need to include them in this list.

    epel_url
        The URL to download the EPEL release package from.

    CLI Examples:

    .. code-block:: bash

        salt myminion genesis.bootstrap pacman /root/arch
        salt myminion genesis.bootstrap rpm /root/redhat
        salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \
            flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static

    '''
    if img_format not in ('dir', 'sparse'):
        raise SaltInvocationError('The img_format must be "sparse" or "dir"')

    if img_format == 'dir':
        # We can just use the root as the root
        if not __salt__['file.directory_exists'](root):
            try:
                __salt__['file.mkdir'](root)
            except Exception as exc:
                return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))}
    elif img_format == 'sparse':
        if not img_size:
            raise SaltInvocationError('An img_size must be specified for a sparse file')
        if not mount_dir:
            mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4())
        __salt__['file.mkdir'](mount_dir, 'root', 'root', '755')
        __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False)
        _mkpart(root, fs_format, fs_opts, mount_dir)

        loop1 = __salt__['cmd.run']('losetup -f')
        log.debug('First loop device is %s', loop1)
        __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root))
        loop2 = __salt__['cmd.run']('losetup -f')
        log.debug('Second loop device is %s', loop2)
        start = six.text_type(2048 * 2048)
        __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1))
        __salt__['mount.mount'](mount_dir, loop2)

        _populate_cache(platform, pkg_cache, mount_dir)

    if mount_dir:
        root = mount_dir

    if pkgs is None:
        pkgs = []

    if exclude_pkgs is None:
        exclude_pkgs = []

    if platform in ('rpm', 'yum'):
        _bootstrap_yum(
            root,
            pkgs=pkgs,
            exclude_pkgs=exclude_pkgs,
            epel_url=epel_url,
        )
    elif platform == 'deb':
        _bootstrap_deb(
            root,
            arch=arch,
            flavor=flavor,
            repo_url=repo_url,
            static_qemu=static_qemu,
            pkgs=pkgs,
            exclude_pkgs=exclude_pkgs,
        )
    elif platform == 'pacman':
        _bootstrap_pacman(
            root,
            img_format=img_format,
            pkgs=pkgs,
            exclude_pkgs=exclude_pkgs,
        )

    if img_format != 'dir':
        blkinfo = __salt__['disk.blkid'](loop2)
        __salt__['file.replace'](
            '{0}/boot/grub/grub.cfg'.format(mount_dir),
            'ad4103fa-d940-47ca-8506-301d8071d467',  # This seems to be the default
            blkinfo[loop2]['UUID']
        )
        __salt__['mount.umount'](root)
        __salt__['cmd.run']('losetup -d {0}'.format(loop2))
        __salt__['cmd.run']('losetup -d {0}'.format(loop1))
        __salt__['file.rmdir'](mount_dir)


Instruction:
Here you have a function in Python 3, explain what it does
def _mkpart(root, fs_format, fs_opts, mount_dir):
    '''
    Make a partition, and make it bootable

    .. versionadded:: Beryllium
    '''
    __salt__['partition.mklabel'](root, 'msdos')
    loop1 = __salt__['cmd.run']('losetup -f')
    log.debug('First loop device is %s', loop1)
    __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root))
    part_info = __salt__['partition.list'](loop1)
    start = six.text_type(2048 * 2048) + 'B'
    end = part_info['info']['size']
    __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end)
    __salt__['partition.set'](loop1, '1', 'boot', 'on')
    part_info = __salt__['partition.list'](loop1)
    loop2 = __salt__['cmd.run']('losetup -f')
    log.debug('Second loop device is %s', loop2)
    start = start.rstrip('B')
    __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1))
    _mkfs(loop2, fs_format, fs_opts)
    __salt__['mount.mount'](mount_dir, loop2)
    __salt__['cmd.run']((
        'grub-install',
        '--target=i386-pc',
        '--debug',
        '--no-floppy',
        '--modules=part_msdos linux',
        '--boot-directory={0}/boot'.format(mount_dir),
        loop1
    ), python_shell=False)
    __salt__['mount.umount'](mount_dir)
    __salt__['cmd.run']('losetup -d {0}'.format(loop2))
    __salt__['cmd.run']('losetup -d {0}'.format(loop1))
    return part_info

Response: Make a partition and make it bootable


Instruction:
Here you have a function in Python 3, explain what it does
def _mkfs(root, fs_format, fs_opts=None):
    '''
    Make a filesystem using the appropriate module

    .. versionadded:: Beryllium
    '''
    if fs_opts is None:
        fs_opts = {}

    if fs_format in ('ext2', 'ext3', 'ext4'):
        __salt__['extfs.mkfs'](root, fs_format, **fs_opts)
    elif fs_format in ('btrfs',):
        __salt__['btrfs.mkfs'](root, **fs_opts)
    elif fs_format in ('xfs',):
        __salt__['xfs.mkfs'](root, **fs_opts)

Response: Make a filesystem using the appropriate module


Instruction:
Can you tell what is the following Python 3 function doing
def _populate_cache(platform, pkg_cache, mount_dir):
    '''
    If a ``pkg_cache`` directory is specified, then use it to populate the
    disk image.
    '''
    if not pkg_cache:
        return
    if not os.path.isdir(pkg_cache):
        return

    if platform == 'pacman':
        cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir)

    __salt__['file.mkdir'](cache_dir, 'root', 'root', '755')
    __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True)

Response: Populate the cache with the contents of pkg_cache.


Instruction:
Write a Python 3 script for
bootstrapping an image using the yum tools

Response:
def _bootstrap_yum(
        root,
        pkg_confs='/etc/yum*',
        pkgs=None,
        exclude_pkgs=None,
        epel_url=EPEL_URL,
    ):
    '''
    Bootstrap an image using the yum tools

    root
        The root of the image to install to. Will be created as a directory if
        it does not exist. (e.x.: /root/arch)

    pkg_confs
        The location of the conf files to copy into the image, to point yum
        to the right repos and configuration.

    pkgs
        A list of packages to be installed on this image. For RedHat, this
        will include ``yum``, ``centos-release`` and ``iputils`` by default.

    exclude_pkgs
        A list of packages to be excluded. If you do not want to install the
        defaults, you need to include them in this list.

    epel_url
        The URL to download the EPEL release package from.

    TODO: Set up a pre-install overlay, to copy files into /etc/ and so on,
        which are required for the install to work.
    '''
    if pkgs is None:
        pkgs = []
    elif isinstance(pkgs, six.string_types):
        pkgs = pkgs.split(',')

    default_pkgs = ('yum', 'centos-release', 'iputils')
    for pkg in default_pkgs:
        if pkg not in pkgs:
            pkgs.append(pkg)

    if exclude_pkgs is None:
        exclude_pkgs = []
    elif isinstance(exclude_pkgs, six.string_types):
        exclude_pkgs = exclude_pkgs.split(',')

    for pkg in exclude_pkgs:
        pkgs.remove(pkg)

    _make_nodes(root)
    release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')]
    __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files)))
    __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files)))
    __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs)))

    yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs
    __salt__['cmd.run'](yum_args, python_shell=False)

    if 'epel-release' not in exclude_pkgs:
        __salt__['cmd.run'](
            ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url),
            python_shell=False
        )


Instruction:
Write a Python 3 function for
bootstrapping an image using the Debian tools.

Response:
def _bootstrap_deb(
        root,
        arch,
        flavor,
        repo_url=None,
        static_qemu=None,
        pkgs=None,
        exclude_pkgs=None,
    ):
    '''
    Bootstrap an image using the Debian tools

    root
        The root of the image to install to. Will be created as a directory if
        it does not exist. (e.x.: /root/wheezy)

    arch
        Architecture of the target image. (e.x.: amd64)

    flavor
        Flavor of Debian to install. (e.x.: wheezy)

    repo_url
        Base URL for the mirror to install from.
        (e.x.: http://ftp.debian.org/debian/)

    static_qemu
        Local path to the static qemu binary required for this arch.
        (e.x.: /usr/bin/qemu-amd64-static)

    pkgs
        A list of packages to be installed on this image.

    exclude_pkgs
        A list of packages to be excluded.
    '''

    if repo_url is None:
        repo_url = 'http://ftp.debian.org/debian/'

    if not salt.utils.path.which('debootstrap'):
        log.error('Required tool debootstrap is not installed.')
        return False

    if static_qemu and not salt.utils.validate.path.is_executable(static_qemu):
        log.error('Required tool qemu not present/readable at: %s', static_qemu)
        return False

    if isinstance(pkgs, (list, tuple)):
        pkgs = ','.join(pkgs)
    if isinstance(exclude_pkgs, (list, tuple)):
        exclude_pkgs = ','.join(exclude_pkgs)

    deb_args = [
        'debootstrap',
        '--foreign',
        '--arch',
        _cmd_quote(arch)]

    if pkgs:
        deb_args += ['--include', _cmd_quote(pkgs)]
    if exclude_pkgs:
        deb_args += ['--exclude', _cmd_quote(exclude_pkgs)]

    deb_args += [
        _cmd_quote(flavor),
        _cmd_quote(root),
        _cmd_quote(repo_url),
    ]

    __salt__['cmd.run'](deb_args, python_shell=False)

    if static_qemu:
        __salt__['cmd.run'](
            'cp {qemu} {root}/usr/bin/'.format(
                qemu=_cmd_quote(static_qemu), root=_cmd_quote(root)
            )
        )

    env = {'DEBIAN_FRONTEND': 'noninteractive',
           'DEBCONF_NONINTERACTIVE_SEEN': 'true',
           'LC_ALL': 'C',
           'LANGUAGE': 'C',
           'LANG': 'C',
           'PATH': '/sbin:/bin:/usr/bin'}
    __salt__['cmd.run'](
        'chroot {root} /debootstrap/debootstrap --second-stage'.format(
            root=_cmd_quote(root)
        ),
        env=env
    )
    __salt__['cmd.run'](
        'chroot {root} dpkg --configure -a'.format(
            root=_cmd_quote(root)
        ),
        env=env
    )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _bootstrap_pacman(
        root,
        pkg_confs='/etc/pacman*',
        img_format='dir',
        pkgs=None,
        exclude_pkgs=None,
    ):
    '''
    Bootstrap an image using the pacman tools

    root
        The root of the image to install to. Will be created as a directory if
        it does not exist. (e.x.: /root/arch)

    pkg_confs
        The location of the conf files to copy into the image, to point pacman
        to the right repos and configuration.

    img_format
        The image format to be used. The ``dir`` type needs no special
        treatment, but others need special treatment.

    pkgs
        A list of packages to be installed on this image. For Arch Linux, this
        will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat``
        by default.

    exclude_pkgs
        A list of packages to be excluded. If you do not want to install the
        defaults, you need to include them in this list.
    '''
    _make_nodes(root)

    if pkgs is None:
        pkgs = []
    elif isinstance(pkgs, six.string_types):
        pkgs = pkgs.split(',')

    default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub')
    for pkg in default_pkgs:
        if pkg not in pkgs:
            pkgs.append(pkg)

    if exclude_pkgs is None:
        exclude_pkgs = []
    elif isinstance(exclude_pkgs, six.string_types):
        exclude_pkgs = exclude_pkgs.split(',')

    for pkg in exclude_pkgs:
        pkgs.remove(pkg)

    if img_format != 'dir':
        __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind')
        __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind')

    __salt__['file.mkdir'](
        '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755'
    )
    pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')]
    for pac_file in pac_files:
        __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root)))
    __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True)

    pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs
    __salt__['cmd.run'](pacman_args, python_shell=False)

    if img_format != 'dir':
        __salt__['mount.umount']('{0}/proc'.format(root))
        __salt__['mount.umount']('{0}/dev'.format(root))

Response: Bootstrap an image using pacman tools


Instruction:
Given the following Python 3 function, write the documentation
def _make_nodes(root):
    '''
    Make the minimum number of nodes inside of /dev/. Based on:

    https://wiki.archlinux.org/index.php/Linux_Containers
    '''
    dirs = (
        ('{0}/etc'.format(root), 'root', 'root', '755'),
        ('{0}/dev'.format(root), 'root', 'root', '755'),
        ('{0}/proc'.format(root), 'root', 'root', '755'),
        ('{0}/dev/pts'.format(root), 'root', 'root', '755'),
        ('{0}/dev/shm'.format(root), 'root', 'root', '1755'),
    )

    nodes = (
        ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'),
        ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'),
        ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'),
        ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'),
        ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'),
        ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'),
        ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'),
        ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'),
        ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'),
        ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'),
    )

    for path in dirs:
        __salt__['file.mkdir'](*path)

    for path in nodes:
        __salt__['file.mknod'](*path)

Response: Make the minimum number of nodes inside of the Linux containers.


Instruction:
Can you generate the documentation for the following Python 3 function
def avail_platforms():
    '''
    Return which platforms are available

    CLI Example:

    .. code-block:: bash

        salt myminion genesis.avail_platforms
    '''
    ret = {}
    for platform in CMD_MAP:
        ret[platform] = True
        for cmd in CMD_MAP[platform]:
            if not salt.utils.path.which(cmd):
                ret[platform] = False
    return ret

Response: Return which platforms are available


Instruction:
Write a Python 3 script for
packing up a directory structure into a specific format

Response:
def pack(name, root, path=None, pack_format='tar', compress='bzip2'):
    '''
    Pack up a directory structure, into a specific format

    CLI Examples:

    .. code-block:: bash

        salt myminion genesis.pack centos /root/centos
        salt myminion genesis.pack centos /root/centos pack_format='tar'
    '''
    if pack_format == 'tar':
        _tar(name, root, path, compress)


Instruction:
Make a summary of the following Python 3 code
def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'):
    '''
    Unpack an image into a directory structure

    CLI Example:

    .. code-block:: bash

        salt myminion genesis.unpack centos /root/centos
    '''
    if pack_format == 'tar':
        _untar(name, dest, path, compress)

Response: Unpack an image into a directory structure


Instruction:
Create a Python 3 function to
pack up a single image in a tar format

Response:
def _tar(name, root, path=None, compress='bzip2'):
    '''
    Pack up image in a tar format
    '''
    if path is None:
        path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img')
    if not __salt__['file.directory_exists'](path):
        try:
            __salt__['file.mkdir'](path)
        except Exception as exc:
            return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))}

    compression, ext = _compress(compress)

    tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext)
    out = __salt__['archive.tar'](
        options='{0}pcf'.format(compression),
        tarfile=tarfile,
        sources='.',
        dest=root,
    )


Instruction:
Make a summary of the following Python 3 code
def mksls(fmt, src, dst=None):
    '''
    Convert an installation file/script to an SLS file. Currently supports
    ``kickstart``, ``preseed``, and ``autoyast``.

    CLI Examples:

        salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg
        salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls

    .. versionadded:: Beryllium
    '''
    if fmt == 'kickstart':
        return salt.utils.kickstart.mksls(src, dst)
    elif fmt == 'preseed':
        return salt.utils.preseed.mksls(src, dst)
    elif fmt == 'autoyast':
        return salt.utils.yast.mksls(src, dst)

Response:
Convert an installation file or script to an SLS file. Currently supports
    kickstart preseed and autoyast.


Instruction:
Create a Python 3 function for
executing the desired powershell command and ensure that it returns data in json format and load that into python

Response:
def _pshell(cmd, cwd=None, json_depth=2):
    '''
    Execute the desired powershell command and ensure that it returns data
    in json format and load that into python
    '''
    if 'convertto-json' not in cmd.lower():
        cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)
    log.debug('DSC: %s', cmd)
    results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)

    if 'pid' in results:
        del results['pid']

    if 'retcode' not in results or results['retcode'] != 0:
        # run_all logs an error to log.error, fail hard back to the user
        raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)

    try:
        ret = salt.utils.json.loads(results['stdout'], strict=False)
    except ValueError:
        raise CommandExecutionError('No JSON results from powershell', info=results)

    return ret


Instruction:
How would you explain what the following Python 3 function does
def avail_modules(desc=False):
    '''
    List available modules in registered Powershell module repositories.

    :param desc: If ``True``, the verbose description will be returned.
    :type  desc: ``bool``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.avail_modules
        salt 'win01' psget.avail_modules desc=True
    '''
    cmd = 'Find-Module'
    modules = _pshell(cmd)
    names = []
    if desc:
        names = {}
    for module in modules:
        if desc:
            names[module['Name']] = module['Description']
            continue
        names.append(module['Name'])
    return names

Response: Return a list of available Powershell modules.


Instruction:
Make a summary of the following Python 3 code
def list_modules(desc=False):
    '''
    List currently installed PSGet Modules on the system.

    :param desc: If ``True``, the verbose description will be returned.
    :type  desc: ``bool``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.list_modules
        salt 'win01' psget.list_modules desc=True
    '''
    cmd = 'Get-InstalledModule'
    modules = _pshell(cmd)
    if isinstance(modules, dict):
        ret = []
        if desc:
            modules_ret = {}
            modules_ret[modules['Name']] = copy.deepcopy(modules)
            modules = modules_ret
            return modules
        ret.append(modules['Name'])
        return ret
    names = []
    if desc:
        names = {}
    for module in modules:
        if desc:
            names[module['Name']] = module
            continue
        names.append(module['Name'])
    return names

Response: List currently installed PSGet Modules on the system.


Instruction:
Implement a Python 3 function for
installing a Powershell module from powershell gallery on the system.

Response:
def install(name, minimum_version=None, required_version=None, scope=None,
            repository=None):
    '''
    Install a Powershell module from powershell gallery on the system.

    :param name: Name of a Powershell module
    :type  name: ``str``

    :param minimum_version: The maximum version to install, e.g. 1.23.2
    :type  minimum_version: ``str``

    :param required_version: Install a specific version
    :type  required_version: ``str``

    :param scope: The scope to install the module to, e.g. CurrentUser, Computer
    :type  scope: ``str``

    :param repository: The friendly name of a private repository, e.g. MyREpo
    :type  repository: ``str``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.install PowerPlan
    '''
    # Putting quotes around the parameter protects against command injection
    flags = [('Name', name)]

    if minimum_version is not None:
        flags.append(('MinimumVersion', minimum_version))
    if required_version is not None:
        flags.append(('RequiredVersion', required_version))
    if scope is not None:
        flags.append(('Scope', scope))
    if repository is not None:
        flags.append(('Repository', repository))
    params = ''
    for flag, value in flags:
        params += '-{0} {1} '.format(flag, value)
    cmd = 'Install-Module {0} -Force'.format(params)
    _pshell(cmd)
    return name in list_modules()


Instruction:
Write a Python 3 script for
updating a Powershell module with a specific version or the newest one.

Response:
def update(name, maximum_version=None, required_version=None):
    '''
    Update a PowerShell module to a specific version, or the newest

    :param name: Name of a Powershell module
    :type  name: ``str``

    :param maximum_version: The maximum version to install, e.g. 1.23.2
    :type  maximum_version: ``str``

    :param required_version: Install a specific version
    :type  required_version: ``str``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.update PowerPlan
    '''
    # Putting quotes around the parameter protects against command injection
    flags = [('Name', name)]

    if maximum_version is not None:
        flags.append(('MaximumVersion', maximum_version))
    if required_version is not None:
        flags.append(('RequiredVersion', required_version))

    params = ''
    for flag, value in flags:
        params += '-{0} {1} '.format(flag, value)
    cmd = 'Update-Module {0} -Force'.format(params)
    _pshell(cmd)
    return name in list_modules()


Instruction:
Can you generate the documentation for the following Python 3 function
def remove(name):
    '''
    Remove a Powershell DSC module from the system.

    :param  name: Name of a Powershell DSC module
    :type   name: ``str``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.remove PowerPlan
    '''
    # Putting quotes around the parameter protects against command injection
    cmd = 'Uninstall-Module "{0}"'.format(name)
    no_ret = _pshell(cmd)
    return name not in list_modules()

Response: Remove a Powershell DSC module from the system.


Instruction:
Create a Python 3 function for
registering a PSGet repository on the local machine

Response:
def register_repository(name, location, installation_policy=None):
    '''
    Register a PSGet repository on the local machine

    :param name: The name for the repository
    :type  name: ``str``

    :param location: The URI for the repository
    :type  location: ``str``

    :param installation_policy: The installation policy
        for packages, e.g. Trusted, Untrusted
    :type  installation_policy: ``str``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages
    '''
    # Putting quotes around the parameter protects against command injection
    flags = [('Name', name)]

    flags.append(('SourceLocation', location))
    if installation_policy is not None:
        flags.append(('InstallationPolicy', installation_policy))

    params = ''
    for flag, value in flags:
        params += '-{0} {1} '.format(flag, value)
    cmd = 'Register-PSRepository {0}'.format(params)
    no_ret = _pshell(cmd)
    return name not in list_modules()


Instruction:
Make a summary of the following Python 3 code
def get_repository(name):
    '''
    Get the details of a local PSGet repository

    :param  name: Name of the repository
    :type   name: ``str``

    CLI Example:

    .. code-block:: bash

        salt 'win01' psget.get_repository MyRepo
    '''
    # Putting quotes around the parameter protects against command injection
    cmd = 'Get-PSRepository "{0}"'.format(name)
    no_ret = _pshell(cmd)
    return name not in list_modules()

Response: Get the details of a local PSGet repository


Instruction:
Can you write a function in Python 3 where it
creates a new container with the specified parameters.

Response:
def present(name,
            running=None,
            clone_from=None,
            snapshot=False,
            profile=None,
            network_profile=None,
            template=None,
            options=None,
            image=None,
            config=None,
            fstype=None,
            size=None,
            backing=None,
            vgname=None,
            lvname=None,
            thinpool=None,
            path=None):
    '''
    .. versionchanged:: 2015.8.0

        The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed
        to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>`
        state has been merged into this state.

    Create the named container if it does not exist

    name
        The name of the container to be created

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0

    running : False
        * If ``True``, ensure that the container is running
        * If ``False``, ensure that the container is stopped
        * If ``None``, do nothing with regards to the running state of the
          container

        .. versionadded:: 2015.8.0

    clone_from
        Create named container as a clone of the specified container

    snapshot : False
        Use Copy On Write snapshots (LVM). Only supported with ``clone_from``.

    profile
        Profile to use in container creation (see the :ref:`LXC Tutorial
        <tutorial-lxc-profiles-container>` for more information). Values in a
        profile will be overridden by the parameters listed below.

    network_profile
        Network Profile to use in container creation
        (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>`
        for more information). Values in a profile will be overridden by
        the parameters listed below.

        .. versionadded:: 2015.5.2

    **Container Creation Arguments**

    template
        The template to use. For example, ``ubuntu`` or ``fedora``.
        For a full list of available templates, check out
        the :mod:`lxc.templates <salt.modules.lxc.templates>` function.

        Conflicts with the ``image`` argument.

        .. note::

            The ``download`` template requires the following three parameters
            to be defined in ``options``:

            * **dist** - The name of the distribution
            * **release** - Release name/version
            * **arch** - Architecture of the container

            The available images can be listed using the :mod:`lxc.images
            <salt.modules.lxc.images>` function.

    options

        .. versionadded:: 2015.5.0

        Template-specific options to pass to the lxc-create command. These
        correspond to the long options (ones beginning with two dashes) that
        the template script accepts. For example:

        .. code-block:: yaml

            web01:
              lxc.present:
                - template: download
                - options:
                    dist: centos
                    release: 6
                    arch: amd64

        Remember to double-indent the options, due to :ref:`how PyYAML works
        <nested-dict-indentation>`.

        For available template options, refer to the lxc template scripts
        which are ususally located under ``/usr/share/lxc/templates``,
        or run ``lxc-create -t <template> -h``.

    image
        A tar archive to use as the rootfs for the container. Conflicts with
        the ``template`` argument.

    backing
        The type of storage to use. Set to ``lvm`` to use an LVM group.
        Defaults to filesystem within /var/lib/lxc.

    fstype
        Filesystem type to use on LVM logical volume

    size
        Size of the volume to create. Only applicable if ``backing`` is set to
        ``lvm``.

    vgname : lxc
        Name of the LVM volume group in which to create the volume for this
        container. Only applicable if ``backing`` is set to ``lvm``.

    lvname
        Name of the LVM logical volume in which to create the volume for this
        container. Only applicable if ``backing`` is set to ``lvm``.

    thinpool
        Name of a pool volume that will be used for thin-provisioning this
        container. Only applicable if ``backing`` is set to ``lvm``.
    '''
    ret = {'name': name,
           'result': True,
           'comment': 'Container \'{0}\' already exists'.format(name),
           'changes': {}}

    if not any((template, image, clone_from)):
        # Take a peek into the profile to see if there is a clone source there.
        # Otherwise, we're assuming this is a template/image creation. Also
        # check to see if none of the create types are in the profile. If this
        # is the case, then bail out early.
        c_profile = __salt__['lxc.get_container_profile'](profile)
        if not any(x for x in c_profile
                   if x in ('template', 'image', 'clone_from')):
            ret['result'] = False
            ret['comment'] = ('No template, image, or clone_from parameter '
                              'was found in either the state\'s arguments or '
                              'the LXC profile')
        else:
            try:
                # Assign the profile's clone_from param to the state, so that
                # we know to invoke lxc.clone to create the container.
                clone_from = c_profile['clone_from']
            except KeyError:
                pass

    # Sanity check(s)
    if clone_from and not __salt__['lxc.exists'](clone_from, path=path):
        ret['result'] = False
        ret['comment'] = ('Clone source \'{0}\' does not exist'
                          .format(clone_from))
    if not ret['result']:
        return ret

    action = 'cloned from {0}'.format(clone_from) if clone_from else 'created'

    state = {'old': __salt__['lxc.state'](name, path=path)}
    if __opts__['test']:
        if state['old'] is None:
            ret['comment'] = (
                'Container \'{0}\' will be {1}'.format(
                    name,
                    'cloned from {0}'.format(clone_from) if clone_from
                    else 'created')
            )
            ret['result'] = None
            return ret
        else:
            if running is None:
                # Container exists and we're not managing whether or not it's
                # running. Set the result back to True and return
                return ret
            elif running:
                if state['old'] in ('frozen', 'stopped'):
                    ret['comment'] = (
                        'Container \'{0}\' would be {1}'.format(
                            name,
                            'unfrozen' if state['old'] == 'frozen'
                                else 'started'
                        )
                    )
                    ret['result'] = None
                    return ret
                else:
                    ret['comment'] += ' and is running'
                    return ret
            else:
                if state['old'] in ('frozen', 'running'):
                    ret['comment'] = (
                        'Container \'{0}\' would be stopped'.format(name)
                    )
                    ret['result'] = None
                    return ret
                else:
                    ret['comment'] += ' and is stopped'
                    return ret

    if state['old'] is None:
        # Container does not exist
        try:
            if clone_from:
                result = __salt__['lxc.clone'](name,
                                               clone_from,
                                               profile=profile,
                                               network_profile=network_profile,
                                               snapshot=snapshot,
                                               size=size,
                                               path=path,
                                               backing=backing)
            else:
                result = __salt__['lxc.create'](
                    name,
                    profile=profile,
                    network_profile=network_profile,
                    template=template,
                    options=options,
                    image=image,
                    config=config,
                    fstype=fstype,
                    size=size,
                    backing=backing,
                    vgname=vgname,
                    path=path,
                    lvname=lvname,
                    thinpool=thinpool)
        except (CommandExecutionError, SaltInvocationError) as exc:
            ret['result'] = False
            ret['comment'] = exc.strerror
        else:
            if clone_from:
                ret['comment'] = ('Cloned container \'{0}\' as \'{1}\''
                                  .format(clone_from, name))
            else:
                ret['comment'] = 'Created container \'{0}\''.format(name)
            state['new'] = result['state']['new']

    if ret['result'] is True:
        # Enforce the "running" parameter
        if running is None:
            # Don't do anything
            pass
        elif running:
            c_state = __salt__['lxc.state'](name, path=path)
            if c_state == 'running':
                ret['comment'] += ' and is running'
            else:
                error = ', but it could not be started'
                try:
                    start_func = 'lxc.unfreeze' if c_state == 'frozen' \
                        else 'lxc.start'
                    state['new'] = __salt__[start_func](
                        name, path=path
                    )['state']['new']
                    if state['new'] != 'running':
                        ret['result'] = False
                        ret['comment'] += error
                except (SaltInvocationError, CommandExecutionError) as exc:
                    ret['result'] = False
                    ret['comment'] += '{0}: {1}'.format(error, exc)
                else:
                    if state['old'] is None:
                        ret['comment'] += ', and the container was started'
                    else:
                        ret['comment'] = (
                            'Container \'{0}\' was {1}'.format(
                                name,
                                'unfrozen' if state['old'] == 'frozen'
                                    else 'started'
                            )
                        )

        else:
            c_state = __salt__['lxc.state'](name, path=path)
            if c_state == 'stopped':
                if state['old'] is not None:
                    ret['comment'] += ' and is stopped'
            else:
                error = ', but it could not be stopped'
                try:
                    state['new'] = __salt__['lxc.stop'](
                        name, path=path
                    )['state']['new']
                    if state['new'] != 'stopped':
                        ret['result'] = False
                        ret['comment'] += error
                except (SaltInvocationError, CommandExecutionError) as exc:
                    ret['result'] = False
                    ret['comment'] += '{0}: {1}'.format(error, exc)
                else:
                    if state['old'] is None:
                        ret['comment'] += ', and the container was stopped'
                    else:
                        ret['comment'] = ('Container \'{0}\' was stopped'
                                          .format(name))

    if 'new' not in state:
        # Make sure we know the final state of the container before we return
        state['new'] = __salt__['lxc.state'](name, path=path)
    if state['old'] != state['new']:
        ret['changes']['state'] = state
    return ret


Instruction:
Here you have a function in Python 3, explain what it does
def absent(name, stop=False, path=None):
    '''
    Ensure a container is not present, destroying it if present

    name
        Name of the container to destroy

    stop
        stop before destroying
        default: false

        .. versionadded:: 2015.5.2

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0

    .. code-block:: yaml

        web01:
          lxc.absent
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': 'Container \'{0}\' does not exist'.format(name)}

    if not __salt__['lxc.exists'](name, path=path):
        return ret

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Container \'{0}\' would be destroyed'.format(name)
        return ret

    try:
        result = __salt__['lxc.destroy'](name, stop=stop, path=path)
    except (SaltInvocationError, CommandExecutionError) as exc:
        ret['result'] = False
        ret['comment'] = 'Failed to destroy container: {0}'.format(exc)
    else:
        ret['changes']['state'] = result['state']
        ret['comment'] = 'Container \'{0}\' was destroyed'.format(name)
    return ret

Response: Ensure a container is absent destroying it if present


Instruction:
Can you implement a function in Python 3 that
ensures that a named container is running.

Response:
def running(name, restart=False, path=None):
    '''
    .. versionchanged:: 2015.5.0
        The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed
        to ``lxc.running``

    Ensure that a container is running

    .. note::

        This state does not enforce the existence of the named container, it
        just starts the container if it is not running. To ensure that the
        named container exists, use :mod:`lxc.present
        <salt.states.lxc.present>`.

    name
        The name of the container

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0

    restart : False
        Restart container if it is already running

    .. code-block:: yaml

        web01:
          lxc.running

        web02:
          lxc.running:
            - restart: True
    '''
    ret = {'name': name,
           'result': True,
           'comment': 'Container \'{0}\' is already running'.format(name),
           'changes': {}}

    state = {'old': __salt__['lxc.state'](name, path=path)}
    if state['old'] is None:
        ret['result'] = False
        ret['comment'] = 'Container \'{0}\' does not exist'.format(name)
        return ret
    elif state['old'] == 'running' and not restart:
        return ret
    elif state['old'] == 'stopped' and restart:
        # No need to restart since container is not running
        restart = False

    if restart:
        if state['old'] != 'stopped':
            action = ('restart', 'restarted')
        else:
            action = ('start', 'started')
    else:
        if state['old'] == 'frozen':
            action = ('unfreeze', 'unfrozen')
        else:
            action = ('start', 'started')

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = ('Container \'{0}\' would be {1}'
                          .format(name, action[1]))
        return ret

    try:
        if state['old'] == 'frozen' and not restart:
            result = __salt__['lxc.unfreeze'](name, path=path)
        else:
            if restart:
                result = __salt__['lxc.restart'](name, path=path)
            else:
                result = __salt__['lxc.start'](name, path=path)
    except (CommandExecutionError, SaltInvocationError) as exc:
        ret['result'] = False
        ret['comment'] = exc.strerror
        state['new'] = __salt__['lxc.state'](name, path=path)
    else:
        state['new'] = result['state']['new']
        if state['new'] != 'running':
            ret['result'] = False
            ret['comment'] = ('Unable to {0} container \'{1}\''
                              .format(action[0], name))
        else:
            ret['comment'] = ('Container \'{0}\' was successfully {1}'
                              .format(name, action[1]))
        try:
            ret['changes']['restarted'] = result['restarted']
        except KeyError:
            pass

    if state['old'] != state['new']:
        ret['changes']['state'] = state
    return ret


Instruction:
How would you explain what the following Python 3 function does
def stopped(name, kill=False, path=None):
    '''
    Ensure that a container is stopped

    .. note::

        This state does not enforce the existence of the named container, it
        just stops the container if it running or frozen. To ensure that the
        named container exists, use :mod:`lxc.present
        <salt.states.lxc.present>`, or use the :mod:`lxc.absent
        <salt.states.lxc.absent>` state to ensure that the container does not
        exist.

    name
        The name of the container

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0

    kill : False
        Do not wait for the container to stop, kill all tasks in the container.
        Older LXC versions will stop containers like this irrespective of this
        argument.

        .. versionadded:: 2015.5.0

    .. code-block:: yaml

        web01:
          lxc.stopped
    '''
    ret = {'name': name,
           'result': True,
           'comment': 'Container \'{0}\' is already stopped'.format(name),
           'changes': {}}

    state = {'old': __salt__['lxc.state'](name, path=path)}
    if state['old'] is None:
        ret['result'] = False
        ret['comment'] = 'Container \'{0}\' does not exist'.format(name)
        return ret
    elif state['old'] == 'stopped':
        return ret

    if kill:
        action = ('force-stop', 'force-stopped')
    else:
        action = ('stop', 'stopped')

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = ('Container \'{0}\' would be {1}'
                          .format(name, action[1]))
        return ret

    try:
        result = __salt__['lxc.stop'](name, kill=kill, path=path)
    except (CommandExecutionError, SaltInvocationError) as exc:
        ret['result'] = False
        ret['comment'] = exc.strerror
        state['new'] = __salt__['lxc.state'](name, path=path)
    else:
        state['new'] = result['state']['new']
        if state['new'] != 'stopped':
            ret['result'] = False
            ret['comment'] = ('Unable to {0} container \'{1}\''
                              .format(action[0], name))
        else:
            ret['comment'] = ('Container \'{0}\' was successfully {1}'
                              .format(name, action[1]))

    if state['old'] != state['new']:
        ret['changes']['state'] = state
    return ret

Response: Ensure that a named container is stopped.


Instruction:
Explain what the following Python 3 code does
def edited_conf(name, lxc_conf=None, lxc_conf_unset=None):
    '''
    .. warning::

        This state is unsuitable for setting parameters that appear more than
        once in an LXC config file, or parameters which must appear in a
        certain order (such as when configuring more than one network
        interface).

        `Issue #35523`_ was opened to track the addition of a suitable replacement
        or fix.

    Edit LXC configuration options

    .. deprecated:: 2015.5.0

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0

    .. code-block:: bash

        setconf:
          lxc.edited_conf:
            - name: ubuntu
            - lxc_conf:
                - network.ipv4.ip: 10.0.3.6
            - lxc_conf_unset:
                - lxc.utsname

    .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523

    '''
    if __opts__['test']:
        return {'name': name,
                'comment': '{0} lxc.conf will be edited'.format(name),
                'result': True,
                'changes': {}}
    if not lxc_conf_unset:
        lxc_conf_unset = {}
    if not lxc_conf:
        lxc_conf = {}
    cret = __salt__['lxc.update_lxc_conf'](name,
                                           lxc_conf=lxc_conf,
                                           lxc_conf_unset=lxc_conf_unset)
    cret['name'] = name
    return cret

Response: Edit the LXC configuration file for a specific entry in a specific LXC container.


Instruction:
Explain what the following Python 3 code does
def generate(extra_mods='', overwrite=False, so_mods='',
             python2_bin='python2', python3_bin='python3', absonly=True,
             compress='gzip'):
    '''
    Generate the salt-thin tarball and print the location of the tarball
    Optional additional mods to include (e.g. mako) can be supplied as a comma
    delimited string.  Permits forcing an overwrite of the output file as well.

    CLI Example:

    .. code-block:: bash

        salt-run thin.generate
        salt-run thin.generate mako
        salt-run thin.generate mako,wempy 1
        salt-run thin.generate overwrite=1
    '''
    conf_mods = __opts__.get('thin_extra_mods')
    if conf_mods:
        extra_mods = ','.join([conf_mods, extra_mods])

    return salt.utils.thin.gen_thin(__opts__['cachedir'],
                                    extra_mods,
                                    overwrite,
                                    so_mods,
                                    python2_bin,
                                    python3_bin,
                                    absonly,
                                    compress)

Response: Generate a salt - thin tarball and print the location of the tarball.


Instruction:
Create a Python 3 function to
generate the salt - thin tarball and print the location of the tarball.

Response:
def generate_min(extra_mods='', overwrite=False, so_mods='',
             python2_bin='python2', python3_bin='python3'):
    '''
    Generate the salt-thin tarball and print the location of the tarball
    Optional additional mods to include (e.g. mako) can be supplied as a comma
    delimited string.  Permits forcing an overwrite of the output file as well.

    CLI Example:

    .. code-block:: bash

        salt-run thin.generate_min
    '''
    conf_mods = __opts__.get('min_extra_mods')
    if conf_mods:
        extra_mods = ','.join([conf_mods, extra_mods])

    return salt.utils.thin.gen_min(__opts__['cachedir'],
                                   extra_mods,
                                   overwrite,
                                   so_mods,
                                   python2_bin,
                                   python3_bin)


Instruction:
Given the following Python 3 function, write the documentation
def present(name, profile="github", **kwargs):
    '''
    Ensure a user is present

    .. code-block:: yaml

        ensure user test is present in github:
            github.present:
                - name: 'gitexample'

    The following parameters are required:

    name
        This is the github handle of the user in the organization
    '''

    ret = {
        'name': name,
        'changes': {},
        'result': None,
        'comment': ''
    }

    target = __salt__['github.get_user'](name, profile=profile, **kwargs)

    # If the user has a valid github handle and is not in the org already
    if not target:
        ret['result'] = False
        ret['comment'] = 'Couldnt find user {0}'.format(name)
    elif isinstance(target, bool) and target:
        ret['comment'] = 'User {0} is already in the org '.format(name)
        ret['result'] = True
    elif not target.get('in_org', False) and target.get('membership_state') != 'pending':
        if __opts__['test']:
            ret['comment'] = 'User {0} will be added to the org'.format(name)
            return ret

        # add the user
        result = __salt__['github.add_user'](
            name, profile=profile, **kwargs
        )

        if result:
            ret['changes'].setdefault('old', None)
            ret['changes'].setdefault('new', 'User {0} exists in the org now'.format(name))
            ret['result'] = True
        else:
            ret['result'] = False
            ret['comment'] = 'Failed to add user {0} to the org'.format(name)
    else:
        ret['comment'] = 'User {0} has already been invited.'.format(name)
        ret['result'] = True

    return ret

Response: Ensure a user is present in github


Instruction:
Here you have a function in Python 3, explain what it does
def absent(name, profile="github", **kwargs):
    '''
    Ensure a github user is absent

    .. code-block:: yaml

        ensure user test is absent in github:
            github.absent:
                - name: 'Example TestUser1'
                - email: example@domain.com
                - username: 'gitexample'

    The following parameters are required:

    name
        Github handle of the user in organization

    '''
    email = kwargs.get('email')
    full_name = kwargs.get('fullname')

    ret = {
        'name': name,
        'changes': {},
        'result': None,
        'comment': 'User {0} is absent.'.format(name)
    }

    target = __salt__['github.get_user'](name, profile=profile, **kwargs)

    if target:
        if isinstance(target, bool) or target.get('in_org', False):
            if __opts__['test']:
                ret['comment'] = "User {0} will be deleted".format(name)
                ret['result'] = None
                return ret

            result = __salt__['github.remove_user'](name, profile=profile, **kwargs)

            if result:
                ret['comment'] = 'Deleted user {0}'.format(name)
                ret['changes'].setdefault('old', 'User {0} exists'.format(name))
                ret['changes'].setdefault('new', 'User {0} deleted'.format(name))
                ret['result'] = True
            else:
                ret['comment'] = 'Failed to delete {0}'.format(name)
                ret['result'] = False
        else:
            ret['comment'] = "User {0} has already been deleted!".format(name)
            ret['result'] = True
    else:
        ret['comment'] = 'User {0} does not exist'.format(name)
        ret['result'] = True
        return ret

    return ret

Response: Ensure a github user is absent in github


Instruction:
Write a Python 3 script to
ensure a team is present in the github.

Response:
def team_present(
        name,
        description=None,
        repo_names=None,
        privacy='secret',
        permission='pull',
        members=None,
        enforce_mfa=False,
        no_mfa_grace_seconds=0,
        profile="github",
        **kwargs):
    '''
    Ensure a team is present

    name
        This is the name of the team in the organization.

    description
        The description of the team.

    repo_names
        The names of repositories to add the team to.

    privacy
        The level of privacy for the team, can be 'secret' or 'closed'. Defaults
        to secret.

    permission
        The default permission for new repositories added to the team, can be
        'pull', 'push' or 'admin'. Defaults to pull.

    members
        The members belonging to the team, specified as a dict of member name to
        optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'.

    enforce_mfa
        Whether to enforce MFA requirements on members of the team. If True then
        all members without `mfa_exempt: True` configured will be removed from
        the team. Note that `no_mfa_grace_seconds` may be set to allow members
        a grace period.

    no_mfa_grace_seconds
        The number of seconds of grace time that a member will have to enable MFA
        before being removed from the team. The grace period will begin from
        `enforce_mfa_from` on the member configuration, which defaults to
        1970/01/01.

    Example:

    .. code-block:: yaml

        Ensure team test is present in github:
            github.team_present:
                - name: 'test'
                - members:
                    user1: {}
                    user2: {}

        Ensure team test_mfa is present in github:
            github.team_present:
                - name: 'test_mfa'
                - members:
                    user1:
                        enforce_mfa_from: 2016/06/15
                - enforce_mfa: True

    .. versionadded:: 2016.11.0
    '''
    ret = {
        'name': name,
        'changes': {},
        'result': True,
        'comment': ''
    }

    target = __salt__['github.get_team'](name, profile=profile, **kwargs)
    test_comments = []

    if target:  # Team already exists
        parameters = {}
        if description is not None and target['description'] != description:
            parameters['description'] = description
        if permission is not None and target['permission'] != permission:
            parameters['permission'] = permission
        if privacy is not None and target['privacy'] != privacy:
            parameters['privacy'] = privacy

        if parameters:
            if __opts__['test']:
                test_comments.append('Team properties are set to be edited: {0}'
                                     .format(parameters))
                ret['result'] = None
            else:
                result = __salt__['github.edit_team'](name, profile=profile,
                                                      **parameters)
                if result:
                    ret['changes']['team'] = {
                        'old': 'Team properties were {0}'.format(target),
                        'new': 'Team properties (that changed) are {0}'.format(parameters)
                    }
                else:
                    ret['result'] = False
                    ret['comment'] = 'Failed to update team properties.'
                    return ret

        manage_repos = repo_names is not None
        current_repos = set(__salt__['github.list_team_repos'](name, profile=profile)
                            .keys())
        repo_names = set(repo_names or [])

        repos_to_add = repo_names - current_repos
        repos_to_remove = current_repos - repo_names if repo_names else []

        if repos_to_add:
            if __opts__['test']:
                test_comments.append('Team {0} will have the following repos '
                                     'added: {1}.'.format(name, list(repos_to_add)))
                ret['result'] = None
            else:
                for repo_name in repos_to_add:
                    result = (__salt__['github.add_team_repo']
                              (repo_name, name, profile=profile, **kwargs))
                    if result:
                        ret['changes'][repo_name] = {
                            'old': 'Repo {0} is not in team {1}'.format(repo_name, name),
                            'new': 'Repo {0} is in team {1}'.format(repo_name, name)
                        }
                    else:
                        ret['result'] = False
                        ret['comment'] = ('Failed to add repo {0} to team {1}.'
                                          .format(repo_name, name))
                        return ret

        if repos_to_remove:
            if __opts__['test']:
                test_comments.append('Team {0} will have the following repos '
                                     'removed: {1}.'.format(name, list(repos_to_remove)))
                ret['result'] = None
            else:
                for repo_name in repos_to_remove:
                    result = (__salt__['github.remove_team_repo']
                              (repo_name, name, profile=profile, **kwargs))
                    if result:
                        ret['changes'][repo_name] = {
                            'old': 'Repo {0} is in team {1}'.format(repo_name, name),
                            'new': 'Repo {0} is not in team {1}'.format(repo_name, name)
                        }
                    else:
                        ret['result'] = False
                        ret['comment'] = ('Failed to remove repo {0} from team {1}.'
                                          .format(repo_name, name))
                        return ret

    else:  # Team does not exist - it will be created.
        if __opts__['test']:
            ret['comment'] = 'Team {0} is set to be created.'.format(name)
            ret['result'] = None
            return ret

        result = __salt__['github.add_team'](
            name,
            description=description,
            repo_names=repo_names,
            permission=permission,
            privacy=privacy,
            profile=profile,
            **kwargs
        )
        if result:
            ret['changes']['team'] = {}
            ret['changes']['team']['old'] = None
            ret['changes']['team']['new'] = 'Team {0} has been created'.format(name)
        else:
            ret['result'] = False
            ret['comment'] = 'Failed to create team {0}.'.format(name)
            return ret

    manage_members = members is not None

    mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(seconds=no_mfa_grace_seconds)
    members_no_mfa = __salt__['github.list_members_without_mfa'](profile=profile)

    members_lower = {}
    for member_name, info in six.iteritems(members or {}):
        members_lower[member_name.lower()] = info

    member_change = False
    current_members = __salt__['github.list_team_members'](name, profile=profile)

    for member, member_info in six.iteritems(members or {}):
        log.info('Checking member %s in team %s', member, name)

        if member.lower() not in current_members:
            if (enforce_mfa and _member_violates_mfa(member, member_info,
                                                     mfa_deadline, members_no_mfa)):
                if __opts__['test']:
                    test_comments.append('User {0} will not be added to the '
                                         'team because they do not have MFA.'
                                         ''.format(member))
            else:  # Add to team
                member_change = True
                if __opts__['test']:
                    test_comments.append('User {0} set to be added to the '
                                         'team.'.format(member))
                    ret['result'] = None
                else:
                    result = (__salt__['github.add_team_member']
                              (member, name, profile=profile, **kwargs))
                    if result:
                        ret['changes'][member] = {}
                        ret['changes'][member]['old'] = (
                            'User {0} is not in team {1}'.format(member, name))
                        ret['changes'][member]['new'] = (
                            'User {0} is in team {1}'.format(member, name))
                    else:
                        ret['result'] = False
                        ret['comment'] = ('Failed to add user {0} to team '
                                          '{1}.'.format(member, name))
                        return ret

    for member in current_members:
        mfa_violation = False
        if member in members_lower:
            mfa_violation = _member_violates_mfa(member, members_lower[member],
                                                 mfa_deadline, members_no_mfa)
        if (manage_members and member not in members_lower or
            (enforce_mfa and mfa_violation)):
            # Remove from team
            member_change = True
            if __opts__['test']:
                if mfa_violation:
                    test_comments.append('User {0} set to be removed from the '
                                         'team because they do not have MFA.'
                                         .format(member))
                else:
                    test_comments.append('User {0} set to be removed from '
                                         'the team.'.format(member))
                ret['result'] = None
            else:
                result = (__salt__['github.remove_team_member']
                          (member, name, profile=profile, **kwargs))
                if result:
                    extra_changes = ' due to MFA violation' if mfa_violation else ''
                    ret['changes'][member] = {
                        'old': 'User {0} is in team {1}'.format(member, name),
                        'new': 'User {0} is not in team {1}{2}'.format(member, name, extra_changes)
                    }
                else:
                    ret['result'] = False
                    ret['comment'] = ('Failed to remove user {0} from team {1}.'
                                      .format(member, name))
                    return ret

    if member_change:  # Refresh team cache
        __salt__['github.list_team_members'](name, profile=profile,
                                             ignore_cache=False, **kwargs)

    if test_comments:
        ret['comment'] = '\n'.join(test_comments)
    return ret