Python operator.contains() Examples

The following are 30 code examples of operator.contains(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module operator , or try the search function .
Example #1
Source File: test_bool.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
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) 
Example #2
Source File: test_bool.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: windbg.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #4
Source File: core.py    From cloud-custodian with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: test_dbm_dumb.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #6
Source File: operators.py    From sqlalchemy with MIT License 6 votes vote down vote up
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)) 
Example #7
Source File: test_bool.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: test_dbm_dumb.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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") 
Example #9
Source File: test_dbm_dumb.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #10
Source File: operators.py    From callee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #11
Source File: test_process.py    From meza with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: test_dbm_dumb.py    From android_universal with MIT License 6 votes vote down vote up
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") 
Example #13
Source File: api.py    From tanner with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #14
Source File: actions_helper.py    From genielibs with Apache License 2.0 6 votes vote down vote up
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) 
Example #15
Source File: tests_unit.py    From finam-export with Apache License 2.0 6 votes vote down vote up
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) 
Example #16
Source File: actions_helper.py    From genielibs with Apache License 2.0 6 votes vote down vote up
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)) 
Example #17
Source File: dtcli.py    From dynatrace-cli with Apache License 2.0 5 votes vote down vote up
def __init__(self, timeframe):
        "parses the string. allowed values are hour,2hours,6hours,day,week,month - also allowed are custom event names, 0=Now, X=Minutes prior to Now or a full UTC Timestamp"
        "Also allows two timeframes in the form of: firsttimestamp:secondtimestamp -> example: 2hours:hour, 120:60"
        self.timeframestr = timeframe

        if timeframe is None:
            self.timeframestr = [None]
            return

        self.type = []
        self.timestamp = []
        self.allowedConsts = ["hour", "2hours", "6hours", "day", "week", "month"]

        self.timeframestr = timeframe.split(":")
        for timeframe in self.timeframestr:
            if operator.contains(self.allowedConsts, timeframe):
                self.type.append("relative")
            elif timeframe.isdigit():
                # if it is an int check whether it is a number we convert relative to now or whether it is a full timestamp
                tsint = int(timeframe)
                if tsint < global_timestampcheck:
                    self.timestamp.append(1000 * int(datetime.datetime.now().timestamp() - tsint*60))
                else:
                    self.timestamp.append(int(timeframe))
                
                self.type.append("absolute")
            else:
                # has to be a custom event name
                # TODO - query events and try to find the timestamp of this event
                self.timestamp.append(None)
                self.type.append(None) 
Example #18
Source File: test_operator.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
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))
        self.assertTrue(operator.sequenceIncludes(range(4), 2))
        self.assertFalse(operator.sequenceIncludes(range(4), 5)) 
Example #19
Source File: sqlbuilder.py    From sqlobject with GNU Lesser General Public License v2.1 5 votes vote down vote up
def contains(self, s):
        return CONTAINSSTRING(self, s) 
Example #20
Source File: structure.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def up(self):
        '''Return all the structure members and addresses that reference this specific structure.'''
        x, sid = idaapi.xrefblk_t(), self.id

        # grab first structure that references this one
        ok = x.first_to(sid, 0)
        if not ok or x.frm == idaapi.BADADDR:
            return []

        # continue collecting all structures that references this one
        res = [(x.frm, x.iscode, x.type)]
        while x.next_to():
            res.append((x.frm, x.iscode, x.type))

        # walk through all references figuring out if its a structure member or an address
        refs = []
        for xrfrom, xriscode, xrtype in res:
            # if it's an address, then just create a regular reference
            if database.contains(xrfrom):
                refs.append( interface.opref_t(xrfrom, xriscode, interface.reftype_t.of(xrtype)) )
                continue

            # so it's not, which means this must be a member id
            fullname = idaapi.get_member_fullname(xrfrom)

            sptr = idaapi.get_member_struc(fullname)
            if not sptr:
                cls = self.__class__
                logging.warn(u"{:s}({:#x}).up() : Unable to find structure from member name \"{:s}\" while trying to handle reference for {:#x}.".format('.'.join((__name__, cls.__name__)), self.id, utils.string.escape(fullname, '"'), xrfrom))
                continue

            # we figured out the owner, so find the member with the ref, and add it.
            st = __instance__(sptr.id)
            refs.append(st.by_identifier(xrfrom))

        # and that's it, so we're done.
        return refs 
Example #21
Source File: _comment.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def encode(cls, iterable, result):
            '''Given an `iterable` string, send each character in a printable form to `result`.'''

            # construct a transformer that writes characters to result
            escape = internal.utils.character.escape(result); next(escape)

            # send the key prefix
            result.send(cls.prefix)

            # now we can actually process the string
            for ch in iterable:

                # first check if character has an existing key mapping
                if operator.contains(cls.mappings, ch):
                    for ch in operator.getitem(cls.mappings, ch):
                        result.send(ch)

                # otherwise pass it to the regular escape function
                else:
                    escape.send(ch)

                continue

            # submit the suffix and we're good
            result.send(cls.suffix)
            return 
