Python operator.and_() Examples

The following are 30 code examples of operator.and_(). 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: utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def unify_nsplits(*tensor_axes):
    tensor_splits = [dict((a, split) for a, split in zip(axes, t.nsplits) if split != (1,))
                     for t, axes in tensor_axes if t.nsplits]
    common_axes = reduce(operator.and_, [set(ts.keys()) for ts in tensor_splits]) if tensor_splits else set()
    axes_unified_splits = dict((ax, decide_unify_split(*(t[ax] for t in tensor_splits)))
                               for ax in common_axes)

    if len(common_axes) == 0:
        return tuple(t[0] for t in tensor_axes)

    res = []
    for t, axes in tensor_axes:
        new_chunk = dict((i, axes_unified_splits[ax]) for ax, i in zip(axes, range(t.ndim))
                         if ax in axes_unified_splits)
        res.append(t.rechunk(new_chunk)._inplace_tile())

    return tuple(res) 
Example #2
Source File: poetry.py    From pdm with MIT License 6 votes vote down vote up
def _convert_req(req_dict):
    if not getattr(req_dict, "items", None):
        return _convert_specifier(req_dict)
    req_dict = dict(req_dict)
    if "version" in req_dict:
        req_dict["version"] = _convert_specifier(req_dict["version"])
    markers = []
    if "markers" in req_dict:
        markers.append(Marker(req_dict.pop("markers")))
    if "python" in req_dict:
        markers.append(
            Marker(_convert_python(req_dict.pop("python")).as_marker_string())
        )
    if markers:
        req_dict["marker"] = str(functools.reduce(operator.and_, markers)).replace(
            '"', "'"
        )
    if "rev" in req_dict or "branch" in req_dict or "tag" in req_dict:
        req_dict["ref"] = req_dict.pop(
            "rev", req_dict.pop("tag", req_dict.pop("branch", None))
        )
    return req_dict 
Example #3
Source File: __init__.py    From aireamhan with MIT License 6 votes vote down vote up
def add_globals(self):
    "Add some Scheme standard procedures."
    import math, cmath, operator as op
    from functools import reduce
    self.update(vars(math))
    self.update(vars(cmath))
    self.update({
     '+':op.add, '-':op.sub, '*':op.mul, '/':op.itruediv, 'níl':op.not_, 'agus':op.and_,
     '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'mod':op.mod, 
     'frmh':cmath.sqrt, 'dearbhluach':abs, 'uas':max, 'íos':min,
     'cothrom_le?':op.eq, 'ionann?':op.is_, 'fad':len, 'cons':cons,
     'ceann':lambda x:x[0], 'tóin':lambda x:x[1:], 'iarcheangail':op.add,  
     'liosta':lambda *x:list(x), 'liosta?': lambda x:isa(x,list),
     'folamh?':lambda x: x == [], 'adamh?':lambda x: not((isa(x, list)) or (x == None)),
     'boole?':lambda x: isa(x, bool), 'scag':lambda f, x: list(filter(f, x)),
     'cuir_le':lambda proc,l: proc(*l), 'mapáil':lambda p, x: list(map(p, x)), 
     'lódáil':lambda fn: load(fn), 'léigh':lambda f: f.read(),
     'oscail_comhad_ionchuir':open,'dún_comhad_ionchuir':lambda p: p.file.close(), 
     'oscail_comhad_aschur':lambda f:open(f,'w'), 'dún_comhad_aschur':lambda p: p.close(),
     'dac?':lambda x:x is eof_object, 'luacháil':lambda x: evaluate(x),
     'scríobh':lambda x,port=sys.stdout:port.write(to_string(x) + '\n')})
    return self 
Example #4
Source File: boxer.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def interpret_multi_sents(self, inputs, discourse_ids=None, question=False, verbose=False):
        """
        Use Boxer to give a first order representation.

        :param inputs: list of list of str Input discourses to parse
        :param occur_index: bool Should predicates be occurrence indexed?
        :param discourse_ids: list of str Identifiers to be inserted to each occurrence-indexed predicate.
        :return: ``drt.DrtExpression``
        """
        if discourse_ids is not None:
            assert len(inputs) == len(discourse_ids)
            assert reduce(operator.and_, (id is not None for id in discourse_ids))
            use_disc_id = True
        else:
            discourse_ids = list(map(str, range(len(inputs))))
            use_disc_id = False

        candc_out = self._call_candc(inputs, discourse_ids, question, verbose=verbose)
        boxer_out = self._call_boxer(candc_out, verbose=verbose)

#        if 'ERROR: input file contains no ccg/2 terms.' in boxer_out:
#            raise UnparseableInputException('Could not parse with candc: "%s"' % input_str)

        drs_dict = self._parse_to_drs_dict(boxer_out, use_disc_id)
        return [drs_dict.get(id, None) for id in discourse_ids] 
