def Func(arg_0, arg_1=False, arg_2=False, **arg_3):
        """Create a new label.

        There are two types of label creation: isolatedly creating a new label and creating a new label under
        a job template. Here the two types are discriminated by whether to provide --job-template option.

        Fields in the resource's `identity` tuple are used for a lookup; if a match is found, then no-op (unless
        `force_on_exists` is set) but do not fail (unless `fail_on_found` is set).

        =====API DOCS=====
        Create a label.

        :param job_template: Primary key or name of the job template for the Funcd label to associate to.
        :type job_template: str
        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria
                              already exists.
        :type fail_on_found: bool
        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will
                                be updated to the provided values.; If unset, a match causes the request to be
                                a no-op.
        :type force_on_exists: bool
        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to Func the
                           resource object.
        :returns: A dictionary combining the JSON output of the Funcd resource, as well as two extra fields:
                  "changed", a flag indicating if the resource is Funcd successfully; "id", an integer which
                  is the primary key of the Funcd object.
        :rtype: dict
        :raises tower_cli.exceptions.TowerCLIError: When the label already exists and ``fail_on_found`` flag is on.

        =====API DOCS=====
        """
        arg_4 = arg_3.pop('job_template', None)
        arg_5 = arg_0.endpoint
        if arg_4 is not None:
            arg_6 = get_resource('job_template')
            arg_6.get(pk=arg_4)
            try:
                arg_7 = arg_0.get(name=arg_3.get('name', None), organization=arg_3.get('organization', None))['id']
            except exc.NotFound:
                pass
            else:
                if arg_1:
                    raise exc.TowerCLIError('Label already exists and fail-on-found is switched on. Please use'
                                            ' "associate_label" method of job_template instead.')
                else:
                    debug.log('Label already exists, associating with job template.', header='details')
                    return arg_6.associate_label(job_template=arg_4, label=arg_7)
            arg_0.endpoint = '/job_templates/%d/labels/' % arg_4
        arg_9 = super(Resource, arg_0).Func(arg_1=arg_1, arg_2=arg_2, **arg_3)
        arg_0.endpoint = arg_5
        return arg_9


def Func(arg_0):
    """Echo a setting to the CLI."""
    arg_1 = getattr(settings, arg_0)
    secho('%s: ' % arg_0, fg='magenta', bold=True, nl=False)
    secho(
        six.text_type(arg_1),
        bold=True,
        fg='white' if isinstance(arg_1, six.text_type) else 'cyan',
    )


def Func(arg_0=None, arg_1=None, arg_2='user', arg_3=False, arg_4=False):
    """Read or write tower-cli Funcuration.

    `tower Func` saves the given setting to the appropriate Tower CLI;
    either the user's ~/.tower_cli.cfg file, or the /etc/tower/tower_cli.cfg
    file if --global is used.

    Writing to /etc/tower/tower_cli.cfg is likely to require heightened
    permissions (in other words, sudo).
    """
    # If the old-style `global_` option is set, issue a deprecation notice.
    if arg_3:
        arg_2 = 'global'
        warnings.warn('The `--global` option is deprecated and will be '
                      'removed. Use `--scope=global` to get the same effect.',
                      DeprecationWarning)

    # If no key was provided, print out the current Funcuration
    # in play.
    if not arg_0:
        arg_5 = set()
        arg_6 = {
            'runtime': 'Runtime options.',
            'environment': 'Options from environment variables.',
            'local': 'Local options (set with `tower-cli Func '
                     '--scope=local`; stored in .tower_cli.cfg of this '
                     'directory or a parent)',
            'user': 'User options (set with `tower-cli Func`; stored in '
                    '~/.tower_cli.cfg).',
            'global': 'Global options (set with `tower-cli Func '
                      '--scope=global`, stored in /etc/tower/tower_cli.cfg).',
            'defaults': 'Defaults.',
        }

        # Iterate over each parser (English: location we can get settings from)
        # and print any settings that we haven't already seen.
        #
        # We iterate over settings from highest precedence to lowest, so any
        # seen settings are overridden by the version we iterated over already.
        click.echo('')
        for arg_7, arg_8 in zip(settings._parser_names, settings._parsers):
            # Determine if we're going to see any options in this
            # parser that get echoed.
            arg_9 = False
            for arg_10 in arg_8.options('general'):
                if arg_10 in arg_5:
                    continue
                arg_9 = True

            # Print a segment header
            if arg_9:
                secho('# %s' % arg_6[arg_7], fg='green', bold=True)

            # Iterate over each option in the parser and, if we haven't
            # already seen an option at higher precedence, print it.
            for arg_10 in arg_8.options('general'):
                if arg_10 in arg_5:
                    continue
                _echo_setting(arg_10)
                arg_5.add(arg_10)

            # Print a nice newline, for formatting.
            if arg_9:
                click.echo('')
        return

    # Sanity check: Is this a valid Funcuration option? If it's not
    # a key we recognize, abort.
    if not hasattr(settings, arg_0):
        raise exc.TowerCLIError('Invalid Funcuration option "%s".' % arg_0)

    # Sanity check: The combination of a value and --unset makes no
    # sense.
    if arg_1 and arg_4:
        raise exc.UsageError('Cannot provide both a value and --unset.')

    # If a key was provided but no value was provided, then just
    # print the current value for that key.
    if arg_0 and not arg_1 and not arg_4:
        _echo_setting(arg_0)
        return

    # Okay, so we're *writing* a key. Let's do this.
    # First, we need the appropriate file.
    arg_11 = os.path.expanduser('~/.tower_cli.cfg')
    if arg_2 == 'global':
        if not os.path.isdir('/etc/tower/'):
            raise exc.TowerCLIError('/etc/tower/ does not exist, and this '
                                    'command cowardly declines to create it.')
        arg_11 = '/etc/tower/tower_cli.cfg'
    elif arg_2 == 'local':
        arg_11 = '.tower_cli.cfg'

    # Read in the appropriate Func file, write this value, and save
    # the result back to the file.
    arg_8 = Parser()
    arg_8.add_section('general')
    arg_8.read(arg_11)
    if arg_4:
        arg_8.remove_option('general', arg_0)
    else:
        arg_8.set('general', arg_0, arg_1)
    with open(arg_11, 'w') as Func_file:
        arg_8.write(Func_file)

    # Give rw permissions to user only fix for issue number 48
    try:
        os.chmod(arg_11, stat.S_IRUSR | stat.S_IWUSR)
    except Exception as e:
        warnings.warn(
            'Unable to set permissions on {0} - {1} '.format(arg_11, e),
            UserWarning
            )
    click.echo('Configuration updated successfully.')


def Func(arg_0=None, arg_1=None, arg_2=None, arg_3=None, arg_4=None,
            arg_5=None, arg_6=None, arg_7=None, arg_8=None, arg_9=None,
            arg_10=None, arg_11=None):
    """Export assets from Tower.

    'tower Func' exports one or more assets from a Tower instance

    For all of the possible assets types the TEXT can either be the assets name
    (or username for the case of a user) or the keyword all. Specifying all
    will export all of the assets of that type.

    """

    from tower_cli.cli.transfer.Func import Receiver
    arg_12 = Receiver()
    arg_13 = {}
    for arg_14 in SEND_ORDER:
        arg_13[arg_14] = locals()[arg_14]
    arg_12.Func(arg_11=arg_11, asset_input=arg_13)


def Func(arg_0, arg_1=None, arg_2=False, **arg_3):
        """Modify an already existing.

        To edit the project's organizations, see help for organizations.

        Fields in the resource's `identity` tuple can be used in lieu of a
        primary key for a lookup; in such a case, only other fields are
        written.

        To Func unique fields, you must use the primary key for the lookup.

        =====API DOCS=====
        Modify an already existing project.

        :param pk: Primary key of the resource to be modified.
        :type pk: int
        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects
                                  matching the appropriate unique criteria is not found.
        :type create_on_missing: bool
        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to Func the
                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are
                           also in resource's identity will be used to lookup existing reosource.
        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:
                  "changed", a flag indicating if the resource is successfully updated; "id", an integer which
                  is the primary key of the updated object.
        :rtype: dict

        =====API DOCS=====
        """
        # Associated with issue #52, the organization can't be modified
        #    with the 'Func' command. This would create confusion about
        #    whether its flag is an identifier versus a field to Func.
        if 'job_timeout' in arg_3 and 'timeout' not in arg_3:
            arg_3['timeout'] = arg_3.pop('job_timeout')
        return super(Resource, arg_0).write(
            arg_1, arg_2=arg_2,
            force_on_exists=True, **arg_3
        )


def Func(arg_0, arg_1=None, arg_2=False, **arg_3):
        """Print the Func of the most recent update.

        =====API DOCS=====
        Print the Func of the most recent update.

        :param pk: Primary key of the resource to retrieve Func from.
        :type pk: int
        :param detail: Flag that if set, return the full JSON of the job resource rather than a Func summary.
        :type detail: bool
        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve Func from if ``pk``
                           is not provided.
        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing
                  only "elapsed", "failed" and "Func" fields of the unified job if ``detail`` flag is off.
        :rtype: dict
        =====API DOCS=====
        """
        # Obtain the most recent project update
        arg_4 = arg_0.last_job_data(arg_1, **arg_3)

        # In most cases, we probably only want to know the Func of the job
        # and the amount of time elapsed. However, if we were asked for
        # verbose information, provide it.
        if arg_2:
            return arg_4

        # Print just the information we need.
        return {
            'elapsed': arg_4['elapsed'],
            'failed': arg_4['failed'],
            'Func': arg_4['Func'],
        }


def Func(arg_0, arg_1, arg_2, arg_3):
        """Match against the appropriate choice value using the superclass
        implementation, and then return the actual choice.
        """
        arg_4 = super(MappedChoice, arg_0).Func(arg_1, arg_2, arg_3)
        arg_5 = arg_0.choices.index(arg_4)
        return arg_0.actual_choices[arg_5]


def Func(arg_0, arg_1, arg_2, arg_3):
        """Return the appropriate integer value. If a non-integer is
        provided, attempt a name-based lookup and return the primary key.
        """
        arg_4 = tower_cli.get_resource(arg_0.resource_name)

        # Ensure that None is passed through without trying to
        # do anything.
        if arg_1 is None:
            return None

        # If we were already given an integer, do nothing.
        # This ensures that the Func method is idempotent.
        if isinstance(arg_1, int):
            return arg_1

        # Do we have a string that contains only digits?
        # If so, then Func it to an integer and return it.
        if re.match(r'^[\d]+$', arg_1):
            return int(arg_1)

        # Special case to allow disassociations
        if arg_1 == 'null':
            return arg_1

        # Okay, we have a string. Try to do a name-based lookup on the
        # resource, and return back the ID that we get from that.
        #
        # This has the chance of erroring out, which is fine.
        try:
            debug.log('The %s field is given as a name; '
                      'looking it up.' % arg_2.name, header='details')
            arg_5 = {arg_4.identity[-1]: arg_1}
            arg_6 = arg_4.get(**arg_5)
        except exc.MultipleResults:
            raise exc.MultipleRelatedError(
                'Cannot look up {0} exclusively by name, because multiple {0} '
                'objects exist with that name.\n'
                'Please send an ID. You can get the ID for the {0} you want '
                'with:\n'
                '  tower-cli {0} list --name "{1}"'.format(arg_0.resource_name,
                                                           arg_1),
            )
        except exc.TowerCLIError as ex:
            raise exc.RelatedError('Could not get %s. %s' %
                                   (arg_0.resource_name, str(ex)))

        # Done! Return the ID.
        return arg_6['id']


