Python numbers 模块,Integral() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numbers.Integral()

项目:DropboxConnect    作者:raguay    | 项目源码 | 文件源码
def generic_type_name(v):
    """Return a descriptive type name that isn't Python specific. For example,
    an int value will return 'integer' rather than 'int'."""
    if isinstance(v, numbers.Integral):
        # Must come before real numbers check since integrals are reals too
        return 'integer'
    elif isinstance(v, numbers.Real):
        return 'float'
    elif isinstance(v, (tuple, list)):
        return 'list'
    elif isinstance(v, six.string_types):
        return 'string'
    elif v is None:
        return 'null'
    else:
        return type(v).__name__
项目:DropboxConnect    作者:raguay    | 项目源码 | 文件源码
def __init__(self, min_value=None, max_value=None):
        """
        A more restrictive minimum or maximum value can be specified than the
        range inherent to the defined type.
        """
        if min_value is not None:
            assert isinstance(min_value, numbers.Integral), \
                'min_value must be an integral number'
            assert min_value >= self.minimum, \
                'min_value cannot be less than the minimum value for this ' \
                'type (%d < %d)' % (min_value, self.minimum)
            self.minimum = min_value
        if max_value is not None:
            assert isinstance(max_value, numbers.Integral), \
                'max_value must be an integral number'
            assert max_value <= self.maximum, \
                'max_value cannot be greater than the maximum value for ' \
                'this type (%d < %d)' % (max_value, self.maximum)
            self.maximum = max_value
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if not dec.is_finite():
            # Catches infinities and nans.
            raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def generic_type_name(v):
    """Return a descriptive type name that isn't Python specific. For example,
    an int value will return 'integer' rather than 'int'."""
    if isinstance(v, numbers.Integral):
        # Must come before real numbers check since integrals are reals too
        return 'integer'
    elif isinstance(v, numbers.Real):
        return 'float'
    elif isinstance(v, (tuple, list)):
        return 'list'
    elif isinstance(v, six.string_types):
        return 'string'
    elif v is None:
        return 'null'
    else:
        return type(v).__name__
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def __init__(self, min_value=None, max_value=None):
        """
        A more restrictive minimum or maximum value can be specified than the
        range inherent to the defined type.
        """
        if min_value is not None:
            assert isinstance(min_value, numbers.Integral), \
                'min_value must be an integral number'
            assert min_value >= self.minimum, \
                'min_value cannot be less than the minimum value for this ' \
                'type (%d < %d)' % (min_value, self.minimum)
            self.minimum = min_value
        if max_value is not None:
            assert isinstance(max_value, numbers.Integral), \
                'max_value must be an integral number'
            assert max_value <= self.maximum, \
                'max_value cannot be greater than the maximum value for ' \
                'this type (%d < %d)' % (max_value, self.maximum)
            self.maximum = max_value
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def _convert_header_value(self, value):
        if isinstance(value, bytes):
            pass
        elif isinstance(value, unicode_type):
            value = value.encode('utf-8')
        elif isinstance(value, numbers.Integral):
            # return immediately since we know the converted value will be safe
            return str(value)
        elif isinstance(value, datetime.datetime):
            return httputil.format_timestamp(value)
        else:
            raise TypeError("Unsupported header value %r" % value)
        # If \n is allowed into the header, it is possible to inject
        # additional headers or split the request.
        if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
            raise ValueError("Unsafe header value %r", value)
        return value
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def _convert_header_value(self, value):
        if isinstance(value, bytes):
            pass
        elif isinstance(value, unicode_type):
            value = value.encode('utf-8')
        elif isinstance(value, numbers.Integral):
            # return immediately since we know the converted value will be safe
            return str(value)
        elif isinstance(value, datetime.datetime):
            return httputil.format_timestamp(value)
        else:
            raise TypeError("Unsupported header value %r" % value)
        # If \n is allowed into the header, it is possible to inject
        # additional headers or split the request.
        if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
            raise ValueError("Unsafe header value %r", value)
        return value
项目:abusehelper    作者:Exploit-install    | 项目源码 | 文件源码
def _signal_numbers_to_names():
    signums = {}

    for name, value in inspect.getmembers(signal):
        if not name.startswith("SIG") or name.startswith("SIG_"):
            continue

        if not isinstance(value, numbers.Integral):
            continue

        signums.setdefault(value, []).append(name)

    for signum, names in signums.items():
        signums[signum] = tuple(sorted(names))

    return signums
项目:mau-mau    作者:obestwalter    | 项目源码 | 文件源码
def fetch(self, criterion=None):
        """Fetch one or several cards from the collection.

        * Given (None, 0, 1): fetch first card from the collection
        * Given a specific card: fetch that specific card
        * Given a number > 1: return a list of cards
        :rtype: Card or list of Card
        """
        if not self.cards:
            raise exceptions.NoCardsLeft()

        try:
            if not criterion or criterion == 1:
                return self.cards.pop(0)

            if isinstance(criterion, Integral):
                return [self.cards.pop(i) for i in range(criterion)]

            return self.cards.pop(self.cards.index(criterion))
        except (IndexError, ValueError):
            raise exceptions.CardNotFound()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def std_PTR_qry(msg):
    qs = msg.question
    DEBUGLOG( str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'PTR')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.PTR, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def std_MX_qry(msg):
    qs = msg.question
    DEBUGLOG(str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
    return resp
    #Temporal disable MX responses
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'MX')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.MX, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def std_AAAA_qry(msg):
    if not Forward:
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp
    qs = msg.question
    DEBUGLOG(str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'AAAA')

    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.AAAA, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if not dec.is_finite():
            # Catches infinities and nans.
            raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp)
项目:fold    作者:tensorflow    | 项目源码 | 文件源码
def __new__(cls, dtype=None, shape=None, tag='', tensor=None):
    if tensor is not None:
      if dtype is not None:
        raise TypeError('Specify only one of tensor and dtype.')
      if shape is not None:
        raise TypeError('Specify only one of tensor and shape.')
      dtype = tensor.dtype
      shape = tensor.get_shape().as_list()
    elif not (isinstance(dtype, tf.DType) or
              isinstance(dtype, six.string_types)):
      raise TypeError('%r is not a tf.DType or string' % (dtype,))
    dtype = tf.as_dtype(dtype).base_dtype.name
    if not all(isinstance(s, numbers.Integral) and s >= 0 for s in shape):
      raise TypeError('shape must be non-negative integers: %s' % shape)
    shape = tuple(int(s) for s in shape)
    if not isinstance(tag, six.string_types):
      raise TypeError('A TypeShape tag must be a string; type of %r is %s' %
                      (tag, type(tag)))
    return _TypeShape.__new__(cls, dtype, shape, tag)
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def __init__(self, n_folds, shuffle, random_state):
        if not isinstance(n_folds, numbers.Integral):
            raise ValueError('n_folds must be of Integral type. '
                             '%s of type %s was passed' % (n_folds, type(n_folds)))

        n_folds = int(n_folds)
        if n_folds <= 1:
            raise ValueError('k-fold cross-validation requires at least one '
                             'train/test split by setting n_folds=2 or more')

        if shuffle not in [True, False]:
            raise TypeError('shuffle must be True or False. Got %s (type=%s)'
                            % (str(shuffle), type(shuffle)))

        self.n_folds = n_folds
        self.shuffle = shuffle
        self.random_state = random_state
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def _is_integer(x):
    """Determine whether some object ``x`` is an
    integer type (int, long, etc). This is part of the 
    ``fixes`` module, since Python 3 removes the long
    datatype, we have to check the version major.

    Parameters
    ----------

    x : object
        The item to assess whether is an integer.


    Returns
    -------

    bool
        True if ``x`` is an integer type
    """
    return (not isinstance(x, (bool, np.bool))) and \
        isinstance(x, (numbers.Integral, int, np.int, np.long, long))  # no long type in python 3
