Python types.StringTypes() Examples

The following are 30 code examples of types.StringTypes(). 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 types , or try the search function .
Example #1
Source File: context.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def dump(self, output_format):
    """Returns the context graph in the specified format."""
    assert isinstance(output_format, types.StringTypes)

    self._context_resources.sort(key=lambda x: x['id'])
    self._context_relations.sort(key=lambda x: (x['source'], x['target']))

    if output_format == 'dot':
      return self.to_dot_graph()
    elif output_format == 'context_graph':
      return self.to_context_graph()
    elif output_format == 'resources':
      return self.to_context_resources()
    else:
      msg = 'invalid dump() output_format: %s' % output_format
      app.logger.error(msg)
      raise collector_error.CollectorError(msg) 
Example #2
Source File: simple_cache_test.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def make_fancy_blob(self, name, timestamp_seconds, value):
    """Makes a blob containing "name", "timestamp" and "value" attributes.

    Args:
      name: the name of this object (the value of the 'id' attribute).
      timestamp_seconds: a timestamp in seconds.
      value: a value of any type.

    Returns:
    A dictionary containing 'id', 'timestamp', and 'value' key/value pairs.
    """
    assert isinstance(name, types.StringTypes)
    assert isinstance(timestamp_seconds, float)
    return {'id': name,
            'timestamp': utilities.seconds_to_timestamp(timestamp_seconds),
            'value': value} 
Example #3
Source File: collector_test.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def count_relations(self, output, type_name,
                      source_type=None, target_type=None):
    """Count relations of the specified type (e.g., "contains").

    If the source type and/or target type is specified (e.g., "Node", "Pod",
    etc.), count only relations that additionally match that constraint.
    """
    assert isinstance(output, dict)
    assert isinstance(type_name, types.StringTypes)
    if not isinstance(output.get('relations'), list):
      return 0

    n = 0
    for r in output.get('relations'):
      assert isinstance(r, dict)
      if r['type'] != type_name:
        continue
      if source_type and r['source'].split(':')[0] != source_type:
        continue
      if target_type and r['target'].split(':')[0] != target_type:
        continue
      n += 1

    return n 
Example #4
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):

        """This is similar to expect(), but uses plain string matching instead
        of compiled regular expressions in 'pattern_list'. The 'pattern_list'
        may be a string; a list or other sequence of strings; or TIMEOUT and
        EOF.

        This call might be faster than expect() for two reasons: string
        searching is faster than RE matching and it is possible to limit the
        search to just the end of the input buffer.

        This method is also useful when you don't want to have to worry about
        escaping regular expression characters that you want to match."""

        if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
            pattern_list = [pattern_list]
        return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) 
Example #5
Source File: microdom.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
                 nsprefixes={}, namespace=''):
        if self.raw:
            val = self.nodeValue
            if not isinstance(val, StringTypes):
                val = str(self.nodeValue)
        else:
            v = self.nodeValue
            if not isinstance(v, StringTypes):
                v = str(v)
            if strip:
                v = ' '.join(v.split())
            val = escape(v)
        if isinstance(val, UnicodeType):
            val = val.encode('utf8')
        stream.write(val) 
Example #6
Source File: util.py    From billing-export-python with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #7
Source File: util.py    From earthengine with MIT License 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #8
Source File: net.py    From pykit with MIT License 6 votes vote down vote up
def is_ip4(ip):

    if type(ip) not in types.StringTypes:
        return False

    ip = ip.split('.')

    for s in ip:

        if not s.isdigit():
            return False

        i = int(s)
        if i < 0 or i > 255:
            return False

    return len(ip) == 4 
Example #9
Source File: util.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #10
Source File: util.py    From splunk-ref-pas-code with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #11
Source File: influx.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def data_to_float(self, data):
        return convert_floats(data)

        for key, value in data.iteritems():

            # Sanity checks
            if type(value) in types.StringTypes:
                continue

            if value is None:
                data[key] = None
                continue

            # Convert to float
            try:
                data[key] = float(value)
            except (TypeError, ValueError) as ex:
                log.warn(u'Measurement "{key}: {value}" float conversion failed: {ex}', key=key, value=value, ex=ex) 
Example #12
Source File: recipe-580623.py    From code with MIT License 6 votes vote down vote up
def getint(v):
    import types
    # extract digits from a string to form an integer
    try:
        return int(v)
    except ValueError:
        pass
    if not isinstance(v, types.StringTypes):
        return 0
    a = "0"
    for d in v:
        if d in "0123456789":
            a += d
    return int(a)