Example #5
Source File: queries.py    From blitzdb with MIT License 6 votes vote down vote up
def compile_query(query):
    """Compile each expression in query recursively."""
    if isinstance(query, dict):
        expressions = []
        for key, value in query.items():
            if key.startswith('$'):
                if key not in query_funcs:
                    raise AttributeError('Invalid operator: {}'.format(key))
                expressions.append(query_funcs[key](value))
            else:
                expressions.append(filter_query(key, value))
        if len(expressions) > 1:
            return boolean_operator_query(operator.and_)(expressions)
        else:
            return (
                expressions[0]
                if len(expressions)
                else lambda query_function: query_function(None, None)
            )
    else:
        return query 
Example #6
Source File: sparse.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _create_comparison_method(cls, op):
        def cmp_method(self, other):
            op_name = op.__name__

            if op_name in {'and_', 'or_'}:
                op_name = op_name[:-1]

            if isinstance(other, (ABCSeries, ABCIndexClass)):
                # Rely on pandas to unbox and dispatch to us.
                return NotImplemented

            if not is_scalar(other) and not isinstance(other, type(self)):
                # convert list-like to ndarray
                other = np.asarray(other)

            if isinstance(other, np.ndarray):
                # TODO: make this more flexible than just ndarray...
                if len(self) != len(other):
                    raise AssertionError("length mismatch: {self} vs. {other}"
                                         .format(self=len(self),
                                                 other=len(other)))
                other = SparseArray(other, fill_value=self.fill_value)

            if isinstance(other, SparseArray):
                return _sparse_array_op(self, other, op, op_name)
            else:
                with np.errstate(all='ignore'):
                    fill_value = op(self.fill_value, other)
                    result = op(self.sp_values, other)

                return type(self)(result,
                                  sparse_index=self.sp_index,
                                  fill_value=fill_value,
                                  dtype=np.bool_)

        name = '__{name}__'.format(name=op.__name__)
        return compat.set_function_name(cmp_method, name, cls) 
Example #7
Source File: selector.py    From fireplace with GNU Affero General Public License v3.0 5 votes vote down vote up
def __add__(self, other: SelectorLike) -> "Selector":
		return SetOpSelector(operator.and_, self, other) 
Example #8
Source File: attributed.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def safe_node(self, node):
        if token.ISNONTERMINAL(node[0]):
            return reduce(operator.and_, map(self.safe_node, node[1:]))
        elif node[0] == token.NAME:
            return node[1] in self._safe_names
        else:
            return True 
Example #9
Source File: attributed.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def safe_node(self, node):
        if token.ISNONTERMINAL(node[0]):
            return reduce(operator.and_, map(self.safe_node, node[1:]))
        elif node[0] == token.NAME:
            return node[1] in self._safe_names
        else:
            return True 
Example #10
Source File: attributed.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def safe_node(self, node):
        if token.ISNONTERMINAL(node[0]):
            return reduce(operator.and_, map(self.safe_node, node[1:]))
        elif node[0] == token.NAME:
            return node[1] in self._safe_names
        else:
            return True 
Example #11
Source File: ops.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def rand_(left, right):
    return operator.and_(right, left) 
Example #12
Source File: sparse.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _add_comparison_ops(cls):
        cls.__and__ = cls._create_comparison_method(operator.and_)
        cls.__or__ = cls._create_comparison_method(operator.or_)
        super(SparseArray, cls)._add_comparison_ops()

    # ----------
    # Formatting
    # ----------- 
Example #13
Source File: _constants.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __and__(self, other):
        """
        Define C{&} on two L{FlagConstant} instances to create a new
        L{FlagConstant} instance with only flags set in both instances set.
        """
        return _flagOp(and_, self, other) 
Example #14
Source File: test_operators.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_logical_operators(self):

        def _check_bin_op(op):
            result = op(df1, df2)
            expected = DataFrame(op(df1.values, df2.values), index=df1.index,
                                 columns=df1.columns)
            assert result.values.dtype == np.bool_
            assert_frame_equal(result, expected)

        def _check_unary_op(op):
            result = op(df1)
            expected = DataFrame(op(df1.values), index=df1.index,
                                 columns=df1.columns)
            assert result.values.dtype == np.bool_
            assert_frame_equal(result, expected)

        df1 = {'a': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True},
               'b': {'a': False, 'b': True, 'c': False,
                     'd': False, 'e': False},
               'c': {'a': False, 'b': False, 'c': True,
                     'd': False, 'e': False},
               'd': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True},
               'e': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True}}

        df2 = {'a': {'a': True, 'b': False, 'c': True, 'd': False, 'e': False},
               'b': {'a': False, 'b': True, 'c': False,
                     'd': False, 'e': False},
               'c': {'a': True, 'b': False, 'c': True, 'd': False, 'e': False},
               'd': {'a': False, 'b': False, 'c': False,
                     'd': True, 'e': False},
               'e': {'a': False, 'b': False, 'c': False,
                     'd': False, 'e': True}}

        df1 = DataFrame(df1)
        df2 = DataFrame(df2)

        _check_bin_op(operator.and_)
        _check_bin_op(operator.or_)
        _check_bin_op(operator.xor)

        _check_unary_op(operator.inv)  # TODO: belongs elsewhere 
