Used internally to parse a filter element.
357850
protected
  void parseFilters(Element element, Appender appender) {
    String clazz = subst(element.getAttribute(CLASS_ATTR));
    Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz,
                                                Filter.class, null);
    
    if(filter != null) {
      PropertySetter propSetter = new PropertySetter(filter);
      NodeList children = element.getChildNodes();
      final int length 	= children.getLength();

      for (int loop = 0; loop < length; loop++) {
	Node currentNode = children.item(loop);
	if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
	  Element currentElement = (Element) currentNode;
	  String tagName = currentElement.getTagName();
	  if(tagName.equals(PARAM_TAG)) {
            setParameter(currentElement, propSetter);
	  } else {
            quietParseUnrecognizedElement(filter, currentElement, props);
      }
	}
      }
      propSetter.activate();
      LogLog.debug("Adding filter of type ["+filter.getClass()
		   +"] to appender named ["+appender.getName()+"].");
      appender.addFilter(filter);
    }    
  }
1355709
def _filter_dom(dom, filters, last_find_all=False):
        
        if isinstance(dom, string_types):
            dom = BeautifulSoup(dom, 'html.parser')
        for idx, find in enumerate(filters, start=1):
            if not dom:
                break
            name, attrs = find.get('name'), find.get('attrs', {})
            if len(filters) == idx and last_find_all:
                dom = dom.find_all(name, attrs=attrs) if name else dom.find_all(attrs=attrs)
            else:
                dom = dom.find(name, attrs=attrs) if name else dom.find(attrs=attrs)
        return dom
896650
function (src, filter) {
    var out = {}, i;
    for (i=0; i<filter.length; i++) {
      if (src[filter[i]] !== undefined) {
        out[filter[i]] = src[filter[i]];
      }
    }
    return out;
  }
91571
function (node, name,filter) {
        if(filter && utils.isString(filter)){
           var className = filter;
           filter =  function(node){return domUtils.hasClass(node,className)}
        }
        name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
        var arr = [];
        for(var n = 0,ni;ni=name[n++];){
            var list = node.getElementsByTagName(ni);
            for (var i = 0, ci; ci = list[i++];) {
                if(!filter || filter(ci))
                    arr.push(ci);
            }
        }

        return arr;
    }
35415
def build_filter(self, filter):
        
        try:
            self.filter = Filter.from_string(filter, self.limit)
        except ValueError:
            raise

        return self
645822
def parse(node)
      node.attributes.each do |key, value|
        case key
        when 'showButton'
          @show_button = attribute_enabled?(value)
        end
      end

      node.xpath('*').each do |node_child|
        case node_child.name
        when 'customFilters'
          @custom_filters = CustomFilters.new(parent: self).parse(node_child)
        end
      end
      self
    end
62345
public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {
		if (null == filter) {
			filter = Filter.INCLUDE;
		}
		List<Object> filteredList = new ArrayList<Object>();
		try {
			synchronized (featuresById) {
				for (Object feature : featuresById.values()) {
					if (filter.evaluate(feature)) {
						filteredList.add(feature);
					}
				}
			}
		} catch (Exception e) { // NOSONAR
			throw new LayerException(e, ExceptionCode.FILTER_EVALUATION_PROBLEM, filter, getId());
		}
		// Sorting of elements.
		if (comparator != null) {
			Collections.sort(filteredList, comparator);
		}
		if (maxResultSize > 0) {
			int fromIndex = Math.max(0, offset);
			int toIndex = Math.min(offset + maxResultSize, filteredList.size());
			toIndex = Math.max(fromIndex, toIndex);
			return filteredList.subList(fromIndex, toIndex).iterator();
		} else {
			return filteredList.iterator();
		}
	}
301325
def parse_at_element(
            self,
            element,  # type: ET.Element
            state  # type: _ProcessorState
    ):
        # type: (...) -> Any
        """"""
        xml_value = self._processor.parse_at_element(element, state)
        return _hooks_apply_after_parse(self._hooks, state, xml_value)
