本文整理匯總了Python中operator.contains方法的典型用法代碼示例。如果您正苦於以下問題:Python operator.contains方法的具體用法?Python operator.contains怎麽用?Python operator.contains使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類operator
的用法示例。
在下文中一共展示了operator.contains方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_operator
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
with test_support.check_py3k_warnings():
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
示例2: test_lookup_name_code_by_comparators
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def test_lookup_name_code_by_comparators(self):
for field in ('name', 'code'):
field_values = getattr(SBER, field), getattr(MICEX, field)
field_value = field_values[0]
for comparator, op in zip((LookupComparator.EQUALS,
LookupComparator.CONTAINS,
LookupComparator.STARTSWITH),
(operator.eq,
operator.contains,
startswith_compat)):
actual = self._meta.lookup(**{
field: field_value, field + '_comparator': comparator
})
assert all(op(val, field_value) for val in set(actual[field]))
actual = self._meta.lookup(**{
field: field_values,
field + '_comparator': comparator
})
for actual_value in set(actual[field]):
assert any(op(actual_value, asked_value)
for asked_value in field_values)
示例3: _verify_dq_query_and_execute_include_exclude
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def _verify_dq_query_and_execute_include_exclude(action_output, style, key):
# Validating execute include exclude keys and queries that are following dq formats
# if key is a query of type (contains('status')) then we show the resulted output
# otherwise the key itself usually for execute action
if not key:
key = action_output
message = "'{k}' is {s} in the output"
if style == "included" and action_output:
return (Passed, message.format(k=key, s=style))
elif style =='excluded' and not action_output:
return (Passed, message.format(k=key, s=style))
elif style == "included" and not action_output:
# change the style if it is not included for reporting
return (Failed, message.format(k=key, s= 'not ' + style))
else:
return (Failed, message.format(k=key, s= 'not ' + style))
示例4: _evaluate_operator
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def _evaluate_operator(result, operation=None, value=None):
# used to evaluate the operation results
# if number 6 operations
if isinstance(value, (float, int)) and isinstance(result, (float, int)):
dict_of_ops = {'==': operator.eq, '>=':operator.ge,
'>': operator.gt, '<=':operator.le, '<':operator.le,
'!=':operator.ne}
elif isinstance(result, (float, int)) and isinstance(value, range):
# just check if the first argument is within the second argument,
# changing the operands order of contains function (in)
dict_of_ops = {'within': lambda item, container: item in container}
elif isinstance(result, str) and isinstance(value, str):
# if strings just check equal or not equal or inclusion
dict_of_ops = {'==': operator.eq, '!=':operator.ne, 'in': operator.contains}
else:
# if any other type return error
return False
# if the operation is not valid errors the testcase
if not operation in dict_of_ops.keys():
raise Exception('Operator {} is not supported'.format(operation))
return dict_of_ops[operation](result, value)
示例5: __repr__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def __repr__(self):
"""Provide an universal representation of the matcher."""
# Mapping from operator functions to their symbols in Python.
#
# There is no point in including ``operator.contains`` due to lack of
# equivalent ``operator.in_``.
# These are handled by membership matchers directly.
operator_symbols = {
operator.eq: '==',
operator.ge: '>=',
operator.gt: '>',
operator.le: '<=',
operator.lt: '<',
}
# try to get the symbol for the operator, falling back to Haskell-esque
# "infix function" representation
op = operator_symbols.get(self.OP)
if op is None:
# TODO: convert CamelCase to either snake_case or kebab-case
op = '`%s`' % (self.__class__.__name__.lower(),)
return "<%s %s %r>" % (self._get_placeholder_repr(), op, self.ref)
示例6: test_check_closed
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def test_check_closed(self):
f = dumbdbm.open(_fname, 'c')
f.close()
for meth in (partial(operator.delitem, f),
partial(operator.setitem, f, 'b'),
partial(operator.getitem, f),
partial(operator.contains, f)):
with self.assertRaises(dumbdbm.error) as cm:
meth('test')
self.assertEqual(str(cm.exception),
"DBM object has already been closed")
for meth in (operator.methodcaller('keys'),
operator.methodcaller('iterkeys'),
operator.methodcaller('items'),
len):
with self.assertRaises(dumbdbm.error) as cm:
meth(f)
self.assertEqual(str(cm.exception),
"DBM object has already been closed")
示例7: _validate_value_regex
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def _validate_value_regex(self):
"""Specific validation for `value_regex` type
The `value_regex` type works a little differently. In
particular it doesn't support OPERATORS that perform
operations on a list of values, specifically 'intersect',
'contains', 'difference', 'in' and 'not-in'
"""
# Sanity check that we can compile
try:
pattern = re.compile(self.data['value_regex'])
if pattern.groups != 1:
raise PolicyValidationError(
"value_regex must have a single capturing group: %s" %
self.data)
except re.error as e:
raise PolicyValidationError(
"Invalid value_regex: %s %s" % (e, self.data))
return self
示例8: test_operator
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
示例9: tokenize
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def tokenize(input, escapables={"'", '"', '\\'} | {item for item in string.whitespace} - {' '}):
"""Yield each token belonging to the windbg format in `input` that would need to be escaped using the specified `escapables`.
If the set `escapables` is defined, then use it as the list of characters to tokenize.
"""
result, iterable = '', iter(input)
try:
while True:
char = six.next(iterable)
if operator.contains(escapables, char):
if result:
yield result
yield char
result = ''
else:
result += char
continue
except StopIteration:
if result:
yield result
return
return
示例10: operate
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def operate(self, op, *other, **kwargs):
r"""Operate on an argument.
This is the lowest level of operation, raises
:class:`NotImplementedError` by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding :class:`.ColumnOperators`
to apply ``func.lower()`` to the left and right
side::
class MyComparator(ColumnOperators):
def operate(self, op, other):
return op(func.lower(self), func.lower(other))
:param op: Operator callable.
:param \*other: the 'other' side of the operation. Will
be a single scalar for most operations.
:param \**kwargs: modifiers. These may be passed by special
operators such as :meth:`ColumnOperators.contains`.
"""
raise NotImplementedError(str(op))
示例11: test_grep
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def test_grep(self):
records = [
{'day': 1, 'name': 'bill'},
{'day': 1, 'name': 'rob'},
{'day': 1, 'name': 'jane'},
{'day': 2, 'name': 'rob'},
{'day': 3, 'name': 'jane'},
]
rules = [{'fields': ['day'], 'pattern': partial(eq, 1)}]
result = next(pr.grep(records, rules))['name']
nt.assert_equal('bill', result)
rules = [{'pattern': partial(contains, {1, 'rob'})}]
result = next(pr.grep(records, rules))['name']
nt.assert_equal('rob', result)
rules = [{'pattern': partial(contains, {1, 'rob'})}]
result = next(pr.grep(records, rules, any_match=True))['name']
nt.assert_equal('bill', result)
rules = [{'fields': ['name'], 'pattern': 'o'}]
result = next(pr.grep(records, rules, inverse=True))['name']
nt.assert_equal('bill', result)
示例12: apply_filter
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def apply_filter(self, filter_name, filter_value, sess):
available_filters = {'user_agent': operator.contains,
'peer_ip': operator.eq,
'attack_types': operator.contains,
'possible_owners': operator.contains,
'start_time': operator.le,
'end_time': operator.ge,
'snare_uuid': operator.eq,
'location': operator.contains
}
try:
if available_filters[filter_name] is operator.contains:
return available_filters[filter_name](sess[filter_name], filter_value)
else:
return available_filters[filter_name](filter_value, sess[filter_name])
except KeyError:
raise
示例13: session_has_permissions
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def session_has_permissions(self, access, session):
"""
Check that the authenticated session has the permissions specified in
*access*. The permissions in *access* are abbreviated with the first
letter of create, read, update, and delete. For example, to check for
read and update permissions, *access* would be ``'ru'``.
.. note::
This will always return ``True`` for sessions which are for
administrative users. To maintain this logic, this method **should
not** be overridden in subclasses. Instead override the specific
``_session_has_*_access`` methods as necessary.
:param str access: The desired permissions.
:param session: The authenticated session to check access for.
:return: Whether the session has the desired permissions.
:rtype: bool
"""
if session.user_is_admin:
return True
cls = self.__class__
if cls.is_private:
return False
access = access.lower()
for case in utilities.switch(access, comp=operator.contains, swapped=True):
if case('c') and not cls.session_has_create_access(session, instance=self):
break
if case('r') and not cls.session_has_read_access(session, instance=self):
break
if case('u') and not cls.session_has_update_access(session, instance=self):
break
if case('d') and not cls.session_has_delete_access(session, instance=self):
break
else:
return True
return False
示例14: test_contains
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def test_contains(self):
self.assertRaises(TypeError, operator.contains)
self.assertRaises(TypeError, operator.contains, None, None)
self.assertTrue(operator.contains(range(4), 2))
self.assertFalse(operator.contains(range(4), 5))
with test_support.check_py3k_warnings():
self.assertTrue(operator.sequenceIncludes(range(4), 2))
self.assertFalse(operator.sequenceIncludes(range(4), 5))
示例15: _verify_include_exclude
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import contains [as 別名]
def _verify_include_exclude(action_output, style, query_type,
operation=None, expected_value=None, key=None):
# Checking the inclusion or exclusion and verifies result values
# With regards to different operations for actions ('api','parse', 'learn')
if query_type == 'api_query':
# if a value exist to compare the result
return _verify_string_query_include_exclude(action_output, expected_value, style, operation=operation)
else:
# if results are dictionary and the queries are in dq format ( contains('value'))
return _verify_dq_query_and_execute_include_exclude(action_output, style, key)