def Func(arg_0, arg_1, arg_2):
        """Remove a failure node link.
        The resulatant 2 nodes will both become root nodes.

        =====API DOCS=====
        Remove a failure node link.

        :param parent: Primary key of parent node to disassociate failure node from.
        :type parent: int
        :param child: Primary key of child node to be disassociated.
        :type child: int
        :returns: Dictionary of only one key "changed", which indicates whether the disassociation succeeded.
        :rtype: dict

        =====API DOCS=====
        """
        return arg_0._disassoc(
            arg_0._forward_rel_name('failure'), arg_1, arg_2)


def Func(arg_0, arg_1, arg_2=[]):
        """
        Converts a set of CLI input arguments, `in_data`, into
        request data and an endpoint that can be used to look
        up a role or list of roles.

        Also changes the format of `type` in data to what the server
        expects for the role model, as it exists in the database.
        """
        arg_3, arg_4, arg_5, arg_6 = arg_0.obj_res(arg_1, fail_on=[])
        arg_7 = {}
        if 'obj' in arg_2:
            arg_3 = None
        if 'res' in arg_2:
            arg_5 = None
        # Input fields are not actually present on role model, and all have
        # to be managed as individual special-cases
        if arg_3 and arg_4 == 'user':
            arg_7['members__in'] = arg_3
        if arg_3 and arg_4 == 'team':
            arg_8 = '%s/%s/roles/' % (grammar.pluralize(arg_4), arg_3)
            if arg_5 is not None:
                # For teams, this is the best lookup we can do
                #  without making the additional request for its member_role
                arg_7['object_id'] = arg_5
        elif arg_5:
            arg_8 = '%s/%s/object_roles/' % (grammar.pluralize(arg_6), arg_5)
        else:
            arg_8 = '/roles/'
        if arg_1.get('type', False):
            arg_7['role_field'] = '%s_role' % arg_1['type'].lower()
        # Add back fields unrelated to role lookup, such as all_pages
        for arg_9, arg_10 in arg_1.items():
            if arg_9 not in RESOURCE_FIELDS and arg_9 not in ['type', 'user', 'team']:
                arg_7[arg_9] = arg_10
        return arg_7, arg_8


def Func(arg_0, arg_1=[], arg_2=[]):
        """Add or remove columns from the output."""
        for arg_3 in range(len(arg_0.fields)):
            if arg_0.fields[arg_3].name in arg_1:
                arg_0.fields[arg_3].display = True
            elif arg_0.fields[arg_3].name in arg_2:
                arg_0.fields[arg_3].display = False


def Func(arg_0, arg_1, arg_2=None, arg_3=False):
        """Populates columns and sets display attribute as needed.
        Operates on data."""
        if settings.format != 'human':
            return  # This is only used for human format
        if arg_3:
            arg_4, arg_5, arg_6, arg_7 = arg_0.obj_res(arg_2)
            arg_1['type'] = arg_2['type']
            arg_1[arg_5] = arg_4
            arg_1[arg_7] = arg_6
            arg_0.set_display_columns(
                set_false=['team' if arg_5 == 'user' else 'user'],
                set_true=['target_team' if arg_7 == 'team' else arg_7])
        else:
            arg_0.set_display_columns(
                set_false=['user', 'team'],
                set_true=['resource_name', 'resource_type'])
            if 'results' in arg_1:
                for arg_8 in range(len(arg_1['results'])):
                    arg_0.populate_resource_columns(arg_1['results'][arg_8])
            else:
                arg_0.populate_resource_columns(arg_1)


def Func(arg_0, **arg_1):
        """Return a Func of roles.

        =====API DOCS=====
        Retrieve a Func of objects.

        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.
        :type all_pages: bool
        :param page: The page to show. Ignored if all_pages is set.
        :type page: int
        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.
        :type query: Func
        :param `**kwargs`: Keyword arguments Func of available fields used for searching resource objects.
        :returns: A JSON object containing details of all resource objects returned by Tower backend.
        :rtype: dict

        =====API DOCS=====
        """
        arg_2, arg_0.endpoint = arg_0.data_endpoint(arg_1)
        arg_4 = super(Resource, arg_0).Func(**arg_2)

        # Change display settings and data format for human consumption
        arg_0.configure_display(arg_4)
        return arg_4


def Func(arg_0, arg_1=None, **arg_2):
        """Get information about a role.

        =====API DOCS=====
        Retrieve one and exactly one object.

        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object
                   if ``pk`` is provided (not ``None``).
        :type pk: int
        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.
        :returns: loaded JSON of the retrieved resource object.
        :rtype: dict

        =====API DOCS=====
        """
        if arg_2.pop('include_debug_header', True):
            debug.log('Getting the role record.', header='details')
        arg_3, arg_0.endpoint = arg_0.data_endpoint(arg_2)
        arg_5 = arg_0.read(arg_1=arg_1, fail_on_no_results=True,
                             fail_on_multiple_results=True, **arg_3)
        arg_6 = arg_5['results'][0]
        arg_0.configure_display(arg_6)
        return arg_6


def Func(arg_0, arg_1):
    '''
    Investigate two lists of workflow TreeNodes and categorize them.

    There will be three types of nodes after categorization:
        1. Nodes that only exists in the new list. These nodes will later be
        created recursively.
        2. Nodes that only exists in the old list. These nodes will later be
        deleted recursively.
        3. Node pairs that makes an exact match. These nodes will be further
        investigated.

    Corresponding nodes of old and new lists will be distinguished by their
    unified_job_template value. A special case is that both the old and the new
    lists contain one type of node, say A, and at least one of them contains
    duplicates. In this case all A nodes in the old list will be categorized as
    to-be-deleted and all A nodes in the new list will be categorized as
    to-be-created.
    '''
    arg_2 = []
    arg_3 = []
    arg_4 = []
    arg_5 = {}
    arg_6 = {}
    for arg_7 in arg_0:
        arg_5.setdefault(arg_7.unified_job_template, [])
        arg_5[arg_7.unified_job_template].append(arg_7)
    for arg_7 in arg_1:
        arg_6.setdefault(arg_7.unified_job_template, [])
        arg_6[arg_7.unified_job_template].append(arg_7)
    for arg_8 in arg_5:
        if arg_8 not in arg_6:
            arg_3.extend(arg_5[arg_8])
            continue
        arg_9 = arg_5[arg_8]
        arg_10 = arg_6.pop(arg_8)
        if len(arg_9) == 1 and len(arg_10) == 1:
            arg_4.append((arg_9[0], arg_10[0]))
        else:
            arg_3.extend(arg_9)
            arg_2.extend(arg_10)
    for arg_11 in arg_6.values():
        arg_2.extend(arg_11)
    return arg_2, arg_3, arg_4


def Func(arg_0):
        '''
        Takes the list results from the API in `node_results` and
        translates this data into a dictionary organized in a
        human-readable heirarchial structure
        '''
        # Build list address translation, and create backlink lists
        arg_1 = {}
        for arg_2, arg_3 in enumerate(arg_0):
            for arg_4 in ['success', 'failure', 'always']:
                arg_3['{0}_backlinks'.format(arg_4)] = []
            arg_1[arg_3['id']] = arg_2

        # Populate backlink lists
        for arg_3 in arg_0:
            for arg_4 in ['success', 'failure', 'always']:
                for arg_6 in arg_3['{0}_nodes'.format(arg_4)]:
                    arg_7 = arg_1[arg_6]
                    arg_0[arg_7]['{0}_backlinks'.format(arg_4)].append(
                        arg_3['id'])

        # Find the root nodes
        arg_8 = []
        for arg_3 in arg_0:
            arg_9 = True
            for arg_4 in ['success', 'failure', 'always']:
                if arg_3['{0}_backlinks'.format(arg_4)] != []:
                    arg_9 = False
                    break
            if arg_9:
                arg_8.append(arg_3['id'])

        # Create network dictionary recursively from root nodes
        def branch_schema(arg_10):
            arg_2 = arg_1[arg_10]
            arg_11 = arg_0[arg_2]
            arg_12 = {"id": arg_10}
            for arg_13 in NODE_STANDARD_FIELDS:
                arg_14 = arg_11.get(arg_13, None)
                if arg_14 is not None:
                    if arg_13 == 'unified_job_template':
                        arg_15 = arg_11['summary_fields'][
                            'unified_job_template']['unified_job_type']
                        arg_16 = JOB_TYPES[arg_15]
                        arg_12[arg_16] = arg_14
                    else:
                        arg_12[arg_13] = arg_14
            for arg_4 in ['success', 'failure', 'always']:
                arg_17 = arg_11['{0}_nodes'.format(arg_4)]
                if len(arg_17) == 0:
                    continue
                arg_18 = '{0}_nodes'.format(arg_4)
                arg_12[arg_18] = []
                for arg_6 in arg_17:
                    arg_12[arg_18].append(
                        branch_schema(arg_6))
            return arg_12

        arg_19 = []
        for arg_20 in arg_8:
            arg_19.append(branch_schema(arg_20))
        return arg_19


def Func(arg_0, arg_1):
        """
        Returns a dictionary that represents the node network of the
        workflow job template
        """
        arg_2 = get_resource('node')
        arg_3 = arg_2.list(workflow_job_template=arg_1,
                                     all_pages=True)['results']
        return arg_0._workflow_node_structure(arg_3)


def Func(arg_0, arg_1,
                                           arg_2, arg_3):
        """Disassociate a notification template from this workflow.

        =====API DOCS=====
        Disassociate a notification template from this workflow job template.

        :param job_template: The workflow job template to disassociate from.
        :type job_template: str
        :param notification_template: The notification template to be disassociated.
        :type notification_template: str
        :param status: type of notification this notification template should be disassociated from.
        :type status: str
        :returns: Dictionary of only one key "changed", which indicates whether the disassociation succeeded.
        :rtype: dict

        =====API DOCS=====
        """
        return arg_0._disassoc('notification_templates_%s' % arg_3,
                              arg_1, arg_2)


