Clean up a query string for searching.

    Removes unmatched parentheses and joining operators.

    Arguments:
        q (str): Query string to be cleaned

    Returns:
        str: The clean query string.
4254
def _clean_query_string(q):
    
    q = q.replace("()", "").strip()
    if q.endswith("("):
        q = q[:-1].strip()
    # Remove misplaced AND/OR/NOT at end
    if q[-3:] == "AND" or q[-3:] == "NOT":
        q = q[:-3]
    elif q[-2:] == "OR":
        q = q[:-2]

    # Balance parentheses
    while q.count("(") > q.count(")"):
        q += ")"
    while q.count(")") > q.count("("):
        q = "(" + q

    return q.strip()
679742
def _parse_prefix_query(self, query_str):
        
        sp = smart_parsing.PrefixSmartParser()
        query = sp.parse(query_str)
        return query
665959
function(query) {
    var qparts = getQueryParts(goog.string.trim(query));

    // if it's trivial, avoid iteration and zipping costs
    if (qparts.length == 1) {
      // We optimize this case here to prevent dispatch further down the
      // chain, potentially slowing things down. We could more elegantly
      // handle this in filterDown(), but it's slower for simple things
      // that need to be fast (e.g., '#someId').
      var tef = getElementsFunc(qparts[0]);
      return function(root) {
        var r = tef(root, []);
        if (r) { r.nozip = true; }
        return r;
      }
    }

    // otherwise, break it up and return a runner that iterates over the parts
    // recursively
    return function(root) {
      return filterDown(root, qparts);
    }
  }
375355
def do_filter(qs, qdata, quick_query_fields=[], int_quick_query_fields=[]):
    
    try:
        qs = qs.filter(
            __gen_quick_query_params(
                qdata.get('q_quick_search_kw'), quick_query_fields,
                int_quick_query_fields)
        )
        q, kw_query_params = __gen_query_params(qdata)
        qs = qs.filter(q, **kw_query_params)
    except:
        import traceback
        traceback.print_exc()
    return qs
1128213
def _remove_qs(self, url):
        '''
        
        '''
        scheme, netloc, path, query, fragment = urlsplit(url)

        return urlunsplit((scheme, netloc, path, '', fragment))
1347434
def query_str_2_dict(query_str):
    
    if query_str:
        query_list = query_str.split('&')
        query_dict = {}
        for t in query_list:
            x = t.split('=')
            query_dict[x[0]] = x[1]
    else:
        query_dict = {}
    return query_dict
828025
function query(q) {
  var filter = Object.keys(q);
  var isValid;
  var valid;
  var val;

  return this.reduce((list, ps) => {
    isValid = filter.every(key => {
      val = q[key];
      valid = true;

      if (typeof val === 'string') {
        if (val.indexOf('<') > -1) {
          valid = ps[key] < cleanValue(val, '<');
        }

        if (valid && val.indexOf('>') > -1) {
          valid = ps[key] > cleanValue(val, '>');
        }

        if (valid && val.indexOf('~') > -1) {
          valid = ps[key].indexOf(q[key].replace('~', '')) > -1;
        }
      } else {
        valid = ps[key] === val;
      }

      return valid;
    });

    if (isValid) list.push(ps);

    return list;
  }, []);
}
1338010
def getquerylist(self, sep='&', encoding='utf-8', errors='strict'):
        
        if not self.query:
            return []
        elif isinstance(sep, type(self.query)):
            qsl = self.query.split(sep)
        elif isinstance(sep, bytes):
            qsl = self.query.split(sep.decode('ascii'))
        else:
            qsl = self.query.split(sep.encode('ascii'))
        items = []
        for parts in [qs.partition(self.EQ) for qs in qsl if qs]:
            name = uridecode(parts[0], encoding, errors)
            if parts[1]:
                value = uridecode(parts[2], encoding, errors)
            else:
                value = None
            items.append((name, value))
        return items
711931
def build_query_string(self, data):
        
        query_params = []
        keys_to_be_removed = []
        for key, value in data.items():
            if key not in ['version', 'restApi', 'resourcePath']:
                if key == 'addressLine':
                    query_params.append('{0}={1}'.format(key,
                                                         quote(value)))
                    keys_to_be_removed.append(key)
                else:
                    query_params.append('{0}={1}'.format(key,
                                                         value))
                    keys_to_be_removed.append(key)
        data['query'] = "&".join(query_params)
        for k in keys_to_be_removed:
            del data[k]
        return data
1119536
function (url, qsName, qsValue) {

    let urlObj = Url.parse(url);
    if (qsName && qsValue) {
        urlObj.query = Querystring.parse(qsName + '=' + qsValue);
        urlObj.search = '?' + encodeURIComponent(qsName) + '=' + encodeURIComponent(qsValue);
    } else {
        urlObj.search = '';
    }
    return urlObj.format(urlObj);
}
886084
def get_querystring(uri):
    
    parts = urlparse.urlsplit(uri)
    return urlparse.parse_qs(parts.query)
217483
def query_params(self, value=None):
        
        if value is not None:
            return URL._mutate(self, query=unicode_urlencode(value, doseq=True))
        query = '' if self._tuple.query is None else self._tuple.query

        # In Python 2.6, urlparse needs a bytestring so we encode and then
        # decode the result.
        if not six.PY3:
            result = parse_qs(to_utf8(query), True)
            return dict_to_unicode(result)

        return parse_qs(query, True)
1046419
def match_list(query_list, string):
    
    # Get rid of 'the' word to ease string matching
    match = False
    index = 0
    string = ' '.join(filter_stopwords(string))

    if not isinstance(query_list, list):
        query_list = [query_list]

    while index < len(query_list):
        query = query_list[index]
        words_query = filter_stopwords(query)
        match = all(word in string for word in words_query)
        if match:
            break

        index += 1

    return match
291215
def clean_url(self):
        """"""
        raw_url = self.request['url']
        parsed_url = urlparse(raw_url)
        qsl = parse_qsl(parsed_url.query)
        for qs in qsl:
            new_url = self._join_url(parsed_url,
                                     [i for i in qsl if i is not qs])
            new_request = deepcopy(self.request)
            new_request['url'] = new_url
            self._add_task('qsl', qs, new_request)
        return self
56539
def filter(self):
        
        if isinstance(self._filter, str):
            return self._decode_query(self._filter)
        return self._filter
1112764
def parse_query_string(query):
    
    result = {}
    qparts = query.split('&')
    for item in qparts:
        key, value = item.split('=')
        key = key.strip()
        value = value.strip()
        result[key] = unquote_plus(value)
    return result
535320
def __filter_query(self) -> str:
        
        filter_query = 'WHERE %s'
        bind_values = {}
        if not self.__filters:
            return None
        for filter in self.__filters:
            bind = {
                'name': Security.random_string(5),
                'value': filter['value']}
            filter_str = '%s %s :%s' % \
                (filter['column'], filter['operator'], bind['name'])
            bind_values[bind['name']] = bind['value']
            filter_query = filter_query % (filter_str + ' AND %s')
        return {
            'query': filter_query.replace(' AND %s', ''),
            'binds': bind_values}