Python types.StringType() Examples

The following are code examples for showing how to use types.StringType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
    """Helper functions for Scrolled Canvas, used to forward
    ScrolledCanvas-methods to Tkinter.Canvas class.
    """
    _dict = {}
    __methodDict(toClass, _dict)
    for ex in _dict.keys():
        if ex[:1] == '_' or ex[-1:] == '_':
            del _dict[ex]
    for ex in exclude:
        if ex in _dict:
            del _dict[ex]
    for ex in __methods(fromClass):
        if ex in _dict:
            del _dict[ex]

    for method, func in _dict.items():
        d = {'method': method, 'func': func}
        if type(toPart) == types.StringType:
            execString = \
                __stringBody % {'method' : method, 'attribute' : toPart}
        exec execString in d
        fromClass.__dict__[method] = d[method] 
Example 2
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def write(self, data):
        """'write()' callable as specified by PEP 333"""

        assert type(data) is StringType,"write() argument must be string"

        if not self.status:
            raise AssertionError("write() before start_response()")

        elif not self.headers_sent:
            # Before the first output, send the stored headers
            self.bytes_sent = len(data)    # make sure we know content-length
            self.send_headers()
        else:
            self.bytes_sent += len(data)

        # XXX check Content-Length and truncate if too many bytes written?
        self._write(data)
        self._flush() 
Example 3
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 6 votes vote down vote up
def _setEPSG(self, epsg=None):
        if epsg == None:
            self._epsg = None
        else:
            if isinstance(epsg, (StringType, UnicodeType)): 
                try:
                    epsg = int(epsg)
                    self._epsg = epsg
                except:
                    raise LMError('Invalid epsg code {}'.format(epsg))
            elif isinstance(epsg, IntType):
                self._epsg = epsg
            elif isinstance(epsg, ListType) or isinstance(epsg, TupleType):
                epsgcodes = set(epsg).discard(None)
                if len(epsgcodes) == 1:
                    self._epsg = epsgcodes[0]
                else:
                    raise LMError('LMSpatialObject may only contain a single EPSG code'
                                      .format(epsgcodes))
            else:
                raise LMError('Invalid EPSG code {} type {}'.format(epsg, type(epsg))) 
Example 4
Project: core   Author: lifemapper   File: gridset.py    GNU General Public License v3.0 6 votes vote down vote up
def addMatrix(self, mtxFileOrObj, doRead=False):
        """
        @summary Fill a Matrix object from Matrix or existing file
        """
        mtx = None
        if mtxFileOrObj is not None:
            usr = self.getUserId()
            if isinstance(mtxFileOrObj, StringType) and os.path.exists(mtxFileOrObj):
                mtx = LMMatrix(dlocation=mtxFileOrObj, userId=usr)
                if doRead:
                    mtx.readData()                
            elif isinstance(mtxFileOrObj, LMMatrix):
                mtx = mtxFileOrObj
                mtx.setUserId(usr)
            if mtx is not None:
                # Make sure to set the parent Id and URL
                if self.getId() is not None:
                    mtx.parentId = self.getId()
                    mtx.setParentMetadataUrl(self.metadataUrl)
                if mtx.getId() is None:
                    self._matrices.append(mtx)
                else:
                    existingIds = [m.getId() for m in self._matrices]
                    if mtx.getId() not in existingIds:
                        self._matrices.append(mtx) 
Example 5
Project: core   Author: lifemapper   File: jsonTree.py    GNU General Public License v3.0 6 votes vote down vote up
def _displayValue(obj, delim, depth):
   """
   @summary: Returns the display representation of a value
   @param obj: The value to represent
   @param delim: The delimiter to use (for spacing)
   @param depth: The depth of this object
   @note: Padding is determined by prepending display with depth copies of 
             delim.  So if the delimiter is "abc" and the depth is 2, the 
             resulting padding is "abcabc"
   @return: The string representation of the value
   @rtype: String
   """
   if isinstance(obj, JsonObject):
      return _displayObject(obj, delim, depth+1)
   elif isinstance(obj, JsonArray):
      return _displayArray(obj, delim, depth+1)
   elif isinstance(obj, StringType):
      return ''.join(("\"", escapeString(obj, "json"), "\""))
   elif isinstance(obj, UnicodeType):
      return u''.join((u"\"", escapeString(obj, "json"), u"\""))
   else:
      return str(obj)
      

