本文整理匯總了Python中six.integer_types方法的典型用法代碼示例。如果您正苦於以下問題:Python six.integer_types方法的具體用法?Python six.integer_types怎麽用?Python six.integer_types使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類six
的用法示例。
在下文中一共展示了six.integer_types方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: to_example
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def to_example(dictionary):
"""Helper: build tf.Example from (string -> int/float/str list) dictionary."""
features = {}
for (k, v) in six.iteritems(dictionary):
if not v:
raise ValueError("Empty generated field: %s" % str((k, v)))
if isinstance(v[0], six.integer_types):
features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v))
elif isinstance(v[0], float):
features[k] = tf.train.Feature(float_list=tf.train.FloatList(value=v))
elif isinstance(v[0], six.string_types):
if not six.PY2: # Convert in python 3.
v = [bytes(x, "utf-8") for x in v]
features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
elif isinstance(v[0], bytes):
features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
else:
raise ValueError("Value for %s is not a recognized type; v: %s type: %s" %
(k, str(v[0]), str(type(v[0]))))
return tf.train.Example(features=tf.train.Features(feature=features))
示例2: _check_len
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def _check_len(self, node):
inferred = _safe_infer_call_result(node, node)
if not inferred or inferred is astroid.Uninferable:
return
if (isinstance(inferred, astroid.Instance)
and inferred.name == 'int'
and not isinstance(inferred, astroid.Const)):
# Assume it's good enough, since the int() call might wrap
# something that's uninferable for us
return
if not isinstance(inferred, astroid.Const):
self.add_message('invalid-length-returned', node=node)
return
value = inferred.value
if not isinstance(value, six.integer_types) or value < 0:
self.add_message('invalid-length-returned', node=node)
示例3: _render_parts
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def _render_parts(self, value, parts=None):
if not parts:
parts = []
if isinstance(value, six.string_types):
parts.append(utils.xhtml_escape(value))
elif isinstance(value, six.integer_types):
parts.append(str(value))
elif isinstance(value, datetime.datetime):
parts.append(value.strftime("%Y-%m-%dT%H:%M:%S.000Z"))
elif isinstance(value, dict):
for name, subvalue in value.items():
if not isinstance(subvalue, list):
subvalue = [subvalue]
for subsubvalue in subvalue:
parts.append('<' + name + '>')
self._render_parts(subsubvalue, parts)
parts.append('</' + name + '>')
else:
raise Exception("Unknown S3 value type %r", value)
示例4: _dense_inner_flatten
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def _dense_inner_flatten(inputs, new_rank):
"""Helper function for `inner_flatten`."""
rank_assertion = check_ops.assert_rank_at_least(
inputs, new_rank, message='inputs has rank less than new_rank')
with ops.control_dependencies([rank_assertion]):
outer_dimensions = array_ops.strided_slice(
array_ops.shape(inputs), [0], [new_rank - 1])
new_shape = array_ops.concat((outer_dimensions, [-1]), 0)
reshaped = array_ops.reshape(inputs, new_shape)
# if `new_rank` is an integer, try to calculate new shape.
if isinstance(new_rank, six.integer_types):
static_shape = inputs.get_shape()
if static_shape is not None and static_shape.dims is not None:
static_shape = static_shape.as_list()
static_outer_dims = static_shape[:new_rank - 1]
static_inner_dims = static_shape[new_rank - 1:]
flattened_dimension = 1
for inner_dim in static_inner_dims:
if inner_dim is None:
flattened_dimension = None
break
flattened_dimension *= inner_dim
reshaped.set_shape(static_outer_dims + [flattened_dimension])
return reshaped
示例5: _convert_to_native_type
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def _convert_to_native_type(self, value):
if isinstance(value, list):
return [self._convert_to_native_type(x) for x in value]
elif isinstance(value, SudsObject):
d = {}
for attr_name, attr_value in value:
d[attr_name] = self._convert_to_native_type(attr_value)
return d
elif isinstance(value, six.string_types):
# This handles suds.sax.text.Text as well, as it derives from
# unicode.
if PY2:
return str(value.encode('utf-8'))
else:
return str(value)
elif isinstance(value, six.integer_types):
return int(value)
return value
示例6: cmp
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def cmp(self, other, abs_vals=False):
if isinstance(other, six.integer_types):
if (other < 0 and abs_vals):
other = abs(other)
if 0 <= other <= MAXUINT64:
return self._c_size.cmp_bytes(other, abs_vals)
else:
other = SizeStruct.new_from_str(str(other))
elif isinstance(other, (Decimal, float)):
other = SizeStruct.new_from_str(str(other))
elif isinstance(other, Size):
other = other._c_size
elif other is None:
return 1
return self._c_size.cmp(other, abs_vals)
## INTERNAL METHODS ##
示例7: _get_kind_name
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def _get_kind_name(item):
"""Returns the kind name in CollectionDef.
Args:
item: A data item.
Returns:
The string representation of the kind in CollectionDef.
"""
if isinstance(item, (six.string_types, six.binary_type)):
kind = "bytes_list"
elif isinstance(item, six.integer_types):
kind = "int64_list"
elif isinstance(item, float):
kind = "float_list"
elif isinstance(item, Any):
kind = "any_list"
else:
kind = "node_list"
return kind
示例8: to_example
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def to_example(dictionary):
"""Helper: build tf.Example from (string -> int/float/str list) dictionary."""
features = {}
for (k, v) in six.iteritems(dictionary):
if not v:
raise ValueError("Empty generated field: %s" % str((k, v)))
# Subtly in PY2 vs PY3, map is not scriptable in py3. As a result,
# map objects will fail with TypeError, unless converted to a list.
if six.PY3 and isinstance(v, map):
v = list(v)
if (isinstance(v[0], six.integer_types) or
np.issubdtype(type(v[0]), np.integer)):
features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v))
elif isinstance(v[0], float):
features[k] = tf.train.Feature(float_list=tf.train.FloatList(value=v))
elif isinstance(v[0], six.string_types):
if not six.PY2: # Convert in python 3.
v = [bytes(x, "utf-8") for x in v]
features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
elif isinstance(v[0], bytes):
features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
else:
raise ValueError("Value for %s is not a recognized type; v: %s type: %s" %
(k, str(v[0]), str(type(v[0]))))
return tf.train.Example(features=tf.train.Features(feature=features))
示例9: make_node
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def make_node(self, x, index):
x = as_sparse_variable(x)
assert x.format in ["csr", "csc"]
assert len(index) == 2
input_op = [x]
for ind in index:
if isinstance(ind, slice):
raise Exception("GetItemScalar called with a slice as index!")
# in case of indexing using int instead of theano variable
elif isinstance(ind, integer_types):
ind = theano.tensor.constant(ind)
input_op += [ind]
# in case of indexing using theano variable
elif ind.ndim == 0:
input_op += [ind]
else:
raise NotImplemented()
return gof.Apply(self, input_op, [tensor.scalar(dtype=x.dtype)])
示例10: __init__
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def __init__(self, scalar_op, axis=None):
if scalar_op.nin not in [-1, 2] or scalar_op.nout != 1:
raise NotImplementedError((
"CAReduce only supports binary functions with a single "
"output."))
self.scalar_op = scalar_op
if axis is None:
self.axis = axis
# There is a bug in numpy that results in isinstance(x,
# integer_types) returning False for numpy integers. See
# <http://projects.scipy.org/numpy/ticket/2235>.
elif isinstance(axis, (integer_types, numpy.integer)):
self.axis = (axis,)
elif isinstance(axis, numpy.ndarray) and axis.ndim == 0:
self.axis = (int(axis),)
else:
self.axis = list(set(int(a) for a in axis))
self.axis.sort()
self.axis = tuple(self.axis)
self.set_ufunc(scalar_op)
示例11: __init__
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def __init__(self, border_mode="valid", subsample=(1, 1)):
if isinstance(border_mode, integer_types):
if border_mode < 0:
raise ValueError(
'invalid border_mode {}, which must be a '
'non-negative integer'.format(border_mode))
border_mode = (border_mode, border_mode)
if isinstance(border_mode, tuple):
if len(border_mode) != 2 or border_mode[0] < 0 or border_mode[1] < 0:
raise ValueError(
'invalid border_mode {}, which must be a '
'pair of non-negative integers'.format(border_mode))
pad_h, pad_w = map(int, border_mode)
border_mode = (pad_h, pad_w)
if not ((isinstance(border_mode, tuple) and min(border_mode) >= 0) or
border_mode in ('valid', 'full', 'half')):
raise ValueError(
'invalid border_mode {}, which must be either '
'"valid", "full", "half", an integer or a pair of'
' integers'.format(border_mode))
self.border_mode = border_mode
if len(subsample) != 2:
raise ValueError("subsample must have two elements")
self.subsample = tuple(subsample)
示例12: __init__
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def __init__(self, ds, ignore_border, st=None, padding=(0, 0), mode='max'):
self.ds = tuple(ds)
if not all([isinstance(d, integer_types) for d in ds]):
raise ValueError(
"Pool downsample parameters must be ints."
" Got %s" % str(ds))
if st is None:
st = ds
assert isinstance(st, (tuple, list))
self.st = tuple(st)
self.ignore_border = ignore_border
self.padding = tuple(padding)
if self.padding != (0, 0) and not ignore_border:
raise NotImplementedError(
'padding works only with ignore_border=True')
if self.padding[0] >= self.ds[0] or self.padding[1] >= self.ds[1]:
raise NotImplementedError(
'padding_h and padding_w must be smaller than strides')
self.mode = mode
assert self.mode == 'max'
示例13: make_constant
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def make_constant(args):
"""
Convert python litterals to theano constants in subtensor arguments.
"""
def conv(a):
if a is None:
return a
elif isinstance(a, slice):
return slice(conv(a.start),
conv(a.stop),
conv(a.step))
elif isinstance(a, (integer_types, numpy.integer)):
return scal.ScalarConstant(scal.int64, a)
else:
return a
return tuple(map(conv, args))
示例14: reshape
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def reshape(self, shape, ndim=None):
"""Return a reshaped view/copy of this variable.
Parameters
----------
shape
Something that can be converted to a symbolic vector of integers.
ndim
The length of the shape. Passing None here means for
Theano to try and guess the length of `shape`.
.. warning:: This has a different signature than numpy's
ndarray.reshape!
In numpy you do not need to wrap the shape arguments
in a tuple, in theano you do need to.
"""
if ndim is not None:
if not isinstance(ndim, integer_types):
raise ValueError("Expected ndim to be an integer, is " +
str(type(ndim)))
return theano.tensor.basic.reshape(self, shape, ndim=ndim)
示例15: makeKeepDims_local
# 需要導入模塊: import six [as 別名]
# 或者: from six import integer_types [as 別名]
def makeKeepDims_local(self, x, y, axis):
if axis is None:
newaxis = list(range(x.ndim))
elif isinstance(axis, integer_types):
if axis < 0:
newaxis = [axis + x.type.ndim]
else:
newaxis = [axis]
else:
newaxis = []
for a in axis:
if a < 0:
a += x.type.ndim
newaxis.append(a)
i = 0
new_dims = []
for j, _ in enumerate(x.shape):
if j in newaxis:
new_dims.append('x')
else:
new_dims.append(i)
i += 1
return tensor.DimShuffle(y.type.broadcastable, new_dims)(y)