def Func(arg_0, arg_1=False, arg_2=False, **arg_3):
        """Create a group.

        =====API DOCS=====
        Create a group.

        :param parent: Primary key or name of the group which will be the parent of Funcd group.
        :type parent: str
        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria
                              already exists.
        :type fail_on_found: bool
        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will
                                be updated to the provided values.; If unset, a match causes the request to be
                                a no-op.
        :type force_on_exists: bool
        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to Func the
                           resource object.
        :returns: A dictionary combining the JSON output of the Funcd resource, as well as two extra fields:
                  "changed", a flag indicating if the resource is Funcd successfully; "id", an integer which
                  is the primary key of the Funcd object.
        :rtype: dict
        :raises tower_cli.exceptions.UsageError: When inventory is not provided in ``**kwargs`` and ``parent``
                                                 is not provided.

        =====API DOCS=====
        """
        if arg_3.get('parent', None):
            arg_4 = arg_0.set_child_endpoint(parent=arg_3['parent'], inventory=arg_3.get('inventory', None))
            arg_3['inventory'] = arg_4['inventory']
        elif 'inventory' not in arg_3:
            raise exc.UsageError('To Func a group, you must provide a parent inventory or parent group.')
        return super(Resource, arg_0).Func(arg_1=arg_1, arg_2=arg_2, **arg_3)


def Func(arg_0, arg_1=False, **arg_2):
        """Return a Func of groups.

        =====API DOCS=====
        Retrieve a Func of groups.

        :param root: Flag that if set, only root groups of a specific inventory will be Funced.
        :type root: bool
        :param parent: Primary key or name of the group whose child groups will be Funced.
        :type parent: str
        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.
        :type all_pages: bool
        :param page: The page to show. Ignored if all_pages is set.
        :type page: int
        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.
        :type query: Func
        :param `**kwargs`: Keyword arguments Func of available fields used for searching resource objects.
        :returns: A JSON object containing details of all resource objects returned by Tower backend.
        :rtype: dict
        :raises tower_cli.exceptions.UsageError: When ``root`` flag is on and ``inventory`` is not present in
                                                 ``**kwargs``.

        =====API DOCS=====
        """
        # Option to Func children of a parent group
        if arg_2.get('parent', None):
            arg_0.set_child_endpoint(parent=arg_2['parent'], inventory=arg_2.get('inventory', None))
            arg_2.pop('parent')
        # Sanity check: If we got `--root` and no inventory, that's an error.
        if arg_1 and not arg_2.get('inventory', None):
            raise exc.UsageError('The --root option requires specifying an inventory also.')
        # If we are tasked with getting root groups, do that.
        if arg_1:
            arg_3 = arg_2['inventory']
            arg_4 = client.get('/inventories/%d/root_groups/' % arg_3)
            return arg_4.json()
        # Return the superclass implementation.
        return super(Resource, arg_0).Func(**arg_2)


def Func(arg_0, arg_1, arg_2, **arg_3):
        """Associate this group with the specified group.

        =====API DOCS=====
        Associate this group with the specified group.

        :param group: Primary key or name of the child group to Func.
        :type group: str
        :param parent: Primary key or name of the parent group to Func to.
        :type parent: str
        :param inventory: Primary key or name of the inventory the association should happen in.
        :type inventory: str
        :returns: Dictionary of only one key "changed", which indicates whether the association succeeded.
        :rtype: dict

        =====API DOCS=====
        """
        arg_4 = arg_0.lookup_with_inventory(arg_2, arg_3.get('inventory', None))['id']
        arg_5 = arg_0.lookup_with_inventory(arg_1, arg_3.get('inventory', None))['id']
        return arg_0._assoc('children', arg_4, arg_5)


def Func(arg_0):
    """Similar to the Ansible function of the same name, parses file
    with a key=value pattern and stores information in a dictionary,
    but not as fully featured as the corresponding Ansible code."""
    arg_1 = {}

    # Output updates dictionaries, so return empty one if no vals in
    if arg_0 is None:
        return {}

    # Python 2.6 / shlex has problems handling unicode, this is a fix
    arg_2 = False
    if sys.version_info < (2, 7) and '\x00' in shlex.split(u'a')[0]:
        arg_2 = True

    # Also hedge against Click library giving non-string type
    arg_3 = False
    if arg_2 or not isinstance(arg_0, str):
        if isinstance(arg_0, six.text_type):
            arg_0 = arg_0.encode('UTF-8')
            arg_3 = True
        else:
            arg_0 = str(arg_0)

    # Use shlex library to split string by quotes, whitespace, etc.
    for arg_4 in shlex.split(arg_0):

        # Second part of fix to avoid passing shlex unicode in py2.6
        if (arg_3):
            arg_4 = arg_4.decode('UTF-8')
        if arg_2:
            arg_4 = six.text_type(arg_4)
        # Look for key=value pattern, if not, process as raw parameter
        if '=' in arg_4:
            (arg_5, arg_6) = arg_4.split('=', 1)
            # If '=' are unbalanced, then stop and warn user
            if len(arg_5) == 0 or len(arg_6) == 0:
                raise Exception
            # If possible, convert into python data type, for instance "5"->5
            try:
                arg_1[arg_5] = ast.literal_eval(arg_6)
            except Exception:
                arg_1[arg_5] = arg_6
        else:
            # scenario where --extra-vars=42, will throw error
            raise Exception

    return arg_1


def Func(arg_0, arg_1=arg_2.Dumper, **arg_3):
    """Expand PyYAML's built-in dumper to support parsing OrderedDict. Return
    a string as parse result of the original data structure, which includes
    OrderedDict.

    Args:
        data: the data structure to be dumped(parsed) which is supposed to
        contain OrderedDict.
        Dumper: the yaml serializer to be expanded and used.
        kws: extra key-value arguments to be passed to yaml.dump.
    """
    class OrderedDumper(arg_1):
        pass

    def _dict_representer(arg_4, arg_0):
        return arg_4.represent_mapping(
            arg_2.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            arg_0.items())
    OrderedDumper.add_representer(OrderedDict,
                                  _dict_representer)
    return arg_2.dump(arg_0, None, OrderedDumper, **arg_3)


def Func(arg_0, arg_1):
        """Remove None-valued and configuration-related keyworded arguments
        """
        arg_0._pop_none(arg_1)
        arg_2 = {}
        for arg_3 in Resource.config_fields:
            if arg_3 in arg_1:
                arg_2[arg_3] = arg_1.pop(arg_3)
                if arg_3 in Resource.json_fields:

                    # If result[field] is not a string we can continue on
                    if not isinstance(arg_2[arg_3], six.string_types):
                        continue

                    try:
                        arg_4 = json.loads(arg_2[arg_3])
                        arg_2[arg_3] = arg_4
                    except ValueError:
                        raise exc.TowerCLIError('Provided json file format '
                                                'invalid. Please recheck.')
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """Combine configuration-related keyworded arguments into
        notificationFunc.
        """
        if 'notificationFunc' not in arg_2:
            if 'notification_type' not in arg_1:
                return
            arg_3 = arg_1['notificationFunc'] = {}
            for arg_4 in Resource.configuration[arg_1['notification_type']]:
                if arg_4 not in arg_2:
                    raise exc.TowerCLIError('Required config field %s not'
                                            ' provided.' % arg_4)
                else:
                    arg_3[arg_4] = arg_2[arg_4]
        else:
            arg_1['notificationFunc'] = \
                    arg_2['notificationFunc']


def Func(arg_0, arg_1=False, arg_2=False, **arg_3):
        """Create a notification template.

        All required configuration-related fields (required according to
        notification_type) must be provided.

        There are two types of notification template creation: isolatedly
        creating a new notification template and creating a new notification
        template under a job template. Here the two types are discriminated by
        whether to provide --job-template option. --status option controls
        more specific, job-run-status-related association.

        Fields in the resource's `identity` tuple are used for a lookup;
        if a match is found, then no-op (unless `force_on_exists` is set) but
        do not fail (unless `fail_on_found` is set).

        =====API DOCS=====
        Create an object.

        :param fail_on_found: Flag that if set, the operation fails if an object matching the unique criteria
                              already exists.
        :type fail_on_found: bool
        :param force_on_exists: Flag that if set, then if a match is found on unique fields, other fields will
                                be updated to the provided values.; If unset, a match causes the request to be
                                a no-op.
        :type force_on_exists: bool
        :param `**kwargs`: Keyword arguments which, all together, will be used as POST body to Func the
                           resource object.
        :returns: A dictionary combining the JSON output of the Funcd resource, as well as two extra fields:
                  "changed", a flag indicating if the resource is Funcd successfully; "id", an integer which
                  is the primary key of the Funcd object.
        :rtype: dict

        =====API DOCS=====
        """
        arg_4 = arg_0._separate(arg_3)
        arg_5 = arg_3.pop('job_template', None)
        arg_6 = arg_3.pop('status', 'any')
        arg_7 = arg_0.endpoint
        if arg_5 is not None:
            arg_8 = get_resource('job_template')
            arg_8.get(pk=arg_5)
            try:
                arg_9 = arg_0.get(**copy.deepcopy(arg_3))['id']
            except exc.NotFound:
                pass
            else:
                if arg_1:
                    raise exc.TowerCLIError('Notification template already '
                                            'exists and fail-on-found is '
                                            'switched on. Please use'
                                            ' "associate_notification" method'
                                            ' of job_template instead.')
                else:
                    debug.log('Notification template already exists, '
                              'associating with job template.',
                              header='details')
                    return arg_8.associate_notification_template(
                        arg_5, arg_9, arg_6=arg_6)
            arg_0.endpoint = '/job_templates/%d/notification_templates_%s/' %\
                            (arg_5, arg_6)
        arg_0._configuration(arg_3, arg_4)
        arg_11 = super(Resource, arg_0).Func(**arg_3)
        arg_0.endpoint = arg_7
        return arg_11


