Make data filter definition consistent.

    Create a tuple where first element is the row filter and the second element
    is the column filter
441
def _homogenize_data_filter(dfilter):
    
    if isinstance(dfilter, tuple) and (len(dfilter) == 1):
        dfilter = (dfilter[0], None)
    if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):
        dfilter = (None, None)
    elif isinstance(dfilter, dict):
        dfilter = (dfilter, None)
    elif isinstance(dfilter, (list, str)) or (
        isinstance(dfilter, int) and (not isinstance(dfilter, bool))
    ):
        dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter])
    elif isinstance(dfilter[0], dict) or (
        (dfilter[0] is None) and (not isinstance(dfilter[1], dict))
    ):
        pass
    else:
        dfilter = (dfilter[1], dfilter[0])
    return dfilter
1082123
def get_filters(cls, raw_filters, num_cols, columns_dict):  # noqa
        """"""
        filters = None
        for flt in raw_filters:
            col = flt.get('col')
            op = flt.get('op')
            eq = flt.get('val')
            if (
                    not col or
                    not op or
                    (eq is None and op not in ('IS NULL', 'IS NOT NULL'))):
                continue

            # Check if this dimension uses an extraction function
            # If so, create the appropriate pydruid extraction object
            column_def = columns_dict.get(col)
            dim_spec = column_def.dimension_spec if column_def else None
            extraction_fn = None
            if dim_spec and 'extractionFn' in dim_spec:
                (col, extraction_fn) = DruidDatasource._create_extraction_fn(dim_spec)

            cond = None
            is_numeric_col = col in num_cols
            is_list_target = op in ('in', 'not in')
            eq = cls.filter_values_handler(
                eq, is_list_target=is_list_target,
                target_column_is_numeric=is_numeric_col)

            # For these two ops, could have used Dimension,
            # but it doesn't support extraction functions
            if op == '==':
                cond = Filter(dimension=col, value=eq, extraction_function=extraction_fn)
            elif op == '!=':
                cond = ~Filter(dimension=col, value=eq, extraction_function=extraction_fn)
            elif op in ('in', 'not in'):
                fields = []
                # ignore the filter if it has no value
                if not len(eq):
                    continue
                # if it uses an extraction fn, use the "in" operator
                # as Dimension isn't supported
                elif extraction_fn is not None:
                    cond = Filter(
                        dimension=col,
                        values=eq,
                        type='in',
                        extraction_function=extraction_fn,
                    )
                elif len(eq) == 1:
                    cond = Dimension(col) == eq[0]
                else:
                    for s in eq:
                        fields.append(Dimension(col) == s)
                    cond = Filter(type='or', fields=fields)
                if op == 'not in':
                    cond = ~cond
            elif op == 'regex':
                cond = Filter(
                    extraction_function=extraction_fn,
                    type='regex',
                    pattern=eq,
                    dimension=col,
                )

            # For the ops below, could have used pydruid's Bound,
            # but it doesn't support extraction functions
            elif op == '>=':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    dimension=col,
                    lowerStrict=False,
                    upperStrict=False,
                    lower=eq,
                    upper=None,
                    alphaNumeric=is_numeric_col,
                )
            elif op == '<=':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    dimension=col,
                    lowerStrict=False,
                    upperStrict=False,
                    lower=None,
                    upper=eq,
                    alphaNumeric=is_numeric_col,
                )
            elif op == '>':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    lowerStrict=True,
                    upperStrict=False,
                    dimension=col,
                    lower=eq,
                    upper=None,
                    alphaNumeric=is_numeric_col,
                )
            elif op == '<':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    upperStrict=True,
                    lowerStrict=False,
                    dimension=col,
                    lower=None,
                    upper=eq,
                    alphaNumeric=is_numeric_col,
                )
            elif op == 'IS NULL':
                cond = Dimension(col) == None  # NOQA
            elif op == 'IS NOT NULL':
                cond = Dimension(col) != None  # NOQA

            if filters:
                filters = Filter(type='and', fields=[
                    cond,
                    filters,
                ])
            else:
                filters = cond

        return filters
1006089
def filter_set(input, **params):
    
    PARAM_WHERE = 'where'

    return Converter.df2list(pd.DataFrame.from_records(input).query(params.get(PARAM_WHERE)))
