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__
python类Integral()的实例源码
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
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)
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__
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
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()
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
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()
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()
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
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
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()
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
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
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
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)
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)
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
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
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)
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
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
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))
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))
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
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'])
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)
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
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
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)