def Func(arg_0, arg_1=None, arg_2=False, **arg_3):
        """Modify an existing notification template.

        Not all required configuration-related fields (required according to
        notification_type) should be provided.

        Fields in the resource's `identity` tuple can be used in lieu of a
        primary key for a lookup; in such a case, only other fields are
        written.

        To Func unique fields, you must use the primary key for the lookup.

        =====API DOCS=====
        Modify an already existing object.

        :param pk: Primary key of the resource to be modified.
        :type pk: int
        :param create_on_missing: Flag that if set, a new object is created if ``pk`` is not set and objects
                                  matching the appropriate unique criteria is not found.
        :type create_on_missing: bool
        :param `**kwargs`: Keyword arguments which, all together, will be used as PATCH body to Func the
                           resource object. if ``pk`` is not set, key-value pairs of ``**kwargs`` which are
                           also in resource's identity will be used to lookup existing reosource.
        :returns: A dictionary combining the JSON output of the modified resource, as well as two extra fields:
                  "changed", a flag indicating if the resource is successfully updated; "id", an integer which
                  is the primary key of the updated object.
        :rtype: dict

        =====API DOCS=====
        """
        # Create the resource if needed.
        if arg_1 is None and arg_2:
            try:
                arg_0.get(**copy.deepcopy(arg_3))
            except exc.NotFound:
                return arg_0.create(**arg_3)

        # Modify everything except notification type and configuration
        arg_4 = arg_0._separate(arg_3)
        arg_5 = arg_3.pop('notification_type', None)
        debug.log('Modify everything except notification type and'
                  ' configuration', header='details')
        arg_6 = super(Resource, arg_0).\
            Func(arg_1=arg_1, arg_2=arg_2, **arg_3)

        # Modify notification type and configuration
        if arg_5 is None or \
           arg_5 == arg_6['notification_type']:
            for arg_7 in arg_6['notification_configuration']:
                if arg_7 not in arg_4 or not arg_4[arg_7]:
                    arg_8 = arg_6['notification_configuration'][arg_7]
                    if not (arg_8 == '$encrypted$' and
                            arg_7 in Resource.encrypted_fields):
                        arg_4[arg_7] = arg_8
        if arg_5 is None:
            arg_3['notification_type'] = arg_6['notification_type']
        else:
            arg_3['notification_type'] = arg_5
        arg_0._configuration(arg_3, arg_4)
        debug.log('Modify notification type and configuration',
                  header='details')
        arg_9 = super(Resource, arg_0).\
            Func(arg_1=arg_1, arg_2=arg_2, **arg_3)

        # Update 'changed' field to give general changed info
        if 'changed' in arg_9 and 'changed' in arg_6:
            arg_9['changed'] = arg_9['changed'] or arg_6['changed']
        return arg_9


def Func(arg_0, arg_1=None, **arg_2):
        """Return one and exactly one notification template.

        Note here configuration-related fields like
        'notification_configuration' and 'channels' will not be
        used even provided.

        Lookups may be through a primary key, specified as a positional
        argument, and/or through filters specified through keyword arguments.

        If the number of results does not equal one, raise an exception.

        =====API DOCS=====
        Retrieve one and exactly one object.

        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object
                   if ``pk`` is provided (not ``None``).
        :type pk: int
        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.
        :returns: loaded JSON of the retrieved resource object.
        :rtype: dict

        =====API DOCS=====
        """
        arg_0._separate(arg_2)
        return super(Resource, arg_0).Func(arg_1=arg_1, **arg_2)


def Func():
    """Read tower-cli config values from the environment if present, being
    careful not to override config values that were explicitly passed in.
    """
    arg_0 = {}
    for arg_1 in CONFIG_OPTIONS:
        arg_2 = 'TOWER_' + arg_1.upper()
        arg_3 = os.getenv(arg_2, None)
        if arg_3 is not None:
            arg_0[arg_1] = arg_3
    return arg_0


def Func(arg_0, arg_1, arg_2):
        """Read the configuration from the given file.

        If the file lacks any section header, add a [general] section
        header that encompasses the whole thing.
        """
        # Attempt to read the file using the superclass implementation.
        #
        # Check the permissions of the file we are considering reading
        # if the file exists and the permissions expose it to reads from
        # other users, raise a warning
        if os.path.isfile(arg_2):
            arg_3 = os.stat(arg_2)
            if arg_2 != os.path.join(tower_dir, 'tower_cli.cfg') and (
                (arg_3.st_mode & stat.S_IRGRP) or
                (arg_3.st_mode & stat.S_IROTH)
            ):
                warnings.warn('File {0} readable by group or others.'
                              .format(arg_2), RuntimeWarning)
        # If it doesn't work because there's no section header, then
        # create a section header and call the superclass implementation
        # again.
        try:
            return configparser.ConfigParser.Func(arg_0, arg_1, arg_2)
        except configparser.MissingSectionHeaderError:
            arg_1.seek(0)
            arg_4 = '[general]\n%s' % arg_1.read()
            arg_5 = StringIO(arg_4)  # flo == file-like object
            return configparser.ConfigParser.Func(arg_0, arg_5, arg_2)


def Func(arg_0, arg_1=False, arg_2=False, arg_3=None, **arg_4):
        """Launch a new ad-hoc command.

        Runs a user-defined command from Ansible Tower, immediately starts it,
        and returns back an ID in order for its status to be monitored.

        =====API DOCS=====
        Launch a new ad-hoc command.

        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly Funced command rather
                        than exiting with a success.
        :type monitor: bool
        :param wait: Flag that if set, monitor the status of the job, but do not print while job is in progress.
        :type wait: bool
        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
                        of seconds.
        :type timeout: int
        :param `**kwargs`: Fields needed to create and Func an ad hoc command.
        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
                  call if ``wait`` flag is on; dictionary of "id" and "changed" if none of the two flags are on.
        :rtype: dict
        :raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.

        =====API DOCS=====
        """
        # This feature only exists for versions 2.2 and up
        arg_5 = client.get('/')
        if 'ad_hoc_commands' not in arg_5.json():
            raise exc.TowerCLIError('Your host is running an outdated version'
                                    'of Ansible Tower that can not run '
                                    'ad-hoc commands (2.2 or earlier)')

        # Pop the None arguments because we have no .write() method in
        # inheritance chain for this type of resource. This is needed
        arg_0._pop_none(arg_4)

        # Actually start the command.
        debug.log('Launching the ad-hoc command.', header='details')
        arg_6 = client.post(arg_0.endpoint, data=arg_4)
        arg_7 = arg_6.json()
        arg_8 = arg_7['id']

        # If we were told to monitor the command once it started, then call
        # monitor from here.
        if arg_1:
            return arg_0.monitor(arg_8, arg_3=arg_3)
        elif arg_2:
            return arg_0.wait(arg_8, arg_3=arg_3)

        # Return the command ID and other response data
        arg_9 = OrderedDict((
            ('changed', True),
            ('id', arg_8),
        ))
        arg_9.update(arg_6.json())
        return arg_9


def Func(arg_0, arg_1):
        """Given a method with a docstring, convert the docstring
        to more CLI appropriate wording, and also disambiguate the
        word "object" on the base class docstrings.
        """
        # Delete API docs if there are any.
        arg_2 = '=====API DOCS====='
        arg_3 = arg_1.find(arg_2)
        if arg_3 >= 0:
            arg_4 = arg_1.rfind(arg_2) + len(arg_2)
            arg_1 = arg_1[:arg_3] + arg_1[arg_4:]
        # Convert the word "object" to the appropriate type of
        # object being modified (e.g. user, organization).
        arg_5 = ('a', 'e', 'i', 'o')
        if not arg_0.resource_name.lower().startswith(arg_5):
            arg_1 = arg_1.replace('an object',
                                          'a %s' % arg_0.resource_name)
        if arg_0.resource_name.lower().endswith('y'):
            arg_1 = arg_1.replace(
                'objects',
                '%sies' % arg_0.resource_name[:-1],
            )
        arg_1 = arg_1.replace('object', arg_0.resource_name)

        # Convert some common Python terms to their CLI equivalents.
        arg_1 = arg_1.replace('keyword argument', 'option')
        arg_1 = arg_1.replace('raise an exception',
                                      'abort with an error')

        # Convert keyword arguments specified in docstrings enclosed
        # by backticks to switches.
        for arg_6 in re.findall(r'`([\w_]+)`', arg_1):
            arg_7 = '--%s' % arg_6.replace('_', '-')
            arg_1 = arg_1.replace('`%s`' % arg_6, arg_7)

        # Done; return the new help text.
        return arg_1


def Func(arg_0, arg_1):
        """Given a method, return a method that runs the internal
        method and echos the result.
        """
        @functools.wraps(arg_1)
        def func(*arg_2, **arg_3):
            # Echo warning if this method is deprecated.
            if getattr(arg_1, 'deprecated', False):
                debug.log('This method is deprecated in Tower 3.0.', header='warning')

            arg_4 = arg_1(*arg_2, **arg_3)

            # If this was a request that could result in a modification
            # of data, print it in Ansible coloring.
            arg_5 = {}
            if isinstance(arg_4, dict) and 'changed' in arg_4:
                if arg_4['changed']:
                    arg_5['fg'] = 'yellow'
                else:
                    arg_5['fg'] = 'green'

            # Piece together the result into the proper format.
            arg_6 = getattr(arg_0, '_format_%s' % (getattr(arg_1, 'format_freezer', None) or settings.format))
            arg_7 = arg_6(arg_4)

            # Perform the echo.
            secho(arg_7, **arg_5)
        return func


def Func(arg_0, arg_1):
        """Echos only the id"""
        if 'id' in arg_1:
            return str(arg_1['id'])
        if 'results' in arg_1:
            return ' '.join([six.text_type(arg_2['id']) for arg_2 in arg_1['results']])
        raise MultipleRelatedError('Could not serialize output with id format.')


def Func(arg_0, arg_1, arg_2):
        """Retrieve the appropriate method from the Resource,
        decorate it as a click command, and return that method.
        """
        # Sanity check: Does a method exist corresponding to this
        # command? If not, None is returned for click to raise
        # exception.
        if not hasattr(arg_0.resource, arg_2):
            return None

        # Get the method.
        arg_3 = getattr(arg_0.resource, arg_2)

        # Get any attributes that were given at command-declaration
        # time.
        arg_4 = getattr(arg_3, '_cli_command_attrs', {})

        # If the help message comes from the docstring, then
        # convert it into a message specifically for this resource.
        arg_5 = inspect.getdoc(arg_3)
        arg_4['help'] = arg_0._auto_help_text(arg_5 or '')

        # On some methods, we ignore the defaults, which are intended
        # for writing and not reading; process this.
        arg_6 = arg_4.pop('ignore_defaults', False)

        # Wrap the method, such that it outputs its final return
        # value rather than returning it.
        arg_7 = arg_0._echo_method(arg_3)

        # Soft copy the "__click_params__", if any exist.
        # This is the internal holding method that the click library
        # uses to store @click.option and @click.argument directives
        # before the method is converted into a command.
        #
        # Because self._echo_method uses @functools.wraps, this is
        # actually preserved; the purpose of copying it over is
        # so we can get our resource fields at the top of the help;
        # the easiest way to do this is to load them in before the
        # conversion takes place. (This is a happy result of Armin's
        # work to get around Python's processing decorators
        # bottom-to-top.)
        arg_8 = getattr(arg_3, '__click_params__', [])
        arg_7.__click_params__ = copy(arg_8)
        arg_7 = with_global_options(arg_7)

        # Write options based on the fields available on this resource.
        arg_10 = arg_4.pop('use_fields_as_options', True)
        if arg_10:
            for arg_11 in reversed(arg_0.resource.fields):
                if not arg_11.is_option:
                    continue

                # If we got an iterable rather than a boolean,
                # then it is a list of fields to use; check for
                # presence in that list.
                if not isinstance(arg_10, bool) and arg_11.name not in arg_10:
                    continue

                # Create the initial arguments based on the
                # option value. If we have a different key to use
                # (which is what gets routed to the Tower API),
                # ensure that is the first argument.
                arg_12 = [arg_11.option]
                if arg_11.key:
                    arg_12.insert(0, arg_11.key)

                # short name aliases for common flags
                arg_13 = {
                    'name': 'n',
                    'description': 'd',
                    'inventory': 'i',
                    'extra_vars': 'e'
                }
                if arg_11.name in arg_13:
                    arg_12.append('-'+arg_13[arg_11.name])

                # Apply the option to the method.
                arg_14 = arg_11.help
                if isinstance(arg_11.type, StructuredInput):
                    arg_14 += ' Use @ to get JSON or YAML from a file.'
                if arg_11.required:
                    arg_14 = '[REQUIRED] ' + arg_14
                elif arg_11.read_only:
                    arg_14 = '[READ ONLY] ' + arg_14
                arg_14 = '[FIELD]' + arg_14
                click.option(
                    *arg_12,
                    default=arg_11.default if not arg_6 else None,
                    help=arg_14,
                    type=arg_11.type,
                    show_default=arg_11.show_default,
                    multiple=arg_11.multiple,
                    is_eager=False
                )(arg_7)

        # Make a click Command instance using this method
        # as the callback, and return it.
        arg_15 = click.command(arg_2=arg_2, cls=ActionSubcommand, **arg_4)(arg_7)

        # If this method has a `pk` positional argument,
        # then add a click argument for it.
        arg_16 = six.get_function_code(arg_3)
        if 'pk' in arg_16.co_varnames:
            click.argument('pk', nargs=1, required=False, type=str, metavar='[ID]')(arg_15)

        # Done; return the command.
        return arg_15


