Python types.StringType() Examples

The following are 30 code examples for showing how to use types.StringType(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: jawfish   Author: war-and-code   File: urllib2.py    License: 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 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: 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 3
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: 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 4
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: 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 5
Project: earthengine   Author: mortcanty   File: pubkey.py    License: MIT License 6 votes vote down vote up
def encrypt(self, plaintext, K):
        """Encrypt a piece of data.

        :Parameter plaintext: The piece of data to encrypt.
        :Type plaintext: byte string or long

        :Parameter K: A random parameter required by some algorithms
        :Type K: byte string or long

        :Return: A tuple with two items. Each item is of the same type as the
         plaintext (string or long).
        """
        wasString=0
        if isinstance(plaintext, types.StringType):
            plaintext=bytes_to_long(plaintext) ; wasString=1
        if isinstance(K, types.StringType):
            K=bytes_to_long(K)
        ciphertext=self._encrypt(plaintext, K)
        if wasString: return tuple(map(long_to_bytes, ciphertext))
        else: return ciphertext 
Example 6
Project: earthengine   Author: mortcanty   File: pubkey.py    License: MIT License 6 votes vote down vote up
def decrypt(self, ciphertext):
        """Decrypt a piece of data. 

        :Parameter ciphertext: The piece of data to decrypt.
        :Type ciphertext: byte string, long or a 2-item tuple as returned by `encrypt`

        :Return: A byte string if ciphertext was a byte string or a tuple
         of byte strings. A long otherwise.
        """
        wasString=0
        if not isinstance(ciphertext, types.TupleType):
            ciphertext=(ciphertext,)
        if isinstance(ciphertext[0], types.StringType):
            ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
        plaintext=self._decrypt(ciphertext)
        if wasString: return long_to_bytes(plaintext)
        else: return plaintext 
Example 7
Project: earthengine   Author: mortcanty   File: pubkey.py    License: MIT License 6 votes vote down vote up
def sign(self, M, K):
        """Sign a piece of data.

        :Parameter M: The piece of data to encrypt.
        :Type M: byte string or long

        :Parameter K: A random parameter required by some algorithms
        :Type K: byte string or long

        :Return: A tuple with two items.
        """
        if (not self.has_private()):
            raise TypeError('Private key not available in this object')
        if isinstance(M, types.StringType): M=bytes_to_long(M)
        if isinstance(K, types.StringType): K=bytes_to_long(K)
        return self._sign(M, K) 
Example 8
Project: earthengine   Author: mortcanty   File: pubkey.py    License: MIT License 6 votes vote down vote up
def blind(self, M, B):
        """Blind a message to prevent certain side-channel attacks.
       
        :Parameter M: The message to blind.
        :Type M: byte string or long

        :Parameter B: Blinding factor.
        :Type B: byte string or long

        :Return: A byte string if M was so. A long otherwise.
        """
        wasString=0
        if isinstance(M, types.StringType):
            M=bytes_to_long(M) ; wasString=1
        if isinstance(B, types.StringType): B=bytes_to_long(B)
        blindedmessage=self._blind(M, B)
        if wasString: return long_to_bytes(blindedmessage)
        else: return blindedmessage 
Example 9
Project: bachbot   Author: feynmanliang   File: RawInstreamFile.py    License: MIT License 6 votes vote down vote up
def __init__(self, infile=''):
        """ 
        If 'file' is a string we assume it is a path and read from 
        that file.
        If it is a file descriptor we read from the file, but we don't 
        close it.
        Midi files are usually pretty small, so it should be safe to 
        copy them into memory.
        """
        if infile:
            if isinstance(infile, StringType):
                infile = open(infile, 'rb')
                self.data = infile.read()
                infile.close()
            else:
                # don't close the f
                self.data = infile.read()
        else:
            self.data = ''
        # start at beginning ;-)
        self.cursor = 0


    # setting up data manually 
Example 10
Project: meddle   Author: glmcdona   File: handlers.py    License: MIT License 6 votes vote down vote up
def start_response(self, status, headers,exc_info=None):
        """'start_response()' callable as specified by PEP 333"""

        if exc_info:
            try:
                if self.headers_sent:
                    # Re-raise original exception if headers sent
                    raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None        # avoid dangling circular ref
        elif self.headers is not None:
            raise AssertionError("Headers already set!")

        assert type(status) is StringType,"Status must be a string"
        assert len(status)>=4,"Status must be at least 4 characters"
        assert int(status[:3]),"Status message must begin w/3-digit code"
        assert status[3]==" ", "Status message must have a space after code"
        if __debug__:
            for name,val in headers:
                assert type(name) is StringType,"Header names must be strings"
                assert type(val) is StringType,"Header values must be strings"
                assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
        self.status = status
        self.headers = self.headers_class(headers)
        return self.write 
Example 11
Project: meddle   Author: glmcdona   File: handlers.py    License: MIT License 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 12
Project: ironpython2   Author: IronLanguages   File: handlers.py    License: Apache License 2.0 6 votes vote down vote up
def start_response(self, status, headers,exc_info=None):
        """'start_response()' callable as specified by PEP 333"""

        if exc_info:
            try:
                if self.headers_sent:
                    # Re-raise original exception if headers sent
                    raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None        # avoid dangling circular ref
        elif self.headers is not None:
            raise AssertionError("Headers already set!")

        assert type(status) is StringType,"Status must be a string"
        assert len(status)>=4,"Status must be at least 4 characters"
        assert int(status[:3]),"Status message must begin w/3-digit code"
        assert status[3]==" ", "Status message must have a space after code"
        if __debug__:
            for name,val in headers:
                assert type(name) is StringType,"Header names must be strings"
                assert type(val) is StringType,"Header values must be strings"
                assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
        self.status = status
        self.headers = self.headers_class(headers)
        return self.write 
Example 13
Project: talklog   Author: gashero   File: json.py    License: MIT License 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: talklog   Author: gashero   File: json.py    License: MIT License 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: talklog   Author: gashero   File: json.py    License: MIT License 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 16
Project: talklog   Author: gashero   File: json.py    License: MIT License 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 17
Project: dumpDex   Author: CvvT   File: idautils.py    License: Apache License 2.0 6 votes vote down vote up
def _Assemble(ea, line):
    """
    Please refer to Assemble() - INTERNAL USE ONLY
    """
    if type(line) == types.StringType:
        lines = [line]
    else:
        lines = line
    ret = []
    for line in lines:
        seg = idaapi.getseg(ea)
        if not seg:
            return (False, "No segment at ea")
        ip  = ea - (idaapi.ask_selector(seg.sel) << 4)
        buf = idaapi.AssembleLine(ea, seg.sel, ip, seg.bitness, line)
        if not buf:
            return (False, "Assembler failed: " + line)
        ea += len(buf)
        ret.append(buf)

    if len(ret) == 1:
        ret = ret[0]
    return (True, ret) 
Example 18
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: Base.py    License: MIT License 6 votes vote down vote up
def argparse(self, name, args):
        if not name and 'name' in self.defaults:
            args['name'] = self.defaults['name']
        if isinstance(name, types.StringType):
            args['name'] = name
        else:
            if len(name) == 1:
                if name[0]:
                    args['name'] = name[0]
        for i in defaults.keys():
            if i not in args:
                if i in self.defaults:
                    args[i] = self.defaults[i]
                else:
                    args[i] = defaults[i]
        if isinstance(args['server'], types.StringType):
            args['server'] = [args['server']]
        self.args = args 
Example 19
Project: BinderFilter   Author: dxwu   File: turtle.py    License: MIT License 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 20
Project: BinderFilter   Author: dxwu   File: handlers.py    License: MIT License 6 votes vote down vote up
def start_response(self, status, headers,exc_info=None):
        """'start_response()' callable as specified by PEP 333"""

        if exc_info:
            try:
                if self.headers_sent:
                    # Re-raise original exception if headers sent
                    raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None        # avoid dangling circular ref
        elif self.headers is not None:
            raise AssertionError("Headers already set!")

        assert type(status) is StringType,"Status must be a string"
        assert len(status)>=4,"Status must be at least 4 characters"
        assert int(status[:3]),"Status message must begin w/3-digit code"
        assert status[3]==" ", "Status message must have a space after code"
        if __debug__:
            for name,val in headers:
                assert type(name) is StringType,"Header names must be strings"
                assert type(val) is StringType,"Header values must be strings"
                assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
        self.status = status
        self.headers = self.headers_class(headers)
        return self.write 
Example 21
Project: BinderFilter   Author: dxwu   File: IOBinding.py    License: MIT License 6 votes vote down vote up
def encode(self, chars):
        if isinstance(chars, types.StringType):
            # This is either plain ASCII, or Tk was returning mixed-encoding
            # text to us. Don't try to guess further.
            return chars
        # See whether there is anything non-ASCII in it.
        # If not, no need to figure out the encoding.
        try:
            return chars.encode('ascii')
        except UnicodeError:
            pass
        # If there is an encoding declared, try this first.
        try:
            enc = coding_spec(chars)
            failed = None
        except LookupError, msg:
            failed = msg
            enc = None 
Example 22
Project: Computable   Author: ktraunmueller   File: FrameWork.py    License: MIT License 6 votes vote down vote up
def fixmenudimstate(self):
        for m in self.menus.keys():
            menu = self.menus[m]
            if menu.__class__ == FrameWork.AppleMenu:
                continue
            for i in range(len(menu.items)):
                label, shortcut, callback, kind = menu.items[i]
                if type(callback) == types.StringType:
                    wid = MyFrontWindow()
                    if wid and wid in self.parent._windows:
                        window = self.parent._windows[wid]
                        if hasattr(window, "domenu_" + callback):
                            menu.menu.EnableMenuItem(i + 1)
                        elif hasattr(self.parent, "domenu_" + callback):
                            menu.menu.EnableMenuItem(i + 1)
                        else:
                            menu.menu.DisableMenuItem(i + 1)
                    elif hasattr(self.parent, "domenu_" + callback):
                        menu.menu.EnableMenuItem(i + 1)
                    else:
                        menu.menu.DisableMenuItem(i + 1)
                elif callback:
                    pass 
Example 23
Project: Computable   Author: ktraunmueller   File: FrameWork.py    License: MIT License 6 votes vote down vote up
def dispatch(self, id, item, window, event):
        title, shortcut, callback, mtype = self.items[item-1]
        if callback:
            if not self.bar.parent or type(callback) != types.StringType:
                menuhandler = callback
            else:
                # callback is string
                wid = MyFrontWindow()
                if wid and wid in self.bar.parent._windows:
                    window = self.bar.parent._windows[wid]
                    if hasattr(window, "domenu_" + callback):
                        menuhandler = getattr(window, "domenu_" + callback)
                    elif hasattr(self.bar.parent, "domenu_" + callback):
                        menuhandler = getattr(self.bar.parent, "domenu_" + callback)
                    else:
                        # nothing we can do. we shouldn't have come this far
                        # since the menu item should have been disabled...
                        return
                elif hasattr(self.bar.parent, "domenu_" + callback):
                    menuhandler = getattr(self.bar.parent, "domenu_" + callback)
                else:
                    # nothing we can do. we shouldn't have come this far
                    # since the menu item should have been disabled...
                    return
            menuhandler(id, item, window, event) 
Example 24
Project: oss-ftp   Author: aliyun   File: turtle.py    License: MIT License 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 25
Project: oss-ftp   Author: aliyun   File: handlers.py    License: MIT License 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 26
Project: pizza   Author: lammps   File: dump.py    License: GNU General Public License v2.0 6 votes vote down vote up
def sort(self,*list):
    if len(list) == 0:
      print "Sorting selected snapshots ..."
      id = self.names["id"]
      for snap in self.snaps:
        if snap.tselect: self.sort_one(snap,id)
    elif type(list[0]) is types.StringType:
      print "Sorting selected snapshots by %s ..." % list[0]
      id = self.names[list[0]]
      for snap in self.snaps:
        if snap.tselect: self.sort_one(snap,id)
    else:
      i = self.findtime(list[0])
      id = self.names["id"]
      self.sort_one(self.snaps[i],id)

  # --------------------------------------------------------------------
  # sort a single snapshot by ID column 
Example 27
Project: Safejumper-for-Desktop   Author: proxysh   File: pubkey.py    License: GNU General Public License v2.0 6 votes vote down vote up
def encrypt(self, plaintext, K):
        """Encrypt a piece of data.

        :Parameter plaintext: The piece of data to encrypt.
        :Type plaintext: byte string or long

        :Parameter K: A random parameter required by some algorithms
        :Type K: byte string or long

        :Return: A tuple with two items. Each item is of the same type as the
         plaintext (string or long).
        """
        wasString=0
        if isinstance(plaintext, types.StringType):
            plaintext=bytes_to_long(plaintext) ; wasString=1
        if isinstance(K, types.StringType):
            K=bytes_to_long(K)
        ciphertext=self._encrypt(plaintext, K)
        if wasString: return tuple(map(long_to_bytes, ciphertext))
        else: return ciphertext 
Example 28
Project: Safejumper-for-Desktop   Author: proxysh   File: pubkey.py    License: GNU General Public License v2.0 6 votes vote down vote up
def decrypt(self, ciphertext):
        """Decrypt a piece of data. 

        :Parameter ciphertext: The piece of data to decrypt.
        :Type ciphertext: byte string, long or a 2-item tuple as returned by `encrypt`

        :Return: A byte string if ciphertext was a byte string or a tuple
         of byte strings. A long otherwise.
        """
        wasString=0
        if not isinstance(ciphertext, types.TupleType):
            ciphertext=(ciphertext,)
        if isinstance(ciphertext[0], types.StringType):
            ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
        plaintext=self._decrypt(ciphertext)
        if wasString: return long_to_bytes(plaintext)
        else: return plaintext 
Example 29
Project: Safejumper-for-Desktop   Author: proxysh   File: pubkey.py    License: GNU General Public License v2.0 6 votes vote down vote up
def sign(self, M, K):
        """Sign a piece of data.

        :Parameter M: The piece of data to encrypt.
        :Type M: byte string or long

        :Parameter K: A random parameter required by some algorithms
        :Type K: byte string or long

        :Return: A tuple with two items.
        """
        if (not self.has_private()):
            raise TypeError('Private key not available in this object')
        if isinstance(M, types.StringType): M=bytes_to_long(M)
        if isinstance(K, types.StringType): K=bytes_to_long(K)
        return self._sign(M, K) 
Example 30
Project: jawfish   Author: war-and-code   File: urllib2.py    License: 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)