# ............................................................................. 
Example 6
Project: neos-classic-electrum-server   Author: neoscoin   File: deserialize.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name, enumList):
        self.__doc__ = name
        lookup = {}
        reverseLookup = {}
        i = 0
        uniqueNames = []
        uniqueValues = []
        for x in enumList:
            if isinstance(x, types.TupleType):
                x, i = x
            if not isinstance(x, types.StringType):
                raise EnumException("enum name is not a string: %r" % x)
            if not isinstance(i, types.IntType):
                raise EnumException("enum value is not an integer: %r" % i)
            if x in uniqueNames:
                raise EnumException("enum name is not unique: %r" % x)
            if i in uniqueValues:
                raise EnumException("enum value is not unique for %r" % x)
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example 7
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_replication_path(self, datastore_id, destinationIp=None, destionationPassphrase=None, destionationPort=None, sourceIp=None, testType=None, request=None):
        """
        Tests the specified replication path on the specified datastore, provide either request or set other params.

        **Supported on:** VMstore (all versions)

        Args:
            datastore_id: Datastore object's UUID
            destinationIp: Remote IPv4 address of another datastore where replication data is received.
            destionationPassphrase: Authorization key used on the remote end of this replication link.
            destionationPort: Remote port of another datastore where replication data is received.
            sourceIp: Local IPv4 address used by datastore to send replication data.
            testType: Test to perform
            request: TestReplicationPath request
        """
        if 'v310.41' in self.version.supportedVersionSet:
            url = "datastore/%s/testReplicationPath"
        else:
            url = "datastore/%s/replicationPath/test"
        self._update(_get_request_object(locals(), ["self", "datastore_id"], TestReplicationPath),
                     path_params = [datastore_id], resource_url=url, request_class=types.StringType) 
Example 8
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 6 votes vote down vote up
def open(self, fullurl, data=None):
        # accept a URL or a Request object
        if isinstance(fullurl, (types.StringType, types.UnicodeType)):
            req = Request(fullurl, data)
        else:
            req = fullurl
            if data is not None:
                req.add_data(data)
        assert isinstance(req, Request) # really only care about interface

        result = self._call_chain(self.handle_open, 'default',
                                  'default_open', req)
        if result:
            return result

        type_ = req.get_type()
        result = self._call_chain(self.handle_open, type_, type_ + \
                                  '_open', req)
        if result:
            return result

        return self._call_chain(self.handle_open, 'unknown',
                                'unknown_open', req) 
Example 9
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, idx):
	"""
	>>> N['dog'][0].synset[0] == N['dog'][0]
	1
	>>> N['dog'][0].synset['dog'] == N['dog'][0]
	1
	>>> N['dog'][0].synset[N['dog']] == N['dog'][0]
	1
	>>> N['cat'][6]
	'cat' in {noun: big cat, cat}
	"""
	senses = self.getSenses()
	if isinstance(idx, Word):
	    idx = idx.form
	if isinstance(idx, StringType):
	    idx = _index(idx, map(lambda sense:sense.form, senses)) or \
		  _index(idx, map(lambda sense:sense.form, senses), _equalsIgnoreCase)
	return senses[idx] 
Example 10
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 11
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, idx):
	"""
	>>> N['dog'][0].synset[0] == N['dog'][0]
	1
	>>> N['dog'][0].synset['dog'] == N['dog'][0]
	1
	>>> N['dog'][0].synset[N['dog']] == N['dog'][0]
	1
	>>> N['cat'][6]
	'cat' in {noun: big cat, cat}
	"""
	senses = self.getSenses()
	if isinstance(idx, Word):
	    idx = idx.form
	if isinstance(idx, StringType):
	    idx = _index(idx, map(lambda sense:sense.form, senses)) or \
		  _index(idx, map(lambda sense:sense.form, senses), _equalsIgnoreCase)
	return senses[idx] 
Example 12
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 6 votes vote down vote up
def _readObject(self):
        result = {}
        assert self._next() == '{'
        done = self._peek() == '}'
        while not done:
            key = self._read()
            if type(key) is not types.StringType:
                raise ReadException, "Not a valid JSON object key (should be a string): %s" % key
            self._eatWhitespace()
            ch = self._next()
            if ch != ":":
                raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch)
            self._eatWhitespace()
            val = self._read()
            result[key] = val
            self._eatWhitespace()
            done = self._peek() == '}'
            if not done:
                ch = self._next()
                if ch != ",":
                    raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
	assert self._next() == "}"
        return result 