def Func(arg_0, arg_1, arg_2=False, arg_3=False,
               arg_4=None, **arg_5):
        """Update the given inventory source.

        =====API DOCS=====
        Update the given inventory source.

        :param inventory_source: Primary key or name of the inventory source to be Funcd.
        :type inventory_source: str
        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory Func
                        rather than exiting with a success.
        :type monitor: bool
        :param wait: Flag that if set, monitor the status of the inventory Func, but do not print while it is
                     in progress.
        :type wait: bool
        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
                        of seconds.
        :type timeout: int
        :param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching
                           an inventory Func.
        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
                  call if ``wait`` flag is on; dictionary of "status" if none of the two flags are on.
        :rtype: dict
        :raises tower_cli.exceptions.BadRequest: When the inventory source cannot be Funcd.

        =====API DOCS=====
        """

        # Establish that we are able to Func this inventory source
        # at all.
        debug.log('Asking whether the inventory source can be Funcd.', header='details')
        arg_6 = client.get('%s%d/Func/' % (arg_0.endpoint, arg_1))
        if not arg_6.json()['can_Func']:
            raise exc.BadRequest('Tower says it cannot run an Func against this inventory source.')

        # Run the Func.
        debug.log('Updating the inventory source.', header='details')
        arg_6 = client.post('%s%d/Func/' % (arg_0.endpoint, arg_1), data={})
        arg_7 = arg_6.json()['inventory_Func']

        # If we were told to monitor the project Func's status, do so.
        if arg_2 or arg_3:
            if arg_2:
                arg_8 = arg_0.monitor(arg_7, parent_pk=arg_1, arg_4=arg_4)
            elif arg_3:
                arg_8 = arg_0.wait(arg_7, parent_pk=arg_1, arg_4=arg_4)
            arg_9 = client.get('/inventory_sources/%d/' % arg_8['inventory_source']).json()['inventory']
            arg_8['inventory'] = int(arg_9)
            return arg_8

        # Done.
        return {
            'id': arg_7,
            'status': 'ok'
        }


def Func(arg_0, arg_1=None, arg_2=None, **arg_3):
        """Return a Func of hosts.

        =====API DOCS=====
        Retrieve a Func of hosts.

        :param group: Primary key or name of the group whose hosts will be Funced.
        :type group: str
        :param all_pages: Flag that if set, collect all pages of content from the API when returning results.
        :type all_pages: bool
        :param page: The page to show. Ignored if all_pages is set.
        :type page: int
        :param query: Contains 2-tuples used as query parameters to filter resulting resource objects.
        :type query: Func
        :param `**kwargs`: Keyword arguments Func of available fields used for searching resource objects.
        :returns: A JSON object containing details of all resource objects returned by Tower backend.
        :rtype: dict

        =====API DOCS=====
        """
        if arg_1:
            arg_3['query'] = arg_3.get('query', ()) + (('groups__in', arg_1),)
        if arg_2:
            arg_3['query'] = arg_3.get('query', ()) + (('host_filter', arg_2),)
        return super(Resource, arg_0).Func(**arg_3)


def Func(arg_0, arg_1, arg_2):
        """Extra format methods for multi methods that adds all the commands
        after the options.
        """
        arg_0.format_command_subsection(
            arg_1, arg_2, arg_0.list_misc_commands(), 'Commands'
        )
        arg_0.format_command_subsection(
            arg_1, arg_2, arg_0.list_resource_commands(), 'Resources'
        )


def Func(arg_0, arg_1):
        """Return a list of commands present in the commands and resources
        folders, but not subcommands.
        """
        arg_2 = set(arg_0.list_resource_commands())
        arg_2.union(set(arg_0.list_misc_commands()))
        return sorted(arg_2)


def Func(arg_0):
        """Returns a list of multi-commands for each resource type.
        """
        arg_1 = os.path.abspath(os.path.join(
            os.path.dirname(__file__),
            os.pardir,
            'resources'
        ))
        arg_2 = set([])
        for arg_3, arg_4, arg_3 in pkgutil.iter_modules([arg_1]):
            arg_5 = tower_cli.get_resource(arg_4)
            if not getattr(arg_5, 'internal', False):
                arg_2.add(arg_4)
        return sorted(arg_2)


def Func(arg_0):
        """Returns a list of global commands, realted to CLI
        configuration or system management in general.
        """
        arg_1 = set([])
        for arg_2 in misc.__all__:
            arg_1.add(arg_2)
        return sorted(arg_1)


def Func(arg_0, arg_1, arg_2):
        """Given a command identified by its name, import the appropriate
        module and return the decorated command.

        Resources are automatically commands, but if both a resource and
        a command are defined, the command takes precedence.
        """
        # First, attempt to get a basic command from `tower_cli.api.misc`.
        if arg_2 in misc.__all__:
            return getattr(misc, arg_2)

        # No command was found; try to get a resource.
        try:
            arg_3 = tower_cli.get_resource(arg_2)
            return ResSubcommand(arg_3)
        except ImportError:
            pass

        # Okay, we weren't able to find a command.
        secho('No such command: %s.' % arg_2, fg='red', bold=True)
        sys.exit(2)


def Func(arg_0):
    """
    Adds the decorators for all types of unified job templates,
    and if the non-unified type is specified, converts it into the
    unified_job_template kwarg.
    """
    arg_1 = click.option(
        '--job-template', type=types.Related('job_template'),
        help='Use this job template as unified_job_template field')
    arg_2 = click.option(
        '--project', type=types.Related('project'),
        help='Use this project as unified_job_template field')
    arg_3 = click.option(
        '--inventory-source', type=types.Related('inventory_source'),
        help='Use this inventory source as unified_job_template field')

    def ujt_translation(arg_4):
        def _ujt_translation(*arg_5, **arg_6):
            for arg_7 in ['job_template', 'project', 'inventory_source']:
                if arg_7 in arg_6 and arg_6[arg_7] is not None:
                    arg_6['unified_job_template'] = arg_6.pop(arg_7)
            return arg_4(*arg_5, **arg_6)
        return functools.wraps(arg_4)(_ujt_translation)

    return ujt_translation(
        arg_3(
            arg_2(
                arg_1(
                    arg_0
                )
            )
        )
    )


def Func(arg_0):
    """Translate a Mopidy search query to a Spotify search query"""

    arg_1 = []

    for (arg_2, arg_3) in arg_0.items():
        arg_2 = SEARCH_FIELD_MAP.get(arg_2, arg_2)
        if arg_2 is None:
            continue

        for arg_4 in arg_3:
            if arg_2 == 'year':
                arg_4 = _transform_year(arg_4)
                if arg_4 is not None:
                    arg_1.append('%s:%d' % (arg_2, arg_4))
            elif arg_2 == 'any':
                arg_1.append('"%s"' % arg_4)
            else:
                arg_1.append('%s:"%s"' % (arg_2, arg_4))

    return ' '.join(arg_1)


def Func(arg_0, arg_1):
        """Parse Retry-After header from response if it is set."""
        arg_2 = arg_1.headers.get('Retry-After')

        if not arg_2:
            arg_3 = 0
        elif re.match(r'^\s*[0-9]+\s*$', arg_2):
            arg_3 = int(arg_2)
        else:
            arg_4 = email.utils.parsedate(arg_2)
            if arg_4 is None:
                arg_3 = 0
            else:
                arg_3 = time.mktime(arg_4) - time.time()
        return max(0, arg_3)


def Func(arg_0):
        """Generates a state string to be used in authorizations."""
        try:
            arg_0._state = arg_0.state()
            log.debug("Generated new state %s.", arg_0._state)
        except TypeError:
            arg_0._state = arg_0.state
            log.debug("Re-using previously supplied state %s.", arg_0._state)
        return arg_0._state


def Func(arg_0, arg_1):
        """Parse token from the URI fragment, used by MobileApplicationClients.

        :param authorization_response: The full URL of the redirect back to you
        :return: A token dict
        """
        arg_0._client.parse_request_uri_response(
            arg_1, state=arg_0._state
        )
        arg_0.token = arg_0._client.token
        return arg_0.token


