Python operator.xor() Examples

The following are 30 code examples of operator.xor(). 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: plot.py    From GSEApy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def zscore(data2d, axis=0):
    """Standardize the mean and variance of the data axis Parameters.

    :param data2d: DataFrame to normalize.
    :param axis: int, Which axis to normalize across. If 0, normalize across rows,
                  if 1, normalize across columns. If None, don't change data
                  
    :Returns: Normalized DataFrame. Normalized data with a mean of 0 and variance of 1
              across the specified axis.

    """
    if axis is None:
        # normalized to mean and std using entire matrix
        # z_scored = (data2d - data2d.values.mean()) / data2d.values.std(ddof=1)
        return data2d
    assert axis in [0,1]
    z_scored = data2d.apply(lambda x: (x-x.mean())/x.std(ddof=1), 
                            axis=operator.xor(1, axis))
    return z_scored 
Example #2
Source File: nmea.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _validateChecksum(sentence):
    """
    Validates the checksum of an NMEA sentence.

    @param sentence: The NMEA sentence to check the checksum of.
    @type sentence: C{bytes}

    @raise ValueError: If the sentence has an invalid checksum.

    Simply returns on sentences that either don't have a checksum,
    or have a valid checksum.
    """
    if sentence[-3:-2] == b'*':  # Sentence has a checksum
        reference, source = int(sentence[-2:], 16), sentence[1:-3]
        computed = reduce(operator.xor, [ord(x) for x in iterbytes(source)])
        if computed != reference:
            raise base.InvalidChecksum("%02x != %02x" % (computed, reference)) 
Example #3
Source File: blobs.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def calc_minhashes(self):
        def minhashes_for_shingles(shingles):
            def calc_onehash(shingle, seed):
                def c4_hash(shingle):
                    h = struct.unpack('<i',shingle)[0]
                    return  h % ((sys.maxsize + 1) * 2)
                if self.sh_type == 'c4':
                    return operator.xor(c4_hash(shingle), long(seed)) % self.modulo
                else:
                    return operator.xor(compute_positive_hash(shingle), long(seed)) % self.modulo

            minhashes = [sys.maxsize for _ in xrange(self.hashes)]
            for shingle in shingles:
                for hno in xrange(self.hashes):
                    h_value = calc_onehash(shingle, self.seeds[hno])
                    minhashes[hno] = min(h_value, minhashes[hno])
            return minhashes
        ##########################################
        shingles = self.shingles()
        minhashes = minhashes_for_shingles(shingles)
        return minhashes 
Example #4
Source File: test_differential_ops.py    From galgebra with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def chain_with_mv(self):
        coords = x, y, z = symbols('x y z', real=True)
        ga, ex, ey, ez = Ga.build('e*x|y|z', g=[1, 1, 1], coords=coords)
        s = Sdop([(x, Pdop(x)), (y, Pdop(y))])

        assert type(ex * s) is Sdop
        assert type(s * ex) is Mv

        # type should be preserved even when the result is 0
        assert type(ex * Sdop([])) is Sdop
        assert type(Sdop([]) * ex) is Mv

        # As discussed with brombo, these operations are not well defined - if
        # you need them, you should be using `Dop` not `Sdop`.
        for op in [operator.xor, operator.or_, operator.lt, operator.gt]:
            with pytest.raises(TypeError):
                op(ex, s)
            with pytest.raises(TypeError):
                op(s, ex) 
Example #5
Source File: test_differential_ops.py    From galgebra with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multiply(self):
        coords = x, y, z = symbols('x y z', real=True)
        ga, ex, ey, ez = Ga.build('e*x|y|z', g=[1, 1, 1], coords=coords)

        p = Pdop(x)
        assert x * p == Sdop([(x, p)])
        assert ex * p == Sdop([(ex, p)])

        assert p * x == p(x) == S(1)
        assert p * ex == p(ex) == S(0)
        assert type(p(ex)) is Mv

        # These are not defined for consistency with Sdop
        for op in [operator.xor, operator.or_, operator.lt, operator.gt]:
            with pytest.raises(TypeError):
                op(ex, p)
            with pytest.raises(TypeError):
                op(p, ex) 
Example #6
Source File: map_reduce.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def calc_minhashes(parsed_text, sh_type, hashes, seeds, modulo):
    def minhashes_for_shingles(shingles, sh_type, hashes, seeds, modulo):
        def calc_onehash(sh_type, shingle, seed, modulo):
            def c4_hash(shingle):
                h = struct.unpack('<i',shingle)[0]
                return  h % ((sys.maxsize + 1) * 2)
            if sh_type == 'c4':
                return operator.xor(c4_hash(shingle), long(seed)) % modulo
            else:
                return operator.xor(compute_positive_hash(shingle), long(seed)) % modulo

        minhashes = [sys.maxsize for _ in xrange(hashes)]
        for shingle in shingles:
            for hno in xrange(hashes):
                h_value = calc_onehash(sh_type, shingle, seeds[hno], modulo)
                minhashes[hno] = min(h_value, minhashes[hno])
        return minhashes

    shingles = parsed_text.split() if sh_type=='w' else set(_get_list_of_shingles(parsed_text))
    minhashes = minhashes_for_shingles(shingles, sh_type, hashes, seeds, modulo)
    return minhashes 