Example 13
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 6 votes vote down vote up
def _readObject(self):
        result = {}
        assert self._next() == '{'
        done = self._peek() == '}'
        while not done:
            key = self._read()
            if type(key) is not types.StringType:
                raise ReadException, "Not a valid JSON object key (should be a string): %s" % key
            self._eatWhitespace()
            ch = self._next()
            if ch != ":":
                raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch)
            self._eatWhitespace()
            val = self._read()
            result[key] = val
            self._eatWhitespace()
            done = self._peek() == '}'
            if not done:
                ch = self._next()
                if ch != ",":
                    raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
	assert self._next() == "}"
        return result 
Example 14
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 6 votes vote down vote up
def _readObject(self):
        result = {}
        assert self._next() == '{'
        done = self._peek() == '}'
        while not done:
            key = self._read()
            if type(key) is not types.StringType:
                raise ReadException, "Not a valid JSON object key (should be a string): %s" % key
            self._eatWhitespace()
            ch = self._next()
            if ch != ":":
                raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch)
            self._eatWhitespace()
            val = self._read()
            result[key] = val
            self._eatWhitespace()
            done = self._peek() == '}'
            if not done:
                ch = self._next()
                if ch != ",":
                    raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
	assert self._next() == "}"
        return result 
Example 15
Project: osg-configure   Author: opensciencegrid   File: utilities.py    Apache License 2.0 6 votes vote down vote up
def rpm_installed(rpm_name):
    """
    Check to see if given rpm is installed

    Arguments:
    rpm_name - a string with rpm name to check or a Iteratable with rpms that
               should be checked

    Returns:
    True if rpms are installed, False otherwise
    """
    trans_set = rpm.TransactionSet()
    if isinstance(rpm_name, types.StringType):
        return trans_set.dbMatch('name', rpm_name).count() in (1, 2)

    # check with iterable type
    try:
        for name in rpm_name:
            if trans_set.dbMatch('name', name).count() not in (1, 2):
                return False
        return True
    except rpm.error:
        return False 
Example 16
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, idx):
        """
        >>> N['dog'][0].synset[0] == N['dog'][0]
        1
        >>> N['dog'][0].synset['dog'] == N['dog'][0]
        1
        >>> N['dog'][0].synset[N['dog']] == N['dog'][0]
        1
        >>> N['cat'][6]
        'cat' in {noun: big cat, cat}
        """
        senses = self.getSenses()
        if isinstance(idx, Word):
            idx = idx.form
        if isinstance(idx, StringType):
            idx = _index(idx, map(lambda sense:sense.form, senses)) or \
              _index(idx, map(lambda sense:sense.form, senses), _equalsIgnoreCase)
        return senses[idx] 
Example 17
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, index):
        """If index is a String, return the Word whose form is
        index.  If index is an integer n, return the Word
        indexed by the n'th Word in the Index file.

        >>> N['dog']
        dog(n.)
        >>> N[0]
        'hood(n.)
        """
        if isinstance(index, StringType):
            return self.getWord(index)
        elif isinstance(index, IntType):
            line = self.indexFile[index]
            return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
        else:
            raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 18
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 6 votes vote down vote up
def __init__(self, function, name=None):
        """
        Construct a new C{FunctionFeatureDetector} from the given
        function.

        @param function: The function that this feature detector is based
            on.  When this feature detector is applied to a labeled
            text M{lt}, it will return M{C{func}(lt)}.
        @type function: C{LabeledText} -> (any)
        @param name: A name for the function used by this feature
            detector.  This name is used in the string representation
            of the feature detector.
        """
        assert _chktype(1, function, types.FunctionType,
                        types.BuiltinFunctionType, types.ClassType)
        assert _chktype(2, name, types.NoneType, types.StringType)
        self._name = name
        self._func = function 
