Instruction:
Create a Python 3 function for
putting values into Consul WorkItem

Response:
def put(consul_url=None, token=None, key=None, value=None, **kwargs):
    '''
    Put values into Consul

    :param consul_url: The Consul server URL.
    :param key: The key to use as the starting point for the list.
    :param value: The value to set the key to.
    :param flags: This can be used to specify an unsigned value
                  between 0 and 2^64-1. Clients can choose to use
                  this however makes sense for their application.
    :param cas: This flag is used to turn the PUT into a
                Check-And-Set operation.
    :param acquire: This flag is used to turn the PUT into a
                    lock acquisition operation.
    :param release: This flag is used to turn the PUT into a
                    lock release operation.
    :return: Boolean & message of success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.put key='web/key1' value="Hello there"

        salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592'

        salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592'

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not key:
        raise SaltInvocationError('Required argument "key" is missing.')

    # Invalid to specified these together
    conflicting_args = ['cas', 'release', 'acquire']
    for _l1 in conflicting_args:
        for _l2 in conflicting_args:
            if _l1 in kwargs and _l2 in kwargs and _l1 != _l2:
                raise SaltInvocationError('Using arguments `{0}` and `{1}`'
                                          ' together is invalid.'.format(_l1, _l2))

    query_params = {}

    available_sessions = session_list(consul_url=consul_url, return_list=True)
    _current = get(consul_url=consul_url, key=key)

    if 'flags' in kwargs:
        if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64:
            query_params['flags'] = kwargs['flags']

    if 'cas' in kwargs:
        if _current['res']:
            if kwargs['cas'] == 0:
                ret['message'] = ('Key {0} exists, index '
                                  'must be non-zero.'.format(key))
                ret['res'] = False
                return ret

            if kwargs['cas'] != _current['data']['ModifyIndex']:
                ret['message'] = ('Key {0} exists, but indexes '
                                  'do not match.'.format(key))
                ret['res'] = False
                return ret
            query_params['cas'] = kwargs['cas']
        else:
            ret['message'] = ('Key {0} does not exists, '
                              'CAS argument can not be used.'.format(key))
            ret['res'] = False
            return ret

    if 'acquire' in kwargs:
        if kwargs['acquire'] not in available_sessions:
            ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire'])
            ret['res'] = False
            return ret

        query_params['acquire'] = kwargs['acquire']

    if 'release' in kwargs:
        if _current['res']:
            if 'Session' in _current['data']:
                if _current['data']['Session'] == kwargs['release']:
                    query_params['release'] = kwargs['release']
                else:
                    ret['message'] = '{0} locked by another session.'.format(key)
                    ret['res'] = False
                    return ret

            else:
                ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire'])
                ret['res'] = False
        else:
            log.error('Key {0} does not exist. Skipping release.')

    data = value
    function = 'kv/{0}'.format(key)
    method = 'PUT'
    ret = _query(consul_url=consul_url,
                 token=token,
                 function=function,
                 method=method,
                 data=data,
                 query_params=query_params)

    if ret['res']:
        ret['res'] = True
        ret['data'] = 'Added key {0} with value {1}.'.format(key, value)
    else:
        ret['res'] = False
        ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value)
    return ret


Instruction:
Given the following Python 3 function, write the documentation
def delete(consul_url=None, token=None, key=None, **kwargs):
    '''
    Delete values from Consul

    :param consul_url: The Consul server URL.
    :param key: The key to use as the starting point for the list.
    :param recurse: Delete values recursively beginning at the value of key.
    :param cas: This flag is used to turn the DELETE into
                a Check-And-Set operation.
    :return: Boolean & message of success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.delete key='web'
        salt '*' consul.delete key='web' recurse='True'

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not key:
        raise SaltInvocationError('Required argument "key" is missing.')

    query_params = {}

    if 'recurse' in kwargs:
        query_params['recurse'] = True

    if 'cas' in kwargs:
        if kwargs['cas'] > 0:
            query_params['cas'] = kwargs['cas']
        else:
            ret['message'] = ('Check and Set Operation ',
                              'value must be greater than 0.')
            ret['res'] = False
            return ret

    function = 'kv/{0}'.format(key)
    ret = _query(consul_url=consul_url,
                 token=token,
                 function=function,
                 method='DELETE',
                 query_params=query_params)

    if ret['res']:
        ret['res'] = True
        ret['message'] = 'Deleted key {0}.'.format(key)
    else:
        ret['res'] = False
        ret['message'] = 'Unable to delete key {0}.'.format(key)
    return ret

Response: Delete the value of a key in the current node.


Instruction:
How would you explain what the following Python 3 function does
def agent_checks(consul_url=None, token=None):
    '''
    Returns the checks the local agent is managing

    :param consul_url: The Consul server URL.
    :return: Returns the checks the local agent is managing

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_checks

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    function = 'agent/checks'
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='GET')
    return ret

Response: Returns the checks the local agent is managing


Instruction:
Can you write a function in Python 3 where it
returns the members as seen by the local serf agent

Response:
def agent_members(consul_url=None, token=None, **kwargs):
    '''
    Returns the members as seen by the local serf agent

    :param consul_url: The Consul server URL.
    :return: Returns the members as seen by the local serf agent

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_members

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'wan' in kwargs:
        query_params['wan'] = kwargs['wan']

    function = 'agent/members'
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='GET',
                 query_params=query_params)
    return ret


Instruction:
Can you tell what is the following Python 3 function doing
def agent_self(consul_url=None, token=None):
    '''
    Returns the local node configuration

    :param consul_url: The Consul server URL.
    :return: Returns the local node configuration

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_self

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    function = 'agent/self'
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='GET',
                 query_params=query_params)
    return ret

Response: Returns the local node configuration


Instruction:
Here you have a function in Python 3, explain what it does
def agent_maintenance(consul_url=None, token=None, **kwargs):
    '''
    Manages node maintenance mode

    :param consul_url: The Consul server URL.
    :param enable: The enable flag is required.
                   Acceptable values are either true
                   (to enter maintenance mode) or
                   false (to resume normal operation).
    :param reason: If provided, its value should be a
                   text string explaining the reason for
                   placing the node into maintenance mode.
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'enable' in kwargs:
        query_params['enable'] = kwargs['enable']
    else:
        ret['message'] = 'Required parameter "enable" is missing.'
        ret['res'] = False
        return ret

    if 'reason' in kwargs:
        query_params['reason'] = kwargs['reason']

    function = 'agent/maintenance'
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='PUT',
                 query_params=query_params)
    if res['res']:
        ret['res'] = True
        ret['message'] = ('Agent maintenance mode '
                          '{0}ed.'.format(kwargs['enable']))
    else:
        ret['res'] = True
        ret['message'] = 'Unable to change maintenance mode for agent.'
    return ret

