Python six.integer_types() Examples
The following are 30
code examples of six.integer_types().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
six
, or try the search function
.
Example #1
Source File: elemwise.py From D-VAE with MIT License | 6 votes |
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)
Example #2
Source File: classes.py From linter-pylama with MIT License | 6 votes |
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)
Example #3
Source File: layers.py From lambda-packs with MIT License | 6 votes |
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
Example #4
Source File: layers.py From tensornets with MIT License | 6 votes |
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
Example #5
Source File: meta_graph.py From lambda-packs with MIT License | 6 votes |
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
Example #6
Source File: meta_graph.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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
Example #7
Source File: layers.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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
Example #8
Source File: s3server.py From ec2-api with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: generator_utils.py From tensor2tensor with Apache License 2.0 | 6 votes |
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))
Example #10
Source File: basic.py From D-VAE with MIT License | 6 votes |
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)])
Example #11
Source File: corr.py From D-VAE with MIT License | 6 votes |
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)
Example #12
Source File: pool.py From D-VAE with MIT License | 6 votes |
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'
Example #13
Source File: subtensor.py From D-VAE with MIT License | 6 votes |
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))
Example #14
Source File: bigsuds.py From bigsuds with MIT License | 6 votes |
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
Example #15
Source File: var.py From D-VAE with MIT License | 6 votes |
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)
Example #16
Source File: test_keepdims.py From D-VAE with MIT License | 6 votes |
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)
Example #17
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 6 votes |
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 ##
Example #18
Source File: generator_utils.py From fine-lm with MIT License | 6 votes |
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))
Example #19
Source File: subtensor.py From D-VAE with MIT License | 5 votes |
def process(self, r, pstate): if r.owner is None: raise TypeError("Can only print Subtensor.") elif isinstance(r.owner.op, Subtensor): idxs = r.owner.op.idx_list inputs = list(r.owner.inputs) input = inputs.pop() sidxs = [] inbrack_pstate = pstate.clone(precedence=-1000) for entry in idxs: if isinstance(entry, integer_types): sidxs.append(str(entry)) elif isinstance(entry, scal.Scalar): sidxs.append(inbrack_pstate.pprinter.process(inputs.pop())) elif isinstance(entry, slice): if entry.start is None or entry.start == 0: msg1 = "" else: msg1 = entry.start if entry.stop is None or entry.stop == sys.maxsize: msg2 = "" else: msg2 = entry.stop if entry.step is None: msg3 = "" else: msg3 = ":%s" % entry.step sidxs.append("%s:%s%s" % (msg1, msg2, msg3)) return "%s[%s]" % (pstate.pprinter.process( input, pstate.clone(precedence=1000)), ", ".join(sidxs)) else: raise TypeError("Can only print Subtensor.")
Example #20
Source File: type_checkers.py From lambda-packs with MIT License | 5 votes |
def CheckValue(self, proposed_value): if not isinstance(proposed_value, numbers.Integral): message = ('%.1024r has type %s, but expected one of: %s' % (proposed_value, type(proposed_value), six.integer_types)) raise TypeError(message) if not self._MIN <= int(proposed_value) <= self._MAX: raise ValueError('Value out of range: %d' % proposed_value) # We force 32-bit values to int and 64-bit values to long to make # alternate implementations where the distinction is more significant # (e.g. the C++ implementation) simpler. proposed_value = self._TYPE(proposed_value) return proposed_value
Example #21
Source File: encode.py From pygeobuf with ISC License | 5 votes |
def encode_property(self, key, val, properties, values): keys = self.keys if not (key in keys): keys[key] = True self.data.keys.append(key) key_index = len(self.data.keys) - 1 else: key_index = list(keys.keys()).index(key) value = values.add() if isinstance(val, dict) or isinstance(val, list): value.json_value = json.dumps(val, separators=(',', ':')) elif isinstance(val, six.text_type): value.string_value = val elif isinstance(val, float): if val.is_integer(): self.encode_int(int(val), value) else: value.double_value = val elif isinstance(val, bool): value.bool_value = val elif isinstance(val, six.integer_types): self.encode_int(val, value) properties.append(key_index) properties.append(len(values) - 1)
Example #22
Source File: encoding.py From lambda-packs with MIT License | 5 votes |
def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_unicode(strings_only=True). """ return isinstance(obj, ( six.integer_types + (types.NoneType, datetime.datetime, datetime.date, datetime.time, float, Decimal)) )
Example #23
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def __init__(self, spec=None): self._c_size = None try: if isinstance(spec, six.string_types): self._c_size = SizeStruct.new_from_str(spec) elif isinstance(spec, six.integer_types): abs_val = abs(spec) if abs_val == spec: sgn = 1 else: sgn = -1 if abs_val <= MAXUINT64: self._c_size = SizeStruct.new_from_bytes(abs_val, sgn) else: self._c_size = SizeStruct.new_from_str(str(spec)) elif isinstance(spec, (Decimal, float)): self._c_size = SizeStruct.new_from_str(str(spec)) elif isinstance(spec, SizeStruct): self._c_size = SizeStruct.new_from_size(spec) elif isinstance(spec, Size): self._c_size = SizeStruct.new_from_size(spec._c_size) elif spec is None: self._c_size = SizeStruct.new() else: raise ValueError("Cannot construct new size from '%s'" % spec) except SizeError as e: raise ValueError(e) ## METHODS ##
Example #24
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def __floordiv__(self, other): if isinstance(other, (Decimal, float)): return Size(self._c_size.mul_float_str(str(Decimal(1)/Decimal(other)))) elif isinstance(other, six.integer_types): if other <= MAXUINT64: return self._safe_floordiv_int(other) else: other = SizeStruct.new_from_str(str(other)) return Size(self._safe_floordiv(other)) return self._safe_floordiv(other)
Example #25
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def __truediv__(self, other): if isinstance(other, six.integer_types): if other <= MAXUINT64: return Size(self._c_size.true_div_int(other)) else: other = SizeStruct.new_from_str(str(other)) return Size(self._c_size.true_div(other)) elif isinstance(other, (Decimal, float)): return Size(self._c_size.mul_float_str(str(Decimal(1)/Decimal(other)))) return _str_to_decimal(self._c_size.true_div(other._c_size))
Example #26
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def __div__(self, other): if not six.PY2: raise AttributeError if isinstance(other, six.integer_types): if other <= MAXUINT64: return Size(self._c_size.div_int(other)) else: other = SizeStruct.new_from_str(str(other)) return Size(_str_to_decimal(self._c_size.true_div(other))) elif isinstance(other, (Decimal, float)): other = SizeStruct.new_from_str(str(other)) return Size(self._c_size.true_div(other)) else: return _str_to_decimal(self._c_size.true_div(other._c_size))
Example #27
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def __sub__(self, other): if isinstance(other, six.integer_types): if other <= MAXUINT64: return Size(self._c_size.sub_bytes(other)) 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 return Size(self._c_size.sub(other))
Example #28
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def __add__(self, other): if isinstance(other, six.integer_types): if other <= MAXUINT64: return Size(self._c_size.add_bytes(other)) 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 return Size(self._c_size.add(other)) # needed to make sum() work with Size arguments
Example #29
Source File: bytesize.py From libbytesize with GNU Lesser General Public License v2.1 | 5 votes |
def human_readable(self, min_unit=B, max_places=2, xlate=True): if isinstance(min_unit, six.string_types): if min_unit in unit_strs.keys(): min_unit = unit_strs[min_unit] else: raise ValueError("Invalid unit specification: '%s'" % min_unit) if not isinstance(max_places, six.integer_types): raise ValueError("max_places has to be an integer number") return self._c_size.human_readable(min_unit, max_places, xlate)
Example #30
Source File: graph.py From D-VAE with MIT License | 5 votes |
def __init__(self, type, owner=None, index=None, name=None): super(Variable, self).__init__() self.tag = utils.scratchpad() self.type = type if owner is not None and not isinstance(owner, Apply): raise TypeError("owner must be an Apply instance", owner) self.owner = owner if index is not None and not isinstance(index, integer_types): raise TypeError("index must be an int", index) self.index = index if name is not None and not isinstance(name, string_types): raise TypeError("name must be a string", name) self.name = name self.auto_name = 'auto_' + str(next(self.__count__))