Example 19
Project: robot-navigation   Author: ronaldahmed   File: naivebayes.py    MIT License 6 votes vote down vote up
def _get_toks(file='ca01', debug=0):
    """
    Load tokens from the given file.  
    """
    assert _chktype(1, file, types.StringType)
    assert _chktype(2, debug, types.IntType)
    
    _resettime()
    if debug: print _timestamp(), 'tokenizing', file

    ttoks = brown.tokenize(file)

    labeled_tokens = [Token(LabeledText(tok.type().base().lower(),
                                           tok.type().tag()),
                               tok.loc())
                         for tok in ttoks]
    if debug: print _timestamp(), '  done tokenizing'
    return labeled_tokens 
Example 20
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 6 votes vote down vote up
def __init__(self, tag_pattern, descr):
        """
        Construct a new C{ChunkRule}.
        
        @type tag_pattern: C{string}
        @param tag_pattern: This rule's tag pattern.  When
            applied to a C{ChunkString}, this rule will
            chunk any substring that matches this tag pattern and that
            is not already part of a chunk.
        @type descr: C{string}
        @param descr: A short description of the purpose and/or effect
            of this rule.
        """
        assert chktype(1, tag_pattern, types.StringType)
        assert chktype(2, descr, types.StringType)
        self._pattern = tag_pattern
        regexp = re.compile('(?P<chunk>%s)%s' %
                            (tag_pattern2re_pattern(tag_pattern),
                             ChunkString.IN_CHINK_PATTERN))
        RegexpChunkParserRule.__init__(self, regexp, '{\g<chunk>}', descr) 
Example 21
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 6 votes vote down vote up
def __init__(self, tag_pattern, descr):
        """
        Construct a new C{ChinkRule}.
        
        @type tag_pattern: C{string}
        @param tag_pattern: This rule's tag pattern.  When
            applied to a C{ChunkString}, this rule will
            find any substring that matches this tag pattern and that
            is contained in a chunk, and remove it from that chunk,
            thus creating two new chunks.
        @type descr: C{string}
        @param descr: A short description of the purpose and/or effect
            of this rule.
        """
        assert chktype(1, tag_pattern, types.StringType)
        assert chktype(2, descr, types.StringType)
        self._pattern = tag_pattern
        regexp = re.compile('(?P<chink>%s)%s' %
                            (tag_pattern2re_pattern(tag_pattern),
                             ChunkString.IN_CHUNK_PATTERN))
        RegexpChunkParserRule.__init__(self, regexp, '}\g<chink>{', descr) 
Example 22
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 6 votes vote down vote up
def __init__(self, tag_pattern, descr):
        """
        Construct a new C{UnChunkRule}.
        
        @type tag_pattern: C{string}
        @param tag_pattern: This rule's tag pattern.  When
            applied to a C{ChunkString}, this rule will
            find any complete chunk that matches this tag pattern,
            and un-chunk it.
        @type descr: C{string}
        @param descr: A short description of the purpose and/or effect
            of this rule.
        """
        assert chktype(1, tag_pattern, types.StringType)
        assert chktype(2, descr, types.StringType)
        self._pattern = tag_pattern
        regexp = re.compile('\{(?P<chunk>%s)\}' %
                            tag_pattern2re_pattern(tag_pattern))
        RegexpChunkParserRule.__init__(self, regexp, '\g<chunk>', descr) 
Example 23
Project: pyomni   Author: taxpon   File: WebdavRequests.py    MIT License 6 votes vote down vote up
def getNameElements(self, nameList):
        '''
        
        @param nameList:
        '''
        
        elements = ""
        for name in nameList:
            if  isinstance(name, types.StringType):
                name = (self.defaultNameSpace, name)        
            if  not name[0]:
                tag = name[1]        
            else:
                tag = self.shortcuts[name[0]] + ':' + name[1]
            elements += "<%s />" % tag
        return elements 
Example 24
Project: pyomni   Author: taxpon   File: VersionHandler.py    MIT License 6 votes vote down vote up
def revertToVersion(self, oldVersion):
        """
        Revert this VCR to the given version.
        Beware: All versions succeeding the given version are made unavailable.
        
        @param oldVersion: URL-path of a previous version of this VCR.
        """
        ## send an update request
        assert isinstance(oldVersion, types.StringType) or isinstance(oldVersion, types.UnicodeType)
        response = self.connection._request(Constants.METHOD_UPDATE, self.path,
                        _createUpdateBody(oldVersion), {})
        return response


    # the following is not needed when using auto-versioning
    
    # warning: not tested yet 
