Construct a filter string to filter on metric or resource labels.
424250
def _build_label_filter(category, *args, **kwargs):
    """"""
    terms = list(args)
    for key, value in six.iteritems(kwargs):
        if value is None:
            continue

        suffix = None
        if key.endswith(
            ("_prefix", "_suffix", "_greater", "_greaterequal", "_less", "_lessequal")
        ):
            key, suffix = key.rsplit("_", 1)

        if category == "resource" and key == "resource_type":
            key = "resource.type"
        else:
            key = ".".join((category, "label", key))

        if suffix == "prefix":
            term = '{key} = starts_with("{value}")'
        elif suffix == "suffix":
            term = '{key} = ends_with("{value}")'
        elif suffix == "greater":
            term = "{key} > {value}"
        elif suffix == "greaterequal":
            term = "{key} >= {value}"
        elif suffix == "less":
            term = "{key} < {value}"
        elif suffix == "lessequal":
            term = "{key} <= {value}"
        else:
            term = '{key} = "{value}"'

        terms.append(term.format(key=key, value=value))

    return " AND ".join(sorted(terms))
507438
def _get_name_filters(cls, filters):
        """"""
        filters = filters.get(cls.__uid_field__)
        if not filters:
            filters = '.*'
        elif not isinstance(filters, string_types):
            filters = r'(%s)' % ('|'.join(filters))
        return filters
708373
private String parseWithMetric(final String metric) {
    // TODO: Try to reduce code duplication with Tags.parseWithMetric().
    final int curly = metric.indexOf('{');
    if (curly < 0) {
      clearTags();
      return metric;
    }
    final int len = metric.length();
    if (metric.charAt(len - 1) != '}') {  // "foo{"
      clearTags();
      return null;  // Missing '}' at the end.
    } else if (curly == len - 2) {  // "foo{}"
      clearTags();
      return metric.substring(0, len - 2);
    }
    final int num_tags_before = getNumTags();
    
    final List<Filter> filters = new ArrayList<Filter>();
    final int close = metric.indexOf('}');
    int i = 0;
    if (close != metric.length() - 1) { // "foo{...}{tagk=filter}" 
      final int filter_bracket = metric.lastIndexOf('{');
      for (final String filter : metric.substring(filter_bracket + 1, 
          metric.length() - 1).split(",")) {
        if (filter.isEmpty()) {
          break;
        }
        final String[] kv = filter.split("=");
        if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
          continue;  // Invalid tag.
        }
        final Filter f = new Filter();
        f.tagk = kv[0];
        f.tagv = kv[1];
        f.is_groupby = false;
        filters.add(f);
        i++;  
      }
    }
    
    i = 0;
    for (final String tag : metric.substring(curly + 1, close).split(",")) {
      if (tag.isEmpty() && close != metric.length() - 1){
        break;
      }
      final String[] kv = tag.split("=");
      if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
        continue;  // Invalid tag.
      }
      final Filter f = new Filter();
      f.tagk = kv[0];
      f.tagv = kv[1];
      f.is_groupby = true;
      filters.add(f);
      i++;
    }
    if (!filters.isEmpty()) {
      Collections.sort(filters);
    }
    
    i = 0;
    for (int x = filters.size() - 1; x >= 0; x--) {
      final Filter filter = filters.get(x);
      if (i < num_tags_before) {
        setTag(i++, filter.tagk, filter.tagv, filter.is_groupby);
      } else {
        addTag(filter.tagk, filter.tagv, filter.is_groupby);
      }
    }
    
    if (i < num_tags_before) {
      setTag(i, "", "", true);
    } else {
      addTag();
    }
    // Remove extra tags.
    for (i++; i < num_tags_before; i++) {
      tagtable.removeRow(i + 1);
    }
    // Return the "foo" part of "foo{a=b,...,x=y}"
    return metric.substring(0, curly);
    
    /*
    // substring the tags out of "foo{a=b,...,x=y}" and parse them.
    int i = 0;  // Tag index.
    final int num_tags_before = getNumTags();
    for (final String tag : metric.substring(curly + 1, len - 1).split(",")) {
      final String[] kv = tag.split("=");
      if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
        setTag(i, "", "", true);
        continue;  // Invalid tag.
      }
      if (i < num_tags_before) {
        setTag(i, kv[0], kv[1], true);
      } else {
        addTag(kv[0], kv[1]);
      }
      i++;
    }
    // Leave an empty line at the end.
    if (i < num_tags_before) {
      setTag(i, "", "", true);
    } else {
      addTag();
    }
    // Remove extra tags.
    for (i++; i < num_tags_before; i++) {
      tagtable.removeRow(i + 1);
    }
    // Return the "foo" part of "foo{a=b,...,x=y}"
    return metric.substring(0, curly); */
  }
1365016
private String getStringPredicate(String fieldName, String filterValue, List<Object> prms)
    {
        if (filterValue == null)
        {
            return "";
        }
        return getStringPredicate(fieldName, Arrays.asList(filterValue), prms);
    }
103697
def filter(self):
        
        argmap = {
            filter.label or label: filter.field
            for label, filter in self.filters.items()
        }
        args = self.opts.parser.parse(argmap)
        query = self.query if self.query is not None else self.opts.query
        for label, filter in self.filters.items():
            value = args.get(filter.label or label)
            if value is not None:
                query = filter.filter(query, self.opts.model, label, value)
        return query