Response: This function is used to manage the node maintenance mode.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def agent_leave(consul_url=None, token=None, node=None):
    '''
    Used to instruct the agent to force a node into the left state.

    :param consul_url: The Consul server URL.
    :param node: The node the agent will force into left state
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_leave node='web1.example.com'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not node:
        raise SaltInvocationError('Required argument "node" is missing.')

    function = 'agent/force-leave/{0}'.format(node)
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='GET',
                 query_params=query_params)
    if res['res']:
        ret['res'] = True
        ret['message'] = 'Node {0} put in leave state.'.format(node)
    else:
        ret['res'] = False
        ret['message'] = 'Unable to change state for {0}.'.format(node)
    return ret

Response: This function allows the agent to force a node into the left state.


Instruction:
Given the following Python 3 function, write the documentation
def agent_check_register(consul_url=None, token=None, **kwargs):
    '''
    The register endpoint is used to add a new check to the local agent.

    :param consul_url: The Consul server URL.
    :param name: The description of what the check is for.
    :param id: The unique name to use for the check, if not
               provided 'name' is used.
    :param notes: Human readable description of the check.
    :param script: If script is provided, the check type is
                   a script, and Consul will evaluate that script
                   based on the interval parameter.
    :param http: Check will perform an HTTP GET request against
                 the value of HTTP (expected to be a URL) based
                 on the interval parameter.
    :param ttl: If a TTL type is used, then the TTL update endpoint
                must be used periodically to update the state of the check.
    :param interval: Interval at which the check should run.
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s'

    '''
    ret = {}
    data = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'name' in kwargs:
        data['Name'] = kwargs['name']
    else:
        raise SaltInvocationError('Required argument "name" is missing.')

    if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]:
        ret['message'] = 'Required parameter "script" or "http" is missing.'
        ret['res'] = False
        return ret

    if 'id' in kwargs:
        data['ID'] = kwargs['id']

    if 'notes' in kwargs:
        data['Notes'] = kwargs['notes']

    if 'script' in kwargs:
        if 'interval' not in kwargs:
            ret['message'] = 'Required parameter "interval" is missing.'
            ret['res'] = False
            return ret
        data['Script'] = kwargs['script']
        data['Interval'] = kwargs['interval']

    if 'http' in kwargs:
        if 'interval' not in kwargs:
            ret['message'] = 'Required parameter "interval" is missing.'
            ret['res'] = False
            return ret
        data['HTTP'] = kwargs['http']
        data['Interval'] = kwargs['interval']

    if 'ttl' in kwargs:
        data['TTL'] = kwargs['ttl']

    function = 'agent/check/register'
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='PUT',
                 data=data)

    if res['res']:
        ret['res'] = True
        ret['message'] = ('Check {0} added to agent.'.format(kwargs['name']))
    else:
        ret['res'] = False
        ret['message'] = 'Unable to add check to agent.'
    return ret

Response: Register a new check in the local agent.


Instruction:
Given the following Python 3 function, write the documentation
def agent_check_deregister(consul_url=None, token=None, checkid=None):
    '''
    The agent will take care of deregistering the check from the Catalog.

    :param consul_url: The Consul server URL.
    :param checkid: The ID of the check to deregister from Consul.
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_check_deregister checkid='Memory Utilization'

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not checkid:
        raise SaltInvocationError('Required argument "checkid" is missing.')

    function = 'agent/check/deregister/{0}'.format(checkid)
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='GET')
    if res['res']:
        ret['res'] = True
        ret['message'] = ('Check {0} removed from agent.'.format(checkid))
    else:
        ret['res'] = False
        ret['message'] = 'Unable to remove check from agent.'
    return ret

Response: This function will take care of deregistering a check from the catalog.


Instruction:
Can you tell what is the following Python 3 function doing
def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs):
    '''
    This endpoint is used with a check that is of the TTL type. When this
    is called, the status of the check is set to warning and the TTL
    clock is reset.

    :param consul_url: The Consul server URL.
    :param checkid: The ID of the check to deregister from Consul.
    :param note: A human-readable message with the status of the check.
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not checkid:
        raise SaltInvocationError('Required argument "checkid" is missing.')

    if 'note' in kwargs:
        query_params['note'] = kwargs['note']

    function = 'agent/check/warn/{0}'.format(checkid)
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params,
                 method='GET')
    if res['res']:
        ret['res'] = True
        ret['message'] = 'Check {0} marked as warning.'.format(checkid)
    else:
        ret['res'] = False
        ret['message'] = 'Unable to update check {0}.'.format(checkid)
    return ret

Response: This endpoint is used to mark a check as warning.


Instruction:
Here you have a function in Python 3, explain what it does
def agent_service_deregister(consul_url=None, token=None, serviceid=None):
    '''
    Used to remove a service.

    :param consul_url: The Consul server URL.
    :param serviceid: A serviceid describing the service.
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_service_deregister serviceid='redis'

    '''
    ret = {}
    data = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not serviceid:
        raise SaltInvocationError('Required argument "serviceid" is missing.')

    function = 'agent/service/deregister/{0}'.format(serviceid)
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='PUT',
                 data=data)
    if res['res']:
        ret['res'] = True
        ret['message'] = 'Service {0} removed from agent.'.format(serviceid)
    else:
        ret['res'] = False
        ret['message'] = 'Unable to remove service {0}.'.format(serviceid)
    return ret

Response: This function removes a service from the current node.


Instruction:
Here you have a function in Python 3, explain what it does
def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs):
    '''
    Used to place a service into maintenance mode.

    :param consul_url: The Consul server URL.
    :param serviceid: A name of the service.
    :param enable: Whether the service should be enabled or disabled.
    :param reason: A human readable message of why the service was
                   enabled or disabled.
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not serviceid:
        raise SaltInvocationError('Required argument "serviceid" is missing.')

    if 'enable' in kwargs:
        query_params['enable'] = kwargs['enable']
    else:
        ret['message'] = 'Required parameter "enable" is missing.'
        ret['res'] = False
        return ret

    if 'reason' in kwargs:
        query_params['reason'] = kwargs['reason']

    function = 'agent/service/maintenance/{0}'.format(serviceid)
    res = _query(consul_url=consul_url,
                 token=token,
                 function=function,
                 query_params=query_params)

    if res['res']:
        ret['res'] = True
        ret['message'] = ('Service {0} set in '
                          'maintenance mode.'.format(serviceid))
    else:
        ret['res'] = False
        ret['message'] = ('Unable to set service '
                          '{0} to maintenance mode.'.format(serviceid))
    return ret

Response: This function is used to set a service into maintenance mode.


Instruction:
Given the following Python 3 function, write the documentation
def session_create(consul_url=None, token=None, **kwargs):
    '''
    Used to create a session.

    :param consul_url: The Consul server URL.
    :param lockdelay: Duration string using a "s" suffix for seconds.
                      The default is 15s.
    :param node: Must refer to a node that is already registered,
                 if specified. By default, the agent's own node
                 name is used.
    :param name: A human-readable name for the session
    :param checks: A list of associated health checks. It is highly
                   recommended that, if you override this list, you
                   include the default "serfHealth".
    :param behavior: Can be set to either release or delete. This controls
                     the behavior when a session is invalidated. By default,
                     this is release, causing any locks that are held to be
                     released. Changing this to delete causes any locks that
                     are held to be deleted. delete is useful for creating
                     ephemeral key/value entries.
    :param ttl: Session is invalidated if it is not renewed before
                the TTL expires
    :return: Boolean and message indicating success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s'

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret
    data = {}

    if 'lockdelay' in kwargs:
        data['LockDelay'] = kwargs['lockdelay']

    if 'node' in kwargs:
        data['Node'] = kwargs['node']

    if 'name' in kwargs:
        data['Name'] = kwargs['name']
    else:
        raise SaltInvocationError('Required argument "name" is missing.')

    if 'checks' in kwargs:
        data['Touch'] = kwargs['touch']

    if 'behavior' in kwargs:
        if not kwargs['behavior'] in ('delete', 'release'):
            ret['message'] = ('Behavior must be ',
                              'either delete or release.')
            ret['res'] = False
            return ret
        data['Behavior'] = kwargs['behavior']

    if 'ttl' in kwargs:
        _ttl = kwargs['ttl']
        if six.text_type(_ttl).endswith('s'):
            _ttl = _ttl[:-1]

        if int(_ttl) < 0 or int(_ttl) > 3600:
            ret['message'] = ('TTL must be ',
                              'between 0 and 3600.')
            ret['res'] = False
            return ret
        data['TTL'] = '{0}s'.format(_ttl)

    function = 'session/create'
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='PUT',
                 data=data)

    if res['res']:
        ret['res'] = True
        ret['message'] = 'Created session {0}.'.format(kwargs['name'])
    else:
        ret['res'] = False
        ret['message'] = 'Unable to create session {0}.'.format(kwargs['name'])
    return ret

Response: This function creates a new session in a node.


Instruction:
Can you write a function in Python 3 where it
uses to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list

Response:
def session_list(consul_url=None, token=None, return_list=False, **kwargs):
    '''
    Used to list sessions.

    :param consul_url: The Consul server URL.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :param return_list: By default, all information about the sessions is
                        returned, using the return_list parameter will return
                        a list of session IDs.
    :return: A list of all available sessions.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.session_list

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    query_params = {}

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    function = 'session/list'
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)

    if return_list:
        _list = []
        for item in ret['data']:
            _list.append(item['ID'])
        return _list
    return ret


Instruction:
Write a Python 3 script for
destroying session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'

