Python six.integer_types() Examples

The following are 30 code examples for showing how to use six.integer_types(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module six , or try the search function .

Example 1
Project: fine-lm   Author: akzaidi   File: generator_utils.py    License: MIT License 6 votes vote down vote up
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 2
Project: linter-pylama   Author: AtomLinter   File: classes.py    License: MIT License 6 votes vote down vote up
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
Project: ec2-api   Author: openstack   File: s3server.py    License: Apache License 2.0 6 votes vote down vote up
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 4
Project: tensornets   Author: taehoonlee   File: layers.py    License: MIT License 6 votes vote down vote up
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
Project: bigsuds   Author: F5Networks   File: bigsuds.py    License: MIT License 6 votes vote down vote up
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 6
Project: libbytesize   Author: storaged-project   File: bytesize.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 7
Project: lambda-packs   Author: ryfeus   File: meta_graph.py    License: MIT License 6 votes vote down vote up
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 8
Project: lambda-packs   Author: ryfeus   File: layers.py    License: MIT License 6 votes vote down vote up
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 9
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: meta_graph.py    License: MIT License 6 votes vote down vote up
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 10
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: layers.py    License: MIT License 6 votes vote down vote up
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 11
Project: tensor2tensor   Author: tensorflow   File: generator_utils.py    License: Apache License 2.0 6 votes vote down vote up
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 12
Project: D-VAE   Author: muhanzhang   File: basic.py    License: MIT License 6 votes vote down vote up
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 13
Project: D-VAE   Author: muhanzhang   File: elemwise.py    License: MIT License 6 votes vote down vote up
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 14
Project: D-VAE   Author: muhanzhang   File: corr.py    License: MIT License 6 votes vote down vote up
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 15
Project: D-VAE   Author: muhanzhang   File: pool.py    License: MIT License 6 votes vote down vote up
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 16
Project: D-VAE   Author: muhanzhang   File: subtensor.py    License: MIT License 6 votes vote down vote up
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 17
Project: D-VAE   Author: muhanzhang   File: var.py    License: MIT License 6 votes vote down vote up
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 18
Project: D-VAE   Author: muhanzhang   File: test_keepdims.py    License: MIT License 6 votes vote down vote up
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 19
Project: BERT-Classification-Tutorial   Author: Socialbird-AILab   File: modeling.py    License: Apache License 2.0 5 votes vote down vote up
def assert_rank(tensor, expected_rank, name=None):
    """Raises an exception if the tensor rank is not of the expected rank.

    Args:
      tensor: A tf.Tensor to check the rank of.
      expected_rank: Python integer or list of integers, expected rank.
      name: Optional name of the tensor for the error message.

    Raises:
      ValueError: If the expected shape doesn't match the actual shape.
    """
    if name is None:
        name = tensor.name

    expected_rank_dict = {}
    if isinstance(expected_rank, six.integer_types):
        expected_rank_dict[expected_rank] = True
    else:
        for x in expected_rank:
            expected_rank_dict[x] = True

    actual_rank = tensor.shape.ndims
    if actual_rank not in expected_rank_dict:
        scope_name = tf.get_variable_scope().name
        raise ValueError(
            "For the tensor `%s` in scope `%s`, the actual rank "
            "`%d` (shape = %s) is not equal to the expected rank `%s`" %
            (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank))) 
Example 20
Project: gnocchi   Author: gnocchixyz   File: json.py    License: Apache License 2.0 5 votes vote down vote up
def to_primitive(obj):
    if isinstance(obj, ((six.text_type,)
                        + six.integer_types
                        + (type(None), bool, float))):
        return obj
    if isinstance(obj, uuid.UUID):
        return six.text_type(obj)
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    if isinstance(obj, numpy.datetime64):
        # Do not include nanoseconds if null
        return str(obj).rpartition(".000000000")[0] + "+00:00"
    if isinstance(obj, numpy.timedelta64):
        return obj / numpy.timedelta64(1, 's')
    if isinstance(obj, datetime.timedelta):
        return obj.total_seconds()
    # This mimics what Pecan implements in its default JSON encoder
    if hasattr(obj, "jsonify"):
        return to_primitive(obj.jsonify())
    if isinstance(obj, dict):
        return {to_primitive(k): to_primitive(v)
                for k, v in obj.items()}
    if hasattr(obj, 'iteritems'):
        return to_primitive(dict(obj.iteritems()))
    # Python 3 does not have iteritems
    if hasattr(obj, 'items'):
        return to_primitive(dict(obj.items()))
    if hasattr(obj, '__iter__'):
        return list(map(to_primitive, obj))
    return obj 