268561
def describe_filter(f):
    """"""
    if f.__class__ is logging.Filter:  # using type() breaks in Python <= 2.6
        return 'name=%r' % f.name
    return repr(f)
357933
def filter_link(model_class, filter_name, filters: {}, url_params: {})
      is_all = filter_name == :all
      config = filters[filter_name] || {}
      label = is_all ? all_label : filter_label(filter_name, filters)
      url_params =
        if config[:default] then index_params.except(:filter).merge(url_params)
        else index_params.merge(filter: filter_name).merge(url_params)
        end
      index_link(model_class, url_params: url_params) { label }
    end
294715
def filter(self, table, domains, filter_string):
        """"""
        q = filter_string.lower()

        def comp(domain):
            if q in domain.name.lower():
                return True
            return False

        return filter(comp, domains)
1072745
def _init_filters(self):
        """"""
        self.filters = {}

        @self.template_filter()
        def format_ts(value, format_='%a, %b %d %Y %H:%M:%S'):
            """Formats the supplied timestamp using format_

            :param str value: The timestamp to be formatted
            :param str format_:  The format string
            :return: The correctly formatted timestamp as determined by format_
            :rtype: str
            """
            if format_ == '%s':
                return timestamp_to_sec(value)
            else:
                value = timestamp_to_datetime(value)
                return value.strftime(format_)

        @self.template_filter('urlsplit')
        def get_urlsplit(url):
            """Splits the supplied URL

            :param str url: The url to be split
            :return: The split url
            :rtype: urllib.parse.SplitResult
            """
            split = urlsplit(url)
            return split

        @self.template_filter()
        def tojson(obj):
            """Converts the supplied object/array/any to a JSON string if it can be JSONified

            :param any obj: The value to be converted to a JSON string
            :return: The JSON string representation of the supplied value
            :rtype: str
            """
            return json.dumps(obj)

        @self.template_filter()
        def tobool(bool_val):
            """Converts a python boolean to a JS "true" or "false" string
            :param any obj: A value to be evaluated as a boolean
            :return: The string "true" or "false" to be inserted into JS
            """

            return 'true' if bool_val else 'false'
710072
def filter(self, table, idps, filter_string):
        """"""
        q = filter_string.lower()
        return [idp for idp in idps
                if q in idp.ud.lower()]
349147
public static lbmetrictable_metric_binding[] get_filtered(nitro_service service, String metrictable, String filter) throws Exception{
		lbmetrictable_metric_binding obj = new lbmetrictable_metric_binding();
		obj.set_metrictable(metrictable);
		options option = new options();
		option.set_filter(filter);
		lbmetrictable_metric_binding[] response = (lbmetrictable_metric_binding[]) obj.getfiltered(service, option);
		return response;
	}
1360019
private String getStringPredicate(String fieldName, List<String> filterValues, List<Object> prms)
    {
        if (filterValues != null && !filterValues.isEmpty())
        {
            String res = "";
            for (String filterValue : filterValues)
            {
                if (filterValue == null)
                {
                    continue;
                }
                if (!filterValue.isEmpty())
                {
                    prms.add(filterValue);
                    if (filterValue.contains("%"))
                    {
                        res += String.format("(%s LIKE ?) OR ", fieldName);
                    }
                    else
                    {
                        res += String.format("(%s = ?) OR ", fieldName);
                    }
                }
                else
                {
                    res += String.format("(%s IS NULL OR %s = '') OR ", fieldName, fieldName);
                }
            }
            if (!res.isEmpty())
            {
                res = "AND (" + res.substring(0, res.length() - 4) + ") ";
                return res;
            }
        }
        return "";
    }
172972
def add_filter(self, label):
        
        if label not in self.FILTER:
            if "PASS" in self.FILTER:
                self.FILTER = [f for f in self.FILTER if f != "PASS"]
            self.FILTER.append(label)
361325
protected List<Metric> filter(List<Metric> metrics) {
    final List<Metric> filtered = metrics.stream().filter(this::shouldIncludeMetric)
        .collect(Collectors.toList());
    LOGGER.debug("Filter: input {} metrics, output {} metrics",
        metrics.size(), filtered.size());
    return filtered;
  }
337229
def _filter_candidates(self, tokens, candidates):
        """"""
        results = []
        for abbr_span, long_span in candidates:
            abbr = tokens[abbr_span[0]:abbr_span[1]]
            long = tokens[long_span[0]:long_span[1]]
            if not all(a in long for a in abbr) and len(''.join(long)) > len(''.join(abbr)):
                results.append((abbr_span, long_span))
        return results
194568
def filter(self):  # noqa A001
        """"""

        return [tag for tag in self.get_contents(self.tag) if not self.is_navigable_string(tag) and self.match(tag)]
294572
def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None):
        
        value = data

        # Traverse the nested dictionaries
        for key in path.split('.'):
            if value is not None:
                value = value.get(key)
            else:
                break

        if value is not None:
            if xform:
                value = xform(value)
            if xtype == "gauge":
                self.gauge(metric, value, tags=tags, hostname=hostname)
            else:
                self.rate(metric, value, tags=tags, hostname=hostname)
        else:
            self.log.debug("Metric not found: %s -> %s", path, metric)