Python types.StringType() Examples

The following are 30 code examples of types.StringType(). 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: handlers.py    From meddle with 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 #2
Source File: wordnet.py    From razzy-spinner with 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 #3
Source File: wordnet.py    From razzy-spinner with 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 #4
Source File: pubkey.py    From earthengine with 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 #5
Source File: RawInstreamFile.py    From bachbot with 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 #6
Source File: pubkey.py    From earthengine with 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 #7
Source File: pubkey.py    From Safejumper-for-Desktop with 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 #8
Source File: pubkey.py    From earthengine with 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 #9
Source File: pubkey.py    From earthengine with 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 #10
Source File: pubkey.py    From Safejumper-for-Desktop with 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 #11
Source File: wordnet.py    From razzy-spinner with 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
Source File: dump.py    From pizza with 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 #13
Source File: pubkey.py    From Safejumper-for-Desktop with 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 #14
Source File: urllib2.py    From jawfish with 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 #15
Source File: handlers.py    From oss-ftp with 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 #16
Source File: monitoring.py    From automatron with Apache License 2.0 6 votes vote down vote up
def schedule(scheduler, runbook, target, config, dbc, logger):
    ''' Setup schedule for new runbooks and targets '''
    # Default schedule (every minute)
    task_schedule = {
        'second' : 0,
        'minute' : '*',
        'hour' : '*',
        'day' : '*',
        'month' : '*',
        'day_of_week' : '*'
    }
    # If schedule is present override default
    if 'schedule' in target['runbooks'][runbook].keys():
        if type(target['runbooks'][runbook]['schedule']) == types.DictType:
            for key in target['runbooks'][runbook]['schedule'].keys():
                task_schedule[key] = target['runbooks'][runbook]['schedule'][key]
        elif type(target['runbooks'][runbook]['schedule']) == types.StringType:
            breakdown = target['runbooks'][runbook]['schedule'].split(" ")
            task_schedule = {
                'second' : 0,
                'minute' : breakdown[0],
                'hour' : breakdown[1],
                'day' : breakdown[2],
                'month' :  breakdown[3],
                'day_of_week' : breakdown[4]
            }
    cron = CronTrigger(
        second=task_schedule['second'],
        minute=task_schedule['minute'],
        hour=task_schedule['hour'],
        day=task_schedule['day'],
        month=task_schedule['month'],
        day_of_week=task_schedule['day_of_week'],
    )
    return scheduler.add_job(
        monitor,
        trigger=cron,
        args=[runbook, target, config, dbc, logger]
    ) 
Example #17
Source File: handlers.py    From meddle with 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 #18
Source File: turtle.py    From oss-ftp with 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 #19
Source File: handlers.py    From ironpython2 with 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 #20
Source File: FrameWork.py    From Computable with 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 #21
Source File: FrameWork.py    From Computable with 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 #22
Source File: json.py    From talklog with 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 #23
Source File: IOBinding.py    From BinderFilter with 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 #24
Source File: json.py    From talklog with 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 #25
Source File: json.py    From talklog with 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 #26
Source File: json.py    From talklog with 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 #27
Source File: idautils.py    From dumpDex with 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 #28
Source File: Base.py    From Yuki-Chan-The-Auto-Pentest with 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 #29
Source File: handlers.py    From BinderFilter with 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 #30
Source File: turtle.py    From BinderFilter with 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]