Example 21
Project: redis-trib.py   Author: projecteru   File: connection.py    License: MIT License 5 votes vote down vote up
def encode(value):
    if isinstance(value, six.binary_type):
        return value
    if isinstance(value, six.integer_types):
        return b(str(value))
    if isinstance(value, float):
        return b(repr(value))
    if isinstance(value, six.text_type):
        return value.encode(ENCODING)
    if not isinstance(value, six.string_types):
        return b(value)
    return value 
Example 22
Project: tudouNLP   Author: fennuDetudou   File: modeling.py    License: MIT License 5 votes vote down vote up
def assert_rank(tensor, expected_rank, name=None):
  """Raises an exception if the tensor rank is not of the expected rank.

  Args:
    tensor: A tf.Tensor to check the rank of.
    expected_rank: Python integer or list of integers, expected rank.
    name: Optional name of the tensor for the error message.

  Raises:
    ValueError: If the expected shape doesn't match the actual shape.

    tensor的rank表示一个tensor需要的索引数目来唯一表示任何一个元素。也就是通常所说的 “order”, “degree”或”ndims”,不是矩阵的秩。
    eg:
    ’t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]
    shape of tensor ‘t’ is [2, 2, 3]
    rank(t) = 3
  """
  if name is None:
    name = tensor.name

  expected_rank_dict = {}
  if isinstance(expected_rank, six.integer_types):
    expected_rank_dict[expected_rank] = True
  else:
    for x in expected_rank:
      expected_rank_dict[x] = True

  actual_rank = tensor.shape.ndims
  if actual_rank not in expected_rank_dict:
    scope_name = tf.get_variable_scope().name
    raise ValueError(
        "For the tensor `%s` in scope `%s`, the actual rank "
        "`%d` (shape = %s) is not equal to the expected rank `%s`" %
        (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank))) 
Example 23
Project: dataflow   Author: tensorpack   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def _batch_numpy(data_list):
        data = data_list[0]
        if isinstance(data, six.integer_types):
            dtype = 'int32'
        elif type(data) == bool:
            dtype = 'bool'
        elif type(data) == float:
            dtype = 'float32'
        elif isinstance(data, (six.binary_type, six.text_type)):
            dtype = 'str'
        else:
            try:
                dtype = data.dtype
            except AttributeError:
                raise TypeError("Unsupported type to batch: {}".format(type(data)))
        try:
            return np.asarray(data_list, dtype=dtype)
        except Exception as e:  # noqa
            logger.exception("Cannot batch data. Perhaps they are of inconsistent shape?")
            if isinstance(data, np.ndarray):
                s = pprint.pformat([x.shape for x in data_list])
                logger.error("Shape of all arrays to be batched: " + s)
            try:
                # open an ipython shell if possible
                import IPython as IP; IP.embed()    # noqa
            except ImportError:
                pass 
Example 24
Project: pwnypack   Author: edibledinos   File: base.py    License: MIT License 5 votes vote down vote up
def reg_add(self, reg, value):
        """
        Add a value to a register. The value can be another :class:`Register`,
        an :class:`Offset`, a :class:`Buffer`, an integer or ``None``.

        Arguments:
            reg(pwnypack.shellcode.types.Register): The register to add the
                value to.
            value: The value to add to the register.

        Returns:
            list: A list of mnemonics that will add ``value`` to ``reg``.
        """

        if value is None:
            return []

        elif isinstance(value, Register):
            return self.reg_add_reg(reg, value)

        elif isinstance(value, (Buffer, six.integer_types)):
            if isinstance(reg, Buffer):
                value = sum(len(v) for v in six.iterkeys(self.data)) + value.offset

            if not value:
                return []

            reg_width = self.REGISTER_WIDTH[reg]
            if value < -2 ** (reg_width-1):
                raise ValueError('%d does not fit %s' % (value, reg))
            elif value >= 2 ** reg_width:
                raise ValueError('%d does not fit %s' % (value, reg))

            if value > 0:
                return self.reg_add_imm(reg, value)
            else:
                return self.reg_sub_imm(reg, -value)

        else:
            raise ValueError('Invalid argument type "%s"' % repr(value)) 