831877
def idat(self, rows, packed=False):
        """"""
        # http://www.w3.org/TR/PNG/#11IDAT
        filt = Filter(self.bitdepth * self.planes,
                      self.interlace, self.height)
        data = bytearray()

        def byteextend(rowbytes):
            """Default extending data with bytes. Applying filter"""
            data.extend(filt.do_filter(self.filter_type, rowbytes))

        # Choose an extend function based on the bitdepth.  The extend
        # function packs/decomposes the pixel values into bytes and
        # stuffs them onto the data array.
        if self.bitdepth == 8 or packed:
            extend = byteextend
        elif self.bitdepth == 16:
            def extend(sl):
                """Decompose into bytes before byteextend"""
                fmt = '!%dH' % len(sl)
                byteextend(bytearray(struct.pack(fmt, *sl)))
        else:
            # Pack into bytes
            assert self.bitdepth < 8
            # samples per byte
            spb = 8 // self.bitdepth

            def extend(sl):
                """Pack into bytes before byteextend"""
                a = bytearray(sl)
                # Adding padding bytes so we can group into a whole
                # number of spb-tuples.
                l = float(len(a))
                extra = math.ceil(l / float(spb)) * spb - l
                a.extend([0] * int(extra))
                # Pack into bytes
                l = group(a, spb)
                l = [reduce(lambda x, y: (x << self.bitdepth) + y, e)
                     for e in l]
                byteextend(l)

        # Build the first row, testing mostly to see if we need to
        # changed the extend function to cope with NumPy integer types
        # (they cause our ordinary definition of extend to fail, so we
        # wrap it).  See
        # http://code.google.com/p/pypng/issues/detail?id=44
        enumrows = enumerate(rows)
        del rows

        # :todo: Certain exceptions in the call to ``.next()`` or the
        # following try would indicate no row data supplied.
        # Should catch.
        i, row = next(enumrows)
        try:
            # If this fails...
            extend(row)
        except:
            # ... try a version that converts the values to int first.
            # Not only does this work for the (slightly broken) NumPy
            # types, there are probably lots of other, unknown, "nearly"
            # int types it works for.
            def wrapmapint(f):
                return lambda sl: f([int(x) for x in sl])
            extend = wrapmapint(extend)
            del wrapmapint
            extend(row)

        for i, row in enumrows:
            extend(row)
            if len(data) > self.chunk_limit:
                yield bytearray_to_bytes(data)
                # Because of our very witty definition of ``extend``,
                # above, we must re-use the same ``data`` object.  Hence
                # we use ``del`` to empty this one, rather than create a
                # fresh one (which would be my natural FP instinct).
                del data[:]
        if len(data):
            yield bytearray_to_bytes(data)
        self.irows = i + 1
545469
def filterAcceptsRow(self, source_row, source_parent):
        """"""
        model = self.sourceModel()
        item = model.items[source_row]
        key = getattr(item, "filter", None)
        if key is not None:
            regex = self.filterRegExp()
            if regex.pattern():
                match = regex.indexIn(key)
                return False if match == -1 else True

        # --- Check if any family assigned to the plugin is in allowed families
        for role, values in self.includes.items():
            includes_list = [([x] if isinstance(x, (list, tuple)) else x)
                             for x in getattr(item, role, None)]
            return any(include in values for include in includes_list)

        for role, values in self.excludes.items():
            data = getattr(item, role, None)
            if data in values:
                return False

        return super(ProxyModel, self).filterAcceptsRow(
            source_row, source_parent)
1210375
def _add_filter_node(root, filter_, value):
        """"""
        filter_el = ElementTree.SubElement(root, 'Filter')
        filter_el.set('name', filter_.name)

        # Set filter value depending on type.
        if filter_.type == 'boolean':
            # Boolean case.
            if value is True or value.lower() in {'included', 'only'}:
                filter_el.set('excluded', '0')
            elif value is False or value.lower() == 'excluded':
                filter_el.set('excluded', '1')
            else:
                raise ValueError('Invalid value for boolean filter ({})'
                                 .format(value))
        elif isinstance(value, list) or isinstance(value, tuple):
            # List case.
            filter_el.set('value', ','.join(map(str, value)))
        else:
            # Default case.
            filter_el.set('value', str(value))
