Formats search parameters/values for use with API
        
        :param \*\*kwargs: search parameters/values
180104
def _options(self, **kwargs):
        
        def _format_fq(d):
            for k,v in d.items():
                if isinstance(v, list):
                    d[k] = ' '.join(map(lambda x: '"' + x + '"', v))
                else:
                    d[k] = '"' + v + '"'
            values = []
            for k,v in d.items():
                value = '%s:(%s)' % (k,v)
                values.append(value)
            values = ' AND '.join(values)
            return values
        
        kwargs = self._utf8_encode(kwargs)
        kwargs = self._bool_encode(kwargs)
        
        values = ''
        
        for k, v in kwargs.items():
            if k is 'fq' and isinstance(v, dict):
                v = _format_fq(v)
            elif isinstance(v, list):
                v = ','.join(v)
            values += '%s=%s&' % (k, v)
        
        return values
1168190
def pretty_format_args(*args, **kwargs):
    
    args = list([repr(a) for a in args])
    for key, value in kwargs.items():
        args.append("%s=%s" % (key, repr(value)))
    return "(%s)" % ", ".join([a for a in args])
613282
def format_search(q, **kwargs):
    ''''''
    m = search(q, **kwargs)
    count = m['count']
    if not count:
        raise DapiCommError('Could not find any DAP packages for your query.')
        return
    for mdap in m['results']:
        mdap = mdap['content_object']
        return _format_dap_with_description(mdap)
65600
def query_params(self, params, key, def_value, short_hand=None):
    
    if key not in params and short_hand:
        # value is associated with shorthand, move to key
        params[key] = params.get(short_hand, def_value)
        del params[short_hand]
    elif key not in params and not short_hand:
        params[key] = def_value
    elif key in params:
        # key is there, also possibly shorthand
        # assume def value at this point is not needed
        if short_hand in params:
            del params[short_hand]
    return params
90475
def _encode_params(**kw):
    '''
    
    '''
    args = []
    for k, v in kw.iteritems():
        if isinstance(v, basestring):
            qv = v.encode('utf-8') if isinstance(v, unicode) else v
            args.append('%s=%s' % (k, urllib.quote(qv)))
        elif isinstance(v, collections.Iterable):
            for i in v:
                qv = i.encode('utf-8') if isinstance(i, unicode) else str(i)
                args.append('%s=%s' % (k, urllib.quote(qv)))
        else:
            qv = str(v)
            args.append('%s=%s' % (k, urllib.quote(qv)))
    return '&'.join(args)
1161923
def prepare_url(self, uri, kwargs):
        
        params = dict()
        for key in kwargs:
            if key in ('include', 'exclude', 'fields'):
                params.update({
                    key: ','.join(kwargs.get(key))
                })
            elif key in ('search', 'kind'):
                params.update({
                    key: kwargs.get(key)
                })

        if params:
            params = urlencode(params)
            uri = '%s?%s' % (uri, params)

        return uri
102971
def read_parameters(request, view_kwargs=None, capture_errors=False):  # noqa: C901
    
    if view_kwargs is None:
        view_kwargs = {}
    params = {}
    errors = {}
    for param in request.api_info.operation.parameters:
        try:
            value = param.get_value(request, view_kwargs)
            if value is NO_VALUE:
                if param.has_default:
                    params[param.name] = param.default
                elif param.required:  # Required but missing
                    errors[param.name] = MissingParameter('parameter %s is required but missing' % param.name)
                continue  # No value, or a default was added, or an error was added.
            params[param.name] = param.cast(request.api_info.api, value)
        except (NotImplementedError, ImproperlyConfigured):
            raise
        except Exception as e:
            if not capture_errors:
                raise
            errors[param.name] = e
    if errors:
        raise ErroneousParameters(errors, params)
    return params
108651
def get_form_kwargs(self):
        
        kwargs = {"initial": self.get_initial()}
        if self.request.method == "GET":
            kwargs.update({"data": self.request.GET})
        kwargs.update({"searchqueryset": self.get_query_set()})
        return kwargs
237630
def process_kwargs(self, kwargs, prefix='default_', delete=True):
        
        processed = []
        for k in kwargs:
            if hasattr(self, prefix + k):
                processed += [k]
                setattr(self, prefix + k, kwargs[k])
        for k in processed:
            del(kwargs[k])
        return kwargs
25823
def use_args(
        self,
        argmap: ArgMap,
        req: typing.Optional[Request] = None,
        locations: typing.Iterable = None,
        as_kwargs: bool = False,
        validate: Validate = None,
        error_status_code: typing.Optional[int] = None,
        error_headers: typing.Union[typing.Mapping[str, str], None] = None,
    ) -> typing.Callable[..., typing.Callable]:
        
        locations = locations or self.locations
        request_obj = req
        # Optimization: If argmap is passed as a dictionary, we only need
        # to generate a Schema once
        if isinstance(argmap, Mapping):
            argmap = core.dict2schema(argmap, self.schema_class)()

        def decorator(func: typing.Callable) -> typing.Callable:
            req_ = request_obj

            if inspect.iscoroutinefunction(func):

                @functools.wraps(func)
                async def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = await self.parse(
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args or {})
                        return await func(*args, **kwargs)
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return await func(*new_args, **kwargs)

            else:

                @functools.wraps(func)  # type: ignore
                def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = yield from self.parse(  # type: ignore
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args)
                        return func(*args, **kwargs)  # noqa: B901
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return func(*new_args, **kwargs)

            return wrapper

        return decorator
761523
def kwargs_to_string(kwargs):
    
    outstr = ''
    for arg in kwargs:
        outstr += ' -{} {}'.format(arg, kwargs[arg])
    return outstr
17094
def get_params(self, *args, **kwargs):
        '''
        
        '''
        kwargs.update(self._data)
        if args and kwargs:
            raise ValueError('Cannot mix positional and named parameters')
        if args:
            return list(args)
        else:
            return kwargs
186702
def _get(cls, kwarg_name):
        
        param_classes = cls._discover_params()
        try:
            param_class = param_classes[kwarg_name]
        except KeyError:
            raise ValueError('invalid param keyword {}'.format(kwarg_name))
        else:
            return param_class
41194
def get_kwargs(self, **kwargs):
        
        version = kwargs.pop("version", "v1")
        if version == "v1":
            base = kwargs.pop("base", "/api")
        elif "/" in version:
            base = kwargs.pop("base", "/apis")
        else:
            if "base" not in kwargs:
                raise TypeError("unknown API version; base kwarg must be specified.")
            base = kwargs.pop("base")
        bits = [base, version]
        # Overwrite (default) namespace from context if it was set
        if "namespace" in kwargs:
            n = kwargs.pop("namespace")
            if n is not None:
                if n:
                    namespace = n
                else:
                    namespace = self.config.namespace
                if namespace:
                    bits.extend([
                        "namespaces",
                        namespace,
                    ])
        url = kwargs.get("url", "")
        if url.startswith("/"):
            url = url[1:]
        bits.append(url)
        kwargs["url"] = self.url + posixpath.join(*bits)
        return kwargs
706127
def get_list(self, method="list", **kwargs):
        

        lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
        lg.setLevel(self.log_level)

        args = inspect.getargvalues(inspect.currentframe())[3]
        lg.debug("\n****** Args *****:\n%s",
                 pp.pformat(args))

        es = kwargs.get("es",self.es)
        doc_type = get2(kwargs, "doc_type", self.doc_type)
        id_field = get2(kwargs, "id_field", "_id")
        value_fld = kwargs.get("value_fld")
        fields = kwargs.get("fields")
        sort_dir = get2(kwargs,"sort_dir", "asc")
        sort_fields = get2(kwargs,"sort_fields", get2(kwargs, "fields", [value_fld]))
        size = get2(kwargs,"size",2000)
        term = get2(kwargs,"term",'').replace("/","//")
        filter_field = kwargs.get('filter_field')
        filter_value = kwargs.get('filter_value')
        dsl = {}
        # set retutn to only return the fields specified or return the whole
        # document if not specified
        if fields is not None:
            dsl["_source"] = fields
        elif value_fld is not None:
            dsl["_source"] = [value_fld]
            fields = [value_fld]
        else:
            fields = []
        # set query parameters based on the return method "list" or "search"
        if sort_dir != "none" and method == "list":
            dsl["sort"] = []
            for fld in sort_fields:
                if fld is not None:
                    dsl["sort"].append({ fld: sort_dir })
        if method == "search":
            # query in elasticsearch breaks if the is a single open parenthesis
            # remove a single parenthesis from the search term
            if "(" in term and ")" not in term:
                search_term = term.replace("(", "")
            else:
                search_term = term
            size = 5
            dsl['query'] =  {
                "bool": {
                    "should": [
                        {
                            "query_string" : {
                                "analyze_wildcard": {
                                    "query": "*%s*" % search_term
                                }

                            }
                        },
                        {
                            "query_string" : {
                                "query": "*%s*" % search_term,
                                "analyzer": "default",
                                "analyze_wildcard": True,
                                "fields": fields,
                                "boost": 10
                            }
                        }
                    ]
                }
            }
        else:
            pass
        if filter_value:
            dsl['filter'] = {
                "term": { filter_field: filter_value }
            }
        lg.info("\n-------- size: %s\ndsl:\n%s", size, json.dumps(dsl,indent=4))
        result = es.search(index=self.es_index,
                           size=size,
                           doc_type=doc_type,
                           body=dsl)
        if kwargs.get("calc"):
            result = self._calc_result(result, kwargs['calc'])
        lg.debug(pp.pformat(result))
        return result
278929
def get_kwargs(self):
        
        return {
            'host': self.host,
            'port': self.port,
            'channel': self.channel,
            'password': self.password
        }
1247959
def _check_search_kwarg_types(self, kwargs):
        ''''''
        for key in kwargs:
            if key not in self.node_types:
                raise TypeError("Invalid search type: {}".format(key))