Python operator.ne() Examples

The following are 30 code examples of operator.ne(). 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_richcmp.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_values(self):
        # check all operators and all comparison results
        self.checkvalue("lt", 0, 0, False)
        self.checkvalue("le", 0, 0, True )
        self.checkvalue("eq", 0, 0, True )
        self.checkvalue("ne", 0, 0, False)
        self.checkvalue("gt", 0, 0, False)
        self.checkvalue("ge", 0, 0, True )

        self.checkvalue("lt", 0, 1, True )
        self.checkvalue("le", 0, 1, True )
        self.checkvalue("eq", 0, 1, False)
        self.checkvalue("ne", 0, 1, True )
        self.checkvalue("gt", 0, 1, False)
        self.checkvalue("ge", 0, 1, False)

        self.checkvalue("lt", 1, 0, False)
        self.checkvalue("le", 1, 0, False)
        self.checkvalue("eq", 1, 0, False)
        self.checkvalue("ne", 1, 0, True )
        self.checkvalue("gt", 1, 0, True )
        self.checkvalue("ge", 1, 0, True ) 
Example #2
Source File: test_operators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_compare_frame(self):
        # GH#24282 check that Categorical.__cmp__(DataFrame) defers to frame
        data = ["a", "b", 2, "a"]
        cat = Categorical(data)

        df = DataFrame(cat)

        for op in [operator.eq, operator.ne, operator.ge,
                   operator.gt, operator.le, operator.lt]:
            with pytest.raises(ValueError):
                # alignment raises unless we transpose
                op(cat, df)

        result = cat == df.T
        expected = DataFrame([[True, True, True, True]])
        tm.assert_frame_equal(result, expected)

        result = cat[::-1] != df.T
        expected = DataFrame([[False, True, True, False]])
        tm.assert_frame_equal(result, expected) 
Example #3
Source File: sa_utils.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def op(operation, column):
    if operation == 'in':
        def comparator(column, v):
            return column.in_(v)
    elif operation == 'like':
        def comparator(column, v):
            return column.like(v + '%')
    elif operation == 'eq':
        comparator = _operator.eq
    elif operation == 'ne':
        comparator = _operator.ne
    elif operation == 'le':
        comparator = _operator.le
    elif operation == 'lt':
        comparator = _operator.lt
    elif operation == 'ge':
        comparator = _operator.ge
    elif operation == 'gt':
        comparator = _operator.gt
    else:
        raise ValueError('Operation {} not supported'.format(operation))
    return comparator


# TODO: fix comparators, keys should be something better 
Example #4
Source File: test_regression.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_richcompare_crash(self):
        # gh-4613
        import operator as op

        # dummy class where __array__ throws exception
        class Foo(object):
            __array_priority__ = 1002

            def __array__(self,*args,**kwargs):
                raise Exception()

        rhs = Foo()
        lhs = np.array(1)
        for f in [op.lt, op.le, op.gt, op.ge]:
            if sys.version_info[0] >= 3:
                assert_raises(TypeError, f, lhs, rhs)
            else:
                f(lhs, rhs)
        assert_(not op.eq(lhs, rhs))
        assert_(op.ne(lhs, rhs)) 
Example #5
Source File: test_regression.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_richcompare_crash(self):
        # gh-4613
        import operator as op

        # dummy class where __array__ throws exception
        class Foo(object):
            __array_priority__ = 1002

            def __array__(self, *args, **kwargs):
                raise Exception()

        rhs = Foo()
        lhs = np.array(1)
        for f in [op.lt, op.le, op.gt, op.ge]:
            if sys.version_info[0] >= 3:
                assert_raises(TypeError, f, lhs, rhs)
            elif not sys.py3kwarning:
                # With -3 switch in python 2, DeprecationWarning is raised
                # which we are not interested in
                f(lhs, rhs)
        assert_(not op.eq(lhs, rhs))
        assert_(op.ne(lhs, rhs)) 
Example #6
Source File: validate_data.py    From tcex with Apache License 2.0 6 votes vote down vote up
def not_null(self, variable):
        """Validate that a variable is not empty/null"""
        # Could do something like self.ne(variable, None), but want to be pretty specific on
        # the errors on this one
        variable_data = self.provider.tcex.playbook.read(variable)
        self.log.data('validate', 'Variable', variable)
        self.log.data('validate', 'DB Data', variable_data)
        if not variable:
            self.log.data(
                'validate', 'None Error', f'Redis variable not provided', 'error',
            )
            return False

        if not variable_data:
            self.log.data(
                'validate', 'None Found', f'Redis variable {variable} was not found', 'error',
            )
            return False

        return True 