Example 25
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def addCollection(self, name, lockToken=None):
        """
        Make a new WebDAV collection resource within this collection.
        
        @param name: of the new collection
        @param lockToken: None or token returned by last lock operation
        @type  lockToken: L{LockToken}
        """
        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        header = {}
        if lockToken:
            header = lockToken.toHeader()
        if self.validateResourceNames:
            validateResourceName(name)
        if  name[-1] != '/':     # Collection URL must end with slash
            name += '/'
        self.connection.mkcol(self.path + name, header)
        return CollectionStorer(self.url + name, self.connection, self.validateResourceNames) 
Example 26
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def addResource(self, name, content=None, properties=None, lockToken=None):
        """
        Create a new empty WebDAV resource contained in this collection with the given
        properties.
        
        @param name: leaf name of the new resource    
        @param content: None or initial binary content of resource
        @param properties: name/value-map containing properties
        @param lockToken: None or token returned by last lock operation
        @type  lockToken: L{LockToken}
        """
        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        if self.validateResourceNames:
            validateResourceName(name) # check for invalid characters        
        resource_ = ResourceStorer(self.url + name, self.connection, self.validateResourceNames)
        resource_.uploadContent(content, lockToken)
        if properties:
            resource_.writeProperties(properties, lockToken)
        return resource_ 
Example 27
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def deleteResource(self, name, lockToken=None):
        """
        Delete a collection which is contained within this collection
        
        @param name: leaf name of a contained collection resource
        @param lockToken: None or token returned by last lock operation
        @type  lockToken: L{LockToken}
        """
        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        header = {}
        if lockToken:
            header = lockToken.toHeader()
        if self.validateResourceNames:
            validateResourceName(name)
        response = self.connection.delete(self.path + name, header)
        if response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
            raise WebdavError("Request failed: %s" % response.msr.reason, response.msr.code) 
Example 28
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value 
Example 29
Project: pyblish-win   Author: pyblish   File: pyversioncheck.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def checkonly(package, url, version, verbose=0):
    if verbose >= VERBOSE_EACHFILE:
        print '%s:'%package
    if type(url) == types.StringType:
        ok, newversion, fp = _check1version(package, url, version, verbose)
    else:
        for u in url:
            ok, newversion, fp = _check1version(package, u, version, verbose)
            if ok >= 0 and verbose < VERBOSE_CHECKALL:
                break
    return ok, newversion, fp 
Example 30
Project: pyblish-win   Author: pyblish   File: version.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __cmp__ (self, other):
        if isinstance(other, StringType):
            other = LooseVersion(other)

        return cmp(self.version, other.version)


# end class LooseVersion 
Example 31
Project: pyblish-win   Author: pyblish   File: validate.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_status(status):
    assert_(type(status) is StringType,
        "Status must be a string (not %r)" % status)
    # Implicitly check that we can turn it into an integer:
    status_code = status.split(None, 1)[0]
    assert_(len(status_code) == 3,
        "Status codes must be three characters: %r" % status_code)
    status_int = int(status_code)
    assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
    if len(status) < 4 or status[3] != ' ':
        warnings.warn(
            "The status string (%r) should be a three-digit integer "
            "followed by a single space and a status explanation"
            % status, WSGIWarning) 
Example 32
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def isbasestring(x):
        return isinstance(x, (types.StringType, types.UnicodeType)) 
Example 33
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def add_option_group(self, *args, **kwargs):
        # XXX lots of overlap with OptionContainer.add_option()
        if type(args[0]) is types.StringType:
            group = OptionGroup(self, *args, **kwargs)
        elif len(args) == 1 and not kwargs:
            group = args[0]
            if not isinstance(group, OptionGroup):
                raise TypeError, "not an OptionGroup instance: %r" % group
            if group.parser is not self:
                raise ValueError, "invalid OptionGroup (wrong parser)"
        else:
            raise TypeError, "invalid arguments"

        self.option_groups.append(group)
        return group 