1282545
def _parse_ldap(ldap_filter):
    # type: (str) -> Optional[LDAPFilter]
    
    if ldap_filter is None:
        # Nothing to do
        return None

    assert is_string(ldap_filter)

    # Remove surrounding spaces
    ldap_filter = ldap_filter.strip()
    if not ldap_filter:
        # Empty string
        return None

    escaped = False
    filter_len = len(ldap_filter)
    root = None
    stack = []
    subfilter_stack = []

    idx = 0
    while idx < filter_len:
        if not escaped:
            if ldap_filter[idx] == "(":
                # Opening filter : get the operator
                idx = _skip_spaces(ldap_filter, idx + 1)
                if idx == -1:
                    raise ValueError(
                        "Missing filter operator: {0}".format(ldap_filter)
                    )

                operator = _compute_operation(ldap_filter, idx)
                if operator is not None:
                    # New sub-filter
                    stack.append(LDAPFilter(operator))
                else:
                    # Sub-filter content
                    subfilter_stack.append(idx)

            elif ldap_filter[idx] == ")":
                # Ending filter : store it in its parent
                if subfilter_stack:
                    # criterion finished
                    start_idx = subfilter_stack.pop()
                    criterion = _parse_ldap_criteria(
                        ldap_filter, start_idx, idx
                    )

                    if stack:
                        top = stack.pop()
                        top.append(criterion)
                        stack.append(top)
                    else:
                        # No parent : filter contains only one criterion
                        # Make a parent to stay homogeneous
                        root = LDAPFilter(AND)
                        root.append(criterion)
                elif stack:
                    # Sub filter finished
                    ended_filter = stack.pop()
                    if stack:
                        top = stack.pop()
                        top.append(ended_filter)
                        stack.append(top)
                    else:
                        # End of the parse
                        root = ended_filter
                else:
                    raise ValueError(
                        "Too many end of parenthesis:{0}: {1}".format(
                            idx, ldap_filter[idx:]
                        )
                    )
            elif ldap_filter[idx] == "\\":
                # Next character must be ignored
                escaped = True
        else:
            # Escaped character ignored
            escaped = False

        # Don't forget to increment...
        idx += 1

    # No root : invalid content
    if root is None:
        raise ValueError("Invalid filter string: {0}".format(ldap_filter))

    # Return the root of the filter
    return root.normalize()
803800
def filterstr_to_filterfunc(filter_str: str, item_type: type):
    """"""

    # The filter_str is parsed, then all names occurring in its AST are replaced by loads to post.<name>. A
    # function Post->bool is returned which evaluates the filter with the post as 'post' in its namespace.

    class TransformFilterAst(ast.NodeTransformer):
        def visit_Name(self, node: ast.Name):
            # pylint:disable=no-self-use
            if not isinstance(node.ctx, ast.Load):
                raise InvalidArgumentException("Invalid filter: Modifying variables ({}) not allowed.".format(node.id))
            if node.id == "datetime":
                return node
            if not hasattr(item_type, node.id):
                raise InvalidArgumentException("Invalid filter: {} not a {} attribute.".format(node.id,
                                                                                               item_type.__name__))
            new_node = ast.Attribute(ast.copy_location(ast.Name('item', ast.Load()), node), node.id,
                                     ast.copy_location(ast.Load(), node))
            return ast.copy_location(new_node, node)

    input_filename = '<command line filter parameter>'
    compiled_filter = compile(TransformFilterAst().visit(ast.parse(filter_str, filename=input_filename, mode='eval')),
                              filename=input_filename, mode='eval')

    def filterfunc(item) -> bool:
        # pylint:disable=eval-used
        return bool(eval(compiled_filter, {'item': item, 'datetime': datetime.datetime}))

    return filterfunc