Example #22
Source File: _interface.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def supersetQ(self, other):
        '''Returns true if the `other` register actually contains `self`.'''
        res, pos = set(), self
        while pos is not None:
            res.add(pos)
            pos = pos.__parent__
        return other in self.alias or other in res 
Example #23
Source File: _comment.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def descend(self, symbols):
        yield self
        for i, symbol in enumerate(symbols):
            if not isinstance(self, node) or not operator.contains(self, symbol):
                raise KeyError(i, symbol)    # raise KeyError for .get() and .find()
            self = self[symbol]
            yield self
        return 
Example #24
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def escape(cls, string, quote=''):
        """Escape the characters in `string` specified by `quote`.

        Handles both unicode and ascii. Defaults to escaping only
        the unprintable characters.
        """

        # construct a list for anything that gets transformed
        res = internal.interface.collect_t(list, lambda agg, value: agg + [value])

        # instantiate our generator for escaping unprintables in the string
        transform = character.escape(res); next(transform)

        # iterate through each character, sending everything to res
        for ch in iter(string or ''):

            # check if character is a user-specified quote or a backslash
            if any(operator.contains(set, ch) for set in (quote, '\\')):
                res.send('\\')
                res.send(ch)

            # check if character has an escape mapping to use
            elif operator.contains(cls.mapping, ch):
                map(res.send, cls.mapping[ch])

            # otherwise we can just send it to transform to escape it
            else:
                transform.send(ch)
            continue

        # figure out the correct function that determines how to join the res
        fjoin = (unicode() if isinstance(string, unicode) else str()).join

        return fjoin(res.get()) 
Example #25
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hexQ(cls, ch):
        '''Returns whether a character is a hex digit or not.'''
        return operator.contains(cls.const.hexadecimal, ch) 
Example #26
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def whitespaceQ(cls, ch):
        '''Returns whether a character represents whitespace or not.'''
        return operator.contains(cls.const.whitespace, ch) 
Example #27
Source File: _utils.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def asciiQ(cls, ch):
        '''Returns whether an ascii character is printable or not.'''
        return operator.contains(cls.const.printable, ch) 
Example #28
Source File: structure.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def down(self):
        '''Return all the structure members and addresses that are referenced by this specific structure.'''
        x, sid = idaapi.xrefblk_t(), self.id

        # grab structures that this one references
        ok = x.first_from(sid, 0)
        if not ok or x.to == idaapi.BADADDR:
            return []

        # continue collecting all structures that this one references
        res = [(x.to, x.iscode, x.type)]
        while x.next_from():
            res.append((x.to, x.iscode, x.type))

        # walk through all references figuring out if its a structure member or an address
        refs = []
        for xrto, xriscode, xrtype in res:
            # if it's  an address, then just create a regular reference
            if database.contains(xrto):
                refs.append( interface.opref_t(xrto, xriscode, interface.reftype_t.of(xrtype)) )
                continue

            # so it's not, which means this must be a member id
            fullname = idaapi.get_member_fullname(xrto)

            sptr = idaapi.get_member_struc(fullname)
            if not sptr:
                cls = self.__class__
                logging.warn(u"{:s}({:#x}).down() : Unable to find structure from member name \"{:s}\" while trying to handle reference for {:#x}.".format('.'.join((__name__, cls.__name__)), self.id, utils.string.escape(fullname, '"'), xrto))
                continue

            # we figured out the owner, so find the member with the ref, and add it.
            st = __instance__(sptr.id)
            refs.append(st.by_identifier(xrto))

        # and that's it, so we're done.
        return refs 
Example #29
Source File: structure.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ptr(self):
        '''Return the pointer to the ``idaapi.member_t`` that contains all the members.'''
        return self.__parent.ptr.members 
Example #30
Source File: structure.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fragment(id, offset, size):
    """Yield each member of the structure identified by `id` from the `offset` up to the `size`.

    Each iteration yields a tuple of the following format for each
    member within the requested bounds. This allows one to select
    certain fragments of a structure which can then be used to export
    to other programs or applications.

    `((offset, size), (name, comment, repeatable))`

    In this tuple, the field `comment` represents the non-repeatable
    comment whereas `repeatable` contains the member's `repeatable`
    comment.
    """
    member = members(id)

    # seek
    while True:
        (m_offset, m_size), (m_name, m_cmt, m_rcmt) = member.next()

        left, right = m_offset, m_offset+m_size
        if (offset >= left) and (offset < right):
            yield (m_offset, m_size), (m_name, m_cmt, m_rcmt)
            size -= m_size
            break
        continue

    # return
    while size > 0:
        (m_offset, m_size), (m_name, m_cmt, m_rcmt) = member.next()
        yield (m_offset, m_size), (m_name, m_cmt, m_rcmt)
        size -= m_size
    return