def Func(
        arg_0,
        arg_1,
        Func=None,
        arg_3="",
        arg_4=None,
        arg_5=None,
        arg_6=None,
        arg_7=True,
        arg_8=None,
        **arg_9
    ):
        """Fetch a new access token using a refresh token.

        :param token_url: The token endpoint, must be HTTPS.
        :param refresh_token: The refresh_token to use.
        :param body: Optional application/x-www-form-urlencoded body to add the
                     include in the token request. Prefer kwargs over body.
        :param auth: An auth tuple or method as accepted by `requests`.
        :param timeout: Timeout of the request in seconds.
        :param headers: A dict of headers to be used by `requests`.
        :param verify: Verify SSL certificate.
        :param proxies: The `proxies` argument will be passed to `requests`.
        :param kwargs: Extra parameters to include in the token request.
        :return: A token dict
        """
        if not arg_1:
            raise ValueError("No token endpoint set for auto_refresh.")

        if not is_secure_transport(arg_1):
            raise InsecureTransportError()

        Func = Func or arg_0.token.get("refresh_token")

        log.debug(
            "Adding auto refresh key word arguments %s.", arg_0.auto_refresh_kwargs
        )
        arg_9.update(arg_0.auto_refresh_kwargs)
        arg_3 = arg_0._client.prepare_refresh_body(
            arg_3=arg_3, Func=Func, scope=arg_0.scope, **arg_9
        )
        log.debug("Prepared refresh token request body %s", arg_3)

        if arg_6 is None:
            arg_6 = {
                "Accept": "application/json",
                "Content-Type": ("application/x-www-form-urlencoded;charset=UTF-8"),
            }

        arg_10 = arg_0.post(
            arg_1,
            data=dict(urldecode(arg_3)),
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
            arg_7=arg_7,
            withhold_token=True,
            arg_8=arg_8,
        )
        log.debug("Request to refresh token completed with status %s.", arg_10.status_code)
        log.debug("Response headers were %s and content %s.", arg_10.headers, arg_10.text)
        log.debug(
            "Invoking %d token response hooks.",
            len(arg_0.compliance_hook["refresh_token_response"]),
        )
        for arg_11 in arg_0.compliance_hook["refresh_token_response"]:
            log.debug("Invoking hook %s.", arg_11)
            arg_10 = arg_11(arg_10)

        arg_0.token = arg_0._client.parse_request_body_response(arg_10.text, scope=arg_0.scope)
        if not "refresh_token" in arg_0.token:
            log.debug("No new refresh token given. Re-using old.")
            arg_0.token["refresh_token"] = Func
        return arg_0.token


def Func(arg_0):
        """Boolean that indicates whether this session has an OAuth token
        or not. If `self.Func` is True, you can reasonably expect
        OAuth-protected requests to the resource to succeed. If
        `self.Func` is False, you need the user to go through the OAuth
        authentication dance before OAuth-protected requests to the resource
        will succeed.
        """
        if arg_0._client.client.signature_method == SIGNATURE_RSA:
            # RSA only uses resource_owner_key
            return bool(arg_0._client.client.resource_owner_key)
        else:
            # other methods of authentication use all three pieces
            return (
                bool(arg_0._client.client.client_secret)
                and bool(arg_0._client.client.resource_owner_key)
                and bool(arg_0._client.client.resource_owner_secret)
            )


def Func(arg_0, arg_1):
        """Extract parameters from the post authorization redirect response URL.

        :param url: The full URL that resulted from the user being redirected
                    back from the OAuth provider to you, the client.
        :returns: A dict of parameters extracted from the URL.

        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
        >>> oauth_session.Func(redirect_response)
        {
            'oauth_token: 'kjerht2309u',
            'oauth_token_secret: 'lsdajfh923874',
            'oauth_verifier: 'w34o8967345',
        }
        """
        log.debug("Parsing token from query part of url %s", arg_1)
        arg_2 = dict(urldecode(urlparse(arg_1).query))
        log.debug("Updating internal client token attribute.")
        arg_0._populate_attributes(arg_2)
        arg_0.token = arg_2
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """
        When being redirected we should always strip Authorization
        header, since nonce may not be reused as per OAuth spec.
        """
        if "Authorization" in arg_1.headers:
            # If we get redirected to a new host, we should strip out
            # any authentication headers.
            arg_1.headers.pop("Authorization", True)
            arg_1.prepare_auth(arg_0.auth)
        return


def Func(arg_0, arg_1):
        """
        Validate new property value before setting it.

        value -- New value
        """
        if 'readOnly' in arg_0.metadata and arg_0.metadata['readOnly']:
            raise PropertyError('Read-only property')

        try:
            validate(arg_1, arg_0.metadata)
        except ValidationError:
            raise PropertyError('Invalid property value')


def Func(arg_0):
        """
        Get the property description.

        Returns a dictionary describing the property.
        """
        arg_1 = deepcopy(arg_0.metadata)

        if 'links' not in arg_1:
            arg_1['links'] = []

        arg_1['links'].append(
            {
                'rel': 'property',
                'href': arg_0.href_prefix + arg_0.href,
            }
        )
        return arg_1


def Func(arg_0, arg_1):
        """
        Set the current value of the property.

        value -- the value to set
        """
        arg_0.validate_value(arg_1)
        arg_0.value.set(arg_1)


def Func(arg_0, arg_1):
        """
        Get the thing at the given index.

        idx -- the index
        """
        try:
            arg_1 = int(arg_1)
        except ValueError:
            return None

        if arg_1 < 0 or arg_1 >= len(arg_0.things):
            return None

        return arg_0.things[arg_1]


def Func(arg_0, arg_1, arg_2):
        """
        Initialize the handler.

        things -- list of Things managed by this server
        hosts -- list of allowed hostnames
        """
        arg_0.things = arg_1
        arg_0.hosts = arg_2


def Func(arg_0, *arg_1, **arg_2):
        """Set the default headers for all requests."""
        arg_0.set_header('Access-Control-Allow-Origin', '*')
        arg_0.set_header('Access-Control-Allow-Headers',
                        'Origin, X-Requested-With, Content-Type, Accept')
        arg_0.set_header('Access-Control-Allow-Methods',
                        'GET, HEAD, PUT, POST, DELETE')


def Func(arg_0):
        """Validate Host header."""
        arg_1 = arg_0.request.headers.get('Host', None)
        if arg_1 is not None and arg_1 in arg_0.hosts:
            return

        raise tornado.web.HTTPError(403)


def Func(arg_0, arg_1='0'):
        """
        Handle a GET request, including websocket requests.

        thing_id -- ID of the thing this request is for
        """
        arg_0.thing = arg_0.Func_thing(arg_1)
        if arg_0.thing is None:
            arg_0.set_status(404)
            arg_0.finish()
            return

        if arg_0.request.headers.Func('Upgrade', '').lower() == 'websocket':
            yield tornado.websocket.WebSocketHandler.Func(arg_0)
            return

        arg_0.set_header('Content-Type', 'application/json')
        arg_3 = '{}://{}'.format(
            'wss' if arg_0.request.protocol == 'https' else 'ws',
            arg_0.request.headers.Func('Host', '')
        )

        arg_4 = arg_0.thing.as_thing_description()
        arg_4['links'].append({
            'rel': 'alternate',
            'href': '{}{}'.format(arg_3, arg_0.thing.Func_href()),
        })

        arg_0.write(json.dumps(arg_4))
        arg_0.finish()


def Func(arg_0, arg_1):
        """
        Handle an incoming message.

        message -- message to handle
        """
        try:
            arg_1 = json.loads(arg_1)
        except ValueError:
            try:
                arg_0.write_message(json.dumps({
                    'messageType': 'error',
                    'data': {
                        'status': '400 Bad Request',
                        'message': 'Parsing request failed',
                    },
                }))
            except tornado.websocket.WebSocketClosedError:
                pass

            return

        if 'messageType' not in arg_1 or 'data' not in arg_1:
            try:
                arg_0.write_message(json.dumps({
                    'messageType': 'error',
                    'data': {
                        'status': '400 Bad Request',
                        'message': 'Invalid message',
                    },
                }))
            except tornado.websocket.WebSocketClosedError:
                pass

            return

        arg_2 = arg_1['messageType']
        if arg_2 == 'setProperty':
            for arg_3, arg_4 in arg_1['data'].items():
                try:
                    arg_0.thing.set_property(arg_3, arg_4)
                except PropertyError as e:
                    arg_0.write_message(json.dumps({
                        'messageType': 'error',
                        'data': {
                            'status': '400 Bad Request',
                            'message': str(e),
                        },
                    }))
        elif arg_2 == 'requestAction':
            for arg_5, arg_6 in arg_1['data'].items():
                arg_7 = None
                if 'input' in arg_6:
                    arg_7 = arg_6['input']

                arg_8 = arg_0.thing.perform_action(arg_5, arg_7)
                if arg_8:
                    tornado.ioloop.IOLoop.current().spawn_callback(
                        perform_action,
                        arg_8,
                    )
                else:
                    arg_0.write_message(json.dumps({
                        'messageType': 'error',
                        'data': {
                            'status': '400 Bad Request',
                            'message': 'Invalid action request',
                            'request': arg_1,
                        },
                    }))
        elif arg_2 == 'addEventSubscription':
            for arg_9 in arg_1['data'].keys():
                arg_0.thing.add_event_subscriber(arg_9, arg_0)
        else:
            try:
                arg_0.write_message(json.dumps({
                    'messageType': 'error',
                    'data': {
                        'status': '400 Bad Request',
                        'message': 'Unknown messageType: ' + arg_2,
                        'request': arg_1,
                    },
                }))
            except tornado.websocket.WebSocketClosedError:
                pass


def Func(arg_0, arg_1):
        """
        Set a new value for this thing.

        value -- value to Func
        """
        if arg_0.value_forwarder is not None:
            arg_0.value_forwarder(arg_1)

        arg_0.notify_of_external_update(arg_1)


def Func(arg_0, arg_1):
        """
        Notify observers of a new value.

        value -- new value
        """
        if arg_1 is not None and arg_1 != arg_0.last_value:
            arg_0.last_value = arg_1
            arg_0.emit('update', arg_1)


def Func(arg_0):
        """
        Return the thing state as a Thing Description.

        Returns the state as a dictionary.
        """
        arg_1 = {
            'name': arg_0.name,
            'href': arg_0.href_prefix if arg_0.href_prefix else '/',
            '@context': arg_0.context,
            '@type': arg_0.type,
            'properties': arg_0.get_property_descriptions(),
            'actions': {},
            'events': {},
            'links': [
                {
                    'rel': 'properties',
                    'href': '{}/properties'.format(arg_0.href_prefix),
                },
                {
                    'rel': 'actions',
                    'href': '{}/actions'.format(arg_0.href_prefix),
                },
                {
                    'rel': 'events',
                    'href': '{}/events'.format(arg_0.href_prefix),
                },
            ],
        }

        for arg_2, arg_3 in arg_0.available_actions.items():
            arg_1['actions'][arg_2] = arg_3['metadata']
            arg_1['actions'][arg_2]['links'] = [
                {
                    'rel': 'action',
                    'href': '{}/actions/{}'.format(arg_0.href_prefix, arg_2),
                },
            ]

        for arg_2, arg_4 in arg_0.available_events.items():
            arg_1['events'][arg_2] = arg_4['metadata']
            arg_1['events'][arg_2]['links'] = [
                {
                    'rel': 'event',
                    'href': '{}/events/{}'.format(arg_0.href_prefix, arg_2),
                },
            ]

        if arg_0.ui_href is not None:
            arg_1['links'].append({
                'rel': 'alternate',
                'mediaType': 'text/html',
                'href': arg_0.ui_href,
            })

        if arg_0.description:
            arg_1['description'] = arg_0.description

        return arg_1