#==============================================================================
# define scale factor for displaying page images (20% larger)
#============================================================================== 
Example #13
Source File: zkutil.py    From pykit with MIT License 6 votes vote down vote up
def parse_lock_id(data_str):
    """
    Parse string generated by lock_id()
    """

    node_id, ip, process_id, _uuid = (
        data_str.split('-', 3) + ([None] * 4))[:4]

    if type(process_id) in types.StringTypes and process_id.isdigit():
        process_id = int(process_id)
    else:
        process_id = None

    rst = {
        'node_id': node_id,
        'ip': ip,
        'process_id': process_id,
        'uuid': _uuid,
        'txid': None
    }

    if node_id.startswith('txid:'):
        rst['txid'] = node_id.split(':', 1)[1]

    return rst 
Example #14
Source File: util.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #15
Source File: wvlib.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def similarity(self, v1, v2):
        """Return cosine similarity of given words or vectors.

        If v1/v2 is a string, look up the corresponding word vector.
        This is not particularly efficient function. Instead of many
        invocations, consider word_similarity() or direct computation.
        """
        
        vs = [v1, v2]
        for i, v in enumerate(vs):
            if isinstance(v, StringTypes):
                v = self.word_to_unit_vector(v)
            else:
                v = v/numpy.linalg.norm(v) # costly but safe
            vs[i] = v
        return numpy.dot(vs[0], vs[1]) 
Example #16
Source File: microdom.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, node='div'):
        if isinstance(node, StringTypes):
            node = Element(node)
        self.node = node 
Example #17
Source File: inspect.py    From BinderFilter with MIT License 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc) 
Example #18
Source File: test_humannum.py    From pykit with MIT License 5 votes vote down vote up
def test_safe_parse(self):

        cases = (
                ('1%',    0.01,),
                ('1%x',   '1%x',),
                ('x1%x',  'x1%x',),
                ('1',     1,),
                ('1-',    '1-',),
                ('x1y',   'x1y',),
                ('1K',    1024,),
                ('1Kqq',  '1Kqq',),
                ('1.01',  1.01,),
                ('1..01', '1..01',),
        )

        for _in, expected in cases:

            rst = humannum.parsenum(_in, safe=True)

            msg = 'parse: in: {_in} expect: {expected}, rst: {rst}'.format(
                _in=repr(_in),
                expected=repr(expected),
                rst=repr(rst),
            )
            dd(msg)

            self.assertEqual(expected, rst)

            if not isinstance(expected, types.StringTypes):
                rst = humannum.parseint(_in, safe=True)
                self.assertEqual(int(expected), rst) 
Example #19
Source File: humannum.py    From pykit with MIT License 5 votes vote down vote up
def parsenum(data, safe=None):

    if safe is None:
        safe = False

    original = data

    if isinstance(data, integer_types):
        return data

    if not isinstance(data, types.StringTypes):
        return data

    if data == '':
        return 0

    if data.endswith('%'):
        fl = float(data[:-1]) / 100.0
        return fl

    data = data.upper().rstrip('B').rstrip('I')

    unit_name = data[-1]

    try:
        if unit_name in unit_to_value:
            val = float(data[:-1]) * unit_to_value[unit_name]
        else:
            val = float(data)

        if val == int(val):
            val = int(val)

    except ValueError:
        if safe:
            val = original
        else:
            raise

    return val 
Example #20
Source File: _config.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _parse_environment_config(self, application_name, config):
        """
        Validate and return an application config's environment variables.

        :param unicode application_name: The name of the application.

        :param dict config: The config of a single ``Application`` instance,
            as extracted from the ``applications`` ``dict`` in
            ``_applications_from_configuration``.

        :raises ConfigurationError: if the ``environment`` element of
            ``config`` is not a ``dict`` or ``dict``-like value.

        :returns: ``None`` if there is no ``environment`` element in the
            config, or the ``frozenset`` of environment variables if there is,
            in the form of a ``frozenset`` of ``tuple`` \s mapped to
            (key, value)

        """
        environment = config.pop('environment', None)
        if environment:
            _check_type(value=environment, types=(dict,),
                        description="'environment' must be a dictionary of "
                                    "key/value pairs",
                        application_name=application_name)
            for key, value in environment.iteritems():
                # We should normailzie strings to either bytes or unicode here
                # https://clusterhq.atlassian.net/browse/FLOC-636
                _check_type(value=key, types=types.StringTypes,
                            description="Environment variable name "
                                        "must be a string",
                            application_name=application_name)
                _check_type(value=value, types=types.StringTypes,
                            description="Environment variable '{key}' "
                                        "must be a string".format(key=key),
                            application_name=application_name)
            environment = frozenset(environment.items())
        return environment 