项目:Dshield    作者:ywjt    | 项目源码 | 文件源码
def _convert_timestamp(timestamp, precision=None):
    if isinstance(timestamp, Integral):
        return timestamp  # assume precision is correct if timestamp is int
    if isinstance(_get_unicode(timestamp), text_type):
        timestamp = parse(timestamp)
    if isinstance(timestamp, datetime):
        if not timestamp.tzinfo:
            timestamp = UTC.localize(timestamp)
        ns = (timestamp - EPOCH).total_seconds() * 1e9
        if precision is None or precision == 'n':
            return ns
        elif precision == 'u':
            return ns / 1e3
        elif precision == 'ms':
            return ns / 1e6
        elif precision == 's':
            return ns / 1e9
        elif precision == 'm':
            return ns / 1e9 / 60
        elif precision == 'h':
            return ns / 1e9 / 3600
    raise ValueError(timestamp)
项目:specdb    作者:specdb    | 项目源码 | 文件源码
def add_to_flag(cur_flag, add_flag):
    """ Add a bitwise flag to an existing flag

    Parameters
    ----------
    cur_flag : int or ndarray
    add_flag : int

    Returns
    -------
    new_flag : int or ndarray

    """
    if isinstance(cur_flag, numbers.Integral):
        if (cur_flag % add_flag) < (add_flag//2):
            cur_flag += add_flag
        return cur_flag
    else:  # Array
        mods = cur_flag % add_flag
        upd = mods < (add_flag//2)
        cur_flag[upd] += add_flag
        return cur_flag
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def __init__(self, pvals, shape, seed=0):
        if isinstance(shape, numbers.Integral):
            shape = (shape,)
        self.__rng = np.random.RandomState(seed)
        self.nclasses = len(pvals)
        self.shape = shape
        self.size = 1
        for s in shape:
            self.size = self.size * s
        self.As = self.__rng.uniform(-1, 1, (self.size, self.size, self.nclasses,))
        self.bs = self.__rng.uniform(-1, 1, (self.size, self.nclasses,))

        self.accum = []
        s = 0
        for pval in pvals:
            s = s + pval
            self.accum.append(s)
        self.accum[-1] = 2
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def make_pos_axis(length, pos, prefix=POS_AXIS_PREFIX):
    """
    Make positional Axis of length `length` and of position `pos`

    Args:
        length: the length of the Axis, can be None
        pos: position of the Axis

    Example:
        for a tensor of shape (4, 3), it's positional axes are:
        [make_pos_axis(4, 1), make_pos_axis(3, 1)]

    Returns:
        Axis object
    """
    if not (isinstance(pos, numbers.Integral) and pos >= 0):
        raise ValueError("pos {} must be integer greater or equal than zero."
                         .format(pos))
    return ng.make_axis(length, name='%s%s' % (prefix, pos))
项目:sonnet    作者:deepmind    | 项目源码 | 文件源码
def _fill_and_one_pad_stride(stride, n, data_format=DATA_FORMAT_NHWC):
  """Expands the provided stride to size n and pads it with 1s."""
  if isinstance(stride, numbers.Integral) or (
      isinstance(stride, collections.Iterable) and len(stride) <= n):
    if data_format == DATA_FORMAT_NHWC:
      return (1,) + _fill_shape(stride, n) + (1,)
    elif data_format == DATA_FORMAT_NCHW:
      return (1, 1,) + _fill_shape(stride, n)
    else:
      raise ValueError("Invalid data_format {:s}. Allowed formats "
                       "{:s}".format(data_format, SUPPORTED_DATA_FORMATS))

  elif isinstance(stride, collections.Iterable) and len(stride) == n + 2:
    return stride
  else:
    raise base.IncompatibleShapeError(
        "stride is {} ({}), must be either a positive integer or an iterable of"
        " positive integers of size {}".format(stride, type(stride), n))
项目:odoo-rpc-client    作者:katyukha    | 项目源码 | 文件源码
def insert(self, index, item):
        """ Insert record to list

            :param item: Record instance to be inserted into list.
                         if int passed, it considered to be ID of record
            :type item: Record|int
            :param int index: position where to place new element
            :return: self
            :rtype: RecordList
        """
        assert isinstance(item, (Record, numbers.Integral)), \
            "Only Record or int instances could be added to list"
        if isinstance(item, Record):
            self._records.insert(index, item)
        else:
            self._records.insert(index, self._object.read_records(
                item, cache=self._cache))
        return self

    # Overridden to make ability to call methods of object on list of IDs
    # present in this RecordList
项目:odoo-rpc-client    作者:katyukha    | 项目源码 | 文件源码
def test_search_records(self):
        res = self.object.search_records([('id', '=', 1)])
        self.assertIsInstance(res, RecordList)
        self.assertEqual(res.length, 1)
        self.assertEqual(res[0].id, 1)

        res = self.object.search_records([('id', '=', 99999)])
        self.assertIsInstance(res, RecordList)
        self.assertEqual(res.length, 0)

        res = self.object.search_records([('id', '=', 1)], count=1)
        self.assertIsInstance(res, numbers.Integral)
        self.assertEqual(res, 1)

        # test search_records with read_fields argument
        res = self.object.search_records([],
                                         read_fields=['name', 'country_id'],
                                         limit=10)
        self.assertIsInstance(res, RecordList)
        self.assertEqual(res.length, 10)
        self.assertEqual(len(res._lcache), res.length)
        for record in res:
            self.assertEqual(len(record._data), 3)
            self.assertItemsEqual(list(record._data),
                                  ['id', 'name', 'country_id'])
项目:odoo-rpc-client    作者:katyukha    | 项目源码 | 文件源码
def report(self, report_name, model, ids, report_type='pdf', context=None):
        """ Proxy to report service *report* method

            :param str report_name: string representing name of report service
            :param str model: name of model to generate report for
            :param ids: list of object ID to get report for (or just single id)
            :type ids: list of int | int
            :param str report_type: Type of report to generate.
                                    default is 'pdf'.
            :param dict context: Aditional info. Optional.
            :return: ID of report to get by method *report_get*
            :rtype: int
        """
        context = {} if context is None else context
        ids = [ids] if isinstance(ids, numbers.Integral) else ids
        data = self._prepare_report_data(model, ids, report_type)
        return self._service.report(self.client.dbname,
                                    self.client.uid,
                                    self.client._pwd,
                                    report_name,
                                    ids,
                                    data,
                                    context)
项目:mitmAP    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def std_PTR_qry(msg):
    qs = msg.question
    DEBUGLOG( str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'PTR')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.PTR, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:mitmAP    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def std_MX_qry(msg):
    qs = msg.question
    DEBUGLOG(str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
    return resp
    #Temporal disable MX responses
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'MX')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.MX, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types)
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def __init__(self, amount=None, currency=DEFAULT_CURRENCY,
            amount_raw=None):
        if not (amount is None) ^ (amount_raw is None):
            raise ValueError("You must specify an amount or a raw amount")

        if not isinstance(currency, Currency):
            raise TypeError("You must specify a valid Currency")

        if amount is not None:
            if not isinstance(amount, numbers.Real):
                raise TypeError("Amount must be an integer or float")
            amount_raw = int(amount * 10**currency.precision)

        if not isinstance(amount_raw, numbers.Integral):
            raise TypeError("Amount must be an integer or float")

        self.amount_raw = amount_raw
        self.currency = currency
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def __init__(self, amount=None, currency=DEFAULT_CURRENCY,
            amount_raw=None):
        if not (amount is None) ^ (amount_raw is None):
            raise ValueError("You must specify an amount or a raw amount")

        if not isinstance(currency, Currency):
            raise TypeError("You must specify a valid Currency")

        if amount is not None:
            if not isinstance(amount, numbers.Real):
                raise TypeError("Amount must be an integer or float")
            amount_raw = int(amount * 10**currency.precision)

        if not isinstance(amount_raw, numbers.Integral):
            raise TypeError("Amount must be an integer or float")

        self.amount_raw = amount_raw
        self.currency = currency
项目:CommunityCellularManager    作者:facebookincubator    | 项目源码 | 文件源码
def __init__(self, amount=None, currency=DEFAULT_CURRENCY,
            amount_raw=None):
        if not (amount is None) ^ (amount_raw is None):
            raise ValueError("You must specify an amount or a raw amount")

        if not isinstance(currency, Currency):
            raise TypeError("You must specify a valid Currency")

        if amount is not None:
            if not isinstance(amount, numbers.Real):
                raise TypeError("Amount must be an integer or float")
            amount_raw = int(amount * 10**currency.precision)

        if not isinstance(amount_raw, numbers.Integral):
            raise TypeError("Amount must be an integer or float")

        self.amount_raw = amount_raw
        self.currency = currency
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if not dec.is_finite():
            # Catches infinities and nans.
            raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp)
项目:juicer    作者:eubr-bigsea    | 项目源码 | 文件源码
def _number_to_bucket(value, bucket_size):
    result = None
    if isinstance(value, numbers.Integral):
        start = int(math.ceil(value / bucket_size) * bucket_size - 1)
        end = int(math.floor(value / bucket_size) * bucket_size)
        result = [start, end]
    elif isinstance(value, numbers.Real):
        start = float(math.ceil(value / bucket_size) * bucket_size - 1)
        end = float(math.floor(value / bucket_size) * bucket_size)
        result = [start, end]
    elif isinstance(value, basestring):
        # @FIXME Implement
        result = ''
    elif isinstance(value, (datetime.datetime, datetime.date)):
        pass
    return result
项目:hydpy    作者:tyralla    | 项目源码 | 文件源码
def __call__(self, value):
        decimals = pub.options.reprdigits
        if isinstance(value, str):
            if self._preserve_strings:
                return '"%s"' % value
            else:
                return value
        if isinstance(value, (pointerutils.Double, pointerutils.PDouble)):
            value = float(value)
        if ((decimals > -1) and
                isinstance(value, numbers.Real) and
                (not isinstance(value, numbers.Integral))):
            string = '{0:.{1}f}'.format(value, decimals)
            string = string.rstrip('0')
            if string.endswith('.'):
                string += '0'
            return string
        else:
            return repr(value)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if not dec.is_finite():
            # Catches infinities and nans.
            raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if not dec.is_finite():
            # Catches infinities and nans.
            raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp)
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
def test_round(self):
        """
        Note that the Python 2.x round() function fails these tests. The
        Python 3.x round() function passes them, as should our custom
        round() function.
        """
        self.assertEqual(round(0.1250, 2), 0.12)
        self.assertEqual(round(0.1350, 2), 0.14)
        self.assertEqual(round(0.1251, 2), 0.13)
        self.assertEqual(round(0.125000001, 2), 0.13)
        self.assertEqual(round(123.5, 0), 124.0)
        self.assertEqual(round(123.5), 124)
        self.assertEqual(round(12.35, 2), 12.35)
        self.assertEqual(round(12.35, 1), 12.3)
        self.assertEqual(round(12.35, 0), 12.0)
        self.assertEqual(round(123.5, 1), 123.5)

        self.assertTrue(isinstance(round(123.5, 0), float))
        self.assertTrue(isinstance(round(123.5), Integral))
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types)
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
def isint(obj):
    """
    Deprecated. Tests whether an object is a Py3 ``int`` or either a Py2 ``int`` or
    ``long``.

    Instead of using this function, you can use:

        >>> from future.builtins import int
        >>> isinstance(obj, int)

    The following idiom is equivalent:

        >>> from numbers import Integral
        >>> isinstance(obj, Integral)
    """

    return isinstance(obj, numbers.Integral)