Response:
def session_destroy(consul_url=None, token=None, session=None, **kwargs):
    '''
    Destroy session

    :param consul_url: The Consul server URL.
    :param session: The ID of the session to destroy.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :return: Boolean & message of success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not session:
        raise SaltInvocationError('Required argument "session" is missing.')

    query_params = {}

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    function = 'session/destroy/{0}'.format(session)
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)
    if res['res']:
        ret['res'] = True
        ret['message'] = 'Created Service {0}.'.format(kwargs['name'])
    else:
        ret['res'] = False
        ret['message'] = 'Unable to create service {0}.'.format(kwargs['name'])
    return ret


Instruction:
Can you generate the documentation for the following Python 3 function
def session_info(consul_url=None, token=None, session=None, **kwargs):
    '''
    Information about a session

    :param consul_url: The Consul server URL.
    :param session: The ID of the session to return information about.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :return: Boolean & message of success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not session:
        raise SaltInvocationError('Required argument "session" is missing.')

    query_params = {}

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    function = 'session/info/{0}'.format(session)
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)
    return ret

Response: Return information about a session.


Instruction:
Given the following Python 3 function, write the documentation
def catalog_register(consul_url=None, token=None, **kwargs):
    '''
    Registers a new node, service, or check

    :param consul_url: The Consul server URL.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :param node: The node to register.
    :param address: The address of the node.
    :param service: The service that will be registered.
    :param service_address: The address that the service listens on.
    :param service_port: The port for the service.
    :param service_id: A unique identifier for the service, if this is not
                       provided "name" will be used.
    :param service_tags: Any tags associated with the service.
    :param check: The name of the health check to register
    :param check_status: The initial status of the check,
                         must be one of unknown, passing, warning, or critical.
    :param check_service: The service that the check is performed against.
    :param check_id: Unique identifier for the service.
    :param check_notes: An opaque field that is meant to hold human-readable text.
    :return: Boolean & message of success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1'

    '''
    ret = {}
    data = {}
    data['NodeMeta'] = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'datacenter' in kwargs:
        data['Datacenter'] = kwargs['datacenter']

    if 'node' in kwargs:
        data['Node'] = kwargs['node']
    else:
        ret['message'] = 'Required argument node argument is missing.'
        ret['res'] = False
        return ret

    if 'address' in kwargs:
        if isinstance(kwargs['address'], list):
            _address = kwargs['address'][0]
        else:
            _address = kwargs['address']
        data['Address'] = _address
    else:
        ret['message'] = 'Required argument address argument is missing.'
        ret['res'] = False
        return ret

    if 'ip_interfaces' in kwargs:
        data['TaggedAddresses'] = {}
        for k in kwargs['ip_interfaces']:
            if kwargs['ip_interfaces'].get(k):
                data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0]

    if 'service' in kwargs:
        data['Service'] = {}
        data['Service']['Service'] = kwargs['service']

        if 'service_address' in kwargs:
            data['Service']['Address'] = kwargs['service_address']

        if 'service_port' in kwargs:
            data['Service']['Port'] = kwargs['service_port']

        if 'service_id' in kwargs:
            data['Service']['ID'] = kwargs['service_id']

        if 'service_tags' in kwargs:
            _tags = kwargs['service_tags']
            if not isinstance(_tags, list):
                _tags = [_tags]
            data['Service']['Tags'] = _tags

    if 'cpu' in kwargs:
        data['NodeMeta']['Cpu'] = kwargs['cpu']

    if 'num_cpus' in kwargs:
        data['NodeMeta']['Cpu_num'] = kwargs['num_cpus']

    if 'mem' in kwargs:
        data['NodeMeta']['Memory'] = kwargs['mem']

    if 'oscode' in kwargs:
        data['NodeMeta']['Os'] = kwargs['oscode']

    if 'osarch' in kwargs:
        data['NodeMeta']['Osarch'] = kwargs['osarch']

    if 'kernel' in kwargs:
        data['NodeMeta']['Kernel'] = kwargs['kernel']

    if 'kernelrelease' in kwargs:
        data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease']

    if 'localhost' in kwargs:
        data['NodeMeta']['localhost'] = kwargs['localhost']

    if 'nodename' in kwargs:
        data['NodeMeta']['nodename'] = kwargs['nodename']

    if 'os_family' in kwargs:
        data['NodeMeta']['os_family'] = kwargs['os_family']

    if 'lsb_distrib_description' in kwargs:
        data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description']

    if 'master' in kwargs:
        data['NodeMeta']['master'] = kwargs['master']

    if 'check' in kwargs:
        data['Check'] = {}
        data['Check']['Name'] = kwargs['check']

        if 'check_status' in kwargs:
            if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'):
                ret['message'] = 'Check status must be unknown, passing, warning, or critical.'
                ret['res'] = False
                return ret
            data['Check']['Status'] = kwargs['check_status']

        if 'check_service' in kwargs:
            data['Check']['ServiceID'] = kwargs['check_service']

        if 'check_id' in kwargs:
            data['Check']['CheckID'] = kwargs['check_id']

        if 'check_notes' in kwargs:
            data['Check']['Notes'] = kwargs['check_notes']

    function = 'catalog/register'
    res = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 method='PUT',
                 data=data)
    if res['res']:
        ret['res'] = True
        ret['message'] = ('Catalog registration '
                          'for {0} successful.'.format(kwargs['node']))
    else:
        ret['res'] = False
        ret['message'] = ('Catalog registration '
                          'for {0} failed.'.format(kwargs['node']))
    ret['data'] = data
    return ret

Response: This function registers a new node service or check with the Redis server.


Instruction:
Can you create a Python 3 function that
returns list of available datacenters from catalog.

Response:
def catalog_datacenters(consul_url=None, token=None):
    '''
    Return list of available datacenters from catalog.

    :param consul_url: The Consul server URL.
    :return: The list of available datacenters.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.catalog_datacenters

    '''
    ret = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    function = 'catalog/datacenters'
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token)
    return ret


Instruction:
Create a Python 3 function for
returning list of available nodes from catalog.

Response:
def catalog_nodes(consul_url=None, token=None, **kwargs):
    '''
    Return list of available nodes from catalog.

    :param consul_url: The Consul server URL.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :return: The list of available nodes.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.catalog_nodes

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    function = 'catalog/nodes'
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)
    return ret


Instruction:
Write a Python 3 script for
getting health information about a node.

Response:
def health_node(consul_url=None, token=None, node=None, **kwargs):
    '''
    Health information about the registered node.

    :param consul_url: The Consul server URL.
    :param node: The node to request health information about.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :return: Health information about the requested node.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.health_node node='node1'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not node:
        raise SaltInvocationError('Required argument "node" is missing.')

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    function = 'health/node/{0}'.format(node)
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)
    return ret


Instruction:
Can you create a Python 3 function that
gets health information about a node.

Response:
def health_checks(consul_url=None, token=None, service=None, **kwargs):
    '''
    Health information about the registered service.

    :param consul_url: The Consul server URL.
    :param service: The service to request health information about.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :return: Health information about the requested node.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.health_checks service='redis1'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not service:
        raise SaltInvocationError('Required argument "service" is missing.')

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    function = 'health/checks/{0}'.format(service)
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)
    return ret


Instruction:
Can you generate the documentation for the following Python 3 function
def health_state(consul_url=None, token=None, state=None, **kwargs):
    '''
    Returns the checks in the state provided on the path.

    :param consul_url: The Consul server URL.
    :param state: The state to show checks for. The supported states
                  are any, unknown, passing, warning, or critical.
                  The any state is a wildcard that can be used to
                  return all checks.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :return: The checks in the provided state.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.health_state state='redis1'

        salt '*' consul.health_state service='redis1' passing='True'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not state:
        raise SaltInvocationError('Required argument "state" is missing.')

    if 'dc' in kwargs:
        query_params['dc'] = kwargs['dc']

    if state not in ('any', 'unknown', 'passing', 'warning', 'critical'):
        ret['message'] = 'State must be any, unknown, passing, warning, or critical.'
        ret['res'] = False
        return ret

    function = 'health/state/{0}'.format(state)
    ret = _query(consul_url=consul_url,
                 function=function,
                 token=token,
                 query_params=query_params)
    return ret

Response: Return the checks in the provided state on the path.