Example #21
Source File: _config.py    From flocker with Apache License 2.0 5 votes vote down vote up
def parse_storage_string(value):
    """
    Converts a string representing a quantity and a unit identifier in to
    an integer value representing the number of bytes in that quantity, e.g.
    an input of "1G" is parsed to 1073741824. Raises ``ValueError`` if
    value cannot be converted.

    An int is always returned, so conversions resulting in a floating-point
    are always rounded UP to ensure sufficient bytes for the specified storage
    size, e.g. input of "2.1M" is converted to 2202010 bytes, not 2202009.

    :param StringTypes value: The string value to convert to integer bytes.

    :returns: ``int`` representing the supplied value converted to bytes, e.g.
        input of "2G" (2 gigabytes) returns 2147483648.
    """
    byte_multipliers = {
        'K': 1024, 'M': 1048576,
        'G': 1073741824, 'T': 1099511627776
    }
    if not isinstance(value, types.StringTypes):
        raise ValueError("Value must be string, got {type}.".format(
            type=type(value).__name__))
    pattern = re.compile("^(\d+\.?\d*)(K|M|G|T)?$", re.I | re.U)
    parsed = pattern.match(value)
    if not parsed:
        raise ValueError(
            "Value '{value}' could not be parsed as a storage quantity.".
            format(value=value)
        )
    quantity, unit = parsed.groups()
    quantity = float(quantity)
    if unit is not None:
        unit = unit.upper()
        quantity = quantity * byte_multipliers[unit]
    quantity = int(math.ceil(quantity))
    return quantity 
Example #22
Source File: smtp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, fromEmail, toEmail, file, deferred, retries=5,
                 timeout=None):
        """
        @param fromEmail: The RFC 2821 address from which to send this
        message.

        @param toEmail: A sequence of RFC 2821 addresses to which to
        send this message.

        @param file: A file-like object containing the message to send.

        @param deferred: A Deferred to callback or errback when sending
        of this message completes.
        @type deferred: L{defer.Deferred}

        @param retries: The number of times to retry delivery of this
        message.

        @param timeout: Period, in seconds, for which to wait for
        server responses, or None to wait forever.
        """
        assert isinstance(retries, (int, long))

        if isinstance(toEmail, types.StringTypes):
            toEmail = [toEmail]
        self.fromEmail = Address(fromEmail)
        self.nEmails = len(toEmail)
        self.toEmail = toEmail
        self.file = file
        self.result = deferred
        self.result.addBoth(self._removeDeferred)
        self.sendFinished = False
        self.currentProtocol = None

        self.retries = -retries
        self.timeout = timeout 
Example #23
Source File: strutil.py    From pykit with MIT License 5 votes vote down vote up
def line_pad(linestr, padding=''):

    lines = linestr.split("\n")

    if type(padding) in types.StringTypes:
        lines = [padding + x for x in lines]

    elif callable(padding):
        lines = [padding(x) + x for x in lines]

    lines = "\n".join(lines)

    return lines 
Example #24
Source File: optparse.py    From Computable with MIT License 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example #25
Source File: optparse.py    From hacker-scripts with MIT License 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example #26
Source File: inputstream.py    From nzb-subliminal with GNU General Public License v3.0 5 votes vote down vote up
def codecName(encoding):
    """Return the python codec name corresponding to an encoding or None if the
    string doesn't correspond to a valid encoding."""
    if (encoding is not None and type(encoding) in types.StringTypes):
        canonicalName = ascii_punctuation_re.sub("", encoding).lower()
        return encodings.get(canonicalName, None)
    else:
        return None 
Example #27
Source File: inspect.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc) 
Example #28
Source File: optparse.py    From BinderFilter with MIT License 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example #29
Source File: NoFormattingInWhenRule.py    From cinch with GNU General Public License v3.0 5 votes vote down vote up
def _is_valid(self, when):
        if not isinstance(when, StringTypes):
            return True
        return when.find('{{') == -1 and when.find('}}') == -1 
Example #30
Source File: inspect.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc)