python类mod()的实例源码

YoutubeCom.py 文件源码 项目:pyload-plugins 作者: pyload 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def __init__(self, code, objects=None):
        self._OPERATORS = [
            ('|', operator.or_),
            ('^', operator.xor),
            ('&', operator.and_),
            ('>>', operator.rshift),
            ('<<', operator.lshift),
            ('-', operator.sub),
            ('+', operator.add),
            ('%', operator.mod),
            ('/', operator.truediv),
            ('*', operator.mul),
        ]
        self._ASSIGN_OPERATORS = [(op + '=', opfunc)
                                  for op, opfunc in self._OPERATORS]
        self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
        self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*'

        if objects is None:
            objects = {}
        self.code = code
        self._functions = {}
        self._objects = objects
PyPtxt.py 文件源码 项目:Pyfhel 作者: ibarrond 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __isub__(self, other):
        if not isinstance(other, (PyPtxt, int)):
            raise TypeError("PyPtxt '-=' error: lhs must be of type PyPtxt or int instead of type " + str(type(other)))
        from operator import sub, mod
        if isinstance(other, PyPtxt):
            self = PyPtxt([mod(elt, self.__pyfhel.getModulus())
                           for elt in
                           list(map(sub, self.getPtxt(), other.getPtxt()))],
                          self.getPyfhel())
        else:
            constPtxt = [other for _ in range(self.__length)]

            self = PyPtxt([mod(elt, self.__pyfhel.getModulus())
                           for elt in
                           list(map(sub, self.getPtxt(), constPtxt))],
                          self.getPyfhel())
            del constPtxt
        return self



    # MULTIPLY:
    # '*' operator
PyPtxt.py 文件源码 项目:Pyfhel 作者: ibarrond 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __imul__(self, other):
        if not isinstance(other, (PyPtxt, int)):
            raise TypeError("PyPtxt '*=' error: lhs must be of type PyPtxt or int instead of type " + str(type(other)))
        from operator import mul, mod
        if isinstance(other, PyPtxt):
            self = PyPtxt([mod(elt, self.__pyfhel.getModulus())
                           for elt in
                           list(map(mul, self.getPtxt(), other.getPtxt()))],
                          self.getPyfhel())
        else:
            constPtxt = [other for _ in range(self.__length)]
            self = PyPtxt([mod(elt, self.__pyfhel.getModulus())
                           for elt in
                           list(map(mul, self.getPtxt(), constPtxt))],
                          self.getPyfhel())
            del constPtxt
        return self



    # SCALAR PRODUCT:
    # '%' operator
pycalcal.py 文件源码 项目:calendars 作者: tdongsi 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def easter(g_year):
    """Return fixed date of Easter in Gregorian year g_year."""
    century = quotient(g_year, 100) + 1
    shifted_epact = mod(14 +
                        11 * mod(g_year, 19) -
                        quotient(3 * century, 4) +
                        quotient(5 + (8 * century), 25), 30)
    adjusted_epact = ((shifted_epact + 1)
                      if ((shifted_epact == 0) or ((shifted_epact == 1) and
                                                  (10 < mod(g_year, 19))))
                      else  shifted_epact)
    paschal_moon = (fixed_from_gregorian(gregorian_date(g_year, APRIL, 19)) -
                    adjusted_epact)
    return kday_after(SUNDAY, paschal_moon)

# see lines 1429-1431 in calendrica-3.0.cl
pycalcal.py 文件源码 项目:calendars 作者: tdongsi 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def standard_from_sundial(tee, location):
    """Return standard time of temporal moment, tee, at location, location.
    Return BOGUS if temporal hour is undefined that day."""
    date = fixed_from_moment(tee)
    hour = 24 * mod(tee, 1)
    if (6 <= hour <= 18):
        h = daytime_temporal_hour(date, location)
    elif (hour < 6):
        h = nighttime_temporal_hour(date - 1, location)
    else:
        h = nighttime_temporal_hour(date, location)

    # return
    if (h == BOGUS):
        return BOGUS
    elif (6 <= hour <= 18):
        return sunrise(date, location) + ((hour - 6) * h)
    elif (hour < 6):
        return sunset(date - 1, location) + ((hour + 6) * h)
    else:
        return sunset(date, location) + ((hour - 18) * h)


# see lines 3075-3079 in calendrica-3.0.cl
pycalcal.py 文件源码 项目:calendars 作者: tdongsi 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def lunar_phase(tee):
    """Return the lunar phase, as an angle in degrees, at moment tee.
    An angle of 0 means a new moon, 90 degrees means the
    first quarter, 180 means a full moon, and 270 degrees
    means the last quarter."""
    phi = mod(lunar_longitude(tee) - solar_longitude(tee), 360)
    t0 = nth_new_moon(0)
    n = iround((tee - t0) / MEAN_SYNODIC_MONTH)
    phi_prime = (deg(360) *
                 mod((tee - nth_new_moon(n)) / MEAN_SYNODIC_MONTH, 1))
    if abs(phi - phi_prime) > deg(180):
        return phi_prime
    else:
        return phi


# see lines 3615-3625 in calendrica-3.0.cl
pycalcal.py 文件源码 项目:calendars 作者: tdongsi 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def fixed_from_arithmetic_persian(p_date):
    """Return fixed date equivalent to Persian date p_date."""
    day    = standard_day(p_date)
    month  = standard_month(p_date)
    p_year = standard_year(p_date)
    y      = (p_year - 474) if (0 < p_year) else (p_year - 473)
    year   = mod(y, 2820) + 474
    temp   = (31 * (month - 1)) if (month <= 7) else ((30 * (month - 1)) + 6)

    return ((PERSIAN_EPOCH - 1)
            + (1029983 * quotient(y, 2820))
            + (365 * (year - 1))
            + quotient((31 * year) - 5, 128)
            + temp
            + day)

# see lines 3960-3986 in calendrica-3.0.cl
pycalcal.py 文件源码 项目:calendars 作者: tdongsi 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def fixed_from_tibetan(t_date):
    """Return the fixed date corresponding to Tibetan lunar date, t_date."""
    year       = tibetan_year(t_date)
    month      = tibetan_month(t_date)
    leap_month = tibetan_leap_month(t_date)
    day        = tibetan_day(t_date)
    leap_day   = tibetan_leap_day(t_date)
    months = ifloor((804/65 * (year - 1)) +
                   (67/65 * month) +
                   (-1 if leap_month else 0) +
                   64/65)
    days = (30 * months) + day
    mean = ((days * 11135/11312) -30 +
            (0 if leap_day else -1) +
            1071/1616)
    solar_anomaly = mod((days * 13/4824) + 2117/4824, 1)
    lunar_anomaly = mod((days * 3781/105840) +
                        2837/15120, 1)
    sun  = -tibetan_sun_equation(12 * solar_anomaly)
    moon = tibetan_moon_equation(28 * lunar_anomaly)
    return ifloor(TIBETAN_EPOCH + mean + sun + moon)


# see lines 5757-5796 in calendrica-3.0.cl
test_scalarmath.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_modulus_basic(self):
        dt = np.typecodes['AllInteger'] + np.typecodes['Float']
        for dt1, dt2 in itertools.product(dt, dt):
            for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
                if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']:
                    continue
                if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']:
                    continue
                fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
                msg = fmt % (dt1, dt2, sg1, sg2)
                a = np.array(sg1*71, dtype=dt1)[()]
                b = np.array(sg2*19, dtype=dt2)[()]
                div = self.floordiv(a, b)
                rem = self.mod(a, b)
                assert_equal(div*b + rem, a, err_msg=msg)
                if sg2 == -1:
                    assert_(b < rem <= 0, msg)
                else:
                    assert_(b > rem >= 0, msg)