项目:mitmAP    作者:xdavidhu    | 项目源码 | 文件源码
def std_PTR_qry(msg):
    qs = msg.question
    DEBUGLOG( str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'PTR')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.PTR, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:mitmAP    作者:xdavidhu    | 项目源码 | 文件源码
def std_MX_qry(msg):
    qs = msg.question
    DEBUGLOG(str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
    return resp
    #Temporal disable MX responses
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'MX')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.MX, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:dask-searchcv    作者:dask    | 项目源码 | 文件源码
def check_cv(cv=3, y=None, classifier=False):
    """Dask aware version of ``sklearn.model_selection.check_cv``

    Same as the scikit-learn version, but works if ``y`` is a dask object.
    """
    if cv is None:
        cv = 3

    # If ``cv`` is not an integer, the scikit-learn implementation doesn't
    # touch the ``y`` object, so passing on a dask object is fine
    if not is_dask_collection(y) or not isinstance(cv, numbers.Integral):
        return model_selection.check_cv(cv, y, classifier)

    if classifier:
        # ``y`` is a dask object. We need to compute the target type
        target_type = delayed(type_of_target, pure=True)(y).compute()
        if target_type in ('binary', 'multiclass'):
            return StratifiedKFold(cv)
    return KFold(cv)
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def __init__(self, date=None, calendar=gregorian, format=None):
        self.calendar = calendar
        if date is None:
            self.ordinal = datetime.date.today().toordinal()
            self.ymd = calendar.ordinal_to_date(self.ordinal)
        elif isinstance(date, Date):
            self.ordinal = date.ordinal
            self.ymd = calendar.ordinal_to_date(self.ordinal)
        elif isinstance(date, datetime.date):
            self.ordinal = date.toordinal()
            self.ymd = calendar.ordinal_to_date(self.ordinal)
        elif isinstance(date, Integral):
            self.ordinal = int(date)
            self.ymd = calendar.ordinal_to_date(self.ordinal)
        elif non_string_sequence(date, Integral) and len(date) == 3:
            self.ymd = YMD(*date)
            if not calendar.validate(self.ymd):
                raise InvalidDate("Invalid {} date: {}".format(calendar.calendar_name, self.ymd))
            self.ordinal = calendar.date_to_ordinal(self.ymd)
        else:
            raise TypeError("Invalid input type for Date")
        self.weekday = calendar.weekday(self.ymd, self.ordinal)
        self.format = format
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
        if not dec.is_finite():
            # Catches infinities and nans.
            raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
        sign, digits, exp = dec.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        else:
            return cls(digits, 10 ** -exp)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def std_PTR_qry(msg):
    qs = msg.question
    DEBUGLOG( str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'PTR')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.PTR, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def std_MX_qry(msg):
    qs = msg.question
    DEBUGLOG(str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
    return resp
    #Temporal disable MX responses
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'MX')
    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.MX, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def std_AAAA_qry(msg):
    if not Forward:
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp
    qs = msg.question
    DEBUGLOG(str(len(qs)) + ' questions.')
    iparpa = qs[0].to_text().split(' ', 1)[0]
    DEBUGLOG('Host: ' + iparpa)
    resp = make_response(qry=msg)
    hosts = respuestas(iparpa[:-1], 'AAAA')

    if isinstance(hosts, numbers.Integral):
        DEBUGLOG('No host....')
        resp = make_response(qry=msg, RCODE=3)  # RCODE =  3    NXDOMAIN
        return resp

    for host in hosts:
        DEBUGLOG('Adding ' + host.to_text())
        rrset = dns.rrset.from_text(iparpa, 1000, dns.rdataclass.IN, dns.rdatatype.AAAA, host.to_text())
        resp.answer.append(rrset)

    return resp
项目:islam-buddy    作者:hamir    | 项目源码 | 文件源码
def no(mytype, argnums=(1,)):
    """
    A shortcut for the disallow_types decorator that disallows only one type
    (in any position in argnums).

    Example use:

    >>> class newstr(object):
    ...     @no('bytes')
    ...     def __add__(self, other):
    ...          pass

    >>> newstr(u'1234') + b'1234'     #doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TypeError: argument can't be bytes

    The object can also be passed directly, but passing the string helps
    to prevent circular import problems.
    """
    if isinstance(argnums, Integral):
        argnums = (argnums,)
    disallowed_types = [mytype] * len(argnums)
    return disallow_types(argnums, disallowed_types)