Example #7
Source File: test_operators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_inplace_ops_identity2(self, op):

        if compat.PY3 and op == 'div':
            return

        df = DataFrame({'a': [1., 2., 3.],
                        'b': [1, 2, 3]})

        operand = 2
        if op in ('and', 'or', 'xor'):
            # cannot use floats for boolean ops
            df['a'] = [True, False, True]

        df_copy = df.copy()
        iop = '__i{}__'.format(op)
        op = '__{}__'.format(op)

        # no id change and value is correct
        getattr(df, iop)(operand)
        expected = getattr(df_copy, op)(operand)
        assert_frame_equal(df, expected)
        expected = id(df)
        assert id(df) == expected 
Example #8
Source File: pyblowfish.py    From vrequest with MIT License 6 votes vote down vote up
def ctr_counter(nonce, f, start = 0):
    """
    Return an infinite iterator that starts at `start` and iterates by 1 over
    integers between 0 and 2^64 - 1 cyclically, returning on each iteration the
    result of combining each number with `nonce` using function `f`.
    
    `nonce` should be an random 64-bit integer that is used to make the counter
    unique.
    
    `f` should be a function that takes two 64-bit integers, the first being the
    `nonce`, and combines the two in a lossless manner (i.e. xor, addition, etc.)
    The returned value should be a 64-bit integer.
    
    `start` should be a number less than 2^64.
    """
    for n in range(start, 2**64):
        yield f(nonce, n)
    while True:
        for n in range(0, 2**64):
            yield f(nonce, n) 
Example #9
Source File: utils.py    From grove with Apache License 2.0 6 votes vote down vote up
def binary_back_substitute(W: np.ndarray, s: np.ndarray) -> np.ndarray:
    """
    Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination
    over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that
    :math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where all arithmetic is taken bitwise
    and modulo 2.

    :param W: A square :math:`n\\times n` matrix of 0s and 1s,
              in row-echelon (upper-triangle) form
    :param s: An :math:`n\\times 1` vector of 0s and 1s
    :return: The :math:`n\\times 1` vector of 0s and 1s that solves the above
             system of equations.
    """
    # iterate backwards, starting from second to last row for back-substitution
    m = np.copy(s)
    n = len(s)
    for row_num in range(n - 2, -1, -1):
        row = W[row_num]
        for col_num in range(row_num + 1, n):
            if row[col_num] == 1:
                m[row_num] = xor(s[row_num], s[col_num])

    return m[::-1] 
Example #10
Source File: encoder.py    From plugin.program.openwizard with GNU General Public License v3.0 6 votes vote down vote up
def calc_structured_append_parity(content):
    """\
    Calculates the parity data for the Structured Append mode.

    :param str content: The content.
    :rtype: int
    """
    if not isinstance(content, str_type):
        content = str(content)
    try:
        data = content.encode('iso-8859-1')
    except UnicodeError:
        try:
            data = content.encode('shift-jis')
        except (LookupError, UnicodeError):
            data = content.encode('utf-8')
    if _PY2:
        data = (ord(c) for c in data)
    return reduce(xor, data) 
Example #11
Source File: test_operators.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_inplace_ops_identity2(self, op):

        if compat.PY3 and op == 'div':
            return

        df = DataFrame({'a': [1., 2., 3.],
                        'b': [1, 2, 3]})

        operand = 2
        if op in ('and', 'or', 'xor'):
            # cannot use floats for boolean ops
            df['a'] = [True, False, True]

        df_copy = df.copy()
        iop = '__i{}__'.format(op)
        op = '__{}__'.format(op)

        # no id change and value is correct
        getattr(df, iop)(operand)
        expected = getattr(df_copy, op)(operand)
        assert_frame_equal(df, expected)
        expected = id(df)
        assert id(df) == expected 
Example #12
Source File: test_operators.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_inplace_ops_identity2(self, op):

        if compat.PY3 and op == 'div':
            return

        df = DataFrame({'a': [1., 2., 3.],
                        'b': [1, 2, 3]})

        operand = 2
        if op in ('and', 'or', 'xor'):
            # cannot use floats for boolean ops
            df['a'] = [True, False, True]

        df_copy = df.copy()
        iop = '__i{}__'.format(op)
        op = '__{}__'.format(op)

        # no id change and value is correct
        getattr(df, iop)(operand)
        expected = getattr(df_copy, op)(operand)
        assert_frame_equal(df, expected)
        expected = id(df)
        assert id(df) == expected 
