Python types.TupleType() Examples

The following are 30 code examples of types.TupleType(). 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: handler.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def send_resp_header(self, cont_type, cont_length, range=False):  # @ReservedAssignment
        if range:
            self.send_response(206, 'Partial Content')
        else:
            self.send_response(200, 'OK')

        self.send_header('Content-Type', cont_type)
        self.send_header('transferMode.dlna.org', 'Streaming')
        self.send_header('contentFeatures.dlna.org',
                         'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000')
        self.send_header('Accept-Ranges', 'bytes')

        if range:
            if isinstance(range, (types.TupleType, types.ListType)) and len(range) == 3:
                self.send_header('Content-Range', 'bytes %d-%d/%d' % range)
                self.send_header('Content-Length', range[1] - range[0] + 1)
            else:
                raise ValueError('Invalid range value')
        else:
            self.send_header('Content-Length', cont_length)
        self.finish_header() 
Example #2
Source File: location.py    From Robofont-scripts with MIT License 6 votes vote down vote up
def isAmbivalent(self, dim=None):
        """
        Return True if any of the factors are in fact tuples.
        If a dimension name is given only that dimension is tested.
        ::
            >>> l = Location(pop=1)
            >>> l.isAmbivalent()
            False
            >>> l = Location(pop=1, snap=(100, -100))
            >>> l.isAmbivalent()
            True
        """
        if dim is not None:
            try:
                return type(self[dim]) == TupleType
            except KeyError:
                # dimension is not present, it should be 0, so not ambivalent
                return False
        for dim, val in self.items():
            if type(val) == TupleType:
                return True
        return False 
Example #3
Source File: location.py    From Robofont-scripts with MIT License 6 votes vote down vote up
def split(self):
        """
        Split an ambivalent location into 2. One for the x, the other for the y.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.split()
            (<Location pop:-5 >, <Location pop:5 >)
        """
        x = self.__class__()
        y = self.__class__()
        for dim, val in self.items():
            if type(val) == TupleType:
                x[dim] = val[0]
                y[dim] = val[1]
            else:
                x[dim] = val
                y[dim] = val
        return x, y 
Example #4
Source File: validate.py    From oss-ftp with MIT License 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example #5
Source File: location.py    From Robofont-scripts with MIT License 6 votes vote down vote up
def spliceX(self):
        """
        Return a copy with the x values preferred for ambivalent locations.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.spliceX()
            <Location pop:-5 >
        """
        new = self.__class__()
        for dim, val in self.items():
            if type(val) == TupleType:
                new[dim] = val[0]
            else:
                new[dim] = val
        return new 
Example #6
Source File: validate.py    From pmatic with GNU General Public License v2.0 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example #7
Source File: location.py    From Robofont-scripts with MIT License 6 votes vote down vote up
def spliceY(self):
        """
        Return a copy with the y values preferred for ambivalent locations.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.spliceY()
            <Location pop:5 >
        """
        new = self.__class__()
        for dim, val in self.items():
            if type(val) == TupleType:
                new[dim] = val[1]
            else:
                new[dim] = val
        return new 
Example #8
Source File: validate.py    From BinderFilter with MIT License 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example #9
Source File: validate.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example #10
Source File: recipe-473818.py    From code with MIT License 6 votes vote down vote up
def new_looper(a, arg=None):
    """Helper function for nest()
    determines what sort of looper to make given a's type"""
    if isinstance(a,types.TupleType):
        if len(a) == 2:
            return RangeLooper(a[0],a[1])
        elif len(a) == 3:
            return RangeLooper(a[0],a[1],a[2])
    elif isinstance(a, types.BooleanType):
        return BooleanLooper(a)
    elif isinstance(a,types.IntType) or isinstance(a, types.LongType):
        return RangeLooper(a)
    elif isinstance(a, types.StringType) or isinstance(a, types.ListType):
        return ListLooper(a)
    elif isinstance(a, Looper):
        return a
    elif isinstance(a, types.LambdaType):
        return CalcField(a, arg) 