Example #15
Source File: selector.py    From fireplace with GNU Affero General Public License v3.0 5 votes vote down vote up
def __repr__(self):
		name = self.op.__name__
		if name == "and_":
			infix = "+"
		elif name == "or_":
			infix = "|"
		elif name == "sub":
			infix = "-"
		else:
			infix = "UNKNOWN_OP"

		return "<%r %s %r>" % (self.left, infix, self.right) 
Example #16
Source File: UserFloat.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __rand__(self, other):
        return self._rop(other, operator.and_) 
Example #17
Source File: UserInt.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __and__(self, other):
        return self._op(other, operator.and_) 
Example #18
Source File: dataset.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __and__(self, other):
        return self._bin_op(other, operator.and_) 
Example #19
Source File: test_expr.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_binary_operations():
    OP_MAP = {
        "+": operator.add,
        "-": operator.sub,
        "*": operator.mul,
        "/": operator.truediv,
        "%": operator.mod,
        "===": operator.eq,
        "<": operator.lt,
        "<=": operator.le,
        ">": operator.gt,
        ">=": operator.ge,
        "!==": operator.ne,
        "&&": operator.and_,
        "||": operator.or_,
    }
    # When these are on the RHS, the opposite is evaluated instead.
    INEQ_REVERSE = {
        ">": "<",
        "<": ">",
        "<=": ">=",
        ">=": "<=",
        "===": "===",
        "!==": "!==",
    }
    for op, func in OP_MAP.items():
        z1 = func(datum.xxx, 2)
        assert repr(z1) == "(datum.xxx {} 2)".format(op)

        z2 = func(2, datum.xxx)
        if op in INEQ_REVERSE:
            assert repr(z2) == "(datum.xxx {} 2)".format(INEQ_REVERSE[op])
        else:
            assert repr(z2) == "(2 {} datum.xxx)".format(op)

        z3 = func(datum.xxx, datum.yyy)
        assert repr(z3) == "(datum.xxx {} datum.yyy)".format(op) 
Example #20
Source File: UserFloat.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __and__(self, other):
        return self._op(other, operator.and_) 
Example #21
Source File: QueryLarkDjangoParser.py    From qmpy with MIT License 5 votes vote down vote up
def and_(self,a,b):
        return operator.and_(a,b) 
Example #22
Source File: QueryLarkDjangoParser.py    From qmpy with MIT License 5 votes vote down vote up
def __init__(self):
        self.L2D_version = '0.1'
        self.opers = {'=':self.eq,  '>':self.gt,    '>=':self.ge, \
                      '<':self.lt,  '<=':self.le,   '!=':self.ne,\
                      'OR':self.or_,'AND':self.and_,'NOT':self.not_}
        self.parser = LarkParser(version=(0, 9, 7))
        self.db_keys = json.load(open(sorted(glob(os.path.join(os.path.dirname(__file__), "./grammar", "*.oqmd")))[-1])) 
Example #23
Source File: test_operator.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_bitwise_and(self):
        self.assertRaises(TypeError, operator.and_)
        self.assertRaises(TypeError, operator.and_, None, None)
        self.assertTrue(operator.and_(0xf, 0xa) == 0xa) 
Example #24
Source File: pkg_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def and_test(cls, nodelist):
        # MUST NOT short-circuit evaluation, or invalid syntax can be skipped!
        items = [
            cls.interpret(nodelist[i])
            for i in range(1, len(nodelist), 2)
        ]
        return functools.reduce(operator.and_, items) 
Example #25
Source File: pkg_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def and_test(cls, nodelist):
        # MUST NOT short-circuit evaluation, or invalid syntax can be skipped!
        return functools.reduce(operator.and_, [cls.interpret(nodelist[i]) for i in range(1,len(nodelist),2)]) 
Example #26
Source File: test_operator.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_bitwise_and(self):
        self.assertRaises(TypeError, operator.and_)
        self.assertRaises(TypeError, operator.and_, None, None)
        self.assertTrue(operator.and_(0xf, 0xa) == 0xa) 
Example #27
Source File: ops.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def rand_(left, right):
    return operator.and_(right, left) 
Example #28
Source File: abstract.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def _reduced_filter(self) -> t.Optional[Predicate]:
        """Before evaluation, sum up all filter predicates into a single one"""
        return None if self._is_trivial else reduce(and_, self._filters)

    # lazy queries 
Example #29
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def _all(func, items):
        results = [func(item) for item in items]
        return reduce(operator.and_, results, True) 
Example #30
Source File: view.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def list_contain_filter(self, qs, name, values):
        """Filter items that contain values in their name."""
        lookup = "__".join([name, "icontains"])
        value_list = values.split(",")
        queries = [Q(**{lookup: val}) for val in value_list]
        return qs.filter(reduce(and_, queries))