test_scalarmath.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def test_float_modulus_roundoff(self):
        # gh-6127
        dt = np.typecodes['Float']
        for dt1, dt2 in itertools.product(dt, dt):
            for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
                fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
                msg = fmt % (dt1, dt2, sg1, sg2)
                a = np.array(sg1*78*6e-8, dtype=dt1)[()]
                b = np.array(sg2*6e-8, dtype=dt2)[()]
                div = self.floordiv(a, b)
                rem = self.mod(a, b)
                # Equal assertion should hold when fmod is used
                assert_equal(div*b + rem, a, err_msg=msg)
                if sg2 == -1:
                    assert_(b < rem <= 0, msg)
                else:
                    assert_(b > rem >= 0, msg)
test_classes.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def check_mod(Poly):
    # This checks commutation, not numerical correctness
    c1 = list(random((4,)) + .5)
    c2 = list(random((3,)) + .5)
    c3 = list(random((2,)) + .5)
    p1 = Poly(c1)
    p2 = Poly(c2)
    p3 = Poly(c3)
    p4 = p1 * p2 + p3
    c4 = list(p4.coef)
    assert_poly_almost_equal(p4 % p2, p3)
    assert_poly_almost_equal(p4 % c2, p3)
    assert_poly_almost_equal(c4 % p2, p3)
    assert_poly_almost_equal(p4 % tuple(c2), p3)
    assert_poly_almost_equal(tuple(c4) % p2, p3)
    assert_poly_almost_equal(p4 % np.array(c2), p3)
    assert_poly_almost_equal(np.array(c4) % p2, p3)
    assert_poly_almost_equal(2 % p2, Poly([2]))
    assert_poly_almost_equal(p2 % 2, Poly([0]))
    assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1))
    assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1))
    if Poly is Polynomial:
        assert_raises(TypeError, op.mod, p1, Chebyshev([0]))
    else:
        assert_raises(TypeError, op.mod, p1, Polynomial([0]))
myhdlpeek.py 文件源码 项目:myhdlpeek 作者: xesscorp 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __mod__(self, trc):
        return self.apply_op2(trc, operator.mod)
color_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_mod (self):
        c1 = pygame.Color (0xFFFFFFFF)
        self.assertEquals (c1.r, 255)
        self.assertEquals (c1.g, 255)
        self.assertEquals (c1.b, 255)
        self.assertEquals (c1.a, 255)

        c2 = pygame.Color (2, 4, 8, 16)
        self.assertEquals (c2.r, 2)
        self.assertEquals (c2.g, 4)
        self.assertEquals (c2.b, 8)
        self.assertEquals (c2.a, 16)

        c3 = c1 % c2
        self.assertEquals (c3.r, 1)
        self.assertEquals (c3.g, 3)
        self.assertEquals (c3.b, 7)
        self.assertEquals (c3.a, 15)

        # Issue #286: Is type checking done for Python 3.x?
        self.assertRaises (TypeError, operator.mod, c1, None)
        self.assertRaises (TypeError, operator.mod, None, c1)

        # Division by zero check
        dividend = pygame.Color (255, 255, 255, 255)
        for i in range (4):
            divisor = pygame.Color (64, 64, 64, 64)
            divisor[i] = 0
            quotient = pygame.Color (63, 63, 63, 63)
            quotient[i] = 0
            self.assertEqual (dividend % divisor, quotient)
Functions.py 文件源码 项目:turtle 作者: icse-turtle 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def module(self, *args):
        if not len(args) > 1:
            raise EvaluateException('% requires at least 2 parameters!' + ' (' + str(len(args)) + ' given).')

        elif False in [isinstance(x, NumberType) for x in args]:
            raise EvaluateException('% requires all parameters to be numbers!')

        elif 0 in [x.content for x in args[1:]]:
            raise EvaluateException('module by zero!')

        return reduce(op.mod, args[1:], args[0])