Example #13
Source File: test_eval.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def should_warn(*args):
    not_mono = not any(map(operator.attrgetter('is_monotonic'), args))
    only_one_dt = reduce(operator.xor, map(_is_datetime, args))
    return not_mono and only_one_dt 
Example #14
Source File: test_operator.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_bitwise_xor(self):
        self.assertRaises(TypeError, operator.xor)
        self.assertRaises(TypeError, operator.xor, None, None)
        self.assertTrue(operator.xor(0xb, 0xc) == 0x7) 
Example #15
Source File: vec2d.py    From omnitool with MIT License 5 votes vote down vote up
def __xor__(self, other):
        return self._o2(other, operator.xor) 
Example #16
Source File: ops.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def rxor(left, right):
    return operator.xor(right, left)


# ----------------------------------------------------------------------------- 
Example #17
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 #18
Source File: utils.py    From grove with Apache License 2.0 5 votes vote down vote up
def bitwise_xor(bs0: str, bs1: str) -> str:
    """
    A helper to calculate the bitwise XOR of two bit string

    :param bs0: String of 0's and 1's representing a number in binary representations
    :param bs1: String of 0's and 1's representing a number in binary representations
    :return: String of 0's and 1's representing the XOR between bs0 and bs1
    """
    if len(bs0) != len(bs1):
        raise ValueError("Bit strings are not of equal length")
    n_bits = len(bs0)
    return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits) 
Example #19
Source File: simon.py    From grove with Apache License 2.0 5 votes vote down vote up
def _add_to_dict_of_indep_bit_vectors(self, z: np.ndarray) -> None:
        """
        This method adds a bit-vector z to the dictionary of independent vectors. It checks the
        provenance (most significant bit) of the vector and only adds it to the dictionary if the
        provenance is not yet found in the dictionary. This guarantees that we can write up a
        resulting matrix in upper-triangular form which by virtue of its form is invertible

        :param z: array containing the bit-vector
        :return: None
        """
        if (z == 0).all() or (z == 1).all():
            return None
        msb_z = utils.most_significant_bit(z)

        # try to add bitstring z to samples dictionary directly
        if msb_z not in self._dict_of_linearly_indep_bit_vectors.keys():
            self._dict_of_linearly_indep_bit_vectors[msb_z] = z
        # if we have a conflict with the provenance of a sample try to create
        # bit-wise XOR vector (guaranteed to be orthogonal to the conflict) and add
        # that to the samples.
        # Bail if this doesn't work and continue sampling.
        else:
            conflict_z = self._dict_of_linearly_indep_bit_vectors[msb_z]
            not_z = [xor(conflict_z[idx], z[idx]) for idx in range(len(z))]
            if (np.asarray(not_z) == 0).all():
                return None
            msb_not_z = utils.most_significant_bit(np.asarray(not_z))
            if msb_not_z not in self._dict_of_linearly_indep_bit_vectors.keys():
                self._dict_of_linearly_indep_bit_vectors[msb_not_z] = not_z 
Example #20
Source File: utils.py    From grove with Apache License 2.0 5 votes vote down vote up
def bitwise_xor(bs0: str, bs1: str) -> str:
    """
    A helper to calculate the bitwise XOR of two bit string

    :param bs0: String of 0's and 1's representing a number in binary representations
    :param bs1: String of 0's and 1's representing a number in binary representations
    :return: String of 0's and 1's representing the XOR between bs0 and bs1
    """
    if len(bs0) != len(bs1):
        raise ValueError("Bit strings are not of equal length")
    n_bits = len(bs0)
    return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits) 
Example #21
Source File: raidzdev.py    From zfsp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def xor_blocks(*args):
    args = [x for x in args if len(x)]
    if len(args) == 0:
        return ''
    size = min(len(x) for x in args)
    args = [x[:size] for x in args]
    format_str = '>'
    if size >= 8:
        format_str += '{}Q'.format(int(size/8))
    if size % 8:
        format_str += '{}B'.format(size % 8)
    structure = struct.Struct(format_str)
    out = [reduce(operator.xor, t) for t in zip(*(structure.unpack(x) for x in args))]
    return structure.pack(*out) 
Example #22
Source File: misc.py    From pyshtrih with MIT License 5 votes vote down vote up
def lrc(buff):
    """
    Расчет контрольной суммы.
    """

    return reduce(operator.xor, buff) 
Example #23
Source File: chip_match.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def get_fs_list(cm, colx=None, col=None):
        assert xor(colx is None, col is None)
        if col is not None:
            colx = cm.fsv_col_lbls.index(col)
        fs_list = [fsv.T[colx].T for fsv in cm.fsv_list]
        return fs_list 