Example #11
Source File: validate.py    From meddle with MIT License 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example #12
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 #13
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 #14
Source File: lint.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def check_headers(headers):
    assert type(headers) is ListType, (
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert type(item) is TupleType, (
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert len(item) == 2
        name, value = item
        assert name.lower() != 'status', (
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert '\n' not in name and ':' not in name, (
            "Header names may not contain ':' or '\\n': %r" % name)
        assert header_re.search(name), "Bad header name: %r" % name
        assert not name.endswith('-') and not name.endswith('_'), (
            "Names may not end in '-' or '_': %r" % name)
        assert not bad_header_value_re.search(value), (
            "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example #15
Source File: recipe-223610.py    From code with MIT License 6 votes vote down vote up
def __init__(self,rowset,description):
    # save the description as is
    self.description = fRow(description)
    self.description.__Field2Index__ = self.__fieldToIndex
    
    # Create the list and dict of fields
    self.fields = []
    self.__fieldDict = {}
    for f in range(len(description)):
      if type(description[f]) == types.TupleType or type(description[f]) == types.ListType:
        self.__fieldDict[description[f][0].lower()] = f
        self.fields.append( description[f][0].lower())
      else:
        self.__fieldDict[description[f].lower()] = f
        self.fields.append( description[f].lower())
    # Add all the rows
    for r in rowset:
      self.append(r) 
Example #16
Source File: transaction.py    From encompass with GNU 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 type(x) == types.TupleType:
                x, i = x
            if type(x) != types.StringType:
                raise EnumException, "enum name is not a string: " + x
            if type(i) != types.IntType:
                raise EnumException, "enum value is not an integer: " + i
            if x in uniqueNames:
                raise EnumException, "enum name is not unique: " + x
            if i in uniqueValues:
                raise EnumException, "enum value is not unique for " + x
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example #17
Source File: admin.py    From uac-a-mola with GNU General Public License v3.0 6 votes vote down vote up
def runAsAdmin(cmdLine=None, wait=True):

    if os.name != 'nt':
        raise RuntimeError, "This function is only implemented on Windows."

    import win32api
    import win32con
    import win32event
    import win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon

    python_exe = sys.executable

    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType, types.ListType):
        raise ValueError, "cmdLine is not a sequence."
    cmd = '"%s"' % (cmdLine[0],)
    # XXX TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    cmdDir = ''
    #showCmd = win32con.SW_SHOWNORMAL
    showCmd = win32con.SW_HIDE
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        # print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = None

    return rc 
Example #18
Source File: handler.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def send_resp_header(self, cont_type, size, range=False):
    
        if range:
            self.send_response(206, 'Partial Content')
        else:
            self.send_response(200, 'OK')

        self.send_header('Content-Type', cont_type)
        self.send_header('Accept-Ranges', 'bytes')

        if range:
            if isinstance(range, (types.TupleType, types.ListType)) and len(range)==3:
                self.send_header('Content-Range', 'bytes %d-%d/%d' % range)
                self.send_header('Content-Length', range[1]-range[0]+1)
            else:
                raise ValueError('Invalid range value')
        else:
            self.send_header('Content-Length', size)
            
        self.send_header('Connection', 'close')
        self.end_headers() 
Example #19
Source File: builder.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def from_lineno(asttuple):
    """return the minimum line number of the given ast tuple"""
    if type(asttuple[1]) is TupleType:
        return from_lineno(asttuple[1])
    return asttuple[2] 
Example #20
Source File: astutils.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def _clean(ast_tuple):
    """ transform the ast into as list of tokens (i.e. final elements)
    """
    if type(ast_tuple[1]) is TupleType:
        v = []
        for c in ast_tuple[1:]:
            v += _clean(c)
        return v
    else:
        return [list(ast_tuple[:2])] 
Example #21
Source File: astutils.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def debuild(ast_tuple):
    """
    reverse ast_tuple to string
    """
    if type(ast_tuple[1]) is TupleType:
        result = ''
        for child in ast_tuple[1:]: 
            result = '%s%s' % (result, debuild(child))
        return result
    else:
        return ast_tuple[1] 
Example #22
Source File: builder.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def to_lineno(asttuple):
    """return the maximum line number of the given ast tuple"""
    if type(asttuple[-1]) is TupleType:
        return to_lineno(asttuple[-1])
    return asttuple[2] 
Example #23
Source File: optparse.py    From hacker-scripts with MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example #24
Source File: optparse.py    From hacker-scripts with MIT License 5 votes vote down vote up
def _check_choice(self):
        if self.type == "choice":
            if self.choices is None:
                raise OptionError(
                    "must supply a list of choices for type 'choice'", self)
            elif type(self.choices) not in (types.TupleType, types.ListType):
                raise OptionError(
                    "choices must be a list of strings ('%s' supplied)"
                    % str(type(self.choices)).split("'")[1], self)
        elif self.choices is not None:
            raise OptionError(
                "must not supply choices for type %r" % self.type, self) 
Example #25
Source File: _pydev_inspect.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def strseq(object, convert, join=joinseq):
    """Recursively walk a sequence, stringifying each element."""
    if type(object) in [types.ListType, types.TupleType]:
        return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
    else:
        return convert(object) 
Example #26
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toUTF8(v):
    if isinstance(v, unicode):
        return v.encode('utf-8')
    elif isinstance(v, (types.TupleType, types.ListType)):
        return [toUTF8(e) for e in v]
    elif isinstance(v, types.DictType):
        return dict([(toUTF8(k), toUTF8(v_)) for k, v_ in v.items()])
    else:
        return v 
Example #27
Source File: astutils.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def cvrtr(tuple):
    """debug method returning an ast string in a readable fashion"""
    if type(tuple) is TupleType:
        try:
            try:
                txt = 'token.'+token.tok_name[tuple[0]]
            except:
                txt = 'symbol.'+symbol.sym_name[tuple[0]]
        except:
            txt =  'Unknown token/symbol'
        return [txt] + list(map(cvrtr, tuple[1:]))
    else:
        return tuple 
Example #28
Source File: astutils.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def cvrtr(tuple):
    """debug method returning an ast string in a readable fashion"""
    if type(tuple) is TupleType:
        try:
            try:
                txt = 'token.'+token.tok_name[tuple[0]]
            except:
                txt = 'symbol.'+symbol.sym_name[tuple[0]]
        except:
            txt =  'Unknown token/symbol'
        return [txt] + list(map(cvrtr, tuple[1:]))
    else:
        return tuple 
Example #29
Source File: optparse.py    From hacker-scripts with MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example #30
Source File: astutils.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def _clean(ast_tuple):
    """ transform the ast into as list of tokens (i.e. final elements)
    """
    if type(ast_tuple[1]) is TupleType:
        v = []
        for c in ast_tuple[1:]:
            v += _clean(c)
        return v
    else:
        return [list(ast_tuple[:2])]