Example 34
Project: pyblish-win   Author: pyblish   File: test_optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def assertOutput(self,
                     cmdline_args,
                     expected_output,
                     expected_status=0,
                     expected_error=None):
        """Assert the parser prints the expected output on stdout."""
        save_stdout = sys.stdout
        encoding = getattr(save_stdout, 'encoding', None)
        try:
            try:
                sys.stdout = StringIO()
                if encoding:
                    sys.stdout.encoding = encoding
                self.parser.parse_args(cmdline_args)
            finally:
                output = sys.stdout.getvalue()
                sys.stdout = save_stdout

        except InterceptedError, err:
            self.assertTrue(
                type(output) is types.StringType,
                "expected output to be an ordinary string, not %r"
                % type(output))

            if output != expected_output:
                self.fail("expected: \n'''\n" + expected_output +
                          "'''\nbut got \n'''\n" + output + "'''")
            self.assertEqual(err.exit_status, expected_status)
            self.assertEqual(err.exit_message, expected_error) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_old_type_object(self):
        self.parser.add_option("-s", type=types.StringType)
        self.assertEqual(self.parser.get_option("-s").type, "string")
        self.parser.add_option("-x", type=types.IntType)
        self.assertEqual(self.parser.get_option("-x").type, "int")


# Custom type for testing processing of default values. 
Example 36
Project: core   Author: lifemapper   File: datalocator.py    GNU General Public License v3.0 5 votes vote down vote up
def _getGETQuery(self, urlprefix, paramTpls):
        """
        Method to construct a GET query from a URL endpoint and a list of  
        of key-value tuples. URL endpoint concludes in either a '?' or a key/value 
        pair (i.e. id=25)
        @note: using list of tuples to ensure that the order of the parameters
               is always the same so we can string compare GET Queries
        """
        kvSep = '&'
        paramsSep = '?'
         
        pairs = []
        for key, val in paramTpls:
            if isinstance(val, (StringType, UnicodeType)):
                val = val.replace(' ', '%20')
            pairs.append('%s=%s' % (key, val))
         
        # Don't end in key/value pair separator
        if urlprefix.endswith(paramsSep) or urlprefix.endswith('&amp;') :
            raise LMError(['Improperly formatted URL prefix %s' % urlprefix])
        # If url/key-value-pair separator isn't present, append it
        elif urlprefix.find(paramsSep) == -1:
            urlprefix = urlprefix + '?'
        # > one key/value pair on the urlprefix, add separator before more pairs
        elif not urlprefix.endswith('?') and pairs:
            urlprefix = urlprefix + kvSep
         
        return urlprefix + kvSep.join(pairs)

    # ............................................... 
Example 37
Project: radius-1xtest   Author: shanghai-edu   File: packet.py    Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key):
        if type(key)!=types.StringType:
            return self.data[key]

        values=self.data[self._EncodeKey(key)]
        attr=self.dict.attributes[key]
        res=[]
        for v in values:
            res.append(self._DecodeValue(attr, v))
        return res 
Example 38
Project: radius-1xtest   Author: shanghai-edu   File: packet.py    Apache License 2.0 5 votes vote down vote up
def __setitem__(self, key, item):
        if type(key)==types.StringType:
            (key,item)=self._EncodeKeyValues(key, [item])
            self.data[key]=item
        else:
            assert isinstance(item, list)
            self.data[key]=item 
Example 39
Project: AshsSDK   Author: thehappydinoa   File: _version133.py    MIT License 5 votes vote down vote up
def bytes2int(bytes):
    """Converts a list of bytes or a string to an integer
    """

    if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
        raise TypeError("You must pass a string or a list")

    # Convert byte stream to integer
    integer = 0
    for byte in bytes:
        integer *= 256
        if type(byte) is types.StringType: byte = ord(byte)
        integer += byte

    return integer 
Example 40
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 5 votes vote down vote up
def bytes2int(bytes):
    r"""Converts a list of bytes or a string to an integer
    """

    if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
        raise TypeError("You must pass a string or a list")

    # Convert byte stream to integer
    integer = 0
    for byte in bytes:
        integer *= 256
        if type(byte) is types.StringType: byte = ord(byte)
        integer += byte

    return integer 
Example 41
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 5 votes vote down vote up
def str642int(string):
    """Converts a base64 encoded string into an integer.
    The chars of this string in in the range '0'-'9','A'-'Z','a'-'z','-','_'
    """

    if not (type(string) is types.ListType or type(string) is types.StringType):
        raise TypeError("You must pass a string or a list")

    integer = 0
    for byte in string:
        integer *= 64
        if type(byte) is types.StringType: byte = ord(byte)
        integer += from64(byte)

    return integer 