Example #7
Source File: test_regression.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_richcompare_crash(self):
        # gh-4613
        import operator as op

        # dummy class where __array__ throws exception
        class Foo(object):
            __array_priority__ = 1002

            def __array__(self, *args, **kwargs):
                raise Exception()

        rhs = Foo()
        lhs = np.array(1)
        for f in [op.lt, op.le, op.gt, op.ge]:
            if sys.version_info[0] >= 3:
                assert_raises(TypeError, f, lhs, rhs)
            elif not sys.py3kwarning:
                # With -3 switch in python 2, DeprecationWarning is raised
                # which we are not interested in
                f(lhs, rhs)
        assert_(not op.eq(lhs, rhs))
        assert_(op.ne(lhs, rhs)) 
Example #8
Source File: __init__.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
            '<':  operator.lt,
            '>':  operator.gt,
            '<=': operator.le,
            '>=': operator.ge,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #9
Source File: test_operators.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_timestamp_compare(self):
        # make sure we can compare Timestamps on the right AND left hand side
        # GH4982
        df = DataFrame({'dates1': date_range('20010101', periods=10),
                        'dates2': date_range('20010102', periods=10),
                        'intcol': np.random.randint(1000000000, size=10),
                        'floatcol': np.random.randn(10),
                        'stringcol': list(tm.rands(10))})
        df.loc[np.random.rand(len(df)) > 0.5, 'dates2'] = pd.NaT
        ops = {'gt': 'lt', 'lt': 'gt', 'ge': 'le', 'le': 'ge', 'eq': 'eq',
               'ne': 'ne'}

        for left, right in ops.items():
            left_f = getattr(operator, left)
            right_f = getattr(operator, right)

            # no nats
            expected = left_f(df, Timestamp('20010109'))
            result = right_f(Timestamp('20010109'), df)
            assert_frame_equal(result, expected)

            # nats
            expected = left_f(df, Timestamp('nat'))
            result = right_f(Timestamp('nat'), df)
            assert_frame_equal(result, expected) 
Example #10
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_values(self):
        # check all operators and all comparison results
        self.checkvalue("lt", 0, 0, False)
        self.checkvalue("le", 0, 0, True )
        self.checkvalue("eq", 0, 0, True )
        self.checkvalue("ne", 0, 0, False)
        self.checkvalue("gt", 0, 0, False)
        self.checkvalue("ge", 0, 0, True )

        self.checkvalue("lt", 0, 1, True )
        self.checkvalue("le", 0, 1, True )
        self.checkvalue("eq", 0, 1, False)
        self.checkvalue("ne", 0, 1, True )
        self.checkvalue("gt", 0, 1, False)
        self.checkvalue("ge", 0, 1, False)

        self.checkvalue("lt", 1, 0, False)
        self.checkvalue("le", 1, 0, False)
        self.checkvalue("eq", 1, 0, False)
        self.checkvalue("ne", 1, 0, True )
        self.checkvalue("gt", 1, 0, True )
        self.checkvalue("ge", 1, 0, True ) 
Example #11
Source File: redditDataExtractor.py    From redditDataExtractor with GNU General Public License v3.0 6 votes vote down vote up
def xorLst(lst):
    """
    Essentially does what any() and all() do for OR and AND, except for XOR now

    :param lst: A list of booleans
    :type lst: list
    :rtype: bool
    """
    if len(lst) > 1:
        res = lst[0] ^ lst[1]
        lst = lst[2:]
        for b in lst:
            res ^= b
    elif len(lst) == 1:
        res = lst[0]
    else:
        res = False
    return res


# The following functions are made to get around the fact that lambdas and builtin functions on str like str.endswith
# are not pickleable. Operator functions like operator.ne are pickleable though...weird. 
Example #12
Source File: __init__.py    From jbox with MIT License 6 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
            '<':  operator.lt,
            '>':  operator.gt,
            '<=': operator.le,
            '>=': operator.ge,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #13