698846
function filterRows(columnFilters) {
      var _this4 = this;

      var fromFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      // if (!this.rows.length) return;
      // this is invoked either as a result of changing filters
      // or as a result of modifying rows.
      this.columnFilters = columnFilters;
      var computedRows = cloneDeep(this.originalRows); // do we have a filter to care about?
      // if not we don't need to do anything

      if (this.columnFilters && Object.keys(this.columnFilters).length) {
        // every time we filter rows, we need to set current page
        // to 1
        // if the mode is remote, we only need to reset, if this is
        // being called from filter, not when rows are changing
        if (this.mode !== 'remote' || fromFilter) {
          this.changePage(1);
        } // we need to emit an event and that's that.
        // but this only needs to be invoked if filter is changing
        // not when row object is modified.


        if (fromFilter) {
          this.$emit('on-column-filter', {
            columnFilters: this.columnFilters
          });
        } // if mode is remote, we don't do any filtering here.


        if (this.mode === 'remote') {
          if (fromFilter) {
            this.$emit('update:isLoading', true);
          } else {
            // if remote filtering has already been taken care of.
            this.filteredRows = computedRows;
          }

          return;
        }

        var _loop = function _loop(i) {
          var col = _this4.typedColumns[i];

          if (_this4.columnFilters[col.field]) {
            computedRows = each(computedRows, function (headerRow) {
              var newChildren = headerRow.children.filter(function (row) {
                // If column has a custom filter, use that.
                if (col.filterOptions && typeof col.filterOptions.filterFn === 'function') {
                  return col.filterOptions.filterFn(_this4.collect(row, col.field), _this4.columnFilters[col.field]);
                } // Otherwise Use default filters


                var typeDef = col.typeDef;
                return typeDef.filterPredicate(_this4.collect(row, col.field), _this4.columnFilters[col.field]);
              }); // should we remove the header?

              headerRow.children = newChildren;
            });
          }
        };

        for (var i = 0; i < this.typedColumns.length; i++) {
          _loop(i);
        }
      }

      this.filteredRows = computedRows;
    }
192239
def _construct_select_query(**filter_definition):
    
    table_name = filter_definition.pop('table')
    distinct = filter_definition.pop('distinct', False)
    select_count = filter_definition.pop('count', False)

    if distinct and select_count:
        raise UnsupportedDefinitionError('SELECT (DISTINCT ...) is not supported')

    if select_count and 'select' in filter_definition:
        raise UnsupportedDefinitionError('SELECT COUNT(columns) is not supported')

    if 'joins' in filter_definition:
        join_definitions = filter_definition.pop('joins')

        if not isinstance(join_definitions, (tuple, list)):
            join_definitions = (join_definitions,)

        filter_definition['joins'] = []
        for join_def in join_definitions:
            filter_definition['joins'].append(_expand_join(join_def))

    if 'where' in filter_definition:
        for key, value in filter_definition['where'].items():
            if is_filter_query(value):
                # We can do it recursively here
                sub_query = value.pop(DEFAULT_FILTER_KEY)
                if value:
                    raise ParsingInputError("Unknown keys for sub-query provided: %s" % value)
                filter_definition['where'][key] = mosql_raw('( {} )'.format(_construct_select_query(**sub_query)))
            elif isinstance(value, str) and value.startswith('$') and QUERY_REFERENCE.fullmatch(value[1:]):
                # Make sure we construct correct query with escaped table name and escaped column for sub-queries
                filter_definition['where'][key] = mosql_raw('"{}"'.format('"."'.join(value[1:].split('.'))))

    raw_select = select(table_name, **filter_definition)

    if distinct:
        # Note that we want to limit replace to the current SELECT, not affect nested ones
        raw_select = raw_select.replace('SELECT', 'SELECT DISTINCT', 1)
    if select_count:
        # Note that we want to limit replace to the current SELECT, not affect nested ones
        raw_select = raw_select.replace('SELECT *', 'SELECT COUNT(*)', 1)

    return raw_select
40275
private boolean acceptValue(int row, Map<Integer, Object> filter) {
		boolean accept = true;
		Set<Integer> keys = filter.keySet();
		for (int index : keys) {
			if (!filter.get(index).equals(dataSource.getValueAt(row, fields.get(index)))) {
				// System.out.println(" + " + filter.get(j));
				// System.out.println(" - " + dataSource.getValueAt(i,
				// fields.get(j)));
				return false;
			}
		}

		return accept;
	}
