query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
filter array
|
python
|
def filter(array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation
"""
weld_obj = WeldObject(encoder_, decoder_)
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
predicates_var = weld_obj.update(predicates)
if isinstance(predicates, WeldObject):
predicates_var = predicates.obj_id
weld_obj.dependencies[predicates_var] = predicates
weld_template = """
result(
for(
zip(%(array)s, %(predicates)s),
appender,
|b, i, e| if (e.$1, merge(b, e.$0), b)
)
)
"""
weld_obj.weld_code = weld_template % {
"array": array_var,
"predicates": predicates_var}
return weld_obj
|
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L155-L193
|
filter array
|
python
|
def weld_filter(array, weld_type, bool_array):
"""Returns a new array only with the elements with a corresponding True in bool_array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
weld_type : WeldType
Type of the elements in the input array.
bool_array : numpy.ndarray or WeldObject
Array of bool with True for elements in array desired in the result array.
Returns
-------
WeldObject
Representation of this computation.
"""
obj_id, weld_obj = create_weld_object(array)
bool_obj_id = get_weld_obj_id(weld_obj, bool_array)
weld_template = """result(
for(
zip({array}, {bool_array}),
appender[{type}],
|b: appender[{type}], i: i64, e: {{{type}, bool}}|
if (e.$1,
merge(b, e.$0),
b)
)
)"""
weld_obj.weld_code = weld_template.format(array=obj_id,
bool_array=bool_obj_id,
type=weld_type)
return weld_obj
|
https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/weld/weld_ops.py#L97-L133
|
filter array
|
python
|
def filter(self, func, axis=(0,)):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the
keys, which may require a transpose/reshape.
Parameters
----------
func : function
Function to apply, should return boolean
axis : tuple or int, optional, default=(0,)
Axis or multiple axes to filter along.
Returns
-------
BoltArrayLocal
"""
axes = sorted(tupleize(axis))
reshaped = self._align(axes)
filtered = asarray(list(filter(func, reshaped)))
return self._constructor(filtered)
|
https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/local/array.py#L66-L92
|
filter array
|
python
|
def filter(self, func, axis=(0,), sort=False):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the keys,
which may incur a swap.
Parameters
----------
func : function
Function to apply, should return boolean
axis : tuple or int, optional, default=(0,)
Axis or multiple axes to filter along.
sort: bool, optional, default=False
Whether or not to sort by key before reindexing
Returns
-------
BoltArraySpark
"""
axis = tupleize(axis)
swapped = self._align(axis)
def f(record):
return func(record[1])
rdd = swapped._rdd.filter(f)
if sort:
rdd = rdd.sortByKey().values()
else:
rdd = rdd.values()
# count the resulting array in order to reindex (linearize) the keys
count, zipped = zip_with_index(rdd)
if not count:
count = zipped.count()
reindexed = zipped.map(lambda kv: (tupleize(kv[1]), kv[0]))
# since we can only filter over one axis, the remaining shape is always the following
remaining = list(swapped.shape[len(axis):])
if count != 0:
shape = tuple([count] + remaining)
else:
shape = (0,)
return self._constructor(reindexed, shape=shape, split=1).__finalize__(swapped)
|
https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L193-L241
|
filter array
|
python
|
def filter(self, func):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the
keys, which may require a transpose/reshape.
Parameters
----------
func : function
Function to apply, should return boolean
"""
if self.mode == 'local':
reshaped = self._align(self.baseaxes)
filtered = asarray(list(filter(func, reshaped)))
if self.labels is not None:
mask = asarray(list(map(func, reshaped)))
if self.mode == 'spark':
sort = False if self.labels is None else True
filtered = self.values.filter(func, axis=self.baseaxes, sort=sort)
if self.labels is not None:
keys, vals = zip(*self.values.map(func, axis=self.baseaxes, value_shape=(1,)).tordd().collect())
perm = sorted(range(len(keys)), key=keys.__getitem__)
mask = asarray(vals)[perm]
if self.labels is not None:
s1 = prod(self.baseshape)
newlabels = self.labels.reshape(s1, 1)[mask].squeeze()
else:
newlabels = None
return self._constructor(filtered, labels=newlabels).__finalize__(self, noprop=('labels',))
|
https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L372-L410
|
filter array
|
python
|
def std_filter(array, n_std=2.0, return_index=False):
"""Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance(array, np.ndarray):
array = np.array(array)
mean, std = array.mean(), array.std()
good_index = np.where(abs(array - mean) <= n_std * std)
bad_index = np.where(abs(array - mean) > n_std * std)
if return_index:
return good_index[0], bad_index[0]
else:
return array[good_index], array[bad_index]
|
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/outlier.py#L47-L64
|
filter array
|
python
|
def bandpass_filter(data, low, high, fs, order=5):
"""
Does a bandpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param low: The low cutoff in Hz.
:param high: The high cutoff in Hz.
:param fs: The sample rate (in Hz) of the data.
:param order: The order of the filter. The higher the order, the tighter the roll-off.
:returns: Filtered data (numpy array).
"""
nyq = 0.5 * fs
low = low / nyq
high = high / nyq
b, a = signal.butter(order, [low, high], btype='band')
y = signal.lfilter(b, a, data)
return y
|
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/algorithms/filters.py#L7-L23
|
filter array
|
python
|
def pivot_filter(pivot_array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation
"""
weld_obj = WeldObject(encoder_, decoder_)
pivot_array_var = weld_obj.update(pivot_array)
if isinstance(pivot_array, WeldObject):
pivot_array_var = pivot_array.obj_id
weld_obj.dependencies[pivot_array_var] = pivot_array
predicates_var = weld_obj.update(predicates)
if isinstance(predicates, WeldObject):
predicates_var = predicates.obj_id
weld_obj.dependencies[predicates_var] = predicates
weld_template = """
let index_filtered =
result(
for(
zip(%(array)s.$0, %(predicates)s),
appender,
|b, i, e| if (e.$1, merge(b, e.$0), b)
)
);
let pivot_filtered =
map(
%(array)s.$1,
|x|
result(
for(
zip(x, %(predicates)s),
appender,
|b, i, e| if (e.$1, merge(b, e.$0), b)
)
)
);
{index_filtered, pivot_filtered, %(array)s.$2}
"""
weld_obj.weld_code = weld_template % {
"array": pivot_array_var,
"predicates": predicates_var}
return weld_obj
|
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L195-L247
|
filter array
|
python
|
def overlaps(self, *args):
"""Construct an array overlaps (``&&``) filter.
:param args: Filter values
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field
"""
self.op = '&&'
self.negate_op = None
self.value = self._array_value(args)
return self
|
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/filters.py#L214-L224
|
filter array
|
python
|
def contains(self, *args):
"""Construct an array contains (``@>``) filter.
:param args: Filter values
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field
"""
self.op = '@>'
self.negate_op = None
self.value = self._array_value(args)
return self
|
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/filters.py#L190-L200
|
filter array
|
python
|
def filter(self, index): #@ReservedAssignment
"""
Filters a datamat by different aspects.
This function is a device to filter the datamat by certain logical
conditions. It takes as input a logical array (contains only True
or False for every datapoint) and kicks out all datapoints for which
the array says False. The logical array can conveniently be created
with numpy::
>>> print np.unique(fm.category)
np.array([2,9])
>>> fm_filtered = fm[ fm.category == 9 ]
>>> print np.unique(fm_filtered)
np.array([9])
Parameters:
index : array
Array-like that contains True for every element that
passes the filter; else contains False
Returns:
datamat : Datamat Instance
"""
return Datamat(categories=self._categories, datamat=self, index=index)
|
https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L140-L163
|
filter array
|
python
|
def filter_by_func(self, func:Callable)->'ItemList':
"Only keep elements for which `func` returns `True`."
self.items = array([o for o in self.items if func(o)])
return self
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L149-L152
|
filter array
|
python
|
def contained_by(self, *args):
"""Construct an array contained by (``<@``) filter.
:param args: Filter values
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field
"""
self.op = '<@'
self.negate_op = None
self.value = self._array_value(args)
return self
|
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/filters.py#L202-L212
|
filter array
|
python
|
def average_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculates a multi-dimensional average filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2).
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'reflect'
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
origin : scalar, optional
The ``origin`` parameter controls the placement of the filter.
Default 0
Returns
-------
average_filter : ndarray
Returned array of same shape as `input`.
Notes
-----
Convenience implementation employing convolve.
See Also
--------
scipy.ndimage.filters.convolve : Convolve an image with a kernel.
"""
footprint = __make_footprint(input, size, footprint)
filter_size = footprint.sum()
output = _get_output(output, input)
sum_filter(input, footprint=footprint, output=output, mode=mode, cval=cval, origin=origin)
output /= filter_size
return output
|
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/image.py#L230-L284
|
filter array
|
python
|
def iter_filter(self, filters, databases=None, fields=None,
filter_behavior="and"):
"""General purpose filter iterator.
This general filter iterator allows the filtering of entries based
on one or more custom filters. These filters must contain
an entry of the `storage` attribute, a comparison operator, and the
test value. For example, to filter out entries with coverage below 80::
my_filter = ["coverage", ">=", 80]
Filters should always be provide as a list of lists::
iter_filter([["coverage", ">=", 80]])
# or
my_filters = [["coverage", ">=", 80],
["identity", ">=", 50]]
iter_filter(my_filters)
As a convenience, a list of the desired databases can be directly
specified using the `database` argument, which will only report
entries for the specified databases::
iter_filter(my_filters, databases=["plasmidfinder"])
By default, this method will yield the complete entry record. However,
the returned filters can be specified using the `fields` option::
iter_filter(my_filters, fields=["reference", "coverage"])
Parameters
----------
filters : list
List of lists with the custom filter. Each list should have three
elements. (1) the key from the entry to be compared; (2) the
comparison operator; (3) the test value. Example:
``[["identity", ">", 80]]``.
databases : list
List of databases that should be reported.
fields : list
List of fields from each individual entry that are yielded.
filter_behavior : str
options: ``'and'`` ``'or'``
Sets the behaviour of the filters, if multiple filters have been
provided. By default it is set to ``'and'``, which means that an
entry has to pass all filters. It can be set to ``'or'``, in which
case one one of the filters has to pass.
yields
------
dic : dict
Dictionary object containing a :py:attr:`Abricate.storage` entry
that passed the filters.
"""
if filter_behavior not in ["and", "or"]:
raise ValueError("Filter behavior must be either 'and' or 'or'")
for dic in self.storage.values():
# This attribute will determine whether an entry will be yielded
# or not
_pass = False
# Stores the flags with the test results for each filter
# The results will be either True or False
flag = []
# Filter for databases
if databases:
# Skip entry if not in specified database
if dic["database"] not in databases:
continue
# Apply filters
for f in filters:
# Get value of current filter
val = dic[f[0]]
if not self._test_truth(val, f[1], f[2]):
flag.append(False)
else:
flag.append(True)
# Test whether the entry will pass based on the test results
# and the filter behaviour
if filter_behavior == "and":
if all(flag):
_pass = True
elif filter_behavior == "or":
if any(flag):
_pass = True
if _pass:
if fields:
yield dict((x, y) for x, y in dic.items() if x in fields)
else:
yield dic
|
https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/templates/process_abricate.py#L242-L340
|
filter array
|
python
|
def _filter_attrs(attrs, ignored_attrs):
""" Return attrs that are not in ignored_attrs
"""
return dict((k, v) for k, v in attrs.items() if k not in ignored_attrs)
|
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/convert.py#L30-L33
|
filter array
|
python
|
def filter(self, collection, data, **kwargs):
"""Filter given collection."""
ops = self.parse(data)
collection = self.apply(collection, ops, **kwargs)
return ops, collection
|
https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/filters.py#L41-L45
|
filter array
|
python
|
def list_current_filter_set(self,raw=False):
"""User to list a currently selected filter set"""
buf = []
self.open_umanager()
self.ser.write(''.join((self.cmd_current_filter_list,self.cr)))
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout,lambda x,y,z: buf.append(y.rstrip()[:-1])):
if raw:
rv = buf = buf[0]
else:
rv, buf = self.filter_organizer(buf[0])
else:
raise Dam1021Error(16,"Failed to list currently selected filter set")
self.close_umanager()
log.info(buf)
return rv
|
https://github.com/fortaa/dam1021/blob/1bc5b75ebf2cc7bc8dc2a451793a9e769e16ce5f/src/dam1021.py#L374-L392
|
filter array
|
python
|
def filtered(self, *, type_=None, lang=None, attrs={}):
"""
This method is a convencience wrapper around :meth:`filter` which
evaluates the result into a list and returns that list.
"""
return list(self.filter(type_=type_, lang=lang, attrs=attrs))
|
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L262-L267
|
filter array
|
python
|
def in_array(self, event_property, value):
"""An in-array filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.in_array('path', '/event')
>>> print(filtered)
request(elapsed_ms).in(path, ["/", "e", "v", "e", "n", "t"])
>>> filtered = request_time.in_array('path', ['/event', '/'])
>>> print(filtered)
request(elapsed_ms).in(path, ["/event", "/"])
"""
c = self.copy()
c.filters.append(filters.IN(event_property, value))
return c
|
https://github.com/sbuss/pypercube/blob/e9d2cca9c004b8bad6d1e0b68b080f887a186a22/pypercube/expression.py#L361-L374
|
filter array
|
python
|
def apply_filter_list(func, obj):
"""Apply `func` to list or tuple `obj` element-wise and directly otherwise."""
if isinstance(obj, (list, tuple)):
return [func(item) for item in obj]
return func(obj)
|
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/expression_engines/jinja/filters.py#L13-L17
|
filter array
|
python
|
def _get_filter_field(field_name, field_value):
""" Return field to apply into filter, if an array then use a range, otherwise look for a term match """
filter_field = None
if isinstance(field_value, ValueRange):
range_values = {}
if field_value.lower:
range_values.update({"gte": field_value.lower_string})
if field_value.upper:
range_values.update({"lte": field_value.upper_string})
filter_field = {
"range": {
field_name: range_values
}
}
elif _is_iterable(field_value):
filter_field = {
"terms": {
field_name: field_value
}
}
else:
filter_field = {
"term": {
field_name: field_value
}
}
return filter_field
|
https://github.com/edx/edx-search/blob/476cf02b71ceba34ae7d8b798f36d60692317c55/search/elastic.py#L64-L90
|
filter array
|
python
|
def filter(self, fn, skip_na=True, seed=None):
"""
Filter this SArray by a function.
Returns a new SArray filtered by this SArray. If `fn` evaluates an
element to true, this element is copied to the new SArray. If not, it
isn't. Throws an exception if the return type of `fn` is not castable
to a boolean value.
Parameters
----------
fn : function
Function that filters the SArray. Must evaluate to bool or int.
skip_na : bool, optional
If True, will not apply fn to any undefined values.
seed : int, optional
Used as the seed if a random number generator is included in fn.
Returns
-------
out : SArray
The SArray filtered by fn. Each element of the SArray is of
type int.
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.filter(lambda x: x < 3)
dtype: int
Rows: 2
[1, 2]
"""
assert callable(fn), "Input must be callable"
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed))
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1923-L1963
|
filter array
|
python
|
def filter(self, callback=None):
"""
Run a filter over each of the items.
:param callback: The filter callback
:type callback: callable or None
:rtype: Collection
"""
if callback:
return self.__class__(list(filter(callback, self.items)))
return self.__class__(list(filter(None, self.items)))
|
https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L240-L252
|
filter array
|
python
|
def filter_by_rand(self, p:float, seed:int=None):
"Keep random sample of `items` with probability `p` and an optional `seed`."
if seed is not None: np.random.seed(seed)
return self.filter_by_func(lambda o: rand_bool(p))
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L165-L168
|
filter array
|
python
|
def bandpass_filter(data, k, w1, w2):
"""
This function will apply a bandpass filter to data. It will be kth
order and will select the band between w1 and w2.
Parameters
----------
data: array, dtype=float
The data you wish to filter
k: number, int
The order of approximation for the filter. A max value for
this isdata.size/2
w1: number, float
This is the lower bound for which frequencies will pass
through.
w2: number, float
This is the upper bound for which frequencies will pass
through.
Returns
-------
y: array, dtype=float
The filtered data.
"""
data = np.asarray(data)
low_w = np.pi * 2 / w2
high_w = np.pi * 2 / w1
bweights = np.zeros(2 * k + 1)
bweights[k] = (high_w - low_w) / np.pi
j = np.arange(1, int(k) + 1)
weights = 1 / (np.pi * j) * (sin(high_w * j) - sin(low_w * j))
bweights[k + j] = weights
bweights[:k] = weights[::-1]
bweights -= bweights.mean()
return fftconvolve(bweights, data, mode='valid')
|
https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/filters.py#L83-L119
|
filter array
|
python
|
def make_filter_list(filters):
"""Transform filters into list of table rows."""
filter_list = []
filter_ids = []
for f in filters:
filter_ids.append(f.index)
fullname = URL_P.sub(r'`<\1>`_', f.fullname)
filter_list.append((str(f.index + 1),
f.name,
"{0:.2f}".format(f.msun_vega),
"{0:.2f}".format(f.msun_ab),
"{0:.1f}".format(f.lambda_eff),
fullname))
sortf = lambda item: int(item[0])
filter_list.sort(key=sortf)
return filter_list
|
https://github.com/dfm/python-fsps/blob/29b81d0ff317532919451ca60b9d36aa1743bd21/scripts/fsps_filter_table.py#L28-L43
|
filter array
|
python
|
def filter_by(self, values, exclude=False):
"""
Filter an SArray by values inside an iterable object. The result is an SArray that
only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`.
If ``values`` is not an SArray, we attempt to convert it to one before filtering.
Parameters
----------
values : SArray | list | numpy.ndarray | pandas.Series | str
The values to use to filter the SArray. The resulting SArray will
only include rows that have one of these values in the given
column.
exclude : bool
If True, the result SArray will contain all rows EXCEPT those that
have one of the ``values``.
Returns
-------
out : SArray
The filtered SArray.
Examples
--------
>>> sa = SArray(['dog', 'cat', 'cow', 'horse'])
>>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake'])
dtype: str
Rows: 2
['dog', 'cat']
>>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake'], exclude=True)
dtype: str
Rows: 2
['horse', 'cow']
"""
from .sframe import SFrame as _SFrame
column_name = 'sarray'
# Convert values to SArray
if not isinstance(values, SArray): #type(values) is not SArray:
# If we were given a single element, try to put in list and convert
# to SArray
if not _is_non_string_iterable(values):
values = [values]
values = SArray(values)
# Convert values to SFrame
value_sf = _SFrame()
value_sf.add_column(values, column_name, inplace=True)
given_type = value_sf.column_types()[0] #value column type
existing_type = self.dtype
sarray_sf = _SFrame()
sarray_sf.add_column(self, column_name, inplace=True)
if given_type != existing_type:
raise TypeError("Type of given values does not match type of the SArray")
# Make sure the values list has unique values, or else join will not
# filter.
value_sf = value_sf.groupby(column_name, {})
with cython_context():
if exclude:
id_name = "id"
value_sf = value_sf.add_row_number(id_name)
tmp = _SFrame(_proxy=sarray_sf.__proxy__.join(value_sf.__proxy__,
'left',
{column_name:column_name}))
ret_sf = tmp[tmp[id_name] == None]
return ret_sf[column_name]
else:
ret_sf = _SFrame(_proxy=sarray_sf.__proxy__.join(value_sf.__proxy__,
'inner',
{column_name:column_name}))
return ret_sf[column_name]
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4402-L4480
|
filter array
|
python
|
def _parse_filter_arg(self, arg):
"""
Parses a filter arg in the format:
<colname>__<op>
:returns: colname, op tuple
"""
statement = arg.rsplit('__', 1)
if len(statement) == 1:
return arg, None
elif len(statement) == 2:
return statement[0], statement[1]
else:
raise QueryException("Can't parse '{}'".format(arg))
|
https://github.com/cqlengine/cqlengine/blob/7079eaf7071cbf5a045e1d1ab57f6d1b5ba3f9dc/cqlengine/query.py#L406-L418
|
filter array
|
python
|
def assembla_filter(func):
"""
Filters :data for the objects in it which possess attributes equal in
name/value to a key/value in kwargs.
Each key/value combination in kwargs is compared against the object, so
multiple keyword arguments can be passed in to constrain the filtering.
"""
@wraps(func)
def wrapper(class_instance, **kwargs):
# Get the result
extra_params = kwargs.get('extra_params', None)
if extra_params:
del kwargs['extra_params']
results = func(class_instance, extra_params)
# Filter the result
if kwargs:
results = filter(
# Find the objects who have an equal number of matching attr/value
# combinations as `len(kwargs)`
lambda obj: len(kwargs) == len(
filter(
lambda boolean: boolean,
[obj.get(attr_name) == value
for attr_name, value in kwargs.iteritems()]
)
),
results
)
return results
return wrapper
|
https://github.com/markfinger/assembla/blob/967a77a5ba718df94f60e832b6e0cf14c72426aa/assembla/lib.py#L43-L76
|
filter array
|
python
|
def check_filter(self, args, kwargs):
"""
Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippet:
`all(f(*args, **kwargs) for f in self.filters)`
"""
for f in self._filters:
if not f(*args, **kwargs):
return False
return True
|
https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/filters.py#L48-L61
|
filter array
|
python
|
def _filter(request, object_, tags=None, more=False, orderby='created'):
"""Filters Piece objects from self based on filters, search, and range
:param tags: List of tag IDs to filter
:type tags: list
:param more -- bool, Returns more of the same filtered set of images based on session range
return list, Objects filtered
"""
res = Result()
models = QUERY_MODELS
idDict = {}
objDict = {}
data = {}
modelmap = {}
length = 75
# -- Get all IDs for each model
for m in models:
modelmap[m.model_class()] = m.model
if object_:
idDict[m.model] = m.model_class().objects.filter(gallery=object_)
else:
idDict[m.model] = m.model_class().objects.all()
if idDict[m.model] is None:
continue
if tags:
for bucket in tags:
searchQuery = ""
o = None
for item in bucket:
if item == 0:
# -- filter by tagless
idDict[m.model].annotate(num_tags=Count('tags'))
if not o:
o = Q()
o |= Q(num_tags__lte=1)
break
elif isinstance(item, six.integer_types):
# -- filter by tag
if not o:
o = Q()
o |= Q(tags__id=item)
else:
# -- add to search string
searchQuery += item + ' '
if not HAYSTACK:
if not o:
o = Q()
# -- use a basic search
o |= Q(title__icontains=item)
if HAYSTACK and searchQuery != "":
# -- once all tags have been filtered, filter by search
searchIDs = search(searchQuery, m.model_class())
if searchIDs:
if not o:
o = Q()
o |= Q(id__in=searchIDs)
if o:
# -- apply the filters
idDict[m.model] = idDict[m.model].annotate(num_tags=Count('tags')).filter(o)
else:
idDict[m.model] = idDict[m.model].none()
# -- Get all ids of filtered objects, this will be a very fast query
idDict[m.model] = list(idDict[m.model].order_by('-{}'.format(orderby)).values_list('id', flat=True))
lastid = request.session.get('last_{}'.format(m.model), 0)
if not idDict[m.model]:
continue
if not more:
lastid = idDict[m.model][0]
index = idDict[m.model].index(lastid)
if more and lastid != 0:
index += 1
idDict[m.model] = idDict[m.model][index:index + length]
# -- perform the main query to retrieve the objects we want
objDict[m.model] = m.model_class().objects.filter(id__in=idDict[m.model])
objDict[m.model] = objDict[m.model].select_related('author').prefetch_related('tags').order_by('-{}'.format(orderby))
objDict[m.model] = list(objDict[m.model])
# -- combine and sort all objects by date
objects = _sortObjects(orderby, **objDict) if len(models) > 1 else objDict.values()[0]
objects = objects[:length]
# -- Find out last ids
lastids = {}
for obj in objects:
lastids['last_{}'.format(modelmap[obj.__class__])] = obj.id
for key, value in lastids.items():
request.session[key] = value
# -- serialize objects
for i in objects:
res.append(i.json())
data['count'] = len(objects)
if settings.DEBUG:
data['queries'] = connection.queries
res.value = data
return JsonResponse(res.asDict())
|
https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L219-L331
|
filter array
|
python
|
def parse_column_filter(definition):
"""Parse a `str` of the form 'column>50'
Parameters
----------
definition : `str`
a column filter definition of the form ``<name><operator><threshold>``
or ``<threshold><operator><name><operator><threshold>``, e.g.
``frequency >= 10``, or ``50 < snr < 100``
Returns
-------
filters : `list` of `tuple`
a `list` of filter 3-`tuple`s, where each `tuple` contains the
following elements:
- ``column`` (`str`) - the name of the column on which to operate
- ``operator`` (`callable`) - the operator to call when evaluating
the filter
- ``operand`` (`anything`) - the argument to the operator function
Raises
------
ValueError
if the filter definition cannot be parsed
KeyError
if any parsed operator string cannnot be mapped to a function from
the `operator` module
Notes
-----
Strings that contain non-alphanumeric characters (e.g. hyphen `-`) should
be quoted inside the filter definition, to prevent such characters
being interpreted as operators, e.g. ``channel = X1:TEST`` should always
be passed as ``channel = "X1:TEST"``.
Examples
--------
>>> parse_column_filter("frequency>10")
[('frequency', <function operator.gt>, 10.)]
>>> parse_column_filter("50 < snr < 100")
[('snr', <function operator.gt>, 50.), ('snr', <function operator.lt>, 100.)]
>>> parse_column_filter("channel = "H1:TEST")
[('channel', <function operator.eq>, 'H1:TEST')]
""" # noqa
# parse definition into parts (skipping null tokens)
parts = list(generate_tokens(StringIO(definition.strip()).readline))
while parts[-1][0] in (token.ENDMARKER, token.NEWLINE):
parts = parts[:-1]
# parse simple definition: e.g: snr > 5
if len(parts) == 3:
a, b, c = parts # pylint: disable=invalid-name
if a[0] in [token.NAME, token.STRING]: # string comparison
name = QUOTE_REGEX.sub('', a[1])
oprtr = OPERATORS[b[1]]
value = _float_or_str(c[1])
return [(name, oprtr, value)]
elif b[0] in [token.NAME, token.STRING]:
name = QUOTE_REGEX.sub('', b[1])
oprtr = OPERATORS_INV[b[1]]
value = _float_or_str(a[1])
return [(name, oprtr, value)]
# parse between definition: e.g: 5 < snr < 10
elif len(parts) == 5:
a, b, c, d, e = list(zip(*parts))[1] # pylint: disable=invalid-name
name = QUOTE_REGEX.sub('', c)
return [(name, OPERATORS_INV[b], _float_or_str(a)),
(name, OPERATORS[d], _float_or_str(e))]
raise ValueError("Cannot parse filter definition from %r" % definition)
|
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/filter.py#L99-L171
|
filter array
|
python
|
def min_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
"""
minimum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling (only if data is ndarray)
Returns
-------
filtered image or None (if OCLArray)
"""
if data.ndim == 2:
_filt = make_filter(_generic_filter_gpu_2d(FUNC="(val<res?val:res)", DEFAULT="INFINITY"))
elif data.ndim == 3:
_filt = make_filter(_generic_filter_gpu_3d(FUNC="(val<res?val:res)", DEFAULT="INFINITY"))
else:
raise ValueError("currently only 2 or 3 dimensional data is supported")
return _filt(data=data, size=size, res_g=res_g, sub_blocks=sub_blocks)
|
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L142-L167
|
filter array
|
python
|
def filter(self, *args):
"""
为文本 ``(text)`` 消息添加 handler 的简便方法。
使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))``
或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。
"""
def wraps(f):
self.add_filter(func=f, rules=list(args))
return f
return wraps
|
https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L486-L498
|
filter array
|
python
|
async def filter(self, request):
"""Filter collection."""
collection = self.collection
self.filter_form.process(request.query)
data = self.filter_form.data
self.filter_form.active = any(o and o is not DEFAULT for o in data.values())
for flt in self.columns_filters:
try:
collection = flt.apply(collection, data)
# Invalid filter value
except ValueError:
continue
return collection
|
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/handler.py#L138-L150
|
filter array
|
python
|
def filter(self, table, column_slice=None):
"""
Use the current Query object to create a mask (a boolean array)
for `table`.
Parameters
----------
table : NumPy structured array, astropy Table, etc.
column_slice : Column to return. Default is None (return all columns).
Returns
-------
table : filtered table
"""
if self._operator is None and self._operands is None:
return table if column_slice is None else self._get_table_column(table, column_slice)
if self._operator == 'AND' and column_slice is None:
for op in self._operands:
table = op.filter(table)
return table
return self._mask_table(
table if column_slice is None else self._get_table_column(table, column_slice),
self.mask(table)
)
|
https://github.com/yymao/easyquery/blob/cd94c100e26f59042cd9ffb26d0a7b61cdcd457d/easyquery.py#L237-L262
|
filter array
|
python
|
def filters(self):
"""
Returns the list of base filters.
:return: the filter list
:rtype: list
"""
objects = javabridge.get_env().get_object_array_elements(
javabridge.call(self.jobject, "getFilters", "()[Lweka/filters/Filter;"))
result = []
for obj in objects:
result.append(Filter(jobject=obj))
return result
|
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/filters.py#L201-L213
|
filter array
|
python
|
def filter(self, *filters, **kw):
"""
Return a new S instance with filter args combined with
existing set with AND.
:arg filters: this will be instances of F
:arg kw: this will be in the form of ``field__action=value``
Examples:
>>> s = S().filter(foo='bar')
>>> s = S().filter(F(foo='bar'))
>>> s = S().filter(foo='bar', bat='baz')
>>> s = S().filter(foo='bar').filter(bat='baz')
By default, everything is combined using AND. If you provide
multiple filters in a single filter call, those are ANDed
together. If you provide multiple filters in multiple filter
calls, those are ANDed together.
If you want something different, use the F class which supports
``&`` (and), ``|`` (or) and ``~`` (not) operators. Then call
filter once with the resulting F instance.
See the documentation on :py:class:`elasticutils.F` for more
details on composing filters with F.
See the documentation on :py:class:`elasticutils.S` for more
details on adding support for new filter types.
"""
items = kw.items()
if six.PY3:
items = list(items)
return self._clone(
next_step=('filter', list(filters) + items))
|
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L782-L817
|
filter array
|
python
|
def _filter_attrs(cls, attrs):
"""
attrs: { attr_name: attr_value }
if __attr_whitelist__ is True:
only attr in __attr_accessible__ AND not in __attr_protected__
will pass
else:
only attr not in __attr_protected__ OR in __attr_accessible__
will pass
"""
if cls.__attr_whitelist__:
whitelist = cls.__attr_accessible__ - cls.__attr_protected__
return {k: v for k, v in attrs.items() if k in whitelist}
else:
blacklist = cls.__attr_protected__ - cls.__attr_accessible__
return {k: v for k, v in attrs.items() if k not in blacklist}
|
https://github.com/shanbay/peeweext/blob/ff62a3d01e4584d50fde1944b9616c3b4236ecf0/peeweext/model.py#L62-L77
|
filter array
|
python
|
def filter(self, func):
"""
A lazy way to skip elements in the stream that gives False for the given
function.
"""
self._data = xfilter(func, self._data)
return self
|
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L388-L394
|
filter array
|
python
|
def filter(self, func):
""" Return all the elements that pass a truth test.
"""
return self._wrap(list(filter(func, self.obj)))
|
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L245-L248
|
filter array
|
python
|
def filter(table, predicates):
"""
Select rows from table based on boolean expressions
Parameters
----------
predicates : boolean array expressions, or list thereof
Returns
-------
filtered_expr : TableExpr
"""
resolved_predicates = _resolve_predicates(table, predicates)
return _L.apply_filter(table, resolved_predicates)
|
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L3130-L3143
|
filter array
|
python
|
def parse_filter(self, filters):
""" This method process the filters """
for filter_type in filters:
if filter_type == 'or' or filter_type == 'and':
conditions = []
for field in filters[filter_type]:
if self.is_field_allowed(field):
conditions.append(self.create_query(self.parse_field(field, filters[filter_type][field])))
if filter_type == 'or':
self.model_query = self.model_query.filter(or_(*conditions))
elif filter_type == 'and':
self.model_query = self.model_query.filter(and_(*conditions))
else:
if self.is_field_allowed(filter_type):
conditions = self.create_query(self.parse_field(filter_type, filters[filter_type]))
self.model_query = self.model_query.filter(conditions)
return self.model_query
|
https://github.com/loverajoel/sqlalchemy-elasticquery/blob/4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c/sqlalchemy_elasticquery/elastic_query.py#L95-L111
|
filter array
|
python
|
def _filter(self, value):
"""
Predicate used to exclude, False, or include, True, a computed value.
"""
if self.ignores and value in self.ignores:
return False
return True
|
https://github.com/bninja/pilo/blob/32b7298a47e33fb7383103017b4f3b59ad76ea6f/pilo/fields.py#L473-L479
|
filter array
|
python
|
def filter(self, given_filter, apply_zerovalue=False):
"""Apply filter into all values
Params
<lambda> | <function> given_filter
<bool> only_nonzero
"""
get_ = self.get___method
set_ = self.set___method
max_value = self.max_value
for table_id in range(self.depth):
for cell_id in range(self.width):
val = get_(self, table_id, cell_id)
if val or apply_zerovalue:
val = given_filter(val)
val = max_value if val > max_value else val
set_(self, table_id, cell_id, val)
|
https://github.com/ikegami-yukino/madoka-python/blob/a9a1efecbc85ac4a24a78cbb19f9aed77b7162d3/madoka/madoka.py#L469-L484
|
filter array
|
python
|
def filter(self, func):
"""
:param func:
:type func: (K, T) -> bool
:rtype: TList[T]
Usage:
>>> TDict(k1=1, k2=2, k3=3).filter(lambda k, v: v < 2)
[1]
"""
return TList([v for k, v in self.items() if func(k, v)])
|
https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/owlcollections.py#L464-L475
|
filter array
|
python
|
def filter(self, f: Callable[[A], B]) -> 'List[T]':
"""doufo.List.filter: filter this `List` obj with input `f` function
Args:
`self`:
f (`Callable[[A],B]`): function that tells `True` or `False`
Returns:
return (`List[T]`): Filtered List
Raises:
"""
return List([x for x in self.unbox() if f(x) is True])
|
https://github.com/tech-pi/doufo/blob/3d375fef30670597768a6eef809b75b4b1b5a3fd/src/python/doufo/list.py#L111-L120
|
filter array
|
python
|
def make_filter(self, fieldname, query_func, expct_value):
''' makes a filter that will be appliead to an object's property based
on query_func '''
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
return False
if query_func == 'eq':
return value == expct_value
elif query_func == 'ne':
return value != expct_value
elif query_func == 'lt':
return value < expct_value
elif query_func == 'lte':
return value <= expct_value
elif query_func == 'gt':
return value > expct_value
elif query_func == 'gte':
return value >= expct_value
elif query_func == 'startswith':
return value.startswith(expct_value)
elif query_func == 'endswith':
return value.endswith(expct_value)
actual_filter.__doc__ = '{} {} {}'.format('val', query_func, expct_value)
return actual_filter
|
https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/queryset.py#L35-L64
|
filter array
|
python
|
def set_filter(self, names=None):
"""
Set the names of columns to be used when iterating through the list,
retrieving names, etc.
:param list names: A list of names to be used, or :code:`None` for all
"""
_names = []
if names:
for name in names:
_safe_name = safe_name(name)
if _safe_name not in self._column_map:
raise GiraffeTypeError("Column '{}' does not exist".format(name))
if _safe_name in _names:
continue
_names.append(_safe_name)
self._filtered_columns = _names
|
https://github.com/capitalone/giraffez/blob/6b4d27eb1a1eaf188c6885c7364ef27e92b1b957/giraffez/types.py#L233-L249
|
filter array
|
python
|
def filter(self, data, collection, **kwargs):
"""Filter given collection."""
if not data or self.filters is None:
return None, collection
filters = {}
for f in self.filters:
if f.name not in data:
continue
ops, collection = f.filter(collection, data, **kwargs)
filters[f.name] = ops
return filters, collection
|
https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/filters.py#L96-L108
|
filter array
|
python
|
def _gauss_filter(data, sigma=4, res_g=None, sub_blocks=(1, 1, 1)):
"""
gaussian filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling (only if data is ndarray)
Returns
-------
filtered image or None (if OCLArray)
"""
truncate = 4.
radius = tuple(int(truncate*s +0.5) for s in sigma)
size = tuple(2*r+1 for r in radius)
s = sigma[0]
if data.ndim == 2:
_filt = make_filter(_generic_filter_gpu_2d(FUNC="res+(val*native_exp((float)(-(ht-%s)*(ht-%s)/2/%s/%s)))"%(size[0]//2,size[0]//2,s,s), DEFAULT="0.f"))
elif data.ndim == 3:
_filt = make_filter(_generic_filter_gpu_3d(FUNC="res+(val*native_exp((float)(-(ht-%s)*(ht-%s)/2/%s/%s)))"%(size[0]//2,size[0]//2,s,s), DEFAULT="0.f"))
else:
raise ValueError("currently only 2 or 3 dimensional data is supported")
return _filt(data=data, size=size, res_g=res_g, sub_blocks=sub_blocks)
|
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L216-L248
|
filter array
|
python
|
def get_array(array, **kw):
"""
Extract a subarray by filtering on the given keyword arguments
"""
for name, value in kw.items():
array = array[array[name] == value]
return array
|
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L890-L896
|
filter array
|
python
|
def _filter_matrix_rows(cls, matrix):
'''matrix = output from _to_matrix'''
indexes_to_keep = []
for i in range(len(matrix)):
keep_row = False
for element in matrix[i]:
if element not in {'NA', 'no'}:
keep_row = True
break
if keep_row:
indexes_to_keep.append(i)
return [matrix[i] for i in indexes_to_keep]
|
https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/summary.py#L223-L236
|
filter array
|
python
|
def random_filter(objects, reduction_factor, seed=42):
"""
Given a list of objects, returns a sublist by extracting randomly
some elements. The reduction factor (< 1) tells how small is the extracted
list compared to the original list.
"""
assert 0 < reduction_factor <= 1, reduction_factor
rnd = random.Random(seed)
out = []
for obj in objects:
if rnd.random() <= reduction_factor:
out.append(obj)
return out
|
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L973-L985
|
filter array
|
python
|
def filter_by_rows(self, rows, ID=None):
"""
Keep only Measurements in corresponding rows.
"""
rows = to_list(rows)
fil = lambda x: x in rows
applyto = {k: self._positions[k][0] for k in self.keys()}
if ID is None:
ID = self.ID
return self.filter(fil, applyto=applyto, ID=ID)
|
https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/bases.py#L668-L677
|
filter array
|
python
|
def lowpass_filter(data, cutoff, fs, order=5):
"""
Does a lowpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param cutoff: The high cutoff in Hz.
:param fs: The sample rate in Hz of the data.
:param order: The order of the filter. The higher the order, the tighter the roll-off.
:returns: Filtered data (numpy array).
"""
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = signal.butter(order, normal_cutoff, btype='low', analog=False)
y = signal.lfilter(b, a, data)
return y
|
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/algorithms/filters.py#L25-L39
|
filter array
|
python
|
def filter_by(self, **kwargs):
"""
:param kwargs: dict of column == value
:return: SeabornTable
"""
ret = self.__class__(
columns=self.columns, row_columns=self.row_columns, tab=self.tab,
key_on=self.key_on)
for row in self:
if False not in [row[k] == v for k, v in kwargs.items()]:
ret.append(row)
return ret
|
https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L997-L1008
|
filter array
|
python
|
def filter_formatter(kwargs, attr_map):
"""Builds a filter according to the cross-api specification
:param kwargs: expected to contain {'filter': {filter dict}}
:returns: {validated filter dict}
"""
params = _depluralise_filters_key(copy.copy(kwargs))
params.update(_get_filter(sdk_filter=params.pop('filter', {}), attr_map=attr_map))
return params
|
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/filters.py#L128-L136
|
filter array
|
python
|
def check_filters(filters):
"""
Execute range_check for every element of an iterable.
Parameters
----------
filters : iterable
The collection of filters to check. Each element
must be a two-element tuple of floats or ints.
Returns
-------
The input as-is, or None if it evaluates to False.
Raises
------
ValueError
Low is greater than or equal to high for any element.
"""
if not filters:
return None
try:
return [range_check(f[0], f[1]) for f in filters]
except ValueError as err:
raise ValueError("Error in --filter: " + py23_str(err))
|
https://github.com/SethMMorton/natsort/blob/ea0d37ef790b42c424a096e079edd9ea0d5717e3/natsort/__main__.py#L169-L194
|
filter array
|
python
|
def from_filter(cls, filtername, **kwargs):
"""Load :ref:`pre-defined filter bandpass <synphot-predefined-filter>`.
Parameters
----------
filtername : str
Filter name. Choose from 'bessel_j', 'bessel_h', 'bessel_k',
'cousins_r', 'cousins_i', 'johnson_u', 'johnson_b', 'johnson_v',
'johnson_r', 'johnson_i', 'johnson_j', or 'johnson_k'.
kwargs : dict
Keywords acceptable by :func:`~synphot.specio.read_remote_spec`.
Returns
-------
bp : `SpectralElement`
Empirical bandpass.
Raises
------
synphot.exceptions.SynphotError
Invalid filter name.
"""
filtername = filtername.lower()
# Select filename based on filter name
if filtername == 'bessel_j':
cfgitem = Conf.bessel_j_file
elif filtername == 'bessel_h':
cfgitem = Conf.bessel_h_file
elif filtername == 'bessel_k':
cfgitem = Conf.bessel_k_file
elif filtername == 'cousins_r':
cfgitem = Conf.cousins_r_file
elif filtername == 'cousins_i':
cfgitem = Conf.cousins_i_file
elif filtername == 'johnson_u':
cfgitem = Conf.johnson_u_file
elif filtername == 'johnson_b':
cfgitem = Conf.johnson_b_file
elif filtername == 'johnson_v':
cfgitem = Conf.johnson_v_file
elif filtername == 'johnson_r':
cfgitem = Conf.johnson_r_file
elif filtername == 'johnson_i':
cfgitem = Conf.johnson_i_file
elif filtername == 'johnson_j':
cfgitem = Conf.johnson_j_file
elif filtername == 'johnson_k':
cfgitem = Conf.johnson_k_file
else:
raise exceptions.SynphotError(
'Filter name {0} is invalid.'.format(filtername))
filename = cfgitem()
if 'flux_unit' not in kwargs:
kwargs['flux_unit'] = cls._internal_flux_unit
if ((filename.endswith('fits') or filename.endswith('fit')) and
'flux_col' not in kwargs):
kwargs['flux_col'] = 'THROUGHPUT'
header, wavelengths, throughput = specio.read_remote_spec(
filename, **kwargs)
header['filename'] = filename
header['descrip'] = cfgitem.description
meta = {'header': header, 'expr': filtername}
return cls(Empirical1D, points=wavelengths, lookup_table=throughput,
meta=meta)
|
https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/spectrum.py#L1839-L1909
|
filter array
|
python
|
def bandpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
lower_freq_hz: float,
upper_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a band-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
lower_freq_hz: filter cutoff lower frequency in Hz
(or other consistent units)
upper_freq_hz: filter cutoff upper frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1
"""
f1 = normalized_frequency(lower_freq_hz, sampling_freq_hz)
f2 = normalized_frequency(upper_freq_hz, sampling_freq_hz)
coeffs = firwin(
numtaps=numtaps,
cutoff=[f1, f2],
pass_zero=False
)
filtered_data = lfilter(b=coeffs, a=1.0, x=data)
return filtered_data
|
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dsp.py#L129-L160
|
filter array
|
python
|
def bandpass_filter(rate=None, low=None, high=None, order=None):
"""Butterworth bandpass filter."""
assert low < high
assert order >= 1
return signal.butter(order,
(low / (rate / 2.), high / (rate / 2.)),
'pass')
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/traces/filter.py#L19-L25
|
filter array
|
python
|
def _filter(self, query, **kwargs):
"""
Filter a query with user-supplied arguments.
"""
query = self._auto_filter(query, **kwargs)
return query
|
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L211-L217
|
filter array
|
python
|
def _build_filter_list(self, filters):
"""
:returns: Iterator building a list of filter
"""
i = 0
for (filter_type, values) in filters.items():
if isinstance(values[0], str):
for line in values[0].split('\n'):
line = line.strip()
yield "{filter_name} {filter_type} {filter_value}".format(
filter_name="filter" + str(i),
filter_type=filter_type,
filter_value='"{}" {}'.format(line, " ".join([str(v) for v in values[1:]]))).strip()
i += 1
else:
yield "{filter_name} {filter_type} {filter_value}".format(
filter_name="filter" + str(i),
filter_type=filter_type,
filter_value=" ".join([str(v) for v in values]))
i += 1
|
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L621-L640
|
filter array
|
python
|
def filter_off(self, filt=None, analyte=None, samples=None, subset=None, show_status=False):
"""
Turns data filters off for particular analytes and samples.
Parameters
----------
filt : optional, str or array_like
Name, partial name or list of names of filters. Supports
partial matching. i.e. if 'cluster' is specified, all
filters with 'cluster' in the name are activated.
Defaults to all filters.
analyte : optional, str or array_like
Name or list of names of analytes. Defaults to all analytes.
samples : optional, array_like or None
Which samples to apply this filter to. If None, applies to all
samples.
Returns
-------
None
"""
if samples is not None:
subset = self.make_subset(samples)
samples = self._get_samples(subset)
for s in samples:
try:
self.data[s].filt.off(analyte, filt)
except:
warnings.warn("filt.off failure in sample " + s)
if show_status:
self.filter_status(subset=subset)
return
|
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/latools.py#L2389-L2423
|
filter array
|
python
|
def filter_by_cols(self, cols, ID=None):
"""
Keep only Measurements in corresponding columns.
"""
rows = to_list(cols)
fil = lambda x: x in rows
applyto = {k: self._positions[k][1] for k in self.keys()}
if ID is None:
ID = self.ID + '.filtered_by_cols'
return self.filter(fil, applyto=applyto, ID=ID)
|
https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/bases.py#L679-L688
|
filter array
|
python
|
def filter(func, data):
"""Parameter <func> must be a single-argument
function that takes a sequence (i.e.,
a sample point) and returns a boolean. This procedure calls <func> on
each element in <data> and returns a list comprising elements for
which <func> returns True.
>>> data = [[1,5], [2,10], [3,13], [4,16]]
... chart_data.filter(lambda x: x[1] % 2 == 0, data)
[[2,10], [4,16]].
"""
out = []
for r in data:
if func(r):
out.append(r)
return out
|
https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Plugins/local_pychart/chart_data.py#L159-L175
|
filter array
|
python
|
def get_filter_list(p_expression):
"""
Returns a list of GrepFilters, OrdinalTagFilters or NegationFilters based
on the given filter expression.
The filter expression is a list of strings.
"""
result = []
for arg in p_expression:
# when a word starts with -, it should be negated
is_negated = len(arg) > 1 and arg[0] == '-'
arg = arg[1:] if is_negated else arg
argfilter = None
for match, _filter in MATCHES:
if re.match(match, arg):
argfilter = _filter(arg)
break
if not argfilter:
argfilter = GrepFilter(arg)
if is_negated:
argfilter = NegationFilter(argfilter)
result.append(argfilter)
return result
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L377-L404
|
filter array
|
python
|
def list_filter(lst, startswith=None, notstartswith=None,
contain=None, notcontain=None):
""" Keep in list items according to filter parameters.
:param lst: item list
:param startswith: keep items starting with
:param notstartswith: remove items starting with
:return:
"""
keeped = []
for item in lst:
keep = False
if startswith is not None:
if item.startswith(startswith):
keep = True
if notstartswith is not None:
if not item.startswith(notstartswith):
keep = True
if contain is not None:
if contain in item:
keep = True
if notcontain is not None:
if not notcontain in item:
keep = True
if keep:
keeped.append(item)
return keeped
|
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L41-L68
|
filter array
|
python
|
def make_filter(**tests):
"""Create a filter from keyword arguments."""
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests)
|
https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/utils.py#L116-L119
|
filter array
|
python
|
async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
raise FilterNotPassed()
elif isinstance(f, dict):
data.update(f)
return data
|
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L61-L77
|
filter array
|
python
|
def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
"""
maximum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling (only if data is ndarray)
Returns
-------
filtered image or None (if OCLArray)
"""
if data.ndim == 2:
_filt = make_filter(_generic_filter_gpu_2d(FUNC = "(val>res?val:res)", DEFAULT = "-INFINITY"))
elif data.ndim == 3:
_filt = make_filter(_generic_filter_gpu_3d(FUNC = "(val>res?val:res)", DEFAULT = "-INFINITY"))
return _filt(data = data, size = size, res_g = res_g, sub_blocks=sub_blocks)
|
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L115-L139
|
filter array
|
python
|
def filter(self, *args):
'''Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
'''
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return self
|
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L384-L403
|
filter array
|
python
|
def _filter_fields(self, filter_function):
"""
Utility to iterate through all fields (super types first) of a type.
:param filter: A function that takes in a Field object. If it returns
True, the field is part of the generated output. If False, it is
omitted.
"""
fields = []
if self.parent_type:
fields.extend(self.parent_type._filter_fields(filter_function))
fields.extend(filter(filter_function, self.fields))
return fields
|
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/ir/data_types.py#L956-L968
|
filter array
|
python
|
def where(self, attrs=None, first=False):
"""
Convenience version of a common use case of `filter`:
selecting only objects
containing specific `key:value` pairs.
"""
if attrs is None:
return None if first is True else []
method = _.find if first else _.filter
def by(val, *args):
for key, value in attrs.items():
try:
if attrs[key] != val[key]:
return False
except KeyError:
return False
return True
return self._wrap(method(self.obj, by))
|
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L321-L341
|
filter array
|
python
|
def __undo_filter_paeth(self, scanline):
"""Undo Paeth filter."""
ai = -self.fu
previous = self.prev
for i in range(len(scanline)):
x = scanline[i]
if ai < 0:
pr = previous[i] # a = c = 0
else:
a = scanline[ai] # result
c = previous[ai]
b = previous[i]
pa = abs(b - c) # b
pb = abs(a - c) # 0
pc = abs(a + b - c - c) # b
if pa <= pb and pa <= pc: # False
pr = a
elif pb <= pc: # True
pr = b
else:
pr = c
scanline[i] = (x + pr) & 0xff # result
ai += 1
|
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L582-L604
|
filter array
|
python
|
def filter_table(table, *column_filters):
"""Apply one or more column slice filters to a `Table`
Multiple column filters can be given, and will be applied
concurrently
Parameters
----------
table : `~astropy.table.Table`
the table to filter
column_filter : `str`, `tuple`
a column slice filter definition, in one of two formats:
- `str` - e.g. ``'snr > 10``
- `tuple` - ``(<column>, <operator>, <operand>)``, e.g.
``('snr', operator.gt, 10)``
multiple filters can be given and will be applied in order
Returns
-------
table : `~astropy.table.Table`
a view of the input table with only those rows matching the filters
Examples
--------
>>> filter(my_table, 'snr>10', 'frequency<1000')
custom operations can be defined using filter tuple definitions:
>>> from gwpy.table.filters import in_segmentlist
>>> filter(my_table, ('time', in_segmentlist, segs))
"""
keep = numpy.ones(len(table), dtype=bool)
for name, op_func, operand in parse_column_filters(*column_filters):
col = table[name].view(numpy.ndarray)
keep &= op_func(col, operand)
return table[keep]
|
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/filter.py#L218-L256
|
filter array
|
python
|
def filter_matrix_rows(A, theta):
"""Filter each row of A with tol.
i.e., drop all entries in row k where
abs(A[i,k]) < tol max( abs(A[:,k]) )
Parameters
----------
A : sparse_matrix
theta : float
In range [0,1) and defines drop-tolerance used to filter the row of A
Returns
-------
A_filter : sparse_matrix
Each row has been filtered by dropping all entries where
abs(A[i,k]) < tol max( abs(A[:,k]) )
Examples
--------
>>> from pyamg.gallery import poisson
>>> from pyamg.util.utils import filter_matrix_rows
>>> from scipy import array
>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix( array([[ 0.24, -0.5 , 0. , 0. ],
... [ 1. , 1. , 0.49, 0. ],
... [ 0. , -0.5 , 1. , -0.5 ]]) )
>>> filter_matrix_rows(A, 0.5).todense()
matrix([[ 0. , -0.5, 0. , 0. ],
[ 1. , 1. , 0. , 0. ],
[ 0. , -0.5, 1. , -0.5]])
"""
if not isspmatrix(A):
raise ValueError("Sparse matrix input needed")
if isspmatrix_bsr(A):
blocksize = A.blocksize
Aformat = A.format
A = A.tocsr()
if (theta < 0) or (theta >= 1.0):
raise ValueError("theta must be in [0,1)")
# Apply drop-tolerance to each row of A. We apply the drop-tolerance with
# amg_core.classical_strength_of_connection(), which ignores diagonal
# entries, thus necessitating the trick where we add A.shape[0] to each of
# the row indices
A_filter = A.copy()
A.indices += A.shape[0]
A_filter.indices += A.shape[0]
# classical_strength_of_connection takes an absolute value internally
pyamg.amg_core.classical_strength_of_connection_abs(
A.shape[0],
theta,
A.indptr,
A.indices,
A.data,
A_filter.indptr,
A_filter.indices,
A_filter.data)
A_filter.indices[:A_filter.indptr[-1]] -= A_filter.shape[0]
A_filter = csr_matrix((A_filter.data[:A_filter.indptr[-1]],
A_filter.indices[:A_filter.indptr[-1]],
A_filter.indptr), shape=A_filter.shape)
if Aformat == 'bsr':
A_filter = A_filter.tobsr(blocksize)
else:
A_filter = A_filter.asformat(Aformat)
A.indices -= A.shape[0]
return A_filter
|
https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/util/utils.py#L2070-L2142
|
filter array
|
python
|
def _build_filter_part(self, cls, filters, order_by=None, select=None):
"""
Build the filter part
"""
import types
query_parts = []
order_by_filtered = False
if order_by:
if order_by[0] == "-":
order_by_method = "DESC";
order_by = order_by[1:]
else:
order_by_method = "ASC";
if select:
if order_by and order_by in select:
order_by_filtered = True
query_parts.append("(%s)" % select)
if isinstance(filters, str) or isinstance(filters, unicode):
query = "WHERE %s AND `__type__` = '%s'" % (filters, cls.__name__)
if order_by in ["__id__", "itemName()"]:
query += " ORDER BY itemName() %s" % order_by_method
elif order_by != None:
query += " ORDER BY `%s` %s" % (order_by, order_by_method)
return query
for filter in filters:
filter_parts = []
filter_props = filter[0]
if type(filter_props) != list:
filter_props = [filter_props]
for filter_prop in filter_props:
(name, op) = filter_prop.strip().split(" ", 1)
value = filter[1]
property = cls.find_property(name)
if name == order_by:
order_by_filtered = True
if types.TypeType(value) == types.ListType:
filter_parts_sub = []
for val in value:
val = self.encode_value(property, val)
if isinstance(val, list):
for v in val:
filter_parts_sub.append(self._build_filter(property, name, op, v))
else:
filter_parts_sub.append(self._build_filter(property, name, op, val))
filter_parts.append("(%s)" % (" OR ".join(filter_parts_sub)))
else:
val = self.encode_value(property, value)
if isinstance(val, list):
for v in val:
filter_parts.append(self._build_filter(property, name, op, v))
else:
filter_parts.append(self._build_filter(property, name, op, val))
query_parts.append("(%s)" % (" or ".join(filter_parts)))
type_query = "(`__type__` = '%s'" % cls.__name__
for subclass in self._get_all_decendents(cls).keys():
type_query += " or `__type__` = '%s'" % subclass
type_query +=")"
query_parts.append(type_query)
order_by_query = ""
if order_by:
if not order_by_filtered:
query_parts.append("`%s` LIKE '%%'" % order_by)
if order_by in ["__id__", "itemName()"]:
order_by_query = " ORDER BY itemName() %s" % order_by_method
else:
order_by_query = " ORDER BY `%s` %s" % (order_by, order_by_method)
if len(query_parts) > 0:
return "WHERE %s %s" % (" AND ".join(query_parts), order_by_query)
else:
return ""
|
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sdb/db/manager/sdbmanager.py#L538-L617
|
filter array
|
python
|
def sfilter(self, source):
"""Filter."""
return self._filter(source.text, source.context, source.encoding)
|
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L250-L253
|
filter array
|
python
|
def class_filter(classes, class_name):
"""
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list
"""
result_classes = classes
if isinstance(class_name, list):
if set(class_name) <= set(classes):
result_classes = class_name
return result_classes
|
https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L59-L73
|
filter array
|
python
|
def parse_filters(self, vt_filter):
""" Parse a string containing one or more filters
and return a list of filters
Arguments:
vt_filter (string): String containing filters separated with
semicolon.
Return:
List with filters. Each filters is a list with 3 elements
e.g. [arg, operator, value]
"""
filter_list = vt_filter.split(';')
filters = list()
for single_filter in filter_list:
filter_aux = re.split('(\W)', single_filter, 1)
if len(filter_aux) < 3:
raise OSPDError("Invalid number of argument in the filter", "get_vts")
_element, _oper, _val = filter_aux
if _element not in self.allowed_filter:
raise OSPDError("Invalid filter element", "get_vts")
if _oper not in self.filter_operator:
raise OSPDError("Invalid filter operator", "get_vts")
filters.append(filter_aux)
return filters
|
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L41-L67
|
filter array
|
python
|
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()):
"""Read the repository and return results as per the filer"""
if criteria.children:
items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values())
else:
items = list(self.conn['data'][self.schema_name].values())
# Sort the filtered results based on the order_by clause
for o_key in order_by:
reverse = False
if o_key.startswith('-'):
reverse = True
o_key = o_key[1:]
items = sorted(items, key=itemgetter(o_key), reverse=reverse)
result = ResultSet(
offset=offset,
limit=limit,
total=len(items),
items=items[offset: offset + limit])
return result
|
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L190-L211
|
filter array
|
python
|
def check_array(array, *args, **kwargs):
"""Validate inputs
Parameters
----------
accept_dask_array : bool, default True
accept_dask_dataframe : bool, default False
accept_unknown_chunks : bool, default False
For dask Arrays, whether to allow the `.chunks` attribute to contain
any unknown values
accept_multiple_blocks : bool, default False
For dask Arrays, whether to allow multiple blocks along the second
axis.
*args, **kwargs : tuple, dict
Passed through to scikit-learn
Returns
-------
array : obj
Same type as the input
Notes
-----
For dask.array, a small numpy array emulating ``array`` is created
and passed to scikit-learn's ``check_array`` with all the additional
arguments.
"""
accept_dask_array = kwargs.pop("accept_dask_array", True)
preserve_pandas_dataframe = kwargs.pop("preserve_pandas_dataframe", False)
accept_dask_dataframe = kwargs.pop("accept_dask_dataframe", False)
accept_unknown_chunks = kwargs.pop("accept_unknown_chunks", False)
accept_multiple_blocks = kwargs.pop("accept_multiple_blocks", False)
if isinstance(array, da.Array):
if not accept_dask_array:
raise TypeError
if not accept_unknown_chunks:
if np.isnan(array.shape[0]):
raise TypeError(
"Cannot operate on Dask array with unknown chunk sizes."
)
if not accept_multiple_blocks and array.ndim > 1:
if len(array.chunks[1]) > 1:
msg = (
"Chunking is only allowed on the first axis. "
"Use 'array.rechunk({1: array.shape[1]})' to "
"rechunk to a single block along the second axis."
)
raise TypeError(msg)
# hmmm, we want to catch things like shape errors.
# I'd like to make a small sample somehow
shape = array.shape
if len(shape) == 2:
shape = (min(10, shape[0]), shape[1])
elif shape == 1:
shape = min(10, shape[0])
sample = np.ones(shape=shape, dtype=array.dtype)
sk_validation.check_array(sample, *args, **kwargs)
return array
elif isinstance(array, dd.DataFrame):
if not accept_dask_dataframe:
raise TypeError("This estimator does not support dask dataframes.")
# TODO: sample?
return array
elif isinstance(array, pd.DataFrame) and preserve_pandas_dataframe:
# TODO: validation?
return array
else:
return sk_validation.check_array(array, *args, **kwargs)
|
https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/utils.py#L87-L158
|
filter array
|
python
|
def filter_rows(self, filters, rows):
'''returns rows as filtered by filters'''
ret = []
for row in rows:
if not self.row_is_filtered(row, filters):
ret.append(row)
return ret
|
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L165-L171
|
filter array
|
python
|
def _filter(filterObj, **kwargs):
'''
Internal for handling filters; the guts of .filter and .filterInline
'''
for key, value in kwargs.items():
if key.endswith('__ne'):
notFilter = True
key = key[:-4]
else:
notFilter = False
if key not in filterObj.indexedFields:
raise ValueError('Field "' + key + '" is not in INDEXED_FIELDS array. Filtering is only supported on indexed fields.')
if notFilter is False:
filterObj.filters.append( (key, value) )
else:
filterObj.notFilters.append( (key, value) )
return filterObj
|
https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1443-L1461
|
filter array
|
python
|
def sfilter(self, source):
"""Filter."""
sources = []
if source.text[:4].encode(source.encoding) != b'PK\x03\x04':
sources.extend(self._filter(source.text, source.context, source.encoding))
else:
for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))):
sources.extend(self._filter(content, source.context, enc))
return sources
|
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L179-L188
|
filter array
|
python
|
def trace_filter(self, from_block: int = 1, to_block: Optional[int] = None,
from_address: Optional[List[str]] = None, to_address: Optional[List[str]] = None,
after: Optional[int] = None, count: Optional[int] = None) -> List[Dict[str, any]]:
"""
:param from_block: Quantity or Tag - (optional) From this block. `0` is not working, it needs to be `>= 1`
:param to_block: Quantity or Tag - (optional) To this block.
:param from_address: Array - (optional) Sent from these addresses.
:param to_address: Address - (optional) Sent to these addresses.
:param after: Quantity - (optional) The offset trace number
:param count: Quantity - (optional) Integer number of traces to display in a batch.
:return:
[
{
"action": {
"callType": "call",
"from": "0x32be343b94f860124dc4fee278fdcbd38c102d88",
"gas": "0x4c40d",
"input": "0x",
"to": "0x8bbb73bcb5d553b5a556358d27625323fd781d37",
"value": "0x3f0650ec47fd240000"
},
"blockHash": "0x86df301bcdd8248d982dbf039f09faf792684e1aeee99d5b58b77d620008b80f",
"blockNumber": 3068183,
"result": {
"gasUsed": "0x0",
"output": "0x"
},
"subtraces": 0,
"traceAddress": [],
"transactionHash": "0x3321a7708b1083130bd78da0d62ead9f6683033231617c9d268e2c7e3fa6c104",
"transactionPosition": 3,
"type": "call"
},
{
"action": {
"from": "0x3b169a0fb55ea0b6bafe54c272b1fe4983742bf7",
"gas": "0x49b0b",
"init": "0x608060405234801561001057600080fd5b5060405161060a38038061060a833981018060405281019080805190602001909291908051820192919060200180519060200190929190805190602001909291908051906020019092919050505084848160008173ffffffffffffffffffffffffffffffffffffffff1614151515610116576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001807f496e76616c6964206d617374657220636f707920616464726573732070726f7681526020017f696465640000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550506000815111156101a35773ffffffffffffffffffffffffffffffffffffffff60005416600080835160208501846127105a03f46040513d6000823e600082141561019f573d81fd5b5050505b5050600081111561036d57600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156102b7578273ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f1935050505015156102b2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001807f436f756c64206e6f74207061792073616665206372656174696f6e207769746881526020017f206574686572000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b61036c565b6102d1828483610377640100000000026401000000009004565b151561036b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001807f436f756c64206e6f74207061792073616665206372656174696f6e207769746881526020017f20746f6b656e000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b5b5b5050505050610490565b600060608383604051602401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828152602001925050506040516020818303038152906040527fa9059cbb000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505090506000808251602084016000896127105a03f16040513d6000823e3d60008114610473576020811461047b5760009450610485565b829450610485565b8151158315171594505b505050509392505050565b61016b8061049f6000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634555d5c91461008b5780635c60da1b146100b6575b73ffffffffffffffffffffffffffffffffffffffff600054163660008037600080366000845af43d6000803e6000811415610086573d6000fd5b3d6000f35b34801561009757600080fd5b506100a061010d565b6040518082815260200191505060405180910390f35b3480156100c257600080fd5b506100cb610116565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b60006002905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050905600a165627a7a7230582007fffd557dfc8c4d2fdf56ba6381a6ce5b65b6260e1492d87f26c6d4f1d0410800290000000000000000000000008942595a2dc5181df0465af0d7be08c8f23c93af00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000d9e09beaeb338d81a7c5688358df0071d498811500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001b15f91a8c35300000000000000000000000000000000000000000000000000000000000001640ec78d9e00000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000004000000000000000000000000f763ea5fbb191d47dc4b083dcdc3cdfb586468f8000000000000000000000000ad25c9717d04c0a12086a1d352c1ccf4bf5fcbf80000000000000000000000000da7155692446c80a4e7ad72018e586f20fa3bfe000000000000000000000000bce0cc48ce44e0ac9ee38df4d586afbacef191fa0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"value": "0x0"
},
"blockHash": "0x03f9f64dfeb7807b5df608e6957dd4d521fd71685aac5533451d27f0abe03660",
"blockNumber": 3793534,
"result": {
"address": "0x61a7cc907c47c133d5ff5b685407201951fcbd08",
"code": "0x60806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634555d5c91461008b5780635c60da1b146100b6575b73ffffffffffffffffffffffffffffffffffffffff600054163660008037600080366000845af43d6000803e6000811415610086573d6000fd5b3d6000f35b34801561009757600080fd5b506100a061010d565b6040518082815260200191505060405180910390f35b3480156100c257600080fd5b506100cb610116565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b60006002905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050905600a165627a7a7230582007fffd557dfc8c4d2fdf56ba6381a6ce5b65b6260e1492d87f26c6d4f1d041080029",
"gasUsed": "0x4683f"
},
"subtraces": 2,
"traceAddress": [],
"transactionHash": "0x6c7e8f8778d33d81b29c4bd7526ee50a4cea340d69eed6c89ada4e6fab731789",
"transactionPosition": 1,
"type": "create"
},
...
]
"""
assert from_address or to_address, 'You must provide at least `from_address` or `to_address`'
parameters = {}
if from_block:
parameters['fromBlock'] = '0x%x' % from_block
if to_block:
parameters['toBlock'] = '0x%x' % to_block
if from_address:
parameters['fromAddress'] = from_address
if to_address:
parameters['toAddress'] = to_address
if after:
parameters['after'] = after
if count:
parameters['count'] = count
try:
return self._decode_traces(self.slow_w3.parity.traceFilter(parameters))
except ParityTraceDecodeException as exc:
logger.warning('Problem decoding trace: %s - Retrying', exc)
return self._decode_traces(self.slow_w3.parity.traceFilter(parameters))
|
https://github.com/gnosis/gnosis-py/blob/2a9a5d75a375fc9813ac04df133e6910c82f9d49/gnosis/eth/ethereum_client.py#L252-L327
|
filter array
|
python
|
def filter_rows(filters, rows):
"""
Yield rows matching all applicable filters.
Filter functions have binary arity (e.g. `filter(row, col)`) where
the first parameter is the dictionary of row data, and the second
parameter is the data at one particular column.
Args:
filters: a tuple of (cols, filter_func) where filter_func will
be tested (filter_func(row, col)) for each col in cols where
col exists in the row
rows: an iterable of rows to filter
Yields:
Rows matching all applicable filters
.. deprecated:: v0.7.0
"""
for row in rows:
if all(condition(row, row.get(col))
for (cols, condition) in filters
for col in cols
if col is None or col in row):
yield row
|
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1831-L1854
|
filter array
|
python
|
def format_row_filter(self, next_filter):
""" Apply overflow, justification, padding and expansion to a row. """
next(next_filter)
while True:
items = (yield)
assert all(isinstance(x, VTMLBuffer) for x in items)
raw = (fn(x) for x, fn in zip(items, self.formatters))
for x in itertools.zip_longest(*raw):
next_filter.send(x)
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L653-L661
|
filter array
|
python
|
def filter(self, value, table=None):
'''
Return True if the value should be pruned; False otherwise.
If a `table` argument was provided, pass it to filterable_func.
'''
if table is not None:
filterable = self.filterable_func(value, table)
else:
filterable = self.filterable_func(value)
return filterable
|
https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/filters.py#L21-L31
|
filter array
|
python
|
def __do_filter_sub(self, scanline, result):
"""Sub filter."""
ai = 0
for i in range(self.fu, len(result)):
x = scanline[i]
a = scanline[ai]
result[i] = (x - a) & 0xff
ai += 1
|
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L529-L536
|
filter array
|
python
|
def filter(self, func=None):
"""
Return a new Collection with some items removed.
Parameters:
func : function(Node) -> Scalar
A function that, when called on each item
in the collection, returns a boolean-like
value. If no function is provided, then
false-y items will be removed.
Returns:
A new Collection consisting of the items
where bool(func(item)) == True
Examples:
node.find_all('a').filter(Q['href'].startswith('http'))
"""
func = _make_callable(func)
return Collection(filter(func, self._items))
|
https://github.com/ChrisBeaumont/soupy/blob/795f2f61f711f574d5218fc8a3375d02bda1104f/soupy.py#L583-L606
|
filter array
|
python
|
def find_by_filter(self, filters, all_items):
"""
Find items by filters
:param filters: list of filters
:type filters: list
:param all_items: monitoring items
:type: dict
:return: list of items
:rtype: list
"""
items = []
for i in self:
failed = False
if hasattr(i, "host"):
all_items["service"] = i
else:
all_items["host"] = i
for filt in filters:
if not filt(all_items):
failed = True
break
if failed is False:
items.append(i)
return items
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3379-L3403
|
filter array
|
python
|
def _filter_desc(self, indexing):
'''
Private function to filter data, goes with filter_desc
'''
# now filter data
if len(indexing) > 0:
desc_tmp = np.zeros((len(indexing),len(self.header_desc)),dtype='|S1024')
data_tmp = np.zeros((len(indexing),len(self.header_data)))
style_tmp= np.zeros((len(indexing),len(self.header_style)),dtype='|S1024')
for i in range(len(indexing)):
for j in range(len(self.header_desc)):
desc_tmp[i][j] = self.desc[indexing[i]][j]
for k in range(len(self.header_data)):
data_tmp[i][k] = self.data[indexing[i]][k]
for l in range(len(self.header_style)):
style_tmp[i][l]= self.style[indexing[i]][l]
self.desc = desc_tmp
self.data = data_tmp
self.style= style_tmp
else:
print('No filter selected or no data found!')
|
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/grain.py#L372-L394
|
filter array
|
python
|
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L70-L87
|
filter array
|
python
|
def get_filter(self, name=constants.STRING_FILTER):
"""Get the filter on the source.
:param name: The name of the filter. This will be encoded as
an AMQP Symbol. By default this is set to b'apache.org:selector-filter:string'.
:type name: bytes
"""
try:
filter_key = c_uamqp.symbol_value(name)
return self._address.filter_set[filter_key].value
except (TypeError, KeyError):
return None
|
https://github.com/Azure/azure-uamqp-python/blob/b67e4fcaf2e8a337636947523570239c10a58ae2/uamqp/address.py#L176-L187
|
filter array
|
python
|
def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes:
"""
A field could be found for this term, try to get filter string for it.
"""
assert isinstance(name, str)
assert isinstance(value, bytes)
if operation is None:
return filter_format(b"(%s=%s)", [name, value])
elif operation == "contains":
assert value != ""
return filter_format(b"(%s=*%s*)", [name, value])
else:
raise ValueError("Unknown search operation %s" % operation)
|
https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/query.py#L28-L40
|
filter array
|
python
|
def filter_by_user(self, user):
"""All filters that should be displayed to a user (by users/group)"""
return self.filter(Q(users=user) | Q(groups__in=user.groups.all()))
|
https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/models.py#L10-L13
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.