Source File: ec2.py    From ssha with MIT License 6 votes vote down vote up
def _rules_pass(obj, rules, compare=operator.eq):

    for key, expected_value in rules.items():

        if isinstance(expected_value, dict):

            if key.endswith('NotEqual'):
                nested_compare = operator.ne
                key = key[:-len('NotEqual')]
            else:
                nested_compare = compare

            nested_rules_passed = _rules_pass(
                obj=obj.get(key) or {},
                rules=expected_value,
                compare=nested_compare,
            )
            if not nested_rules_passed:
                return False

        elif not compare(obj.get(key), expected_value):
            return False

    return True 
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: test_query_eval.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_inf(self):
        n = 10
        df = DataFrame({'a': np.random.rand(n), 'b': np.random.rand(n)})
        df.loc[::2, 0] = np.inf
        ops = '==', '!='
        d = dict(zip(ops, (operator.eq, operator.ne)))
        for op, f in d.items():
            q = 'a %s inf' % op
            expected = df[f(df.a, np.inf)]
            result = df.query(q, engine=self.engine, parser=self.parser)
            assert_frame_equal(result, expected) 
Example #16
Source File: test_query_eval.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_str_query_method(self, parser, engine):
        df = DataFrame(randn(10, 1), columns=['b'])
        df['strings'] = Series(list('aabbccddee'))
        expect = df[df.strings == 'a']

        if parser != 'pandas':
            col = 'strings'
            lst = '"a"'

            lhs = [col] * 2 + [lst] * 2
            rhs = lhs[::-1]

            eq, ne = '==', '!='
            ops = 2 * ([eq] + [ne])

            for lhs, op, rhs in zip(lhs, ops, rhs):
                ex = '{lhs} {op} {rhs}'.format(lhs=lhs, op=op, rhs=rhs)
                pytest.raises(NotImplementedError, df.query, ex,
                              engine=engine, parser=parser,
                              local_dict={'strings': df.strings})
        else:
            res = df.query('"a" == strings', engine=engine, parser=parser)
            assert_frame_equal(res, expect)

            res = df.query('strings == "a"', engine=engine, parser=parser)
            assert_frame_equal(res, expect)
            assert_frame_equal(res, df[df.strings.isin(['a'])])

            expect = df[df.strings != 'a']
            res = df.query('strings != "a"', engine=engine, parser=parser)
            assert_frame_equal(res, expect)

            res = df.query('"a" != strings', engine=engine, parser=parser)
            assert_frame_equal(res, expect)
            assert_frame_equal(res, df[~df.strings.isin(['a'])]) 
Example #17
Source File: ops.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _gen_eval_kwargs(name):
    """
    Find the keyword arguments to pass to numexpr for the given operation.

    Parameters
    ----------
    name : str

    Returns
    -------
    eval_kwargs : dict

    Examples
    --------
    >>> _gen_eval_kwargs("__add__")
    {}

    >>> _gen_eval_kwargs("rtruediv")
    {"reversed": True, "truediv": True}
    """
    kwargs = {}

    # Series and Panel appear to only pass __add__, __radd__, ...
    # but DataFrame gets both these dunder names _and_ non-dunder names
    # add, radd, ...
    name = name.replace('__', '')

    if name.startswith('r'):
        if name not in ['radd', 'rand', 'ror', 'rxor']:
            # Exclude commutative operations
            kwargs['reversed'] = True

    if name in ['truediv', 'rtruediv']:
        kwargs['truediv'] = True

    if name in ['ne']:
        kwargs['masker'] = True

    return kwargs 
Example #18
Source File: base.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _add_comparison_methods(cls):
        """ add in comparison methods """
        cls.__eq__ = _make_comparison_op(operator.eq, cls)
        cls.__ne__ = _make_comparison_op(operator.ne, cls)
        cls.__lt__ = _make_comparison_op(operator.lt, cls)
        cls.__gt__ = _make_comparison_op(operator.gt, cls)
        cls.__le__ = _make_comparison_op(operator.le, cls)
        cls.__ge__ = _make_comparison_op(operator.ge, cls) 