475801
function getFilterFunc(selector, context) {
    function wordRegExpTester(name, prop) {
      var re = RegExp('(^|\\s+)' + name + '(?=$|\\s)', 'i');
      return function(obj) {return  name ? re.test(obj[prop]) : true;};
    }

    var nodeSet = {};
    var dotPos = nodeSet;
    if (isFunction(selector))
      return selector;
    else if (isNumber(selector))
      return function(v, index) { return index == selector; };
    else if (!selector || selector == '*' ||
             (isString(selector) && (dotPos = /^([\w-]*)\.?([\w-]*)$/.exec(selector)))) {
      var nodeNameFilter = wordRegExpTester(dotPos[1], 'tagName');
      var classNameFilter = wordRegExpTester(dotPos[2], 'className');
      return function(v) {
        return isNode(v) == 1 && nodeNameFilter(v) && classNameFilter(v);
      };
    }
    else if (context)
      return function(v) {
        return $(selector, context)['find'](v)!=_null; // live search instead of node set, for on()
      };
    else {
      $(selector)['each'](function(node) {
        nodeSet[getNodeId(node)] = true;
      });
      return function(v) {
        return nodeSet[getNodeId(v)];
      };
    }
  }
1347037
function filterGenerator(filter) {
	if(typeof filter === "boolean")
		return () => filter;

	if(typeof filter === "function")
		return filter;

	if(filter instanceof RegExp)
		return input => filter.test(input);

	if(filter instanceof Set)
		return input => filter.has(input);

	if(filter instanceof Map)
		return input => !!filter.get(input);

	if(Array.isArray(filter))
		return input => filter.indexOf(input) !== -1;

	if(filter && typeof filter === "object")
		return input => !!filter[input];

	throw new TypeError("Invalid filter type.");
}
293781
def _get_filter_modifier(self, field):
        """"""
        tokens = field.split(FIELD_SEPARATOR)
        if len(tokens) == 1:
            return field, ""
        if tokens[-1] in self.FILTER_OPERATORS.keys():
            return u'.'.join(tokens[:-1]), tokens[-1]
        return u'.'.join(tokens), ""
1204082
function(sel) {
  var filter = []
    , comb = combinators.noop
    , qname
    , cap
    , op
    , len;

  // add implicit universal selectors
  sel = sel.replace(/(^|\s)(:|\[|\.|#)/g, '$1*$2');

  while (cap = /\s*((?:\w+|\*)(?:[.#:][^\s]+|\[[^\]]+\])*)\s*$/.exec(sel)) {
    len = sel.length - cap[0].length;
    cap = cap[1].split(/(?=[\[:.#])/);
    if (!qname) qname = cap[0];
    filter.push(comb(parse(cap)));
    if (len) {
      op = sel[len - 1];
      // if the combinator doesn't exist, 
      // assume it was a whitespace.
      comb = combinators[op] || combinators[op = ' '];
      sel = sel.substring(0, op !== ' ' ? --len : len);
    } else {
      break;
    }
  }

  // compile to a single function
  filter = make(filter);

  // optimize the first qname
  filter.qname = qname;

  return filter;
}
182533
def get_filtered_values_by_selector(self, selector, regex=None, group=1):
        
        data = [
            self.get_text_from_node(node, regex, group)
            for node in self.get_nodes_by_selector(selector)
            if self.get_text_from_node(node, regex, group)
        ]

        return data if len(data) > 1 else data[0]
1189417
def parse(self, element):
        
        """
        values = {}
        for child in element:
            node = self.get_node(child)
            subs = self.parse(child)
            value = subs or node['value']
            if node['tag'] not in values:
                values[node['tag']] = value
            else:
                if not isinstance(values[node['tag']], list):
                    values[node['tag']] = [values.pop(node['tag'])]
                values[node['tag']].append(value)
        return values
797014
def parse(source, remove_comments=True, **kw):
    """"""
    return ElementTree.parse(source, SourceLineParser(), **kw)