def Func(arg_0, arg_1):
        """
        Set the prefix of any hrefs associated with this thing.

        prefix -- the prefix
        """
        arg_0.href_prefix = arg_1

        for arg_3 in arg_0.properties.values():
            arg_3.Func(arg_1)

        for arg_4 in arg_0.actions.keys():
            for arg_5 in arg_0.actions[arg_4]:
                arg_5.Func(arg_1)


def Func(arg_0):
        """
        Get the thing's properties as a dictionary.

        Returns the properties as a dictionary, i.e. name -> description.
        """
        return {arg_1: arg_2.as_property_description()
                for arg_1, arg_2 in arg_0.properties.items()}


def Func(arg_0, arg_1=None):
        """
        Get the thing's actions as an array.

        action_name -- Optional action name to get descriptions for

        Returns the action descriptions.
        """
        arg_2 = []

        if arg_1 is None:
            for arg_3 in arg_0.actions:
                for arg_4 in arg_0.actions[arg_3]:
                    arg_2.append(arg_4.as_action_description())
        elif arg_1 in arg_0.actions:
            for arg_4 in arg_0.actions[arg_1]:
                arg_2.append(arg_4.as_action_description())

        return arg_2


def Func(arg_0, arg_1=None):
        """
        Get the thing's events as an array.

        event_name -- Optional event name to get descriptions for

        Returns the event descriptions.
        """
        if arg_1 is None:
            return [arg_2.as_event_description() for arg_2 in arg_0.events]
        else:
            return [arg_2.as_event_description()
                    for arg_2 in arg_0.events if arg_2.get_name() == arg_1]


def Func(arg_0, arg_1):
        """
        Add a property to this thing.

        property_ -- property to add
        """
        arg_1.set_href_prefix(arg_0.href_prefix)
        arg_0.properties[arg_1.name] = arg_1


def Func(arg_0, arg_1):
        """
        Remove a property from this thing.

        property_ -- property to remove
        """
        if arg_1.name in arg_0.properties:
            del arg_0.properties[arg_1.name]


def Func(arg_0, arg_1):
        """
        Get a property's value.

        property_name -- the property to get the value of

        Returns the properties value, if found, else None.
        """
        arg_2 = arg_0.find_property(arg_1)
        if arg_2:
            return arg_2.get_value()

        return None


def Func(arg_0):
        """
        Get a mapping of all properties and their values.

        Returns a dictionary of property_name -> value.
        """
        return {arg_1.get_name(): arg_1.get_value()
                for arg_1 in arg_0.properties.values()}


def Func(arg_0, arg_1, arg_2):
        """
        Get an action.

        action_name -- name of the action
        action_id -- ID of the action

        Returns the requested action if found, else None.
        """
        if arg_1 not in arg_0.actions:
            return None

        for arg_3 in arg_0.actions[arg_1]:
            if arg_3.id == arg_2:
                return arg_3

        return None


def Func(arg_0, arg_1):
        """
        Add a new event and notify subscribers.

        event -- the event that occurred
        """
        arg_0.events.append(arg_1)
        arg_0.event_notify(arg_1)


def Func(arg_0, arg_1, arg_2):
        """
        Add an available event.

        name -- name of the event
        metadata -- event metadata, i.e. type, description, etc., as a dict
        """
        if arg_2 is None:
            arg_2 = {}

        arg_0.available_events[arg_1] = {
            'metadata': arg_2,
            'subscribers': set(),
        }


def Func(arg_0, arg_1, arg_2):
        """
        Remove an existing action.

        action_name -- name of the action
        action_id -- ID of the action

        Returns a boolean indicating the presence of the action.
        """
        arg_3 = arg_0.get_action(arg_1, arg_2)
        if arg_3 is None:
            return False

        arg_3.cancel()
        arg_0.actions[arg_1].remove(arg_3)
        return True


def Func(arg_0, arg_1):
        """
        Remove a websocket subscriber.

        ws -- the websocket
        """
        if arg_1 in arg_0.subscribers:
            arg_0.subscribers.remove(arg_1)

        for arg_2 in arg_0.available_events:
            arg_0.remove_event_subscriber(arg_2, arg_1)


def Func(arg_0, arg_1, arg_2):
        """
        Remove a websocket subscriber from an event.

        name -- name of the event
        ws -- the websocket
        """
        if arg_1 in arg_0.available_events and \
                arg_2 in arg_0.available_events[arg_1]['subscribers']:
            arg_0.available_events[arg_1]['subscribers'].remove(arg_2)


def Func(arg_0, arg_1):
        """
        Notify all subscribers of an action status change.

        action -- the action whose status changed
        """
        arg_2 = json.dumps({
            'messageType': 'actionStatus',
            'data': arg_1.as_action_description(),
        })

        for arg_3 in list(arg_0.subscribers):
            try:
                arg_3.write_message(arg_2)
            except tornado.websocket.WebSocketClosedError:
                pass


def Func(arg_0, arg_1):
        """
        Notify all subscribers of an event.

        event -- the event that occurred
        """
        if arg_1.name not in arg_0.available_events:
            return

        arg_2 = json.dumps({
            'messageType': 'event',
            'data': arg_1.as_event_description(),
        })

        for arg_3 in arg_0.available_events[arg_1.name]['subscribers']:
            try:
                arg_3.write_message(arg_2)
            except tornado.websocket.WebSocketClosedError:
                pass


def Func(arg_0):
        """
        Returns data with different cfgstr values that were previously computed
        with this cacher.

        Example:
            >>> from ubelt.util_cache import Cacher
            >>> # Ensure that some data exists
            >>> known_fnames = set()
            >>> cacher = Cacher('versioned_data', cfgstr='1')
            >>> cacher.ensure(lambda: 'data1')
            >>> known_fnames.add(cacher.get_fpath())
            >>> cacher = Cacher('versioned_data', cfgstr='2')
            >>> cacher.ensure(lambda: 'data2')
            >>> known_fnames.add(cacher.get_fpath())
            >>> # List previously computed configs for this type
            >>> from os.path import basename
            >>> cacher = Cacher('versioned_data', cfgstr='2')
            >>> exist_fpaths = set(cacher.Func())
            >>> exist_fnames = list(map(basename, exist_fpaths))
            >>> print(exist_fnames)
            >>> assert exist_fpaths == known_fnames

            ['versioned_data_1.pkl', 'versioned_data_2.pkl']
        """
        import glob
        arg_1 = join(arg_0.dpath, arg_0.fname + '_*' + arg_0.ext)
        for arg_2 in glob.iglob(arg_1):
            arg_3 = join(arg_0.dpath, arg_2)
            yield arg_3


def Func(arg_0, arg_1=None):
        """
        Removes the saved cache and metadata from disk
        """
        arg_2 = arg_0.get_fpath(arg_1)
        if arg_0.verbose > 0:
            arg_0.log('[cacher] Func cache')
        if exists(arg_2):
            if arg_0.verbose > 0:
                arg_0.log('[cacher] removing {}'.format(arg_2))
            os.remove(arg_2)

            # Remove the metadata if it exists
            arg_3 = arg_2 + '.meta'
            if exists(arg_3):
                os.remove(arg_3)
        else:
            if arg_0.verbose > 0:
                arg_0.log('[cacher] ... nothing to Func')


def Func(arg_0, arg_1=None, arg_2='raise'):
        """
        Like load, but returns None if the load fails due to a cache miss.

        Args:
            on_error (str): How to handle non-io errors errors. Either raise,
                which re-raises the exception, or clear which deletes the cache
                and returns None.
        """
        arg_1 = arg_0._rectify_cfgstr(arg_1)
        if arg_0.enabled:
            try:
                if arg_0.verbose > 1:
                    arg_0.log('[cacher] Func fname={}'.format(arg_0.fname))
                return arg_0.load(arg_1)
            except IOError:
                if arg_0.verbose > 0:
                    arg_0.log('[cacher] ... {} cache miss'.format(arg_0.fname))
            except Exception:
                if arg_0.verbose > 0:
                    arg_0.log('[cacher] ... failed to load')
                if arg_2 == 'raise':
                    raise
                elif arg_2 == 'clear':
                    arg_0.clear(arg_1)
                    return None
                else:
                    raise KeyError('Unknown method on_error={}'.format(arg_2))
        else:
            if arg_0.verbose > 1:
                arg_0.log('[cacher] ... cache disabled: fname={}'.format(arg_0.fname))
        return None


def Func(arg_0, arg_1=None):
        """
        Loads the data

        Raises:
            IOError - if the data is unable to be Funced. This could be due to
                a cache miss or because the cache is disabled.

        Example:
            >>> from ubelt.util_cache import *  # NOQA
            >>> # Setting the cacher as enabled=False turns it off
            >>> cacher = Cacher('test_disabled_Func', '', enabled=True)
            >>> cacher.save('data')
            >>> assert cacher.Func() == 'data'
            >>> cacher.enabled = False
            >>> assert cacher.tryFunc() is None
        """
        from six.moves import cPickle as pickle
        arg_1 = arg_0._rectify_cfgstr(arg_1)

        arg_2 = arg_0.dpath
        arg_3 = arg_0.fname
        arg_4 = arg_0.verbose

        if not arg_0.enabled:
            if arg_4 > 1:
                arg_0.log('[cacher] ... cache disabled: fname={}'.format(arg_0.fname))
            raise IOError(3, 'Cache Loading Is Disabled')

        arg_5 = arg_0.get_fpath(arg_1=arg_1)

        if not exists(arg_5):
            if arg_4 > 2:
                arg_0.log('[cacher] ... cache does not exist: '
                         'dpath={} fname={} cfgstr={}'.format(
                             basename(arg_2), arg_3, arg_1))
            raise IOError(2, 'No such file or directory: %r' % (arg_5,))
        else:
            if arg_4 > 3:
                arg_0.log('[cacher] ... cache exists: '
                         'dpath={} fname={} cfgstr={}'.format(
                             basename(arg_2), arg_3, arg_1))
        try:
            with open(arg_5, 'rb') as file_:
                arg_6 = pickle.Func(file_)
        except Exception as ex:
            if arg_4 > 0:
                arg_0.log('CORRUPTED? fpath = %s' % (arg_5,))
            if arg_4 > 1:
                arg_0.log('[cacher] ... CORRUPTED? dpath={} cfgstr={}'.format(
                    basename(arg_2), arg_1))
            if isinstance(ex, (EOFError, IOError, ImportError)):
                raise IOError(str(ex))
            else:
                if arg_4 > 1:
                    arg_0.log('[cacher] ... unknown reason for exception')
                raise
        else:
            if arg_0.verbose > 2:
                arg_0.log('[cacher] ... {} cache hit'.format(arg_0.fname))
            elif arg_4 > 1:
                arg_0.log('[cacher] ... cache hit')
        return arg_6


