def build_binary_op(self, op, other):
"""
Compute new expression strings and a new inputs tuple for combining
self and other with a binary operator.
"""
if isinstance(other, NumericalExpression):
self_expr, other_expr, new_inputs = self._merge_expressions(other)
elif isinstance(other, Term):
self_expr = self._expr
new_inputs, other_idx = _ensure_element(self.inputs, other)
other_expr = "x_%d" % other_idx
elif isinstance(other, Number):
self_expr = self._expr
other_expr = str(other)
new_inputs = self.inputs
else:
raise BadBinaryOperator(op, other)
return self_expr, other_expr, new_inputs
python类Number()的实例源码
def coerce_numbers_to_my_dtype(f):
"""
A decorator for methods whose signature is f(self, other) that coerces
``other`` to ``self.dtype``.
This is used to make comparison operations between numbers and `Factor`
instances work independently of whether the user supplies a float or
integer literal.
For example, if I write::
my_filter = my_factor > 3
my_factor probably has dtype float64, but 3 is an int, so we want to coerce
to float64 before doing the comparison.
"""
@wraps(f)
def method(self, other):
if isinstance(other, Number):
other = coerce_to_dtype(self.dtype, other)
return f(self, other)
return method
def quantiles(self, bins, mask=NotSpecified):
"""
Construct a Classifier computing quantiles of the output of ``self``.
Every non-NaN data point the output is labelled with an integer value
from 0 to (bins - 1). NaNs are labelled with -1.
If ``mask`` is supplied, ignore data points in locations for which
``mask`` produces False, and emit a label of -1 at those locations.
Parameters
----------
bins : int
Number of bins labels to compute.
mask : zipline.pipeline.Filter, optional
Mask of values to ignore when computing quantiles.
Returns
-------
quantiles : zipline.pipeline.classifiers.Quantiles
A Classifier producing integer labels ranging from 0 to (bins - 1).
"""
if mask is NotSpecified:
mask = self.mask
return Quantiles(inputs=(self,), bins=bins, mask=mask)
def bottom(self, N, mask=NotSpecified):
"""
Construct a Filter matching the bottom N asset values of self each day.
Parameters
----------
N : int
Number of assets passing the returned filter each day.
mask : zipline.pipeline.Filter, optional
A Filter representing assets to consider when computing ranks.
If mask is supplied, bottom values are computed ignoring any
asset/date pairs for which `mask` produces a value of False.
Returns
-------
filter : zipline.pipeline.Filter
"""
return self.rank(ascending=True, mask=mask) <= N
def version_range(version):
"""\
Returns the version range for the provided version. This applies to QR Code
versions, only.
:param int version: The QR Code version (1 .. 40)
:rtype: int
"""
# ISO/IEC 18004:2015(E)
# Table 3 — Number of bits in character count indicator for QR Code (page 23)
if 0 < version < 10:
return consts.VERSION_RANGE_01_09
elif 9 < version < 27:
return consts.VERSION_RANGE_10_26
elif 26 < version < 41:
return consts.VERSION_RANGE_27_40
raise VersionError('Unknown version "{0}"'.format(version))
def _getink(self, ink, fill=None):
if ink is None and fill is None:
if self.fill:
fill = self.ink
else:
ink = self.ink
else:
if ink is not None:
if isStringType(ink):
ink = ImageColor.getcolor(ink, self.mode)
if self.palette and not isinstance(ink, numbers.Number):
ink = self.palette.getcolor(ink)
ink = self.draw.draw_ink(ink, self.mode)
if fill is not None:
if isStringType(fill):
fill = ImageColor.getcolor(fill, self.mode)
if self.palette and not isinstance(fill, numbers.Number):
fill = self.palette.getcolor(fill)
fill = self.draw.draw_ink(fill, self.mode)
return ink, fill
##
# Draw an arc.
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
return c, 0.0
if a is stub and b == "__add__" and isinstance(c, numbers.Number):
return 1.0, c
except TypeError:
pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
d == "__add__" and isinstance(e, numbers.Number)):
return c, e
except TypeError:
pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
def __imul__(self, other):
"""
>>> g = GlyphCoordinates([(1,2)])
>>> g *= (2,.5)
>>> g *= 2
>>> g
GlyphCoordinates([(4.0, 2.0)])
>>> g = GlyphCoordinates([(1,2)])
>>> g *= 2
>>> g
GlyphCoordinates([(2, 4)])
"""
if isinstance(other, Number):
other = (other, other)
if isinstance(other, tuple):
if other == (1,1):
return self
assert len(other) == 2
self.scale(other)
return self
return NotImplemented
def __itruediv__(self, other):
"""
>>> g = GlyphCoordinates([(1,3)])
>>> g /= (.5,1.5)
>>> g /= 2
>>> g
GlyphCoordinates([(1.0, 1.0)])
"""
if isinstance(other, Number):
other = (other, other)
if isinstance(other, tuple):
if other == (1,1):
return self
assert len(other) == 2
self.scale((1./other[0],1./other[1]))
return self
return NotImplemented
def _getink(self, ink, fill=None):
if ink is None and fill is None:
if self.fill:
fill = self.ink
else:
ink = self.ink
else:
if ink is not None:
if isStringType(ink):
ink = ImageColor.getcolor(ink, self.mode)
if self.palette and not isinstance(ink, numbers.Number):
ink = self.palette.getcolor(ink)
ink = self.draw.draw_ink(ink, self.mode)
if fill is not None:
if isStringType(fill):
fill = ImageColor.getcolor(fill, self.mode)
if self.palette and not isinstance(fill, numbers.Number):
fill = self.palette.getcolor(fill)
fill = self.draw.draw_ink(fill, self.mode)
return ink, fill
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
return c, 0.0
if a is stub and b == "__add__" and isinstance(c, numbers.Number):
return 1.0, c
except TypeError:
pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
d == "__add__" and isinstance(e, numbers.Number)):
return c, e
except TypeError:
pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
def __mul__(self, mult):
"""Multiply the point by a scalar.
Parameters
----------
mult : float
The number by which to multiply the Point.
Returns
-------
:obj:`Point3D`
A 3D point created by the multiplication.
Raises
------
ValueError
If mult is not a scalar value.
"""
if isinstance(mult, numbers.Number):
return Point(mult * self._data, self._frame)
raise ValueError('Type %s not supported. Only scalar multiplication is supported' %(type(mult)))
def __div__(self, div):
"""Divide the point by a scalar.
Parameters
----------
div : float
The number by which to divide the Point.
Returns
-------
:obj:`Point3D`
A 3D point created by the division.
Raises
------
ValueError
If div is not a scalar value.
"""
if not isinstance(div, numbers.Number):
raise ValueError('Type %s not supported. Only scalar division is supported' %(type(div)))
return self.__mul__(1.0 / div)
def __mul__(self, mult):
"""Multiply each point in the cloud by a scalar.
Parameters
----------
mult : float
The number by which to multiply the PointCloud.
Returns
-------
:obj:`PointCloud`
A PointCloud created by the multiplication.
Raises
------
ValueError
If mult is not a scalar value.
"""
if isinstance(mult, numbers.Number):
return PointCloud(mult * self._data, self._frame)
raise ValueError('Type %s not supported. Only scalar multiplication is supported' %(type(mult)))
def __div__(self, div):
"""Divide each point in the cloud by a scalar.
Parameters
----------
div : float
The number by which to divide the PointCloud.
Returns
-------
:obj:`PointCloud`
A PointCloud created by the division.
Raises
------
ValueError
If div is not a scalar value.
"""
if not isinstance(div, numbers.Number):
raise ValueError('Type %s not supported. Only scalar division is supported' %(type(div)))
return self.__mul__(1.0 / div)
def _render_node(self, node):
"""
Renders a node. Recursive callee for node rendering.
:param node: the representation of a node (dependent of rendered data structure)
:return: node id of created node
"""
if isinstance(node, (str, numbers.Number)) or node is None:
node_id = uuid()
else:
node_id = id(node)
node_id = str(node_id)
if node_id not in self._rendered:
self._rendered.add(node_id)
if isinstance(node, dict):
self._render_dict(node, node_id)
elif isinstance(node, list):
self._render_list(node, node_id)
else:
self._graph.node(node_id, label=self._escape_label(self._shorten_label(repr(node))))
return node_id
def set_ibasset(self, ibasset):
"""Set interbank assets.
Interbank assets are represented as a sequence of 2-tuples whose first
element is a `Bank` object (the borrower) and whose second element is
the face value of the interbank asset.
Parameters:
ibasset (sequence of tuples (`Bank`, float)): interbank assets.
"""
if not isinstance(ibasset, (list, tuple)):
raise TypeError
for item in ibasset:
if not isinstance(item, (list, tuple)):
raise TypeError
else:
if (not isinstance(item[0], Bank)) or (not isinstance(item[1], numbers.Number)):
raise TypeError
self.ibasset = ibasset
self.equity = self.get_naiveequity()
def rescale_exchange(exc, value, remove_uncertainty=True):
"""Dummy function to rescale exchange amount and uncertainty.
This depends on some code being separated from Ocelot, which will take a bit of time.
* ``exc`` is an exchange dataset.
* ``value`` is a number, to be multiplied by the existing amount.
* ``remove_uncertainty``: Remove (unscaled) uncertainty data, default is ``True``.
Returns the modified exchange."""
assert isinstance(exc, dict), "Must pass exchange dictionary"
assert isinstance(value, Number), "Constant factor ``value`` must be a number"
exc['amount'] *= value
FIELDS = ('shape', 'size', 'minimum', 'maximum')
if remove_uncertainty:
exc['uncertainty type'] = 0
exc['loc'] = exc['amount']
for field in FIELDS:
if field in exc:
del exc[field]
return exc
def _getink(self, ink, fill=None):
if ink is None and fill is None:
if self.fill:
fill = self.ink
else:
ink = self.ink
else:
if ink is not None:
if isStringType(ink):
ink = ImageColor.getcolor(ink, self.mode)
if self.palette and not isinstance(ink, numbers.Number):
ink = self.palette.getcolor(ink)
ink = self.draw.draw_ink(ink, self.mode)
if fill is not None:
if isStringType(fill):
fill = ImageColor.getcolor(fill, self.mode)
if self.palette and not isinstance(fill, numbers.Number):
fill = self.palette.getcolor(fill)
fill = self.draw.draw_ink(fill, self.mode)
return ink, fill
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
return c, 0.0
if a is stub and b == "__add__" and isinstance(c, numbers.Number):
return 1.0, c
except TypeError:
pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
d == "__add__" and isinstance(e, numbers.Number)):
return c, e
except TypeError:
pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
def logfmt_key(self, k):
if isinstance(k, bytes):
k = k.decode('utf8')
if isinstance(k, str):
k = k.replace(' ', '_').replace('.', '_').replace('=', '_')
k = self.safe_string(k, self.MAX_KEY_SIZE, self.TRUNCATED_KEY)
# TODO: look at measuring perf of this
# ' ' and = are replaced because they're are not valid logfmt
# . is replaced because elasticsearch can't do keys with . in
elif isinstance(k, bool):
# need to do this here, as bool are also numbers
return None
elif isinstance(k, numbers.Number):
k = str(k)
else:
return None
return k
def sync(self, method):
self.setHorizontalHeaderLabels(self.HEADERS)
method = bw.Method(method)
data = method.load()
self.setRowCount(len(data))
for row, obj in enumerate(data):
key, amount = obj[:2]
flow = bw.get_activity(key)
if isinstance(amount, numbers.Number):
uncertain = "False"
else:
uncertain = "True"
amount = amount['amount']
self.setItem(row, 0, ABTableItem(flow['name'], key=key))
self.setItem(row, 1, ABTableItem("{:.6g}".format(amount), key=key))
self.setItem(row, 2, ABTableItem(flow.get('unit', 'Unknown'), key=key))
self.setItem(row, 3, ABTableItem(str(uncertain), key=key))
def __init__(self, name,
type=None,
required=False, min=None, max=None,
regex=None, logic=None, default=None):
"""
:param name ?????????????
:param required ???True?????????
:param min ?????????????????(???????)?
?????(numbers.Number??)??????????(???????)
:param max ??
:param regex ????
:param type ???????????????
:param logic ??????????????????????????????????
?????????True?False????????????????????
?????????????None
:param default ??????
"""
pass
def _query_len(self):
"""influxdb only counts non-null values, so we return the count of the field with maximum non-null values"""
q = u'SELECT COUNT(*) FROM "{}" {} {}'.format(
self.measurement_name,
self._where_expression(),
self._groupby_expression()
).strip()
self.container.client.switch_database(self.db_name)
logger.info('Querying InfluxDB: {}'.format(q))
rs = self.container.client.query(q)
interval_list = list(rs.get_points())
if request and request.args.get('aggregate'):
max_count = len(interval_list)
else:
max_count = max(val for val in rs.get_points().next().values() if isinstance(val, numbers.Number))
self._influxdb_len = max_count
return max_count
def add(self, output, target):
if torch.is_tensor(output):
output = output.cpu().squeeze().numpy()
if torch.is_tensor(target):
target = target.cpu().squeeze().numpy()
elif isinstance(target, numbers.Number):
target = np.asarray([target])
assert np.ndim(output) == 1, \
'wrong output size (1D expected)'
assert np.ndim(target) == 1, \
'wrong target size (1D expected)'
assert output.shape[0] == target.shape[0], \
'number of outputs and targets does not match'
assert np.all(np.add(np.equal(target, 1), np.equal(target, 0))), \
'targets should be binary (0, 1)'
self.scores = np.append(self.scores, output)
self.targets = np.append(self.targets, target)
def _getink(self, ink, fill=None):
if ink is None and fill is None:
if self.fill:
fill = self.ink
else:
ink = self.ink
else:
if ink is not None:
if isStringType(ink):
ink = ImageColor.getcolor(ink, self.mode)
if self.palette and not isinstance(ink, numbers.Number):
ink = self.palette.getcolor(ink)
ink = self.draw.draw_ink(ink, self.mode)
if fill is not None:
if isStringType(fill):
fill = ImageColor.getcolor(fill, self.mode)
if self.palette and not isinstance(fill, numbers.Number):
fill = self.palette.getcolor(fill)
fill = self.draw.draw_ink(fill, self.mode)
return ink, fill
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
return c, 0.0
if a is stub and b == "__add__" and isinstance(c, numbers.Number):
return 1.0, c
except TypeError:
pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
d == "__add__" and isinstance(e, numbers.Number)):
return c, e
except TypeError:
pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
def __init__(self, target):
self.error_dict = {}
self._data = {}
for field in self.fields:
self._data[field] = target.get(field)
for field in self.defaults:
if not target.get(field):
self._data[field] = self.defaults[field]
for field in self.required_fields:
if not self._data.get(field) and not isinstance(self._data.get(field), Number):
self.error_dict[field] = ['This field is required']
self.validate()
def _validate_X_predict(
self, X: np.ndarray, check_input: bool) -> np.ndarray:
if check_input:
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
if issparse(X) and (X.indices.dtype != np.intc or
X.indptr.dtype != np.intc):
raise ValueError(
"No support for np.int64 index based sparse matrices")
n_features = X.shape[1]
if self.n_features_ != n_features:
raise ValueError(
"Number of features of the model must match the input."
" Model n_features is %s and input n_features is %s "
% (self.n_features_, n_features))
return X
def _getink(self, ink, fill=None):
if ink is None and fill is None:
if self.fill:
fill = self.ink
else:
ink = self.ink
else:
if ink is not None:
if isStringType(ink):
ink = ImageColor.getcolor(ink, self.mode)
if self.palette and not isinstance(ink, numbers.Number):
ink = self.palette.getcolor(ink)
ink = self.draw.draw_ink(ink, self.mode)
if fill is not None:
if isStringType(fill):
fill = ImageColor.getcolor(fill, self.mode)
if self.palette and not isinstance(fill, numbers.Number):
fill = self.palette.getcolor(fill)
fill = self.draw.draw_ink(fill, self.mode)
return ink, fill
##
# Draw an arc.