Example #19
Source File: validate_data.py    From tcex with Apache License 2.0 5 votes vote down vote up
def details(self, app_data, test_data, op):
        """Return details about the validation."""
        details = ''
        if app_data is not None and test_data is not None and op in ['eq', 'ne']:
            try:
                diff_count = 0
                for i, diff in enumerate(difflib.ndiff(app_data, test_data)):
                    if diff[0] == ' ':  # no difference
                        continue

                    if diff[0] == '-':
                        details += f'\n    * Missing data at index {i}'
                    elif diff[0] == '+':
                        details += f'\n    * Extra data at index {i}'
                    if diff_count > self.max_diff:
                        details += '\n    * Max number of differences reached.'
                        # don't spam the logs if string are vastly different
                        self.log.data(
                            'validate', 'Maximum Reached', 'Max number of differences reached.'
                        )
                        break
                    diff_count += 1
            except TypeError:
                pass
            except KeyError:
                pass
        return details 
Example #20
Source File: test_sqlalchemy.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_ne(self):
        criterion = {"a": "!foo"}

        op = dummy_table.c.a != "foo"
        with mock.patch.object(dummy_table.c.a, 'operate') as func:
            func.return_value = op

            base.SQLAlchemy._apply_criterion(
                dummy_table, self.query, criterion)
            func.assert_called_with(operator.ne, "foo")
            self.query.where.assert_called_with(op) 
Example #21
Source File: pkg_resources.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #22
Source File: test_richcmp.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_mixed(self):
        # check that comparisons involving Vector objects
        # which return rich results (i.e. Vectors with itemwise
        # comparison results) work
        a = Vector(range(2))
        b = Vector(range(3))
        # all comparisons should fail for different length
        for opname in opmap:
            self.checkfail(ValueError, opname, a, b)

        a = range(5)
        b = 5 * [2]
        # try mixed arguments (but not (a, b) as that won't return a bool vector)
        args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
        for (a, b) in args:
            self.checkequal("lt", a, b, [True,  True,  False, False, False])
            self.checkequal("le", a, b, [True,  True,  True,  False, False])
            self.checkequal("eq", a, b, [False, False, True,  False, False])
            self.checkequal("ne", a, b, [True,  True,  False, True,  True ])
            self.checkequal("gt", a, b, [False, False, False, True,  True ])
            self.checkequal("ge", a, b, [False, False, True,  True,  True ])

            for ops in opmap.itervalues():
                for op in ops:
                    # calls __nonzero__, which should fail
                    self.assertRaises(TypeError, bool, op(a, b)) 
Example #23
Source File: test_deprecations.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_none_comparison(self):
        # Test comparison of None, which should result in element-wise
        # comparison in the future. [1, 2] == None should be [False, False].
        with warnings.catch_warnings():
            warnings.filterwarnings('always', '', FutureWarning)
            assert_warns(FutureWarning, operator.eq, np.arange(3), None)
            assert_warns(FutureWarning, operator.ne, np.arange(3), None)

        with warnings.catch_warnings():
            warnings.filterwarnings('error', '', FutureWarning)
            assert_raises(FutureWarning, operator.eq, np.arange(3), None)
            assert_raises(FutureWarning, operator.ne, np.arange(3), None) 
Example #24
Source File: test_deprecations.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_normal_types(self):
        for op in (operator.eq, operator.ne):
            # Broadcasting errors:
            self.assert_deprecated(op, args=(np.zeros(3), []))
            a = np.zeros(3, dtype='i,i')
            # (warning is issued a couple of times here)
            self.assert_deprecated(op, args=(a, a[:-1]), num=None)

            # Element comparison error (numpy array can't be compared).
            a = np.array([1, np.array([1,2,3])], dtype=object)
            b = np.array([1, np.array([1,2,3])], dtype=object)
            self.assert_deprecated(op, args=(a, b), num=None) 
Example #25
Source File: test_operator.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ne(self):
        class C(object):
            def __ne__(self, other):
                raise SyntaxError
        self.assertRaises(TypeError, operator.ne)
        self.assertRaises(SyntaxError, operator.ne, C(), C())
        self.assertTrue(operator.ne(1, 0))
        self.assertTrue(operator.ne(1, 0.0))
        self.assertFalse(operator.ne(1, 1))
        self.assertFalse(operator.ne(1, 1.0))
        self.assertTrue(operator.ne(1, 2))
        self.assertTrue(operator.ne(1, 2.0)) 