Example 25
Project: pwnypack   Author: edibledinos   File: base.py    License: MIT License 5 votes vote down vote up
def reg_sub(self, reg, value):
        if value is None:
            return []
        elif isinstance(value, Register):
            return self.reg_sub_reg(reg, value)
        elif isinstance(value, Buffer):
            value = sum(len(v) for v in six.iterkeys(self.data)) + value.offset
            return self.reg_add(reg, -value)
        elif isinstance(value, six.integer_types):
            return self.reg_add(reg, -value)
        else:
            raise ValueError('Invalid argument type "%s"' % repr(value)) 
Example 26
Project: pwnypack   Author: edibledinos   File: types.py    License: MIT License 5 votes vote down vote up
def verify(value):
        if not isinstance(value, (six.integer_types, Register, SyscallInvoke)):
            raise ValueError('syscall argument not of expected type int') 
Example 27
Project: pwnypack   Author: edibledinos   File: types.py    License: MIT License 5 votes vote down vote up
def verify(value):
        if not isinstance(value, (type(None), six.integer_types, Register, Offset, Buffer, SyscallInvoke,
                                  six.string_types, six.binary_type, list)):
            raise ValueError('syscall argument not of expected type ptr') 
Example 28
Project: pyjsgf   Author: Danesprite   File: expansions.py    License: MIT License 5 votes vote down vote up
def set_weight(self, child, weight):
        """
        Set the weight of a child.

        The weight determines how likely it is that an alternative was spoken.

        Higher values are more likely, lower values are less likely. A value
        of 0 means that the alternative will never be matched. Negative
        weights are not allowed.

        *Note*: weights are compiled as floating-point numbers accurate to 4
        decimal places, e.g. 5.0001.

        :param child: child/list index/compiled child to set the weight for.
        :type child: Expansion|int|str
        :param weight: weight value - must be >= 0
        :type weight: float|int
        """
        # Check that weight is a non-negative number.
        weight = float(weight)
        if weight < 0:
            raise TypeError("weight value '%s' is a negative number" % weight)

        # Use the alternative as the key for _weights.
        if isinstance(child, integer_types):
            child = self.children[child]
        elif isinstance(child, string_types):
            compiled_child = child
            for c in self.children:
                if c.compile() == compiled_child:
                    child = c

        self._weights[child] = weight

        # Invalidate this expansion. This is a quick procedure if the matcher
        # element hasn't been initialised.
        self.invalidate_matcher() 
Example 29
Project: pyjsgf   Author: Danesprite   File: parser.py    License: MIT License 5 votes vote down vote up
def __init__(self, *expansions):
        children = []
        weights = []
        last_weight = None
        for e in expansions:
            # Unravel any alternative set without a tag.
            if isinstance(e, AlternativeSet) and not e.tag:
                # Add each child and preserve the weights.
                if last_weight is not None:
                    weights.append((e.children[0], last_weight))
                    last_weight = None

                children.extend(e.children)
                weights.extend(list(e.weights.items()))
            elif isinstance(e, WeightedExpansion):
                children.append(e.child)
                weights.append((e.child, e.weight))
                e.child.parent = None
            elif isinstance(e, (float, integer_types)):
                last_weight = e
            else:
                if last_weight is not None:
                    weights.append((e, last_weight))
                    last_weight = None

                children.append(e)
        super(ParsedAlternativeSet, self).__init__(*children)
        self.weights = weights 
Example 30
Project: monero-python   Author: monero-ecosystem   File: numbers.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_atomic(amount):
    """Convert Monero decimal to atomic integer of piconero."""
    if not isinstance(amount, (Decimal, float) + six.integer_types):
        raise ValueError("Amount '{}' doesn't have numeric type. Only Decimal, int, long and "
                "float (not recommended) are accepted as amounts.")
    return int(amount * 10**12)