473332
def filter(self, column, condition='!=', value=None):
        
        ret = self.__class__(
            columns=self.columns, row_columns=self.row_columns, tab=self.tab,
            key_on=self.key_on)
        for row in self:
            if getattr(row[column], condition, None):
                if eval('row[column].%s(%s)' % (condition, value)):
                    ret.append(row)
            if eval('row[column] %s value' % condition):
                ret.append(row)
        return ret
1024584
def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):
        """"""
        key = self._actual_key(key)
        locations = [x[0] for x in lst]

        if not include_self and key in locations:
            lst.pop(locations.index(key))

        lst.sort(key=lambda x: x[1], reverse=biggest_first)
        lst = [x for x, y in lst]

        # RoW in both key and lst, but not defined; only RoW remains if exclusive
        if key == 'RoW' and 'RoW' not in self and exclusive:
            return ['RoW'] if 'RoW' in lst else []
        elif exclusive:
            removed, remaining = set(), []
            while lst:
                current = lst.pop(0)
                faces = self[current]
                if not faces.intersection(removed):
                    removed.update(faces)
                    remaining.append(current)
            lst = remaining

        # If RoW not resolved, make it the smallest
        if 'RoW' not in self and 'RoW' in lst:
            lst[-1 if biggest_first else 0] = lst.pop(lst.index('RoW'))

        return lst
250447
private Filter createChain(
      ColumnPaginationFilter filter, Filter intermediate) {
    ChainFilter chain = FILTERS.chain();
    chain.filter(FILTERS.limit().cellsPerColumn(1));
    if (intermediate != null) {
      chain.filter(intermediate);
    }
    chain.filter(FILTERS.limit().cellsPerRow(filter.getLimit()));
    return chain;
  }
990819
def apply_filter_list(func, obj):
    """"""
    if isinstance(obj, (list, tuple)):
        return [func(item) for item in obj]
    return func(obj)
937644
def apply(row, offset)
      row.hidden = @filter.apply(row.cells[offset+col_id.to_i])
    end
219520
def convolve( filter )
      filter = Node.match( filter, typecode ).new filter unless filter.matched?
      array = self
      (dimension - filter.dimension).times { array = array.roll }
      array.table(filter) { |a,b| a * b }.diagonal { |s,x| s + x }
    end
1249031
def _build_filters(_filters):
    
    root = utils.NestedDict({})
    for _filter in _filters:
        operation = None
        for operation, token in SPLIT_TOKENS:
            # split "some.key=value" into ["some.key", "value"]
            top_parts = _filter.split(token, 1)
            if len(top_parts) == 2:
                break
        else:
            raise exceptions.CLIAbort('Failed to find valid operation for: %s'
                                      % _filter)

        key, value = top_parts
        current = root
        # split "some.key" into ["some", "key"]
        parts = [part.strip() for part in key.split('.')]

        # Actually drill down and add the filter
        for part in parts[:-1]:
            current = current[part]

        if operation == 'eq':
            current[parts[-1]] = utils.query_filter(value.strip())
        elif operation == 'in':
            current[parts[-1]] = {
                'operation': 'in',
                'options': [{
                    'name': 'data',
                    'value': [p.strip() for p in value.split(',')],
                }],
            }

    return root.to_dict()
839645
def __reversed_filter(filterable, filter_, logic_operation='and'):
        
        condition = []
        try:
            subscribers_for_any = filterable.query('type == "__ANY__"')
        except pd.core.computation.ops.UndefinedVariableError:
            subscribers_for_any = pd.DataFrame()
        if not filter_:
            return filterable
        else:
            for existing_col in filterable:
                for meta_tag, meta_value in filter_.items():
                    if meta_tag == existing_col:
                        condition.append('{key} == "{value}"'.format(key=meta_tag, value=meta_value))
            try:
                res = filterable.query(" {operation} ".format(operation=logic_operation).join(condition))
            except pd.core.computation.ops.UndefinedVariableError:
                return pd.DataFrame().append(subscribers_for_any)
            else:
                return res.append(subscribers_for_any)