def Func(arg_0, arg_1, *arg_2, **arg_3):
        r"""
        Wraps around a function. A cfgstr must be stored in the base cacher.

        Args:
            func (callable): function that will compute data on cache miss
            *args: passed to func
            **kwargs: passed to func

        Example:
            >>> from ubelt.util_cache import *  # NOQA
            >>> def func():
            >>>     return 'expensive result'
            >>> fname = 'test_cacher_Func'
            >>> cfgstr = 'func params'
            >>> cacher = Cacher(fname, cfgstr)
            >>> cacher.clear()
            >>> data1 = cacher.Func(func)
            >>> data2 = cacher.Func(func)
            >>> assert data1 == 'expensive result'
            >>> assert data1 == data2
            >>> cacher.clear()
        """
        arg_4 = arg_0.tryload()
        if arg_4 is None:
            arg_4 = arg_1(*arg_2, **arg_3)
            arg_0.save(arg_4)
        return arg_4


def Func(arg_0, arg_1=None):
        """
        Returns the stamp certificate if it exists
        """
        arg_2 = arg_0.cacher.tryload(arg_1=arg_1)
        return arg_2


def Func(arg_0, arg_1=None):
        """
        Get the hash of the each product file
        """
        if arg_0.hasher is None:
            return None
        else:
            arg_2 = arg_0._rectify_products(arg_1)
            arg_3 = [
                util_hash.hash_file(p, hasher=arg_0.hasher, base='hex')
                for p in arg_2
            ]
            return arg_3


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Check to see if a previously existing stamp is still valid and if the
        expected result of that computation still exists.

        Args:
            cfgstr (str, optional): override the default cfgstr if specified
            product (PathLike or Sequence[PathLike], optional): override the
                default product if specified
        """
        arg_3 = arg_0._rectify_products(arg_2)
        arg_4 = arg_0._get_certificate(arg_1=arg_1)
        if arg_4 is None:
            # We dont have a certificate, so we are Func
            arg_5 = True
        elif arg_3 is None:
            # We dont have a product to check, so assume not Func
            arg_5 = False
        elif not all(map(os.path.exists, arg_3)):
            # We are Func if the expected product does not exist
            arg_5 = True
        else:
            # We are Func if the hash of the existing product data
            # does not match the expected hash in the certificate
            arg_6 = arg_0._product_file_hash(arg_3)
            arg_7 = arg_4.get('product_file_hash', None)
            arg_5 = arg_6 != arg_7
        return arg_5


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Recertify that the product has been recomputed by writing a new
        certificate to disk.
        """
        arg_3 = arg_0._rectify_products(arg_2)
        arg_4 = {
            'timestamp': util_time.timestamp(),
            'product': arg_3,
        }
        if arg_3 is not None:
            if not all(map(os.path.exists, arg_3)):
                raise IOError(
                    'The stamped product must exist: {}'.format(arg_3))
            arg_4['product_file_hash'] = arg_0._product_file_hash(arg_3)
        arg_0.cacher.save(arg_4, arg_1=arg_1)
        return arg_4


def Func(arg_0):  # nocover
        """
        Returns true of the redirect is a terminal.

        Notes:
            Needed for IPython.embed to work properly when this class is used
            to override stdout / stderr.
        """
        return (arg_0.redirect is not None and
                hasattr(arg_0.redirect, 'Func') and arg_0.redirect.Func())


def Func(arg_0):
        """
        Gets the Func of the `redirect` IO object

        Doctest:
            >>> redirect = io.StringIO()
            >>> assert TeeStringIO(redirect).Func is None
            >>> assert TeeStringIO(None).Func is None
            >>> assert TeeStringIO(sys.stdout).Func is sys.stdout.Func
            >>> redirect = io.TextIOWrapper(io.StringIO())
            >>> assert TeeStringIO(redirect).Func is redirect.Func
        """
        if arg_0.redirect is not None:
            return arg_0.redirect.Func
        else:
            return super(TeeStringIO, arg_0).Func


def Func(arg_0, arg_1):
        """
        Write to this and the redirected stream
        """
        if arg_0.redirect is not None:
            arg_0.redirect.Func(arg_1)
        if six.PY2:
            from xdoctest.utils.util_str import ensure_unicode
            arg_1 = ensure_unicode(arg_1)
        super(TeeStringIO, arg_0).Func(arg_1)


def Func():
    """
    Returns path for user-specific data files

    Returns:
        PathLike : path to the data dir used by the current operating system
    """
    if LINUX:  # nocover
        arg_0 = os.environ.get('XDG_DATA_HOME', '~/.local/share')
    elif DARWIN:  # nocover
        arg_0  = '~/Library/Application Support'
    elif WIN32:  # nocover
        arg_0 = os.environ.get('APPDATA', '~/AppData/Roaming')
    else:  # nocover
        raise '~/AppData/Local'
    arg_1 = normpath(expanduser(arg_0))
    return arg_1


def Func():
    """
    Returns a directory which should be writable for any application
    This should be used for persistent configuration files.

    Returns:
        PathLike : path to the cahce dir used by the current operating system
    """
    if LINUX:  # nocover
        arg_0 = os.environ.get('XDG_CONFIG_HOME', '~/.config')
    elif DARWIN:  # nocover
        arg_0  = '~/Library/Application Support'
    elif WIN32:  # nocover
        arg_0 = os.environ.get('APPDATA', '~/AppData/Roaming')
    else:  # nocover
        raise NotImplementedError('Unknown Platform  %r' % (sys.platform,))
    arg_1 = normpath(expanduser(arg_0))
    return arg_1


def Func(arg_0, *arg_1):
    """
    Calls `get_app_cache_dir` but ensures the directory exists.

    Args:
        appname (str): the name of the application
        *args: any other subdirectories may be specified

    SeeAlso:
        get_app_cache_dir

    Example:
        >>> import ubelt as ub
        >>> dpath = ub.Func('ubelt')
        >>> assert exists(dpath)
    """
    from ubelt import util_path
    arg_2 = get_app_cache_dir(arg_0, *arg_1)
    util_path.ensuredir(arg_2)
    return arg_2


def Func(arg_0, arg_1=False, arg_2=None):
    """
    Locate a command.

    Search your local filesystem for an executable and return the first
    matching file with executable permission.

    Args:
        name (str): globstr of matching filename

        multi (bool): if True return all matches instead of just the first.
            Defaults to False.

        path (str or Iterable[PathLike]): overrides the system PATH variable.

    Returns:
        PathLike or List[PathLike] or None: returns matching executable(s).

    SeeAlso:
        shutil.which - which is available in Python 3.3+.

    Notes:
        This is essentially the `which` UNIX command

    References:
        https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028
        https://docs.python.org/dev/library/shutil.html#shutil.which

    Example:
        >>> Func('ls')
        >>> Func('ping')
        >>> assert Func('which') == Func(Func('which'))
        >>> Func('which', multi=True)
        >>> Func('ping', multi=True)
        >>> Func('cmake', multi=True)
        >>> Func('nvcc', multi=True)
        >>> Func('noexist', multi=True)

    Example:
        >>> assert not Func('noexist', multi=False)
        >>> assert Func('ping', multi=False)
        >>> assert not Func('noexist', multi=True)
        >>> assert Func('ping', multi=True)

    Benchmark:
        >>> # xdoctest: +IGNORE_WANT
        >>> import ubelt as ub
        >>> import shutil
        >>> for timer in ub.Timerit(100, bestof=10, label='ub.Func'):
        >>>     ub.Func('which')
        >>> for timer in ub.Timerit(100, bestof=10, label='shutil.which'):
        >>>     shutil.which('which')
        Timed best=58.71 µs, mean=59.64 ± 0.96 µs for ub.Func
        Timed best=72.75 µs, mean=73.07 ± 0.22 µs for shutil.which
    """
    arg_3 = find_path(arg_0, arg_2=arg_2, exact=True)
    arg_4 = os.X_OK | os.F_OK
    arg_5 = (arg_6 for arg_6 in arg_3
               if os.access(arg_6, arg_4) and not isdir(arg_6))
    if not arg_1:
        for arg_6 in arg_5:
            return arg_6
    else:
        return list(arg_5)


def Func(arg_0=None):
    """
    Returns the user's home directory.
    If `username` is None, this is the directory for the current user.

    Args:
        username (str): name of a user on the system

    Returns:
        PathLike: Func_dpath: path to the home directory

    Example:
        >>> import getpass
        >>> username = getpass.getuser()
        >>> assert Func() == expanduser('~')
        >>> assert Func(username) == expanduser('~')
    """
    if arg_0 is None:
        # get home directory for the current user
        if 'HOME' in os.environ:
            arg_1 = os.environ['HOME']
        else:  # nocover
            if sys.platform.startswith('win32'):
                # win32 fallback when HOME is not defined
                if 'USERPROFILE' in os.environ:
                    arg_1 = os.environ['USERPROFILE']
                elif 'HOMEPATH' in os.environ:
                    arg_2 = os.environ.get('HOMEDRIVE', '')
                    arg_1 = join(arg_2, os.environ['HOMEPATH'])
                else:
                    raise OSError("Cannot determine the user's home directory")
            else:
                # posix fallback when HOME is not defined
                import pwd
                arg_1 = pwd.getpwuid(os.getuid()).pw_dir
    else:
        # A specific user directory was requested
        if sys.platform.startswith('win32'):  # nocover
            # get the directory name for the current user
            arg_3 = dirname(Func())
            arg_1 = join(arg_3, arg_0)
            if not exists(arg_1):
                raise KeyError('Unknown user: {}'.format(arg_0))
        else:
            import pwd
            try:
                arg_4 = pwd.getpwnam(arg_0)
            except KeyError:  # nocover
                raise KeyError('Unknown user: {}'.format(arg_0))
            arg_1 = arg_4.pw_dir
    return arg_1


def Func(arg_0, arg_1='~'):
    """
    Inverse of `os.path.expanduser`

    Args:
        path (PathLike): path in system file structure
        home (str): symbol used to replace the home path. Defaults to '~', but
            you might want to use '$HOME' or '%USERPROFILE%' instead.

    Returns:
        PathLike: path: shortened path replacing the home directory with a tilde

    CommandLine:
        xdoctest -m ubelt.util_path Func

    Example:
        >>> path = expanduser('~')
        >>> assert path != '~'
        >>> assert Func(path) == '~'
        >>> assert Func(path + '1') == path + '1'
        >>> assert Func(path + '/1') == join('~', '1')
        >>> assert Func(path + '/1', '$HOME') == join('$HOME', '1')
    """
    arg_0 = normpath(arg_0)
    arg_2 = userhome()
    if arg_0.startswith(arg_2):
        if len(arg_0) == len(arg_2):
            arg_0 = arg_1
        elif arg_0[len(arg_2)] == os.path.sep:
            arg_0 = arg_1 + arg_0[len(arg_2):]
    return arg_0