Instruction:
Here you have a function in Python 3, explain what it does
def acl_delete(consul_url=None, token=None, **kwargs):
    '''
    Delete an ACL token.

    :param consul_url: The Consul server URL.
    :param id: Unique identifier for the ACL to update.
    :return: Boolean & message of success or failure.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'

    '''
    ret = {}
    data = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'id' not in kwargs:
        ret['message'] = 'Required parameter "id" is missing.'
        ret['res'] = False
        return ret

    function = 'acl/delete/{0}'.format(kwargs['id'])
    res = _query(consul_url=consul_url,
                 token=token,
                 data=data,
                 method='PUT',
                 function=function)

    if res['res']:
        ret['res'] = True
        ret['message'] = 'ACL {0} deleted.'.format(kwargs['id'])
    else:
        ret['res'] = False
        ret['message'] = ('Removing ACL '
                          '{0} failed.'.format(kwargs['id']))

    return ret

Response: Delete an ACL token.


Instruction:
Given the following Python 3 function, write the documentation
def acl_info(consul_url=None, **kwargs):
    '''
    Information about an ACL token.

    :param consul_url: The Consul server URL.
    :param id: Unique identifier for the ACL to update.
    :return: Information about the ACL requested.

    CLI Example:

    .. code-block:: bash

        salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'

    '''
    ret = {}
    data = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'id' not in kwargs:
        ret['message'] = 'Required parameter "id" is missing.'
        ret['res'] = False
        return ret

    function = 'acl/info/{0}'.format(kwargs['id'])
    ret = _query(consul_url=consul_url,
                 data=data,
                 method='GET',
                 function=function)
    return ret

Response: Return information about an ACL token.


Instruction:
Write a Python 3 script to
list the ACL tokens.

Response:
def acl_list(consul_url=None, token=None, **kwargs):
    '''
    List the ACL tokens.

    :param consul_url: The Consul server URL.
    :return: List of ACLs

    CLI Example:

    .. code-block:: bash

        salt '*' consul.acl_list

    '''
    ret = {}
    data = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'id' not in kwargs:
        ret['message'] = 'Required parameter "id" is missing.'
        ret['res'] = False
        return ret

    function = 'acl/list'
    ret = _query(consul_url=consul_url,
                 token=token,
                 data=data,
                 method='PUT',
                 function=function)
    return ret


Instruction:
Can you write a function in Python 3 where it
lists the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy'