Example 42
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_historic_stats_report(self, datastore_id, report_filter):
        """
        Create a URL for retrieving the system historical performance statistics report which is returned as output.

        **Supported on:** TGC (all versions)

        Args:
            datastore_id (str): Datastore object's UUID
            report_filter (`DatastoreStatDownloadableReportFilter`): filter for generating the report

        Returns:
            str: URL to retrieve historic datastore statistics report
        """
        return self._create(report_filter, path_params=[datastore_id], resource_url="datastore/%s/statsDownloadable", request_class=types.StringType) 
Example 43
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_alert_report(self, report_filter):
        """
        Gets the URL for retrieving specified alert report.

        **Supported on:** TGC (all versions)

        Args:
            repot_filter (`AlertDownloadableReportFilter`): filter for generating report

        Returns:
            str: URL to retrieve alert list report
        """
        return self._create(report_filter, resource_url="alert/alertListDownloadable", request_class=types.StringType) 
Example 44
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_license_report(self, license_report_filter):
        """
        Get license list report as URL

        **Supported on:** TGC (since v310.51)

        Args:
            license_report_filter (`LicenseDownloadableReportFilter`): License report filter

        Returns:
            str: URL to retrieve license list report
        """
        return self._create(license_report_filter, resource_url="license/licenseListDownloadable", request_class=types.StringType) 
Example 45
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_service_group_report(self, report_filter):
        """
        Get a URL for retrieving service group report

        **Supported on:** TGC (all versions)

        Args:
            report_filter (`SvgDownloadableReportFilter`): filter for generating the report

        Returns:
            str: URL to retrieve service group list report
        """
        return self._create(report_filter, resource_url="servicegroup/svgListDownloadable", request_class=types.StringType) 
Example 46
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_vm_historical_stats_report(self, vm_id, report_filter):
        """
        Creates a URL for retrieving specified VM historical statistics report.

        **Supported on:** TGC (all versions)

        Args:
            vm_id (str): VM Object's UUID
            report_filter (`VirtualMachineStatDownloadableReportFilter`): Filter to use for generating report

        Returns:
            str: URL to the report
        """
        return self._create(report_filter, path_params=[vm_id], resource_url="vm/%s/statsDownloadable", request_class=types.StringType) 
Example 47
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_vmstore_list_report(self, report_filter):
        """
        Creates a URL for retrieving specified VM historical statistics report.

        **Supported on:** TGC (all versions)

        Args:
            report_filter (`VMstoreDownloadableReportFilter`): Filter to use for generating report

        Returns:
            str: URL to the report
        """
        return self._create(report_filter, resource_url="vmstore/vmstoreListDownloadable", request_class=types.StringType) 
Example 48
Project: tintri-python-sdk   Author: Tintri   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_vmpool_list_report(self, report_filter):
        """
        Creates a URL for retrieving specified VM pool report.

        **Supported on:** TGC (since v310.51)

        Args:
            report_filter (`VmstorePoolDownloadableReportFilter`): Filter to use for generating report

        Returns:
            str: URL to the report
        """
        return self._create(report_filter, resource_url="vmstorePool/vmPoolListDownloadable", request_class=types.StringType) 
Example 49
Project: tintri-python-sdk   Author: Tintri   File: common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _process_result(self, method, url, response, request_class, response_class, query_params, path_params):
        cls = response_class and response_class or request_class
        if cls in [types.StringType, types.UnicodeType]: # if we expect string type result, no need for further processing
            return response.text
        else:
            # prepare context to hold url and data along with method to navigate pages
            context = { 'method': method, 'url': url, 'query_params': query_params, 'response_class': response_class, 'func': self._get_all, 'request_class': request_class, 'path_params': path_params, 'response_data': response.text }
            return self._json_object_to_object(json.loads(response.text), cls, context=context) # first load JSON to a Python list or dict 
Example 50
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 5 votes vote down vote up
def add_password(self, realm, uri, user, passwd):
        # uri could be a single URI or a sequence
        if isinstance(uri, (types.StringType, types.UnicodeType)):
            uri = [uri]
        uri = tuple(map(self.reduce_uri, uri))
        if not self.passwd.has_key(realm):
            self.passwd[realm] = {}
        self.passwd[realm][uri] = (user, passwd)