test_quantity.py 文件源码 项目:deb-python-pint 作者: openstack 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _test_quantity_mod(self, unit, func):
        a = self.Q_('10*meter')
        b = self.Q_('3*second')
        self.assertRaises(DimensionalityError, op.mod, a, b)
        self.assertRaises(DimensionalityError, op.mod, 3, b)
        self.assertRaises(DimensionalityError, op.mod, a, 3)
        self.assertRaises(DimensionalityError, op.imod, a, b)
        self.assertRaises(DimensionalityError, op.imod, 3, b)
        self.assertRaises(DimensionalityError, op.imod, a, 3)
        func(op.mod, unit * 10.0, '4.2*meter/meter', 1.6, unit)
test_scalarmath.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_float_modulus_exact(self):
        # test that float results are exact for small integers. This also
        # holds for the same integers scaled by powers of two.
        nlst = list(range(-127, 0))
        plst = list(range(1, 128))
        dividend = nlst + [0] + plst
        divisor = nlst + plst
        arg = list(itertools.product(dividend, divisor))
        tgt = list(divmod(*t) for t in arg)

        a, b = np.array(arg, dtype=int).T
        # convert exact integer results from Python to float so that
        # signed zero can be used, it is checked.
        tgtdiv, tgtrem = np.array(tgt, dtype=float).T
        tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
        tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)

        for dt in np.typecodes['Float']:
            msg = 'dtype: %s' % (dt,)
            fa = a.astype(dt)
            fb = b.astype(dt)
            # use list comprehension so a_ and b_ are scalars
            div = [self.floordiv(a_, b_) for  a_, b_ in zip(fa, fb)]
            rem = [self.mod(a_, b_) for a_, b_ in zip(fa, fb)]
            assert_equal(div, tgtdiv, err_msg=msg)
            assert_equal(rem, tgtrem, err_msg=msg)
test_scalarmath.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_float_modulus_corner_cases(self):
        # Check remainder magnitude.
        for dt in np.typecodes['Float']:
            b = np.array(1.0, dtype=dt)
            a = np.nextafter(np.array(0.0, dtype=dt), -b)
            rem = self.mod(a, b)
            assert_(rem <= b, 'dt: %s' % dt)
            rem = self.mod(-a, -b)
            assert_(rem >= -b, 'dt: %s' % dt)

        # Check nans, inf
        with warnings.catch_warnings():
            warnings.simplefilter('always')
            warnings.simplefilter('ignore', RuntimeWarning)
            for dt in np.typecodes['Float']:
                fone = np.array(1.0, dtype=dt)
                fzer = np.array(0.0, dtype=dt)
                finf = np.array(np.inf, dtype=dt)
                fnan = np.array(np.nan, dtype=dt)
                rem = self.mod(fone, fzer)
                assert_(np.isnan(rem), 'dt: %s' % dt)
                # MSVC 2008 returns NaN here, so disable the check.
                #rem = self.mod(fone, finf)
                #assert_(rem == fone, 'dt: %s' % dt)
                rem = self.mod(fone, fnan)
                assert_(np.isnan(rem), 'dt: %s' % dt)
                rem = self.mod(finf, fone)
                assert_(np.isnan(rem), 'dt: %s' % dt)
test_ndarray_elementwise_op.py 文件源码 项目:cupy 作者: cupy 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_mod_scalar(self):
        with testing.NumpyError(divide='ignore', invalid='ignore'):
            self.check_array_scalar_op(operator.mod)
test_ndarray_elementwise_op.py 文件源码 项目:cupy 作者: cupy 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_rmod_scalar(self):
        with testing.NumpyError(divide='ignore', invalid='ignore'):
            self.check_array_scalar_op(operator.mod, swap=True)
test_ndarray_elementwise_op.py 文件源码 项目:cupy 作者: cupy 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_mod_scalarzero(self):
        with testing.NumpyError(divide='ignore', invalid='ignore'):
            self.check_array_scalarzero_op(operator.mod)


问题


面经


文章

微信
公众号

扫码关注公众号