Example #26
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_recursion(self):
        # Check that comparison for recursive objects fails gracefully
        from UserList import UserList
        a = UserList()
        b = UserList()
        a.append(b)
        b.append(a)
        self.assertRaises(RuntimeError, operator.eq, a, b)
        self.assertRaises(RuntimeError, operator.ne, a, b)
        self.assertRaises(RuntimeError, operator.lt, a, b)
        self.assertRaises(RuntimeError, operator.le, a, b)
        self.assertRaises(RuntimeError, operator.gt, a, b)
        self.assertRaises(RuntimeError, operator.ge, a, b)

        b.append(17)
        # Even recursive lists of different lengths are different,
        # but they cannot be ordered
        self.assertTrue(not (a == b))
        self.assertTrue(a != b)
        self.assertRaises(RuntimeError, operator.lt, a, b)
        self.assertRaises(RuntimeError, operator.le, a, b)
        self.assertRaises(RuntimeError, operator.gt, a, b)
        self.assertRaises(RuntimeError, operator.ge, a, b)
        a.append(17)
        self.assertRaises(RuntimeError, operator.eq, a, b)
        self.assertRaises(RuntimeError, operator.ne, a, b)
        a.insert(0, 11)
        b.insert(0, 12)
        self.assertTrue(not (a == b))
        self.assertTrue(a != b)
        self.assertTrue(a < b) 
Example #27
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_mixed(self):
        # check that comparisons involving Vector objects
        # which return rich results (i.e. Vectors with itemwise
        # comparison results) work
        a = Vector(range(2))
        b = Vector(range(3))
        # all comparisons should fail for different length
        for opname in opmap:
            self.checkfail(ValueError, opname, a, b)

        a = range(5)
        b = 5 * [2]
        # try mixed arguments (but not (a, b) as that won't return a bool vector)
        args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
        for (a, b) in args:
            self.checkequal("lt", a, b, [True,  True,  False, False, False])
            self.checkequal("le", a, b, [True,  True,  True,  False, False])
            self.checkequal("eq", a, b, [False, False, True,  False, False])
            self.checkequal("ne", a, b, [True,  True,  False, True,  True ])
            self.checkequal("gt", a, b, [False, False, False, True,  True ])
            self.checkequal("ge", a, b, [False, False, True,  True,  True ])

            for ops in opmap.itervalues():
                for op in ops:
                    # calls __nonzero__, which should fail
                    self.assertRaises(TypeError, bool, op(a, b)) 
Example #28
Source File: compressed.py    From lambda-packs with MIT License 5 votes vote down vote up
def __ne__(self, other):
        # Scalar other.
        if isscalarlike(other):
            if np.isnan(other):
                warn("Comparing a sparse matrix with nan using != is inefficient",
                     SparseEfficiencyWarning)
                all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
                return all_true
            elif other != 0:
                warn("Comparing a sparse matrix with a nonzero scalar using !="
                     " is inefficient, try using == instead.", SparseEfficiencyWarning)
                all_true = self.__class__(np.ones(self.shape), dtype=np.bool_)
                inv = self._scalar_binopt(other, operator.eq)
                return all_true - inv
            else:
                return self._scalar_binopt(other, operator.ne)
        # Dense other.
        elif isdense(other):
            return self.todense() != other
        # Sparse other.
        elif isspmatrix(other):
            #TODO sparse broadcasting
            if self.shape != other.shape:
                return True
            elif self.format != other.format:
                other = other.asformat(self.format)
            return self._binopt(other,'_ne_')
        else:
            return True 
Example #29
Source File: compressed.py    From lambda-packs with MIT License 5 votes vote down vote up
def __eq__(self, other):
        # Scalar other.
        if isscalarlike(other):
            if np.isnan(other):
                return self.__class__(self.shape, dtype=np.bool_)

            if other == 0:
                warn("Comparing a sparse matrix with 0 using == is inefficient"
                        ", try using != instead.", SparseEfficiencyWarning)
                all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
                inv = self._scalar_binopt(other, operator.ne)
                return all_true - inv
            else:
                return self._scalar_binopt(other, operator.eq)
        # Dense other.
        elif isdense(other):
            return self.todense() == other
        # Sparse other.
        elif isspmatrix(other):
            warn("Comparing sparse matrices using == is inefficient, try using"
                    " != instead.", SparseEfficiencyWarning)
            #TODO sparse broadcasting
            if self.shape != other.shape:
                return False
            elif self.format != other.format:
                other = other.asformat(self.format)
            res = self._binopt(other,'_ne_')
            all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
            return all_true - res
        else:
            return False 
Example #30
Source File: version.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def __ne__(self, other): return self.__compare(other, operator.ne)