Example #24
Source File: UserFloat.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def __rxor__(self, other):
        return self._rop(other, operator.xor) 
Example #25
Source File: _constants.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __xor__(self, other):
        """
        Define C{^} on two L{FlagConstant} instances to create a new
        L{FlagConstant} instance with only flags set on exactly one instance
        set.
        """
        return _flagOp(xor, self, other) 
Example #26
Source File: test_operator.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_bitwise_xor(self):
        self.assertRaises(TypeError, operator.xor)
        self.assertRaises(TypeError, operator.xor, None, None)
        self.assertTrue(operator.xor(0xb, 0xc) == 0x7) 
Example #27
Source File: pyblowfish.py    From vrequest with MIT License 5 votes vote down vote up
def decrypt(
        key:bytes, 
        plaintext:bytes, 
        iv:bytes=None, 
        mode='ecb', 
        defunc=base64.b64decode,
    ):
    # 默认强制使用 pkcs7 填充模式
    # key         = b'asdf'           # 4-56 个字符
    # plaintext   = b'asdfasdf'       # 8 字符
    # iv          = b'asdfasdf'       # 8 字符 # 部分模式不使用该参数
    c = Cipher(key)
    if mode == 'ecb':        _enc, _dec = c.encrypt_ecb,     c.decrypt_ecb
    if mode == 'ecb_cts':    _enc, _dec = c.encrypt_ecb_cts, c.decrypt_ecb_cts
    if mode == 'cbc':        _enc, _dec = c.encrypt_cbc,     c.decrypt_cbc
    if mode == 'cbc_cts':    _enc, _dec = c.encrypt_cbc_cts, c.decrypt_cbc_cts
    if mode == 'pcbc':       _enc, _dec = c.encrypt_pcbc,    c.decrypt_pcbc
    if mode == 'cfb':        _enc, _dec = c.encrypt_cfb,     c.decrypt_cfb
    if mode == 'ofb':        _enc, _dec = c.encrypt_ofb,     c.decrypt_ofb
    if mode == 'ctr':        _enc, _dec = c.encrypt_ctr,     c.decrypt_ctr;\
                                     iv = ctr_counter(int.from_bytes(iv, "big"), operator.xor)

    plaintext = defunc(plaintext)
    if mode in ('ecb', 'ecb_cts'):
        v = b''.join([i for i in _dec(plaintext)])
    else:
        v = b''.join([i for i in _dec(plaintext, iv)])
    return PKCS7_unpadding(v) 
Example #28
Source File: vector_v6.py    From pythonic-api with MIT License 5 votes vote down vote up
def __hash__(self):
        hashes = (hash(x) for x in self)
        return functools.reduce(operator.xor, hashes, 0) 
Example #29
Source File: thutil.py    From Depth-Map-Prediction with GNU General Public License v3.0 5 votes vote down vote up
def __hash__(self):
        return reduce(operator.xor, map(hash, (type(self), self.msg))) 
Example #30
Source File: pyblowfish.py    From vrequest with MIT License 5 votes vote down vote up
def encrypt(
        key:bytes, 
        plaintext:bytes, 
        iv:bytes=None, 
        mode='ecb', 
        enfunc=base64.b64encode,
    ):
    # 默认强制使用 pkcs7 填充模式
    # key         = b'asdf'           # 4-56 个字符
    # plaintext   = b'asdfasdf'       # 8 字符
    # iv          = b'asdfasdf'       # 8 字符 # 部分模式不使用该参数
    c = Cipher(key)
    if mode == 'ecb':        _enc, _dec = c.encrypt_ecb,     c.decrypt_ecb
    if mode == 'ecb_cts':    _enc, _dec = c.encrypt_ecb_cts, c.decrypt_ecb_cts
    if mode == 'cbc':        _enc, _dec = c.encrypt_cbc,     c.decrypt_cbc
    if mode == 'cbc_cts':    _enc, _dec = c.encrypt_cbc_cts, c.decrypt_cbc_cts
    if mode == 'pcbc':       _enc, _dec = c.encrypt_pcbc,    c.decrypt_pcbc
    if mode == 'cfb':        _enc, _dec = c.encrypt_cfb,     c.decrypt_cfb
    if mode == 'ofb':        _enc, _dec = c.encrypt_ofb,     c.decrypt_ofb
    if mode == 'ctr':        _enc, _dec = c.encrypt_ctr,     c.decrypt_ctr; iv = ctr_counter(int.from_bytes(iv, "big"), operator.xor)

    if mode in ('ecb', 'ecb_cts'):
        v = b''.join([i for i in _enc(PKCS7_padding(plaintext, 8))])
    else:
        v = b''.join([i for i in _enc(PKCS7_padding(plaintext, 8), iv)])
    return enfunc(v)