Response:
def event_fire(consul_url=None, token=None, name=None, **kwargs):
    '''
    List the ACL tokens.

    :param consul_url: The Consul server URL.
    :param name: The name of the event to fire.
    :param dc: By default, the datacenter of the agent is queried;
               however, the dc can be provided using the "dc" parameter.
    :param node: Filter by node name.
    :param service: Filter by service name.
    :param tag: Filter by tag name.
    :return: List of ACLs

    CLI Example:

    .. code-block:: bash

        salt '*' consul.event_fire name='deploy'

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if not name:
        raise SaltInvocationError('Required argument "name" is missing.')

    if 'dc' in kwargs:
        query_params = kwargs['dc']

    if 'node' in kwargs:
        query_params = kwargs['node']

    if 'service' in kwargs:
        query_params = kwargs['service']

    if 'tag' in kwargs:
        query_params = kwargs['tag']

    function = 'event/fire/{0}'.format(name)
    res = _query(consul_url=consul_url,
                 token=token,
                 query_params=query_params,
                 method='PUT',
                 function=function)

    if res['res']:
        ret['res'] = True
        ret['message'] = 'Event {0} fired.'.format(name)
        ret['data'] = ret['data']
    else:
        ret['res'] = False
        ret['message'] = ('Cloning ACL'
                          'item {0} failed.'.format(kwargs['name']))
    return ret


Instruction:
Write a Python 3 function for
listing the recent events.

Response:
def event_list(consul_url=None, token=None, **kwargs):
    '''
    List the recent events.

    :param consul_url: The Consul server URL.
    :param name: The name of the event to fire.
    :return: List of ACLs

    CLI Example:

    .. code-block:: bash

        salt '*' consul.event_list

    '''
    ret = {}
    query_params = {}
    if not consul_url:
        consul_url = _get_config()
        if not consul_url:
            log.error('No Consul URL found.')
            ret['message'] = 'No Consul URL found.'
            ret['res'] = False
            return ret

    if 'name' in kwargs:
        query_params = kwargs['name']
    else:
        raise SaltInvocationError('Required argument "name" is missing.')

    function = 'event/list/'
    ret = _query(consul_url=consul_url,
                 token=token,
                 query_params=query_params,
                 function=function)
    return ret


Instruction:
Explain what the following Python 3 code does
def managed(name, value, **kwargs):
    '''
    Ensure a sysrc variable is set to a specific value.

    name
        The variable name to set
    value
        Value to set the variable to
    file
        (optional) The rc file to add the variable to.
    jail
        (option) the name or JID of the jail to set the value in.

    Example:

    .. code-block:: yaml

        syslogd:
          sysrc.managed:
            - name: syslogd_flags
            - value: -ss
    '''

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

    # Check the current state
    current_state = __salt__['sysrc.get'](name=name, **kwargs)
    if current_state is not None:
        for rcname, rcdict in six.iteritems(current_state):
            if rcdict[name] == value:
                ret['result'] = True
                ret['comment'] = '{0} is already set to the desired value.'.format(name)
                return ret

    if __opts__['test'] is True:
        ret['comment'] = 'The value of "{0}" will be changed!'.format(name)
        ret['changes'] = {
            'old': current_state,
            'new': name+' = '+value+' will be set.'
        }

        # When test=true return none
        ret['result'] = None

        return ret

    new_state = __salt__['sysrc.set'](name=name, value=value, **kwargs)

    ret['comment'] = 'The value of "{0}" was changed!'.format(name)

    ret['changes'] = {
        'old': current_state,
        'new': new_state
    }

    ret['result'] = True

    return ret

Response: Ensure a sysrc variable is set to a specific value.


Instruction:
Make a summary of the following Python 3 code
def item(*args):
    '''
    .. versionadded:: 0.16.2

    Return one or more pillar entries

    CLI Examples:

    .. code-block:: bash

        salt '*' pillar.item foo
        salt '*' pillar.item foo bar baz
    '''
    ret = {}
    for arg in args:
        try:
            ret[arg] = __pillar__[arg]
        except KeyError:
            pass
    return ret

Response: Return one or more pillar entries


Instruction:
Create a Python 3 function for
returning the raw pillar data that is available in the module.

Response:
def raw(key=None):
    '''
    Return the raw pillar data that is available in the module. This will
    show the pillar as it is loaded as the __pillar__ dict.

    CLI Example:

    .. code-block:: bash

        salt '*' pillar.raw

    With the optional key argument, you can select a subtree of the
    pillar raw data.::

        salt '*' pillar.raw key='roles'
    '''
    if key:
        ret = __pillar__.get(key, {})
    else:
        ret = __pillar__

    return ret


Instruction:
Implement a function in Python 3 to
return a list of keys from the named value in the pillar

Response:
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
    '''
    .. versionadded:: 2015.8.0

    Attempt to retrieve a list of keys from the named value from the pillar.

    The value can also represent a value in a nested dict using a ":" delimiter
    for the dict, similar to how pillar.get works.

    delimiter
        Specify an alternate delimiter to use when traversing a nested dict

    CLI Example:

    .. code-block:: bash

        salt '*' pillar.keys web:sites
    '''
    ret = salt.utils.data.traverse_dict_and_list(
        __pillar__, key, KeyError, delimiter)

    if ret is KeyError:
        raise KeyError("Pillar key not found: {0}".format(key))

    if not isinstance(ret, dict):
        raise ValueError("Pillar value in key {0} is not a dict".format(key))

    return ret.keys()


Instruction:
Write a Python 3 script for
ensuring a domain exists in the specified state definition.

Response:
def present(name, DomainName,
            ElasticsearchClusterConfig=None,
            EBSOptions=None,
            AccessPolicies=None,
            SnapshotOptions=None,
            AdvancedOptions=None,
            Tags=None,
            region=None, key=None, keyid=None, profile=None,
            ElasticsearchVersion="1.5"):
    '''
    Ensure domain exists.

    name
        The name of the state definition

    DomainName
        Name of the domain.

    ElasticsearchClusterConfig
        Configuration options for an Elasticsearch domain. Specifies the
        instance type and number of instances in the domain cluster.

        InstanceType (string) --
        The instance type for an Elasticsearch cluster.

        InstanceCount (integer) --
        The number of instances in the specified domain cluster.

        DedicatedMasterEnabled (boolean) --
        A boolean value to indicate whether a dedicated master node is enabled.
        See About Dedicated Master Nodes for more information.

        ZoneAwarenessEnabled (boolean) --
        A boolean value to indicate whether zone awareness is enabled. See About
        Zone Awareness for more information.

        DedicatedMasterType (string) --
        The instance type for a dedicated master node.

        DedicatedMasterCount (integer) --
        Total number of dedicated master nodes, active and on standby, for the
        cluster.

    EBSOptions
        Options to enable, disable and specify the type and size of EBS storage
        volumes.

        EBSEnabled (boolean) --
        Specifies whether EBS-based storage is enabled.

        VolumeType (string) --
        Specifies the volume type for EBS-based storage.

        VolumeSize (integer) --
        Integer to specify the size of an EBS volume.

        Iops (integer) --
        Specifies the IOPD for a Provisioned IOPS EBS volume (SSD).

    AccessPolicies
        IAM access policy

    SnapshotOptions
        Option to set time, in UTC format, of the daily automated snapshot.
        Default value is 0 hours.

        AutomatedSnapshotStartHour (integer) --
        Specifies the time, in UTC format, when the service takes a daily
        automated snapshot of the specified Elasticsearch domain. Default value
        is 0 hours.

    AdvancedOptions
        Option to allow references to indices in an HTTP request body. Must be
        false when configuring access to individual sub-resources. By default,
        the value is true .

    region
        Region to connect to.

    key
        Secret key to be used.

    keyid
        Access key to be used.

    profile
        A dict with region, key and keyid, or a pillar key (string) that
        contains a dict with region, key and keyid.

    ElasticsearchVersion
        String of format X.Y to specify version for the Elasticsearch domain eg.
        "1.5" or "2.3".
    '''
    ret = {'name': DomainName,
           'result': True,
           'comment': '',
           'changes': {}
           }

    if ElasticsearchClusterConfig is None:
        ElasticsearchClusterConfig = {
            'DedicatedMasterEnabled': False,
            'InstanceCount': 1,
            'InstanceType': 'm3.medium.elasticsearch',
            'ZoneAwarenessEnabled': False
        }
    if EBSOptions is None:
        EBSOptions = {
            'EBSEnabled': False,
        }
    if SnapshotOptions is None:
        SnapshotOptions = {
            'AutomatedSnapshotStartHour': 0
        }
    if AdvancedOptions is None:
        AdvancedOptions = {
            'rest.action.multi.allow_explicit_index': 'true'
        }
    if Tags is None:
        Tags = {}
    if AccessPolicies is not None and isinstance(AccessPolicies, six.string_types):
        try:
            AccessPolicies = salt.utils.json.loads(AccessPolicies)
        except ValueError as e:
            ret['result'] = False
            ret['comment'] = 'Failed to create domain: {0}.'.format(e.message)
            return ret
    r = __salt__['boto_elasticsearch_domain.exists'](DomainName=DomainName,
                              region=region, key=key, keyid=keyid, profile=profile)

    if 'error' in r:
        ret['result'] = False
        ret['comment'] = 'Failed to create domain: {0}.'.format(r['error']['message'])
        return ret

    if not r.get('exists'):
        if __opts__['test']:
            ret['comment'] = 'Domain {0} is set to be created.'.format(DomainName)
            ret['result'] = None
            return ret
        r = __salt__['boto_elasticsearch_domain.create'](DomainName=DomainName,
                                                     ElasticsearchClusterConfig=ElasticsearchClusterConfig,
                                                     EBSOptions=EBSOptions,
                                                     AccessPolicies=AccessPolicies,
                                                     SnapshotOptions=SnapshotOptions,
                                                     AdvancedOptions=AdvancedOptions,
                                                     ElasticsearchVersion=str(ElasticsearchVersion),  # future lint: disable=blacklisted-function
                                               region=region, key=key,
                                               keyid=keyid, profile=profile)
        if not r.get('created'):
            ret['result'] = False
            ret['comment'] = 'Failed to create domain: {0}.'.format(r['error']['message'])
            return ret
        _describe = __salt__['boto_elasticsearch_domain.describe'](DomainName,
                                   region=region, key=key, keyid=keyid, profile=profile)
        ret['changes']['old'] = {'domain': None}
        ret['changes']['new'] = _describe
        ret['comment'] = 'Domain {0} created.'.format(DomainName)
        return ret

    ret['comment'] = os.linesep.join([ret['comment'], 'Domain {0} is present.'.format(DomainName)])
    ret['changes'] = {}
    # domain exists, ensure config matches
    _status = __salt__['boto_elasticsearch_domain.status'](DomainName=DomainName,
                                  region=region, key=key, keyid=keyid,
                                  profile=profile)['domain']
    if _status.get('ElasticsearchVersion') != str(ElasticsearchVersion):  # future lint: disable=blacklisted-function
        ret['result'] = False
        ret['comment'] = (
            'Failed to update domain: version cannot be modified '
            'from {0} to {1}.'.format(
                _status.get('ElasticsearchVersion'),
                str(ElasticsearchVersion)  # future lint: disable=blacklisted-function
            )
        )
        return ret
    _describe = __salt__['boto_elasticsearch_domain.describe'](DomainName=DomainName,
                                  region=region, key=key, keyid=keyid,
                                  profile=profile)['domain']
    _describe['AccessPolicies'] = salt.utils.json.loads(_describe['AccessPolicies'])

    # When EBSEnabled is false, describe returns extra values that can't be set
    if not _describe.get('EBSOptions', {}).get('EBSEnabled'):
        opts = _describe.get('EBSOptions', {})
        opts.pop('VolumeSize', None)
        opts.pop('VolumeType', None)

    comm_args = {}
    need_update = False
    es_opts = {'ElasticsearchClusterConfig': ElasticsearchClusterConfig,
               'EBSOptions': EBSOptions,
               'AccessPolicies': AccessPolicies,
               'SnapshotOptions': SnapshotOptions,
               'AdvancedOptions': AdvancedOptions}

    for k, v in six.iteritems(es_opts):
        if not _compare_json(v, _describe[k]):
            need_update = True
            comm_args[k] = v
            ret['changes'].setdefault('new', {})[k] = v
            ret['changes'].setdefault('old', {})[k] = _describe[k]
    if need_update:
        if __opts__['test']:
            msg = 'Domain {0} set to be modified.'.format(DomainName)
            ret['comment'] = msg
            ret['result'] = None
            return ret

        ret['comment'] = os.linesep.join([ret['comment'], 'Domain to be modified'])

        r = __salt__['boto_elasticsearch_domain.update'](DomainName=DomainName,
                                               region=region, key=key,
                                               keyid=keyid, profile=profile,
                                               **comm_args)
        if not r.get('updated'):
            ret['result'] = False
            ret['comment'] = 'Failed to update domain: {0}.'.format(r['error'])
            ret['changes'] = {}
            return ret
    return ret


Instruction:
How would you explain what the following Python 3 function does
def open(self, new=False):
        '''
        Init the database, if required.
        '''
        self._db.new() if new else self._db.open()  # pylint: disable=W0106
        self._run_init_queries()

Response: Open the database if required.


Instruction:
Write a Python 3 function for
initializing the tables in the database.

Response:
def _run_init_queries(self):
        '''
        Initialization queries
        '''
        for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
            self._db.create_table_from_object(obj())


Instruction:
Here you have a function in Python 3, explain what it does
def purge(self):
        '''
        Purge whole database.
        '''
        for table_name in self._db.list_tables():
            self._db.flush(table_name)

        self._run_init_queries()

Response: Purge all the data in the database.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_config_value(profile, config_name):
    '''
    Helper function that returns a profile's configuration value based on
    the supplied configuration name.

    profile
        The profile name that contains configuration information.

    config_name
        The configuration item's name to use to return configuration values.
    '''
    config = __salt__['config.option'](profile)
    if not config:
        raise CommandExecutionError(
            'Authentication information could not be found for the '
            '\'{0}\' profile.'.format(profile)
        )

    config_value = config.get(config_name)
    if config_value is None:
        raise CommandExecutionError(
            'The \'{0}\' parameter was not found in the \'{1}\' '
            'profile.'.format(
                config_name,
                profile
            )
        )

    return config_value

Response: Helper function that returns a profile s configuration value based on the supplied configuration name.


Instruction:
Explain what the following Python 3 code does
def _get_client(profile):
    '''
    Return the GitHub client, cached into __context__ for performance
    '''
    token = _get_config_value(profile, 'token')
    key = 'github.{0}:{1}'.format(
        token,
        _get_config_value(profile, 'org_name')
    )

    if key not in __context__:
        __context__[key] = github.Github(
            token,
            per_page=100
        )
    return __context__[key]

Response: Return the GitHub client cached into __context__ for performance


Instruction:
How would you explain what the following Python 3 function does
def list_users(profile="github", ignore_cache=False):
    '''
    List all users within the organization.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    ignore_cache
        Bypasses the use of cached users.

        .. versionadded:: 2016.11.0

    CLI Example:

    .. code-block:: bash

        salt myminion github.list_users
        salt myminion github.list_users profile='my-github-profile'
    '''
    org_name = _get_config_value(profile, 'org_name')
    key = "github.{0}:users".format(
        org_name
    )
    if key not in __context__ or ignore_cache:
        client = _get_client(profile)
        organization = client.get_organization(org_name)
        __context__[key] = [member.login for member in _get_members(organization, None)]
    return __context__[key]

Response: List all users within the organization.


Instruction:
Can you write a function in Python 3 where it
gets a GitHub user by name.

Response:
def get_user(name, profile='github', user_details=False):
    '''
    Get a GitHub user by name.

    name
        The user for which to obtain information.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    user_details
        Prints user information details. Defaults to ``False``. If the user is
        already in the organization and user_details is set to False, the
        get_user function returns ``True``. If the user is not already present
        in the organization, user details will be printed by default.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_user github-handle
        salt myminion github.get_user github-handle user_details=true

    '''

    if not user_details and name in list_users(profile):
        # User is in the org, no need for additional Data
        return True

    response = {}
    client = _get_client(profile)
    organization = client.get_organization(
        _get_config_value(profile, 'org_name')
    )

    try:
        user = client.get_user(name)
    except UnknownObjectException:
        log.exception("Resource not found")
        return False

    response['company'] = user.company
    response['created_at'] = user.created_at
    response['email'] = user.email
    response['html_url'] = user.html_url
    response['id'] = user.id
    response['login'] = user.login
    response['name'] = user.name
    response['type'] = user.type
    response['url'] = user.url

    try:
        headers, data = organization._requester.requestJsonAndCheck(
            "GET",
            organization.url + "/memberships/" + user._identity
        )
    except UnknownObjectException:
        response['membership_state'] = 'nonexistent'
        response['in_org'] = False
        return response

    response['in_org'] = organization.has_in_members(user)
    response['membership_state'] = data.get('state')

    return response


Instruction:
Write a Python 3 script for
adding a GitHub user to the list of users.

Response:
def add_user(name, profile='github'):
    '''
    Add a GitHub user.

    name
        The user for which to obtain information.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.add_user github-handle
    '''

    client = _get_client(profile)
    organization = client.get_organization(
        _get_config_value(profile, 'org_name')
    )

    try:
        github_named_user = client.get_user(name)
    except UnknownObjectException:
        log.exception("Resource not found")
        return False

    headers, data = organization._requester.requestJsonAndCheck(
        "PUT",
        organization.url + "/memberships/" + github_named_user._identity
    )

    return data.get('state') == 'pending'


Instruction:
Can you generate the documentation for the following Python 3 function
def remove_user(name, profile='github'):
    '''
    Remove a Github user by name.

    name
        The user for which to obtain information.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.remove_user github-handle
    '''

    client = _get_client(profile)
    organization = client.get_organization(
        _get_config_value(profile, 'org_name')
    )

    try:
        git_user = client.get_user(name)
    except UnknownObjectException:
        log.exception("Resource not found")
        return False

    if organization.has_in_members(git_user):
        organization.remove_from_members(git_user)

    return not organization.has_in_members(git_user)

Response: Remove a Github user by name.


Instruction:
Make a summary of the following Python 3 code
def get_issue(issue_number, repo_name=None, profile='github', output='min'):
    '''
    Return information about a single issue in a named repository.

    .. versionadded:: 2016.11.0

    issue_number
        The number of the issue to retrieve.

    repo_name
        The name of the repository from which to get the issue. This argument is
        required, either passed via the CLI, or defined in the configured
        profile. A ``repo_name`` passed as a CLI argument will override the
        repo_name defined in the configured profile, if provided.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    output
        The amount of data returned by each issue. Defaults to ``min``. Change
        to ``full`` to see all issue output.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_issue 514
        salt myminion github.get_issue 514 repo_name=salt
    '''
    org_name = _get_config_value(profile, 'org_name')
    if repo_name is None:
        repo_name = _get_config_value(profile, 'repo_name')

    action = '/'.join(['repos', org_name, repo_name])
    command = 'issues/' + six.text_type(issue_number)

    ret = {}
    issue_data = _query(profile, action=action, command=command)

    issue_id = issue_data.get('id')
    if output == 'full':
        ret[issue_id] = issue_data
    else:
        ret[issue_id] = _format_issue(issue_data)

    return ret

Response: Get information about a single issue in a named repository.


Instruction:
Can you write a function in Python 3 where it
gets the comments for a given issue in a named repository.

Response:
def get_issue_comments(issue_number,
                       repo_name=None,
                       profile='github',
                       since=None,
                       output='min'):
    '''
    Return information about the comments for a given issue in a named repository.

    .. versionadded:: 2016.11.0

    issue_number
        The number of the issue for which to retrieve comments.

    repo_name
        The name of the repository to which the issue belongs. This argument is
        required, either passed via the CLI, or defined in the configured
        profile. A ``repo_name`` passed as a CLI argument will override the
        repo_name defined in the configured profile, if provided.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    since
        Only comments updated at or after this time are returned. This is a
        timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``.

    output
        The amount of data returned by each issue. Defaults to ``min``. Change
        to ``full`` to see all issue output.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_issue_comments 514
        salt myminion github.get_issue 514 repo_name=salt
    '''
    org_name = _get_config_value(profile, 'org_name')
    if repo_name is None:
        repo_name = _get_config_value(profile, 'repo_name')

    action = '/'.join(['repos', org_name, repo_name])
    command = '/'.join(['issues', six.text_type(issue_number), 'comments'])

    args = {}
    if since:
        args['since'] = since

    comments = _query(profile, action=action, command=command, args=args)

    ret = {}
    for comment in comments:
        comment_id = comment.get('id')
        if output == 'full':
            ret[comment_id] = comment
        else:
            ret[comment_id] = {'id': comment.get('id'),
                               'created_at': comment.get('created_at'),
                               'updated_at': comment.get('updated_at'),
                               'user_login': comment.get('user').get('login')}
    return ret


Instruction:
How would you implement a function in Python 3 that
returns a new tree of issues in a given repository.

Response:
def get_issues(repo_name=None,
               profile='github',
               milestone=None,
               state='open',
               assignee=None,
               creator=None,
               mentioned=None,
               labels=None,
               sort='created',
               direction='desc',
               since=None,
               output='min',
               per_page=None):
    '''
    Returns information for all issues in a given repository, based on the search options.

    .. versionadded:: 2016.11.0

    repo_name
        The name of the repository for which to list issues. This argument is
        required, either passed via the CLI, or defined in the configured
        profile. A ``repo_name`` passed as a CLI argument will override the
        repo_name defined in the configured profile, if provided.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    milestone
        The number of a GitHub milestone, or a string of either ``*`` or
        ``none``.

        If a number is passed, it should refer to a milestone by its number
        field. Use the ``github.get_milestone`` function to obtain a milestone's
        number.

        If the string ``*`` is passed, issues with any milestone are
        accepted. If the string ``none`` is passed, issues without milestones
        are returned.

    state
        Indicates the state of the issues to return. Can be either ``open``,
        ``closed``, or ``all``. Default is ``open``.

    assignee
        Can be the name of a user. Pass in ``none`` (as a string) for issues
        with no assigned user or ``*`` for issues assigned to any user.

    creator
        The user that created the issue.

    mentioned
        A user that's mentioned in the issue.

    labels
        A string of comma separated label names. For example, ``bug,ui,@high``.

    sort
        What to sort results by. Can be either ``created``, ``updated``, or
        ``comments``. Default is ``created``.

    direction
        The direction of the sort. Can be either ``asc`` or ``desc``. Default
        is ``desc``.

    since
        Only issues updated at or after this time are returned. This is a
        timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``.

    output
        The amount of data returned by each issue. Defaults to ``min``. Change
        to ``full`` to see all issue output.

    per_page
        GitHub paginates data in their API calls. Use this value to increase or
        decrease the number of issues gathered from GitHub, per page. If not set,
        GitHub defaults are used. Maximum is 100.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_issues my-github-repo
    '''
    org_name = _get_config_value(profile, 'org_name')
    if repo_name is None:
        repo_name = _get_config_value(profile, 'repo_name')

    action = '/'.join(['repos', org_name, repo_name])
    args = {}

    # Build API arguments, as necessary.
    if milestone:
        args['milestone'] = milestone
    if assignee:
        args['assignee'] = assignee
    if creator:
        args['creator'] = creator
    if mentioned:
        args['mentioned'] = mentioned
    if labels:
        args['labels'] = labels
    if since:
        args['since'] = since
    if per_page:
        args['per_page'] = per_page

    # Only pass the following API args if they're not the defaults listed.
    if state and state != 'open':
        args['state'] = state
    if sort and sort != 'created':
        args['sort'] = sort
    if direction and direction != 'desc':
        args['direction'] = direction

    ret = {}
    issues = _query(profile, action=action, command='issues', args=args)

    for issue in issues:
        # Pull requests are included in the issue list from GitHub
        # Let's not include those in the return.
        if issue.get('pull_request'):
            continue
        issue_id = issue.get('id')
        if output == 'full':
            ret[issue_id] = issue
        else:
            ret[issue_id] = _format_issue(issue)

    return ret


Instruction:
Write a Python 3 function that can
return information about milestones for a given repository.

Response:
def get_milestones(repo_name=None,
                   profile='github',
                   state='open',
                   sort='due_on',
                   direction='asc',
                   output='min',
                   per_page=None):
    '''
    Return information about milestones for a given repository.

    .. versionadded:: 2016.11.0

    repo_name
        The name of the repository for which to list issues. This argument is
        required, either passed via the CLI, or defined in the configured
        profile. A ``repo_name`` passed as a CLI argument will override the
        repo_name defined in the configured profile, if provided.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    state
        The state of the milestone. Either ``open``, ``closed``, or ``all``.
        Default is ``open``.

    sort
        What to sort results by. Either ``due_on`` or ``completeness``. Default
        is ``due_on``.

    direction
        The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``.

    output
        The amount of data returned by each issue. Defaults to ``min``. Change
        to ``full`` to see all issue output.

    per_page
        GitHub paginates data in their API calls. Use this value to increase or
        decrease the number of issues gathered from GitHub, per page. If not set,
        GitHub defaults are used.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_milestones

    '''
    org_name = _get_config_value(profile, 'org_name')
    if repo_name is None:
        repo_name = _get_config_value(profile, 'repo_name')

    action = '/'.join(['repos', org_name, repo_name])
    args = {}

    if per_page:
        args['per_page'] = per_page

    # Only pass the following API args if they're not the defaults listed.
    if state and state != 'open':
        args['state'] = state
    if sort and sort != 'due_on':
        args['sort'] = sort
    if direction and direction != 'asc':
        args['direction'] = direction

    ret = {}
    milestones = _query(profile, action=action, command='milestones', args=args)

    for milestone in milestones:
        milestone_id = milestone.get('id')
        if output == 'full':
            ret[milestone_id] = milestone
        else:
            milestone.pop('creator')
            milestone.pop('html_url')
            milestone.pop('labels_url')
            ret[milestone_id] = milestone

    return ret


Instruction:
Can you create a Python 3 function that
returns information about a single milestone in a named repository.

Response:
def get_milestone(number=None,
                  name=None,
                  repo_name=None,
                  profile='github',
                  output='min'):
    '''
    Return information about a single milestone in a named repository.

    .. versionadded:: 2016.11.0

    number
        The number of the milestone to retrieve. If provided, this option
        will be favored over ``name``.

    name
        The name of the milestone to retrieve.

    repo_name
        The name of the repository for which to list issues. This argument is
        required, either passed via the CLI, or defined in the configured
        profile. A ``repo_name`` passed as a CLI argument will override the
        repo_name defined in the configured profile, if provided.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    output
        The amount of data returned by each issue. Defaults to ``min``. Change
        to ``full`` to see all issue output.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_milestone 72
        salt myminion github.get_milestone name=my_milestone

    '''
    ret = {}

    if not any([number, name]):
        raise CommandExecutionError(
            'Either a milestone \'name\' or \'number\' must be provided.'
        )

    org_name = _get_config_value(profile, 'org_name')
    if repo_name is None:
        repo_name = _get_config_value(profile, 'repo_name')

    action = '/'.join(['repos', org_name, repo_name])
    if number:
        command = 'milestones/' + six.text_type(number)
        milestone_data = _query(profile, action=action, command=command)
        milestone_id = milestone_data.get('id')
        if output == 'full':
            ret[milestone_id] = milestone_data
        else:
            milestone_data.pop('creator')
            milestone_data.pop('html_url')
            milestone_data.pop('labels_url')
            ret[milestone_id] = milestone_data
        return ret

    else:
        milestones = get_milestones(repo_name=repo_name, profile=profile, output=output)
        for key, val in six.iteritems(milestones):
            if val.get('title') == name:
                ret[key] = val
                return ret

    return ret


Instruction:
Can you create a Python 3 function that
returns information for a given repository.

Response:
def get_repo_info(repo_name, profile='github', ignore_cache=False):
    '''
    Return information for a given repo.

    .. versionadded:: 2016.11.0

    repo_name
        The name of the repository.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_repo_info salt
        salt myminion github.get_repo_info salt profile='my-github-profile'
    '''

    org_name = _get_config_value(profile, 'org_name')
    key = "github.{0}:{1}:repo_info".format(
        _get_config_value(profile, 'org_name'),
        repo_name.lower()
    )

    if key not in __context__ or ignore_cache:
        client = _get_client(profile)
        try:
            repo = client.get_repo('/'.join([org_name, repo_name]))
            if not repo:
                return {}

            # client.get_repo can return a github.Repository.Repository object,
            # even if the repo is invalid. We need to catch the exception when
            # we try to perform actions on the repo object, rather than above
            # the if statement.
            ret = _repo_to_dict(repo)

            __context__[key] = ret
        except github.UnknownObjectException:
            raise CommandExecutionError(
                'The \'{0}\' repository under the \'{1}\' organization could not '
                'be found.'.format(
                    repo_name,
                    org_name
                )
            )
    return __context__[key]


Instruction:
Create a Python 3 function to
return a list of teams belonging to a repository.

Response:
def get_repo_teams(repo_name, profile='github'):
    '''
    Return teams belonging to a repository.

    .. versionadded:: 2017.7.0

    repo_name
        The name of the repository from which to retrieve teams.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.get_repo_teams salt
        salt myminion github.get_repo_teams salt profile='my-github-profile'
    '''
    ret = []
    org_name = _get_config_value(profile, 'org_name')
    client = _get_client(profile)

    try:
        repo = client.get_repo('/'.join([org_name, repo_name]))
    except github.UnknownObjectException:
        raise CommandExecutionError(
            'The \'{0}\' repository under the \'{1}\' organization could not '
            'be found.'.format(repo_name, org_name)
        )
    try:
        teams = repo.get_teams()
        for team in teams:
            ret.append({
                'id': team.id,
                'name': team.name,
                'permission': team.permission
            })
    except github.UnknownObjectException:
        raise CommandExecutionError(
            'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' '
            'organization.'.format(repo_name, org_name)
        )
    return ret


Instruction:
Here you have a function in Python 3, explain what it does
def list_private_repos(profile='github'):
    '''
    List private repositories within the organization. Dependent upon the access
    rights of the profile token.

    .. versionadded:: 2016.11.0

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.list_private_repos
        salt myminion github.list_private_repos profile='my-github-profile'
    '''
    repos = []
    for repo in _get_repos(profile):
        if repo.private is True:
            repos.append(repo.name)
    return repos

Response: List private repositories within the organization.


Instruction:
Write a Python 3 function for
listing public repositories within the organization.

Response:
def list_public_repos(profile='github'):
    '''
    List public repositories within the organization.

    .. versionadded:: 2016.11.0

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.list_public_repos
        salt myminion github.list_public_repos profile='my-github-profile'
    '''
    repos = []
    for repo in _get_repos(profile):
        if repo.private is False:
            repos.append(repo.name)
    return repos


Instruction:
Explain what the following Python 3 code does
def add_repo(name,
             description=None,
             homepage=None,
             private=None,
             has_issues=None,
             has_wiki=None,
             has_downloads=None,
             auto_init=None,
             gitignore_template=None,
             license_template=None,
             profile="github"):
    '''
    Create a new github repository.

    name
        The name of the team to be created.

    description
        The description of the repository.

    homepage
        The URL with more information about the repository.

    private
        The visiblity of the repository. Note that private repositories require
        a paid GitHub account.

    has_issues
        Whether to enable issues for this repository.

    has_wiki
        Whether to enable the wiki for this repository.

    has_downloads
        Whether to enable downloads for this repository.

    auto_init
        Whether to create an initial commit with an empty README.

    gitignore_template
        The desired language or platform for a .gitignore, e.g "Haskell".

    license_template
        The desired LICENSE template to apply, e.g "mit" or "mozilla".

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.add_repo 'repo_name'

    .. versionadded:: 2016.11.0
    '''
    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        given_params = {
            'description': description,
            'homepage': homepage,
            'private': private,
            'has_issues': has_issues,
            'has_wiki': has_wiki,
            'has_downloads': has_downloads,
            'auto_init': auto_init,
            'gitignore_template': gitignore_template,
            'license_template': license_template
        }
        parameters = {'name': name}
        for param_name, param_value in six.iteritems(given_params):
            if param_value is not None:
                parameters[param_name] = param_value

        organization._requester.requestJsonAndCheck(
            "POST",
            organization.url + "/repos",
            input=parameters
        )
        return True
    except github.GithubException:
        log.exception('Error creating a repo')
        return False

Response: Creates a new github repository.


Instruction:
Can you create a Python 3 function that
edits an existing Github repository.

Response:
def edit_repo(name,
              description=None,
              homepage=None,
              private=None,
              has_issues=None,
              has_wiki=None,
              has_downloads=None,
              profile="github"):
    '''
    Updates an existing Github repository.

    name
        The name of the team to be created.

    description
        The description of the repository.

    homepage
        The URL with more information about the repository.

    private
        The visiblity of the repository. Note that private repositories require
        a paid GitHub account.

    has_issues
        Whether to enable issues for this repository.

    has_wiki
        Whether to enable the wiki for this repository.

    has_downloads
        Whether to enable downloads for this repository.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.add_repo 'repo_name'

    .. versionadded:: 2016.11.0
    '''

    try:
        allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes')
    except CommandExecutionError:
        allow_private_change = False

    if private is not None and not allow_private_change:
        raise CommandExecutionError("The private field is set to be changed for "
                                    "repo {0} but allow_repo_privacy_changes "
                                    "disallows this.".format(name))

    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        repo = organization.get_repo(name)

        given_params = {
            'description': description,
            'homepage': homepage,
            'private': private,
            'has_issues': has_issues,
            'has_wiki': has_wiki,
            'has_downloads': has_downloads
        }
        parameters = {'name': name}
        for param_name, param_value in six.iteritems(given_params):
            if param_value is not None:
                parameters[param_name] = param_value

        organization._requester.requestJsonAndCheck(
            "PATCH",
            repo.url,
            input=parameters
        )
        get_repo_info(name, profile=profile, ignore_cache=True)  # Refresh cache
        return True
    except github.GithubException:
        log.exception('Error editing a repo')
        return False


Instruction:
Can you write a function in Python 3 where it
removes a Github repository.

Response:
def remove_repo(name, profile="github"):
    '''
    Remove a Github repository.

    name
        The name of the repository to be removed.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.remove_repo 'my-repo'

    .. versionadded:: 2016.11.0
    '''
    repo_info = get_repo_info(name, profile=profile)
    if not repo_info:
        log.error('Repo %s to be removed does not exist.', name)
        return False
    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        repo = organization.get_repo(name)
        repo.delete()
        _get_repos(profile=profile, ignore_cache=True)  # refresh cache
        return True
    except github.GithubException:
        log.exception('Error deleting a repo')
        return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_team(name,
             description=None,
             repo_names=None,
             privacy=None,
             permission=None,
             profile="github"):
    '''
    Create a new Github team within an organization.

    name
        The name of the team to be created.

    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'.

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

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.add_team 'team_name'

    .. versionadded:: 2016.11.0
    '''
    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        parameters = {}
        parameters['name'] = name

        if description is not None:
            parameters['description'] = description
        if repo_names is not None:
            parameters['repo_names'] = repo_names
        if permission is not None:
            parameters['permission'] = permission
        if privacy is not None:
            parameters['privacy'] = privacy

        organization._requester.requestJsonAndCheck(
            'POST',
            organization.url + '/teams',
            input=parameters
        )
        list_teams(ignore_cache=True)  # Refresh cache
        return True
    except github.GithubException:
        log.exception('Error creating a team')
        return False

Response: Creates a new Github team within an organization.


Instruction:
Can you write a function in Python 3 where it
edits an existing Github team.

Response:
def edit_team(name,
              description=None,
              privacy=None,
              permission=None,
              profile="github"):
    '''
    Updates an existing Github team.

    name
        The name of the team to be edited.

    description
        The description of the team.

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

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

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.edit_team 'team_name' description='Team description'

    .. versionadded:: 2016.11.0
    '''
    team = get_team(name, profile=profile)
    if not team:
        log.error('Team %s does not exist', name)
        return False
    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        team = organization.get_team(team['id'])

        parameters = {}
        if name is not None:
            parameters['name'] = name
        if description is not None:
            parameters['description'] = description
        if privacy is not None:
            parameters['privacy'] = privacy
        if permission is not None:
            parameters['permission'] = permission

        team._requester.requestJsonAndCheck(
            "PATCH",
            team.url,
            input=parameters
        )
        return True
    except UnknownObjectException:
        log.exception('Resource not found')
        return False


Instruction:
Can you create a Python 3 function that
removes a github team.

Response:
def remove_team(name, profile="github"):
    '''
    Remove a github team.

    name
        The name of the team to be removed.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    CLI Example:

    .. code-block:: bash

        salt myminion github.remove_team 'team_name'

    .. versionadded:: 2016.11.0
    '''
    team_info = get_team(name, profile=profile)
    if not team_info:
        log.error('Team %s to be removed does not exist.', name)
        return False
    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        team = organization.get_team(team_info['id'])
        team.delete()
        return list_teams(ignore_cache=True, profile=profile).get(name) is None
    except github.GithubException:
        log.exception('Error deleting a team')
        return False


Instruction:
Can you create a Python 3 function that
returns the list of repos for a given team.

Response:
def list_team_repos(team_name, profile="github", ignore_cache=False):
    '''
    Gets the repo details for a given team as a dict from repo_name to repo details.
    Note that repo names are always in lower case.

    team_name
        The name of the team from which to list repos.

    profile
        The name of the profile configuration to use. Defaults to ``github``.

    ignore_cache
        Bypasses the use of cached team repos.

    CLI Example:

    .. code-block:: bash

        salt myminion github.list_team_repos 'team_name'

    .. versionadded:: 2016.11.0
    '''
    cached_team = get_team(team_name, profile=profile)
    if not cached_team:
        log.error('Team %s does not exist.', team_name)
        return False

    # Return from cache if available
    if cached_team.get('repos') and not ignore_cache:
        return cached_team.get('repos')

    try:
        client = _get_client(profile)
        organization = client.get_organization(
            _get_config_value(profile, 'org_name')
        )
        team = organization.get_team(cached_team['id'])
    except UnknownObjectException:
        log.exception('Resource not found: %s', cached_team['id'])
    try:
        repos = {}
        for repo in team.get_repos():
            permission = 'pull'
            if repo.permissions.admin:
                permission = 'admin'
            elif repo.permissions.push:
                permission = 'push'

            repos[repo.name.lower()] = {
                'permission': permission
            }
        cached_team['repos'] = repos
        return repos
    except UnknownObjectException:
        log.exception('Resource not found: %s', cached_team['id'])
        return []